use crate::constants::NodeId;
use crate::error::Result;
use crate::state::GraphState;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::future::Future;
use std::marker::PhantomData;
use std::sync::Arc;
#[derive(Debug, Clone)]
pub enum NodeOutput {
Update(serde_json::Value),
Command(Command),
None,
}
impl NodeOutput {
pub fn update(value: serde_json::Value) -> Self {
Self::Update(value)
}
pub fn update_from<T: Serialize>(value: &T) -> Result<Self> {
Ok(Self::Update(serde_json::to_value(value)?))
}
pub fn command(cmd: Command) -> Self {
Self::Command(cmd)
}
pub fn none() -> Self {
Self::None
}
pub fn has_update(&self) -> bool {
match self {
Self::Update(v) => !v.is_null() && v != &serde_json::Value::Object(Default::default()),
Self::Command(cmd) => cmd.update.is_some(),
Self::None => false,
}
}
pub fn get_update(&self) -> Option<&serde_json::Value> {
match self {
Self::Update(v) => Some(v),
Self::Command(cmd) => cmd.update.as_ref(),
Self::None => None,
}
}
pub fn get_goto(&self) -> Option<&CommandGoto> {
match self {
Self::Command(cmd) => cmd.goto.as_ref(),
_ => None,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Command {
#[serde(skip_serializing_if = "Option::is_none")]
pub update: Option<serde_json::Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub goto: Option<CommandGoto>,
#[serde(skip_serializing_if = "Option::is_none")]
pub resume: Option<serde_json::Value>,
}
impl Command {
pub fn new() -> Self {
Self {
update: None,
goto: None,
resume: None,
}
}
pub fn with_update(update: serde_json::Value) -> Self {
Self {
update: Some(update),
goto: None,
resume: None,
}
}
pub fn with_goto(goto: impl Into<CommandGoto>) -> Self {
Self {
update: None,
goto: Some(goto.into()),
resume: None,
}
}
pub fn update(mut self, update: serde_json::Value) -> Self {
self.update = Some(update);
self
}
pub fn goto(mut self, target: impl Into<CommandGoto>) -> Self {
self.goto = Some(target.into());
self
}
pub fn resume(mut self, value: serde_json::Value) -> Self {
self.resume = Some(value);
self
}
}
impl Default for Command {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum CommandGoto {
One(NodeId),
Many(Vec<NodeId>),
}
impl CommandGoto {
pub fn one(node: impl Into<NodeId>) -> Self {
Self::One(node.into())
}
pub fn many(nodes: impl IntoIterator<Item = impl Into<NodeId>>) -> Self {
Self::Many(nodes.into_iter().map(Into::into).collect())
}
pub fn is_end(&self) -> bool {
match self {
Self::One(id) => id.is_end(),
Self::Many(ids) => ids.iter().all(|id| id.is_end()),
}
}
pub fn targets(&self) -> Vec<&NodeId> {
match self {
Self::One(id) => vec![id],
Self::Many(ids) => ids.iter().collect(),
}
}
}
impl From<NodeId> for CommandGoto {
fn from(id: NodeId) -> Self {
Self::One(id)
}
}
impl From<&str> for CommandGoto {
fn from(s: &str) -> Self {
Self::One(NodeId::from(s))
}
}
impl From<String> for CommandGoto {
fn from(s: String) -> Self {
Self::One(NodeId::from(s))
}
}
impl From<Vec<NodeId>> for CommandGoto {
fn from(ids: Vec<NodeId>) -> Self {
Self::Many(ids)
}
}
pub use crate::config::RunnableConfig;
#[async_trait]
pub trait Node<S: GraphState>: Send + Sync {
async fn execute(&self, state: &S, config: &RunnableConfig) -> Result<NodeOutput>;
fn name(&self) -> Option<&str> {
None
}
fn retry_policy(&self) -> RetryPolicy {
RetryPolicy::None
}
}
#[derive(Debug, Clone, Default)]
pub enum RetryPolicy {
#[default]
None,
Exponential {
max_retries: usize,
initial_delay_ms: u64,
max_delay_ms: u64,
},
Fixed {
max_retries: usize,
delay_ms: u64,
},
}
pub struct FnNode<S, F, Fut>
where
S: GraphState,
F: Fn(&S, &RunnableConfig) -> Fut + Send + Sync,
Fut: Future<Output = Result<NodeOutput>> + Send,
{
func: F,
name: Option<String>,
_marker: PhantomData<fn(S) -> Fut>,
}
impl<S, F, Fut> FnNode<S, F, Fut>
where
S: GraphState,
F: Fn(&S, &RunnableConfig) -> Fut + Send + Sync,
Fut: Future<Output = Result<NodeOutput>> + Send,
{
pub fn new(func: F) -> Self {
Self {
func,
name: None,
_marker: PhantomData,
}
}
pub fn with_name(func: F, name: impl Into<String>) -> Self {
Self {
func,
name: Some(name.into()),
_marker: PhantomData,
}
}
}
#[async_trait]
impl<S, F, Fut> Node<S> for FnNode<S, F, Fut>
where
S: GraphState,
F: Fn(&S, &RunnableConfig) -> Fut + Send + Sync,
Fut: Future<Output = Result<NodeOutput>> + Send,
{
async fn execute(&self, state: &S, config: &RunnableConfig) -> Result<NodeOutput> {
(self.func)(state, config).await
}
fn name(&self) -> Option<&str> {
self.name.as_deref()
}
}
pub fn node_fn<S, F, Fut>(f: F) -> impl Node<S>
where
S: GraphState,
F: Fn(&S, &RunnableConfig) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<NodeOutput>> + Send + 'static,
{
FnNode::new(f)
}
pub fn node_fn_named<S, F, Fut>(name: impl Into<String>, f: F) -> impl Node<S>
where
S: GraphState,
F: Fn(&S, &RunnableConfig) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<NodeOutput>> + Send + 'static,
{
FnNode::with_name(f, name)
}
pub type BoxedNode<S> = Arc<dyn Node<S>>;
#[cfg(test)]
mod tests {
use super::*;
use crate::channel::ChannelSpec;
use std::collections::HashMap;
#[derive(Clone, serde::Serialize, serde::Deserialize)]
struct TestState {
counter: i32,
}
impl GraphState for TestState {
fn channels() -> HashMap<String, ChannelSpec> {
let mut channels = HashMap::new();
channels.insert("counter".to_string(), ChannelSpec::LastValue);
channels
}
}
#[test]
fn test_node_output_update() {
let output = NodeOutput::update(serde_json::json!({"counter": 42}));
assert!(output.has_update());
assert!(matches!(output, NodeOutput::Update(_)));
}
#[test]
fn test_node_output_none() {
let output = NodeOutput::none();
assert!(!output.has_update());
}
#[test]
fn test_command_builder() {
let cmd = Command::new()
.update(serde_json::json!({"counter": 100}))
.goto("next_node");
assert!(cmd.update.is_some());
assert!(cmd.goto.is_some());
}
#[test]
fn test_command_goto_one() {
let goto = CommandGoto::one("agent");
assert!(!goto.is_end());
assert_eq!(goto.targets().len(), 1);
}
#[test]
fn test_command_goto_many() {
let goto = CommandGoto::many(vec!["a", "b", "c"]);
assert!(!goto.is_end());
assert_eq!(goto.targets().len(), 3);
}
#[test]
fn test_command_goto_from_str() {
let goto: CommandGoto = "agent".into();
assert!(matches!(goto, CommandGoto::One(_)));
}
#[tokio::test]
async fn test_fn_node() {
let node = node_fn(|state: &TestState, _config: &RunnableConfig| {
let counter = state.counter;
async move {
Ok(NodeOutput::update(serde_json::json!({
"counter": counter + 1
})))
}
});
let state = TestState { counter: 10 };
let config = RunnableConfig::new();
let output = node.execute(&state, &config).await.unwrap();
assert!(output.has_update());
if let NodeOutput::Update(value) = output {
assert_eq!(value["counter"], 11);
}
}
#[test]
fn test_retry_policy_default() {
let policy = RetryPolicy::default();
assert!(matches!(policy, RetryPolicy::None));
}
}