pub mod cron;
pub mod scheduler;
pub mod subagents;
pub mod table;
pub mod worker;
use std::collections::{BTreeMap, HashMap};
use std::sync::Arc;
use adk_core::{
AdkError, DurableRunStore, Enqueued, GovernanceControl, InMemoryRunStore, NewRun, OnConflict,
RequestContext, RunCheckpointRef, RunFilter, RunRecord, RunState,
};
use adk_runner::Runner;
use axum::{
Extension, Json, Router,
extract::{Path, Query, State},
http::StatusCode,
response::{IntoResponse, Response},
routing::{get, post},
};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use tokio_util::sync::CancellationToken;
pub use cron::{
ConcurrencyPolicy, CreateCronJobRequest, CronJobResponse, CronJobStatus, CronState,
RUN_NOW_IDEMPOTENCY_HEADER, RunCronJobNowResponse, cron_jobs_router,
cron_jobs_router_with_state, run_cron_job_now, start_cron_scheduler, validate_cron_expression,
};
pub use scheduler::{DurableScheduler, SchedulerTick};
pub use subagents::{
DurableSubagents, RunStoreBackend, SubagentBackend, SubagentConfig, SubagentHooks,
WeakSubagents,
};
pub use table::AgentTable;
pub use worker::{
DurableWorker, DurableWorkerConfig, FREEZE_PAUSED_NOTICE, FREEZE_RESUMED_ACTION,
FREEZE_RESUMED_NOTICE, GovernanceRefusal, ParkReason, WorkerHandle, WorkerHooks,
};
pub type WorkflowState = HashMap<String, Value>;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum RunStatus {
Queued,
Running,
Waiting,
Completed,
Failed,
Cancelled,
}
impl From<RunState> for RunStatus {
fn from(state: RunState) -> Self {
match state {
RunState::Queued => Self::Queued,
RunState::Running => Self::Running,
RunState::Waiting => Self::Waiting,
RunState::Completed => Self::Completed,
RunState::Failed => Self::Failed,
RunState::Cancelled => Self::Cancelled,
_ => Self::Failed,
}
}
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SubmitRunRequest {
#[serde(default)]
pub target: Option<String>,
#[serde(default)]
pub workflow_id: Option<String>,
#[serde(default)]
pub input: Value,
#[serde(default)]
pub max_retries: Option<u32>,
#[serde(default)]
pub session_id: Option<String>,
#[serde(default)]
pub user_id: Option<String>,
#[serde(default)]
pub idempotency_key: Option<String>,
#[serde(default)]
pub concurrency_key: Option<String>,
#[serde(default)]
pub on_conflict: Option<OnConflict>,
#[serde(default)]
pub not_before: Option<DateTime<Utc>>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SubmitRunResponse {
pub run_id: String,
pub status: RunStatus,
pub created_at: String,
pub existing: bool,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RunStatusResponse {
pub run_id: String,
pub target: String,
pub status: RunStatus,
pub created_at: String,
pub updated_at: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub result: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
pub attempt: u32,
pub max_attempts: u32,
pub retry_count: u32,
pub retries_remaining: u32,
pub cancel_requested: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub session_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub checkpoint: Option<RunCheckpointRef>,
}
impl From<RunRecord> for RunStatusResponse {
fn from(run: RunRecord) -> Self {
Self {
target: run.target,
status: run.state.into(),
created_at: run.created_at.to_rfc3339(),
updated_at: run.updated_at.to_rfc3339(),
result: run.result,
error: run.error,
retry_count: run.attempt.saturating_sub(1),
retries_remaining: run.max_attempts.saturating_sub(run.attempt),
attempt: run.attempt,
max_attempts: run.max_attempts,
cancel_requested: run.cancel_requested,
session_id: run.session_id,
checkpoint: run.checkpoint,
run_id: run.run_id,
}
}
}
#[async_trait::async_trait]
pub trait WorkflowExecutor: Send + Sync {
fn has_workflow(&self, workflow_id: &str) -> bool;
async fn execute(
&self,
workflow_id: &str,
input: WorkflowState,
cancel_token: CancellationToken,
) -> std::result::Result<Value, String>;
async fn execute_durable(
&self,
workflow_id: &str,
input: WorkflowState,
run: WorkflowRunContext,
) -> std::result::Result<Value, String> {
self.execute(workflow_id, input, run.cancel).await
}
}
#[derive(Clone)]
pub(crate) struct CheckpointSink {
pub(crate) runs: Arc<dyn DurableRunStore>,
pub(crate) run_id: String,
pub(crate) epoch: u64,
}
#[derive(Clone)]
#[non_exhaustive]
pub struct WorkflowRunContext {
pub run_id: String,
pub attempt: u32,
pub thread_id: String,
pub checkpoint_id: Option<String>,
pub resumed: bool,
pub cancel: CancellationToken,
pub(crate) sink: Option<CheckpointSink>,
}
impl std::fmt::Debug for WorkflowRunContext {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("WorkflowRunContext")
.field("run_id", &self.run_id)
.field("attempt", &self.attempt)
.field("thread_id", &self.thread_id)
.field("checkpoint_id", &self.checkpoint_id)
.field("resumed", &self.resumed)
.finish_non_exhaustive()
}
}
impl WorkflowRunContext {
pub fn detached(run_id: impl Into<String>, cancel: CancellationToken) -> Self {
let run_id = run_id.into();
Self {
thread_id: run_id.clone(),
run_id,
attempt: 1,
checkpoint_id: None,
resumed: false,
cancel,
sink: None,
}
}
pub async fn record_checkpoint(
&self,
checkpoint_id: impl Into<String>,
) -> std::result::Result<(), AdkError> {
let Some(sink) = &self.sink else { return Ok(()) };
sink.runs
.set_checkpoint(
&sink.run_id,
sink.epoch,
RunCheckpointRef::Graph {
thread_id: self.thread_id.clone(),
checkpoint_id: Some(checkpoint_id.into()),
},
)
.await
}
}
#[derive(Default)]
pub struct WorkflowRegistry {
workflows: HashMap<String, Arc<BoxedWorkflow>>,
}
type BoxedWorkflow = dyn Fn(
WorkflowState,
WorkflowRunContext,
) -> std::pin::Pin<
Box<dyn std::future::Future<Output = std::result::Result<Value, String>> + Send>,
> + Send
+ Sync;
impl WorkflowRegistry {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn register<F, Fut>(self, workflow_id: impl Into<String>, workflow: F) -> Self
where
F: Fn(WorkflowState, CancellationToken) -> Fut + Send + Sync + 'static,
Fut: std::future::Future<Output = std::result::Result<Value, String>> + Send + 'static,
{
self.register_durable(workflow_id, move |input, run| workflow(input, run.cancel))
}
#[must_use]
pub fn register_durable<F, Fut>(mut self, workflow_id: impl Into<String>, workflow: F) -> Self
where
F: Fn(WorkflowState, WorkflowRunContext) -> Fut + Send + Sync + 'static,
Fut: std::future::Future<Output = std::result::Result<Value, String>> + Send + 'static,
{
self.workflows
.insert(workflow_id.into(), Arc::new(move |input, run| Box::pin(workflow(input, run))));
self
}
}
#[async_trait::async_trait]
impl WorkflowExecutor for WorkflowRegistry {
fn has_workflow(&self, workflow_id: &str) -> bool {
self.workflows.contains_key(workflow_id)
}
async fn execute(
&self,
workflow_id: &str,
input: WorkflowState,
cancel_token: CancellationToken,
) -> std::result::Result<Value, String> {
let run = WorkflowRunContext::detached(uuid::Uuid::new_v4().to_string(), cancel_token);
self.execute_durable(workflow_id, input, run).await
}
async fn execute_durable(
&self,
workflow_id: &str,
input: WorkflowState,
run: WorkflowRunContext,
) -> std::result::Result<Value, String> {
match self.workflows.get(workflow_id) {
Some(workflow) => workflow(input, run).await,
None => Err(format!("workflow '{workflow_id}' is not registered")),
}
}
}
#[derive(Clone)]
pub struct BackgroundState {
runs: Arc<dyn DurableRunStore>,
executor: Option<Arc<dyn WorkflowExecutor>>,
agents: BTreeMap<String, Arc<Runner>>,
app_name: String,
governance: Arc<std::sync::RwLock<Option<GovernanceControl>>>,
worker: DurableWorkerConfig,
embedded_worker: bool,
started: Arc<std::sync::Mutex<Option<WorkerHandle>>>,
}
impl std::fmt::Debug for BackgroundState {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("BackgroundState")
.field("agents", &self.agents.keys().collect::<Vec<_>>())
.field("has_executor", &self.executor.is_some())
.field("app_name", &self.app_name)
.field("queue", &self.worker.queue)
.field("embedded_worker", &self.embedded_worker)
.finish_non_exhaustive()
}
}
impl Default for BackgroundState {
fn default() -> Self {
Self::new()
}
}
impl BackgroundState {
pub fn new() -> Self {
Self {
runs: Arc::new(InMemoryRunStore::new()),
executor: None,
agents: BTreeMap::new(),
app_name: "background".to_string(),
governance: Arc::default(),
worker: DurableWorkerConfig::default(),
embedded_worker: true,
started: Arc::default(),
}
}
#[must_use]
pub fn with_run_store(mut self, store: Arc<dyn DurableRunStore>) -> Self {
self.runs = store;
self
}
#[must_use]
pub fn with_executor(mut self, executor: Arc<dyn WorkflowExecutor>) -> Self {
self.executor = Some(executor);
self
}
#[must_use]
pub fn with_agent(mut self, target: impl Into<String>, runner: Arc<Runner>) -> Self {
self.agents.insert(target.into(), runner);
self
}
#[must_use]
pub fn with_app_name(mut self, app_name: impl Into<String>) -> Self {
self.app_name = app_name.into();
self
}
#[must_use]
pub fn with_governance(self, control: GovernanceControl) -> Self {
*self.governance.write().unwrap_or_else(|e| e.into_inner()) = Some(control);
self
}
#[must_use]
pub fn with_worker_config(mut self, config: DurableWorkerConfig) -> Self {
self.worker = config;
self
}
#[must_use]
pub fn with_embedded_worker(mut self, enabled: bool) -> Self {
self.embedded_worker = enabled;
self
}
pub fn run_store(&self) -> &Arc<dyn DurableRunStore> {
&self.runs
}
pub fn governance(&self) -> Option<GovernanceControl> {
self.governance.read().unwrap_or_else(|e| e.into_inner()).clone()
}
pub(crate) fn governance_or(&self, control: &GovernanceControl) {
let mut slot = self.governance.write().unwrap_or_else(|e| e.into_inner());
if slot.is_none() {
*slot = Some(control.clone());
}
}
pub fn worker(&self) -> DurableWorker {
let mut worker =
DurableWorker::new(Arc::clone(&self.runs)).with_config(self.worker.clone());
for (target, runner) in &self.agents {
worker = worker.with_agent(target.clone(), Arc::clone(runner));
}
if let Some(executor) = &self.executor {
worker = worker.with_workflows(Arc::clone(executor));
}
if let Some(control) = self.governance() {
worker = worker.with_governance(control);
}
worker
}
pub fn ensure_worker_started(&self) {
if !self.embedded_worker || tokio::runtime::Handle::try_current().is_err() {
return;
}
let mut started = self.started.lock().unwrap_or_else(|e| e.into_inner());
if started.as_ref().is_none_or(WorkerHandle::is_finished) {
*started = Some(self.worker().spawn());
}
}
fn wake_worker(&self) {
if let Some(handle) = self.started.lock().unwrap_or_else(|e| e.into_inner()).as_ref() {
handle.wake();
}
}
pub async fn wake_run(&self, run_id: &str) -> std::result::Result<(), AdkError> {
self.runs.wake(run_id).await?;
tracing::info!(run.id = %run_id, "run woken");
self.wake_worker();
Ok(())
}
pub async fn wake_session_runs(
&self,
app_name: &str,
user_id: &str,
session_id: &str,
) -> std::result::Result<usize, AdkError> {
let waiting = self
.runs
.list(
RunFilter::default()
.app_name(app_name)
.user_id(user_id)
.session_id(session_id)
.states([RunState::Waiting]),
)
.await?;
for run in &waiting {
self.runs.wake(&run.run_id).await?;
tracing::info!(run.id = %run.run_id, "run woken");
}
if !waiting.is_empty() {
self.wake_worker();
}
Ok(waiting.len())
}
pub async fn shutdown_worker(&self) {
let handle = self.started.lock().unwrap_or_else(|e| e.into_inner()).take();
if let Some(handle) = handle {
handle.shutdown().await;
}
}
fn app_name_for(&self, target: &str) -> String {
self.agents
.get(target)
.map_or_else(|| self.app_name.clone(), |runner| runner.app_name().to_string())
}
fn knows_target(&self, target: &str) -> bool {
self.agents.contains_key(target)
|| self.executor.as_ref().is_some_and(|executor| executor.has_workflow(target))
}
}
fn problem(status: StatusCode, message: impl Into<String>) -> Response {
(status, Json(serde_json::json!({ "error": message.into() }))).into_response()
}
fn store_error(error: &AdkError) -> Response {
let status =
StatusCode::from_u16(error.http_status_code()).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
problem(status, error.to_string())
}
fn run_owner(caller: Option<Extension<Option<RequestContext>>>) -> Option<String> {
caller.and_then(|Extension(caller)| caller).map(|caller| caller.user_id)
}
pub(crate) fn warn_open_mode(routes: &str) {
tracing::warn!(
server.routes = routes,
"background routes mounted in open mode: no caller is authenticated, so every client \
can list, read, cancel, and wake every run and cron job, and a run acts for whatever \
userId its request names; outside local development, mount them with \
ServerBuilder on a ServerConfig with a RequestContextExtractor \
(ServerConfig::with_request_context)"
);
}
async fn visible_run(
state: &BackgroundState,
run_id: &str,
owner: Option<&str>,
) -> std::result::Result<Option<RunRecord>, AdkError> {
let run = state.runs.get(run_id).await?;
Ok(run.filter(|run| owner.is_none_or(|owner| run.user_id == owner)))
}
async fn submit_run(
State(state): State<BackgroundState>,
caller: Option<Extension<Option<RequestContext>>>,
Json(request): Json<SubmitRunRequest>,
) -> Response {
if let Some(control) = state.governance()
&& let Err(error) = control.check()
{
return problem(StatusCode::SERVICE_UNAVAILABLE, error.to_string());
}
let Some(target) = request.target.or(request.workflow_id) else {
return problem(StatusCode::BAD_REQUEST, "a run needs a `target` (or `workflowId`)");
};
if !state.knows_target(&target) {
return problem(StatusCode::NOT_FOUND, format!("unknown agent or workflow '{target}'"));
}
let app_name = state.app_name_for(&target);
let owner = run_owner(caller);
let user_id = owner.clone().or(request.user_id).unwrap_or_else(|| "anonymous".to_string());
let scoped = |user: &str, key: String| {
if key.is_empty() { key } else { format!("{}:{user}:{key}", user.len()) }
};
let mut run =
NewRun::new(state.worker.queue.clone(), app_name, user_id.clone(), target, request.input)
.with_max_attempts(request.max_retries.unwrap_or(0).saturating_add(1));
if owner.is_some() {
run = run.with_authenticated_user();
}
if let Some(session_id) = request.session_id {
run = run.with_session_id(session_id);
}
if let Some(key) = request.idempotency_key {
let key = match &owner {
Some(owner) => scoped(owner, key),
None if key.is_empty() => key,
None => format!("open:{}", scoped(&user_id, key)),
};
run = run.with_idempotency_key(key);
}
if let Some(key) = request.concurrency_key {
let key = match &owner {
Some(owner) => scoped(owner, key),
None => key,
};
run = run.with_concurrency_key(key, request.on_conflict.unwrap_or_default());
}
if let Some(at) = request.not_before {
run = run.with_not_before(at);
}
let enqueued = match state.runs.enqueue(run).await {
Ok(enqueued) => enqueued,
Err(error) => return store_error(&error),
};
state.ensure_worker_started();
state.wake_worker();
let (status, record, existing) = match enqueued {
Enqueued::Created(record) => (StatusCode::CREATED, record, false),
Enqueued::Existing(record) => (StatusCode::OK, record, true),
Enqueued::Rejected { blocking_run_id } => {
return (
StatusCode::CONFLICT,
Json(serde_json::json!({
"error": "an unfinished run holds this concurrency key",
"blockingRunId": blocking_run_id,
})),
)
.into_response();
}
};
let response = SubmitRunResponse {
run_id: record.run_id,
status: record.state.into(),
created_at: record.created_at.to_rfc3339(),
existing,
};
(status, Json(response)).into_response()
}
#[derive(Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ListRunsQuery {
#[serde(default)]
pub state: Option<RunState>,
#[serde(default)]
pub session_id: Option<String>,
#[serde(default)]
pub limit: Option<usize>,
}
async fn list_runs(
State(state): State<BackgroundState>,
caller: Option<Extension<Option<RequestContext>>>,
Query(query): Query<ListRunsQuery>,
) -> Response {
let mut filter =
RunFilter::default().queue(state.worker.queue.clone()).limit(query.limit.unwrap_or(100));
if let Some(owner) = run_owner(caller) {
filter = filter.user_id(owner);
}
if let Some(run_state) = query.state {
filter = filter.states([run_state]);
}
if let Some(session_id) = query.session_id {
filter = filter.session_id(session_id);
}
match state.runs.list(filter).await {
Ok(runs) => {
let runs: Vec<RunStatusResponse> = runs.into_iter().map(Into::into).collect();
(StatusCode::OK, Json(runs)).into_response()
}
Err(error) => store_error(&error),
}
}
async fn get_run_status(
State(state): State<BackgroundState>,
caller: Option<Extension<Option<RequestContext>>>,
Path(run_id): Path<String>,
) -> Response {
match visible_run(&state, &run_id, run_owner(caller).as_deref()).await {
Ok(Some(run)) => (StatusCode::OK, Json(RunStatusResponse::from(run))).into_response(),
Ok(None) => problem(StatusCode::NOT_FOUND, "run not found"),
Err(error) => store_error(&error),
}
}
async fn cancel_run(
State(state): State<BackgroundState>,
caller: Option<Extension<Option<RequestContext>>>,
Path(run_id): Path<String>,
) -> Response {
match visible_run(&state, &run_id, run_owner(caller).as_deref()).await {
Ok(Some(_)) => {}
Ok(None) => return problem(StatusCode::NOT_FOUND, "run not found"),
Err(error) => return store_error(&error),
}
if let Err(error) = state.runs.request_cancel(&run_id).await {
return if error.is_not_found() {
problem(StatusCode::NOT_FOUND, "run not found")
} else {
store_error(&error)
};
}
tracing::info!(run.id = %run_id, "run cancellation requested");
if let Some(handle) = state.started.lock().unwrap_or_else(|e| e.into_inner()).as_ref() {
handle.heartbeat_now();
}
match state.runs.get(&run_id).await {
Ok(Some(run)) => (StatusCode::OK, Json(RunStatusResponse::from(run))).into_response(),
Ok(None) => problem(StatusCode::NOT_FOUND, "run not found"),
Err(error) => store_error(&error),
}
}
async fn wake_run(
State(state): State<BackgroundState>,
caller: Option<Extension<Option<RequestContext>>>,
Path(run_id): Path<String>,
) -> Response {
match visible_run(&state, &run_id, run_owner(caller).as_deref()).await {
Ok(Some(_)) => {}
Ok(None) => return problem(StatusCode::NOT_FOUND, "run not found"),
Err(error) => return store_error(&error),
}
if let Err(error) = state.wake_run(&run_id).await {
return if error.is_not_found() {
problem(StatusCode::NOT_FOUND, "run not found")
} else {
store_error(&error)
};
}
match state.runs.get(&run_id).await {
Ok(Some(run)) => (StatusCode::OK, Json(RunStatusResponse::from(run))).into_response(),
Ok(None) => problem(StatusCode::NOT_FOUND, "run not found"),
Err(error) => store_error(&error),
}
}
pub fn background_runs_router() -> Router {
background_runs_router_with_state(BackgroundState::new())
}
pub fn background_runs_router_with_state(state: BackgroundState) -> Router {
warn_open_mode("/runs");
runs_routes(state)
}
pub(crate) fn runs_routes(state: BackgroundState) -> Router {
state.ensure_worker_started();
Router::new()
.route("/runs", post(submit_run).get(list_runs))
.route("/runs/{run_id}", get(get_run_status).delete(cancel_run))
.route("/runs/{run_id}/wake", post(wake_run))
.with_state(state)
}