Skip to main content

trusty_code/jsonrpc/
context.rs

1//! Per-connection context threaded through every method handler (#2054).
2//!
3//! Why: `session.attach` needs a way to push server-initiated JSON-RPC
4//! notifications (session lifecycle/events) back to the SAME connection
5//! that called it, asynchronously, after the initial response has already
6//! been sent. Most handlers (`ping`, `health`, `session.list`, …) have no
7//! use for this, but the [`Router`](super::router::Router) dispatch path
8//! must thread it uniformly so a handful of methods aren't a special case
9//! with a different call signature.
10//! What: [`ConnectionContext`] carries a `connection_id` (identifies which
11//! connection/subscriber this call came from — one per STDIO process
12//! lifetime, one per HTTP `POST /rpc` call) and a [`NotifySender`] the
13//! connection's transport drains and writes to the wire. Over STDIO, the
14//! transport loop keeps one long-lived receiver for the whole process and
15//! interleaves notifications with request/response lines on stdout. Over
16//! HTTP, each `POST /rpc` call gets a throwaway channel — any queued
17//! notification vanishes once the response is written, because HTTP's real
18//! streaming path for `session.attach` is the dedicated `GET
19//! /sessions/{id}/events` SSE route (see `crate::serve::http`), not this
20//! channel. A handler that spawns a background forwarder using `notify`
21//! (like `session.attach`) must treat a failed `send` as "the connection is
22//! gone" and stop.
23//! Test: `context::tests::connection_context_is_constructible`.
24
25use serde_json::Value;
26use tokio::sync::mpsc;
27use uuid::Uuid;
28
29/// Channel used to push a fully-formed JSON-RPC wire object (a `Response`
30/// serialised to `Value`, or a server-initiated notification) to the
31/// connection's outbound stream, asynchronously, outside the normal
32/// request/response cycle.
33///
34/// Why: `serde_json::Value` (rather than `trusty_mcp::Response`) is
35/// the channel item type because a server-initiated *notification*
36/// (`{"jsonrpc":"2.0","method":"session.event","params":{...}}`) has no
37/// `result`/`error` field — it isn't a `Response` at all — so the channel
38/// must be able to carry either shape. The transport writes whatever
39/// arrives verbatim as one NDJSON line.
40/// What: `mpsc::UnboundedSender<Value>`. Unbounded because session events
41/// are rare relative to request/response traffic and a bounded channel
42/// would require a backpressure policy (drop? block the emitter?) that no
43/// current requirement calls for.
44pub type NotifySender = mpsc::UnboundedSender<Value>;
45
46/// Per-connection state passed to every JSON-RPC method handler.
47///
48/// Why: threading this uniformly (rather than adding a second handler trait
49/// just for `session.attach`) keeps the dispatch path — and every future
50/// method — on one call signature. See the module docs for the STDIO vs.
51/// HTTP distinction.
52/// What: `connection_id` is a fresh `Uuid` per STDIO process invocation or
53/// per HTTP `POST /rpc` call; `notify` is that connection's outbound
54/// notification sink.
55/// Test: `context::tests::connection_context_is_constructible`.
56#[derive(Clone)]
57pub struct ConnectionContext {
58    pub connection_id: Uuid,
59    pub notify: NotifySender,
60}
61
62impl ConnectionContext {
63    /// Build a fresh context with a brand-new `connection_id` and the given
64    /// notify sender.
65    ///
66    /// Why: every transport builds exactly one context per connection
67    /// (STDIO: once per process; HTTP: once per `POST /rpc` call).
68    /// What: `Uuid::new_v4()` for the id, `notify` stored verbatim.
69    /// Test: `context::tests::connection_context_is_constructible`.
70    pub fn new(notify: NotifySender) -> Self {
71        Self {
72            connection_id: Uuid::new_v4(),
73            notify,
74        }
75    }
76}
77
78#[cfg(test)]
79mod tests {
80    use super::*;
81
82    /// A context must be constructible and expose a usable notify sender.
83    #[test]
84    fn connection_context_is_constructible() {
85        let (tx, mut rx) = mpsc::unbounded_channel::<Value>();
86        let ctx = ConnectionContext::new(tx);
87        ctx.notify.send(serde_json::json!({"ok": true})).unwrap();
88        assert_eq!(rx.try_recv().unwrap(), serde_json::json!({"ok": true}));
89    }
90}