Skip to main content

regula_core/
node.rs

1//! Node trait and related types.
2//!
3//! Nodes are the fundamental building blocks of a REGULA graph. Each node
4//! is an async function that receives state and produces updates.
5
6use crate::constants::NodeId;
7use crate::error::Result;
8use crate::state::GraphState;
9use async_trait::async_trait;
10use serde::{Deserialize, Serialize};
11use std::future::Future;
12use std::marker::PhantomData;
13use std::sync::Arc;
14
15/// The output from a node execution.
16///
17/// Nodes can return either a simple state update or a command that
18/// includes routing information.
19#[derive(Debug, Clone)]
20pub enum NodeOutput {
21    /// A partial state update to be merged into the current state.
22    Update(serde_json::Value),
23
24    /// A command that includes both state update and routing.
25    Command(Command),
26
27    /// No output - the state remains unchanged.
28    None,
29}
30
31impl NodeOutput {
32    /// Create an update output from a JSON value.
33    pub fn update(value: serde_json::Value) -> Self {
34        Self::Update(value)
35    }
36
37    /// Create an update output, serializing the given value.
38    pub fn update_from<T: Serialize>(value: &T) -> Result<Self> {
39        Ok(Self::Update(serde_json::to_value(value)?))
40    }
41
42    /// Create a command output.
43    pub fn command(cmd: Command) -> Self {
44        Self::Command(cmd)
45    }
46
47    /// Create a no-op output.
48    pub fn none() -> Self {
49        Self::None
50    }
51
52    /// Check if this output has state updates.
53    pub fn has_update(&self) -> bool {
54        match self {
55            Self::Update(v) => !v.is_null() && v != &serde_json::Value::Object(Default::default()),
56            Self::Command(cmd) => cmd.update.is_some(),
57            Self::None => false,
58        }
59    }
60
61    /// Get the state update, if any.
62    pub fn get_update(&self) -> Option<&serde_json::Value> {
63        match self {
64            Self::Update(v) => Some(v),
65            Self::Command(cmd) => cmd.update.as_ref(),
66            Self::None => None,
67        }
68    }
69
70    /// Get routing from a command, if any.
71    pub fn get_goto(&self) -> Option<&CommandGoto> {
72        match self {
73            Self::Command(cmd) => cmd.goto.as_ref(),
74            _ => None,
75        }
76    }
77}
78
79/// A command that combines state update with explicit routing.
80///
81/// Commands allow nodes to control which node(s) execute next,
82/// overriding the graph's edge definitions.
83#[derive(Debug, Clone, Serialize, Deserialize)]
84pub struct Command {
85    /// State update to apply.
86    #[serde(skip_serializing_if = "Option::is_none")]
87    pub update: Option<serde_json::Value>,
88
89    /// Explicit next node(s) to execute.
90    #[serde(skip_serializing_if = "Option::is_none")]
91    pub goto: Option<CommandGoto>,
92
93    /// Value to resume with (for interrupt handling).
94    #[serde(skip_serializing_if = "Option::is_none")]
95    pub resume: Option<serde_json::Value>,
96}
97
98impl Command {
99    /// Create a new empty command.
100    pub fn new() -> Self {
101        Self {
102            update: None,
103            goto: None,
104            resume: None,
105        }
106    }
107
108    /// Create a command with a state update.
109    pub fn with_update(update: serde_json::Value) -> Self {
110        Self {
111            update: Some(update),
112            goto: None,
113            resume: None,
114        }
115    }
116
117    /// Create a command with a goto target.
118    pub fn with_goto(goto: impl Into<CommandGoto>) -> Self {
119        Self {
120            update: None,
121            goto: Some(goto.into()),
122            resume: None,
123        }
124    }
125
126    /// Add a state update to this command.
127    pub fn update(mut self, update: serde_json::Value) -> Self {
128        self.update = Some(update);
129        self
130    }
131
132    /// Add a goto target to this command.
133    pub fn goto(mut self, target: impl Into<CommandGoto>) -> Self {
134        self.goto = Some(target.into());
135        self
136    }
137
138    /// Add a resume value to this command.
139    pub fn resume(mut self, value: serde_json::Value) -> Self {
140        self.resume = Some(value);
141        self
142    }
143}
144
145impl Default for Command {
146    fn default() -> Self {
147        Self::new()
148    }
149}
150
151/// Target for command routing.
152#[derive(Debug, Clone, Serialize, Deserialize)]
153#[serde(untagged)]
154pub enum CommandGoto {
155    /// Go to a single node.
156    One(NodeId),
157
158    /// Go to multiple nodes in parallel.
159    Many(Vec<NodeId>),
160}
161
162impl CommandGoto {
163    /// Create a goto to a single node.
164    pub fn one(node: impl Into<NodeId>) -> Self {
165        Self::One(node.into())
166    }
167
168    /// Create a goto to multiple nodes.
169    pub fn many(nodes: impl IntoIterator<Item = impl Into<NodeId>>) -> Self {
170        Self::Many(nodes.into_iter().map(Into::into).collect())
171    }
172
173    /// Check if this goto ends the graph.
174    pub fn is_end(&self) -> bool {
175        match self {
176            Self::One(id) => id.is_end(),
177            Self::Many(ids) => ids.iter().all(|id| id.is_end()),
178        }
179    }
180
181    /// Get all target node IDs.
182    pub fn targets(&self) -> Vec<&NodeId> {
183        match self {
184            Self::One(id) => vec![id],
185            Self::Many(ids) => ids.iter().collect(),
186        }
187    }
188}
189
190impl From<NodeId> for CommandGoto {
191    fn from(id: NodeId) -> Self {
192        Self::One(id)
193    }
194}
195
196impl From<&str> for CommandGoto {
197    fn from(s: &str) -> Self {
198        Self::One(NodeId::from(s))
199    }
200}
201
202impl From<String> for CommandGoto {
203    fn from(s: String) -> Self {
204        Self::One(NodeId::from(s))
205    }
206}
207
208impl From<Vec<NodeId>> for CommandGoto {
209    fn from(ids: Vec<NodeId>) -> Self {
210        Self::Many(ids)
211    }
212}
213
214/// Configuration passed to nodes during execution.
215///
216/// This is a re-export from the config module, included here
217/// for convenience in node signatures.
218pub use crate::config::RunnableConfig;
219
220/// Trait for graph nodes.
221///
222/// Nodes are async functions that receive the current state and configuration,
223/// and return a state update or command.
224///
225/// # Type Parameters
226///
227/// - `S`: The state type for this graph.
228///
229/// # Examples
230///
231/// ```ignore
232/// use regula_core::{Node, NodeOutput, GraphState, RunnableConfig, Result};
233/// use async_trait::async_trait;
234///
235/// struct MyNode;
236///
237/// #[async_trait]
238/// impl<S: GraphState> Node<S> for MyNode {
239///     async fn execute(&self, state: &S, config: &RunnableConfig) -> Result<NodeOutput> {
240///         // Process state and return update
241///         Ok(NodeOutput::update(serde_json::json!({
242///             "counter": 42
243///         })))
244///     }
245/// }
246/// ```
247#[async_trait]
248pub trait Node<S: GraphState>: Send + Sync {
249    /// Execute the node with the current state.
250    ///
251    /// # Arguments
252    ///
253    /// - `state`: The current graph state.
254    /// - `config`: Runtime configuration and context.
255    ///
256    /// # Returns
257    ///
258    /// A `NodeOutput` containing state updates and/or routing commands.
259    async fn execute(&self, state: &S, config: &RunnableConfig) -> Result<NodeOutput>;
260
261    /// Get the name of this node (for debugging/tracing).
262    fn name(&self) -> Option<&str> {
263        None
264    }
265
266    /// Check if this node should be retried on failure.
267    fn retry_policy(&self) -> RetryPolicy {
268        RetryPolicy::None
269    }
270}
271
272/// Retry policy for node execution.
273#[derive(Debug, Clone, Default)]
274pub enum RetryPolicy {
275    /// No retries.
276    #[default]
277    None,
278
279    /// Retry with exponential backoff.
280    Exponential {
281        /// Maximum number of retries.
282        max_retries: usize,
283        /// Initial delay in milliseconds.
284        initial_delay_ms: u64,
285        /// Maximum delay in milliseconds.
286        max_delay_ms: u64,
287    },
288
289    /// Retry with fixed delay.
290    Fixed {
291        /// Maximum number of retries.
292        max_retries: usize,
293        /// Delay between retries in milliseconds.
294        delay_ms: u64,
295    },
296}
297
298/// A node created from an async function.
299pub struct FnNode<S, F, Fut>
300where
301    S: GraphState,
302    F: Fn(&S, &RunnableConfig) -> Fut + Send + Sync,
303    Fut: Future<Output = Result<NodeOutput>> + Send,
304{
305    func: F,
306    name: Option<String>,
307    _marker: PhantomData<fn(S) -> Fut>,
308}
309
310impl<S, F, Fut> FnNode<S, F, Fut>
311where
312    S: GraphState,
313    F: Fn(&S, &RunnableConfig) -> Fut + Send + Sync,
314    Fut: Future<Output = Result<NodeOutput>> + Send,
315{
316    /// Create a new function node.
317    pub fn new(func: F) -> Self {
318        Self {
319            func,
320            name: None,
321            _marker: PhantomData,
322        }
323    }
324
325    /// Create a new function node with a name.
326    pub fn with_name(func: F, name: impl Into<String>) -> Self {
327        Self {
328            func,
329            name: Some(name.into()),
330            _marker: PhantomData,
331        }
332    }
333}
334
335#[async_trait]
336impl<S, F, Fut> Node<S> for FnNode<S, F, Fut>
337where
338    S: GraphState,
339    F: Fn(&S, &RunnableConfig) -> Fut + Send + Sync,
340    Fut: Future<Output = Result<NodeOutput>> + Send,
341{
342    async fn execute(&self, state: &S, config: &RunnableConfig) -> Result<NodeOutput> {
343        (self.func)(state, config).await
344    }
345
346    fn name(&self) -> Option<&str> {
347        self.name.as_deref()
348    }
349}
350
351/// Create a node from an async function.
352///
353/// This is a convenience function to create nodes from closures or
354/// async functions without implementing the `Node` trait manually.
355///
356/// # Examples
357///
358/// ```ignore
359/// use regula_core::{node_fn, NodeOutput, Result};
360///
361/// let my_node = node_fn(|state: &MyState, config: &RunnableConfig| async move {
362///     Ok(NodeOutput::update(serde_json::json!({
363///         "counter": state.counter + 1
364///     })))
365/// });
366/// ```
367pub fn node_fn<S, F, Fut>(f: F) -> impl Node<S>
368where
369    S: GraphState,
370    F: Fn(&S, &RunnableConfig) -> Fut + Send + Sync + 'static,
371    Fut: Future<Output = Result<NodeOutput>> + Send + 'static,
372{
373    FnNode::new(f)
374}
375
376/// Create a named node from an async function.
377pub fn node_fn_named<S, F, Fut>(name: impl Into<String>, f: F) -> impl Node<S>
378where
379    S: GraphState,
380    F: Fn(&S, &RunnableConfig) -> Fut + Send + Sync + 'static,
381    Fut: Future<Output = Result<NodeOutput>> + Send + 'static,
382{
383    FnNode::with_name(f, name)
384}
385
386/// A boxed node for type erasure.
387pub type BoxedNode<S> = Arc<dyn Node<S>>;
388
389#[cfg(test)]
390mod tests {
391    use super::*;
392    use crate::channel::ChannelSpec;
393    use std::collections::HashMap;
394
395    #[derive(Clone, serde::Serialize, serde::Deserialize)]
396    struct TestState {
397        counter: i32,
398    }
399
400    impl GraphState for TestState {
401        fn channels() -> HashMap<String, ChannelSpec> {
402            let mut channels = HashMap::new();
403            channels.insert("counter".to_string(), ChannelSpec::LastValue);
404            channels
405        }
406    }
407
408    #[test]
409    fn test_node_output_update() {
410        let output = NodeOutput::update(serde_json::json!({"counter": 42}));
411        assert!(output.has_update());
412        assert!(matches!(output, NodeOutput::Update(_)));
413    }
414
415    #[test]
416    fn test_node_output_none() {
417        let output = NodeOutput::none();
418        assert!(!output.has_update());
419    }
420
421    #[test]
422    fn test_command_builder() {
423        let cmd = Command::new()
424            .update(serde_json::json!({"counter": 100}))
425            .goto("next_node");
426
427        assert!(cmd.update.is_some());
428        assert!(cmd.goto.is_some());
429    }
430
431    #[test]
432    fn test_command_goto_one() {
433        let goto = CommandGoto::one("agent");
434        assert!(!goto.is_end());
435        assert_eq!(goto.targets().len(), 1);
436    }
437
438    #[test]
439    fn test_command_goto_many() {
440        let goto = CommandGoto::many(vec!["a", "b", "c"]);
441        assert!(!goto.is_end());
442        assert_eq!(goto.targets().len(), 3);
443    }
444
445    #[test]
446    fn test_command_goto_from_str() {
447        let goto: CommandGoto = "agent".into();
448        assert!(matches!(goto, CommandGoto::One(_)));
449    }
450
451    #[tokio::test]
452    async fn test_fn_node() {
453        let node = node_fn(|state: &TestState, _config: &RunnableConfig| {
454            let counter = state.counter;
455            async move {
456                Ok(NodeOutput::update(serde_json::json!({
457                    "counter": counter + 1
458                })))
459            }
460        });
461
462        let state = TestState { counter: 10 };
463        let config = RunnableConfig::new();
464
465        let output = node.execute(&state, &config).await.unwrap();
466        assert!(output.has_update());
467
468        if let NodeOutput::Update(value) = output {
469            assert_eq!(value["counter"], 11);
470        }
471    }
472
473    #[test]
474    fn test_retry_policy_default() {
475        let policy = RetryPolicy::default();
476        assert!(matches!(policy, RetryPolicy::None));
477    }
478}