Skip to main content

synapse_rpc/codec/
mod.rs

1//! Codec layer for serializing/deserializing Synapse messages
2//!
3//! This module provides codec implementations for converting between
4//! SynapseMessage (the wire envelope) and bytes. Codecs handle pure
5//! serialization - they don't handle I/O, framing, or transport concerns.
6
7use anyhow::Result;
8use bytes::Bytes;
9use synapse_proto::SynapseMessage;
10
11pub mod content_type;
12pub mod json;
13pub mod protobuf;
14
15pub use content_type::ContentType;
16pub use json::JsonCodec;
17pub use protobuf::ProtobufCodec;
18
19/// Codec trait for serializing/deserializing SynapseMessage envelope
20pub trait Codec: Send + Sync {
21    /// Encode a SynapseMessage to bytes
22    fn encode(message: &SynapseMessage) -> Result<Bytes>
23    where
24        Self: Sized;
25
26    /// Decode bytes to a SynapseMessage
27    fn decode(data: &[u8]) -> Result<SynapseMessage>
28    where
29        Self: Sized;
30
31    /// Get the content type this codec produces
32    fn content_type() -> ContentType
33    where
34        Self: Sized;
35}
36
37/// Get the appropriate encoder function for a content type
38pub fn encode_message(message: &SynapseMessage, content_type: ContentType) -> Result<Bytes> {
39    match content_type {
40        ContentType::Protobuf => ProtobufCodec::encode(message),
41        ContentType::Json => JsonCodec::encode(message),
42    }
43}
44
45/// Get the appropriate decoder function for a content type
46pub fn decode_message(data: &[u8], content_type: ContentType) -> Result<SynapseMessage> {
47    match content_type {
48        ContentType::Protobuf => ProtobufCodec::decode(data),
49        ContentType::Json => JsonCodec::decode(data),
50    }
51}