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