Skip to main content

repe_core/
structs.rs

1use crate::constants::{BodyFormat, ErrorCode};
2use serde::Serialize;
3use serde::de::DeserializeOwned;
4use serde_json::Value;
5/// Errors produced while handling struct-backed endpoints.
6///
7/// Non-exhaustive: match with a wildcard arm, or use [`StructError::code`] to
8/// map any error onto its protocol [`ErrorCode`].
9#[derive(Debug, thiserror::Error)]
10#[non_exhaustive]
11pub enum StructError {
12    #[error("invalid path `{path}`")]
13    InvalidPath { path: String },
14    #[error("unexpected additional path segments at `{path}`")]
15    InvalidSubpath { path: String },
16    #[error("body required for `{path}`")]
17    BodyExpected { path: String },
18    #[error("body not allowed for `{path}`")]
19    BodyUnexpected { path: String },
20    #[error("serialization error for `{path}`: {source}")]
21    Serialize {
22        path: String,
23        #[source]
24        source: serde_json::Error,
25    },
26    #[error("deserialization error for `{path}`: {source}")]
27    Deserialize {
28        path: String,
29        #[source]
30        source: serde_json::Error,
31    },
32    #[error("method `{path}` failed: {message}")]
33    Execution { path: String, message: String },
34}
35
36impl StructError {
37    pub fn code(&self) -> ErrorCode {
38        match self {
39            StructError::InvalidPath { .. } | StructError::InvalidSubpath { .. } => {
40                ErrorCode::MethodNotFound
41            }
42            StructError::BodyExpected { .. } | StructError::BodyUnexpected { .. } => {
43                ErrorCode::InvalidBody
44            }
45            StructError::Serialize { .. } | StructError::Deserialize { .. } => {
46                ErrorCode::InvalidBody
47            }
48            StructError::Execution { .. } => ErrorCode::ParseError,
49        }
50    }
51}
52
53/// Convenience alias for results returned by struct handlers.
54pub type StructResult<T> = Result<T, StructError>;
55
56/// Trait implemented by structs that can be exposed directly through the REPE router.
57///
58/// The implementation should interpret the provided JSON Pointer path segments and
59/// either return a JSON value (for reads) or mutate the struct (for writes).
60#[diagnostic::on_unimplemented(
61    message = "`{Self}` cannot be served over REPE: it does not implement `RepeStruct`",
62    label = "not a REPE-servable type",
63    note = "derive it with `#[derive(RepeStruct)]`, or, for a field of a type you do not own, use `#[repe(nested_serde)]` to route through its `Serialize`/`Deserialize` impls instead of `#[repe(nested)]`",
64    note = "a type in a crate that depends only on `repe-core` can derive this too; `repe` re-exports the same trait"
65)]
66pub trait RepeStruct: Send + Sync {
67    /// Handle a read or write against this struct.
68    ///
69    /// * `segments` – JSON Pointer path split into unescaped segments.
70    /// * `body` – `Some(value)` when the request contains a JSON body, `None` for reads.
71    ///
72    /// Return `Ok(Some(value))` to send a JSON response payload, `Ok(None)` to send `null`.
73    fn repe_handle(
74        &mut self,
75        segments: &[&str],
76        body: Option<Value>,
77    ) -> StructResult<Option<Value>>;
78
79    /// Encode-in-place counterpart of [`repe_handle`](Self::repe_handle): write the
80    /// response body straight into `out` instead of returning an owned
81    /// [`serde_json::Value`] for the caller to re-serialize.
82    ///
83    /// This is the method the router calls. The default implementation delegates
84    /// to [`repe_handle`](Self::repe_handle) and encodes whatever it returns, so a
85    /// hand-written impl only needs `repe_handle`; `#[derive(RepeStruct)]`
86    /// overrides it so a leaf read serializes the live field directly into the
87    /// outgoing frame buffer with no intermediate `Value`.
88    ///
89    /// Writes are unaffected — a request body still arrives as a `Value`.
90    ///
91    /// [`repe_handle`]: Self::repe_handle
92    fn repe_handle_into(
93        &mut self,
94        segments: &[&str],
95        body: Option<Value>,
96        out: &mut ResponseBody<'_>,
97    ) -> StructResult<()> {
98        let value = self.repe_handle(segments, body)?;
99        write_optional(out, segments, value)
100    }
101
102    /// Serve a request through a **shared** borrow, or decline it.
103    ///
104    /// The router tries this first for every request against a struct
105    /// registered behind a lock that has a shared mode, which is what keeps a
106    /// `/version` read from queueing behind a half-second method call on the
107    /// same object.
108    ///
109    /// A body-carrying frame is offered here too, and that is deliberate: REPE
110    /// separates read from write at the *frame* level, but a `&self` method
111    /// taking arguments is a call, not a mutation. Deciding from the frame
112    /// alone put a long-running `&self` call behind the write guard and
113    /// stalled every read of the object for as long as it ran. The receiver is known
114    /// where these arms are generated, so it is the receiver that decides.
115    ///
116    /// Return `None` for any path this borrow cannot serve: a field write, a
117    /// `&mut self` method, a nested field whose child declined. The router then
118    /// retakes the lock exclusively and dispatches through
119    /// [`repe_handle_into`](Self::repe_handle_into), so declining costs
120    /// correctness nothing — it is the default, and a hand-written impl that
121    /// never overrides this behaves exactly as it did before the path existed.
122    ///
123    /// Three obligations come with overriding it:
124    ///
125    /// * **Answer identically.** Whatever this returns for a path is what the
126    ///   client sees; the exclusive path is not consulted afterwards. Decline
127    ///   rather than approximate.
128    /// * **Write nothing when declining.** A `None` return must leave `out` as
129    ///   it was found, so the exclusive attempt starts from an empty body.
130    ///   [`ObjectBody::entry_try_with`] exists to make that mechanical when the
131    ///   decline surfaces partway through an object: it rewinds the whole
132    ///   object, so propagating its `None` is all a caller has to do.
133    /// * **Leave the body alone when declining.** `body` is handed over as
134    ///   `&mut Option<Value>` rather than by value precisely so the exclusive
135    ///   retry can re-dispatch the same request without a clone. Call
136    ///   [`Option::take`] on it only once this borrow has committed to
137    ///   answering — an `Err` counts as an answer — and never on a path that
138    ///   goes on to return `None`. A body taken and then declined reaches the
139    ///   exclusive path as `None`, where it surfaces as a spurious
140    ///   [`BodyExpected`](StructError::BodyExpected).
141    ///
142    /// A derived impl settles the whole-object listing before it writes or
143    /// invokes anything, through
144    /// [`repe_listing_declines`](Self::repe_listing_declines) — because a
145    /// decline discovered later would leave the entries before it run twice,
146    /// once here and once on the exclusive retry, and a rewind cannot undo a
147    /// call. A hand-written impl that invokes anything before it can decide owes
148    /// the same care.
149    fn repe_shared_into(
150        &self,
151        segments: &[&str],
152        body: &mut Option<Value>,
153        out: &mut ResponseBody<'_>,
154    ) -> Option<StructResult<()>> {
155        let _ = (segments, body, out);
156        None
157    }
158
159    /// Whether a shared whole-object listing of this struct declines — asked
160    /// **before** the listing writes or invokes anything.
161    ///
162    /// A listing is the one read that composes many others, so a decline
163    /// discovered partway through is not recoverable: the exclusive retry
164    /// re-runs the entries before it, and an entry that was *invoked* rather
165    /// than serialized runs a second time. Rewinding the response buffer undoes
166    /// the bytes; it cannot undo a call.
167    ///
168    /// So the answer has to be available at the top, and it has to cover the
169    /// whole subtree — a parent's listing composes its children's, so a child
170    /// that declines takes the parent's listing with it. That is why this is on
171    /// [`RepeStruct`] rather than only on
172    /// [`RepeMethods::REPE_LISTING_NEEDS_EXCLUSIVE`], which answers the same
173    /// question about one method table's accessors and nothing beneath them. A
174    /// derived impl returns that const OR'd with every `#[repe(nested)]` child's
175    /// answer, so the whole tree is settled before the first byte is written.
176    ///
177    /// The default is `true`, which is the accurate answer for the default
178    /// [`repe_shared_into`](Self::repe_shared_into): it declines every path,
179    /// listings included. A hand-written impl that overrides `repe_shared_into`
180    /// to serve a listing should override this too, or every derived struct
181    /// nesting it gives up its own shared listing.
182    ///
183    /// **Overriding it is a promise**, and it is the promise the invariant rests
184    /// on: returning `false` asserts that `repe_shared_into(&[], &mut None, ..)`
185    /// answers `Some(..)`. Breaking it still yields a correct response — the listing
186    /// rewinds and the exclusive path retries — but anything the shared attempt
187    /// had already invoked runs twice.
188    fn repe_listing_declines(&self) -> bool {
189        true
190    }
191
192    /// Whether any path can answer a **body-carrying** frame through
193    /// [`repe_shared_into`](Self::repe_shared_into).
194    ///
195    /// The router asks before it takes the read lock. REPE puts a body on a
196    /// write *and* on a call with arguments, so a body alone cannot say which
197    /// one arrived — but a struct whose every write needs `&mut self` knows the
198    /// answer for all of them in advance, and `false` lets the router skip the
199    /// lock, the walk and the certain decline.
200    ///
201    /// This is a hint, and it cannot cost correctness. Everything the shared
202    /// borrow answers with a body, the exclusive path answers identically: a
203    /// `&self` method is callable through either, and every refusal
204    /// ([`BodyUnexpected`](StructError::BodyUnexpected) on a read-only endpoint,
205    /// [`InvalidPath`](StructError::InvalidPath) on an unknown one) is generated
206    /// from the same shape on both sides. `false` on an impl that could have
207    /// served one costs concurrency for that frame and nothing else.
208    ///
209    /// The default is `true`, the accurate answer for a hand-written
210    /// `repe_shared_into` this crate cannot see inside. A derived impl narrows
211    /// it to `false` when nothing it generates can answer a body: no `&self`
212    /// method taking arguments, no read-only endpoint whose refusal is servable
213    /// shared, and no `#[repe(nested)]` child that has either.
214    const REPE_SHARED_SERVES_BODIES: bool = true;
215}
216
217/// A **conditionally-present** child: a component that is not in every build, a
218/// subsystem that is not configured, a resource that failed to open.
219///
220/// `Option` is a foreign type and [`RepeStruct`] is this crate's trait, so a
221/// host cannot write this impl itself — its choices without one are a newtype
222/// per crate or one impl per concrete `Option<Child>`. Carrying it here is what
223/// lets `#[repe(nested)]` be put on an `Option<T>` field directly, which is
224/// where a host reaches for it first.
225///
226/// Present forwards everything to the inner value. Absent answers:
227///
228/// * a **read at the child's own path** with `null`, so a whole-object listing
229///   of the parent shows the key with nothing behind it rather than failing;
230/// * a **write, or any subpath** with [`StructError::InvalidPath`], because a
231///   silent no-op against a live resource is worse than an error — a client
232///   that configured an absent component would otherwise be told it succeeded;
233/// * [`repe_listing_declines`](RepeStruct::repe_listing_declines) with `false`
234///   when absent, since a `null` needs no exclusive borrow, and with the inner
235///   value's own answer when present.
236///
237/// **Presence is the host's, not the client's.** A `null` written at the child's
238/// own path is refused with [`StructError::BodyUnexpected`] whether the child is
239/// there or not, so the one value this path can read back is the one value it
240/// will not take. Removing a child would otherwise be a door that only opens one
241/// way, since creating one is the write an absent child already refuses. A
242/// whole-object write at the *parent* replaces the field, `null` included; that
243/// is a replace of the parent rather than a write to this path.
244///
245/// This matches what Glaze publishes for an unmapped optional member, so a
246/// port's wire shape does not change with the language.
247impl<T: RepeStruct> RepeStruct for Option<T> {
248    fn repe_handle(
249        &mut self,
250        segments: &[&str],
251        body: Option<Value>,
252    ) -> StructResult<Option<Value>> {
253        refuse_presence_write(segments, body.as_ref())?;
254        match self {
255            Some(inner) => inner.repe_handle(segments, body),
256            None => absent_child(segments, body.is_some()).map(|()| None),
257        }
258    }
259
260    fn repe_handle_into(
261        &mut self,
262        segments: &[&str],
263        body: Option<Value>,
264        out: &mut ResponseBody<'_>,
265    ) -> StructResult<()> {
266        refuse_presence_write(segments, body.as_ref())?;
267        match self {
268            Some(inner) => inner.repe_handle_into(segments, body, out),
269            None => {
270                absent_child(segments, body.is_some())?;
271                out.write_null();
272                Ok(())
273            }
274        }
275    }
276
277    fn repe_shared_into(
278        &self,
279        segments: &[&str],
280        body: &mut Option<Value>,
281        out: &mut ResponseBody<'_>,
282    ) -> Option<StructResult<()>> {
283        // Refusing touches nothing, so it needs no exclusive borrow — and it has
284        // to be decided here rather than left to the retry, or a present child
285        // would forward the `null` to its inner value under both guards.
286        if let Err(err) = refuse_presence_write(segments, body.as_ref()) {
287            return Some(Err(err));
288        }
289        match self {
290            Some(inner) => inner.repe_shared_into(segments, body, out),
291            // Absent is a constant: no state to borrow exclusively, so every
292            // answer above is servable here and none of them touches `body`.
293            None => Some(absent_child(segments, body.is_some()).map(|()| out.write_null())),
294        }
295    }
296
297    fn repe_listing_declines(&self) -> bool {
298        match self {
299            Some(inner) => inner.repe_listing_declines(),
300            None => false,
301        }
302    }
303
304    /// A present child answers for itself. An absent one refuses every write
305    /// and every sub-path, and refuses them identically on both borrows, so it
306    /// contributes nothing the exclusive path would not also say.
307    const REPE_SHARED_SERVES_BODIES: bool = T::REPE_SHARED_SERVES_BODIES;
308}
309
310/// Refuse a `null` written at an optional child's **own** path, present or
311/// absent.
312///
313/// `null` is what that path *reads* when the child is absent, so a client will
314/// try writing it back, and without this it lands on whichever branch happens to
315/// be live: a present child forwards it to its inner value and answers with that
316/// type's serde complaint, an absent one answers `InvalidPath`. Neither says
317/// what is actually true, which is that presence is not settable here.
318///
319/// It is refused rather than honoured because honouring it would open a one-way
320/// door: `null` could remove a child, and nothing could put it back — creating
321/// one is the write an absent child already refuses, for the reason that a
322/// client configuring something that is not there must not be told it worked.
323/// Presence belongs to the host on both sides of that. A whole-object write at
324/// the *parent* still replaces the field, `null` included; that is a replace of
325/// the parent, not a write to this path.
326fn refuse_presence_write(segments: &[&str], body: Option<&Value>) -> StructResult<()> {
327    if segments.is_empty() && matches!(body, Some(Value::Null)) {
328        return Err(StructError::BodyUnexpected {
329            path: path_from_segments(segments),
330        });
331    }
332    Ok(())
333}
334
335/// The absent half of [`RepeStruct for Option<T>`](RepeStruct#impl-RepeStruct-for-Option<T>):
336/// `Ok(())` for the one request an absent child can answer, and
337/// [`StructError::InvalidPath`] for the rest.
338///
339/// The path is relative to the child, so a parent's
340/// [`prepend_path`] names the field the client actually asked for.
341fn absent_child(segments: &[&str], has_body: bool) -> StructResult<()> {
342    if segments.is_empty() && !has_body {
343        Ok(())
344    } else {
345        Err(StructError::InvalidPath {
346            path: path_from_segments(segments),
347        })
348    }
349}
350
351/// Method table for a struct whose methods are declared with `#[repe::methods]`
352/// on an inherent `impl` block.
353///
354/// Generated by the attribute macro, which sees every signature in the block and
355/// so cannot fall behind the type the way a hand-maintained
356/// `#[repe(methods(..))]` list can. `#[derive(RepeStruct)]` dispatches path
357/// segments that match no field through this table when the struct carries the
358/// `#[repe(methods)]` marker.
359///
360/// Implementing this by hand is supported but unusual; the macro exists so the
361/// signatures stay derived from the `impl` block.
362#[diagnostic::on_unimplemented(
363    message = "`{Self}` declares `#[repe(methods)]` but its impl block is not annotated",
364    label = "no method table for `{Self}`",
365    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"
366)]
367pub trait RepeMethods: MethodsDeclared {
368    /// `(endpoint, signature)` pairs published in the whole-struct listing.
369    const REPE_METHOD_SIGNATURES: &'static [(&'static str, &'static str)];
370
371    /// Endpoints in this table that are **field-shaped**: served by a
372    /// getter/setter pair (`#[repe(get = "...")]` / `#[repe(set = "...")]`)
373    /// rather than by an argument list.
374    ///
375    /// They are deliberately absent from
376    /// [`REPE_METHOD_SIGNATURES`](Self::REPE_METHOD_SIGNATURES), because they
377    /// have no signature to publish: a client reads and writes one the way it
378    /// reads and writes a field, so the whole-struct listing shows each one's
379    /// current value rather than a signature string. The derived listing reads
380    /// those values back through [`repe_call`](Self::repe_call), or through
381    /// [`repe_call_shared_into`](Self::repe_call_shared_into) when it is being
382    /// served under a shared borrow.
383    ///
384    /// Defaults to empty, so a hand-written impl need not mention it. One
385    /// invariant comes with listing a name here, and the derived listing relies
386    /// on it: [`repe_call`](Self::repe_call) must answer
387    /// `segments = &[name], body = None` with `Ok(Some(value))`. A name the
388    /// table cannot dispatch turns every whole-struct read into that name's
389    /// error. `#[repe::methods]` upholds it by construction, because it emits
390    /// this list from the getters it generated arms for. The shared-borrow
391    /// listing asks the same question of `repe_call_shared_into`, where a `None`
392    /// is not a failure — it declines the whole listing to the exclusive path.
393    const REPE_ACCESSOR_ENDPOINTS: &'static [&'static str] = &[];
394
395    /// `true` only on the placeholder table `#[repe::methods]` emits when the
396    /// block itself failed to parse.
397    ///
398    /// That table publishes nothing, so every compile-time check against it
399    /// would fire and bury the real error under a second, misleading one. This
400    /// says "these tables are not the truth" so those checks can stand down —
401    /// which emptiness alone cannot say, because a block that compiles and
402    /// publishes nothing is empty too, and its checks must still run.
403    #[doc(hidden)]
404    const REPE_TABLE_RECOVERED: bool = false;
405
406    /// Whether the whole-struct listing must be served exclusively because some
407    /// entry in it can only be read through `&mut self`.
408    ///
409    /// This is the one question the shared listing has to settle **before** it
410    /// runs anything, and it is why it is a `const` rather than a check per
411    /// entry. A listing is the one read that composes many others; a decline
412    /// discovered partway through leaves the entries before it already invoked,
413    /// and the exclusive retry invokes them again. A `&self` getter over a read
414    /// counter would report the second call.
415    ///
416    /// Only the getter half of a field-shaped endpoint can force it. Fields
417    /// serialize, published signatures are string literals, and a nested child
418    /// declines before writing anything of its own — none of those is a *call*.
419    /// So this is `true` exactly when some accessor's getter takes `&mut self`.
420    ///
421    /// The default is the conservative one: any accessor at all forces the
422    /// exclusive path, which is what a hand-written table gets for free and what
423    /// this crate did for every table before the receiver was carried here.
424    /// `#[repe::methods]` overrides it with the answer it computed from the
425    /// receivers it has already seen, so a struct whose computed values are pure
426    /// reads keeps its shared listing — and so does every ancestor that nests
427    /// it, since a child's decline propagates.
428    ///
429    /// **Overriding it is a promise.** Setting it to `false` asserts that
430    /// [`repe_call_shared_into`](Self::repe_call_shared_into) answers
431    /// `segments = &[name], body = None` with `Some(..)` for every name in
432    /// [`REPE_ACCESSOR_ENDPOINTS`](Self::REPE_ACCESSOR_ENDPOINTS). A table that
433    /// breaks that promise still produces a correct response — the listing
434    /// rewinds and retries exclusively — but the getters that ran before the
435    /// decline run a second time, which is the double invocation this const
436    /// exists to rule out.
437    const REPE_LISTING_NEEDS_EXCLUSIVE: bool = !Self::REPE_ACCESSOR_ENDPOINTS.is_empty();
438
439    /// Whether any endpoint in this table can answer a body-carrying frame
440    /// through [`repe_call_shared_into`](Self::repe_call_shared_into).
441    ///
442    /// The table half of
443    /// [`RepeStruct::REPE_SHARED_SERVES_BODIES`], which ORs this with what the
444    /// struct's own fields and children say. Three shapes here can answer one: a
445    /// `&self` method that takes arguments, a `&self` setter, and a read-only
446    /// accessor, whose refusal needs no exclusive borrow to give.
447    ///
448    /// The default is `true`, which is never wrong — only, for a table that
449    /// serves no body, slower than it needs to be.
450    const REPE_SHARED_SERVES_BODIES: bool = true;
451
452    /// Invoke the method named by `segments[0]`.
453    ///
454    /// `segments` is the remaining path relative to the struct root, so error
455    /// paths match the ones [`RepeStruct::repe_handle`] produces for fields.
456    /// Returns [`StructError::InvalidPath`] when no method matches.
457    fn repe_call(&mut self, segments: &[&str], body: Option<Value>) -> StructResult<Option<Value>>;
458
459    /// Encode-in-place counterpart of [`repe_call`](Self::repe_call), mirroring
460    /// [`RepeStruct::repe_handle_into`].
461    fn repe_call_into(
462        &mut self,
463        segments: &[&str],
464        body: Option<Value>,
465        out: &mut ResponseBody<'_>,
466    ) -> StructResult<()> {
467        let value = self.repe_call(segments, body)?;
468        write_optional(out, segments, value)
469    }
470
471    /// Shared-borrow counterpart of [`repe_call_into`](Self::repe_call_into),
472    /// mirroring [`RepeStruct::repe_shared_into`] and carrying the same three
473    /// obligations: answer identically, decline without writing, and leave
474    /// `body` in place when declining.
475    ///
476    /// `#[repe::methods]` serves every `&self` method here — including one
477    /// taking arguments, which is a call rather than a mutation however the
478    /// frame is shaped — along with the getter half of a `&self` accessor, and
479    /// declines everything else.
480    fn repe_call_shared_into(
481        &self,
482        segments: &[&str],
483        body: &mut Option<Value>,
484        out: &mut ResponseBody<'_>,
485    ) -> Option<StructResult<()>> {
486        let _ = (segments, body, out);
487        None
488    }
489}
490
491/// Marker emitted by `#[derive(RepeStruct)]` when the struct carries the
492/// `#[repe(methods)]` attribute.
493///
494/// A derive macro cannot see `impl` blocks, so the two halves of the
495/// `#[repe::methods]` surface are tied together by a compile-time handshake.
496/// This marker is a supertrait of [`RepeMethods`], so the table the attribute
497/// macro generates simply cannot be implemented for a struct that did not
498/// declare it — no assertion to emit, and none to forget. Missing either half is
499/// a compile error naming the attribute that is absent, rather than a method
500/// that quietly never reaches the wire.
501#[diagnostic::on_unimplemented(
502    message = "`{Self}` has an annotated `methods` impl block but does not declare it",
503    label = "`{Self}` is missing `#[repe(methods)]`",
504    note = "add `#[repe(methods)]` next to `#[derive(RepeStruct)]` on `{Self}` so the derived router dispatches to the impl block"
505)]
506pub trait MethodsDeclared {}
507
508/// Build a path string from segments for error messages.
509pub fn path_from_segments(segments: &[&str]) -> String {
510    if segments.is_empty() {
511        String::from("")
512    } else {
513        let mut s = String::new();
514        for segment in segments {
515            s.push('/');
516            s.push_str(segment);
517        }
518        s
519    }
520}
521
522/// Prefix error paths with an additional segment when bubbling errors from nested structs.
523pub fn prepend_path(mut err: StructError, prefix: &str) -> StructError {
524    let with_prefix = |path: String| {
525        if prefix.is_empty() {
526            path
527        } else if path.is_empty() {
528            format!("/{}", prefix)
529        } else if path.starts_with('/') {
530            format!("/{prefix}{path}")
531        } else {
532            format!("/{prefix}/{path}")
533        }
534    };
535
536    match &mut err {
537        StructError::InvalidPath { path }
538        | StructError::InvalidSubpath { path }
539        | StructError::BodyExpected { path }
540        | StructError::BodyUnexpected { path }
541        | StructError::Serialize { path, .. }
542        | StructError::Deserialize { path, .. }
543        | StructError::Execution { path, .. } => {
544            *path = with_prefix(std::mem::take(path));
545        }
546    }
547    err
548}
549
550/// Response body under construction for a [`RepeStruct`] read.
551///
552/// Handed to [`RepeStruct::repe_handle_into`] so a read serializes the live field
553/// straight into the outgoing frame buffer. The alternative — returning a
554/// [`serde_json::Value`] that the router then re-serializes — allocates an
555/// intermediate tree per read, which is what a client polling a wide object at
556/// kilohertz pays for.
557///
558/// The body starts out empty and [`BodyFormat::Json`]; the write that fills it
559/// also settles the format, so a [`write_typed_slice`](Self::write_typed_slice)
560/// body reports [`BodyFormat::Beve`]. Exactly one top-level write is expected —
561/// a value, a null, or an [`object`](Self::object).
562///
563/// Any failed write — including one that fails partway through an
564/// [`object`](Self::object) — rewinds the buffer to where that write began, so a
565/// caller that recovers from a [`StructError`] never ships half-serialized
566/// bytes.
567pub struct ResponseBody<'a> {
568    buf: &'a mut Vec<u8>,
569    format: BodyFormat,
570    /// True while this body is a value *inside* an enclosing JSON object, where
571    /// the frame format is already committed to JSON.
572    ///
573    /// Reached from generated code by exactly one path: the whole-struct listing
574    /// writes each accessor endpoint's value through
575    /// [`ObjectBody::entry_with`] or [`ObjectBody::entry_try_with`], so a
576    /// `#[repe(typed)]` getter listed inside the object emits a JSON array
577    /// rather than switching the enclosing frame to BEVE. (A `#[repe(nested)]`
578    /// field also gets a nested body, but its child is always entered with empty
579    /// segments and so always takes its own object branch.) The flag also covers
580    /// hand-written `repe_handle_into` impls, which can call anything from
581    /// anywhere; a JSON-array fallback beats corrupting the frame.
582    nested: bool,
583}
584
585impl<'a> ResponseBody<'a> {
586    /// Wrap an output buffer. `buf` is normally empty; writes append to it.
587    pub fn new(buf: &'a mut Vec<u8>) -> Self {
588        Self {
589            buf,
590            format: BodyFormat::Json,
591            nested: false,
592        }
593    }
594
595    /// The body format settled by the write that filled this body.
596    pub fn format(&self) -> BodyFormat {
597        self.format
598    }
599
600    /// Serialize `value` as the whole body, as JSON.
601    ///
602    /// `path` names the field for the error message and is only read when
603    /// serialization fails.
604    pub fn write<T>(&mut self, path: &str, value: &T) -> StructResult<()>
605    where
606        T: Serialize + ?Sized,
607    {
608        self.write_with_path(|| String::from(path), value)
609    }
610
611    /// [`write`](Self::write) with the error path built only if one is needed.
612    ///
613    /// The derived arms pass a `&'static str` literal and pay nothing either
614    /// way, but the [`RepeStruct::repe_handle_into`] default has to *assemble*
615    /// its path from the segments — on every successful read, for a string it
616    /// then throws away.
617    fn write_with_path<T, F>(&mut self, path: F, value: &T) -> StructResult<()>
618    where
619        T: Serialize + ?Sized,
620        F: FnOnce() -> String,
621    {
622        let start = self.buf.len();
623        match serde_json::to_writer(&mut *self.buf, value) {
624            Ok(()) => Ok(()),
625            Err(source) => {
626                self.buf.truncate(start);
627                Err(StructError::Serialize {
628                    path: path(),
629                    source,
630                })
631            }
632        }
633    }
634
635    /// Write a JSON `null` body — the response to a write, or to a read that has
636    /// nothing to return.
637    pub fn write_null(&mut self) {
638        self.buf.extend_from_slice(b"null");
639    }
640
641    /// Write `slice` as a BEVE typed numeric array and set the body format to
642    /// [`BodyFormat::Beve`].
643    ///
644    /// The same bulk encode `repe::message::MessageBuilder::body_typed_slice`
645    /// produces — one `copy_nonoverlapping` on little-endian targets rather than
646    /// a per-element serde walk, and byte-identical to what Glaze emits for the
647    /// same array. This is what `#[repe(typed)]` routes a numeric field to.
648    /// (Named rather than linked: the builder lives in `repe`, which this crate
649    /// deliberately does not depend on.)
650    ///
651    /// Inside an enclosing object — the whole-struct listing — the frame is
652    /// already committed to JSON, so the slice is written as a JSON array
653    /// instead. A field only reaches the typed encoding when it is read on its
654    /// own.
655    pub fn write_typed_slice<T>(&mut self, path: &str, slice: &[T]) -> StructResult<()>
656    where
657        T: beve::BeveTypedSlice + Serialize,
658    {
659        if self.nested {
660            return self.write(path, slice);
661        }
662        let encoded_len = beve::typed_slice_size(slice) as usize;
663        self.buf.reserve(encoded_len);
664        let start = self.buf.len();
665        beve::to_writer_typed_slice(&mut *self.buf, slice)
666            .expect("writing a typed slice into a Vec is infallible");
667        debug_assert_eq!(self.buf.len() - start, encoded_len);
668        self.format = BodyFormat::Beve;
669        Ok(())
670    }
671
672    /// Begin a JSON object body, written key by key.
673    ///
674    /// Used by the whole-struct listing so a wide object is emitted in one pass
675    /// instead of through a [`serde_json::Map`].
676    pub fn object(&mut self) -> ObjectBody<'_> {
677        let start = self.buf.len();
678        self.buf.push(b'{');
679        ObjectBody {
680            buf: self.buf,
681            start,
682            first: true,
683        }
684    }
685}
686
687/// A JSON object body being written key by key. Created by
688/// [`ResponseBody::object`]; call [`finish`](Self::finish) to close it.
689///
690/// An entry that fails — or that [`entry_try_with`](Self::entry_try_with)
691/// declines — rewinds the buffer past the opening brace, so a partly written
692/// object is never left behind for a caller that recovers from it. Dropping
693/// without calling [`finish`](Self::finish) is the same situation and leaves
694/// nothing behind either, since both ways out without finishing have already
695/// rewound.
696pub struct ObjectBody<'a> {
697    buf: &'a mut Vec<u8>,
698    /// Buffer length before the opening brace, to rewind to on failure.
699    start: usize,
700    first: bool,
701}
702
703impl ObjectBody<'_> {
704    fn key(&mut self, key: &str) -> StructResult<()> {
705        if self.first {
706            self.first = false;
707        } else {
708            self.buf.push(b',');
709        }
710        serde_json::to_writer(&mut *self.buf, key).map_err(|source| StructError::Serialize {
711            path: format!("/{key}"),
712            source,
713        })?;
714        self.buf.push(b':');
715        Ok(())
716    }
717
718    /// Run one entry, rewinding the whole object if it fails.
719    fn entry_with_rewind<F>(&mut self, f: F) -> StructResult<()>
720    where
721        F: FnOnce(&mut Self) -> StructResult<()>,
722    {
723        match f(self) {
724            Ok(()) => Ok(()),
725            Err(err) => {
726                self.buf.truncate(self.start);
727                Err(err)
728            }
729        }
730    }
731
732    /// Write one `"key": value` entry.
733    pub fn entry<T>(&mut self, key: &str, value: &T) -> StructResult<()>
734    where
735        T: Serialize + ?Sized,
736    {
737        self.entry_with_rewind(|this| {
738            this.key(key)?;
739            serde_json::to_writer(&mut *this.buf, value).map_err(|source| StructError::Serialize {
740                path: format!("/{key}"),
741                source,
742            })
743        })
744    }
745
746    /// Write one `"key": <value>` entry whose value is produced by `f`, for a
747    /// nested [`RepeStruct`] that fills the body itself.
748    ///
749    /// The body handed to `f` is marked as nested: the enclosing frame is
750    /// already JSON, so a [`ResponseBody::write_typed_slice`] inside it falls
751    /// back to a JSON array rather than switching the frame to BEVE.
752    pub fn entry_with<F>(&mut self, key: &str, f: F) -> StructResult<()>
753    where
754        F: FnOnce(&mut ResponseBody<'_>) -> StructResult<()>,
755    {
756        self.entry_with_rewind(|this| {
757            this.key(key)?;
758            let mut body = ResponseBody {
759                buf: this.buf,
760                format: BodyFormat::Json,
761                nested: true,
762            };
763            f(&mut body)
764        })
765    }
766
767    /// [`entry_with`](Self::entry_with) for a value the source may decline to
768    /// produce, as [`RepeStruct::repe_shared_into`] declines a path that needs
769    /// exclusive access.
770    ///
771    /// `None` rewinds the whole object, exactly as an `Err` does, so a caller
772    /// that declines in turn leaves the buffer as it found it without a second
773    /// step. Dropping the object without calling [`finish`](Self::finish) then
774    /// leaves nothing behind, because the only ways out without finishing are
775    /// an error and a decline, and both have already rewound.
776    pub fn entry_try_with<F>(&mut self, key: &str, f: F) -> Option<StructResult<()>>
777    where
778        F: FnOnce(&mut ResponseBody<'_>) -> Option<StructResult<()>>,
779    {
780        let outcome = match self.key(key) {
781            Ok(()) => {
782                let mut body = ResponseBody {
783                    buf: self.buf,
784                    format: BodyFormat::Json,
785                    nested: true,
786                };
787                f(&mut body)
788            }
789            Err(err) => Some(Err(err)),
790        };
791        if !matches!(outcome, Some(Ok(()))) {
792            self.buf.truncate(self.start);
793        }
794        outcome
795    }
796
797    /// Close the object.
798    pub fn finish(self) {
799        self.buf.push(b'}');
800    }
801}
802
803/// Write the `Option<Value>` a [`RepeStruct::repe_handle`] returned as the whole
804/// body: the payload, or `null` when there is nothing to send.
805///
806/// Shared by the [`RepeStruct::repe_handle_into`] and
807/// [`RepeMethods::repe_call_into`] defaults, which differ only in which method
808/// they delegate to.
809fn write_optional(
810    out: &mut ResponseBody<'_>,
811    segments: &[&str],
812    value: Option<Value>,
813) -> StructResult<()> {
814    match value {
815        Some(value) => out.write_with_path(|| path_from_segments(segments), &value),
816        None => {
817            out.write_null();
818            Ok(())
819        }
820    }
821}
822
823/// Compile-time check that the three sets of endpoints on one struct do not
824/// overlap.
825///
826/// The two macros cannot see each other's input, so the derive emits a call to
827/// this against everything *it* publishes — fields, plus any method named in a
828/// struct-level `#[repe(methods(..))]` list — and the two generated
829/// [`RepeMethods`] tables. Without it a collision is silent and costly: one
830/// declaration wins dispatch, the other becomes permanently unreachable, and
831/// the whole-struct listing emits the same key twice. The two listings do not
832/// even agree on that last part, since a `serde_json::Map` deduplicates the key
833/// and the streaming encoder does not.
834///
835/// Collisions the macros *can* see on their own — two fields, two listed
836/// methods, a field against a listed method, two endpoints in one
837/// `#[repe::methods]` block — are rejected at macro time with a message naming
838/// the endpoint and pointing at the second declaration.
839///
840/// The third pairing, methods against accessors, is unreachable from a
841/// generated table for the same reason; it is checked because a hand-written
842/// [`RepeMethods`] impl can produce it.
843#[doc(hidden)]
844pub const fn assert_no_endpoint_collision(
845    declared: &[&str],
846    methods: &[(&str, &str)],
847    accessors: &[&str],
848) {
849    let mut i = 0;
850    while i < methods.len() {
851        if const_contains(declared, methods[i].0) {
852            panic!(
853                "a published method and an endpoint declared on the struct itself \
854                 share a name: the struct's declaration wins dispatch and the method could \
855                 never be called. Rename one with `#[repe(rename = \"...\")]`."
856            );
857        }
858        i += 1;
859    }
860
861    let mut i = 0;
862    while i < accessors.len() {
863        if const_contains(declared, accessors[i]) {
864            panic!(
865                "a `#[repe(get = \"...\")]` accessor and an endpoint declared on the struct \
866                 itself share a name: the struct's declaration wins dispatch and the accessor \
867                 could never be called. Rename the struct's with \
868                 `#[repe(rename = \"...\")]`, or give the accessor a different endpoint."
869            );
870        }
871
872        if listed_signature(methods, accessors[i]).is_some() {
873            panic!(
874                "a published method and a `#[repe(get = \"...\")]` accessor in the \
875                 same table share an endpoint name: one of them is unreachable, and the \
876                 whole-struct listing would show the endpoint twice."
877            );
878        }
879        i += 1;
880    }
881}
882
883/// Compile-time check that a `#[repe(listing_order(..))]` list names exactly the
884/// endpoints the struct publishes.
885///
886/// The derive validates the half it can see on its own — fields and struct-level
887/// `#[repe(methods(..))]` entries — with an error that names the offending key.
888/// It cannot see the `#[repe::methods]` impl block, so the other half is checked
889/// here, where both generated tables are in scope. A `const` panic cannot name
890/// the key, which is why the derive keeps everything it can reach at macro time.
891///
892/// Both directions matter. An order naming an endpoint that does not exist would
893/// emit a key whose value came from a failed dispatch; an order omitting one
894/// would silently drop it from every whole-object read, which is the harder bug
895/// to see because the endpoint still answers on its own path.
896#[doc(hidden)]
897pub const fn assert_listing_order(
898    order: &[&str],
899    declared: &[&str],
900    methods: &[(&str, &str)],
901    accessors: &[&str],
902    recovering: bool,
903) {
904    // `recovering` is [`RepeMethods::REPE_TABLE_RECOVERED`]: the block failed to
905    // parse, so the tables describe nothing and every key here would look
906    // unknown. This assertion would then be exactly the extra error that
907    // recovery exists to prevent. It must come from the marker rather than from
908    // the tables being empty — a block that compiles and publishes nothing is
909    // also empty, and an unknown key in *that* struct's order has to be caught
910    // here, because the derive skips its own check whenever an impl block is in
911    // play.
912    let mut i = 0;
913    while i < order.len() {
914        let known = const_contains(declared, order[i])
915            || const_contains(accessors, order[i])
916            || listed_signature(methods, order[i]).is_some();
917        if !known && !recovering {
918            panic!(
919                "`#[repe(listing_order(..))]` names a key that is not an endpoint on this \
920                 struct. It lists the whole-object listing's keys, so every name in it has to \
921                 be a field, a listed method, or an endpoint of the annotated `methods` impl block."
922            );
923        }
924        i += 1;
925    }
926
927    let mut j = 0;
928    while j < methods.len() {
929        if !const_contains(order, methods[j].0) {
930            panic!(
931                "a method on the annotated `methods` impl block is missing from `#[repe(listing_order(..))]`, \
932                 which names the whole-object listing's keys in full. An omitted endpoint \
933                 would disappear from every whole-object read while still answering on its \
934                 own path."
935            );
936        }
937        j += 1;
938    }
939
940    let mut j = 0;
941    while j < accessors.len() {
942        if !const_contains(order, accessors[j]) {
943            panic!(
944                "a `#[repe(get = \"...\")]` accessor is missing from \
945                 `#[repe(listing_order(..))]`, which names the whole-object listing's keys in \
946                 full. An omitted endpoint would disappear from every whole-object read while \
947                 still answering on its own path."
948            );
949        }
950        j += 1;
951    }
952}
953
954/// The published signature for `name`, or `None` when the name belongs to a
955/// field-shaped accessor instead.
956///
957/// Called from a `const` block in the ordered listing a
958/// `#[repe(listing_order(..))]` produces: the derive cannot see the
959/// `#[repe::methods]` block, so it does not know which of the two tables an
960/// ordered key came from, but the tables themselves are constants and the
961/// question folds away before run time.
962#[doc(hidden)]
963pub const fn listed_signature<'a>(methods: &[(&'a str, &'a str)], name: &str) -> Option<&'a str> {
964    let mut i = 0;
965    while i < methods.len() {
966        if const_str_eq(methods[i].0, name) {
967            return Some(methods[i].1);
968        }
969        i += 1;
970    }
971    None
972}
973
974/// `slice.contains(&name)` usable in a `const` context.
975const fn const_contains(list: &[&str], name: &str) -> bool {
976    let mut i = 0;
977    while i < list.len() {
978        if const_str_eq(list[i], name) {
979            return true;
980        }
981        i += 1;
982    }
983    false
984}
985
986/// Resolve path `segments` against a [`serde_json::Value`], for a
987/// `#[repe(nested_serde)]` field.
988///
989/// Objects are indexed by key and arrays by decimal position, matching RFC 6901
990/// evaluation; this takes already-split segments because the struct router has
991/// them in that form and the pointer string does not exist.
992///
993/// `None` means the path does not resolve, which the caller reports as
994/// [`StructError::InvalidPath`].
995pub fn serde_pointer<'a>(value: &'a Value, segments: &[&str]) -> Option<&'a Value> {
996    let mut cursor = value;
997    for segment in segments {
998        cursor = match cursor {
999            Value::Object(map) => map.get(*segment)?,
1000            Value::Array(items) => items.get(segment.parse::<usize>().ok()?)?,
1001            _ => return None,
1002        };
1003    }
1004    Some(cursor)
1005}
1006
1007/// The mutable counterpart of [`serde_pointer`], for a write below a
1008/// `#[repe(nested_serde)]` field.
1009///
1010/// `segments` must be non-empty: replacing the whole value is the caller's own
1011/// assignment, not a walk. Every segment, the last included, has to name
1012/// something that is **already there** — a key an object does not have is
1013/// rejected rather than inserted, because the value is about to be deserialized
1014/// back into a typed field where an invented key is either dropped or an error,
1015/// and a client that misspelled one deserves to hear about it here.
1016///
1017/// Contrast [`crate::structs`]' sibling in `repe`'s registry, `set_pointer`,
1018/// which deliberately *inserts* a missing object key: that one is building a
1019/// free-form document, this one is editing a value with a type. Do not unify
1020/// them.
1021pub fn serde_pointer_set(value: &mut Value, segments: &[&str], new: Value) -> Option<()> {
1022    if segments.is_empty() {
1023        return None;
1024    }
1025    let mut cursor = value;
1026    for segment in segments {
1027        cursor = match cursor {
1028            Value::Object(map) => map.get_mut(*segment)?,
1029            Value::Array(items) => items.get_mut(segment.parse::<usize>().ok()?)?,
1030            _ => return None,
1031        };
1032    }
1033    *cursor = new;
1034    Some(())
1035}
1036
1037/// `str` equality usable in a `const` context, which `PartialEq` is not.
1038const fn const_str_eq(a: &str, b: &str) -> bool {
1039    let (a, b) = (a.as_bytes(), b.as_bytes());
1040    if a.len() != b.len() {
1041        return false;
1042    }
1043    let mut i = 0;
1044    while i < a.len() {
1045        if a[i] != b[i] {
1046            return false;
1047        }
1048        i += 1;
1049    }
1050    true
1051}
1052
1053/// Decoder for the body of a struct method taking two or more arguments.
1054///
1055/// A single-argument method takes the request body *as* the argument, which is
1056/// the shape the wire has always had. Beyond one argument the body carries the
1057/// whole list, in either of two forms:
1058///
1059/// * a JSON/BEVE **array** of exactly N values, positionally, or
1060/// * an **object** keyed by parameter name, where a missing key decodes as
1061///   `null` (so an `Option<T>` parameter may be omitted).
1062///
1063/// Generated code names this, and a hand-written [`RepeMethods`] impl that
1064/// publishes a multi-argument method should too: it is what makes such a table
1065/// accept the same two body shapes a derived one does, instead of inventing a
1066/// third that no client of a derived struct would speak. That is why it is
1067/// public and documented rather than hidden — it carries a wire contract, not
1068/// an implementation detail.
1069pub struct MethodArgs<'a> {
1070    path: &'a str,
1071    names: &'a [&'a str],
1072    values: std::vec::IntoIter<Value>,
1073    index: usize,
1074}
1075
1076impl<'a> MethodArgs<'a> {
1077    /// Split `body` into the argument list for `names`.
1078    pub fn new(path: &'a str, names: &'a [&'a str], body: Value) -> StructResult<Self> {
1079        let values = match body {
1080            Value::Array(items) => {
1081                if items.len() != names.len() {
1082                    return Err(arg_error(
1083                        path,
1084                        format!("expected {} arguments, got {}", names.len(), items.len()),
1085                    ));
1086                }
1087                items
1088            }
1089            Value::Object(mut map) => names
1090                .iter()
1091                .map(|name| map.remove(*name).unwrap_or(Value::Null))
1092                .collect(),
1093            _ => {
1094                return Err(arg_error(
1095                    path,
1096                    format!(
1097                        "expected an array of {} arguments or an object with keys [{}]",
1098                        names.len(),
1099                        names.join(", ")
1100                    ),
1101                ));
1102            }
1103        };
1104        Ok(Self {
1105            path,
1106            names,
1107            values: values.into_iter(),
1108            index: 0,
1109        })
1110    }
1111
1112    /// Decode the next argument in declaration order.
1113    pub fn next_arg<T: DeserializeOwned>(&mut self) -> StructResult<T> {
1114        let name = self.names.get(self.index).copied().unwrap_or("?");
1115        self.index += 1;
1116        let value = self.values.next().unwrap_or(Value::Null);
1117        serde_json::from_value(value).map_err(|source| StructError::Deserialize {
1118            path: format!("{path}({name})", path = self.path),
1119            source,
1120        })
1121    }
1122}
1123
1124/// A `StructError::Deserialize` carrying a message of our own rather than one
1125/// from serde, so argument-shape complaints read like every other body error.
1126fn arg_error(path: &str, message: String) -> StructError {
1127    StructError::Deserialize {
1128        path: path.to_string(),
1129        source: <serde_json::Error as serde::de::Error>::custom(message),
1130    }
1131}