Skip to main content

rings_node/extension/ext/
envelope.rs

1//! Wire envelope — the namespaced message carried over the P2P transport.
2
3use bytes::Bytes;
4use serde::Deserialize;
5use serde::Serialize;
6
7use crate::error::Error;
8use crate::error::Result;
9
10/// Namespaced message envelope carried over the P2P transport codec, in place of
11/// the old closed `BackendMessage` enum. `payload` is opaque to the core.
12#[derive(Clone, Debug, Serialize, Deserialize)]
13pub struct Envelope {
14    /// Protocol namespace this payload belongs to.
15    pub namespace: String,
16    /// Opaque protocol payload; the inner codec is the protocol's own business.
17    pub payload: Bytes,
18}
19
20impl Envelope {
21    /// Build an envelope.
22    pub fn new(namespace: impl Into<String>, payload: Bytes) -> Self {
23        Self {
24            namespace: namespace.into(),
25            payload,
26        }
27    }
28
29    /// Encode for the P2P transport. `encode : Envelope → [u8]`.
30    pub fn encode(&self) -> Result<Vec<u8>> {
31        rings_codec::serialize(self).map_err(|_| Error::EncodeError)
32    }
33
34    /// Decode from the P2P transport. `decode : [u8] ⇀ Envelope` (partial).
35    pub fn decode(bytes: &[u8]) -> Result<Self> {
36        rings_codec::deserialize(bytes).map_err(|_| Error::DecodeError)
37    }
38}