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
use std::{error::Error, fmt};
use crate::{
custom::{CustomProblem, StatusCode, Uri},
CowStr, Extensions, Problem,
};
#[track_caller]
pub fn bad_request(msg: impl Into<CowStr>) -> Problem {
Problem::from(BadRequest { msg: msg.into() })
}
#[track_caller]
pub fn unauthorized() -> Problem {
Problem::from(Unauthorized { _inner: () })
}
#[track_caller]
pub fn forbidden() -> Problem {
Problem::from(Forbidden { _inner: () })
}
#[track_caller]
pub fn not_found(entity: &'static str, identifier: impl fmt::Display) -> Problem {
Problem::from(NotFound {
entity,
identifier: identifier.to_string(),
})
}
#[track_caller]
pub fn not_found_unknown(entity: &'static str) -> Problem {
not_found(entity, "<unknown>")
}
#[track_caller]
pub fn conflict(msg: impl Into<CowStr>) -> Problem {
Problem::from(Conflict { msg: msg.into() })
}
#[track_caller]
pub fn failed_precondition() -> Problem {
Problem::from(PreconditionFailed { _inner: () })
}
#[track_caller]
pub fn unprocessable(msg: impl Into<CowStr>) -> Problem {
Problem::from(UnprocessableEntity { msg: msg.into() })
}
#[track_caller]
pub fn internal_error<M>(msg: M) -> Problem
where
M: Error + Send + Sync + 'static,
{
Problem::from_status(StatusCode::INTERNAL_SERVER_ERROR)
.with_detail("An unexpected error occurred")
.with_cause(InternalError {
inner: Box::new(msg),
})
}
#[track_caller]
pub fn service_unavailable() -> Problem {
Problem::from(ServiceUnavailable { _inner: () })
}
macro_rules! http_problem_type {
($status: ident) => {
fn problem_type(&self) -> Uri {
crate::blank_type_uri()
}
fn title(&self) -> &'static str {
self.status_code().canonical_reason().unwrap()
}
fn status_code(&self) -> StatusCode {
StatusCode::$status
}
};
($status: ident, display) => {
http_problem_type!($status);
fn details(&self) -> CowStr {
self.to_string().into()
}
};
($status: ident, details: $detail: expr) => {
http_problem_type!($status);
fn details(&self) -> CowStr {
$detail.into()
}
};
($status: ident, details <- $detail: ident) => {
http_problem_type!($status);
fn details(&self) -> CowStr {
self.$detail.to_string().into()
}
};
}
macro_rules! zst_problem_type {
($(#[$doc:meta])+ $name:ident, $status_code:ident, $details:literal) => {
$(#[$doc])+
#[derive(Debug, Copy, Clone)]
pub struct $name {
_inner: (),
}
impl fmt::Display for $name {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(stringify!($name))
}
}
impl Error for $name {}
impl CustomProblem for $name {
http_problem_type!(
$status_code,
details: $details
);
fn add_extensions(&self, _: &mut Extensions) {}
}
}
}
#[derive(Debug)]
pub struct BadRequest {
msg: CowStr,
}
impl fmt::Display for BadRequest {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.msg)
}
}
impl Error for BadRequest {}
impl CustomProblem for BadRequest {
http_problem_type!(BAD_REQUEST, details <- msg);
fn add_extensions(&self, _: &mut Extensions) {}
}
zst_problem_type!(
Unauthorized,
UNAUTHORIZED,
"You don't have the necessary permissions"
);
zst_problem_type!(
Forbidden,
FORBIDDEN,
"You don't have the necessary permissions"
);
zst_problem_type!(
PreconditionFailed,
PRECONDITION_FAILED,
"Some request precondition could not be satisfied."
);
#[derive(Debug)]
pub struct NotFound {
identifier: String,
entity: &'static str,
}
impl NotFound {
pub const fn entity(&self) -> &'static str {
self.entity
}
}
impl fmt::Display for NotFound {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"The {} identified by '{}' wasn't found",
self.entity, self.identifier
)
}
}
impl Error for NotFound {}
impl CustomProblem for NotFound {
http_problem_type!(NOT_FOUND, display);
fn add_extensions(&self, extensions: &mut Extensions) {
extensions.insert("identifier", &self.identifier);
extensions.insert("entity", self.entity);
}
}
#[derive(Debug, Clone)]
pub struct Conflict {
msg: CowStr,
}
impl fmt::Display for Conflict {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Conflict: {}", self.msg)
}
}
impl Error for Conflict {}
impl CustomProblem for Conflict {
http_problem_type!(CONFLICT, details <- msg);
fn add_extensions(&self, _: &mut Extensions) {}
}
#[derive(Debug)]
pub struct UnprocessableEntity {
msg: CowStr,
}
impl fmt::Display for UnprocessableEntity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Unprocessable Entity: {}", self.msg)
}
}
impl Error for UnprocessableEntity {}
impl CustomProblem for UnprocessableEntity {
http_problem_type!(UNPROCESSABLE_ENTITY, details <- msg);
fn add_extensions(&self, _: &mut Extensions) {}
}
#[derive(Debug)]
pub struct InternalError {
inner: Box<dyn Error + Send + Sync + 'static>,
}
impl fmt::Display for InternalError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.inner.fmt(f)
}
}
impl Error for InternalError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
Some(&*self.inner)
}
}
zst_problem_type!(
ServiceUnavailable,
SERVICE_UNAVAILABLE,
"The service is currently unavailable, try again after an exponential backoff"
);
#[cfg(test)]
mod tests {
use super::*;
macro_rules! test_constructor {
($test_fn: ident, $constructor: ident, $ty: ty $(,$arg: expr)*) => {
#[test]
fn $test_fn() {
let prd = $constructor($($arg),*);
assert!(prd.is::<$ty>());
}
};
}
test_constructor!(test_bad_request, bad_request, BadRequest, "bla");
test_constructor!(test_unauthorized, unauthorized, Unauthorized);
test_constructor!(test_forbidden, forbidden, Forbidden);
test_constructor!(test_not_found, not_found, NotFound, "bla", "foo");
test_constructor!(test_conflict, conflict, Conflict, "bla");
test_constructor!(
test_failed_precondition,
failed_precondition,
PreconditionFailed
);
test_constructor!(
test_unprocessable,
unprocessable,
UnprocessableEntity,
"bla"
);
test_constructor!(
test_internal_error,
internal_error,
InternalError,
std::io::Error::new(std::io::ErrorKind::Other, "bla")
);
test_constructor!(
test_service_unavailable,
service_unavailable,
ServiceUnavailable
);
}