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
use ::internal_prelude::works_everywhere::*;
type ResponderFn<'a, T, D> = Box<Fn(&mut T, D) -> Result<s::ResponsePayload> + 'a + Sync>;
type MethodHandler<'a, T> = Box<Fn(&mut T, &[u8]) -> Result<JsonResponse> + 'a + Sync>;
pub struct MethodRouter<'a, T> {
handlers: HashMap<&'static str, MethodHandler<'a, T>>,
method_names: Vec<&'static str>,
}
impl<'a, T> MethodRouter<'a, T> {
pub fn new() -> MethodRouter<'a, T> {
MethodRouter {
handlers: HashMap::new(),
method_names: vec![],
}
}
pub fn add(&mut self,
method: &'static str,
handler: MethodHandler<'a, T>)
-> Option<MethodHandler<'a, T>> {
self.method_names.push(method);
self.handlers.insert(method, handler)
}
pub fn add_responder<D>(&mut self,
method: &'static str,
responder: ResponderFn<'a, T, D>)
-> Option<MethodHandler<'a, T>>
where D: serde::Deserialize,
D: 'a,
T: 'a
{
self.method_names.push(method);
self.handlers.insert(method, create_handler_over_responder(responder))
}
pub fn list(&self) -> &[&str] {
&self.method_names
}
pub fn invoke(&self,
upon: &mut T,
method: &str,
json_request_body: &[u8])
-> Result<JsonResponse> {
match self.handlers.get(method) {
Some(handler) => handler(upon as &mut T, json_request_body),
None => Ok(JsonResponse::method_not_understood()),
}
}
}
pub fn create_handler_over_responder<'a, T, D>(responder: ResponderFn<'a, T, D>)
-> MethodHandler<'a, T>
where D: serde::Deserialize,
D: 'a,
T: 'a
{
Box::new(move |upon: &mut T, json_request_bytes: &[u8]| {
let parsed_maybe: std::result::Result<D, serde_json::Error> =
serde_json::from_slice(json_request_bytes);
match parsed_maybe {
Ok(parsed) => {
let payload_maybe = responder(upon, parsed);
match payload_maybe {
Ok(payload) => {
Ok(JsonResponse::success_with_payload(payload))
}
Err(error) => {
let message = format!("{:?}", error);
Ok(JsonResponse::fail_with_message(500,
&message))
}
}
}
Err(e) => Ok(JsonResponse::from_parse_error(e, json_request_bytes)),
}
})
}
pub struct JsonResponse {
pub status_code: i64,
pub response_json: Cow<'static, [u8]>,
}
impl JsonResponse {
pub fn from_parse_error(err: serde_json::error::Error, json: &[u8]) -> JsonResponse {
let message = format!("Parse error: {}\n Received {}",
err,
std::str::from_utf8(json).unwrap_or("[INVALID UTF-8]"));
let r = s::Response001 {
success: false,
code: 400,
message: Some(message.to_owned()),
data: s::ResponsePayload::None,
};
JsonResponse::from_response001(r)
}
pub fn from_response001(r: s::Response001) -> JsonResponse {
JsonResponse {
status_code: 400,
response_json: Cow::Owned(serde_json::to_vec_pretty(&r).unwrap()),
}
}
pub fn success_with_payload(r: s::ResponsePayload) -> JsonResponse {
let r = s::Response001 {
success: true,
code: 200,
message: Some("OK".to_owned()),
data: r,
};
JsonResponse {
status_code: r.code,
response_json: Cow::Owned(serde_json::to_vec_pretty(&r).unwrap()),
}
}
pub fn status_2xx(&self) -> bool {
self.status_code >= 200 && self.status_code < 300
}
pub fn assert_ok(&self) {
if !self.status_2xx() {
panic!("status {} - {:?}",
self.status_code,
std::str::from_utf8(self.response_json.as_ref()).unwrap());
}
}
pub fn unwrap_status200(&self) -> &JsonResponse {
self.assert_ok();
self
}
pub fn ok() -> JsonResponse {
JsonResponse {
status_code: 200,
response_json: Cow::Borrowed(br#"{"success": "true","code": 200,"message": "OK"}"#),
}
}
pub fn teapot() -> JsonResponse {
JsonResponse {
status_code: 418,
response_json:
Cow::Borrowed(br#"{"success": "false","code": 418, "message": "I'm a little teapot, short and stout..."}"#)
}
}
pub fn method_not_understood() -> JsonResponse {
JsonResponse {
status_code: 404,
response_json: Cow::Borrowed(br#"{
"success": "false",
"code": 404,
"message": "Endpoint name not understood"}"#),
}
}
pub fn fail_with_message(code: i64, message: &str) -> JsonResponse {
let r = s::Response001 {
success: false,
code: code,
message: Some(message.to_owned()),
data: s::ResponsePayload::None,
};
JsonResponse {
status_code: r.code,
response_json: Cow::Owned(serde_json::to_vec_pretty(&r).unwrap()),
}
}
}