use std::{
collections::BTreeMap,
fmt,
sync::{Arc, OnceLock},
time::Duration,
};
use jsonx_lib::{Parser, Value};
use crate::{
error::Error,
error_object::ErrorObject,
framing::FrameError,
handles::{Call, Peer, Responder},
id::Id,
link::{Link, Scope, Turn},
raw::{Json, Raw},
};
pub(crate) type RequestFn<S> = Box<
dyn for<'b> FnMut(
&mut S,
Params<'_>,
&mut Context<'_>,
&'b mut String,
) -> Result<Json<'b>, ErrorObject>
+ Send,
>;
pub(crate) type DeferredFn<S> =
Box<dyn FnMut(&mut S, Params<'_>, &mut Context<'_>, Responder) + Send>;
pub(crate) type NotificationFn<S> =
Box<dyn FnMut(&mut S, Params<'_>, &mut Context<'_>) -> Result<(), ErrorObject> + Send>;
pub(crate) type EventFn<S> = Box<dyn FnMut(&mut S, &Event<'_>) + Send>;
pub(crate) type InterceptFn<S> =
Box<dyn FnMut(&mut S, &str, Option<&Id<'_>>, &Params<'_>) -> Result<(), ErrorObject> + Send>;
pub(crate) enum RequestHandler<S> {
Now(RequestFn<S>),
Deferred(DeferredFn<S>),
}
pub struct Router<S> {
pub(crate) requests: BTreeMap<Box<str>, RequestHandler<S>>,
pub(crate) notifications: BTreeMap<Box<str>, NotificationFn<S>>,
pub(crate) on_event: Option<EventFn<S>>,
pub(crate) intercept: Option<InterceptFn<S>>,
}
impl<S> Router<S> {
#[must_use]
pub fn new() -> Self {
Self {
requests: BTreeMap::new(),
notifications: BTreeMap::new(),
on_event: None,
intercept: None,
}
}
#[must_use]
pub fn request<F, J>(self, method: &str, mut handler: F) -> Self
where
F: FnMut(&mut S, Params<'_>, &mut Context<'_>) -> Result<J, ErrorObject> + Send + 'static,
J: Into<Json<'static>>,
{
self.request_into(method, move |state, params, cx, _out| {
handler(state, params, cx).map(Into::into)
})
}
pub(crate) fn request_into<F>(mut self, method: &str, handler: F) -> Self
where
F: for<'b> FnMut(
&mut S,
Params<'_>,
&mut Context<'_>,
&'b mut String,
) -> Result<Json<'b>, ErrorObject>
+ Send
+ 'static,
{
let _replaced = self
.requests
.insert(method.into(), RequestHandler::Now(Box::new(handler)));
self
}
#[must_use]
pub fn deferred<F>(mut self, method: &str, handler: F) -> Self
where
F: FnMut(&mut S, Params<'_>, &mut Context<'_>, Responder) + Send + 'static,
{
let _replaced = self
.requests
.insert(method.into(), RequestHandler::Deferred(Box::new(handler)));
self
}
#[must_use]
pub fn notification<F>(self, method: &str, mut handler: F) -> Self
where
F: FnMut(&mut S, Params<'_>, &mut Context<'_>) + Send + 'static,
{
self.notification_with(method, move |state, params, cx| {
handler(state, params, cx);
Ok(())
})
}
pub(crate) fn notification_with<F>(mut self, method: &str, handler: F) -> Self
where
F: FnMut(&mut S, Params<'_>, &mut Context<'_>) -> Result<(), ErrorObject> + Send + 'static,
{
let _replaced = self.notifications.insert(method.into(), Box::new(handler));
self
}
#[must_use]
pub fn on_event<F>(mut self, hook: F) -> Self
where
F: FnMut(&mut S, &Event<'_>) + Send + 'static,
{
self.on_event = Some(Box::new(hook));
self
}
#[must_use]
pub fn intercept<F>(mut self, hook: F) -> Self
where
F: FnMut(&mut S, &str, Option<&Id<'_>>, &Params<'_>) -> Result<(), ErrorObject>
+ Send
+ 'static,
{
self.intercept = Some(Box::new(hook));
self
}
#[must_use]
pub fn has_request(&self, method: &str) -> bool {
self.requests.contains_key(method)
}
#[must_use]
pub fn has_notification(&self, method: &str) -> bool {
self.notifications.contains_key(method)
}
}
impl<S> Default for Router<S> {
fn default() -> Self {
Self::new()
}
}
impl<S> fmt::Debug for Router<S> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Router")
.field("requests", &self.requests.keys().collect::<Vec<_>>())
.field(
"notifications",
&self.notifications.keys().collect::<Vec<_>>(),
)
.finish_non_exhaustive()
}
}
#[derive(Clone, Debug)]
pub struct Params<'a> {
raw: Option<Raw<'a>>,
parser: Parser,
}
impl<'a> Params<'a> {
pub(crate) fn new(raw: Option<Raw<'a>>, parser: Parser) -> Self {
Self { raw, parser }
}
pub(crate) fn parser(&self) -> Parser {
self.parser
}
pub(crate) fn text(&self) -> Option<&str> {
self.raw.as_ref().map(Raw::as_str)
}
pub fn parse(&self) -> Result<Value<'_>, ErrorObject> {
match &self.raw {
Some(raw) => raw.parse_with(&self.parser).map_err(ErrorObject::from),
None => Ok(Value::Null),
}
}
#[must_use]
pub fn raw(&self) -> Option<&Raw<'a>> {
self.raw.as_ref()
}
#[must_use]
pub fn is_present(&self) -> bool {
self.raw.is_some()
}
#[must_use]
pub fn into_owned(self) -> Params<'static> {
Params {
raw: self.raw.map(Raw::into_owned),
parser: self.parser,
}
}
#[must_use]
pub fn into_raw(self) -> Option<Raw<'a>> {
self.raw
}
}
pub struct Context<'a> {
link: &'a Arc<dyn Link>,
stop: &'a mut bool,
id: Option<&'a Id<'a>>,
method: &'a str,
deferred: Option<u64>,
turn: OnceLock<Arc<Turn>>,
}
impl<'a> Context<'a> {
pub(crate) fn new(
link: &'a Arc<dyn Link>,
stop: &'a mut bool,
id: Option<&'a Id<'a>>,
method: &'a str,
deferred: Option<u64>,
) -> Self {
Self {
link,
stop,
id,
method,
deferred,
turn: OnceLock::new(),
}
}
pub(crate) fn scope(&self) -> Option<Scope> {
let id = self.id?;
Some(match self.deferred {
Some(serial) => Scope::Deferred {
id: id.clone().into_owned(),
serial,
},
None => Scope::Turn(Arc::clone(self.turn.get_or_init(|| Arc::new(Turn::new())))),
})
}
#[must_use]
pub fn notifier(&self) -> Option<crate::Notifier> {
self.scope()
.map(|scope| crate::Notifier::new(self.peer(), scope))
}
pub(crate) fn take_turn(&mut self) -> Option<Arc<Turn>> {
self.turn.take()
}
#[must_use]
pub fn method(&self) -> &str {
self.method
}
#[must_use]
pub fn id(&self) -> Option<&Id<'a>> {
self.id
}
pub fn notify<'j>(&self, method: &str, params: impl Into<Json<'j>>) -> Result<(), Error> {
Peer::new(Arc::clone(self.link)).notify(method, params)
}
pub fn request<'j>(&self, method: &str, params: impl Into<Json<'j>>) -> Result<Call, Error> {
Peer::new(Arc::clone(self.link)).request(method, params)
}
pub fn request_with_timeout<'j>(
&self,
method: &str,
params: impl Into<Json<'j>>,
timeout: Duration,
) -> Result<Call, Error> {
Peer::new(Arc::clone(self.link)).request_with_timeout(method, params, timeout)
}
#[must_use]
pub fn peer(&self) -> Peer {
Peer::new(Arc::clone(self.link))
}
pub fn stop(&mut self) {
*self.stop = true;
}
}
impl fmt::Debug for Context<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Context")
.field("method", &self.method)
.field("id", &self.id)
.finish_non_exhaustive()
}
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum Event<'a> {
Panicked {
method: &'a str,
message: &'a str,
},
Invalid {
error: &'a ErrorObject,
answered: bool,
},
UnknownNotification {
method: &'a str,
},
Dropped {
method: &'a str,
},
Unmatched {
id: &'a Id<'a>,
},
PeerError {
error: &'a ErrorObject,
},
Oversized {
error: FrameError,
},
Cancelled {
id: &'a Id<'a>,
},
Refused {
method: &'a str,
error: &'a ErrorObject,
},
InvalidParams {
method: &'a str,
error: &'a ErrorObject,
},
}