Skip to main content

astrs_operator_api/
operator.rs

1//! [`Operator`] and [`Status`] — the trait an in-process dataflow stage
2//! implements, and the result it returns (blueprint §9.3).
3
4use std::collections::BTreeMap;
5
6use astrs_wire::Parameter;
7
8use crate::error::OpResult;
9use crate::event::OpEvent;
10use crate::output::OpOutput;
11
12/// What an [`Operator::on_event`] call decided.
13///
14/// ```
15/// use astrs_operator_api::Status;
16///
17/// assert_ne!(Status::Continue, Status::Finished);
18/// ```
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
20#[non_exhaustive]
21pub enum Status {
22    /// Keep running; more events may still arrive.
23    Continue,
24    /// This operator is done — its host may retire it without treating that
25    /// as a failure (distinct from an `Err` return, which the host reports
26    /// as `NodeFailed`, blueprint §9.3).
27    Finished,
28}
29
30impl Status {
31    /// Whether the operator should keep receiving events.
32    #[must_use]
33    pub const fn is_continue(self) -> bool {
34        matches!(self, Self::Continue)
35    }
36
37    /// Whether the operator is done.
38    #[must_use]
39    pub const fn is_finished(self) -> bool {
40        matches!(self, Self::Finished)
41    }
42}
43
44/// An in-process dataflow stage hosted by `astrs-runtime` (blueprint §9.3).
45///
46/// ```text
47/// pub trait Operator: Default + Send {
48///     fn on_event(&mut self, event: &OpEvent, out: &mut OpOutput) -> OpResult<Status>;
49/// }
50/// astrs::register_operator!(MyOp);
51/// ```
52///
53/// is the blueprint's own sketch (quoted verbatim, hence untested as code
54/// — it does not compile, which is exactly the point below); this trait
55/// realizes it faithfully with one
56/// necessary correction. §9.3 also writes `Operator: Default + Send`, but
57/// the registry it describes in the same breath —
58/// `Box<dyn Fn() -> Box<dyn Operator>>` — requires `Box<dyn Operator>` to be
59/// a legal type, and a trait with `Default` as a supertrait is not
60/// object-safe (`Default::default()` has no receiver to dispatch on). This
61/// trait therefore drops `Default` from its own supertraits and asks for it
62/// at the registration site instead: [`register_operator!`](crate::register_operator)
63/// requires `$ty: Default` on the type it wraps, so a registered operator
64/// is exactly as default-constructible as the blueprint intends, enforced
65/// at the one place that actually needs it.
66///
67/// Operators compile **into** the runtime binary via the registry macro by
68/// default — static dispatch, the flagship path. A type that implements
69/// this trait can *also* be exported from a `cdylib` via
70/// [`crate::export_dylib_operator`] (the `dylib` feature) and loaded at
71/// `dlopen` time by `astrs-runtime`'s `dylib-operators` feature — the same
72/// trait either way; only how the host obtains a `Box<dyn Operator>`
73/// differs. Each operator runs on its own thread over a bounded channel;
74/// panics are caught, reported as `NodeFailed`, and honor the operator's
75/// restart policy without tearing down siblings (blueprint §9.3) — none of
76/// which this trait needs to know about, since it is the *contract* the
77/// host schedules against, not the scheduler itself.
78///
79/// # Lifecycle
80///
81/// [`Operator::configure`] runs once immediately after construction, before
82/// [`Operator::on_start`] and before any event — it is how this operator
83/// instance receives its own entry's manifest `config:` map (blueprint
84/// §9.3's `operators:` list), the one thing `Default::default()` itself
85/// cannot supply. [`Operator::on_start`] runs once after that, before the
86/// first [`Operator::on_event`]. [`Operator::on_stop`] runs once, when the
87/// host is winding the operator down (typically because
88/// [`Operator::on_event`] returned [`Status::Finished`] or an
89/// [`OpEvent::Stop`] arrived). [`Operator::on_reload`] runs on
90/// [`OpEvent::Reload`] instead of routing it through `on_event`, so an
91/// operator that only cares about resetting state does not need a
92/// catch-all arm in its own event match. All four default to a no-op, so a
93/// minimal operator implements only `on_event`.
94pub trait Operator: Send + 'static {
95    /// Runs once immediately after construction, before
96    /// [`Operator::on_start`].
97    ///
98    /// `config` is this operator instance's manifest `config:` map
99    /// (`astrs_manifest::OperatorConfig::config`, converted from JSON to
100    /// this crate's own [`Parameter`] vocabulary by `astrs-runtime` — the
101    /// same closed value set [`OpEvent::ParamUpdate`] already carries, so
102    /// an operator author reads static construction-time configuration and
103    /// live parameter updates through one shared set of types rather than
104    /// two). Because the host always builds a fresh operator via
105    /// `Default::default()` (blueprint §9.3's static registry), this hook
106    /// — not the constructor — is where a `crop`/`nms`-style operator
107    /// reads a threshold, a label set, or any other per-instance setting
108    /// its wiring alone does not carry.
109    ///
110    /// Runs again, with the same map, on every restarted incarnation
111    /// (blueprint §9.3): a fresh `Default::default()` has no memory of the
112    /// previous incarnation's configuration, so re-delivering it here is
113    /// what makes a restarted operator behave like the manifest describes
114    /// rather than like a blank slate.
115    ///
116    /// The default does nothing, which is correct for an operator with no
117    /// configuration of its own.
118    ///
119    /// # Errors
120    ///
121    /// Any [`crate::OpError`] the operator wants to refuse its
122    /// configuration with — folded into the same restart/give-up decision
123    /// as any other failed hook (blueprint §9.3).
124    fn configure(&mut self, config: &BTreeMap<String, Parameter>) -> OpResult<()> {
125        let _ = config;
126        Ok(())
127    }
128
129    /// Runs once before the first [`Operator::on_event`] call.
130    ///
131    /// The default does nothing.
132    ///
133    /// # Errors
134    ///
135    /// Any [`crate::OpError`] the operator wants to fail startup with.
136    fn on_start(&mut self, out: &mut OpOutput) -> OpResult<()> {
137        let _ = out;
138        Ok(())
139    }
140
141    /// Handles one event, optionally producing output.
142    ///
143    /// # Errors
144    ///
145    /// Any [`crate::OpError`] the operator wants to report as a failure
146    /// (surfaced as `NodeFailed` by the host, blueprint §9.3).
147    fn on_event(&mut self, event: &OpEvent, out: &mut OpOutput) -> OpResult<Status>;
148
149    /// Runs once when the host is winding the operator down.
150    ///
151    /// The default does nothing. A operator that wants to flush a final
152    /// message overrides this instead of trying to catch [`OpEvent::Stop`]
153    /// in [`Operator::on_event`] and remembering to still return
154    /// [`Status::Finished`].
155    ///
156    /// # Errors
157    ///
158    /// Any [`crate::OpError`] the operator wants to report.
159    fn on_stop(&mut self, out: &mut OpOutput) -> OpResult<()> {
160        let _ = out;
161        Ok(())
162    }
163
164    /// Runs on [`OpEvent::Reload`] instead of `on_event`.
165    ///
166    /// The default does nothing, which is the correct behavior for an
167    /// operator with no state to reset.
168    ///
169    /// # Errors
170    ///
171    /// Any [`crate::OpError`] the operator wants to report.
172    fn on_reload(&mut self, out: &mut OpOutput) -> OpResult<()> {
173        let _ = out;
174        Ok(())
175    }
176}
177
178#[cfg(test)]
179mod tests {
180    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
181
182    use super::*;
183
184    #[test]
185    fn status_predicates() {
186        assert!(Status::Continue.is_continue());
187        assert!(!Status::Continue.is_finished());
188        assert!(Status::Finished.is_finished());
189        assert!(!Status::Finished.is_continue());
190    }
191
192    /// A toy operator driven through a scripted event sequence — the
193    /// integration-style test the task calls for, exercised here at the
194    /// trait level (the registry-level version lives in `registry.rs`).
195    #[derive(Default)]
196    struct Counter {
197        seen: u32,
198        started: bool,
199        stopped: bool,
200        reloaded: bool,
201    }
202
203    impl Operator for Counter {
204        fn on_start(&mut self, _out: &mut OpOutput) -> OpResult<()> {
205            self.started = true;
206            Ok(())
207        }
208
209        fn on_event(&mut self, event: &OpEvent, out: &mut OpOutput) -> OpResult<Status> {
210            match event {
211                OpEvent::Input { metadata, .. } => {
212                    self.seen += 1;
213                    out.send_bytes("count", metadata.clone(), vec![self.seen as u8])?;
214                    Ok(Status::Continue)
215                }
216                OpEvent::Stop { .. } => Ok(Status::Finished),
217                _ => Ok(Status::Continue),
218            }
219        }
220
221        fn on_stop(&mut self, _out: &mut OpOutput) -> OpResult<()> {
222            self.stopped = true;
223            Ok(())
224        }
225
226        fn on_reload(&mut self, _out: &mut OpOutput) -> OpResult<()> {
227            self.reloaded = true;
228            self.seen = 0;
229            Ok(())
230        }
231    }
232
233    fn input_event(payload: Vec<u8>) -> OpEvent {
234        use astrs_time::HlcTimestamp;
235        use astrs_wire::{DataId, Metadata};
236
237        OpEvent::Input {
238            id: DataId::new("frames").unwrap(),
239            source: "camera/image".parse().unwrap(),
240            metadata: Metadata::new(HlcTimestamp::EPOCH),
241            payload,
242        }
243    }
244
245    #[test]
246    fn a_toy_operator_runs_through_a_scripted_sequence() {
247        let mut op = Counter::default();
248        let mut out = OpOutput::new();
249
250        op.on_start(&mut out).unwrap();
251        assert!(op.started);
252
253        for i in 0..3u8 {
254            let status = op.on_event(&input_event(vec![i]), &mut out).unwrap();
255            assert_eq!(status, Status::Continue);
256        }
257        assert_eq!(op.seen, 3);
258        assert_eq!(out.len(), 3);
259        let sends = out.drain();
260        assert_eq!(sends[2].payload(), &[3]);
261
262        op.on_reload(&mut out).unwrap();
263        assert!(op.reloaded);
264        assert_eq!(op.seen, 0);
265
266        let stop = OpEvent::Stop {
267            cause: astrs_wire::StopCause::Requested,
268            grace: None,
269        };
270        let status = op.on_event(&stop, &mut out).unwrap();
271        assert_eq!(status, Status::Finished);
272
273        op.on_stop(&mut out).unwrap();
274        assert!(op.stopped);
275    }
276
277    #[test]
278    fn operator_is_object_safe() {
279        // The compile-time check the blueprint's literal `Default + Send`
280        // signature fails: this line does not compile unless `Operator`
281        // has no non-object-safe supertrait.
282        let boxed: Box<dyn Operator> = Box::new(Counter::default());
283        drop(boxed);
284    }
285
286    #[test]
287    fn configure_defaults_to_a_no_op() {
288        // `Counter` never overrides `configure`; the default must accept
289        // any map, including a non-empty one, without complaint.
290        let mut op = Counter::default();
291        let mut config = BTreeMap::new();
292        config.insert("threshold".to_owned(), Parameter::Float(0.5));
293        op.configure(&config).unwrap();
294        assert_eq!(op.seen, 0, "the default configure touches no state");
295    }
296
297    /// An operator whose behavior is driven entirely by
298    /// [`Operator::configure`] — the shape a real `crop`/`nms`-style
299    /// manifest `config:` map is meant to reach.
300    #[derive(Default)]
301    struct Thresholded {
302        threshold: i64,
303        labels: Vec<String>,
304    }
305
306    impl Operator for Thresholded {
307        fn configure(&mut self, config: &BTreeMap<String, Parameter>) -> OpResult<()> {
308            match config.get("threshold") {
309                Some(Parameter::Integer(value)) => self.threshold = *value,
310                Some(other) => {
311                    return Err(crate::OpError::failed(format!(
312                        "threshold must be an integer, got {other:?}"
313                    )));
314                }
315                None => {}
316            }
317            if let Some(Parameter::ListString(values)) = config.get("labels") {
318                self.labels = values.clone();
319            }
320            Ok(())
321        }
322
323        fn on_event(&mut self, _event: &OpEvent, _out: &mut OpOutput) -> OpResult<Status> {
324            Ok(Status::Continue)
325        }
326    }
327
328    #[test]
329    fn configure_can_read_a_typed_config_map() {
330        let mut op = Thresholded::default();
331        let mut config = BTreeMap::new();
332        config.insert("threshold".to_owned(), Parameter::Integer(7));
333        config.insert(
334            "labels".to_owned(),
335            Parameter::ListString(vec!["person".to_owned(), "car".to_owned()]),
336        );
337        op.configure(&config).unwrap();
338        assert_eq!(op.threshold, 7);
339        assert_eq!(op.labels, vec!["person".to_owned(), "car".to_owned()]);
340    }
341
342    #[test]
343    fn configure_can_reject_a_bad_value() {
344        let mut op = Thresholded::default();
345        let mut config = BTreeMap::new();
346        config.insert("threshold".to_owned(), Parameter::String("nope".to_owned()));
347        let error = op.configure(&config).unwrap_err();
348        assert!(matches!(error, crate::OpError::Failed { .. }));
349        assert_eq!(op.threshold, 0, "the rejected value must never be applied");
350    }
351}