serde_tc/
lib.rs

1/*!
2`serde-tc` is a library for de/serializing method invocations for trait objects.
3
4`serde-tc-macro` provides a macro for generating various code for a particular trait defiiniation.
51. A dispatcher; it takes the method name and the arguemnts (an opaque string) and invokes the method on the object.
62. A encoder; it defines a copy of the methods of the trait. Instead of the original return types,
7the newly defined methods return encoded strings that can be directly used by the dispatcher.
8
9`serde-tc` also provides a convenient module `http`,
10which automatically builds a HTTP server using the given trait objects
11to serve as a RPC server. The module also provides a `stub` implementation,
12which can be used as the HTTP client when the server is built with the same trait.
13
14Please refer to `serde-tc/tests/integration_tests.rs` for the actual usage.
15*/
16
17pub mod http;
18
19use async_trait::async_trait;
20pub use serde;
21pub use serde_tc_macro::*;
22use std::sync::Arc;
23use thiserror::Error;
24
25#[derive(Error, Debug)]
26pub enum Error<T: std::error::Error> {
27    #[error("`{0}`")]
28    MethodNotFound(String),
29    #[error("`{0}`")]
30    ArgumentNotFound(String),
31    #[error("`{0}`")]
32    Parse(T),
33}
34
35pub trait DispatchStringTuple {
36    type Error: std::error::Error;
37    fn dispatch(&self, method: &str, arguments: &str) -> Result<String, Error<Self::Error>>;
38}
39
40pub trait DispatchStringDict {
41    type Error: std::error::Error;
42    type Poly;
43    fn dispatch(&self, method: &str, arguments: &str) -> Result<String, Error<Self::Error>>;
44}
45
46#[async_trait]
47pub trait DispatchStringTupleAsync {
48    type Error: std::error::Error;
49    async fn dispatch(&self, method: &str, arguments: &str) -> Result<String, Error<Self::Error>>;
50}
51
52#[async_trait]
53pub trait DispatchStringDictAsync {
54    type Error: std::error::Error;
55    type Poly;
56    async fn dispatch(&self, method: &str, arguments: &str) -> Result<String, Error<Self::Error>>;
57}
58
59#[async_trait]
60impl<T> DispatchStringDictAsync for Arc<T>
61where
62    T: DispatchStringDictAsync + Send + Sync + 'static + ?Sized,
63{
64    type Error = T::Error;
65    type Poly = T::Poly;
66    async fn dispatch(&self, method: &str, arguments: &str) -> Result<String, Error<Self::Error>> {
67        (self.as_ref() as &T).dispatch(method, arguments).await
68    }
69}
70
71#[async_trait]
72impl<T> DispatchStringTupleAsync for Arc<T>
73where
74    T: DispatchStringTupleAsync + Send + Sync + 'static + ?Sized,
75{
76    type Error = T::Error;
77    async fn dispatch(&self, method: &str, arguments: &str) -> Result<String, Error<Self::Error>> {
78        (self.as_ref() as &T).dispatch(method, arguments).await
79    }
80}
81
82#[async_trait]
83pub trait StubCall: Send + Sync {
84    type Error;
85
86    async fn call(&self, method: &'static str, params: String) -> Result<String, Self::Error>;
87}