use serde::de::DeserializeOwned;
use serde_json::Value;
#[derive(Debug)]
#[non_exhaustive]
pub enum MethodDispatchError {
UnknownMethod {
method: String,
},
InvalidPayload {
method: String,
source: serde_json::Error,
},
}
impl std::fmt::Display for MethodDispatchError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::UnknownMethod { method } => write!(f, "unknown method `{method}`"),
Self::InvalidPayload { method, source } => {
write!(f, "invalid payload for method `{method}`: {source}")
}
}
}
}
impl std::error::Error for MethodDispatchError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::UnknownMethod { .. } => None,
Self::InvalidPayload { source, .. } => Some(source),
}
}
}
pub(crate) fn deserialize<T: DeserializeOwned>(
method: &str,
payload: Value,
) -> Result<T, MethodDispatchError> {
serde_json::from_value(payload).map_err(|source| MethodDispatchError::InvalidPayload {
method: method.to_owned(),
source,
})
}
macro_rules! impl_message_dispatch {
(
$enum:ident {
$( $(#[$meta:meta])* $variant:ident => $method:expr, )*
}
$(extension $ext_variant:ident($ext_type:ty);)?
) => {
impl $enum {
#[must_use]
pub fn method(&self) -> &str {
match self {
$( $(#[$meta])* Self::$variant(_) => $method, )*
$(Self::$ext_variant(payload) => &payload.method,)?
}
}
#[must_use]
pub fn supports_method(method: &str) -> bool {
match method {
$( $(#[$meta])* m if m == $method => true, )*
_ => impl_message_dispatch!(@extension method $(, $ext_variant)?),
}
}
pub fn from_method_and_params(
method: &str,
params: &serde_json::Value,
) -> Result<Self, crate::MethodDispatchError> {
match method {
$( $(#[$meta])* m if m == $method =>
crate::dispatch::deserialize(method, params.clone()).map(Self::$variant), )*
_ => {
$(
if method.starts_with('_') {
return crate::dispatch::deserialize(method, params.clone())
.map(|mut payload: $ext_type| {
payload.method = method.into();
Self::$ext_variant(payload)
});
}
)?
Err(crate::MethodDispatchError::UnknownMethod {
method: method.to_owned(),
})
}
}
}
}
};
(@extension $method:ident, $variant:ident) => { $method.starts_with('_') };
(@extension $method:ident) => { false };
}
macro_rules! impl_request_dispatch {
(
$request:ident => $response:ident {
$( $(#[$meta:meta])* $req_variant:ident => $resp_variant:ident: $method:expr, )*
}
extension $ext_req:ident($ext_type:ty) => $ext_resp:ident;
) => {
impl_message_dispatch! {
$request {
$( $(#[$meta])* $req_variant => $method, )*
}
extension $ext_req($ext_type);
}
impl $response {
pub fn from_method_and_result(
method: &str,
result: serde_json::Value,
) -> Result<Self, crate::MethodDispatchError> {
match method {
$( $(#[$meta])* m if m == $method =>
crate::dispatch::deserialize(method, result).map(Self::$resp_variant), )*
_ if method.starts_with('_') =>
crate::dispatch::deserialize(method, result).map(Self::$ext_resp),
_ => Err(crate::MethodDispatchError::UnknownMethod {
method: method.to_owned(),
}),
}
}
}
};
}