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
39    /// Read an encoded envelope in place, `decode` without copying: the namespace and the
40    /// payload borrowed from `bytes` (#938).
41    pub(crate) fn view(bytes: &[u8]) -> Result<EnvelopeView<'_>> {
42        match rings_codec::deserialize_prefix(bytes) {
43            Ok((view, [])) => Ok(view),
44            Ok(_) | Err(_) => Err(Error::DecodeError),
45        }
46    }
47
48    /// The encoded prefix every envelope of `namespace` starts with. The encoding is
49    /// length-prefixed, so the prefixes of distinct namespaces never prefix each other.
50    /// `namespace_prefix : str → [u8]`.
51    pub(crate) fn namespace_prefix(namespace: &str) -> Result<Vec<u8>> {
52        rings_codec::serialize(&namespace).map_err(|_| Error::EncodeError)
53    }
54}
55
56/// An [`Envelope`] read in place: the same encoding, its namespace and payload borrowed from
57/// the bytes it was read from, so routing an envelope copies neither.
58///
59/// ```text
60///   Envelope::view(b) = Ok(v)  ⟺  Envelope::decode(b) = Ok(e),
61///                                  v.namespace = e.namespace, v.payload = e.payload
62/// ```
63#[derive(Deserialize)]
64pub(crate) struct EnvelopeView<'a> {
65    /// Protocol namespace this payload belongs to.
66    pub(crate) namespace: &'a str,
67    /// Opaque protocol payload.
68    pub(crate) payload: &'a [u8],
69}
70
71#[cfg(test)]
72mod tests {
73    use bytes::Bytes;
74
75    use super::Envelope;
76
77    /// Viewing reads what decoding reads, without copying.
78    #[test]
79    fn test_viewing_an_envelope_reads_what_decoding_reads() {
80        let envelope = Envelope::new("relay", Bytes::from_static(b"payload"));
81        let bytes = envelope.encode().expect("an envelope encodes");
82        let view = Envelope::view(&bytes).expect("an encoded envelope is read in place");
83        assert_eq!(view.namespace, envelope.namespace);
84        assert_eq!(view.payload, envelope.payload.as_ref());
85        assert!(Envelope::view(&bytes[..bytes.len() - 1]).is_err());
86    }
87}