telemetry.rs

  1use crate::http::HttpClient;
  2use db::kvp::KEY_VALUE_STORE;
  3use gpui::{
  4    executor::Background,
  5    serde_json::{self, value::Map, Value},
  6    AppContext, Task,
  7};
  8use isahc::Request;
  9use lazy_static::lazy_static;
 10use parking_lot::Mutex;
 11use serde::Serialize;
 12use serde_json::json;
 13use settings::TelemetrySettings;
 14use std::{
 15    io::Write,
 16    mem,
 17    path::PathBuf,
 18    sync::Arc,
 19    time::{Duration, SystemTime, UNIX_EPOCH},
 20};
 21use tempfile::NamedTempFile;
 22use util::{channel::ReleaseChannel, post_inc, ResultExt, TryFutureExt};
 23use uuid::Uuid;
 24
 25pub struct Telemetry {
 26    http_client: Arc<dyn HttpClient>,
 27    executor: Arc<Background>,
 28    state: Mutex<TelemetryState>,
 29}
 30
 31#[derive(Default)]
 32struct TelemetryState {
 33    metrics_id: Option<Arc<str>>,
 34    device_id: Option<Arc<str>>,
 35    app_version: Option<Arc<str>>,
 36    release_channel: Option<&'static str>,
 37    os_version: Option<Arc<str>>,
 38    os_name: &'static str,
 39    queue: Vec<MixpanelEvent>,
 40    next_event_id: usize,
 41    flush_task: Option<Task<()>>,
 42    log_file: Option<NamedTempFile>,
 43}
 44
 45const MIXPANEL_EVENTS_URL: &'static str = "https://api.mixpanel.com/track";
 46const MIXPANEL_ENGAGE_URL: &'static str = "https://api.mixpanel.com/engage#profile-set";
 47
 48lazy_static! {
 49    static ref MIXPANEL_TOKEN: Option<String> = std::env::var("ZED_MIXPANEL_TOKEN")
 50        .ok()
 51        .or_else(|| option_env!("ZED_MIXPANEL_TOKEN").map(|key| key.to_string()));
 52}
 53
 54#[derive(Serialize, Debug)]
 55struct MixpanelEvent {
 56    event: String,
 57    properties: MixpanelEventProperties,
 58}
 59
 60#[derive(Serialize, Debug)]
 61struct MixpanelEventProperties {
 62    // Mixpanel required fields
 63    #[serde(skip_serializing_if = "str::is_empty")]
 64    token: &'static str,
 65    time: u128,
 66    distinct_id: Option<Arc<str>>,
 67    #[serde(rename = "$insert_id")]
 68    insert_id: usize,
 69    // Custom fields
 70    #[serde(skip_serializing_if = "Option::is_none", flatten)]
 71    event_properties: Option<Map<String, Value>>,
 72    #[serde(rename = "OS Name")]
 73    os_name: &'static str,
 74    #[serde(rename = "OS Version")]
 75    os_version: Option<Arc<str>>,
 76    #[serde(rename = "Release Channel")]
 77    release_channel: Option<&'static str>,
 78    #[serde(rename = "App Version")]
 79    app_version: Option<Arc<str>>,
 80    #[serde(rename = "Signed In")]
 81    signed_in: bool,
 82}
 83
 84#[derive(Serialize)]
 85struct MixpanelEngageRequest {
 86    #[serde(rename = "$token")]
 87    token: &'static str,
 88    #[serde(rename = "$distinct_id")]
 89    distinct_id: Arc<str>,
 90    #[serde(rename = "$set")]
 91    set: Value,
 92}
 93
 94#[cfg(debug_assertions)]
 95const MAX_QUEUE_LEN: usize = 1;
 96
 97#[cfg(not(debug_assertions))]
 98const MAX_QUEUE_LEN: usize = 10;
 99
