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