use crate::constants::{BodyFormat, ErrorCode};
use crate::message::Message;
use crate::peer::CallContext;
use crate::structs::{RequestBody, ResponseBody};
use std::borrow::Cow;
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
type RegistryFunction = Arc<dyn RegistryCallable>;
#[derive(Debug, thiserror::Error)]
pub enum RegistryError {
#[error("invalid JSON pointer `{pointer}`")]
InvalidPointer { pointer: String },
#[error("path not found `{path}`")]
PathNotFound { path: String },
#[error("registry body format `{format}` is unsupported")]
UnsupportedBodyFormat { format: u16 },
#[error("{message}")]
Execution { code: ErrorCode, message: String },
}
impl RegistryError {
pub fn code(&self) -> ErrorCode {
match self {
RegistryError::InvalidPointer { .. } | RegistryError::PathNotFound { .. } => {
ErrorCode::MethodNotFound
}
RegistryError::UnsupportedBodyFormat { .. } => ErrorCode::InvalidBody,
RegistryError::Execution { code, .. } => *code,
}
}
}
pub trait RegistryCallable: Send + Sync {
fn call(
&self,
ctx: &CallContext,
params: Option<RequestBody<'_>>,
out: &mut ResponseBody<'_>,
) -> Result<(), (ErrorCode, String)>;
}
impl<F, R> RegistryCallable for F
where
F: for<'a> Fn(Option<RequestBody<'a>>) -> Result<R, (ErrorCode, String)>
+ Send
+ Sync
+ 'static,
R: repe_core::structs::ServableWrite,
{
fn call(
&self,
_ctx: &CallContext,
params: Option<RequestBody<'_>>,
out: &mut ResponseBody<'_>,
) -> Result<(), (ErrorCode, String)> {
out.write(&(self)(params)?);
Ok(())
}
}
pub struct WithContext<F>(pub F);
impl<F, R> RegistryCallable for WithContext<F>
where
F: for<'a> Fn(&CallContext, Option<RequestBody<'a>>) -> Result<R, (ErrorCode, String)>
+ Send
+ Sync
+ 'static,
R: repe_core::structs::ServableWrite,
{
fn call(
&self,
ctx: &CallContext,
params: Option<RequestBody<'_>>,
out: &mut ResponseBody<'_>,
) -> Result<(), (ErrorCode, String)> {
out.write(&(self.0)(ctx, params)?);
Ok(())
}
}
pub struct WithBody<F>(pub F);
impl<F> RegistryCallable for WithBody<F>
where
F: for<'a> Fn(
Option<RequestBody<'a>>,
&mut ResponseBody<'_>,
) -> Result<(), (ErrorCode, String)>
+ Send
+ Sync
+ 'static,
{
fn call(
&self,
_ctx: &CallContext,
params: Option<RequestBody<'_>>,
out: &mut ResponseBody<'_>,
) -> Result<(), (ErrorCode, String)> {
(self.0)(params, out)
}
}
#[derive(Default)]
pub struct Registry {
state: RwLock<HashMap<String, RegistryFunction>>,
}
impl Registry {
pub fn new() -> Self {
Self::default()
}
pub fn register_function(
&self,
path: &str,
function: impl RegistryCallable + 'static,
) -> Result<(), RegistryError> {
self.register_function_arc(path, Arc::new(function))
}
pub fn register_function_arc(
&self,
path: &str,
function: Arc<dyn RegistryCallable>,
) -> Result<(), RegistryError> {
let normalized: Cow<'_, str> = if path.starts_with('/') {
Cow::Borrowed(path)
} else {
Cow::Owned(format!("/{path}"))
};
if crate::json_pointer::addresses_root(&normalized) {
return Err(invalid(path));
}
let key = canonical_key(&normalized)
.map_err(|_| invalid(path))?
.to_string();
self.write_state().insert(key, function);
Ok(())
}
pub fn is_function(&self, pointer: &str) -> bool {
match canonical_key(pointer) {
Ok(key) => self.read_state().contains_key(key),
Err(_) => false,
}
}
pub fn endpoints(&self) -> Vec<String> {
self.read_state().keys().cloned().collect()
}
pub fn call(
&self,
pointer: &str,
params: Option<RequestBody<'_>>,
ctx: &CallContext,
out: &mut ResponseBody<'_>,
) -> Result<(), RegistryError> {
let key = canonical_key(pointer)?;
let function = {
let state = self.read_state();
state.get(key).cloned()
};
let Some(function) = function else {
return Err(RegistryError::PathNotFound {
path: pointer.to_string(),
});
};
function
.call(ctx, params, out)
.map_err(|(code, message)| RegistryError::Execution { code, message })
}
pub fn call_detached(
&self,
pointer: &str,
params: Option<RequestBody<'_>>,
out: &mut ResponseBody<'_>,
) -> Result<(), RegistryError> {
let ctx = CallContext::detached(pointer);
self.call(pointer, params, &ctx, out)
}
pub fn body_of(req: &Message) -> Result<Option<RequestBody<'_>>, RegistryError> {
if req.body.is_empty() {
return Ok(None);
}
match BodyFormat::try_from(req.header.body_format) {
Ok(format) => Ok(Some(RequestBody::new(&req.body, format))),
Err(_) => Err(RegistryError::UnsupportedBodyFormat {
format: req.header.body_format,
}),
}
}
fn read_state(&self) -> std::sync::RwLockReadGuard<'_, HashMap<String, RegistryFunction>> {
match self.state.read() {
Ok(guard) => guard,
Err(poisoned) => poisoned.into_inner(),
}
}
fn write_state(&self) -> std::sync::RwLockWriteGuard<'_, HashMap<String, RegistryFunction>> {
match self.state.write() {
Ok(guard) => guard,
Err(poisoned) => poisoned.into_inner(),
}
}
}
fn invalid(pointer: &str) -> RegistryError {
RegistryError::InvalidPointer {
pointer: pointer.to_string(),
}
}
fn canonical_key(pointer: &str) -> Result<&str, RegistryError> {
if crate::json_pointer::addresses_root(pointer) {
return Ok("/");
}
crate::json_pointer::validate_escapes(pointer).map_err(|_| invalid(pointer))?;
Ok(pointer)
}
pub(crate) fn normalize_mount(prefix: &str) -> String {
if prefix.is_empty() || prefix == "/" {
return String::new();
}
let absolute = if prefix.starts_with('/') {
prefix.to_string()
} else {
format!("/{prefix}")
};
let trimmed = absolute.trim_end_matches('/');
if trimmed.is_empty() {
String::new()
} else {
trimmed.to_string()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn call(registry: &Registry, pointer: &str, params: Option<RequestBody<'_>>) -> String {
let mut buf = Vec::new();
let mut out = ResponseBody::new(&mut buf);
registry
.call_detached(pointer, params, &mut out)
.expect("call");
String::from_utf8(buf).expect("json is utf-8")
}
#[test]
fn a_handler_can_write_its_own_body() {
let registry = Registry::new();
registry
.register_function(
"/samples",
WithBody(
|_params: Option<RequestBody<'_>>, out: &mut ResponseBody<'_>| {
out.write_typed_slice(&[1.0f64, 2.0, 3.0]);
Ok(())
},
),
)
.expect("register");
let mut buf = Vec::new();
let mut out = ResponseBody::new(&mut buf);
registry
.call_detached("/samples", None, &mut out)
.expect("call");
assert_eq!(out.format(), BodyFormat::Beve);
assert_eq!(
structio::from_beve::<Vec<f64>>(&buf).unwrap(),
vec![1.0, 2.0, 3.0]
);
}
#[test]
fn a_beve_request_is_answered_in_beve() {
let registry = Registry::new();
registry
.register_function("/echo", |_: Option<RequestBody<'_>>| Ok(7u64))
.expect("register");
let mut buf = Vec::new();
let mut out = ResponseBody::with_format(&mut buf, BodyFormat::Beve);
registry
.call_detached("/echo", None, &mut out)
.expect("call");
assert_eq!(out.format(), BodyFormat::Beve);
assert_eq!(structio::from_beve::<u64>(&buf).unwrap(), 7);
}
#[test]
fn a_malformed_pointer_is_refused_at_registration_and_at_lookup() {
let registry = Registry::new();
assert!(matches!(
registry.register_function("/a~2b", |_: Option<RequestBody<'_>>| Ok(0u64)),
Err(RegistryError::InvalidPointer { .. })
));
assert!(!registry.is_function("/a~2b"));
}
#[test]
fn an_escaped_pointer_registers_and_resolves() {
let registry = Registry::new();
registry
.register_function("/a~1b/run", |_: Option<RequestBody<'_>>| Ok(true))
.expect("register");
registry
.register_function("/m~0n", |_: Option<RequestBody<'_>>| Ok(true))
.expect("register");
assert!(registry.is_function("/a~1b/run"));
assert!(registry.is_function("/m~0n"));
}
#[test]
fn a_call_reads_its_parameters_and_writes_its_result() {
let registry = Registry::new();
registry
.register_function("/double", |params: Option<RequestBody<'_>>| {
let n: i64 = params
.ok_or((ErrorCode::InvalidBody, String::from("body required")))?
.read("/double")
.map_err(|err| (ErrorCode::InvalidBody, err.to_string()))?;
Ok(n * 2)
})
.expect("register");
let body = RequestBody::new(b"21", BodyFormat::Json);
assert_eq!(call(®istry, "/double", Some(body)), "42");
}
#[test]
fn a_bodiless_frame_calls_with_no_parameters() {
let registry = Registry::new();
registry
.register_function("/ping", |params: Option<RequestBody<'_>>| {
assert!(params.is_none());
Ok("pong")
})
.expect("register");
assert_eq!(call(®istry, "/ping", None), "\"pong\"");
}
#[test]
fn an_unregistered_pointer_is_not_found() {
let registry = Registry::new();
let mut buf = Vec::new();
let mut out = ResponseBody::new(&mut buf);
let err = registry
.call_detached("/missing", None, &mut out)
.unwrap_err();
assert!(matches!(err, RegistryError::PathNotFound { .. }));
}
#[test]
fn calls_resolve_at_escaped_pointers() {
let registry = Registry::new();
registry
.register_function("/a~1b/run", |_params: Option<RequestBody<'_>>| Ok("slash"))
.expect("register escaped-slash function");
registry
.register_function("/m~0n", |_params: Option<RequestBody<'_>>| Ok("tilde"))
.expect("register escaped-tilde function");
assert_eq!(call(®istry, "/a~1b/run", None), "\"slash\"");
assert_eq!(call(®istry, "/m~0n", None), "\"tilde\"");
assert!(registry.is_function("/a~1b/run"));
let mut endpoints = registry.endpoints();
endpoints.sort();
assert_eq!(endpoints, vec!["/a~1b/run", "/m~0n"]);
}
#[test]
fn a_context_aware_call_reaches_the_peer() {
use crate::peer::{NotifyBody, PeerHandle, PeerId, PeerSendError, PeerSink};
use std::sync::Mutex;
#[derive(Default)]
struct CapturingSink {
captured: Mutex<Vec<String>>,
}
impl PeerSink for CapturingSink {
fn send_notify(&self, method: &str, _body: NotifyBody) -> Result<(), PeerSendError> {
self.captured.lock().unwrap().push(method.to_string());
Ok(())
}
}
let sink = Arc::new(CapturingSink::default());
let peer = PeerHandle::new(PeerId(7), sink.clone());
let observed_peer = Arc::new(Mutex::new(None::<PeerId>));
let observed_peer_clone = Arc::clone(&observed_peer);
let registry = Registry::new();
registry
.register_function(
"/run",
WithContext(move |ctx: &CallContext, _params: Option<RequestBody<'_>>| {
if let Some(p) = ctx.peer() {
*observed_peer_clone.lock().unwrap() = Some(p.peer_id());
p.send_notify("/progress", NotifyBody::Json(b"{}".to_vec()))
.ok();
}
Ok("ok")
}),
)
.expect("register WithContext function");
let ctx = CallContext::new("/run", &peer);
let mut buf = Vec::new();
let mut out = ResponseBody::new(&mut buf);
registry.call("/run", None, &ctx, &mut out).expect("call");
assert_eq!(buf, b"\"ok\"");
assert_eq!(*observed_peer.lock().unwrap(), Some(PeerId(7)));
assert_eq!(sink.captured.lock().unwrap().as_slice(), &["/progress"]);
}
#[test]
fn call_detached_uses_a_detached_context() {
let registry = Registry::new();
let observed = Arc::new(std::sync::Mutex::new(false));
let observed_clone = Arc::clone(&observed);
registry
.register_function(
"/probe",
WithContext(move |ctx: &CallContext, _params: Option<RequestBody<'_>>| {
*observed_clone.lock().unwrap() = ctx.peer().is_none();
Ok("ok")
}),
)
.expect("register");
call(®istry, "/probe", None);
assert!(
*observed.lock().unwrap(),
"call_detached must use a detached context"
);
}
#[test]
fn body_of_borrows_the_frame_under_its_declared_format() {
let req = Message::builder()
.id(1)
.query_str("/name")
.query_format(crate::constants::QueryFormat::JsonPointer)
.body_utf8("alice")
.build();
let body = Registry::body_of(&req).expect("body").expect("present");
assert_eq!(body.bytes(), b"alice");
assert_eq!(body.format(), BodyFormat::Utf8);
}
#[test]
fn body_of_is_none_for_a_bodiless_frame() {
let req = Message::builder().id(1).query_str("/ping").build();
assert!(Registry::body_of(&req).expect("body").is_none());
}
}