ash_jsonapi/lib.rs
1//! Serve [JSON:API](https://jsonapi.org) from axum.
2//!
3//! Describe a resource once, and get the wire format for free: the
4//! `type`/`id` envelope, relationship linkage, `self`/`related` links,
5//! spec-shaped errors with JSON Pointers, and request-body validation.
6//!
7//! # One resource, end to end
8//!
9//! ```
10//! use std::collections::HashMap;
11//! use std::sync::{Arc, Mutex};
12//!
13//! use ash_jsonapi::Context;
14//! use ash_jsonapi::crud::{Create, List, Listing, Read, Storage};
15//! use ash_jsonapi::{Page, Query};
16//! use ash_jsonapi::validation::DocumentValidator;
17//!
18//! #[derive(Clone)]
19//! struct Todo { id: String, message: String, done: bool }
20//!
21//! // Your application state, however you already build it.
22//! #[derive(Clone)]
23//! struct App {
24//! rows: Arc<Mutex<HashMap<String, Todo>>>,
25//! validator: Arc<DocumentValidator>,
26//! }
27//!
28//! // Declared once: this writes `TodoSchema`, the `NewTodo` request body and
29//! // its parsing, the serialization, and the JSON Schema bodies are checked
30//! // against. See `resource!` for what each line turns into.
31//! ash_jsonapi::resource! {
32//! Todo as "todo" at "/todos",
33//! state: App,
34//! schema: TodoSchema,
35//! input: NewTodo,
36//! id: id,
37//! attributes: { message: String, done: bool },
38//! }
39//!
40//! // Where the validators live. Needed here because this service routes
41//! // CREATE, which has a body to check; a read-only service writes
42//! // `impl Validators for App {}` instead and carries no validator at all.
43//! ash_jsonapi::registry! {
44//! App { validator: Todo }
45//! }
46//!
47//! // Your storage. One trait per operation, so you implement only what you
48//! // route — this service creates and reads, so there is no `Update` or
49//! // `Delete` impl anywhere.
50//! impl Storage<Todo> for App {
51//! type Error = String;
52//! }
53//!
54//! impl Create<Todo> for App {
55//! // The parsed body arrives as an argument.
56//! async fn create(&self, input: NewTodo, _ctx: &Context) -> Result<Todo, String> {
57//! let mut rows = self.rows.lock().unwrap();
58//! let todo = Todo {
59//! id: format!("t_{}", rows.len() + 1),
60//! message: input.message,
61//! done: input.done,
62//! };
63//! rows.insert(todo.id.clone(), todo.clone());
64//! Ok(todo)
65//! }
66//! }
67//!
68//! impl Read<Todo> for App {
69//! async fn get(&self, id: &str) -> Result<Option<Todo>, String> {
70//! Ok(self.rows.lock().unwrap().get(id).cloned())
71//! }
72//! }
73//!
74//! impl List<Todo> for App {
75//! // `?page[…]` and `?sort=` arrive parsed; applying them is yours.
76//! async fn list(&self, query: &Query, _ctx: &Context) -> Result<Listing<Todo>, String> {
77//! let rows = self.rows.lock().unwrap();
78//! let total = rows.len();
79//! let Page::Offset { offset, limit } = query.page() else {
80//! return Err("this service pages by offset".into());
81//! };
82//!
83//! let page = rows.values().skip(*offset).take(*limit).cloned();
84//! Ok(Listing::new(page).total(total))
85//! }
86//! }
87//!
88//! // The routes: `GET|POST /todos` and `GET /todos/{id}`, and nothing else.
89//! ash_jsonapi::api! {
90//! operations: [ash_jsonapi::LIST, ash_jsonapi::CREATE, ash_jsonapi::READ],
91//! resource: Todo,
92//! name: "todo",
93//! path: "/todos",
94//! state: App,
95//! }
96//!
97//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
98//! let state = App {
99//! rows: Arc::new(Mutex::new(HashMap::new())),
100//! validator: Arc::new(Todo::validator()?),
101//! };
102//!
103//! // `layer()` attaches the per-request `Context` every handler needs.
104//! // Without it each request is a 500, so it is not optional.
105//! let app: axum::Router = routes()
106//! .layer(ash_jsonapi::layer())
107//! .with_state(state);
108//!
109//! // Then serve it:
110//! // let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await?;
111//! // axum::serve(listener, app).await?;
112//! # Ok(())
113//! # }
114//! ```
115//!
116//! That is the whole service. `routes()` is an `axum::Router<App>`; name a
117//! different set in `operations` to expose more or less, and only those
118//! operations' traits are required — so a service backed by no storage at all
119//! is `operations: [READ]` over whatever you compute on the fly.
120//!
121//! The two macros are independent. [`resource!`] writes the wire format and
122//! [`api!`] the routes, and either can be replaced by the traits it stands
123//! for — see [`crud`] and [`serialize`] for the hand-written form, which is
124//! what you want for a computed attribute or a body that is not JSON:API.
125//!
126//! # Features
127//!
128//! | Feature | Default | What it adds |
129//! |---|---|---|
130//! | `http` | yes | The axum integration: [`api!`], [`response`] |
131//! | `validation` | yes | [`validation::DocumentValidator`] — request bodies vs. a JSON Schema |
132//! | `domain` | no | [`ash-domain`](crate::domain) integration |
133//! | `audit` | yes | [`audit::Audit`] — one recorded event per operation |
134//! | `streaming` | no | [`jsonl`] — JSONL in and out: the `STREAM` and `INGEST` operations |
135//!
136//! That is the whole list. TLS, health, metrics, OpenTelemetry, OpenAPI and
137//! idempotency are planned rather than shipped, and are deliberately *not*
138//! declared as features until they gate real code — a feature that compiles
139//! and does nothing is worse than one that is absent.
140//!
141//! With `default-features = false` you get the document, error and
142//! serialization types alone — no axum, no async runtime.
143//!
144//! # Using `ash-domain`?
145//!
146//! Optional, and off by default. Enable the `domain` feature and
147//! [`domain_resource!`] writes the same traits from the schema the domain
148//! already holds — no attribute, type or relationship is restated. Actions
149//! run through the domain's own pipeline, so policies and extensions apply
150//! and a denial reaches the client as a `403`. See [`crate::domain`].
151//!
152//! Everything above works with no `ash-*` crate in the tree; the integration
153//! is a second way in, not the way in.
154//!
155//! # Layout
156//!
157//! - [`document`] — the JSON:API wire types.
158//! - [`serialize`] — your data → [`ResourceObject`], driven by [`Schema`].
159//! - [`error`] — spec-shaped errors and their statuses.
160//! - [`validation`] — request-body checking.
161//! - [`extract`] — [`FromRequest`](extract::FromRequest): a request → your types.
162//! - [`layer`](mod@layer) — [`layer()`](fn@layer): the per-request [`Context`] middleware.
163//! - [`attribute`] — [`Attribute`]: a field's type, schema and conversions,
164//! and [`Formatted`] for `format`-checked strings.
165//! - [`declare`] — [`resource!`]: one declaration, all four impls.
166//! - [`query`] — [`Query`]: `?page[…]` and `?sort=`, parsed and checked.
167//! - [`crud`] — [`Resource`](crud::Resource), the per-operation traits, and [`api!`].
168//! - files — [`Upload`](extract::Upload) in, [`Download`](response::Download)
169//! out, and the `CONTENT` operation that routes `/{id}/content`.
170//! - [`jsonl`] — one resource per line, streamed, for collections too large
171//! to be a document. `STREAM` sends them, selected by `Accept`; `INGEST`
172//! reads them, selected by `Content-Type`, answering one result line per
173//! input line so a partial batch is visible rather than guessed at.
174//! - [`response`] — axum responses.
175//! - [`context`] — per-request correlation id and principal.
176//! - [`macros`] — the one-liners a handler is made of: [`not_found!`],
177//! [`ensure!`], [`found!`], [`router!`], [`serve!`].
178//! - [`i18n`] — [`Translation`] keys on errors, and the negotiated [`Locale`].
179//! - [`hook`] — [`before`](hook::Hook::before)/[`after`](hook::Hook::after)
180//! around every operation; what audit, and later metrics, are built on.
181//! - [`audit`] — [`Audit`](audit::Audit): the audit trail, as a hook.
182
183//!
184//! # Shorthand
185//!
186//! The macros in [`macros`] are sugar over what is above — nothing there is
187//! unreachable by writing the long form. What they buy is that the short form
188//! is also the correct one: an error keeps its correlation id, a router keeps
189//! its [`layer()`](layer()), and a server keeps its shutdown signal.
190//!
191//! ```ignore
192//! // A guard, a lookup, and the service — three lines that are hard to get
193//! // subtly wrong:
194//! ash_jsonapi::ensure!(!name.is_empty(), ctx, "name must not be empty", "name");
195//! let todo = ash_jsonapi::found!(row, ctx, "no todo with that id");
196//!
197//! let app = ash_jsonapi::router!(App, todos::routes()).with_state(state);
198//! ash_jsonapi::serve!("0.0.0.0:3000", app).await?;
199//! ```
200
201#![cfg_attr(docsrs, feature(doc_cfg))]
202
203#[cfg(feature = "domain")]
204#[doc(hidden)]
205pub use ash_domain as __ash_domain;
206
207/// Re-exported so the macros can name it without the caller depending on it.
208#[doc(hidden)]
209pub use serde_json as __serde_json;
210
211pub mod attribute;
212#[cfg(feature = "audit")]
213#[cfg_attr(docsrs, doc(cfg(feature = "audit")))]
214pub mod audit;
215pub mod context;
216#[cfg(all(feature = "http", feature = "validation"))]
217#[cfg_attr(docsrs, doc(cfg(all(feature = "http", feature = "validation"))))]
218pub mod declare;
219pub mod document;
220#[cfg(feature = "domain")]
221#[cfg_attr(docsrs, doc(cfg(feature = "domain")))]
222pub mod domain;
223pub mod error;
224pub mod hook;
225pub mod i18n;
226#[cfg(all(feature = "streaming", feature = "http"))]
227#[cfg_attr(docsrs, doc(cfg(feature = "streaming")))]
228pub mod jsonl;
229pub mod macros;
230pub mod query;
231#[cfg(feature = "validation")]
232#[cfg_attr(docsrs, doc(cfg(feature = "validation")))]
233pub mod validation;
234
235#[cfg(all(feature = "http", feature = "validation"))]
236#[cfg_attr(docsrs, doc(cfg(all(feature = "http", feature = "validation"))))]
237pub mod crud;
238
239#[cfg(feature = "http")]
240#[cfg_attr(docsrs, doc(cfg(feature = "http")))]
241pub mod extract;
242
243#[cfg(feature = "http")]
244#[cfg_attr(docsrs, doc(cfg(feature = "http")))]
245pub mod layer;
246#[cfg(feature = "http")]
247#[cfg_attr(docsrs, doc(cfg(feature = "http")))]
248pub mod response;
249pub mod serialize;
250
251pub use attribute::{Attribute, FormatName, Formatted};
252pub use context::Context;
253pub use document::{
254 Document, ErrorObject, ErrorSource, Linkage, Links, MEDIA_TYPE, PrimaryData, Relationship,
255 ResourceIdentifier, ResourceObject,
256};
257pub use error::{ErrorCode, JsonApiError};
258pub use i18n::{Locale, Translation};
259#[cfg(feature = "http")]
260pub use layer::layer;
261#[cfg(feature = "http")]
262pub use macros::shutdown_signal;
263pub use query::{Page, Paginator, Query, Sort};
264pub use serialize::{NoRelationships, Rel, RelationshipDef, Schema, Serializer};