trusty_code/workstreams/sse.rs
1//! Workstream-level SSE event aggregation route (DOC-48 §5.3, §5.3.1; issue
2//! #3297, epic #3292); thin `trusty-agents-common::transport` adapter (issue
3//! #3299, Phase 1B).
4//!
5//! # Spec References
6//!
7//! - [`SPEC-WS-05~draft`](docs/specs/DOC-48-tcode-workstreams.md#SPEC-WS-05~draft) §5.3, §5.3.1
8//! - [`SPEC-WS-07~draft`](docs/specs/DOC-48-tcode-workstreams.md#SPEC-WS-07~draft) AC-7
9//!
10//! Why: `GET /sessions/{id}/events` (`crate::serve::http::session_events_sse`)
11//! is a direct lookup against ONE session's ring buffer + live filter. A
12//! workstream is a GROUP of sessions (§2.1), so observing "this workstream"
13//! is not a lookup at all — it is a fan-out: subscribe once to the daemon's
14//! existing session-scoped event bus (`crate::events::subscribe`, already
15//! shared by every per-session SSE connection) and forward only the events
16//! whose `session_id` is currently bound to this workstream, tagged with the
17//! generic `{session_id, event_type, payload}` envelope AC-7.2 requires.
18//! "Currently bound" is re-checked against the store on every event (not a
19//! snapshot taken at subscribe time) so a session added to the workstream
20//! after the client connected is picked up without a reconnect (§5.3 point
21//! 4) — cheap in practice because `WorkstreamStore::get` only re-parses the
22//! backing file when its (mtime, len) fingerprint actually changed.
23//!
24//! **AC-7 harness-agnostic seam (Phase 1B, issue #3299):** the fan-out
25//! algorithm itself now lives in
26//! [`trusty_agents_common::transport::aggregate_live`] — this module is a
27//! thin adapter that implements the shared `EventSource`/`MembershipProvider`
28//! traits over `crate::events`/`SharedWorkstreamStore` and supplies the
29//! `classify` closure encoding tcode's two group-scoped bypass events
30//! (`WorkstreamActivationChanged`, `WorkstreamStateInferred`). Behavior is
31//! byte-for-byte identical to the Phase 1A implementation this replaces (see
32//! `sse_tests`, ported unchanged); only the fan-out combinator itself moved.
33//!
34//! What: [`WorkstreamEventEnvelope`] (a type alias over the shared
35//! `EventEnvelope<Event>`), [`aggregate_live`] (this module's adapter
36//! function — constructs the two trait impls and the `classify` closure,
37//! then delegates to the shared combinator), and [`routes`] (the single
38//! `GET /workstreams/{id}/events` axum route, merged into
39//! `crate::serve::http::build_axum_router` alongside `rest::workstreams`).
40//! Unknown workstream id -> `404`; malformed (non-UUID) id -> `400`; a
41//! CLOSED workstream is still observable (`200`, not `404`) because its
42//! existing bound sessions "remain valid and may accumulate turns" after
43//! closure (§4.4) — closing only stops NEW session bindings, not event
44//! delivery for the ones it already has. A workstream with zero bound
45//! sessions returns `200` with a stream that simply never emits (until a
46//! future session is added or the workstream's activation state changes) —
47//! it does not error or close early.
48//! Test: `sse_tests`.
49
50use std::convert::Infallible;
51
52use async_trait::async_trait;
53use axum::extract::{Path, State};
54use axum::response::sse::{Event as SseEvent, KeepAlive, Sse};
55use axum::routing::get;
56use axum::{Json, Router as AxumRouter};
57use futures_util::{Stream, StreamExt};
58use tokio_stream::wrappers::BroadcastStream;
59use trusty_agents_common::transport::{
60 BoxEventStream, EventSource, MembershipProvider, SourceEvent,
61};
62use trusty_mcp::Response;
63use uuid::Uuid;
64
65use crate::events::Event;
66use crate::jsonrpc::RpcError;
67
68use super::activation::SharedWorkstreamStore;
69use super::model::WorkstreamId;
70use super::store::StoreError;
71
72/// The harness-agnostic wire envelope AC-7.2 requires: `{session_id,
73/// event_type, payload}` — a type alias over
74/// `trusty_agents_common::transport::EventEnvelope<Event>` (Phase 1B, issue
75/// #3299), deliberately distinct from `crate::events::SessionEventEnvelope`
76/// (which carries `seq`/`at`/`kind`/`event`, tuned for one session's
77/// ring-buffer replay).
78pub type WorkstreamEventEnvelope = trusty_agents_common::transport::EventEnvelope<Event>;
79
80/// [`EventSource`] adapter over `crate::events` — subscribes to the SAME
81/// daemon-global broadcast bus every per-session SSE connection already
82/// reads, wrapping each envelope into the shared crate's
83/// session-id/event-type/payload triple.
84struct TcodeEventSource;
85
86impl EventSource for TcodeEventSource {
87 type Payload = Event;
88
89 fn subscribe(&self) -> BoxEventStream<Event> {
90 Box::pin(
91 BroadcastStream::new(crate::events::subscribe()).filter_map(|item| async move {
92 item.ok().map(|envelope| SourceEvent {
93 session_id: envelope.session_id.clone(),
94 event_type: envelope.kind.clone(),
95 payload: envelope.event.clone(),
96 })
97 }),
98 )
99 }
100}
101
102/// [`MembershipProvider`] adapter over [`SharedWorkstreamStore`] — "is this
103/// session currently in `workstream_id`'s `session_ids`" re-fetched from the
104/// store on every call (never a stale snapshot), matching §5.3's dynamic
105/// membership requirement. A store lookup failure (the workstream vanished
106/// from under an open connection — not reachable via any current mutation
107/// path, since `workstream.close` never removes a record) is treated as
108/// "no match" per this trait's documented contract, matching this route's
109/// "stay open" bias for a zero-session workstream.
110#[derive(Clone)]
111struct WorkstreamMembership(SharedWorkstreamStore);
112
113#[async_trait]
114impl MembershipProvider<WorkstreamId> for WorkstreamMembership {
115 async fn contains(&self, group: &WorkstreamId, session_id: &str) -> bool {
116 self.0
117 .lock()
118 .await
119 .get(*group)
120 .await
121 .map(|ws| ws.session_ids.iter().any(|s| s == session_id))
122 .unwrap_or(false)
123 }
124}
125
126/// The `classify` bypass: forwards `WorkstreamActivationChanged` iff it
127/// names `target` as its `new_active_id` OR `prior_id` (a workstream
128/// observer must learn when IT stops being active, not only when a session
129/// it owns emits, §6.3), and `WorkstreamStateInferred` iff its
130/// `workstream_id` names `target` (an observer must learn its own state
131/// changed — e.g. it was closed — even with zero bound sessions). Any other
132/// event falls through to [`WorkstreamMembership`] (`None`). `target` is
133/// `&str` (not `&WorkstreamId`) so [`aggregate_live`] can stringify the id
134/// ONCE at stream construction rather than on every event flowing over the
135/// daemon-global bus.
136fn classify(event: &Event, target: &str) -> Option<bool> {
137 match event {
138 Event::WorkstreamActivationChanged {
139 new_active_id,
140 prior_id,
141 } => Some(new_active_id.as_deref() == Some(target) || prior_id.as_deref() == Some(target)),
142 Event::WorkstreamStateInferred { workstream_id, .. } => {
143 Some(workstream_id.as_str() == target)
144 }
145 _ => None,
146 }
147}
148
149/// Build the live aggregation stream for one workstream (no ring-buffer
150/// replay — see module docs).
151///
152/// Why: the single seam [`routes`]' handler drives; kept as a free function
153/// (not inlined into the handler) so a unit test can exercise the fan-out
154/// logic directly against a `SharedWorkstreamStore`, without going through
155/// axum at all. As of Phase 1B (issue #3299) this is a thin adapter over
156/// [`trusty_agents_common::transport::aggregate_live`] — see this module's
157/// docs for the trait impls it supplies.
158/// What: delegates to the shared combinator with [`TcodeEventSource`],
159/// [`WorkstreamMembership`], and the [`classify`] bypass closure.
160/// Test: `sse_tests::fan_out_tags_events_from_bound_sessions_only`,
161/// `sse_tests::activation_changed_event_is_forwarded_regardless_of_session_binding`,
162/// `sse_tests::state_inferred_event_is_forwarded_for_this_workstream_only`,
163/// `sse_tests::empty_workstream_stream_yields_nothing`.
164pub fn aggregate_live(
165 workstream_id: WorkstreamId,
166 store: SharedWorkstreamStore,
167) -> impl Stream<Item = WorkstreamEventEnvelope> {
168 // Stringified ONCE here (not per event): the classify closure runs for
169 // every event on the daemon-global bus, so it must not re-allocate the
170 // target id each time.
171 let target = workstream_id.to_string();
172 trusty_agents_common::transport::aggregate_live(
173 workstream_id,
174 TcodeEventSource,
175 WorkstreamMembership(store),
176 move |event: &Event, _group: &WorkstreamId| classify(event, &target),
177 )
178}
179
180/// Serialise one [`WorkstreamEventEnvelope`] as an SSE `data:` frame — mirrors
181/// `crate::serve::http::sse_event_for`'s (practically infallible) fallback
182/// convention.
183fn sse_event_for(envelope: &WorkstreamEventEnvelope) -> SseEvent {
184 SseEvent::default()
185 .json_data(envelope)
186 .unwrap_or_else(|_| SseEvent::default().data("{}"))
187}
188
189/// Map a [`StoreError`] onto the JSON-RPC error taxonomy (mirrors
190/// `crate::workstreams::protocol::map_store_err`, kept separate since that
191/// function is private to `protocol`).
192///
193/// `pub(super)` since #6637: `crate::workstreams::events_stream` answers the
194/// same two refusals over the socket transport and must report the same codes.
195pub(super) fn map_store_err(err: StoreError) -> RpcError {
196 match err {
197 StoreError::NotFound(id) => RpcError::not_found(format!("workstream not found: {id}")),
198 StoreError::Io(_) | StoreError::Serialize(_) => RpcError::internal(err.to_string()),
199 }
200}
201
202/// Shared axum state for this route: just the workstream store.
203#[derive(Clone)]
204struct WorkstreamSseState {
205 store: SharedWorkstreamStore,
206}
207
208/// `GET /workstreams/{id}/events` — SSE aggregation over a workstream's
209/// bound sessions.
210///
211/// Why: see module docs for the full fan-out design.
212/// What: `400` (`-32602 invalid_params`) if `id` is not a valid UUID; `404`
213/// (`-32002 not_found`) if it names no existing workstream (a CLOSED
214/// workstream is NOT a 404 — see module docs); otherwise `200` with an SSE
215/// stream from [`aggregate_live`], kept alive with axum's default
216/// keep-alive comments (matching `session_events_sse`'s convention).
217/// Test: `sse_tests::unknown_id_returns_404`,
218/// `sse_tests::malformed_id_returns_400`.
219async fn workstream_events_sse(
220 State(state): State<WorkstreamSseState>,
221 Path(id): Path<String>,
222) -> Result<
223 Sse<impl Stream<Item = Result<SseEvent, Infallible>>>,
224 (axum::http::StatusCode, Json<Response>),
225> {
226 let ws_id = Uuid::parse_str(&id).map(WorkstreamId::from).map_err(|e| {
227 let err = RpcError::invalid_params(format!("invalid workstream id: {e}"));
228 (
229 axum::http::StatusCode::BAD_REQUEST,
230 Json(Response::err(None, err.code, err.message)),
231 )
232 })?;
233
234 {
235 let mut store = state.store.lock().await;
236 store.get(ws_id).await.map_err(map_store_err).map_err(|e| {
237 (
238 axum::http::StatusCode::NOT_FOUND,
239 Json(Response::err(None, e.code, e.message)),
240 )
241 })?;
242 }
243
244 let stream = aggregate_live(ws_id, state.store.clone()).map(|env| Ok(sse_event_for(&env)));
245 Ok(Sse::new(stream).keep_alive(KeepAlive::default()))
246}
247
248/// Build the `GET /workstreams/{id}/events` route group.
249///
250/// Why: kept separate from `crate::serve::http::build_axum_router` so this
251/// route is unit-testable via `tower::util::ServiceExt::oneshot` on its own,
252/// exactly like every `rest::*` group — `crate::serve::rest::workstreams`
253/// merges the CRUD/activation REST surface, this merges the observation
254/// surface, both sharing the SAME `SharedWorkstreamStore` handle the daemon
255/// boot path constructs.
256/// What: one route, `with_state`-erased to `axum::Router<()>` so the caller
257/// can `.merge()` it.
258/// Test: `sse_tests::*`.
259pub fn routes(store: SharedWorkstreamStore) -> AxumRouter {
260 AxumRouter::new()
261 .route("/workstreams/{id}/events", get(workstream_events_sse))
262 .with_state(WorkstreamSseState { store })
263}
264
265#[cfg(test)]
266#[path = "sse_tests.rs"]
267mod sse_tests;