1use 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
47pub mod paths {
49 pub const GRAPHS: &str = "/surface/workflow/graphs";
51 pub const RUNS: &str = "/surface/workflow/sessions/{session}/runs";
53 pub const RUN: &str = "/surface/workflow/sessions/{session}/run";
55 pub const CHECKPOINT: &str = "/surface/workflow/sessions/{session}/checkpoints/{id}";
57 pub const FEED: &str = "/surface/workflow/sessions/{session}/feed";
59 pub const FORK: &str = "/surface/workflow/sessions/{session}/fork";
61 pub const START: &str = "/surface/workflow/sessions/{session}/start";
63 pub const OPENAPI: &str = "/surface/workflow/openapi.json";
65}
66
67const FEED_POLL: Duration = Duration::from_millis(250);
69
70#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
72#[serde(rename_all = "camelCase")]
73pub struct WorkflowChanged {
74 pub version: u64,
76}
77
78#[derive(Debug, Clone, Default, Deserialize, JsonSchema)]
80#[serde(rename_all = "camelCase")]
81pub struct GraphQuery {
82 #[serde(default)]
85 pub graph: Option<String>,
86}
87
88#[derive(Clone)]
89struct Routes {
90 workflows: Workflows,
91 engine: SurfaceEngine,
92}
93
94pub 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
126pub 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 if let Err(error) = routes.workflows.version(&caller, &session).await {
244 return failed(error);
245 }
246 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
258fn 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
297pub fn openapi() -> serde_json::Value {
307 super::openapi::workflow::openapi()
308}
309
310pub fn typescript() -> String {
318 super::openapi::workflow::typescript()
319}