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    platform: &'static str,
 83}
 84
 85#[derive(Serialize)]
 86struct MixpanelEngageRequest {
 87    #[serde(rename = "$token")]
 88    token: &'static str,
 89    #[serde(rename = "$distinct_id")]
 90    distinct_id: Arc<str>,
 91    #[serde(rename = "$set")]
 92    set: Value,
 93}
 94
 95#[cfg(debug_assertions)]
 96const MAX_QUEUE_LEN: usize = 1;
 97
 98#[cfg(not(debug_assertions))]
 99const MAX_QUEUE_LEN: usize = 10;
100
101#[cfg(debug_assertions)]
102const DEBOUNCE_INTERVAL: Duration = Duration::from_secs(1);
103
104#[cfg(not(debug_assertions))]
105const DEBOUNCE_INTERVAL: Duration = Duration::from_secs(30);
106
107impl Telemetry {
108    pub fn new(client: Arc<dyn HttpClient>, cx: &AppContext) -> Arc<Self> {
109        let platform = cx.platform();
110        let release_channel = if cx.has_global::<ReleaseChannel>() {
111            Some(cx.global::<ReleaseChannel>().name())
112        } else {
113            None
114        };
115        let this = Arc::new(Self {
116            http_client: client,
117            executor: cx.background().clone(),
118            state: Mutex::new(TelemetryState {
119                os_version: platform.os_version().ok().map(|v| v.to_string().into()),
120                os_name: platform.os_name().into(),
121                app_version: platform.app_version().ok().map(|v| v.to_string().into()),
122                release_channel,
123                device_id: None,
124                metrics_id: None,
125                queue: Default::default(),
126                flush_task: Default::default(),
127                next_event_id: 0,
128                log_file: None,
129            }),
130        });
131
132        if MIXPANEL_TOKEN.is_some() {
133            this.executor
134                .spawn({
135                    let this = this.clone();
136                    async move {
137                        if let Some(tempfile) = NamedTempFile::new().log_err() {
138                            this.state.lock().log_file = Some(tempfile);
139                        }
140                    }
141                })
142                .detach();
143        }
144
145        this
146    }
147
148    pub fn log_file_path(&self) -> Option<PathBuf> {
149        Some(self.state.lock().log_file.as_ref()?.path().to_path_buf())
150    }
151
152    pub fn start(self: &Arc<Self>, db: Db) {
153        let this = self.clone();
154        self.executor
155            .spawn(
156                async move {
157                    let device_id = if let Ok(Some(device_id)) = db.read_kvp("device_id") {
158                        device_id
159                    } else {
160                        let device_id = Uuid::new_v4().to_string();
161                        db.write_kvp("device_id", &device_id)?;
162                        device_id
163                    };
164
165                    let device_id: Arc<str> = device_id.into();
166                    let mut state = this.state.lock();
167                    state.device_id = Some(device_id.clone());
168                    for event in &mut state.queue {
169                        event
170                            .properties
171                            .distinct_id
172                            .get_or_insert_with(|| device_id.clone());
173                    }
174                    if !state.queue.is_empty() {
175                        drop(state);
176                        this.flush();
177                    }
178
179                    anyhow::Ok(())
180                }
181                .log_err(),
182            )
183            .detach();
184    }
185
186    pub fn set_authenticated_user_info(
187        self: &Arc<Self>,
188        metrics_id: Option<String>,
189        is_staff: bool,
190    ) {
191        let this = self.clone();
192        let mut state = self.state.lock();
193        let device_id = state.device_id.clone();
194        let metrics_id: Option<Arc<str>> = metrics_id.map(|id| id.into());
195        state.metrics_id = metrics_id.clone();
196        drop(state);
197
198        if let Some((token, device_id)) = MIXPANEL_TOKEN.as_ref().zip(device_id) {
199            self.executor
200                .spawn(
201                    async move {
202                        let json_bytes = serde_json::to_vec(&[MixpanelEngageRequest {
203                            token,
204                            distinct_id: device_id,
205                            set: json!({ "Staff": is_staff, "ID": metrics_id }),
206                        }])?;
207                        let request = Request::post(MIXPANEL_ENGAGE_URL)
208                            .header("Content-Type", "application/json")
209                            .body(json_bytes.into())?;
210                        this.http_client.send(request).await?;
211                        Ok(())
212                    }
213                    .log_err(),
214                )
215                .detach();
216        }
217    }
218
219    pub fn report_event(self: &Arc<Self>, kind: &str, properties: Value) {
220        let mut state = self.state.lock();
221        let event = MixpanelEvent {
222            event: kind.to_string(),
223            properties: MixpanelEventProperties {
224                token: "",
225                time: SystemTime::now()
226                    .duration_since(UNIX_EPOCH)
227                    .unwrap()
228                    .as_millis(),
229                distinct_id: state.device_id.clone(),
230                insert_id: post_inc(&mut state.next_event_id),
231                event_properties: if let Value::Object(properties) = properties {
232                    Some(properties)
233                } else {
234                    None
235                },
236                os_name: state.os_name,
237                os_version: state.os_version.clone(),
238                release_channel: state.release_channel,
239                app_version: state.app_version.clone(),
240                signed_in: state.metrics_id.is_some(),
241                platform: "Zed",
242            },
243        };
244        state.queue.push(event);
245        if state.device_id.is_some() {
246            if state.queue.len() >= MAX_QUEUE_LEN {
247                drop(state);
248                self.flush();
249            } else {
250                let this = self.clone();
251                let executor = self.executor.clone();
252                state.flush_task = Some(self.executor.spawn(async move {
253                    executor.timer(DEBOUNCE_INTERVAL).await;
254                    this.flush();
255                }));
256            }
257        }
258    }
259
260    fn flush(self: &Arc<Self>) {
261        let mut state = self.state.lock();
262        let mut events = mem::take(&mut state.queue);
263        state.flush_task.take();
264        drop(state);
265
266        if let Some(token) = MIXPANEL_TOKEN.as_ref() {
267            let this = self.clone();
268            self.executor
269                .spawn(
270                    async move {
271                        let mut json_bytes = Vec::new();
272
273                        if let Some(file) = &mut this.state.lock().log_file {
274                            let file = file.as_file_mut();
275                            for event in &mut events {
276                                json_bytes.clear();
277                                serde_json::to_writer(&mut json_bytes, event)?;
278                                file.write_all(&json_bytes)?;
279                                file.write(b"\n")?;
280
281                                event.properties.token = token;
282                            }
283                        }
284
285                        json_bytes.clear();
286                        serde_json::to_writer(&mut json_bytes, &events)?;
287                        let request = Request::post(MIXPANEL_EVENTS_URL)
288                            .header("Content-Type", "application/json")
289                            .body(json_bytes.into())?;
290                        this.http_client.send(request).await?;
291                        Ok(())
292                    }
293                    .log_err(),
294                )
295                .detach();
296        }
297    }
298}