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