potatonet_common/
lib.rs

1#[macro_use]
2extern crate serde_derive;
3#[macro_use]
4extern crate thiserror;
5#[macro_use]
6extern crate anyhow;
7
8#[doc(hidden)]
9pub mod bus_message;
10
11mod error;
12mod id;
13mod request;
14
15pub use error::*;
16pub use id::*;
17pub use request::*;
18
19use serde::de::DeserializeOwned;
20use serde::Serialize;
21use std::io::Cursor;
22
23pub type Result<T> = anyhow::Result<T>;
24
25/// 订阅消息
26pub trait Topic: Serialize + DeserializeOwned + Send + Sync + 'static {
27    fn name() -> &'static str;
28
29    fn encode(&self) -> Result<Vec<u8>> {
30        let data = rmp_serde::to_vec(self)?;
31        Ok(data)
32    }
33
34    fn decode(data: &[u8]) -> Result<Self> {
35        let msg = rmp_serde::from_read(Cursor::new(data))?;
36        Ok(msg)
37    }
38}
39
40/// 上下文
41#[async_trait::async_trait]
42pub trait Context {
43    /// 调用服务
44    async fn call<T, R>(&self, service_name: &str, request: Request<T>) -> Result<Response<R>>
45    where
46        T: Serialize + Send + 'static,
47        R: DeserializeOwned + Send + 'static;
48
49    /// 发送通知
50    async fn notify<T: Serialize + Send + 'static>(&self, service_name: &str, request: Request<T>);
51
52    /// 给指定服务发送通知
53    async fn notify_to<T: Serialize + Send + 'static>(&self, to: ServiceId, request: Request<T>);
54
55    /// 发布消息
56    async fn publish_with_topic<T: Topic>(&self, topic: &str, msg: T);
57
58    /// 发布消息
59    async fn publish<T: Topic>(&self, msg: T) {
60        self.publish_with_topic(T::name(), msg).await
61    }
62}