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