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    is_staff: Option<bool>,
 44}
 45
 46const MIXPANEL_EVENTS_URL: &'static str = "https://api.mixpanel.com/track";
 47const MIXPANEL_ENGAGE_URL: &'static str = "https://api.mixpanel.com/engage#profile-set";
 48
 49lazy_static! {
 50    static ref MIXPANEL_TOKEN: Option<String> = std::env::var("ZED_MIXPANEL_TOKEN")
 51        .ok()
 52        .or_else(|| option_env!("ZED_MIXPANEL_TOKEN").map(|key| key.to_string()));
 53}
 54
 55#[derive(Serialize, Debug)]
 56struct MixpanelEvent {
 57    event: String,
 58    properties: MixpanelEventProperties,
 59}
 60
 61#[derive(Serialize, Debug)]
 62struct MixpanelEventProperties {
 63    // Mixpanel required fields
 64    #[serde(skip_serializing_if = "str::is_empty")]
 65    token: &'static str,
 66    time: u128,
 67    distinct_id: Option<Arc<str>>,
 68    #[serde(rename = "$insert_id")]
 69    insert_id: usize,
 70    // Custom fields
 71    #[serde(skip_serializing_if = "Option::is_none", flatten)]
 72    event_properties: Option<Map<String, Value>>,
 73    #[serde(rename = "OS Name")]
 74    os_name: &'static str,
 75    #[serde(rename = "OS Version")]
 76    os_version: Option<Arc<str>>,
 77    #[serde(rename = "Release Channel")]
 78    release_channel: Option<&'static str>,
 79    #[serde(rename = "App Version")]
 80    app_version: Option<Arc<str>>,
 81    #[serde(rename = "Signed In")]
 82    signed_in: bool,
 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>().display_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                is_staff: None,
130            }),
131        });
132
133        if MIXPANEL_TOKEN.is_some() {
134            this.executor
135                .spawn({
136                    let this = this.clone();
137                    async move {
138                        if let Some(tempfile) = NamedTempFile::new().log_err() {
139                            this.state.lock().log_file = Some(tempfile);
140                        }
141                    }
142                })
143                .detach();
144        }
145
146        this
147    }
148
149    pub fn log_file_path(&self) -> Option<PathBuf> {
150        Some(self.state.lock().log_file.as_ref()?.path().to_path_buf())
151    }
152
153    pub fn start(self: &Arc<Self>) {
154        let this = self.clone();
155        self.executor
156            .spawn(
157                async move {
158                    let device_id =
159                        if let Ok(Some(device_id)) = KEY_VALUE_STORE.read_kvp("device_id") {
160                            device_id
161                        } else {
162                            let device_id = Uuid::new_v4().to_string();
163                            KEY_VALUE_STORE
164                                .write_kvp("device_id".to_string(), device_id.clone())
165                                .await?;
166                            device_id
167                        };
168
169                    let device_id: Arc<str> = device_id.into();
170                    let mut state = this.state.lock();
171                    state.device_id = Some(device_id.clone());
172                    for event in &mut state.queue {
173                        event
174                            .properties
175                            .distinct_id
176                            .get_or_insert_with(|| device_id.clone());
177                    }
178                    if !state.queue.is_empty() {
179                        drop(state);
180                        this.flush();
181                    }
182
183                    anyhow::Ok(())
184                }
185                .log_err(),
186            )
187            .detach();
188    }
189
190    /// This method takes the entire TelemetrySettings struct in order to force client code
191    /// to pull the struct out of the settings global. Do not remove!
192    pub fn set_authenticated_user_info(
193        self: &Arc<Self>,
194        metrics_id: Option<String>,
195        is_staff: bool,
196        telemetry_settings: TelemetrySettings,
197    ) {
198        if !telemetry_settings.metrics() {
199            return;
200        }
201
202        let this = self.clone();
203        let mut state = self.state.lock();
204        let device_id = state.device_id.clone();
205        let metrics_id: Option<Arc<str>> = metrics_id.map(|id| id.into());
206        state.metrics_id = metrics_id.clone();
207        state.is_staff = Some(is_staff);
208        drop(state);
209
210        if let Some((token, device_id)) = MIXPANEL_TOKEN.as_ref().zip(device_id) {
211            self.executor
212                .spawn(
213                    async move {
214                        let json_bytes = serde_json::to_vec(&[MixpanelEngageRequest {
215                            token,
216                            distinct_id: device_id,
217                            set: json!({
218                                "Staff": is_staff,
219                                "ID": metrics_id,
220                                "App": true
221                            }),
222                        }])?;
223                        let request = Request::post(MIXPANEL_ENGAGE_URL)
224                            .header("Content-Type", "application/json")
225                            .body(json_bytes.into())?;
226                        this.http_client.send(request).await?;
227                        anyhow::Ok(())
228                    }
229                    .log_err(),
230                )
231                .detach();
232        }
233    }
234
235    pub fn report_event(
236        self: &Arc<Self>,
237        kind: &str,
238        properties: Value,
239        telemetry_settings: TelemetrySettings,
240    ) {
241        if !telemetry_settings.metrics() {
242            return;
243        }
244
245        let mut state = self.state.lock();
246        let event = MixpanelEvent {
247            event: kind.to_string(),
248            properties: MixpanelEventProperties {
249                token: "",
250                time: SystemTime::now()
251                    .duration_since(UNIX_EPOCH)
252                    .unwrap()
253                    .as_millis(),
254                distinct_id: state.device_id.clone(),
255                insert_id: post_inc(&mut state.next_event_id),
256                event_properties: if let Value::Object(properties) = properties {
257                    Some(properties)
258                } else {
259                    None
260                },
261                os_name: state.os_name,
262                os_version: state.os_version.clone(),
263                release_channel: state.release_channel,
264                app_version: state.app_version.clone(),
265                signed_in: state.metrics_id.is_some(),
266            },
267        };
268        state.queue.push(event);
269        if state.device_id.is_some() {
270            if state.queue.len() >= MAX_QUEUE_LEN {
271                drop(state);
272                self.flush();
273            } else {
274                let this = self.clone();
275                let executor = self.executor.clone();
276                state.flush_task = Some(self.executor.spawn(async move {
277                    executor.timer(DEBOUNCE_INTERVAL).await;
278                    this.flush();
279                }));
280            }
281        }
282    }
283
284    pub fn metrics_id(self: &Arc<Self>) -> Option<Arc<str>> {
285        self.state.lock().metrics_id.clone()
286    }
287
288    pub fn is_staff(self: &Arc<Self>) -> Option<bool> {
289        self.state.lock().is_staff
290    }
291
292    fn flush(self: &Arc<Self>) {
293        let mut state = self.state.lock();
294        let mut events = mem::take(&mut state.queue);
295        state.flush_task.take();
296        drop(state);
297
298        if let Some(token) = MIXPANEL_TOKEN.as_ref() {
299            let this = self.clone();
300            self.executor
301                .spawn(
302                    async move {
303                        let mut json_bytes = Vec::new();
304
305                        if let Some(file) = &mut this.state.lock().log_file {
306                            let file = file.as_file_mut();
307                            for event in &mut events {
308                                json_bytes.clear();
309                                serde_json::to_writer(&mut json_bytes, event)?;
310                                file.write_all(&json_bytes)?;
311                                file.write(b"\n")?;
312
313                                event.properties.token = token;
314                            }
315                        }
316
317                        json_bytes.clear();
318                        serde_json::to_writer(&mut json_bytes, &events)?;
319                        let request = Request::post(MIXPANEL_EVENTS_URL)
320                            .header("Content-Type", "application/json")
321                            .body(json_bytes.into())?;
322                        this.http_client.send(request).await?;
323                        anyhow::Ok(())
324                    }
325                    .log_err(),
326                )
327                .detach();
328        }
329    }
330}