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, $($key:ident $(= $value:expr)?),+ $(,)?) => {{
21 let event = $crate::Event {
22 event_type: $name.to_string(),
23 event_properties: std::collections::HashMap::from([
24 $(
25 (stringify!($key).to_string(),
26 $crate::serde_json::value::to_value(&$crate::serialize_property!($key $(= $value)?))
27 .unwrap_or_else(|_| $crate::serde_json::to_value(&()).unwrap())
28 ),
29 )+
30 ]),
31 };
32 $crate::send_event(event);
33 }};
34}
35
36#[macro_export]
37macro_rules! serialize_property {
38 ($key:ident) => {
39 $key
40 };
41 ($key:ident = $value:expr) => {
42 $value
43 };
44}
45
46pub fn send_event(event: Event) {
47 if let Some(queue) = TELEMETRY_QUEUE.get() {
48 queue.unbounded_send(event).ok();
49 return;
50 }
51}
52
53pub fn init(tx: mpsc::UnboundedSender<Event>) {
54 TELEMETRY_QUEUE.set(tx).ok();
55}
56
57static TELEMETRY_QUEUE: OnceLock<mpsc::UnboundedSender<Event>> = OnceLock::new();