1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
|
use axum::{
extract::State,
http::StatusCode,
response::{
sse::{self, Sse},
IntoResponse, Response,
},
routing::get,
Router,
};
use axum_extra::extract::Query;
use chrono::{self, format::SecondsFormat};
use futures::stream::{self, Stream, StreamExt as _, TryStreamExt as _};
use super::repo::broadcast;
use crate::{
app::App,
channel::app::EventsError,
clock::RequestedAt,
error::InternalError,
header::LastEventId,
repo::{channel, login::Login},
};
pub fn router() -> Router<App> {
Router::new().route("/api/events", get(events))
}
#[derive(serde::Deserialize)]
struct EventsQuery {
#[serde(default, rename = "channel")]
channels: Vec<channel::Id>,
}
async fn events(
State(app): State<App>,
RequestedAt(now): RequestedAt,
_: Login, // requires auth, but doesn't actually care who you are
last_event_id: Option<LastEventId>,
Query(query): Query<EventsQuery>,
) -> Result<Events<impl Stream<Item = ChannelEvent>>, ErrorResponse> {
let resume_at = last_event_id.as_deref();
let streams = stream::iter(query.channels)
.then(|channel| {
let app = app.clone();
async move {
let events = app
.channels()
.events(&channel, &now, resume_at)
.await?
.map(ChannelEvent::wrap(channel));
Ok::<_, EventsError>(events)
}
})
.try_collect::<Vec<_>>()
.await
// impl From would take more code; this is used once.
.map_err(ErrorResponse)?;
let stream = stream::select_all(streams);
Ok(Events(stream))
}
struct Events<S>(S);
impl<S> IntoResponse for Events<S>
where
S: Stream<Item = ChannelEvent> + Send + 'static,
{
fn into_response(self) -> Response {
let Self(stream) = self;
let stream = stream.map(sse::Event::try_from);
Sse::new(stream)
.keep_alive(sse::KeepAlive::default())
.into_response()
}
}
struct ErrorResponse(EventsError);
impl IntoResponse for ErrorResponse {
fn into_response(self) -> Response {
let Self(error) = self;
match error {
not_found @ EventsError::ChannelNotFound(_) => {
(StatusCode::NOT_FOUND, not_found.to_string()).into_response()
}
resume_at @ EventsError::ResumeAtError(_) => {
(StatusCode::BAD_REQUEST, resume_at.to_string()).into_response()
}
other => InternalError::from(other).into_response(),
}
}
}
#[derive(serde::Serialize)]
struct ChannelEvent {
channel: channel::Id,
#[serde(flatten)]
message: broadcast::Message,
}
impl ChannelEvent {
fn wrap(channel: channel::Id) -> impl Fn(broadcast::Message) -> Self {
move |message| Self {
channel: channel.clone(),
message,
}
}
fn event_id(&self) -> String {
self.message
.sent_at
.to_rfc3339_opts(SecondsFormat::AutoSi, /* use_z */ true)
}
}
impl TryFrom<ChannelEvent> for sse::Event {
type Error = serde_json::Error;
fn try_from(value: ChannelEvent) -> Result<Self, Self::Error> {
let data = serde_json::to_string_pretty(&value)?;
let event = Self::default().id(value.event_id()).data(&data);
Ok(event)
}
}
|