telemetry.rs

  1use crate::{TelemetrySettings, ZED_SECRET_CLIENT_TOKEN, ZED_SERVER_URL};
  2use gpui::{executor::Background, serde_json, AppContext, Task};
  3use lazy_static::lazy_static;
  4use parking_lot::Mutex;
  5use serde::Serialize;
  6use std::{env, io::Write, mem, path::PathBuf, sync::Arc, time::Duration};
  7use sysinfo::{Pid, PidExt, ProcessExt, System, SystemExt};
  8use tempfile::NamedTempFile;
  9use util::http::HttpClient;
 10use util::{channel::ReleaseChannel, TryFutureExt};
 11
 12pub struct Telemetry {
 13    http_client: Arc<dyn HttpClient>,
 14    executor: Arc<Background>,
 15    state: Mutex<TelemetryState>,
 16}
 17
 18#[derive(Default)]
 19struct TelemetryState {
 20    metrics_id: Option<Arc<str>>,      // Per logged-in user
 21    installation_id: Option<Arc<str>>, // Per app installation
 22    app_version: Option<Arc<str>>,
 23    release_channel: Option<&'static str>,
 24    os_name: &'static str,
 25    os_version: Option<Arc<str>>,
 26    architecture: &'static str,
 27    clickhouse_events_queue: Vec<ClickhouseEventWrapper>,
 28    flush_clickhouse_events_task: Option<Task<()>>,
 29    log_file: Option<NamedTempFile>,
 30    is_staff: Option<bool>,
 31}
 32
 33const CLICKHOUSE_EVENTS_URL_PATH: &'static str = "/api/events";
 34
 35lazy_static! {
 36    static ref CLICKHOUSE_EVENTS_URL: String =
 37        format!("{}{}", *ZED_SERVER_URL, CLICKHOUSE_EVENTS_URL_PATH);
 38}
 39
 40#[derive(Serialize, Debug)]
 41struct ClickhouseEventRequestBody {
 42    token: &'static str,
 43    installation_id: Option<Arc<str>>,
 44    is_staff: Option<bool>,
 45    app_version: Option<Arc<str>>,
 46    os_name: &'static str,
 47    os_version: Option<Arc<str>>,
 48    architecture: &'static str,
 49    release_channel: Option<&'static str>,
 50    events: Vec<ClickhouseEventWrapper>,
 51}
 52
 53#[derive(Serialize, Debug)]
 54struct ClickhouseEventWrapper {
 55    signed_in: bool,
 56    #[serde(flatten)]
 57    event: ClickhouseEvent,
 58}
 59
 60#[derive(Serialize, Debug)]
 61#[serde(rename_all = "snake_case")]
 62pub enum AssistantKind {
 63    Panel,
 64    Inline,
 65}
 66
 67#[derive(Serialize, Debug)]
 68#[serde(tag = "type")]
 69pub enum ClickhouseEvent {
 70    Editor {
 71        operation: &'static str,
 72        file_extension: Option<String>,
 73        vim_mode: bool,
 74        copilot_enabled: bool,
 75        copilot_enabled_for_language: bool,
 76    },
 77    Copilot {
 78        suggestion_id: Option<String>,
 79        suggestion_accepted: bool,
 80        file_extension: Option<String>,
 81    },
 82    Call {
 83        operation: &'static str,
 84        room_id: Option<u64>,
 85        channel_id: Option<u64>,
 86    },
 87    Assistant {
 88        conversation_id: Option<String>,
 89        kind: AssistantKind,
 90        model: &'static str,
 91    },
 92    Cpu {
 93        usage_as_percentage: f32,
 94        core_count: u32,
 95    },
 96    Memory {
 97        memory_in_bytes: u64,
 98        virtual_memory_in_bytes: u64,
 99    },
100}
101
102#[cfg(debug_assertions)]
103const MAX_QUEUE_LEN: usize = 1;
104
105#[cfg(not(debug_assertions))]
106const MAX_QUEUE_LEN: usize = 10;
107
108#[cfg(debug_assertions)]
109const DEBOUNCE_INTERVAL: Duration = Duration::from_secs(1);
110
111#[cfg(not(debug_assertions))]
112const DEBOUNCE_INTERVAL: Duration = Duration::from_secs(30);
113
114impl Telemetry {
115    pub fn new(client: Arc<dyn HttpClient>, cx: &AppContext) -> Arc<Self> {
116        let platform = cx.platform();
117        let release_channel = if cx.has_global::<ReleaseChannel>() {
118            Some(cx.global::<ReleaseChannel>().display_name())
119        } else {
120            None
121        };
122        // TODO: Replace all hardware stuff with nested SystemSpecs json
123        let this = Arc::new(Self {
124            http_client: client,
125            executor: cx.background().clone(),
126            state: Mutex::new(TelemetryState {
127                os_name: platform.os_name().into(),
128                os_version: platform.os_version().ok().map(|v| v.to_string().into()),
129                architecture: env::consts::ARCH,
130                app_version: platform.app_version().ok().map(|v| v.to_string().into()),
131                release_channel,
132                installation_id: None,
133                metrics_id: None,
134                clickhouse_events_queue: Default::default(),
135                flush_clickhouse_events_task: Default::default(),
136                log_file: None,
137                is_staff: None,
138            }),
139        });
140
141        this
142    }
143
144    pub fn log_file_path(&self) -> Option<PathBuf> {
145        Some(self.state.lock().log_file.as_ref()?.path().to_path_buf())
146    }
147
148    pub fn start(self: &Arc<Self>, installation_id: Option<String>, cx: &mut AppContext) {
149        let mut state = self.state.lock();
150        state.installation_id = installation_id.map(|id| id.into());
151        let has_clickhouse_events = !state.clickhouse_events_queue.is_empty();
152        drop(state);
153
154        if has_clickhouse_events {
155            self.flush_clickhouse_events();
156        }
157
158        let this = self.clone();
159        cx.spawn(|mut cx| async move {
160            let mut system = System::new_all();
161            system.refresh_all();
162
163            loop {
164                // Waiting some amount of time before the first query is important to get a reasonable value
165                // https://docs.rs/sysinfo/0.29.10/sysinfo/trait.ProcessExt.html#tymethod.cpu_usage
166                const DURATION_BETWEEN_SYSTEM_EVENTS: Duration = Duration::from_secs(60);
167                smol::Timer::after(DURATION_BETWEEN_SYSTEM_EVENTS).await;
168
169                system.refresh_memory();
170                system.refresh_processes();
171
172                let current_process = Pid::from_u32(std::process::id());
173                let Some(process) = system.processes().get(&current_process) else {
174                    let process = current_process;
175                    log::error!("Failed to find own process {process:?} in system process table");
176                    // TODO: Fire an error telemetry event
177                    return;
178                };
179
180                let memory_event = ClickhouseEvent::Memory {
181                    memory_in_bytes: process.memory(),
182                    virtual_memory_in_bytes: process.virtual_memory(),
183                };
184
185                let cpu_event = ClickhouseEvent::Cpu {
186                    usage_as_percentage: process.cpu_usage(),
187                    core_count: system.cpus().len() as u32,
188                };
189
190                let telemetry_settings = cx.update(|cx| *settings::get::<TelemetrySettings>(cx));
191
192                this.report_clickhouse_event(memory_event, telemetry_settings);
193                this.report_clickhouse_event(cpu_event, telemetry_settings);
194            }
195        })
196        .detach();
197    }
198
199    pub fn set_authenticated_user_info(
200        self: &Arc<Self>,
201        metrics_id: Option<String>,
202        is_staff: bool,
203        cx: &AppContext,
204    ) {
205        if !settings::get::<TelemetrySettings>(cx).metrics {
206            return;
207        }
208
209        let mut state = self.state.lock();
210        let metrics_id: Option<Arc<str>> = metrics_id.map(|id| id.into());
211        state.metrics_id = metrics_id.clone();
212        state.is_staff = Some(is_staff);
213        drop(state);
214    }
215
216    pub fn report_clickhouse_event(
217        self: &Arc<Self>,
218        event: ClickhouseEvent,
219        telemetry_settings: TelemetrySettings,
220    ) {
221        if !telemetry_settings.metrics {
222            return;
223        }
224
225        let mut state = self.state.lock();
226        let signed_in = state.metrics_id.is_some();
227        state
228            .clickhouse_events_queue
229            .push(ClickhouseEventWrapper { signed_in, event });
230
231        if state.installation_id.is_some() {
232            if state.clickhouse_events_queue.len() >= MAX_QUEUE_LEN {
233                drop(state);
234                self.flush_clickhouse_events();
235            } else {
236                let this = self.clone();
237                let executor = self.executor.clone();
238                state.flush_clickhouse_events_task = Some(self.executor.spawn(async move {
239                    executor.timer(DEBOUNCE_INTERVAL).await;
240                    this.flush_clickhouse_events();
241                }));
242            }
243        }
244    }
245
246    pub fn metrics_id(self: &Arc<Self>) -> Option<Arc<str>> {
247        self.state.lock().metrics_id.clone()
248    }
249
250    pub fn installation_id(self: &Arc<Self>) -> Option<Arc<str>> {
251        self.state.lock().installation_id.clone()
252    }
253
254    pub fn is_staff(self: &Arc<Self>) -> Option<bool> {
255        self.state.lock().is_staff
256    }
257
258    fn flush_clickhouse_events(self: &Arc<Self>) {
259        let mut state = self.state.lock();
260        let mut events = mem::take(&mut state.clickhouse_events_queue);
261        state.flush_clickhouse_events_task.take();
262        drop(state);
263
264        let this = self.clone();
265        self.executor
266            .spawn(
267                async move {
268                    let mut json_bytes = Vec::new();
269
270                    if let Some(file) = &mut this.state.lock().log_file {
271                        let file = file.as_file_mut();
272                        for event in &mut events {
273                            json_bytes.clear();
274                            serde_json::to_writer(&mut json_bytes, event)?;
275                            file.write_all(&json_bytes)?;
276                            file.write(b"\n")?;
277                        }
278                    }
279
280                    {
281                        let state = this.state.lock();
282                        json_bytes.clear();
283                        serde_json::to_writer(
284                            &mut json_bytes,
285                            &ClickhouseEventRequestBody {
286                                token: ZED_SECRET_CLIENT_TOKEN,
287                                installation_id: state.installation_id.clone(),
288                                is_staff: state.is_staff.clone(),
289                                app_version: state.app_version.clone(),
290                                os_name: state.os_name,
291                                os_version: state.os_version.clone(),
292                                architecture: state.architecture,
293
294                                release_channel: state.release_channel,
295                                events,
296                            },
297                        )?;
298                    }
299
300                    this.http_client
301                        .post_json(CLICKHOUSE_EVENTS_URL.as_str(), json_bytes.into())
302                        .await?;
303                    anyhow::Ok(())
304                }
305                .log_err(),
306            )
307            .detach();
308    }
309}