100#[cfg(debug_assertions)]
101const DEBOUNCE_INTERVAL: Duration = Duration::from_secs(1);
102
103#[cfg(not(debug_assertions))]
104const DEBOUNCE_INTERVAL: Duration = Duration::from_secs(30);
105
106impl Telemetry {
107    pub fn new(client: Arc<dyn HttpClient>, cx: &AppContext) -> Arc<Self> {
108        let platform = cx.platform();
109        let release_channel = if cx.has_global::<ReleaseChannel>() {
110            Some(cx.global::<ReleaseChannel>().display_name())
111        } else {
112            None
113        };
114        let this = Arc::new(Self {
115            http_client: client,
116            executor: cx.background().clone(),
117            state: Mutex::new(TelemetryState {
118                os_version: platform.os_version().ok().map(|v| v.to_string().into()),
119                os_name: platform.os_name().into(),
120                app_version: platform.app_version().ok().map(|v| v.to_string().into()),
121                release_channel,
122                device_id: None,
123                metrics_id: None,
124                queue: Default::default(),
125                flush_task: Default::default(),
126                next_event_id: 0,
127                log_file: None,
128            }),
129        });
130
131        if MIXPANEL_TOKEN.is_some() {
132            this.executor
133                .spawn({
134                    let this = this.clone();
135                    async move {
136                        if let Some(tempfile) = NamedTempFile::new().log_err() {
137                            this.state.lock().log_file = Some(tempfile);
138                        }
139                    }
140                })
141                .detach();
142        }
143
144        this
145    }
146
147    pub fn log_file_path(&self) -> Option<PathBuf> {
148        Some(self.state.lock().log_file.as_ref()?.path().to_path_buf())
149    }
150
151    pub fn start(self: &Arc<Self>) {
152        let this = self.clone();
153        self.executor
154            .spawn(
155                async move {
156                    let device_id =
157                        if let Ok(Some(device_id)) = KEY_VALUE_STORE.read_kvp("device_id") {
158                            device_id
159                        } else {
160                            let device_id = Uuid::new_v4().to_string();
161                            KEY_VALUE_STORE
162                                .write_kvp("device_id".to_string(), device_id.clone())
163                                .await?;
164                            device_id
165                        };
166
167                    let device_id: Arc<str> = device_id.into();
168                    let mut state = this.state.lock();
169                    state.device_id = Some(device_id.clone());
170                    for event in &mut state.queue {
171                        event
172                            .properties
173                            .distinct_id
174                            .get_or_insert_with(|| device_id.clone());
175                    }
176                    if !state.queue.is_empty() {
177                        drop(state);
178                        this.flush();
179                    }
180
181                    anyhow::Ok(())
182                }
183                .log_err(),
184            )
185            .detach();
186    }
187
188    /// This method takes the entire TelemetrySettings struct in order to force client code
189    /// to pull the struct out of the settings global. Do not remove!
190    pub fn set_authenticated_user_info(
191        self: &Arc<Self>,
192        metrics_id: Option<String>,
193        is_staff: bool,
194        telemetry_settings: TelemetrySettings,
195    ) {
196        if !telemetry_settings.metrics() {
197            return;
198        }
199
200        let this = self.clone();
201        let mut state = self.state.lock();
202        let device_id = state.device_id.clone();
203        let metrics_id: Option<Arc<str>> = metrics_id.map(|id| id.into());
204        state.metrics_id = metrics_id.clone();
205        drop(state);
206
207        if let Some((token, device_id)) = MIXPANEL_TOKEN.as_ref().zip(device_id) {
208            self.executor
209                .spawn(
210                    async move {
211                        let json_bytes = serde_json::to_vec(&[MixpanelEngageRequest {
212                            token,
213                            distinct_id: device_id,
214                            set: json!({
215                                "Staff": is_staff,
216                                "ID": metrics_id,
217                                "App": true
218                            }),
219                        }])?;
220                        let request = Request::post(MIXPANEL_ENGAGE_URL)
221                            .header("Content-Type", "application/json")
222                            .body(json_bytes.into())?;
223                        this.http_client.send(request).await?;
224                        Ok(())
225                    }
226                    .log_err(),
227                )
228                .detach();
229        }
230    }
231
232    pub fn report_event(
233        self: &Arc<Self>,
234        kind: &str,
235        properties: Value,
236        telemetry_settings: TelemetrySettings,
237    ) {
238        if !telemetry_settings.metrics() {
239            return;
240        }
241
242        let mut state = self.state.lock();
243        let event = MixpanelEvent {
244            event: kind.to_string(),
245            properties: MixpanelEventProperties {
246                token: "",
247                time: SystemTime::now()
248                    .duration_since(UNIX_EPOCH)
249                    .unwrap()
250                    .as_millis(),
251                distinct_id: state.device_id.clone(),
252                insert_id: post_inc(&mut state.next_event_id),
253                event_properties: if let Value::Object(properties) = properties {
254                    Some(properties)
255                } else {
256                    None
257                },
258                os_name: state.os_name,
259                os_version: state.os_version.clone(),
260                release_channel: state.release_channel,
261                app_version: state.app_version.clone(),
262                signed_in: state.metrics_id.is_some(),
263            },
264        };
265        state.queue.push(event);
266        if state.device_id.is_some() {
267            if state.queue.len() >= MAX_QUEUE_LEN {
268                drop(state);
269                self.flush();
270            } else {
271                let this = self.clone();
272                let executor = self.executor.clone();
273                state.flush_task = Some(self.executor.spawn(async move {
274                    executor.timer(DEBOUNCE_INTERVAL).await;
275                    this.flush();
276                }));
277            }
278        }
279    }
280
281    pub fn metrics_id(self: &Arc<Self>) -> Option<Arc<str>> {
282        self.state.lock().metrics_id.clone()
283    }
284
285    fn flush(self: &Arc<Self>) {
286        let mut state = self.state.lock();
287        let mut events = mem::take(&mut state.queue);
288        state.flush_task.take();
289        drop(state);
290
291        if let Some(token) = MIXPANEL_TOKEN.as_ref() {
292            let this = self.clone();
293            self.executor
294                .spawn(
295                    async move {
296                        let mut json_bytes = Vec::new();
297
298                        if let Some(file) = &mut this.state.lock().log_file {
299                            let file = file.as_file_mut();
300                            for event in &mut events {
301                                json_bytes.clear();
302                                serde_json::to_writer(&mut json_bytes, event)?;
303                                file.write_all(&json_bytes)?;
304                                file.write(b"\n")?;
305
306                                event.properties.token = token;
307                            }
308                        }
309
310                        json_bytes.clear();
311                        serde_json::to_writer(&mut json_bytes, &events)?;
312                        let request = Request::post(MIXPANEL_EVENTS_URL)
313                            .header("Content-Type", "application/json")
314                            .body(json_bytes.into())?;
315                        this.http_client.send(request).await?;
316                        Ok(())
317                    }
318                    .log_err(),
319                )
320                .detach();
321        }
322    }
323}