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 settings::ReleaseChannel;
 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::{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>().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>, db: Db) {
152        let this = self.clone();
153        self.executor
154            .spawn(
155                async move {
156                    let device_id = if let Ok(Some(device_id)) = db.read_kvp("device_id") {
157                        device_id
158                    } else {
159                        let device_id = Uuid::new_v4().to_string();
160                        db.write_kvp("device_id", &device_id)?;
161                        device_id
162                    };
163
164                    let device_id: Arc<str> = device_id.into();
165                    let mut state = this.state.lock();
166                    state.device_id = Some(device_id.clone());
167                    for event in &mut state.queue {
168                        event
169                            .properties
170                            .distinct_id
171                            .get_or_insert_with(|| device_id.clone());
172                    }
173                    if !state.queue.is_empty() {
174                        drop(state);
175                        this.flush();
176                    }
177
178                    anyhow::Ok(())
179                }
180                .log_err(),
181            )
182            .detach();
183    }
184
185    pub fn set_authenticated_user_info(
186        self: &Arc<Self>,
187        metrics_id: Option<String>,
188        is_staff: bool,
189    ) {
190        let this = self.clone();
191        let mut state = self.state.lock();
192        let device_id = state.device_id.clone();
193        let metrics_id: Option<Arc<str>> = metrics_id.map(|id| id.into());
194        state.metrics_id = metrics_id.clone();
195        drop(state);
196
197        if let Some((token, device_id)) = MIXPANEL_TOKEN.as_ref().zip(device_id) {
198            self.executor
199                .spawn(
200                    async move {
201                        let json_bytes = serde_json::to_vec(&[MixpanelEngageRequest {
202                            token,
203                            distinct_id: device_id,
204                            set: json!({
205                                "Staff": is_staff,
206                                "ID": metrics_id,
207                                "App": true
208                            }),
209                        }])?;
210                        let request = Request::post(MIXPANEL_ENGAGE_URL)
211                            .header("Content-Type", "application/json")
212                            .body(json_bytes.into())?;
213                        this.http_client.send(request).await?;
214                        Ok(())
215                    }
216                    .log_err(),
217                )
218                .detach();
219        }
220    }
221
222    pub fn report_event(self: &Arc<Self>, kind: &str, properties: Value) {
223        let mut state = self.state.lock();
224        let event = MixpanelEvent {
225            event: kind.to_string(),
226            properties: MixpanelEventProperties {
227                token: "",
228                time: SystemTime::now()
229                    .duration_since(UNIX_EPOCH)
230                    .unwrap()
231                    .as_millis(),
232                distinct_id: state.device_id.clone(),
233                insert_id: post_inc(&mut state.next_event_id),
234                event_properties: if let Value::Object(properties) = properties {
235                    Some(properties)
236                } else {
237                    None
238                },
239                os_name: state.os_name,
240                os_version: state.os_version.clone(),
241                release_channel: state.release_channel,
242                app_version: state.app_version.clone(),
243                signed_in: state.metrics_id.is_some(),
244            },
245        };
246        state.queue.push(event);
247        if state.device_id.is_some() {
248            if state.queue.len() >= MAX_QUEUE_LEN {
249                drop(state);
250                self.flush();
251            } else {
252                let this = self.clone();
253                let executor = self.executor.clone();
254                state.flush_task = Some(self.executor.spawn(async move {
255                    executor.timer(DEBOUNCE_INTERVAL).await;
256                    this.flush();
257                }));
258            }
259        }
260    }
261
262    fn flush(self: &Arc<Self>) {
263        let mut state = self.state.lock();
264        let mut events = mem::take(&mut state.queue);
265        state.flush_task.take();
266        drop(state);
267
268        if let Some(token) = MIXPANEL_TOKEN.as_ref() {
269            let this = self.clone();
270            self.executor
271                .spawn(
272                    async move {
273                        let mut json_bytes = Vec::new();
274
275                        if let Some(file) = &mut this.state.lock().log_file {
276                            let file = file.as_file_mut();
277                            for event in &mut events {
278                                json_bytes.clear();
279                                serde_json::to_writer(&mut json_bytes, event)?;
280                                file.write_all(&json_bytes)?;
281                                file.write(b"\n")?;
282
283                                event.properties.token = token;
284                            }
285                        }
286
287                        json_bytes.clear();
288                        serde_json::to_writer(&mut json_bytes, &events)?;
289                        let request = Request::post(MIXPANEL_EVENTS_URL)
290                            .header("Content-Type", "application/json")
291                            .body(json_bytes.into())?;
292                        this.http_client.send(request).await?;
293                        Ok(())
294                    }
295                    .log_err(),
296                )
297                .detach();
298        }
299    }
300}