cat_gateway/service/common/responses/
mod.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
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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
//! Generic Responses are all contained in their own modules, grouped by response codes.

use std::{
    collections::HashSet,
    hash::{Hash, Hasher},
};

use code_401_unauthorized::Unauthorized;
use code_403_forbidden::Forbidden;
use code_422_unprocessable_content::UnprocessableContent;
use code_429_too_many_requests::TooManyRequests;
use code_503_service_unavailable::ServiceUnavailable;
use poem::IntoResponse;
use poem_openapi::{
    payload::Json,
    registry::{MetaHeader, MetaResponse, MetaResponses, Registry},
    ApiResponse,
};
use tracing::error;

mod code_401_unauthorized;
mod code_403_forbidden;
mod code_422_unprocessable_content;
mod code_429_too_many_requests;
pub(crate) mod code_500_internal_server_error;
mod code_503_service_unavailable;

use code_500_internal_server_error::InternalServerError;

use super::types::headers::{
    access_control_allow_origin::AccessControlAllowOriginHeader,
    ratelimit::RateLimitHeader,
    retry_after::{RetryAfterHeader, RetryAfterOption},
};

/// Default error responses
#[derive(ApiResponse)]
pub(crate) enum ErrorResponses {
    /// ## Unauthorized
    ///
    /// The client has not sent valid authentication credentials for the requested
    /// resource.
    #[oai(status = 401)]
    Unauthorized(Json<Unauthorized>),

    /// ## Forbidden
    ///
    /// The client has not sent valid authentication credentials for the requested
    /// resource.
    #[oai(status = 403)]
    Forbidden(Json<Forbidden>),

    /// ## Unprocessable Content
    ///
    /// The client has not sent valid data in its request, headers, parameters or body.
    #[oai(status = 422)]
    UnprocessableContent(Json<UnprocessableContent>),

    /// ## Too Many Requests
    ///
    /// The client has sent too many requests in a given amount of time.
    #[oai(status = 429)]
    TooManyRequests(
        Json<TooManyRequests>,
        #[oai(header = "Retry-After")] RetryAfterHeader,
    ),

    /// ## Internal Server Error.
    ///
    /// An internal server error occurred.
    ///
    /// *The contents of this response should be reported to the projects issue tracker.*
    #[oai(status = 500)]
    ServerError(Json<InternalServerError>),

    /// ## Service Unavailable
    ///
    /// The service is not available, try again later.
    ///
    /// *This is returned when the service either has not started,
    /// or has become unavailable.*
    #[oai(status = 503)]
    ServiceUnavailable(
        Json<ServiceUnavailable>,
        #[oai(header = "Retry-After")] Option<RetryAfterHeader>,
    ),
}

impl ErrorResponses {
    /// Handle a 401 unauthorized response.
    ///
    /// Returns a 401 Unauthorized response.
    /// Its OK if we actually never call this.  Required for the API.
    /// May be generated by the ingress.
    pub(crate) fn unauthorized() -> Self {
        let error = Unauthorized::new(None);
        ErrorResponses::Unauthorized(Json(error))
    }

    /// Handle a 403 forbidden response.
    ///
    /// Returns a 403 Forbidden response.
    /// Its OK if we actually never call this.  Required for the API.
    /// May be generated by the ingress.
    pub(crate) fn forbidden(roles: Option<Vec<String>>) -> Self {
        let error = Forbidden::new(None, roles);
        ErrorResponses::Forbidden(Json(error))
    }
}

/// Combine provided responses type with the default responses under one type.
pub(crate) enum WithErrorResponses<T> {
    /// Provided responses
    With(T),
    /// Error responses
    Error(ErrorResponses),
}

impl<T> WithErrorResponses<T> {
    /// Handle a 5xx response.
    /// Returns a Server Error or a Service Unavailable response.
    pub(crate) fn handle_error(err: &anyhow::Error) -> Self {
        match err {
            err if err.is::<bb8::RunError<tokio_postgres::Error>>() => {
                Self::service_unavailable(err, RetryAfterOption::Default)
            },
            err => Self::internal_error(err),
        }
    }

    /// Handle a 503 service unavailable error response.
    ///
    /// Returns a 503 Service unavailable Error response.
    pub(crate) fn service_unavailable(err: &anyhow::Error, retry: RetryAfterOption) -> Self {
        let error = ServiceUnavailable::new(None);
        error!(id=%error.id(), error=?err, retry_after=?retry);
        let retry = match retry {
            RetryAfterOption::Default => Some(RetryAfterHeader::default()),
            RetryAfterOption::None => None,
            RetryAfterOption::Some(value) => Some(value),
        };
        WithErrorResponses::Error(ErrorResponses::ServiceUnavailable(Json(error), retry))
    }

