Skip to main content

adk_graph/action/
mod.rs

1//! Action node executor for adk-graph.
2//!
3//! Wraps any `ActionNodeConfig` and implements the `Node` trait, applying
4//! `StandardProperties` (error handling, timeout, skip condition) before
5//! dispatching to node-specific execution logic.
6
7pub mod code;
8pub mod file;
9pub mod loop_node;
10pub mod merge;
11pub mod set;
12pub mod switch;
13pub mod transform;
14pub mod trigger;
15#[cfg(feature = "action-trigger")]
16pub mod trigger_runtime;
17pub mod wait;
18
19#[cfg(feature = "action-http")]
20pub mod http;
21
22#[cfg(feature = "action-db")]
23pub mod database;
24
25#[cfg(feature = "action-email")]
26pub mod email;
27
28#[cfg(feature = "action-http")]
29pub mod notification;
30
31#[cfg(feature = "action-rss")]
32pub mod rss;
33
34use std::collections::HashMap;
35
36use adk_action::{ActionNodeConfig, ErrorMode, interpolate_variables};
37use async_trait::async_trait;
38use serde_json::Value;
39
40use crate::error::{GraphError, Result};
41use crate::node::{Node, NodeContext, NodeOutput};
42
43/// Executor that wraps an `ActionNodeConfig` and implements the `Node` trait.
44///
45/// Applies `StandardProperties` uniformly:
46/// 1. Check skip condition
47/// 2. Apply timeout from `ExecutionControl`
48/// 3. Dispatch to the appropriate node executor
49/// 4. Apply error handling (stop/continue/retry/fallback)
50pub struct ActionNodeExecutor {
51    config: ActionNodeConfig,
52    /// Directories a file node may touch; empty means the working directory.
53    file_roots: Vec<std::path::PathBuf>,
54    /// URLs the HTTP, notification, and RSS nodes may request.
55    #[cfg(feature = "action-http")]
56    http_policy: http::HttpActionPolicy,
57}
58
59impl ActionNodeExecutor {
60    /// Create a new executor wrapping the given action node config.
61    ///
62    /// A file node is confined to the current working directory, and the HTTP,
63    /// notification, and RSS nodes to `https`/`http` URLs; see
64    /// [`Self::with_file_roots`] and `with_http_policy`.
65    pub fn new(config: ActionNodeConfig) -> Self {
66        Self {
67            config,
68            file_roots: Vec::new(),
69            #[cfg(feature = "action-http")]
70            http_policy: http::HttpActionPolicy::default(),
71        }
72    }
73
74    /// Confines a file node to these directories instead of the working directory.
75    ///
76    /// A relative path resolves against the first root. A path that resolves
77    /// outside every root, through `..` or a symbolic link, fails the node; see
78    /// [`mod@file`] for the full rules.
79    ///
80    /// # Example
81    ///
82    /// ```rust,ignore
83    /// use adk_graph::action::ActionNodeExecutor;
84    ///
85    /// let executor = ActionNodeExecutor::new(config).with_file_roots(["/srv/workflow-data"]);
86    /// ```
87    #[must_use]
88    pub fn with_file_roots<I, P>(mut self, roots: I) -> Self
89    where
90        I: IntoIterator<Item = P>,
91        P: Into<std::path::PathBuf>,
92    {
93        self.file_roots = roots.into_iter().map(Into::into).collect();
94        self
95    }
96
97    /// Sets which URLs the HTTP, notification, and RSS nodes may request, and how
98    /// redirects are followed.
99    ///
100    /// # Example
101    ///
102    /// ```rust,ignore
103    /// use adk_graph::action::ActionNodeExecutor;
104    /// use adk_graph::action::http::HttpActionPolicy;
105    ///
106    /// let executor = ActionNodeExecutor::new(config)
107    ///     .with_http_policy(HttpActionPolicy::new().allow_hosts(["api.example.com"]));
108    /// ```
109    #[cfg(feature = "action-http")]
110    #[must_use]
111    pub fn with_http_policy(mut self, policy: http::HttpActionPolicy) -> Self {
112        self.http_policy = policy;
113        self
114    }
115
116    /// Returns a reference to the inner config.
117    pub fn config(&self) -> &ActionNodeConfig {
118        &self.config
119    }
120
121    /// Why this node cannot execute, if it cannot.
122    ///
123    /// Some action variants accept and validate a configuration while their backend is
124    /// still a placeholder, and some require a feature that is not compiled in. Both
125    /// used to surface only when the node ran, which is operationally different from a
126    /// configuration rejected before the workflow starts.
127    pub fn unavailable_reason(&self) -> Option<String> {
128        match &self.config {
129            ActionNodeConfig::Database(config) => Some(format!(
130                "database node '{}' cannot execute: database action nodes are not \
131                 implemented in any feature configuration",
132                config.standard.id
133            )),
134            ActionNodeConfig::Email(config) => Some(format!(
135                "email node '{}' cannot execute: email action nodes are not implemented \
136                 in any feature configuration",
137                config.standard.id
138            )),
139            ActionNodeConfig::Code(config)
140                if matches!(
141                    config.language,
142                    adk_action::CodeLanguage::Javascript | adk_action::CodeLanguage::Typescript
143                ) =>
144            {
145                Some(format!(
146                    "code node '{}' cannot execute: JavaScript and TypeScript code nodes are \
147                     not implemented in any feature configuration; use language 'rust'",
148                    config.standard.id
149                ))
150            }
151            #[cfg(not(feature = "action-http"))]
152            ActionNodeConfig::Http(config) => Some(format!(
153                "http node '{}' cannot execute: the 'action-http' feature is not enabled",
154                config.standard.id
155            )),
156            _ => None,
157        }
158    }
159
160    /// Build a state map from the `NodeContext` for interpolation.
161    fn state_map(ctx: &NodeContext) -> HashMap<String, Value> {
162        ctx.state.clone()
163    }
164
165    /// Check the skip condition. Returns `true` if the node should be skipped.
166    fn should_skip(&self, ctx: &NodeContext) -> bool {
167        let std = self.config.standard();
168        if let Some(condition) = &std.execution.condition {
169            let state = Self::state_map(ctx);
170            let resolved = interpolate_variables(condition, &state);
171            let trimmed = resolved.trim().to_lowercase();
172            trimmed.is_empty() || trimmed == "false"
173        } else {
174            false
175        }
176    }
177
178    /// Dispatch to the appropriate node executor based on the config variant.
179    async fn dispatch(&self, ctx: &NodeContext) -> Result<NodeOutput> {
180        match &self.config {
181            ActionNodeConfig::Trigger(c) => trigger::execute_trigger(c, ctx).await,
182            ActionNodeConfig::Set(c) => set::execute_set(c, ctx).await,
183            ActionNodeConfig::Transform(c) => transform::execute_transform(c, ctx).await,
184            ActionNodeConfig::Switch(c) => switch::execute_switch(c, ctx).await,
185            ActionNodeConfig::Loop(c) => loop_node::execute_loop(c, ctx).await,
186            ActionNodeConfig::Merge(c) => merge::execute_merge(c, ctx).await,
187            ActionNodeConfig::Wait(c) => wait::execute_wait(c, ctx).await,
188            ActionNodeConfig::File(c) => file::execute_file_in(c, ctx, &self.file_roots).await,
189            ActionNodeConfig::Code(c) => code::execute_code(c, ctx).await,
190
191            #[cfg(feature = "action-http")]
192            ActionNodeConfig::Http(c) => {
193                http::execute_http_with_policy(c, ctx, &self.http_policy).await
194            }
195            #[cfg(not(feature = "action-http"))]
196            ActionNodeConfig::Http(_) => Err(GraphError::NodeExecutionFailed {
197                node: self.config.standard().id.clone(),
198                message: "HTTP node requires the 'action-http' feature".into(),
199            }),
200
201            #[cfg(feature = "action-db")]
202            ActionNodeConfig::Database(c) => database::execute_database(c, ctx).await,
203            // Not "enable the feature": the feature compiles a placeholder that
204            // fails the same way, so naming it would send the caller nowhere.
205            #[cfg(not(feature = "action-db"))]
206            ActionNodeConfig::Database(_) => Err(GraphError::NodeExecutionFailed {
207                node: self.config.standard().id.clone(),
208                message: "database action nodes are not implemented; no database driver is \
209                          integrated"
210                    .into(),
211            }),
212
213            #[cfg(feature = "action-email")]
214            ActionNodeConfig::Email(c) => email::execute_email(c, ctx).await,
215            #[cfg(not(feature = "action-email"))]
216            ActionNodeConfig::Email(_) => Err(GraphError::NodeExecutionFailed {
217                node: self.config.standard().id.clone(),
218                message: "email action nodes are not implemented; neither IMAP monitoring nor \
219                          SMTP sending is integrated"
220                    .into(),
221            }),
222
223            #[cfg(feature = "action-http")]
224            ActionNodeConfig::Notification(c) => {
225                notification::execute_notification_with_policy(c, ctx, &self.http_policy).await
226            }
227            #[cfg(not(feature = "action-http"))]
228            ActionNodeConfig::Notification(_) => Err(GraphError::NodeExecutionFailed {
229                node: self.config.standard().id.clone(),
230                message: "Notification node requires the 'action-http' feature".into(),
231            }),
232
233            #[cfg(feature = "action-rss")]
234            ActionNodeConfig::Rss(c) => {
235                rss::execute_rss_with_policy(c, ctx, &self.http_policy).await
236            }
237            #[cfg(not(feature = "action-rss"))]
238            ActionNodeConfig::Rss(_) => Err(GraphError::NodeExecutionFailed {
239                node: self.config.standard().id.clone(),
240                message: "RSS node requires the 'action-rss' feature".into(),
241            }),
242        }
243    }
244
245    /// Applies the skip condition, the timeout and the error handling around `run`.
246    ///
247    /// A governed node's call runs once (spec 3.3 §12): its error handling neither retries
248    /// it nor swallows or replaces its failure, so the action ledger records what happened,
249    /// and its timeout is a [`GraphError::NodeTimedOut`], an outcome the bracket keeps
250    /// unknown because the call may have taken effect.
251    async fn run_guarded<F, Fut>(&self, ctx: &NodeContext, run: F) -> Result<NodeOutput>
252    where
253        F: Fn() -> Fut,
254        Fut: std::future::Future<Output = Result<NodeOutput>>,
255    {
256        // 1. Check skip condition
257        if self.should_skip(ctx) {
258            tracing::debug!(node = %self.config.standard().id, "skipping action node (condition false)");
259            return Ok(NodeOutput::new());
260        }
261
262        // 2. Apply timeout
263        let timeout_ms = self.config.standard().execution.timeout;
264        let timeout_duration = std::time::Duration::from_millis(timeout_ms);
265
266        if ctx.governed_call() {
267            return match tokio::time::timeout(timeout_duration, run()).await {
268                Ok(result) => result,
269                Err(_) => Err(GraphError::NodeTimedOut {
270                    node: self.config.standard().id.clone(),
271                    elapsed: timeout_duration,
272                }),
273            };
274        }
275
276        match tokio::time::timeout(timeout_duration, self.execute_with_error_handling(run)).await {
277            Ok(result) => result,
278            Err(_) => Err(GraphError::NodeExecutionFailed {
279                node: self.config.standard().id.clone(),
280                message: format!("action node timed out after {timeout_ms}ms"),
281            }),
282        }
283    }
284
285    /// Apply error handling around `run`, the dispatch or an approved call.
286    ///
287    /// A governed refusal is never swallowed or retried: the call was not sent.
288    async fn execute_with_error_handling<F, Fut>(&self, run: F) -> Result<NodeOutput>
289    where
290        F: Fn() -> Fut,
291        Fut: std::future::Future<Output = Result<NodeOutput>>,
292    {
293        let std = self.config.standard();
294        let error_handling = &std.error_handling;
295        let governed = |e: &GraphError| crate::governed::GovernedError::code_of(e).is_some();
296
297        match error_handling.mode {
298            ErrorMode::Stop => run().await,
299
300            ErrorMode::Continue => match run().await {
301                Ok(output) => Ok(output),
302                Err(e) if governed(&e) => Err(e),
303                Err(e) => {
304                    tracing::warn!(
305                        node = %std.id,
306                        error = %e,
307                        "action node error swallowed (continue mode)"
308                    );
309                    Ok(NodeOutput::new())
310                }
311            },
312
313            ErrorMode::Retry => {
314                let max_attempts = error_handling.retry_count.unwrap_or(1) + 1;
315                let delay_ms = error_handling.retry_delay.unwrap_or(0);
316                let mut last_err = None;
317
318                for attempt in 0..max_attempts {
319                    match run().await {
320                        Ok(output) => return Ok(output),
321                        Err(e) if governed(&e) => return Err(e),
322                        Err(e) => {
323                            tracing::warn!(
324                                node = %std.id,
325                                attempt = attempt + 1,
326                                max_attempts,
327                                error = %e,
328                                "action node retry"
329                            );
330                            last_err = Some(e);
331                            if attempt + 1 < max_attempts && delay_ms > 0 {
332                                tokio::time::sleep(std::time::Duration::from_millis(delay_ms))
333                                    .await;
334                            }
335                        }
336                    }
337                }
338
339                Err(last_err.unwrap_or_else(|| GraphError::NodeExecutionFailed {
340                    node: std.id.clone(),
341                    message: "retry exhausted with no error captured".into(),
342                }))
343            }
344
345            ErrorMode::Fallback => match run().await {
346                Ok(output) => Ok(output),
347                Err(e) if governed(&e) => Err(e),
348                Err(e) => {
349                    tracing::warn!(
350                        node = %std.id,
351                        error = %e,
352                        "action node error caught, using fallback value"
353                    );
354                    let fallback = error_handling.fallback_value.clone().unwrap_or(Value::Null);
355                    Ok(NodeOutput::new().with_update(&std.mapping.output_key, fallback))
356                }
357            },
358        }
359    }
360}
361
362#[async_trait]
363impl Node for ActionNodeExecutor {
364    fn validate(&self) -> Result<()> {
365        match self.unavailable_reason() {
366            Some(message) => Err(GraphError::InvalidGraph(message)),
367            None => Ok(()),
368        }
369    }
370
371    #[allow(clippy::misnamed_getters)]
372    fn name(&self) -> &str {
373        // Node::name() is used as a unique identifier, which is the `id` field
374        &self.config.standard().id
375    }
376
377    fn kind(&self) -> crate::shape::NodeKind {
378        use crate::shape::NodeKind;
379        match &self.config {
380            ActionNodeConfig::Trigger(_) => NodeKind::Trigger,
381            ActionNodeConfig::Http(_) => NodeKind::HttpCall,
382            ActionNodeConfig::Set(_) => NodeKind::Set,
383            ActionNodeConfig::Transform(_) => NodeKind::Transform,
384            ActionNodeConfig::Switch(_) => NodeKind::Switch,
385            ActionNodeConfig::Loop(_) => NodeKind::Loop,
386            ActionNodeConfig::Merge(_) => NodeKind::Merge,
387            ActionNodeConfig::Wait(_) => NodeKind::Wait,
388            ActionNodeConfig::Code(_) => NodeKind::Code,
389            ActionNodeConfig::Database(_) => NodeKind::Database,
390            ActionNodeConfig::Email(_) => NodeKind::Email,
391            ActionNodeConfig::Notification(_) => NodeKind::Notification,
392            ActionNodeConfig::Rss(_) => NodeKind::Rss,
393            ActionNodeConfig::File(_) => NodeKind::File,
394        }
395    }
396
397    /// `false` when the node's condition is false, so a governed node asks for no decision;
398    /// an error when an HTTP node's request cannot be built (spec 3.3 §12).
399    fn will_act(&self, ctx: &NodeContext) -> Result<bool> {
400        if self.should_skip(ctx) {
401            return Ok(false);
402        }
403        match (&self.config, ctx) {
404            #[cfg(feature = "action-http")]
405            (ActionNodeConfig::Http(config), ctx) => {
406                http::buildable(config, &ctx.state, &self.http_policy).map(|()| true)
407            }
408            _ => Ok(true),
409        }
410    }
411
412    /// The HTTP node's call with its credentials as digests (spec 3.3 §12); `None` for
413    /// other action nodes, whose call is bound to the state they read.
414    fn call_args(&self, ctx: &NodeContext) -> Option<Value> {
415        match (&self.config, ctx) {
416            #[cfg(feature = "action-http")]
417            (ActionNodeConfig::Http(config), ctx) => {
418                http::call_args(config, &ctx.state, &self.http_policy)
419            }
420            _ => None,
421        }
422    }
423
424    async fn execute(&self, ctx: &NodeContext) -> Result<NodeOutput> {
425        self.run_guarded(ctx, || self.dispatch(ctx)).await
426    }
427
428    /// Sends exactly the approved HTTP call, with each credential digest replaced by the
429    /// current credential (spec 3.3 §7.1). Other action nodes cannot run an edited call.
430    async fn run_call(&self, ctx: &NodeContext, args: Value) -> Result<NodeOutput> {
431        match (&self.config, ctx, args) {
432            #[cfg(feature = "action-http")]
433            (ActionNodeConfig::Http(config), ctx, args) => {
434                self.run_guarded(ctx, || {
435                    http::run_call(
436                        config,
437                        &ctx.state,
438                        &self.http_policy,
439                        &args,
440                        ctx.governed_call(),
441                    )
442                })
443                .await
444            }
445            _ => Err(crate::governed::GovernedError::EditUnsupported {
446                node: self.config.standard().id.clone(),
447            }
448            .into()),
449        }
450    }
451}