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