df_st_api 0.3.0-development-2

Starting an API server for the DF Storyteller project.
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
use anyhow::Error;
use df_rocket_okapi::gen::OpenApiGenerator;
use df_rocket_okapi::response::OpenApiResponder;
use df_rocket_okapi::Result as OpenApiResult;
#[allow(unused_imports)]
use log::{debug, error, info, trace, warn};
use okapi::openapi3::Responses;
use rocket::catch;
use rocket::http::{ContentType, Status};
use rocket::request::Request;
use rocket::response::{self, Responder, Response};
use rocket_contrib::json::Json;
use serde::{Deserialize, Serialize};

fn add_204_error(responses: &mut Responses) {
    responses
        .responses
        .entry("204".to_owned())
        .or_insert_with(|| {
            let response = okapi::openapi3::Response {
                description: "\
                # [204 No Content](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/204)\n\
                This response is given when you request an item using a filter and there is no \
                item with the exact filter criteria.\n\n\
                In most cases you requested an `id` that does not exists in the database. \
                The body of this response will be empty.\
                "
                .to_owned(),
                ..Default::default()
            };
            response.into()
        });
}

fn add_304_error(responses: &mut Responses) {
    responses
        .responses
        .entry("304".to_owned())
        .or_insert_with(|| {
            let response = okapi::openapi3::Response{
                description: "\
                # [304 Not Modified](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/304)\n\
                This response is given when the ETag of in the query parameters matches the \
                generated response by the server. This can then be used to enable caching of \
                responses.\n\n\
                If the ETags do not match it will give you the full response (with a 200 OK). \
                The response will give include the new ETag.\n\n\
                [More info can be found here]\
                (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-None-Match).\
                "
                .to_owned(),
                ..Default::default()
            };
            response.into()
        });
}

fn add_400_error(responses: &mut Responses) {
    responses
        .responses
        .entry("400".to_owned())
        .or_insert_with(|| {
            let response = okapi::openapi3::Response{
                description: "\
                # [400 Bad Request](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400)\n\
                This request given is wrongly formatted or data asked could not be fulfilled.\n\n\
                This is most likely because of the `filter_by`, `order_by` or `group_by` parameters. \
                The properties you are asking for do not exist or does not allow filtering or ordering. \
                "
                .to_owned(),
                ..Default::default()
            };
            response.into()
        });
}

fn add_404_error(responses: &mut Responses) {
    responses.responses.entry("404".to_owned())
        .or_insert_with(|| {
            let response = okapi::openapi3::Response{
                description: "\
                # [404 Not Found](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404)\n\
                This response is given when you request a page that does not exists.\n\n\
                **Note:** This is not exactly a response by this endpoint. But might returned when \
                you wrongly input one or more of the path or query parameters. An example would be \
                that the server expects and `int32` and you have given it \"100m\", which is a `string` \
                because of the `m` character.\n\n\
                So when you get this error and you expect a result. Check all the types of the parameters. \
                ".to_owned(),
                ..Default::default()
            };
            response.into()
        });
}

fn add_500_error(responses: &mut Responses) {
    responses
        .responses
        .entry("500".to_owned())
        .or_insert_with(|| {
            let response = okapi::openapi3::Response {
                description: format!(
                    "\
                    # [500 Internal Server Error]\
                    (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500)\n\
                    This response is given when the server has an internal error that it could not \
                    recover from.\n\n\
                    If you get this response please report this as an [issue here]({}).\
                    ",
                    df_st_core::git_issue::link_to_issue_template("bug")
                ),
                ..Default::default()
            };
            response.into()
        });
}

#[derive(Serialize, Deserialize)]
pub struct APIErrorResponse {
    errors: Vec<APIError>,
}

#[derive(Serialize, Deserialize)]
pub struct APIError {
    pub message: String,
    pub issue_link: Option<String>,
    pub code: u16,
}

#[derive(Serialize, Deserialize)]
pub struct APIMessageResponse {
    message: APIMessage,
}

#[derive(Serialize, Deserialize)]
pub struct APIMessage {
    pub message: String,
    pub code: u16,
}

#[derive(Debug, Default)]
pub struct APIErrorBadRequest {
    pub err: Option<Error>,
    pub message: Option<String>,
}

impl From<Error> for APIErrorBadRequest {
    fn from(error: Error) -> Self {
        APIErrorBadRequest {
            err: Some(error),
            message: None,
        }
    }
}

impl From<String> for APIErrorBadRequest {
    fn from(message: String) -> Self {
        APIErrorBadRequest {
            err: None,
            message: Some(message),
        }
    }
}

impl From<&str> for APIErrorBadRequest {
    fn from(message: &str) -> Self {
        APIErrorBadRequest {
            err: None,
            message: Some(message.to_owned()),
        }
    }
}

#[derive(Debug, Default)]
pub struct APIErrorNoContent {
    pub err: Option<Error>,
    pub bad_request: bool,
    pub message: Option<String>,
}

impl APIErrorNoContent {
    pub fn new() -> Self {
        APIErrorNoContent::default()
    }
}

impl From<Error> for APIErrorNoContent {
    fn from(error: Error) -> Self {
        APIErrorNoContent {
            err: Some(error),
            bad_request: false,
            message: None,
        }
    }
}

