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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
//! Call-site conveniences: the one-liners a handler is mostly made of.
//!
//! Everything here is sugar over [`JsonApiError`](crate::JsonApiError),
//! [`api!`](crate::api!) and axum — there is no behaviour in this module that
//! is not reachable by writing the long form, and the long form stays the
//! documented one. What these buy is that the short form is *also* the
//! correct one: an error built by hand is one forgotten `.in_context(ctx)`
//! away from an error the audit log cannot resolve, and a router assembled by
//! hand is one forgotten [`layer()`](crate::layer()) away from a service where
//! every request is a `500`.
//!
//! # Errors
//!
//! [`jsonapi_error!`](crate::jsonapi_error!) builds any code, and the named
//! shortcuts cover the ones a handler actually reaches for:
//!
//! ```
//! # use ash_jsonapi::Context;
//! # let ctx = Context::new("");
//! # let field = "message";
//! // Long form:
//! # use ash_jsonapi::{ErrorCode, JsonApiError};
//! let err = JsonApiError::in_request(ErrorCode::NotFound, &ctx)
//! .detail("no such todo");
//!
//! // Short form — the same error, with the context threaded for you:
//! let err = ash_jsonapi::not_found!(ctx, "no such todo");
//!
//! // Pointing at the member at fault:
//! let err = ash_jsonapi::invalid_attribute!(ctx, "must not be empty", field);
//! # let _ = err;
//! ```
//!
//! # Guards
//!
//! [`ensure!`](crate::ensure!) is the `rpc_validate!` of this crate: a
//! precondition that returns a JSON:API error rather than panicking, so a
//! handler reads as its rules.
//!
//! ```
//! # use ash_jsonapi::{Context, JsonApiError};
//! fn check(message: &str, ctx: &Context) -> Result<(), JsonApiError> {
//! ash_jsonapi::ensure!(!message.is_empty(), ctx, "message must not be empty", "message");
//! Ok(())
//! }
//! # let ctx = Context::new("");
//! # assert!(check("", &ctx).is_err());
//! # assert!(check("hi", &ctx).is_ok());
//! ```
/// Build a [`JsonApiError`](crate::JsonApiError) of any code, in a request's
/// context.
///
/// The general form the named shortcuts below are written in terms of. The
/// context comes first because every error should carry the correlation id —
/// that is what makes "here is my error id" resolvable in the audit log, and
/// threading it here means it cannot be forgotten at a call site.
///
/// ```
/// # use ash_jsonapi::{Context, ErrorCode};
/// # let ctx = Context::new("");
/// // A bare code:
/// let err = ash_jsonapi::jsonapi_error!(ctx, ErrorCode::Conflict);
///
/// // With client-facing detail:
/// let err = ash_jsonapi::jsonapi_error!(ctx, ErrorCode::Conflict, "the row moved under you");
///
/// // Pointing at an attribute, or a query parameter:
/// let err = ash_jsonapi::jsonapi_error!(ctx, ErrorCode::InvalidAttribute, "too long", attribute: "message");
/// let err = ash_jsonapi::jsonapi_error!(ctx, ErrorCode::InvalidParameter, "unknown field", parameter: "sort");
/// # let _ = err;
/// ```
/// A `404`, optionally saying what was not found.
///
/// ```
/// # use ash_jsonapi::Context;
/// # let ctx = Context::new("");
/// let err = ash_jsonapi::not_found!(ctx);
/// let err = ash_jsonapi::not_found!(ctx, "no todo with that id");
/// # let _ = err;
/// ```
/// A `403` — a deliberate denial, not an outage.
/// A `409` — an optimistic-concurrency failure the client may retry.
/// A `422` naming the attribute at fault.
///
/// The third argument is an attribute *name*, not a pointer: `message`
/// becomes `/data/attributes/message`, and a dotted `address.city` nests.
/// Omit it when no single member is to blame.
///
/// ```
/// # use ash_jsonapi::Context;
/// # let ctx = Context::new("");
/// let err = ash_jsonapi::invalid_attribute!(ctx, "must not be empty", "message");
/// let err = ash_jsonapi::invalid_attribute!(ctx, "one of `from`/`to` is required");
/// # let _ = err;
/// ```
/// A `400` naming the query parameter at fault.
///
/// ```
/// # use ash_jsonapi::Context;
/// # let ctx = Context::new("");
/// let err = ash_jsonapi::invalid_parameter!(ctx, "cannot sort on `secret`", "sort");
/// # let _ = err;
/// ```
/// A `500` that says nothing to the client.
///
/// There is no detail argument, and that is deliberate: the detail of an
/// internal error is exactly what must not reach a client, and
/// [`ErrorCode::is_sanitized`](crate::ErrorCode::is_sanitized) would drop it
/// anyway. Log the cause against the correlation id this carries.
/// Return a JSON:API error unless a condition holds.
///
/// The guard clause a handler's preconditions are written as — the
/// counterpart of `assert!` for something that is the client's fault rather
/// than a bug. Everything after the condition is passed to
/// [`invalid_attribute!`](crate::invalid_attribute!), so the member at fault
/// is named where there is one.
///
/// ```
/// # use ash_jsonapi::{Context, JsonApiError};
/// fn rename(name: &str, ctx: &Context) -> Result<(), JsonApiError> {
/// ash_jsonapi::ensure!(!name.is_empty(), ctx, "name must not be empty", "name");
/// ash_jsonapi::ensure!(name.len() <= 80, ctx, "name must be 80 characters or fewer", "name");
/// Ok(())
/// }
/// # let ctx = Context::new("");
/// # assert!(rename("", &ctx).is_err());
/// # assert!(rename("ok", &ctx).is_ok());
/// ```
///
/// Use [`ensure_code!`](crate::ensure_code!) for a guard that is not a `422`.
/// Return an error of a chosen code unless a condition holds.
///
/// [`ensure!`](crate::ensure!) with the code spelled out — for a guard that
/// is a denial, a conflict, or anything else a `422` would misdescribe.
///
/// ```
/// # use ash_jsonapi::{Context, ErrorCode, JsonApiError};
/// fn delete(owner: &str, actor: &str, ctx: &Context) -> Result<(), JsonApiError> {
/// ash_jsonapi::ensure_code!(
/// owner == actor,
/// ctx,
/// ErrorCode::Forbidden,
/// "only the owner may delete this todo"
/// );
/// Ok(())
/// }
/// # let ctx = Context::new("");
/// # assert!(delete("a", "b", &ctx).is_err());
/// # assert!(delete("a", "a", &ctx).is_ok());
/// ```
/// Unwrap an [`Option`], or return a `404`.
///
/// The shape of nearly every `READ` handler: a row that is not there is not
/// an error the server made, it is a `404` with a sentence.
///
/// ```
/// # use ash_jsonapi::{Context, JsonApiError};
/// # struct Todo;
/// fn fetch(row: Option<Todo>, ctx: &Context) -> Result<Todo, JsonApiError> {
/// let todo = ash_jsonapi::found!(row, ctx, "no todo with that id");
/// Ok(todo)
/// }
/// # let ctx = Context::new("");
/// # assert!(fetch(None, &ctx).is_err());
/// # assert!(fetch(Some(Todo), &ctx).is_ok());
/// ```
/// A [`Translation`](crate::i18n::Translation) key with its params.
///
/// The short form of `Translation::new(key).param(k, v)…`, for attaching to
/// an error with [`translate`](crate::JsonApiError::translate).
///
/// ```
/// # use ash_jsonapi::Context;
/// # let ctx = Context::new("");
/// let err = ash_jsonapi::invalid_attribute!(ctx, "must be 80 or fewer", "name")
/// .translate(ash_jsonapi::t!("todo.name.too_long", max = 80));
///
/// let meta = err.to_object().meta.unwrap();
/// assert_eq!(meta["i18n"]["key"], "todo.name.too_long");
/// assert_eq!(meta["i18n"]["params"]["max"], 80);
/// ```
/// Assemble a router from several `api!` modules, with the context layer
/// already attached.
///
/// [`api!`](crate::api!) writes a `routes()` per resource, which leaves two
/// things to remember at the top level: merging them, and calling
/// [`layer()`](crate::layer()). Forgetting the second is not a subtle bug —
/// every request becomes a `500`, because no handler can find its
/// [`Context`](crate::Context) — so it is worth not being able to forget.
///
/// ```ignore
/// mod todos { ash_jsonapi::api! { /* … */ } }
/// mod users { ash_jsonapi::api! { /* … */ } }
///
/// let app = ash_jsonapi::router!(App, todos::routes(), users::routes());
/// ```
///
/// Equivalent to merging each router, adding `layer()`, and calling
/// `.with_state(…)` yourself — write that out when you need another layer in
/// between.
/// Bind an address and serve, until the process is asked to stop.
///
/// The last step of every service, and the one with the most ways to be
/// subtly wrong: a server that ignores `SIGTERM` is killed mid-request on
/// every deploy, so the shutdown signal is wired in rather than left as an
/// exercise.
///
/// ```ignore
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let app = ash_jsonapi::router!(App, todos::routes()).with_state(state);
/// ash_jsonapi::serve!("0.0.0.0:3000", app).await?;
/// Ok(())
/// }
/// ```
///
/// Yields `std::io::Result<()>`. Use [`axum::serve()`] directly when you need
/// a listener you built yourself, or a different shutdown condition.
/// Resolve when the process is asked to stop: `Ctrl-C`, or `SIGTERM`.
///
/// What [`serve!`](crate::serve!) waits on, exposed because a service that
/// builds its own [`axum::serve()`] wants the same condition. `SIGTERM` is the
/// one that matters in production — it is what a container runtime and an
/// orchestrator send before a deploy — and it is the one most hand-written
/// shutdown handlers omit, leaving in-flight requests to be killed rather
/// than finished.
///
/// On a non-Unix target only `Ctrl-C` is awaited; there is no `SIGTERM` to
/// listen for.
pub async