Skip to main content

cja/
product_event.rs

1//! Explicit product analytics declarations. Ordinary tracing events never enter capture.
2use color_eyre::eyre::WrapErr as _;
3use serde::Serialize;
4use serde_json::{Map, Value};
5use std::sync::atomic::{AtomicU64, Ordering};
6use std::{
7    fmt,
8    sync::{OnceLock, RwLock},
9    time::Duration,
10};
11use tokio::{sync::mpsc, task::JoinHandle};
12use uuid::Uuid;
13
14pub(crate) const MAX_CAPTURE_QUEUE: usize = 1024;
15const MAX_EVENT_BYTES: usize = 1024 * 1024;
16const MAX_BODY_BYTES: usize = 9 * 1024 * 1024;
17static DROPPED: AtomicU64 = AtomicU64::new(0);
18static FAILURES: AtomicU64 = AtomicU64::new(0);
19fn report_failure() -> Option<u64> {
20    let count = FAILURES.fetch_add(1, Ordering::Relaxed) + 1;
21    count.is_power_of_two().then_some(count)
22}
23fn dropped(reason: &str) {
24    let count = DROPPED.fetch_add(1, Ordering::Relaxed) + 1;
25    if count.is_power_of_two() {
26        tracing::warn!(target: "posthog", count, reason, "capture events dropped");
27    }
28}
29
30#[derive(Serialize)]
31struct CaptureEvent {
32    event: String,
33    uuid: Uuid,
34    distinct_id: String,
35    timestamp: String,
36    #[serde(skip_serializing_if = "Option::is_none")]
37    options: Option<CaptureOptions>,
38    properties: Map<String, Value>,
39}
40#[derive(Serialize)]
41struct CaptureOptions {
42    process_person_profile: bool,
43}
44
45struct SerializedEvent {
46    uuid: Uuid,
47    bytes: Vec<u8>,
48}
49
50#[derive(Clone)]
51struct Sender {
52    tx: mpsc::Sender<SerializedEvent>,
53    service: String,
54}
55static SENDER: OnceLock<RwLock<Option<Sender>>> = OnceLock::new();
56fn registry() -> &'static RwLock<Option<Sender>> {
57    SENDER.get_or_init(|| RwLock::new(None))
58}
59
60#[doc(hidden)]
61pub fn identity(id: Option<&dyn fmt::Display>) -> Option<String> {
62    id.map(ToString::to_string)
63}
64#[doc(hidden)]
65pub fn bare<T: Serialize>(value: &T) -> Option<Value> {
66    serde_json::to_value(value)
67        .map_err(|_| tracing::warn!(target: "posthog", "product property serialization failed"))
68        .ok()
69}
70#[doc(hidden)]
71pub fn enabled() -> bool {
72    registry()
73        .read()
74        .unwrap_or_else(std::sync::PoisonError::into_inner)
75        .is_some()
76}
77#[doc(hidden)]
78pub fn submit(name: &str, id: Option<&str>, mut properties: Map<String, Value>) {
79    let sender = registry()
80        .read()
81        .unwrap_or_else(std::sync::PoisonError::into_inner)
82        .clone();
83    let Some(sender) = sender else { return };
84    properties.insert("service.name".into(), sender.service.into());
85    let event = CaptureEvent {
86        event: name.to_owned(),
87        uuid: Uuid::now_v7(),
88        distinct_id: id.map_or_else(|| Uuid::new_v4().to_string(), str::to_owned),
89        timestamp: format!("{:.3}", jiff::Timestamp::now()),
90        options: id.is_none().then_some(CaptureOptions {
91            process_person_profile: false,
92        }),
93        properties,
94    };
95    let Ok(bytes) = serde_json::to_vec(&event) else {
96        dropped("event serialization failed");
97        return;
98    };
99    if bytes.len() >= MAX_EVENT_BYTES {
100        dropped("event too large");
101        return;
102    }
103    if sender
104        .tx
105        .try_send(SerializedEvent {
106            uuid: event.uuid,
107            bytes,
108        })
109        .is_err()
110    {
111        dropped("queue full or closed");
112    }
113}
114
115pub(crate) struct CaptureShutdownHandle {
116    task: JoinHandle<()>,
117}
118impl fmt::Debug for CaptureShutdownHandle {
119    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
120        f.write_str("CaptureShutdownHandle")
121    }
122}
123impl CaptureShutdownHandle {
124    pub(crate) async fn shutdown(self, budget: Duration) {
125        registry()
126            .write()
127            .unwrap_or_else(std::sync::PoisonError::into_inner)
128            .take();
129        let mut task = self.task;
130        match tokio::time::timeout(budget, &mut task).await {
131            Err(_) => {
132                tracing::warn!(target: "posthog", "capture shutdown budget exceeded; queued events dropped");
133                task.abort();
134                let _ = task.await;
135            }
136            Ok(Err(error)) => tracing::warn!(target: "posthog", ?error, "capture worker failed"),
137            Ok(Ok(())) => {}
138        }
139    }
140}
141
142pub(crate) fn start(
143    host: &str,
144    token: &str,
145    service: &str,
146    capacity: usize,
147) -> color_eyre::Result<Option<CaptureShutdownHandle>> {
148    let Ok(runtime) = tokio::runtime::Handle::try_current() else {
149        println!("Skipping PostHog capture: no Tokio runtime");
150        return Ok(None);
151    };
152    let client = reqwest_012::Client::builder()
153        .use_preconfigured_tls(
154            crate::tls::ring_client_config().wrap_err("building the PostHog capture TLS config")?,
155        )
156        .timeout(Duration::from_secs(2))
157        .build()
158        .wrap_err("building the PostHog capture HTTP client")?;
159    let (tx, rx) = mpsc::channel(capacity);
160    let url = format!("{host}/i/v1/analytics/events");
161    let bearer = format!("Bearer {token}");
162    let task = runtime.spawn(worker(rx, client, url, bearer));
163    *registry()
164        .write()
165        .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(Sender {
166        tx,
167        service: service.to_owned(),
168    });
169    Ok(Some(CaptureShutdownHandle { task }))
170}
171
172#[allow(clippy::too_many_lines)]
173async fn worker(
174    mut rx: mpsc::Receiver<SerializedEvent>,
175    client: reqwest_012::Client,
176    url: String,
177    bearer: String,
178) {
179    let mut batch = Vec::new();
180    let mut deadline = None;
181    loop {
182        let (next, channel_drained) = if let Some(batch_deadline) = deadline {
183            match tokio::time::timeout_at(batch_deadline, rx.recv()).await {
184                Ok(Some(event)) => (Some(event), false),
185                Ok(None) => (None, true),
186                Err(_) => (None, false),
187            }
188        } else {
189            match rx.recv().await {
190                Some(event) => (Some(event), false),
191                None => (None, true),
192            }
193        };
194        let received = next.is_some();
195        if let Some(event) = next {
196            if batch.is_empty() {
197                deadline = Some(tokio::time::Instant::now() + Duration::from_secs(1));
198            }
199            batch.push(event);
200        }
201        if batch.len() < 100 && received {
202            continue;
203        }
204        if !batch.is_empty() {
205            let events = std::mem::take(&mut batch);
206            deadline = None;
207            let mut chunks: Vec<Vec<SerializedEvent>> = Vec::new();
208            let mut chunk = Vec::new();
209            let mut size = 128;
210            for event in events {
211                let event_size = event.bytes.len() + 1;
212                if size + event_size >= MAX_BODY_BYTES && !chunk.is_empty() {
213                    chunks.push(std::mem::take(&mut chunk));
214                    size = 128;
215                }
216                size += event_size;
217                chunk.push(event);
218            }
219            if !chunk.is_empty() {
220                chunks.push(chunk);
221            }
222            for chunk in chunks {
223                let sent_uuids: Vec<String> =
224                    chunk.iter().map(|event| event.uuid.to_string()).collect();
225                let created_at = format!("{:.3}", jiff::Timestamp::now());
226                let Ok(created_at) = serde_json::to_vec(&created_at) else {
227                    dropped("batch serialization failed");
228                    continue;
229                };
230                let mut bytes = Vec::with_capacity(size);
231                bytes.extend_from_slice(b"{\"created_at\":");
232                bytes.extend_from_slice(&created_at);
233                bytes.extend_from_slice(b",\"batch\":[");
234                for (index, event) in chunk.iter().enumerate() {
235                    if index != 0 {
236                        bytes.push(b',');
237                    }
238                    bytes.extend_from_slice(&event.bytes);
239                }
240                bytes.extend_from_slice(b"]}");
241                if bytes.len() >= MAX_BODY_BYTES {
242                    dropped("batch too large");
243                    continue;
244                }
245                let result = client
246                    .post(&url)
247                    .header("Authorization", &bearer)
248                    .header("User-Agent", format!("cja/{}", env!("CARGO_PKG_VERSION")))
249                    .header(
250                        "PostHog-Sdk-Info",
251                        format!("cja/{}", env!("CARGO_PKG_VERSION")),
252                    )
253                    .header("PostHog-Request-Id", Uuid::new_v4().to_string())
254                    .header("PostHog-Attempt", "1")
255                    .header(
256                        "PostHog-Request-Timestamp",
257                        format!("{:.3}", jiff::Timestamp::now()),
258                    )
259                    .header("Content-Type", "application/json")
260                    .body(bytes)
261                    .send()
262                    .await;
263                match result {
264                    Ok(response) if response.status().is_success() => {
265                        match capture_result(response, &sent_uuids).await {
266                            CaptureResult::Delivered => {}
267                            CaptureResult::Rejected => {
268                                if let Some(count) = report_failure() {
269                                    tracing::warn!(target: "posthog", count, "capture rejected events");
270                                }
271                            }
272                            CaptureResult::Unreadable => {
273                                if let Some(count) = report_failure() {
274                                    tracing::warn!(target: "posthog", count, "capture response unreadable");
275                                }
276                            }
277                        }
278                    }
279                    Ok(response) => {
280                        if let Some(count) = report_failure() {
281                            tracing::warn!(target: "posthog", count, status = %response.status(), "capture request failed");
282                        }
283                    }
284                    Err(error) => {
285                        if let Some(count) = report_failure() {
286                            let kind = if error.is_timeout() {
287                                "timeout"
288                            } else if error.is_connect() {
289                                "connect"
290                            } else {
291                                "transport"
292                            };
293                            tracing::warn!(target: "posthog", count, kind, "capture request failed");
294                        }
295                    }
296                }
297            }
298        }
299        if channel_drained {
300            break;
301        }
302    }
303}
304
305#[derive(Clone, Copy)]
306enum CaptureResult {
307    Delivered,
308    Rejected,
309    Unreadable,
310}
311
312async fn capture_result(
313    mut response: reqwest_012::Response,
314    sent_uuids: &[String],
315) -> CaptureResult {
316    let mut body = Vec::new();
317    loop {
318        match response.chunk().await {
319            Ok(Some(chunk)) if body.len() + chunk.len() <= 65536 => body.extend_from_slice(&chunk),
320            Ok(None) => break,
321            _ => return CaptureResult::Unreadable,
322        }
323    }
324    let Ok(value) = serde_json::from_slice::<Value>(&body) else {
325        return CaptureResult::Unreadable;
326    };
327    let Some(raw_results) = value.get("results") else {
328        return CaptureResult::Delivered;
329    };
330    let Some(results) = raw_results.as_object() else {
331        return CaptureResult::Unreadable;
332    };
333    let rejected = results.iter().any(|(uuid, entry)| {
334        sent_uuids.iter().any(|sent| sent == uuid)
335            && (matches!(
336                entry.get("result").and_then(Value::as_str),
337                Some("drop" | "retry")
338            ) || entry
339                .get("duplicates_dropped")
340                .and_then(Value::as_u64)
341                .is_some_and(|n| n > 0))
342    });
343    if rejected {
344        CaptureResult::Rejected
345    } else {
346        CaptureResult::Delivered
347    }
348}
349
350/// Declares a product event for tracing and optional `PostHog` capture.
351///
352/// `properties` accepts bare `key = value` (typed tracing value, JSON serialized),
353/// `%value` (Display string), and `?value` (Debug string). `user_id` and
354/// `message` are reserved fields; cja sets the capture `service.name` property.
355/// `user_id` accepts `Option<&dyn std::fmt::Display>`. Anonymous events use a
356/// fresh random distinct ID and `process_person_profile = false`.
357/// `user_id` must be an opaque internal ID, never an email, name, or other PII.
358/// Property values, especially `?` Debug output, are sent to `PostHog` verbatim;
359/// callers must not include PII or secrets.
360///
361/// `POSTHOG_PROJECT_TOKEN` enables capture. Explicit capture is independent of
362/// `RUST_LOG`, `EnvFilter`, and `POSTHOG_LOG_LEVEL`. Capture uses a bounded,
363/// lossy queue (1024 events): full queues and events of at least 1 MiB are
364/// dropped, with no retry. The tracing event is still emitted.
365#[macro_export]
366macro_rules! product_event {
367    (name: $name:expr, user_id: $user:expr, message: $message:literal, properties: { $($fields:tt)* }) => {{
368        let __name = $name;
369        let __id: Option<&dyn std::fmt::Display> = $user;
370        let __id = $crate::__private::identity(__id);
371        let mut __properties = $crate::__private::serde_json::Map::new();
372        let mut __capture_ok = true;
373        $crate::__product_fields! { @parse [__name] [$message] [__id] [__properties] [__capture_ok] [] $($fields)* }
374    }};
375}
376#[doc(hidden)]
377#[macro_export]
378macro_rules! __product_fields {
379    (@parse [$name:expr] [$msg:literal] [$id:ident] [$props:ident] [$ok:ident] [$($trace:tt)*] user_id = $($rest:tt)*) => { compile_error!("user_id is a reserved product event field"); };
380    (@parse [$name:expr] [$msg:literal] [$id:ident] [$props:ident] [$ok:ident] [$($trace:tt)*] message = $($rest:tt)*) => { compile_error!("message is a reserved product event field"); };
381    (@parse [$name:expr] [$msg:literal] [$id:ident] [$props:ident] [$ok:ident] [$($trace:tt)*]) => {{
382        if let Some(ref id) = $id {
383            $crate::__private::tracing::info!(event_type = $name, user_id = %id, $($trace)* "{}", $msg);
384        } else {
385            $crate::__private::tracing::info!(event_type = $name, $($trace)* "{}", $msg);
386        }
387        if $ok { $crate::__private::submit($name, $id.as_deref(), $props); }
388    }};
389    (@parse [$name:expr] [$msg:literal] [$id:ident] [$props:ident] [$ok:ident] [$($trace:tt)*] $key:ident = % $value:expr $(, $($rest:tt)*)?) => {{
390        let __value = &$value;
391        if $crate::__private::enabled() { $props.insert(stringify!($key).into(), $crate::__private::serde_json::Value::String(format!("{}", __value))); }
392        $crate::__product_fields! { @parse [$name] [$msg] [$id] [$props] [$ok] [$($trace)* $key = %__value,] $($($rest)*)? }
393    }};
394    (@parse [$name:expr] [$msg:literal] [$id:ident] [$props:ident] [$ok:ident] [$($trace:tt)*] $key:ident = ? $value:expr $(, $($rest:tt)*)?) => {{
395        let __value = &$value;
396        if $crate::__private::enabled() { $props.insert(stringify!($key).into(), $crate::__private::serde_json::Value::String(format!("{:?}", __value))); }
397        $crate::__product_fields! { @parse [$name] [$msg] [$id] [$props] [$ok] [$($trace)* $key = ?__value,] $($($rest)*)? }
398    }};
399    (@parse [$name:expr] [$msg:literal] [$id:ident] [$props:ident] [$ok:ident] [$($trace:tt)*] $key:ident = $value:expr $(, $($rest:tt)*)?) => {{
400        let __value = &$value;
401        if $crate::__private::enabled() {
402            if let Some(value) = $crate::__private::bare(__value) { $props.insert(stringify!($key).into(), value); } else { $ok = false; }
403        }
404        $crate::__product_fields! { @parse [$name] [$msg] [$id] [$props] [$ok] [$($trace)* $key = __value,] $($($rest)*)? }
405    }};
406}
407
408#[cfg(test)]
409mod tests {
410    use super::*;
411
412    #[tokio::test(flavor = "multi_thread")]
413    async fn capacity_one_drops_overflow_promptly() {
414        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
415        let host = format!("http://{}", listener.local_addr().unwrap());
416        let (accepted_tx, accepted_rx) = tokio::sync::oneshot::channel();
417        let server = tokio::spawn(async move {
418            let (stream, _) = listener.accept().await.unwrap();
419            let _hold = stream;
420            let _ = accepted_tx.send(());
421            tokio::time::sleep(Duration::from_secs(5)).await;
422        });
423        let handle = start(&host, "phc_fixture", "fixture", 1).unwrap().unwrap();
424        submit("first", None, Map::new());
425        tokio::time::timeout(Duration::from_secs(3), accepted_rx)
426            .await
427            .unwrap()
428            .unwrap();
429        let before_large = DROPPED.load(Ordering::Relaxed);
430        let mut properties = Map::new();
431        properties.insert("text".into(), Value::String("x".repeat(MAX_EVENT_BYTES)));
432        submit("large", None, properties);
433        assert_eq!(DROPPED.load(Ordering::Relaxed), before_large + 1);
434        assert_eq!(
435            registry().read().unwrap().as_ref().unwrap().tx.capacity(),
436            1
437        );
438        submit("queued", None, Map::new());
439        assert_eq!(
440            registry().read().unwrap().as_ref().unwrap().tx.capacity(),
441            0
442        );
443        let before = DROPPED.load(Ordering::Relaxed);
444        let start = std::time::Instant::now();
445        submit("overflow", None, Map::new());
446        assert!(start.elapsed() < Duration::from_millis(50));
447        assert_eq!(DROPPED.load(Ordering::Relaxed), before + 1);
448        handle.shutdown(Duration::from_millis(100)).await;
449        server.abort();
450    }
451
452    #[test]
453    fn ring_client_does_not_install_global_provider() {
454        let tls = crate::tls::ring_client_config().unwrap();
455        reqwest_012::Client::builder()
456            .use_preconfigured_tls(tls)
457            .build()
458            .unwrap();
459        assert!(rustls::crypto::CryptoProvider::get_default().is_none());
460    }
461}