1use alloc::sync::Arc;
26use alloc::vec::Vec;
27
28use serde::{Deserialize, Serialize};
29use serde_json::value::RawValue;
30
31use crate::clock::Stamp;
32use crate::session::{CodecError, EnvelopeCodec, Inbound, Outbound, Payload, RpcError};
33
34#[derive(Clone, Copy, Default)]
36pub struct AimxCodec;
37
38#[derive(Serialize, Deserialize)]
43struct Frame<'a> {
44 t: &'a str,
45 #[serde(default, skip_serializing_if = "Option::is_none")]
46 id: Option<u64>,
47 #[serde(default, skip_serializing_if = "Option::is_none")]
48 seq: Option<u64>,
49 #[serde(default, skip_serializing_if = "Option::is_none")]
51 last: Option<bool>,
52 #[serde(default, borrow, skip_serializing_if = "Option::is_none")]
53 method: Option<&'a str>,
54 #[serde(default, borrow, skip_serializing_if = "Option::is_none")]
55 topic: Option<&'a str>,
56 #[serde(default, borrow, skip_serializing_if = "Option::is_none")]
57 sub: Option<&'a str>,
58 #[serde(default, skip_serializing_if = "Option::is_none")]
62 ts: Option<u64>,
63 #[serde(default, borrow, skip_serializing_if = "Option::is_none")]
64 params: Option<&'a RawValue>,
65 #[serde(default, borrow, skip_serializing_if = "Option::is_none")]
66 payload: Option<&'a RawValue>,
67 #[serde(default, borrow, skip_serializing_if = "Option::is_none")]
68 data: Option<&'a RawValue>,
69 #[serde(default, borrow, skip_serializing_if = "Option::is_none")]
70 ok: Option<&'a RawValue>,
71 #[serde(default, borrow, skip_serializing_if = "Option::is_none")]
72 err: Option<&'a str>,
73}
74
75impl<'a> Frame<'a> {
76 fn tagged(t: &'a str) -> Self {
78 Self {
79 t,
80 id: None,
81 seq: None,
82 last: None,
83 method: None,
84 topic: None,
85 sub: None,
86 ts: None,
87 params: None,
88 payload: None,
89 data: None,
90 ok: None,
91 err: None,
92 }
93 }
94}
95
96fn as_raw(bytes: &[u8]) -> Result<&RawValue, CodecError> {
99 serde_json::from_slice(bytes).map_err(|_| CodecError::Malformed)
100}
101
102pub fn value_reply(value: &[u8], ts: Stamp) -> Payload {
110 let mut digits = [0u8; 20];
111 let ts = decimal(ts.as_nanos(), &mut digits);
112 let pieces: [&[u8]; 5] = [br#"{"value":"#, value, br#","ts":"#, ts, b"}"];
113 let mut reply = Vec::with_capacity(pieces.iter().map(|piece| piece.len()).sum());
114 for piece in pieces {
115 reply.extend_from_slice(piece);
116 }
117 Payload::from(reply)
118}
119
120fn decimal(mut n: u64, buf: &mut [u8; 20]) -> &[u8] {
122 let mut start = buf.len();
123 loop {
124 start -= 1;
125 buf[start] = b'0' + (n % 10) as u8;
126 n /= 10;
127 if n == 0 {
128 return &buf[start..];
129 }
130 }
131}
132
133fn stamp_of(ts: Option<u64>, sub: &str) -> Result<Stamp, CodecError> {
136 ts.map(Stamp::from_nanos)
137 .ok_or_else(|| CodecError::MissingStamp { sub: sub.into() })
138}
139
140fn payload_of(raw: Option<&RawValue>) -> Payload {
141 match raw {
142 Some(r) => Arc::from(r.get().as_bytes()),
143 None => Arc::from(&b"null"[..]),
144 }
145}
146
147fn err_code(e: &RpcError) -> &'static str {
148 match e {
149 RpcError::NotFound => "not_found",
150 RpcError::Denied => "denied",
151 RpcError::Internal => "internal",
152 RpcError::VersionMismatch => "version_mismatch",
153 RpcError::Protocol => "internal",
155 }
156}
157
158fn code_err(s: &str) -> RpcError {
159 match s {
160 "not_found" => RpcError::NotFound,
161 "denied" => RpcError::Denied,
162 "version_mismatch" => RpcError::VersionMismatch,
163 _ => RpcError::Internal,
164 }
165}
166
167fn write_frame(out: &mut alloc::vec::Vec<u8>, frame: &Frame<'_>) -> Result<(), CodecError> {
168 let bytes = serde_json::to_vec(frame).map_err(|_| CodecError::Malformed)?;
171 out.extend_from_slice(&bytes);
172 Ok(())
173}
174
175fn write_frame_splicing_data(
207 out: &mut alloc::vec::Vec<u8>,
208 frame: &Frame<'_>,
209 data: &[u8],
210) -> Result<(), CodecError> {
211 debug_assert!(frame.data.is_none(), "data must be spliced, not serialized");
212 debug_assert!(
213 frame.ok.is_none() && frame.err.is_none(),
214 "fields declared after `data` must be None so the spliced `data` stays last"
215 );
216 let scaffold = serde_json::to_vec(frame).map_err(|_| CodecError::Malformed)?;
217 let Some((&b'}', head)) = scaffold.split_last() else {
219 return Err(CodecError::Malformed);
220 };
221 out.extend_from_slice(head);
222 out.extend_from_slice(br#","data":"#);
223 out.extend_from_slice(data);
224 out.push(b'}');
225 Ok(())
226}
227
228impl EnvelopeCodec for AimxCodec {
229 fn decode(&self, frame: &[u8]) -> Result<Inbound, CodecError> {
231 let f: Frame = serde_json::from_slice(frame).map_err(|_| CodecError::Malformed)?;
232 match f.t {
233 "req" => Ok(Inbound::Request {
234 id: f.id.ok_or(CodecError::Malformed)?,
235 method: f.method.ok_or(CodecError::Malformed)?.into(),
236 params: payload_of(f.params),
237 }),
238 "sub" => Ok(Inbound::Subscribe {
239 id: f.id.ok_or(CodecError::Malformed)?,
240 topic: f.topic.ok_or(CodecError::Malformed)?.into(),
241 }),
242 "unsub" => Ok(Inbound::Unsubscribe {
243 sub: f.sub.ok_or(CodecError::Malformed)?.into(),
244 }),
245 "write" => Ok(Inbound::Write {
246 topic: f.topic.ok_or(CodecError::Malformed)?.into(),
247 payload: payload_of(f.payload),
248 }),
249 "ping" => Ok(Inbound::Ping),
250 _ => Err(CodecError::Malformed),
251 }
252 }
253
254 fn encode(&self, msg: Outbound<'_>, out: &mut alloc::vec::Vec<u8>) -> Result<(), CodecError> {
255 match msg {
256 Outbound::Reply { id, result } => {
257 let mut frame = Frame::tagged("reply");
258 frame.id = Some(id);
259 match &result {
260 Ok(data) => {
261 let raw = as_raw(data)?;
262 frame.ok = Some(raw);
263 write_frame(out, &frame)
264 }
265 Err(e) => {
266 frame.err = Some(err_code(e));
267 write_frame(out, &frame)
268 }
269 }
270 }
271 Outbound::Event {
272 sub,
273 seq,
274 topic,
275 ts,
276 data,
277 } => {
278 let mut frame = Frame::tagged("event");
279 frame.sub = Some(sub);
280 frame.seq = Some(seq);
281 frame.topic = topic;
282 frame.ts = Some(ts.as_nanos());
283 write_frame_splicing_data(out, &frame, &data)
286 }
287 Outbound::Snapshot {
288 sub,
289 seq,
290 last,
291 topic,
292 ts,
293 data,
294 } => {
295 let raw = as_raw(&data)?;
296 let mut frame = Frame::tagged("snap");
297 frame.sub = Some(sub);
298 frame.seq = Some(seq);
299 frame.last = last.then_some(true);
302 frame.topic = Some(topic);
303 frame.ts = Some(ts.as_nanos());
304 frame.data = Some(raw);
305 write_frame(out, &frame)
306 }
307 Outbound::Pong => write_frame(out, &Frame::tagged("pong")),
308 Outbound::Subscribed { sub } => {
311 let mut frame = Frame::tagged("subscribed");
312 frame.sub = Some(sub);
313 write_frame(out, &frame)
314 }
315 }
316 }
317
318 fn encode_inbound(
320 &self,
321 msg: Inbound,
322 out: &mut alloc::vec::Vec<u8>,
323 ) -> Result<(), CodecError> {
324 match msg {
325 Inbound::Request { id, method, params } => {
326 let raw = as_raw(¶ms)?;
327 let mut frame = Frame::tagged("req");
328 frame.id = Some(id);
329 frame.method = Some(&method);
330 frame.params = Some(raw);
331 write_frame(out, &frame)
332 }
333 Inbound::Subscribe { id, topic } => {
334 let mut frame = Frame::tagged("sub");
335 frame.id = Some(id);
336 frame.topic = Some(&topic);
337 write_frame(out, &frame)
338 }
339 Inbound::Unsubscribe { sub } => {
340 let mut frame = Frame::tagged("unsub");
341 frame.sub = Some(&sub);
342 write_frame(out, &frame)
343 }
344 Inbound::Write { topic, payload } => {
345 let raw = as_raw(&payload)?;
346 let mut frame = Frame::tagged("write");
347 frame.topic = Some(&topic);
348 frame.payload = Some(raw);
349 write_frame(out, &frame)
350 }
351 Inbound::Ping => write_frame(out, &Frame::tagged("ping")),
352 }
353 }
354
355 fn decode_outbound<'a>(&self, frame: &'a [u8]) -> Result<Outbound<'a>, CodecError> {
356 let f: Frame<'a> = serde_json::from_slice(frame).map_err(|_| CodecError::Malformed)?;
357 match f.t {
358 "reply" => {
359 let id = f.id.ok_or(CodecError::Malformed)?;
360 let result = match (f.ok, f.err) {
361 (Some(_), _) => Ok(payload_of(f.ok)),
362 (None, Some(code)) => Err(code_err(code)),
363 (None, None) => return Err(CodecError::Malformed),
364 };
365 Ok(Outbound::Reply { id, result })
366 }
367 "event" => {
368 let sub = f.sub.ok_or(CodecError::Malformed)?;
369 Ok(Outbound::Event {
370 sub,
371 seq: f.seq.ok_or(CodecError::Malformed)?,
372 topic: f.topic,
373 ts: stamp_of(f.ts, sub)?,
374 data: payload_of(f.data),
375 })
376 }
377 "snap" => {
378 let sub = f.sub.ok_or(CodecError::Malformed)?;
379 Ok(Outbound::Snapshot {
380 sub,
381 seq: f.seq.ok_or(CodecError::Malformed)?,
382 last: f.last.unwrap_or(false),
383 topic: f.topic.ok_or(CodecError::Malformed)?,
384 ts: stamp_of(f.ts, sub)?,
385 data: payload_of(f.data),
386 })
387 }
388 "subscribed" => Ok(Outbound::Subscribed {
389 sub: f.sub.ok_or(CodecError::Malformed)?,
390 }),
391 "pong" => Ok(Outbound::Pong),
392 _ => Err(CodecError::Malformed),
393 }
394 }
395}
396
397#[cfg(test)]
398mod tests {
399 use super::*;
400 use alloc::string::ToString;
401 use alloc::vec::Vec;
402
403 fn payload(s: &str) -> Payload {
404 Arc::from(s.as_bytes())
405 }
406
407 fn roundtrip_inbound(msg: Inbound) -> Inbound {
409 let codec = AimxCodec;
410 let mut out = Vec::new();
411 codec.encode_inbound(msg, &mut out).expect("encode_inbound");
412 codec.decode(&out).expect("decode")
413 }
414
415 fn encode_outbound(msg: Outbound<'_>) -> Vec<u8> {
417 let codec = AimxCodec;
418 let mut out = Vec::new();
419 codec.encode(msg, &mut out).expect("encode");
420 out
421 }
422
423 #[test]
424 fn request_roundtrip() {
425 match roundtrip_inbound(Inbound::Request {
426 id: 7,
427 method: "record.get".to_string(),
428 params: payload(r#"{"name":"temp"}"#),
429 }) {
430 Inbound::Request { id, method, params } => {
431 assert_eq!(id, 7);
432 assert_eq!(method, "record.get");
433 assert_eq!(¶ms[..], br#"{"name":"temp"}"#);
434 }
435 _ => panic!("expected Request"),
436 }
437 }
438
439 #[test]
440 fn subscribe_and_unsubscribe_roundtrip() {
441 match roundtrip_inbound(Inbound::Subscribe {
442 id: 3,
443 topic: "sensors.#".to_string(),
444 }) {
445 Inbound::Subscribe { id, topic } => {
446 assert_eq!(id, 3);
447 assert_eq!(topic, "sensors.#");
448 }
449 _ => panic!("expected Subscribe"),
450 }
451 match roundtrip_inbound(Inbound::Unsubscribe {
452 sub: "3".to_string(),
453 }) {
454 Inbound::Unsubscribe { sub } => assert_eq!(sub, "3"),
455 _ => panic!("expected Unsubscribe"),
456 }
457 }
458
459 #[test]
460 fn write_roundtrip_splices_payload_verbatim() {
461 match roundtrip_inbound(Inbound::Write {
462 topic: "cfg".to_string(),
463 payload: payload(r#"{"value":{"level":9}}"#),
464 }) {
465 Inbound::Write { topic, payload } => {
466 assert_eq!(topic, "cfg");
467 assert_eq!(&payload[..], br#"{"value":{"level":9}}"#);
468 }
469 _ => panic!("expected Write"),
470 }
471 }
472
473 #[test]
474 fn ping_pong_roundtrip() {
475 assert!(matches!(roundtrip_inbound(Inbound::Ping), Inbound::Ping));
476 let frame = encode_outbound(Outbound::Pong);
477 assert!(matches!(
478 AimxCodec.decode_outbound(&frame).unwrap(),
479 Outbound::Pong
480 ));
481 }
482
483 #[test]
484 fn reply_ok_roundtrip() {
485 let frame = encode_outbound(Outbound::Reply {
486 id: 11,
487 result: Ok(payload(r#"{"status":"success"}"#)),
488 });
489 match AimxCodec.decode_outbound(&frame).unwrap() {
490 Outbound::Reply { id, result } => {
491 assert_eq!(id, 11);
492 assert_eq!(&result.unwrap()[..], br#"{"status":"success"}"#);
493 }
494 _ => panic!("expected Reply"),
495 }
496 }
497
498 #[test]
499 fn reply_err_codes_roundtrip() {
500 for err in [
501 RpcError::NotFound,
502 RpcError::Denied,
503 RpcError::Internal,
504 RpcError::VersionMismatch,
505 ] {
506 let frame = encode_outbound(Outbound::Reply {
507 id: 1,
508 result: Err(err.clone()),
509 });
510 match AimxCodec.decode_outbound(&frame).unwrap() {
511 Outbound::Reply { result, .. } => assert_eq!(result.unwrap_err(), err),
512 _ => panic!("expected Reply"),
513 }
514 }
515 }
516
517 #[test]
518 fn event_roundtrip_without_topic() {
519 let frame = encode_outbound(Outbound::Event {
520 sub: "5",
521 seq: 2,
522 topic: None,
523 ts: Stamp::from_nanos(81_234_567_000),
524 data: payload("42"),
525 });
526 assert!(!frame.windows(7).any(|w| w == b"\"topic\""));
528 match AimxCodec.decode_outbound(&frame).unwrap() {
529 Outbound::Event {
530 sub,
531 seq,
532 topic,
533 ts,
534 data,
535 } => {
536 assert_eq!((sub, seq, topic), ("5", 2, None));
537 assert_eq!(ts, Stamp::from_nanos(81_234_567_000));
538 assert_eq!(&data[..], b"42");
539 }
540 _ => panic!("expected Event"),
541 }
542 }
543
544 #[test]
545 fn event_roundtrip_with_topic() {
546 let frame = encode_outbound(Outbound::Event {
547 sub: "5",
548 seq: 9,
549 topic: Some("temp.vienna"),
550 ts: Stamp::from_nanos(7),
551 data: payload(r#"{"c":21.5}"#),
552 });
553 match AimxCodec.decode_outbound(&frame).unwrap() {
554 Outbound::Event { sub, topic, .. } => {
555 assert_eq!(sub, "5");
556 assert_eq!(topic, Some("temp.vienna"));
557 }
558 _ => panic!("expected Event"),
559 }
560 }
561
562 #[test]
567 fn event_encode_splices_data_byte_for_byte() {
568 let with_topic = encode_outbound(Outbound::Event {
569 sub: "5",
570 seq: 9,
571 topic: Some("temp.vienna"),
572 ts: Stamp::from_nanos(81_234_567_000),
573 data: payload(r#"{"c":21.5,"a":[1,2,3]}"#),
574 });
575 assert_eq!(
576 with_topic,
577 br#"{"t":"event","seq":9,"topic":"temp.vienna","sub":"5","ts":81234567000,"data":{"c":21.5,"a":[1,2,3]}}"#
578 );
579
580 let without_topic = encode_outbound(Outbound::Event {
581 sub: "5",
582 seq: 2,
583 topic: None,
584 ts: Stamp::from_nanos(0),
585 data: payload("42"),
586 });
587 assert_eq!(
588 without_topic,
589 br#"{"t":"event","seq":2,"sub":"5","ts":0,"data":42}"#
590 );
591 }
592
593 #[test]
594 fn snapshot_roundtrip_carries_sub_seq_and_topic() {
595 let frame = encode_outbound(Outbound::Snapshot {
596 sub: "8",
597 seq: 3,
598 last: false,
599 topic: "temp.berlin",
600 ts: Stamp::from_nanos(42),
601 data: payload(r#"{"c":18.0}"#),
602 });
603 assert_eq!(
605 frame,
606 br#"{"t":"snap","seq":3,"topic":"temp.berlin","sub":"8","ts":42,"data":{"c":18.0}}"#
607 );
608 match AimxCodec.decode_outbound(&frame).unwrap() {
609 Outbound::Snapshot {
610 sub,
611 seq,
612 last,
613 topic,
614 ts,
615 data,
616 } => {
617 assert_eq!((sub, seq, last, topic), ("8", 3, false, "temp.berlin"));
618 assert_eq!(ts, Stamp::from_nanos(42));
619 assert_eq!(&data[..], br#"{"c":18.0}"#);
620 }
621 _ => panic!("expected Snapshot"),
622 }
623 }
624
625 #[test]
628 fn last_snapshot_of_a_burst_is_flagged() {
629 let frame = encode_outbound(Outbound::Snapshot {
630 sub: "8",
631 seq: 4,
632 last: true,
633 topic: "temp.berlin",
634 ts: Stamp::from_nanos(1),
635 data: payload("1"),
636 });
637 match AimxCodec.decode_outbound(&frame).unwrap() {
638 Outbound::Snapshot { seq, last, .. } => assert_eq!((seq, last), (4, true)),
639 _ => panic!("expected Snapshot"),
640 }
641 }
642
643 #[test]
644 fn value_reply_splices_value_and_stamp() {
645 let reply = value_reply(br#"{"c":21.5}"#, Stamp::from_nanos(81_234_567_000));
646 assert_eq!(&reply[..], br#"{"value":{"c":21.5},"ts":81234567000}"#);
647 let edge = value_reply(b"null", Stamp::from_nanos(0));
648 assert_eq!(&edge[..], br#"{"value":null,"ts":0}"#);
649 let max = value_reply(b"1", Stamp::from_nanos(u64::MAX));
650 assert_eq!(&max[..], br#"{"value":1,"ts":18446744073709551615}"#);
651 }
652
653 #[test]
657 fn value_frame_without_ts_is_a_missing_stamp() {
658 let event = br#"{"t":"event","seq":2,"sub":"5","data":42}"#;
659 let snap = br#"{"t":"snap","seq":1,"topic":"temp.berlin","sub":"8","data":1}"#;
660 for (frame, sub) in [(&event[..], "5"), (&snap[..], "8")] {
661 assert_eq!(
662 AimxCodec.decode_outbound(frame).err(),
663 Some(CodecError::MissingStamp { sub: sub.into() })
664 );
665 }
666 }
667
668 #[test]
672 fn snapshot_without_seq_is_malformed() {
673 let frame = br#"{"t":"snap","sub":"8","topic":"temp.berlin","ts":1,"data":1}"#;
674 assert!(matches!(
675 AimxCodec.decode_outbound(frame),
676 Err(CodecError::Malformed)
677 ));
678 }
679
680 #[test]
681 fn subscribed_ack_roundtrip() {
682 let frame = encode_outbound(Outbound::Subscribed { sub: "13" });
683 match AimxCodec.decode_outbound(&frame).unwrap() {
684 Outbound::Subscribed { sub } => assert_eq!(sub, "13"),
685 _ => panic!("expected Subscribed"),
686 }
687 }
688
689 #[test]
690 fn malformed_frames_are_rejected() {
691 let codec = AimxCodec;
692 assert!(codec.decode(b"{not json").is_err());
693 assert!(codec.decode(br#"{"t":"nope"}"#).is_err());
694 assert!(codec.decode(br#"{"t":"sub","id":1}"#).is_err());
696 assert!(codec.decode_outbound(br#"{"t":"reply","id":1}"#).is_err());
697 assert!(codec
699 .decode_outbound(br#"{"t":"snap","topic":"x","data":1}"#)
700 .is_err());
701 }
702}