Skip to main content

astrs_operator_api/
event.rs

1//! [`OpEvent`] — the event stream an [`crate::Operator`] sees.
2//!
3//! A lean mirror of [`astrs_wire::NodeEvent`] (blueprint §7.3, §9.3):
4//! operators run inside a node-shaped host (`astrs-runtime`) that already
5//! resolved routing, extension-table plumbing and peer bookkeeping at the
6//! node level, so the operator only ever needs the five variants below.
7//! Every field reuses the exact `astrs-wire` type the node-level event
8//! carries — no parallel id/metadata vocabulary, no wire dependency beyond
9//! those types themselves.
10
11use astrs_wire::{
12    DataId, DurationMs, Metadata, NodeEvent, ParamKey, ParamScope, Parameter, PortRef,
13    RouteCloseReason, StopCause,
14};
15
16/// One event delivered to an [`crate::Operator`] (blueprint §9.3).
17///
18/// `#[non_exhaustive]`: new variants may join at the tail as the runtime's
19/// operator-hosting story grows (blueprint §3.4's append-only rule).
20#[derive(Debug, Clone, PartialEq)]
21#[non_exhaustive]
22pub enum OpEvent {
23    /// One message for one of the operator's inputs.
24    ///
25    /// The payload is raw bytes — an Arrow IPC stream (blueprint §6.1) —
26    /// exactly as it rides `astrs_wire::NodeEvent::Input`; decoding into a
27    /// typed [`astrs_data::AstrsMessage`] is the operator's own business.
28    Input {
29        /// The input this message arrived on.
30        id: DataId,
31        /// The producer port it came from.
32        source: PortRef,
33        /// The metadata riding beside the payload.
34        metadata: Metadata,
35        /// The payload bytes.
36        payload: Vec<u8>,
37    },
38    /// An input will receive nothing further.
39    InputClosed {
40        /// The input that closed.
41        id: DataId,
42        /// The producer port that stopped.
43        source: PortRef,
44        /// Why it closed.
45        reason: RouteCloseReason,
46    },
47    /// Finish up: the host is winding the operator down.
48    Stop {
49        /// Why the operator is being stopped.
50        cause: StopCause,
51        /// How long it has before it is dropped without a clean exit.
52        grace: Option<DurationMs>,
53    },
54    /// Reset the operator's own state (blueprint §9.3).
55    ///
56    /// Unlike `astrs_wire::NodeEvent::Reload`, this carries no `operator`
57    /// selector or `path`: by the time the host delivers this event on a
58    /// *specific* operator's channel, the routing question is already
59    /// answered, and dylib hot-reload (the case `path` exists for) is
60    /// deferred to 0.2 (blueprint §9.3, §22) — there is no artefact to name
61    /// yet.
62    Reload,
63    /// A parameter this operator reads was written (blueprint §17
64    /// `param set`).
65    ParamUpdate {
66        /// The scope it was written in.
67        scope: ParamScope,
68        /// The key.
69        key: ParamKey,
70        /// The new value.
71        value: Parameter,
72    },
73}
74
75impl OpEvent {
76    /// The input this event concerns, when it concerns one.
77    #[must_use]
78    pub const fn input(&self) -> Option<&DataId> {
79        match self {
80            Self::Input { id, .. } | Self::InputClosed { id, .. } => Some(id),
81            _ => None,
82        }
83    }
84
85    /// Whether this event delivers data.
86    #[must_use]
87    pub const fn is_input(&self) -> bool {
88        matches!(self, Self::Input { .. })
89    }
90
91    /// Whether this event means the operator should wind down.
92    #[must_use]
93    pub const fn is_terminal(&self) -> bool {
94        matches!(self, Self::Stop { .. })
95    }
96
97    /// The payload bytes this event carries, for bandwidth accounting.
98    #[must_use]
99    pub fn payload_len(&self) -> usize {
100        match self {
101            Self::Input { payload, .. } => payload.len(),
102            _ => 0,
103        }
104    }
105
106    /// Narrows a node-level [`NodeEvent`] to the operator-level event it
107    /// corresponds to, or `None` when the node event has no operator-level
108    /// meaning (route-plane changes, peer lifecycle, extension-table
109    /// traffic and registration — all handled by the node host itself,
110    /// never surfaced to an operator).
111    ///
112    /// This is the bridge `astrs-runtime` uses to fan a node's event stream
113    /// out to each hosted operator's own channel (blueprint §9.3: "each
114    /// operator runs on its own thread over a bounded channel").
115    ///
116    /// # Examples
117    ///
118    /// ```
119    /// use astrs_operator_api::OpEvent;
120    /// use astrs_wire::{DataId, Metadata, NodeEvent};
121    /// use astrs_time::HlcTimestamp;
122    ///
123    /// let node_event = NodeEvent::Input {
124    ///     id: DataId::new("frames").unwrap(),
125    ///     source: "camera/image".parse().unwrap(),
126    ///     metadata: Metadata::new(HlcTimestamp::EPOCH),
127    ///     payload: vec![1, 2, 3],
128    /// };
129    /// assert!(OpEvent::from_node_event(&node_event).is_some());
130    /// assert!(OpEvent::from_node_event(&NodeEvent::AllInputsClosed).is_none());
131    /// ```
132    #[must_use]
133    pub fn from_node_event(event: &NodeEvent) -> Option<Self> {
134        match event {
135            NodeEvent::Input {
136                id,
137                source,
138                metadata,
139                payload,
140            } => Some(Self::Input {
141                id: id.clone(),
142                source: source.clone(),
143                metadata: metadata.clone(),
144                payload: payload.clone(),
145            }),
146            NodeEvent::InputClosed { id, source, reason } => Some(Self::InputClosed {
147                id: id.clone(),
148                source: source.clone(),
149                reason: reason.clone(),
150            }),
151            NodeEvent::Stop { cause, grace } => Some(Self::Stop {
152                cause: cause.clone(),
153                grace: *grace,
154            }),
155            NodeEvent::Reload { .. } => Some(Self::Reload),
156            NodeEvent::ParamUpdate { scope, key, value } => Some(Self::ParamUpdate {
157                scope: scope.clone(),
158                key: key.clone(),
159                value: value.clone(),
160            }),
161            _ => None,
162        }
163    }
164}
165
166#[cfg(test)]
167mod tests {
168    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
169
170    use super::*;
171    use astrs_time::HlcTimestamp;
172
173    fn sample_input() -> OpEvent {
174        OpEvent::Input {
175            id: DataId::new("frames").unwrap(),
176            source: "camera/image".parse().unwrap(),
177            metadata: Metadata::new(HlcTimestamp::EPOCH),
178            payload: vec![1, 2, 3, 4],
179        }
180    }
181
182    #[test]
183    fn input_accessors() {
184        let event = sample_input();
185        assert!(event.is_input());
186        assert_eq!(event.input().map(DataId::as_str), Some("frames"));
187        assert_eq!(event.payload_len(), 4);
188        assert!(!event.is_terminal());
189    }
190
191    #[test]
192    fn stop_is_terminal_and_carries_no_input() {
193        let event = OpEvent::Stop {
194            cause: StopCause::Requested,
195            grace: None,
196        };
197        assert!(event.is_terminal());
198        assert!(event.input().is_none());
199        assert!(!event.is_input());
200        assert_eq!(event.payload_len(), 0);
201    }
202
203    #[test]
204    fn input_closed_names_its_input_but_is_not_data() {
205        let event = OpEvent::InputClosed {
206            id: DataId::new("frames").unwrap(),
207            source: "camera/image".parse().unwrap(),
208            reason: RouteCloseReason::ProducerFinished,
209        };
210        assert_eq!(event.input().map(DataId::as_str), Some("frames"));
211        assert!(!event.is_input());
212    }
213
214    #[test]
215    fn from_node_event_narrows_the_five_operator_relevant_variants() {
216        let input = NodeEvent::Input {
217            id: DataId::new("frames").unwrap(),
218            source: "camera/image".parse().unwrap(),
219            metadata: Metadata::new(HlcTimestamp::EPOCH),
220            payload: vec![9],
221        };
222        assert_eq!(
223            OpEvent::from_node_event(&input),
224            Some(OpEvent::Input {
225                id: DataId::new("frames").unwrap(),
226                source: "camera/image".parse().unwrap(),
227                metadata: Metadata::new(HlcTimestamp::EPOCH),
228                payload: vec![9],
229            })
230        );
231
232        let closed = NodeEvent::InputClosed {
233            id: DataId::new("frames").unwrap(),
234            source: "camera/image".parse().unwrap(),
235            reason: RouteCloseReason::ProducerFinished,
236        };
237        assert!(matches!(
238            OpEvent::from_node_event(&closed),
239            Some(OpEvent::InputClosed { .. })
240        ));
241
242        let stop = NodeEvent::Stop {
243            cause: StopCause::Requested,
244            grace: None,
245        };
246        assert_eq!(
247            OpEvent::from_node_event(&stop),
248            Some(OpEvent::Stop {
249                cause: StopCause::Requested,
250                grace: None
251            })
252        );
253
254        let reload = NodeEvent::Reload {
255            operator: None,
256            path: None,
257        };
258        assert_eq!(OpEvent::from_node_event(&reload), Some(OpEvent::Reload));
259
260        let param = NodeEvent::ParamUpdate {
261            scope: ParamScope::Global,
262            key: ParamKey::new("gain").unwrap(),
263            value: Parameter::Float(1.5),
264        };
265        assert_eq!(
266            OpEvent::from_node_event(&param),
267            Some(OpEvent::ParamUpdate {
268                scope: ParamScope::Global,
269                key: ParamKey::new("gain").unwrap(),
270                value: Parameter::Float(1.5),
271            })
272        );
273    }
274
275    #[test]
276    fn from_node_event_drops_events_with_no_operator_level_meaning() {
277        for event in [
278            NodeEvent::AllInputsClosed,
279            NodeEvent::InputRecovered {
280                id: DataId::new("frames").unwrap(),
281                source: "camera/image".parse().unwrap(),
282                generation: 2,
283            },
284            NodeEvent::NodeFailed {
285                peer: astrs_wire::NodeId::new("camera").unwrap(),
286                cause: astrs_wire::NodeExitCause::Success,
287            },
288            NodeEvent::Restarted {
289                peer: astrs_wire::NodeId::new("camera").unwrap(),
290                generation: 2,
291            },
292            NodeEvent::ParamDeleted {
293                scope: ParamScope::Global,
294                key: ParamKey::new("gain").unwrap(),
295            },
296        ] {
297            assert!(
298                OpEvent::from_node_event(&event).is_none(),
299                "{event:?} should have no operator-level meaning"
300            );
301        }
302    }
303}