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