telemetry.rs

 1//! See [Telemetry in Zed](https://zed.dev/docs/telemetry) for additional information.
 2use futures::channel::mpsc;
 3pub use serde_json;
 4use std::sync::OnceLock;
 5pub use telemetry_events::FlexibleEvent as Event;
 6
 7/// Macro to create telemetry events and send them to the telemetry queue.
 8///
 9/// By convention, the name should be "Noun Verbed", e.g. "Keymap Changed"
10/// or "Project Diagnostics Opened".
11///
12/// The properties can be any value that implements serde::Serialize.
13///
14/// ```
15/// telemetry::event!("Keymap Changed", version = "1.0.0");
16/// telemetry::event!("Documentation Viewed", url, source = "Extension Upsell");
17/// ```
18#[macro_export]
19macro_rules! event {
20    ($name:expr) => {{
21        let event = $crate::Event {
22            event_type: $name.to_string(),
23            event_properties: std::collections::HashMap::new(),
24        };
25        $crate::send_event(event);
26    }};
27    ($name:expr, $($key:ident $(= $value:expr)?),+ $(,)?) => {{
28        let event = $crate::Event {
29            event_type: $name.to_string(),
30            event_properties: std::collections::HashMap::from([
31                $(
32                    (stringify!($key).to_string(),
33                        $crate::serde_json::value::to_value(&$crate::serialize_property!($key $(= $value)?))
34                            .unwrap_or_else(|_| $crate::serde_json::to_value(&()).unwrap())
35                    ),
36                )+
37            ]),
38        };
39        $crate::send_event(event);
40    }};
41}
42
43#[macro_export]
44macro_rules! serialize_property {
45    ($key:ident) => {
46        $key
47    };
48    ($key:ident = $value:expr) => {
49        $value
50    };
51}
52
53pub fn send_event(event: Event) {
54    if let Some(queue) = TELEMETRY_QUEUE.get() {
55        queue.unbounded_send(event).ok();
56        return;
57    }
58}
59
60pub fn init(tx: mpsc::UnboundedSender<Event>) {
61    TELEMETRY_QUEUE.set(tx).ok();
62}
63
64static TELEMETRY_QUEUE: OnceLock<mpsc::UnboundedSender<Event>> = OnceLock::new();