Skip to main content

astrs_operator_api/
registry.rs

1//! [`OperatorRegistry`] and [`register_operator!`](crate::register_operator) — the static
2//! registration table `astrs-runtime` iterates to build the operators a
3//! manifest's `operators:` node names (blueprint §9.3).
4//!
5//! Operators compile into the runtime binary; this table is not populated
6//! by `dlopen` (the `dylib` feature's [`crate::export_dylib_operator`] is a
7//! separate, parallel path — see that macro's docs — with its own loader
8//! in `astrs-runtime`'s `dylib-operators` feature, never funneled through
9//! this registry), so "static" here means "fixed once the table is built",
10//! not "collected by the linker" — this crate adds no dependency capable of
11//! that (`linkme`/`ctor` are not on the retained list, blueprint §18.1),
12//! and a portable, Pure Rust table the caller assembles explicitly is both
13//! simpler and dependency-free. `register_operator!` is the ergonomic
14//! front-end for one entry; `OperatorRegistry::from_entries` builds the
15//! whole table from a list of them.
16
17use std::collections::BTreeMap;
18
19use crate::error::{OpError, OpResult};
20use crate::operator::Operator;
21
22/// A registered operator's constructor.
23///
24/// `Send + Sync` so one [`OperatorRegistry`] can be shared across the
25/// per-operator threads blueprint §9.3 describes.
26pub type OperatorConstructor = Box<dyn Fn() -> Box<dyn Operator> + Send + Sync + 'static>;
27
28/// The static registration table `astrs-runtime` iterates by name.
29///
30/// ```
31/// use astrs_operator_api::{register_operator, OperatorRegistry, OpEvent, OpOutput, OpResult, Operator, Status};
32///
33/// #[derive(Default)]
34/// struct Noop;
35///
36/// impl Operator for Noop {
37///     fn on_event(&mut self, _event: &OpEvent, _out: &mut OpOutput) -> OpResult<Status> {
38///         Ok(Status::Continue)
39///     }
40/// }
41///
42/// let registry = OperatorRegistry::from_entries([register_operator!(Noop)])?;
43/// assert!(registry.contains("Noop"));
44/// let operator = registry.build("Noop")?;
45/// drop(operator);
46/// # Ok::<(), astrs_operator_api::OpError>(())
47/// ```
48#[derive(Default)]
49pub struct OperatorRegistry {
50    entries: BTreeMap<&'static str, OperatorConstructor>,
51}
52
53impl OperatorRegistry {
54    /// An empty registry.
55    #[must_use]
56    pub fn new() -> Self {
57        Self {
58            entries: BTreeMap::new(),
59        }
60    }
61
62    /// Builds a registry from a list of `(name, constructor)` entries —
63    /// exactly the shape [`register_operator!`](crate::register_operator) produces.
64    ///
65    /// # Errors
66    ///
67    /// [`OpError::DuplicateOperator`] if two entries share a name.
68    pub fn from_entries(
69        entries: impl IntoIterator<Item = (&'static str, OperatorConstructor)>,
70    ) -> OpResult<Self> {
71        let mut registry = Self::new();
72        for (name, constructor) in entries {
73            registry.register(name, constructor)?;
74        }
75        Ok(registry)
76    }
77
78    /// Adds one entry.
79    ///
80    /// # Errors
81    ///
82    /// [`OpError::DuplicateOperator`] if `name` is already registered.
83    pub fn register(
84        &mut self,
85        name: &'static str,
86        constructor: OperatorConstructor,
87    ) -> OpResult<()> {
88        if self.entries.contains_key(name) {
89            return Err(OpError::DuplicateOperator {
90                name: name.to_owned(),
91            });
92        }
93        self.entries.insert(name, constructor);
94        Ok(())
95    }
96
97    /// Whether `name` has a registered constructor.
98    #[must_use]
99    pub fn contains(&self, name: &str) -> bool {
100        self.entries.contains_key(name)
101    }
102
103    /// Every registered name, in sorted order.
104    pub fn names(&self) -> impl Iterator<Item = &'static str> + '_ {
105        self.entries.keys().copied()
106    }
107
108    /// Number of registered entries.
109    #[must_use]
110    pub fn len(&self) -> usize {
111        self.entries.len()
112    }
113
114    /// Whether nothing is registered.
115    #[must_use]
116    pub fn is_empty(&self) -> bool {
117        self.entries.is_empty()
118    }
119
120    /// Constructs the operator registered as `name`.
121    ///
122    /// # Errors
123    ///
124    /// [`OpError::UnknownOperator`] when nothing is registered under that
125    /// name.
126    pub fn build(&self, name: &str) -> OpResult<Box<dyn Operator>> {
127        let constructor = self
128            .entries
129            .get(name)
130            .ok_or_else(|| OpError::UnknownOperator {
131                name: name.to_owned(),
132            })?;
133        Ok(constructor())
134    }
135}
136
137/// Builds one `(name, constructor)` registry entry for `$ty`.
138///
139/// Two forms:
140///
141/// - `register_operator!(MyOp)` — the registered name is `stringify!(MyOp)`
142///   (the type's own written name; for a qualified path this includes the
143///   path, spaces and all — use the explicit-name form for those).
144/// - `register_operator!("my-op" => MyOp)` — an explicit name, for a
145///   qualified path or a name the manifest's `operators:` block expects
146///   that differs from the Rust type name.
147///
148/// `$ty` must implement both [`Operator`](crate::Operator) and
149/// [`Default`] — the compile error if it does not is the enforcement point
150/// this crate uses in place of the blueprint's non-object-safe `Operator:
151/// Default + Send` (see [`Operator`](crate::Operator)'s own docs).
152///
153/// ```
154/// use astrs_operator_api::{register_operator, Operator, OpEvent, OpOutput, OpResult, Status};
155///
156/// #[derive(Default)]
157/// struct Crop;
158///
159/// impl Operator for Crop {
160///     fn on_event(&mut self, _event: &OpEvent, _out: &mut OpOutput) -> OpResult<Status> {
161///         Ok(Status::Continue)
162///     }
163/// }
164///
165/// let (name, ctor) = register_operator!(Crop);
166/// assert_eq!(name, "Crop");
167/// let operator = ctor();
168/// drop(operator);
169///
170/// let (name, _ctor) = register_operator!("crop-v2" => Crop);
171/// assert_eq!(name, "crop-v2");
172/// ```
173#[macro_export]
174macro_rules! register_operator {
175    ($ty:ty) => {
176        (
177            ::core::stringify!($ty),
178            (Box::new(|| -> ::std::boxed::Box<dyn $crate::Operator> {
179                ::std::boxed::Box::new(<$ty as ::core::default::Default>::default())
180            }) as $crate::OperatorConstructor),
181        )
182    };
183    ($name:expr => $ty:ty) => {
184        (
185            $name,
186            (Box::new(|| -> ::std::boxed::Box<dyn $crate::Operator> {
187                ::std::boxed::Box::new(<$ty as ::core::default::Default>::default())
188            }) as $crate::OperatorConstructor),
189        )
190    };
191}
192
193#[cfg(test)]
194mod tests {
195    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
196
197    use super::*;
198    use crate::event::OpEvent;
199    use crate::operator::Status;
200    use crate::output::OpOutput;
201
202    #[derive(Default)]
203    struct Alpha;
204    impl Operator for Alpha {
205        fn on_event(&mut self, _event: &OpEvent, _out: &mut OpOutput) -> OpResult<Status> {
206            Ok(Status::Continue)
207        }
208    }
209
210    #[derive(Default)]
211    struct Beta;
212    impl Operator for Beta {
213        fn on_event(&mut self, _event: &OpEvent, _out: &mut OpOutput) -> OpResult<Status> {
214            Ok(Status::Finished)
215        }
216    }
217
218    #[test]
219    fn register_operator_produces_the_stringified_name() {
220        let (name, ctor) = register_operator!(Alpha);
221        assert_eq!(name, "Alpha");
222        let mut op = ctor();
223        let mut out = OpOutput::new();
224        let status = op.on_event(&OpEvent::Reload, &mut out).unwrap();
225        assert_eq!(status, Status::Continue);
226    }
227
228    #[test]
229    fn register_operator_accepts_an_explicit_name() {
230        let (name, _ctor) = register_operator!("beta-v1" => Beta);
231        assert_eq!(name, "beta-v1");
232    }
233
234    #[test]
235    fn registry_lookup_and_registration() {
236        let mut registry = OperatorRegistry::new();
237        assert!(registry.is_empty());
238
239        let (name, ctor) = register_operator!(Alpha);
240        registry.register(name, ctor).unwrap();
241        assert_eq!(registry.len(), 1);
242        assert!(registry.contains("Alpha"));
243        assert!(!registry.contains("Beta"));
244
245        let mut op = registry.build("Alpha").unwrap();
246        let mut out = OpOutput::new();
247        assert_eq!(
248            op.on_event(&OpEvent::Reload, &mut out).unwrap(),
249            Status::Continue
250        );
251    }
252
253    #[test]
254    fn duplicate_registration_is_rejected() {
255        let mut registry = OperatorRegistry::new();
256        let (name, ctor) = register_operator!(Alpha);
257        registry.register(name, ctor).unwrap();
258        let (name2, ctor2) = register_operator!(Alpha);
259        let err = registry.register(name2, ctor2).unwrap_err();
260        match err {
261            OpError::DuplicateOperator { name } => assert_eq!(name, "Alpha"),
262            other => panic!("expected DuplicateOperator, got {other:?}"),
263        }
264    }
265
266    #[test]
267    fn unknown_operator_is_reported() {
268        let registry = OperatorRegistry::new();
269        // `Box<dyn Operator>` is not `Debug` (it is a trait-object closure
270        // product), so this checks the error branch by hand rather than
271        // through `unwrap_err`, which needs the `Ok` side to be `Debug`.
272        match registry.build("nope") {
273            Err(OpError::UnknownOperator { name }) => assert_eq!(name, "nope"),
274            other => panic!("expected Err(UnknownOperator), got {}", other.is_ok()),
275        }
276    }
277
278    #[test]
279    fn from_entries_builds_a_multi_operator_table() {
280        let registry =
281            OperatorRegistry::from_entries([register_operator!(Alpha), register_operator!(Beta)])
282                .unwrap();
283        assert_eq!(registry.len(), 2);
284        let names: Vec<&str> = registry.names().collect();
285        assert_eq!(names, ["Alpha", "Beta"]);
286
287        let mut out = OpOutput::new();
288        let mut beta = registry.build("Beta").unwrap();
289        assert_eq!(
290            beta.on_event(&OpEvent::Reload, &mut out).unwrap(),
291            Status::Finished
292        );
293    }
294
295    #[test]
296    fn from_entries_rejects_duplicate_names_from_the_same_type() {
297        // `OperatorRegistry` holds `Box<dyn Fn(..) -> ..>` constructors,
298        // which are not `Debug`, so this checks the error branch by hand
299        // rather than through `unwrap_err`.
300        match OperatorRegistry::from_entries([register_operator!(Alpha), register_operator!(Alpha)])
301        {
302            Err(OpError::DuplicateOperator { name }) => assert_eq!(name, "Alpha"),
303            Ok(_) => panic!("expected a duplicate-name error"),
304            Err(other) => panic!(
305                "expected DuplicateOperator, got a different OpError variant instead: {other}"
306            ),
307        }
308    }
309}