Skip to main content

aimdb_core/session/aimx/
codec.rs

1//! AimX NDJSON envelope codec (`no_std + alloc`, features `connector-session`
2//! + `remote`).
3//!
4//! One JSON object per line, tagged by a `"t"` field, mapping onto the engine's
5//! role-neutral [`Inbound`]/[`Outbound`] message set. This is **not**
6//! backward-compatible with the legacy AimX wire:
7//!
8//! - `record.subscribe` is an [`Inbound::Subscribe`] keyed by the request `id`;
9//!   events carry the `id` back as [`Outbound::Event::sub`]. An explicit
10//!   `{"t":"subscribed"}` ack exists for servers running
11//!   `acks_subscribe:true` (the WebSocket connector); UDS/serial/TCP leave it
12//!   off and the ack stays implicit.
13//! - events carry `{sub, seq, data}` plus an optional `topic` naming the
14//!   concrete record on wildcard/bus subscriptions (no server-side
15//!   `timestamp`/`dropped`).
16//! - snapshots carry the opening subscription's `sub` so the client demux
17//!   routes them like events.
18//! - the Hello/Welcome handshake is a normal `call("hello", …)`, so
19//!   `authenticate` stays peer-only.
20//!
21//! The record-value `Payload` is spliced into / sliced out of the envelope
22//! verbatim via [`serde_json::value::RawValue`] — no intermediate `Value` tree,
23//! no re-escaping.
24
25use 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/// The zero-sized AimX NDJSON codec.
35#[derive(Clone, Copy, Default)]
36pub struct AimxCodec;
37
38/// One wire frame. A single flat, all-optional struct (rather than an internally
39/// tagged enum, which cannot borrow) so both directions can zero-copy-borrow the
40/// `&str` / [`RawValue`] fields out of the frame slice. Each logical message
41/// fills the subset of fields its `"t"` tag implies; the rest skip-serialize.
42#[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    /// Marks the final `snap` of a late-join burst; absent everywhere else.
50    #[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    /// Write stamp of a value frame (`event`, `snap`), in nanoseconds since
59    /// the instance started. Mandatory on those frames (AimX 4.0); a value
60    /// frame without it is malformed. Ordered before the payload fields.
61    #[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    /// An empty frame with only the tag set; fill the relevant fields after.
77    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
96/// Borrow a [`RawValue`] view over already-serialized payload bytes (validates
97/// the bytes are one JSON value, but does not re-serialize the structure).
98fn as_raw(bytes: &[u8]) -> Result<&RawValue, CodecError> {
99    serde_json::from_slice(bytes).map_err(|_| CodecError::Malformed)
100}
101
102/// Slice a [`RawValue`]'s verbatim JSON bytes back out into an owned [`Payload`];
103/// a missing field decodes as the JSON literal `null`.
104/// The AimX 4.0 reply to `record.get`: `{"value":<value>,"ts":<ns>}`, with
105/// `value` the record's already-encoded JSON, spliced verbatim.
106///
107/// Two allocations: the reply is assembled in an exactly sized buffer, then
108/// moved into the shared [`Payload`]; the stamp is formatted on the stack.
109pub 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
120/// `n` in decimal, written into the end of `buf`.
121fn 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
133/// A value frame's write stamp. Its absence is a protocol error on that
134/// frame's subscription, `sub`.
135fn 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        // Client-side only; a server has no reason to send it.
154        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    // `serde_json::to_writer` is gated behind serde_json's `std` feature (the
169    // workspace builds it on `alloc` only), so serialize via `to_vec` and splice.
170    let bytes = serde_json::to_vec(frame).map_err(|_| CodecError::Malformed)?;
171    out.extend_from_slice(&bytes);
172    Ok(())
173}
174
175/// Encode a frame whose `data` field is already-serialized JSON (a record
176/// serializer's output), splicing `data` verbatim instead of re-validating it
177/// into a [`RawValue`]. Outbound event payloads are trusted-valid, so `as_raw`'s
178/// O(payload) scan is redundant — and on a fan-out subscription it would run
179/// once *per subscriber* over the shared payload (the fan-out encode fast path;
180/// see `docs/design/048-fanout-event-encoding.md`).
181///
182/// `frame` must carry `data = None` so serde emits every other field; the
183/// spliced `data` is then appended as the final member. This is byte-identical
184/// to serializing the same frame with `data = Some(as_raw(payload))` **only
185/// while `data` is the last member serde emits** — i.e. every field declared
186/// after `data` in [`Frame`] (`ok`, `err`) also skip-serializes. That holds for
187/// the frames this path encodes (`Event` never sets `ok`/`err`), and the
188/// `debug_assert` below makes the precondition explicit rather than incidental:
189/// splicing a frame that set `ok`/`err` would emit `…,"ok":X,"data":Y}` with
190/// `data` no longer last, breaking the byte-identical claim.
191///
192/// # Contract (deliberately unchecked)
193///
194/// `data` **must** be exactly one well-formed JSON value. The splice does not
195/// validate it, that is the entire point of Improvement A and re-checking
196/// here (or per-subscriber) is the O(payload) cost this path exists to avoid.
197/// The invariant is upheld upstream, not defended here: `data` is a record
198/// serializer's output and every record reachable over an AimX transport
199/// serializes to JSON (the wire envelope *is* JSON). A caller that feeds
200/// non-JSON bytes — e.g. a non-JSON per-link codec (`linked_*_with`) on a
201/// `ws://` route, which is a JSON-envelope transport — violates the contract
202/// and produces a corrupt frame (empty `data` yields `…,"data":}`); such a
203/// codec/transport pairing is a misconfiguration, not an input to guard against.
204/// The `debug_assert` below is a dev-time tripwire for the `frame.data` half of
205/// the contract; there is intentionally no release-mode check on `data` itself.
206fn 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    // A `Frame` always serializes to a JSON object closed by `}`.
218    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    // --- server direction: read a request, write a reply/event -------------
230    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                // `data` is spliced verbatim (Improvement A) — see
284                // `write_frame_splicing_data`.
285                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                // Only the burst's final frame carries it, so mid-burst frames
300                // stay byte-identical to before.
301                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            // Explicit subscribe ack — only emitted by servers running
309            // `acks_subscribe:true` (the WebSocket connector).
310            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    // --- client direction: write a request, read a reply/event -------------
319    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(&params)?;
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    /// Encode client-direction, decode server-direction (the request path).
408    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    /// Encode server-direction, return the frame bytes (the reply/event path).
416    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!(&params[..], 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        // The optional field skip-serializes — the exact-topic wire is unchanged.
527        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    /// The verbatim-splice event encode (Improvement A) must be byte-identical
563    /// to the previous `data = Some(as_raw(payload))` serde path — the record
564    /// payload is spliced unchanged as the final `data` member, in both the
565    /// with-topic and without-topic layouts.
566    #[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        // A mid-burst snapshot omits `last` entirely.
604        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    /// The burst's final snapshot is flagged, so the client can attach the
626    /// burst's loss total to an update it is guaranteed to deliver.
627    #[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    /// AimX 4.0: `ts` is mandatory on every value frame. A 3.x-shaped `event`
654    /// or `snap` (no `ts`) is a protocol error naming its subscription, rather
655    /// than read with a made-up stamp.
656    #[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    /// A `snap` frame without `seq` is not decodable: snapshots share the
669    /// subscription's sequence space, so an unnumbered one would silently
670    /// defeat the client's gap accounting.
671    #[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        // A `sub` frame missing its topic is malformed.
695        assert!(codec.decode(br#"{"t":"sub","id":1}"#).is_err());
696        assert!(codec.decode_outbound(br#"{"t":"reply","id":1}"#).is_err());
697        // A snap without its routing sub is malformed on the new wire.
698        assert!(codec
699            .decode_outbound(br#"{"t":"snap","topic":"x","data":1}"#)
700            .is_err());
701    }
702}