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(tag = "type")]
 61pub enum ClickhouseEvent {
 62    Editor {
 63        operation: &'static str,
 64        file_extension: Option<String>,
 65        vim_mode: bool,
 66        copilot_enabled: bool,
 67        copilot_enabled_for_language: bool,
 68    },
 69    Copilot {
 70        suggestion_id: Option<String>,
 71        suggestion_accepted: bool,
 72        file_extension: Option<String>,
 73    },
 74    Call {
 75        operation: &'static str,
 76        room_id: Option<u64>,
 77        channel_id: Option<u64>,
 78    },
 79}
 80
 81#[cfg(debug_assertions)]
 82const MAX_QUEUE_LEN: usize = 1;
 83
 84#[cfg(not(debug_assertions))]
 85const MAX_QUEUE_LEN: usize = 10;
 86
 87#[cfg(debug_assertions)]
 88const DEBOUNCE_INTERVAL: Duration = Duration::from_secs(1);
 89
 90#[cfg(not(debug_assertions))]
 91const DEBOUNCE_INTERVAL: Duration = Duration::from_secs(30);
 92
 93impl Telemetry {
 94    pub fn new(client: Arc<dyn HttpClient>, cx: &AppContext) -> Arc<Self> {
 95        let platform = cx.platform();
 96        let release_channel = if cx.has_global::<ReleaseChannel>() {
 97            Some(cx.global::<ReleaseChannel>().display_name())
 98        } else {
 99            None
100        };
101        // TODO: Replace all hardware stuff with nested SystemSpecs json
102        let this = Arc::new(Self {
103            http_client: client,
104            executor: cx.background().clone(),
105            state: Mutex::new(TelemetryState {
106                os_name: platform.os_name().into(),
107                os_version: platform.os_version().ok().map(|v| v.to_string().into()),
108                architecture: env::consts::ARCH,
109                app_version: platform.app_version().ok().map(|v| v.to_string().into()),
110                release_channel,
111                installation_id: None,
112                metrics_id: None,
113                clickhouse_events_queue: Default::default(),
114                flush_clickhouse_events_task: Default::default(),
115                log_file: None,
116                is_staff: None,
117            }),
118        });
119
120        this
121    }
122
123    pub fn log_file_path(&self) -> Option<PathBuf> {
124        Some(self.state.lock().log_file.as_ref()?.path().to_path_buf())
125    }
126
127    pub fn start(self: &Arc<Self>, installation_id: Option<String>) {
128        let mut state = self.state.lock();
129        state.installation_id = installation_id.map(|id| id.into());
130        let has_clickhouse_events = !state.clickhouse_events_queue.is_empty();
131        drop(state);
132
133        if has_clickhouse_events {
134            self.flush_clickhouse_events();
135        }
136    }
137
138    pub fn set_authenticated_user_info(
139        self: &Arc<Self>,
140        metrics_id: Option<String>,
141        is_staff: bool,
142        cx: &AppContext,
143    ) {
144        if !settings::get::<TelemetrySettings>(cx).metrics {
145            return;
146        }
147
148        let mut state = self.state.lock();
149        let metrics_id: Option<Arc<str>> = metrics_id.map(|id| id.into());
150        state.metrics_id = metrics_id.clone();
151        state.is_staff = Some(is_staff);
152        drop(state);
153    }
154
155    pub fn report_clickhouse_event(
156        self: &Arc<Self>,
157        event: ClickhouseEvent,
158        telemetry_settings: TelemetrySettings,
159    ) {
160        if !telemetry_settings.metrics {
161            return;
162        }
163
164        let mut state = self.state.lock();
165        let signed_in = state.metrics_id.is_some();
166        state
167            .clickhouse_events_queue
168            .push(ClickhouseEventWrapper { signed_in, event });
169
170        if state.installation_id.is_some() {
171            if state.clickhouse_events_queue.len() >= MAX_QUEUE_LEN {
172                drop(state);
173                self.flush_clickhouse_events();
174            } else {
175                let this = self.clone();
176                let executor = self.executor.clone();
177                state.flush_clickhouse_events_task = Some(self.executor.spawn(async move {
178                    executor.timer(DEBOUNCE_INTERVAL).await;
179                    this.flush_clickhouse_events();
180                }));
181            }
182        }
183    }
184
185    pub fn metrics_id(self: &Arc<Self>) -> Option<Arc<str>> {
186        self.state.lock().metrics_id.clone()
187    }
188
189    pub fn installation_id(self: &Arc<Self>) -> Option<Arc<str>> {
190        self.state.lock().installation_id.clone()
191    }
192
193    pub fn is_staff(self: &Arc<Self>) -> Option<bool> {
194        self.state.lock().is_staff
195    }
196
197    fn flush_clickhouse_events(self: &Arc<Self>) {
198        let mut state = self.state.lock();
199        let mut events = mem::take(&mut state.clickhouse_events_queue);
200        state.flush_clickhouse_events_task.take();
201        drop(state);
202
203        let this = self.clone();
204        self.executor
205            .spawn(
206                async move {
207                    let mut json_bytes = Vec::new();
208
209                    if let Some(file) = &mut this.state.lock().log_file {
210                        let file = file.as_file_mut();
211                        for event in &mut events {
212                            json_bytes.clear();
213                            serde_json::to_writer(&mut json_bytes, event)?;
214                            file.write_all(&json_bytes)?;
215                            file.write(b"\n")?;
216                        }
217                    }
218
219                    {
220                        let state = this.state.lock();
221                        json_bytes.clear();
222                        serde_json::to_writer(
223                            &mut json_bytes,
224                            &ClickhouseEventRequestBody {
225                                token: ZED_SECRET_CLIENT_TOKEN,
226                                installation_id: state.installation_id.clone(),
227                                is_staff: state.is_staff.clone(),
228                                app_version: state.app_version.clone(),
229                                os_name: state.os_name,
230                                os_version: state.os_version.clone(),
231                                architecture: state.architecture,
232
233                                release_channel: state.release_channel,
234                                events,
235                            },
236                        )?;
237                    }
238
239                    this.http_client
240                        .post_json(CLICKHOUSE_EVENTS_URL.as_str(), json_bytes.into())
241                        .await?;
242                    anyhow::Ok(())
243                }
244                .log_err(),
245            )
246            .detach();
247    }
248}