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}
116
117#[cfg(debug_assertions)]
118const MAX_QUEUE_LEN: usize = 1;
119
120#[cfg(not(debug_assertions))]
121const MAX_QUEUE_LEN: usize = 10;
122
123#[cfg(debug_assertions)]
124const DEBOUNCE_INTERVAL: Duration = Duration::from_secs(1);
125
126#[cfg(not(debug_assertions))]
127const DEBOUNCE_INTERVAL: Duration = Duration::from_secs(30);
128
129impl Telemetry {
130 pub fn new(client: Arc<dyn HttpClient>, cx: &mut AppContext) -> Arc<Self> {
131 let release_channel = if cx.has_global::<ReleaseChannel>() {
132 Some(cx.global::<ReleaseChannel>().display_name())
133 } else {
134 None
135 };
136
137 // TODO: Replace all hardware stuff with nested SystemSpecs json
138 let this = Arc::new(Self {
139 http_client: client,
140 executor: cx.background_executor().clone(),
141 state: Mutex::new(TelemetryState {
142 app_metadata: cx.app_metadata(),
143 architecture: env::consts::ARCH,
144 release_channel,
145 installation_id: None,
146 metrics_id: None,
147 session_id: None,
148 clickhouse_events_queue: Default::default(),
149 flush_clickhouse_events_task: Default::default(),
150 log_file: None,
151 is_staff: None,
152 first_event_datetime: None,
153 }),
154 });
155
156 // We should only ever have one instance of Telemetry, leak the subscription to keep it alive
157 // rather than store in TelemetryState, complicating spawn as subscriptions are not Send
158 std::mem::forget(cx.on_app_quit({
159 let this = this.clone();
160 move |cx| this.shutdown_telemetry(cx)
161 }));
162
163 this
164 }
165
166 fn shutdown_telemetry(self: &Arc<Self>, cx: &mut AppContext) -> impl Future<Output = ()> {
167 let telemetry_settings = TelemetrySettings::get_global(cx).clone();
168 self.report_app_event(telemetry_settings, "close");
169 Task::ready(())
170 }
171
172 pub fn log_file_path(&self) -> Option<PathBuf> {
173 Some(self.state.lock().log_file.as_ref()?.path().to_path_buf())
174 }
175
176 pub fn start(
177 self: &Arc<Self>,
178 installation_id: Option<String>,
179 session_id: String,
180 cx: &mut AppContext,
181 ) {
182 let mut state = self.state.lock();
183 state.installation_id = installation_id.map(|id| id.into());
184 state.session_id = Some(session_id.into());
185 drop(state);
186
187 let this = self.clone();
188 cx.spawn(|cx| async move {
189 // Avoiding calling `System::new_all()`, as there have been crashes related to it
190 let refresh_kind = RefreshKind::new()
191 .with_memory() // For memory usage
192 .with_processes(ProcessRefreshKind::everything()) // For process usage
193 .with_cpu(CpuRefreshKind::everything()); // For core count
194
195 let mut system = System::new_with_specifics(refresh_kind);
196
197 // Avoiding calling `refresh_all()`, just update what we need
198 system.refresh_specifics(refresh_kind);
199
200 loop {
201 // Waiting some amount of time before the first query is important to get a reasonable value
202 // https://docs.rs/sysinfo/0.29.10/sysinfo/trait.ProcessExt.html#tymethod.cpu_usage
203 const DURATION_BETWEEN_SYSTEM_EVENTS: Duration = Duration::from_secs(60);
204 smol::Timer::after(DURATION_BETWEEN_SYSTEM_EVENTS).await;
205
206 system.refresh_specifics(refresh_kind);
207
208 let current_process = Pid::from_u32(std::process::id());
209 let Some(process) = system.processes().get(¤t_process) else {
210 let process = current_process;
211 log::error!("Failed to find own process {process:?} in system process table");
212 // TODO: Fire an error telemetry event
213 return;
214 };
215
216 let telemetry_settings = if let Ok(telemetry_settings) =
217 cx.update(|cx| *TelemetrySettings::get_global(cx))
218 {
219 telemetry_settings
220 } else {
221 break;
222 };
223
224 this.report_memory_event(
225 telemetry_settings,
226 process.memory(),
227 process.virtual_memory(),
228 );
229 this.report_cpu_event(
230 telemetry_settings,
231 process.cpu_usage(),
232 system.cpus().len() as u32,
233 );
234 }
235 })
236 .detach();
237 }
238
239 pub fn set_authenticated_user_info(
240 self: &Arc<Self>,
241 metrics_id: Option<String>,
242 is_staff: bool,
243 cx: &AppContext,
244 ) {
245 if !TelemetrySettings::get_global(cx).metrics {
246 return;
247 }
248
249 let mut state = self.state.lock();
250 let metrics_id: Option<Arc<str>> = metrics_id.map(|id| id.into());
251 state.metrics_id = metrics_id.clone();
252 state.is_staff = Some(is_staff);
253 drop(state);
254 }
255
256 pub fn report_editor_event(
257 self: &Arc<Self>,
258 telemetry_settings: TelemetrySettings,
259 file_extension: Option<String>,
260 vim_mode: bool,
261 operation: &'static str,
262 copilot_enabled: bool,
263 copilot_enabled_for_language: bool,
264 ) {
265 let event = ClickhouseEvent::Editor {
266 file_extension,
267 vim_mode,
268 operation,
269 copilot_enabled,
270 copilot_enabled_for_language,
271 milliseconds_since_first_event: self.milliseconds_since_first_event(),
272 };
273
274 self.report_clickhouse_event(event, telemetry_settings, false)
275 }
276
277 pub fn report_copilot_event(
278 self: &Arc<Self>,
279 telemetry_settings: TelemetrySettings,
280 suggestion_id: Option<String>,
281 suggestion_accepted: bool,
282 file_extension: Option<String>,
283 ) {
284 let event = ClickhouseEvent::Copilot {
285 suggestion_id,
286 suggestion_accepted,
287 file_extension,
288 milliseconds_since_first_event: self.milliseconds_since_first_event(),
289 };
290
291 self.report_clickhouse_event(event, telemetry_settings, false)
292 }
293
294 pub fn report_assistant_event(
295 self: &Arc<Self>,
296 telemetry_settings: TelemetrySettings,
297 conversation_id: Option<String>,
298 kind: AssistantKind,
299 model: &'static str,
300 ) {
301 let event = ClickhouseEvent::Assistant {
302 conversation_id,
303 kind,
304 model,
305 milliseconds_since_first_event: self.milliseconds_since_first_event(),
306 };
307
308 self.report_clickhouse_event(event, telemetry_settings, false)
309 }
310
311 pub fn report_call_event(
312 self: &Arc<Self>,
313 telemetry_settings: TelemetrySettings,
314 operation: &'static str,
315 room_id: Option<u64>,
316 channel_id: Option<u64>,
317 ) {
318 let event = ClickhouseEvent::Call {
319 operation,
320 room_id,
321 channel_id,
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_cpu_event(
329 self: &Arc<Self>,
330 telemetry_settings: TelemetrySettings,
331 usage_as_percentage: f32,
332 core_count: u32,
333 ) {
334 let event = ClickhouseEvent::Cpu {
335 usage_as_percentage,
336 core_count,
337 milliseconds_since_first_event: self.milliseconds_since_first_event(),
338 };
339
340 self.report_clickhouse_event(event, telemetry_settings, false)
341 }
342
343 pub fn report_memory_event(
344 self: &Arc<Self>,
345 telemetry_settings: TelemetrySettings,
346 memory_in_bytes: u64,
347 virtual_memory_in_bytes: u64,
348 ) {
349 let event = ClickhouseEvent::Memory {
350 memory_in_bytes,
351 virtual_memory_in_bytes,
352 milliseconds_since_first_event: self.milliseconds_since_first_event(),
353 };
354
355 self.report_clickhouse_event(event, telemetry_settings, false)
356 }
357
358 // app_events are called at app open and app close, so flush is set to immediately send
359 pub fn report_app_event(
360 self: &Arc<Self>,
361 telemetry_settings: TelemetrySettings,
362 operation: &'static str,
363 ) {
364 let event = ClickhouseEvent::App {
365 operation,
366 milliseconds_since_first_event: self.milliseconds_since_first_event(),
367 };
368
369 self.report_clickhouse_event(event, telemetry_settings, true)
370 }
371
372 fn milliseconds_since_first_event(&self) -> i64 {
373 let mut state = self.state.lock();
374 match state.first_event_datetime {
375 Some(first_event_datetime) => {
376 let now: DateTime<Utc> = Utc::now();
377 now.timestamp_millis() - first_event_datetime.timestamp_millis()
378 }
379 None => {
380 state.first_event_datetime = Some(Utc::now());
381 0
382 }
383 }
384 }
385
386 fn report_clickhouse_event(
387 self: &Arc<Self>,
388 event: ClickhouseEvent,
389 telemetry_settings: TelemetrySettings,
390 immediate_flush: bool,
391 ) {
392 if !telemetry_settings.metrics {
393 return;
394 }
395
396 let mut state = self.state.lock();
397 let signed_in = state.metrics_id.is_some();
398 state
399 .clickhouse_events_queue
400 .push(ClickhouseEventWrapper { signed_in, event });
401
402 if state.installation_id.is_some() {
403 if immediate_flush || state.clickhouse_events_queue.len() >= MAX_QUEUE_LEN {
404 drop(state);
405 self.flush_clickhouse_events();
406 } else {
407 let this = self.clone();
408 let executor = self.executor.clone();
409 state.flush_clickhouse_events_task = Some(self.executor.spawn(async move {
410 executor.timer(DEBOUNCE_INTERVAL).await;
411 this.flush_clickhouse_events();
412 }));
413 }
414 }
415 }
416
417 pub fn metrics_id(self: &Arc<Self>) -> Option<Arc<str>> {
418 self.state.lock().metrics_id.clone()
419 }
420
421 pub fn installation_id(self: &Arc<Self>) -> Option<Arc<str>> {
422 self.state.lock().installation_id.clone()
423 }
424
425 pub fn is_staff(self: &Arc<Self>) -> Option<bool> {
426 self.state.lock().is_staff
427 }
428
429 fn flush_clickhouse_events(self: &Arc<Self>) {
430 let mut state = self.state.lock();
431 state.first_event_datetime = None;
432 let mut events = mem::take(&mut state.clickhouse_events_queue);
433 state.flush_clickhouse_events_task.take();
434 drop(state);
435
436 let this = self.clone();
437 self.executor
438 .spawn(
439 async move {
440 let mut json_bytes = Vec::new();
441
442 if let Some(file) = &mut this.state.lock().log_file {
443 let file = file.as_file_mut();
444 for event in &mut events {
445 json_bytes.clear();
446 serde_json::to_writer(&mut json_bytes, event)?;
447 file.write_all(&json_bytes)?;
448 file.write(b"\n")?;
449 }
450 }
451
452 {
453 let state = this.state.lock();
454 let request_body = ClickhouseEventRequestBody {
455 token: ZED_SECRET_CLIENT_TOKEN,
456 installation_id: state.installation_id.clone(),
457 session_id: state.session_id.clone(),
458 is_staff: state.is_staff.clone(),
459 app_version: state
460 .app_metadata
461 .app_version
462 .map(|version| version.to_string()),
463 os_name: state.app_metadata.os_name,
464 os_version: state
465 .app_metadata
466 .os_version
467 .map(|version| version.to_string()),
468 architecture: state.architecture,
469
470 release_channel: state.release_channel,
471 events,
472 };
473 json_bytes.clear();
474 serde_json::to_writer(&mut json_bytes, &request_body)?;
475 }
476
477 this.http_client
478 .post_json(CLICKHOUSE_EVENTS_URL.as_str(), json_bytes.into())
479 .await?;
480 anyhow::Ok(())
481 }
482 .log_err(),
483 )
484 .detach();
485 }
486}