use std::{collections::BTreeMap, fmt, sync::Arc, time::Duration};
use jsonx_lib::{Parser, Value};
use crate::{
error::Error,
error_object::ErrorObject,
framing::FrameError,
handles::{Call, Peer, Responder},
id::Id,
link::Link,
raw::{Json, Raw},
};
pub(crate) type RequestFn<S> = Box<
dyn FnMut(&mut S, Params<'_>, &mut Context<'_>) -> Result<Json<'static>, 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<'_>) + Send>;
pub(crate) type EventFn<S> = Box<dyn FnMut(&mut S, &Event<'_>) + 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>>,
}
impl<S> Router<S> {
#[must_use]
pub fn new() -> Self {
Self {
requests: BTreeMap::new(),
notifications: BTreeMap::new(),
on_event: None,
}
}
#[must_use]
pub fn request<F, J>(mut self, method: &str, mut handler: F) -> Self
where
F: FnMut(&mut S, Params<'_>, &mut Context<'_>) -> Result<J, ErrorObject> + Send + 'static,
J: Into<Json<'static>>,
{
let boxed: RequestFn<S> = Box::new(
move |state: &mut S, params: Params<'_>, cx: &mut Context<'_>| {
handler(state, params, cx).map(Into::into)
},
);
let _replaced = self
.requests
.insert(method.into(), RequestHandler::Now(boxed));
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>(mut self, method: &str, handler: F) -> Self
where
F: FnMut(&mut S, Params<'_>, &mut Context<'_>) + 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 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 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,
}
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,
) -> Self {
Self {
link,
stop,
id,
method,
}
}
#[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>,
},
}