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 tempfile::NamedTempFile;
  8use util::http::HttpClient;
  9use util::{channel::ReleaseChannel, TryFutureExt};
 10
 11pub struct Telemetry {
 12    http_client: Arc<dyn HttpClient>,
 13    executor: Arc<Background>,
 14    state: Mutex<TelemetryState>,
 15}
 16
 17#[derive(Default)]
 18struct TelemetryState {
 19    metrics_id: Option<Arc<str>>,      // Per logged-in user
 20    installation_id: Option<Arc<str>>, // Per app installation
 21    app_version: Option<Arc<str>>,
 22    release_channel: Option<&'static str>,
 23    os_name: &'static str,
 24    os_version: Option<Arc<str>>,
 25    architecture: &'static str,
 26    clickhouse_events_queue: Vec<ClickhouseEventWrapper>,
 27    flush_clickhouse_events_task: Option<Task<()>>,
 28    log_file: Option<NamedTempFile>,
 29    is_staff: Option<bool>,
 30}
 31
 32const CLICKHOUSE_EVENTS_URL_PATH: &'static str = "/api/events";
 33
 34lazy_static! {
 35    static ref CLICKHOUSE_EVENTS_URL: String =
 36        format!("{}{}", *ZED_SERVER_URL, CLICKHOUSE_EVENTS_URL_PATH);
 37}
 38
 39#[derive(Serialize, Debug)]
 40struct ClickhouseEventRequestBody {
 41    token: &'static str,
 42    installation_id: Option<Arc<str>>,
 43    is_staff: Option<bool>,
 44    app_version: Option<Arc<str>>,
 45    os_name: &'static str,
 46    os_version: Option<Arc<str>>,
 47    architecture: &'static str,
 48    release_channel: Option<&'static str>,
 49    events: Vec<ClickhouseEventWrapper>,
 50}
 51
 52#[derive(Serialize, Debug)]
 53struct ClickhouseEventWrapper {
 54    signed_in: bool,
 55    #[serde(flatten)]
 56    event: ClickhouseEvent,
 57}
 58
 59#[derive(Serialize, Debug)]
 60#[serde(rename_all = "snake_case")]
 61pub enum AssistantKind {
 62    Panel,
 63    Inline,
 64}
 65
 66#[derive(Serialize, Debug)]
 67#[serde(tag = "type")]
 68pub enum ClickhouseEvent {
 69    Editor {
 70        operation: &'static str,
 71        file_extension: Option<String>,
 72        vim_mode: bool,
 73        copilot_enabled: bool,
 74        copilot_enabled_for_language: bool,
 75    },
 76    Copilot {
 77        suggestion_id: Option<String>,
 78        suggestion_accepted: bool,
 79        file_extension: Option<String>,
 80    },
 81    Call {
 82        operation: &'static str,
 83        room_id: Option<u64>,
 84        channel_id: Option<u64>,
 85    },
 86    Assistant {
 87        conversation_id: Option<String>,
 88        kind: AssistantKind,
 89        model: &'static str,
 90    },
 91}
 92
 93#[cfg(debug_assertions)]
 94const MAX_QUEUE_LEN: usize = 1;
 95
 96#[cfg(not(debug_assertions))]
 97const MAX_QUEUE_LEN: usize = 10;
 98
 99#[cfg(debug_assertions)]
