use std::convert::Infallible;
use std::net::SocketAddr;
use std::sync::Arc;
use anyhow::{Context, Result};
use axum::{
Json, Router as AxumRouter,
body::Bytes,
extract::{Path, State},
response::sse::{Event as SseEvent, KeepAlive, Sse},
routing::{get, post},
};
use futures_util::{Stream, StreamExt, stream};
use tokio::net::TcpListener;
use tokio::sync::mpsc;
use tokio_stream::wrappers::BroadcastStream;
use tracing::info;
use trusty_common::mcp::Response;
use crate::jsonrpc::{ConnectionContext, Router};
use crate::serve::methods::health_payload;
use crate::session::SessionRegistry;
#[derive(Clone)]
struct HttpState {
router: Arc<Router>,
sessions: Arc<SessionRegistry>,
}
pub fn build_axum_router(router: Arc<Router>, sessions: Arc<SessionRegistry>) -> AxumRouter {
let state = HttpState { router, sessions };
let app = AxumRouter::new()
.route("/rpc", post(rpc_handler))
.route("/health", get(health_handler))
.route("/sessions/{id}/events", get(session_events_sse))
.with_state(state);
trusty_common::server::with_standard_middleware(app)
}
async fn rpc_handler(State(state): State<HttpState>, body: Bytes) -> Json<Response> {
let (notify_tx, _notify_rx) = mpsc::unbounded_channel();
let ctx = ConnectionContext::new(notify_tx);
Json(state.router.dispatch_json(&body, &ctx).await)
}
async fn health_handler() -> Json<serde_json::Value> {
Json(health_payload())
}
async fn session_events_sse(
State(state): State<HttpState>,
Path(session_id): Path<String>,
) -> Result<
Sse<impl Stream<Item = Result<SseEvent, Infallible>>>,
(axum::http::StatusCode, Json<Response>),
> {
let replay = state.sessions.replay(&session_id).map_err(|e| {
let body = Response::err(None, e.code, e.message);
(axum::http::StatusCode::NOT_FOUND, Json(body))
})?;
let replay_stream = stream::iter(
replay
.into_iter()
.map(|envelope| Ok(sse_event_for(&envelope))),
);
let filter_id = session_id.clone();
let live_stream = BroadcastStream::new(crate::events::subscribe()).filter_map(move |item| {
let filter_id = filter_id.clone();
async move {
match item {
Ok(envelope) if envelope.session_id == filter_id => {
Some(Ok(sse_event_for(&envelope)))
}
_ => None,
}
}
});
Ok(Sse::new(replay_stream.chain(live_stream)).keep_alive(KeepAlive::default()))
}
fn sse_event_for(envelope: &crate::events::SessionEventEnvelope) -> SseEvent {
SseEvent::default()
.json_data(envelope)
.unwrap_or_else(|_| SseEvent::default().data("{}"))
}
pub async fn run_http(router: Router, sessions: Arc<SessionRegistry>, port: u16) -> Result<()> {
let addr = SocketAddr::from(([127, 0, 0, 1], port));
let listener = TcpListener::bind(addr)
.await
.with_context(|| format!("tcode serve --http: bind {addr}"))?;
let bound = listener
.local_addr()
.context("tcode serve --http: read bound local address")?;
info!("tcode serve --http: listening on http://{bound}");
eprintln!("tcode serve --http: listening on http://{bound}");
let app = build_axum_router(Arc::new(router), sessions);
axum::serve(listener, app)
.with_graceful_shutdown(trusty_common::shutdown_signal())
.await
.context("tcode serve --http: axum serve failed")?;
info!("tcode serve --http: stopped");
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use axum::body::{Body, to_bytes};
use axum::http::{Request, StatusCode};
use serde_json::{Value, json};
use tower::util::ServiceExt;
use trusty_common::mcp::error_codes;
fn router_and_sessions() -> (Arc<Router>, Arc<SessionRegistry>) {
let sessions = Arc::new(SessionRegistry::new());
let mut router = Router::new();
crate::serve::methods::register(&mut router);
crate::session::protocol::register(&mut router, sessions.clone());
(Arc::new(router), sessions)
}
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()
}
#[tokio::test]
async fn http_rpc_ping_returns_pong() {
let (router, sessions) = router_and_sessions();
let app = build_axum_router(router, sessions);
let req_body = json!({"jsonrpc": "2.0", "id": 1, "method": "ping"}).to_string();
let resp = app
.oneshot(
Request::builder()
.method("POST")
.uri("/rpc")
.header("content-type", "application/json")
.body(Body::from(req_body))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let v = body_json(resp).await;
assert_eq!(v["result"], json!({"pong": true}));
assert_eq!(v["id"], 1);
}
#[tokio::test]
async fn http_rpc_malformed_json_returns_parse_error() {
let (router, sessions) = router_and_sessions();
let app = build_axum_router(router, sessions);
let resp = app
.oneshot(
Request::builder()
.method("POST")
.uri("/rpc")
.header("content-type", "application/json")
.body(Body::from("not json at all"))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let v = body_json(resp).await;
assert_eq!(v["error"]["code"], error_codes::PARSE_ERROR);
}
#[tokio::test]
async fn http_health_matches_jsonrpc_health_payload() {
let (router, sessions) = router_and_sessions();
let app = build_axum_router(router, sessions);
let resp = app
.oneshot(
Request::builder()
.method("GET")
.uri("/health")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let v = body_json(resp).await;
assert_eq!(v, health_payload());
}
#[tokio::test]
async fn http_session_events_sse_unknown_session_returns_404() {
let (router, sessions) = router_and_sessions();
let app = build_axum_router(router, sessions);
let resp = app
.oneshot(
Request::builder()
.method("GET")
.uri("/sessions/does-not-exist/events")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
let v = body_json(resp).await;
assert_eq!(v["error"]["code"], -32007);
}
#[tokio::test]
async fn http_session_events_sse_streams_replay() {
let (router, sessions) = router_and_sessions();
let session = sessions.create("t".to_string(), None, None);
let app = build_axum_router(router, sessions);
let resp = app
.oneshot(
Request::builder()
.method("GET")
.uri(format!("/sessions/{}/events", session.id))
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let mut stream = resp.into_body().into_data_stream();
let mut collected = Vec::new();
let read_replay = tokio::time::timeout(std::time::Duration::from_secs(5), async {
while !String::from_utf8_lossy(&collected).contains("session_status_changed") {
match stream.next().await {
Some(Ok(chunk)) => collected.extend_from_slice(&chunk),
_ => break,
}
}
})
.await;
assert!(
read_replay.is_ok(),
"timed out waiting for the SSE replay burst"
);
let text = String::from_utf8(collected).unwrap();
assert!(text.contains("session_started"), "body so far: {text}");
assert!(
text.contains("session_status_changed"),
"body so far: {text}"
);
assert!(text.contains("\"seq\":1"), "body so far: {text}");
assert!(
text.contains("\"kind\":\"session_started\""),
"body so far: {text}"
);
}
}