repe 8.1.0

Rust implementation of the REPE RPC protocol (JSON-focused)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
use crate::constants::{BodyFormat, ErrorCode};
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::Value;
/// Errors produced while handling struct-backed endpoints.
#[derive(Debug, thiserror::Error)]
pub enum StructError {
    #[error("invalid path `{path}`")]
    InvalidPath { path: String },
    #[error("unexpected additional path segments at `{path}`")]
    InvalidSubpath { path: String },
    #[error("body required for `{path}`")]
    BodyExpected { path: String },
    #[error("body not allowed for `{path}`")]
    BodyUnexpected { path: String },
    #[error("serialization error for `{path}`: {source}")]
    Serialize {
        path: String,
        #[source]
        source: serde_json::Error,
    },
    #[error("deserialization error for `{path}`: {source}")]
    Deserialize {
        path: String,
        #[source]
        source: serde_json::Error,
    },
    #[error("method `{path}` failed: {message}")]
    Execution { path: String, message: String },
}

impl StructError {
    pub fn code(&self) -> ErrorCode {
        match self {
            StructError::InvalidPath { .. } | StructError::InvalidSubpath { .. } => {
                ErrorCode::MethodNotFound
            }
            StructError::BodyExpected { .. } | StructError::BodyUnexpected { .. } => {
                ErrorCode::InvalidBody
            }
            StructError::Serialize { .. } | StructError::Deserialize { .. } => {
                ErrorCode::InvalidBody
            }
            StructError::Execution { .. } => ErrorCode::ParseError,
        }
    }
}

/// Convenience alias for results returned by struct handlers.
pub type StructResult<T> = Result<T, StructError>;

/// Trait implemented by structs that can be exposed directly through the REPE router.
///
/// The implementation should interpret the provided JSON Pointer path segments and
/// either return a JSON value (for reads) or mutate the struct (for writes).
pub trait RepeStruct: Send + Sync {
    /// Handle a read or write against this struct.
    ///
    /// * `segments` – JSON Pointer path split into unescaped segments.
    /// * `body` – `Some(value)` when the request contains a JSON body, `None` for reads.
    ///
    /// Return `Ok(Some(value))` to send a JSON response payload, `Ok(None)` to send `null`.
    fn repe_handle(
        &mut self,
        segments: &[&str],
        body: Option<Value>,
    ) -> StructResult<Option<Value>>;

    /// Encode-in-place counterpart of [`repe_handle`](Self::repe_handle): write the
    /// response body straight into `out` instead of returning an owned
    /// [`serde_json::Value`] for the caller to re-serialize.
    ///
    /// This is the method the router calls. The default implementation delegates
    /// to [`repe_handle`](Self::repe_handle) and encodes whatever it returns, so a
    /// hand-written impl only needs `repe_handle`; `#[derive(RepeStruct)]`
    /// overrides it so a leaf read serializes the live field directly into the
    /// outgoing frame buffer with no intermediate `Value`.
    ///
    /// Writes are unaffected — a request body still arrives as a `Value`.
    ///
    /// [`repe_handle`]: Self::repe_handle
    fn repe_handle_into(
        &mut self,
        segments: &[&str],
        body: Option<Value>,
        out: &mut ResponseBody<'_>,
    ) -> StructResult<()> {
        let value = self.repe_handle(segments, body)?;
        write_optional(out, segments, value)
    }
}

/// Method table for a struct whose methods are declared with `#[repe::methods]`
/// on an inherent `impl` block.
///
/// Generated by the attribute macro, which sees every signature in the block and
/// so cannot fall behind the type the way a hand-maintained
/// `#[repe(methods(..))]` list can. `#[derive(RepeStruct)]` dispatches path
/// segments that match no field through this table when the struct carries the
/// `#[repe(methods)]` marker.
///
/// Implementing this by hand is supported but unusual; the macro exists so the
/// signatures stay derived from the `impl` block.
#[diagnostic::on_unimplemented(
    message = "`{Self}` declares `#[repe(methods)]` but has no `#[repe::methods]` impl block",
    label = "no method table for `{Self}`",
    note = "annotate the inherent `impl {Self}` block with `#[repe::methods]`, or drop `#[repe(methods)]` from the struct"
)]
pub trait RepeMethods: MethodsDeclared {
    /// `(endpoint, signature)` pairs published in the whole-struct listing.
    const REPE_METHOD_SIGNATURES: &'static [(&'static str, &'static str)];

