From 2e4afb752bab5edb7a3bb39e08f3d7f1d76a726a Mon Sep 17 00:00:00 2001 From: piquel Date: Sun, 22 Nov 2026 14:49:03 +0100 Subject: [PATCH 1/2] refactor(core): name live stream messages in one enum The daemon's live server-sent event streams sent `event`, `timeline`, `history_expired`, `stream_error` and `access_ended` as literals, and the client's timeline stream and the dashboard's `EventStream` matched on the same literals. `StreamMessage` in piqueld-core names each one, and both ends use its variants: the daemon sends `name.as_str()`, the client parses the name and still skips ones it doesn't know, and the dashboard subscribes to typed names. Part of PQD-161 --- .../src/browser/management/timeline.rs | 10 ++--- apps/piqueld-ui/src/browser/stream.rs | 34 ++++++++------- apps/piqueld/src/api/http/events.rs | 16 +++---- apps/piqueld/src/api/http/live.rs | 25 +++++++---- apps/piqueld/src/api/http/operations.rs | 7 ++- crates/piqueld-client/src/lib.rs | 2 + crates/piqueld-client/src/operations.rs | 10 ++--- crates/piqueld-core/src/api/mod.rs | 2 + crates/piqueld-core/src/api/streams.rs | 43 +++++++++++++++++++ docs/dev/rust-conventions.md | 16 ++++--- 10 files changed, 111 insertions(+), 54 deletions(-) create mode 100644 crates/piqueld-core/src/api/streams.rs diff --git a/apps/piqueld-ui/src/browser/management/timeline.rs b/apps/piqueld-ui/src/browser/management/timeline.rs index f900ddb80..e202a943d 100644 --- a/apps/piqueld-ui/src/browser/management/timeline.rs +++ b/apps/piqueld-ui/src/browser/management/timeline.rs @@ -24,7 +24,7 @@ use leptos_router::components::A; use piqueld_client::observability::Elapsed; use piqueld_client::timeline::{Progress, Step, StepKey, StepState, Timeline}; use piqueld_client::{ - API_PREFIX, BuildRecord, Client, Event, Operation, Phase, access::AppPermission, + API_PREFIX, BuildRecord, Client, Event, Operation, Phase, StreamMessage, access::AppPermission, }; use std::collections::VecDeque; use std::time::Duration; @@ -136,9 +136,9 @@ impl LiveTimeline { ); let stream = EventStream::open( &url, - &["timeline", "access_ended"], - move |kind, data| { - if kind == "access_ended" { + &[StreamMessage::Timeline, StreamMessage::AccessEnded], + move |name, data| { + if name == StreamMessage::AccessEnded { self.error .set(Some("You can no longer read this operation.".into())); self.stop(); @@ -1239,7 +1239,7 @@ fn EventFeed(operation: String, live: Memo, attempt: Memo) -> impl In }; stream.set_value(EventStream::open( &url, - &["event"], + &[StreamMessage::Event], move |_, data| { let Ok(event) = serde_json::from_str::(data) else { return; diff --git a/apps/piqueld-ui/src/browser/stream.rs b/apps/piqueld-ui/src/browser/stream.rs index 88abffed6..c20267aac 100644 --- a/apps/piqueld-ui/src/browser/stream.rs +++ b/apps/piqueld-ui/src/browser/stream.rs @@ -1,5 +1,6 @@ //! Server-sent event streams over the browser's `EventSource`. use leptos::wasm_bindgen::{JsCast, closure::Closure}; +use piqueld_client::StreamMessage; use std::rc::Rc; use web_sys::{Event, EventSource, MessageEvent}; @@ -11,34 +12,36 @@ type Listener = Closure; /// connection on its own; dropping it closes the stream. pub(super) struct EventStream { source: EventSource, - listeners: Vec<(&'static str, Listener)>, + listeners: Vec<(StreamMessage, Listener)>, _error: Closure, } impl EventStream { - /// Opens `url`, calling `message` with the kind and data of each message - /// of one of `kinds`, and `failed` once the browser gave up on the + /// Opens `url`, calling `message` with the name and data of each message + /// named one of `names`, and `failed` once the browser gave up on the /// stream: it was refused, or ended in a way the browser does not retry. /// `None` when the browser refused to open it. pub(super) fn open( url: &str, - kinds: &[&'static str], - message: impl Fn(&str, &str) + 'static, + names: &[StreamMessage], + message: impl Fn(StreamMessage, &str) + 'static, failed: impl Fn() + 'static, ) -> Option { let source = EventSource::new(url).ok()?; let message = Rc::new(message); - let listeners = kinds + let listeners = names .iter() - .map(|&kind| { + .map(|&name| { let message = Rc::clone(&message); let listener = Listener::new(move |event: MessageEvent| { - message(kind, &event.data().as_string().unwrap_or_default()); + message(name, &event.data().as_string().unwrap_or_default()); }); // Only fails for a listener that is not a function. - let _ = source - .add_event_listener_with_callback(kind, listener.as_ref().unchecked_ref()); - (kind, listener) + let _ = source.add_event_listener_with_callback( + name.as_str(), + listener.as_ref().unchecked_ref(), + ); + (name, listener) }) .collect(); let error = Closure::::new({ @@ -62,10 +65,11 @@ impl EventStream { impl Drop for EventStream { fn drop(&mut self) { self.source.set_onerror(None); - for (kind, listener) in &self.listeners { - let _ = self - .source - .remove_event_listener_with_callback(kind, listener.as_ref().unchecked_ref()); + for (name, listener) in &self.listeners { + let _ = self.source.remove_event_listener_with_callback( + name.as_str(), + listener.as_ref().unchecked_ref(), + ); } self.source.close(); } diff --git a/apps/piqueld/src/api/http/events.rs b/apps/piqueld/src/api/http/events.rs index 1da972d81..20ee50927 100644 --- a/apps/piqueld/src/api/http/events.rs +++ b/apps/piqueld/src/api/http/events.rs @@ -17,7 +17,7 @@ use axum::{ use piqueld_core::ApiErrorCode; use piqueld_core::{ Event, - api::{Envelope, Page}, + api::{Envelope, Page, StreamMessage}, observability::{EventFilter, EventKinds, EventScope}, }; use piqueld_store::Visibility; @@ -248,7 +248,7 @@ impl Follow for FollowEvents { if let Some(event) = self.pending.pop_front() { self.after = event.id; let message = ServerEvent::default().id(format!("v1:{}", self.after)); - return Some(live::json(message, "event", event)); + return Some(live::json(message, StreamMessage::Event, event)); } if self.checkpoint > self.after { // An ID-only message moves Last-Event-ID past events the filter @@ -270,22 +270,18 @@ impl Follow for FollowEvents { self.checkpoint = next; } Err(error) => { - let kind = if matches!( + let name = if matches!( error, crate::api::ApplicationError::Store( piqueld_store::StoreError::HistoryExpired ) ) { - "history_expired" + StreamMessage::HistoryExpired } else { - "stream_error" + StreamMessage::StreamError }; self.done = true; - return Some( - ServerEvent::default() - .event(kind) - .data("Reload history before reconnecting"), - ); + return Some(live::named(name).data("Reload history before reconnecting")); } } } diff --git a/apps/piqueld/src/api/http/live.rs b/apps/piqueld/src/api/http/live.rs index 25638e1c1..559b9d4fd 100644 --- a/apps/piqueld/src/api/http/live.rs +++ b/apps/piqueld/src/api/http/live.rs @@ -6,6 +6,7 @@ use axum::response::{ sse::{Event as ServerEvent, KeepAlive}, }; use futures_util::Stream; +use piqueld_core::api::StreamMessage; use std::{convert::Infallible, time::Duration}; use tokio::{sync::watch, time::Instant}; @@ -31,14 +32,22 @@ pub(super) trait Follow: Send + 'static { } } -/// `message` named `kind` with `data` as JSON, or a `stream_error` message +/// A new message named `name`. +pub(super) fn named(name: StreamMessage) -> ServerEvent { + ServerEvent::default().event(name.as_str()) +} + +/// `message` named `name` with `data` as JSON, or a `stream_error` message /// when `data` does not serialize. -pub(super) fn json(message: ServerEvent, kind: &str, data: impl serde::Serialize) -> ServerEvent { - message.event(kind).json_data(data).unwrap_or_else(|_| { - ServerEvent::default() - .event("stream_error") - .data("serialization failed") - }) +pub(super) fn json( + message: ServerEvent, + name: StreamMessage, + data: impl serde::Serialize, +) -> ServerEvent { + message + .event(name.as_str()) + .json_data(data) + .unwrap_or_else(|_| named(StreamMessage::StreamError).data("serialization failed")) } impl Ended { @@ -49,7 +58,7 @@ impl Ended { let Self::Refused(error) = self else { return None; }; - let message = || ServerEvent::default().event("access_ended"); + let message = || named(StreamMessage::AccessEnded); Some( message() .json_data(error.body()) diff --git a/apps/piqueld/src/api/http/operations.rs b/apps/piqueld/src/api/http/operations.rs index e2efacf53..fed6e7573 100644 --- a/apps/piqueld/src/api/http/operations.rs +++ b/apps/piqueld/src/api/http/operations.rs @@ -16,7 +16,7 @@ use axum::{ }; use piqueld_core::Operation; use piqueld_core::access::{AppPermission, Grants}; -use piqueld_core::api::Envelope; +use piqueld_core::api::{Envelope, StreamMessage}; use piqueld_core::timeline::Timeline; /// Requires `grants` to read operation `id`'s environment, returning the @@ -158,7 +158,7 @@ impl Follow for FollowTimeline { self.sent = true; return Some(live::json( ServerEvent::default(), - "timeline", + StreamMessage::Timeline, &self.timeline, )); } @@ -166,8 +166,7 @@ impl Follow for FollowTimeline { let Ok(changed) = self.state.advance_timeline(&mut self.timeline).await else { self.done = true; return Some( - ServerEvent::default() - .event("stream_error") + live::named(StreamMessage::StreamError) .data("Reload the timeline before reconnecting"), ); }; diff --git a/crates/piqueld-client/src/lib.rs b/crates/piqueld-client/src/lib.rs index e17cb9283..f434539b8 100644 --- a/crates/piqueld-client/src/lib.rs +++ b/crates/piqueld-client/src/lib.rs @@ -81,6 +81,8 @@ pub use environments::{ PromotedFrom, ReleasePlan, ReleasePromotion, RestoreRequest, RouteUrl, RunState, SecretProblem, TelemetryReport, TrackedBranch, UrlCondition, UrlState, }; +/// The names of the messages a live event stream sends. +pub use piqueld_core::api::StreamMessage; /// Request size and page size limits the daemon enforces. pub use piqueld_core::api::{ ApiErrorCode, DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE, MAX_REQUEST_BODY_BYTES, MAX_SECRET_VALUE_BYTES, diff --git a/crates/piqueld-client/src/operations.rs b/crates/piqueld-client/src/operations.rs index c71cf06a9..7ddbc6ae6 100644 --- a/crates/piqueld-client/src/operations.rs +++ b/crates/piqueld-client/src/operations.rs @@ -1,6 +1,6 @@ //! Asynchronous operation inspection, and their timelines of steps. use crate::{ - Client, ClientError, Operation, + Client, ClientError, Operation, StreamMessage, client::{EnvelopedCall, GeneratedCall}, sse::{Messages, Received}, }; @@ -69,15 +69,15 @@ impl TimelineStream { Ok(Received::Comment) => return Some(Ok(None)), Err(error) => return Some(Err(error)), }; - return Some(match message.event.as_str() { - "timeline" => serde_json::from_str(&message.data) + return Some(match StreamMessage::parse(&message.event) { + Some(StreamMessage::Timeline) => serde_json::from_str(&message.data) .map(Some) .map_err(|source| ClientError::Decode { source }), - "stream_error" => Err(ClientError::exchange(format!( + Some(StreamMessage::StreamError) => Err(ClientError::exchange(format!( "the timeline stream failed: {}", message.data ))), - "access_ended" => Err(ClientError::api( + Some(StreamMessage::AccessEnded) => Err(ClientError::api( http::StatusCode::FORBIDDEN, message.data.as_bytes(), )), diff --git a/crates/piqueld-core/src/api/mod.rs b/crates/piqueld-core/src/api/mod.rs index 97fab0f4f..efb72df8a 100644 --- a/crates/piqueld-core/src/api/mod.rs +++ b/crates/piqueld-core/src/api/mod.rs @@ -12,6 +12,7 @@ mod ingress; mod logs; mod previews; mod secrets; +mod streams; mod system; mod telemetry; #[cfg(test)] @@ -26,6 +27,7 @@ pub use ingress::*; pub use logs::*; pub use previews::*; pub use secrets::*; +pub use streams::*; pub use system::*; pub use telemetry::*; diff --git a/crates/piqueld-core/src/api/streams.rs b/crates/piqueld-core/src/api/streams.rs new file mode 100644 index 000000000..bb7ac086f --- /dev/null +++ b/crates/piqueld-core/src/api/streams.rs @@ -0,0 +1,43 @@ +//! The messages of the daemon's live server-sent event streams. + +use crate::names::string_enum; + +string_enum! { + /// The name of a message a live server-sent event stream sends, as its + /// `event` field. A stream may add messages, so a reader skips names it + /// doesn't know. + pub enum StreamMessage { + /// One history event, as JSON, from the event stream. + Event => "event", + /// The whole operation timeline, as JSON, from the timeline stream, + /// first when it opens and then again on each change. + Timeline => "timeline", + /// The event stream resumed after events that history no longer + /// holds; history must be reloaded. The stream ends. + HistoryExpired => "history_expired", + /// The stream could no longer read the store, or serialize what it + /// read. The stream ends. + StreamError => "stream_error", + /// The caller lost access to what the stream shows; its data is the + /// `ErrorBody` of the request that would now be refused. The stream + /// ends. + AccessEnded => "access_ended", + } +} + +#[cfg(test)] +mod tests { + use super::StreamMessage; + use std::collections::BTreeSet; + + /// Each message is sent under its own name and read back as itself. + #[test] + fn messages_have_distinct_names() { + for message in StreamMessage::ALL { + assert_eq!(StreamMessage::parse(message.as_str()), Some(message)); + assert_eq!(message.to_string(), message.as_str()); + } + let names = StreamMessage::ALL.map(StreamMessage::as_str); + assert_eq!(BTreeSet::from(names).len(), names.len()); + } +} diff --git a/docs/dev/rust-conventions.md b/docs/dev/rust-conventions.md index dc3a89e36..46f22031b 100644 --- a/docs/dev/rust-conventions.md +++ b/docs/dev/rust-conventions.md @@ -37,13 +37,15 @@ still reads a code it doesn't know yet; compare one with their own `DiagnosticCode`. Other strings that cross crates are named the same way, as a `string_enum!` -in `piqueld-core`: the kind of each history event is an `EventKind`. Record -and compare one through its variant, never its string, and in SQL bind it as -a parameter. Migrations can't name it, so a store test checks that every kind -the schema spells out, in an index or a view, is an `EventKind`. `Event.kind` -stays a `String`, since history holds kinds older daemons recorded and a -client may read kinds a newer daemon adds; compare it with -`Event::known_kind` or `==`. +in `piqueld-core`: the kind of each history event is an `EventKind`, and the +name of each message a live server-sent event stream sends a `StreamMessage`. +Record and compare one through its variant, never its string, and in SQL bind +it as a parameter. Migrations can't name an `EventKind`, so a store test +checks that every kind the schema spells out, in an index or a view, is one. +`Event.kind` stays a `String`, since history holds kinds older daemons +recorded and a client may read kinds a newer daemon adds; compare it with +`Event::known_kind` or `==`. A stream reader likewise skips message names it +doesn't know. Production code never panics without saying why: `expect_used`, `panic`, `todo`, `unimplemented` and `dbg_macro` are denied outside tests. Return an From be5bde9e5af6c14bcf7ff2b719673d3a5b266631 Mon Sep 17 00:00:00 2001 From: piquel Date: Sun, 22 Nov 2026 16:10:46 +0100 Subject: [PATCH 2/2] refactor(core): drop the stream message test the macro already guarantees `string_enum!` already makes each name parse back to its variant, and a duplicate name fails `unreachable_patterns`. Part of PQD-161 --- crates/piqueld-core/src/api/streams.rs | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/crates/piqueld-core/src/api/streams.rs b/crates/piqueld-core/src/api/streams.rs index bb7ac086f..b3f8bff63 100644 --- a/crates/piqueld-core/src/api/streams.rs +++ b/crates/piqueld-core/src/api/streams.rs @@ -24,20 +24,3 @@ string_enum! { AccessEnded => "access_ended", } } - -#[cfg(test)] -mod tests { - use super::StreamMessage; - use std::collections::BTreeSet; - - /// Each message is sent under its own name and read back as itself. - #[test] - fn messages_have_distinct_names() { - for message in StreamMessage::ALL { - assert_eq!(StreamMessage::parse(message.as_str()), Some(message)); - assert_eq!(message.to_string(), message.as_str()); - } - let names = StreamMessage::ALL.map(StreamMessage::as_str); - assert_eq!(BTreeSet::from(names).len(), names.len()); - } -}