1use crate::http::HttpClient;
2use db::Db;
3use gpui::{
4 executor::Background,
5 serde_json::{self, value::Map, Value},
6 AppContext, Task,
7};
8use isahc::Request;
9use lazy_static::lazy_static;
10use parking_lot::Mutex;
11use serde::Serialize;
12use serde_json::json;
13use std::{
14 io::Write,
15 mem,
16 path::PathBuf,
17 sync::Arc,
18 time::{Duration, SystemTime, UNIX_EPOCH},
19};
20use tempfile::NamedTempFile;
21use util::{post_inc, ResultExt, TryFutureExt};
22use uuid::Uuid;
23
24pub struct Telemetry {
25 http_client: Arc<dyn HttpClient>,
26 executor: Arc<Background>,
27 state: Mutex<TelemetryState>,
28}
29
30#[derive(Default)]
31struct TelemetryState {
32 metrics_id: Option<Arc<str>>,
33 device_id: Option<Arc<str>>,
34 app_version: Option<Arc<str>>,
35 os_version: Option<Arc<str>>,
36 os_name: &'static str,
37 queue: Vec<MixpanelEvent>,
38 next_event_id: usize,
39 flush_task: Option<Task<()>>,
40 log_file: Option<NamedTempFile>,
41}
42
43const MIXPANEL_EVENTS_URL: &'static str = "https://api.mixpanel.com/track";
44const MIXPANEL_ENGAGE_URL: &'static str = "https://api.mixpanel.com/engage#profile-set";
45
46lazy_static! {
47 static ref MIXPANEL_TOKEN: Option<String> = std::env::var("ZED_MIXPANEL_TOKEN")
48 .ok()
49 .or_else(|| option_env!("ZED_MIXPANEL_TOKEN").map(|key| key.to_string()));
50}
51
52#[derive(Serialize, Debug)]
53struct MixpanelEvent {
54 event: String,
55 properties: MixpanelEventProperties,
56}
57
58#[derive(Serialize, Debug)]
59struct MixpanelEventProperties {
60 // Mixpanel required fields
61 #[serde(skip_serializing_if = "str::is_empty")]
62 token: &'static str,
63 time: u128,
64 distinct_id: Option<Arc<str>>,
65 #[serde(rename = "$insert_id")]
66 insert_id: usize,
67 // Custom fields
68 #[serde(skip_serializing_if = "Option::is_none", flatten)]
69 event_properties: Option<Map<String, Value>>,
70 os_name: &'static str,
71 os_version: Option<Arc<str>>,
72 app_version: Option<Arc<str>>,
73 signed_in: bool,
74 #[serde(rename = "App")]
75 app: &'static str,
76}
77
78#[derive(Serialize)]
79struct MixpanelEngageRequest {
80 #[serde(rename = "$token")]
81 token: &'static str,
82 #[serde(rename = "$distinct_id")]
83 distinct_id: Arc<str>,
84 #[serde(rename = "$set")]
85 set: Value,
86}
87
88#[cfg(debug_assertions)]
89const MAX_QUEUE_LEN: usize = 1;
90
91#[cfg(not(debug_assertions))]
92const MAX_QUEUE_LEN: usize = 10;
93
94#[cfg(debug_assertions)]
95const DEBOUNCE_INTERVAL: Duration = Duration::from_secs(1);
96
97#[cfg(not(debug_assertions))]
98const DEBOUNCE_INTERVAL: Duration = Duration::from_secs(30);
99
100impl Telemetry {
101 pub fn new(client: Arc<dyn HttpClient>, cx: &AppContext) -> Arc<Self> {
102 let platform = cx.platform();
103 let this = Arc::new(Self {
104 http_client: client,
105 executor: cx.background().clone(),
106 state: Mutex::new(TelemetryState {
107 os_version: platform.os_version().ok().map(|v| v.to_string().into()),
108 os_name: platform.os_name().into(),
109 app_version: platform.app_version().ok().map(|v| v.to_string().into()),
110 device_id: None,
111 metrics_id: None,
112 queue: Default::default(),
113 flush_task: Default::default(),
114 next_event_id: 0,
115 log_file: None,
116 }),
117 });
118
119 if MIXPANEL_TOKEN.is_some() {
120 this.executor
121 .spawn({
122 let this = this.clone();
123 async move {
124 if let Some(tempfile) = NamedTempFile::new().log_err() {
125 this.state.lock().log_file = Some(tempfile);
126 }
127 }
128 })
129 .detach();
130 }
131
132 this
133 }
134
135 pub fn log_file_path(&self) -> Option<PathBuf> {
136 Some(self.state.lock().log_file.as_ref()?.path().to_path_buf())
137 }
138
139 pub fn start(self: &Arc<Self>, db: Db) {
140 let this = self.clone();
141 self.executor
142 .spawn(
143 async move {
144 let device_id = if let Ok(Some(device_id)) = db.read_kvp("device_id") {
145 device_id
146 } else {
147 let device_id = Uuid::new_v4().to_string();
148 db.write_kvp("device_id", &device_id)?;
149 device_id
150 };
151
152 let device_id: Arc<str> = device_id.into();
153 let mut state = this.state.lock();
154 state.device_id = Some(device_id.clone());
155 for event in &mut state.queue {
156 event
157 .properties
158 .distinct_id
159 .get_or_insert_with(|| device_id.clone());
160 }
161 if !state.queue.is_empty() {
162 drop(state);
163 this.flush();
164 }
165
166 anyhow::Ok(())
167 }
168 .log_err(),
169 )
170 .detach();
171 }
172
173 pub fn set_authenticated_user_info(
174 self: &Arc<Self>,
175 metrics_id: Option<String>,
176 is_staff: bool,
177 ) {
178 let this = self.clone();
179 let mut state = self.state.lock();
180 let device_id = state.device_id.clone();
181 let metrics_id: Option<Arc<str>> = metrics_id.map(|id| id.into());
182 state.metrics_id = metrics_id.clone();
183 drop(state);
184
185 if let Some((token, device_id)) = MIXPANEL_TOKEN.as_ref().zip(device_id) {
186 self.executor
187 .spawn(
188 async move {
189 let json_bytes = serde_json::to_vec(&[MixpanelEngageRequest {
190 token,
191 distinct_id: device_id,
192 set: json!({ "staff": is_staff, "id": metrics_id }),
193 }])?;
194 let request = Request::post(MIXPANEL_ENGAGE_URL)
195 .header("Content-Type", "application/json")
196 .body(json_bytes.into())?;
197 this.http_client.send(request).await?;
198 Ok(())
199 }
200 .log_err(),
201 )
202 .detach();
203 }
204 }
205
206 pub fn report_event(self: &Arc<Self>, kind: &str, properties: Value) {
207 let mut state = self.state.lock();
208 let event = MixpanelEvent {
209 event: kind.to_string(),
210 properties: MixpanelEventProperties {
211 token: "",
212 time: SystemTime::now()
213 .duration_since(UNIX_EPOCH)
214 .unwrap()
215 .as_millis(),
216 distinct_id: state.device_id.clone(),
217 insert_id: post_inc(&mut state.next_event_id),
218 event_properties: if let Value::Object(properties) = properties {
219 Some(properties)
220 } else {
221 None
222 },
223 os_name: state.os_name,
224 os_version: state.os_version.clone(),
225 app_version: state.app_version.clone(),
226 signed_in: state.metrics_id.is_some(),
227 app: "Zed",
228 },
229 };
230 state.queue.push(event);
231 if state.device_id.is_some() {
232 if state.queue.len() >= MAX_QUEUE_LEN {
233 drop(state);
234 self.flush();
235 } else {
236 let this = self.clone();
237 let executor = self.executor.clone();
238 state.flush_task = Some(self.executor.spawn(async move {
239 executor.timer(DEBOUNCE_INTERVAL).await;
240 this.flush();
241 }));
242 }
243 }
244 }
245
246 fn flush(self: &Arc<Self>) {
247 let mut state = self.state.lock();
248 let mut events = mem::take(&mut state.queue);
249 state.flush_task.take();
250 drop(state);
251
252 if let Some(token) = MIXPANEL_TOKEN.as_ref() {
253 let this = self.clone();
254 self.executor
255 .spawn(
256 async move {
257 let mut json_bytes = Vec::new();
258
259 if let Some(file) = &mut this.state.lock().log_file {
260 let file = file.as_file_mut();
261 for event in &mut events {
262 json_bytes.clear();
263 serde_json::to_writer(&mut json_bytes, event)?;
264 file.write_all(&json_bytes)?;
265 file.write(b"\n")?;
266
267 event.properties.token = token;
268 }
269 }
270
271 json_bytes.clear();
272 serde_json::to_writer(&mut json_bytes, &events)?;
273 let request = Request::post(MIXPANEL_EVENTS_URL)
274 .header("Content-Type", "application/json")
275 .body(json_bytes.into())?;
276 this.http_client.send(request).await?;
277 Ok(())
278 }
279 .log_err(),
280 )
281 .detach();
282 }
283 }
284}