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

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

pub async fn handler(
    State(app): State<App>,
    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);
        Sse::new(stream)
            .keep_alive(sse::KeepAlive::default())
            .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(),
        }
    }
}