Skip to main content

adk_server/background/
mod.rs

1//! # Background Runs and Cron Scheduling
2//!
3//! REST endpoints and runtime for durable background runs and schedules, gated behind
4//! the `background` feature.
5//!
6//! Runs live in a [`DurableRunStore`] and schedules in a [`ScheduleStore`](adk_core::ScheduleStore) — in memory by
7//! default, or a shared backend so several replicas serve one queue. A
8//! [`DurableWorker`] claims runs under fenced leases and executes them; a
9//! [`DurableScheduler`] on every replica enqueues each schedule's fire times exactly
10//! once. Both respect the governance kill switch.
11//!
12//! ## Background runs
13//!
14//! - `POST /runs` — Enqueue a run of a workflow or an agent
15//! - `GET /runs` — List runs (`state`, `sessionId`, `limit` query parameters)
16//! - `GET /runs/{run_id}` — Get a run
17//! - `DELETE /runs/{run_id}` — Cancel a run; a running run stops at its worker's next heartbeat
18//! - `POST /runs/{run_id}/wake` — Make a run parked on a held tool call claimable now
19//!
20//! ## Cron jobs
21//!
22//! - `POST /cron` — Create a cron schedule
23//! - `GET /cron` — List schedules
24//! - `GET /cron/{job_id}` — Get a schedule
25//! - `PATCH /cron/{job_id}` — Pause or resume a schedule
26//! - `DELETE /cron/{job_id}` — Delete a schedule
27//!
28//! ## Ownership
29//!
30//! With a `RequestContextExtractor` on the server, a run belongs to the authenticated
31//! caller: `GET /runs` lists only the caller's runs, and `GET`, `DELETE`, and
32//! `POST .../wake` on another owner's run answer `404`. The caller's `idempotencyKey` and
33//! `concurrencyKey` are scoped to the caller, so one user's key never returns, rejects, or
34//! interrupts another user's run.
35//!
36//! ## Open mode
37//!
38//! Without an extractor — a server with no `RequestContextExtractor`, or a standalone router
39//! — the routes run in open mode, meant for local development:
40//!
41//! | Aspect | Open mode |
42//! |--------|-----------|
43//! | Caller | None is authenticated |
44//! | A run's user | The `userId` its request names, or `anonymous` when it names none |
45//! | Visibility | Every client lists, reads, cancels, and wakes every run and cron job |
46//! | `idempotencyKey` | Scoped to the run's user: two users' identical keys create two runs, and requests naming no user share `anonymous`'s keys |
47//! | `concurrencyKey` | Shared by every client |
48//! | Cron jobs | A job's name is its id, and its runs act for the user `cron` |
49//!
50//! A `userId` in the request is a claim, not an identity, so open-mode key scoping keeps
51//! clients' retries apart but authorizes nothing. An open-mode key never matches an
52//! authenticated caller's key or the server's own `schedule:` and `hook:` keys. The server
53//! logs a warning when the routes mount in open mode.
54//!
55//! ## Production
56//!
57//! Outside local development, serve these routes only through
58//! [`ServerBuilder::with_background_runs`](crate::ServerBuilder::with_background_runs) and
59//! [`ServerBuilder::with_cron_jobs`](crate::ServerBuilder::with_cron_jobs) on a
60//! [`ServerConfig`](crate::ServerConfig) with
61//! [`with_request_context`](crate::ServerConfig::with_request_context), which mount them
62//! under `/api` behind the server's auth middleware and scope runs, jobs, and keys to the
63//! authenticated caller.
64//!
65//! ## Usage
66//!
67//! > **Important:** these routers carry no authentication of their own. A standalone mount
68//! > runs in open mode and must sit behind an authentication layer, or anyone who reaches it
69//! > can submit, schedule, and cancel work.
70//!
71//! ```rust,ignore
72//! use std::sync::Arc;
73//! use adk_server::background::{BackgroundState, CronState, WorkflowRegistry, start_cron_scheduler};
74//!
75//! // In memory, one process: the embedded worker starts with the server.
76//! let background = BackgroundState::new().with_executor(Arc::new(registry));
77//!
78//! // Shared stores, several replicas: each replica runs a worker and a scheduler.
79//! let background = BackgroundState::new()
80//!     .with_run_store(run_store)
81//!     .with_executor(Arc::new(registry))
82//!     .with_agent("support", Arc::new(runner));
83//! let cron = CronState::new(background.clone()).with_schedule_store(schedule_store);
84//! start_cron_scheduler(cron.clone());
85//! let app = ServerBuilder::new(config)
86//!     .with_background_runs(background)
87//!     .with_cron_jobs(cron)
88//!     .build();
89//! ```
90
91pub mod cron;
92pub mod scheduler;
93pub mod subagents;
94pub mod table;
95pub mod worker;
96
97use std::collections::{BTreeMap, HashMap};
98use std::sync::Arc;
99
100use adk_core::{
101    AdkError, DurableRunStore, Enqueued, GovernanceControl, InMemoryRunStore, NewRun, OnConflict,
102    RequestContext, RunCheckpointRef, RunFilter, RunRecord, RunState,
103};
104use adk_runner::Runner;
105use axum::{
106    Extension, Json, Router,
107    extract::{Path, Query, State},
108    http::StatusCode,
109    response::{IntoResponse, Response},
110    routing::{get, post},
111};
112use chrono::{DateTime, Utc};
113use serde::{Deserialize, Serialize};
114use serde_json::Value;
115use tokio_util::sync::CancellationToken;
116
117pub use cron::{
118    ConcurrencyPolicy, CreateCronJobRequest, CronJobResponse, CronJobStatus, CronState,
119    RUN_NOW_IDEMPOTENCY_HEADER, RunCronJobNowResponse, cron_jobs_router,
120    cron_jobs_router_with_state, run_cron_job_now, start_cron_scheduler, validate_cron_expression,
121};
122pub use scheduler::{DurableScheduler, SchedulerTick};
123pub use subagents::{
124    DurableSubagents, RunStoreBackend, SubagentBackend, SubagentConfig, SubagentHooks,
125    WeakSubagents,
126};
127pub use table::AgentTable;
128pub use worker::{
129    DurableWorker, DurableWorkerConfig, FREEZE_PAUSED_NOTICE, FREEZE_RESUMED_ACTION,
130    FREEZE_RESUMED_NOTICE, GovernanceRefusal, ParkReason, WorkerHandle, WorkerHooks,
131};
132
133// ---------------------------------------------------------------------------
134// Data Types
135// ---------------------------------------------------------------------------
136
137/// Workflow input state — a map of string keys to JSON values.
138pub type WorkflowState = HashMap<String, Value>;
139
140/// Run lifecycle status as the REST API reports it.
141#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
142#[serde(rename_all = "lowercase")]
143#[non_exhaustive]
144pub enum RunStatus {
145    /// Waiting for a worker.
146    Queued,
147    /// Claimed by a worker.
148    Running,
149    /// Parked until a timer passes or the run is woken.
150    Waiting,
151    /// Finished with a result.
152    Completed,
153    /// Finished with an error.
154    Failed,
155    /// Cancelled before or during execution.
156    Cancelled,
157}
158
159impl From<RunState> for RunStatus {
160    fn from(state: RunState) -> Self {
161        match state {
162            RunState::Queued => Self::Queued,
163            RunState::Running => Self::Running,
164            RunState::Waiting => Self::Waiting,
165            RunState::Completed => Self::Completed,
166            RunState::Failed => Self::Failed,
167            RunState::Cancelled => Self::Cancelled,
168            _ => Self::Failed,
169        }
170    }
171}
172
173/// `POST /runs` request body.
174///
175/// # Example
176///
177/// ```rust
178/// use adk_server::background::SubmitRunRequest;
179///
180/// let request: SubmitRunRequest = serde_json::from_value(serde_json::json!({
181///     "target": "support",
182///     "input": { "text": "where is order 7?" },
183///     "sessionId": "thread-42",
184///     "concurrencyKey": "thread-42",
185///     "onConflict": "interrupt",
186///     "idempotencyKey": "webhook:evt_1"
187/// })).unwrap();
188/// assert_eq!(request.target.as_deref(), Some("support"));
189/// ```
190#[derive(Debug, Deserialize)]
191#[serde(rename_all = "camelCase")]
192pub struct SubmitRunRequest {
193    /// The agent or workflow to run.
194    #[serde(default)]
195    pub target: Option<String>,
196    /// The workflow to run; an alias of `target` kept for existing clients.
197    #[serde(default)]
198    pub workflow_id: Option<String>,
199    /// The run's input: workflow state for a workflow, a string, `{"text": ...}`, or
200    /// `{"content": ...}` for an agent.
201    #[serde(default)]
202    pub input: Value,
203    /// Retries after the first attempt; `maxAttempts` is this plus one. Defaults to 0.
204    #[serde(default)]
205    pub max_retries: Option<u32>,
206    /// The session an agent run continues; defaults to `run-{runId}`.
207    #[serde(default)]
208    pub session_id: Option<String>,
209    /// The user the run belongs to in open mode; `anonymous` when absent. Ignored with an
210    /// authenticated caller, whose run is always their own.
211    #[serde(default)]
212    pub user_id: Option<String>,
213    /// Enqueueing an existing key returns the existing run. The key is scoped to the run's
214    /// user — the authenticated caller, or in open mode the request's `userId` — so only that
215    /// user's runs match it.
216    #[serde(default)]
217    pub idempotency_key: Option<String>,
218    /// Runs sharing a key run one at a time. With an authenticated caller the key is the
219    /// caller's own, so it never holds back or interrupts another user's run.
220    #[serde(default)]
221    pub concurrency_key: Option<String>,
222    /// What happens when an unfinished run holds `concurrencyKey` (double texting).
223    #[serde(default)]
224    pub on_conflict: Option<OnConflict>,
225    /// The run is not claimed before this time.
226    #[serde(default)]
227    pub not_before: Option<DateTime<Utc>>,
228}
229
230/// `POST /runs` response.
231#[derive(Debug, Serialize)]
232#[serde(rename_all = "camelCase")]
233pub struct SubmitRunResponse {
234    /// The run identifier.
235    pub run_id: String,
236    /// The run's status.
237    pub status: RunStatus,
238    /// When the run was enqueued.
239    pub created_at: String,
240    /// `true` when the idempotency key matched an existing run.
241    pub existing: bool,
242}
243
244/// `GET /runs/{run_id}` response.
245#[derive(Debug, Serialize)]
246#[serde(rename_all = "camelCase")]
247pub struct RunStatusResponse {
248    /// The run identifier.
249    pub run_id: String,
250    /// The agent or workflow the run executes.
251    pub target: String,
252    /// The run's status.
253    pub status: RunStatus,
254    /// When the run was enqueued.
255    pub created_at: String,
256    /// When the run last changed.
257    pub updated_at: String,
258    /// The result of a completed run.
259    #[serde(skip_serializing_if = "Option::is_none")]
260    pub result: Option<Value>,
261    /// The error of the latest failed attempt.
262    #[serde(skip_serializing_if = "Option::is_none")]
263    pub error: Option<String>,
264    /// Attempts started so far, counting recoveries.
265    pub attempt: u32,
266    /// The most attempts the run may take.
267    pub max_attempts: u32,
268    /// Retries used: `attempt - 1`.
269    pub retry_count: u32,
270    /// Attempts left.
271    pub retries_remaining: u32,
272    /// Whether cancellation was requested while the run was running.
273    pub cancel_requested: bool,
274    /// The session an agent run continues.
275    #[serde(skip_serializing_if = "Option::is_none")]
276    pub session_id: Option<String>,
277    /// Where the run's progress is checkpointed.
278    #[serde(skip_serializing_if = "Option::is_none")]
279    pub checkpoint: Option<RunCheckpointRef>,
280}
281
282impl From<RunRecord> for RunStatusResponse {
283    fn from(run: RunRecord) -> Self {
284        Self {
285            target: run.target,
286            status: run.state.into(),
287            created_at: run.created_at.to_rfc3339(),
288            updated_at: run.updated_at.to_rfc3339(),
289            result: run.result,
290            error: run.error,
291            retry_count: run.attempt.saturating_sub(1),
292            retries_remaining: run.max_attempts.saturating_sub(run.attempt),
293            attempt: run.attempt,
294            max_attempts: run.max_attempts,
295            cancel_requested: run.cancel_requested,
296            session_id: run.session_id,
297            checkpoint: run.checkpoint,
298            run_id: run.run_id,
299        }
300    }
301}
302
303// ---------------------------------------------------------------------------
304// Workflow executors
305// ---------------------------------------------------------------------------
306
307/// Executes a registered workflow for a background run.
308///
309/// A background run names a target; something has to turn that into work. Implement
310/// this to bridge to whatever executes workflows in your application — `adk-graph`, the
311/// functional API, or your own dispatcher.
312///
313/// # Errors
314///
315/// Return `Err` to fail the attempt. A failed attempt is retried while the run has
316/// attempts left, so surface real failures rather than encoding them as `Ok`.
317#[async_trait::async_trait]
318pub trait WorkflowExecutor: Send + Sync {
319    /// Whether `workflow_id` can be executed.
320    ///
321    /// Checked before a run is queued, so an unknown workflow is rejected instead of
322    /// being accepted and then failed.
323    fn has_workflow(&self, workflow_id: &str) -> bool;
324
325    /// Run `workflow_id` with `input`.
326    ///
327    /// `cancel_token` fires when the run is cancelled; implementations should observe it
328    /// and stop.
329    async fn execute(
330        &self,
331        workflow_id: &str,
332        input: WorkflowState,
333        cancel_token: CancellationToken,
334    ) -> std::result::Result<Value, String>;
335
336    /// Run `workflow_id` as one attempt of a durable run.
337    ///
338    /// `run` carries the run's identity, its checkpoint thread, whether this attempt
339    /// resumes a stopped one, and the cancellation token. A graph workflow passes
340    /// `run.thread_id` to its executor so a resumed attempt continues from its
341    /// checkpointer, and may report checkpoints with
342    /// [`WorkflowRunContext::record_checkpoint`]. The default calls
343    /// [`execute`](Self::execute), which restarts the workflow from its input.
344    async fn execute_durable(
345        &self,
346        workflow_id: &str,
347        input: WorkflowState,
348        run: WorkflowRunContext,
349    ) -> std::result::Result<Value, String> {
350        self.execute(workflow_id, input, run.cancel).await
351    }
352}
353
354/// Records a workflow's checkpoints on its durable run, fenced by the claim's epoch.
355#[derive(Clone)]
356pub(crate) struct CheckpointSink {
357    pub(crate) runs: Arc<dyn DurableRunStore>,
358    pub(crate) run_id: String,
359    pub(crate) epoch: u64,
360}
361
362/// One attempt of a durable workflow run.
363///
364/// # Example
365///
366/// ```rust
367/// use adk_server::background::WorkflowRunContext;
368/// use tokio_util::sync::CancellationToken;
369///
370/// let run = WorkflowRunContext::detached("run-1", CancellationToken::new());
371/// assert_eq!(run.thread_id, "run-1");
372/// assert!(!run.resumed);
373/// ```
374#[derive(Clone)]
375#[non_exhaustive]
376pub struct WorkflowRunContext {
377    /// The run identifier.
378    pub run_id: String,
379    /// The attempt number, counting recoveries.
380    pub attempt: u32,
381    /// The checkpoint thread; a graph workflow uses it as its `thread_id`.
382    pub thread_id: String,
383    /// The last checkpoint the run reported, if any.
384    pub checkpoint_id: Option<String>,
385    /// Whether this attempt resumes one that stopped.
386    pub resumed: bool,
387    /// Fires when the run is cancelled.
388    pub cancel: CancellationToken,
389    pub(crate) sink: Option<CheckpointSink>,
390}
391
392impl std::fmt::Debug for WorkflowRunContext {
393    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
394        f.debug_struct("WorkflowRunContext")
395            .field("run_id", &self.run_id)
396            .field("attempt", &self.attempt)
397            .field("thread_id", &self.thread_id)
398            .field("checkpoint_id", &self.checkpoint_id)
399            .field("resumed", &self.resumed)
400            .finish_non_exhaustive()
401    }
402}
403
404impl WorkflowRunContext {
405    /// A context for a run with no durable store behind it, for tests and direct calls.
406    pub fn detached(run_id: impl Into<String>, cancel: CancellationToken) -> Self {
407        let run_id = run_id.into();
408        Self {
409            thread_id: run_id.clone(),
410            run_id,
411            attempt: 1,
412            checkpoint_id: None,
413            resumed: false,
414            cancel,
415            sink: None,
416        }
417    }
418
419    /// Records `checkpoint_id` on the run, so a recovering worker resumes from it.
420    ///
421    /// # Errors
422    ///
423    /// Returns `run_store.stale_epoch` when another worker recovered the run; the
424    /// workflow must then stop without writing further results.
425    pub async fn record_checkpoint(
426        &self,
427        checkpoint_id: impl Into<String>,
428    ) -> std::result::Result<(), AdkError> {
429        let Some(sink) = &self.sink else { return Ok(()) };
430        sink.runs
431            .set_checkpoint(
432                &sink.run_id,
433                sink.epoch,
434                RunCheckpointRef::Graph {
435                    thread_id: self.thread_id.clone(),
436                    checkpoint_id: Some(checkpoint_id.into()),
437                },
438            )
439            .await
440    }
441}
442
443/// A `WorkflowExecutor` holding closures registered by name.
444///
445/// # Example
446///
447/// ```rust
448/// use adk_server::background::WorkflowRegistry;
449/// use serde_json::json;
450///
451/// let registry = WorkflowRegistry::new()
452///     .register("greet", |input, _cancel| async move {
453///         Ok(json!({ "greeted": input.get("name").cloned() }))
454///     })
455///     .register_durable("settle", |_input, run| async move {
456///         // A graph workflow would invoke its executor with `run.thread_id` here.
457///         Ok(json!({ "thread": run.thread_id, "resumed": run.resumed }))
458///     });
459/// ```
460#[derive(Default)]
461pub struct WorkflowRegistry {
462    workflows: HashMap<String, Arc<BoxedWorkflow>>,
463}
464
465/// The boxed form of a registered workflow.
466type BoxedWorkflow = dyn Fn(
467        WorkflowState,
468        WorkflowRunContext,
469    ) -> std::pin::Pin<
470        Box<dyn std::future::Future<Output = std::result::Result<Value, String>> + Send>,
471    > + Send
472    + Sync;
473
474impl WorkflowRegistry {
475    /// An empty registry, which accepts no workflow.
476    pub fn new() -> Self {
477        Self::default()
478    }
479
480    /// Registers `workflow_id`; a recovered run restarts it from its input.
481    #[must_use]
482    pub fn register<F, Fut>(self, workflow_id: impl Into<String>, workflow: F) -> Self
483    where
484        F: Fn(WorkflowState, CancellationToken) -> Fut + Send + Sync + 'static,
485        Fut: std::future::Future<Output = std::result::Result<Value, String>> + Send + 'static,
486    {
487        self.register_durable(workflow_id, move |input, run| workflow(input, run.cancel))
488    }
489
490    /// Registers `workflow_id` with the attempt's [`WorkflowRunContext`], so a recovered
491    /// run can resume from its checkpoint thread.
492    #[must_use]
493    pub fn register_durable<F, Fut>(mut self, workflow_id: impl Into<String>, workflow: F) -> Self
494    where
495        F: Fn(WorkflowState, WorkflowRunContext) -> Fut + Send + Sync + 'static,
496        Fut: std::future::Future<Output = std::result::Result<Value, String>> + Send + 'static,
497    {
498        self.workflows
499            .insert(workflow_id.into(), Arc::new(move |input, run| Box::pin(workflow(input, run))));
500        self
501    }
502}
503
504#[async_trait::async_trait]
505impl WorkflowExecutor for WorkflowRegistry {
506    fn has_workflow(&self, workflow_id: &str) -> bool {
507        self.workflows.contains_key(workflow_id)
508    }
509
510    async fn execute(
511        &self,
512        workflow_id: &str,
513        input: WorkflowState,
514        cancel_token: CancellationToken,
515    ) -> std::result::Result<Value, String> {
516        let run = WorkflowRunContext::detached(uuid::Uuid::new_v4().to_string(), cancel_token);
517        self.execute_durable(workflow_id, input, run).await
518    }
519
520    async fn execute_durable(
521        &self,
522        workflow_id: &str,
523        input: WorkflowState,
524        run: WorkflowRunContext,
525    ) -> std::result::Result<Value, String> {
526        match self.workflows.get(workflow_id) {
527            Some(workflow) => workflow(input, run).await,
528            None => Err(format!("workflow '{workflow_id}' is not registered")),
529        }
530    }
531}
532
533// ---------------------------------------------------------------------------
534// Shared Application State for Axum Handlers
535// ---------------------------------------------------------------------------
536
537/// Shared state for the background run endpoints, and the embedded worker.
538///
539/// Holds the run store (in memory by default), the targets runs execute, and the
540/// governance control. Unless disabled with
541/// [`with_embedded_worker(false)`](Self::with_embedded_worker), a [`DurableWorker`] over
542/// the same store and targets starts in this process the first time the server is built
543/// inside a Tokio runtime or a run is submitted.
544#[derive(Clone)]
545pub struct BackgroundState {
546    runs: Arc<dyn DurableRunStore>,
547    executor: Option<Arc<dyn WorkflowExecutor>>,
548    agents: BTreeMap<String, Arc<Runner>>,
549    app_name: String,
550    /// Shared by every clone, so a control installed by the server builder reaches a
551    /// scheduler started earlier from a clone.
552    governance: Arc<std::sync::RwLock<Option<GovernanceControl>>>,
553    worker: DurableWorkerConfig,
554    embedded_worker: bool,
555    started: Arc<std::sync::Mutex<Option<WorkerHandle>>>,
556}
557
558impl std::fmt::Debug for BackgroundState {
559    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
560        f.debug_struct("BackgroundState")
561            .field("agents", &self.agents.keys().collect::<Vec<_>>())
562            .field("has_executor", &self.executor.is_some())
563            .field("app_name", &self.app_name)
564            .field("queue", &self.worker.queue)
565            .field("embedded_worker", &self.embedded_worker)
566            .finish_non_exhaustive()
567    }
568}
569
570impl Default for BackgroundState {
571    fn default() -> Self {
572        Self::new()
573    }
574}
575
576impl BackgroundState {
577    /// A state over a fresh [`InMemoryRunStore`] with no targets.
578    pub fn new() -> Self {
579        Self {
580            runs: Arc::new(InMemoryRunStore::new()),
581            executor: None,
582            agents: BTreeMap::new(),
583            app_name: "background".to_string(),
584            governance: Arc::default(),
585            worker: DurableWorkerConfig::default(),
586            embedded_worker: true,
587            started: Arc::default(),
588        }
589    }
590
591    /// Uses `store` for runs; share one store across replicas.
592    #[must_use]
593    pub fn with_run_store(mut self, store: Arc<dyn DurableRunStore>) -> Self {
594        self.runs = store;
595        self
596    }
597
598    /// Attaches the executor that resolves and runs workflows.
599    #[must_use]
600    pub fn with_executor(mut self, executor: Arc<dyn WorkflowExecutor>) -> Self {
601        self.executor = Some(executor);
602        self
603    }
604
605    /// Runs whose target is `target` execute through `runner`, in the runner's app.
606    #[must_use]
607    pub fn with_agent(mut self, target: impl Into<String>, runner: Arc<Runner>) -> Self {
608        self.agents.insert(target.into(), runner);
609        self
610    }
611
612    /// Sets the app name workflow runs are recorded under. Defaults to `background`.
613    #[must_use]
614    pub fn with_app_name(mut self, app_name: impl Into<String>) -> Self {
615        self.app_name = app_name.into();
616        self
617    }
618
619    /// Refuses submissions, and stops the embedded worker claiming, while `control`
620    /// refuses work. [`ServerBuilder`](crate::ServerBuilder) installs
621    /// [`ServerConfig::governance`](crate::ServerConfig::governance) when none is set.
622    #[must_use]
623    pub fn with_governance(self, control: GovernanceControl) -> Self {
624        *self.governance.write().unwrap_or_else(|e| e.into_inner()) = Some(control);
625        self
626    }
627
628    /// Sets the embedded worker's configuration, including the queue runs are enqueued on.
629    #[must_use]
630    pub fn with_worker_config(mut self, config: DurableWorkerConfig) -> Self {
631        self.worker = config;
632        self
633    }
634
635    /// Whether this process runs a worker; disable it on API-only replicas.
636    #[must_use]
637    pub fn with_embedded_worker(mut self, enabled: bool) -> Self {
638        self.embedded_worker = enabled;
639        self
640    }
641
642    /// The run store.
643    pub fn run_store(&self) -> &Arc<dyn DurableRunStore> {
644        &self.runs
645    }
646
647    /// The governance control, if one is installed.
648    pub fn governance(&self) -> Option<GovernanceControl> {
649        self.governance.read().unwrap_or_else(|e| e.into_inner()).clone()
650    }
651
652    /// Installs `control` unless one is already installed.
653    pub(crate) fn governance_or(&self, control: &GovernanceControl) {
654        let mut slot = self.governance.write().unwrap_or_else(|e| e.into_inner());
655        if slot.is_none() {
656            *slot = Some(control.clone());
657        }
658    }
659
660    /// A [`DurableWorker`] over this state's store, targets, governance, and configuration.
661    pub fn worker(&self) -> DurableWorker {
662        let mut worker =
663            DurableWorker::new(Arc::clone(&self.runs)).with_config(self.worker.clone());
664        for (target, runner) in &self.agents {
665            worker = worker.with_agent(target.clone(), Arc::clone(runner));
666        }
667        if let Some(executor) = &self.executor {
668            worker = worker.with_workflows(Arc::clone(executor));
669        }
670        if let Some(control) = self.governance() {
671            worker = worker.with_governance(control);
672        }
673        worker
674    }
675
676    /// Starts the embedded worker once, when enabled and a Tokio runtime is running.
677    pub fn ensure_worker_started(&self) {
678        if !self.embedded_worker || tokio::runtime::Handle::try_current().is_err() {
679            return;
680        }
681        let mut started = self.started.lock().unwrap_or_else(|e| e.into_inner());
682        if started.as_ref().is_none_or(WorkerHandle::is_finished) {
683            *started = Some(self.worker().spawn());
684        }
685    }
686
687    fn wake_worker(&self) {
688        if let Some(handle) = self.started.lock().unwrap_or_else(|e| e.into_inner()).as_ref() {
689            handle.wake();
690        }
691    }
692
693    /// Makes a parked run claimable now, for the approval service to call once it
694    /// records a decision for the run's held tool call.
695    ///
696    /// A waiting run is claimed again at once and resumes its session, so the agent
697    /// dispatches the held call through the governed path with the decision. A wake
698    /// that arrives while the run is still running is kept and applied when it parks.
699    ///
700    /// # Errors
701    ///
702    /// Returns `run_store.not_found` for an unknown run, or the store's error.
703    pub async fn wake_run(&self, run_id: &str) -> std::result::Result<(), AdkError> {
704        self.runs.wake(run_id).await?;
705        tracing::info!(run.id = %run_id, "run woken");
706        self.wake_worker();
707        Ok(())
708    }
709
710    /// Wakes every parked run of `app_name` continuing `session_id` for `user_id`, and
711    /// returns how many were woken; for an approval service that knows the decision's
712    /// session but not its run.
713    ///
714    /// # Errors
715    ///
716    /// Returns the store's error.
717    pub async fn wake_session_runs(
718        &self,
719        app_name: &str,
720        user_id: &str,
721        session_id: &str,
722    ) -> std::result::Result<usize, AdkError> {
723        let waiting = self
724            .runs
725            .list(
726                RunFilter::default()
727                    .app_name(app_name)
728                    .user_id(user_id)
729                    .session_id(session_id)
730                    .states([RunState::Waiting]),
731            )
732            .await?;
733        for run in &waiting {
734            self.runs.wake(&run.run_id).await?;
735            tracing::info!(run.id = %run.run_id, "run woken");
736        }
737        if !waiting.is_empty() {
738            self.wake_worker();
739        }
740        Ok(waiting.len())
741    }
742
743    /// Stops the embedded worker, letting in-flight attempts finish.
744    pub async fn shutdown_worker(&self) {
745        let handle = self.started.lock().unwrap_or_else(|e| e.into_inner()).take();
746        if let Some(handle) = handle {
747            handle.shutdown().await;
748        }
749    }
750
751    /// The app a run of `target` is recorded under: the agent's runner app, or this
752    /// state's app name for a workflow.
753    fn app_name_for(&self, target: &str) -> String {
754        self.agents
755            .get(target)
756            .map_or_else(|| self.app_name.clone(), |runner| runner.app_name().to_string())
757    }
758
759    fn knows_target(&self, target: &str) -> bool {
760        self.agents.contains_key(target)
761            || self.executor.as_ref().is_some_and(|executor| executor.has_workflow(target))
762    }
763}
764
765// ---------------------------------------------------------------------------
766// REST Endpoint Handlers
767// ---------------------------------------------------------------------------
768
769fn problem(status: StatusCode, message: impl Into<String>) -> Response {
770    (status, Json(serde_json::json!({ "error": message.into() }))).into_response()
771}
772
773fn store_error(error: &AdkError) -> Response {
774    let status =
775        StatusCode::from_u16(error.http_status_code()).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
776    problem(status, error.to_string())
777}
778
779/// The authenticated caller's user id, or `None` in open mode.
780///
781/// The auth middleware inserts `Option<RequestContext>`: `Some` when a
782/// `RequestContextExtractor` authenticated the request, `None` when none is configured. A
783/// router mounted without the middleware has no extension at all. Owner checks need an
784/// authenticated caller (spec 3.1 §8.2); the open-mode warning is logged when the routes
785/// mount ([`warn_open_mode`]), not here.
786fn run_owner(caller: Option<Extension<Option<RequestContext>>>) -> Option<String> {
787    caller.and_then(|Extension(caller)| caller).map(|caller| caller.user_id)
788}
789
790/// Logs that `routes` mount in open mode: no caller is authenticated, so every client
791/// reaches every run and cron job.
792pub(crate) fn warn_open_mode(routes: &str) {
793    tracing::warn!(
794        server.routes = routes,
795        "background routes mounted in open mode: no caller is authenticated, so every client \
796         can list, read, cancel, and wake every run and cron job, and a run acts for whatever \
797         userId its request names; outside local development, mount them with \
798         ServerBuilder on a ServerConfig with a RequestContextExtractor \
799         (ServerConfig::with_request_context)"
800    );
801}
802
803/// The run `run_id` when `owner` may see it: any run without an authenticated caller, only
804/// the caller's own run with one. Another owner's run reads as missing.
805async fn visible_run(
806    state: &BackgroundState,
807    run_id: &str,
808    owner: Option<&str>,
809) -> std::result::Result<Option<RunRecord>, AdkError> {
810    let run = state.runs.get(run_id).await?;
811    Ok(run.filter(|run| owner.is_none_or(|owner| run.user_id == owner)))
812}
813
814/// POST /runs — Enqueue a run.
815async fn submit_run(
816    State(state): State<BackgroundState>,
817    caller: Option<Extension<Option<RequestContext>>>,
818    Json(request): Json<SubmitRunRequest>,
819) -> Response {
820    if let Some(control) = state.governance()
821        && let Err(error) = control.check()
822    {
823        return problem(StatusCode::SERVICE_UNAVAILABLE, error.to_string());
824    }
825    let Some(target) = request.target.or(request.workflow_id) else {
826        return problem(StatusCode::BAD_REQUEST, "a run needs a `target` (or `workflowId`)");
827    };
828    // Rejected before it is queued, rather than accepted and then failed.
829    if !state.knows_target(&target) {
830        return problem(StatusCode::NOT_FOUND, format!("unknown agent or workflow '{target}'"));
831    }
832    let app_name = state.app_name_for(&target);
833    let owner = run_owner(caller);
834    let user_id = owner.clone().or(request.user_id).unwrap_or_else(|| "anonymous".to_string());
835    // The length prefix keeps ("a:b", "c") and ("a", "b:c") apart, and the leading digit
836    // keeps caller keys apart from the server's own `schedule:` and `hook:` keys. An empty
837    // key stays empty so validation still refuses it.
838    let scoped = |user: &str, key: String| {
839        if key.is_empty() { key } else { format!("{}:{user}:{key}", user.len()) }
840    };
841
842    let mut run =
843        NewRun::new(state.worker.queue.clone(), app_name, user_id.clone(), target, request.input)
844            .with_max_attempts(request.max_retries.unwrap_or(0).saturating_add(1));
845    // The worker runs it as the identity the server authenticated (spec 3.1 §9.2 I6).
846    if owner.is_some() {
847        run = run.with_authenticated_user();
848    }
849    if let Some(session_id) = request.session_id {
850        run = run.with_session_id(session_id);
851    }
852    if let Some(key) = request.idempotency_key {
853        let key = match &owner {
854            Some(owner) => scoped(owner, key),
855            None if key.is_empty() => key,
856            // A user the request only names gets `open:` keys, so it never shares the keys
857            // of an authenticated caller with the same id.
858            None => format!("open:{}", scoped(&user_id, key)),
859        };
860        run = run.with_idempotency_key(key);
861    }
862    if let Some(key) = request.concurrency_key {
863        let key = match &owner {
864            Some(owner) => scoped(owner, key),
865            None => key,
866        };
867        run = run.with_concurrency_key(key, request.on_conflict.unwrap_or_default());
868    }
869    if let Some(at) = request.not_before {
870        run = run.with_not_before(at);
871    }
872
873    let enqueued = match state.runs.enqueue(run).await {
874        Ok(enqueued) => enqueued,
875        Err(error) => return store_error(&error),
876    };
877    state.ensure_worker_started();
878    state.wake_worker();
879    let (status, record, existing) = match enqueued {
880        Enqueued::Created(record) => (StatusCode::CREATED, record, false),
881        Enqueued::Existing(record) => (StatusCode::OK, record, true),
882        Enqueued::Rejected { blocking_run_id } => {
883            return (
884                StatusCode::CONFLICT,
885                Json(serde_json::json!({
886                    "error": "an unfinished run holds this concurrency key",
887                    "blockingRunId": blocking_run_id,
888                })),
889            )
890                .into_response();
891        }
892    };
893    let response = SubmitRunResponse {
894        run_id: record.run_id,
895        status: record.state.into(),
896        created_at: record.created_at.to_rfc3339(),
897        existing,
898    };
899    (status, Json(response)).into_response()
900}
901
902/// `GET /runs` query parameters.
903#[derive(Debug, Default, Deserialize)]
904#[serde(rename_all = "camelCase")]
905pub struct ListRunsQuery {
906    /// Only runs in this state.
907    #[serde(default)]
908    pub state: Option<RunState>,
909    /// Only runs continuing this session.
910    #[serde(default)]
911    pub session_id: Option<String>,
912    /// At most this many runs; defaults to 100.
913    #[serde(default)]
914    pub limit: Option<usize>,
915}
916
917/// GET /runs — List runs; with an authenticated caller, only the caller's.
918async fn list_runs(
919    State(state): State<BackgroundState>,
920    caller: Option<Extension<Option<RequestContext>>>,
921    Query(query): Query<ListRunsQuery>,
922) -> Response {
923    let mut filter =
924        RunFilter::default().queue(state.worker.queue.clone()).limit(query.limit.unwrap_or(100));
925    if let Some(owner) = run_owner(caller) {
926        filter = filter.user_id(owner);
927    }
928    if let Some(run_state) = query.state {
929        filter = filter.states([run_state]);
930    }
931    if let Some(session_id) = query.session_id {
932        filter = filter.session_id(session_id);
933    }
934    match state.runs.list(filter).await {
935        Ok(runs) => {
936            let runs: Vec<RunStatusResponse> = runs.into_iter().map(Into::into).collect();
937            (StatusCode::OK, Json(runs)).into_response()
938        }
939        Err(error) => store_error(&error),
940    }
941}
942
943/// GET /runs/{run_id} — Get a run; another owner's run is `404`.
944async fn get_run_status(
945    State(state): State<BackgroundState>,
946    caller: Option<Extension<Option<RequestContext>>>,
947    Path(run_id): Path<String>,
948) -> Response {
949    match visible_run(&state, &run_id, run_owner(caller).as_deref()).await {
950        Ok(Some(run)) => (StatusCode::OK, Json(RunStatusResponse::from(run))).into_response(),
951        Ok(None) => problem(StatusCode::NOT_FOUND, "run not found"),
952        Err(error) => store_error(&error),
953    }
954}
955
956/// DELETE /runs/{run_id} — Cancel a run; another owner's run is `404`.
957///
958/// A queued or waiting run is cancelled at once; a running run is flagged and its
959/// worker, on whichever replica, stops it at its next heartbeat.
960async fn cancel_run(
961    State(state): State<BackgroundState>,
962    caller: Option<Extension<Option<RequestContext>>>,
963    Path(run_id): Path<String>,
964) -> Response {
965    match visible_run(&state, &run_id, run_owner(caller).as_deref()).await {
966        Ok(Some(_)) => {}
967        Ok(None) => return problem(StatusCode::NOT_FOUND, "run not found"),
968        Err(error) => return store_error(&error),
969    }
970    if let Err(error) = state.runs.request_cancel(&run_id).await {
971        return if error.is_not_found() {
972            problem(StatusCode::NOT_FOUND, "run not found")
973        } else {
974            store_error(&error)
975        };
976    }
977    tracing::info!(run.id = %run_id, "run cancellation requested");
978    // A run owned by this process stops now; one owned elsewhere at its worker's next heartbeat.
979    if let Some(handle) = state.started.lock().unwrap_or_else(|e| e.into_inner()).as_ref() {
980        handle.heartbeat_now();
981    }
982    match state.runs.get(&run_id).await {
983        Ok(Some(run)) => (StatusCode::OK, Json(RunStatusResponse::from(run))).into_response(),
984        Ok(None) => problem(StatusCode::NOT_FOUND, "run not found"),
985        Err(error) => store_error(&error),
986    }
987}
988
989/// POST /runs/{run_id}/wake — Make a parked run claimable now; another owner's run is `404`.
990async fn wake_run(
991    State(state): State<BackgroundState>,
992    caller: Option<Extension<Option<RequestContext>>>,
993    Path(run_id): Path<String>,
994) -> Response {
995    match visible_run(&state, &run_id, run_owner(caller).as_deref()).await {
996        Ok(Some(_)) => {}
997        Ok(None) => return problem(StatusCode::NOT_FOUND, "run not found"),
998        Err(error) => return store_error(&error),
999    }
1000    if let Err(error) = state.wake_run(&run_id).await {
1001        return if error.is_not_found() {
1002            problem(StatusCode::NOT_FOUND, "run not found")
1003        } else {
1004            store_error(&error)
1005        };
1006    }
1007    match state.runs.get(&run_id).await {
1008        Ok(Some(run)) => (StatusCode::OK, Json(RunStatusResponse::from(run))).into_response(),
1009        Ok(None) => problem(StatusCode::NOT_FOUND, "run not found"),
1010        Err(error) => store_error(&error),
1011    }
1012}
1013
1014// ---------------------------------------------------------------------------
1015// Router
1016// ---------------------------------------------------------------------------
1017
1018/// Create the background runs router over a fresh in-memory state.
1019///
1020/// > **Important:** the router carries no authentication. Anyone who reaches it can
1021/// > submit and cancel runs. Mount it through
1022/// > [`ServerBuilder::with_background_runs`](crate::ServerBuilder::with_background_runs),
1023/// > which applies the server's auth middleware, or behind your own authentication layer.
1024pub fn background_runs_router() -> Router {
1025    background_runs_router_with_state(BackgroundState::new())
1026}
1027
1028/// Create the background runs router with a pre-configured state.
1029///
1030/// Mounts `POST /runs`, `GET /runs`, `GET /runs/{run_id}`, `DELETE /runs/{run_id}`, and
1031/// `POST /runs/{run_id}/wake`,
1032/// and starts the embedded worker when a Tokio runtime is running. The routes run in
1033/// [open mode](self#open-mode), and building the router logs a warning that says so.
1034///
1035/// > **Important:** the router carries no authentication; see
1036/// > [`background_runs_router`].
1037pub fn background_runs_router_with_state(state: BackgroundState) -> Router {
1038    warn_open_mode("/runs");
1039    runs_routes(state)
1040}
1041
1042/// The run routes without the open-mode warning, for [`ServerBuilder`](crate::ServerBuilder),
1043/// which knows whether it authenticates callers.
1044pub(crate) fn runs_routes(state: BackgroundState) -> Router {
1045    state.ensure_worker_started();
1046    Router::new()
1047        .route("/runs", post(submit_run).get(list_runs))
1048        .route("/runs/{run_id}", get(get_run_status).delete(cancel_run))
1049        .route("/runs/{run_id}/wake", post(wake_run))
1050        .with_state(state)
1051}