Skip to main content

regula_core/
edge.rs

1//! Edge types and routing logic.
2//!
3//! Edges define the control flow between nodes in a REGULA graph.
4//! Normal edges provide fixed routing, while conditional edges use
5//! a router function to determine the next node(s) dynamically.
6
7use 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/// An edge in the state graph.
17///
18/// Edges connect nodes and define the control flow of the graph.
19#[derive(Clone)]
20pub enum Edge<S: GraphState> {
21    /// A fixed transition from one node to another.
22    Normal {
23        /// Source node.
24        from: NodeId,
25        /// Target node.
26        to: NodeId,
27    },
28
29    /// A conditional transition where the target is determined at runtime.
30    Conditional {
31        /// Source node.
32        from: NodeId,
33        /// Router that determines the target(s).
34        router: Arc<dyn EdgeRouter<S>>,
35        /// Optional mapping from router output strings to node IDs.
36        path_map: Option<HashMap<String, NodeId>>,
37    },
38}
39
40impl<S: GraphState> Edge<S> {
41    /// Create a normal edge.
42    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    /// Create a conditional edge.
50    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    /// Create a conditional edge with a path map.
59    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    /// Get the source node of this edge.
72    pub fn from(&self) -> &NodeId {
73        match self {
74            Self::Normal { from, .. } => from,
75            Self::Conditional { from, .. } => from,
76        }
77    }
78
79    /// Check if this is a conditional edge.
80    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/// The result of a routing decision.
105#[derive(Debug, Clone)]
106pub enum RouteOutput {
107    /// Go to a single node.
108    One(NodeId),
109
110    /// Go to multiple nodes in parallel.
111    Many(Vec<NodeId>),
112
113    /// End the graph execution.
114    End,
115}
116
117impl RouteOutput {
118    /// Create a route to a single node.
119    pub fn one(node: impl Into<NodeId>) -> Self {
120        Self::One(node.into())
121    }
122
123    /// Create a route to multiple nodes.
124    pub fn many(nodes: impl IntoIterator<Item = impl Into<NodeId>>) -> Self {
125        Self::Many(nodes.into_iter().map(Into::into).collect())
126    }
127
128    /// Create a route to end the graph.
129    pub fn end() -> Self {
130        Self::End
131    }
132
133    /// Check if this route ends the graph.
134    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    /// Get all target node IDs.
143    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    /// Convert to node IDs, replacing END sentinel with actual end.
152    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/// Trait for edge routing logic.
186///
187/// Implement this trait to create custom routing logic for conditional edges.
188/// The router receives the current state and returns the next node(s).
189///
190/// # Examples
191///
192/// ```ignore
193/// use regula_core::{EdgeRouter, RouteOutput, GraphState, Result};
194/// use async_trait::async_trait;
195///
196/// struct MyRouter;
197///
198/// #[async_trait]
199/// impl<S: GraphState> EdgeRouter<S> for MyRouter {
200///     async fn route(&self, state: &S) -> Result<RouteOutput> {
201///         // Decide based on state
202///         Ok(RouteOutput::one("next_node"))
203///     }
204/// }
205/// ```
206#[async_trait]
207pub trait EdgeRouter<S: GraphState>: Send + Sync {
208    /// Determine the next node(s) based on the current state.
209    async fn route(&self, state: &S) -> Result<RouteOutput>;
210
211    /// Get a description of this router (for debugging).
212    fn description(&self) -> Option<&str> {
213        None
214    }
215}
216
217/// A router created from a sync function.
218pub 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    /// Create a new function router.
234    pub fn new(func: F) -> Self {
235        Self {
236            func,
237            description: None,
238            _marker: PhantomData,
239        }
240    }
241
242    /// Create a new function router with a description.
243    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
267/// A router created from an async function.
268pub 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    /// Create a new async function router.
286    pub fn new(func: F) -> Self {
287        Self {
288            func,
289            description: None,
290            _marker: PhantomData,
291        }
292    }
293
294    /// Create a new async function router with a description.
295    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
320/// Create a router from a sync function.
321///
322/// # Examples
323///
324/// ```ignore
325/// use regula_core::{router_fn, RouteOutput};
326///
327/// let router = router_fn(|state: &MyState| {
328///     if state.done {
329///         RouteOutput::end()
330///     } else {
331///         RouteOutput::one("continue")
332///     }
333/// });
334/// ```
335pub 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
343/// Create a named router from a sync function.
344pub 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
352/// Create a router from an async function.
353///
354/// # Examples
355///
356/// ```ignore
357/// use regula_core::{async_router_fn, RouteOutput, Result};
358///
359/// let router = async_router_fn(|state: &MyState| async move {
360///     // Can do async operations here
361///     Ok(RouteOutput::one("next"))
362/// });
363/// ```
364pub 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
373/// A boxed router for type erasure.
374pub 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}