-
-
Notifications
You must be signed in to change notification settings - Fork 60
/
Copy pathutil.rs
100 lines (91 loc) · 3.06 KB
/
util.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
use std::io::Cursor;
use rocket::http::ContentType;
use rocket::http::Status;
use rocket::request::Request;
use rocket::response::{self, Responder, Response};
use rocket_okapi::JsonSchema;
use serde::Serialize;
#[derive(Serialize, JsonSchema, Debug)]
pub struct HttpErrorJson {
#[serde(skip)]
#[schemars(skip)]
status: Status,
message: String,
}
impl HttpErrorJson {
pub fn new(status: Status, err: String) -> HttpErrorJson {
HttpErrorJson {
status: status,
message: format!("{}", err),
}
}
}
impl<'r> Responder<'r> for HttpErrorJson {
fn respond_to(self, _: &Request) -> response::Result<'r> {
// TODO: Fix unwrap
let body = serde_json::to_string(&self).unwrap();
Response::build()
.status(self.status)
.sized_body(Cursor::new(body))
.header(ContentType::new("application", "json"))
.ok()
}
}
use std::collections::BTreeMap;
impl<'r> rocket_okapi::response::OpenApiResponder<'r> for HttpErrorJson {
fn responses(
_gen: &mut rocket_okapi::gen::OpenApiGenerator,
) -> Result<okapi::openapi3::Responses, rocket_okapi::OpenApiError> {
Ok(okapi::openapi3::Responses {
default: None,
responses: BTreeMap::new(),
extensions: BTreeMap::new(),
})
}
}
use aw_datastore::DatastoreError;
impl Into<HttpErrorJson> for DatastoreError {
fn into(self) -> HttpErrorJson {
match self {
DatastoreError::NoSuchBucket(bucket_id) => HttpErrorJson::new(
Status::NotFound,
format!("The requested bucket '{}' does not exist", bucket_id),
),
DatastoreError::BucketAlreadyExists(bucket_id) => HttpErrorJson::new(
Status::NotModified,
format!("Bucket '{}' already exists", bucket_id),
),
DatastoreError::NoSuchKey(key) => HttpErrorJson::new(
Status::NotFound,
format!("The requested key(s) '{}' do not exist", key),
),
DatastoreError::MpscError => HttpErrorJson::new(
Status::InternalServerError,
"Unexpected Mpsc error!".to_string(),
),
DatastoreError::InternalError(msg) => {
HttpErrorJson::new(Status::InternalServerError, msg)
}
// When upgrade is disabled
DatastoreError::Uninitialized(msg) => {
HttpErrorJson::new(Status::InternalServerError, msg)
}
DatastoreError::OldDbVersion(msg) => {
HttpErrorJson::new(Status::InternalServerError, msg)
}
}
}
}
#[macro_export]
macro_rules! endpoints_get_lock {
( $lock:expr ) => {
match $lock.lock() {
Ok(r) => r,
Err(e) => {
let err_msg = format!("Taking datastore lock failed, returning 504: {}", e);
warn!("{}", err_msg);
return Err(HttpErrorJson::new(Status::ServiceUnavailable, err_msg));
}
}
};
}