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