Skip to main content

muta_protocol/traits/
network.rs

1use std::{error::Error, fmt::Debug};
2
3use async_trait::async_trait;
4use bytes::Bytes;
5use derive_more::Display;
6use serde::{Deserialize, Serialize};
7
8use crate::{traits::Context, types::Address, ProtocolError, ProtocolErrorKind, ProtocolResult};
9
10#[derive(Debug)]
11pub enum Priority {
12    High,
13    Normal,
14}
15
16#[async_trait]
17pub trait MessageCodec: Sized + Send + Debug + 'static {
18    async fn encode(&mut self) -> ProtocolResult<Bytes>;
19
20    async fn decode(bytes: Bytes) -> ProtocolResult<Self>;
21}
22
23#[derive(Debug, Display)]
24#[display(fmt = "cannot serde encode or decode: {}", _0)]
25struct SerdeError(Box<dyn Error + Send>);
26
27impl Error for SerdeError {}
28
29impl From<SerdeError> for ProtocolError {
30    fn from(err: SerdeError) -> ProtocolError {
31        ProtocolError::new(ProtocolErrorKind::Network, Box::new(err))
32    }
33}
34
35#[async_trait]
36impl<T> MessageCodec for T
37where
38    T: Serialize + for<'a> Deserialize<'a> + Send + Debug + 'static,
39{
40    async fn encode(&mut self) -> ProtocolResult<Bytes> {
41        let bytes = bincode::serialize(self).map_err(|e| SerdeError(Box::new(e)))?;
42
43        Ok(bytes.into())
44    }
45
46    async fn decode(bytes: Bytes) -> ProtocolResult<Self> {
47        bincode::deserialize::<T>(&bytes.as_ref()).map_err(|e| SerdeError(Box::new(e)).into())
48    }
49}
50
51#[async_trait]
52pub trait Gossip: Send + Sync {
53    async fn broadcast<M>(&self, cx: Context, end: &str, msg: M, p: Priority) -> ProtocolResult<()>
54    where
55        M: MessageCodec;
56
57    async fn users_cast<M>(
58        &self,
59        cx: Context,
60        end: &str,
61        users: Vec<Address>,
62        msg: M,
63        p: Priority,
64    ) -> ProtocolResult<()>
65    where
66        M: MessageCodec;
67}
68
69#[async_trait]
70pub trait Rpc: Send + Sync {
71    async fn call<M, R>(&self, ctx: Context, end: &str, msg: M, pri: Priority) -> ProtocolResult<R>
72    where
73        M: MessageCodec,
74        R: MessageCodec;
75
76    async fn response<M>(&self, cx: Context, end: &str, msg: M, p: Priority) -> ProtocolResult<()>
77    where
78        M: MessageCodec;
79}
80
81#[async_trait]
82pub trait MessageHandler: Sync + Send + 'static {
83    type Message: MessageCodec;
84
85    async fn process(&self, ctx: Context, msg: Self::Message) -> ProtocolResult<()>;
86}