Skip to main content

dfir_rs/scheduled/
context.rs

1//! Module for the inline DFIR runtime context and execution engine.
2//!
3//! Provides [`Context`] (the lightweight operator context) and
4//! [`Dfir`] (the dataflow execution wrapper).
5
6use std::future::Future;
7use std::marker::PhantomData;
8use std::pin::Pin;
9use std::sync::Arc;
10use std::sync::atomic::Ordering;
11use std::task::Wake;
12
13#[cfg(feature = "meta")]
14use dfir_lang::diagnostic::{Diagnostic, Diagnostics, SerdeSpan};
15#[cfg(feature = "meta")]
16use dfir_lang::graph::DfirGraph;
17
18use super::metrics::{DfirMetrics, DfirMetricsIntervals, MetricsState};
19use crate::scheduled::ticks::TickInstant;
20
21/// Coordinates waking between [`Context`] (inside the tick closure) and [`Dfir`]
22/// (the external runner). Shared via `Arc` between both.
23///
24/// When external data arrives (e.g., a tokio stream receives a message), the [`Context::waker`]
25/// fires, which sets `can_start_tick` and wakes the [`Dfir::run`](Dfir::run) task so it starts a new tick.
26/// Implements [`Wake`] directly so it can be used as a `Waker` without an extra wrapper.
27#[doc(hidden)]
28pub struct WakeState {
29    /// Set to `true` when external data arrives, signaling that a new tick should run.
30    /// Checked by [`Dfir::run_tick`](Dfir::run_tick) and [`Dfir::run_available`](Dfir::run_available).
31    can_start_tick: std::sync::atomic::AtomicBool,
32    /// Wakes the [`Dfir::run`](Dfir::run) task from its idle `poll_fn` sleep.
33    task_waker: futures::task::AtomicWaker,
34}
35
36impl Default for WakeState {
37    fn default() -> Self {
38        Self {
39            can_start_tick: std::sync::atomic::AtomicBool::new(false),
40            task_waker: futures::task::AtomicWaker::new(),
41        }
42    }
43}
44
45impl Wake for WakeState {
46    fn wake(self: Arc<Self>) {
47        self.wake_by_ref();
48    }
49
50    fn wake_by_ref(self: &Arc<Self>) {
51        self.can_start_tick.store(true, Ordering::Relaxed);
52        self.task_waker.wake();
53    }
54}
55
56/// A lightweight context for inline codegen that avoids the overhead of the full
57/// scheduled graph (no tokio channels, no scheduler queues, no loop machinery).
58///
59/// Exposes methods that operator-generated code calls on both
60/// `df` (for prologues: `request_task`) and
61/// `context` (for iterators: `current_tick`, `schedule_subgraph`, etc.).
62///
63/// # Metrics typestate
64///
65/// The `M` type parameter is a [`MetricsState`] typestate which statically records whether this
66/// context tracks runtime metrics:
67///
68/// - `Context<DfirMetrics>` (the default) is created via [`Context::new_with_metrics`] and holds
69///   a shared `Arc<DfirMetrics>` handle, accessible via [`Context::metrics`].
70/// - `Context<()>` is created via [`Context::new`] and holds no metrics state whatsoever. The
71///   `metrics()` accessor does not exist on it, so it is a compile error to try to read metrics
72///   from a context which never tracked them.
73pub struct Context<M: MetricsState = DfirMetrics> {
74    /// Counter for number of ticks run.
75    current_tick: TickInstant,
76    /// Coordinates waking between [`Context`] (inside the tick closure) and [`Dfir`]
77    /// (the external runner). Shared via `Arc` between both. Implements [`Wake`].
78    wake_state: Arc<WakeState>,
79    /// Live-updating DFIR runtime metrics via atomics (`Arc<DfirMetrics>`), or `()`
80    /// when metrics are not tracked.
81    metrics: M::Handle,
82    /// Tasks buffered via [`Self::request_task`], spawned via [`tokio::spawn`] by
83    /// [`Dfir::spawn_tasks`] once the runtime is running inside a tokio runtime.
84    ///
85    /// Futures are required to be `Send` so that `Context` (and therefore [`Dfir`]) can be moved
86    /// between threads before being run, and so that the tasks can be spawned onto any tokio
87    /// runtime (no `LocalSet` required).
88    #[cfg(feature = "tokio")]
89    tasks_to_spawn: Vec<Pin<Box<dyn Future<Output = ()> + Send + 'static>>>,
90}
91
92impl Context<()> {
93    /// Create a new inline context with a fresh wake state and **no** metrics tracking.
94    ///
95    /// The returned `Context<()>` statically contains no metrics state. Use
96    /// [`Context::new_with_metrics`] to create a `Context<DfirMetrics>` which tracks metrics.
97    pub fn new() -> Self {
98        Self::with_metrics_handle(())
99    }
100}
101
102impl Default for Context<()> {
103    fn default() -> Self {
104        Self::new()
105    }
106}
107
108impl Context<DfirMetrics> {
109    /// Create a new inline context with a fresh wake state and the given (pre-populated) metrics.
110    pub fn new_with_metrics(metrics: DfirMetrics) -> Self {
111        Self::with_metrics_handle(Arc::new(metrics))
112    }
113
114    /// Returns a reference to the runtime metrics.
115    pub fn metrics(&self) -> &Arc<DfirMetrics> {
116        &self.metrics
117    }
118}
119
120impl<M: MetricsState> Context<M> {
121    fn with_metrics_handle(metrics: M::Handle) -> Self {
122        Self {
123            current_tick: TickInstant::default(),
124            wake_state: Arc::default(),
125            metrics,
126            #[cfg(feature = "tokio")]
127            tasks_to_spawn: Vec::new(),
128        }
129    }
130
131    // --- Methods called as `df.xxx()` in operator prologues ---
132
133    /// Buffers an async task to be spawned later by `Dfir::spawn_tasks`.
134    ///
135    /// Tasks are deferred because `write_prologue` runs during graph construction,
136    /// which may occur before a tokio runtime is entered. Buffered tasks are
137    /// drained and spawned via [`tokio::spawn`] at the start of
138    /// [`Dfir::run_tick`]. Tasks requested after that point remain buffered until
139    /// the next call to [`Dfir::run_tick`].
140    ///
141    /// The future must be `Send` so that the `Context` remains `Send` and so the task can be
142    /// spawned onto any tokio runtime.
143    #[cfg(feature = "tokio")]
144    pub fn request_task<Fut>(&mut self, future: Fut)
145    where
146        Fut: Future<Output = ()> + Send + 'static,
147    {
148        self.tasks_to_spawn.push(Box::pin(future));
149    }
150
151    // --- Methods called as `context.xxx()` in operator iterators ---
152
153    /// Gets the current tick count.
154    pub fn current_tick(&self) -> TickInstant {
155        self.current_tick
156    }
157
158    /// Signals that external data has arrived and a new tick should be started.
159    pub fn schedule_subgraph(&self, is_external: bool) {
160        if is_external {
161            self.wake_state.wake_by_ref();
162        }
163    }
164
165    /// Returns a waker that signals external data has arrived.
166    pub fn waker(&self) -> std::task::Waker {
167        std::task::Waker::from(self.wake_state.clone())
168    }
169
170    /// Increments the tick counter.
171    /// Called by the generated tick closure at the end of each tick.
172    #[doc(hidden)]
173    pub fn __end_tick(&mut self) {
174        self.current_tick += crate::scheduled::ticks::TickDuration::SINGLE_TICK;
175    }
176}
177
178/// An executable DFIR dataflow, as created by
179/// [`dfir_syntax!`](crate::dfir_syntax). Provides the [`Self::run`],
180/// [`Self::run_available`], and [`Self::run_tick`] family of methods to
181/// execute the dataflow.
182///
183/// # Design
184///
185/// The inline codegen generates an `async move |df: &mut Context<M>|` closure that captures
186/// dataflow-specific state (handoff buffers, source iterators) and receives the [`Context`]
187/// (tick counter, metrics) by reference each tick. `Dfir` owns both the
188/// closure and the context, and coordinates tick lifecycle and idle/wake behavior.
189///
190/// We use a single opaque closure rather than generating a bespoke struct per dataflow because:
191/// - The closure naturally captures exactly the state it needs with correct lifetimes
192/// - No codegen needed for struct definitions, field accessors, or initialization
193/// - Rust's async closure machinery handles the complex state machine (suspend/resume across
194///   `.await` points) that would be very difficult to replicate in a generated struct
195///
196/// The `Tick` type parameter is bounded by [`TickClosure`] (not `AsyncFnMut` directly) so
197/// that the runners can be split by what the closure supports ([`TickClosureSync`] /
198/// [`TickClosureAsync`]) and to support type erasure ([`TickClosureErasedSync`],
199/// [`TickClosureErasedAsync`], [`TickClosureErased`]) for storing graphs of different concrete
200/// types in one place (a struct field, or the sim runtime's `Vec` of locations). The concrete
201/// (non-erased) path used by trybuild and embedded has zero overhead.
202///
203/// # Metrics
204///
205/// Whether this `Dfir` tracks runtime metrics is determined statically by
206/// [`TickClosure::Metrics`] (see [`MetricsState`]). The [`Self::metrics`] and
207/// [`Self::metrics_intervals`] accessors only exist when `Tick::Metrics = DfirMetrics`. When
208/// returning a `Dfir` from a function via `impl TickClosureBoth`, use
209/// `Dfir<impl TickClosureBoth<Metrics = DfirMetrics>>` if callers need to access the metrics.
210pub struct Dfir<Tick: TickClosure> {
211    /// Closure which runs a single tick when called.
212    tick_closure: Tick,
213    /// Coordinates waking between [`Context`] (inside the tick closure) and [`Dfir`]
214    /// (the external runner). Shared via `Arc` between both. Implements [`Wake`].
215    wake_state: Arc<WakeState>,
216    /// The inline context, owned by `Dfir` and passed to the tick closure by reference.
217    context: Context<Tick::Metrics>,
218    /// See [`Self::meta_graph()`].
219    ///
220    /// Stored as the serialized JSON string rather than a deserialized [`DfirGraph`], since
221    /// `DfirGraph` contains `proc_macro2` types which are `!Send`. Deserialized on demand.
222    #[cfg(feature = "meta")]
223    meta_graph_json: Option<String>,
224    /// See [`Self::diagnostics()`].
225    #[cfg(feature = "meta")]
226    diagnostics: Option<Vec<Diagnostic<SerdeSpan>>>,
227}
228
229/// Base trait of the tick closure traits: names the [`MetricsState`] typestate of the context the
230/// closure expects, so that [`Dfir<Tick>`] can be parameterized by the closure alone.
231///
232/// On its own, this bound gives access to a [`Dfir`]'s metadata ([`Dfir::meta_graph`],
233/// [`Dfir::metrics`], ...) but not to any runner. The tick closure traits form a small hierarchy;
234/// bound on the one that matches what you need to do with the graph:
235///
236/// - [`TickClosure`] (this trait): inspect only.
237/// - [`TickClosureSync`]: run a tick synchronously ([`Dfir::run_tick_sync`],
238///   [`Dfir::run_available_sync`]).
239/// - [`TickClosureAsync`]: run a tick as a future ([`Dfir::run_tick`],
240///   [`Dfir::run_available`], [`Dfir::run`]).
241/// - [`TickClosureBoth`]: both. Implemented automatically for any type implementing the two above.
242///   This is what functions returning a concrete generated graph promise:
243///   `Dfir<impl TickClosureBoth<Metrics = ..>>`.
244///
245/// Concrete closures ([`TickClosureFn`]) implement all of them. The type-erased wrappers implement
246/// only what their vtable carries, so that erasing a graph for one kind of runner does not
247/// instantiate the code for the other: [`TickClosureErasedSync`] is `Sync`-only,
248/// [`TickClosureErasedAsync`] is `Async`-only, and [`TickClosureErased`] is both.
249pub trait TickClosure {
250    /// Whether the context passed to this closure tracks metrics. See [`MetricsState`].
251    type Metrics: MetricsState;
252}
253
254/// A tick closure that can run a tick synchronously. See [`TickClosure`] for the hierarchy.
255///
256/// The `&mut Context` parameter is owned by [`Dfir`] and lent to the closure each tick, avoiding
257/// shared-ownership overhead for the context.
258pub trait TickClosureSync: TickClosure {
259    /// Run one tick to completion synchronously. Returns `true` if any subgraph received input
260    /// data.
261    ///
262    /// For closures that are async underneath (e.g. [`TickClosureFn`]), this polls the tick's
263    /// future exactly once on the stack and panics if it yields.
264    #[doc(hidden)]
265    fn call_tick_sync(&mut self, ctx: &mut Context<Self::Metrics>) -> bool;
266}
267
268/// A tick closure that can run a tick as a future. See [`TickClosure`] for the hierarchy.
269///
270/// The `&mut Context` parameter is owned by [`Dfir`] and lent to the closure each tick, avoiding
271/// shared-ownership overhead for the context.
272pub trait TickClosureAsync: TickClosure {
273    /// Call the tick closure. Returns `true` if any subgraph received input data.
274    #[doc(hidden)]
275    fn call_tick<'a>(
276        &'a mut self,
277        ctx: &'a mut Context<Self::Metrics>,
278    ) -> impl Future<Output = bool> + 'a;
279}
280
281/// A tick closure that supports both the sync and the async runners. Implemented automatically
282/// for every type implementing both [`TickClosureSync`] and [`TickClosureAsync`]; see
283/// [`TickClosure`] for the hierarchy.
284///
285/// This is what concrete generated graphs are: `Dfir<impl TickClosureBoth<Metrics = ..>>`.
286pub trait TickClosureBoth: TickClosureSync + TickClosureAsync {}
287
288impl<T: TickClosureSync + TickClosureAsync + ?Sized> TickClosureBoth for T {}
289
290/// Polls `fut` exactly once on the stack, panicking if it yields. Shared by every
291/// [`TickClosureSync`] implementation that is async underneath.
292fn poll_tick_sync(fut: impl Future<Output = bool>) -> bool {
293    let mut fut = std::pin::pin!(fut);
294    let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
295    match fut.as_mut().poll(&mut cx) {
296        std::task::Poll::Ready(result) => result,
297        std::task::Poll::Pending => {
298            panic!("Dfir::run_tick_sync: tick yielded asynchronously.")
299        }
300    }
301}
302
303/// Wraps an `AsyncFnMut(&mut Context<M>) -> bool` closure as a [`TickClosureBoth`].
304///
305/// A blanket `impl<M, F: AsyncFnMut(&mut Context<M>)> TickClosureAsync for F` is not allowed
306/// since `M` would only be constrained via the `AsyncFnMut` bound (E0207), so the generated code
307/// wraps the tick closure in this newtype which carries `M` explicitly.
308#[doc(hidden)]
309pub struct TickClosureFn<M, F> {
310    func: F,
311    _metrics: PhantomData<fn() -> M>,
312}
313
314impl<M, F> TickClosureFn<M, F>
315where
316    M: MetricsState,
317    F: for<'a> AsyncFnMut(&'a mut Context<M>) -> bool,
318{
319    /// Wrap the given async tick closure.
320    pub fn new(func: F) -> Self {
321        Self {
322            func,
323            _metrics: PhantomData,
324        }
325    }
326}
327
328impl<M, F> TickClosure for TickClosureFn<M, F>
329where
330    M: MetricsState,
331    F: for<'a> AsyncFnMut(&'a mut Context<M>) -> bool,
332{
333    type Metrics = M;
334}
335
336impl<M, F> TickClosureAsync for TickClosureFn<M, F>
337where
338    M: MetricsState,
339    F: for<'a> AsyncFnMut(&'a mut Context<M>) -> bool,
340{
341    fn call_tick<'a>(&'a mut self, ctx: &'a mut Context<M>) -> impl Future<Output = bool> + 'a {
342        (self.func)(ctx)
343    }
344}
345
346impl<M, F> TickClosureSync for TickClosureFn<M, F>
347where
348    M: MetricsState,
349    F: for<'a> AsyncFnMut(&'a mut Context<M>) -> bool,
350{
351    fn call_tick_sync(&mut self, ctx: &mut Context<M>) -> bool {
352        poll_tick_sync((self.func)(ctx))
353    }
354}
355
356/// No-op `TickClosureBoth`. Used by `dfir_syntax!` as a stand-in when codegen fails, so its
357/// `Metrics` matches the macro's default (metrics tracking enabled).
358#[doc(hidden)]
359pub struct NullTickClosure;
360
361impl TickClosure for NullTickClosure {
362    type Metrics = DfirMetrics;
363}
364
365impl TickClosureAsync for NullTickClosure {
366    fn call_tick<'a>(
367        &'a mut self,
368        _ctx: &'a mut Context<DfirMetrics>,
369    ) -> impl Future<Output = bool> + 'a {
370        std::future::ready(false)
371    }
372}
373
374impl TickClosureSync for NullTickClosure {
375    fn call_tick_sync(&mut self, _ctx: &mut Context<DfirMetrics>) -> bool {
376        false
377    }
378}
379
380// --- Type erasure ---
381//
382// Each erased wrapper boxes a private object-safe trait whose vtable carries exactly the entry
383// points that wrapper supports. [`TickClosureAsync::call_tick`] returns `impl Future` (not
384// object-safe), so the async vtable entry returns `Pin<Box<dyn Future + '_>>` instead: the future
385// borrows the trait object which owns the closure, and has nowhere else to live across `.await`
386// points. The sync vtable entry needs no allocation: the concrete side pins and polls the future
387// on its own stack.
388
389/// Type-erased [`TickClosureSync`] (only). Created via [`Dfir::into_erased_sync`].
390///
391/// Its vtable carries only `call_tick_sync`, so erasing a graph this way never instantiates the
392/// boxed-future async path, and running it allocates nothing per tick.
393#[doc(hidden)]
394pub struct TickClosureErasedSync<M: MetricsState = DfirMetrics>(
395    Box<dyn TickClosureErasedSyncInner<M>>,
396);
397
398trait TickClosureErasedSyncInner<M: MetricsState> {
399    fn call_tick_sync(&mut self, ctx: &mut Context<M>) -> bool;
400}
401
402impl<Tick: TickClosureSync> TickClosureErasedSyncInner<Tick::Metrics> for Tick {
403    fn call_tick_sync(&mut self, ctx: &mut Context<Tick::Metrics>) -> bool {
404        TickClosureSync::call_tick_sync(self, ctx)
405    }
406}
407
408impl<M: MetricsState> TickClosure for TickClosureErasedSync<M> {
409    type Metrics = M;
410}
411
412impl<M: MetricsState> TickClosureSync for TickClosureErasedSync<M> {
413    fn call_tick_sync(&mut self, ctx: &mut Context<M>) -> bool {
414        self.0.call_tick_sync(ctx)
415    }
416}
417
418/// Type-erased [`TickClosureAsync`] (only). Created via [`Dfir::into_erased_async`].
419///
420/// Its vtable carries only `call_tick`, which boxes the tick's future (one allocation per tick).
421#[doc(hidden)]
422pub struct TickClosureErasedAsync<M: MetricsState = DfirMetrics>(
423    Box<dyn TickClosureErasedAsyncInner<M>>,
424);
425
426trait TickClosureErasedAsyncInner<M: MetricsState> {
427    fn call_tick<'a>(
428        &'a mut self,
429        ctx: &'a mut Context<M>,
430    ) -> Pin<Box<dyn Future<Output = bool> + 'a>>;
431}
432
433impl<Tick: TickClosureAsync> TickClosureErasedAsyncInner<Tick::Metrics> for Tick {
434    fn call_tick<'a>(
435        &'a mut self,
436        ctx: &'a mut Context<Tick::Metrics>,
437    ) -> Pin<Box<dyn Future<Output = bool> + 'a>> {
438        Box::pin(TickClosureAsync::call_tick(self, ctx))
439    }
440}
441
442impl<M: MetricsState> TickClosure for TickClosureErasedAsync<M> {
443    type Metrics = M;
444}
445
446impl<M: MetricsState> TickClosureAsync for TickClosureErasedAsync<M> {
447    fn call_tick<'a>(&'a mut self, ctx: &'a mut Context<M>) -> impl Future<Output = bool> + 'a {
448        self.0.call_tick(ctx)
449    }
450}
451
452/// Type-erased [`TickClosureBoth`] (both sync and async). Created via [`Dfir::into_erased`].
453///
454/// Its vtable carries both `call_tick_sync` (allocation-free) and `call_tick` (boxes the future).
455/// Prefer [`TickClosureErasedSync`] or [`TickClosureErasedAsync`] when only one kind of runner is
456/// used, so the other path is not instantiated.
457#[doc(hidden)]
458pub struct TickClosureErased<M: MetricsState = DfirMetrics>(Box<dyn TickClosureErasedInner<M>>);
459
460trait TickClosureErasedInner<M: MetricsState>:
461    TickClosureErasedSyncInner<M> + TickClosureErasedAsyncInner<M>
462{
463}
464
465impl<Tick: TickClosureBoth> TickClosureErasedInner<Tick::Metrics> for Tick {}
466
467impl<M: MetricsState> TickClosure for TickClosureErased<M> {
468    type Metrics = M;
469}
470
471impl<M: MetricsState> TickClosureSync for TickClosureErased<M> {
472    fn call_tick_sync(&mut self, ctx: &mut Context<M>) -> bool {
473        TickClosureErasedSyncInner::call_tick_sync(&mut *self.0, ctx)
474    }
475}
476
477impl<M: MetricsState> TickClosureAsync for TickClosureErased<M> {
478    fn call_tick<'a>(&'a mut self, ctx: &'a mut Context<M>) -> impl Future<Output = bool> + 'a {
479        TickClosureErasedAsyncInner::call_tick(&mut *self.0, ctx)
480    }
481}
482
483/// A type-erased [`Dfir`] that supports only the sync runners ([`Dfir::run_tick_sync`],
484/// [`Dfir::run_available_sync`]). Created via [`Dfir::into_erased_sync`].
485///
486/// This is the type to store a generated graph as when driving it synchronously, e.g. from an
487/// embedding application's own event loop: it is nameable, allocation-free per tick, and its
488/// vtable carries nothing for the async path.
489///
490/// `M` is the [`MetricsState`] of the erased dataflow: `DfirMetrics` (the default) if metrics
491/// are tracked, or `()` if not.
492pub type DfirErasedSync<M = DfirMetrics> = Dfir<TickClosureErasedSync<M>>;
493
494/// A type-erased [`Dfir`] that supports only the async runners ([`Dfir::run_tick`],
495/// [`Dfir::run_available`], [`Dfir::run`]). Created via [`Dfir::into_erased_async`].
496///
497/// `M` is the [`MetricsState`] of the erased dataflow: `DfirMetrics` (the default) if metrics
498/// are tracked, or `()` if not.
499pub type DfirErasedAsync<M = DfirMetrics> = Dfir<TickClosureErasedAsync<M>>;
500
501/// A type-erased [`Dfir`] that supports both the sync and the async runners. Created via
502/// [`Dfir::into_erased`]. Prefer [`DfirErasedSync`] or [`DfirErasedAsync`] when only one is
503/// needed.
504///
505/// `M` is the [`MetricsState`] of the erased dataflow: `DfirMetrics` (the default) if metrics
506/// are tracked, or `()` if not.
507pub type DfirErased<M = DfirMetrics> = Dfir<TickClosureErased<M>>;
508
509impl<Tick: TickClosure> Dfir<Tick> {
510    /// Create a new `Dfir` from a tick closure, inline context,
511    /// and meta graph / diagnostics JSON strings.
512    #[doc(hidden)]
513    pub fn new(
514        tick_closure: Tick,
515        context: Context<Tick::Metrics>,
516        meta_graph_json: Option<&str>,
517        diagnostics_json: Option<&str>,
518    ) -> Self {
519        #[cfg(not(feature = "meta"))]
520        let _ = (meta_graph_json, diagnostics_json);
521        Self {
522            tick_closure,
523            wake_state: context.wake_state.clone(),
524            context,
525            #[cfg(feature = "meta")]
526            meta_graph_json: meta_graph_json.map(str::to_owned),
527            #[cfg(feature = "meta")]
528            diagnostics: diagnostics_json.map(|json| {
529                serde_json::from_str(json).expect("Failed to deserialize diagnostics.")
530            }),
531        }
532    }
533
534    /// Returns the meta graph, if set.
535    ///
536    /// The graph is deserialized from its JSON representation on each call, so callers which need
537    /// it multiple times should store the result.
538    #[cfg(feature = "meta")]
539    #[cfg_attr(docsrs, doc(cfg(feature = "meta")))]
540    pub fn meta_graph(&self) -> Option<DfirGraph> {
541        self.meta_graph_json.as_deref().map(|json| {
542            let mut meta_graph: DfirGraph =
543                serde_json::from_str(json).expect("Failed to deserialize graph.");
544            let mut op_inst_diagnostics = Diagnostics::new();
545            meta_graph.insert_node_op_insts_all(&mut op_inst_diagnostics);
546            assert!(
547                op_inst_diagnostics.is_empty(),
548                "Expected no diagnostics, got: {:#?}",
549                op_inst_diagnostics
550            );
551            meta_graph
552        })
553    }
554
555    /// Returns any diagnostics generated by the surface syntax macro.
556    #[cfg(feature = "meta")]
557    #[cfg_attr(docsrs, doc(cfg(feature = "meta")))]
558    pub fn diagnostics(&self) -> Option<&[Diagnostic<SerdeSpan>]> {
559        self.diagnostics.as_deref()
560    }
561
562    /// Gets the current tick (local time) count.
563    pub fn current_tick(&self) -> TickInstant {
564        self.context.current_tick()
565    }
566}
567
568/// Metrics accessors, only available when metrics tracking is enabled (`Tick::Metrics = DfirMetrics`).
569impl<Tick: TickClosure<Metrics = DfirMetrics>> Dfir<Tick> {
570    /// Returns a reference-counted handle to the continually-updated runtime metrics for this DFIR instance.
571    ///
572    /// Only available when metrics tracking is enabled, see [`MetricsState`].
573    pub fn metrics(&self) -> Arc<DfirMetrics> {
574        Arc::clone(self.context.metrics())
575    }
576
577    /// Returns a [`DfirMetricsIntervals`] handle where each call to
578    /// [`DfirMetricsIntervals::take_interval`] ends the current interval and returns its metrics.
579    ///
580    /// The first call to `take_interval` returns metrics since this DFIR instance was created. Each subsequent call to
581    /// `take_interval` returns metrics since the previous call.
582    ///
583    /// Cloning the handle "forks" it from the original, as afterwards each interval may return different metrics
584    /// depending on when exactly `take_interval` is called.
585    ///
586    /// Only available when metrics tracking is enabled, see [`MetricsState`].
587    pub fn metrics_intervals(&self) -> DfirMetricsIntervals {
588        DfirMetricsIntervals {
589            curr: self.metrics(),
590            prev: None,
591        }
592    }
593}
594
595impl<Tick: TickClosure> Dfir<Tick> {
596    /// Spawns all tasks buffered via [`Context::request_task`] onto the current tokio runtime.
597    ///
598    /// This drains the buffer, so subsequent calls are no-ops until new tasks are requested.
599    ///
600    /// # Panics
601    ///
602    /// Panics if there are buffered tasks and this is called outside of a tokio runtime.
603    #[cfg(feature = "tokio")]
604    fn spawn_tasks(&mut self) {
605        for task in self.context.tasks_to_spawn.drain(..) {
606            tokio::spawn(task);
607        }
608    }
609
610    /// Bookkeeping before the tick closure runs. Returns whether external data had arrived.
611    fn begin_tick(&mut self) -> bool {
612        #[cfg(feature = "tokio")]
613        self.spawn_tasks();
614        self.wake_state
615            .can_start_tick
616            .swap(false, Ordering::Relaxed)
617    }
618
619    /// Bookkeeping after the tick closure ran. Returns whether work was done.
620    fn end_tick(&self, had_external: bool, tick_had_work: bool) -> bool {
621        had_external || tick_had_work || self.wake_state.can_start_tick.load(Ordering::Relaxed)
622    }
623
624    /// Replaces the tick closure with `f(tick_closure)`, keeping the rest of the dataflow (its
625    /// context, wake state and meta graph). Lets a runner wrap every tick, e.g. to catch panics
626    /// raised by the dataflow at the boundary of the code that compiled it.
627    #[doc(hidden)]
628    pub fn map_tick_closure<Tick2: TickClosure<Metrics = Tick::Metrics>>(
629        self,
630        f: impl FnOnce(Tick) -> Tick2,
631    ) -> Dfir<Tick2> {
632        Dfir {
633            tick_closure: f(self.tick_closure),
634            wake_state: self.wake_state,
635            context: self.context,
636            #[cfg(feature = "meta")]
637            meta_graph_json: self.meta_graph_json,
638            #[cfg(feature = "meta")]
639            diagnostics: self.diagnostics,
640        }
641    }
642}
643
644/// The async runners. Available when the tick closure is [`TickClosureAsync`].
645impl<Tick: TickClosureAsync> Dfir<Tick> {
646    /// Run a single tick. Returns `true` if any subgraph received input data.
647    ///
648    /// Checks both handoff buffers (via `work_done` flag set in generated recv port code)
649    /// and external events (via `can_start_tick` set by `waker`/`schedule_subgraph`).
650    pub async fn run_tick(&mut self) -> bool {
651        let had_external = self.begin_tick();
652        let tick_had_work = self.tick_closure.call_tick(&mut self.context).await;
653        self.end_tick(had_external, tick_had_work)
654    }
655
656    /// Run ticks as long as work is available, then return.
657    #[cfg(feature = "tokio")]
658    pub async fn run_available(&mut self) {
659        // Always run at least one tick.
660        self.wake_state
661            .can_start_tick
662            .store(false, Ordering::Relaxed);
663        loop {
664            self.run_tick().await;
665            let can_start_tick = self
666                .wake_state
667                .can_start_tick
668                .swap(false, Ordering::Relaxed);
669            if !can_start_tick {
670                break;
671            }
672            // Yield between each tick to receive more events.
673            tokio::task::yield_now().await;
674        }
675    }
676
677    /// Run forever, processing ticks when work is available and yielding when idle.
678    #[cfg(feature = "tokio")]
679    pub async fn run(&mut self) -> crate::Never {
680        loop {
681            self.run_available().await;
682            // Wait for an external event to wake us.
683            std::future::poll_fn(|cx| {
684                // Register waker first to avoid race: if an event fires between
685                // the check and the register, the waker is already in place.
686                self.wake_state.task_waker.register(cx.waker());
687                if self.wake_state.can_start_tick.load(Ordering::Relaxed) {
688                    std::task::Poll::Ready(())
689                } else {
690                    std::task::Poll::Pending
691                }
692            })
693            .await;
694        }
695    }
696}
697
698/// The sync runners. Available when the tick closure is [`TickClosureSync`].
699impl<Tick: TickClosureSync> Dfir<Tick> {
700    /// Run a single tick synchronously. Panics if the tick yields (async suspension).
701    /// Returns `true` if work was done (see [`Self::run_tick`]).
702    ///
703    /// Goes through [`TickClosureSync::call_tick_sync`], which stays allocation-free even for the
704    /// type-erased [`DfirErasedSync`] / [`DfirErased`].
705    pub fn run_tick_sync(&mut self) -> bool {
706        let had_external = self.begin_tick();
707        let tick_had_work = self.tick_closure.call_tick_sync(&mut self.context);
708        self.end_tick(had_external, tick_had_work)
709    }
710
711    /// [`Self::run_available`] but panics if any tick yields asynchronously.
712    pub fn run_available_sync(&mut self) {
713        self.wake_state
714            .can_start_tick
715            .store(false, Ordering::Relaxed);
716        loop {
717            self.run_tick_sync();
718            let can_start_tick = self
719                .wake_state
720                .can_start_tick
721                .swap(false, Ordering::Relaxed);
722            if !can_start_tick {
723                break;
724            }
725        }
726    }
727}
728
729/// Type erasure. Each option keeps the [`MetricsState`] typestate and gives the graph a nameable
730/// type, so it can be stored in a struct field or a heterogeneous collection. They differ in which
731/// runners the result supports and, accordingly, in what its vtable carries; see
732/// [`TickClosure`].
733impl<Tick: TickClosure + 'static> Dfir<Tick> {
734    /// Type-erase for the sync runners only: the result is [`DfirErasedSync`].
735    ///
736    /// Allocation-free per tick. Use this to store a graph that is driven synchronously, e.g.
737    /// from an embedding application's own event loop.
738    pub fn into_erased_sync(self) -> DfirErasedSync<Tick::Metrics>
739    where
740        Tick: TickClosureSync,
741    {
742        self.map_tick_closure(|tick| TickClosureErasedSync(Box::new(tick)))
743    }
744
745    /// Type-erase for the async runners only: the result is [`DfirErasedAsync`].
746    ///
747    /// Boxes the tick's future, one allocation per tick. Use this for graphs driven by
748    /// [`Dfir::run_tick`] / [`Dfir::run_available`] / [`Dfir::run`], e.g. the sim runtime.
749    pub fn into_erased_async(self) -> DfirErasedAsync<Tick::Metrics>
750    where
751        Tick: TickClosureAsync,
752    {
753        self.map_tick_closure(|tick| TickClosureErasedAsync(Box::new(tick)))
754    }
755
756    /// Type-erase keeping both the sync and the async runners: the result is [`DfirErased`].
757    ///
758    /// Prefer [`Self::into_erased_sync`] or [`Self::into_erased_async`] when only one kind of
759    /// runner is used, so the other path is not instantiated.
760    pub fn into_erased(self) -> DfirErased<Tick::Metrics>
761    where
762        Tick: TickClosureBoth,
763    {
764        self.map_tick_closure(|tick| TickClosureErased(Box::new(tick)))
765    }
766}
767
768#[cfg(test)]
769mod tests {
770    use std::future::ready;
771
772    use static_assertions::assert_impl_all;
773
774    use super::{Context, Dfir, NullTickClosure, TickClosure, TickClosureAsync, TickClosureSync};
775    use crate::scheduled::metrics::{
776        AtomicCount, AtomicDuration, DfirMetrics, DfirMetricsIntervals,
777    };
778
779    struct SendTick;
780
781    impl TickClosure for SendTick {
782        type Metrics = ();
783    }
784
785    impl TickClosureAsync for SendTick {
786        fn call_tick<'a>(
787            &'a mut self,
788            _ctx: &'a mut Context<()>,
789        ) -> impl Future<Output = bool> + 'a {
790            ready(false)
791        }
792    }
793
794    impl TickClosureSync for SendTick {
795        fn call_tick_sync(&mut self, _ctx: &mut Context<()>) -> bool {
796            false
797        }
798    }
799
800    // Without metrics tracking.
801    assert_impl_all!(Context<()>: Send);
802    assert_impl_all!(Dfir<SendTick>: Send);
803
804    // With metrics tracking (`NullTickClosure` has `Metrics = DfirMetrics`).
805    assert_impl_all!(AtomicCount: Send, Sync);
806    assert_impl_all!(AtomicDuration: Send, Sync);
807    assert_impl_all!(DfirMetrics: Send, Sync);
808    assert_impl_all!(DfirMetricsIntervals: Send);
809    assert_impl_all!(Context<DfirMetrics>: Send);
810    assert_impl_all!(Dfir<NullTickClosure>: Send);
811}