summaryrefslogtreecommitdiff
path: root/src/events/routes.rs
blob: d901f9b6d0d3189a73576852ff75268a080dff60 (plain)
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
use std::collections::{BTreeMap, HashSet};

use axum::{
    extract::State,
    http::StatusCode,
    response::{
        sse::{self, Sse},
        IntoResponse, Response,
    },
    routing::get,
    Router,
};
use axum_extra::extract::Query;
use futures::{
    future,
    stream::{self, Stream, StreamExt as _, TryStreamExt as _},
};

use super::{extract::LastEventId, repo::broadcast};
use crate::{
    app::App,
    clock::RequestedAt,
    error::Internal,
    events::app::EventsError,
    repo::{channel, login::Login},
};

#[cfg(test)]
mod test;

// For the purposes of event replay, an "event ID" is a vector of per-channel
// sequence numbers. Replay will start with messages whose sequence number in
// its channel is higher than the sequence in the event ID, or if the channel
// is not listed in the event ID, then at the beginning.
//
// Using a sorted map ensures that there is a canonical representation for
// each event ID.
type EventId = BTreeMap<channel::Id, broadcast::Sequence>;

pub fn router() -> Router<App> {
    Router::new().route("/api/events", get(events))
}

#[derive(Clone, serde::Deserialize)]
struct EventsQuery {
    #[serde(default, rename = "channel")]
    channels: HashSet<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<EventId>>,
    Query(query): Query<EventsQuery>,
) -> Result<Events<impl Stream<Item = ReplayableEvent> + std::fmt::Debug>, ErrorResponse> {
    let resume_at = last_event_id
        .map(LastEventId::into_inner)
        .unwrap_or_default();

    let streams = stream::iter(query.channels)
        .then(|channel| {
            let app = app.clone();
            let resume_at = resume_at.clone();
            async move {
                let resume_at = resume_at.get(&channel).copied();

                let events = app
                    .events()
                    .subscribe(&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)?;

    // We resume counting from the provided last-event-id mapping, rather than
    // starting from scratch, so that the events in a resumed stream contain
    // the full vector of channel IDs for their event IDs right off the bat,
    // even before any events are actually delivered.
    let stream = stream::select_all(streams).scan(resume_at, |sequences, event| {
        let (channel, sequence) = event.event_id();
        sequences.insert(channel, sequence);

        let event = ReplayableEvent(sequences.clone(), event);

        future::ready(Some(event))
    });

    Ok(Events(stream))
}

#[derive(Debug)]
struct Events<S>(S);

impl<S> IntoResponse for Events<S>
where
    S: Stream<Item = ReplayableEvent> + 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()
    }
}

#[derive(Debug)]
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()
            }
            other => Internal::from(other).into_response(),
        }
    }
}

#[derive(Debug)]
struct ReplayableEvent(EventId, ChannelEvent);

#[derive(Debug, 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) -> (channel::Id, broadcast::Sequence) {
        (self.channel.clone(), self.message.sequence)
    }
}

impl TryFrom<ReplayableEvent> for sse::Event {
    type Error = serde_json::Error;

    fn try_from(value: ReplayableEvent) -> Result<Self, Self::Error> {
        let ReplayableEvent(id, data) = value;

        let id = serde_json::to_string(&id)?;
        let data = serde_json::to_string_pretty(&data)?;

        let event = Self::default().id(id).data(data);

        Ok(event)
    }
}