Skip to main content

ash_jsonapi/
crud.rs

1//! Generated CRUD routes.
2//!
3//! The four handlers for a resource differ only in its type and its
4//! relationships — everything else is the same shape every time. [`api!`](crate::api!)
5//! writes them, against whatever storage you already have.
6//!
7//! Two traits connect them to your code:
8//!
9//! - [`Resource`] — how one of your types becomes a JSON:API resource
10//!   object, and how a request document becomes one of your types.
11//! - [`Validators`] — where the validators live, on your application state.
12//! - [`Storage<R>`](Storage) — names the error type for one resource, plus
13//!   one trait per operation: [`Create`], [`Read`], [`Update`], [`Delete`].
14//!   Implement only the ones you route — a read-only proxy writes [`Read`]
15//!   and nothing else.
16//!
17//! ```ignore
18//! ash_jsonapi::api! {
19//!     operations: [ash_jsonapi::CRUD],
20//!     resource: Todo,
21//!     name: "todo",
22//!     path: "/api/v1/todos",
23//!     state: App,
24//! }
25//! ```
26//!
27//! [`resource!`](crate::resource!) writes the [`Resource`] impl for you, so
28//! in practice what you write here is the storage: one trait per operation
29//! you route.
30//!
31//! The generated handlers take the request's [`Context`] as an axum
32//! extension, so the router needs [`ash_jsonapi::layer()`](crate::layer())
33//! — without it every request is a `500`.
34
35use crate::context::Context;
36use crate::document::ResourceObject;
37use crate::error::JsonApiError;
38use crate::extract::FromRequest;
39use crate::query::Query;
40use crate::response::Errors;
41use crate::validation::DocumentValidator;
42
43/// One of your types, as a JSON:API resource.
44///
45/// The two directions a handler needs: reading a validated request document
46/// into your type, and writing your type back out as a resource object.
47pub trait Resource<S: Validators>: Sized + Send + 'static {
48    /// What a create body turns into.
49    ///
50    /// Its [`FromRequest`] impl owns reading and validating the request, so a
51    /// resource whose body is not JSON:API — multipart, form-encoded — needs
52    /// no special case here.
53    ///
54    /// Usually `Self`, but it can be a distinct type when a create carries
55    /// different fields from a stored row.
56    type Create: FromRequest<S>;
57
58    /// What an update body turns into. Usually the same as
59    /// [`Self::Create`](Resource::Create).
60    type Update: FromRequest<S>;
61
62    /// The JSON:API `type` member, e.g. `"todo"`.
63    const NAME: &'static str;
64
65    /// Where the resource is mounted, e.g. `/api/v1/todos`.
66    const PATH: &'static str;
67
68    /// Write this row out as a resource object, links and linkage included.
69    ///
70    /// `state` is your application state, for anything resolved at startup
71    /// rather than compiled in — a schema registry, a base URL, a feature
72    /// flag deciding whether an attribute is exposed. Ignore it when the
73    /// resource knows its own shape, which is the usual case.
74    fn to_resource(&self, state: &S, ctx: &Context) -> Result<ResourceObject, JsonApiError>;
75}
76
77/// Your application state, as the generated handlers see it.
78///
79/// Only the validators live here, because they are per-resource but built
80/// once at startup. The operations are on [`Create`], [`Read`], [`Update`]
81/// and [`Delete`] — one trait each, so a resource implements only what it
82/// actually serves.
83///
84/// # A read-only service implements this for free
85///
86/// Validators check *request bodies*, and `GET` has none. A service that
87/// routes only [`LIST`](crate::api!) and [`READ`](crate::api!) therefore
88/// never reaches a validator, so the method below defaults to `None` and
89/// such a service needs no [`registry!`](crate::registry!) at all:
90///
91/// ```ignore
92/// // The whole implementation, for a service that accepts no bodies.
93/// impl Validators for App {}
94/// ```
95///
96/// Route an operation that *does* carry a body — `CREATE` or `UPDATE` —
97/// without registering its validator, and the request fails as the wiring
98/// bug it is, naming the resource. Use [`registry!`](crate::registry!) to
99/// write the lookup rather than spelling it out.
100#[diagnostic::on_unimplemented(
101    message = "`{Self}` is not wired up as ash-jsonapi application state",
102    label = "this state needs a `Validators` impl",
103    note = "a service that accepts no request bodies needs only an empty impl: `impl ash_jsonapi::crud::Validators for {Self}` with no body",
104    note = "one that routes CREATE or UPDATE registers its validators instead, with the `ash_jsonapi::registry!` macro"
105)]
106pub trait Validators: Clone + Send + Sync + 'static {
107    /// The compiled request-body validator for one resource, by name.
108    ///
109    /// `None` means the resource has no validator registered. For a service
110    /// that accepts no request bodies that is the correct answer and the
111    /// default; for one that routes `CREATE` or `UPDATE` it is a wiring bug,
112    /// and reported as one rather than as a `404`.
113    fn validator(&self, _resource: &str) -> Option<&DocumentValidator> {
114        None
115    }
116
117    /// The hooks to run around every operation on this state.
118    ///
119    /// `None` — the default — skips the mechanism entirely: no event is
120    /// built and no hook list is walked, so a service that registers no
121    /// hooks pays nothing for their existence.
122    ///
123    /// This lives on `Validators` rather than a trait of its own because every
124    /// state already implements `Validators`; a second required trait would make
125    /// every existing service add an empty impl to keep compiling, and a
126    /// blanket impl would make the override impossible rather than optional.
127    ///
128    /// ```ignore
129    /// impl Validators for App {
130    ///     fn hooks(&self) -> Option<&Hooks> {
131    ///         Some(&self.hooks)
132    ///     }
133    /// }
134    /// ```
135    fn hooks(&self) -> Option<&crate::hook::Hooks> {
136        None
137    }
138}
139
140/// What a resource's operations fail with.
141///
142/// Split from the operation traits so an implementation names its error once
143/// rather than in each of the four.
144///
145/// The error reaches the client as a `500` carrying only the correlation id —
146/// the `Display` output is logged, never serialized — so it is safe to return
147/// whatever your data layer produces.
148pub trait Storage<R>: Validators {
149    /// Whatever your storage fails with.
150    type Error: std::fmt::Display + Send;
151
152    /// Report a failure that is the client's fault, not the server's.
153    ///
154    /// Storage errors are `500`s by default, and deliberately opaque: the
155    /// `Display` output is logged, never serialized, so a connection string
156    /// in an error message cannot reach a client.
157    ///
158    /// Some failures are not the server's fault, though — a `?sort=` field
159    /// the table cannot order on, a cursor that has expired, a page beyond
160    /// what the backend will serve. Returning `500` for those tells the
161    /// client to retry something that will never work. Override this to
162    /// classify them:
163    ///
164    /// ```ignore
165    /// fn classify(&self, err: &Self::Error, ctx: &Context) -> Option<JsonApiError> {
166    ///     match err {
167    ///         Error::UnsortableField(field) => Some(
168    ///             JsonApiError::in_request(ErrorCode::InvalidParameter, ctx)
169    ///                 .detail(format!("cannot sort on `{field}`"))
170    ///                 .parameter("sort"),
171    ///         ),
172    ///         // Everything else stays a logged 500.
173    ///         _ => None,
174    ///     }
175    /// }
176    /// ```
177    ///
178    /// `None` — the default — keeps whatever you return out of the response
179    /// body. Whatever you *do* return is sent to the client, so return only
180    /// what you would put in a log anyone can read. `ctx` is the request's,
181    /// so the error carries the same correlation id as everything else it
182    /// will be read beside.
183    ///
184    /// Note that the most common reason to reach for this — a `?sort=` field
185    /// you cannot order by — is already handled: declare
186    /// [`sortable`](Storage::sortable) and the request is refused with a
187    /// `400` before `list` is ever called.
188    fn classify(&self, err: &Self::Error, ctx: &Context) -> Option<JsonApiError> {
189        let _ = (err, ctx);
190        None
191    }
192
193    /// The attributes `?sort=` may name, or `None` for "anything goes".
194    ///
195    /// Declaring this closes the gap that
196    /// [`classify`](Storage::classify) otherwise leaves open. A `?sort=`
197    /// naming something absent from this list is the client's mistake, and
198    /// without the list it reaches `list`, comes back as a storage error, and
199    /// — unless `classify` recognises it — is answered with a `500` telling
200    /// the client to retry a request that can never succeed.
201    ///
202    /// With the list, the same request is refused with a `400` naming the
203    /// `sort` parameter, before storage is touched:
204    ///
205    /// ```ignore
206    /// impl Storage<Todo> for App {
207    ///     type Error = StoreError;
208    ///
209    ///     fn sortable(&self) -> Option<&[&str]> {
210    ///         Some(&["id", "message", "done"])
211    ///     }
212    /// }
213    /// ```
214    ///
215    /// `None` — the default — preserves the old behaviour for storage that
216    /// can order by anything, or that would rather decide for itself.
217    fn sortable(&self) -> Option<&[&str]> {
218        None
219    }
220}
221
222/// `POST /resource` — persist a new row.
223///
224/// Implement it only if you route [`CREATE`](crate::api!); a resource that
225/// does not accept creates needs no impl at all.
226///
227/// ```ignore
228/// impl Create<Todo> for App {
229///     async fn create(&self, input: NewTodo, ctx: &Context) -> Result<Todo, Self::Error> {
230///         sqlx::query_as("insert into todos …")
231///             .bind(&input.message)
232///             .fetch_one(&self.db)
233///             .await
234///     }
235/// }
236/// ```
237pub trait Create<R: Resource<Self>>: Storage<R> {
238    /// Persist a new row, assigning its id.
239    ///
240    /// The parsed body arrives as an argument, built by
241    /// [`Resource::Create`]'s [`FromRequest`] impl. `ctx` comes alongside it
242    /// for the principal, the tenant, and anything else bound to the
243    /// request.
244    fn create(
245        &self,
246        input: R::Create,
247        ctx: &Context,
248    ) -> impl Future<Output = Result<R, Self::Error>> + Send;
249}
250
251/// One page of a collection, on its way back to the client.
252///
253/// Storage returns the rows plus whatever it knows about the rest of the
254/// collection; the handler turns that into `first`/`prev`/`next`/`last`
255/// links. What is absent is simply not linked — a cursor-paged listing that
256/// reports no total gets no `last` link rather than a wrong one.
257pub struct Listing<R> {
258    /// The rows on this page.
259    pub rows: Vec<R>,
260    /// How many rows the whole collection holds, if storage counted.
261    ///
262    /// Drives the `last` link and `meta.total`. Leave it `None` when
263    /// counting costs a second query you do not want to pay for.
264    pub total: Option<usize>,
265    /// Where the next page resumes, for cursor paging.
266    ///
267    /// `None` means this is the last page, so no `next` link is emitted.
268    /// Ignored under offset paging, which derives `next` from
269    /// [`has_more`](Listing::has_more) or, failing that, arithmetically.
270    pub cursor: Option<String>,
271    /// Whether the collection continues past this page, when storage knows.
272    ///
273    /// Offset paging only, and an override for the `next` link: without it a
274    /// full page is *assumed* to have a successor, so the last full page
275    /// links to an empty one. Storage that can answer exactly — by reading
276    /// one row past the page, say — sets this and the guess is not used.
277    ///
278    /// `None` means "not known", not "no more".
279    pub has_more: Option<bool>,
280}
281
282impl<R> Listing<R> {
283    /// A page of rows, with nothing else known about the collection.
284    pub fn new(rows: impl IntoIterator<Item = R>) -> Self {
285        Self {
286            rows: rows.into_iter().collect(),
287            total: None,
288            cursor: None,
289            has_more: None,
290        }
291    }
292
293    /// How many rows the collection holds in total.
294    #[must_use]
295    pub fn total(mut self, total: usize) -> Self {
296        self.total = Some(total);
297        self
298    }
299
300    /// Whether the collection continues past this page.
301    ///
302    /// Set it when storage knows exactly, and the `next` link stops being a
303    /// guess — see [`has_more`](Listing::has_more).
304    #[must_use]
305    pub fn has_more(mut self, has_more: bool) -> Self {
306        self.has_more = Some(has_more);
307        self
308    }
309
310    /// The cursor the next page resumes from.
311    ///
312    /// Set it only when there *is* a next page: it is what emits the `next`
313    /// link, so a cursor on the final page walks the client into an empty
314    /// one.
315    #[must_use]
316    pub fn cursor(mut self, cursor: impl Into<String>) -> Self {
317        self.cursor = Some(cursor.into());
318        self
319    }
320}
321
322/// `GET /resource` — fetch a page of the collection.
323///
324/// Implement it only if you route [`LIST`](crate::api!).
325///
326/// ```ignore
327/// impl List<Todo> for App {
328///     async fn list(&self, query: &Query, ctx: &Context) -> Result<Listing<Todo>, Self::Error> {
329///         match query.page() {
330///             Page::Offset { offset, limit } => { /* … */ }
331///             // Storage that pages one way refuses the other rather than
332///             // pretending; `query.sort()` is likewise yours to apply.
333///             Page::Cursor { .. } => { /* … */ }
334///         }
335///     }
336/// }
337/// ```
338pub trait List<R: Resource<Self>>: Storage<R> {
339    /// Fetch one page.
340    ///
341    /// The [`Query`] carries the paging the client asked for, already parsed
342    /// and bounds-checked, and its sort keys. An empty collection is an empty
343    /// [`Listing`], not a `404`.
344    fn list(
345        &self,
346        query: &Query,
347        ctx: &Context,
348    ) -> impl Future<Output = Result<Listing<R>, Self::Error>> + Send;
349}
350
351/// `GET /resource/{id}` — fetch one row.
352///
353/// Implement it only if you route [`READ`](crate::api!).
354pub trait Read<R: Resource<Self>>: Storage<R> {
355    /// Fetch one row by id. `None` becomes a `404`.
356    fn get(&self, id: &str) -> impl Future<Output = Result<Option<R>, Self::Error>> + Send;
357}
358
359/// `PATCH /resource/{id}` — replace a row.
360///
361/// Implement it only if you route [`UPDATE`](crate::api!).
362pub trait Update<R: Resource<Self>>: Storage<R> {
363    /// Replace the row at `id`.
364    ///
365    /// The parsed body arrives as an argument, as with [`Create::create`].
366    /// The `id` is the path's, which is authoritative over anything the body
367    /// carries.
368    fn update(
369        &self,
370        id: &str,
371        input: R::Update,
372        ctx: &Context,
373    ) -> impl Future<Output = Result<R, Self::Error>> + Send;
374}
375
376/// `GET /resource` with `Accept: application/jsonl` — rows, streamed.
377///
378/// Implement it only if you route [`STREAM`](crate::api!). It is the
379/// streaming counterpart of [`List`]: where `list` returns a page that is
380/// fully in memory before anything is sent, this yields rows as storage
381/// produces them, and each is serialized and written before the next is
382/// asked for.
383///
384/// That is the whole point. A `Vec<R>` of a million rows is a million rows in
385/// memory; a stream of them is one. The same query that would exhaust the
386/// heap as a `List` runs in constant space here.
387///
388/// ```ignore
389/// impl Stream<Todo> for App {
390///     fn stream(
391///         self,
392///         query: Query,
393///         ctx: Context,
394///     ) -> impl futures_core::Stream<Item = Result<Todo, Self::Error>> + Send + Unpin {
395///         // A real implementation hands back its driver's row stream —
396///         // `sqlx::query_as(…).fetch(&self.pool)` is already one.
397///         futures_util::stream::iter(self.rows().into_iter().map(Ok))
398///     }
399/// }
400/// ```
401///
402/// # Paging
403///
404/// The [`Query`] is passed for its sort keys and any limit the client set,
405/// but a stream is not paged: the client asked for the whole collection and
406/// gets it. Honour `page[limit]` as a cap if you want one — nothing in the
407/// crate imposes it, because the point of streaming is to exceed what a page
408/// can hold.
409///
410/// # Failing partway
411///
412/// Once the first row is written the status is `200`, so a later error
413/// cannot change it. Yield `Err` and the stream ends with an error line —
414/// see [`ERROR_LINE`](crate::jsonl::ERROR_LINE) for why a client must check
415/// the last line rather than the status.
416#[cfg(feature = "streaming")]
417#[cfg_attr(docsrs, doc(cfg(feature = "streaming")))]
418pub trait Stream<R: Resource<Self>>: Storage<R> {
419    /// Yield the collection's rows, in order.
420    ///
421    /// Takes `self` and the query **by value**: the returned stream outlives
422    /// this call — it is polled while the response body is written — so it
423    /// cannot borrow either. Your state is [`Clone`] already (a cheap handle
424    /// to a pool, in practice), which is what makes that free.
425    fn stream(
426        self,
427        query: Query,
428        ctx: Context,
429    ) -> impl futures_core::Stream<Item = Result<R, Self::Error>> + Send + Unpin + 'static;
430}
431
432/// `POST /resource` with `Content-Type: application/jsonl` — a batch, streamed.
433///
434/// Implement it only if you route [`INGEST`](crate::api!). It is the
435/// streaming counterpart of [`Create`]: where `create` reads one document and
436/// answers with one resource, this reads a line at a time and answers with
437/// one result line per input line.
438///
439/// There is a blanket impl over [`Create`], so a resource that already
440/// creates gets ingest for free — routing `INGEST` is usually the only change:
441///
442/// ```ignore
443/// ash_jsonapi::api! {
444///     operations: [ash_jsonapi::CREATE, ash_jsonapi::INGEST],
445///     resource: Todo, name: "todo", path: "/todos", state: App,
446/// }
447/// ```
448///
449/// Override it only when a batch write differs from a single one — to take a
450/// connection once for the run, say, rather than per row.
451///
452/// # Partial success is the model
453///
454/// A line that fails does not stop the batch: it becomes an error line
455/// carrying its line number, and the next line is attempted. That is the
456/// whole difference from a transactional bulk endpoint, and it is deliberate
457/// — an export of a million rows that is refused in full because row 999,999
458/// was malformed is not a useful endpoint.
459///
460/// Nothing is rolled back, so a client reconciles from the result lines
461/// rather than assuming all-or-nothing. See
462/// [`LINE_MEMBER`](crate::jsonl::LINE_MEMBER).
463#[cfg(feature = "streaming")]
464#[cfg_attr(docsrs, doc(cfg(feature = "streaming")))]
465pub trait Ingest<R: Resource<Self>>: Storage<R> {
466    /// Persist one row of the batch.
467    ///
468    /// Called once per non-blank input line, in order, each awaited before
469    /// the next line is read — so a slow store applies backpressure to the
470    /// upload rather than buffering it.
471    fn create_one(
472        &self,
473        input: R::Create,
474        ctx: &Context,
475    ) -> impl Future<Output = Result<R, Self::Error>> + Send;
476}
477
478#[cfg(feature = "streaming")]
479impl<S, R> Ingest<R> for S
480where
481    S: Create<R>,
482    R: Resource<S>,
483{
484    /// A batch row is an ordinary create unless storage says otherwise.
485    async fn create_one(&self, input: R::Create, ctx: &Context) -> Result<R, Self::Error> {
486        self.create(input, ctx).await
487    }
488}
489
490/// `GET /resource/{id}/content` — the resource's bytes.
491///
492/// Implement it only if you route [`CONTENT`](crate::api!).
493///
494/// The seam for a resource that *is* a file: an avatar, an attachment, an
495/// exported report. The row at `/docs/{id}` stays an ordinary JSON:API
496/// document describing the file — its name, size and media type — and the
497/// bytes live at `/docs/{id}/content`, because a JSON:API document has no
498/// place to put them that is not base64 in an attribute.
499///
500/// ```ignore
501/// impl Content<Doc> for App {
502///     async fn content(&self, id: &str) -> Result<Option<Download>, Self::Error> {
503///         let Some(doc) = self.fetch(id) else { return Ok(None) };
504///         Ok(Some(
505///             Download::new(doc.bytes, doc.content_type).filename(doc.name),
506///         ))
507///     }
508/// }
509/// ```
510///
511/// `None` is a `404`, exactly as [`Read::get`] — a row whose bytes are
512/// missing is not found, not a server error.
513pub trait Content<R: Resource<Self>>: Storage<R> {
514    /// Fetch one resource's bytes.
515    ///
516    /// Returns a [`Download`](crate::response::Download), which carries the
517    /// media type and filename and sets the headers that keep a browser from
518    /// interpreting the bytes.
519    fn content(
520        &self,
521        id: &str,
522    ) -> impl Future<Output = Result<Option<crate::response::Download>, Self::Error>> + Send;
523}
524
525/// `DELETE /resource/{id}` — remove a row.
526///
527/// Implement it only if you route [`DELETE`](crate::api!).
528pub trait Delete<R: Resource<Self>>: Storage<R> {
529    /// Remove the row at `id`.
530    fn destroy(&self, id: &str) -> impl Future<Output = Result<(), Self::Error>> + Send;
531}
532
533/// The validator for one resource, or a logged `500`.
534///
535/// A resource whose validator is missing was never registered, which is a
536/// wiring bug rather than a bad request.
537pub fn validator<'a, S: Validators>(
538    state: &'a S,
539    resource: &str,
540    ctx: &Context,
541) -> Result<&'a DocumentValidator, Errors> {
542    state
543        .validator(resource)
544        .ok_or_else(|| logged(ctx, format_args!("resource `{resource}` is not registered")))
545}
546
547/// Run a `before` hook set, if the state carries any.
548///
549/// Returns the refusal as [`Errors`] so a handler can `?` it: a refused
550/// request never reaches storage, which is the point of `before`.
551pub fn before<S: Validators>(
552    state: &S,
553    event: &crate::hook::Event<'_>,
554    ctx: &Context,
555) -> Result<(), Errors> {
556    let Some(hooks) = state.hooks() else {
557        return Ok(());
558    };
559    hooks.before(event, ctx).map_err(Errors::from)
560}
561
562/// Run the `after` hooks against whatever the operation produced.
563///
564/// Takes and returns the result unchanged: an `after` hook observes, and
565/// threading the value through keeps that impossible to get wrong at a call
566/// site. The outcome's status is the one the client will actually see.
567pub fn after<S: Validators, T>(
568    state: &S,
569    event: &crate::hook::Event<'_>,
570    ctx: &Context,
571    result: Result<T, Errors>,
572) -> Result<T, Errors> {
573    let Some(hooks) = state.hooks() else {
574        return result;
575    };
576
577    let outcome = match &result {
578        // The success status is the operation's, not a guess: a create is a
579        // `201` with a Location header and a delete a `204` with no body.
580        Ok(_) => crate::hook::Outcome::Succeeded {
581            status: match event.operation {
582                crate::hook::Operation::Create => 201,
583                crate::hook::Operation::Delete => 204,
584                _ => 200,
585            },
586        },
587        Err(errors) => crate::hook::Outcome::Failed {
588            status: errors
589                .0
590                .iter()
591                .map(|error| error.status().as_u16())
592                .max()
593                .unwrap_or(500),
594        },
595    };
596
597    hooks.after(event, &outcome, ctx);
598    result
599}
600
601/// Refuse a `?sort=` naming a field this storage did not declare.
602///
603/// Runs before the operation, so an unsortable field never reaches storage
604/// and never has the chance to become an opaque `500`. Storage that declares
605/// no list is trusted to sort by anything, and this is a no-op.
606pub fn check_sort<S, R>(state: &S, query: &Query, ctx: &Context) -> Result<(), Errors>
607where
608    S: Storage<R>,
609{
610    let Some(sortable) = state.sortable() else {
611        return Ok(());
612    };
613
614    for key in query.sort() {
615        if !sortable.contains(&key.field()) {
616            return Err(
617                JsonApiError::in_request(crate::ErrorCode::InvalidParameter, ctx)
618                    .detail(format!(
619                        "cannot sort on `{}`; this collection sorts by {}",
620                        key.field(),
621                        sortable
622                            .iter()
623                            .map(|field| format!("`{field}`"))
624                            .collect::<Vec<_>>()
625                            .join(", ")
626                    ))
627                    .parameter("sort")
628                    .into(),
629            );
630        }
631    }
632
633    Ok(())
634}
635
636/// Drive a [`Stream`] into a JSONL body.
637///
638/// Each row is converted, serialized and yielded as it arrives — nothing
639/// accumulates, which is the whole reason this exists rather than collecting
640/// into a [`Listing`].
641///
642/// A row that fails, or that cannot be serialized, ends the stream with an
643/// error line rather than truncating it: the status is already `200`, so a
644/// client that sees a short stream and no error line would keep a partial
645/// export believing it complete.
646#[cfg(feature = "streaming")]
647pub fn stream_lines<S, R>(state: S, query: Query, ctx: Context) -> crate::response::Streamed
648where
649    S: Stream<R> + Clone + Send + Sync + Unpin + 'static,
650    R: Resource<S> + Send + 'static,
651{
652    use std::pin::Pin;
653    use std::task::{Context as TaskContext, Poll};
654
655    // A hand-written stream rather than a combinator chain: the rows borrow
656    // `state` and `query`, so both have to live inside the stream itself.
657    struct Lines<S, R, F> {
658        rows: F,
659        state: S,
660        ctx: Context,
661        done: bool,
662        _row: std::marker::PhantomData<fn() -> R>,
663    }
664
665    impl<S, R, F> futures_core::Stream for Lines<S, R, F>
666    where
667        // `Unpin` so the stream can be polled through a `&mut`: the state is
668        // only read here, never moved, and every real state satisfies it.
669        S: Stream<R> + Send + Sync + Unpin + 'static,
670        R: Resource<S> + Send + 'static,
671        F: futures_core::Stream<Item = Result<R, S::Error>> + Send + Unpin,
672    {
673        type Item = Result<Vec<u8>, std::convert::Infallible>;
674
675        fn poll_next(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Option<Self::Item>> {
676            let this = self.get_mut();
677            if this.done {
678                return Poll::Ready(None);
679            }
680
681            match Pin::new(&mut this.rows).poll_next(cx) {
682                Poll::Pending => Poll::Pending,
683                Poll::Ready(None) => {
684                    this.done = true;
685                    Poll::Ready(None)
686                }
687                Poll::Ready(Some(Ok(row))) => match row.to_resource(&this.state, &this.ctx) {
688                    Ok(resource) => {
689                        Poll::Ready(Some(Ok(crate::response::Streamed::line(&resource))))
690                    }
691                    Err(error) => {
692                        this.done = true;
693                        Poll::Ready(Some(Ok(crate::response::Streamed::error_line(
694                            &error.in_context(&this.ctx),
695                        ))))
696                    }
697                },
698                Poll::Ready(Some(Err(err))) => {
699                    this.done = true;
700                    // `classify` decides what the client may know, exactly as
701                    // it does for a non-streamed failure.
702                    let error = this
703                        .state
704                        .classify(&err, &this.ctx)
705                        .unwrap_or_else(|| JsonApiError::internal(&this.ctx));
706                    Poll::Ready(Some(Ok(crate::response::Streamed::error_line(&error))))
707                }
708            }
709        }
710    }
711
712    let rows = state.clone().stream(query, ctx.clone());
713
714    crate::response::Streamed::new(Lines::<S, R, _> {
715        rows,
716        state,
717        ctx,
718        done: false,
719        _row: std::marker::PhantomData,
720    })
721}
722
723/// Drive a JSONL request body into a JSONL response body.
724///
725/// One result line per input line, in order: `{"data":{…}}` for a row that
726/// landed, `{"errors":[…]}` carrying `meta.line` for one that did not. Each
727/// line is read, parsed, validated, written and dropped before the next is
728/// read, so a batch of any size costs a line of memory in each direction.
729///
730/// A failing line does not end the run — see [`Ingest`] for why partial
731/// success is the model here rather than a transaction.
732#[cfg(feature = "streaming")]
733pub fn ingest_lines<S, R>(
734    state: S,
735    lines: crate::extract::JsonlLines,
736    ctx: Context,
737) -> crate::response::Streamed
738where
739    S: Ingest<R> + Clone + Send + Sync + Unpin + 'static,
740    R: Resource<S> + Send + 'static,
741{
742    use std::pin::Pin;
743    use std::task::{Context as TaskContext, Poll};
744
745    /// What the driver is waiting on.
746    ///
747    /// A create is `async`, so the driver cannot simply read a line and
748    /// return — it has to hold the in-flight future across polls. That is
749    /// the whole reason this is a state machine rather than a `map` over the
750    /// line stream.
751    enum State<R> {
752        /// Reading the next line from the body.
753        Reading,
754        /// A create is in flight for the line being held.
755        ///
756        /// The error is already-shaped JSON:API errors rather than the
757        /// storage error: `Storage::Error` is only `Display + Send` with no
758        /// `'static`, so it cannot cross into a boxed future. Classifying
759        /// inside the future — where the state is owned — is what keeps a
760        /// `422` a `422` instead of collapsing every failure to a `500`.
761        Writing(
762            usize,
763            Pin<Box<dyn Future<Output = Result<R, Vec<JsonApiError>>> + Send>>,
764        ),
765    }
766
767    struct Ingesting<S, R> {
768        lines: crate::extract::JsonlLines,
769        state: S,
770        ctx: Context,
771        phase: State<R>,
772        done: bool,
773    }
774
775    impl<S, R> futures_core::Stream for Ingesting<S, R>
776    where
777        S: Ingest<R> + Clone + Send + Sync + Unpin + 'static,
778        R: Resource<S> + Send + 'static,
779    {
780        type Item = Result<Vec<u8>, std::convert::Infallible>;
781
782        fn poll_next(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Option<Self::Item>> {
783            let this = self.get_mut();
784
785            loop {
786                if this.done {
787                    return Poll::Ready(None);
788                }
789
790                match &mut this.phase {
791                    State::Writing(number, writing) => {
792                        let number = *number;
793                        let finished = std::task::ready!(writing.as_mut().poll(cx));
794                        this.phase = State::Reading;
795
796                        let line = match finished {
797                            Ok(row) => match row.to_resource(&this.state, &this.ctx) {
798                                Ok(resource) => crate::response::Streamed::result_line(&resource),
799                                Err(error) => crate::response::Streamed::error_line_at(
800                                    &error.in_context(&this.ctx),
801                                    number,
802                                ),
803                            },
804                            // The line did not land. The errors arrive
805                            // already shaped — a validation failure keeps its
806                            // pointer and its 422, a storage failure has been
807                            // through `classify` — so nothing is re-decided
808                            // here.
809                            Err(errors) => {
810                                let error = errors
811                                    .first()
812                                    .cloned()
813                                    .unwrap_or_else(|| JsonApiError::internal(&this.ctx));
814                                crate::response::Streamed::error_line_at(&error, number)
815                            }
816                        };
817
818                        return Poll::Ready(Some(Ok(line)));
819                    }
820
821                    State::Reading => {
822                        let next = std::task::ready!(Pin::new(&mut this.lines).poll_next(cx));
823
824                        let (number, line) = match next {
825                            Some(item) => item,
826                            None => {
827                                this.done = true;
828                                return Poll::Ready(None);
829                            }
830                        };
831
832                        // A line that could not be read at all — over the
833                        // cap, or a truncated body. `JsonlLines` has already
834                        // ended itself, so this is the last line.
835                        let bytes = match line {
836                            Ok(bytes) => bytes,
837                            Err(error) => {
838                                this.done = true;
839                                return Poll::Ready(Some(Ok(
840                                    crate::response::Streamed::error_line_at(&error, number),
841                                )));
842                            }
843                        };
844
845                        // Each line is its own request document, so it is
846                        // parsed and validated exactly as a single create's
847                        // body would be — same pointers, same i18n keys.
848                        let request = match axum::http::Request::builder()
849                            .method(axum::http::Method::POST)
850                            .header(
851                                axum::http::header::CONTENT_TYPE,
852                                crate::document::MEDIA_TYPE,
853                            )
854                            .body(axum::body::Body::from(bytes))
855                        {
856                            Ok(request) => request,
857                            Err(_) => {
858                                return Poll::Ready(Some(Ok(
859                                    crate::response::Streamed::error_line_at(
860                                        &JsonApiError::internal(&this.ctx),
861                                        number,
862                                    ),
863                                )));
864                            }
865                        };
866
867                        let state = this.state.clone();
868                        let ctx = this.ctx.clone();
869
870                        this.phase = State::Writing(
871                            number,
872                            Box::pin(async move {
873                                type Input<S, R> = <R as Resource<S>>::Create;
874
875                                // Parsing and validation, exactly as a single
876                                // create does it. A failure here is the
877                                // client's and keeps its own status.
878                                let input = <Input<S, R> as FromRequest<S>>::from_request(
879                                    request, &state, &ctx,
880                                )
881                                .await
882                                .map_err(|errors| errors.0)?;
883
884                                state.create_one(input, &ctx).await.map_err(|err| {
885                                    // `classify` gets first refusal, as it
886                                    // does for a non-streamed create; only
887                                    // what it declines becomes a logged 500,
888                                    // since the storage message must not
889                                    // reach the client.
890                                    match state.classify(&err, &ctx) {
891                                        Some(error) => vec![error.in_context(&ctx)],
892                                        None => {
893                                            eprintln!(
894                                                "[{}] ingest failed: {err}",
895                                                ctx.correlation_id()
896                                            );
897                                            vec![JsonApiError::internal(&ctx)]
898                                        }
899                                    }
900                                })
901                            }),
902                        );
903                    }
904                }
905            }
906        }
907    }
908
909    crate::response::Streamed::new(Ingesting::<S, R> {
910        lines,
911        state,
912        ctx,
913        phase: State::<R>::Reading,
914        done: false,
915    })
916}
917
918/// A storage error on its way to the client.
919///
920/// [`Storage::classify`] gets first refusal: a failure it names becomes that
921/// error, correlation id attached. Anything else is logged with the id and
922/// answered with a bare `500`.
923pub fn failed<S, R>(state: &S, ctx: &Context, stage: &str, err: &S::Error) -> Errors
924where
925    S: Storage<R>,
926{
927    match state.classify(err, ctx) {
928        Some(error) => error.in_context(ctx).into(),
929        None => logged(ctx, format_args!("{stage} failed: {err}")),
930    }
931}
932
933/// Log a cause, return a `500` that carries only the correlation id.
934///
935/// The single place the two halves are tied together: whatever goes to the
936/// operator is prefixed with the id the client is handed.
937fn logged(ctx: &Context, cause: std::fmt::Arguments<'_>) -> Errors {
938    eprintln!("[{}] {cause}", ctx.correlation_id());
939    JsonApiError::internal(ctx).into()
940}
941
942/// `404` for a row that does not exist.
943pub fn missing(ctx: &Context, resource: &str, id: &str) -> Errors {
944    JsonApiError::in_request(crate::ErrorCode::NotFound, ctx)
945        .detail(format!("no {resource} with id `{id}`"))
946        .into()
947}
948
949/// Generate JSON:API routes for one resource.
950///
951/// Pick the operations you want; nothing else is exposed. Routing every
952/// action a resource declares just because it exists is how internal
953/// operations leak, so this is opt-in.
954///
955/// ```ignore
956/// ash_jsonapi::api! {
957///     operations: [ash_jsonapi::CREATE, ash_jsonapi::READ],
958///     resource: Todo,
959///     name: "todo",
960///     path: "/api/v1/todos",
961///     state: App,
962/// }
963/// ```
964///
965/// | Operation | Route |
966/// |---|---|
967/// | `LIST` | `GET /todos` |
968/// | `CREATE` | `POST /todos` |
969/// | `READ` | `GET /todos/{id}` |
970/// | `UPDATE` | `PATCH /todos/{id}` |
971/// | `DELETE` | `DELETE /todos/{id}` |
972/// | `CRUD` | all five |
973/// | `STREAM` | `GET /todos`, when `Accept: application/jsonl` |
974/// | `INGEST` | `POST /todos`, when `Content-Type: application/jsonl` |
975/// | `CONTENT` | `GET /todos/{id}/content` |
976///
977/// `STREAM` and `INGEST` share a verb with `LIST` and `CREATE` rather than
978/// adding a route: one URL with two representations, selected by the header.
979/// Routing either alongside its document counterpart is the usual case and
980/// changes nothing for an existing client. Routing `INGEST` *without*
981/// `CREATE` makes the collection batch-only, and a document body there is a
982/// `415`.
983///
984/// The names are macro keywords, not items, so they work bare (`READ`) or
985/// qualified (`ash_jsonapi::READ`) — write whichever reads better at the call
986/// site. An unrecognised name is a compile error naming the valid ones.
987///
988/// Anything not listed is not routed: a `[READ]` resource answers `405` to a
989/// `DELETE`, rather than reaching a handler that then refuses.
990///
991/// Fields:
992///
993/// - `operations` — which routes to expose. Required: an empty list is a
994///   resource with no HTTP surface, which is a mistake worth spelling out.
995/// - `resource` — your resource type.
996/// - `name` — its JSON:API `type`, for validator lookup.
997/// - `path` — where it is mounted.
998/// - `state` — your state type, implementing [`Validators`] and the traits for
999///   each operation you list.
1000///
1001/// Expands to `pub fn routes() -> axum::Router<App>` plus the handlers, in a
1002/// private module. Write your own route for anything the generated set does
1003/// not cover; this is a starting point, not a ceiling.
1004#[macro_export]
1005macro_rules! api {
1006    (
1007        operations: [$($op:tt)+],
1008        resource: $resource:ident,
1009        name: $name:literal,
1010        path: $base:literal,
1011        state: $state:ident
1012        $(,)?
1013    ) => {
1014        /// Routes generated by `api!`.
1015        pub fn routes() -> ::axum::Router<$state> {
1016            // One `MethodRouter` per path, each selected operation adding its
1017            // verb. Building them this way means READ + UPDATE + DELETE share
1018            // the `/{id}` entry rather than clobbering one another.
1019            #[allow(unused_mut)]
1020            let mut collection = ::axum::routing::MethodRouter::<$state>::new();
1021            #[allow(unused_mut)]
1022            let mut member = ::axum::routing::MethodRouter::<$state>::new();
1023            // `CONTENT` is the one operation that is not a verb on an
1024            // existing path: bytes live beside the document, not instead of
1025            // it, so `/{id}/content` is its own entry.
1026            #[allow(unused_mut)]
1027            let mut content = ::axum::routing::MethodRouter::<$state>::new();
1028
1029            $crate::__api_routes!(collection, member, content, __api, $($op)+);
1030
1031            // The collection's `GET`, registered exactly once — STREAM and
1032            // LIST both want it, and two `.get()` calls on one MethodRouter
1033            // panic. Which handler answers is decided during expansion, so
1034            // only the one that exists is ever named.
1035            $crate::__api_collection_get!(collection, __api, [$($op)+], [$($op)+]);
1036
1037            // The collection's `POST`, for the same reason: CREATE and INGEST
1038            // both want it, and only one handler may be registered.
1039            $crate::__api_collection_post!(collection, __api, [$($op)+], [$($op)+]);
1040
1041            let router = ::axum::Router::new()
1042                .route($base, collection)
1043                .route(::std::concat!($base, "/{id}"), member);
1044
1045            // Added only when CONTENT was routed: an empty MethodRouter
1046            // answers 405 on a path that should not exist at all.
1047            if $crate::__api_has_content!($($op)+) {
1048                router.route(::std::concat!($base, "/{id}/content"), content)
1049            } else {
1050                router
1051            }
1052        }
1053
1054        #[doc(hidden)]
1055        mod __api {
1056            use super::*;
1057
1058            $crate::__api_handlers!($resource, $name, $base, $state, $($op)+);
1059
1060            // The `POST` dispatcher, when INGEST was routed. Emitted here
1061            // rather than from `__api_handlers!` because which fallback it
1062            // needs depends on the whole operation list, and that macro sees
1063            // one operation at a time.
1064            $crate::__api_maybe_ingest_dispatch!(
1065                $resource, $name, $base, $state, [$($op)+], [$($op)+]
1066            );
1067
1068            use $crate::context::Context;
1069            #[allow(unused_imports)]
1070            use $crate::crud::{
1071                Content as _, Create as _, Delete as _, Read as _, Resource as _, Update as _,
1072                failed, missing,
1073            };
1074            use $crate::extract::FromRequest;
1075            use $crate::response::{Created, Errors, Fetched, NoContent};
1076
1077
1078
1079
1080        }
1081
1082    };
1083}
1084
1085/// Walks the operation list, tolerating `READ` and `ash_jsonapi::READ` alike.
1086///
1087/// A `tt` list rather than `path` fragments: a path cannot be matched against
1088/// literal names, and the leading segments are noise here — only the final
1089/// name selects a route.
1090#[doc(hidden)]
1091#[macro_export]
1092macro_rules! __api_routes {
1093    // Done.
1094    ($collection:ident, $member:ident, $content:ident, $m:ident $(,)?) => {};
1095
1096    // Skip a qualifying prefix: `ash_jsonapi :: READ` → `READ`.
1097    ($collection:ident, $member:ident, $content:ident, $m:ident, $prefix:ident :: $($rest:tt)+) => {
1098        $crate::__api_routes!($collection, $member, $content, $m, $($rest)+);
1099    };
1100
1101    // One operation, then whatever follows.
1102    ($collection:ident, $member:ident, $content:ident, $m:ident, $op:ident $(, $($rest:tt)*)?) => {
1103        $crate::__api_route!($collection, $member, $content, $m, $op);
1104        $($crate::__api_routes!($collection, $member, $content, $m, $($rest)*);)?
1105    };
1106}
1107
1108/// Whether the operation list names `CONTENT`, so `routes()` knows whether to
1109/// mount `/{id}/content` at all.
1110#[doc(hidden)]
1111#[macro_export]
1112macro_rules! __api_has_content {
1113    ($($op:tt)*) => { $crate::__api_has!(CONTENT, $($op)*) };
1114}
1115
1116/// Register the collection's `GET`, choosing the handler at expansion time.
1117///
1118/// Walks the operation list twice: the first copy looks for `STREAM` (which
1119/// wins, since its handler falls back to the document), the second for
1120/// `LIST`/`CRUD`. Naming a handler that was not generated would not compile,
1121/// so the choice cannot be a runtime `if`.
1122#[doc(hidden)]
1123#[macro_export]
1124macro_rules! __api_collection_get {
1125    // STREAM found: the branching handler answers.
1126    ($collection:ident, $m:ident, [STREAM $(, $($a:tt)*)?], [$($b:tt)*]) => {
1127        $collection = $collection.get($m::list_or_stream);
1128    };
1129    ($collection:ident, $m:ident, [$p:ident :: $($a:tt)+], [$($b:tt)*]) => {
1130        $crate::__api_collection_get!($collection, $m, [$($a)+], [$($b)*]);
1131    };
1132    ($collection:ident, $m:ident, [$op:ident $(, $($a:tt)*)?], [$($b:tt)*]) => {
1133        $crate::__api_collection_get!($collection, $m, [$($($a)*)?], [$($b)*]);
1134    };
1135    // No STREAM anywhere: fall through to the LIST/CRUD pass.
1136    ($collection:ident, $m:ident, [], [$($b:tt)*]) => {
1137        $crate::__api_plain_list_get!($collection, $m, $($b)*);
1138    };
1139}
1140
1141/// The LIST/CRUD half of [`__api_collection_get`].
1142#[doc(hidden)]
1143#[macro_export]
1144macro_rules! __api_plain_list_get {
1145    ($collection:ident, $m:ident, LIST $(, $($rest:tt)*)?) => {
1146        $collection = $collection.get($m::list);
1147    };
1148    ($collection:ident, $m:ident, CRUD $(, $($rest:tt)*)?) => {
1149        $collection = $collection.get($m::list);
1150    };
1151    ($collection:ident, $m:ident, $p:ident :: $($rest:tt)+) => {
1152        $crate::__api_plain_list_get!($collection, $m, $($rest)+);
1153    };
1154    ($collection:ident, $m:ident, $op:ident $(, $($rest:tt)*)?) => {
1155        $crate::__api_plain_list_get!($collection, $m, $($($rest)*)?);
1156    };
1157    // Neither LIST nor CRUD: the collection has no GET.
1158    ($collection:ident, $m:ident,) => {};
1159}
1160
1161/// Whether the operation list names `$what`, ignoring any path prefix.
1162#[doc(hidden)]
1163#[macro_export]
1164macro_rules! __api_has {
1165    ($what:ident,) => { false };
1166    ($what:ident, $prefix:ident :: $($rest:tt)+) => { $crate::__api_has!($what, $($rest)+) };
1167    ($what:ident, $op:ident $(, $($rest:tt)*)?) => {
1168        ::std::stringify!($op) == ::std::stringify!($what)
1169            || $crate::__api_has!($what, $($($rest)*)?)
1170    };
1171}
1172
1173/// Attaches one operation's verb to the right `MethodRouter`.
1174#[doc(hidden)]
1175#[macro_export]
1176macro_rules! __api_route {
1177    // LIST's `GET` is registered by `routes()` itself, because STREAM
1178    // replaces the handler on the same verb and two `.get()` calls on one
1179    // MethodRouter panic at startup.
1180    ($collection:ident, $member:ident, $content:ident, $m:ident, LIST) => {};
1181    // CREATE's `POST` is registered by `routes()` itself, for the same reason
1182    // LIST's `GET` is: INGEST replaces the handler on the same verb, and two
1183    // `.post()` calls on one MethodRouter panic at startup.
1184    ($collection:ident, $member:ident, $content:ident, $m:ident, CREATE) => {};
1185    ($collection:ident, $member:ident, $content:ident, $m:ident, READ) => {
1186        $member = $member.get($m::show);
1187    };
1188    ($collection:ident, $member:ident, $content:ident, $m:ident, UPDATE) => {
1189        $member = $member.patch($m::update);
1190    };
1191    ($collection:ident, $member:ident, $content:ident, $m:ident, DELETE) => {
1192        $member = $member.delete($m::destroy);
1193    };
1194    ($collection:ident, $member:ident, $content:ident, $m:ident, CONTENT) => {
1195        $content = $content.get($m::content);
1196    };
1197    // Likewise registered by `routes()`: STREAM selects which handler
1198    // answers the collection's `GET`, it does not add a second one.
1199    ($collection:ident, $member:ident, $content:ident, $m:ident, STREAM) => {};
1200    // Likewise registered by `routes()`: INGEST selects which handler answers
1201    // the collection's `POST`, it does not add a second one.
1202    ($collection:ident, $member:ident, $content:ident, $m:ident, INGEST) => {};
1203    ($collection:ident, $member:ident, $content:ident, $m:ident, CRUD) => {
1204        // The `POST` is left to `routes()` along with CREATE's, so that
1205        // `CRUD, INGEST` resolves to one handler rather than panicking.
1206        $member = $member.get($m::show).patch($m::update).delete($m::destroy);
1207    };
1208    ($collection:ident, $member:ident, $content:ident, $m:ident, $other:ident) => {
1209        ::std::compile_error!(::std::concat!(
1210            "unknown operation `",
1211            ::std::stringify!($other),
1212            "`; expected LIST, CREATE, READ, UPDATE, DELETE, CONTENT, STREAM, INGEST or CRUD"
1213        ));
1214    };
1215}
1216
1217/// Register the collection's `POST`, choosing the handler at expansion time.
1218///
1219/// The `POST` counterpart of [`__api_collection_get`], and it exists for the
1220/// same reason: `CREATE` and `INGEST` both want the verb, and two `.post()`
1221/// calls on one `MethodRouter` panic at startup. `INGEST` wins where both are
1222/// named, because its handler falls back to the single create for any body
1223/// that is not JSONL.
1224#[doc(hidden)]
1225#[macro_export]
1226macro_rules! __api_collection_post {
1227    // INGEST found: the branching handler answers.
1228    ($collection:ident, $m:ident, [INGEST $(, $($a:tt)*)?], [$($b:tt)*]) => {
1229        $collection = $collection.post($m::create_or_ingest);
1230    };
1231    ($collection:ident, $m:ident, [$p:ident :: $($a:tt)+], [$($b:tt)*]) => {
1232        $crate::__api_collection_post!($collection, $m, [$($a)+], [$($b)*]);
1233    };
1234    ($collection:ident, $m:ident, [$op:ident $(, $($a:tt)*)?], [$($b:tt)*]) => {
1235        $crate::__api_collection_post!($collection, $m, [$($($a)*)?], [$($b)*]);
1236    };
1237    // No INGEST anywhere: fall through to the CREATE/CRUD pass.
1238    ($collection:ident, $m:ident, [], [$($b:tt)*]) => {
1239        $crate::__api_plain_create_post!($collection, $m, $($b)*);
1240    };
1241}
1242
1243/// Emit the `POST` dispatcher only when `INGEST` was actually routed.
1244///
1245/// The guard in front of [`__api_ingest_dispatch`]: a resource that routes no
1246/// batch must not get a `create_or_ingest`, since nothing would name it and
1247/// the `ingest` handler it calls was never generated.
1248#[doc(hidden)]
1249#[macro_export]
1250macro_rules! __api_maybe_ingest_dispatch {
1251    // INGEST found: emit the dispatcher, choosing its fallback from the
1252    // second (untouched) copy of the operation list.
1253    ($r:ident, $name:literal, $base:literal, $state:ident, [INGEST $(, $($a:tt)*)?], [$($b:tt)*]) => {
1254        $crate::__api_ingest_dispatch!($r, $name, $base, $state, [$($b)*], [$($b)*]);
1255    };
1256    ($r:ident, $name:literal, $base:literal, $state:ident, [$p:ident :: $($a:tt)+], [$($b:tt)*]) => {
1257        $crate::__api_maybe_ingest_dispatch!($r, $name, $base, $state, [$($a)+], [$($b)*]);
1258    };
1259    ($r:ident, $name:literal, $base:literal, $state:ident, [$op:ident $(, $($a:tt)*)?], [$($b:tt)*]) => {
1260        $crate::__api_maybe_ingest_dispatch!($r, $name, $base, $state, [$($($a)*)?], [$($b)*]);
1261    };
1262    // No INGEST: nothing to emit.
1263    ($r:ident, $name:literal, $base:literal, $state:ident, [], [$($b:tt)*]) => {};
1264}
1265
1266/// Emit the `POST` dispatcher, when `INGEST` was routed.
1267///
1268/// Two variants, chosen at expansion time, because the fallback has to name
1269/// a handler that exists: with `CREATE` (or `CRUD`) also routed a non-JSONL
1270/// body is an ordinary single create, and with `INGEST` alone there is no
1271/// `create` to call, so anything but JSONL is a `415`.
1272///
1273/// Walks the list twice like [`__api_collection_get`]: the first copy looks
1274/// for `CREATE`/`CRUD`, the second is kept whole so the search can restart.
1275#[doc(hidden)]
1276#[macro_export]
1277macro_rules! __api_ingest_dispatch {
1278    // A single create exists: fall back to it.
1279    ($r:ident, $name:literal, $base:literal, $state:ident, [CREATE $(, $($a:tt)*)?], [$($b:tt)*]) => {
1280        $crate::__api_dispatch_with_create!($r, $name, $base, $state);
1281    };
1282    ($r:ident, $name:literal, $base:literal, $state:ident, [CRUD $(, $($a:tt)*)?], [$($b:tt)*]) => {
1283        $crate::__api_dispatch_with_create!($r, $name, $base, $state);
1284    };
1285    ($r:ident, $name:literal, $base:literal, $state:ident, [$p:ident :: $($a:tt)+], [$($b:tt)*]) => {
1286        $crate::__api_ingest_dispatch!($r, $name, $base, $state, [$($a)+], [$($b)*]);
1287    };
1288    ($r:ident, $name:literal, $base:literal, $state:ident, [$op:ident $(, $($a:tt)*)?], [$($b:tt)*]) => {
1289        $crate::__api_ingest_dispatch!($r, $name, $base, $state, [$($($a)*)?], [$($b)*]);
1290    };
1291    // INGEST stands alone: the collection takes batches and nothing else.
1292    ($r:ident, $name:literal, $base:literal, $state:ident, [], [$($b:tt)*]) => {
1293        $crate::__api_dispatch_ingest_only!($r, $name, $base, $state);
1294    };
1295}
1296
1297/// The `POST` dispatcher where a single create is also routed.
1298#[doc(hidden)]
1299#[macro_export]
1300macro_rules! __api_dispatch_with_create {
1301    ($r:ident, $name:literal, $base:literal, $state:ident) => {
1302        /// `POST` — one document, or a JSONL batch.
1303        ///
1304        /// Selected by `Content-Type`: `application/jsonl` (or
1305        /// `application/x-ndjson`) is a batch, anything else is the ordinary
1306        /// single create. One URL, two request shapes — so routing `INGEST`
1307        /// cannot change what an existing client sends.
1308        pub async fn create_or_ingest(
1309            state: ::axum::extract::State<$state>,
1310            ctx: ::axum::Extension<Context>,
1311            request: ::axum::extract::Request,
1312        ) -> ::axum::response::Response {
1313            use ::axum::response::IntoResponse as _;
1314
1315            let content_type = request
1316                .headers()
1317                .get(::axum::http::header::CONTENT_TYPE)
1318                .and_then(|value| value.to_str().ok())
1319                .map(::std::string::ToString::to_string);
1320
1321            if $crate::jsonl::is_jsonl_request(content_type.as_deref()) {
1322                return ingest(state, ctx, request).await;
1323            }
1324
1325            create(state, ctx, request).await.into_response()
1326        }
1327    };
1328}
1329
1330/// The `POST` dispatcher where `INGEST` is the only create routed.
1331#[doc(hidden)]
1332#[macro_export]
1333macro_rules! __api_dispatch_ingest_only {
1334    ($r:ident, $name:literal, $base:literal, $state:ident) => {
1335        /// `POST` — a JSONL batch, which is the only body this collection takes.
1336        pub async fn create_or_ingest(
1337            state: ::axum::extract::State<$state>,
1338            ::axum::Extension(ctx): ::axum::Extension<Context>,
1339            request: ::axum::extract::Request,
1340        ) -> ::axum::response::Response {
1341            use ::axum::response::IntoResponse as _;
1342
1343            let content_type = request
1344                .headers()
1345                .get(::axum::http::header::CONTENT_TYPE)
1346                .and_then(|value| value.to_str().ok())
1347                .map(::std::string::ToString::to_string);
1348
1349            if !$crate::jsonl::is_jsonl_request(content_type.as_deref()) {
1350                // This collection routes no single create, so a document
1351                // body is not "invalid" — it is the wrong media type.
1352                return $crate::response::Errors::from(
1353                    $crate::JsonApiError::in_request($crate::ErrorCode::UnsupportedMediaType, &ctx)
1354                        .detail(::std::concat!(
1355                            "this collection accepts batches only; send `",
1356                            "application/jsonl",
1357                            "`"
1358                        )),
1359                )
1360                .into_response();
1361            }
1362
1363            ingest(state, ::axum::Extension(ctx), request).await
1364        }
1365    };
1366}
1367
1368/// The CREATE/CRUD half of [`__api_collection_post`].
1369#[doc(hidden)]
1370#[macro_export]
1371macro_rules! __api_plain_create_post {
1372    ($collection:ident, $m:ident, CREATE $(, $($rest:tt)*)?) => {
1373        $collection = $collection.post($m::create);
1374    };
1375    ($collection:ident, $m:ident, CRUD $(, $($rest:tt)*)?) => {
1376        $collection = $collection.post($m::create);
1377    };
1378    ($collection:ident, $m:ident, $p:ident :: $($rest:tt)+) => {
1379        $crate::__api_plain_create_post!($collection, $m, $($rest)+);
1380    };
1381    ($collection:ident, $m:ident, $op:ident $(, $($rest:tt)*)?) => {
1382        $crate::__api_plain_create_post!($collection, $m, $($($rest)*)?);
1383    };
1384    // Neither CREATE nor CRUD: the collection has no POST.
1385    ($collection:ident, $m:ident,) => {};
1386}
1387
1388/// Emits a handler for each selected operation, and nothing for the rest.
1389///
1390/// This is what makes the operation traits opt-in: an unrouted verb generates
1391/// no handler, so its trait is never required.
1392#[doc(hidden)]
1393#[macro_export]
1394macro_rules! __api_handlers {
1395    ($r:ident, $name:literal, $base:literal, $state:ident $(,)?) => {};
1396
1397    ($r:ident, $name:literal, $base:literal, $state:ident, $prefix:ident :: $($rest:tt)+) => {
1398        $crate::__api_handlers!($r, $name, $base, $state, $($rest)+);
1399    };
1400
1401    ($r:ident, $name:literal, $base:literal, $state:ident, CRUD $(, $($rest:tt)*)?) => {
1402        $crate::__api_handlers!($r, $name, $base, $state, LIST, CREATE, READ, UPDATE, DELETE);
1403        $($crate::__api_handlers!($r, $name, $base, $state, $($rest)*);)?
1404    };
1405
1406    ($r:ident, $name:literal, $base:literal, $state:ident, LIST $(, $($rest:tt)*)?) => {
1407        /// `GET` — one page of the collection.
1408        pub async fn list(
1409            ::axum::extract::State(state): ::axum::extract::State<$state>,
1410            ::axum::Extension(ctx): ::axum::Extension<Context>,
1411            uri: ::axum::http::Uri,
1412        ) -> ::std::result::Result<Fetched, Errors> {
1413            let query = $crate::query::Query::parse(uri.query().unwrap_or_default(), &ctx)?;
1414
1415            $crate::crud::check_sort::<$state, $r>(&state, &query, &ctx)?;
1416
1417            let event = $crate::hook::Event {
1418                operation: $crate::hook::Operation::List,
1419                resource: $name,
1420                id: ::std::option::Option::None,
1421            };
1422            $crate::crud::before(&state, &event, &ctx)?;
1423
1424            let listing = match $crate::crud::List::<$r>::list(&state, &query, &ctx).await {
1425                ::std::result::Result::Ok(listing) => listing,
1426                ::std::result::Result::Err(err) => {
1427                    let errors = failed::<$state, $r>(&state, &ctx, "list", &err);
1428                    return $crate::crud::after(&state, &event, &ctx, ::std::result::Result::Err(errors));
1429                }
1430            };
1431
1432            let mut resources = ::std::vec::Vec::with_capacity(listing.rows.len());
1433            for row in &listing.rows {
1434                resources.push(row.to_resource(&state, &ctx)?);
1435            }
1436
1437            let links = $crate::query::Paginator::new($base, &query).links(
1438                listing.rows.len(),
1439                listing.total,
1440                listing.cursor.as_deref(),
1441                listing.has_more,
1442            );
1443
1444            $crate::crud::after(
1445                &state,
1446                &event,
1447                &ctx,
1448                ::std::result::Result::Ok(
1449                    Fetched::page(resources, links, listing.total).in_context(&ctx),
1450                ),
1451            )
1452        }
1453        $($crate::__api_handlers!($r, $name, $base, $state, $($rest)*);)?
1454    };
1455
1456    ($r:ident, $name:literal, $base:literal, $state:ident, CREATE $(, $($rest:tt)*)?) => {
1457        /// `POST` — create.
1458        pub async fn create(
1459            ::axum::extract::State(state): ::axum::extract::State<$state>,
1460            ::axum::Extension(ctx): ::axum::Extension<Context>,
1461            request: ::axum::extract::Request,
1462        ) -> ::std::result::Result<Created, Errors> {
1463            // Your FromRequest reads the body; what it produces is handed
1464            // straight to storage. It is an argument rather than a context
1465            // extension because a create always has a body — routing it
1466            // through the context would make an infallible step fallible.
1467            let event = $crate::hook::Event {
1468                operation: $crate::hook::Operation::Create,
1469                resource: $name,
1470                id: ::std::option::Option::None,
1471            };
1472            $crate::crud::before(&state, &event, &ctx)?;
1473
1474            type Input = <$r as $crate::crud::Resource<$state>>::Create;
1475            let input =
1476                match <Input as FromRequest<$state>>::from_request(request, &state, &ctx).await {
1477                    ::std::result::Result::Ok(input) => input,
1478                    ::std::result::Result::Err(errors) => {
1479                        return $crate::crud::after(
1480                            &state, &event, &ctx, ::std::result::Result::Err(errors),
1481                        );
1482                    }
1483                };
1484
1485            let created = match $crate::crud::Create::<$r>::create(&state, input, &ctx).await {
1486                ::std::result::Result::Ok(created) => created,
1487                ::std::result::Result::Err(err) => {
1488                    let errors = failed::<$state, $r>(&state, &ctx, "create", &err);
1489                    return $crate::crud::after(&state, &event, &ctx, ::std::result::Result::Err(errors));
1490                }
1491            };
1492
1493            $crate::crud::after(
1494                &state,
1495                &event,
1496                &ctx,
1497                created.to_resource(&state, &ctx).map(Created).map_err(Errors::from),
1498            )
1499        }
1500        $($crate::__api_handlers!($r, $name, $base, $state, $($rest)*);)?
1501    };
1502
1503    ($r:ident, $name:literal, $base:literal, $state:ident, READ $(, $($rest:tt)*)?) => {
1504        /// `GET /{id}` — fetch one.
1505        pub async fn show(
1506            ::axum::extract::State(state): ::axum::extract::State<$state>,
1507            ::axum::Extension(ctx): ::axum::Extension<Context>,
1508            ::axum::extract::Path(id): ::axum::extract::Path<::std::string::String>,
1509        ) -> ::std::result::Result<Fetched, Errors> {
1510            let event = $crate::hook::Event {
1511                operation: $crate::hook::Operation::Read,
1512                resource: $name,
1513                id: ::std::option::Option::Some(&id),
1514            };
1515            $crate::crud::before(&state, &event, &ctx)?;
1516
1517            let found = match $crate::crud::Read::<$r>::get(&state, &id).await {
1518                ::std::result::Result::Ok(found) => found,
1519                ::std::result::Result::Err(err) => {
1520                    let errors = failed::<$state, $r>(&state, &ctx, "get", &err);
1521                    return $crate::crud::after(&state, &event, &ctx, ::std::result::Result::Err(errors));
1522                }
1523            };
1524
1525            let outcome = found
1526                .ok_or_else(|| missing(&ctx, $name, &id))
1527                .and_then(|row| {
1528                    row.to_resource(&state, &ctx)
1529                        .map(|resource| Fetched::one(resource).in_context(&ctx))
1530                        .map_err(Errors::from)
1531                });
1532
1533            $crate::crud::after(&state, &event, &ctx, outcome)
1534        }
1535        $($crate::__api_handlers!($r, $name, $base, $state, $($rest)*);)?
1536    };
1537
1538    ($r:ident, $name:literal, $base:literal, $state:ident, UPDATE $(, $($rest:tt)*)?) => {
1539        /// `PATCH /{id}` — update.
1540        pub async fn update(
1541            ::axum::extract::State(state): ::axum::extract::State<$state>,
1542            ::axum::Extension(ctx): ::axum::Extension<Context>,
1543            ::axum::extract::Path(id): ::axum::extract::Path<::std::string::String>,
1544            request: ::axum::extract::Request,
1545        ) -> ::std::result::Result<Fetched, Errors> {
1546            let event = $crate::hook::Event {
1547                operation: $crate::hook::Operation::Update,
1548                resource: $name,
1549                id: ::std::option::Option::Some(&id),
1550            };
1551            $crate::crud::before(&state, &event, &ctx)?;
1552
1553            type Input = <$r as $crate::crud::Resource<$state>>::Update;
1554            let input =
1555                match <Input as FromRequest<$state>>::from_request(request, &state, &ctx).await {
1556                    ::std::result::Result::Ok(input) => input,
1557                    ::std::result::Result::Err(errors) => {
1558                        return $crate::crud::after(
1559                            &state, &event, &ctx, ::std::result::Result::Err(errors),
1560                        );
1561                    }
1562                };
1563
1564            // The path's id wins over anything the body says.
1565            let updated = match $crate::crud::Update::<$r>::update(&state, &id, input, &ctx).await {
1566                ::std::result::Result::Ok(updated) => updated,
1567                ::std::result::Result::Err(err) => {
1568                    let errors = failed::<$state, $r>(&state, &ctx, "update", &err);
1569                    return $crate::crud::after(&state, &event, &ctx, ::std::result::Result::Err(errors));
1570                }
1571            };
1572
1573            $crate::crud::after(
1574                &state,
1575                &event,
1576                &ctx,
1577                updated
1578                    .to_resource(&state, &ctx)
1579                    .map(|resource| Fetched::one(resource).in_context(&ctx))
1580                    .map_err(Errors::from),
1581            )
1582        }
1583        $($crate::__api_handlers!($r, $name, $base, $state, $($rest)*);)?
1584    };
1585
1586    ($r:ident, $name:literal, $base:literal, $state:ident, STREAM $(, $($rest:tt)*)?) => {
1587        /// `GET` with `Accept: application/jsonl` — the collection, streamed.
1588        ///
1589        /// Routed in place of `list` when STREAM is named, and falls back to
1590        /// it for any other `Accept`: one URL, two representations.
1591        pub async fn list_or_stream(
1592            ::axum::extract::State(state): ::axum::extract::State<$state>,
1593            ::axum::Extension(ctx): ::axum::Extension<Context>,
1594            headers: ::axum::http::HeaderMap,
1595            uri: ::axum::http::Uri,
1596        ) -> ::axum::response::Response {
1597            use ::axum::response::IntoResponse as _;
1598
1599            let accept = headers
1600                .get(::axum::http::header::ACCEPT)
1601                .and_then(|value| value.to_str().ok());
1602
1603            if !$crate::jsonl::wants_jsonl(accept) {
1604                // Not asked for: the document is what every other client gets.
1605                return list(
1606                    ::axum::extract::State(state),
1607                    ::axum::Extension(ctx),
1608                    uri,
1609                )
1610                .await
1611                .into_response();
1612            }
1613
1614            let query = match $crate::query::Query::parse(uri.query().unwrap_or_default(), &ctx) {
1615                ::std::result::Result::Ok(query) => query,
1616                ::std::result::Result::Err(err) => {
1617                    return $crate::response::Errors::from(err).into_response();
1618                }
1619            };
1620
1621            if let ::std::result::Result::Err(errors) =
1622                $crate::crud::check_sort::<$state, $r>(&state, &query, &ctx)
1623            {
1624                return errors.into_response();
1625            }
1626
1627            let event = $crate::hook::Event {
1628                operation: $crate::hook::Operation::List,
1629                resource: $name,
1630                id: ::std::option::Option::None,
1631            };
1632            if let ::std::result::Result::Err(errors) =
1633                $crate::crud::before(&state, &event, &ctx)
1634            {
1635                return errors.into_response();
1636            }
1637
1638            // The status is committed with the first byte, so the `after`
1639            // hook records the outcome now: a row that fails later becomes an
1640            // error *line*, not a different status.
1641            let outcome = $crate::crud::after(
1642                &state,
1643                &event,
1644                &ctx,
1645                ::std::result::Result::Ok::<(), $crate::response::Errors>(()),
1646            );
1647            if let ::std::result::Result::Err(errors) = outcome {
1648                return errors.into_response();
1649            }
1650
1651            $crate::crud::stream_lines::<$state, $r>(state, query, ctx).into_response()
1652        }
1653        $($crate::__api_handlers!($r, $name, $base, $state, $($rest)*);)?
1654    };
1655
1656    ($r:ident, $name:literal, $base:literal, $state:ident, INGEST $(, $($rest:tt)*)?) => {
1657        /// `POST` with `Content-Type: application/jsonl` — a streamed batch.
1658        ///
1659        /// One result line per input line. The status is `200` and is
1660        /// committed with the first byte, so a client reads outcomes from the
1661        /// lines rather than from the status — a batch in which every row
1662        /// failed is still a `200` whose every line is an error.
1663        pub async fn ingest(
1664            ::axum::extract::State(state): ::axum::extract::State<$state>,
1665            ::axum::Extension(ctx): ::axum::Extension<Context>,
1666            request: ::axum::extract::Request,
1667        ) -> ::axum::response::Response {
1668            use ::axum::response::IntoResponse as _;
1669
1670            // Authorization is a batch-level decision: a denial must not
1671            // reach storage, and must not be re-asked per row.
1672            let event = $crate::hook::Event {
1673                operation: $crate::hook::Operation::Create,
1674                resource: $name,
1675                id: ::std::option::Option::None,
1676            };
1677            if let ::std::result::Result::Err(errors) =
1678                $crate::crud::before(&state, &event, &ctx)
1679            {
1680                return errors.into_response();
1681            }
1682
1683            // The status is committed with the first byte, so the outcome is
1684            // recorded now; each line's own fate is recorded by the driver.
1685            let outcome = $crate::crud::after(
1686                &state,
1687                &event,
1688                &ctx,
1689                ::std::result::Result::Ok::<(), $crate::response::Errors>(()),
1690            );
1691            if let ::std::result::Result::Err(errors) = outcome {
1692                return errors.into_response();
1693            }
1694
1695            let lines = $crate::extract::JsonlLines::new(request, &ctx);
1696            $crate::crud::ingest_lines::<$state, $r>(state, lines, ctx).into_response()
1697        }
1698        $($crate::__api_handlers!($r, $name, $base, $state, $($rest)*);)?
1699    };
1700
1701    ($r:ident, $name:literal, $base:literal, $state:ident, CONTENT $(, $($rest:tt)*)?) => {
1702        /// `GET /{id}/content` — the resource's bytes.
1703        pub async fn content(
1704            ::axum::extract::State(state): ::axum::extract::State<$state>,
1705            ::axum::Extension(ctx): ::axum::Extension<Context>,
1706            ::axum::extract::Path(id): ::axum::extract::Path<::std::string::String>,
1707        ) -> ::std::result::Result<$crate::response::Download, Errors> {
1708            // Recorded as a read: it is one, and an audit trail that cannot
1709            // see who downloaded a file is missing the interesting half.
1710            let event = $crate::hook::Event {
1711                operation: $crate::hook::Operation::Read,
1712                resource: $name,
1713                id: ::std::option::Option::Some(&id),
1714            };
1715            $crate::crud::before(&state, &event, &ctx)?;
1716
1717            let found = match $crate::crud::Content::<$r>::content(&state, &id).await {
1718                ::std::result::Result::Ok(found) => found,
1719                ::std::result::Result::Err(err) => {
1720                    let errors = failed::<$state, $r>(&state, &ctx, "content", &err);
1721                    return $crate::crud::after(&state, &event, &ctx, ::std::result::Result::Err(errors));
1722                }
1723            };
1724
1725            let outcome = found.ok_or_else(|| missing(&ctx, $name, &id));
1726            $crate::crud::after(&state, &event, &ctx, outcome)
1727        }
1728        $($crate::__api_handlers!($r, $name, $base, $state, $($rest)*);)?
1729    };
1730
1731    ($r:ident, $name:literal, $base:literal, $state:ident, DELETE $(, $($rest:tt)*)?) => {
1732        /// `DELETE /{id}` — destroy.
1733        pub async fn destroy(
1734            ::axum::extract::State(state): ::axum::extract::State<$state>,
1735            ::axum::Extension(ctx): ::axum::Extension<Context>,
1736            ::axum::extract::Path(id): ::axum::extract::Path<::std::string::String>,
1737        ) -> ::std::result::Result<NoContent, Errors> {
1738            let event = $crate::hook::Event {
1739                operation: $crate::hook::Operation::Delete,
1740                resource: $name,
1741                id: ::std::option::Option::Some(&id),
1742            };
1743            $crate::crud::before(&state, &event, &ctx)?;
1744
1745            let outcome = $crate::crud::Delete::<$r>::destroy(&state, &id)
1746                .await
1747                .map(|()| NoContent)
1748                .map_err(|err| failed::<$state, $r>(&state, &ctx, "destroy", &err));
1749
1750            $crate::crud::after(&state, &event, &ctx, outcome)
1751        }
1752        $($crate::__api_handlers!($r, $name, $base, $state, $($rest)*);)?
1753    };
1754}