    /// Invoke the method named by `segments[0]`.
    ///
    /// `segments` is the remaining path relative to the struct root, so error
    /// paths match the ones [`RepeStruct::repe_handle`] produces for fields.
    /// Returns [`StructError::InvalidPath`] when no method matches.
    fn repe_call(&mut self, segments: &[&str], body: Option<Value>) -> StructResult<Option<Value>>;

    /// Encode-in-place counterpart of [`repe_call`](Self::repe_call), mirroring
    /// [`RepeStruct::repe_handle_into`].
    fn repe_call_into(
        &mut self,
        segments: &[&str],
        body: Option<Value>,
        out: &mut ResponseBody<'_>,
    ) -> StructResult<()> {
        let value = self.repe_call(segments, body)?;
        write_optional(out, segments, value)
    }
}

/// Marker emitted by `#[derive(RepeStruct)]` when the struct carries the
/// `#[repe(methods)]` attribute.
///
/// A derive macro cannot see `impl` blocks, so the two halves of the
/// `#[repe::methods]` surface are tied together by a compile-time handshake.
/// This marker is a supertrait of [`RepeMethods`], so the table the attribute
/// macro generates simply cannot be implemented for a struct that did not
/// declare it — no assertion to emit, and none to forget. Missing either half is
/// a compile error naming the attribute that is absent, rather than a method
/// that quietly never reaches the wire.
#[diagnostic::on_unimplemented(
    message = "`{Self}` has a `#[repe::methods]` impl block but does not declare it",
    label = "`{Self}` is missing `#[repe(methods)]`",
    note = "add `#[repe(methods)]` next to `#[derive(RepeStruct)]` on `{Self}` so the derived router dispatches to the impl block"
)]
pub trait MethodsDeclared {}

/// Build a fully-qualified child path from the current path segments.
pub fn join_path(current: &[&str], segment: &str) -> String {
    if current.is_empty() {
        format!("/{}", segment)
    } else {
        let mut s = String::new();
        for part in current {
            s.push('/');
            s.push_str(part);
        }
        s.push('/');
        s.push_str(segment);
        s
    }
}

/// Build a path string from segments for error messages.
pub fn path_from_segments(segments: &[&str]) -> String {
    if segments.is_empty() {
        String::from("")
    } else {
        let mut s = String::new();
        for segment in segments {
            s.push('/');
            s.push_str(segment);
        }
        s
    }
}

/// Prefix error paths with an additional segment when bubbling errors from nested structs.
pub fn prepend_path(mut err: StructError, prefix: &str) -> StructError {
    let with_prefix = |path: String| {
        if prefix.is_empty() {
            path
        } else if path.is_empty() {
            format!("/{}", prefix)
        } else if path.starts_with('/') {
            format!("/{prefix}{path}")
        } else {
            format!("/{prefix}/{path}")
        }
    };

    match &mut err {
        StructError::InvalidPath { path }
        | StructError::InvalidSubpath { path }
        | StructError::BodyExpected { path }
        | StructError::BodyUnexpected { path }
        | StructError::Serialize { path, .. }
        | StructError::Deserialize { path, .. }
        | StructError::Execution { path, .. } => {
            *path = with_prefix(std::mem::take(path));
        }
    }
    err
}

