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