1use std::fmt;
7
8use crate::cbor::{CborOptions, Value, decode_cbor, encode_cbor};
9use crate::framing::{DEFAULT_MAX_FRAME_LENGTH, FrameDecoder, encode_frame};
10
11pub const PROTOCOL_VERSION: i64 = 8;
12
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub struct ProtocolValidationError(pub String);
15
16impl fmt::Display for ProtocolValidationError {
17 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
18 f.write_str(&self.0)
19 }
20}
21
22impl std::error::Error for ProtocolValidationError {}
23
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct ProtocolError {
26 pub code: String,
27 pub message: String,
28}
29
30impl ProtocolError {
31 pub fn new(code: &str, message: impl Into<String>) -> Self {
32 Self {
33 code: code.into(),
34 message: message.into(),
35 }
36 }
37}
38
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub struct SessionTarget {
41 pub server_id: String,
42 pub session_id: String,
43 pub attachment_id: String,
44}
45
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub enum RpcTarget {
48 Server { server_id: String },
50 Session(SessionTarget),
52}
53
54impl RpcTarget {
55 pub fn server_id(&self) -> &str {
56 match self {
57 RpcTarget::Server { server_id } | RpcTarget::Session(SessionTarget { server_id, .. }) => server_id,
58 }
59 }
60}
61
62#[derive(Debug, Clone, PartialEq)]
63pub enum ClientMessage {
64 Hello { version: i64 },
65 Request { id: String, target: RpcTarget, call: Value },
66 Cancel { id: String, target: RpcTarget },
67}
68
69#[derive(Debug, Clone, PartialEq)]
70pub enum ServerMessage {
71 Hello {
72 version: i64,
73 server_id: String,
74 },
75 HelloError {
76 error: ProtocolError,
77 },
78 Response {
80 id: String,
81 result: Result<Option<Value>, ProtocolError>,
82 },
83 ServiceUpdate {
84 subscription_id: String,
85 update: Value,
86 },
87 Attachment {
88 attachment: Option<SessionTarget>,
89 },
90}
91
92pub fn is_server_id(value: &str) -> bool {
94 let bytes = value.as_bytes();
95 bytes.len() == 36
96 && bytes.iter().enumerate().all(|(i, &b)| match i {
97 8 | 13 | 18 | 23 => b == b'-',
98 14 => b == b'4',
99 19 => matches!(b, b'8' | b'9' | b'a' | b'b'),
100 _ => b.is_ascii_digit() || (b'a'..=b'f').contains(&b),
101 })
102}
103
104pub fn is_supported_protocol_version(version: i64) -> bool {
105 version == PROTOCOL_VERSION
106}
107
108fn text(value: &str) -> Value {
109 Value::text(value)
110}
111
112fn target_value(target: &RpcTarget) -> Value {
113 match target {
114 RpcTarget::Server { server_id } => Value::map([("serverId", text(server_id))]),
115 RpcTarget::Session(session) => session_value(session),
116 }
117}
118
119fn session_value(session: &SessionTarget) -> Value {
120 Value::map([
121 ("serverId", text(&session.server_id)),
122 ("sessionId", text(&session.session_id)),
123 ("attachmentId", text(&session.attachment_id)),
124 ])
125}
126
127fn error_value(error: &ProtocolError) -> Value {
128 Value::map([("code", text(&error.code)), ("message", text(&error.message))])
129}
130
131impl ClientMessage {
132 pub fn to_value(&self) -> Value {
133 match self {
134 ClientMessage::Hello { version } => {
135 Value::map([("type", text("hello")), ("version", Value::Int(*version))])
136 }
137 ClientMessage::Request { id, target, call } => Value::map([
138 ("type", text("request")),
139 ("id", text(id)),
140 ("target", target_value(target)),
141 ("call", call.clone()),
142 ]),
143 ClientMessage::Cancel { id, target } => Value::map([
144 ("type", text("cancel")),
145 ("id", text(id)),
146 ("target", target_value(target)),
147 ]),
148 }
149 }
150}
151
152impl ServerMessage {
153 pub fn to_value(&self) -> Value {
154 match self {
155 ServerMessage::Hello { version, server_id } => Value::map([
156 ("type", text("hello")),
157 ("version", Value::Int(*version)),
158 ("serverId", text(server_id)),
159 ]),
160 ServerMessage::HelloError { error } => {
161 Value::map([("type", text("hello_error")), ("error", error_value(error))])
162 }
163 ServerMessage::Response { id, result: Ok(None) } => {
164 Value::map([("type", text("response")), ("id", text(id)), ("ok", Value::Bool(true))])
165 }
166 ServerMessage::Response {
167 id,
168 result: Ok(Some(result)),
169 } => Value::map([
170 ("type", text("response")),
171 ("id", text(id)),
172 ("ok", Value::Bool(true)),
173 ("result", result.clone()),
174 ]),
175 ServerMessage::Response { id, result: Err(error) } => Value::map([
176 ("type", text("response")),
177 ("id", text(id)),
178 ("ok", Value::Bool(false)),
179 ("error", error_value(error)),
180 ]),
181 ServerMessage::ServiceUpdate {
182 subscription_id,
183 update,
184 } => Value::map([
185 ("type", text("service_update")),
186 ("subscriptionId", text(subscription_id)),
187 ("update", update.clone()),
188 ]),
189 ServerMessage::Attachment { attachment } => Value::map([
190 ("type", text("attachment")),
191 ("attachment", attachment.as_ref().map_or(Value::Null, session_value)),
192 ]),
193 }
194 }
195}
196
197fn strict<'a>(value: &'a Value, required: &[&str], optional: &[&str]) -> Option<&'a [(String, Value)]> {
199 let Value::Map(entries) = value else { return None };
200 let known = |k: &str| required.contains(&k) || optional.contains(&k);
201 (entries.iter().all(|(k, _)| known(k)) && required.iter().all(|k| value.get(k).is_some())).then_some(entries)
202}
203
204fn field<'a>(value: &'a Value, key: &str) -> Option<&'a Value> {
205 value.get(key)
206}
207
208fn id(value: &Value, key: &str) -> Option<String> {
209 field(value, key)?.as_str().filter(|s| !s.is_empty()).map(str::to_owned)
210}
211
212fn server_id(value: &Value) -> Option<String> {
213 field(value, "serverId")?
214 .as_str()
215 .filter(|s| is_server_id(s))
216 .map(str::to_owned)
217}
218
219fn is_json(value: &Value) -> bool {
220 match value {
221 Value::Bytes(_) => false,
222 Value::Float(f) => f.is_finite(),
223 Value::Array(items) => items.iter().all(is_json),
224 Value::Map(entries) => entries.iter().all(|(_, v)| is_json(v)),
225 _ => true,
226 }
227}
228
229fn opaque(value: &Value, key: &str) -> Option<Value> {
230 field(value, key).filter(|v| is_json(v)).cloned()
231}
232
233fn session_target(value: &Value) -> Option<SessionTarget> {
234 strict(value, &["serverId", "sessionId", "attachmentId"], &[])?;
235 Some(SessionTarget {
236 server_id: server_id(value)?,
237 session_id: id(value, "sessionId")?,
238 attachment_id: id(value, "attachmentId")?,
239 })
240}
241
242fn target(value: &Value) -> Option<RpcTarget> {
243 if strict(value, &["serverId"], &[]).is_some() {
244 return Some(RpcTarget::Server {
245 server_id: server_id(value)?,
246 });
247 }
248 session_target(value).map(RpcTarget::Session)
249}
250
251fn protocol_error(value: &Value) -> Option<ProtocolError> {
252 strict(value, &["code", "message"], &[])?;
253 Some(ProtocolError {
254 code: id(value, "code")?,
255 message: field(value, "message")?.as_str()?.to_owned(),
256 })
257}
258
259fn integer(value: &Value) -> Option<i64> {
260 match value {
261 Value::Int(n) => Some(*n),
262 Value::Float(f) if f.fract() == 0.0 => Some(*f as i64),
263 _ => None,
264 }
265}
266
267fn client_message(value: &Value) -> Option<ClientMessage> {
268 match field(value, "type")?.as_str()? {
269 "hello" => {
270 strict(value, &["type", "version"], &[])?;
271 let version = integer(field(value, "version")?).filter(|v| *v >= 0)?;
272 Some(ClientMessage::Hello { version })
273 }
274 "request" => {
275 strict(value, &["type", "id", "target", "call"], &[])?;
276 Some(ClientMessage::Request {
277 id: id(value, "id")?,
278 target: target(field(value, "target")?)?,
279 call: opaque(value, "call")?,
280 })
281 }
282 "cancel" => {
283 strict(value, &["type", "id", "target"], &[])?;
284 Some(ClientMessage::Cancel {
285 id: id(value, "id")?,
286 target: target(field(value, "target")?)?,
287 })
288 }
289 _ => None,
290 }
291}
292
293fn server_message(value: &Value) -> Option<ServerMessage> {
294 match field(value, "type")?.as_str()? {
295 "hello" => {
296 strict(value, &["type", "version", "serverId"], &[])?;
297 let version = integer(field(value, "version")?).filter(|v| *v == PROTOCOL_VERSION)?;
298 Some(ServerMessage::Hello {
299 version,
300 server_id: server_id(value)?,
301 })
302 }
303 "hello_error" => {
304 strict(value, &["type", "error"], &[])?;
305 Some(ServerMessage::HelloError {
306 error: protocol_error(field(value, "error")?)?,
307 })
308 }
309 "response" => {
310 let id = id(value, "id")?;
311 match field(value, "ok")? {
312 Value::Bool(true) => {
313 strict(value, &["type", "id", "ok"], &["result"])?;
314 let result = match field(value, "result") {
315 Some(_) => Some(opaque(value, "result")?),
316 None => None,
317 };
318 Some(ServerMessage::Response { id, result: Ok(result) })
319 }
320 Value::Bool(false) => {
321 strict(value, &["type", "id", "ok", "error"], &[])?;
322 Some(ServerMessage::Response {
323 id,
324 result: Err(protocol_error(field(value, "error")?)?),
325 })
326 }
327 _ => None,
328 }
329 }
330 "service_update" => {
331 strict(value, &["type", "subscriptionId", "update"], &[])?;
332 Some(ServerMessage::ServiceUpdate {
333 subscription_id: id(value, "subscriptionId")?,
334 update: opaque(value, "update")?,
335 })
336 }
337 "attachment" => {
338 strict(value, &["type", "attachment"], &[])?;
339 let attachment = match field(value, "attachment")? {
340 Value::Null => None,
341 other => Some(session_target(other)?),
342 };
343 Some(ServerMessage::Attachment { attachment })
344 }
345 _ => None,
346 }
347}
348
349pub fn parse_client_message(value: &Value) -> Result<ClientMessage, ProtocolValidationError> {
350 client_message(value).ok_or_else(|| ProtocolValidationError("Invalid client protocol message".into()))
351}
352
353pub fn parse_server_message(value: &Value) -> Result<ServerMessage, ProtocolValidationError> {
354 server_message(value).ok_or_else(|| ProtocolValidationError("Invalid server protocol message".into()))
355}
356
357fn bounded(message: &str) -> String {
358 let units: Vec<u16> = message.encode_utf16().collect();
359 if units.len() <= 500 {
360 return message.to_owned();
361 }
362 format!("{}...", String::from_utf16_lossy(&units[..497]))
363}
364
365fn options(max_frame_length: usize) -> CborOptions {
366 CborOptions {
367 max_byte_length: max_frame_length,
368 ..CborOptions::default()
369 }
370}
371
372fn encode(value: &Value, kind: &str, max_frame_length: usize) -> Result<Vec<u8>, ProtocolValidationError> {
373 encode_cbor(value, &options(max_frame_length))
374 .map_err(|e| e.0)
375 .and_then(|payload| encode_frame(&payload).map_err(|e| e.0))
376 .map_err(|e| ProtocolValidationError(format!("Unable to encode {kind} protocol message: {}", bounded(&e))))
377}
378
379pub fn encode_client_message(
380 message: &ClientMessage,
381 max_frame_length: usize,
382) -> Result<Vec<u8>, ProtocolValidationError> {
383 let value = message.to_value();
384 parse_client_message(&value)?;
385 encode(&value, "client", max_frame_length)
386}
387
388pub fn encode_server_message(
389 message: &ServerMessage,
390 max_frame_length: usize,
391) -> Result<Vec<u8>, ProtocolValidationError> {
392 let value = message.to_value();
393 parse_server_message(&value)?;
394 encode(&value, "server", max_frame_length)
395}
396
397struct Decoder {
398 frames: FrameDecoder,
399 kind: &'static str,
400 max_frame_length: usize,
401 failed: bool,
402}
403
404impl Decoder {
405 fn new(kind: &'static str, max_frame_length: usize) -> Result<Self, ProtocolValidationError> {
406 let frames = FrameDecoder::new(max_frame_length).map_err(|e| ProtocolValidationError(e.0))?;
407 Ok(Self {
408 frames,
409 kind,
410 max_frame_length,
411 failed: false,
412 })
413 }
414
415 fn push<T>(
416 &mut self,
417 chunk: &[u8],
418 parse: fn(&Value) -> Result<T, ProtocolValidationError>,
419 ) -> Result<Vec<T>, ProtocolValidationError> {
420 if self.failed {
421 return Err(ProtocolValidationError(format!(
422 "{} message decoder has failed",
423 self.kind
424 )));
425 }
426 let result = self.frames.push(chunk).map_err(|e| e.0).and_then(|frames| {
427 let mut messages = Vec::new();
428 for frame in frames {
429 let value = decode_cbor(&frame, &options(self.max_frame_length)).map_err(|e| e.0)?;
430 match parse(&value) {
431 Ok(message) => messages.push(message),
432 Err(error) => return Ok(Err(error)),
433 }
434 }
435 Ok(Ok(messages))
436 });
437 let outcome = match result {
438 Ok(parsed) => parsed,
439 Err(message) => Err(ProtocolValidationError(format!(
440 "Invalid {} protocol frame: {}",
441 self.kind,
442 bounded(&message)
443 ))),
444 };
445 self.failed |= outcome.is_err();
446 outcome
447 }
448
449 fn end(&mut self) -> Result<(), ProtocolValidationError> {
450 if self.failed {
451 return Err(ProtocolValidationError(format!(
452 "{} message decoder has failed",
453 self.kind
454 )));
455 }
456 self.frames.end().map_err(|e| {
457 self.failed = true;
458 ProtocolValidationError(format!("Invalid {} protocol framing: {}", self.kind, bounded(&e.0)))
459 })
460 }
461}
462
463pub struct ClientMessageDecoder(Decoder);
464
465impl ClientMessageDecoder {
466 pub fn new(max_frame_length: usize) -> Result<Self, ProtocolValidationError> {
467 Decoder::new("client", max_frame_length).map(Self)
468 }
469
470 pub fn push(&mut self, chunk: &[u8]) -> Result<Vec<ClientMessage>, ProtocolValidationError> {
471 self.0.push(chunk, parse_client_message)
472 }
473
474 pub fn end(&mut self) -> Result<(), ProtocolValidationError> {
475 self.0.end()
476 }
477}
478
479impl Default for ClientMessageDecoder {
480 fn default() -> Self {
481 Self(Decoder {
482 frames: FrameDecoder::default(),
483 kind: "client",
484 max_frame_length: DEFAULT_MAX_FRAME_LENGTH,
485 failed: false,
486 })
487 }
488}
489
490pub struct ServerMessageDecoder(Decoder);
491
492impl ServerMessageDecoder {
493 pub fn new(max_frame_length: usize) -> Result<Self, ProtocolValidationError> {
494 Decoder::new("server", max_frame_length).map(Self)
495 }
496
497 pub fn push(&mut self, chunk: &[u8]) -> Result<Vec<ServerMessage>, ProtocolValidationError> {
498 self.0.push(chunk, parse_server_message)
499 }
500
501 pub fn end(&mut self) -> Result<(), ProtocolValidationError> {
502 self.0.end()
503 }
504}
505
506impl Default for ServerMessageDecoder {
507 fn default() -> Self {
508 Self(Decoder {
509 frames: FrameDecoder::default(),
510 kind: "server",
511 max_frame_length: DEFAULT_MAX_FRAME_LENGTH,
512 failed: false,
513 })
514 }
515}