/// Response body under construction for a [`RepeStruct`] read.
///
/// Handed to [`RepeStruct::repe_handle_into`] so a read serializes the live field
/// straight into the outgoing frame buffer. The alternative — returning a
/// [`serde_json::Value`] that the router then re-serializes — allocates an
/// intermediate tree per read, which is what a client polling a wide object at
/// kilohertz pays for.
///
/// The body starts out empty and [`BodyFormat::Json`]; the write that fills it
/// also settles the format, so a [`write_typed_slice`](Self::write_typed_slice)
/// body reports [`BodyFormat::Beve`]. Exactly one top-level write is expected —
/// a value, a null, or an [`object`](Self::object).
///
/// Any failed write — including one that fails partway through an
/// [`object`](Self::object) — rewinds the buffer to where that write began, so a
/// caller that recovers from a [`StructError`] never ships half-serialized
/// bytes.
pub struct ResponseBody<'a> {
    buf: &'a mut Vec<u8>,
    format: BodyFormat,
    /// True while this body is a value *inside* an enclosing JSON object, where
    /// the frame format is already committed to JSON.
    ///
    /// Unreachable from generated code: the derive only hands out a nested body
    /// for a `#[repe(nested)]` field, whose child is always entered with empty
    /// segments and so always takes its own object branch. The flag is here for
    /// hand-written `repe_handle_into` impls, which can call anything from
    /// anywhere; a JSON-array fallback beats corrupting the frame.
    nested: bool,
}

impl<'a> ResponseBody<'a> {
    /// Wrap an output buffer. `buf` is normally empty; writes append to it.
    pub fn new(buf: &'a mut Vec<u8>) -> Self {
        Self {
            buf,
            format: BodyFormat::Json,
            nested: false,
        }
    }

    /// The body format settled by the write that filled this body.
    pub fn format(&self) -> BodyFormat {
        self.format
    }

    /// Serialize `value` as the whole body, as JSON.
    ///
    /// `path` names the field for the error message and is only read when
    /// serialization fails.
    pub fn write<T>(&mut self, path: &str, value: &T) -> StructResult<()>
    where
        T: Serialize + ?Sized,
    {
        self.write_with_path(|| String::from(path), value)
    }

    /// [`write`](Self::write) with the error path built only if one is needed.
    ///
    /// The derived arms pass a `&'static str` literal and pay nothing either
    /// way, but the [`RepeStruct::repe_handle_into`] default has to *assemble*
    /// its path from the segments — on every successful read, for a string it
    /// then throws away.
    fn write_with_path<T, F>(&mut self, path: F, value: &T) -> StructResult<()>
    where
        T: Serialize + ?Sized,
        F: FnOnce() -> String,
    {
        let start = self.buf.len();
        match serde_json::to_writer(&mut *self.buf, value) {
            Ok(()) => Ok(()),
            Err(source) => {
                self.buf.truncate(start);
                Err(StructError::Serialize {
                    path: path(),
                    source,
                })
            }
        }
    }

    /// Write a JSON `null` body — the response to a write, or to a read that has
    /// nothing to return.
    pub fn write_null(&mut self) {
        self.buf.extend_from_slice(b"null");
    }

    /// Write `slice` as a BEVE typed numeric array and set the body format to
    /// [`BodyFormat::Beve`].
    ///
    /// The bulk encode behind
    /// [`MessageBuilder::body_typed_slice`](crate::message::MessageBuilder::body_typed_slice):
    /// one `copy_nonoverlapping` on little-endian targets rather than a
    /// per-element serde walk, and byte-identical to what Glaze emits for the
    /// same array. This is what `#[repe(typed)]` routes a numeric field to.
    ///
    /// Inside an enclosing object — the whole-struct listing — the frame is
    /// already committed to JSON, so the slice is written as a JSON array
    /// instead. A field only reaches the typed encoding when it is read on its
    /// own.
    pub fn write_typed_slice<T>(&mut self, path: &str, slice: &[T]) -> StructResult<()>
    where
        T: beve::BeveTypedSlice + Serialize,
    {
        if self.nested {
            return self.write(path, slice);
        }
        let encoded_len = beve::typed_slice_size(slice) as usize;
        self.buf.reserve(encoded_len);
        let start = self.buf.len();
        beve::to_writer_typed_slice(&mut *self.buf, slice)
            .expect("writing a typed slice into a Vec is infallible");
        debug_assert_eq!(self.buf.len() - start, encoded_len);
        self.format = BodyFormat::Beve;
        Ok(())
    }

