trusty_code/serve/http.rs
1//! HTTP JSON-RPC 2.0 transport for `tcode serve --http` (#2053, #2054).
2//!
3//! Why: matches how `trusty-memory` (`web::router` + `run_http_on`) and
4//! `trusty-search` (`service::server::build_router`) stand up their axum
5//! daemons: a pure `axum::Router` builder — testable via `oneshot`, no real
6//! socket — wrapped in `trusty_common::server::with_standard_middleware`
7//! (CORS/trace/gzip), plus a bind+serve entry point that installs the
8//! shared `trusty_common::shutdown_signal()` graceful-shutdown watcher
9//! (SIGTERM + SIGINT), exactly like `trusty-memory`'s `run_http_on`. `POST
10//! /rpc` and `GET /health` dispatch through the SAME [`crate::jsonrpc::Router`]
11//! the STDIO transport (`crate::serve::transport`) uses via
12//! [`Router::dispatch_json`] — there is exactly one implementation of each
13//! method (`ping`, `health`, `session.*`, …), not one per transport.
14//!
15//! #2054 adds `GET /sessions/{id}/events`: an SSE route that is HTTP's real
16//! live-streaming mechanism for `session.attach`. HTTP `POST /rpc` is
17//! fundamentally one request/one response, so `session.attach` over HTTP
18//! acknowledges immediately (replay burst + this endpoint's URL in
19//! `stream_url`) rather than holding the connection open — a browser or CLI
20//! client then opens this endpoint to receive the ring-buffer replay
21//! followed by live events, and simply closing that connection IS "detach"
22//! for HTTP (there is nothing further to call). See
23//! `crate::jsonrpc::ConnectionContext`'s docs and `session::protocol::attach`
24//! for the full STDIO-vs-HTTP rationale. Multi-client attach falls out for
25//! free here: every `GET` gets its own `crate::events::subscribe()`
26//! receiver.
27//!
28//! What: [`build_axum_router`] (pure, unit-testable) and [`run_http`] (binds
29//! a `TcpListener` — port `0` yields an OS-assigned ephemeral port — logs
30//! the bound address to stderr, never stdout, and serves until graceful
31//! shutdown).
32//!
33//! Deferred: batch JSON-RPC requests (a JSON array body) are not supported —
34//! `POST /rpc` accepts a single request object per call, matching what the
35//! ticket asked for ("single-request is fine for now").
36//!
37//! Test: `http::tests::*` drive [`build_axum_router`] via
38//! `tower::util::ServiceExt::oneshot` (no real socket): `POST /rpc` ping
39//! success, `POST /rpc` malformed JSON -> `-32700`, `GET /health`,
40//! `session.create` + `GET /sessions/{id}/events` SSE replay + live event.
41
42use std::convert::Infallible;
43use std::net::SocketAddr;
44use std::sync::Arc;
45
46use anyhow::{Context, Result};
47use axum::{
48 Json, Router as AxumRouter,
49 body::Bytes,
50 extract::{Path, State},
51 response::sse::{Event as SseEvent, KeepAlive, Sse},
52 routing::{get, post},
53};
54use futures_util::{Stream, StreamExt, stream};
55use tokio::net::TcpListener;
56use tokio::sync::mpsc;
57use tokio_stream::wrappers::BroadcastStream;
58use tracing::info;
59use trusty_common::mcp::Response;
60
61use crate::jsonrpc::{ConnectionContext, Router};
62use crate::serve::methods::health_payload;
63use crate::session::SessionRegistry;
64
65/// Shared axum state: the JSON-RPC router (for `POST /rpc`) and the session
66/// registry (for the SSE route, which reads it directly rather than going
67/// through the router).
68///
69/// Why: both fields are `Arc` so cloning per-request (axum requires `State`
70/// to be `Clone`) is cheap and every route sees the same daemon-wide
71/// instances.
72#[derive(Clone)]
73struct HttpState {
74 router: Arc<Router>,
75 sessions: Arc<SessionRegistry>,
76}
77
78/// Build the pure axum router (no listener bound) exposing `POST /rpc`,
79/// `GET /health`, and `GET /sessions/{id}/events`.
80///
81/// Why: kept separate from [`run_http`] so unit tests exercise routing and
82/// dispatch via `tower::util::ServiceExt::oneshot` without opening a real
83/// socket, and so the standard CORS/trace/gzip middleware stack wraps it
84/// identically to trusty-memory/trusty-search.
85/// What: `POST /rpc` dispatches the request body through
86/// `Router::dispatch_json` (shared with the STDIO transport); `GET /health`
87/// returns [`health_payload`]; `GET /sessions/{id}/events` streams that
88/// session's ring-buffer replay then live events as SSE.
89/// Test: `http_rpc_ping_returns_pong`,
90/// `http_rpc_malformed_json_returns_parse_error`,
91/// `http_health_matches_jsonrpc_health_payload`,
92/// `http_session_events_sse_streams_replay_then_live_event`.
93pub fn build_axum_router(router: Arc<Router>, sessions: Arc<SessionRegistry>) -> AxumRouter {
94 let state = HttpState { router, sessions };
95 let app = AxumRouter::new()
96 .route("/rpc", post(rpc_handler))
97 .route("/health", get(health_handler))
98 .route("/sessions/{id}/events", get(session_events_sse))
99 .with_state(state);
100 trusty_common::server::with_standard_middleware(app)
101}
102
103/// `POST /rpc` — JSON-RPC 2.0 dispatch endpoint.
104///
105/// Why: lets browser clients, curl, and any HTTP-only caller reach the same
106/// method surface the STDIO transport exposes, without learning a REST
107/// vocabulary per method.
108/// What: builds a throwaway [`ConnectionContext`] for this one call (its
109/// `notify` receiver is dropped once this function returns, so any handler
110/// that queued a notification via it — e.g. `session.attach`'s forwarder —
111/// simply stops on its next send; the real HTTP live-streaming path is
112/// `GET /sessions/{id}/events`, not this channel), then dispatches the raw
113/// request body through `Router::dispatch_json` (single request per call —
114/// batch/array bodies are not supported, see module docs). Always returns
115/// HTTP 200; JSON-RPC errors, including malformed JSON (mapped to
116/// `-32700`), are carried in the response envelope's `error` field rather
117/// than the HTTP status.
118/// Test: `http_rpc_ping_returns_pong`, `http_rpc_malformed_json_returns_parse_error`.
119async fn rpc_handler(State(state): State<HttpState>, body: Bytes) -> Json<Response> {
120 let (notify_tx, _notify_rx) = mpsc::unbounded_channel();
121 let ctx = ConnectionContext::new(notify_tx);
122 Json(state.router.dispatch_json(&body, &ctx).await)
123}
124
125/// `GET /health` — liveness probe matching the `health` JSON-RPC method.
126///
127/// Why: the ecosystem convention (trusty-search, trusty-memory) is an
128/// unauthenticated `GET /health`; trusty-console's gateway polls it to
129/// confirm a daemon is alive. Reusing [`health_payload`] — the exact
130/// function the `health` JSON-RPC method calls — keeps the two transports
131/// from drifting into two different health shapes.
132/// What: always returns HTTP 200 with `{"server","version","status"}`.
133/// Test: `http_health_matches_jsonrpc_health_payload`.
134async fn health_handler() -> Json<serde_json::Value> {
135 Json(health_payload())
136}
137
138/// `GET /sessions/{id}/events` — Server-Sent Events stream of a session's
139/// ring-buffer replay followed by its live events.
140///
141/// Why: HTTP's real live-streaming mechanism for `session.attach` (see
142/// module docs for why `POST /rpc` itself can't hold the stream open).
143/// Multiple concurrent `GET`s against the same session id each get their
144/// own subscription (multi-client attach, vision spec Axiom 4) — no extra
145/// bookkeeping needed because `crate::events::subscribe()` already hands
146/// out an independent `broadcast::Receiver` per call.
147/// What: 404 with a JSON-RPC error envelope if the session id is unknown
148/// (`SessionRegistry::replay` -> `session_not_found`, spec-mapped HTTP
149/// status per §13.2). Otherwise: an SSE stream that first emits the
150/// ring-buffer replay (oldest-first) then chains the live bus, filtered to
151/// this `session_id`, forever (until the client disconnects — which is
152/// "detach" for HTTP).
153/// Test: `http_session_events_sse_streams_replay_then_live_event`,
154/// `http_session_events_sse_unknown_session_returns_404`.
155async fn session_events_sse(
156 State(state): State<HttpState>,
157 Path(session_id): Path<String>,
158) -> Result<
159 Sse<impl Stream<Item = Result<SseEvent, Infallible>>>,
160 (axum::http::StatusCode, Json<Response>),
161> {
162 let replay = state.sessions.replay(&session_id).map_err(|e| {
163 let body = Response::err(None, e.code, e.message);
164 (axum::http::StatusCode::NOT_FOUND, Json(body))
165 })?;
166
167 let replay_stream = stream::iter(
168 replay
169 .into_iter()
170 .map(|envelope| Ok(sse_event_for(&envelope))),
171 );
172
173 let filter_id = session_id.clone();
174 let live_stream = BroadcastStream::new(crate::events::subscribe()).filter_map(move |item| {
175 let filter_id = filter_id.clone();
176 async move {
177 match item {
178 Ok(envelope) if envelope.session_id == filter_id => {
179 Some(Ok(sse_event_for(&envelope)))
180 }
181 _ => None,
182 }
183 }
184 });
185
186 Ok(Sse::new(replay_stream.chain(live_stream)).keep_alive(KeepAlive::default()))
187}
188
189/// Serialise one `crate::events::SessionEventEnvelope` as an SSE `data:`
190/// frame.
191///
192/// Why: centralises the (practically infallible — the envelope has no
193/// untagged maps or non-string keys) JSON encoding so `session_events_sse`
194/// doesn't repeat the fallback logic at two call sites. Sending the full
195/// envelope (not just the bare `event`) means the HTTP SSE transport carries
196/// exactly the same `session_id`/`seq`/`at`/`kind`/`event` shape the STDIO
197/// `session.event` notification does (#2055 requirement: both transports
198/// carry the full taxonomy with the envelope).
199/// What: `SseEvent::default().json_data(envelope)`, falling back to an empty
200/// JSON object on the (unreachable in practice) serialisation error rather
201/// than `unwrap`ing.
202fn sse_event_for(envelope: &crate::events::SessionEventEnvelope) -> SseEvent {
203 SseEvent::default()
204 .json_data(envelope)
205 .unwrap_or_else(|_| SseEvent::default().data("{}"))
206}
207
208/// Bind a `TcpListener` and serve `POST /rpc` + `GET /health` +
209/// `GET /sessions/{id}/events` until SIGTERM/SIGINT (graceful) or an
210/// internal axum error.
211///
212/// Why: the top-level entry point `crate::serve::run_http` delegates to this
213/// once the router and session registry are assembled.
214/// What: binds `127.0.0.1:port` (`port = 0` lets the OS assign an ephemeral
215/// port), logs the real bound address to stderr — mirroring
216/// `trusty-memory`'s `run_http_on`, and never touching stdout — then serves
217/// with `trusty_common::shutdown_signal()` installed via
218/// `with_graceful_shutdown`: SIGTERM/SIGINT stop new connections and drain
219/// in-flight requests before this function returns (issue #534 convention).
220/// Test: not directly unit-tested (would require a real socket + a real
221/// signal); [`build_axum_router`]'s tests cover the routing/dispatch logic
222/// this serves.
223pub async fn run_http(router: Router, sessions: Arc<SessionRegistry>, port: u16) -> Result<()> {
224 let addr = SocketAddr::from(([127, 0, 0, 1], port));
225 let listener = TcpListener::bind(addr)
226 .await
227 .with_context(|| format!("tcode serve --http: bind {addr}"))?;
228 let bound = listener
229 .local_addr()
230 .context("tcode serve --http: read bound local address")?;
231 info!("tcode serve --http: listening on http://{bound}");
232 eprintln!("tcode serve --http: listening on http://{bound}");
233
234 let app = build_axum_router(Arc::new(router), sessions);
235 axum::serve(listener, app)
236 .with_graceful_shutdown(trusty_common::shutdown_signal())
237 .await
238 .context("tcode serve --http: axum serve failed")?;
239
240 info!("tcode serve --http: stopped");
241 Ok(())
242}
243
244#[cfg(test)]
245mod tests {
246 use super::*;
247 use axum::body::{Body, to_bytes};
248 use axum::http::{Request, StatusCode};
249 use serde_json::{Value, json};
250 use tower::util::ServiceExt;
251 use trusty_common::mcp::error_codes;
252
253 fn router_and_sessions() -> (Arc<Router>, Arc<SessionRegistry>) {
254 let sessions = Arc::new(SessionRegistry::new());
255 let mut router = Router::new();
256 crate::serve::methods::register(&mut router);
257 crate::session::protocol::register(&mut router, sessions.clone());
258 (Arc::new(router), sessions)
259 }
260
261 async fn body_json(response: axum::response::Response) -> Value {
262 let bytes = to_bytes(response.into_body(), 1024 * 1024).await.unwrap();
263 serde_json::from_slice(&bytes).unwrap()
264 }
265
266 /// `POST /rpc` with a `ping` request must return HTTP 200 and the same
267 /// `{"pong": true}` result the STDIO transport returns.
268 #[tokio::test]
269 async fn http_rpc_ping_returns_pong() {
270 let (router, sessions) = router_and_sessions();
271 let app = build_axum_router(router, sessions);
272 let req_body = json!({"jsonrpc": "2.0", "id": 1, "method": "ping"}).to_string();
273
274 let resp = app
275 .oneshot(
276 Request::builder()
277 .method("POST")
278 .uri("/rpc")
279 .header("content-type", "application/json")
280 .body(Body::from(req_body))
281 .unwrap(),
282 )
283 .await
284 .unwrap();
285
286 assert_eq!(resp.status(), StatusCode::OK);
287 let v = body_json(resp).await;
288 assert_eq!(v["result"], json!({"pong": true}));
289 assert_eq!(v["id"], 1);
290 }
291
292 /// `POST /rpc` with a malformed body must still return HTTP 200 with a
293 /// JSON-RPC `-32700 Parse error` envelope, not a bare HTTP 400.
294 #[tokio::test]
295 async fn http_rpc_malformed_json_returns_parse_error() {
296 let (router, sessions) = router_and_sessions();
297 let app = build_axum_router(router, sessions);
298
299 let resp = app
300 .oneshot(
301 Request::builder()
302 .method("POST")
303 .uri("/rpc")
304 .header("content-type", "application/json")
305 .body(Body::from("not json at all"))
306 .unwrap(),
307 )
308 .await
309 .unwrap();
310
311 assert_eq!(resp.status(), StatusCode::OK);
312 let v = body_json(resp).await;
313 assert_eq!(v["error"]["code"], error_codes::PARSE_ERROR);
314 }
315
316 /// `GET /health` must return the exact payload `health_payload()`
317 /// (and thus the `health` JSON-RPC method) returns.
318 #[tokio::test]
319 async fn http_health_matches_jsonrpc_health_payload() {
320 let (router, sessions) = router_and_sessions();
321 let app = build_axum_router(router, sessions);
322
323 let resp = app
324 .oneshot(
325 Request::builder()
326 .method("GET")
327 .uri("/health")
328 .body(Body::empty())
329 .unwrap(),
330 )
331 .await
332 .unwrap();
333
334 assert_eq!(resp.status(), StatusCode::OK);
335 let v = body_json(resp).await;
336 assert_eq!(v, health_payload());
337 }
338
339 /// `GET /sessions/{id}/events` on an unknown session must 404 with a
340 /// JSON-RPC `session_not_found` envelope.
341 #[tokio::test]
342 async fn http_session_events_sse_unknown_session_returns_404() {
343 let (router, sessions) = router_and_sessions();
344 let app = build_axum_router(router, sessions);
345
346 let resp = app
347 .oneshot(
348 Request::builder()
349 .method("GET")
350 .uri("/sessions/does-not-exist/events")
351 .body(Body::empty())
352 .unwrap(),
353 )
354 .await
355 .unwrap();
356
357 assert_eq!(resp.status(), StatusCode::NOT_FOUND);
358 let v = body_json(resp).await;
359 assert_eq!(v["error"]["code"], -32007);
360 }
361
362 /// `GET /sessions/{id}/events` on a real session must stream the
363 /// ring-buffer replay as SSE `data:` frames.
364 ///
365 /// Why: the response body never terminates (the live half subscribes to
366 /// the bus forever), so this reads a bounded prefix of the body as a
367 /// `Stream` (rather than `axum::body::to_bytes`, which would hang or
368 /// error waiting for a completion that never comes) until the expected
369 /// content shows up or a timeout fires.
370 #[tokio::test]
371 async fn http_session_events_sse_streams_replay() {
372 let (router, sessions) = router_and_sessions();
373 let session = sessions.create("t".to_string(), None, None);
374 let app = build_axum_router(router, sessions);
375
376 let resp = app
377 .oneshot(
378 Request::builder()
379 .method("GET")
380 .uri(format!("/sessions/{}/events", session.id))
381 .body(Body::empty())
382 .unwrap(),
383 )
384 .await
385 .unwrap();
386 assert_eq!(resp.status(), StatusCode::OK);
387
388 let mut stream = resp.into_body().into_data_stream();
389 let mut collected = Vec::new();
390 let read_replay = tokio::time::timeout(std::time::Duration::from_secs(5), async {
391 while !String::from_utf8_lossy(&collected).contains("session_status_changed") {
392 match stream.next().await {
393 Some(Ok(chunk)) => collected.extend_from_slice(&chunk),
394 _ => break,
395 }
396 }
397 })
398 .await;
399
400 assert!(
401 read_replay.is_ok(),
402 "timed out waiting for the SSE replay burst"
403 );
404 let text = String::from_utf8(collected).unwrap();
405 assert!(text.contains("session_started"), "body so far: {text}");
406 assert!(
407 text.contains("session_status_changed"),
408 "body so far: {text}"
409 );
410 // #2055: the SSE frames must carry the full envelope, not a bare
411 // event — `seq` and the top-level `kind` field must both appear.
412 assert!(text.contains("\"seq\":1"), "body so far: {text}");
413 assert!(
414 text.contains("\"kind\":\"session_started\""),
415 "body so far: {text}"
416 );
417 }
418}