Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions apps/piqueld-ui/src/browser/management/timeline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -1239,7 +1239,7 @@ fn EventFeed(operation: String, live: Memo<bool>, attempt: Memo<u64>) -> impl In
};
stream.set_value(EventStream::open(
&url,
&["event"],
&[StreamMessage::Event],
move |_, data| {
let Ok(event) = serde_json::from_str::<Event>(data) else {
return;
Expand Down
34 changes: 19 additions & 15 deletions apps/piqueld-ui/src/browser/stream.rs
Original file line number Diff line number Diff line change
@@ -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};

Expand All @@ -11,34 +12,36 @@ type Listener = Closure<dyn FnMut(MessageEvent)>;
/// 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<dyn FnMut(Event)>,
}

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<Self> {
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::<dyn FnMut(Event)>::new({
Expand All @@ -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();
}
Expand Down
16 changes: 6 additions & 10 deletions apps/piqueld/src/api/http/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand All @@ -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"));
}
}
}
Expand Down
25 changes: 17 additions & 8 deletions apps/piqueld/src/api/http/live.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};

Expand All @@ -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 {
Expand All @@ -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())
Expand Down
7 changes: 3 additions & 4 deletions apps/piqueld/src/api/http/operations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -158,16 +158,15 @@ impl Follow for FollowTimeline {
self.sent = true;
return Some(live::json(
ServerEvent::default(),
"timeline",
StreamMessage::Timeline,
&self.timeline,
));
}
self.pace.wait(&self.lease, false).await;
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"),
);
};
Expand Down
2 changes: 2 additions & 0 deletions crates/piqueld-client/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
10 changes: 5 additions & 5 deletions crates/piqueld-client/src/operations.rs
Original file line number Diff line number Diff line change
@@ -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},
};
Expand Down Expand Up @@ -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(),
)),
Expand Down
2 changes: 2 additions & 0 deletions crates/piqueld-core/src/api/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ mod ingress;
mod logs;
mod previews;
mod secrets;
mod streams;
mod system;
mod telemetry;
#[cfg(test)]
Expand All @@ -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::*;

Expand Down
26 changes: 26 additions & 0 deletions crates/piqueld-core/src/api/streams.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
//! 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",
}
}
16 changes: 9 additions & 7 deletions docs/dev/rust-conventions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down