Skip to main content

synapse_rpc/codec/
json.rs

1//! JSON codec implementation
2
3use super::{Codec, ContentType};
4use anyhow::{Context, Result};
5use bytes::Bytes;
6use synapse_proto::SynapseMessage;
7
8/// JSON codec for human-readable serialization
9///
10/// Uses serde_json for encoding/decoding.
11/// This format is intended for debugging, testing, and Postman support.
12pub struct JsonCodec;
13
14impl Codec for JsonCodec {
15    fn encode(message: &SynapseMessage) -> Result<Bytes> {
16        let json = serde_json::to_vec(message).context("Failed to serialize to JSON")?;
17        Ok(Bytes::from(json))
18    }
19
20    fn decode(data: &[u8]) -> Result<SynapseMessage> {
21        serde_json::from_slice(data).context("Failed to deserialize JSON")
22    }
23
24    fn content_type() -> ContentType {
25        ContentType::Json
26    }
27}
28
29#[cfg(test)]
30mod tests {
31    use super::*;
32    use synapse_proto::{MessageKind, RpcRequest, synapse_message};
33
34    #[test]
35    fn test_synapse_message_roundtrip() {
36        let msg = SynapseMessage {
37            protocol_version: 1_000_000,
38            kind: MessageKind::RpcRequest as i32,
39            request_id: Bytes::from(vec![
40                1u8, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
41            ]),
42            message: Some(synapse_message::Message::RpcRequest(RpcRequest {
43                interface_id: 12345,
44                method_id: 67890,
45                headers: vec![],
46                payload: Bytes::from("test payload"),
47                sent_at_unix_ms: 1234567890123,
48            })),
49        };
50
51        let encoded = JsonCodec::encode(&msg).unwrap();
52        let decoded = JsonCodec::decode(&encoded).unwrap();
53
54        assert_eq!(msg.protocol_version, decoded.protocol_version);
55        assert_eq!(msg.kind, decoded.kind);
56        assert_eq!(msg.request_id, decoded.request_id);
57    }
58}