Skip to main content

graphrt_core/
node.rs

1//! The node contract.
2//!
3//! A node is an immutable, pre-validated object built once from its
4//! [`NodeDoc`] by a factory in the [`Registry`]. At run time the engine calls
5//! [`Node::run`] with an owned [`NodeContext`]; the node reads inputs from the
6//! context's pool snapshot and returns a [`NodeOutcome`]. Nodes never mutate
7//! shared state directly: outputs and variable writes are returned and
8//! committed by the engine.
9
10use std::any::{Any, TypeId};
11use std::collections::HashMap;
12use std::fmt;
13use std::sync::{Arc, OnceLock};
14use std::time::Duration;
15
16use futures::future::BoxFuture;
17use indexmap::IndexMap;
18
19use crate::dsl::NodeDoc;
20use crate::event::{Event, FrameId, PauseReason, Usage};
21use crate::pool::{Selector, VariablePool};
22use crate::snapshot::FrameSnapshot;
23use crate::value::Value;
24use crate::variables::{VarName, Variables};
25
26/// How the scheduler treats a node.
27#[derive(Clone, Copy, Debug, PartialEq, Eq)]
28#[non_exhaustive]
29pub enum NodeRole {
30    /// Entry point of the root graph.
31    Root,
32    /// Entry point of a container body (iteration-start / loop-start).
33    ScopeStart,
34    /// Regular node: on success every outgoing edge is taken.
35    Executable,
36    /// Selects exactly one outgoing handle via [`NodeOutput::branch`].
37    Branch,
38    /// Produces user-facing output (answer / end). Outputs are merged into the frame outputs.
39    Response,
40    /// Owns a child scope executed through [`NodeContext::subgraph`].
41    Container,
42}
43
44/// Error produced by a node.
45#[derive(Clone, Debug, PartialEq, thiserror::Error)]
46#[error("{kind}: {message}")]
47pub struct NodeError {
48    /// Machine-readable category, e.g. `timeout`, `http`, `invalid_input`, `model`.
49    pub kind: String,
50    pub message: String,
51    /// Whether a retry may succeed. Non-retryable errors skip the retry policy.
52    pub retryable: bool,
53    /// Minimum delay before a retry, as requested by the remote side (e.g. an
54    /// HTTP `Retry-After` header or a provider rate limit). The engine waits for
55    /// the larger of this and the node's retry policy delay.
56    pub retry_after_ms: Option<u64>,
57}
58
59impl NodeError {
60    pub fn new(kind: impl Into<String>, message: impl Into<String>) -> Self {
61        Self { kind: kind.into(), message: message.into(), retryable: true, retry_after_ms: None }
62    }
63
64    /// Error that retrying cannot fix (bad configuration, invalid input).
65    pub fn fatal(kind: impl Into<String>, message: impl Into<String>) -> Self {
66        Self { kind: kind.into(), message: message.into(), retryable: false, retry_after_ms: None }
67    }
68
69    /// Attach a server-requested retry delay.
70    pub fn with_retry_after(mut self, retry_after_ms: Option<u64>) -> Self {
71        self.retry_after_ms = retry_after_ms;
72        self
73    }
74
75    /// Replace the message, keeping kind, retryability and retry delay.
76    pub fn with_message(mut self, message: impl Into<String>) -> Self {
77        self.message = message.into();
78        self
79    }
80
81    pub fn invalid_input(message: impl Into<String>) -> Self {
82        Self::fatal("invalid_input", message)
83    }
84
85    pub fn timeout(after: Duration) -> Self {
86        Self::new("timeout", format!("node timed out after {} ms", after.as_millis()))
87    }
88}
89
90/// Error raised when a node's configuration is invalid (at graph build time).
91#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
92#[error("node `{node_id}` ({kind}): {}{message}", field_prefix(.field))]
93pub struct ConfigError {
94    pub node_id: String,
95    pub kind: String,
96    pub message: String,
97    /// Config field the error is about, as a path below the node such as
98    /// `variables[0].value_selector`, when known.
99    pub field: Option<String>,
100}
101
102fn field_prefix(field: &Option<String>) -> String {
103    field.as_ref().map(|f| format!("{f}: ")).unwrap_or_default()
104}
105
106impl ConfigError {
107    pub fn new(doc: &NodeDoc, message: impl Into<String>) -> Self {
108        Self { node_id: doc.id.clone(), kind: doc.kind.clone(), message: message.into(), field: None }
109    }
110
111    /// Attach the config field the error is about.
112    #[must_use]
113    pub fn at_field(mut self, field: impl Into<String>) -> Self {
114        self.field = Some(field.into());
115        self
116    }
117}
118
119/// Successful node result.
120#[derive(Clone, Debug, Default, PartialEq)]
121pub struct NodeOutput {
122    /// Outputs stored under the node's namespace (`<node_id>.<key>`). The
123    /// engine stores this map as the namespace and emits it in
124    /// [`Event::NodeSucceeded`] without copying it.
125    pub outputs: Variables,
126    /// Selected handle for branch nodes.
127    pub branch: Option<String>,
128    /// Writes to other namespaces (conversation variables, loop variables, ...), applied in order.
129    pub writes: Vec<(Selector, Value)>,
130    pub usage: Option<Usage>,
131    /// Observability data (resolved inputs, request details...). Not stored in the pool.
132    pub metadata: IndexMap<String, Value>,
133}
134
135impl NodeOutput {
136    pub fn new() -> Self {
137        Self::default()
138    }
139
140    /// Add an output. A string-literal name costs no allocation.
141    pub fn with(mut self, key: impl Into<VarName>, value: impl Into<Value>) -> Self {
142        self.outputs.insert(key.into(), value.into());
143        self
144    }
145
146    pub fn branch(mut self, handle: impl Into<String>) -> Self {
147        self.branch = Some(handle.into());
148        self
149    }
150
151    pub fn write(mut self, selector: Selector, value: Value) -> Self {
152        self.writes.push((selector, value));
153        self
154    }
155
156    pub fn usage(mut self, usage: Usage) -> Self {
157        self.usage = Some(usage);
158        self
159    }
160
161    pub fn meta(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
162        self.metadata.insert(key.into(), value.into());
163        self
164    }
165}
166
167/// A request from a node to pause the run (e.g. waiting for a human).
168#[derive(Clone, Debug, PartialEq)]
169pub struct PauseRequest {
170    /// Machine-readable kind, e.g. `human_input`.
171    pub kind: String,
172    /// Details shown to the host (form schema, prompt...).
173    pub data: Value,
174    /// State handed back to the node in [`Resume::state`].
175    pub state: serde_json::Value,
176}
177
178/// What a node run produced.
179#[derive(Clone, Debug, PartialEq)]
180pub enum NodeOutcome {
181    Completed(NodeOutput),
182    Paused(PauseRequest),
183}
184
185impl From<NodeOutput> for NodeOutcome {
186    fn from(o: NodeOutput) -> Self {
187        NodeOutcome::Completed(o)
188    }
189}
190
191/// Data given to a node that previously paused.
192#[derive(Clone, Debug, PartialEq)]
193pub struct Resume {
194    /// The node's own saved state ([`PauseRequest::state`]).
195    pub state: serde_json::Value,
196    /// Host-supplied input for this node (e.g. a submitted human-input form), if any.
197    pub input: Option<Value>,
198}
199
200/// Result type of [`Node::run`].
201pub type NodeResult = Result<NodeOutcome, NodeError>;
202
203/// An executable node.
204pub trait Node: Send + Sync + fmt::Debug {
205    /// Scheduling role. Must be constant for a given instance.
206    fn role(&self) -> NodeRole {
207        NodeRole::Executable
208    }
209
210    /// Execute the node. Dropping the returned future cancels the node.
211    fn run(&self, ctx: NodeContext) -> BoxFuture<'_, NodeResult>;
212
213    /// Selectors this node reads. [`crate::graph::Graph::build`] rejects selectors
214    /// whose namespace is neither a node id nor `sys` / `env` / `conversation`
215    /// (catching typos at load time) and warns about references into other
216    /// container bodies. Return every selector the node may read, including
217    /// placeholders inside templates.
218    fn inputs(&self) -> Vec<Selector> {
219        Vec::new()
220    }
221
222    /// Every handle a [`NodeRole::Branch`] node may select, when known from its
223    /// configuration (if-else case ids, classifier class ids...). Graph building
224    /// rejects edges with other handles. `None` (the default) falls back to the
225    /// kind's catalog descriptor: `Fixed` handles are checked, `Dynamic` ones are
226    /// not, and non-branch nodes have the single handle `source`.
227    fn branch_handles(&self) -> Option<Vec<String>> {
228        None
229    }
230}
231
232/// Append `new` writes to `acc`, keeping only the latest write per exact selector.
233///
234/// An earlier write to the same selector is removed and the new one is appended
235/// at the end, so replaying `acc` in order still yields the same final state
236/// while its length stays bounded by the number of distinct selectors (no
237/// quadratic growth across loop rounds or iteration items).
238pub fn merge_writes(acc: &mut Vec<(Selector, Value)>, new: impl IntoIterator<Item = (Selector, Value)>) {
239    for (selector, value) in new {
240        if let Some(pos) = acc.iter().position(|(s, _)| *s == selector) {
241            acc.remove(pos);
242        }
243        acc.push((selector, value));
244    }
245}
246
247/// Request to execute a container's body once.
248#[derive(Debug)]
249pub struct SubgraphRequest {
250    /// Iteration index / loop round. Used for the child frame id.
251    pub index: usize,
252    /// Variables visible to the body. Usually a cheap clone of the context pool plus
253    /// the container's per-round values.
254    pub pool: VariablePool,
255    /// Resume a previously paused body run.
256    pub resume: Option<FrameSnapshot>,
257}
258
259/// Outcome of a container body run.
260///
261/// Produced once per body run and moved straight into the container node, so
262/// the size difference between variants does not matter.
263#[derive(Debug)]
264#[allow(clippy::large_enum_variant)]
265pub enum SubgraphResult {
266    Completed {
267        /// Final pool of the body run.
268        pool: VariablePool,
269        /// Response outputs accumulated in the body (answer text...).
270        outputs: IndexMap<String, Value>,
271        /// Writes to namespaces outside the body (container variables, conversation...),
272        /// in commit order. The container should forward them via [`NodeOutput::writes`].
273        writes: Vec<(Selector, Value)>,
274        usage: Usage,
275        /// Whether a `loop-end` (break) node completed in this body run.
276        broke: bool,
277    },
278    Failed {
279        error: NodeError,
280        usage: Usage,
281    },
282    Paused {
283        snapshot: FrameSnapshot,
284        reasons: Vec<PauseReason>,
285    },
286}
287
288/// Executes a container's child scope. Provided to container nodes by the engine.
289pub trait Subgraph: Send + Sync + fmt::Debug {
290    fn run(&self, request: SubgraphRequest) -> BoxFuture<'_, SubgraphResult>;
291}
292
293/// Time source used by the engine and nodes (retries, timeouts, elapsed time).
294pub trait Clock: Send + Sync + fmt::Debug {
295    /// Milliseconds since an arbitrary fixed origin.
296    fn now_ms(&self) -> u64;
297    /// Wait for `duration`.
298    fn sleep(&self, duration: Duration) -> BoxFuture<'static, ()>;
299    /// Whether [`Clock::sleep`] actually waits. Timeouts are only enforced when true.
300    fn supports_timers(&self) -> bool {
301        true
302    }
303}
304
305/// A clock without timers: sleeps complete immediately and timeouts are not enforced.
306/// Useful for tests and for executors without a timer facility.
307#[derive(Debug, Default, Clone, Copy)]
308pub struct NoTimerClock;
309
310impl Clock for NoTimerClock {
311    fn now_ms(&self) -> u64 {
312        system_now_ms()
313    }
314    fn sleep(&self, _duration: Duration) -> BoxFuture<'static, ()> {
315        Box::pin(futures::future::ready(()))
316    }
317    fn supports_timers(&self) -> bool {
318        false
319    }
320}
321
322/// Wall-clock milliseconds since the Unix epoch.
323///
324/// `wasm32-unknown-unknown` has no system clock (`SystemTime::now` panics there),
325/// so that target returns a monotonically increasing counter instead. Hosts on
326/// that target should supply their own [`Clock`] for meaningful timestamps.
327#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
328fn system_now_ms() -> u64 {
329    std::time::SystemTime::now()
330        .duration_since(std::time::UNIX_EPOCH)
331        .map(|d| u64::try_from(d.as_millis()).unwrap_or(u64::MAX))
332        .unwrap_or(0)
333}
334
335#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
336fn system_now_ms() -> u64 {
337    use std::sync::atomic::{AtomicU64, Ordering};
338    static COUNTER: AtomicU64 = AtomicU64::new(0);
339    COUNTER.fetch_add(1, Ordering::Relaxed)
340}
341
342/// Tokio-backed clock.
343#[cfg(feature = "tokio")]
344#[derive(Debug, Default, Clone, Copy)]
345pub struct TokioClock;
346
347#[cfg(feature = "tokio")]
348impl Clock for TokioClock {
349    fn now_ms(&self) -> u64 {
350        NoTimerClock.now_ms()
351    }
352    /// Outside a Tokio runtime this completes immediately instead of panicking
353    /// (and [`Clock::supports_timers`] reports `false`, so timeouts are not
354    /// enforced). Inside a runtime, the runtime must have its time driver enabled
355    /// (`enable_time()` / `enable_all()`).
356    fn sleep(&self, duration: Duration) -> BoxFuture<'static, ()> {
357        if tokio::runtime::Handle::try_current().is_ok() {
358            Box::pin(tokio::time::sleep(duration))
359        } else {
360            Box::pin(futures::future::ready(()))
361        }
362    }
363
364    /// `true` only when called from inside a Tokio runtime.
365    fn supports_timers(&self) -> bool {
366        tokio::runtime::Handle::try_current().is_ok()
367    }
368}
369
370/// The default clock for this build: [`TokioClock`] with the `tokio` feature, else [`NoTimerClock`].
371pub fn default_clock() -> Arc<dyn Clock> {
372    #[cfg(feature = "tokio")]
373    {
374        Arc::new(TokioClock)
375    }
376    #[cfg(not(feature = "tokio"))]
377    {
378        Arc::new(NoTimerClock)
379    }
380}
381
382/// Type-indexed registry of host services (LLM providers, HTTP clients, tool
383/// runtimes, file resolvers...). Nodes look services up at run time, so node
384/// factories stay pure and graphs can be built without any integration.
385#[derive(Default, Clone)]
386pub struct Services {
387    map: HashMap<TypeId, Arc<dyn Any + Send + Sync>>,
388}
389
390impl fmt::Debug for Services {
391    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
392        write!(f, "Services({} entries)", self.map.len())
393    }
394}
395
396impl Services {
397    pub fn new() -> Self {
398        Self::default()
399    }
400
401    /// Register a service. `T` is usually an `Arc<dyn Trait>` or a concrete struct.
402    pub fn insert<T: Any + Send + Sync>(&mut self, service: T) -> &mut Self {
403        self.map.insert(TypeId::of::<T>(), Arc::new(service));
404        self
405    }
406
407    /// Builder-style [`Services::insert`].
408    pub fn with<T: Any + Send + Sync>(mut self, service: T) -> Self {
409        self.insert(service);
410        self
411    }
412
413    pub fn get<T: Any + Send + Sync>(&self) -> Option<&T> {
414        self.map.get(&TypeId::of::<T>()).and_then(|s| s.downcast_ref::<T>())
415    }
416}
417
418/// Callback receiving events from nodes.
419pub type EventSink = Arc<dyn Fn(Event) + Send + Sync>;
420
421/// Everything a node may use while running. Cheap to clone.
422#[derive(Clone)]
423pub struct NodeContext {
424    pub node_id: Arc<str>,
425    pub exec_id: Arc<str>,
426    pub frame: FrameId,
427    /// 1-based attempt number (increments on retries).
428    pub attempt: u32,
429    /// Snapshot of the frame's variables at the time the node started.
430    pub pool: VariablePool,
431    pub services: Arc<Services>,
432    pub clock: Arc<dyn Clock>,
433    /// Present when the node is resumed after pausing.
434    pub resume: Option<Resume>,
435    /// Present for container nodes.
436    pub subgraph: Option<Arc<dyn Subgraph>>,
437    /// Absolute deadline of the current attempt in [`Clock::now_ms`] time, when
438    /// the node has an effective timeout. See [`NodeContext::remaining`].
439    pub deadline_ms: Option<u64>,
440    sink: EventSink,
441}
442
443impl fmt::Debug for NodeContext {
444    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
445        f.debug_struct("NodeContext")
446            .field("node_id", &self.node_id)
447            .field("exec_id", &self.exec_id)
448            .field("frame", &self.frame)
449            .field("attempt", &self.attempt)
450            .finish_non_exhaustive()
451    }
452}
453
454impl NodeContext {
455    /// Construct a context. Used by the engine and by node unit tests.
456    #[allow(clippy::too_many_arguments)]
457    pub fn new(
458        node_id: impl Into<Arc<str>>,
459        exec_id: impl Into<Arc<str>>,
460        frame: FrameId,
461        attempt: u32,
462        pool: VariablePool,
463        services: Arc<Services>,
464        clock: Arc<dyn Clock>,
465        sink: EventSink,
466    ) -> Self {
467        Self {
468            node_id: node_id.into(),
469            exec_id: exec_id.into(),
470            frame,
471            attempt,
472            pool,
473            services,
474            clock,
475            resume: None,
476            subgraph: None,
477            deadline_ms: None,
478            sink,
479        }
480    }
481
482    /// A context with an empty pool and a no-op sink, for unit tests.
483    pub fn for_test(node_id: &str, pool: VariablePool) -> Self {
484        Self::new(
485            node_id,
486            format!("{node_id}-exec"),
487            Arc::from(""),
488            1,
489            pool,
490            Arc::new(Services::new()),
491            Arc::new(NoTimerClock),
492            Arc::new(|_| {}),
493        )
494    }
495
496    pub fn with_services(mut self, services: Arc<Services>) -> Self {
497        self.services = services;
498        self
499    }
500
501    pub fn with_sink(mut self, sink: EventSink) -> Self {
502        self.sink = sink;
503        self
504    }
505
506    pub fn with_resume(mut self, resume: Option<Resume>) -> Self {
507        self.resume = resume;
508        self
509    }
510
511    pub fn with_subgraph(mut self, subgraph: Option<Arc<dyn Subgraph>>) -> Self {
512        self.subgraph = subgraph;
513        self
514    }
515
516    pub fn with_deadline(mut self, deadline_ms: Option<u64>) -> Self {
517        self.deadline_ms = deadline_ms;
518        self
519    }
520
521    /// Time left before the current attempt times out, if it has a deadline.
522    /// Nodes that block synchronously (e.g. an embedded interpreter) should
523    /// cap their own work by this.
524    pub fn remaining(&self) -> Option<Duration> {
525        self.deadline_ms.map(|deadline| Duration::from_millis(deadline.saturating_sub(self.clock.now_ms())))
526    }
527
528    /// Look up a host service.
529    pub fn service<T: Any + Send + Sync>(&self) -> Option<&T> {
530        self.services.get::<T>()
531    }
532
533    /// Look up a host service or fail with a descriptive error.
534    pub fn require_service<T: Any + Send + Sync>(&self, what: &str) -> Result<&T, NodeError> {
535        self.services.get::<T>().ok_or_else(|| NodeError::fatal("missing_service", format!("no {what} configured")))
536    }
537
538    /// Resolve a selector against the pool snapshot.
539    pub fn get(&self, selector: &Selector) -> Option<Value> {
540        self.pool.get(selector)
541    }
542
543    /// Stream an incremental chunk for output `field`.
544    ///
545    /// Allocates the field name for every chunk; nodes that stream many chunks
546    /// should keep the name in an `Arc<str>` and use [`NodeContext::chunk_shared`].
547    pub fn chunk(&self, field: &str, chunk: impl Into<String>) {
548        self.chunk_shared(&Arc::from(field), chunk);
549    }
550
551    /// Stream an incremental chunk for output `field`, sharing the field name
552    /// (no allocation besides the chunk text itself).
553    ///
554    /// ```
555    /// # use std::sync::Arc;
556    /// # let ctx = graphrt_core::NodeContext::for_test("n", graphrt_core::VariablePool::new());
557    /// let field: Arc<str> = Arc::from("text");
558    /// for token in ["Hel", "lo"] {
559    ///     ctx.chunk_shared(&field, token);
560    /// }
561    /// ```
562    pub fn chunk_shared(&self, field: &Arc<str>, chunk: impl Into<String>) {
563        (self.sink)(Event::NodeChunk {
564            frame: self.frame.clone(),
565            node_id: Arc::clone(&self.node_id),
566            exec_id: Arc::clone(&self.exec_id),
567            field: Arc::clone(field),
568            chunk: chunk.into(),
569        });
570    }
571
572    /// Report structured progress.
573    pub fn progress(&self, name: &str, data: Value) {
574        (self.sink)(Event::NodeProgress {
575            frame: self.frame.clone(),
576            node_id: Arc::clone(&self.node_id),
577            exec_id: Arc::clone(&self.exec_id),
578            name: name.to_owned(),
579            data,
580        });
581    }
582
583    /// Raw access to the event sink (used by container implementations).
584    pub fn sink(&self) -> &EventSink {
585        &self.sink
586    }
587}
588
589/// Builds a node from its document.
590pub type NodeFactory = Arc<dyn Fn(&NodeDoc) -> Result<Arc<dyn Node>, ConfigError> + Send + Sync>;
591
592/// Builds a node kind's catalog descriptor.
593pub type DescriptorFn = fn() -> crate::catalog::NodeDescriptor;
594
595/// A catalog descriptor, either given up front or built on first request.
596///
597/// Descriptors carry JSON Schemas and are only read by catalog consumers
598/// (`graphrt nodes`, `GET /v1/nodes`, builders), never while compiling or
599/// running a graph, so built-in kinds build theirs lazily: registering every
600/// built-in eagerly cost about half a millisecond of every process start.
601#[derive(Clone)]
602enum DescriptorSlot {
603    Ready(Box<crate::catalog::NodeDescriptor>),
604    Lazy(Arc<LazyDescriptor>),
605}
606
607struct LazyDescriptor {
608    build: DescriptorFn,
609    built: OnceLock<crate::catalog::NodeDescriptor>,
610}
611
612/// Maps node kinds (`llm`, `if-else`, ...) to factories.
613#[derive(Clone, Default)]
614pub struct Registry {
615    factories: HashMap<String, NodeFactory>,
616    descriptors: HashMap<String, DescriptorSlot>,
617}
618
619impl fmt::Debug for Registry {
620    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
621        let mut kinds: Vec<&String> = self.factories.keys().collect();
622        kinds.sort();
623        f.debug_struct("Registry").field("kinds", &kinds).finish()
624    }
625}
626
627impl Registry {
628    /// Empty registry.
629    pub fn new() -> Self {
630        Self::default()
631    }
632
633    /// Registry with every built-in core node.
634    pub fn with_builtins() -> Self {
635        let mut r = Self::new();
636        crate::nodes::register_builtins(&mut r);
637        r
638    }
639
640    /// Register (or replace) a factory for `kind`.
641    pub fn register<F>(&mut self, kind: &str, factory: F) -> &mut Self
642    where
643        F: Fn(&NodeDoc) -> Result<Arc<dyn Node>, ConfigError> + Send + Sync + 'static,
644    {
645        self.factories.insert(kind.to_owned(), Arc::new(factory));
646        self
647    }
648
649    /// Register (or replace) a factory together with its catalog descriptor.
650    /// The descriptor's `kind` is the registered node type.
651    pub fn register_described<F>(&mut self, descriptor: crate::catalog::NodeDescriptor, factory: F) -> &mut Self
652    where
653        F: Fn(&NodeDoc) -> Result<Arc<dyn Node>, ConfigError> + Send + Sync + 'static,
654    {
655        let kind = descriptor.kind.clone();
656        self.factories.insert(kind.clone(), Arc::new(factory));
657        self.descriptors.insert(kind, DescriptorSlot::Ready(Box::new(descriptor)));
658        self
659    }
660
661    /// Register a factory whose catalog descriptor is built by `descriptor` the
662    /// first time it is requested. Use this for kinds registered on every start
663    /// (built-ins), so processes that never list the catalog skip building it.
664    /// The built descriptor's `kind` must be `kind`.
665    pub fn register_lazily_described<F>(&mut self, kind: &str, descriptor: DescriptorFn, factory: F) -> &mut Self
666    where
667        F: Fn(&NodeDoc) -> Result<Arc<dyn Node>, ConfigError> + Send + Sync + 'static,
668    {
669        self.factories.insert(kind.to_owned(), Arc::new(factory));
670        let slot = LazyDescriptor { build: descriptor, built: OnceLock::new() };
671        self.descriptors.insert(kind.to_owned(), DescriptorSlot::Lazy(Arc::new(slot)));
672        self
673    }
674
675    /// Attach or replace the descriptor of an already-registered kind.
676    pub fn describe(&mut self, descriptor: crate::catalog::NodeDescriptor) -> &mut Self {
677        if self.factories.contains_key(&descriptor.kind) {
678            self.descriptors.insert(descriptor.kind.clone(), DescriptorSlot::Ready(Box::new(descriptor)));
679        }
680        self
681    }
682
683    /// Descriptor of a kind. Kinds registered without one get a bare descriptor.
684    pub fn descriptor(&self, kind: &str) -> Option<crate::catalog::NodeDescriptor> {
685        if !self.factories.contains_key(kind) {
686            return None;
687        }
688        let descriptor = match self.descriptors.get(kind) {
689            None => crate::catalog::NodeDescriptor::bare(kind),
690            Some(DescriptorSlot::Ready(descriptor)) => (**descriptor).clone(),
691            Some(DescriptorSlot::Lazy(slot)) => slot.built.get_or_init(slot.build).clone(),
692        };
693        Some(descriptor)
694    }
695
696    /// Borrowed descriptor of a kind registered with one (`None` for unknown
697    /// kinds and kinds registered without a descriptor). Builds a lazy
698    /// descriptor on first use.
699    pub fn descriptor_ref(&self, kind: &str) -> Option<&crate::catalog::NodeDescriptor> {
700        match self.descriptors.get(kind)? {
701            DescriptorSlot::Ready(descriptor) => Some(descriptor),
702            DescriptorSlot::Lazy(slot) => Some(slot.built.get_or_init(slot.build)),
703        }
704    }
705
706    /// Catalog of every registered kind, sorted by kind.
707    pub fn descriptors(&self) -> Vec<crate::catalog::NodeDescriptor> {
708        let mut kinds: Vec<&String> = self.factories.keys().collect();
709        kinds.sort();
710        kinds.into_iter().filter_map(|k| self.descriptor(k)).collect()
711    }
712
713    /// Register an alias resolving to an already-registered kind.
714    pub fn alias(&mut self, alias: &str, kind: &str) -> &mut Self {
715        if let Some(f) = self.factories.get(kind).cloned() {
716            self.factories.insert(alias.to_owned(), f);
717        }
718        self
719    }
720
721    pub fn contains(&self, kind: &str) -> bool {
722        self.factories.contains_key(kind)
723    }
724
725    pub fn kinds(&self) -> impl Iterator<Item = &str> {
726        self.factories.keys().map(String::as_str)
727    }
728
729    /// Build a node from its document.
730    pub fn build(&self, doc: &NodeDoc) -> Result<Arc<dyn Node>, ConfigError> {
731        let factory = self.factories.get(&doc.kind).ok_or_else(|| {
732            let suggestion = crate::validate::suggest(&doc.kind, self.kinds());
733            ConfigError::new(
734                doc,
735                format!("unknown node type `{}`{}", doc.kind, crate::validate::did_you_mean(&suggestion)),
736            )
737        })?;
738        factory(doc)
739    }
740}
741
742/// Helper for factories: parse the node config into `T`, mapping errors to [`ConfigError`].
743pub fn parse_config<T: serde::de::DeserializeOwned>(doc: &NodeDoc) -> Result<T, ConfigError> {
744    crate::dsl::parse_config_at(&doc.config).map_err(|(path, e)| {
745        let error = ConfigError::new(doc, e.to_string());
746        if path == "." { error } else { error.at_field(path) }
747    })
748}