use crate::constants::{BodyFormat, ErrorCode};
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::Value;
#[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,
}
}
}
pub type StructResult<T> = Result<T, StructError>;
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_read_into(
&self,
segments: &[&str],
out: &mut ResponseBody<'_>,
) -> Option<StructResult<()>> {
let _ = (segments, out);
None
}
}
#[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 {
const REPE_METHOD_SIGNATURES: &'static [(&'static str, &'static str)];
const REPE_ACCESSOR_ENDPOINTS: &'static [&'static str] = &[];
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_read_into(
&self,
segments: &[&str],
out: &mut ResponseBody<'_>,
) -> Option<StructResult<()>> {
let _ = (segments, out);
None
}
}
#[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 {}
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
}
}
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
}
pub struct ResponseBody<'a> {
buf: &'a mut Vec<u8>,
format: BodyFormat,
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");
}
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(())
}
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(())
}
}
}
pub const fn assert_no_endpoint_collision(
declared: &[&str],
methods: &[(&str, &str)],
accessors: &[&str],
) {
let mut i = 0;
while i < methods.len() {
let mut j = 0;
while j < declared.len() {
if const_str_eq(methods[i].0, declared[j]) {
panic!(
"a `#[repe::methods]` 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 = \"...\")]`."
);
}
j += 1;
}
i += 1;
}
let mut i = 0;
while i < accessors.len() {
let mut j = 0;
while j < declared.len() {
if const_str_eq(accessors[i], declared[j]) {
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."
);
}
j += 1;
}
let mut j = 0;
while j < methods.len() {
if const_str_eq(accessors[i], methods[j].0) {
panic!(
"a `#[repe::methods]` 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."
);
}
j += 1;
}
i += 1;
}
}
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),
}
}