    /// Begin a JSON object body, written key by key.
    ///
    /// Used by the whole-struct listing so a wide object is emitted in one pass
    /// instead of through a [`serde_json::Map`].
    pub fn object(&mut self) -> ObjectBody<'_> {
        let start = self.buf.len();
        self.buf.push(b'{');
        ObjectBody {
            buf: self.buf,
            start,
            first: true,
        }
    }
}

/// A JSON object body being written key by key. Created by
/// [`ResponseBody::object`]; call [`finish`](Self::finish) to close it.
///
/// An entry that fails rewinds the buffer past the opening brace, so a partly
/// written object is never left behind for a caller that recovers from the
/// error. Dropping without calling [`finish`](Self::finish) is the same
/// situation and leaves nothing behind either, since the only way out without
/// finishing is an error that has already rewound.
pub struct ObjectBody<'a> {
    buf: &'a mut Vec<u8>,
    /// Buffer length before the opening brace, to rewind to on failure.
    start: usize,
    first: bool,
}

impl ObjectBody<'_> {
    fn key(&mut self, key: &str) -> StructResult<()> {
        if self.first {
            self.first = false;
        } else {
            self.buf.push(b',');
        }
        serde_json::to_writer(&mut *self.buf, key).map_err(|source| StructError::Serialize {
            path: format!("/{key}"),
            source,
        })?;
        self.buf.push(b':');
        Ok(())
    }

    /// Run one entry, rewinding the whole object if it fails.
    fn entry_with_rewind<F>(&mut self, f: F) -> StructResult<()>
    where
        F: FnOnce(&mut Self) -> StructResult<()>,
    {
        match f(self) {
            Ok(()) => Ok(()),
            Err(err) => {
                self.buf.truncate(self.start);
                Err(err)
            }
        }
    }

    /// Write one `"key": value` entry.
    pub fn entry<T>(&mut self, key: &str, value: &T) -> StructResult<()>
    where
        T: Serialize + ?Sized,
    {
        self.entry_with_rewind(|this| {
            this.key(key)?;
            serde_json::to_writer(&mut *this.buf, value).map_err(|source| StructError::Serialize {
                path: format!("/{key}"),
                source,
            })
        })
    }

    /// Write one `"key": <value>` entry whose value is produced by `f`, for a
    /// nested [`RepeStruct`] that fills the body itself.
    ///
    /// The body handed to `f` is marked as nested: the enclosing frame is
    /// already JSON, so a [`ResponseBody::write_typed_slice`] inside it falls
    /// back to a JSON array rather than switching the frame to BEVE.
    pub fn entry_with<F>(&mut self, key: &str, f: F) -> StructResult<()>
    where
        F: FnOnce(&mut ResponseBody<'_>) -> StructResult<()>,
    {
        self.entry_with_rewind(|this| {
            this.key(key)?;
            let mut body = ResponseBody {
                buf: this.buf,
                format: BodyFormat::Json,
                nested: true,
            };
            f(&mut body)
        })
    }

    /// Close the object.
    pub fn finish(self) {
        self.buf.push(b'}');
    }
}

/// Write the `Option<Value>` a [`RepeStruct::repe_handle`] returned as the whole
/// body: the payload, or `null` when there is nothing to send.
///
/// Shared by the [`RepeStruct::repe_handle_into`] and
/// [`RepeMethods::repe_call_into`] defaults, which differ only in which method
/// they delegate to.
fn write_optional(
    out: &mut ResponseBody<'_>,
    segments: &[&str],
    value: Option<Value>,
) -> StructResult<()> {
    match value {
        Some(value) => out.write_with_path(|| path_from_segments(segments), &value),
        None => {
            out.write_null();
            Ok(())
        }
    }
}

