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 session_id: u128,
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 os_version: Option<Arc<str>>,
37 os_name: &'static str,
38 queue: Vec<AmplitudeEvent>,
39 next_event_id: usize,
40 flush_task: Option<Task<()>>,
41 log_file: Option<NamedTempFile>,
42}
43
44const AMPLITUDE_EVENTS_URL: &'static str = "https://api2.amplitude.com/batch";
45
46lazy_static! {
47 static ref AMPLITUDE_API_KEY: Option<String> = std::env::var("ZED_AMPLITUDE_API_KEY")
48 .ok()
49 .or_else(|| option_env!("ZED_AMPLITUDE_API_KEY").map(|key| key.to_string()));
50}
51
52#[derive(Serialize)]
53struct AmplitudeEventBatch {
54 api_key: &'static str,
55 events: Vec<AmplitudeEvent>,
56}
57
58#[derive(Serialize)]
59struct AmplitudeEvent {
60 #[serde(skip_serializing_if = "Option::is_none")]
61 user_id: Option<Arc<str>>,
62 device_id: Option<Arc<str>>,
63 event_type: String,
64 #[serde(skip_serializing_if = "Option::is_none")]
65 event_properties: Option<Map<String, Value>>,
66 #[serde(skip_serializing_if = "Option::is_none")]
67 user_properties: Option<Map<String, Value>>,
68 os_name: &'static str,
69 os_version: Option<Arc<str>>,
70 app_version: Option<Arc<str>>,
71 platform: &'static str,
72 event_id: usize,
73 session_id: u128,
74 time: u128,
75}
76
77#[cfg(debug_assertions)]
78const MAX_QUEUE_LEN: usize = 1;
79
80#[cfg(not(debug_assertions))]
81const MAX_QUEUE_LEN: usize = 10;
82
83#[cfg(debug_assertions)]
84const DEBOUNCE_INTERVAL: Duration = Duration::from_secs(1);
85
86#[cfg(not(debug_assertions))]
87const DEBOUNCE_INTERVAL: Duration = Duration::from_secs(30);
88
89impl Telemetry {
90 pub fn new(client: Arc<dyn HttpClient>, cx: &AppContext) -> Arc<Self> {
91 let platform = cx.platform();
92 let this = Arc::new(Self {
93 http_client: client,
94 executor: cx.background().clone(),
95 session_id: SystemTime::now()
96 .duration_since(UNIX_EPOCH)
97 .unwrap()
98 .as_millis(),
99 state: Mutex::new(TelemetryState {
100 os_version: platform
101 .os_version()
102 .log_err()
103 .map(|v| v.to_string().into()),
104 os_name: platform.os_name().into(),
105 app_version: platform
106 .app_version()
107 .log_err()
108 .map(|v| v.to_string().into()),
109 device_id: None,
110 queue: Default::default(),
111 flush_task: Default::default(),
112 next_event_id: 0,
113 log_file: None,
114 metrics_id: None,
115 }),
116 });
117
118 if AMPLITUDE_API_KEY.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: Arc<Mutex<Db>>) {
139 let this = self.clone();
140 self.executor
141 .spawn(
142 async move {
143 let db = db.lock();
144 let device_id = if let Ok(device_id) = db.read_kvp("device_id") {
145 device_id
146 } else {
147 let device_id = Uuid::new_v4().to_string();
148 db.write_kvp("device_id", &device_id)?;
149 device_id
150 };
151
152 drop(db);
153 let device_id = Some(Arc::from(device_id));
154 let mut state = this.state.lock();
155 state.device_id = device_id.clone();
156 for event in &mut state.queue {
157 event.device_id = device_id.clone();
158 }
159 if !state.queue.is_empty() {
160 drop(state);
161 this.flush();
162 }
163
164 anyhow::Ok(())
165 }
166 .log_err(),
167 )
168 .detach();
169 }
170
171 pub fn set_authenticated_user_info(
172 self: &Arc<Self>,
173 metrics_id: Option<String>,
174 is_staff: bool,
175 ) {
176 let is_signed_in = metrics_id.is_some();
177 self.state.lock().metrics_id = metrics_id.map(|s| s.into());
178 if is_signed_in {
179 self.report_event_with_user_properties(
180 "$identify",
181 Default::default(),
182 json!({ "$set": { "staff": is_staff } }),
183 )
184 }
185 }
186
187 pub fn report_event(self: &Arc<Self>, kind: &str, properties: Value) {
188 self.report_event_with_user_properties(kind, properties, Default::default());
189 }
190
191 fn report_event_with_user_properties(
192 self: &Arc<Self>,
193 kind: &str,
194 properties: Value,
195 user_properties: Value,
196 ) {
197 if AMPLITUDE_API_KEY.is_none() {
198 return;
199 }
200
201 let mut state = self.state.lock();
202 let event = AmplitudeEvent {
203 event_type: kind.to_string(),
204 time: SystemTime::now()
205 .duration_since(UNIX_EPOCH)
206 .unwrap()
207 .as_millis(),
208 session_id: self.session_id,
209 event_properties: if let Value::Object(properties) = properties {
210 Some(properties)
211 } else {
212 None
213 },
214 user_properties: if let Value::Object(user_properties) = user_properties {
215 Some(user_properties)
216 } else {
217 None
218 },
219 user_id: state.metrics_id.clone(),
220 device_id: state.device_id.clone(),
221 os_name: state.os_name,
222 platform: "Zed",
223 os_version: state.os_version.clone(),
224 app_version: state.app_version.clone(),
225 event_id: post_inc(&mut state.next_event_id),
226 };
227 state.queue.push(event);
228 if state.device_id.is_some() {
229 if state.queue.len() >= MAX_QUEUE_LEN {
230 drop(state);
231 self.flush();
232 } else {
233 let this = self.clone();
234 let executor = self.executor.clone();
235 state.flush_task = Some(self.executor.spawn(async move {
236 executor.timer(DEBOUNCE_INTERVAL).await;
237 this.flush();
238 }));
239 }
240 }
241 }
242
243 fn flush(self: &Arc<Self>) {
244 let mut state = self.state.lock();
245 let events = mem::take(&mut state.queue);
246 state.flush_task.take();
247 drop(state);
248
249 if let Some(api_key) = AMPLITUDE_API_KEY.as_ref() {
250 let this = self.clone();
251 self.executor
252 .spawn(
253 async move {
254 let mut json_bytes = Vec::new();
255
256 if let Some(file) = &mut this.state.lock().log_file {
257 let file = file.as_file_mut();
258 for event in &events {
259 json_bytes.clear();
260 serde_json::to_writer(&mut json_bytes, event)?;
261 file.write_all(&json_bytes)?;
262 file.write(b"\n")?;
263 }
264 }
265
266 let batch = AmplitudeEventBatch { api_key, events };
267 json_bytes.clear();
268 serde_json::to_writer(&mut json_bytes, &batch)?;
269 let request =
270 Request::post(AMPLITUDE_EVENTS_URL).body(json_bytes.into())?;
271 this.http_client.send(request).await?;
272 Ok(())
273 }
274 .log_err(),
275 )
276 .detach();
277 }
278 }
279}