summaryrefslogtreecommitdiff
path: root/src/event/handlers/stream/mod.rs
blob: 8b89c31509acf4e0b757405e21c43079e95e8afe (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
use axum::{
    extract::State,
    response::{
        self, IntoResponse,
        sse::{self, Sse},
    },
};
use axum_extra::extract::Query;
use futures::stream::{Stream, StreamExt as _};

use crate::{
    app::App,
    error::{Internal, Unauthorized},
    event::{Event, Heartbeat::Heartbeat, Sequence, Sequenced as _, app, extract::LastEventId},
    token::{app::ValidateError, extract::Identity},
};

#[cfg(test)]
mod test;

pub async fn handler<P>(
    State(app): State<App<P>>,
    identity: Identity,
    last_event_id: Option<LastEventId<Sequence>>,
    Query(query): Query<QueryParams>,
) -> Result<Response<impl Stream<Item = Event> + std::fmt::Debug>, Error> {
    let resume_at = last_event_id.map_or(query.resume_point, LastEventId::into_inner);

    let stream = app.events().subscribe(resume_at).await?;
    let stream = app.tokens().limit_stream(&identity.token, stream).await?;

    Ok(Response(stream))
}

#[derive(serde::Deserialize)]
pub struct QueryParams {
    pub resume_point: Sequence,
}

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

impl<S> IntoResponse for Response<S>
where
    S: Stream<Item = Event> + Send + 'static,
{
    fn into_response(self) -> response::Response {
        let Self(stream) = self;
        let stream = stream.map(sse::Event::try_from);
        let heartbeat = match Heartbeat.try_into().map_err(Internal::from) {
            Ok(heartbeat) => heartbeat,
            Err(err) => return err.into_response(),
        };
        Sse::new(stream).keep_alive(heartbeat).into_response()
    }
}

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

    fn try_from(event: Event) -> Result<Self, Self::Error> {
        let id = serde_json::to_string(&event.sequence())?;
        let data = serde_json::to_string_pretty(&event)?;

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

        Ok(event)
    }
}

#[derive(Debug, thiserror::Error)]
#[error(transparent)]
pub enum Error {
    Subscribe(#[from] app::Error),
    Validate(#[from] ValidateError),
}

impl IntoResponse for Error {
    fn into_response(self) -> response::Response {
        match self {
            Self::Validate(ValidateError::InvalidToken) => Unauthorized.into_response(),
            other => Internal::from(other).into_response(),
        }
    }
}