100const DEBOUNCE_INTERVAL: Duration = Duration::from_secs(1);
101
102#[cfg(not(debug_assertions))]
103const DEBOUNCE_INTERVAL: Duration = Duration::from_secs(30);
104
105impl Telemetry {
106    pub fn new(client: Arc<dyn HttpClient>, cx: &AppContext) -> Arc<Self> {
107        let platform = cx.platform();
108        let release_channel = if cx.has_global::<ReleaseChannel>() {
109            Some(cx.global::<ReleaseChannel>().display_name())
110        } else {
111            None
112        };
113        // TODO: Replace all hardware stuff with nested SystemSpecs json
114        let this = Arc::new(Self {
115            http_client: client,
116            executor: cx.background().clone(),
117            state: Mutex::new(TelemetryState {
118                os_name: platform.os_name().into(),
119                os_version: platform.os_version().ok().map(|v| v.to_string().into()),
120                architecture: env::consts::ARCH,
121                app_version: platform.app_version().ok().map(|v| v.to_string().into()),
122                release_channel,
123                installation_id: None,
124                metrics_id: None,
125                clickhouse_events_queue: Default::default(),
126                flush_clickhouse_events_task: Default::default(),
127                log_file: None,
128                is_staff: None,
129            }),
130        });
131
132        this
133    }
134
135    pub fn log_file_path(&self) -> Option<PathBuf> {
136        Some(self.state.lock().log_file.as_ref()?.path().to_path_buf())
137    }
138
139    pub fn start(self: &Arc<Self>, installation_id: Option<String>) {
140        let mut state = self.state.lock();
141        state.installation_id = installation_id.map(|id| id.into());
142        let has_clickhouse_events = !state.clickhouse_events_queue.is_empty();
143        drop(state);
144
145        if has_clickhouse_events {
146            self.flush_clickhouse_events();
147        }
148    }
149
150    pub fn set_authenticated_user_info(
151        self: &Arc<Self>,
152        metrics_id: Option<String>,
153        is_staff: bool,
154        cx: &AppContext,
155    ) {
156        if !settings::get::<TelemetrySettings>(cx).metrics {
157            return;
158        }
159
160        let mut state = self.state.lock();
161        let metrics_id: Option<Arc<str>> = metrics_id.map(|id| id.into());
162        state.metrics_id = metrics_id.clone();
163        state.is_staff = Some(is_staff);
164        drop(state);
165    }
166
167    pub fn report_clickhouse_event(
168        self: &Arc<Self>,
169        event: ClickhouseEvent,
170        telemetry_settings: TelemetrySettings,
171    ) {
172        if !telemetry_settings.metrics {
173            return;
174        }
175
176        let mut state = self.state.lock();
177        let signed_in = state.metrics_id.is_some();
178        state
179            .clickhouse_events_queue
180            .push(ClickhouseEventWrapper { signed_in, event });
181
182        if state.installation_id.is_some() {
183            if state.clickhouse_events_queue.len() >= MAX_QUEUE_LEN {
184                drop(state);
185                self.flush_clickhouse_events();
186            } else {
187                let this = self.clone();
188                let executor = self.executor.clone();
189                state.flush_clickhouse_events_task = Some(self.executor.spawn(async move {
190                    executor.timer(DEBOUNCE_INTERVAL).await;
191                    this.flush_clickhouse_events();
192                }));
193            }
194        }
195    }
196
197    pub fn metrics_id(self: &Arc<Self>) -> Option<Arc<str>> {
198        self.state.lock().metrics_id.clone()
199    }
200
201    pub fn installation_id(self: &Arc<Self>) -> Option<Arc<str>> {
202        self.state.lock().installation_id.clone()
203    }
204
205    pub fn is_staff(self: &Arc<Self>) -> Option<bool> {
206        self.state.lock().is_staff
207    }
208
209    fn flush_clickhouse_events(self: &Arc<Self>) {
210        let mut state = self.state.lock();
211        let mut events = mem::take(&mut state.clickhouse_events_queue);
212        state.flush_clickhouse_events_task.take();
213        drop(state);
214
215        let this = self.clone();
216        self.executor
217            .spawn(
218                async move {
219                    let mut json_bytes = Vec::new();
220
221                    if let Some(file) = &mut this.state.lock().log_file {
222                        let file = file.as_file_mut();
223                        for event in &mut events {
224                            json_bytes.clear();
225                            serde_json::to_writer(&mut json_bytes, event)?;
226                            file.write_all(&json_bytes)?;
227                            file.write(b"\n")?;
228                        }
229                    }
230
231                    {
232                        let state = this.state.lock();
233                        json_bytes.clear();
234                        serde_json::to_writer(
235                            &mut json_bytes,
236                            &ClickhouseEventRequestBody {
237                                token: ZED_SECRET_CLIENT_TOKEN,
238                                installation_id: state.installation_id.clone(),
239                                is_staff: state.is_staff.clone(),
240                                app_version: state.app_version.clone(),
241                                os_name: state.os_name,
242                                os_version: state.os_version.clone(),
243                                architecture: state.architecture,
244
245                                release_channel: state.release_channel,
246                                events,
247                            },
248                        )?;
249                    }
250
251                    this.http_client
252                        .post_json(CLICKHOUSE_EVENTS_URL.as_str(), json_bytes.into())
253                        .await?;
254                    anyhow::Ok(())
255                }
256                .log_err(),
257            )
258            .detach();
259    }
260}