telemetry.rs

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