Skip to main content

troupekit_trace/
tracer.rs

1use crate::category::{Trace, TraceSet};
2use crate::error::TraceError;
3use crate::record;
4use crate::redact;
5use crate::sink::TraceSink;
6use crate::switch;
7use crate::value::{cut_to, Value};
8use std::cell::{Cell, RefCell};
9use std::future::Future;
10use std::pin::Pin;
11use std::sync::atomic::{AtomicU64, Ordering};
12use std::sync::Arc;
13use std::task::{Context, Poll};
14use std::time::{SystemTime, UNIX_EPOCH};
15
16const SECRETS_MAX: usize = 1024;
17const NAME_BYTES_MAX: usize = 128;
18
19thread_local! {
20    static CURRENT: RefCell<Option<Ctx>> = const { RefCell::new(None) };
21    static EMITTING: Cell<bool> = const { Cell::new(false) };
22}
23
24pub(crate) struct Shared {
25    pub(crate) trace_id: u64,
26    pub(crate) name: String,
27    pub(crate) sink: Arc<dyn TraceSink>,
28    next_span: AtomicU64,
29    pub(crate) dropped: AtomicU64,
30    pub(crate) truncated: AtomicU64,
31}
32
33impl Shared {
34    fn alloc_span(&self) -> u64 {
35        let id = self.next_span.fetch_add(1, Ordering::Relaxed);
36        assert!(id > 0, "span ids start at 1");
37        assert!(id < u64::MAX, "span ids exhausted");
38        id
39    }
40}
41
42impl Drop for Shared {
43    fn drop(&mut self) {
44        let line = record::footer(self);
45        write_line(&*self.sink, &line);
46        flush_sink(&*self.sink);
47    }
48}
49
50pub(crate) struct Inner {
51    pub(crate) shared: Arc<Shared>,
52    pub(crate) categories: TraceSet,
53    pub(crate) content: bool,
54    content_set: bool,
55    pub(crate) scrub: Vec<String>,
56}
57
58impl Inner {
59    fn new(
60        shared: Arc<Shared>,
61        categories: TraceSet,
62        content: Option<bool>,
63        scrub: Vec<String>,
64    ) -> Inner {
65        switch::acquire(categories);
66        let content_set = content.is_some();
67        Inner {
68            shared,
69            categories,
70            content: content.unwrap_or(false),
71            content_set,
72            scrub,
73        }
74    }
75}
76
77impl Drop for Inner {
78    fn drop(&mut self) {
79        switch::release(self.categories);
80    }
81}
82
83/// A live trace: categories, content flag, scrubbed secrets and one sink.
84/// Built with `Tracer::builder()`. While any clone is alive its categories
85/// are switched on, but points record only inside `enter` or `in_scope`.
86#[derive(Clone)]
87pub struct Tracer {
88    inner: Arc<Inner>,
89}
90
91/// Settings for a new `Tracer`. The trace id is chosen when the builder is
92/// made, so a caller can name a file after it before picking the sink.
93/// Defaults: every category, content withheld, name `trace`.
94pub struct TracerBuilder {
95    trace_id: u64,
96    categories: TraceSet,
97    content: Option<bool>,
98    sink: Option<Arc<dyn TraceSink>>,
99    scrub: Vec<String>,
100    name: String,
101}
102
103impl Tracer {
104    /// Starts a tracer with the default settings and a fresh trace id.
105    /// Input: none. Output: a builder; `.sink(..)` is required.
106    pub fn builder() -> TracerBuilder {
107        TracerBuilder {
108            trace_id: new_trace_id(),
109            categories: TraceSet::all(),
110            content: None,
111            sink: None,
112            scrub: Vec::new(),
113            name: "trace".to_owned(),
114        }
115    }
116
117    /// Returns the 64-bit trace id; records show it as 16 hex characters.
118    /// Input: none. Output: the id.
119    pub fn trace_id(&self) -> u64 {
120        self.inner.shared.trace_id
121    }
122
123    /// Returns the categories this tracer switches on.
124    /// Input: none. Output: the set.
125    pub fn categories(&self) -> TraceSet {
126        self.inner.categories
127    }
128
129    /// Runs `f` with this tracer as the current scope on this thread.
130    /// Inside an active scope of another tracer it nests (see `Ctx::nest`).
131    /// Input: the closure. Output: its result.
132    pub fn enter<R>(&self, f: impl FnOnce() -> R) -> R {
133        self.scope_ctx().enter(f)
134    }
135
136    /// Wraps `fut` so this tracer is the current scope on every poll,
137    /// on whatever thread polls it. The scope is fixed when this is called.
138    /// Input: the future. Output: the wrapped future.
139    pub fn in_scope<F: Future>(&self, fut: F) -> Instrumented<F> {
140        self.scope_ctx().in_scope(fut)
141    }
142
143    fn scope_ctx(&self) -> Ctx {
144        match current() {
145            Some(outer) if Arc::ptr_eq(&outer.inner.shared, &self.inner.shared) => outer,
146            Some(outer) => outer.merge(&self.inner),
147            None => Ctx {
148                inner: self.inner.clone(),
149                span: 0,
150            },
151        }
152    }
153}
154
155impl TracerBuilder {
156    /// Sets the categories. Input: the set. Output: the builder.
157    pub fn categories(mut self, categories: TraceSet) -> TracerBuilder {
158        self.categories = categories;
159        self
160    }
161
162    /// Keeps (`true`) or withholds content values. Input: the flag.
163    /// Output: the builder. Unset means withheld, or the outer scope's value.
164    pub fn content(mut self, content: bool) -> TracerBuilder {
165        self.content = Some(content);
166        self
167    }
168
169    /// Sets the sink that receives every record line. Required.
170    /// Input: the sink. Output: the builder.
171    pub fn sink(mut self, sink: Arc<dyn TraceSink>) -> TracerBuilder {
172        self.sink = Some(sink);
173        self
174    }
175
176    /// Adds a secret value, such as an API key, replaced by `[redacted]`
177    /// in every record. An empty value is ignored. At most 1024 secrets.
178    /// Input: the secret. Output: the builder.
179    pub fn scrub(mut self, secret: &str) -> TracerBuilder {
180        if !secret.is_empty() {
181            self.scrub.push(secret.to_owned());
182        }
183        self
184    }
185
186    /// Sets the trace name written in the header. `build` scrubs it first
187    /// and then cuts it to 128 bytes, so a secret across the cut is removed.
188    /// Input: the name. Output: the builder.
189    pub fn name(mut self, name: &str) -> TracerBuilder {
190        self.name = name.to_owned();
191        self
192    }
193
194    /// Returns the trace id the tracer will have. Input: none. Output: the id.
195    pub fn trace_id(&self) -> u64 {
196        self.trace_id
197    }
198
199    /// Builds the tracer and writes the header record to its sink.
200    /// Input: none. Output: the tracer, or `MissingSink`, `TooManySecrets`,
201    /// or `InsideSink` when called from a sink write or flush, where the
202    /// header could not be written.
203    pub fn build(self) -> Result<Tracer, TraceError> {
204        let sink = self.sink.ok_or(TraceError::MissingSink)?;
205        if self.scrub.len() > SECRETS_MAX {
206            return Err(TraceError::TooManySecrets(self.scrub.len()));
207        }
208        if EMITTING.try_with(Cell::get).unwrap_or(true) {
209            return Err(TraceError::InsideSink);
210        }
211        assert_ne!(self.trace_id, 0);
212        let name = cut_to(&redact::scrub(&self.name, &self.scrub), NAME_BYTES_MAX).to_owned();
213        assert!(name.len() <= NAME_BYTES_MAX);
214        let shared = Arc::new(Shared {
215            trace_id: self.trace_id,
216            name,
217            sink,
218            next_span: AtomicU64::new(1),
219            dropped: AtomicU64::new(0),
220            truncated: AtomicU64::new(0),
221        });
222        let inner = Arc::new(Inner::new(
223            shared,
224            self.categories,
225            self.content,
226            self.scrub,
227        ));
228        write_line(&*inner.shared.sink, &record::header(&inner));
229        Ok(Tracer { inner })
230    }
231}
232
233/// A captured trace scope: a tracer plus the current span id.
234/// Get one with `current()` and re-enter it in a spawned task or a
235/// blocking closure with `enter` or `in_scope`, so parents stay right.
236#[derive(Clone)]
237pub struct Ctx {
238    pub(crate) inner: Arc<Inner>,
239    pub(crate) span: u64,
240}
241
242impl Ctx {
243    /// Runs `f` with this scope current on this thread, restoring the
244    /// previous scope afterwards, also when `f` panics.
245    /// Input: the closure. Output: its result.
246    pub fn enter<R>(&self, f: impl FnOnce() -> R) -> R {
247        let _guard = ScopeGuard::set(Some(self.clone()));
248        f()
249    }
250
251    /// Wraps `fut` so this scope is current on every poll.
252    /// Input: the future. Output: the wrapped future.
253    pub fn in_scope<F: Future>(&self, fut: F) -> Instrumented<F> {
254        Instrumented {
255            fut: Box::pin(fut),
256            ctx: self.clone(),
257        }
258    }
259
260    /// Returns a scope in the same trace and sink with `categories` added.
261    /// `content` replaces this scope's content flag when given.
262    /// Input: extra categories and an optional flag. Output: the nested scope.
263    pub fn nest(&self, categories: TraceSet, content: Option<bool>) -> Ctx {
264        let inner = Inner::new(
265            self.inner.shared.clone(),
266            self.inner.categories.union(categories),
267            Some(content.unwrap_or(self.inner.content)),
268            self.inner.scrub.clone(),
269        );
270        Ctx {
271            inner: Arc::new(inner),
272            span: self.span,
273        }
274    }
275
276    fn merge(&self, other: &Inner) -> Ctx {
277        let content = if other.content_set {
278            other.content
279        } else {
280            self.inner.content
281        };
282        let mut scrub = self.inner.scrub.clone();
283        scrub.extend(other.scrub.iter().cloned());
284        let inner = Inner::new(
285            self.inner.shared.clone(),
286            self.inner.categories.union(other.categories),
287            Some(content),
288            scrub,
289        );
290        Ctx {
291            inner: Arc::new(inner),
292            span: self.span,
293        }
294    }
295
296    /// Returns the trace id. Input: none. Output: the id.
297    pub fn trace_id(&self) -> u64 {
298        self.inner.shared.trace_id
299    }
300
301    /// Returns the current span id, 0 at the root. Input: none. Output: the id.
302    pub fn span_id(&self) -> u64 {
303        self.span
304    }
305
306    /// Returns the categories of this scope. Input: none. Output: the set.
307    pub fn categories(&self) -> TraceSet {
308        self.inner.categories
309    }
310
311    /// Returns whether this scope keeps content. Input: none. Output: the flag.
312    pub fn content(&self) -> bool {
313        self.inner.content
314    }
315
316    pub(crate) fn child(&self, span: u64) -> Ctx {
317        Ctx {
318            inner: self.inner.clone(),
319            span,
320        }
321    }
322
323    pub(crate) fn alloc_span(&self) -> u64 {
324        let id = self.inner.shared.alloc_span();
325        check_parent(self.span, id);
326        id
327    }
328
329    pub(crate) fn emit(&self, line: &str) {
330        write_line(&*self.inner.shared.sink, line);
331    }
332
333    pub(crate) fn flush(&self) {
334        flush_sink(&*self.inner.shared.sink);
335    }
336}
337
338/// Returns the trace scope current on this thread, if any.
339/// Input: none. Output: a clone of the scope, to pass into a spawned task
340/// or a blocking closure and re-enter there.
341pub fn current() -> Option<Ctx> {
342    CURRENT
343        .try_with(|cell| cell.try_borrow().ok().and_then(|ctx| ctx.clone()))
344        .ok()
345        .flatten()
346}
347
348pub(crate) fn scope_contains(t: Trace) -> bool {
349    if EMITTING.try_with(Cell::get).unwrap_or(true) {
350        return false;
351    }
352    CURRENT
353        .try_with(|cell| {
354            cell.try_borrow()
355                .ok()
356                .is_some_and(|ctx| ctx.as_ref().is_some_and(|c| c.inner.categories.contains(t)))
357        })
358        .unwrap_or(false)
359}
360
361/// Writes a point event of category `cat` in the current scope.
362/// Called by `trace!` after `enabled`; not meant to be called directly.
363#[doc(hidden)]
364pub fn point(cat: Trace, name: &'static str, fields: Vec<(&'static str, Value)>) {
365    let Some(ctx) = current() else { return };
366    let line = record::event(&ctx, cat, name, fields);
367    ctx.emit(&line);
368}
369
370fn write_line(sink: &dyn TraceSink, line: &str) {
371    if EMITTING.try_with(|flag| flag.replace(true)).unwrap_or(true) {
372        return;
373    }
374    let _guard = EmitGuard;
375    sink.write(line);
376}
377
378/// Flushes `sink` under the same guard as `write_line`, so a flush that
379/// traces cannot flush again and its trace points are suppressed.
380/// Input: the sink. Output: none.
381fn flush_sink(sink: &dyn TraceSink) {
382    if EMITTING.try_with(|flag| flag.replace(true)).unwrap_or(true) {
383        return;
384    }
385    let _guard = EmitGuard;
386    sink.flush();
387}
388
389struct EmitGuard;
390
391impl Drop for EmitGuard {
392    fn drop(&mut self) {
393        let _ = EMITTING.try_with(|flag| flag.set(false));
394    }
395}
396
397fn check_parent(parent: u64, id: u64) {
398    assert!(id > 0, "span id 0 is reserved");
399    assert!(
400        parent < id,
401        "parent span {parent} not opened before span {id}"
402    );
403}
404
405struct ScopeGuard {
406    prev: Option<Ctx>,
407}
408
409impl ScopeGuard {
410    fn set(ctx: Option<Ctx>) -> ScopeGuard {
411        let prev = CURRENT.try_with(|cell| cell.replace(ctx)).ok().flatten();
412        ScopeGuard { prev }
413    }
414}
415
416impl Drop for ScopeGuard {
417    fn drop(&mut self) {
418        let prev = self.prev.take();
419        let _ = CURRENT.try_with(|cell| cell.replace(prev));
420    }
421}
422
423/// A future that installs a trace scope on every poll and restores the
424/// previous one after, so the scope follows the task across threads.
425/// Made by `Tracer::in_scope` and `Ctx::in_scope`.
426pub struct Instrumented<F> {
427    fut: Pin<Box<F>>,
428    ctx: Ctx,
429}
430
431impl<F: Future> Future for Instrumented<F> {
432    type Output = F::Output;
433
434    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<F::Output> {
435        let this = self.get_mut();
436        let _guard = ScopeGuard::set(Some(this.ctx.clone()));
437        this.fut.as_mut().poll(cx)
438    }
439}
440
441fn new_trace_id() -> u64 {
442    static COUNTER: AtomicU64 = AtomicU64::new(0);
443    let nanos = SystemTime::now()
444        .duration_since(UNIX_EPOCH)
445        .map_or(0, |d| d.as_nanos());
446    let count = COUNTER.fetch_add(1, Ordering::Relaxed);
447    let id = splitmix64((nanos as u64) ^ count.rotate_left(32) ^ u64::from(std::process::id()));
448    if id == 0 {
449        1
450    } else {
451        id
452    }
453}
454
455fn splitmix64(seed: u64) -> u64 {
456    let mut z = seed.wrapping_add(0x9E37_79B9_7F4A_7C15);
457    z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
458    z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
459    z ^ (z >> 31)
460}
461
462#[cfg(test)]
463mod tests {
464    use super::*;
465
466    #[test]
467    #[should_panic(expected = "not opened before")]
468    fn parent_after_child_panics() {
469        check_parent(5, 3);
470    }
471
472    #[test]
473    fn trace_ids_differ() {
474        assert_ne!(new_trace_id(), new_trace_id());
475    }
476}