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