1use crate::constants::{end, NodeId};
8use crate::error::Result;
9use crate::state::GraphState;
10use async_trait::async_trait;
11use std::collections::HashMap;
12use std::future::Future;
13use std::marker::PhantomData;
14use std::sync::Arc;
15
16#[derive(Clone)]
20pub enum Edge<S: GraphState> {
21 Normal {
23 from: NodeId,
25 to: NodeId,
27 },
28
29 Conditional {
31 from: NodeId,
33 router: Arc<dyn EdgeRouter<S>>,
35 path_map: Option<HashMap<String, NodeId>>,
37 },
38}
39
40impl<S: GraphState> Edge<S> {
41 pub fn normal(from: impl Into<NodeId>, to: impl Into<NodeId>) -> Self {
43 Self::Normal {
44 from: from.into(),
45 to: to.into(),
46 }
47 }
48
49 pub fn conditional<R: EdgeRouter<S> + 'static>(from: impl Into<NodeId>, router: R) -> Self {
51 Self::Conditional {
52 from: from.into(),
53 router: Arc::new(router),
54 path_map: None,
55 }
56 }
57
58 pub fn conditional_with_map<R: EdgeRouter<S> + 'static>(
60 from: impl Into<NodeId>,
61 router: R,
62 path_map: HashMap<String, NodeId>,
63 ) -> Self {
64 Self::Conditional {
65 from: from.into(),
66 router: Arc::new(router),
67 path_map: Some(path_map),
68 }
69 }
70
71 pub fn from(&self) -> &NodeId {
73 match self {
74 Self::Normal { from, .. } => from,
75 Self::Conditional { from, .. } => from,
76 }
77 }
78
79 pub fn is_conditional(&self) -> bool {
81 matches!(self, Self::Conditional { .. })
82 }
83}
84
85impl<S: GraphState> std::fmt::Debug for Edge<S> {
86 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
87 match self {
88 Self::Normal { from, to } => {
89 f.debug_struct("Edge::Normal")
90 .field("from", from)
91 .field("to", to)
92 .finish()
93 }
94 Self::Conditional { from, path_map, .. } => {
95 f.debug_struct("Edge::Conditional")
96 .field("from", from)
97 .field("path_map", path_map)
98 .finish()
99 }
100 }
101 }
102}
103
104#[derive(Debug, Clone)]
106pub enum RouteOutput {
107 One(NodeId),
109
110 Many(Vec<NodeId>),
112
113 End,
115}
116
117impl RouteOutput {
118 pub fn one(node: impl Into<NodeId>) -> Self {
120 Self::One(node.into())
121 }
122
123 pub fn many(nodes: impl IntoIterator<Item = impl Into<NodeId>>) -> Self {
125 Self::Many(nodes.into_iter().map(Into::into).collect())
126 }
127
128 pub fn end() -> Self {
130 Self::End
131 }
132
133 pub fn is_end(&self) -> bool {
135 match self {
136 Self::End => true,
137 Self::One(id) => id.is_end(),
138 Self::Many(ids) => ids.iter().all(|id| id.is_end()),
139 }
140 }
141
142 pub fn targets(&self) -> Vec<NodeId> {
144 match self {
145 Self::One(id) => vec![id.clone()],
146 Self::Many(ids) => ids.clone(),
147 Self::End => vec![end()],
148 }
149 }
150
151 pub fn into_nodes(self) -> Vec<NodeId> {
153 self.targets()
154 }
155}
156
157impl From<NodeId> for RouteOutput {
158 fn from(id: NodeId) -> Self {
159 Self::One(id)
160 }
161}
162
163impl From<&str> for RouteOutput {
164 fn from(s: &str) -> Self {
165 Self::One(NodeId::from(s))
166 }
167}
168
169impl From<String> for RouteOutput {
170 fn from(s: String) -> Self {
171 Self::One(NodeId::from(s))
172 }
173}
174
175impl From<Vec<NodeId>> for RouteOutput {
176 fn from(ids: Vec<NodeId>) -> Self {
177 if ids.is_empty() {
178 Self::End
179 } else {
180 Self::Many(ids)
181 }
182 }
183}
184
185#[async_trait]
207pub trait EdgeRouter<S: GraphState>: Send + Sync {
208 async fn route(&self, state: &S) -> Result<RouteOutput>;
210
211 fn description(&self) -> Option<&str> {
213 None
214 }
215}
216
217pub struct FnRouter<S, F>
219where
220 S: GraphState,
221 F: Fn(&S) -> RouteOutput + Send + Sync,
222{
223 func: F,
224 description: Option<String>,
225 _marker: PhantomData<S>,
226}
227
228impl<S, F> FnRouter<S, F>
229where
230 S: GraphState,
231 F: Fn(&S) -> RouteOutput + Send + Sync,
232{
233 pub fn new(func: F) -> Self {
235 Self {
236 func,
237 description: None,
238 _marker: PhantomData,
239 }
240 }
241
242 pub fn with_description(func: F, description: impl Into<String>) -> Self {
244 Self {
245 func,
246 description: Some(description.into()),
247 _marker: PhantomData,
248 }
249 }
250}
251
252#[async_trait]
253impl<S, F> EdgeRouter<S> for FnRouter<S, F>
254where
255 S: GraphState,
256 F: Fn(&S) -> RouteOutput + Send + Sync,
257{
258 async fn route(&self, state: &S) -> Result<RouteOutput> {
259 Ok((self.func)(state))
260 }
261
262 fn description(&self) -> Option<&str> {
263 self.description.as_deref()
264 }
265}
266
267pub struct AsyncFnRouter<S, F, Fut>
269where
270 S: GraphState,
271 F: Fn(&S) -> Fut + Send + Sync,
272 Fut: Future<Output = Result<RouteOutput>> + Send,
273{
274 func: F,
275 description: Option<String>,
276 _marker: PhantomData<fn(S) -> Fut>,
277}
278
279impl<S, F, Fut> AsyncFnRouter<S, F, Fut>
280where
281 S: GraphState,
282 F: Fn(&S) -> Fut + Send + Sync,
283 Fut: Future<Output = Result<RouteOutput>> + Send,
284{
285 pub fn new(func: F) -> Self {
287 Self {
288 func,
289 description: None,
290 _marker: PhantomData,
291 }
292 }
293
294 pub fn with_description(func: F, description: impl Into<String>) -> Self {
296 Self {
297 func,
298 description: Some(description.into()),
299 _marker: PhantomData,
300 }
301 }
302}
303
304#[async_trait]
305impl<S, F, Fut> EdgeRouter<S> for AsyncFnRouter<S, F, Fut>
306where
307 S: GraphState,
308 F: Fn(&S) -> Fut + Send + Sync,
309 Fut: Future<Output = Result<RouteOutput>> + Send,
310{
311 async fn route(&self, state: &S) -> Result<RouteOutput> {
312 (self.func)(state).await
313 }
314
315 fn description(&self) -> Option<&str> {
316 self.description.as_deref()
317 }
318}
319
320pub fn router_fn<S, F>(f: F) -> impl EdgeRouter<S>
336where
337 S: GraphState,
338 F: Fn(&S) -> RouteOutput + Send + Sync + 'static,
339{
340 FnRouter::new(f)
341}
342
343pub fn router_fn_named<S, F>(description: impl Into<String>, f: F) -> impl EdgeRouter<S>
345where
346 S: GraphState,
347 F: Fn(&S) -> RouteOutput + Send + Sync + 'static,
348{
349 FnRouter::with_description(f, description)
350}
351
352pub fn async_router_fn<S, F, Fut>(f: F) -> impl EdgeRouter<S>
365where
366 S: GraphState,
367 F: Fn(&S) -> Fut + Send + Sync + 'static,
368 Fut: Future<Output = Result<RouteOutput>> + Send + 'static,
369{
370 AsyncFnRouter::new(f)
371}
372
373pub type BoxedRouter<S> = Arc<dyn EdgeRouter<S>>;
375
376#[cfg(test)]
377mod tests {
378 use super::*;
379 use crate::channel::ChannelSpec;
380
381 #[derive(Clone, serde::Serialize, serde::Deserialize)]
382 struct TestState {
383 done: bool,
384 }
385
386 impl GraphState for TestState {
387 fn channels() -> std::collections::HashMap<String, ChannelSpec> {
388 let mut channels = std::collections::HashMap::new();
389 channels.insert("done".to_string(), ChannelSpec::LastValue);
390 channels
391 }
392 }
393
394 #[test]
395 fn test_edge_normal() {
396 let edge: Edge<TestState> = Edge::normal("a", "b");
397 assert_eq!(edge.from(), &NodeId::from("a"));
398 assert!(!edge.is_conditional());
399 }
400
401 #[test]
402 fn test_edge_conditional() {
403 let router = router_fn(|state: &TestState| {
404 if state.done {
405 RouteOutput::end()
406 } else {
407 RouteOutput::one("continue")
408 }
409 });
410
411 let edge: Edge<TestState> = Edge::conditional("a", router);
412 assert_eq!(edge.from(), &NodeId::from("a"));
413 assert!(edge.is_conditional());
414 }
415
416 #[test]
417 fn test_route_output_one() {
418 let route = RouteOutput::one("agent");
419 assert!(!route.is_end());
420 assert_eq!(route.targets().len(), 1);
421 }
422
423 #[test]
424 fn test_route_output_many() {
425 let route = RouteOutput::many(vec!["a", "b", "c"]);
426 assert!(!route.is_end());
427 assert_eq!(route.targets().len(), 3);
428 }
429
430 #[test]
431 fn test_route_output_end() {
432 let route = RouteOutput::end();
433 assert!(route.is_end());
434 }
435
436 #[test]
437 fn test_route_output_from_str() {
438 let route: RouteOutput = "agent".into();
439 assert!(matches!(route, RouteOutput::One(_)));
440 }
441
442 #[tokio::test]
443 async fn test_fn_router() {
444 let router = router_fn(|state: &TestState| {
445 if state.done {
446 RouteOutput::end()
447 } else {
448 RouteOutput::one("continue")
449 }
450 });
451
452 let state = TestState { done: false };
453 let result = router.route(&state).await.unwrap();
454 assert!(matches!(result, RouteOutput::One(_)));
455
456 let state = TestState { done: true };
457 let result = router.route(&state).await.unwrap();
458 assert!(result.is_end());
459 }
460
461 #[tokio::test]
462 async fn test_async_fn_router() {
463 let router = async_router_fn(|state: &TestState| {
464 let done = state.done;
465 async move {
466 if done {
467 Ok(RouteOutput::end())
468 } else {
469 Ok(RouteOutput::one("continue"))
470 }
471 }
472 });
473
474 let state = TestState { done: false };
475 let result = router.route(&state).await.unwrap();
476 assert!(matches!(result, RouteOutput::One(_)));
477 }
478}