relay_server/endpoints/
envelope.rs

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
//! Handles envelope store requests.

use std::convert::Infallible;

use axum::extract::rejection::BytesRejection;
use axum::extract::{DefaultBodyLimit, FromRequest, Request};
use axum::response::IntoResponse;
use axum::routing::{post, MethodRouter};
use axum::{Json, RequestExt};
use bytes::Bytes;
use relay_config::Config;
use relay_event_schema::protocol::EventId;
use serde::Serialize;

use crate::endpoints::common::{self, BadStoreRequest};
use crate::envelope::Envelope;
use crate::extractors::{BadEventMeta, PartialMeta, RequestMeta};
use crate::service::ServiceState;

/// Aggregate rejection thrown when extracting [`EnvelopeParams`].
#[derive(Debug)]
enum BadEnvelopeParams {
    EventMeta(BadEventMeta),
    InvalidBody(BytesRejection),
}

impl From<BadEventMeta> for BadEnvelopeParams {
    fn from(value: BadEventMeta) -> Self {
        Self::EventMeta(value)
    }
}

impl From<BytesRejection> for BadEnvelopeParams {
    fn from(value: BytesRejection) -> Self {
        Self::InvalidBody(value)
    }
}

impl From<Infallible> for BadEnvelopeParams {
    fn from(value: Infallible) -> Self {
        match value {}
    }
}

impl IntoResponse for BadEnvelopeParams {
    fn into_response(self) -> axum::response::Response {
        match self {
            BadEnvelopeParams::EventMeta(inner) => inner.into_response(),
            BadEnvelopeParams::InvalidBody(inner) => inner.into_response(),
        }
    }
}

#[derive(Debug)]
struct EnvelopeParams {
    meta: RequestMeta,
    body: Bytes,
}

impl EnvelopeParams {
    fn extract_envelope(self) -> Result<Box<Envelope>, BadStoreRequest> {
        let Self { meta, body } = self;

        if body.is_empty() {
            return Err(BadStoreRequest::EmptyBody);
        }

        Ok(Envelope::parse_request(body, meta)?)
    }
}

#[axum::async_trait]
impl FromRequest<ServiceState> for EnvelopeParams {
    type Rejection = BadEnvelopeParams;

    async fn from_request(
        mut request: Request,
        state: &ServiceState,
    ) -> Result<Self, Self::Rejection> {
        let result = request.extract_parts_with_state(state).await;

        if !matches!(result, Err(BadEventMeta::MissingAuth)) {
            return Ok(Self {
                meta: result?,
                body: request.extract().await?,
            });
        }

        let partial_meta: PartialMeta = request.extract_parts_with_state(state).await?;
        let body: Bytes = request.extract().await?;

        let line = body
            .splitn(2, |b| *b == b'\n')
            .next()
            .ok_or(BadEventMeta::MissingAuth)?;

        let request_meta = serde_json::from_slice(line).map_err(BadEventMeta::BadEnvelopeAuth)?;

        Ok(Self {
            meta: partial_meta.copy_to(request_meta),
            body,
        })
    }
}

#[derive(Serialize)]
struct StoreResponse {
    #[serde(skip_serializing_if = "Option::is_none")]
    id: Option<EventId>,
}

/// Handler for the envelope store endpoint.
async fn handle(
    state: ServiceState,
    params: EnvelopeParams,
) -> Result<impl IntoResponse, BadStoreRequest> {
    let envelope = params.extract_envelope()?;
    let id = common::handle_envelope(&state, envelope).await?;
    Ok(Json(StoreResponse { id }))
}

pub fn route(config: &Config) -> MethodRouter<ServiceState> {
    post(handle).route_layer(DefaultBodyLimit::max(config.max_envelope_size()))
}