1use 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#[derive(Debug, Clone)]
20pub enum NodeOutput {
21 Update(serde_json::Value),
23
24 Command(Command),
26
27 None,
29}
30
31impl NodeOutput {
32 pub fn update(value: serde_json::Value) -> Self {
34 Self::Update(value)
35 }
36
37 pub fn update_from<T: Serialize>(value: &T) -> Result<Self> {
39 Ok(Self::Update(serde_json::to_value(value)?))
40 }
41
42 pub fn command(cmd: Command) -> Self {
44 Self::Command(cmd)
45 }
46
47 pub fn none() -> Self {
49 Self::None
50 }
51
52 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 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 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#[derive(Debug, Clone, Serialize, Deserialize)]
84pub struct Command {
85 #[serde(skip_serializing_if = "Option::is_none")]
87 pub update: Option<serde_json::Value>,
88
89 #[serde(skip_serializing_if = "Option::is_none")]
91 pub goto: Option<CommandGoto>,
92
93 #[serde(skip_serializing_if = "Option::is_none")]
95 pub resume: Option<serde_json::Value>,
96}
97
98impl Command {
99 pub fn new() -> Self {
101 Self {
102 update: None,
103 goto: None,
104 resume: None,
105 }
106 }
107
108 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 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 pub fn update(mut self, update: serde_json::Value) -> Self {
128 self.update = Some(update);
129 self
130 }
131
132 pub fn goto(mut self, target: impl Into<CommandGoto>) -> Self {
134 self.goto = Some(target.into());
135 self
136 }
137
138 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#[derive(Debug, Clone, Serialize, Deserialize)]
153#[serde(untagged)]
154pub enum CommandGoto {
155 One(NodeId),
157
158 Many(Vec<NodeId>),
160}
161
162impl CommandGoto {
163 pub fn one(node: impl Into<NodeId>) -> Self {
165 Self::One(node.into())
166 }
167
168 pub fn many(nodes: impl IntoIterator<Item = impl Into<NodeId>>) -> Self {
170 Self::Many(nodes.into_iter().map(Into::into).collect())
171 }
172
173 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 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
214pub use crate::config::RunnableConfig;
219
220#[async_trait]
248pub trait Node<S: GraphState>: Send + Sync {
249 async fn execute(&self, state: &S, config: &RunnableConfig) -> Result<NodeOutput>;
260
261 fn name(&self) -> Option<&str> {
263 None
264 }
265
266 fn retry_policy(&self) -> RetryPolicy {
268 RetryPolicy::None
269 }
270}
271
272#[derive(Debug, Clone, Default)]
274pub enum RetryPolicy {
275 #[default]
277 None,
278
279 Exponential {
281 max_retries: usize,
283 initial_delay_ms: u64,
285 max_delay_ms: u64,
287 },
288
289 Fixed {
291 max_retries: usize,
293 delay_ms: u64,
295 },
296}
297
298pub 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 pub fn new(func: F) -> Self {
318 Self {
319 func,
320 name: None,
321 _marker: PhantomData,
322 }
323 }
324
325 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
351pub 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
376pub 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
386pub 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}