Skip to main content

deq_runtime/misc/
fastrace.rs

1//! Tracing utilities for performance profiling.
2//!
3//! When the `fastrace` feature is enabled, spans and events are recorded using
4//! the fastrace crate and can be exported to a file via `FileReporter`.
5//! When disabled, all tracing calls are no-ops with zero runtime cost.
6
7#[cfg(feature = "cli")]
8mod inner {
9    use fastrace::collector::Reporter;
10    use prost::Message;
11    use std::fs::File;
12    use std::io::{BufWriter, Write};
13
14    include!("../proto/deq.misc.fastrace.rs");
15
16    pub struct FileReporter {
17        buf_writer: BufWriter<std::fs::File>,
18        buffer: Vec<u8>,
19    }
20
21    impl FileReporter {
22        pub fn new(file_path: &str) -> Self {
23            let file = File::create(file_path).unwrap();
24            let buf_writer = BufWriter::new(file);
25            Self {
26                buf_writer,
27                buffer: vec![],
28            }
29        }
30    }
31
32    impl Reporter for FileReporter {
33        fn report(&mut self, spans: Vec<fastrace::prelude::SpanRecord>) {
34            for span in spans.iter() {
35                let record = convert(span);
36                let content = TraceFile { spans: vec![record] };
37                self.buffer.clear();
38                content.encode(&mut self.buffer).unwrap();
39                self.buf_writer.write_all(&self.buffer).unwrap();
40            }
41            self.buf_writer.flush().unwrap();
42        }
43    }
44
45    pub fn convert(span: &fastrace::prelude::SpanRecord) -> SpanRecord {
46        let mut last_time = span.begin_time_unix_ns;
47        SpanRecord {
48            begin_time_unix_ns: span.begin_time_unix_ns,
49            duration_ns: span.duration_ns,
50            name: span.name.to_string(),
51            properties: span
52                .properties
53                .iter()
54                .map(|(k, v)| Property {
55                    key: k.to_string(),
56                    value: v.to_string(),
57                })
58                .collect(),
59            events: span
60                .events
61                .iter()
62                .map(|e| {
63                    let delta_ns = e.timestamp_unix_ns.saturating_sub(last_time);
64                    last_time = e.timestamp_unix_ns;
65                    EventRecord {
66                        name: e.name.to_string(),
67                        timestamp_unix_ns: e.timestamp_unix_ns,
68                        properties: e
69                            .properties
70                            .iter()
71                            .map(|(k, v)| Property {
72                                key: k.to_string(),
73                                value: v.to_string(),
74                            })
75                            .collect(),
76                        delta_ns,
77                    }
78                })
79                .collect(),
80        }
81    }
82}
83
84#[cfg(feature = "cli")]
85pub use inner::FileReporter;
86
87// Re-export or provide no-op shims so call sites compile without cfg blocks.
88#[cfg(feature = "cli")]
89pub use fastrace::prelude::{Event, Span, SpanContext};
90
91/// No-op span that silently discards all property and event calls.
92#[cfg(not(feature = "cli"))]
93pub struct Span;
94
95#[cfg(not(feature = "cli"))]
96impl Span {
97    #[inline]
98    pub fn root(_name: &'static str, _context: SpanContext) -> Self {
99        Self
100    }
101    #[inline]
102    pub fn add_property<K: Into<String>, V: Into<String>, F: FnOnce() -> (K, V)>(&self, _f: F) {}
103    #[inline]
104    pub fn add_event(&self, _event: Event) {}
105}
106
107/// No-op event.
108#[cfg(not(feature = "cli"))]
109pub struct Event;
110
111#[cfg(not(feature = "cli"))]
112impl Event {
113    #[inline]
114    pub fn new(_name: &'static str) -> Self {
115        Self
116    }
117    #[inline]
118    pub fn with_property<K: Into<String>, V: Into<String>, F: FnOnce() -> (K, V)>(self, _f: F) -> Self {
119        self
120    }
121}
122
123/// No-op span context.
124#[cfg(not(feature = "cli"))]
125pub struct SpanContext;
126
127#[cfg(not(feature = "cli"))]
128impl SpanContext {
129    #[inline]
130    pub fn random() -> Self {
131        Self
132    }
133}