use std::time::Duration;
use axum::extract::{Path, Query, State};
use axum::http::HeaderMap;
use axum::response::sse::{Event as SseEvent, KeepAlive, Sse};
use axum::response::{IntoResponse, Response};
use axum::routing::{get, post};
use axum::{Extension, Json, Router};
use futures::{FutureExt, Stream, StreamExt};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use super::devices::DeviceEnds;
use super::{Context, Unauthenticated, caller, failed, unauthenticated};
use crate::engine::SurfaceEngine;
use crate::origin::{Caller, SurfaceKind};
use crate::workflow::{
ForkOutcome, ForkRequest, GraphsResponse, RunsResponse, StepDetail, WorkflowRun, Workflows,
};
pub mod paths {
pub const GRAPHS: &str = "/surface/workflow/graphs";
pub const RUNS: &str = "/surface/workflow/sessions/{session}/runs";
pub const RUN: &str = "/surface/workflow/sessions/{session}/run";
pub const CHECKPOINT: &str = "/surface/workflow/sessions/{session}/checkpoints/{id}";
pub const FEED: &str = "/surface/workflow/sessions/{session}/feed";
pub const FORK: &str = "/surface/workflow/sessions/{session}/fork";
pub const START: &str = "/surface/workflow/sessions/{session}/start";
pub const OPENAPI: &str = "/surface/workflow/openapi.json";
}
const FEED_POLL: Duration = Duration::from_millis(250);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct WorkflowChanged {
pub version: u64,
}
#[derive(Debug, Clone, Default, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct GraphQuery {
#[serde(default)]
pub graph: Option<String>,
}
#[derive(Clone)]
struct Routes {
workflows: Workflows,
engine: SurfaceEngine,
}
pub fn router(workflows: Workflows, engine: SurfaceEngine) -> Router {
engine.serve(crate::Served::Workflow);
Router::new()
.route(paths::GRAPHS, get(graphs))
.route(paths::RUNS, get(runs))
.route(paths::RUN, get(run))
.route(paths::CHECKPOINT, get(checkpoint))
.route(paths::FEED, get(feed))
.route(paths::FORK, post(fork))
.route(paths::START, post(start))
.route(paths::OPENAPI, get(openapi_document))
.with_state(Routes { workflows, engine })
}
pub fn router_with_devices(
workflows: Workflows,
engine: SurfaceEngine,
pairing: adk_kernel::pairing::Pairing,
) -> Router {
router(workflows, engine).layer(Extension(DeviceEnds(pairing)))
}
fn web_caller(context: Context) -> Result<Caller, Unauthenticated> {
caller(context, SurfaceKind::Web, None)
}
macro_rules! caller_or_401 {
($context:expr) => {
match web_caller($context) {
Ok(caller) => caller,
Err(Unauthenticated) => return unauthenticated(),
}
};
}
fn answer<T: Serialize>(result: crate::Result<T>) -> Response {
match result {
Ok(value) => Json(value).into_response(),
Err(error) => failed(error),
}
}
async fn graphs(State(routes): State<Routes>, context: Context) -> Response {
let _caller = caller_or_401!(context);
Json(GraphsResponse { graphs: routes.workflows.graphs() }).into_response()
}
async fn runs(
State(routes): State<Routes>,
context: Context,
Path(session): Path<String>,
Query(query): Query<GraphQuery>,
) -> Response {
let caller = caller_or_401!(context);
answer::<RunsResponse>(routes.workflows.runs(&caller, &session, query.graph.as_deref()).await)
}
async fn run(
State(routes): State<Routes>,
context: Context,
Path(session): Path<String>,
Query(query): Query<GraphQuery>,
) -> Response {
let caller = caller_or_401!(context);
answer::<WorkflowRun>(
routes.workflows.run(&routes.engine, &caller, &session, query.graph.as_deref()).await,
)
}
async fn checkpoint(
State(routes): State<Routes>,
context: Context,
Path((session, id)): Path<(String, String)>,
) -> Response {
let caller = caller_or_401!(context);
answer::<StepDetail>(routes.workflows.step(&routes.engine, &caller, &session, &id).await)
}
async fn fork(
State(routes): State<Routes>,
context: Context,
Path(session): Path<String>,
Json(request): Json<ForkRequest>,
) -> Response {
let caller = caller_or_401!(context);
answer::<ForkOutcome>(routes.workflows.fork(&routes.engine, &caller, &session, request).await)
}
async fn start(
State(routes): State<Routes>,
context: Context,
Path(session): Path<String>,
) -> Response {
let caller = caller_or_401!(context);
answer::<ForkOutcome>(routes.workflows.start(&routes.engine, &caller, &session).await)
}
async fn feed(
State(routes): State<Routes>,
context: Context,
ends: Option<Extension<DeviceEnds>>,
headers: HeaderMap,
Path(session): Path<String>,
) -> Response {
let caller = caller_or_401!(context);
let after = headers
.get("last-event-id")
.and_then(|value| value.to_str().ok())
.and_then(|value| value.trim().parse::<u64>().ok());
if let Err(error) = routes.workflows.version(&caller, &session).await {
return failed(error);
}
let device_ends = match (ends, caller.device.clone()) {
(Some(Extension(DeviceEnds(pairing))), Some(device)) => {
pairing.until_device_ends(device).boxed()
}
_ => futures::future::pending().boxed(),
};
Sse::new(changes(routes.workflows, caller, session, after).take_until(device_ends))
.keep_alive(KeepAlive::new().interval(Duration::from_secs(15)))
.into_response()
}
fn changes(
workflows: Workflows,
caller: Caller,
session: String,
after: Option<u64>,
) -> impl Stream<Item = Result<SseEvent, std::convert::Infallible>> {
futures::stream::unfold(Some(after), move |state| {
let (workflows, caller, session) = (workflows.clone(), caller.clone(), session.clone());
async move {
let after = state?;
loop {
match workflows.version(&caller, &session).await {
Ok(Some(version)) if after.is_none_or(|after| version > after) => {
let event = SseEvent::default()
.id(version.to_string())
.event("changed")
.json_data(WorkflowChanged { version })
.unwrap_or_else(|_| SseEvent::default().comment("unencodable"));
return Some((Ok(event), Some(Some(version))));
}
Ok(_) => tokio::time::sleep(FEED_POLL).await,
Err(error) => {
let event = SseEvent::default()
.event("error")
.json_data(adk_core::AdkError::from(error).to_problem_json())
.unwrap_or_else(|_| SseEvent::default().comment("unencodable"));
return Some((Ok(event), None));
}
}
}
}
})
}
async fn openapi_document() -> Response {
Json(openapi()).into_response()
}
pub fn openapi() -> serde_json::Value {
super::openapi::workflow::openapi()
}
pub fn typescript() -> String {
super::openapi::workflow::typescript()
}