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 AmplitudeTelemetry {
25 http_client: Arc<dyn HttpClient>,
26 executor: Arc<Background>,
27 session_id: u128,
28 state: Mutex<AmplitudeTelemetryState>,
29}
30
31#[derive(Default)]
32struct AmplitudeTelemetryState {
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 #[serde(rename = "App")]
72 app: &'static str,
73 event_id: usize,
74 session_id: u128,
75 time: u128,
76}
77
78#[cfg(debug_assertions)]
79const MAX_QUEUE_LEN: usize = 1;
80
81#[cfg(not(debug_assertions))]
82const MAX_QUEUE_LEN: usize = 10;
83
84#[cfg(debug_assertions)]
85const DEBOUNCE_INTERVAL: Duration = Duration::from_secs(1);
86
87#[cfg(not(debug_assertions))]
88const DEBOUNCE_INTERVAL: Duration = Duration::from_secs(30);
89
90impl AmplitudeTelemetry {
91 pub fn new(client: Arc<dyn HttpClient>, cx: &AppContext) -> Arc<Self> {
92 let platform = cx.platform();
93 let this = Arc::new(Self {
94 http_client: client,
95 executor: cx.background().clone(),
96 session_id: SystemTime::now()
97 .duration_since(UNIX_EPOCH)
98 .unwrap()
99 .as_millis(),
100 state: Mutex::new(AmplitudeTelemetryState {
101 os_version: platform.os_version().ok().map(|v| v.to_string().into()),
102 os_name: platform.os_name().into(),
103 app_version: platform.app_version().ok().map(|v| v.to_string().into()),
104 device_id: None,
105 queue: Default::default(),
106 flush_task: Default::default(),
107 next_event_id: 0,
108 log_file: None,
109 metrics_id: None,
110 }),
111 });
112
113 if AMPLITUDE_API_KEY.is_some() {
114 this.executor
115 .spawn({
116 let this = this.clone();
117 async move {
118 if let Some(tempfile) = NamedTempFile::new().log_err() {
119 this.state.lock().log_file = Some(tempfile);
120 }
121 }
122 })
123 .detach();
124 }
125
126 this
127 }
128
129 pub fn log_file_path(&self) -> Option<PathBuf> {
130 Some(self.state.lock().log_file.as_ref()?.path().to_path_buf())
131 }
132
133 pub fn start(self: &Arc<Self>, db: Db) {
134 let this = self.clone();
135 self.executor
136 .spawn(
137 async move {
138 let device_id = if let Ok(Some(device_id)) = db.read_kvp("device_id") {
139 device_id
140 } else {
141 let device_id = Uuid::new_v4().to_string();
142 db.write_kvp("device_id", &device_id)?;
143 device_id
144 };
145
146 let device_id = Some(Arc::from(device_id));
147 let mut state = this.state.lock();
148 state.device_id = device_id.clone();
149 for event in &mut state.queue {
150 event.device_id = device_id.clone();
151 }
152 if !state.queue.is_empty() {
153 drop(state);
154 this.flush();
155 }
156
157 anyhow::Ok(())
158 }
159 .log_err(),
160 )
161 .detach();
162 }
163
164 pub fn set_authenticated_user_info(
165 self: &Arc<Self>,
166 metrics_id: Option<String>,
167 is_staff: bool,
168 ) {
169 let is_signed_in = metrics_id.is_some();
170 self.state.lock().metrics_id = metrics_id.map(|s| s.into());
171 if is_signed_in {
172 self.report_event_with_user_properties(
173 "$identify",
174 Default::default(),
175 json!({ "$set": { "staff": is_staff } }),
176 )
177 }
178 }
179
180 pub fn report_event(self: &Arc<Self>, kind: &str, properties: Value) {
181 self.report_event_with_user_properties(kind, properties, Default::default());
182 }
183
184 fn report_event_with_user_properties(
185 self: &Arc<Self>,
186 kind: &str,
187 properties: Value,
188 user_properties: Value,
189 ) {
190 if AMPLITUDE_API_KEY.is_none() {
191 return;
192 }
193
194 let mut state = self.state.lock();
195 let event = AmplitudeEvent {
196 event_type: kind.to_string(),
197 time: SystemTime::now()
198 .duration_since(UNIX_EPOCH)
199 .unwrap()
200 .as_millis(),
201 session_id: self.session_id,
202 event_properties: if let Value::Object(properties) = properties {
203 Some(properties)
204 } else {
205 None
206 },
207 user_properties: if let Value::Object(user_properties) = user_properties {
208 Some(user_properties)
209 } else {
210 None
211 },
212 user_id: state.metrics_id.clone(),
213 device_id: state.device_id.clone(),
214 os_name: state.os_name,
215 app: "Zed",
216 os_version: state.os_version.clone(),
217 app_version: state.app_version.clone(),
218 event_id: post_inc(&mut state.next_event_id),
219 };
220 state.queue.push(event);
221 if state.device_id.is_some() {
222 if state.queue.len() >= MAX_QUEUE_LEN {
223 drop(state);
224 self.flush();
225 } else {
226 let this = self.clone();
227 let executor = self.executor.clone();
228 state.flush_task = Some(self.executor.spawn(async move {
229 executor.timer(DEBOUNCE_INTERVAL).await;
230 this.flush();
231 }));
232 }
233 }
234 }
235
236 fn flush(self: &Arc<Self>) {
237 let mut state = self.state.lock();
238 let events = mem::take(&mut state.queue);
239 state.flush_task.take();
240 drop(state);
241
242 if let Some(api_key) = AMPLITUDE_API_KEY.as_ref() {
243 let this = self.clone();
244 self.executor
245 .spawn(
246 async move {
247 let mut json_bytes = Vec::new();
248
249 if let Some(file) = &mut this.state.lock().log_file {
250 let file = file.as_file_mut();
251 for event in &events {
252 json_bytes.clear();
253 serde_json::to_writer(&mut json_bytes, event)?;
254 file.write_all(&json_bytes)?;
255 file.write(b"\n")?;
256 }
257 }
258
259 let batch = AmplitudeEventBatch { api_key, events };
260 json_bytes.clear();
261 serde_json::to_writer(&mut json_bytes, &batch)?;
262 let request =
263 Request::post(AMPLITUDE_EVENTS_URL).body(json_bytes.into())?;
264 this.http_client.send(request).await?;
265 Ok(())
266 }
267 .log_err(),
268 )
269 .detach();
270 }
271 }
272}