use crate::constants::{BodyFormat, ErrorCode};
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
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("could not decode body for `{path}`: {source}")]
Decode {
path: String,
#[source]
source: structio::Error,
},
#[error("invalid arguments for `{path}`: {message}")]
Arguments { path: String, message: String },
#[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::Decode { .. } | StructError::Arguments { .. } => ErrorCode::InvalidBody,
StructError::Execution { .. } => ErrorCode::ParseError,
}
}
}
pub type StructResult<T> = Result<T, StructError>;
pub trait Servable: for<'de> ServableRead<'de> + ServableWrite {}
impl<T: for<'de> ServableRead<'de> + ServableWrite> Servable for T {}
#[diagnostic::on_unimplemented(
message = "`{Self}` cannot be decoded from a REPE body: it has no structio declaration",
label = "no JSON/BEVE encoding for `{Self}`",
note = "declare it with `structio::object!({Self} {{ field, .. }})` — or `tagged_enum!` / `array!` / `unit_enum!`",
note = "`#[derive(RepeStruct)]` publishes endpoints; the structio declaration is what gives the type a wire encoding. A served type needs both."
)]
pub trait ServableRead<'de>: structio::json::Read<'de> + structio::beve::Read<'de> {}
impl<'de, T> ServableRead<'de> for T where T: structio::json::Read<'de> + structio::beve::Read<'de> {}
pub type WirePolicy = structio::SkipUnknown;
#[diagnostic::on_unimplemented(
message = "`{Self}` cannot be decoded from a REPE response",
label = "not decodable as an owned JSON/BEVE value",
note = "declare it with `structio::object!({Self} {{ field, .. }})` — or `tagged_enum!` / `array!` / `unit_enum!`",
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`)"
)]
pub trait ServableOwned: for<'de> ServableRead<'de> + Default {}
impl<T: for<'de> ServableRead<'de> + Default> ServableOwned for T {}
#[diagnostic::on_unimplemented(
message = "`{Self}` cannot be encoded into a REPE body: it has no structio declaration",
label = "no JSON/BEVE encoding for `{Self}`",
note = "declare it with `structio::object!({Self} {{ field, .. }})` — or `tagged_enum!` / `array!` / `unit_enum!`",
note = "`#[derive(RepeStruct)]` publishes endpoints; the structio declaration is what gives the type a wire encoding. A served type needs both."
)]
pub trait ServableWrite: structio::json::Write + structio::beve::Write {}
impl<T: structio::json::Write + structio::beve::Write + ?Sized> ServableWrite for T {}
#[derive(Debug, Clone, Copy)]
pub struct RequestBody<'a> {
bytes: &'a [u8],
format: BodyFormat,
}
impl<'a> RequestBody<'a> {
pub fn new(bytes: &'a [u8], format: BodyFormat) -> Self {
Self { bytes, format }
}
pub fn bytes(&self) -> &'a [u8] {
self.bytes
}
pub fn format(&self) -> BodyFormat {
self.format
}
pub fn is_null(&self) -> bool {
match self.format {
BodyFormat::Beve => structio::beve::Reader::new(self.bytes)
.try_null()
.unwrap_or(false),
_ => self.bytes.trim_ascii() == b"null",
}
}
pub fn read_into<T>(&self, path: &str, value: &mut T) -> StructResult<()>
where
T: ServableRead<'a>,
{
self.read_into_with::<WirePolicy, T>(path, value)
}
pub fn read_into_with<O, T>(&self, path: &str, value: &mut T) -> StructResult<()>
where
O: structio::Options,
T: ServableRead<'a>,
{
self.read_raw_with::<O, T>(value)
.map_err(|source| StructError::Decode {
path: path.to_string(),
source,
})
}
fn read_into_raw<T>(&self, value: &mut T) -> Result<(), structio::Error>
where
T: ServableRead<'a>,
{
self.read_raw_with::<WirePolicy, T>(value)
}
fn read_raw_with<O, T>(&self, value: &mut T) -> Result<(), structio::Error>
where
O: structio::Options,
T: ServableRead<'a>,
{
match self.format {
BodyFormat::Beve => structio::beve::read_into_with::<O, T>(value, self.bytes),
_ => match core::str::from_utf8(self.bytes) {
Ok(text) => structio::json::read_into_with::<O, T>(value, text),
Err(err) => Err(structio::Error::new(
structio::ErrorCode::InvalidUtf8,
err.valid_up_to(),
)),
},
}
}
pub fn read<T>(&self, path: &str) -> StructResult<T>
where
T: ServableRead<'a> + Default,
{
let mut value = T::default();
self.read_into(path, &mut value)?;
Ok(value)
}
}
#[diagnostic::on_unimplemented(
message = "`{Self}` cannot be served over REPE: it does not implement `RepeStruct`",
label = "not a REPE-servable type",
note = "derive it with `#[derive(RepeStruct)]`",
note = "a field's own type needs a structio declaration — `structio::object!(Field {{ .. }})` — not a derive",
note = "a type in a crate that depends only on `repe-core` can derive this too; `repe` re-exports the same trait"
)]
pub trait RepeStruct: Send + Sync {
fn repe_handle_into(
&mut self,
segments: &[&str],
body: Option<RequestBody<'_>>,
out: &mut ResponseBody<'_>,
) -> StructResult<()>;
fn repe_shared_into(
&self,
segments: &[&str],
body: Option<RequestBody<'_>>,
out: &mut ResponseBody<'_>,
) -> Option<StructResult<()>> {
let _ = (segments, body, out);
None
}
fn repe_listing_declines(&self) -> bool {
true
}
const REPE_SHARED_SERVES_BODIES: bool = true;
}
impl<T: RepeStruct> RepeStruct for Option<T> {
fn repe_handle_into(
&mut self,
segments: &[&str],
body: Option<RequestBody<'_>>,
out: &mut ResponseBody<'_>,
) -> StructResult<()> {
refuse_presence_write(segments, body)?;
match self {
Some(inner) => inner.repe_handle_into(segments, body, out),
None => {
absent_child(segments, body.is_some())?;
out.write_null();
Ok(())
}
}
}
fn repe_shared_into(
&self,
segments: &[&str],
body: Option<RequestBody<'_>>,
out: &mut ResponseBody<'_>,
) -> Option<StructResult<()>> {
if let Err(err) = refuse_presence_write(segments, body) {
return Some(Err(err));
}
match self {
Some(inner) => inner.repe_shared_into(segments, body, out),
None => Some(absent_child(segments, body.is_some()).map(|()| out.write_null())),
}
}
fn repe_listing_declines(&self) -> bool {
match self {
Some(inner) => inner.repe_listing_declines(),
None => false,
}
}
const REPE_SHARED_SERVES_BODIES: bool = T::REPE_SHARED_SERVES_BODIES;
}
fn refuse_presence_write(segments: &[&str], body: Option<RequestBody<'_>>) -> StructResult<()> {
if segments.is_empty() && body.is_some_and(|b| b.is_null()) {
return Err(StructError::BodyUnexpected {
path: path_from_segments(segments),
});
}
Ok(())
}
fn absent_child(segments: &[&str], has_body: bool) -> StructResult<()> {
if segments.is_empty() && !has_body {
Ok(())
} else {
Err(StructError::InvalidPath {
path: path_from_segments(segments),
})
}
}
#[diagnostic::on_unimplemented(
message = "`{Self}` declares `#[repe(methods)]` but its impl block is not annotated",
label = "no method table for `{Self}`",
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"
)]
pub trait RepeMethods: MethodsDeclared {
const REPE_METHOD_SIGNATURES: &'static [(&'static str, &'static str)];
const REPE_ACCESSOR_ENDPOINTS: &'static [&'static str] = &[];
#[doc(hidden)]
const REPE_TABLE_RECOVERED: bool = false;
const REPE_LISTING_NEEDS_EXCLUSIVE: bool = !Self::REPE_ACCESSOR_ENDPOINTS.is_empty();
const REPE_SHARED_SERVES_BODIES: bool = true;
fn repe_call_into(
&mut self,
segments: &[&str],
body: Option<RequestBody<'_>>,
out: &mut ResponseBody<'_>,
) -> StructResult<()>;
fn repe_call_shared_into(
&self,
segments: &[&str],
body: Option<RequestBody<'_>>,
out: &mut ResponseBody<'_>,
) -> Option<StructResult<()>> {
let _ = (segments, body, out);
None
}
}
#[diagnostic::on_unimplemented(
message = "`{Self}` has an annotated `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 {}
pub fn path_from_segments(segments: &[&str]) -> String {
let mut s = String::new();
for segment in segments {
s.push('/');
s.push_str(segment);
}
s
}
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::Decode { path, .. }
| StructError::Arguments { path, .. }
| StructError::Execution { path, .. } => {
*path = with_prefix(std::mem::take(path));
}
}
err
}
pub struct ResponseBody<'a> {
buf: &'a mut Vec<u8>,
requested: BodyFormat,
format: BodyFormat,
nested: bool,
}
impl<'a> ResponseBody<'a> {
pub fn new(buf: &'a mut Vec<u8>) -> Self {
Self::with_format(buf, BodyFormat::Json)
}
pub fn with_format(buf: &'a mut Vec<u8>, requested: BodyFormat) -> Self {
Self {
buf,
requested: match requested {
BodyFormat::Beve => BodyFormat::Beve,
_ => BodyFormat::Json,
},
format: BodyFormat::Json,
nested: false,
}
}
pub fn format(&self) -> BodyFormat {
self.format
}
pub fn write<T>(&mut self, value: &T)
where
T: ServableWrite + ?Sized,
{
if self.requested == BodyFormat::Beve {
structio::beve::append(value, self.buf);
self.format = BodyFormat::Beve;
} else {
structio::append(value, self.buf);
}
}
pub fn write_null(&mut self) {
if self.requested == BodyFormat::Beve {
structio::beve::append(&(), self.buf);
self.format = BodyFormat::Beve;
} else {
self.buf.extend_from_slice(b"null");
}
}
pub fn write_typed_slice<T>(&mut self, slice: &[T])
where
T: structio::beve::NumericBytes + ServableWrite,
{
if self.nested {
self.write(slice);
return;
}
structio::beve::append(slice, self.buf);
self.format = BodyFormat::Beve;
}
pub fn object(&mut self, entries: usize) -> ObjectBody<'_> {
let start = self.buf.len();
let format = if self.nested {
self.format
} else {
self.format = self.requested;
self.requested
};
match format {
BodyFormat::Beve => {
let mut w = beve_writer(self.buf);
w.push(structio::beve::header::OBJECT);
w.size(entries as u64);
*self.buf = w.into_vec();
}
_ => self.buf.push(b'{'),
}
ObjectBody {
buf: self.buf,
start,
format,
first: true,
declared: entries,
written: 0,
}
}
}
pub struct ObjectBody<'a> {
buf: &'a mut Vec<u8>,
start: usize,
format: BodyFormat,
first: bool,
declared: usize,
written: usize,
}
fn beve_writer(buf: &mut Vec<u8>) -> structio::beve::Writer<'static, structio::Standard> {
structio::beve::Writer::appending(std::mem::take(buf))
}
impl ObjectBody<'_> {
fn key(&mut self, key: &str) {
self.written += 1;
match self.format {
BodyFormat::Beve => {
let mut w = beve_writer(self.buf);
w.write_str_body(key);
*self.buf = w.into_vec();
}
_ => {
if self.first {
self.first = false;
} else {
self.buf.push(b',');
}
structio::append(key, self.buf);
self.buf.push(b':');
}
}
}
fn value_body(&mut self) -> ResponseBody<'_> {
ResponseBody {
buf: self.buf,
requested: self.format,
format: self.format,
nested: true,
}
}
pub fn entry<T>(&mut self, key: &str, value: &T)
where
T: ServableWrite + ?Sized,
{
self.key(key);
self.value_body().write(value);
}
pub fn entry_with<F>(&mut self, key: &str, f: F) -> StructResult<()>
where
F: FnOnce(&mut ResponseBody<'_>) -> StructResult<()>,
{
self.key(key);
let outcome = f(&mut self.value_body());
if outcome.is_err() {
self.buf.truncate(self.start);
}
outcome
}
pub fn entry_try_with<F>(&mut self, key: &str, f: F) -> Option<StructResult<()>>
where
F: FnOnce(&mut ResponseBody<'_>) -> Option<StructResult<()>>,
{
self.key(key);
let outcome = f(&mut self.value_body());
if !matches!(outcome, Some(Ok(()))) {
self.buf.truncate(self.start);
}
outcome
}
pub fn finish(self) {
assert_eq!(
self.written, self.declared,
"repe: a listing declared {} entries and wrote {}; under BEVE the \
count is in the header and a disagreement corrupts the document",
self.declared, self.written,
);
if self.format != BodyFormat::Beve {
self.buf.push(b'}');
}
}
}
#[doc(hidden)]
pub const fn assert_no_endpoint_collision(
declared: &[&str],
methods: &[(&str, &str)],
accessors: &[&str],
) {
let mut i = 0;
while i < methods.len() {
if const_contains(declared, methods[i].0) {
panic!(
"a published method and an endpoint declared on the struct itself \
share a name: the struct's declaration wins dispatch and the method could \
never be called. Rename one with `#[repe(rename = \"...\")]`."
);
}
i += 1;
}
let mut i = 0;
while i < accessors.len() {
if const_contains(declared, accessors[i]) {
panic!(
"a `#[repe(get = \"...\")]` accessor and an endpoint declared on the struct \
itself share a name: the struct's declaration wins dispatch and the accessor \
could never be called. Rename the struct's with \
`#[repe(rename = \"...\")]`, or give the accessor a different endpoint."
);
}
if listed_signature(methods, accessors[i]).is_some() {
panic!(
"a published method and a `#[repe(get = \"...\")]` accessor in the \
same table share an endpoint name: one of them is unreachable, and the \
whole-struct listing would show the endpoint twice."
);
}
i += 1;
}
}
#[doc(hidden)]
pub const fn assert_listing_order(
order: &[&str],
declared: &[&str],
methods: &[(&str, &str)],
accessors: &[&str],
recovering: bool,
) {
let mut i = 0;
while i < order.len() {
let known = const_contains(declared, order[i])
|| const_contains(accessors, order[i])
|| listed_signature(methods, order[i]).is_some();
if !known && !recovering {
panic!(
"`#[repe(listing_order(..))]` names a key that is not an endpoint on this \
struct. It lists the whole-object listing's keys, so every name in it has to \
be a field, a listed method, or an endpoint of the annotated `methods` impl block."
);
}
i += 1;
}
let mut j = 0;
while j < methods.len() {
if !const_contains(order, methods[j].0) {
panic!(
"a method on the annotated `methods` impl block is missing from `#[repe(listing_order(..))]`, \
which names the whole-object listing's keys in full. An omitted endpoint \
would disappear from every whole-object read while still answering on its \
own path."
);
}
j += 1;
}
let mut j = 0;
while j < accessors.len() {
if !const_contains(order, accessors[j]) {
panic!(
"a `#[repe(get = \"...\")]` accessor is missing from \
`#[repe(listing_order(..))]`, which names the whole-object listing's keys in \
full. An omitted endpoint would disappear from every whole-object read while \
still answering on its own path."
);
}
j += 1;
}
}
#[doc(hidden)]
pub const fn listed_signature<'a>(methods: &[(&'a str, &'a str)], name: &str) -> Option<&'a str> {
let mut i = 0;
while i < methods.len() {
if const_str_eq(methods[i].0, name) {
return Some(methods[i].1);
}
i += 1;
}
None
}
const fn const_contains(list: &[&str], name: &str) -> bool {
let mut i = 0;
while i < list.len() {
if const_str_eq(list[i], name) {
return true;
}
i += 1;
}
false
}
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
}
pub struct MethodArgs<'a> {
path: &'a str,
names: &'a [&'a str],
format: BodyFormat,
source: ArgSource<'a>,
index: usize,
}
enum ArgSource<'a> {
Spans(Vec<Option<&'a [u8]>>),
Cursor(structio::beve::Documents<&'a [u8], WirePolicy>),
}
impl<'a> MethodArgs<'a> {
pub fn new(path: &'a str, names: &'a [&'a str], body: RequestBody<'a>) -> StructResult<Self> {
let source = match body.format() {
BodyFormat::Beve => split_beve(path, names, body.bytes())?,
_ => ArgSource::Spans(split_json(path, names, body.bytes())?),
};
Ok(Self {
path,
names,
format: body.format(),
source,
index: 0,
})
}
pub fn next_arg<T>(&mut self) -> StructResult<T>
where
T: for<'de> ServableRead<'de> + Default,
{
let name = self.names.get(self.index).copied().unwrap_or("?");
let index = self.index;
self.index += 1;
let mut value = T::default();
let label = || format!("{}({name})", self.path);
match &mut self.source {
ArgSource::Spans(spans) => {
let (bytes, format) = match spans.get(index).copied().flatten() {
Some(bytes) => (bytes, self.format),
None => (&b"null"[..], BodyFormat::Json),
};
RequestBody::new(bytes, format)
.read_into_raw(&mut value)
.map_err(|source| StructError::Decode {
path: label(),
source,
})?;
}
ArgSource::Cursor(documents) => {
let outcome =
documents
.next_value_into(&mut value)
.ok_or_else(|| StructError::Decode {
path: label(),
source: structio::Error::new(structio::ErrorCode::UnexpectedEnd, 0),
})?;
outcome.map_err(|err| StructError::Decode {
path: label(),
source: stream_parse_error(err),
})?;
}
}
Ok(value)
}
}
fn decode_error(path: &str, code: structio::ErrorCode, at: usize) -> StructError {
StructError::Decode {
path: path.to_string(),
source: structio::Error::new(code, at),
}
}
fn split_json<'a>(
path: &str,
names: &[&str],
bytes: &'a [u8],
) -> StructResult<Vec<Option<&'a [u8]>>> {
let text = core::str::from_utf8(bytes)
.map_err(|err| decode_error(path, structio::ErrorCode::InvalidUtf8, err.valid_up_to()))?;
let mut p = structio::json::Parser::new(text);
p.skip_ws();
match p.rest().first() {
Some(b'[') => {
let mut positional: Vec<Option<&'a [u8]>> = Vec::new();
p.read_seq(|p, _| {
let start = p.position();
p.skip_value()?;
positional.push(Some(&bytes[start..p.position()]));
Ok(())
})
.and_then(|_| p.finish())
.map_err(|code| decode_error(path, code, p.position()))?;
check_arity(path, names, positional.len())?;
Ok(positional)
}
Some(b'{') => {
let mut spans: Vec<Option<&'a [u8]>> = vec![None; names.len()];
p.read_map(|p, key| {
let slot = names.iter().position(|name| *name == key.as_str());
let start = p.position();
p.skip_value()?;
if let Some(i) = slot {
spans[i] = Some(&bytes[start..p.position()]);
}
Ok(())
})
.and_then(|()| p.finish())
.map_err(|code| decode_error(path, code, p.position()))?;
Ok(spans)
}
_ => Err(shape_error(path, names)),
}
}
fn stream_parse_error(err: structio::StreamError) -> structio::Error {
match err {
structio::StreamError::Parse(err) => err,
_ => structio::Error::new(structio::ErrorCode::UnexpectedEnd, 0),
}
}
fn split_beve<'a>(path: &str, names: &[&str], bytes: &'a [u8]) -> StructResult<ArgSource<'a>> {
match bytes.first().map(|&h| structio::beve::header::ty(h)) {
Some(structio::beve::header::TY_GENERIC_ARRAY) => {
let mut positional: Vec<Option<&'a [u8]>> = Vec::new();
let mut r = structio::beve::Reader::new(bytes);
r.read_seq(|r, _| {
let start = r.position();
r.skip_value()?;
positional.push(Some(&bytes[start..r.position()]));
Ok(())
})
.and_then(|_| r.finish())
.map_err(|code| decode_error(path, code, r.position()))?;
check_arity(path, names, positional.len())?;
Ok(ArgSource::Spans(positional))
}
Some(structio::beve::header::TY_OBJECT) => {
let mut spans: Vec<Option<&'a [u8]>> = vec![None; names.len()];
let mut r = structio::beve::Reader::new(bytes);
r.read_map(|r, key| {
let slot = match key {
structio::beve::Key::Str(key) => names.iter().position(|name| *name == key),
_ => None,
};
let start = r.position();
r.skip_value()?;
if let Some(i) = slot {
spans[i] = Some(&bytes[start..r.position()]);
}
Ok(())
})
.and_then(|()| r.finish())
.map_err(|code| decode_error(path, code, r.position()))?;
Ok(ArgSource::Spans(spans))
}
Some(structio::beve::header::TY_TYPED_ARRAY | structio::beve::header::TY_EXTENSION) => {
let mut r = structio::beve::Reader::new(bytes);
let count = r
.read_seq(|r, _| r.skip_value())
.and_then(|count| r.finish().map(|()| count))
.map_err(|code| decode_error(path, code, r.position()))?;
check_arity(path, names, count)?;
Ok(ArgSource::Cursor(
structio::beve::Documents::array(bytes)
.with_options::<WirePolicy>()
.read_size(bytes.len().max(1)),
))
}
_ => Err(shape_error(path, names)),
}
}
fn check_arity(path: &str, names: &[&str], got: usize) -> StructResult<()> {
if got == names.len() {
Ok(())
} else {
Err(StructError::Arguments {
path: path.to_string(),
message: format!("expected {} arguments, got {got}", names.len()),
})
}
}
fn shape_error(path: &str, names: &[&str]) -> StructError {
StructError::Arguments {
path: path.to_string(),
message: format!(
"expected an array of {} arguments or an object with keys [{}]",
names.len(),
names.join(", ")
),
}
}