1use crate::{TelemetrySettings, ZED_SECRET_CLIENT_TOKEN, ZED_SERVER_URL};
2use chrono::{DateTime, Utc};
3use gpui::{serde_json, AppContext, AppMetadata, BackgroundExecutor, Task};
4use lazy_static::lazy_static;
5use parking_lot::Mutex;
6use serde::Serialize;
7use settings::Settings;
8use std::{env, io::Write, mem, path::PathBuf, sync::Arc, time::Duration};
9use sysinfo::{
10 CpuRefreshKind, Pid, PidExt, ProcessExt, ProcessRefreshKind, RefreshKind, System, SystemExt,
11};
12use tempfile::NamedTempFile;
13use util::http::HttpClient;
14use util::{channel::ReleaseChannel, TryFutureExt};
15
16pub struct Telemetry {
17 http_client: Arc<dyn HttpClient>,
18 executor: BackgroundExecutor,
19 state: Mutex<TelemetryState>,
20}
21
22struct TelemetryState {
23 metrics_id: Option<Arc<str>>, // Per logged-in user
24 installation_id: Option<Arc<str>>, // Per app installation (different for dev, nightly, preview, and stable)
25 session_id: Option<Arc<str>>, // Per app launch
26 release_channel: Option<&'static str>,
27 app_metadata: AppMetadata,
28 architecture: &'static str,
29 clickhouse_events_queue: Vec<ClickhouseEventWrapper>,
30 flush_clickhouse_events_task: Option<Task<()>>,
31 log_file: Option<NamedTempFile>,
32 is_staff: Option<bool>,
33 first_event_datetime: Option<DateTime<Utc>>,
34}
35
36const CLICKHOUSE_EVENTS_URL_PATH: &'static str = "/api/events";
37
38lazy_static! {
39 static ref CLICKHOUSE_EVENTS_URL: String =
40 format!("{}{}", *ZED_SERVER_URL, CLICKHOUSE_EVENTS_URL_PATH);
41}
42
43#[derive(Serialize, Debug)]
44struct ClickhouseEventRequestBody {
45 token: &'static str,
46 installation_id: Option<Arc<str>>,
47 session_id: Option<Arc<str>>,
48 is_staff: Option<bool>,
49 app_version: Option<String>,
50 os_name: &'static str,
51 os_version: Option<String>,
52 architecture: &'static str,
53 release_channel: Option<&'static str>,
54 events: Vec<ClickhouseEventWrapper>,
55}
56
57#[derive(Serialize, Debug)]
58struct ClickhouseEventWrapper {
59 signed_in: bool,
60 #[serde(flatten)]
61 event: ClickhouseEvent,
62}
63
64#[derive(Serialize, Debug)]
65#[serde(rename_all = "snake_case")]
66pub enum AssistantKind {
67 Panel,
68 Inline,
69}
70
71#[derive(Serialize, Debug)]
72#[serde(tag = "type")]
73pub enum ClickhouseEvent {
74 Editor {
75 operation: &'static str,
76 file_extension: Option<String>,
77 vim_mode: bool,
78 copilot_enabled: bool,
79 copilot_enabled_for_language: bool,
80 milliseconds_since_first_event: i64,
81 },
82 Copilot {
83 suggestion_id: Option<String>,
84 suggestion_accepted: bool,
85 file_extension: Option<String>,
86 milliseconds_since_first_event: i64,
87 },
88 Call {
89 operation: &'static str,
90 room_id: Option<u64>,
91 channel_id: Option<u64>,
92 milliseconds_since_first_event: i64,
93 },
94 Assistant {
95 conversation_id: Option<String>,
96 kind: AssistantKind,
97 model: &'static str,
98 milliseconds_since_first_event: i64,
99 },
100 Cpu {
101 usage_as_percentage: f32,
102 core_count: u32,
103 milliseconds_since_first_event: i64,
104 },
105 Memory {
106 memory_in_bytes: u64,
107 virtual_memory_in_bytes: u64,
108 milliseconds_since_first_event: i64,
109 },
110 App {
111 operation: &'static str,
112 milliseconds_since_first_event: i64,
113 },
114}
115
116#[cfg(debug_assertions)]
117const MAX_QUEUE_LEN: usize = 1;
118
119#[cfg(not(debug_assertions))]
120const MAX_QUEUE_LEN: usize = 10;
121
122#[cfg(debug_assertions)]
123const DEBOUNCE_INTERVAL: Duration = Duration::from_secs(1);
124
125#[cfg(not(debug_assertions))]
126const DEBOUNCE_INTERVAL: Duration = Duration::from_secs(30);
127
128impl Telemetry {
129 pub fn new(client: Arc<dyn HttpClient>, cx: &AppContext) -> Arc<Self> {
130 let release_channel = if cx.has_global::<ReleaseChannel>() {
131 Some(cx.global::<ReleaseChannel>().display_name())
132 } else {
133 None
134 };
135 // TODO: Replace all hardware stuff with nested SystemSpecs json
136 let this = Arc::new(Self {
137 http_client: client,
138 executor: cx.background_executor().clone(),
139 state: Mutex::new(TelemetryState {
140 app_metadata: cx.app_metadata(),
141 architecture: env::consts::ARCH,
142 release_channel,
143 installation_id: None,
144 metrics_id: None,
145 session_id: None,
146 clickhouse_events_queue: Default::default(),
147 flush_clickhouse_events_task: Default::default(),
148 log_file: None,
149 is_staff: None,
150 first_event_datetime: None,
151 }),
152 });
153
154 this
155 }
156
157 pub fn log_file_path(&self) -> Option<PathBuf> {
158 Some(self.state.lock().log_file.as_ref()?.path().to_path_buf())
159 }
160
161 pub fn start(
162 self: &Arc<Self>,
163 installation_id: Option<String>,
164 session_id: String,
165 cx: &mut AppContext,
166 ) {
167 let mut state = self.state.lock();
168 state.installation_id = installation_id.map(|id| id.into());
169 state.session_id = Some(session_id.into());
170 drop(state);
171
172 let this = self.clone();
173 cx.spawn(|cx| async move {
174 // Avoiding calling `System::new_all()`, as there have been crashes related to it
175 let refresh_kind = RefreshKind::new()
176 .with_memory() // For memory usage
177 .with_processes(ProcessRefreshKind::everything()) // For process usage
178 .with_cpu(CpuRefreshKind::everything()); // For core count
179
180 let mut system = System::new_with_specifics(refresh_kind);
181
182 // Avoiding calling `refresh_all()`, just update what we need
183 system.refresh_specifics(refresh_kind);
184
185 loop {
186 // Waiting some amount of time before the first query is important to get a reasonable value
187 // https://docs.rs/sysinfo/0.29.10/sysinfo/trait.ProcessExt.html#tymethod.cpu_usage
188 const DURATION_BETWEEN_SYSTEM_EVENTS: Duration = Duration::from_secs(60);
189 smol::Timer::after(DURATION_BETWEEN_SYSTEM_EVENTS).await;
190
191 system.refresh_specifics(refresh_kind);
192
193 let current_process = Pid::from_u32(std::process::id());
194 let Some(process) = system.processes().get(¤t_process) else {
195 let process = current_process;
196 log::error!("Failed to find own process {process:?} in system process table");
197 // TODO: Fire an error telemetry event
198 return;
199 };
200
201 let telemetry_settings = if let Ok(telemetry_settings) =
202 cx.update(|cx| *TelemetrySettings::get_global(cx))
203 {
204 telemetry_settings
205 } else {
206 break;
207 };
208
209 this.report_memory_event(
210 telemetry_settings,
211 process.memory(),
212 process.virtual_memory(),
213 );
214 this.report_cpu_event(
215 telemetry_settings,
216 process.cpu_usage(),
217 system.cpus().len() as u32,
218 );
219 }
220 })
221 .detach();
222 }
223
224 pub fn set_authenticated_user_info(
225 self: &Arc<Self>,
226 metrics_id: Option<String>,
227 is_staff: bool,
228 cx: &AppContext,
229 ) {
230 if !TelemetrySettings::get_global(cx).metrics {
231 return;
232 }
233
234 let mut state = self.state.lock();
235 let metrics_id: Option<Arc<str>> = metrics_id.map(|id| id.into());
236 state.metrics_id = metrics_id.clone();
237 state.is_staff = Some(is_staff);
238 drop(state);
239 }
240
241 pub fn report_editor_event(
242 self: &Arc<Self>,
243 telemetry_settings: TelemetrySettings,
244 file_extension: Option<String>,
245 vim_mode: bool,
246 operation: &'static str,
247 copilot_enabled: bool,
248 copilot_enabled_for_language: bool,
249 ) {
250 let event = ClickhouseEvent::Editor {
251 file_extension,
252 vim_mode,
253 operation,
254 copilot_enabled,
255 copilot_enabled_for_language,
256 milliseconds_since_first_event: self.milliseconds_since_first_event(),
257 };
258
259 self.report_clickhouse_event(event, telemetry_settings, false)
260 }
261
262 pub fn report_copilot_event(
263 self: &Arc<Self>,
264 telemetry_settings: TelemetrySettings,
265 suggestion_id: Option<String>,
266 suggestion_accepted: bool,
267 file_extension: Option<String>,
268 ) {
269 let event = ClickhouseEvent::Copilot {
270 suggestion_id,
271 suggestion_accepted,
272 file_extension,
273 milliseconds_since_first_event: self.milliseconds_since_first_event(),
274 };
275
276 self.report_clickhouse_event(event, telemetry_settings, false)
277 }
278
279 pub fn report_assistant_event(
280 self: &Arc<Self>,
281 telemetry_settings: TelemetrySettings,
282 conversation_id: Option<String>,
283 kind: AssistantKind,
284 model: &'static str,
285 ) {
286 let event = ClickhouseEvent::Assistant {
287 conversation_id,
288 kind,
289 model,
290 milliseconds_since_first_event: self.milliseconds_since_first_event(),
291 };
292
293 self.report_clickhouse_event(event, telemetry_settings, false)
294 }
295
296 pub fn report_call_event(
297 self: &Arc<Self>,
298 telemetry_settings: TelemetrySettings,
299 operation: &'static str,
300 room_id: Option<u64>,
301 channel_id: Option<u64>,
302 ) {
303 let event = ClickhouseEvent::Call {
304 operation,
305 room_id,
306 channel_id,
307 milliseconds_since_first_event: self.milliseconds_since_first_event(),
308 };
309
310 self.report_clickhouse_event(event, telemetry_settings, false)
311 }
312
313 pub fn report_cpu_event(
314 self: &Arc<Self>,
315 telemetry_settings: TelemetrySettings,
316 usage_as_percentage: f32,
317 core_count: u32,
318 ) {
319 let event = ClickhouseEvent::Cpu {
320 usage_as_percentage,
321 core_count,
322 milliseconds_since_first_event: self.milliseconds_since_first_event(),
323 };
324
325 self.report_clickhouse_event(event, telemetry_settings, false)
326 }
327
328 pub fn report_memory_event(
329 self: &Arc<Self>,
330 telemetry_settings: TelemetrySettings,
331 memory_in_bytes: u64,
332 virtual_memory_in_bytes: u64,
333 ) {
334 let event = ClickhouseEvent::Memory {
335 memory_in_bytes,
336 virtual_memory_in_bytes,
337 milliseconds_since_first_event: self.milliseconds_since_first_event(),
338 };
339
340 self.report_clickhouse_event(event, telemetry_settings, false)
341 }
342
343 // app_events are called at app open and app close, so flush is set to immediately send
344 pub fn report_app_event(
345 self: &Arc<Self>,
346 telemetry_settings: TelemetrySettings,
347 operation: &'static str,
348 ) {
349 let event = ClickhouseEvent::App {
350 operation,
351 milliseconds_since_first_event: self.milliseconds_since_first_event(),
352 };
353
354 self.report_clickhouse_event(event, telemetry_settings, true)
355 }
356
357 fn milliseconds_since_first_event(&self) -> i64 {
358 let mut state = self.state.lock();
359 match state.first_event_datetime {
360 Some(first_event_datetime) => {
361 let now: DateTime<Utc> = Utc::now();
362 now.timestamp_millis() - first_event_datetime.timestamp_millis()
363 }
364 None => {
365 state.first_event_datetime = Some(Utc::now());
366 0
367 }
368 }
369 }
370
371 fn report_clickhouse_event(
372 self: &Arc<Self>,
373 event: ClickhouseEvent,
374 telemetry_settings: TelemetrySettings,
375 immediate_flush: bool,
376 ) {
377 if !telemetry_settings.metrics {
378 return;
379 }
380
381 let mut state = self.state.lock();
382 let signed_in = state.metrics_id.is_some();
383 state
384 .clickhouse_events_queue
385 .push(ClickhouseEventWrapper { signed_in, event });
386
387 if state.installation_id.is_some() {
388 if immediate_flush || state.clickhouse_events_queue.len() >= MAX_QUEUE_LEN {
389 drop(state);
390 self.flush_clickhouse_events();
391 } else {
392 let this = self.clone();
393 let executor = self.executor.clone();
394 state.flush_clickhouse_events_task = Some(self.executor.spawn(async move {
395 executor.timer(DEBOUNCE_INTERVAL).await;
396 this.flush_clickhouse_events();
397 }));
398 }
399 }
400 }
401
402 pub fn metrics_id(self: &Arc<Self>) -> Option<Arc<str>> {
403 self.state.lock().metrics_id.clone()
404 }
405
406 pub fn installation_id(self: &Arc<Self>) -> Option<Arc<str>> {
407 self.state.lock().installation_id.clone()
408 }
409
410 pub fn is_staff(self: &Arc<Self>) -> Option<bool> {
411 self.state.lock().is_staff
412 }
413
414 fn flush_clickhouse_events(self: &Arc<Self>) {
415 let mut state = self.state.lock();
416 state.first_event_datetime = None;
417 let mut events = mem::take(&mut state.clickhouse_events_queue);
418 state.flush_clickhouse_events_task.take();
419 drop(state);
420
421 let this = self.clone();
422 self.executor
423 .spawn(
424 async move {
425 let mut json_bytes = Vec::new();
426
427 if let Some(file) = &mut this.state.lock().log_file {
428 let file = file.as_file_mut();
429 for event in &mut events {
430 json_bytes.clear();
431 serde_json::to_writer(&mut json_bytes, event)?;
432 file.write_all(&json_bytes)?;
433 file.write(b"\n")?;
434 }
435 }
436
437 {
438 let state = this.state.lock();
439 let request_body = ClickhouseEventRequestBody {
440 token: ZED_SECRET_CLIENT_TOKEN,
441 installation_id: state.installation_id.clone(),
442 session_id: state.session_id.clone(),
443 is_staff: state.is_staff.clone(),
444 app_version: state
445 .app_metadata
446 .app_version
447 .map(|version| version.to_string()),
448 os_name: state.app_metadata.os_name,
449 os_version: state
450 .app_metadata
451 .os_version
452 .map(|version| version.to_string()),
453 architecture: state.architecture,
454
455 release_channel: state.release_channel,
456 events,
457 };
458 json_bytes.clear();
459 serde_json::to_writer(&mut json_bytes, &request_body)?;
460 }
461
462 this.http_client
463 .post_json(CLICKHOUSE_EVENTS_URL.as_str(), json_bytes.into())
464 .await?;
465 anyhow::Ok(())
466 }
467 .log_err(),
468 )
469 .detach();
470 }
471}