diff options
author | hozan23 <hozan23@karyontech.net> | 2024-05-21 02:20:45 +0200 |
---|---|---|
committer | hozan23 <hozan23@karyontech.net> | 2024-05-22 15:02:06 +0200 |
commit | 028940fe3e0a87cdc421a6d07f1ecfb6c208b9d0 (patch) | |
tree | 3272d5c71cafb098e548cb9811e8f9ddc260ef2f /jsonrpc/src/server/pubsub_service.rs | |
parent | 0f0cefb62ee8b641dcabcc0a2a1cf019c1de4843 (diff) |
jsonrpc: support pubsub
Diffstat (limited to 'jsonrpc/src/server/pubsub_service.rs')
-rw-r--r-- | jsonrpc/src/server/pubsub_service.rs | 67 |
1 files changed, 67 insertions, 0 deletions
diff --git a/jsonrpc/src/server/pubsub_service.rs b/jsonrpc/src/server/pubsub_service.rs new file mode 100644 index 0000000..5b4bf9a --- /dev/null +++ b/jsonrpc/src/server/pubsub_service.rs @@ -0,0 +1,67 @@ +use std::{future::Future, pin::Pin}; + +use crate::Result; + +use super::channel::ArcChannel; + +/// Represents the RPC method +pub type PubSubRPCMethod<'a> = + Box<dyn Fn(ArcChannel, serde_json::Value) -> PubSubRPCMethodOutput<'a> + Send + 'a>; +type PubSubRPCMethodOutput<'a> = + Pin<Box<dyn Future<Output = Result<serde_json::Value>> + Send + Sync + 'a>>; + +/// Defines the interface for an RPC service. +pub trait PubSubRPCService: Sync + Send { + fn get_pubsub_method<'a>(&'a self, name: &'a str) -> Option<PubSubRPCMethod>; + fn name(&self) -> String; +} + +/// Implements the [`PubSubRPCService`] trait for a provided type. +/// +/// # Example +/// +/// ``` +/// use serde_json::Value; +/// +/// use karyon_jsonrpc::{Error, impl_rpc_service}; +/// +/// struct Hello {} +/// +/// impl Hello { +/// async fn foo(&self, params: Value) -> Result<Value, Error> { +/// Ok(serde_json::json!("foo!")) +/// } +/// +/// async fn bar(&self, params: Value) -> Result<Value, Error> { +/// Ok(serde_json::json!("bar!")) +/// } +/// } +/// +/// impl_rpc_service!(Hello, foo, bar); +/// +/// ``` +#[macro_export] +macro_rules! impl_pubsub_rpc_service { + ($t:ty, $($m:ident),*) => { + impl karyon_jsonrpc::PubSubRPCService for $t { + fn get_pubsub_method<'a>( + &'a self, + name: &'a str + ) -> Option<karyon_jsonrpc::PubSubRPCMethod> { + match name { + $( + stringify!($m) => { + Some(Box::new(move |chan: karyon_jsonrpc::ArcChannel, params: serde_json::Value| Box::pin(self.$m(chan, params)))) + } + )* + _ => None, + } + + + } + fn name(&self) -> String{ + stringify!($t).to_string() + } + } + }; +} |