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