Skip to main content

trusty_code/session/
events_stream.rs

1//! `session.events` — the streaming method a UDS client tails a session
2//! through (#6637).
3//!
4//! Why: `session.attach` is the one production handler that pushes on
5//! `crate::jsonrpc::ConnectionContext::notify`, and a UDS connection served by
6//! [`trusty_common::uds::server`] reads one request frame and writes one
7//! response frame, so it is not a push channel. HTTP solved the same problem
8//! with a dedicated SSE route (`crate::serve::http::session_events_sse`);
9//! this is that route's transport-native twin, registered with
10//! [`trusty_common::uds::server::RpcRouter::typed_stream`] so the answer is a
11//! sequence of frames instead of one.
12//!
13//! What: [`open`](crate::session::events_stream::open) snapshots the session's
14//! ring buffer, then forwards the
15//! daemon-global event bus filtered to that session, into the
16//! [`trusty_common::uds::server::RpcStreamItems`] channel the router writes
17//! frames from.
18//! [`SessionEventsParams::after_seq`](crate::session::events_stream::SessionEventsParams::after_seq)
19//! is what HTTP has no
20//! equivalent of: a client whose connection was cut names the last `seq` it
21//! confirmed, and the replay resumes above it instead of repeating the whole
22//! ring. The subscribe happens BEFORE the replay snapshot so an event
23//! published between the two is delivered rather than dropped, and every
24//! forwarded envelope's `seq` is compared against the highest already sent, so
25//! the overlap that ordering creates never reaches the client twice.
26//!
27//! **A lagged bus ends the stream.** The `tokio::sync::broadcast` bus drops
28//! the oldest envelopes for a receiver that falls behind, so continuing would
29//! deliver a tail with a hole in it that the client could not see. The stream
30//! ends with an error frame instead; the client reconnects with `after_seq`
31//! and the ring buffer refills the gap. `session_events_sse` skips a lag
32//! silently, which is the behaviour this deliberately does not copy.
33//!
34//! Test: `events_stream_tests`.
35
36use std::sync::Arc;
37
38use serde::Deserialize;
39use serde_json::Value;
40use tokio::sync::broadcast;
41use tokio::sync::mpsc;
42use tokio_stream::StreamExt as _;
43use tokio_stream::wrappers::BroadcastStream;
44use tokio_stream::wrappers::errors::BroadcastStreamRecvError;
45use trusty_common::uds::server::{RpcError, RpcStreamItems};
46
47use crate::events::SessionEventEnvelope;
48use crate::session::SessionRegistry;
49
50/// The method name this stream is registered under.
51pub const METHOD: &str = "session.events";
52
53/// How many event frames may sit unwritten before the producer waits.
54///
55/// Why: back-pressure rather than an unbounded queue — the consumer is one
56/// socket, and a client that stops reading must slow the producer down instead
57/// of growing memory without limit. Sized to the same order as the session
58/// ring buffer so a burst of a whole replay does not block.
59const CHANNEL_CAPACITY: usize = 256;
60
61/// `session.events`' params.
62#[derive(Debug, Clone, Deserialize)]
63pub struct SessionEventsParams {
64    /// Session whose events to tail.
65    pub session_id: String,
66    /// Resume above this `seq`, skipping everything already confirmed.
67    ///
68    /// Absent means "replay the whole ring buffer", which is what a first
69    /// attach wants and what HTTP's SSE route always does.
70    #[serde(default)]
71    pub after_seq: Option<u64>,
72}
73
74/// Open one `session.events` stream.
75///
76/// Why/What: see module docs.
77///
78/// # Errors
79///
80/// [`crate::jsonrpc::RpcError::session_not_found`], converted onto the
81/// transport's error type, when `session_id` names no live session — the same
82/// refusal `session_events_sse` answers as a `404`.
83///
84/// Test: `events_stream_tests::session_events_replays_ring_buffer_then_live`,
85/// `events_stream_tests::session_events_after_seq_skips_replayed_events`,
86/// `events_stream_tests::session_events_unknown_session_is_refused`.
87pub async fn open(
88    sessions: Arc<SessionRegistry>,
89    params: SessionEventsParams,
90) -> Result<RpcStreamItems, RpcError> {
91    // Subscribed BEFORE the snapshot: an envelope published between the two
92    // would otherwise be in neither half. The overlap this creates is removed
93    // by the `seq` floor in `forward`.
94    let live = crate::events::subscribe();
95    let replay = sessions.replay(&params.session_id)?;
96    // #8100: this stream's client can answer a permission prompt it sees, so
97    // it counts as a prompter for exactly as long as the stream runs.
98    let prompter = sessions.claim_prompter(&params.session_id);
99    let (tx, rx) = mpsc::channel(CHANNEL_CAPACITY);
100    let session_id = params.session_id;
101    tokio::spawn(async move {
102        let _prompter = prompter;
103        forward(session_id, params.after_seq, replay, live, tx).await;
104    });
105    Ok(rx)
106}
107
108/// Replay, then tail, until the client goes away or the bus lags.
109///
110/// `delivered` is the highest `seq` already written. It starts at the caller's
111/// `after_seq`, rises through the replay, and then filters the live half — one
112/// rule covering both the client's resume point and the replay/subscribe
113/// overlap.
114async fn forward(
115    session_id: String,
116    after_seq: Option<u64>,
117    replay: Vec<SessionEventEnvelope>,
118    live: broadcast::Receiver<SessionEventEnvelope>,
119    tx: mpsc::Sender<Result<Value, RpcError>>,
120) {
121    let mut delivered = after_seq;
122    for envelope in replay {
123        if delivered.is_some_and(|floor| envelope.seq <= floor) {
124            continue;
125        }
126        delivered = Some(envelope.seq);
127        if !send(&tx, &envelope).await {
128            return;
129        }
130    }
131
132    let mut live = BroadcastStream::new(live);
133    while let Some(item) = live.next().await {
134        match item {
135            Ok(envelope) => {
136                if envelope.session_id != session_id {
137                    continue;
138                }
139                if delivered.is_some_and(|floor| envelope.seq <= floor) {
140                    continue;
141                }
142                delivered = Some(envelope.seq);
143                if !send(&tx, &envelope).await {
144                    return;
145                }
146            }
147            Err(BroadcastStreamRecvError::Lagged(missed)) => {
148                let resume = delivered
149                    .map(|seq| format!("after_seq {seq}"))
150                    .unwrap_or_else(|| "no after_seq".to_string());
151                let _ = tx
152                    .send(Err(RpcError::internal(format!(
153                        "event bus lagged and dropped {missed} events for session \
154                         {session_id}; reconnect with {resume}"
155                    ))))
156                    .await;
157                return;
158            }
159        }
160    }
161}
162
163/// Write one envelope, reporting whether the stream may continue.
164///
165/// `false` means the receiver is gone (the client disconnected) or the
166/// envelope would not serialise — the second is a bug on this side of the
167/// wire, so it is reported as a terminal error rather than skipped.
168async fn send(tx: &mpsc::Sender<Result<Value, RpcError>>, envelope: &SessionEventEnvelope) -> bool {
169    match serde_json::to_value(envelope) {
170        Ok(value) => tx.send(Ok(value)).await.is_ok(),
171        Err(e) => {
172            let _ = tx
173                .send(Err(RpcError::internal(format!(
174                    "serialize session event: {e}"
175                ))))
176                .await;
177            false
178        }
179    }
180}
181
182#[cfg(test)]
183#[path = "events_stream_tests.rs"]
184mod events_stream_tests;