use std::sync::Arc;
use axum::Json;
use axum::Router as AxumRouter;
use axum::extract::{Path, Query, State};
use axum::http::StatusCode;
use axum::routing::{get, post};
use serde::Deserialize;
use serde_json::{Value, json};
use trusty_mcp::Response;
use crate::jsonrpc::Router;
use super::{RestResult, respond};
#[derive(Clone)]
struct WorkstreamsState {
router: Arc<Router>,
}
pub fn routes(router: Arc<Router>) -> AxumRouter {
AxumRouter::new()
.route(
"/workstreams",
get(list_workstreams).post(create_workstream),
)
.route("/workstreams/{id}", get(get_workstream))
.route("/workstreams/{id}/close", post(close_workstream))
.route("/workstreams/{id}/activate", post(activate))
.route("/workstreams/{id}/deactivate", post(deactivate))
.route("/workstreams/{id}/rename", post(rename))
.with_state(WorkstreamsState { router })
}
#[derive(Deserialize, Default)]
struct CreateBody {
#[serde(default)]
name: Option<String>,
}
#[derive(Deserialize, Default)]
struct ListQuery {
#[serde(default)]
include_closed: bool,
}
#[derive(Deserialize, Default)]
struct ActivateBody {
#[serde(default)]
force: bool,
}
#[derive(Deserialize)]
struct RenameBody {
name: String,
}
async fn respond_created(
router: &Router,
method: &str,
params: Value,
) -> Result<(StatusCode, Json<Value>), (StatusCode, Json<Response>)> {
respond(router, method, params)
.await
.map(|Json(v)| (StatusCode::CREATED, Json(v)))
}
async fn create_workstream(
State(state): State<WorkstreamsState>,
Json(body): Json<CreateBody>,
) -> Result<(StatusCode, Json<Value>), (StatusCode, Json<Response>)> {
respond_created(
&state.router,
"workstream.create",
json!({ "name": body.name }),
)
.await
}
async fn get_workstream(
State(state): State<WorkstreamsState>,
Path(id): Path<String>,
) -> RestResult {
respond(&state.router, "workstream.get", json!({"id": id})).await
}
async fn list_workstreams(
State(state): State<WorkstreamsState>,
Query(q): Query<ListQuery>,
) -> RestResult {
respond(
&state.router,
"workstream.list",
json!({"include_closed": q.include_closed}),
)
.await
}
async fn close_workstream(
State(state): State<WorkstreamsState>,
Path(id): Path<String>,
) -> RestResult {
respond(&state.router, "workstream.close", json!({"id": id})).await
}
async fn activate(
State(state): State<WorkstreamsState>,
Path(id): Path<String>,
Json(body): Json<ActivateBody>,
) -> RestResult {
respond(
&state.router,
"workstream.activate",
json!({"id": id, "force": body.force}),
)
.await
}
async fn deactivate(State(state): State<WorkstreamsState>, Path(id): Path<String>) -> RestResult {
respond(&state.router, "workstream.deactivate", json!({"id": id})).await
}
async fn rename(
State(state): State<WorkstreamsState>,
Path(id): Path<String>,
Json(body): Json<RenameBody>,
) -> RestResult {
respond(
&state.router,
"workstream.rename",
json!({"id": id, "name": body.name}),
)
.await
}
#[cfg(test)]
mod tests {
use super::*;
use axum::body::{Body, to_bytes};
use axum::http::Request;
use tower::util::ServiceExt;
async fn app() -> AxumRouter {
let dir = tempfile::tempdir().expect("tempdir");
let store =
crate::workstreams::WorkstreamStore::load(dir.path().join("workstreams-test.json"))
.await
.expect("load");
std::mem::forget(dir);
let mut router = Router::new();
crate::workstreams::protocol::register(
&mut router,
std::sync::Arc::new(tokio::sync::Mutex::new(store)),
);
routes(Arc::new(router))
}
async fn app_and_id() -> (AxumRouter, String, tempfile::TempDir) {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("workstreams-test.json");
let mut store = crate::workstreams::WorkstreamStore::load(path)
.await
.expect("load fresh store");
let id = store.create("t").await.expect("create");
let store = Arc::new(tokio::sync::Mutex::new(store));
let mut router = Router::new();
crate::workstreams::protocol::register(&mut router, store);
let app = routes(Arc::new(router));
(app, id.to_string(), dir)
}
async fn body_json(response: axum::response::Response) -> Value {
let bytes = to_bytes(response.into_body(), 1024 * 1024).await.unwrap();
serde_json::from_slice(&bytes).unwrap()
}
async fn post(app: &AxumRouter, uri: &str, body: &str) -> axum::response::Response {
app.clone()
.oneshot(
Request::builder()
.method("POST")
.uri(uri)
.header("content-type", "application/json")
.body(Body::from(body.to_string()))
.unwrap(),
)
.await
.unwrap()
}
async fn get(app: &AxumRouter, uri: &str) -> axum::response::Response {
app.clone()
.oneshot(
Request::builder()
.method("GET")
.uri(uri)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap()
}
#[tokio::test]
async fn create_workstream_returns_201_with_id() {
let app = app().await;
let resp = post(&app, "/workstreams", r#"{"name": "Token rotation"}"#).await;
assert_eq!(resp.status(), StatusCode::CREATED);
let v = body_json(resp).await;
assert!(v["id"].is_string());
}
#[tokio::test]
async fn create_workstream_empty_body_defaults_name() {
let app = app().await;
let resp = post(&app, "/workstreams", "{}").await;
assert_eq!(resp.status(), StatusCode::CREATED);
let id = body_json(resp).await["id"].as_str().unwrap().to_string();
let get_resp = get(&app, &format!("/workstreams/{id}")).await;
let v = body_json(get_resp).await;
assert_eq!(v["name"], "");
}
#[tokio::test]
async fn get_workstream_found_returns_200() {
let app = app().await;
let created = body_json(post(&app, "/workstreams", r#"{"name": "A"}"#).await).await;
let id = created["id"].as_str().unwrap();
let resp = get(&app, &format!("/workstreams/{id}")).await;
assert_eq!(resp.status(), StatusCode::OK);
let v = body_json(resp).await;
assert_eq!(v["name"], "A");
assert_eq!(v["state"], "idle");
}
#[tokio::test]
async fn get_workstream_missing_returns_404() {
let app = app().await;
let resp = get(&app, "/workstreams/00000000-0000-0000-0000-000000000000").await;
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
let v = body_json(resp).await;
assert_eq!(v["error"]["code"], -32002);
}
#[tokio::test]
async fn list_workstreams_returns_active_id_and_records() {
let app = app().await;
post(&app, "/workstreams", r#"{"name": "A"}"#).await;
post(&app, "/workstreams", r#"{"name": "B"}"#).await;
let resp = get(&app, "/workstreams").await;
assert_eq!(resp.status(), StatusCode::OK);
let v = body_json(resp).await;
assert_eq!(v["active_workstream_id"], Value::Null);
assert_eq!(v["workstreams"].as_array().unwrap().len(), 2);
}
#[tokio::test]
async fn close_workstream_returns_200_empty_object() {
let app = app().await;
let created = body_json(post(&app, "/workstreams", r#"{"name": "A"}"#).await).await;
let id = created["id"].as_str().unwrap();
let resp = post(&app, &format!("/workstreams/{id}/close"), "").await;
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(body_json(resp).await, json!({}));
let get_resp = get(&app, &format!("/workstreams/{id}")).await;
assert_eq!(body_json(get_resp).await["state"], "closed");
}
#[tokio::test]
async fn close_workstream_missing_returns_404() {
let app = app().await;
let resp = post(
&app,
"/workstreams/00000000-0000-0000-0000-000000000000/close",
"",
)
.await;
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
let v = body_json(resp).await;
assert_eq!(v["error"]["code"], -32002);
}
#[tokio::test]
async fn list_include_closed_query_param_includes_closed_workstream() {
let app = app().await;
let created = body_json(post(&app, "/workstreams", r#"{"name": "A"}"#).await).await;
let id = created["id"].as_str().unwrap();
post(&app, &format!("/workstreams/{id}/close"), "").await;
let default_resp = get(&app, "/workstreams").await;
assert!(
body_json(default_resp).await["workstreams"]
.as_array()
.unwrap()
.is_empty(),
"closed workstream must be excluded by default"
);
let included_resp = get(&app, "/workstreams?include_closed=true").await;
let v = body_json(included_resp).await;
assert_eq!(v["workstreams"].as_array().unwrap().len(), 1);
}
#[tokio::test]
async fn activate_returns_200_with_active_id() {
let (app, id, _dir) = app_and_id().await;
let resp = post(&app, &format!("/workstreams/{id}/activate"), "{}").await;
assert_eq!(resp.status(), StatusCode::OK);
let v = body_json(resp).await;
assert_eq!(v["active_id"], json!(id));
assert_eq!(v["prior_id"], Value::Null);
}
#[tokio::test]
async fn activate_conflict_returns_409() {
let (app, id, dir) = app_and_id().await;
let mut store =
crate::workstreams::WorkstreamStore::load(dir.path().join("workstreams-test.json"))
.await
.expect("reload store");
let other = store.create("other").await.expect("create other");
post(&app, &format!("/workstreams/{id}/activate"), "{}").await;
let resp = post(
&app,
&format!("/workstreams/{other}/activate"),
r#"{"force": false}"#,
)
.await;
assert_eq!(resp.status(), StatusCode::CONFLICT);
let v = body_json(resp).await;
assert_eq!(v["error"]["code"], -32008);
}
#[tokio::test]
async fn activate_unknown_id_returns_404() {
let (app, _id, _dir) = app_and_id().await;
let resp = post(
&app,
&format!("/workstreams/{}/activate", uuid::Uuid::new_v4()),
"{}",
)
.await;
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
let v = body_json(resp).await;
assert_eq!(v["error"]["code"], -32002);
}
#[tokio::test]
async fn deactivate_returns_200_empty_object() {
let (app, id, _dir) = app_and_id().await;
post(&app, &format!("/workstreams/{id}/activate"), "{}").await;
let resp = app
.clone()
.oneshot(
Request::builder()
.method("POST")
.uri(format!("/workstreams/{id}/deactivate"))
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let v = body_json(resp).await;
assert_eq!(v, json!({}));
}
#[tokio::test]
async fn rename_returns_200_with_updated_name() {
let (app, id, _dir) = app_and_id().await;
let resp = post(
&app,
&format!("/workstreams/{id}/rename"),
r#"{"name": "renamed"}"#,
)
.await;
assert_eq!(resp.status(), StatusCode::OK);
let v = body_json(resp).await;
assert_eq!(v["name"], "renamed");
}
#[tokio::test]
async fn rename_missing_returns_404() {
let app = app().await;
let resp = post(
&app,
"/workstreams/00000000-0000-0000-0000-000000000000/rename",
r#"{"name": "renamed"}"#,
)
.await;
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
let v = body_json(resp).await;
assert_eq!(v["error"]["code"], -32002);
}
}