1use 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#[derive(Debug, Clone, PartialEq, Eq)]
34pub enum RouteSummary {
35 Default,
37 String(String),
39 Int(i64),
41 Bool(bool),
43 Multi(Vec<RouteSummary>),
45 Other(String),
47}
48
49pub trait Route: Send + Sync {
51 fn matches(&self, event: &Event) -> bool;
53 fn summary(&self) -> RouteSummary {
55 RouteSummary::Other(std::any::type_name::<Self>().to_string())
56 }
57}
58
59fn match_route(route_value: &str, event: &Event) -> bool {
61 event.routes.iter().any(|v| v == route_value)
62}
63
64#[derive(Debug, Clone, PartialEq, Eq)]
66pub struct StringRoute(pub String);
67
68#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70pub struct IntRoute(pub i64);
71
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74pub struct BoolRoute(pub bool);
75
76#[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 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 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 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 fn matches(&self, e: &Event) -> bool {
131 self.0.iter().any(|el| match_route(&sprint(el), e))
132 }
133 fn summary(&self) -> RouteSummary {
136 RouteSummary::Multi(self.0.iter().map(element_summary).collect())
137 }
138}
139
140fn 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#[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
199struct 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
211pub static DEFAULT: LazyLock<Arc<dyn Route>> = LazyLock::new(|| Arc::new(DefaultRoute));
213
214pub(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#[derive(Clone)]
221pub struct Edge {
222 pub from: Arc<dyn Node>,
224 pub to: Arc<dyn Node>,
226 pub route: Option<Arc<dyn Route>>,
228}
229
230pub(crate) use gadk_agent::go_quote;
234
235#[derive(Debug, Clone, Copy, PartialEq, Eq)]
241pub(crate) enum RouteKind {
242 String,
244 Bool,
246 Other,
248}
249
250#[derive(Debug, Clone, PartialEq, Eq)]
253pub(crate) struct RouteValue {
254 pub(crate) kind: RouteKind,
255 pub(crate) label: String,
256}
257
258#[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
266pub(crate) type RouteValidator =
268 Arc<dyn Fn(&dyn Node, &OutgoingSummary) -> Result<(), WorkflowError> + Send + Sync>;
269
270static VALIDATORS: LazyLock<RwLock<Vec<RouteValidator>>> =
272 LazyLock::new(|| RwLock::new(Vec::new()));
273
274#[cfg(test)]
277pub(crate) fn register_route_validator(v: RouteValidator) {
278 VALIDATORS.write().push(v);
279}
280
281pub(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}