Skip to main content

adk_graph/action/
trigger_runtime.rs

1//! Trigger runtime for managing background trigger listeners.
2//!
3//! The `TriggerRuntime` manages webhook routes, cron schedules, and event
4//! subscriptions that start graph execution when triggered. This module is
5//! gated behind the `action-trigger` feature flag.
6//!
7//! - **Webhook**: Validates auth (bearer token or API key) and returns the
8//!   payload. Actual HTTP route registration happens in `adk-server`.
9//! - **Schedule**: Uses `tokio-cron-scheduler` for cron-based execution.
10//! - **Event**: Uses `tokio::sync::mpsc` channels for event-driven execution.
11
12use std::sync::Arc;
13
14use adk_action::{EventConfig, ScheduleConfig, TriggerNodeConfig, TriggerType, WebhookAuthConfig};
15use serde_json::{Value, json};
16use tokio::sync::{mpsc, watch};
17use tokio::task::JoinHandle;
18
19use crate::agent::GraphAgent;
20use crate::node::ExecutionConfig;
21use crate::state::State;
22
23// ── TriggerRuntime ────────────────────────────────────────────────────
24
25/// Manages background trigger listeners that start graph execution.
26///
27/// The runtime holds a reference to the graph agent and spawns background
28/// tasks for each configured trigger (webhook, schedule, event).
29pub struct TriggerRuntime {
30    /// The graph agent to invoke when a trigger fires.
31    graph: Arc<GraphAgent>,
32    /// Trigger configurations extracted from the workflow.
33    triggers: Vec<TriggerNodeConfig>,
34    /// Shutdown signal sender — set to `true` to stop all background tasks.
35    shutdown_tx: watch::Sender<bool>,
36    /// Shutdown signal receiver (cloned for each background task).
37    shutdown_rx: watch::Receiver<bool>,
38    /// Event sender for external systems to push events into the runtime.
39    event_tx: Option<mpsc::Sender<IncomingEvent>>,
40    /// Event receiver consumed by the event listener task.
41    event_rx: Option<mpsc::Receiver<IncomingEvent>>,
42}
43
44/// An incoming event from an external system.
45#[derive(Debug, Clone)]
46pub struct IncomingEvent {
47    /// The source system that produced the event.
48    pub source: String,
49    /// The type of event.
50    pub event_type: String,
51    /// The event payload.
52    pub data: Value,
53}
54
55impl TriggerRuntime {
56    /// Create a new `TriggerRuntime` for the given graph and trigger configs.
57    pub fn new(graph: Arc<GraphAgent>, triggers: Vec<TriggerNodeConfig>) -> Self {
58        let (shutdown_tx, shutdown_rx) = watch::channel(false);
59
60        // Create event channel if any event triggers are configured
61        let has_event_triggers =
62            triggers.iter().any(|t| matches!(t.trigger_type, TriggerType::Event));
63
64        let (event_tx, event_rx) = if has_event_triggers {
65            let (tx, rx) = mpsc::channel::<IncomingEvent>(256);
66            (Some(tx), Some(rx))
67        } else {
68            (None, None)
69        };
70
71        Self { graph, triggers, shutdown_tx, shutdown_rx, event_tx, event_rx }
72    }
73
74    /// Returns a clone of the event sender for external systems to push events.
75    ///
76    /// Returns `None` if no event triggers are configured.
77    pub fn event_sender(&self) -> Option<mpsc::Sender<IncomingEvent>> {
78        self.event_tx.clone()
79    }
80
81    /// Start all background trigger tasks.
82    ///
83    /// Spawns a background task for each non-manual trigger and returns
84    /// the `JoinHandle`s. Manual and webhook triggers are not spawned here —
85    /// manual triggers are on-demand, and webhook routes are registered
86    /// separately via `validate_webhook_auth()`.
87    pub async fn start(&mut self) -> Vec<JoinHandle<()>> {
88        let mut handles = Vec::new();
89
90        // Collect schedule and event configs
91        let mut schedule_configs: Vec<(ScheduleConfig, String)> = Vec::new();
92        let mut event_configs: Vec<EventConfig> = Vec::new();
93
94        for trigger in &self.triggers {
95            match trigger.trigger_type {
96                TriggerType::Schedule => {
97                    if let Some(schedule) = &trigger.schedule {
98                        let default_prompt = schedule.default_prompt.clone().unwrap_or_default();
99                        schedule_configs.push((schedule.clone(), default_prompt));
100                    }
101                }
102                TriggerType::Event => {
103                    if let Some(event) = &trigger.event {
104                        event_configs.push(event.clone());
105                    }
106                }
107                // Manual and Webhook are not background tasks
108                TriggerType::Manual | TriggerType::Webhook => {}
109            }
110        }
111
112        // Spawn schedule triggers
113        for (schedule_config, default_prompt) in schedule_configs {
114            let graph = Arc::clone(&self.graph);
115            let shutdown_rx = self.shutdown_rx.clone();
116            let handle = tokio::spawn(async move {
117                run_schedule_trigger(graph, schedule_config, default_prompt, shutdown_rx).await;
118            });
119            handles.push(handle);
120        }
121
122        // Spawn event listener (single task handles all event configs)
123        if !event_configs.is_empty()
124            && let Some(event_rx) = self.event_rx.take()
125        {
126            let graph = Arc::clone(&self.graph);
127            let shutdown_rx = self.shutdown_rx.clone();
128            let handle = tokio::spawn(async move {
129                run_event_trigger(graph, event_configs, event_rx, shutdown_rx).await;
130            });
131            handles.push(handle);
132        }
133
134        handles
135    }
136
137    /// Signal all background tasks to stop.
138    pub fn shutdown(&self) {
139        let _ = self.shutdown_tx.send(true);
140    }
141}
142
143// ── Webhook trigger ───────────────────────────────────────────────────
144
145/// Result of webhook authentication validation.
146#[derive(Debug)]
147pub enum WebhookAuthResult {
148    /// Authentication succeeded; contains the request payload.
149    Ok(Value),
150    /// Authentication failed.
151    Unauthorized,
152    /// No authentication configured; pass through.
153    NoAuth(Value),
154}
155
156/// Validate webhook authentication and return the payload if valid.
157///
158/// This is a standalone function that `adk-server` can call from its Axum
159/// route handler. It does not depend on Axum types — the caller extracts
160/// the relevant headers and body before calling this function.
161///
162/// # Arguments
163///
164/// * `auth_config` - Optional webhook auth configuration
165/// * `authorization_header` - The value of the `Authorization` header (if present)
166/// * `custom_header_value` - The value of the custom API key header (if present)
167/// * `payload` - The request body as a JSON value
168pub fn validate_webhook_auth(
169    auth_config: Option<&WebhookAuthConfig>,
170    authorization_header: Option<&str>,
171    custom_header_value: Option<&str>,
172    payload: Value,
173) -> WebhookAuthResult {
174    let Some(auth) = auth_config else {
175        return WebhookAuthResult::NoAuth(payload);
176    };
177
178    match auth.auth_type.as_str() {
179        "bearer" => {
180            let expected_token = auth.token.as_deref().unwrap_or("");
181            match authorization_header {
182                Some(header_value) => {
183                    let token = header_value
184                        .strip_prefix("Bearer ")
185                        .or_else(|| header_value.strip_prefix("bearer "))
186                        .unwrap_or("");
187                    if token == expected_token {
188                        WebhookAuthResult::Ok(payload)
189                    } else {
190                        WebhookAuthResult::Unauthorized
191                    }
192                }
193                None => WebhookAuthResult::Unauthorized,
194            }
195        }
196        "api_key" => {
197            let expected_key = auth.api_key.as_deref().unwrap_or("");
198            match custom_header_value {
199                Some(value) if value == expected_key => WebhookAuthResult::Ok(payload),
200                _ => WebhookAuthResult::Unauthorized,
201            }
202        }
203        // Unknown auth type — reject
204        _ => WebhookAuthResult::Unauthorized,
205    }
206}
207
208/// Invoke the graph with a webhook payload injected into state.
209///
210/// This is a helper for `adk-server` to call after successful auth validation.
211pub async fn invoke_graph_with_webhook(
212    graph: &GraphAgent,
213    payload: Value,
214    thread_id: &str,
215) -> crate::error::Result<State> {
216    let mut input = State::new();
217    input.insert("webhook_payload".to_string(), payload);
218    graph.invoke(input, ExecutionConfig::new(thread_id)).await
219}
220
221// ── Schedule trigger ──────────────────────────────────────────────────
222
223/// Run a schedule trigger using `tokio-cron-scheduler`.
224///
225/// Parses the cron expression, creates a job, and invokes the graph on each
226/// tick until the shutdown signal is received.
227async fn run_schedule_trigger(
228    graph: Arc<GraphAgent>,
229    config: ScheduleConfig,
230    default_prompt: String,
231    mut shutdown_rx: watch::Receiver<bool>,
232) {
233    use tokio_cron_scheduler::{Job, JobScheduler};
234
235    let mut scheduler = match JobScheduler::new().await {
236        Ok(s) => s,
237        Err(e) => {
238            tracing::error!(error = %e, cron = %config.cron, "failed to create job scheduler");
239            return;
240        }
241    };
242
243    let cron_expr = config.cron.clone();
244    let graph_clone = Arc::clone(&graph);
245    let prompt = default_prompt.clone();
246
247    let job = match Job::new_async(cron_expr.as_str(), move |_uuid, _lock| {
248        let graph = Arc::clone(&graph_clone);
249        let prompt = prompt.clone();
250        Box::pin(async move {
251            let mut input = State::new();
252            if !prompt.is_empty() {
253                input.insert("input".to_string(), json!(prompt));
254            }
255            let thread_id = uuid::Uuid::new_v4().to_string();
256            match graph.invoke(input, ExecutionConfig::new(&thread_id)).await {
257                Ok(_) => {
258                    tracing::debug!(thread_id = %thread_id, "schedule trigger invocation completed");
259                }
260                Err(e) => {
261                    tracing::warn!(error = %e, "schedule trigger invocation failed");
262                }
263            }
264        })
265    }) {
266        Ok(j) => j,
267        Err(e) => {
268            tracing::error!(error = %e, cron = %cron_expr, "failed to create cron job");
269            return;
270        }
271    };
272
273    if let Err(e) = scheduler.add(job).await {
274        tracing::error!(error = %e, "failed to add job to scheduler");
275        return;
276    }
277
278    if let Err(e) = scheduler.start().await {
279        tracing::error!(error = %e, "failed to start scheduler");
280        return;
281    }
282
283    tracing::info!(cron = %cron_expr, "schedule trigger started");
284
285    // Wait for shutdown signal
286    let _ = shutdown_rx.wait_for(|&val| val).await;
287
288    tracing::info!(cron = %cron_expr, "schedule trigger shutting down");
289    if let Err(e) = scheduler.shutdown().await {
290        tracing::warn!(error = %e, "error shutting down scheduler");
291    }
292}
293
294// ── Event trigger ─────────────────────────────────────────────────────
295
296/// Run the event trigger listener.
297///
298/// Receives events from the `mpsc` channel, filters them against the
299/// configured event sources and types, and invokes the graph for matches.
300async fn run_event_trigger(
301    graph: Arc<GraphAgent>,
302    event_configs: Vec<EventConfig>,
303    mut event_rx: mpsc::Receiver<IncomingEvent>,
304    mut shutdown_rx: watch::Receiver<bool>,
305) {
306    tracing::info!(config_count = event_configs.len(), "event trigger listener started");
307
308    loop {
309        tokio::select! {
310            // Check for shutdown
311            _ = shutdown_rx.changed() => {
312                if *shutdown_rx.borrow() {
313                    tracing::info!("event trigger listener shutting down");
314                    break;
315                }
316            }
317            // Receive events
318            event = event_rx.recv() => {
319                let Some(event) = event else {
320                    tracing::info!("event channel closed, stopping listener");
321                    break;
322                };
323
324                // Check if any config matches this event
325                let matches = event_configs.iter().any(|cfg| {
326                    cfg.source == event.source && cfg.event_type == event.event_type
327                });
328
329                if matches {
330                    let graph = Arc::clone(&graph);
331                    let event_data = event.data.clone();
332
333                    // Spawn invocation so we don't block the listener
334                    tokio::spawn(async move {
335                        let mut input = State::new();
336                        input.insert("event_data".to_string(), event_data);
337                        let thread_id = uuid::Uuid::new_v4().to_string();
338                        match graph.invoke(input, ExecutionConfig::new(&thread_id)).await {
339                            Ok(_) => {
340                                tracing::debug!(
341                                    thread_id = %thread_id,
342                                    "event trigger invocation completed"
343                                );
344                            }
345                            Err(e) => {
346                                tracing::warn!(error = %e, "event trigger invocation failed");
347                            }
348                        }
349                    });
350                }
351            }
352        }
353    }
354}