Skip to main content

zz_p2p/protocols/
command.rs

1use std::sync::Arc;
2
3use anyhow::Result;
4use bincode::{ Decode, Encode, config };
5use futures::future::BoxFuture;
6
7use crate::context::Context;
8use crate::protocols::client_type::{ ClientType, send_bytes };
9use crate::protocols::codec::Codec;
10use crate::protocols::frame::Frame;
11
12#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, Encode, Decode)]
13pub enum Entity {
14    Node = 1,
15    Message,
16    Witness,
17    Telephone,
18    File,
19}
20
21#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, Encode, Decode)]
22pub enum Action {
23    //Node Actions
24    OnLine = 1,
25    OnLineAck,
26    OffLine,
27    Ack,
28    Update,
29
30    //Message Actions
31    SendText,
32    SendBinary,
33
34    //Witness Actions
35    Tick,
36    Check,
37
38    //Telephone Actions
39    Call,
40    HangUp,
41    Accept,
42    Reject,
43}
44
45
46pub type CommandCallback = fn(Command, Frame, Arc<Context>, Arc<ClientType>) -> BoxFuture<'static, ()>;
47
48#[derive(Clone, PartialEq, Encode, Decode, Debug)]
49pub struct Command {
50    pub entity: u8,
51    pub action: u8,
52    pub data: Option<Vec<u8>>
53}
54
55impl Command {
56    pub fn new(entity: u8, action: u8, data: Option<Vec<u8>>) -> Self {
57        Self {
58            entity,
59            action,
60            data,
61        }
62    }
63
64    fn config() -> impl bincode::config::Config {
65        config::standard().with_fixed_int_encoding().with_big_endian()
66    }
67
68    pub fn serialize(&self) -> Result<Vec<u8>> {
69        Ok(bincode::encode_to_vec(self, Self::config())?)
70    }
71
72    pub fn deserialize(bytes: &[u8]) -> Result<Self> {
73        let (cmd, _len): (Self, usize) = bincode::decode_from_slice(bytes, Self::config())?;
74        Ok(cmd)
75    }
76    /* =========================
77       Protocol helpers
78    ========================= */
79
80    /// send = build + encode (protocol layer, no IO)
81    pub fn to_bytes(entity: Entity, action: Action, data: Option<Vec<u8>>) -> Result<Vec<u8>> {
82        let cmd = Command::new(entity as u8, action as u8, data);
83        cmd.serialize()
84    }
85
86    /// receive = decode from wire bytes
87    pub fn from_bytes(bytes: &[u8]) -> Result<Command> {
88        Command::deserialize(bytes)
89    }
90
91    pub async fn send(
92        &self,
93        context: Arc<Context>,
94        client_type: &ClientType,
95        version: u8
96    ) -> Result<()> {
97        let frame = Frame::build(context, self.clone(), version).await?;
98        let bytes = Frame::to_bytes(&frame);
99        send_bytes(client_type, &bytes).await;
100        Ok(())
101    }
102}
103
104#[cfg(test)]
105mod tests {
106    use super::*;
107
108    #[test]
109    fn test_command_serialize_deserialize() {
110        let cmd = Command::new(Entity::Node as u8, Action::OnLine as u8, Some(vec![1, 2, 3, 4]));
111        let bytes = cmd.serialize().unwrap();
112        let cmd2 = Command::deserialize(&bytes).unwrap();
113        assert_eq!(cmd, cmd2);
114    }
115
116    #[test]
117    fn test_send_receive_roundtrip() {
118        let payload = vec![10, 20, 30];
119
120        let bytes = Command::to_bytes(Entity::Node, Action::OnLine, Some(payload.clone())).unwrap();
121
122        let cmd = Command::from_bytes(&bytes).unwrap();
123
124        assert_eq!(cmd.entity, Entity::Node as u8);
125        assert_eq!(cmd.action, Action::OnLine as u8);
126        assert_eq!(cmd.data, Some(payload));
127    }
128}