telemetry.rs

  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        self.report_app_event("close", true, cx);
181        Task::ready(())
182    }
183
184    pub fn log_file_path(&self) -> Option<PathBuf> {
185        Some(self.state.lock().log_file.as_ref()?.path().to_path_buf())
186    }
187
188    pub fn start(
189        self: &Arc<Self>,
190        installation_id: Option<String>,
191        session_id: String,
192        cx: &mut AppContext,
193    ) {
194        let mut state = self.state.lock();
195        state.installation_id = installation_id.map(|id| id.into());
196        state.session_id = Some(session_id.into());
197        drop(state);
198
199        let this = self.clone();
200        cx.spawn(|cx| async move {
201            // Avoiding calling `System::new_all()`, as there have been crashes related to it
202            let refresh_kind = RefreshKind::new()
203                .with_memory() // For memory usage
204                .with_processes(ProcessRefreshKind::everything()) // For process usage
205                .with_cpu(CpuRefreshKind::everything()); // For core count
206
207            let mut system = System::new_with_specifics(refresh_kind);
208
209            // Avoiding calling `refresh_all()`, just update what we need
210            system.refresh_specifics(refresh_kind);
211
212            // Waiting some amount of time before the first query is important to get a reasonable value
213            // https://docs.rs/sysinfo/0.29.10/sysinfo/trait.ProcessExt.html#tymethod.cpu_usage
214            const DURATION_BETWEEN_SYSTEM_EVENTS: Duration = Duration::from_secs(4 * 60);
215
216            loop {
217                smol::Timer::after(DURATION_BETWEEN_SYSTEM_EVENTS).await;
218
219                system.refresh_specifics(refresh_kind);
220
221                let current_process = Pid::from_u32(std::process::id());
222                let Some(process) = system.processes().get(&current_process) else {
223                    let process = current_process;
224                    log::error!("Failed to find own process {process:?} in system process table");
225                    // TODO: Fire an error telemetry event
226                    return;
227                };
228
229                cx.update(|cx| {
230                    this.report_memory_event(process.memory(), process.virtual_memory(), cx);
231                    this.report_cpu_event(process.cpu_usage(), system.cpus().len() as u32, cx);
232                })
233                .ok();
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        file_extension: Option<String>,
259        vim_mode: bool,
260        operation: &'static str,
261        copilot_enabled: bool,
262        copilot_enabled_for_language: bool,
263        cx: &AppContext,
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, false, cx)
275    }
276
277    pub fn report_copilot_event(
278        self: &Arc<Self>,
279        suggestion_id: Option<String>,
280        suggestion_accepted: bool,
281        file_extension: Option<String>,
282        cx: &AppContext,
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, false, cx)
292    }
293
294    pub fn report_assistant_event(
295        self: &Arc<Self>,
296        conversation_id: Option<String>,
297        kind: AssistantKind,
298        model: &'static str,
299        cx: &AppContext,
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, false, cx)
309    }
310
311    pub fn report_call_event(
312        self: &Arc<Self>,
313        operation: &'static str,
314        room_id: Option<u64>,
315        channel_id: Option<u64>,
316        cx: &AppContext,
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, false, cx)
326    }
327
328    pub fn report_cpu_event(
329        self: &Arc<Self>,
330        usage_as_percentage: f32,
331        core_count: u32,
332        cx: &AppContext,
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, false, cx)
341    }
342
343    pub fn report_memory_event(
344        self: &Arc<Self>,
345        memory_in_bytes: u64,
346        virtual_memory_in_bytes: u64,
347        cx: &AppContext,
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, false, cx)
356    }
357
358    pub fn report_app_event(
359        self: &Arc<Self>,
360        operation: &'static str,
361        immediate_flush: bool,
362        cx: &AppContext,
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, immediate_flush, cx)
370    }
371
372    pub fn report_setting_event(
373        self: &Arc<Self>,
374        setting: &'static str,
375        value: String,
376        cx: &AppContext,
377    ) {
378        let event = ClickhouseEvent::Setting {
379            setting,
380            value,
381            milliseconds_since_first_event: self.milliseconds_since_first_event(),
382        };
383
384        self.report_clickhouse_event(event, false, cx)
385    }
386
387    fn milliseconds_since_first_event(&self) -> i64 {
388        let mut state = self.state.lock();
389        match state.first_event_datetime {
390            Some(first_event_datetime) => {
391                let now: DateTime<Utc> = Utc::now();
392                now.timestamp_millis() - first_event_datetime.timestamp_millis()
393            }
394            None => {
395                state.first_event_datetime = Some(Utc::now());
396                0
397            }
398        }
399    }
400
401    fn report_clickhouse_event(
402        self: &Arc<Self>,
403        event: ClickhouseEvent,
404        immediate_flush: bool,
405        cx: &AppContext,
406    ) {
407        if !TelemetrySettings::get_global(cx).metrics {
408            return;
409        }
410
411        let mut state = self.state.lock();
412        let signed_in = state.metrics_id.is_some();
413        state
414            .clickhouse_events_queue
415            .push(ClickhouseEventWrapper { signed_in, event });
416
417        if state.installation_id.is_some() {
418            if immediate_flush || state.clickhouse_events_queue.len() >= MAX_QUEUE_LEN {
419                drop(state);
420                self.flush_clickhouse_events();
421            } else {
422                let this = self.clone();
423                let executor = self.executor.clone();
424                state.flush_clickhouse_events_task = Some(self.executor.spawn(async move {
425                    executor.timer(DEBOUNCE_INTERVAL).await;
426                    this.flush_clickhouse_events();
427                }));
428            }
429        }
430    }
431
432    pub fn metrics_id(self: &Arc<Self>) -> Option<Arc<str>> {
433        self.state.lock().metrics_id.clone()
434    }
435
436    pub fn installation_id(self: &Arc<Self>) -> Option<Arc<str>> {
437        self.state.lock().installation_id.clone()
438    }
439
440    pub fn is_staff(self: &Arc<Self>) -> Option<bool> {
441        self.state.lock().is_staff
442    }
443
444    fn flush_clickhouse_events(self: &Arc<Self>) {
445        let mut state = self.state.lock();
446        state.first_event_datetime = None;
447        let mut events = mem::take(&mut state.clickhouse_events_queue);
448        state.flush_clickhouse_events_task.take();
449        drop(state);
450
451        let this = self.clone();
452        self.executor
453            .spawn(
454                async move {
455                    let mut json_bytes = Vec::new();
456
457                    if let Some(file) = &mut this.state.lock().log_file {
458                        let file = file.as_file_mut();
459                        for event in &mut events {
460                            json_bytes.clear();
461                            serde_json::to_writer(&mut json_bytes, event)?;
462                            file.write_all(&json_bytes)?;
463                            file.write(b"\n")?;
464                        }
465                    }
466
467                    {
468                        let state = this.state.lock();
469                        let request_body = ClickhouseEventRequestBody {
470                            token: ZED_SECRET_CLIENT_TOKEN,
471                            installation_id: state.installation_id.clone(),
472                            session_id: state.session_id.clone(),
473                            is_staff: state.is_staff.clone(),
474                            app_version: state
475                                .app_metadata
476                                .app_version
477                                .map(|version| version.to_string()),
478                            os_name: state.app_metadata.os_name,
479                            os_version: state
480                                .app_metadata
481                                .os_version
482                                .map(|version| version.to_string()),
483                            architecture: state.architecture,
484
485                            release_channel: state.release_channel,
486                            events,
487                        };
488                        json_bytes.clear();
489                        serde_json::to_writer(&mut json_bytes, &request_body)?;
490                    }
491
492                    this.http_client
493                        .post_json(CLICKHOUSE_EVENTS_URL.as_str(), json_bytes.into())
494                        .await?;
495                    anyhow::Ok(())
496                }
497                .log_err(),
498            )
499            .detach();
500    }
501}