use std::collections::{HashMap, HashSet};
use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::error::{Result, RustyError};
use crate::node::Node;
use crate::state::State;
pub const END: &str = "__end__";
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Route {
Node(String),
Send(Vec<Send>),
End,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Send {
pub node: String,
pub state: Value,
}
impl Send {
pub fn new(node: impl Into<String>, state: Value) -> Self {
Self {
node: node.into(),
state,
}
}
}
pub type ConditionalRouter = Arc<
dyn Fn(State) -> Pin<Box<dyn Future<Output = Result<Route>> + std::marker::Send>>
+ std::marker::Send
+ Sync,
>;
#[derive(Clone)]
pub enum Edge {
Direct { from: String, to: String },
Conditional {
from: String,
router: ConditionalRouter,
},
}
impl Edge {
pub fn from(&self) -> &str {
match self {
Edge::Direct { from, .. } | Edge::Conditional { from, .. } => from,
}
}
}
impl fmt::Debug for Edge {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Edge::Direct { from, to } => write!(f, "Edge::Direct({from} -> {to})"),
Edge::Conditional { from, .. } => write!(f, "Edge::Conditional({from} -> ?)"),
}
}
}
struct GraphInner {
nodes: HashMap<String, Arc<dyn Node>>,
edges: Vec<Edge>,
entry_point: String,
}
pub struct Graph {
inner: Arc<GraphInner>,
}
impl Clone for Graph {
fn clone(&self) -> Self {
Self {
inner: Arc::clone(&self.inner),
}
}
}
impl fmt::Debug for Graph {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Graph")
.field("nodes", &self.inner.nodes.keys().collect::<Vec<_>>())
.field("edges", &self.inner.edges)
.field("entry_point", &self.inner.entry_point)
.finish()
}
}
impl Graph {
pub fn entry_point(&self) -> &str {
&self.inner.entry_point
}
pub fn node(&self, name: &str) -> Option<Arc<dyn Node>> {
self.inner.nodes.get(name).cloned()
}
pub fn has_node(&self, name: &str) -> bool {
self.inner.nodes.contains_key(name)
}
pub fn node_names(&self) -> impl Iterator<Item = &str> {
self.inner.nodes.keys().map(String::as_str)
}
pub fn outgoing_edges(&self, from: &str) -> Vec<&Edge> {
self.inner
.edges
.iter()
.filter(|e| e.from() == from)
.collect()
}
pub fn edges(&self) -> &[Edge] {
&self.inner.edges
}
pub fn node_count(&self) -> usize {
self.inner.nodes.len()
}
pub fn topology_hash(&self) -> String {
let mut lines: Vec<String> =
Vec::with_capacity(self.inner.nodes.len() + self.inner.edges.len());
lines.extend(self.inner.nodes.keys().map(|name| format!("node:{name}")));
lines.extend(self.inner.edges.iter().map(|edge| match edge {
Edge::Direct { from, to } => format!("edge:{from}>{to}"),
Edge::Conditional { from, .. } => format!("edge:{from}>?"),
}));
lines.push(format!("entry:{}", self.inner.entry_point));
lines.sort_unstable();
crate::record::sha256_hex(lines.join("\n").as_bytes())
}
}
#[derive(Default)]
pub struct GraphBuilder {
nodes: HashMap<String, Arc<dyn Node>>,
edges: Vec<Edge>,
entry_point: Option<String>,
}
impl GraphBuilder {
pub fn new() -> Self {
Self::default()
}
pub fn add_node<N>(&mut self, name: impl Into<String>, node: N) -> &mut Self
where
N: Node + 'static,
{
self.nodes.insert(name.into(), Arc::new(node));
self
}
pub fn add_edge(&mut self, from: impl Into<String>, to: impl Into<String>) -> &mut Self {
self.edges.push(Edge::Direct {
from: from.into(),
to: to.into(),
});
self
}
pub fn add_conditional_edges<F, Fut>(&mut self, from: impl Into<String>, router: F) -> &mut Self
where
F: Fn(State) -> Fut + std::marker::Send + Sync + 'static,
Fut: Future<Output = Result<Route>> + std::marker::Send + 'static,
{
let router: ConditionalRouter = Arc::new(move |state| Box::pin(router(state)));
self.edges.push(Edge::Conditional {
from: from.into(),
router,
});
self
}
pub fn set_entry_point(&mut self, name: impl Into<String>) -> &mut Self {
self.entry_point = Some(name.into());
self
}
pub fn compile(self) -> Result<Graph> {
if self.nodes.is_empty() {
return Err(RustyError::Graph(
"cannot compile an empty graph: register at least one node".into(),
));
}
for name in self.nodes.keys() {
if name == END || name.starts_with("__") {
return Err(RustyError::Graph(format!(
"node name `{name}` is reserved (`{END}` and `__`-prefixed names \
form the engine's sentinel namespace)"
)));
}
}
let entry_point = self.entry_point.ok_or_else(|| {
RustyError::Graph("no entry point set: call set_entry_point()".into())
})?;
if !self.nodes.contains_key(&entry_point) {
return Err(RustyError::Graph(format!(
"entry point `{entry_point}` does not reference a known node"
)));
}
let mut direct_edges: HashSet<(&str, &str)> = HashSet::new();
let mut direct_sources: HashSet<&str> = HashSet::new();
let mut conditional_sources: HashSet<&str> = HashSet::new();
for edge in &self.edges {
let from = edge.from();
if !self.nodes.contains_key(from) {
return Err(RustyError::Graph(format!(
"edge source `{from}` does not reference a known node"
)));
}
match edge {
Edge::Direct { to, .. } => {
if !self.nodes.contains_key(to) {
return Err(RustyError::Graph(format!(
"edge target `{to}` (from `{from}`) does not reference a known node"
)));
}
if !direct_edges.insert((from, to.as_str())) {
return Err(RustyError::Graph(format!(
"duplicate edge `{from} -> {to}`: the target would be \
activated twice in one super-step"
)));
}
direct_sources.insert(from);
}
Edge::Conditional { .. } => {
if !conditional_sources.insert(from) {
return Err(RustyError::Graph(format!(
"node `{from}` has multiple conditional edges; only one \
router per source node is allowed"
)));
}
}
}
}
if let Some(from) = direct_sources.intersection(&conditional_sources).next() {
return Err(RustyError::Graph(format!(
"node `{from}` has both static and conditional edges; routing would \
be ambiguous — use one kind per source node"
)));
}
Ok(Graph {
inner: Arc::new(GraphInner {
nodes: self.nodes,
edges: self.edges,
entry_point,
}),
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::node::NodeOutput;
use serde_json::json;
async fn ok_node(_ctx: crate::node::NodeContext) -> Result<NodeOutput> {
Ok(NodeOutput::empty())
}
#[test]
fn compile_rejects_empty_graph() {
let err = GraphBuilder::new().compile().unwrap_err();
assert!(matches!(err, RustyError::Graph(_)));
}
#[test]
fn compile_rejects_missing_entry_point() {
let mut b = GraphBuilder::new();
b.add_node("a", ok_node);
let err = b.compile().unwrap_err();
assert!(matches!(err, RustyError::Graph(_)));
}
#[test]
fn compile_rejects_unknown_entry_point() {
let mut b = GraphBuilder::new();
b.add_node("a", ok_node);
b.set_entry_point("nope");
assert!(b.compile().is_err());
}
#[test]
fn compile_rejects_dangling_edges() {
let mut b = GraphBuilder::new();
b.add_node("a", ok_node);
b.set_entry_point("a");
b.add_edge("a", "ghost");
assert!(b.compile().is_err());
let mut b = GraphBuilder::new();
b.add_node("a", ok_node);
b.set_entry_point("a");
b.add_conditional_edges("ghost", |_s| async { Ok(Route::End) });
assert!(b.compile().is_err());
}
#[tokio::test]
async fn compile_accepts_valid_graph() {
let mut b = GraphBuilder::new();
b.add_node("agent", ok_node);
b.add_node("tools", ok_node);
b.set_entry_point("agent");
b.add_edge("tools", "agent");
b.add_conditional_edges("agent", |state| async move {
Ok(if state.contains("done") {
Route::End
} else {
Route::Node("tools".into())
})
});
let graph = b.compile().unwrap();
assert_eq!(graph.entry_point(), "agent");
assert_eq!(graph.node_count(), 2);
assert!(graph.has_node("tools"));
assert_eq!(graph.outgoing_edges("agent").len(), 1);
assert_eq!(graph.outgoing_edges("tools").len(), 1);
let g2 = graph.clone();
assert!(g2.node("agent").is_some());
let edges = graph.outgoing_edges("agent");
let route = match edges[0] {
Edge::Conditional { router, .. } => {
router(State::from_value(json!({"done": true})).unwrap()).await
}
_ => panic!("expected conditional edge"),
};
assert_eq!(route.unwrap(), Route::End);
}
#[test]
fn compile_rejects_duplicate_direct_edges() {
let mut b = GraphBuilder::new();
b.add_node("a", ok_node);
b.add_node("b", ok_node);
b.set_entry_point("a");
b.add_edge("a", "b");
b.add_edge("a", "b");
let err = b.compile().unwrap_err();
assert!(matches!(err, RustyError::Graph(_)));
}
#[test]
fn compile_rejects_duplicate_conditional_edges() {
let mut b = GraphBuilder::new();
b.add_node("a", ok_node);
b.set_entry_point("a");
b.add_conditional_edges("a", |_s| async { Ok(Route::End) });
b.add_conditional_edges("a", |_s| async { Ok(Route::End) });
let err = b.compile().unwrap_err();
assert!(matches!(err, RustyError::Graph(_)));
}
#[test]
fn compile_rejects_mixed_static_and_conditional_edges() {
let mut b = GraphBuilder::new();
b.add_node("a", ok_node);
b.add_node("b", ok_node);
b.set_entry_point("a");
b.add_edge("a", "b");
b.add_conditional_edges("a", |_s| async { Ok(Route::End) });
let err = b.compile().unwrap_err();
assert!(matches!(err, RustyError::Graph(_)));
}
#[test]
fn compile_rejects_reserved_node_names() {
for name in [END, "__internal"] {
let mut b = GraphBuilder::new();
b.add_node(name, ok_node);
b.set_entry_point(name);
let err = b.compile().unwrap_err();
assert!(matches!(err, RustyError::Graph(_)), "name: {name}");
}
}
}