Skip to main content

trusty_code/workstreams/
events_stream.rs

1//! `workstream.events` — the streaming method a UDS client observes one
2//! workstream through (#6637).
3//!
4//! Why: `crate::workstreams::sse::routes` serves the same fan-out over HTTP,
5//! and the TUI consumed it as SSE. The socket transport has no long-lived GET,
6//! so the fan-out is registered as a
7//! [`trusty_common::uds::server::RpcRouter::typed_stream`] method instead. The
8//! fan-out itself is NOT reimplemented — [`crate::workstreams::sse::aggregate_live`]
9//! stays the single definition of which events belong to a workstream, and
10//! this module is the bridge from its `Stream` onto the router's channel.
11//!
12//! What: [`open`](crate::workstreams::events_stream::open) validates the id
13//! and the workstream's existence exactly as
14//! `workstream_events_sse` does, then forwards
15//! [`crate::workstreams::WorkstreamEventEnvelope`]s until the client
16//! disconnects.
17//!
18//! **There is no `after_seq` here, and there cannot be.** `aggregate_live` is
19//! live-only by construction: a workstream has no ring buffer of its own, only
20//! the per-session rings its bound sessions each hold, and those carry
21//! per-session `seq` values with no workstream-wide ordering to resume from. A
22//! client that reconnects re-subscribes bare and observes from that moment —
23//! the same contract the HTTP route always had. `session.events`'s resume is
24//! not portable to this method.
25//!
26//! Test: `crate::serve::uds_tests::stream_names_win_over_the_fallback` pins
27//! the registration; the fan-out rules themselves are covered by `sse_tests`.
28
29use serde::Deserialize;
30use tokio::sync::mpsc;
31use tokio_stream::StreamExt as _;
32use trusty_common::uds::server::{RpcError, RpcStreamItems};
33use uuid::Uuid;
34
35use super::activation::SharedWorkstreamStore;
36use super::model::WorkstreamId;
37use super::store::StoreError;
38
39/// The method name this stream is registered under.
40pub const METHOD: &str = "workstream.events";
41
42/// How many event frames may sit unwritten before the producer waits — see
43/// `crate::session::events_stream`'s constant of the same name.
44const CHANNEL_CAPACITY: usize = 256;
45
46/// `workstream.events`' params.
47#[derive(Debug, Clone, Deserialize)]
48pub struct WorkstreamEventsParams {
49    /// Workstream to observe. A UUID; anything else is `invalid_params`.
50    pub workstream_id: String,
51}
52
53/// Open one `workstream.events` stream.
54///
55/// Why/What: see module docs.
56///
57/// # Errors
58///
59/// `invalid_params` for an id that is not a UUID, and `not_found` for one that
60/// names no workstream — the `400` and `404` `workstream_events_sse` answers.
61/// A CLOSED workstream is observable, not an error (DOC-48 §4.4).
62///
63/// Test: `crate::serve::uds_tests::workstream_events_refuses_an_unknown_id`.
64pub async fn open(
65    store: SharedWorkstreamStore,
66    params: WorkstreamEventsParams,
67) -> Result<RpcStreamItems, RpcError> {
68    let id = Uuid::parse_str(&params.workstream_id)
69        .map(WorkstreamId::from)
70        .map_err(|e| RpcError::invalid_params(format!("invalid workstream id: {e}")))?;
71
72    {
73        let mut guard = store.lock().await;
74        guard.get(id).await.map_err(map_store_err)?;
75    }
76
77    let (tx, rx) = mpsc::channel(CHANNEL_CAPACITY);
78    let stream = super::sse::aggregate_live(id, store);
79    tokio::spawn(async move {
80        tokio::pin!(stream);
81        while let Some(envelope) = stream.next().await {
82            let frame = match serde_json::to_value(&envelope) {
83                Ok(value) => Ok(value),
84                Err(e) => Err(RpcError::internal(format!(
85                    "serialize workstream event: {e}"
86                ))),
87            };
88            let failed = frame.is_err();
89            if tx.send(frame).await.is_err() || failed {
90                return;
91            }
92        }
93    });
94    Ok(rx)
95}
96
97/// Map a [`StoreError`] onto the transport's error type.
98///
99/// Delegates to [`crate::workstreams::sse::map_store_err`] rather than
100/// restating the taxonomy — the HTTP route and this stream must refuse an
101/// unknown workstream with the same code.
102fn map_store_err(err: StoreError) -> RpcError {
103    super::sse::map_store_err(err).into()
104}