message.rs

Overview

This file defines the NetMessage struct and associated methods for encapsulating, serializing, compressing, transmitting, decompressing, and deserializing network messages. The primary purpose is to provide a robust and efficient mechanism for packaging arbitrary data types into transferable messages with metadata, optimized for network communication scenarios where message size and serialization/deserialization performance are critical.

The file implements features such as:

The NetMessage type uses Arc<Vec<u8>> to allow shared ownership of the message payload bytes, facilitating efficient cloning and concurrency.

NetMessage Struct

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NetMessage {
    pub delivery_start_timestamp_ms: u64,
    pub id: String,
    pub label: String,
    pub compressed: bool,
    pub data: Arc<Vec<u8>>,
    pub last_sender_is_proxy: bool,
    #[serde(skip)]
    pub received_at: u64,
}

Fields:

Constants

Methods

transfer_size(msg: &NetMessage) -> u64

Calculates the approximate serialized size in bytes of the given NetMessage instance.

delivery_duration_ms(&self) -> Result<u64, String>

Computes the elapsed time in milliseconds since the message delivery was started.

encode<Message: Debug + Serialize>(message: &Message) -> anyhow::Result<(Self, usize)>

Encodes and optionally compresses a given message into a NetMessage.

decode<Message: DeserializeOwned>(&self) -> anyhow::Result<(Message, usize, usize)>

Decodes and decompresses a NetMessage back into the original message type.

Important Implementation Details

Interaction with Other System Components

Mermaid Class Diagram

classDiagram
class NetMessage {
+u64 delivery_start_timestamp_ms
+String id
+String label
+bool compressed
+Arc<Vec<u8>> data
+bool last_sender_is_proxy
+u64 received_at
+transfer_size(msg: &NetMessage) uint64
+delivery_duration_ms() Result<uint64, String>
+encode<Message: Debug + Serialize>(message: &Message) Result<(NetMessage, usize), anyhow::Error>
+decode<Message: DeserializeOwned>() Result<(Message, usize, usize), anyhow::Error>
}

This diagram illustrates the NetMessage struct with its fields and primary methods, emphasizing the structure and functionality encapsulated within this file.