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 platform: &'static str,
75}
76
77#[derive(Serialize)]
78struct MixpanelEngageRequest {
79 #[serde(rename = "$token")]
80 token: &'static str,
81 #[serde(rename = "$distinct_id")]
82 distinct_id: Arc<str>,
83 #[serde(rename = "$set")]
84 set: Value,
85}
86
87#[cfg(debug_assertions)]
88const MAX_QUEUE_LEN: usize = 1;
89
90#[cfg(not(debug_assertions))]
91const MAX_QUEUE_LEN: usize = 10;
92
93#[cfg(debug_assertions)]
94const DEBOUNCE_INTERVAL: Duration = Duration::from_secs(1);
95
96#[cfg(not(debug_assertions))]
97const DEBOUNCE_INTERVAL: Duration = Duration::from_secs(30);
98
99impl Telemetry {
100 pub fn new(client: Arc<dyn HttpClient>, cx: &AppContext) -> Arc<Self> {
101 let platform = cx.platform();
102 let this = Arc::new(Self {
103 http_client: client,
104 executor: cx.background().clone(),
105 state: Mutex::new(TelemetryState {
106 os_version: platform
107 .os_version()
108 .log_err()
109 .map(|v| v.to_string().into()),
110 os_name: platform.os_name().into(),
111 app_version: platform
112 .app_version()
113 .log_err()
114 .map(|v| v.to_string().into()),
115 device_id: None,
116 metrics_id: None,
117 queue: Default::default(),
118 flush_task: Default::default(),
119 next_event_id: 0,
120 log_file: None,
121 }),
122 });
123
124 if MIXPANEL_TOKEN.is_some() {
125 this.executor
126 .spawn({
127 let this = this.clone();
128 async move {
129 if let Some(tempfile) = NamedTempFile::new().log_err() {
130 this.state.lock().log_file = Some(tempfile);
131 }
132 }
133 })
134 .detach();
135 }
136
137 this
138 }
139
140 pub fn log_file_path(&self) -> Option<PathBuf> {
141 Some(self.state.lock().log_file.as_ref()?.path().to_path_buf())
142 }
143
144 pub fn start(self: &Arc<Self>, db: Db) {
145 let this = self.clone();
146 self.executor
147 .spawn(
148 async move {
149 let device_id = if let Ok(Some(device_id)) = db.read_kvp("device_id") {
150 device_id
151 } else {
152 let device_id = Uuid::new_v4().to_string();
153 db.write_kvp("device_id", &device_id)?;
154 device_id
155 };
156
157 let device_id: Arc<str> = device_id.into();
158 let mut state = this.state.lock();
159 state.device_id = Some(device_id.clone());
160 for event in &mut state.queue {
161 event
162 .properties
163 .distinct_id
164 .get_or_insert_with(|| device_id.clone());
165 }
166 if !state.queue.is_empty() {
167 drop(state);
168 this.flush();
169 }
170
171 anyhow::Ok(())
172 }
173 .log_err(),
174 )
175 .detach();
176 }
177
178 pub fn set_authenticated_user_info(
179 self: &Arc<Self>,
180 metrics_id: Option<String>,
181 is_staff: bool,
182 ) {
183 let this = self.clone();
184 let mut state = self.state.lock();
185 let device_id = state.device_id.clone();
186 let metrics_id: Option<Arc<str>> = metrics_id.map(|id| id.into());
187 state.metrics_id = metrics_id.clone();
188 drop(state);
189
190 if let Some((token, device_id)) = MIXPANEL_TOKEN.as_ref().zip(device_id) {
191 self.executor
192 .spawn(
193 async move {
194 let json_bytes = serde_json::to_vec(&[MixpanelEngageRequest {
195 token,
196 distinct_id: device_id,
197 set: json!({ "staff": is_staff, "id": metrics_id }),
198 }])?;
199 let request = Request::post(MIXPANEL_ENGAGE_URL)
200 .header("Content-Type", "application/json")
201 .body(json_bytes.into())?;
202 this.http_client.send(request).await?;
203 Ok(())
204 }
205 .log_err(),
206 )
207 .detach();
208 }
209 }
210
211 pub fn report_event(self: &Arc<Self>, kind: &str, properties: Value) {
212 let mut state = self.state.lock();
213 let event = MixpanelEvent {
214 event: kind.to_string(),
215 properties: MixpanelEventProperties {
216 token: "",
217 time: SystemTime::now()
218 .duration_since(UNIX_EPOCH)
219 .unwrap()
220 .as_millis(),
221 distinct_id: state.device_id.clone(),
222 insert_id: post_inc(&mut state.next_event_id),
223 event_properties: if let Value::Object(properties) = properties {
224 Some(properties)
225 } else {
226 None
227 },
228 os_name: state.os_name,
229 os_version: state.os_version.clone(),
230 app_version: state.app_version.clone(),
231 signed_in: state.metrics_id.is_some(),
232 platform: "Zed",
233 },
234 };
235 state.queue.push(event);
236 if state.device_id.is_some() {
237 if state.queue.len() >= MAX_QUEUE_LEN {
238 drop(state);
239 self.flush();
240 } else {
241 let this = self.clone();
242 let executor = self.executor.clone();
243 state.flush_task = Some(self.executor.spawn(async move {
244 executor.timer(DEBOUNCE_INTERVAL).await;
245 this.flush();
246 }));
247 }
248 }
249 }
250
251 fn flush(self: &Arc<Self>) {
252 let mut state = self.state.lock();
253 let mut events = mem::take(&mut state.queue);
254 state.flush_task.take();
255 drop(state);
256
257 if let Some(token) = MIXPANEL_TOKEN.as_ref() {
258 let this = self.clone();
259 self.executor
260 .spawn(
261 async move {
262 let mut json_bytes = Vec::new();
263
264 if let Some(file) = &mut this.state.lock().log_file {
265 let file = file.as_file_mut();
266 for event in &mut events {
267 json_bytes.clear();
268 serde_json::to_writer(&mut json_bytes, event)?;
269 file.write_all(&json_bytes)?;
270 file.write(b"\n")?;
271
272 event.properties.token = token;
273 }
274 }
275
276 json_bytes.clear();
277 serde_json::to_writer(&mut json_bytes, &events)?;
278 let request = Request::post(MIXPANEL_EVENTS_URL)
279 .header("Content-Type", "application/json")
280 .body(json_bytes.into())?;
281 this.http_client.send(request).await?;
282 Ok(())
283 }
284 .log_err(),
285 )
286 .detach();
287 }
288 }
289}