Skip to main content

gadk_engine/workflow/
route.rs

1// Copyright 2026 Chris Olson
2// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! `Route`, `RouteSummary`, route kinds, `DEFAULT` and `Edge`, with the labels graph validation
17//! uses to describe a node's outgoing routes.
18
19use std::any::Any;
20use std::fmt;
21use std::sync::{Arc, LazyLock};
22
23use gadk_session::Event;
24use parking_lot::RwLock;
25use serde_json::Value;
26
27use crate::error::WorkflowError;
28use crate::workflow::Node;
29
30/// A typed view of a route value, the input to the summary of a node's outgoing edges. `Multi`
31/// holds one summary per MultiRoute element; `Other` carries a label: the type name of a custom
32/// route or element, or `"<nil>"`.
33#[derive(Debug, Clone, PartialEq, Eq)]
34pub enum RouteSummary {
35    /// The `DEFAULT` route.
36    Default,
37    /// A string route value.
38    String(String),
39    /// An integer route value.
40    Int(i64),
41    /// A boolean route value.
42    Bool(bool),
43    /// A `MultiRoute`: one summary per element.
44    Multi(Vec<RouteSummary>),
45    /// Any other route value, described by a label.
46    Other(String),
47}
48
49/// Matches execution results to edges.
50pub trait Route: Send + Sync {
51    /// Reports whether `event` was routed along this route.
52    fn matches(&self, event: &Event) -> bool;
53    /// The default describes a custom route as `Other` with its type name.
54    fn summary(&self) -> RouteSummary {
55        RouteSummary::Other(std::any::type_name::<Self>().to_string())
56    }
57}
58
59/// Whether the event carries `route_value` among its routes.
60fn match_route(route_value: &str, event: &Event) -> bool {
61    event.routes.iter().any(|v| v == route_value)
62}
63
64/// A route defined by a string value.
65#[derive(Debug, Clone, PartialEq, Eq)]
66pub struct StringRoute(pub String);
67
68/// A route defined by an integer value.
69#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70pub struct IntRoute(pub i64);
71
72/// A route defined by a boolean value.
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74pub struct BoolRoute(pub bool);
75
76/// A route that matches any value within a list of allowed routes.
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub struct MultiRoute<T>(pub Vec<T>);
79
80impl fmt::Display for StringRoute {
81    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82        f.write_str(&self.0)
83    }
84}
85
86impl fmt::Display for IntRoute {
87    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88        write!(f, "{}", self.0)
89    }
90}
91
92impl fmt::Display for BoolRoute {
93    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94        write!(f, "{}", self.0)
95    }
96}
97
98impl Route for StringRoute {
99    /// Reports whether the event was routed to this string value.
100    fn matches(&self, e: &Event) -> bool {
101        match_route(&self.0, e)
102    }
103    fn summary(&self) -> RouteSummary {
104        RouteSummary::String(self.0.clone())
105    }
106}
107
108impl Route for IntRoute {
109    /// Reports whether the event was routed to this integer value, compared by its decimal form.
110    fn matches(&self, e: &Event) -> bool {
111        match_route(&self.0.to_string(), e)
112    }
113    fn summary(&self) -> RouteSummary {
114        RouteSummary::Int(self.0)
115    }
116}
117
118impl Route for BoolRoute {
119    /// Reports whether the event was routed to this boolean value ("true"/"false").
120    fn matches(&self, e: &Event) -> bool {
121        match_route(if self.0 { "true" } else { "false" }, e)
122    }
123    fn summary(&self) -> RouteSummary {
124        RouteSummary::Bool(self.0)
125    }
126}
127
128impl<T: fmt::Display + Send + Sync + 'static> Route for MultiRoute<T> {
129    /// Whether any element's display form is in the event's routes.
130    fn matches(&self, e: &Event) -> bool {
131        self.0.iter().any(|el| match_route(&sprint(el), e))
132    }
133    /// One summary per element; an empty list yields `Multi(vec![])`, which
134    /// `summarize_outgoing_edges` renders as an `Other` label `"[]"`.
135    fn summary(&self) -> RouteSummary {
136        RouteSummary::Multi(self.0.iter().map(element_summary).collect())
137    }
138}
139
140/// The display form of a route element. `serde_json::Value` strings print raw (not JSON-quoted)
141/// and null prints "<nil>".
142fn sprint<T: fmt::Display + 'static>(el: &T) -> String {
143    if let Some(v) = (el as &dyn Any).downcast_ref::<Value>() {
144        return match v {
145            Value::String(s) => s.clone(),
146            Value::Null => "<nil>".into(),
147            other => other.to_string(),
148        };
149    }
150    el.to_string()
151}
152
153/// The summary of one route element, by downcast. Strings are unquoted here:
154/// `summarize_outgoing_edges` quotes them. (The `ints!` arms convert every integer type
155/// uniformly, including i64 → i64.)
156#[allow(clippy::useless_conversion, clippy::unnecessary_fallible_conversions)]
157fn element_summary<T: fmt::Display + 'static>(el: &T) -> RouteSummary {
158    let a = el as &dyn Any;
159    if let Some(s) = a.downcast_ref::<String>() {
160        return RouteSummary::String(s.clone());
161    }
162    if let Some(s) = a.downcast_ref::<&'static str>() {
163        return RouteSummary::String((*s).to_string());
164    }
165    if let Some(s) = a.downcast_ref::<StringRoute>() {
166        return RouteSummary::String(s.0.clone());
167    }
168    if let Some(b) = a.downcast_ref::<bool>() {
169        return RouteSummary::Bool(*b);
170    }
171    if let Some(b) = a.downcast_ref::<BoolRoute>() {
172        return RouteSummary::Bool(b.0);
173    }
174    if let Some(i) = a.downcast_ref::<IntRoute>() {
175        return RouteSummary::Int(i.0);
176    }
177    macro_rules! ints {
178        ($($t:ty),*) => { $(
179            if let Some(i) = a.downcast_ref::<$t>() {
180                return i64::try_from(*i).map_or_else(|_| RouteSummary::Other(i.to_string()), RouteSummary::Int);
181            }
182        )* }
183    }
184    ints!(i8, i16, i32, i64, isize, u8, u16, u32, u64, usize);
185    if let Some(v) = a.downcast_ref::<Value>() {
186        return match v {
187            Value::Null => RouteSummary::Other("<nil>".into()),
188            Value::String(s) => RouteSummary::String(s.clone()),
189            Value::Bool(b) => RouteSummary::Bool(*b),
190            Value::Number(n) => n
191                .as_i64()
192                .map_or_else(|| RouteSummary::Other(n.to_string()), RouteSummary::Int),
193            _ => RouteSummary::Other(std::any::type_name::<Value>().to_owned()),
194        };
195    }
196    RouteSummary::Other(std::any::type_name::<T>().to_owned())
197}
198
199/// The route behind [`DEFAULT`]; it never matches on its own.
200struct DefaultRoute;
201
202impl Route for DefaultRoute {
203    fn matches(&self, _: &Event) -> bool {
204        false
205    }
206    fn summary(&self) -> RouteSummary {
207        RouteSummary::Default
208    }
209}
210
211/// Matches when no other concrete route matched (the scheduler decides).
212pub static DEFAULT: LazyLock<Arc<dyn Route>> = LazyLock::new(|| Arc::new(DefaultRoute));
213
214/// Whether the route is [`DEFAULT`] (identity).
215pub(crate) fn is_default_route(r: &Arc<dyn Route>) -> bool {
216    std::ptr::addr_eq(Arc::as_ptr(r), Arc::as_ptr(&*DEFAULT))
217}
218
219/// A directed connection between nodes in the workflow graph.
220#[derive(Clone)]
221pub struct Edge {
222    /// The source node.
223    pub from: Arc<dyn Node>,
224    /// The target node.
225    pub to: Arc<dyn Node>,
226    /// Routing condition; `None` makes the edge unconditional.
227    pub route: Option<Arc<dyn Route>>,
228}
229
230/// Quotes a string for messages and route labels: double quotes, with `"` and `\` backslash-
231/// escaped, short escapes for control characters and `\xNN`/`\uNNNN` for other non-printable
232/// ones. Shared from gadk-agent so both crates quote identically.
233pub(crate) use gadk_agent::go_quote;
234
235// ---------------------------------------------------------------------------------------------
236// outgoing-route summaries
237// ---------------------------------------------------------------------------------------------
238
239/// Classifies a concrete route value extracted from an edge.
240#[derive(Debug, Clone, Copy, PartialEq, Eq)]
241pub(crate) enum RouteKind {
242    /// A string route (StringRoute or string element in MultiRoute).
243    String,
244    /// A boolean route (BoolRoute or bool element in MultiRoute).
245    Bool,
246    /// Any other concrete route (IntRoute, an empty MultiRoute, or a custom Route).
247    Other,
248}
249
250/// One concrete route value on an outgoing edge. `label` is a quoted string for `String`,
251/// "true"/"false" for `Bool`, and a description otherwise.
252#[derive(Debug, Clone, PartialEq, Eq)]
253pub(crate) struct RouteValue {
254    pub(crate) kind: RouteKind,
255    pub(crate) label: String,
256}
257
258/// All outgoing edges from a single node.
259#[derive(Debug, Clone, Default, PartialEq, Eq)]
260pub(crate) struct OutgoingSummary {
261    pub(crate) has_unrouted: bool,
262    pub(crate) has_default: bool,
263    pub(crate) routes: Vec<RouteValue>,
264}
265
266/// Checks the summary of one node's outgoing edges during graph validation.
267pub(crate) type RouteValidator =
268    Arc<dyn Fn(&dyn Node, &OutgoingSummary) -> Result<(), WorkflowError> + Send + Sync>;
269
270/// The registered route validators.
271static VALIDATORS: LazyLock<RwLock<Vec<RouteValidator>>> =
272    LazyLock::new(|| RwLock::new(Vec::new()));
273
274/// Registers `v` to run during workflow graph validation. Test-only: nothing in the engine
275/// registers validators.
276#[cfg(test)]
277pub(crate) fn register_route_validator(v: RouteValidator) {
278    VALIDATORS.write().push(v);
279}
280
281/// Runs every registered validator in registration order and returns the first error.
282pub(crate) fn validate_outgoing(
283    node: &dyn Node,
284    out: &OutgoingSummary,
285) -> Result<(), WorkflowError> {
286    let list = VALIDATORS.read().clone();
287    for v in &list {
288        v(node, out)?;
289    }
290    Ok(())
291}