Skip to main content

gadk_engine/workflow/
node.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//! The `Node` trait and the `START` sentinel.
17
18use std::any::Any;
19use std::sync::{Arc, LazyLock};
20
21use futures::StreamExt;
22use gadk_agent::{AgentError, Context, EventStream};
23use gadk_session::Event;
24use serde_json::Value;
25
26use crate::error::WorkflowError;
27use crate::workflow::{BaseNode, NodeConfig};
28
29/// A node of a workflow graph. Inputs and outputs are `serde_json::Value`; "no value" is
30/// `Value::Null`.
31pub trait Node: Send + Sync + 'static {
32    /// The node's name, unique within a workflow graph.
33    fn name(&self) -> &str;
34    /// The node's human-readable description.
35    fn description(&self) -> &str;
36    /// The node's configuration.
37    fn config(&self) -> &NodeConfig;
38    /// `None` = no schema, no input validation.
39    fn input_schema(&self) -> Option<&Value>;
40    /// `None` = no schema, no output validation.
41    fn output_schema(&self) -> Option<&Value>;
42    /// Called by the scheduler before `run` on every activation.
43    fn validate_input(&self, v: Value) -> Result<Value, WorkflowError>;
44    /// Called by the scheduler on every yielded event with an output.
45    fn validate_output(&self, v: Value) -> Result<Value, WorkflowError>;
46    /// Runs one activation of the node.
47    fn run(&self, ctx: Context, input: Value) -> EventStream;
48    /// The names of the state fields the node binds as parameters; `None` = node does not bind
49    /// state params.
50    fn state_field_names(&self) -> Option<&[String]> {
51        None
52    }
53    /// Downcasting support, to tell concrete node types apart.
54    fn as_any(&self) -> &dyn Any;
55}
56
57/// Whether two nodes are the same node (pointer identity). Compares data addresses only.
58pub(crate) fn same_node(a: &dyn Node, b: &dyn Node) -> bool {
59    std::ptr::addr_eq(a as *const dyn Node, b as *const dyn Node)
60}
61
62/// The entry-point sentinel node: runs nothing and emits no events.
63struct StartNode {
64    base: BaseNode,
65}
66
67impl Node for StartNode {
68    fn name(&self) -> &str {
69        self.base.name()
70    }
71    fn description(&self) -> &str {
72        self.base.description()
73    }
74    fn config(&self) -> &NodeConfig {
75        self.base.config()
76    }
77    fn input_schema(&self) -> Option<&Value> {
78        self.base.input_schema()
79    }
80    fn output_schema(&self) -> Option<&Value> {
81        self.base.output_schema()
82    }
83    fn validate_input(&self, v: Value) -> Result<Value, WorkflowError> {
84        self.base.validate_input(v)
85    }
86    /// The start node's output is passed through unchanged.
87    fn validate_output(&self, v: Value) -> Result<Value, WorkflowError> {
88        Ok(v)
89    }
90    fn run(&self, _ctx: Context, _input: Value) -> EventStream {
91        futures::stream::empty::<Result<Event, AgentError>>().boxed()
92    }
93    fn as_any(&self) -> &dyn Any {
94        self
95    }
96}
97
98/// The entry-point sentinel, named "START" with description "Start node".
99pub static START: LazyLock<Arc<dyn Node>> = LazyLock::new(|| {
100    Arc::new(StartNode {
101        base: BaseNode::new("START", "Start node", NodeConfig::default()),
102    })
103});
104
105#[cfg(test)]
106pub(crate) mod testing {
107    use std::any::Any;
108    use std::sync::Arc;
109
110    use futures::StreamExt;
111    use gadk_agent::{AgentError, Context, EventStream};
112    use gadk_session::Event;
113    use serde_json::Value;
114
115    use super::Node;
116    use crate::error::WorkflowError;
117    use crate::workflow::{BaseNode, Edge, NodeConfig, Route};
118
119    /// Port of Go workflow test helpers dummyNode / testNode: a BaseNode with a no-op run.
120    pub(crate) struct TestNode {
121        pub(crate) base: BaseNode,
122    }
123
124    impl Node for TestNode {
125        fn name(&self) -> &str {
126            self.base.name()
127        }
128        fn description(&self) -> &str {
129            self.base.description()
130        }
131        fn config(&self) -> &NodeConfig {
132            self.base.config()
133        }
134        fn input_schema(&self) -> Option<&Value> {
135            self.base.input_schema()
136        }
137        fn output_schema(&self) -> Option<&Value> {
138            self.base.output_schema()
139        }
140        fn validate_input(&self, v: Value) -> Result<Value, WorkflowError> {
141            self.base.validate_input(v)
142        }
143        fn validate_output(&self, v: Value) -> Result<Value, WorkflowError> {
144            self.base.validate_output(v)
145        }
146        fn run(&self, _ctx: Context, _input: Value) -> EventStream {
147            futures::stream::empty::<Result<Event, AgentError>>().boxed()
148        }
149        fn as_any(&self) -> &dyn Any {
150            self
151        }
152    }
153
154    pub(crate) fn test_node(name: &str) -> Arc<dyn Node> {
155        Arc::new(TestNode {
156            base: BaseNode::new(name, "", NodeConfig::default()),
157        })
158    }
159
160    pub(crate) fn test_node_with_schemas(
161        name: &str,
162        input: Option<Value>,
163        output: Option<Value>,
164    ) -> Arc<dyn Node> {
165        Arc::new(TestNode {
166            base: BaseNode::with_schemas(name, "", input, output, NodeConfig::default())
167                .expect("schemas compile"),
168        })
169    }
170
171    pub(crate) fn edge(from: &Arc<dyn Node>, to: &Arc<dyn Node>) -> Edge {
172        Edge {
173            from: Arc::clone(from),
174            to: Arc::clone(to),
175            route: None,
176        }
177    }
178
179    pub(crate) fn route_edge(
180        from: &Arc<dyn Node>,
181        to: &Arc<dyn Node>,
182        route: Arc<dyn Route>,
183    ) -> Edge {
184        Edge {
185            from: Arc::clone(from),
186            to: Arc::clone(to),
187            route: Some(route),
188        }
189    }
190}