/// Compile-time check that no `#[repe::methods]` endpoint shadows a field.
///
/// The two macros cannot see each other's input, so the derive emits a call to
/// this against its own field names and the generated
/// [`RepeMethods::REPE_METHOD_SIGNATURES`]. Without it a collision is silent and
/// costly: the field wins dispatch, the method becomes permanently unreachable,
/// and the whole-struct listing emits the same key twice.
///
/// Collisions the macros *can* see on their own — two fields, two listed
/// methods, a field against a listed method, two methods in one impl block — are
/// rejected at macro time with a message naming the endpoint.
pub const fn assert_no_endpoint_collision(fields: &[&str], methods: &[(&str, &str)]) {
    let mut i = 0;
    while i < methods.len() {
        let mut j = 0;
        while j < fields.len() {
            if const_str_eq(methods[i].0, fields[j]) {
                panic!(
                    "a `#[repe::methods]` method and a field of the same struct share an \
                     endpoint name: the field would win dispatch and the method could never \
                     be called. Rename one with `#[repe(rename = \"...\")]`."
                );
            }
            j += 1;
        }
        i += 1;
    }
}

/// `str` equality usable in a `const` context, which `PartialEq` is not.
const fn const_str_eq(a: &str, b: &str) -> bool {
    let (a, b) = (a.as_bytes(), b.as_bytes());
    if a.len() != b.len() {
        return false;
    }
    let mut i = 0;
    while i < a.len() {
        if a[i] != b[i] {
            return false;
        }
        i += 1;
    }
    true
}

/// Decoder for the body of a struct method taking two or more arguments.
///
/// A single-argument method takes the request body *as* the argument, which is
/// the shape the wire has always had. Beyond one argument the body carries the
/// whole list, in either of two forms:
///
/// * a JSON/BEVE **array** of exactly N values, positionally, or
/// * an **object** keyed by parameter name, where a missing key decodes as
///   `null` (so an `Option<T>` parameter may be omitted).
///
/// Generated by `#[repe::methods]` and by `#[repe(methods(..))]`; public because
/// the generated code names it, not because it is expected to be called by hand.
pub struct MethodArgs<'a> {
    path: &'a str,
    names: &'a [&'a str],
    values: std::vec::IntoIter<Value>,
    index: usize,
}

impl<'a> MethodArgs<'a> {
    /// Split `body` into the argument list for `names`.
    pub fn new(path: &'a str, names: &'a [&'a str], body: Value) -> StructResult<Self> {
        let values = match body {
            Value::Array(items) => {
                if items.len() != names.len() {
                    return Err(arg_error(
                        path,
                        format!("expected {} arguments, got {}", names.len(), items.len()),
                    ));
                }
                items
            }
            Value::Object(mut map) => names
                .iter()
                .map(|name| map.remove(*name).unwrap_or(Value::Null))
                .collect(),
            _ => {
                return Err(arg_error(
                    path,
                    format!(
                        "expected an array of {} arguments or an object with keys [{}]",
                        names.len(),
                        names.join(", ")
                    ),
                ));
            }
        };
        Ok(Self {
            path,
            names,
            values: values.into_iter(),
            index: 0,
        })
    }

    /// Decode the next argument in declaration order.
    pub fn next_arg<T: DeserializeOwned>(&mut self) -> StructResult<T> {
        let name = self.names.get(self.index).copied().unwrap_or("?");
        self.index += 1;
        let value = self.values.next().unwrap_or(Value::Null);
        serde_json::from_value(value).map_err(|source| StructError::Deserialize {
            path: format!("{path}({name})", path = self.path),
            source,
        })
    }
}

/// A `StructError::Deserialize` carrying a message of our own rather than one
/// from serde, so argument-shape complaints read like every other body error.
fn arg_error(path: &str, message: String) -> StructError {
    StructError::Deserialize {
        path: path.to_string(),
        source: <serde_json::Error as serde::de::Error>::custom(message),
    }
}