Skip to main content

adk_surface/web/
workflow.rs

1//! The Runs tab's routes (spec 3.3 §12 developer track; features `web` and `workflow`): a
2//! graph agent's runs, steps and forks over [`Workflows`].
3//!
4//! [`router`] serves them under `/surface/workflow`, relative to the `/api` prefix: mount it
5//! with `ServerBuilder::add_api_routes` beside [`super::router`], so the server's auth
6//! middleware puts the caller's `RequestContext` in every request. Every route needs that
7//! caller (`401` without one) and reads or forks only the caller's own sessions: anything else
8//! answers `404` (S-I8). A paired device's token reads and never forks (`403
9//! surface.not_here`).
10//!
11//! | Route (under `/api`) | Answer |
12//! |---|---|
13//! | `GET /surface/workflow/graphs` | [`GraphsResponse`] |
14//! | `GET /surface/workflow/sessions/{session}/runs` | [`RunsResponse`]: every run, from records only; `?graph=` names the graph |
15//! | `GET /surface/workflow/sessions/{session}/run` | [`WorkflowRun`]: the latest run, with each waiting node's decision id; `?graph=` names the graph |
16//! | `GET /surface/workflow/sessions/{session}/checkpoints/{id}` | [`StepDetail`]: one step, read from one checkpoint |
17//! | `GET /surface/workflow/sessions/{session}/feed` | Server-sent events: `changed` (with `id` = the newest checkpoint version) whenever the thread writes a checkpoint; resumes after `Last-Event-ID` |
18//! | `POST /surface/workflow/sessions/{session}/fork` | [`ForkRequest`] → [`ForkOutcome`] |
19//! | `POST /surface/workflow/sessions/{session}/start` | [`ForkOutcome`]: starts a fork made and not started |
20//! | `GET /surface/workflow/openapi.json` | This API's OpenAPI document |
21//!
22//! Decisions stay on the engine's routes: a waiting node's card is the inbox entry, answered
23//! with `POST /surface/commands` `decide` (S-I1, S-I2). Errors are problem documents. On a
24//! server that pairs devices, mount [`router_with_devices`] so a paired device's feed ends
25//! with its pairing (S-I7).
26
27use std::time::Duration;
28
29use axum::extract::{Path, Query, State};
30use axum::http::HeaderMap;
31use axum::response::sse::{Event as SseEvent, KeepAlive, Sse};
32use axum::response::{IntoResponse, Response};
33use axum::routing::{get, post};
34use axum::{Extension, Json, Router};
35use futures::{FutureExt, Stream, StreamExt};
36use schemars::JsonSchema;
37use serde::{Deserialize, Serialize};
38
39use super::devices::DeviceEnds;
40use super::{Context, Unauthenticated, caller, failed, unauthenticated};
41use crate::engine::SurfaceEngine;
42use crate::origin::{Caller, SurfaceKind};
43use crate::workflow::{
44    ForkOutcome, ForkRequest, GraphsResponse, RunsResponse, StepDetail, WorkflowRun, Workflows,
45};
46
47/// The route paths, relative to the `/api` prefix (spec 3.3 §12).
48pub mod paths {
49    /// `GET`: the graphs observed.
50    pub const GRAPHS: &str = "/surface/workflow/graphs";
51    /// `GET`: every run of a session.
52    pub const RUNS: &str = "/surface/workflow/sessions/{session}/runs";
53    /// `GET`: a session's latest run.
54    pub const RUN: &str = "/surface/workflow/sessions/{session}/run";
55    /// `GET`: one step, from one checkpoint.
56    pub const CHECKPOINT: &str = "/surface/workflow/sessions/{session}/checkpoints/{id}";
57    /// `GET`: a session's run changes, as server-sent events.
58    pub const FEED: &str = "/surface/workflow/sessions/{session}/feed";
59    /// `POST`: a fork.
60    pub const FORK: &str = "/surface/workflow/sessions/{session}/fork";
61    /// `POST`: start a fork made and not started.
62    pub const START: &str = "/surface/workflow/sessions/{session}/start";
63    /// `GET`: the OpenAPI document.
64    pub const OPENAPI: &str = "/surface/workflow/openapi.json";
65}
66
67/// How often the feed reads the thread's newest checkpoint.
68const FEED_POLL: Duration = Duration::from_millis(250);
69
70/// A `changed` frame of the feed: the thread's newest checkpoint version.
71#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
72#[serde(rename_all = "camelCase")]
73pub struct WorkflowChanged {
74    /// The newest checkpoint version.
75    pub version: u64,
76}
77
78/// Query of the run reads.
79#[derive(Debug, Clone, Default, Deserialize, JsonSchema)]
80#[serde(rename_all = "camelCase")]
81pub struct GraphQuery {
82    /// The graph agent whose runs to read; the one with checkpoints on the session, else the
83    /// only one.
84    #[serde(default)]
85    pub graph: Option<String>,
86}
87
88#[derive(Clone)]
89struct Routes {
90    workflows: Workflows,
91    engine: SurfaceEngine,
92}
93
94/// The Runs tab's routes, relative to `/api` (spec 3.3 §12). Building them names
95/// [`Served::Workflow`](crate::Served::Workflow) on `engine`, so the web home reads them.
96///
97/// # Example
98///
99/// ```rust,no_run
100/// use std::sync::Arc;
101/// use adk_surface::{LocalSource, SurfaceEngine};
102/// use adk_surface::workflow::Workflows;
103///
104/// # fn example(source: LocalSource, workflows: Workflows, builder: adk_server::ServerBuilder) {
105/// let engine = SurfaceEngine::builder(Arc::new(source)).card_hints(Arc::new(workflows.clone())).build();
106/// let builder = builder
107///     .add_api_routes(adk_surface::web::router(engine.clone()))
108///     .add_api_routes(adk_surface::web::workflow::router(workflows, engine));
109/// # let _ = builder;
110/// # }
111/// ```
112pub fn router(workflows: Workflows, engine: SurfaceEngine) -> Router {
113    engine.serve(crate::Served::Workflow);
114    Router::new()
115        .route(paths::GRAPHS, get(graphs))
116        .route(paths::RUNS, get(runs))
117        .route(paths::RUN, get(run))
118        .route(paths::CHECKPOINT, get(checkpoint))
119        .route(paths::FEED, get(feed))
120        .route(paths::FORK, post(fork))
121        .route(paths::START, post(start))
122        .route(paths::OPENAPI, get(openapi_document))
123        .with_state(Routes { workflows, engine })
124}
125
126/// [`router`] for a server that pairs devices (spec 3.3 §10 K2, S-I7): a paired device's
127/// feed ends when the device is removed or its pairing ends, as the engine's feed does under
128/// [`router_with_devices`](super::router_with_devices).
129///
130/// # Example
131///
132/// ```rust,no_run
133/// use std::sync::Arc;
134/// use adk_kernel::pairing::{InMemoryDeviceStore, Pairing};
135/// use adk_surface::{LocalSource, SurfaceEngine};
136/// use adk_surface::workflow::Workflows;
137///
138/// # fn example(source: LocalSource, workflows: Workflows, builder: adk_server::ServerBuilder) {
139/// let engine = SurfaceEngine::builder(Arc::new(source)).card_hints(Arc::new(workflows.clone())).build();
140/// let pairing = Pairing::new(Arc::new(InMemoryDeviceStore::new()));
141/// let builder = builder
142///     .add_api_routes(adk_surface::web::router_with_devices(engine.clone(), pairing.clone()))
143///     .add_api_routes(adk_surface::web::workflow::router_with_devices(workflows, engine, pairing));
144/// # let _ = builder;
145/// # }
146/// ```
147pub fn router_with_devices(
148    workflows: Workflows,
149    engine: SurfaceEngine,
150    pairing: adk_kernel::pairing::Pairing,
151) -> Router {
152    router(workflows, engine).layer(Extension(DeviceEnds(pairing)))
153}
154
155fn web_caller(context: Context) -> Result<Caller, Unauthenticated> {
156    caller(context, SurfaceKind::Web, None)
157}
158
159macro_rules! caller_or_401 {
160    ($context:expr) => {
161        match web_caller($context) {
162            Ok(caller) => caller,
163            Err(Unauthenticated) => return unauthenticated(),
164        }
165    };
166}
167
168fn answer<T: Serialize>(result: crate::Result<T>) -> Response {
169    match result {
170        Ok(value) => Json(value).into_response(),
171        Err(error) => failed(error),
172    }
173}
174
175async fn graphs(State(routes): State<Routes>, context: Context) -> Response {
176    let _caller = caller_or_401!(context);
177    Json(GraphsResponse { graphs: routes.workflows.graphs() }).into_response()
178}
179
180async fn runs(
181    State(routes): State<Routes>,
182    context: Context,
183    Path(session): Path<String>,
184    Query(query): Query<GraphQuery>,
185) -> Response {
186    let caller = caller_or_401!(context);
187    answer::<RunsResponse>(routes.workflows.runs(&caller, &session, query.graph.as_deref()).await)
188}
189
190async fn run(
191    State(routes): State<Routes>,
192    context: Context,
193    Path(session): Path<String>,
194    Query(query): Query<GraphQuery>,
195) -> Response {
196    let caller = caller_or_401!(context);
197    answer::<WorkflowRun>(
198        routes.workflows.run(&routes.engine, &caller, &session, query.graph.as_deref()).await,
199    )
200}
201
202async fn checkpoint(
203    State(routes): State<Routes>,
204    context: Context,
205    Path((session, id)): Path<(String, String)>,
206) -> Response {
207    let caller = caller_or_401!(context);
208    answer::<StepDetail>(routes.workflows.step(&routes.engine, &caller, &session, &id).await)
209}
210
211async fn fork(
212    State(routes): State<Routes>,
213    context: Context,
214    Path(session): Path<String>,
215    Json(request): Json<ForkRequest>,
216) -> Response {
217    let caller = caller_or_401!(context);
218    answer::<ForkOutcome>(routes.workflows.fork(&routes.engine, &caller, &session, request).await)
219}
220
221async fn start(
222    State(routes): State<Routes>,
223    context: Context,
224    Path(session): Path<String>,
225) -> Response {
226    let caller = caller_or_401!(context);
227    answer::<ForkOutcome>(routes.workflows.start(&routes.engine, &caller, &session).await)
228}
229
230async fn feed(
231    State(routes): State<Routes>,
232    context: Context,
233    ends: Option<Extension<DeviceEnds>>,
234    headers: HeaderMap,
235    Path(session): Path<String>,
236) -> Response {
237    let caller = caller_or_401!(context);
238    let after = headers
239        .get("last-event-id")
240        .and_then(|value| value.to_str().ok())
241        .and_then(|value| value.trim().parse::<u64>().ok());
242    // A session that is not the caller's is refused before the stream starts (S-I8).
243    if let Err(error) = routes.workflows.version(&caller, &session).await {
244        return failed(error);
245    }
246    // A paired device's feed ends with the device: removed, or its pairing over (S-I7).
247    let device_ends = match (ends, caller.device.clone()) {
248        (Some(Extension(DeviceEnds(pairing))), Some(device)) => {
249            pairing.until_device_ends(device).boxed()
250        }
251        _ => futures::future::pending().boxed(),
252    };
253    Sse::new(changes(routes.workflows, caller, session, after).take_until(device_ends))
254        .keep_alive(KeepAlive::new().interval(Duration::from_secs(15)))
255        .into_response()
256}
257
258/// A `changed` frame each time the thread's newest version passes `after`.
259fn changes(
260    workflows: Workflows,
261    caller: Caller,
262    session: String,
263    after: Option<u64>,
264) -> impl Stream<Item = Result<SseEvent, std::convert::Infallible>> {
265    futures::stream::unfold(Some(after), move |state| {
266        let (workflows, caller, session) = (workflows.clone(), caller.clone(), session.clone());
267        async move {
268            let after = state?;
269            loop {
270                match workflows.version(&caller, &session).await {
271                    Ok(Some(version)) if after.is_none_or(|after| version > after) => {
272                        let event = SseEvent::default()
273                            .id(version.to_string())
274                            .event("changed")
275                            .json_data(WorkflowChanged { version })
276                            .unwrap_or_else(|_| SseEvent::default().comment("unencodable"));
277                        return Some((Ok(event), Some(Some(version))));
278                    }
279                    Ok(_) => tokio::time::sleep(FEED_POLL).await,
280                    Err(error) => {
281                        let event = SseEvent::default()
282                            .event("error")
283                            .json_data(adk_core::AdkError::from(error).to_problem_json())
284                            .unwrap_or_else(|_| SseEvent::default().comment("unencodable"));
285                        return Some((Ok(event), None));
286                    }
287                }
288            }
289        }
290    })
291}
292
293async fn openapi_document() -> Response {
294    Json(openapi()).into_response()
295}
296
297/// The OpenAPI 3.1 document of [`router`], its schemas generated from the workflow view types
298/// (spec 3.3 §12).
299///
300/// # Example
301///
302/// ```rust
303/// let document = adk_surface::web::workflow::openapi();
304/// assert!(document["components"]["schemas"]["WorkflowRun"].is_object());
305/// ```
306pub fn openapi() -> serde_json::Value {
307    super::openapi::workflow::openapi()
308}
309
310/// TypeScript declarations of every schema in [`openapi`], for the web home's Runs tab.
311///
312/// # Example
313///
314/// ```rust
315/// assert!(adk_surface::web::workflow::typescript().contains("export interface WorkflowRun {"));
316/// ```
317pub fn typescript() -> String {
318    super::openapi::workflow::typescript()
319}