    /// Handle a 500 internal error response.
    ///
    /// Returns a 500 Internal Error response.
    pub(crate) fn internal_error(err: &anyhow::Error) -> Self {
        let error = InternalServerError::new(None);
        error!(id=%error.id(), error=?err);
        WithErrorResponses::Error(ErrorResponses::ServerError(Json(error)))
    }

    /// Handle a 401 unauthorized response.
    ///
    /// Returns a 401 Unauthorized response.
    /// Its OK if we actually never call this.  Required for the API.
    /// May be generated by the ingress.
    #[allow(dead_code)]
    pub(crate) fn unauthorized() -> Self {
        WithErrorResponses::Error(ErrorResponses::unauthorized())
    }

    /// Handle a 403 forbidden response.
    ///
    /// Returns a 403 Forbidden response.
    /// Its OK if we actually never call this.  Required for the API.
    /// May be generated by the ingress.
    #[allow(dead_code)]
    pub(crate) fn forbidden(roles: Option<Vec<String>>) -> Self {
        WithErrorResponses::Error(ErrorResponses::forbidden(roles))
    }

    /// Handle a 422 unprocessable content response.
    ///
    /// Returns a 422 unprocessable content response.
    pub(crate) fn unprocessable_content(errors: Vec<poem::Error>) -> Self {
        let error = UnprocessableContent::new(errors);
        WithErrorResponses::Error(ErrorResponses::UnprocessableContent(Json(error)))
    }

    /// Handle a 429 rate limiting response.
    ///
    /// Returns a 429 Rate limit response.
    /// Its OK if we actually never call this.  Required for the API.
    /// May be generated by the ingress.
    #[allow(dead_code)]
    pub(crate) fn rate_limit(retry_after: Option<RetryAfterHeader>) -> Self {
        let retry_after = retry_after.unwrap_or_default();
        let error = TooManyRequests::new(None);
        WithErrorResponses::Error(ErrorResponses::TooManyRequests(Json(error), retry_after))
    }
}

impl<T: ApiResponse> From<T> for WithErrorResponses<T> {
    fn from(val: T) -> Self {
        Self::With(val)
    }
}

impl<T: ApiResponse> ApiResponse for WithErrorResponses<T> {
    const BAD_REQUEST_HANDLER: bool = true;

    fn meta() -> MetaResponses {
        let t_meta = T::meta();
        let default_meta = ErrorResponses::meta();

        let mut responses = HashSet::new();
        responses.extend(
            t_meta
                .responses
                .into_iter()
                .map(FilteredByStatusCodeResponse),
        );
        responses.extend(
            default_meta
                .responses
                .into_iter()
                .map(FilteredByStatusCodeResponse),
        );

        let responses =
            responses
                .into_iter()
                .map(|val| {
                    let mut response = val.0;
                    // Make modifications to the responses to set common headers
                    if let Some(status) = response.status {
                        // Only 2xx and 4xx responses get RateLimit Headers.
                        if (200..300).contains(&status) || (400..500).contains(&status) {
                            response.headers.insert(0usize, MetaHeader {
                                name: "RateLimit".to_string(),
                                description: Some("RateLimit Header.".to_string()),
                                required: false,
                                deprecated: false,
                                schema: <RateLimitHeader as poem_openapi::types::Type>::schema_ref(),
                            });
                        }

                        // All responses get Access-Control-Allow-Origin headers
                        response.headers.insert(0usize, MetaHeader {
                            name: "Access-Control-Allow-Origin".to_string(),
                            description: Some("Access-Control-Allow-Origin Header.".to_string()),
                            required: false,
                            deprecated: false,
                            schema: <AccessControlAllowOriginHeader as poem_openapi::types::Type>::schema_ref(),
                        });
                    }
                    response
                })
                .collect();

        // Add Rate limiting headers to ALL 2xx and 4xx responses
        // for response in responses.iter_mut() {
        //    response.
        //    debug!(response = response);
        //}

        MetaResponses { responses }
    }

    fn register(registry: &mut Registry) {
        ErrorResponses::register(registry);
        T::register(registry);
    }

    fn from_parse_request_error(err: poem_openapi::__private::poem::Error) -> Self {
        WithErrorResponses::unprocessable_content(vec![err])
    }
}

impl<T: IntoResponse + Send> IntoResponse for WithErrorResponses<T> {
    fn into_response(self) -> poem::Response {
        match self {
            Self::With(t) => t.into_response(),
            Self::Error(default) => default.into_response(),
        }
    }
}

/// `FilteredByStatusCodeResponse` is used to filter out duplicate responses by status
/// code.
struct FilteredByStatusCodeResponse(MetaResponse);

impl PartialEq for FilteredByStatusCodeResponse {
    fn eq(&self, other: &Self) -> bool {
        self.0.status.eq(&other.0.status)
    }
}
impl Eq for FilteredByStatusCodeResponse {}
impl Hash for FilteredByStatusCodeResponse {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.0.status.hash(state);
    }
}