yaiko_core/
ws_protocol.rs1use serde::{Deserialize, Serialize};
4use serde_json::Value;
5
6#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
7pub struct WsEnvelope {
8 pub kind: String,
9 pub request_id: Option<String>,
10 pub payload: Value,
11}
12
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub enum WsProtocolError {
15 Empty,
16 TooLarge,
17 MalformedJson,
18 MissingKind,
19 InvalidKind,
20 MissingPayload,
21}
22
23impl WsProtocolError {
24 pub fn close_code(&self) -> u16 {
25 match self {
26 Self::TooLarge => 1009,
27 Self::MalformedJson
28 | Self::MissingKind
29 | Self::InvalidKind
30 | Self::MissingPayload
31 | Self::Empty => 1003,
32 }
33 }
34}
35
36#[derive(Debug, Clone)]
37pub struct WsProtocol {
38 max_frame_bytes: usize,
39 allowed_kinds: Vec<String>,
40}
41
42impl WsProtocol {
43 pub fn new(
44 max_frame_bytes: usize,
45 allowed_kinds: impl IntoIterator<Item = impl Into<String>>,
46 ) -> Self {
47 Self {
48 max_frame_bytes,
49 allowed_kinds: allowed_kinds.into_iter().map(Into::into).collect(),
50 }
51 }
52 pub fn decode(&self, bytes: &[u8]) -> Result<WsEnvelope, WsProtocolError> {
53 if bytes.is_empty() {
54 return Err(WsProtocolError::Empty);
55 }
56 if bytes.len() > self.max_frame_bytes {
57 return Err(WsProtocolError::TooLarge);
58 }
59 let envelope: WsEnvelope =
60 serde_json::from_slice(bytes).map_err(|_| WsProtocolError::MalformedJson)?;
61 if envelope.kind.trim().is_empty() {
62 return Err(WsProtocolError::MissingKind);
63 }
64 if !self.allowed_kinds.is_empty()
65 && !self.allowed_kinds.iter().any(|kind| kind == &envelope.kind)
66 {
67 return Err(WsProtocolError::InvalidKind);
68 }
69 if envelope.payload.is_null() {
70 return Err(WsProtocolError::MissingPayload);
71 }
72 Ok(envelope)
73 }
74 pub fn encode(&self, envelope: &WsEnvelope) -> Result<Vec<u8>, WsProtocolError> {
75 let bytes = serde_json::to_vec(envelope).map_err(|_| WsProtocolError::MalformedJson)?;
76 if bytes.len() > self.max_frame_bytes {
77 return Err(WsProtocolError::TooLarge);
78 }
79 Ok(bytes)
80 }
81}
82
83#[cfg(test)]
84mod tests {
85 use super::*;
86 fn protocol() -> WsProtocol {
87 WsProtocol::new(128, ["chat", "typing"])
88 }
89
90 #[test]
91 fn encodes_and_decodes_typed_envelopes() {
92 let protocol = protocol();
93 let envelope = WsEnvelope {
94 kind: "chat".into(),
95 request_id: Some("r1".into()),
96 payload: serde_json::json!({"text":"hello"}),
97 };
98 assert_eq!(
99 protocol
100 .decode(&protocol.encode(&envelope).unwrap())
101 .unwrap(),
102 envelope
103 );
104 }
105
106 #[test]
107 fn rejects_malformed_oversized_and_invalid_messages() {
108 let protocol = protocol();
109 assert_eq!(protocol.decode(b""), Err(WsProtocolError::Empty));
110 assert_eq!(
111 protocol.decode(b"not-json"),
112 Err(WsProtocolError::MalformedJson)
113 );
114 let invalid = serde_json::json!({"kind":"unknown","payload":{}});
115 assert_eq!(
116 protocol.decode(&serde_json::to_vec(&invalid).unwrap()),
117 Err(WsProtocolError::InvalidKind)
118 );
119 assert_eq!(WsProtocolError::TooLarge.close_code(), 1009);
120 }
121
122 #[test]
123 fn enforces_frame_size_and_required_fields() {
124 let protocol = WsProtocol::new(16, std::iter::empty::<String>());
125 let payload = serde_json::json!({"kind":"chat","payload":{"value":"large"}});
126 assert_eq!(
127 protocol.decode(&serde_json::to_vec(&payload).unwrap()),
128 Err(WsProtocolError::TooLarge)
129 );
130 let missing = serde_json::json!({"kind":"chat","payload":null});
131 let permissive = WsProtocol::new(128, std::iter::empty::<String>());
132 assert_eq!(
133 permissive.decode(&serde_json::to_vec(&missing).unwrap()),
134 Err(WsProtocolError::MissingPayload)
135 );
136 }
137}