Skip to main content

astrs_node_api/events/
mod.rs

1//! [`Event`] and [`EventStream`] — what a node's loop reads (blueprint §9.1).
2//!
3//! ```no_run
4//! # use astrs_node_api::prelude::*;
5//! # fn run(events: &mut EventStream) {
6//! while let Some(event) = events.recv() {
7//!     match event {
8//!         Event::Input { id, data, meta } => { let _ = (id, data, meta); }
9//!         Event::Stop(_) => break,
10//!         _ => {}
11//!     }
12//! }
13//! # }
14//! ```
15//!
16//! # Two lanes, one stream
17//!
18//! Events reach the stream on one of two paths, and the difference is
19//! observable (§11.3):
20//!
21//! | Lane | Events | Behaviour |
22//! |---|---|---|
23//! | **Control** | `Stop`, `Reload`, `AllInputsClosed`, `NodeFailed`, `Restarted`, `ParamUpdate`, `ParamDeleted`, `ExtDropped`, `Error`, merged external events | Unbounded FIFO, delivered **before** any data |
24//! | **Data** | `Input`, `InputClosed`, `InputRecovered` | Per-input bounded queues under the manifest's `queue_size`/`queue_policy`, round-robin across inputs |
25//!
26//! That is why a `Stop` never waits behind a backlog of camera frames, and
27//! why an `InputClosed` *does* wait behind that input's own queued frames —
28//! it has to, or a node would see "this input is finished" before the frames
29//! that came first.
30//!
31//! # Fusing
32//!
33//! After [`Event::Stop`] the stream fuses: it is delivered once, and every
34//! later `recv` returns `None` (§9.1). A node that ignores `Stop` and keeps
35//! looping therefore terminates rather than spinning.
36//!
37//! # Queue policy is applied *here*
38//!
39//! The daemon does not decide what a node drops. Each input owns an
40//! [`astrs_scheduler::InputQueue`] on the node side, so `queue_size: 1` means
41//! "the node always sees the newest frame" no matter how the daemon batched
42//! them, and eviction immunity (§11.2) protects correlated messages from ever
43//! being the one dropped.
44
45pub mod queued;
46pub mod source;
47pub mod stream;
48
49use astrs_wire::messages::control::types::ParamScope;
50use astrs_wire::metadata::Parameter;
51use astrs_wire::{
52    DataId, ExtensionKey, Metadata, NodeExitCause, NodeId, OperatorId, ParamKey, PortRef,
53    RouteCloseReason, StopCause,
54};
55
56use crate::payload::Payload;
57
58pub use queued::QueuedEvent;
59pub use source::EventSource;
60pub use stream::{EventStream, Stream};
61
62/// One thing that happened to this node.
63///
64/// [`Event::Input`] carries exactly the three fields blueprint §9.1
65/// destructures — `{ id, data, meta }` — so the example there compiles
66/// verbatim. The producer port behind an input is a property of the node's
67/// wiring rather than of the message, and is available from
68/// [`crate::Node::input_source`].
69#[derive(Debug)]
70#[non_exhaustive]
71pub enum Event {
72    /// A message arrived on one of the node's inputs.
73    Input {
74        /// The input it arrived on.
75        id: DataId,
76        /// The metadata beside it, with AstRS-internal keys already
77        /// stripped (§6.1).
78        meta: Metadata,
79        /// The payload — decoded lazily, and zero-copy when the route was
80        /// upgraded (§6.3).
81        data: Payload,
82    },
83    /// An input will receive nothing further.
84    InputClosed {
85        /// The input that closed.
86        id: DataId,
87        /// The producer port that stopped.
88        source: PortRef,
89        /// Why it closed.
90        reason: RouteCloseReason,
91    },
92    /// A closed input is live again, because its producer restarted (§12).
93    InputRecovered {
94        /// The input that recovered.
95        id: DataId,
96        /// The producer port that came back.
97        source: PortRef,
98        /// The producer's new incarnation.
99        generation: u64,
100    },
101    /// Finish up and exit. The stream fuses after this.
102    Stop(StopCause),
103    /// Reload the node's code, or one operator inside it (§9.3).
104    Reload {
105        /// The operator to reload, or `None` for the whole node.
106        operator: Option<OperatorId>,
107        /// The artefact to load, when it moved.
108        path: Option<String>,
109    },
110    /// Every input of this node has closed.
111    AllInputsClosed,
112    /// A parameter this node reads was written (§17 `param set`).
113    ParamUpdate {
114        /// The scope it was written in.
115        scope: ParamScope,
116        /// The key.
117        key: ParamKey,
118        /// The new value.
119        value: Parameter,
120    },
121    /// A parameter this node reads was deleted.
122    ParamDeleted {
123        /// The scope it was deleted from.
124        scope: ParamScope,
125        /// The key.
126        key: ParamKey,
127    },
128    /// A peer node failed (§12).
129    NodeFailed {
130        /// The node that failed.
131        peer: NodeId,
132        /// How it failed.
133        cause: NodeExitCause,
134    },
135    /// A peer node was restarted under its restart policy (§12).
136    Restarted {
137        /// The node that came back.
138        peer: NodeId,
139        /// Its new incarnation.
140        generation: u64,
141    },
142    /// An extension entry this node owned was dropped.
143    ExtDropped {
144        /// The key that went away.
145        key: ExtensionKey,
146        /// Why.
147        reason: String,
148    },
149    /// The session hit a condition the node should know about but that does
150    /// not end it — a queue overflow, an undecodable frame, a route the node
151    /// could not map.
152    Error(String),
153}
154
155impl Event {
156    /// The input this event concerns, when it concerns one.
157    #[must_use]
158    pub const fn input(&self) -> Option<&DataId> {
159        match self {
160            Self::Input { id, .. }
161            | Self::InputClosed { id, .. }
162            | Self::InputRecovered { id, .. } => Some(id),
163            _ => None,
164        }
165    }
166
167    /// Whether this event delivers data.
168    #[must_use]
169    pub const fn is_input(&self) -> bool {
170        matches!(self, Self::Input { .. })
171    }
172
173    /// Whether this event fuses the stream.
174    #[must_use]
175    pub const fn is_stop(&self) -> bool {
176        matches!(self, Self::Stop(_))
177    }
178
179    /// Whether this event travels on the control lane (§11.3).
180    #[must_use]
181    pub const fn is_control(&self) -> bool {
182        !matches!(
183            self,
184            Self::Input { .. } | Self::InputClosed { .. } | Self::InputRecovered { .. }
185        )
186    }
187
188    /// Whether this event reports a fault rather than normal progress.
189    #[must_use]
190    pub fn is_fault(&self) -> bool {
191        match self {
192            Self::NodeFailed { .. } | Self::Error(_) => true,
193            Self::InputClosed { reason, .. } => !reason.is_expected(),
194            _ => false,
195        }
196    }
197
198    /// The metadata this event carries, when it carries any.
199    #[must_use]
200    pub const fn metadata(&self) -> Option<&Metadata> {
201        match self {
202            Self::Input { meta, .. } => Some(meta),
203            _ => None,
204        }
205    }
206
207    /// The payload this event carries, when it carries one.
208    #[must_use]
209    pub const fn payload(&self) -> Option<&Payload> {
210        match self {
211            Self::Input { data, .. } => Some(data),
212            _ => None,
213        }
214    }
215
216    /// Consumes the event and returns its payload and metadata, if it is an
217    /// input.
218    #[must_use]
219    pub fn into_input(self) -> Option<(DataId, Metadata, Payload)> {
220        match self {
221            Self::Input { id, meta, data } => Some((id, meta, data)),
222            _ => None,
223        }
224    }
225
226    /// A short, stable slug for metrics labels and structured logs.
227    #[must_use]
228    pub const fn kind_name(&self) -> &'static str {
229        match self {
230            Self::Input { .. } => "input",
231            Self::InputClosed { .. } => "input_closed",
232            Self::InputRecovered { .. } => "input_recovered",
233            Self::Stop(_) => "stop",
234            Self::Reload { .. } => "reload",
235            Self::AllInputsClosed => "all_inputs_closed",
236            Self::ParamUpdate { .. } => "param_update",
237            Self::ParamDeleted { .. } => "param_deleted",
238            Self::NodeFailed { .. } => "node_failed",
239            Self::Restarted { .. } => "restarted",
240            Self::ExtDropped { .. } => "ext_dropped",
241            Self::Error(_) => "error",
242        }
243    }
244}
245
246impl core::fmt::Display for Event {
247    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
248        match self {
249            Self::Input { id, data, .. } => write!(f, "input {id} ({data})"),
250            Self::InputClosed { id, reason, .. } => write!(f, "input {id} closed: {reason}"),
251            Self::InputRecovered { id, generation, .. } => {
252                write!(f, "input {id} recovered at generation {generation}")
253            }
254            Self::Stop(cause) => write!(f, "stop: {cause}"),
255            Self::Reload { operator, .. } => match operator {
256                Some(operator) => write!(f, "reload operator {operator}"),
257                None => f.write_str("reload node"),
258            },
259            Self::AllInputsClosed => f.write_str("all inputs closed"),
260            Self::ParamUpdate { scope, key, value } => write!(f, "{scope}: {key} = {value}"),
261            Self::ParamDeleted { scope, key } => write!(f, "{scope}: {key} deleted"),
262            Self::NodeFailed { peer, cause } => write!(f, "peer {peer} failed: {cause}"),
263            Self::Restarted { peer, generation } => {
264                write!(f, "peer {peer} restarted as generation {generation}")
265            }
266            Self::ExtDropped { key, reason } => write!(f, "extension {key} dropped: {reason}"),
267            Self::Error(message) => write!(f, "error: {message}"),
268        }
269    }
270}
271
272#[cfg(test)]
273mod tests {
274    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
275
276    use super::*;
277    use astrs_time::HlcTimestamp;
278
279    fn input() -> Event {
280        Event::Input {
281            id: DataId::new("frames").unwrap(),
282            meta: Metadata::new(HlcTimestamp::new(1, 0)),
283            data: Payload::inline(vec![1, 2, 3]),
284        }
285    }
286
287    fn every_variant() -> Vec<Event> {
288        vec![
289            input(),
290            Event::InputClosed {
291                id: DataId::new("frames").unwrap(),
292                source: PortRef::from_parts("camera", "image").unwrap(),
293                reason: RouteCloseReason::ProducerFinished,
294            },
295            Event::InputRecovered {
296                id: DataId::new("frames").unwrap(),
297                source: PortRef::from_parts("camera", "image").unwrap(),
298                generation: 2,
299            },
300            Event::Stop(StopCause::Requested),
301            Event::Reload {
302                operator: None,
303                path: None,
304            },
305            Event::AllInputsClosed,
306            Event::ParamUpdate {
307                scope: ParamScope::Global,
308                key: ParamKey::new("gain").unwrap(),
309                value: Parameter::from(2.0),
310            },
311            Event::ParamDeleted {
312                scope: ParamScope::Global,
313                key: ParamKey::new("gain").unwrap(),
314            },
315            Event::NodeFailed {
316                peer: NodeId::new("camera").unwrap(),
317                cause: NodeExitCause::Success,
318            },
319            Event::Restarted {
320                peer: NodeId::new("camera").unwrap(),
321                generation: 1,
322            },
323            Event::ExtDropped {
324                key: ExtensionKey::user("calibration").unwrap(),
325                reason: "ttl".to_owned(),
326            },
327            Event::Error("queue overflow".to_owned()),
328        ]
329    }
330
331    #[test]
332    fn every_variant_renders_and_classifies() {
333        for event in every_variant() {
334            assert!(!event.to_string().is_empty(), "{event:?}");
335            assert!(!event.kind_name().is_empty());
336        }
337    }
338
339    #[test]
340    fn kind_names_are_unique() {
341        let mut names: Vec<&str> = every_variant().iter().map(Event::kind_name).collect();
342        let total = names.len();
343        names.sort_unstable();
344        names.dedup();
345        assert_eq!(names.len(), total);
346    }
347
348    #[test]
349    fn the_control_lane_is_everything_that_is_not_an_input() {
350        for event in every_variant() {
351            let data_lane = matches!(
352                event,
353                Event::Input { .. } | Event::InputClosed { .. } | Event::InputRecovered { .. }
354            );
355            assert_eq!(event.is_control(), !data_lane, "{event}");
356        }
357    }
358
359    #[test]
360    fn inputs_expose_their_parts() {
361        let event = input();
362        assert!(event.is_input());
363        assert!(!event.is_stop());
364        assert_eq!(event.input().map(DataId::as_str), Some("frames"));
365        assert!(event.metadata().is_some());
366        assert_eq!(event.payload().map(Payload::len), Some(3));
367
368        let (id, meta, data) = input().into_input().unwrap();
369        assert_eq!(id.as_str(), "frames");
370        assert_eq!(meta.timestamp, HlcTimestamp::new(1, 0));
371        assert_eq!(data.len(), 3);
372        assert!(Event::AllInputsClosed.into_input().is_none());
373    }
374
375    #[test]
376    fn stop_is_the_only_fusing_event() {
377        for event in every_variant() {
378            assert_eq!(event.is_stop(), matches!(event, Event::Stop(_)));
379        }
380    }
381
382    #[test]
383    fn faults_are_reported_as_faults() {
384        assert!(Event::Error(String::new()).is_fault());
385        assert!(
386            Event::NodeFailed {
387                peer: NodeId::new("x").unwrap(),
388                cause: NodeExitCause::Success
389            }
390            .is_fault()
391        );
392        assert!(!input().is_fault());
393        assert!(
394            !Event::InputClosed {
395                id: DataId::new("a").unwrap(),
396                source: PortRef::from_parts("b", "c").unwrap(),
397                reason: RouteCloseReason::ProducerFinished,
398            }
399            .is_fault(),
400            "a producer finishing is not a fault"
401        );
402    }
403}