Skip to main content

ash_jsonapi/
macros.rs

1//! Call-site conveniences: the one-liners a handler is mostly made of.
2//!
3//! Everything here is sugar over [`JsonApiError`](crate::JsonApiError),
4//! [`api!`](crate::api!) and axum — there is no behaviour in this module that
5//! is not reachable by writing the long form, and the long form stays the
6//! documented one. What these buy is that the short form is *also* the
7//! correct one: an error built by hand is one forgotten `.in_context(ctx)`
8//! away from an error the audit log cannot resolve, and a router assembled by
9//! hand is one forgotten [`layer()`](crate::layer()) away from a service where
10//! every request is a `500`.
11//!
12//! # Errors
13//!
14//! [`jsonapi_error!`](crate::jsonapi_error!) builds any code, and the named
15//! shortcuts cover the ones a handler actually reaches for:
16//!
17//! ```
18//! # use ash_jsonapi::Context;
19//! # let ctx = Context::new("");
20//! # let field = "message";
21//! // Long form:
22//! # use ash_jsonapi::{ErrorCode, JsonApiError};
23//! let err = JsonApiError::in_request(ErrorCode::NotFound, &ctx)
24//!     .detail("no such todo");
25//!
26//! // Short form — the same error, with the context threaded for you:
27//! let err = ash_jsonapi::not_found!(ctx, "no such todo");
28//!
29//! // Pointing at the member at fault:
30//! let err = ash_jsonapi::invalid_attribute!(ctx, "must not be empty", field);
31//! # let _ = err;
32//! ```
33//!
34//! # Guards
35//!
36//! [`ensure!`](crate::ensure!) is the `rpc_validate!` of this crate: a
37//! precondition that returns a JSON:API error rather than panicking, so a
38//! handler reads as its rules.
39//!
40//! ```
41//! # use ash_jsonapi::{Context, JsonApiError};
42//! fn check(message: &str, ctx: &Context) -> Result<(), JsonApiError> {
43//!     ash_jsonapi::ensure!(!message.is_empty(), ctx, "message must not be empty", "message");
44//!     Ok(())
45//! }
46//! # let ctx = Context::new("");
47//! # assert!(check("", &ctx).is_err());
48//! # assert!(check("hi", &ctx).is_ok());
49//! ```
50
51/// Build a [`JsonApiError`](crate::JsonApiError) of any code, in a request's
52/// context.
53///
54/// The general form the named shortcuts below are written in terms of. The
55/// context comes first because every error should carry the correlation id —
56/// that is what makes "here is my error id" resolvable in the audit log, and
57/// threading it here means it cannot be forgotten at a call site.
58///
59/// ```
60/// # use ash_jsonapi::{Context, ErrorCode};
61/// # let ctx = Context::new("");
62/// // A bare code:
63/// let err = ash_jsonapi::jsonapi_error!(ctx, ErrorCode::Conflict);
64///
65/// // With client-facing detail:
66/// let err = ash_jsonapi::jsonapi_error!(ctx, ErrorCode::Conflict, "the row moved under you");
67///
68/// // Pointing at an attribute, or a query parameter:
69/// let err = ash_jsonapi::jsonapi_error!(ctx, ErrorCode::InvalidAttribute, "too long", attribute: "message");
70/// let err = ash_jsonapi::jsonapi_error!(ctx, ErrorCode::InvalidParameter, "unknown field", parameter: "sort");
71/// # let _ = err;
72/// ```
73#[macro_export]
74macro_rules! jsonapi_error {
75    ($ctx:expr, $code:expr $(,)?) => {
76        $crate::JsonApiError::in_request($code, &$ctx)
77    };
78    ($ctx:expr, $code:expr, $detail:expr $(,)?) => {
79        $crate::JsonApiError::in_request($code, &$ctx).detail($detail)
80    };
81    ($ctx:expr, $code:expr, $detail:expr, attribute: $field:expr $(,)?) => {
82        $crate::JsonApiError::in_request($code, &$ctx)
83            .detail($detail)
84            .attribute($field)
85    };
86    ($ctx:expr, $code:expr, $detail:expr, pointer: $pointer:expr $(,)?) => {
87        $crate::JsonApiError::in_request($code, &$ctx)
88            .detail($detail)
89            .pointer($pointer)
90    };
91    ($ctx:expr, $code:expr, $detail:expr, parameter: $param:expr $(,)?) => {
92        $crate::JsonApiError::in_request($code, &$ctx)
93            .detail($detail)
94            .parameter($param)
95    };
96}
97
98/// A `404`, optionally saying what was not found.
99///
100/// ```
101/// # use ash_jsonapi::Context;
102/// # let ctx = Context::new("");
103/// let err = ash_jsonapi::not_found!(ctx);
104/// let err = ash_jsonapi::not_found!(ctx, "no todo with that id");
105/// # let _ = err;
106/// ```
107#[macro_export]
108macro_rules! not_found {
109    ($ctx:expr $(,)?) => {
110        $crate::jsonapi_error!($ctx, $crate::ErrorCode::NotFound)
111    };
112    ($ctx:expr, $detail:expr $(,)?) => {
113        $crate::jsonapi_error!($ctx, $crate::ErrorCode::NotFound, $detail)
114    };
115}
116
117/// A `403` — a deliberate denial, not an outage.
118#[macro_export]
119macro_rules! forbidden {
120    ($ctx:expr $(,)?) => {
121        $crate::jsonapi_error!($ctx, $crate::ErrorCode::Forbidden)
122    };
123    ($ctx:expr, $detail:expr $(,)?) => {
124        $crate::jsonapi_error!($ctx, $crate::ErrorCode::Forbidden, $detail)
125    };
126}
127
128/// A `409` — an optimistic-concurrency failure the client may retry.
129#[macro_export]
130macro_rules! conflict {
131    ($ctx:expr $(,)?) => {
132        $crate::jsonapi_error!($ctx, $crate::ErrorCode::Conflict)
133    };
134    ($ctx:expr, $detail:expr $(,)?) => {
135        $crate::jsonapi_error!($ctx, $crate::ErrorCode::Conflict, $detail)
136    };
137}
138
139/// A `422` naming the attribute at fault.
140///
141/// The third argument is an attribute *name*, not a pointer: `message`
142/// becomes `/data/attributes/message`, and a dotted `address.city` nests.
143/// Omit it when no single member is to blame.
144///
145/// ```
146/// # use ash_jsonapi::Context;
147/// # let ctx = Context::new("");
148/// let err = ash_jsonapi::invalid_attribute!(ctx, "must not be empty", "message");
149/// let err = ash_jsonapi::invalid_attribute!(ctx, "one of `from`/`to` is required");
150/// # let _ = err;
151/// ```
152#[macro_export]
153macro_rules! invalid_attribute {
154    ($ctx:expr, $detail:expr $(,)?) => {
155        $crate::jsonapi_error!($ctx, $crate::ErrorCode::InvalidAttribute, $detail)
156    };
157    ($ctx:expr, $detail:expr, $field:expr $(,)?) => {
158        $crate::jsonapi_error!(
159            $ctx,
160            $crate::ErrorCode::InvalidAttribute,
161            $detail,
162            attribute: $field
163        )
164    };
165}
166
167/// A `400` naming the query parameter at fault.
168///
169/// ```
170/// # use ash_jsonapi::Context;
171/// # let ctx = Context::new("");
172/// let err = ash_jsonapi::invalid_parameter!(ctx, "cannot sort on `secret`", "sort");
173/// # let _ = err;
174/// ```
175#[macro_export]
176macro_rules! invalid_parameter {
177    ($ctx:expr, $detail:expr $(,)?) => {
178        $crate::jsonapi_error!($ctx, $crate::ErrorCode::InvalidParameter, $detail)
179    };
180    ($ctx:expr, $detail:expr, $param:expr $(,)?) => {
181        $crate::jsonapi_error!(
182            $ctx,
183            $crate::ErrorCode::InvalidParameter,
184            $detail,
185            parameter: $param
186        )
187    };
188}
189
190/// A `500` that says nothing to the client.
191///
192/// There is no detail argument, and that is deliberate: the detail of an
193/// internal error is exactly what must not reach a client, and
194/// [`ErrorCode::is_sanitized`](crate::ErrorCode::is_sanitized) would drop it
195/// anyway. Log the cause against the correlation id this carries.
196#[macro_export]
197macro_rules! internal_error {
198    ($ctx:expr $(,)?) => {
199        $crate::JsonApiError::internal(&$ctx)
200    };
201}
202
203/// Return a JSON:API error unless a condition holds.
204///
205/// The guard clause a handler's preconditions are written as — the
206/// counterpart of `assert!` for something that is the client's fault rather
207/// than a bug. Everything after the condition is passed to
208/// [`invalid_attribute!`](crate::invalid_attribute!), so the member at fault
209/// is named where there is one.
210///
211/// ```
212/// # use ash_jsonapi::{Context, JsonApiError};
213/// fn rename(name: &str, ctx: &Context) -> Result<(), JsonApiError> {
214///     ash_jsonapi::ensure!(!name.is_empty(), ctx, "name must not be empty", "name");
215///     ash_jsonapi::ensure!(name.len() <= 80, ctx, "name must be 80 characters or fewer", "name");
216///     Ok(())
217/// }
218/// # let ctx = Context::new("");
219/// # assert!(rename("", &ctx).is_err());
220/// # assert!(rename("ok", &ctx).is_ok());
221/// ```
222///
223/// Use [`ensure_code!`](crate::ensure_code!) for a guard that is not a `422`.
224#[macro_export]
225macro_rules! ensure {
226    ($condition:expr, $ctx:expr, $($error:tt)+) => {
227        if !($condition) {
228            return ::std::result::Result::Err(
229                $crate::invalid_attribute!($ctx, $($error)+).into()
230            );
231        }
232    };
233}
234
235/// Return an error of a chosen code unless a condition holds.
236///
237/// [`ensure!`](crate::ensure!) with the code spelled out — for a guard that
238/// is a denial, a conflict, or anything else a `422` would misdescribe.
239///
240/// ```
241/// # use ash_jsonapi::{Context, ErrorCode, JsonApiError};
242/// fn delete(owner: &str, actor: &str, ctx: &Context) -> Result<(), JsonApiError> {
243///     ash_jsonapi::ensure_code!(
244///         owner == actor,
245///         ctx,
246///         ErrorCode::Forbidden,
247///         "only the owner may delete this todo"
248///     );
249///     Ok(())
250/// }
251/// # let ctx = Context::new("");
252/// # assert!(delete("a", "b", &ctx).is_err());
253/// # assert!(delete("a", "a", &ctx).is_ok());
254/// ```
255#[macro_export]
256macro_rules! ensure_code {
257    ($condition:expr, $ctx:expr, $($error:tt)+) => {
258        if !($condition) {
259            return ::std::result::Result::Err(
260                $crate::jsonapi_error!($ctx, $($error)+).into()
261            );
262        }
263    };
264}
265
266/// Unwrap an [`Option`], or return a `404`.
267///
268/// The shape of nearly every `READ` handler: a row that is not there is not
269/// an error the server made, it is a `404` with a sentence.
270///
271/// ```
272/// # use ash_jsonapi::{Context, JsonApiError};
273/// # struct Todo;
274/// fn fetch(row: Option<Todo>, ctx: &Context) -> Result<Todo, JsonApiError> {
275///     let todo = ash_jsonapi::found!(row, ctx, "no todo with that id");
276///     Ok(todo)
277/// }
278/// # let ctx = Context::new("");
279/// # assert!(fetch(None, &ctx).is_err());
280/// # assert!(fetch(Some(Todo), &ctx).is_ok());
281/// ```
282#[macro_export]
283macro_rules! found {
284    ($option:expr, $ctx:expr $(,)?) => {
285        match $option {
286            ::std::option::Option::Some(value) => value,
287            ::std::option::Option::None => {
288                return ::std::result::Result::Err($crate::not_found!($ctx).into());
289            }
290        }
291    };
292    ($option:expr, $ctx:expr, $detail:expr $(,)?) => {
293        match $option {
294            ::std::option::Option::Some(value) => value,
295            ::std::option::Option::None => {
296                return ::std::result::Result::Err($crate::not_found!($ctx, $detail).into());
297            }
298        }
299    };
300}
301
302/// A [`Translation`](crate::i18n::Translation) key with its params.
303///
304/// The short form of `Translation::new(key).param(k, v)…`, for attaching to
305/// an error with [`translate`](crate::JsonApiError::translate).
306///
307/// ```
308/// # use ash_jsonapi::Context;
309/// # let ctx = Context::new("");
310/// let err = ash_jsonapi::invalid_attribute!(ctx, "must be 80 or fewer", "name")
311///     .translate(ash_jsonapi::t!("todo.name.too_long", max = 80));
312///
313/// let meta = err.to_object().meta.unwrap();
314/// assert_eq!(meta["i18n"]["key"], "todo.name.too_long");
315/// assert_eq!(meta["i18n"]["params"]["max"], 80);
316/// ```
317#[macro_export]
318macro_rules! t {
319    ($key:expr $(,)?) => {
320        $crate::i18n::Translation::new($key)
321    };
322    ($key:expr, $($name:ident = $value:expr),+ $(,)?) => {
323        $crate::i18n::Translation::new($key)
324            $(.param(::std::stringify!($name), $value))+
325    };
326}
327
328/// Assemble a router from several `api!` modules, with the context layer
329/// already attached.
330///
331/// [`api!`](crate::api!) writes a `routes()` per resource, which leaves two
332/// things to remember at the top level: merging them, and calling
333/// [`layer()`](crate::layer()). Forgetting the second is not a subtle bug —
334/// every request becomes a `500`, because no handler can find its
335/// [`Context`](crate::Context) — so it is worth not being able to forget.
336///
337/// ```ignore
338/// mod todos { ash_jsonapi::api! { /* … */ } }
339/// mod users { ash_jsonapi::api! { /* … */ } }
340///
341/// let app = ash_jsonapi::router!(App, todos::routes(), users::routes());
342/// ```
343///
344/// Equivalent to merging each router, adding `layer()`, and calling
345/// `.with_state(…)` yourself — write that out when you need another layer in
346/// between.
347#[cfg(feature = "http")]
348#[cfg_attr(docsrs, doc(cfg(feature = "http")))]
349#[macro_export]
350macro_rules! router {
351    ($state:ty $(, $routes:expr)+ $(,)?) => {{
352        ::axum::Router::<$state>::new()
353            $(.merge($routes))+
354            .layer($crate::layer())
355    }};
356}
357
358/// Bind an address and serve, until the process is asked to stop.
359///
360/// The last step of every service, and the one with the most ways to be
361/// subtly wrong: a server that ignores `SIGTERM` is killed mid-request on
362/// every deploy, so the shutdown signal is wired in rather than left as an
363/// exercise.
364///
365/// ```ignore
366/// #[tokio::main]
367/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
368///     let app = ash_jsonapi::router!(App, todos::routes()).with_state(state);
369///     ash_jsonapi::serve!("0.0.0.0:3000", app).await?;
370///     Ok(())
371/// }
372/// ```
373///
374/// Yields `std::io::Result<()>`. Use [`axum::serve()`] directly when you need
375/// a listener you built yourself, or a different shutdown condition.
376#[cfg(feature = "http")]
377#[cfg_attr(docsrs, doc(cfg(feature = "http")))]
378#[macro_export]
379macro_rules! serve {
380    ($addr:expr, $app:expr $(,)?) => {
381        async {
382            let listener = ::tokio::net::TcpListener::bind($addr).await?;
383            ::axum::serve(listener, $app)
384                .with_graceful_shutdown($crate::shutdown_signal())
385                .await
386        }
387    };
388}
389
390/// Resolve when the process is asked to stop: `Ctrl-C`, or `SIGTERM`.
391///
392/// What [`serve!`](crate::serve!) waits on, exposed because a service that
393/// builds its own [`axum::serve()`] wants the same condition. `SIGTERM` is the
394/// one that matters in production — it is what a container runtime and an
395/// orchestrator send before a deploy — and it is the one most hand-written
396/// shutdown handlers omit, leaving in-flight requests to be killed rather
397/// than finished.
398///
399/// On a non-Unix target only `Ctrl-C` is awaited; there is no `SIGTERM` to
400/// listen for.
401#[cfg(feature = "http")]
402#[cfg_attr(docsrs, doc(cfg(feature = "http")))]
403pub async fn shutdown_signal() {
404    let interrupt = async {
405        tokio::signal::ctrl_c()
406            .await
407            .expect("failed to install the Ctrl-C handler");
408    };
409
410    #[cfg(unix)]
411    let terminate = async {
412        tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
413            .expect("failed to install the SIGTERM handler")
414            .recv()
415            .await;
416    };
417
418    // Nothing to wait for off Unix; `pending()` keeps the `select!` below one
419    // shape rather than two.
420    #[cfg(not(unix))]
421    let terminate = std::future::pending::<()>();
422
423    tokio::select! {
424        () = interrupt => {}
425        () = terminate => {}
426    }
427}