Skip to main content

dfir_rs/scheduled/
metrics.rs

1//! Runtime metrics for DFIR.
2
3use std::pin::Pin;
4use std::sync::Arc;
5use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
6use std::task::{Context, Poll};
7
8use dfir_lang::graph_ids::{GraphNodeId, GraphSubgraphId};
9use pin_project_lite::pin_project;
10use sealed::sealed;
11use slotmap::SecondaryMap;
12use web_time::{Duration, Instant};
13
14/// Typestate marker for whether a [`Context`](super::context::Context) tracks runtime metrics.
15///
16/// This trait is sealed and is implemented for exactly two types:
17///
18/// - [`DfirMetrics`]: metrics are tracked. The context holds a shared [`Arc<DfirMetrics>`] handle
19///   which is updated by the generated code and exposed via
20///   [`Dfir::metrics`](super::context::Dfir::metrics).
21/// - `()`: metrics are not tracked. The handle is the zero-sized `()`, so the context statically
22///   contains no metrics state at all, and the `metrics()` accessors do not exist.
23///
24/// Which one is used is determined at codegen time by
25/// [`AsCodeOptions::include_metrics_tracking`](dfir_lang::graph::AsCodeOptions::include_metrics_tracking),
26/// so there is no runtime check or default-allocated metrics when tracking is disabled.
27#[sealed]
28pub trait MetricsState: 'static {
29    /// The metrics handle stored inside the context: [`Arc<DfirMetrics>`] or `()`.
30    type Handle;
31}
32
33/// Metrics are tracked.
34#[sealed]
35impl MetricsState for DfirMetrics {
36    type Handle = Arc<DfirMetrics>;
37}
38
39/// Metrics are not tracked. Zero-sized, no runtime cost.
40#[sealed]
41impl MetricsState for () {
42    type Handle = ();
43}
44
45/// Metrics for a [`Dfir`](super::context::Dfir) graph instance.
46///
47/// Call [`Dfir::metrics`](super::context::Dfir::metrics) for reference-counted continually-updated metrics,
48/// or call [`Dfir::metrics_intervals`](super::context::Dfir::metrics_intervals) to obtain a [`DfirMetricsIntervals`] handle, and use
49/// [`DfirMetricsIntervals::take_interval`] to retrieve metrics for successive intervals.
50///
51/// # Thread safety
52///
53/// All counters are atomics, so the live metrics may be read from any thread (e.g. a metrics
54/// reporting task) while the dataflow is running. Each individual counter is always consistent, but
55/// a snapshot (via [`Clone`] or [`DfirMetricsIntervals::take_interval`]) taken from another thread
56/// may observe counters from slightly different moments in time relative to each other (e.g.
57/// [`SubgraphMetrics::total_run_count`] incremented but [`SubgraphMetrics::total_poll_duration`]
58/// not yet updated for that run).
59#[derive(Default, Clone)]
60#[non_exhaustive]
61pub struct DfirMetrics {
62    /// Per-subgraph metrics.
63    pub subgraphs: SecondaryMap<GraphSubgraphId, SubgraphMetrics>,
64    /// Per-handoff metrics.
65    pub handoffs: SecondaryMap<GraphNodeId, HandoffMetrics>,
66}
67
68impl DfirMetrics {
69    /// Subtracts `other` from self.
70    pub(super) fn diff(&mut self, other: &Self) {
71        for (sg_id, prev_sg_metrics) in other.subgraphs.iter() {
72            if let Some(curr_sg_metrics) = self.subgraphs.get_mut(sg_id) {
73                curr_sg_metrics.diff(prev_sg_metrics);
74            }
75        }
76        for (handoff_id, prev_handoff_metrics) in other.handoffs.iter() {
77            if let Some(curr_handoff_metrics) = self.handoffs.get_mut(handoff_id) {
78                curr_handoff_metrics.diff(prev_handoff_metrics);
79            }
80        }
81    }
82}
83
84/// A handle into a DFIR instance's metrics, where each call to [`Self::take_interval`] ends the current interval and
85/// returns its metrics. Obtained via [`Dfir::metrics_intervals`](super::context::Dfir::metrics_intervals).
86///
87/// The first call to `take_interval` returns metrics since this DFIR instance was created. Each subsequent call to
88/// `take_interval` returns metrics since the previous call.
89///
90/// Cloning the handle "forks" it from the original, as afterwards each interval may return different metrics
91/// depending on when exactly `take_interval` is called.
92#[derive(Clone)]
93pub struct DfirMetricsIntervals {
94    /// `curr` is continually updating (via shared ownership).
95    pub(super) curr: Arc<DfirMetrics>,
96    /// `prev` is an unchanging snapshot in time. `None` for "since creation".
97    pub(super) prev: Option<DfirMetrics>,
98}
99
100impl DfirMetricsIntervals {
101    /// Ends the current interval and returns the accumulated metrics across the interval.
102    ///
103    /// The first call to `take_interval` returns metrics since this DFIR instance was created. Each subsequent call to
104    /// `take_interval` returns metrics since the previous call.
105    pub fn take_interval(&mut self) -> DfirMetrics {
106        let mut curr = self.curr.as_ref().clone();
107        if let Some(prev) = self.prev.replace(curr.clone()) {
108            curr.diff(&prev);
109        }
110        curr
111    }
112
113    /// Returns a reference-counted handle to the original continually-updated runtime metrics for this DFIR instance.
114    ///
115    /// See [`Dfir::metrics`](super::context::Dfir::metrics).
116    pub fn all_metrics(&self) -> Arc<DfirMetrics> {
117        Arc::clone(&self.curr)
118    }
119}
120
121/// An atomic cell holding a single metric value: [`AtomicCount`] or [`AtomicDuration`].
122///
123/// Metrics are written only by the thread running the dataflow and may be read concurrently from
124/// other threads, so all operations use [`Ordering::Relaxed`].
125#[sealed]
126pub trait MetricCell: Default {
127    /// The plain value type stored in this cell.
128    type Value: Copy;
129
130    /// Reads the current value.
131    fn get(&self) -> Self::Value;
132    /// Overwrites the current value.
133    fn set(&self, value: Self::Value);
134    /// Adds `value` to the current value.
135    fn add(&self, value: Self::Value);
136}
137
138/// An atomic `usize` counter metric. See [`MetricCell`].
139#[derive(Default, Debug)]
140#[repr(transparent)]
141pub struct AtomicCount(AtomicUsize);
142
143#[sealed]
144impl MetricCell for AtomicCount {
145    type Value = usize;
146
147    fn get(&self) -> usize {
148        self.0.load(Ordering::Relaxed)
149    }
150
151    fn set(&self, value: usize) {
152        self.0.store(value, Ordering::Relaxed);
153    }
154
155    fn add(&self, value: usize) {
156        self.0.fetch_add(value, Ordering::Relaxed);
157    }
158}
159
160impl Clone for AtomicCount {
161    fn clone(&self) -> Self {
162        let cell = Self::default();
163        cell.set(self.get());
164        cell
165    }
166}
167
168/// An atomic [`Duration`] metric, stored as whole nanoseconds in a `u64` (saturating at ~584
169/// years). See [`MetricCell`].
170#[derive(Default, Debug)]
171#[repr(transparent)]
172pub struct AtomicDuration(AtomicU64);
173
174impl AtomicDuration {
175    fn to_nanos(value: Duration) -> u64 {
176        u64::try_from(value.as_nanos()).unwrap_or(u64::MAX)
177    }
178}
179
180#[sealed]
181impl MetricCell for AtomicDuration {
182    type Value = Duration;
183
184    fn get(&self) -> Duration {
185        Duration::from_nanos(self.0.load(Ordering::Relaxed))
186    }
187
188    fn set(&self, value: Duration) {
189        self.0.store(Self::to_nanos(value), Ordering::Relaxed);
190    }
191
192    fn add(&self, value: Duration) {
193        self.0.fetch_add(Self::to_nanos(value), Ordering::Relaxed);
194    }
195}
196
197impl Clone for AtomicDuration {
198    fn clone(&self) -> Self {
199        let cell = Self::default();
200        cell.set(self.get());
201        cell
202    }
203}
204
205/// Declarative macro to generate metrics structs with atomic cell fields and value getter methods.
206macro_rules! define_metrics {
207    (
208        $(#[$struct_attr:meta])*
209        pub struct $struct_name:ident {
210            $(
211                $( #[doc = $doc:literal] )*
212                #[diff($diff:ident)]
213                $( #[$field_attr:meta] )*
214                $field_name:ident: $field_type:ty,
215            )*
216        }
217    ) => {
218        $(#[$struct_attr])*
219        #[derive(Default, Debug, Clone)]
220        #[non_exhaustive] // May add more metrics later.
221        pub struct $struct_name {
222            $(
223                #[doc(hidden)] // Public for codegen access; use the getter method instead.
224                $(#[$field_attr])*
225                pub $field_name: $field_type,
226            )*
227        }
228
229        impl $struct_name {
230            $(
231                $( #[doc = $doc] )*
232                pub fn $field_name(&self) -> <$field_type as MetricCell>::Value {
233                    self.$field_name.get()
234                }
235            )*
236
237            fn diff(&mut self, other: &Self) {
238                $(
239                    define_metrics_diff_field!($diff, $field_name, self, other);
240                )*
241            }
242        }
243    };
244}
245
246macro_rules! define_metrics_diff_field {
247    (total, $field:ident, $slf:ident, $other:ident) => {
248        debug_assert!($other.$field() <= $slf.$field());
249        $slf.$field.set($slf.$field() - $other.$field());
250    };
251    (curr, $field:ident, $slf:ident, $other:ident) => {};
252}
253
254define_metrics! {
255    /// Per-handoff metrics.
256    pub struct HandoffMetrics {
257        /// Number of items currently in the handoff.
258        #[diff(curr)]
259        curr_items_count: AtomicCount,
260
261        /// Total number of items read out of the handoff.
262        #[diff(total)]
263        total_items_count: AtomicCount,
264    }
265}
266
267define_metrics! {
268    /// Per-subgraph metrics.
269    pub struct SubgraphMetrics {
270        /// Number of times the subgraph has run.
271        #[diff(total)]
272        total_run_count: AtomicCount,
273
274        /// Time elapsed during polling (when the subgraph is actively doing work).
275        #[diff(total)]
276        total_poll_duration: AtomicDuration,
277
278        /// Number of times the subgraph has been polled.
279        #[diff(total)]
280        total_poll_count: AtomicCount,
281
282        /// Time elapsed during idle (when the subgraph has yielded and is waiting for async events).
283        #[diff(total)]
284        total_idle_duration: AtomicDuration,
285
286        /// Number of times the subgraph has been idle.
287        #[diff(total)]
288        total_idle_count: AtomicCount,
289    }
290}
291
292pin_project! {
293    /// Helper struct which instruments a future to track polling times.
294    #[doc(hidden)]
295    pub struct InstrumentSubgraph<'a, Fut> {
296        #[pin]
297        future: Fut,
298        idle_start: Option<Instant>,
299        metrics: &'a SubgraphMetrics,
300    }
301}
302
303impl<'a, Fut> InstrumentSubgraph<'a, Fut> {
304    /// Wrap a future to track per-subgraph poll and idle durations.
305    pub fn new(future: Fut, metrics: &'a SubgraphMetrics) -> Self {
306        Self {
307            future,
308            idle_start: None,
309            metrics,
310        }
311    }
312}
313
314impl<'a, Fut> Future for InstrumentSubgraph<'a, Fut>
315where
316    Fut: Future,
317{
318    type Output = Fut::Output;
319    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
320        let this = self.project();
321
322        // End idle duration.
323        if let Some(idle_start) = this.idle_start {
324            this.metrics.total_idle_duration.add(idle_start.elapsed());
325            this.metrics.total_idle_count.add(1);
326        }
327
328        // Begin poll duration.
329        let poll_start = Instant::now();
330        let out = this.future.poll(cx);
331
332        // End poll duration.
333        this.metrics.total_poll_duration.add(poll_start.elapsed());
334        this.metrics.total_poll_count.add(1);
335
336        // Begin idle duration.
337        this.idle_start.replace(Instant::now());
338
339        out
340    }
341}
342
343#[cfg(test)]
344mod test {
345    use dfir_lang::graph_ids::{GraphNodeId, GraphSubgraphId};
346    use slotmap::SlotMap;
347
348    use super::*;
349
350    #[test]
351    fn test_dfir_metrics_intervals() {
352        // Create slotmaps to generate valid keys.
353        let mut sg_map: SlotMap<GraphSubgraphId, ()> = SlotMap::with_key();
354        let mut node_map: SlotMap<GraphNodeId, ()> = SlotMap::with_key();
355        let sg_id = sg_map.insert(());
356        let handoff_id = node_map.insert(());
357
358        let mut metrics = DfirMetrics::default();
359        let sg_metrics = SubgraphMetrics::default();
360        sg_metrics.total_run_count.set(5);
361        sg_metrics.total_poll_count.set(10);
362        sg_metrics.total_idle_count.set(2);
363        sg_metrics
364            .total_poll_duration
365            .set(Duration::from_millis(500));
366        sg_metrics
367            .total_idle_duration
368            .set(Duration::from_millis(200));
369        metrics.subgraphs.insert(sg_id, sg_metrics);
370        let hoff_metrics = HandoffMetrics::default();
371        hoff_metrics.curr_items_count.set(3);
372        hoff_metrics.total_items_count.set(100);
373        metrics.handoffs.insert(handoff_id, hoff_metrics);
374        let metrics = Arc::new(metrics);
375
376        let mut intervals = DfirMetricsIntervals {
377            curr: Arc::clone(&metrics),
378            prev: None,
379        };
380
381        // First iteration - captures initial state
382        let first = intervals.take_interval();
383        let sg_metrics = &first.subgraphs[sg_id];
384        assert_eq!(sg_metrics.total_run_count(), 5);
385        let hoff_metrics = &first.handoffs[handoff_id];
386        assert_eq!(hoff_metrics.total_items_count(), 100);
387        assert_eq!(hoff_metrics.curr_items_count(), 3);
388
389        // Simulate more work being done.
390        let sg_metrics = &metrics.subgraphs[sg_id];
391        sg_metrics.total_run_count.set(12);
392        sg_metrics.total_poll_count.set(25);
393        sg_metrics.total_idle_count.set(7);
394        sg_metrics
395            .total_poll_duration
396            .set(Duration::from_millis(1200));
397        sg_metrics
398            .total_idle_duration
399            .set(Duration::from_millis(600));
400        let hoff_metrics = &metrics.handoffs[handoff_id];
401        hoff_metrics.total_items_count.set(250);
402        hoff_metrics.curr_items_count.set(10);
403
404        // Second iteration - should return the diff
405        let second = intervals.take_interval();
406        let sg_metrics = &second.subgraphs[sg_id];
407        assert_eq!(sg_metrics.total_run_count(), 7); // 12 - 5
408        assert_eq!(sg_metrics.total_poll_count(), 15); // 25 - 10
409        assert_eq!(sg_metrics.total_idle_count(), 5); // 7 - 2
410        //
411        let hoff_metrics = &second.handoffs[handoff_id];
412        // total_items_count should be diffed
413        assert_eq!(hoff_metrics.total_items_count(), 150); // 250 - 100
414        // curr_items_count should NOT be diffed (it's a current value, not cumulative)
415        assert_eq!(hoff_metrics.curr_items_count(), 10);
416    }
417}