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: &'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 os_name: &'static str,
73 os_version: Option<Arc<str>>,
74 release_channel: &'static str,
75 app_version: Option<Arc<str>>,
76 signed_in: bool,
77 #[serde(rename = "App")]
78 app: &'static str,
79}
80
81#[derive(Serialize)]
82struct MixpanelEngageRequest {
83 #[serde(rename = "$token")]
84 token: &'static str,
85 #[serde(rename = "$distinct_id")]
86 distinct_id: Arc<str>,
87 #[serde(rename = "$set")]
88 set: Value,
89}
90
91#[cfg(debug_assertions)]
92const MAX_QUEUE_LEN: usize = 1;
93
94#[cfg(not(debug_assertions))]
95const MAX_QUEUE_LEN: usize = 10;
96
97#[cfg(debug_assertions)]
98const DEBOUNCE_INTERVAL: Duration = Duration::from_secs(1);
99
100#[cfg(not(debug_assertions))]
101const DEBOUNCE_INTERVAL: Duration = Duration::from_secs(30);
102
103impl Telemetry {
104 pub fn new(client: Arc<dyn HttpClient>, cx: &AppContext) -> Arc<Self> {
105 let platform = cx.platform();
106 let release_channel = cx.global::<ReleaseChannel>().name();
107 let this = Arc::new(Self {
108 http_client: client,
109 executor: cx.background().clone(),
110 state: Mutex::new(TelemetryState {
111 os_version: platform.os_version().ok().map(|v| v.to_string().into()),
112 os_name: platform.os_name().into(),
113 app_version: platform.app_version().ok().map(|v| v.to_string().into()),
114 release_channel,
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 release_channel: state.release_channel,
231 app_version: state.app_version.clone(),
232 signed_in: state.metrics_id.is_some(),
233 app: "Zed",
234 },
235 };
236 state.queue.push(event);
237 if state.device_id.is_some() {
238 if state.queue.len() >= MAX_QUEUE_LEN {
239 drop(state);
240 self.flush();
241 } else {
242 let this = self.clone();
243 let executor = self.executor.clone();
244 state.flush_task = Some(self.executor.spawn(async move {
245 executor.timer(DEBOUNCE_INTERVAL).await;
246 this.flush();
247 }));
248 }
249 }
250 }
251
252 fn flush(self: &Arc<Self>) {
253 let mut state = self.state.lock();
254 let mut events = mem::take(&mut state.queue);
255 state.flush_task.take();
256 drop(state);
257
258 if let Some(token) = MIXPANEL_TOKEN.as_ref() {
259 let this = self.clone();
260 self.executor
261 .spawn(
262 async move {
263 let mut json_bytes = Vec::new();
264
265 if let Some(file) = &mut this.state.lock().log_file {
266 let file = file.as_file_mut();
267 for event in &mut events {
268 json_bytes.clear();
269 serde_json::to_writer(&mut json_bytes, event)?;
270 file.write_all(&json_bytes)?;
271 file.write(b"\n")?;
272
273 event.properties.token = token;
274 }
275 }
276
277 json_bytes.clear();
278 serde_json::to_writer(&mut json_bytes, &events)?;
279 let request = Request::post(MIXPANEL_EVENTS_URL)
280 .header("Content-Type", "application/json")
281 .body(json_bytes.into())?;
282 this.http_client.send(request).await?;
283 Ok(())
284 }
285 .log_err(),
286 )
287 .detach();
288 }
289 }
290}