impl From<APIErrorBadRequest> for APIErrorNoContent {
    fn from(error: APIErrorBadRequest) -> Self {
        APIErrorNoContent {
            err: error.err,
            bad_request: true,
            message: error.message,
        }
    }
}

impl<'r> Responder<'r> for APIErrorNoContent {
    fn respond_to(self, _: &Request) -> response::Result<'r> {
        let mut error_response = APIErrorResponse { errors: vec![] };
        if let Some(error) = self.err {
            error!("{}", error);
            error_response.errors.push(APIError {
                message: error.to_string(),
                issue_link: None,
                code: match self.bad_request {
                    true => 400,
                    false => 500,
                },
            });
        }

        if let Some(message) = self.message {
            error_response.errors.push(APIError {
                message,
                issue_link: None,
                code: match self.bad_request {
                    true => 400,
                    false => 500,
                },
            });
        }

        let mut response = Response::build();
        response.status(if error_response.errors.is_empty() {
            Status::NoContent
        } else if self.bad_request {
            Status::BadRequest
        } else {
            Status::InternalServerError
        });

        if !error_response.errors.is_empty() {
            response.header(ContentType::JSON);
            response.sized_body(std::io::Cursor::new(
                serde_json::to_string(&error_response).unwrap(),
            ));
        }
        response.ok()
    }
}

impl OpenApiResponder<'_> for APIErrorNoContent {
    fn responses(_: &mut OpenApiGenerator) -> OpenApiResult<Responses> {
        let mut responses = Responses::default();
        add_204_error(&mut responses);
        add_400_error(&mut responses);
        add_404_error(&mut responses);
        add_500_error(&mut responses);
        Ok(responses)
    }
}

#[derive(Debug, Default)]
pub struct APIErrorNotModified {
    pub err: Option<Error>,
    pub bad_request: bool,
    pub message: Option<String>,
}

impl APIErrorNotModified {
    pub fn new() -> Self {
        APIErrorNotModified::default()
    }
}

impl From<Error> for APIErrorNotModified {
    fn from(error: Error) -> Self {
        APIErrorNotModified {
            err: Some(error),
            bad_request: false,
            message: None,
        }
    }
}

impl From<APIErrorBadRequest> for APIErrorNotModified {
    fn from(error: APIErrorBadRequest) -> Self {
        APIErrorNotModified {
            err: error.err,
            bad_request: true,
            message: error.message,
        }
    }
}

impl<'r> Responder<'r> for APIErrorNotModified {
    fn respond_to(self, _: &Request) -> response::Result<'r> {
        let mut error_response = APIErrorResponse { errors: vec![] };
        if let Some(error) = self.err {
            error!("{}", error);
            error_response.errors.push(APIError {
                message: error.to_string(),
                issue_link: None,
                code: match self.bad_request {
                    true => 400,
                    false => 500,
                },
            });
        }

        if let Some(message) = self.message {
            error_response.errors.push(APIError {
                message,
                issue_link: None,
                code: match self.bad_request {
                    true => 400,
                    false => 500,
                },
            });
        }

        let mut response = Response::build();
        response.status(if error_response.errors.is_empty() {
            Status::NotModified
        } else if self.bad_request {
            Status::BadRequest
        } else {
            Status::InternalServerError
        });

        if !error_response.errors.is_empty() {
            response.header(ContentType::JSON);
            response.sized_body(std::io::Cursor::new(
                serde_json::to_string(&error_response).unwrap(),
            ));
        }
        response.ok()
    }
}

impl OpenApiResponder<'_> for APIErrorNotModified {
    fn responses(_: &mut OpenApiGenerator) -> OpenApiResult<Responses> {
        let mut responses = Responses::default();
        add_304_error(&mut responses);
        add_400_error(&mut responses);
        add_404_error(&mut responses);
        add_500_error(&mut responses);
        Ok(responses)
    }
}

#[catch(500)]
pub fn internal_error() -> Json<APIErrorResponse> {
    Json(APIErrorResponse {
        errors: vec![APIError {
            message: "I don't know what happened there... \
                Did someone leave the caverns open?\n\
                Please open a new issue for this: \
                https://gitlab.com/df_storyteller/df-storyteller/issues/new"
                .to_owned(),
            issue_link: Some(
                "https://gitlab.com/df_storyteller/df-storyteller/issues/new".to_owned(),
            ),
            code: 500,
        }],
    })
}

#[catch(400)]
pub fn bad_request(req: &Request) -> Json<APIErrorResponse> {
    Json(APIErrorResponse {
        errors: vec![APIError {
            message: format!("Bad request: URL `{}`.", req.uri()),
            issue_link: None,
            code: 400,
        }],
    })
}

#[catch(404)]
pub fn not_found(req: &Request) -> Json<APIErrorResponse> {
    Json(APIErrorResponse {
        errors: vec![APIError {
            message: format!("This requested URL `{}` was not found.", req.uri()),
            issue_link: None,
            code: 404,
        }],
    })
}

#[catch(204)]
pub fn no_content(req: &Request) -> Json<APIMessageResponse> {
    Json(APIMessageResponse {
        message: APIMessage {
            message: format!("No Content found here `{}`.", req.uri()),
            code: 204,
        },
    })
}

#[catch(304)]
pub fn not_modified(_req: &Request) -> Json<APIMessageResponse> {
    Json(APIMessageResponse {
        message: APIMessage {
            message: "Content has not been modified.".to_owned(),
            code: 304,
        },
    })
}