use crate::constants::{BodyFormat, ErrorCode};
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::Value;
#[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("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,
}
}
}
pub type StructResult<T> = Result<T, StructError>;
#[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)]`, 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)]`",
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(
&mut self,
segments: &[&str],
body: Option<Value>,
) -> StructResult<Option<Value>>;
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)
}
fn repe_shared_into(
&self,
segments: &[&str],
body: &mut Option<Value>,
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(
&mut self,
segments: &[&str],
body: Option<Value>,
) -> StructResult<Option<Value>> {
refuse_presence_write(segments, body.as_ref())?;
match self {
Some(inner) => inner.repe_handle(segments, body),
None => absent_child(segments, body.is_some()).map(|()| None),
}
}
fn repe_handle_into(
&mut self,
segments: &[&str],
body: Option<Value>,
out: &mut ResponseBody<'_>,
) -> StructResult<()> {
refuse_presence_write(segments, body.as_ref())?;
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: &mut Option<Value>,
out: &mut ResponseBody<'_>,
) -> Option<StructResult<()>> {
if let Err(err) = refuse_presence_write(segments, body.as_ref()) {
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<&Value>) -> StructResult<()> {
if segments.is_empty() && matches!(body, Some(Value::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(&mut self, segments: &[&str], body: Option<Value>) -> StructResult<Option<Value>>;
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)
}
fn repe_call_shared_into(
&self,
segments: &[&str],
body: &mut Option<Value>,
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 {
if segments.is_empty() {
String::from("")
} else {
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::Serialize { path, .. }
| StructError::Deserialize { path, .. }
| StructError::Execution { path, .. } => {
*path = with_prefix(std::mem::take(path));
}
}
err
}
#[cfg(not(feature = "typed"))]
mod sealed {
pub trait Sealed {}
}
#[cfg(not(feature = "typed"))]
#[diagnostic::on_unimplemented(
message = "`#[repe(typed)]` needs the `typed` feature of `repe-core`",
label = "no BEVE typed-array encoding is compiled in",
note = "enable it with `repe-core = {{ version = \"2\", features = [\"typed\"] }}`, or drop \
`#[repe(typed)]` from the field to serve it as a JSON array",
note = "crates that depend on `repe` rather than `repe-core` already have it on"
)]
pub trait TypedSliceElement: sealed::Sealed {}
pub struct ResponseBody<'a> {
buf: &'a mut Vec<u8>,
format: BodyFormat,
#[cfg_attr(not(feature = "typed"), expect(dead_code))]
nested: bool,
}
impl<'a> ResponseBody<'a> {
pub fn new(buf: &'a mut Vec<u8>) -> Self {
Self {
buf,
format: BodyFormat::Json,
nested: false,
}
}
pub fn format(&self) -> BodyFormat {
self.format
}
pub fn write<T>(&mut self, path: &str, value: &T) -> StructResult<()>
where
T: Serialize + ?Sized,
{
self.write_with_path(|| String::from(path), value)
}
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,
})
}
}
}
pub fn write_null(&mut self) {
self.buf.extend_from_slice(b"null");
}
#[cfg(feature = "typed")]
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(())
}
#[cfg(not(feature = "typed"))]
pub fn write_typed_slice<T>(&mut self, path: &str, slice: &[T]) -> StructResult<()>
where
T: TypedSliceElement,
{
let _ = (path, slice);
unreachable!("`TypedSliceElement` is sealed and implemented by nothing")
}
pub fn object(&mut self) -> ObjectBody<'_> {
let start = self.buf.len();
self.buf.push(b'{');
ObjectBody {
buf: self.buf,
start,
first: true,
}
}
}
pub struct ObjectBody<'a> {
buf: &'a mut Vec<u8>,
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(())
}
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)
}
}
}
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,
})
})
}
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)
})
}
pub fn entry_try_with<F>(&mut self, key: &str, f: F) -> Option<StructResult<()>>
where
F: FnOnce(&mut ResponseBody<'_>) -> Option<StructResult<()>>,
{
let outcome = match self.key(key) {
Ok(()) => {
let mut body = ResponseBody {
buf: self.buf,
format: BodyFormat::Json,
nested: true,
};
f(&mut body)
}
Err(err) => Some(Err(err)),
};
if !matches!(outcome, Some(Ok(()))) {
self.buf.truncate(self.start);
}
outcome
}
pub fn finish(self) {
self.buf.push(b'}');
}
}
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(())
}
}
}
#[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
}
pub fn serde_pointer<'a>(value: &'a Value, segments: &[&str]) -> Option<&'a Value> {
let mut cursor = value;
for segment in segments {
cursor = match cursor {
Value::Object(map) => map.get(*segment)?,
Value::Array(items) => items.get(segment.parse::<usize>().ok()?)?,
_ => return None,
};
}
Some(cursor)
}
pub fn serde_pointer_set(value: &mut Value, segments: &[&str], new: Value) -> Option<()> {
if segments.is_empty() {
return None;
}
let mut cursor = value;
for segment in segments {
cursor = match cursor {
Value::Object(map) => map.get_mut(*segment)?,
Value::Array(items) => items.get_mut(segment.parse::<usize>().ok()?)?,
_ => return None,
};
}
*cursor = new;
Some(())
}
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],
values: std::vec::IntoIter<Value>,
index: usize,
}
impl<'a> MethodArgs<'a> {
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,
})
}
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,
})
}
}
fn arg_error(path: &str, message: String) -> StructError {
StructError::Deserialize {
path: path.to_string(),
source: <serde_json::Error as serde::de::Error>::custom(message),
}
}