1pub 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
133pub type WorkflowState = HashMap<String, Value>;
139
140#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
142#[serde(rename_all = "lowercase")]
143#[non_exhaustive]
144pub enum RunStatus {
145 Queued,
147 Running,
149 Waiting,
151 Completed,
153 Failed,
155 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#[derive(Debug, Deserialize)]
191#[serde(rename_all = "camelCase")]
192pub struct SubmitRunRequest {
193 #[serde(default)]
195 pub target: Option<String>,
196 #[serde(default)]
198 pub workflow_id: Option<String>,
199 #[serde(default)]
202 pub input: Value,
203 #[serde(default)]
205 pub max_retries: Option<u32>,
206 #[serde(default)]
208 pub session_id: Option<String>,
209 #[serde(default)]
212 pub user_id: Option<String>,
213 #[serde(default)]
217 pub idempotency_key: Option<String>,
218 #[serde(default)]
221 pub concurrency_key: Option<String>,
222 #[serde(default)]
224 pub on_conflict: Option<OnConflict>,
225 #[serde(default)]
227 pub not_before: Option<DateTime<Utc>>,
228}
229
230#[derive(Debug, Serialize)]
232#[serde(rename_all = "camelCase")]
233pub struct SubmitRunResponse {
234 pub run_id: String,
236 pub status: RunStatus,
238 pub created_at: String,
240 pub existing: bool,
242}
243
244#[derive(Debug, Serialize)]
246#[serde(rename_all = "camelCase")]
247pub struct RunStatusResponse {
248 pub run_id: String,
250 pub target: String,
252 pub status: RunStatus,
254 pub created_at: String,
256 pub updated_at: String,
258 #[serde(skip_serializing_if = "Option::is_none")]
260 pub result: Option<Value>,
261 #[serde(skip_serializing_if = "Option::is_none")]
263 pub error: Option<String>,
264 pub attempt: u32,
266 pub max_attempts: u32,
268 pub retry_count: u32,
270 pub retries_remaining: u32,
272 pub cancel_requested: bool,
274 #[serde(skip_serializing_if = "Option::is_none")]
276 pub session_id: Option<String>,
277 #[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#[async_trait::async_trait]
318pub trait WorkflowExecutor: Send + Sync {
319 fn has_workflow(&self, workflow_id: &str) -> bool;
324
325 async fn execute(
330 &self,
331 workflow_id: &str,
332 input: WorkflowState,
333 cancel_token: CancellationToken,
334 ) -> std::result::Result<Value, String>;
335
336 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#[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#[derive(Clone)]
375#[non_exhaustive]
376pub struct WorkflowRunContext {
377 pub run_id: String,
379 pub attempt: u32,
381 pub thread_id: String,
383 pub checkpoint_id: Option<String>,
385 pub resumed: bool,
387 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 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 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#[derive(Default)]
461pub struct WorkflowRegistry {
462 workflows: HashMap<String, Arc<BoxedWorkflow>>,
463}
464
465type 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 pub fn new() -> Self {
477 Self::default()
478 }
479
480 #[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 #[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#[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 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 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 #[must_use]
593 pub fn with_run_store(mut self, store: Arc<dyn DurableRunStore>) -> Self {
594 self.runs = store;
595 self
596 }
597
598 #[must_use]
600 pub fn with_executor(mut self, executor: Arc<dyn WorkflowExecutor>) -> Self {
601 self.executor = Some(executor);
602 self
603 }
604
605 #[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 #[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 #[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 #[must_use]
630 pub fn with_worker_config(mut self, config: DurableWorkerConfig) -> Self {
631 self.worker = config;
632 self
633 }
634
635 #[must_use]
637 pub fn with_embedded_worker(mut self, enabled: bool) -> Self {
638 self.embedded_worker = enabled;
639 self
640 }
641
642 pub fn run_store(&self) -> &Arc<dyn DurableRunStore> {
644 &self.runs
645 }
646
647 pub fn governance(&self) -> Option<GovernanceControl> {
649 self.governance.read().unwrap_or_else(|e| e.into_inner()).clone()
650 }
651
652 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 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 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 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 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 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 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
765fn 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
779fn run_owner(caller: Option<Extension<Option<RequestContext>>>) -> Option<String> {
787 caller.and_then(|Extension(caller)| caller).map(|caller| caller.user_id)
788}
789
790pub(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
803async 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
814async 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 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 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 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 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#[derive(Debug, Default, Deserialize)]
904#[serde(rename_all = "camelCase")]
905pub struct ListRunsQuery {
906 #[serde(default)]
908 pub state: Option<RunState>,
909 #[serde(default)]
911 pub session_id: Option<String>,
912 #[serde(default)]
914 pub limit: Option<usize>,
915}
916
917async 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
943async 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
956async 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 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
989async 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
1014pub fn background_runs_router() -> Router {
1025 background_runs_router_with_state(BackgroundState::new())
1026}
1027
1028pub fn background_runs_router_with_state(state: BackgroundState) -> Router {
1038 warn_open_mode("/runs");
1039 runs_routes(state)
1040}
1041
1042pub(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}