dfir_rs/scheduled/
metrics.rs1use 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#[sealed]
28pub trait MetricsState: 'static {
29 type Handle;
31}
32
33#[sealed]
35impl MetricsState for DfirMetrics {
36 type Handle = Arc<DfirMetrics>;
37}
38
39#[sealed]
41impl MetricsState for () {
42 type Handle = ();
43}
44
45#[derive(Default, Clone)]
60#[non_exhaustive]
61pub struct DfirMetrics {
62 pub subgraphs: SecondaryMap<GraphSubgraphId, SubgraphMetrics>,
64 pub handoffs: SecondaryMap<GraphNodeId, HandoffMetrics>,
66}
67
68impl DfirMetrics {
69 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#[derive(Clone)]
93pub struct DfirMetricsIntervals {
94 pub(super) curr: Arc<DfirMetrics>,
96 pub(super) prev: Option<DfirMetrics>,
98}
99
100impl DfirMetricsIntervals {
101 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 pub fn all_metrics(&self) -> Arc<DfirMetrics> {
117 Arc::clone(&self.curr)
118 }
119}
120
121#[sealed]
126pub trait MetricCell: Default {
127 type Value: Copy;
129
130 fn get(&self) -> Self::Value;
132 fn set(&self, value: Self::Value);
134 fn add(&self, value: Self::Value);
136}
137
138#[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#[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
205macro_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] pub struct $struct_name {
222 $(
223 #[doc(hidden)] $(#[$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 pub struct HandoffMetrics {
257 #[diff(curr)]
259 curr_items_count: AtomicCount,
260
261 #[diff(total)]
263 total_items_count: AtomicCount,
264 }
265}
266
267define_metrics! {
268 pub struct SubgraphMetrics {
270 #[diff(total)]
272 total_run_count: AtomicCount,
273
274 #[diff(total)]
276 total_poll_duration: AtomicDuration,
277
278 #[diff(total)]
280 total_poll_count: AtomicCount,
281
282 #[diff(total)]
284 total_idle_duration: AtomicDuration,
285
286 #[diff(total)]
288 total_idle_count: AtomicCount,
289 }
290}
291
292pin_project! {
293 #[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 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 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 let poll_start = Instant::now();
330 let out = this.future.poll(cx);
331
332 this.metrics.total_poll_duration.add(poll_start.elapsed());
334 this.metrics.total_poll_count.add(1);
335
336 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 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 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 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 let second = intervals.take_interval();
406 let sg_metrics = &second.subgraphs[sg_id];
407 assert_eq!(sg_metrics.total_run_count(), 7); assert_eq!(sg_metrics.total_poll_count(), 15); assert_eq!(sg_metrics.total_idle_count(), 5); let hoff_metrics = &second.handoffs[handoff_id];
412 assert_eq!(hoff_metrics.total_items_count(), 150); assert_eq!(hoff_metrics.curr_items_count(), 10);
416 }
417}