Skip to main content

repe_core/
structs.rs

1use crate::constants::{BodyFormat, ErrorCode};
2
3/// Errors produced while handling struct-backed endpoints.
4///
5/// Non-exhaustive: match with a wildcard arm, or use [`StructError::code`] to
6/// map any error onto its protocol [`ErrorCode`].
7///
8/// There is no `Serialize` variant. structio's writers cannot fail — a
9/// [`structio::json::Write`] impl returns `()` — so encoding a response is
10/// infallible and the only failures left are about the request: a path that
11/// does not resolve, a body that should or should not be there, a body that
12/// does not parse, and a handler that reported its own failure.
13#[derive(Debug, thiserror::Error)]
14#[non_exhaustive]
15pub enum StructError {
16    #[error("invalid path `{path}`")]
17    InvalidPath { path: String },
18    #[error("unexpected additional path segments at `{path}`")]
19    InvalidSubpath { path: String },
20    #[error("body required for `{path}`")]
21    BodyExpected { path: String },
22    #[error("body not allowed for `{path}`")]
23    BodyUnexpected { path: String },
24    /// The request body did not parse as the endpoint's type.
25    ///
26    /// `source` is [`structio::Error`], a `Copy` code-and-offset pair rather
27    /// than an allocated message, and it carries the offending key when the
28    /// reader knew one.
29    #[error("could not decode body for `{path}`: {source}")]
30    Decode {
31        path: String,
32        #[source]
33        source: structio::Error,
34    },
35    /// The body of a multi-argument method call was the wrong *shape* — the
36    /// wrong number of positional arguments, or neither an array nor an object.
37    ///
38    /// Distinct from [`Decode`](StructError::Decode), which is one argument
39    /// failing to parse as its own type. This one is about the envelope, and it
40    /// carries a message of repe's own because no parser produced it.
41    #[error("invalid arguments for `{path}`: {message}")]
42    Arguments { path: String, message: String },
43    #[error("method `{path}` failed: {message}")]
44    Execution { path: String, message: String },
45}
46
47impl StructError {
48    pub fn code(&self) -> ErrorCode {
49        match self {
50            StructError::InvalidPath { .. } | StructError::InvalidSubpath { .. } => {
51                ErrorCode::MethodNotFound
52            }
53            StructError::BodyExpected { .. } | StructError::BodyUnexpected { .. } => {
54                ErrorCode::InvalidBody
55            }
56            StructError::Decode { .. } | StructError::Arguments { .. } => ErrorCode::InvalidBody,
57            StructError::Execution { .. } => ErrorCode::ParseError,
58        }
59    }
60}
61
62/// Convenience alias for results returned by struct handlers.
63pub type StructResult<T> = Result<T, StructError>;
64
65/// Everything a served field needs to cross the wire in both of REPE's body
66/// formats: readable and writable as JSON and as BEVE.
67///
68/// A served *field* is read by one peer and written by the other, and the frame
69/// header decides the format per request rather than per type, so all four
70/// halves are genuinely required of it.
71///
72/// The halves are separately nameable, and the crate names them separately
73/// wherever only one is used: [`ServableRead`] for a body being decoded,
74/// [`ServableWrite`] for a response being encoded. Asking a type that is only
75/// ever sent to also be readable — or a method parameter that is only ever
76/// received to also be writable — is the bound doing more than the code does.
77///
78/// Declare a type with structio's [`object!`](structio::object) (or
79/// [`tagged_enum!`](structio::tagged_enum), or [`array!`](structio::array)) and
80/// it satisfies all three by construction; there is no derive to add.
81pub trait Servable: for<'de> ServableRead<'de> + ServableWrite {}
82impl<T: for<'de> ServableRead<'de> + ServableWrite> Servable for T {}
83
84/// The read half of [`Servable`]: decodable from either body format.
85///
86/// Carries the body's lifetime, so a type whose fields borrow out of the frame
87/// satisfies it for that frame.
88#[diagnostic::on_unimplemented(
89    message = "`{Self}` cannot be decoded from a REPE body: it has no structio declaration",
90    label = "no JSON/BEVE encoding for `{Self}`",
91    note = "declare it with `structio::object!({Self} {{ field, .. }})` — or `tagged_enum!` / `array!` / `unit_enum!`",
92    note = "`#[derive(RepeStruct)]` publishes endpoints; the structio declaration is what gives the type a wire encoding. A served type needs both."
93)]
94pub trait ServableRead<'de>: structio::json::Read<'de> + structio::beve::Read<'de> {}
95impl<'de, T> ServableRead<'de> for T where T: structio::json::Read<'de> + structio::beve::Read<'de> {}
96
97/// The read policy every REPE body is decoded under: unknown keys are stepped
98/// over rather than refused.
99///
100/// This is the protocol's rule, not a preference. REPE's schema-evolution
101/// guarantee is that a peer may add object members without breaking one built
102/// against an older declaration — see `docs/protocol.md` — and it is pinned
103/// cross-language by Glaze-authored interop fixtures that carry a key this
104/// crate never declared. structio's [`Standard`](structio::Standard) refuses an
105/// unknown key, which is the right default for a document you own and the wrong
106/// one for a frame that arrived from someone else's build.
107///
108/// It applies to what the *body* may contain, and not to what a type demands of
109/// it: an endpoint marks its mandatory members `#[required]` in its structio
110/// declaration, and that is unaffected by this.
111pub type WirePolicy = structio::SkipUnknown;
112
113/// A response a client decodes into: readable in both formats, and owning its
114/// own contents.
115///
116/// [`ServableRead`] carries the frame's lifetime, which is what lets a *server*
117/// borrow out of the body it was handed. A client cannot: it decodes out of a
118/// response message it owns locally and then returns the value, so the value
119/// has to outlive the frame it came from. `for<'de>` says exactly that, and
120/// `Default` is there because structio reads *into* an existing value.
121///
122/// The bound is both formats rather than the one the request used, because a
123/// server answers in the format the frame asked for and a client that names a
124/// result type does not get to assume which one came back.
125#[diagnostic::on_unimplemented(
126    message = "`{Self}` cannot be decoded from a REPE response",
127    label = "not decodable as an owned JSON/BEVE value",
128    note = "declare it with `structio::object!({Self} {{ field, .. }})` — or `tagged_enum!` / `array!` / `unit_enum!`",
129    note = "a type whose fields borrow (`&'de str`) satisfies `ServableRead` but not this: a decoded response outlives the frame, so borrowing fields must be owned (`String`)"
130)]
131pub trait ServableOwned: for<'de> ServableRead<'de> + Default {}
132impl<T: for<'de> ServableRead<'de> + Default> ServableOwned for T {}
133
134/// The write half of [`Servable`]: encodable into either body format.
135///
136/// Both halves, because the frame header picks the format per request and a
137/// response is encoded in whichever one the request asked for.
138#[diagnostic::on_unimplemented(
139    message = "`{Self}` cannot be encoded into a REPE body: it has no structio declaration",
140    label = "no JSON/BEVE encoding for `{Self}`",
141    note = "declare it with `structio::object!({Self} {{ field, .. }})` — or `tagged_enum!` / `array!` / `unit_enum!`",
142    note = "`#[derive(RepeStruct)]` publishes endpoints; the structio declaration is what gives the type a wire encoding. A served type needs both."
143)]
144pub trait ServableWrite: structio::json::Write + structio::beve::Write {}
145impl<T: structio::json::Write + structio::beve::Write + ?Sized> ServableWrite for T {}
146
147/// The request body handed to a [`RepeStruct`], as the bytes that arrived plus
148/// the format the frame header declared.
149///
150/// This is the mirror of [`ResponseBody`], and it is what replaced the
151/// `Option<serde_json::Value>` the trait used to take. A body is now parsed
152/// **once, into the live member it is destined for** — Glaze's `read_params` —
153/// rather than into a tree that is then walked and re-parsed. Nothing here
154/// allocates until a reader does, and a request that no endpoint claims never
155/// parses at all.
156///
157/// The bytes are borrowed from the frame, so a `RequestBody` cannot outlive it.
158/// That is deliberate: it is what lets a `&'de str` field borrow from the
159/// request instead of copying out of it.
160#[derive(Debug, Clone, Copy)]
161pub struct RequestBody<'a> {
162    bytes: &'a [u8],
163    format: BodyFormat,
164}
165
166impl<'a> RequestBody<'a> {
167    /// Wrap the body bytes of a frame, under the format its header declared.
168    pub fn new(bytes: &'a [u8], format: BodyFormat) -> Self {
169        Self { bytes, format }
170    }
171
172    /// The raw body bytes, unparsed.
173    ///
174    /// For an endpoint that forwards a body onward without looking inside it —
175    /// a proxy, a plugin boundary — and for [`BodyFormat::RawBinary`], where
176    /// there is nothing to parse.
177    pub fn bytes(&self) -> &'a [u8] {
178        self.bytes
179    }
180
181    /// The body format the frame header declared.
182    pub fn format(&self) -> BodyFormat {
183        self.format
184    }
185
186    /// Whether the body is the literal `null`.
187    ///
188    /// Asked by the paths that distinguish "no body" from "a body saying
189    /// nothing" — an optional child refusing a presence write, most of all.
190    /// Cheap in both formats: one tag byte in BEVE, a four-byte compare in
191    /// JSON. JSON whitespace is ASCII, so the compare needs no UTF-8 pass over
192    /// a body that may be megabytes long.
193    pub fn is_null(&self) -> bool {
194        match self.format {
195            BodyFormat::Beve => structio::beve::Reader::new(self.bytes)
196                .try_null()
197                .unwrap_or(false),
198            _ => self.bytes.trim_ascii() == b"null",
199        }
200    }
201
202    /// Parse the body into `value`, in place.
203    ///
204    /// `path` names the endpoint for the error message and is only read when
205    /// parsing fails.
206    ///
207    /// Reading *into* rather than returning a new value is what makes this the
208    /// live-member read: a `Vec` or `String` already in the destination keeps
209    /// its allocation, and a field absent from the body keeps the value it had.
210    /// That last part is a **merge**, and it is the behaviour a whole-object
211    /// write wants — a client updating one key of a wide object should not
212    /// blank the rest.
213    ///
214    /// Read under [`WirePolicy`], so a member the sender added and this build
215    /// never declared is stepped over rather than refusing the frame.
216    ///
217    /// An endpoint that wants some members to be mandatory marks them
218    /// `#[required]` in its structio declaration, which is per field and unions
219    /// with whatever policy is in force.
220    ///
221    /// **A failed read is not transactional.** structio parses straight into
222    /// `value`, so a body that is malformed partway through leaves the members
223    /// before the fault already updated and the rest as they were, and the
224    /// error goes back to the client. That is the price of the merge: there is
225    /// no scratch copy to discard, and building one would need `T: Clone` and
226    /// cost the allocation the live read exists to avoid. An endpoint that
227    /// must not expose a torn write reads into a fresh `T::default()` with
228    /// [`read`](Self::read) and assigns on success — replace semantics — or
229    /// validates the body against the schema before applying it.
230    pub fn read_into<T>(&self, path: &str, value: &mut T) -> StructResult<()>
231    where
232        T: ServableRead<'a>,
233    {
234        self.read_into_with::<WirePolicy, T>(path, value)
235    }
236
237    /// [`read_into`](Self::read_into) under an explicit structio
238    /// [read policy](structio::Options).
239    ///
240    /// For a policy that changes what the *body* may contain:
241    /// [`AllowComments`](structio::AllowComments) for a body written by hand,
242    /// or [`Standard`](structio::Standard) to refuse a key this build does not
243    /// declare — the opposite of [`WirePolicy`], and a deliberate narrowing of
244    /// what the protocol permits.
245    ///
246    /// Not for making members mandatory. [`RequireKeys`](structio::RequireKeys)
247    /// demands *every* declared member, and an `Option<T>` is not exempt — the
248    /// test is whether the key is present, not what it holds, so `null`
249    /// satisfies it and absence does not, and a struct with one optional member
250    /// cannot be read under it at all. Mark the mandatory members `#[required]`
251    /// instead.
252    pub fn read_into_with<O, T>(&self, path: &str, value: &mut T) -> StructResult<()>
253    where
254        O: structio::Options,
255        T: ServableRead<'a>,
256    {
257        self.read_raw_with::<O, T>(value)
258            .map_err(|source| StructError::Decode {
259                path: path.to_string(),
260                source,
261            })
262    }
263
264    /// [`read_into`](Self::read_into) without the path, for a caller that
265    /// builds the error label only when there is an error to label.
266    fn read_into_raw<T>(&self, value: &mut T) -> Result<(), structio::Error>
267    where
268        T: ServableRead<'a>,
269    {
270        self.read_raw_with::<WirePolicy, T>(value)
271    }
272
273    fn read_raw_with<O, T>(&self, value: &mut T) -> Result<(), structio::Error>
274    where
275        O: structio::Options,
276        T: ServableRead<'a>,
277    {
278        match self.format {
279            BodyFormat::Beve => structio::beve::read_into_with::<O, T>(value, self.bytes),
280            _ => match core::str::from_utf8(self.bytes) {
281                Ok(text) => structio::json::read_into_with::<O, T>(value, text),
282                Err(err) => Err(structio::Error::new(
283                    structio::ErrorCode::InvalidUtf8,
284                    err.valid_up_to(),
285                )),
286            },
287        }
288    }
289
290    /// Parse the body as a fresh `T`.
291    ///
292    /// [`read_into`](Self::read_into) is the one to reach for when a
293    /// destination already exists; this is for the case where it does not, such
294    /// as a method's parameter struct. The `Default` bound is what structio's
295    /// read-into model costs here: the value has to exist before it can be read
296    /// into.
297    pub fn read<T>(&self, path: &str) -> StructResult<T>
298    where
299        T: ServableRead<'a> + Default,
300    {
301        let mut value = T::default();
302        self.read_into(path, &mut value)?;
303        Ok(value)
304    }
305}
306
307/// Trait implemented by structs that can be exposed directly through the REPE
308/// router.
309///
310/// The implementation interprets the JSON Pointer path segments and either
311/// writes a response into `out` (for reads) or mutates the struct (for writes).
312///
313/// There is one dispatch method rather than two. The `Value`-returning
314/// `repe_handle` is gone with `serde_json::Value` itself: a read now serializes
315/// the live field straight into the outgoing frame, and a write parses the
316/// request bytes straight into it, so there is no tree for a second method to
317/// hand back.
318#[diagnostic::on_unimplemented(
319    message = "`{Self}` cannot be served over REPE: it does not implement `RepeStruct`",
320    label = "not a REPE-servable type",
321    note = "derive it with `#[derive(RepeStruct)]`",
322    note = "a field's own type needs a structio declaration — `structio::object!(Field {{ .. }})` — not a derive",
323    note = "a type in a crate that depends only on `repe-core` can derive this too; `repe` re-exports the same trait"
324)]
325pub trait RepeStruct: Send + Sync {
326    /// Handle a read or write against this struct, writing any response into
327    /// `out`.
328    ///
329    /// * `segments` — JSON Pointer path split into unescaped segments.
330    /// * `body` — `Some(..)` when the frame carried a body, `None` for a bare
331    ///   read.
332    /// * `out` — the response body under construction. Write exactly one
333    ///   top-level value into it: a value, a [`null`](ResponseBody::write_null),
334    ///   or an [`object`](ResponseBody::object). A write endpoint answers with
335    ///   `null`.
336    fn repe_handle_into(
337        &mut self,
338        segments: &[&str],
339        body: Option<RequestBody<'_>>,
340        out: &mut ResponseBody<'_>,
341    ) -> StructResult<()>;
342
343    /// Serve a request through a **shared** borrow, or decline it.
344    ///
345    /// The router tries this first for every request against a struct
346    /// registered behind a lock that has a shared mode, which is what keeps a
347    /// `/version` read from queueing behind a half-second method call on the
348    /// same object.
349    ///
350    /// A body-carrying frame is offered here too, and that is deliberate: REPE
351    /// separates read from write at the *frame* level, but a `&self` method
352    /// taking arguments is a call, not a mutation. Deciding from the frame
353    /// alone put a long-running `&self` call behind the write guard and stalled
354    /// every read of the object for as long as it ran. The receiver is known
355    /// where these arms are generated, so it is the receiver that decides.
356    ///
357    /// Return `None` for any path this borrow cannot serve: a field write, a
358    /// `&mut self` method, a nested field whose child declined. The router then
359    /// retakes the lock exclusively and dispatches through
360    /// [`repe_handle_into`](Self::repe_handle_into), so declining costs
361    /// correctness nothing — it is the default, and a hand-written impl that
362    /// never overrides this behaves exactly as it did before the path existed.
363    ///
364    /// Two obligations come with overriding it:
365    ///
366    /// * **Answer identically.** Whatever this returns for a path is what the
367    ///   client sees; the exclusive path is not consulted afterwards. Decline
368    ///   rather than approximate.
369    /// * **Write nothing when declining.** A `None` return must leave `out` as
370    ///   it was found, so the exclusive attempt starts from an empty body.
371    ///   [`ObjectBody::entry_try_with`] exists to make that mechanical when the
372    ///   decline surfaces partway through an object: it rewinds the whole
373    ///   object, so propagating its `None` is all a caller has to do.
374    ///
375    /// The third obligation this trait used to carry — leave `body` alone when
376    /// declining — is gone. [`RequestBody`] is `Copy` and borrows the frame
377    /// rather than owning a parsed tree, so the exclusive retry re-dispatches
378    /// the same body with no clone and nothing to take. That is the second
379    /// thing removing `Value` bought, after the allocation.
380    ///
381    /// A derived impl settles the whole-object listing before it writes or
382    /// invokes anything, through
383    /// [`repe_listing_declines`](Self::repe_listing_declines) — because a
384    /// decline discovered later would leave the entries before it run twice,
385    /// once here and once on the exclusive retry, and a rewind cannot undo a
386    /// call. A hand-written impl that invokes anything before it can decide owes
387    /// the same care.
388    fn repe_shared_into(
389        &self,
390        segments: &[&str],
391        body: Option<RequestBody<'_>>,
392        out: &mut ResponseBody<'_>,
393    ) -> Option<StructResult<()>> {
394        let _ = (segments, body, out);
395        None
396    }
397
398    /// Whether a shared whole-object listing of this struct declines — asked
399    /// **before** the listing writes or invokes anything.
400    ///
401    /// A listing is the one read that composes many others, so a decline
402    /// discovered partway through is not recoverable: the exclusive retry
403    /// re-runs the entries before it, and an entry that was *invoked* rather
404    /// than serialized runs a second time. Rewinding the response buffer undoes
405    /// the bytes; it cannot undo a call.
406    ///
407    /// So the answer has to be available at the top, and it has to cover the
408    /// whole subtree — a parent's listing composes its children's, so a child
409    /// that declines takes the parent's listing with it. That is why this is on
410    /// [`RepeStruct`] rather than only on
411    /// [`RepeMethods::REPE_LISTING_NEEDS_EXCLUSIVE`], which answers the same
412    /// question about one method table's accessors and nothing beneath them. A
413    /// derived impl returns that const OR'd with every `#[repe(nested)]` child's
414    /// answer, so the whole tree is settled before the first byte is written.
415    ///
416    /// The default is `true`, which is the accurate answer for the default
417    /// [`repe_shared_into`](Self::repe_shared_into): it declines every path,
418    /// listings included. A hand-written impl that overrides `repe_shared_into`
419    /// to serve a listing should override this too, or every derived struct
420    /// nesting it gives up its own shared listing.
421    ///
422    /// **Overriding it is a promise**, and it is the promise the invariant rests
423    /// on: returning `false` asserts that `repe_shared_into(&[], None, ..)`
424    /// answers `Some(..)`. Breaking it still yields a correct response — the
425    /// listing rewinds and the exclusive path retries — but anything the shared
426    /// attempt had already invoked runs twice.
427    fn repe_listing_declines(&self) -> bool {
428        true
429    }
430
431    /// Whether any path can answer a **body-carrying** frame through
432    /// [`repe_shared_into`](Self::repe_shared_into).
433    ///
434    /// The router asks before it takes the read lock. REPE puts a body on a
435    /// write *and* on a call with arguments, so a body alone cannot say which
436    /// one arrived — but a struct whose every write needs `&mut self` knows the
437    /// answer for all of them in advance, and `false` lets the router skip the
438    /// lock, the walk and the certain decline.
439    ///
440    /// This is a hint, and it cannot cost correctness. Everything the shared
441    /// borrow answers with a body, the exclusive path answers identically: a
442    /// `&self` method is callable through either, and every refusal
443    /// ([`BodyUnexpected`](StructError::BodyUnexpected) on a read-only endpoint,
444    /// [`InvalidPath`](StructError::InvalidPath) on an unknown one) is generated
445    /// from the same shape on both sides. `false` on an impl that could have
446    /// served one costs concurrency for that frame and nothing else.
447    ///
448    /// The default is `true`, the accurate answer for a hand-written
449    /// `repe_shared_into` this crate cannot see inside. A derived impl narrows
450    /// it to `false` when nothing it generates can answer a body: no `&self`
451    /// method taking arguments, no read-only endpoint whose refusal is servable
452    /// shared, and no `#[repe(nested)]` child that has either.
453    const REPE_SHARED_SERVES_BODIES: bool = true;
454}
455
456/// A **conditionally-present** child: a component that is not in every build, a
457/// subsystem that is not configured, a resource that failed to open.
458///
459/// `Option` is a foreign type and [`RepeStruct`] is this crate's trait, so a
460/// host cannot write this impl itself — its choices without one are a newtype
461/// per crate or one impl per concrete `Option<Child>`. Carrying it here is what
462/// lets `#[repe(nested)]` be put on an `Option<T>` field directly, which is
463/// where a host reaches for it first.
464///
465/// Present forwards everything to the inner value. Absent answers:
466///
467/// * a **read at the child's own path** with `null`, so a whole-object listing
468///   of the parent shows the key with nothing behind it rather than failing;
469/// * a **write, or any subpath** with [`StructError::InvalidPath`], because a
470///   silent no-op against a live resource is worse than an error — a client
471///   that configured an absent component would otherwise be told it succeeded;
472/// * [`repe_listing_declines`](RepeStruct::repe_listing_declines) with `false`
473///   when absent, since a `null` needs no exclusive borrow, and with the inner
474///   value's own answer when present.
475///
476/// **Presence is the host's, not the client's.** A `null` written at the child's
477/// own path is refused with [`StructError::BodyUnexpected`] whether the child is
478/// there or not, so the one value this path can read back is the one value it
479/// will not take. Removing a child would otherwise be a door that only opens one
480/// way, since creating one is the write an absent child already refuses. A
481/// whole-object write at the *parent* replaces the field, `null` included; that
482/// is a replace of the parent rather than a write to this path.
483///
484/// This matches what Glaze publishes for an unmapped optional member, so a
485/// port's wire shape does not change with the language.
486impl<T: RepeStruct> RepeStruct for Option<T> {
487    fn repe_handle_into(
488        &mut self,
489        segments: &[&str],
490        body: Option<RequestBody<'_>>,
491        out: &mut ResponseBody<'_>,
492    ) -> StructResult<()> {
493        refuse_presence_write(segments, body)?;
494        match self {
495            Some(inner) => inner.repe_handle_into(segments, body, out),
496            None => {
497                absent_child(segments, body.is_some())?;
498                out.write_null();
499                Ok(())
500            }
501        }
502    }
503
504    fn repe_shared_into(
505        &self,
506        segments: &[&str],
507        body: Option<RequestBody<'_>>,
508        out: &mut ResponseBody<'_>,
509    ) -> Option<StructResult<()>> {
510        // Refusing touches nothing, so it needs no exclusive borrow — and it has
511        // to be decided here rather than left to the retry, or a present child
512        // would forward the `null` to its inner value under both guards.
513        if let Err(err) = refuse_presence_write(segments, body) {
514            return Some(Err(err));
515        }
516        match self {
517            Some(inner) => inner.repe_shared_into(segments, body, out),
518            // Absent is a constant: no state to borrow exclusively, so every
519            // answer above is servable here.
520            None => Some(absent_child(segments, body.is_some()).map(|()| out.write_null())),
521        }
522    }
523
524    fn repe_listing_declines(&self) -> bool {
525        match self {
526            Some(inner) => inner.repe_listing_declines(),
527            None => false,
528        }
529    }
530
531    /// A present child answers for itself. An absent one refuses every write
532    /// and every sub-path, and refuses them identically on both borrows, so it
533    /// contributes nothing the exclusive path would not also say.
534    const REPE_SHARED_SERVES_BODIES: bool = T::REPE_SHARED_SERVES_BODIES;
535}
536
537/// Refuse a `null` written at an optional child's **own** path, present or
538/// absent.
539///
540/// `null` is what that path *reads* when the child is absent, so a client will
541/// try writing it back, and without this it lands on whichever branch happens to
542/// be live: a present child forwards it to its inner value and answers with that
543/// type's parse complaint, an absent one answers `InvalidPath`. Neither says
544/// what is actually true, which is that presence is not settable here.
545///
546/// It is refused rather than honoured because honouring it would open a one-way
547/// door: `null` could remove a child, and nothing could put it back — creating
548/// one is the write an absent child already refuses, for the reason that a
549/// client configuring something that is not there must not be told it worked.
550/// Presence belongs to the host on both sides of that. A whole-object write at
551/// the *parent* still replaces the field, `null` included; that is a replace of
552/// the parent, not a write to this path.
553fn refuse_presence_write(segments: &[&str], body: Option<RequestBody<'_>>) -> StructResult<()> {
554    if segments.is_empty() && body.is_some_and(|b| b.is_null()) {
555        return Err(StructError::BodyUnexpected {
556            path: path_from_segments(segments),
557        });
558    }
559    Ok(())
560}
561
562/// The absent half of [`RepeStruct for Option<T>`](RepeStruct#impl-RepeStruct-for-Option<T>):
563/// `Ok(())` for the one request an absent child can answer, and
564/// [`StructError::InvalidPath`] for the rest.
565///
566/// The path is relative to the child, so a parent's
567/// [`prepend_path`] names the field the client actually asked for.
568fn absent_child(segments: &[&str], has_body: bool) -> StructResult<()> {
569    if segments.is_empty() && !has_body {
570        Ok(())
571    } else {
572        Err(StructError::InvalidPath {
573            path: path_from_segments(segments),
574        })
575    }
576}
577
578/// Method table for a struct whose methods are declared with `#[repe::methods]`
579/// on an inherent `impl` block.
580///
581/// Generated by the attribute macro, which sees every signature in the block and
582/// so cannot fall behind the type the way a hand-maintained
583/// `#[repe(methods(..))]` list can. `#[derive(RepeStruct)]` dispatches path
584/// segments that match no field through this table when the struct carries the
585/// `#[repe(methods)]` marker.
586///
587/// Implementing this by hand is supported but unusual; the macro exists so the
588/// signatures stay derived from the `impl` block.
589#[diagnostic::on_unimplemented(
590    message = "`{Self}` declares `#[repe(methods)]` but its impl block is not annotated",
591    label = "no method table for `{Self}`",
592    note = "annotate the inherent `impl {Self}` block with `#[repe::methods]` (or `#[repe_core::methods]` when only `repe-core` is a dependency), or drop `#[repe(methods)]` from the struct"
593)]
594pub trait RepeMethods: MethodsDeclared {
595    /// `(endpoint, signature)` pairs published in the whole-struct listing.
596    const REPE_METHOD_SIGNATURES: &'static [(&'static str, &'static str)];
597
598    /// Endpoints in this table that are **field-shaped**: served by a
599    /// getter/setter pair (`#[repe(get = "...")]` / `#[repe(set = "...")]`)
600    /// rather than by an argument list.
601    ///
602    /// They are deliberately absent from
603    /// [`REPE_METHOD_SIGNATURES`](Self::REPE_METHOD_SIGNATURES), because they
604    /// have no signature to publish: a client reads and writes one the way it
605    /// reads and writes a field, so the whole-struct listing shows each one's
606    /// current value rather than a signature string. The derived listing reads
607    /// those values back through [`repe_call_into`](Self::repe_call_into), or
608    /// through [`repe_call_shared_into`](Self::repe_call_shared_into) when it is
609    /// being served under a shared borrow.
610    ///
611    /// Defaults to empty, so a hand-written impl need not mention it. One
612    /// invariant comes with listing a name here, and the derived listing relies
613    /// on it: [`repe_call_into`](Self::repe_call_into) must answer
614    /// `segments = &[name], body = None` with the endpoint's value. A name the
615    /// table cannot dispatch turns every whole-struct read into that name's
616    /// error. `#[repe::methods]` upholds it by construction, because it emits
617    /// this list from the getters it generated arms for. The shared-borrow
618    /// listing asks the same question of `repe_call_shared_into`, where a `None`
619    /// is not a failure — it declines the whole listing to the exclusive path.
620    const REPE_ACCESSOR_ENDPOINTS: &'static [&'static str] = &[];
621
622    /// `true` only on the placeholder table `#[repe::methods]` emits when the
623    /// block itself failed to parse.
624    ///
625    /// That table publishes nothing, so every compile-time check against it
626    /// would fire and bury the real error under a second, misleading one. This
627    /// says "these tables are not the truth" so those checks can stand down —
628    /// which emptiness alone cannot say, because a block that compiles and
629    /// publishes nothing is empty too, and its checks must still run.
630    #[doc(hidden)]
631    const REPE_TABLE_RECOVERED: bool = false;
632
633    /// Whether the whole-struct listing must be served exclusively because some
634    /// entry in it can only be read through `&mut self`.
635    ///
636    /// This is the one question the shared listing has to settle **before** it
637    /// runs anything, and it is why it is a `const` rather than a check per
638    /// entry. A listing is the one read that composes many others; a decline
639    /// discovered partway through leaves the entries before it already invoked,
640    /// and the exclusive retry invokes them again. A `&self` getter over a read
641    /// counter would report the second call.
642    ///
643    /// Only the getter half of a field-shaped endpoint can force it. Fields
644    /// serialize, published signatures are string literals, and a nested child
645    /// declines before writing anything of its own — none of those is a *call*.
646    /// So this is `true` exactly when some accessor's getter takes `&mut self`.
647    ///
648    /// The default is the conservative one: any accessor at all forces the
649    /// exclusive path, which is what a hand-written table gets for free.
650    /// `#[repe::methods]` overrides it with the answer it computed from the
651    /// receivers it has already seen, so a struct whose computed values are pure
652    /// reads keeps its shared listing — and so does every ancestor that nests
653    /// it, since a child's decline propagates.
654    ///
655    /// **Overriding it is a promise.** Setting it to `false` asserts that
656    /// [`repe_call_shared_into`](Self::repe_call_shared_into) answers
657    /// `segments = &[name], body = None` with `Some(..)` for every name in
658    /// [`REPE_ACCESSOR_ENDPOINTS`](Self::REPE_ACCESSOR_ENDPOINTS). A table that
659    /// breaks that promise still produces a correct response — the listing
660    /// rewinds and retries exclusively — but the getters that ran before the
661    /// decline run a second time, which is the double invocation this const
662    /// exists to rule out.
663    const REPE_LISTING_NEEDS_EXCLUSIVE: bool = !Self::REPE_ACCESSOR_ENDPOINTS.is_empty();
664
665    /// Whether any endpoint in this table can answer a body-carrying frame
666    /// through [`repe_call_shared_into`](Self::repe_call_shared_into).
667    ///
668    /// The table half of
669    /// [`RepeStruct::REPE_SHARED_SERVES_BODIES`], which ORs this with what the
670    /// struct's own fields and children say. Three shapes here can answer one: a
671    /// `&self` method that takes arguments, a `&self` setter, and a read-only
672    /// accessor, whose refusal needs no exclusive borrow to give.
673    ///
674    /// The default is `true`, which is never wrong — only, for a table that
675    /// serves no body, slower than it needs to be.
676    const REPE_SHARED_SERVES_BODIES: bool = true;
677
678    /// Invoke the method named by `segments[0]`, writing its result into `out`.
679    ///
680    /// `segments` is the remaining path relative to the struct root, so error
681    /// paths match the ones [`RepeStruct::repe_handle_into`] produces for
682    /// fields. Returns [`StructError::InvalidPath`] when no method matches.
683    fn repe_call_into(
684        &mut self,
685        segments: &[&str],
686        body: Option<RequestBody<'_>>,
687        out: &mut ResponseBody<'_>,
688    ) -> StructResult<()>;
689
690    /// Shared-borrow counterpart of [`repe_call_into`](Self::repe_call_into),
691    /// mirroring [`RepeStruct::repe_shared_into`] and carrying the same two
692    /// obligations: answer identically, and decline without writing.
693    ///
694    /// `#[repe::methods]` serves every `&self` method here — including one
695    /// taking arguments, which is a call rather than a mutation however the
696    /// frame is shaped — along with the getter half of a `&self` accessor, and
697    /// declines everything else.
698    fn repe_call_shared_into(
699        &self,
700        segments: &[&str],
701        body: Option<RequestBody<'_>>,
702        out: &mut ResponseBody<'_>,
703    ) -> Option<StructResult<()>> {
704        let _ = (segments, body, out);
705        None
706    }
707}
708
709/// Marker emitted by `#[derive(RepeStruct)]` when the struct carries the
710/// `#[repe(methods)]` attribute.
711///
712/// A derive macro cannot see `impl` blocks, so the two halves of the
713/// `#[repe::methods]` surface are tied together by a compile-time handshake.
714/// This marker is a supertrait of [`RepeMethods`], so the table the attribute
715/// macro generates simply cannot be implemented for a struct that did not
716/// declare it — no assertion to emit, and none to forget. Missing either half is
717/// a compile error naming the attribute that is absent, rather than a method
718/// that quietly never reaches the wire.
719#[diagnostic::on_unimplemented(
720    message = "`{Self}` has an annotated `methods` impl block but does not declare it",
721    label = "`{Self}` is missing `#[repe(methods)]`",
722    note = "add `#[repe(methods)]` next to `#[derive(RepeStruct)]` on `{Self}` so the derived router dispatches to the impl block"
723)]
724pub trait MethodsDeclared {}
725
726/// Build a path string from segments for error messages.
727pub fn path_from_segments(segments: &[&str]) -> String {
728    let mut s = String::new();
729    for segment in segments {
730        s.push('/');
731        s.push_str(segment);
732    }
733    s
734}
735
736/// Prefix error paths with an additional segment when bubbling errors from nested structs.
737pub fn prepend_path(mut err: StructError, prefix: &str) -> StructError {
738    let with_prefix = |path: String| {
739        if prefix.is_empty() {
740            path
741        } else if path.is_empty() {
742            format!("/{}", prefix)
743        } else if path.starts_with('/') {
744            format!("/{prefix}{path}")
745        } else {
746            format!("/{prefix}/{path}")
747        }
748    };
749
750    match &mut err {
751        StructError::InvalidPath { path }
752        | StructError::InvalidSubpath { path }
753        | StructError::BodyExpected { path }
754        | StructError::BodyUnexpected { path }
755        | StructError::Decode { path, .. }
756        | StructError::Arguments { path, .. }
757        | StructError::Execution { path, .. } => {
758            *path = with_prefix(std::mem::take(path));
759        }
760    }
761    err
762}
763
764/// Response body under construction for a [`RepeStruct`] read.
765///
766/// Handed to [`RepeStruct::repe_handle_into`] so a read serializes the live
767/// field straight into the outgoing frame buffer, with no intermediate tree —
768/// which is what a client polling a wide object at kilohertz used to pay for.
769///
770/// The body starts out empty, encoding in the format the request asked for.
771/// [`new`](Self::new) defaults that to [`BodyFormat::Json`];
772/// [`with_format`](Self::with_format) is what a server uses to answer a BEVE
773/// request in BEVE. The write that fills the body settles the format it
774/// actually reports, which is normally the requested one and is always
775/// [`BodyFormat::Beve`] for [`write_typed_slice`](Self::write_typed_slice).
776/// Exactly one top-level write is expected — a value, a null, or an
777/// [`object`](Self::object).
778///
779/// A whole-object [`object`](Self::object) listing honours the requested format
780/// too: a BEVE object carries its member count in its header, so the listing
781/// declares its count up front and rewinds whole if an entry declines.
782///
783/// Writing itself cannot fail: a [`structio::json::Write`] impl returns `()`.
784/// What can still fail is the *handler* around it — a nested child that
785/// declines, a method that errors — so [`object`](Self::object) entries that run
786/// arbitrary code keep their `Result`, and rewind the buffer to where the write
787/// began, so a caller that recovers from a [`StructError`] never ships
788/// half-serialized bytes.
789pub struct ResponseBody<'a> {
790    buf: &'a mut Vec<u8>,
791    /// The format the request asked to be answered in. Only ever
792    /// [`BodyFormat::Json`] or [`BodyFormat::Beve`]; a request in one of the
793    /// other two is answered in JSON.
794    requested: BodyFormat,
795    format: BodyFormat,
796    /// True while this body is a value *inside* an enclosing object, where the
797    /// frame's format is already settled and a member cannot change it.
798    ///
799    /// It gates exactly one thing: [`write_typed_slice`](Self::write_typed_slice).
800    /// A `#[repe(typed)]` field read *on its own* answers in BEVE whatever the
801    /// request asked for, that being what the attribute means. The same field
802    /// listed *inside* an object cannot do that without corrupting the frame, so
803    /// there it writes through [`write`](Self::write) and comes out as whatever
804    /// the enclosing object is — a BEVE typed array in a BEVE listing, a JSON
805    /// array in a JSON one.
806    ///
807    /// Every other write follows `requested`, which an enclosing object sets to
808    /// its own format, so nothing else needs to consult this.
809    nested: bool,
810}
811
812impl<'a> ResponseBody<'a> {
813    /// Wrap an output buffer, answering in JSON. `buf` is normally empty; writes
814    /// append to it.
815    pub fn new(buf: &'a mut Vec<u8>) -> Self {
816        Self::with_format(buf, BodyFormat::Json)
817    }
818
819    /// Wrap an output buffer, answering in the format the request declared.
820    ///
821    /// [`BodyFormat::RawBinary`] and [`BodyFormat::Utf8`] describe bodies with
822    /// no value structure to mirror, so a request in either is answered in
823    /// JSON.
824    pub fn with_format(buf: &'a mut Vec<u8>, requested: BodyFormat) -> Self {
825        Self {
826            buf,
827            requested: match requested {
828                BodyFormat::Beve => BodyFormat::Beve,
829                _ => BodyFormat::Json,
830            },
831            format: BodyFormat::Json,
832            nested: false,
833        }
834    }
835
836    /// The body format settled by the write that filled this body.
837    pub fn format(&self) -> BodyFormat {
838        self.format
839    }
840
841    /// Serialize `value` as the whole body, in the requested format.
842    ///
843    /// Inside an enclosing object the frame is already committed to JSON, and
844    /// this writes JSON regardless.
845    pub fn write<T>(&mut self, value: &T)
846    where
847        T: ServableWrite + ?Sized,
848    {
849        if self.requested == BodyFormat::Beve {
850            structio::beve::append(value, self.buf);
851            self.format = BodyFormat::Beve;
852        } else {
853            structio::append(value, self.buf);
854        }
855    }
856
857    /// Write a `null` body — the response to a write, or to a read that has
858    /// nothing to return.
859    pub fn write_null(&mut self) {
860        if self.requested == BodyFormat::Beve {
861            structio::beve::append(&(), self.buf);
862            self.format = BodyFormat::Beve;
863        } else {
864            self.buf.extend_from_slice(b"null");
865        }
866    }
867
868    /// Write `slice` as a BEVE typed numeric array and set the body format to
869    /// [`BodyFormat::Beve`].
870    ///
871    /// The same bulk encode `repe::message::MessageBuilder::body_typed_slice`
872    /// produces — one `copy_nonoverlapping` on little-endian targets rather than
873    /// a per-element walk, and byte-identical to what Glaze emits for the same
874    /// array. This is what `#[repe(typed)]` routes a numeric field to. (Named
875    /// rather than linked: the builder lives in `repe`, which this crate
876    /// deliberately does not depend on.)
877    ///
878    /// Inside an enclosing object — the whole-struct listing — the frame is
879    /// already committed to JSON, so the slice is written as a JSON array
880    /// instead. A field only reaches the typed encoding when it is read on its
881    /// own.
882    ///
883    /// This used to sit behind a `typed` feature, because the encoder arrived
884    /// with `beve` and six transitive packages behind it and a crate that only
885    /// *declares* a served type should not link one to say so. structio has no
886    /// dependencies, so there is nothing left to gate and the feature is gone.
887    pub fn write_typed_slice<T>(&mut self, slice: &[T])
888    where
889        T: structio::beve::NumericBytes + ServableWrite,
890    {
891        if self.nested {
892            self.write(slice);
893            return;
894        }
895        structio::beve::append(slice, self.buf);
896        self.format = BodyFormat::Beve;
897    }
898
899    /// Begin an object body of exactly `entries` members, written key by key.
900    ///
901    /// Used by the whole-struct listing so a wide object is emitted in one pass.
902    ///
903    /// `entries` is what lets the object be BEVE as readily as JSON: a BEVE
904    /// object carries its member count in its header, before any member, so a
905    /// listing that discovered its count by finishing could only ever have been
906    /// JSON. A derived listing knows the count when it is generated, and an
907    /// entry that fails or declines rewinds the whole object rather than
908    /// emitting a short one, so the declared count is never wrong.
909    ///
910    /// Under JSON the count is unused. Under BEVE, writing a number of entries
911    /// other than `entries` would produce a corrupt document, so
912    /// [`finish`](ObjectBody::finish) panics on a disagreement rather than
913    /// letting it reach a peer. The derive never miscounts; a hand-written
914    /// listing that does has a bug, and the panic names it.
915    pub fn object(&mut self, entries: usize) -> ObjectBody<'_> {
916        let start = self.buf.len();
917        let format = if self.nested {
918            // Already inside an object, so the frame's format is settled and
919            // this one follows it.
920            self.format
921        } else {
922            self.format = self.requested;
923            self.requested
924        };
925        match format {
926            BodyFormat::Beve => {
927                let mut w = beve_writer(self.buf);
928                w.push(structio::beve::header::OBJECT);
929                w.size(entries as u64);
930                *self.buf = w.into_vec();
931            }
932            _ => self.buf.push(b'{'),
933        }
934        ObjectBody {
935            buf: self.buf,
936            start,
937            format,
938            first: true,
939            declared: entries,
940            written: 0,
941        }
942    }
943}
944
945/// A JSON object body being written key by key. Created by
946/// [`ResponseBody::object`]; call [`finish`](Self::finish) to close it.
947///
948/// An entry that fails — or that [`entry_try_with`](Self::entry_try_with)
949/// declines — rewinds the buffer past the opening brace, so a partly written
950/// object is never left behind for a caller that recovers from it.
951///
952/// Those are the only two exits that rewind. There is no `Drop` impl, so
953/// abandoning an object after a successful [`entry`](Self::entry) — an early
954/// return, a panic — leaves the open brace and its entries in the buffer.
955/// Generated code never does that: every listing either runs to
956/// [`finish`](Self::finish) or leaves through an arm that has already rewound.
957/// A hand-written listing owes the same.
958pub struct ObjectBody<'a> {
959    buf: &'a mut Vec<u8>,
960    /// Buffer length before the object's header, to rewind to on failure.
961    start: usize,
962    /// The format this object and everything nested inside it is written in.
963    format: BodyFormat,
964    first: bool,
965    declared: usize,
966    written: usize,
967}
968
969/// A BEVE writer appending to `buf`, keeping what it already holds.
970///
971/// `Writer::appending` owns its buffer, so this moves the `Vec` out and the
972/// caller moves it back with `into_vec`. Both are three-word moves; nothing is
973/// copied and the allocation is preserved.
974fn beve_writer(buf: &mut Vec<u8>) -> structio::beve::Writer<'static, structio::Standard> {
975    structio::beve::Writer::appending(std::mem::take(buf))
976}
977
978impl ObjectBody<'_> {
979    /// Write one member's key and open its value position.
980    fn key(&mut self, key: &str) {
981        self.written += 1;
982        match self.format {
983            // A BEVE key is a bare length-prefixed string: no header byte, no
984            // separator, and no comma between members, the count in the header
985            // having said how many to expect.
986            BodyFormat::Beve => {
987                let mut w = beve_writer(self.buf);
988                w.write_str_body(key);
989                *self.buf = w.into_vec();
990            }
991            _ => {
992                if self.first {
993                    self.first = false;
994                } else {
995                    self.buf.push(b',');
996                }
997                // `str`'s JSON encoding is the quoted, escaped form, which is
998                // exactly a key. Going through structio rather than quoting by
999                // hand is what keeps escaping in one place.
1000                structio::append(key, self.buf);
1001                self.buf.push(b':');
1002            }
1003        }
1004    }
1005
1006    /// A body for one member's value, in this object's format.
1007    fn value_body(&mut self) -> ResponseBody<'_> {
1008        ResponseBody {
1009            buf: self.buf,
1010            requested: self.format,
1011            format: self.format,
1012            nested: true,
1013        }
1014    }
1015
1016    /// Write one `key: value` entry.
1017    pub fn entry<T>(&mut self, key: &str, value: &T)
1018    where
1019        T: ServableWrite + ?Sized,
1020    {
1021        self.key(key);
1022        self.value_body().write(value);
1023    }
1024
1025    /// Write one `key: <value>` entry whose value is produced by `f`, for a
1026    /// nested [`RepeStruct`] that fills the body itself.
1027    ///
1028    /// The body handed to `f` is marked as nested: the frame's format is
1029    /// settled by the enclosing object, so nothing inside can switch it. A
1030    /// [`ResponseBody::write_typed_slice`] there writes a BEVE typed array
1031    /// inside a BEVE listing and a JSON array inside a JSON one.
1032    pub fn entry_with<F>(&mut self, key: &str, f: F) -> StructResult<()>
1033    where
1034        F: FnOnce(&mut ResponseBody<'_>) -> StructResult<()>,
1035    {
1036        self.key(key);
1037        let outcome = f(&mut self.value_body());
1038        if outcome.is_err() {
1039            self.buf.truncate(self.start);
1040        }
1041        outcome
1042    }
1043
1044    /// [`entry_with`](Self::entry_with) for a value the source may decline to
1045    /// produce, as [`RepeStruct::repe_shared_into`] declines a path that needs
1046    /// exclusive access.
1047    ///
1048    /// `None` rewinds the whole object, exactly as an `Err` does, so a caller
1049    /// that declines in turn leaves the buffer as it found it without a second
1050    /// step. That is also why a declared count can never be short: an object
1051    /// that did not write every entry does not survive at all.
1052    pub fn entry_try_with<F>(&mut self, key: &str, f: F) -> Option<StructResult<()>>
1053    where
1054        F: FnOnce(&mut ResponseBody<'_>) -> Option<StructResult<()>>,
1055    {
1056        self.key(key);
1057        let outcome = f(&mut self.value_body());
1058        if !matches!(outcome, Some(Ok(()))) {
1059            self.buf.truncate(self.start);
1060        }
1061        outcome
1062    }
1063
1064    /// Close the object.
1065    ///
1066    /// # Panics
1067    ///
1068    /// If the number of entries written differs from the number declared to
1069    /// [`ResponseBody::object`]. Under BEVE the count is already in the header,
1070    /// so a disagreement is a corrupt document, and a panic in a handler is
1071    /// caught and reported by the server where corrupt bytes would not be.
1072    pub fn finish(self) {
1073        assert_eq!(
1074            self.written, self.declared,
1075            "repe: a listing declared {} entries and wrote {}; under BEVE the \
1076             count is in the header and a disagreement corrupts the document",
1077            self.declared, self.written,
1078        );
1079        if self.format != BodyFormat::Beve {
1080            self.buf.push(b'}');
1081        }
1082    }
1083}
1084
1085/// Compile-time check that the three sets of endpoints on one struct do not
1086/// overlap.
1087///
1088/// The two macros cannot see each other's input, so the derive emits a call to
1089/// this against everything *it* publishes — fields, plus any method named in a
1090/// struct-level `#[repe(methods(..))]` list — and the two generated
1091/// [`RepeMethods`] tables. Without it a collision is silent and costly: one
1092/// declaration wins dispatch, the other becomes permanently unreachable, and
1093/// the whole-struct listing emits the same key twice — a duplicate key in the
1094/// response body, which every listing now streams rather than deduplicating in
1095/// a map on the way out.
1096///
1097/// Collisions the macros *can* see on their own — two fields, two listed
1098/// methods, a field against a listed method, two endpoints in one
1099/// `#[repe::methods]` block — are rejected at macro time with a message naming
1100/// the endpoint and pointing at the second declaration.
1101///
1102/// The third pairing, methods against accessors, is unreachable from a
1103/// generated table for the same reason; it is checked because a hand-written
1104/// [`RepeMethods`] impl can produce it.
1105#[doc(hidden)]
1106pub const fn assert_no_endpoint_collision(
1107    declared: &[&str],
1108    methods: &[(&str, &str)],
1109    accessors: &[&str],
1110) {
1111    let mut i = 0;
1112    while i < methods.len() {
1113        if const_contains(declared, methods[i].0) {
1114            panic!(
1115                "a published method and an endpoint declared on the struct itself \
1116                 share a name: the struct's declaration wins dispatch and the method could \
1117                 never be called. Rename one with `#[repe(rename = \"...\")]`."
1118            );
1119        }
1120        i += 1;
1121    }
1122
1123    let mut i = 0;
1124    while i < accessors.len() {
1125        if const_contains(declared, accessors[i]) {
1126            panic!(
1127                "a `#[repe(get = \"...\")]` accessor and an endpoint declared on the struct \
1128                 itself share a name: the struct's declaration wins dispatch and the accessor \
1129                 could never be called. Rename the struct's with \
1130                 `#[repe(rename = \"...\")]`, or give the accessor a different endpoint."
1131            );
1132        }
1133
1134        if listed_signature(methods, accessors[i]).is_some() {
1135            panic!(
1136                "a published method and a `#[repe(get = \"...\")]` accessor in the \
1137                 same table share an endpoint name: one of them is unreachable, and the \
1138                 whole-struct listing would show the endpoint twice."
1139            );
1140        }
1141        i += 1;
1142    }
1143}
1144
1145/// Compile-time check that a `#[repe(listing_order(..))]` list names exactly the
1146/// endpoints the struct publishes.
1147///
1148/// The derive validates the half it can see on its own — fields and struct-level
1149/// `#[repe(methods(..))]` entries — with an error that names the offending key.
1150/// It cannot see the `#[repe::methods]` impl block, so the other half is checked
1151/// here, where both generated tables are in scope. A `const` panic cannot name
1152/// the key, which is why the derive keeps everything it can reach at macro time.
1153///
1154/// Both directions matter. An order naming an endpoint that does not exist would
1155/// emit a key whose value came from a failed dispatch; an order omitting one
1156/// would silently drop it from every whole-object read, which is the harder bug
1157/// to see because the endpoint still answers on its own path.
1158#[doc(hidden)]
1159pub const fn assert_listing_order(
1160    order: &[&str],
1161    declared: &[&str],
1162    methods: &[(&str, &str)],
1163    accessors: &[&str],
1164    recovering: bool,
1165) {
1166    // `recovering` is [`RepeMethods::REPE_TABLE_RECOVERED`]: the block failed to
1167    // parse, so the tables describe nothing and every key here would look
1168    // unknown. This assertion would then be exactly the extra error that
1169    // recovery exists to prevent. It must come from the marker rather than from
1170    // the tables being empty — a block that compiles and publishes nothing is
1171    // also empty, and an unknown key in *that* struct's order has to be caught
1172    // here, because the derive skips its own check whenever an impl block is in
1173    // play.
1174    let mut i = 0;
1175    while i < order.len() {
1176        let known = const_contains(declared, order[i])
1177            || const_contains(accessors, order[i])
1178            || listed_signature(methods, order[i]).is_some();
1179        if !known && !recovering {
1180            panic!(
1181                "`#[repe(listing_order(..))]` names a key that is not an endpoint on this \
1182                 struct. It lists the whole-object listing's keys, so every name in it has to \
1183                 be a field, a listed method, or an endpoint of the annotated `methods` impl block."
1184            );
1185        }
1186        i += 1;
1187    }
1188
1189    let mut j = 0;
1190    while j < methods.len() {
1191        if !const_contains(order, methods[j].0) {
1192            panic!(
1193                "a method on the annotated `methods` impl block is missing from `#[repe(listing_order(..))]`, \
1194                 which names the whole-object listing's keys in full. An omitted endpoint \
1195                 would disappear from every whole-object read while still answering on its \
1196                 own path."
1197            );
1198        }
1199        j += 1;
1200    }
1201
1202    let mut j = 0;
1203    while j < accessors.len() {
1204        if !const_contains(order, accessors[j]) {
1205            panic!(
1206                "a `#[repe(get = \"...\")]` accessor is missing from \
1207                 `#[repe(listing_order(..))]`, which names the whole-object listing's keys in \
1208                 full. An omitted endpoint would disappear from every whole-object read while \
1209                 still answering on its own path."
1210            );
1211        }
1212        j += 1;
1213    }
1214}
1215
1216/// The published signature for `name`, or `None` when the name belongs to a
1217/// field-shaped accessor instead.
1218///
1219/// Called from a `const` block in the ordered listing a
1220/// `#[repe(listing_order(..))]` produces: the derive cannot see the
1221/// `#[repe::methods]` block, so it does not know which of the two tables an
1222/// ordered key came from, but the tables themselves are constants and the
1223/// question folds away before run time.
1224#[doc(hidden)]
1225pub const fn listed_signature<'a>(methods: &[(&'a str, &'a str)], name: &str) -> Option<&'a str> {
1226    let mut i = 0;
1227    while i < methods.len() {
1228        if const_str_eq(methods[i].0, name) {
1229            return Some(methods[i].1);
1230        }
1231        i += 1;
1232    }
1233    None
1234}
1235
1236/// `slice.contains(&name)` usable in a `const` context.
1237const fn const_contains(list: &[&str], name: &str) -> bool {
1238    let mut i = 0;
1239    while i < list.len() {
1240        if const_str_eq(list[i], name) {
1241            return true;
1242        }
1243        i += 1;
1244    }
1245    false
1246}
1247
1248/// `str` equality usable in a `const` context, which `PartialEq` is not.
1249const fn const_str_eq(a: &str, b: &str) -> bool {
1250    let (a, b) = (a.as_bytes(), b.as_bytes());
1251    if a.len() != b.len() {
1252        return false;
1253    }
1254    let mut i = 0;
1255    while i < a.len() {
1256        if a[i] != b[i] {
1257            return false;
1258        }
1259        i += 1;
1260    }
1261    true
1262}
1263
1264/// Decoder for the body of a struct method taking two or more arguments.
1265///
1266/// A single-argument method takes the request body *as* the argument, which is
1267/// the shape the wire has always had. Beyond one argument the body carries the
1268/// whole list, in either of two forms:
1269///
1270/// * a JSON/BEVE **array** of exactly N values, positionally, or
1271/// * an **object** keyed by parameter name, where a missing key decodes as
1272///   `null` (so an `Option<T>` parameter may be omitted) and a repeated key
1273///   takes its last value.
1274///
1275/// All three BEVE array encodings work: generic, typed, and complex. They are
1276/// not read the same way — a generic array's elements are self-contained values
1277/// in the input and are sliced out as spans, while a typed or complex array's
1278/// element headers are supplied by the reader rather than present in the bytes,
1279/// so those are pulled through `structio::beve::Documents::array` instead — but
1280/// that is an implementation detail and not a wire distinction. A client encodes
1281/// a homogeneous argument list however its library naturally would.
1282///
1283/// Generated code names this, and a hand-written [`RepeMethods`] impl that
1284/// publishes a multi-argument method should too: it is what makes such a table
1285/// accept the same two body shapes a derived one does, instead of inventing a
1286/// third that no client of a derived struct would speak. That is why it is
1287/// public and documented rather than hidden — it carries a wire contract, not an
1288/// implementation detail.
1289///
1290/// # How it works without a tree
1291///
1292/// It used to split a `serde_json::Value` into owned `Value`s. There is no tree
1293/// now, so it does the same job by **recording byte spans**: one pass over the
1294/// body notes where each element starts and ends, and
1295/// [`next_arg`](Self::next_arg) parses one span into one argument. Nothing
1296/// between the two is materialized, no key is copied, and an argument the caller
1297/// never asks for is never parsed.
1298///
1299/// The spans borrow the frame, which is why this carries the body's lifetime.
1300pub struct MethodArgs<'a> {
1301    path: &'a str,
1302    names: &'a [&'a str],
1303    format: BodyFormat,
1304    source: ArgSource<'a>,
1305    index: usize,
1306}
1307
1308/// Where [`MethodArgs::next_arg`] gets one argument's bytes.
1309///
1310/// Two arms, because BEVE has two kinds of array. In a generic array — and in
1311/// every JSON body — an element is a self-contained value in the input, so a
1312/// span cut between two reader positions is a document and can be parsed on its
1313/// own. In a *typed* or *complex* array it is not: the element's header is
1314/// supplied by the reader rather than present in the bytes, so those spans are
1315/// headerless payload, and a boolean run's are empty and not even monotonic.
1316///
1317/// `structio::beve::Documents::array` is the seam for the second kind. It hands
1318/// each element out as a document of its own with the header installed, and
1319/// `next_value_into` is generic per call, so a heterogeneous argument list still
1320/// works. It costs a copy of the body into a window sized to the body — which is
1321/// an argument list, never a bulk payload, since a method taking one large array
1322/// takes the body *as* its single argument and never reaches here.
1323enum ArgSource<'a> {
1324    /// One slot per name, in declaration order. `None` is a key the object form
1325    /// left out, which [`MethodArgs::next_arg`] reads as `null`.
1326    Spans(Vec<Option<&'a [u8]>>),
1327    /// Elements pulled in order from an array whose headers the reader supplies.
1328    Cursor(structio::beve::Documents<&'a [u8], WirePolicy>),
1329}
1330
1331impl<'a> MethodArgs<'a> {
1332    /// Split `body` into the argument list for `names`.
1333    pub fn new(path: &'a str, names: &'a [&'a str], body: RequestBody<'a>) -> StructResult<Self> {
1334        let source = match body.format() {
1335            BodyFormat::Beve => split_beve(path, names, body.bytes())?,
1336            _ => ArgSource::Spans(split_json(path, names, body.bytes())?),
1337        };
1338        Ok(Self {
1339            path,
1340            names,
1341            format: body.format(),
1342            source,
1343            index: 0,
1344        })
1345    }
1346
1347    /// Decode the next argument in declaration order.
1348    pub fn next_arg<T>(&mut self) -> StructResult<T>
1349    where
1350        T: for<'de> ServableRead<'de> + Default,
1351    {
1352        let name = self.names.get(self.index).copied().unwrap_or("?");
1353        let index = self.index;
1354        self.index += 1;
1355        let mut value = T::default();
1356        // The label is built on the error branch only: a multi-argument call
1357        // would otherwise format one `String` per argument on every success.
1358        let label = || format!("{}({name})", self.path);
1359
1360        match &mut self.source {
1361            ArgSource::Spans(spans) => {
1362                // An omitted key is the JSON `null` whatever the frame's format
1363                // is: the stand-in never came off the wire, so there is no BEVE
1364                // encoding of it to prefer.
1365                let (bytes, format) = match spans.get(index).copied().flatten() {
1366                    Some(bytes) => (bytes, self.format),
1367                    None => (&b"null"[..], BodyFormat::Json),
1368                };
1369                RequestBody::new(bytes, format)
1370                    .read_into_raw(&mut value)
1371                    .map_err(|source| StructError::Decode {
1372                        path: label(),
1373                        source,
1374                    })?;
1375            }
1376            ArgSource::Cursor(documents) => {
1377                // Arity was settled in `split_beve`, so running out here would
1378                // mean the count in the header disagreed with the elements
1379                // behind it — a malformed document, not a short call.
1380                let outcome =
1381                    documents
1382                        .next_value_into(&mut value)
1383                        .ok_or_else(|| StructError::Decode {
1384                            path: label(),
1385                            source: structio::Error::new(structio::ErrorCode::UnexpectedEnd, 0),
1386                        })?;
1387                outcome.map_err(|err| StructError::Decode {
1388                    path: label(),
1389                    source: stream_parse_error(err),
1390                })?;
1391            }
1392        }
1393        Ok(value)
1394    }
1395}
1396
1397/// Turn a structio parse failure into the error this module reports. Callers
1398/// pass a whole-body offset, which is what the parser's `position` already is.
1399fn decode_error(path: &str, code: structio::ErrorCode, at: usize) -> StructError {
1400    StructError::Decode {
1401        path: path.to_string(),
1402        source: structio::Error::new(code, at),
1403    }
1404}
1405
1406/// Record one span per name from a JSON argument body.
1407fn split_json<'a>(
1408    path: &str,
1409    names: &[&str],
1410    bytes: &'a [u8],
1411) -> StructResult<Vec<Option<&'a [u8]>>> {
1412    let text = core::str::from_utf8(bytes)
1413        .map_err(|err| decode_error(path, structio::ErrorCode::InvalidUtf8, err.valid_up_to()))?;
1414    let mut p = structio::json::Parser::new(text);
1415    p.skip_ws();
1416
1417    // Decide the shape from the opening byte rather than from whether a walk
1418    // succeeded. A walk can fail half way through a body whose shape was never
1419    // in doubt — one malformed element in an otherwise well-formed array — and
1420    // reporting that as "neither an array nor an object" hides the real fault.
1421    match p.rest().first() {
1422        Some(b'[') => {
1423            let mut positional: Vec<Option<&'a [u8]>> = Vec::new();
1424            p.read_seq(|p, _| {
1425                let start = p.position();
1426                p.skip_value()?;
1427                positional.push(Some(&bytes[start..p.position()]));
1428                Ok(())
1429            })
1430            .and_then(|_| p.finish())
1431            .map_err(|code| decode_error(path, code, p.position()))?;
1432            check_arity(path, names, positional.len())?;
1433            Ok(positional)
1434        }
1435        Some(b'{') => {
1436            let mut spans: Vec<Option<&'a [u8]>> = vec![None; names.len()];
1437            p.read_map(|p, key| {
1438                // Matched during the walk, so a key no parameter has costs
1439                // nothing and a repeated key overwrites — last-wins, as the
1440                // `serde_json::Map` this replaced did.
1441                let slot = names.iter().position(|name| *name == key.as_str());
1442                let start = p.position();
1443                p.skip_value()?;
1444                if let Some(i) = slot {
1445                    spans[i] = Some(&bytes[start..p.position()]);
1446                }
1447                Ok(())
1448            })
1449            .and_then(|()| p.finish())
1450            .map_err(|code| decode_error(path, code, p.position()))?;
1451            Ok(spans)
1452        }
1453        _ => Err(shape_error(path, names)),
1454    }
1455}
1456
1457/// A parse failure out of a streaming read, as this module reports it.
1458///
1459/// The source is an in-memory slice, so `StreamError::Io` is unreachable in
1460/// practice; it is mapped rather than unwrapped because a reader is entitled to
1461/// report one and a panic here would be a worse answer than a decode error.
1462fn stream_parse_error(err: structio::StreamError) -> structio::Error {
1463    match err {
1464        structio::StreamError::Parse(err) => err,
1465        _ => structio::Error::new(structio::ErrorCode::UnexpectedEnd, 0),
1466    }
1467}
1468
1469/// Decide how a BEVE argument body is split.
1470fn split_beve<'a>(path: &str, names: &[&str], bytes: &'a [u8]) -> StructResult<ArgSource<'a>> {
1471    // The shape is decided from the header, for the reason `split_json` decides
1472    // it from the opening byte, and for a second reason particular to BEVE.
1473    //
1474    // `Reader::read_seq` accepts a *typed* array as readily as a generic one,
1475    // and a *complex* array through the same door, installing each element's
1476    // header out of band rather than reading it from the input. A span cut
1477    // between two reader positions is therefore not a document those elements
1478    // can be read from — for a typed array of booleans the spans are empty and
1479    // not even monotonic. Those two shapes go to `Documents::array`, which hands
1480    // each element out with the header installed; only the shapes whose elements
1481    // are self-contained in the input are sliced.
1482    match bytes.first().map(|&h| structio::beve::header::ty(h)) {
1483        Some(structio::beve::header::TY_GENERIC_ARRAY) => {
1484            let mut positional: Vec<Option<&'a [u8]>> = Vec::new();
1485            let mut r = structio::beve::Reader::new(bytes);
1486            r.read_seq(|r, _| {
1487                let start = r.position();
1488                r.skip_value()?;
1489                positional.push(Some(&bytes[start..r.position()]));
1490                Ok(())
1491            })
1492            .and_then(|_| r.finish())
1493            .map_err(|code| decode_error(path, code, r.position()))?;
1494            check_arity(path, names, positional.len())?;
1495            Ok(ArgSource::Spans(positional))
1496        }
1497        Some(structio::beve::header::TY_OBJECT) => {
1498            let mut spans: Vec<Option<&'a [u8]>> = vec![None; names.len()];
1499            let mut r = structio::beve::Reader::new(bytes);
1500            r.read_map(|r, key| {
1501                // Argument names are identifiers, so only the string form of a
1502                // BEVE key can match one; a numeric key matches nothing and its
1503                // value is skipped like any other unclaimed key.
1504                let slot = match key {
1505                    structio::beve::Key::Str(key) => names.iter().position(|name| *name == key),
1506                    _ => None,
1507                };
1508                let start = r.position();
1509                r.skip_value()?;
1510                if let Some(i) = slot {
1511                    spans[i] = Some(&bytes[start..r.position()]);
1512                }
1513                Ok(())
1514            })
1515            .and_then(|()| r.finish())
1516            .map_err(|code| decode_error(path, code, r.position()))?;
1517            Ok(ArgSource::Spans(spans))
1518        }
1519        // The two header-synthesizing forms. `TY_EXTENSION` is where
1520        // `header::COMPLEX` lives.
1521        Some(structio::beve::header::TY_TYPED_ARRAY | structio::beve::header::TY_EXTENSION) => {
1522            // Arity is settled before any argument is decoded, as it is for
1523            // every other shape, so a wrong-length call fails the same way
1524            // whichever encoding it arrived in. This walk skips elements rather
1525            // than reading them; it is one pass over an argument list.
1526            let mut r = structio::beve::Reader::new(bytes);
1527            let count = r
1528                .read_seq(|r, _| r.skip_value())
1529                .and_then(|count| r.finish().map(|()| count))
1530                .map_err(|code| decode_error(path, code, r.position()))?;
1531            check_arity(path, names, count)?;
1532            // Sized to the body, so the first fill takes it whole and the window
1533            // never grows. The body is an argument list, so this is bounded by
1534            // the arity and the element width, not by any payload.
1535            Ok(ArgSource::Cursor(
1536                structio::beve::Documents::array(bytes)
1537                    .with_options::<WirePolicy>()
1538                    .read_size(bytes.len().max(1)),
1539            ))
1540        }
1541        _ => Err(shape_error(path, names)),
1542    }
1543}
1544
1545fn check_arity(path: &str, names: &[&str], got: usize) -> StructResult<()> {
1546    if got == names.len() {
1547        Ok(())
1548    } else {
1549        Err(StructError::Arguments {
1550            path: path.to_string(),
1551            message: format!("expected {} arguments, got {got}", names.len()),
1552        })
1553    }
1554}
1555
1556fn shape_error(path: &str, names: &[&str]) -> StructError {
1557    StructError::Arguments {
1558        path: path.to_string(),
1559        message: format!(
1560            "expected an array of {} arguments or an object with keys [{}]",
1561            names.len(),
1562            names.join(", ")
1563        ),
1564    }
1565}