From a48c19f8c933291a3e65a3143eabda03e8bf1ede Mon Sep 17 00:00:00 2001 From: Owen Jacobson Date: Sun, 15 Sep 2024 22:39:23 -0400 Subject: Annotate channel events with channel ID at the router, not intrinsically. This bugged me aesthetically. At `app.channel().events(channel)`, the caller knows the channel ID; they don't need to be told. Having the same info come back out in the returned events felt bad. --- src/events.rs | 29 ++++++++++++++++++++++++----- 1 file changed, 24 insertions(+), 5 deletions(-) (limited to 'src/events.rs') diff --git a/src/events.rs b/src/events.rs index 2d1e1f8..51f06b4 100644 --- a/src/events.rs +++ b/src/events.rs @@ -49,21 +49,33 @@ async fn on_events( let streams = stream::iter(query.channels) .then(|channel| { let app = app.clone(); - async move { app.channels().events(&channel, resume_at.as_ref()).await } + async move { + let events = app + .channels() + .events(&channel, resume_at.as_ref()) + .await? + .map_ok(move |message| ChannelEvent { + channel: channel.clone(), + message, + }); + + Ok::<_, BoxedError>(events) + } }) .try_collect::>() .await?; - let stream = stream::select_all(streams).and_then(|msg| future::ready(to_event(msg))); + let stream = stream::select_all(streams).and_then(|msg| future::ready(to_sse_event(msg))); let sse = Sse::new(stream).keep_alive(sse::KeepAlive::default()); Ok(sse) } -fn to_event(msg: BroadcastMessage) -> Result { - let data = serde_json::to_string(&msg)?; +fn to_sse_event(event: ChannelEvent) -> Result { + let data = serde_json::to_string(&event)?; let event = sse::Event::default() - .id(msg + .id(event + .message .sent_at .to_rfc3339_opts(SecondsFormat::AutoSi, /* use_z */ true)) .data(&data); @@ -71,6 +83,13 @@ fn to_event(msg: BroadcastMessage) -> Result { Ok(event) } +#[derive(serde::Serialize)] +struct ChannelEvent { + channel: ChannelId, + #[serde(flatten)] + message: M, +} + pub struct LastEventId(pub String); static LAST_EVENT_ID: HeaderName = HeaderName::from_static("last-event-id"); -- cgit v1.2.3