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