Skip to main content

zenkey_model/
wire.rs

1//! The zk2c envelope (core §7.5, 0.72; #976, epic #975): the bytes that
2//! carry an owner's run and sequence number with a sample, before its
3//! record, and a call's forms of the same shape (core 0.92, #980's C4a).
4//!
5//! ```text
6//! mutation, a put's payload        CH · run · seq · record
7//! delete, a delete's attachment    CH · run · seq
8//! event, a put's payload           CH · t32 · ms16 · record     (core 0.101, #980's C2a)
9//! heartbeat, a put's payload       CH · run · seq · body        (core 0.81, #978's F1)
10//! frame, a put's payload           CH · run · seq · body        (core 0.83, #981's K1)
11//! snapshot, a GET reply's payload  CH · run · asof · body       (core 0.97, #977's E1)
12//! request, a query's payload       CH · record                  (core 0.92, C4a)
13//! value, a reply's payload         CH · run · seq · record      (core 0.92, C4a)
14//! error, a reply error's payload   CH · run · seq · error       (core 0.92, C4a)
15//! CH                               form (bits 7–5) · run width (bit 4) · tag (bits 3–0)
16//! run                              16 or 32 bits unsigned, big-endian, as CH's width bit says
17//! seq                              24 bits unsigned, big-endian
18//! record                           every byte after the seq, read as the resource's type says
19//! ```
20//!
21//! **Adopted by core §4.3** (0.73, #976's flip): an owner writes the
22//! envelope on every put of a `stream`, `state`, `@state` or `events` key
23//! and every delete of a state member, an `@stream` sample's excepted. What
24//! a run names and how a seq counts are §4.3's, and the order of two
25//! in-band stamps [`crate::seed`]'s; this module fixes the bytes, a
26//! descriptor's spelling of a run ([`Run::hex`]), and which samples carry
27//! an envelope.
28//!
29//! **A call's forms** (core 0.92 §7.5, adopted by core 0.94, #985's C4c,
30//! the only wire of a call since core 0.99's C4d): a request ([`Request`],
31//! [`read_query`]), a value ([`Envelope::value`], [`read_reply`],
32//! [`read_value`]) and an error ([`crate::envelope::ErrorForm`],
33//! [`read_reply_err`]). A value's and an error's stamp is the replying
34//! instance's as-of mark (§5.1); a request carries none. Each travels under
35//! `zenoh/bytes` ([`ENCODING`]), and under any other `Encoding` a call's
36//! sample carries no form.
37//!
38//! **Parsing reads no contract,** as parsing a key does (§1.1): it knows
39//! the sample ([`SampleKind`]) and nothing more: a put ([`Envelope::parse`]),
40//! a delete ([`DeleteStamp::parse`]), or a call's query, reply or reply
41//! error. So the tag of every form but a delete is reported, never checked
42//! against a type; `packed` (#979) is the first type kind to define one. A
43//! put carries a mutation, a heartbeat, a frame or a snapshot
44//! ([`Envelope::form`]); a heartbeat's body is read with its covered
45//! revision ([`crate::heartbeat`]), its tag that revision's, and a frame's
46//! with its declaration ([`crate::frame`]), its tag that declaration's. A
47//! snapshot's body (core 0.97, #977's E1) is taken unread, its asof in the
48//! seq's place, and read by [`crate::collection`], its tag its
49//! collection's type's. An event (core 0.101, #980's C2a) carries its
50//! time where the stamp would be, and its stamp is its key's occurrence
51//! chunk ([`crate::chunk::occurrence`]): [`Event`], which [`read_event`]
52//! and [`read_put`] read with the key, `key_stamp` and `time` among their
53//! refusals; read without one ([`Envelope::parse`]) it is `key_stamp`. [`read_put`] refuses a frame on a key whose kind
54//! token is not `stream`, and a snapshot on one that is neither `state`
55//! nor `@state` (`key_kind`), which [`Envelope::parse_on`] reads. Only a
56//! GET's reply carries a snapshot, but the parser cannot tell how a put
57//! came, so it reads one either way. An error's detail is taken unread.
58//! The first refusal that applies is reported, in §7.5's order, with the
59//! token `spec/conformance/envelope/` pins ([`Refusal::token`]). Every
60//! envelope and form accepted writes back to its bytes.
61//!
62//! Not the error envelope of an earlier core's call (§5.2 before 0.99),
63//! which travelled with no form and which nothing here reads.
64//!
65//! **Reading** (observer §7.3, "the envelope first"): a reader tells a
66//! sample that carries an envelope by its key and its Encoding alone
67//! ([`carries`]), reads a put's payload through [`read_put`] and a
68//! delete's attachment through [`read_delete`], and reads every other
69//! sample as one with no envelope: an `@stream` sample, a foreign key's
70//! (§1.7), or one whose owner broke §4.3. The order of two in-band stamps
71//! is [`crate::seed`]'s, by the key's kind ([`enveloped_kind`]), and a
72//! sample with no envelope is ordered by its Zenoh timestamp (core §4.2).
73
74use thiserror::Error;
75
76use crate::envelope::{Cause, Code, ErrorForm, FormRefusal};
77use crate::grammar::{KindToken, ZkKey, parse};
78
79/// A form: CH's three high bits. This version defines all eight: a
80/// mutation, a delete, a value, an error, an event (core 0.101), a frame,
81/// a heartbeat and a snapshot.
82#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
83pub enum Form {
84    /// Code 0: a put's run and seq, then its record.
85    Mutation,
86    /// Code 1: a delete's run and seq, as its attachment, and no record.
87    Delete,
88    /// Code 2: a call's request, as its query's payload, with no stamp;
89    /// and a reply's run and seq, then its record (core 0.92).
90    Value,
91    /// Code 3: a reply error's run and seq, then §5.2's error in bytes
92    /// (core 0.92, [`crate::envelope::ErrorForm`]).
93    Error,
94    /// Code 4: an event's occurrence, a put's payload on an `events` key,
95    /// its time then its record, its stamp its key's (core 0.101, #980's
96    /// C2a, [`Event`]).
97    Event,
98    /// Code 5: a stream's records under one header, a put's payload on a
99    /// plain stream's key (core 0.83 §7.7, [`crate::frame`]).
100    Frame,
101    /// Code 6: an owner's confirmation of the state it holds for one
102    /// interface, a put's payload (core 0.81, [`crate::heartbeat`]).
103    Heartbeat,
104    /// Code 7: a collection's state, a GET reply's payload, in pages
105    /// (core 0.97, [`crate::collection`]).
106    Snapshot,
107}
108
109impl Form {
110    /// Every form, in code order.
111    pub const ALL: [Form; 8] = [
112        Form::Mutation,
113        Form::Delete,
114        Form::Value,
115        Form::Error,
116        Form::Event,
117        Form::Frame,
118        Form::Heartbeat,
119        Form::Snapshot,
120    ];
121
122    /// The form's code, from 0 to 7.
123    #[must_use]
124    pub const fn code(self) -> u8 {
125        match self {
126            Form::Mutation => 0,
127            Form::Delete => 1,
128            Form::Value => 2,
129            Form::Error => 3,
130            Form::Event => 4,
131            Form::Frame => 5,
132            Form::Heartbeat => 6,
133            Form::Snapshot => 7,
134        }
135    }
136
137    /// The form of a code, `None` above 7.
138    #[must_use]
139    pub const fn from_code(code: u8) -> Option<Form> {
140        if code < 8 {
141            Some(Form::ALL[code as usize])
142        } else {
143            None
144        }
145    }
146
147    /// Whether this version defines the form; a reserved one is refused.
148    /// Every form is defined since core 0.101, so none is: the check stays
149    /// for a later version's.
150    #[must_use]
151    pub const fn is_defined(self) -> bool {
152        true
153    }
154
155    /// The form's name, as §7.5's table and the fixtures spell it.
156    #[must_use]
157    pub const fn as_str(self) -> &'static str {
158        match self {
159            Form::Mutation => "mutation",
160            Form::Delete => "delete",
161            Form::Value => "value",
162            Form::Error => "error",
163            Form::Event => "event",
164            Form::Frame => "frame",
165            Form::Heartbeat => "heartbeat",
166            Form::Snapshot => "snapshot",
167        }
168    }
169}
170
171impl std::fmt::Display for Form {
172    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
173        f.write_str(self.as_str())
174    }
175}
176
177/// What carries an envelope or a form, its **sample** (core §7.5): the
178/// parser knows it, and nothing more.
179#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
180pub enum SampleKind {
181    /// A put's payload, or the payload of a GET's reply that represents a
182    /// put (S2) or carries a snapshot: a mutation, a heartbeat, a frame or
183    /// a snapshot.
184    Put,
185    /// A delete's attachment, or a `reply_del`'s (S2): a delete.
186    Delete,
187    /// A call's query, its payload: a value with no stamp, a request.
188    Query,
189    /// A call's reply, its payload: a value. Never a GET's reply that
190    /// represents a put, which is a [`SampleKind::Put`].
191    Reply,
192    /// A call's `reply_err`, its payload: an error.
193    ReplyErr,
194}
195
196impl SampleKind {
197    /// Every sample, in §7.5's order.
198    pub const ALL: [SampleKind; 5] = [
199        SampleKind::Put,
200        SampleKind::Delete,
201        SampleKind::Query,
202        SampleKind::Reply,
203        SampleKind::ReplyErr,
204    ];
205
206    /// `put`, `delete`, `query`, `reply` or `reply_err`, as the fixtures
207    /// spell it.
208    #[must_use]
209    pub const fn as_str(self) -> &'static str {
210        match self {
211            SampleKind::Put => "put",
212            SampleKind::Delete => "delete",
213            SampleKind::Query => "query",
214            SampleKind::Reply => "reply",
215            SampleKind::ReplyErr => "reply_err",
216        }
217    }
218
219    /// Whether the sample carries the form: a put a mutation, an event, a
220    /// heartbeat, a frame or a snapshot, a delete's attachment a delete, a
221    /// query and a reply a value, and a `reply_err` an error. No sample
222    /// carries a reserved one.
223    #[must_use]
224    pub const fn carries(self, form: Form) -> bool {
225        match self {
226            SampleKind::Put => matches!(
227                form,
228                Form::Mutation | Form::Event | Form::Frame | Form::Heartbeat | Form::Snapshot
229            ),
230            SampleKind::Delete => matches!(form, Form::Delete),
231            SampleKind::Query | SampleKind::Reply => matches!(form, Form::Value),
232            SampleKind::ReplyErr => matches!(form, Form::Error),
233        }
234    }
235}
236
237impl std::fmt::Display for SampleKind {
238    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
239        f.write_str(self.as_str())
240    }
241}
242
243/// CH's four low bits: 0 unless the record's type kind defines a tag. A
244/// value from 0 to 15, by construction.
245#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
246pub struct Tag(u8);
247
248impl Tag {
249    /// Tag 0: every record whose type kind defines no tag, and every delete.
250    pub const NONE: Tag = Tag(0);
251
252    /// A tag, `None` above 15.
253    #[must_use]
254    pub const fn new(value: u8) -> Option<Tag> {
255        if value <= 0x0f {
256            Some(Tag(value))
257        } else {
258            None
259        }
260    }
261
262    /// The tag's value, from 0 to 15.
263    #[must_use]
264    pub const fn get(self) -> u8 {
265        self.0
266    }
267}
268
269/// CH, the header byte, read as its three fields. Every byte reads as a
270/// header, a reserved form's included, and writes back to itself.
271#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
272pub struct Header {
273    /// Bits 7–5.
274    pub form: Form,
275    /// Bit 4: a 32-bit run when set, a 16-bit run when clear.
276    pub wide: bool,
277    /// Bits 3–0.
278    pub tag: Tag,
279}
280
281impl Header {
282    /// CH's fields: the form's code × 32, plus the width bit × 16, plus the
283    /// tag. `0x1b` is `000 1 1011`: a mutation, a 32-bit run, tag 11.
284    #[must_use]
285    pub const fn from_byte(ch: u8) -> Header {
286        Header {
287            form: Form::ALL[(ch >> 5) as usize],
288            wide: ch & 0x10 != 0,
289            tag: Tag(ch & 0x0f),
290        }
291    }
292
293    /// The byte.
294    #[must_use]
295    pub const fn byte(self) -> u8 {
296        (self.form.code() << 5) | ((self.wide as u8) << 4) | self.tag.0
297    }
298}
299
300/// A run: 16 or 32 bits unsigned, written big-endian, as CH's width bit
301/// says. An instance's ordering epoch (core §4.3): a 16-bit run is a
302/// counter in the owner's record, a 32-bit run a random draw. Two runs of
303/// different widths are two runs, whatever their values, and nothing
304/// orders two runs.
305#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
306pub enum Run {
307    U16(u16),
308    U32(u32),
309}
310
311impl std::fmt::Display for Run {
312    /// Its descriptor spelling ([`Run::hex`]).
313    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
314        match self {
315            Run::U16(v) => write!(f, "{v:04x}"),
316            Run::U32(v) => write!(f, "{v:08x}"),
317        }
318    }
319}
320
321impl Run {
322    /// Whether CH's width bit is set for this run.
323    #[must_use]
324    pub const fn is_wide(self) -> bool {
325        matches!(self, Run::U32(_))
326    }
327
328    /// The run's value.
329    #[must_use]
330    pub const fn value(self) -> u32 {
331        match self {
332            Run::U16(v) => v as u32,
333            Run::U32(v) => v,
334        }
335    }
336
337    /// Its bytes on the wire: 2 or 4.
338    #[must_use]
339    pub const fn width_bytes(self) -> usize {
340        if self.is_wide() { 4 } else { 2 }
341    }
342
343    /// The run as a descriptor states it (core §3.3): its bytes in
344    /// lowercase hexadecimal, 4 digits for a 16-bit run and 8 for a 32-bit
345    /// one. So `00a1` and `000000a1` are two runs.
346    #[must_use]
347    pub fn hex(self) -> String {
348        self.to_string()
349    }
350
351    /// A descriptor's `run` read back: exactly 4 or 8 lowercase hex
352    /// digits, the width from their count. `None` for any other spelling,
353    /// which a descriptor checker reports as D002.
354    #[must_use]
355    pub fn from_hex(text: &str) -> Option<Run> {
356        let lower_hex = text
357            .bytes()
358            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b));
359        if !lower_hex {
360            return None;
361        }
362        match text.len() {
363            4 => u16::from_str_radix(text, 16).ok().map(Run::U16),
364            8 => u32::from_str_radix(text, 16).ok().map(Run::U32),
365            _ => None,
366        }
367    }
368}
369
370/// A seq: 24 bits unsigned, written big-endian. A value from 0 to
371/// 16,777,215, by construction.
372#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
373pub struct Seq(u32);
374
375impl Seq {
376    /// 16,777,215, the greatest seq.
377    pub const MAX: Seq = Seq(0x00ff_ffff);
378
379    /// A seq, `None` above [`Seq::MAX`].
380    #[must_use]
381    pub const fn new(value: u32) -> Option<Seq> {
382        if value <= Seq::MAX.0 {
383            Some(Seq(value))
384        } else {
385            None
386        }
387    }
388
389    /// The seq's value.
390    #[must_use]
391    pub const fn get(self) -> u32 {
392        self.0
393    }
394}
395
396/// An envelope's stamp, the sample's in-band stamp (core §4.3): its run
397/// and its seq, which order a key's values within one run.
398#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
399pub struct Stamp {
400    pub run: Run,
401    pub seq: Seq,
402}
403
404impl Stamp {
405    /// CH and the stamp: 6 bytes with a 16-bit run, 8 with a 32-bit one.
406    #[must_use]
407    pub const fn envelope_bytes(self) -> usize {
408        1 + self.run.width_bytes() + 3
409    }
410
411    pub(crate) fn write_to(self, out: &mut Vec<u8>) {
412        match self.run {
413            Run::U16(v) => out.extend_from_slice(&v.to_be_bytes()),
414            Run::U32(v) => out.extend_from_slice(&v.to_be_bytes()),
415        }
416        out.extend_from_slice(&self.seq.0.to_be_bytes()[1..]);
417    }
418}
419
420/// Why bytes are not an envelope or a form of their sample. The variants
421/// are in §7.5's order, which is the order they are found in: CH's checks,
422/// the stamp, a delete's end, then an error's byte and what follows it.
423#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
424pub enum Refusal {
425    /// No byte at all, so no CH.
426    #[error("no byte, so no header byte")]
427    Empty,
428    /// A form this version reserves: an event.
429    #[error("the form {0} is reserved")]
430    Reserved(Form),
431    /// A form the sample does not carry ([`SampleKind::carries`]).
432    #[error("the form {form} on a {sample}, which does not carry it")]
433    WrongSample { form: Form, sample: SampleKind },
434    /// A frame on a key whose kind token is not `stream` (core 0.83), or a
435    /// snapshot on one that is neither `state` nor `@state` (core 0.97).
436    #[error("a {form} on a {kind} key, which does not carry it")]
437    KeyKind { form: Form, kind: KindToken },
438    /// A delete whose tag is not 0.
439    #[error("a delete's tag is {}, not 0", .0.get())]
440    DeleteTag(Tag),
441    /// A request whose width bit is 1: a request carries no run (core
442    /// 0.92).
443    #[error("a request's width bit is 1, and a request carries no run")]
444    RequestRun,
445    /// An event whose key's last chunk is not an occurrence chunk of CH's
446    /// width (core 0.101): the other width's, any other chunk, or no key at
447    /// all.
448    #[error("an event's key ends in no occurrence chunk of a {} run", if *.wide { "32-bit" } else { "16-bit" })]
449    KeyStamp { wide: bool },
450    /// Fewer bytes than CH, the run and the seq need, and an error's byte
451    /// after them.
452    #[error("{have} bytes, short of the {need} that the header, the stamp and what follows need")]
453    Short { need: usize, have: usize },
454    /// Bytes after a delete's seq, or after an error that ends with its
455    /// message or its byte, where no detail follows.
456    #[error("{0} bytes after the form's end")]
457    Trailing(usize),
458    /// An error's cause on a code other than `unavailable`, or none on
459    /// `unavailable` (core 0.92).
460    #[error("{}", cause_text(*.code, *.cause))]
461    Cause { code: Code, cause: Option<Cause> },
462    /// An error's detail on a code other than `app`.
463    #[error("a detail on {0}, where only app carries one")]
464    Detail(Code),
465    /// An error's extension bit set, which this version leaves 0.
466    #[error("the error's extension bit is set")]
467    Extension,
468    /// An error's message cut short: no length byte, or fewer bytes than
469    /// it states.
470    #[error("a message of {need} bytes, {have} given")]
471    MessageShort { need: usize, have: usize },
472    /// An error's message that is not UTF-8, as RFC 3629 defines it.
473    #[error("the message is not UTF-8")]
474    Utf8,
475    /// An event's time with an unused code (core 0.101): an ms16 above
476    /// 999, or any but 0 under a t32 of all ones.
477    #[error("the event's time is an unused code")]
478    Time,
479}
480
481fn cause_text(code: Code, cause: Option<Cause>) -> String {
482    match cause {
483        None => format!("{code} without a cause"),
484        Some(c) => format!("a cause, {c}, on {code}"),
485    }
486}
487
488impl Refusal {
489    /// The reason token `spec/conformance/envelope/vectors.json`,
490    /// `carries.json` and `spec/conformance/errors/forms.json` pin:
491    /// `short`, `form`, `sample_kind`, `key_kind`, `tag`, `request_run`,
492    /// `key_stamp`, `trailing`, `time`, `cause`, `detail`, `extension` or
493    /// `utf8`.
494    #[must_use]
495    pub const fn token(&self) -> &'static str {
496        match self {
497            Refusal::Empty | Refusal::Short { .. } | Refusal::MessageShort { .. } => "short",
498            Refusal::Reserved(_) => "form",
499            Refusal::WrongSample { .. } => "sample_kind",
500            Refusal::KeyKind { .. } => "key_kind",
501            Refusal::DeleteTag(_) => "tag",
502            Refusal::RequestRun => "request_run",
503            Refusal::KeyStamp { .. } => "key_stamp",
504            Refusal::Time => "time",
505            Refusal::Trailing(_) => "trailing",
506            Refusal::Cause { .. } => "cause",
507            Refusal::Detail(_) => "detail",
508            Refusal::Extension => "extension",
509            Refusal::Utf8 => "utf8",
510        }
511    }
512}
513
514/// §7.5's checks on CH, in its order: CH itself, its form, the sample, a
515/// frame's or a snapshot's key kind (when `kind` is known), a delete's tag
516/// and a request's width bit. Returns CH and every byte after it.
517fn read_header(
518    bytes: &[u8],
519    sample: SampleKind,
520    kind: Option<KindToken>,
521) -> Result<(Header, &[u8]), Refusal> {
522    let (&ch, rest) = bytes.split_first().ok_or(Refusal::Empty)?;
523    let header = Header::from_byte(ch);
524    if !header.form.is_defined() {
525        return Err(Refusal::Reserved(header.form));
526    }
527    if !sample.carries(header.form) {
528        return Err(Refusal::WrongSample {
529            form: header.form,
530            sample,
531        });
532    }
533    if let Some(k) = kind
534        && !key_carries(header.form, k)
535    {
536        return Err(Refusal::KeyKind {
537            form: header.form,
538            kind: k,
539        });
540    }
541    if header.form == Form::Delete && header.tag != Tag::NONE {
542        return Err(Refusal::DeleteTag(header.tag));
543    }
544    if sample == SampleKind::Query && header.wide {
545        return Err(Refusal::RequestRun);
546    }
547    Ok((header, rest))
548}
549
550/// Whether a key of the kind `kind` carries the form, by its kind alone: a
551/// frame only a `stream` key, an event only an `events` key, a snapshot
552/// only a `state` or `@state` key, and every other form any key (core
553/// §7.5's `key_kind`).
554const fn key_carries(form: Form, kind: KindToken) -> bool {
555    match form {
556        Form::Frame => matches!(kind, KindToken::Stream),
557        Form::Event => matches!(kind, KindToken::Events),
558        Form::Snapshot => matches!(kind, KindToken::State | KindToken::ExplicitState),
559        _ => true,
560    }
561}
562
563/// §7.5's parse of a form with a stamp, in its order: CH's checks
564/// ([`read_header`]), then the stamp, and an error's byte after it.
565/// Returns CH, the stamp and every byte after it.
566fn read(
567    bytes: &[u8],
568    sample: SampleKind,
569    kind: Option<KindToken>,
570) -> Result<(Header, Stamp, &[u8]), Refusal> {
571    let (header, rest) = read_header(bytes, sample, kind)?;
572    let run_bytes = if header.wide { 4 } else { 2 };
573    let need = 1 + run_bytes + 3 + usize::from(header.form == Form::Error);
574    if bytes.len() < need {
575        return Err(Refusal::Short {
576            need,
577            have: bytes.len(),
578        });
579    }
580    let (run, rest) = rest.split_at(run_bytes);
581    let run = match *run {
582        [a, b] => Run::U16(u16::from_be_bytes([a, b])),
583        [a, b, c, d] => Run::U32(u32::from_be_bytes([a, b, c, d])),
584        _ => unreachable!("a run is 2 or 4 bytes"),
585    };
586    let (seq, rest) = rest.split_at(3);
587    let seq = Seq(u32::from_be_bytes([0, seq[0], seq[1], seq[2]]));
588    Ok((header, Stamp { run, seq }, rest))
589}
590
591/// A put's payload under the envelope, or a call's reply in its value
592/// form. This version defines four forms for a put: the mutation,
593/// `CH · run · seq · record`, the frame, `CH · run · seq · body` (core
594/// 0.83), the heartbeat, `CH · run · seq · body` (core 0.81), and the
595/// snapshot, `CH · run · asof · body` (core 0.97), a GET reply's. A reply's
596/// value has a mutation's shape, `CH · run · seq · record` (core 0.92).
597#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
598pub struct Envelope<'a> {
599    /// [`Form::Mutation`], [`Form::Frame`], [`Form::Heartbeat`] or
600    /// [`Form::Snapshot`] on a put, [`Form::Value`] on a reply.
601    pub form: Form,
602    /// A mutation's: 0 unless the record's type kind defines a tag. A
603    /// frame's: its declaration's ([`crate::frame::Layout::tag`]). A
604    /// heartbeat's: its covered revision's. A snapshot's: its collection's
605    /// type's. A value's: its operation's `response` type's, or its
606    /// `summary` type's on a summary reply.
607    pub tag: Tag,
608    /// A value's is the replying instance's as-of mark (core §5.1). A
609    /// snapshot's is the owner's run and its asof, in the seq's place.
610    pub stamp: Stamp,
611    /// Every byte after the seq, possibly none: a mutation's or a value's
612    /// record, read as the resource's type says (§7.1), or a frame's, a
613    /// heartbeat's or a snapshot's body, a snapshot's unread
614    /// ([`crate::collection::Page::read`] reads it).
615    pub record: &'a [u8],
616}
617
618impl<'a> Envelope<'a> {
619    /// A mutation: a put's record under its stamp.
620    #[must_use]
621    pub const fn mutation(tag: Tag, stamp: Stamp, record: &'a [u8]) -> Envelope<'a> {
622        Envelope {
623            form: Form::Mutation,
624            tag,
625            stamp,
626            record,
627        }
628    }
629
630    /// A value: a call's reply, its record under the replying instance's
631    /// as-of mark (core 0.92 §5.1, §7.5).
632    #[must_use]
633    pub const fn value(tag: Tag, stamp: Stamp, record: &'a [u8]) -> Envelope<'a> {
634        Envelope {
635            form: Form::Value,
636            tag,
637            stamp,
638            record,
639        }
640    }
641
642    /// A frame: a body under the stamp of its record 0 (core §7.7).
643    #[must_use]
644    pub const fn frame(tag: Tag, stamp: Stamp, body: &'a [u8]) -> Envelope<'a> {
645        Envelope {
646            form: Form::Frame,
647            tag,
648            stamp,
649            record: body,
650        }
651    }
652
653    /// A snapshot's page: its body under the owner's run and its asof, in
654    /// the seq's place (core 0.97 §7.5, [`crate::collection`]).
655    #[must_use]
656    pub const fn snapshot(tag: Tag, run: Run, asof: Seq, body: &'a [u8]) -> Envelope<'a> {
657        Envelope {
658            form: Form::Snapshot,
659            tag,
660            stamp: Stamp { run, seq: asof },
661            record: body,
662        }
663    }
664
665    /// Whether it is a frame's: its bytes after the seq are a body, never a
666    /// record.
667    #[must_use]
668    pub const fn is_frame(&self) -> bool {
669        matches!(self.form, Form::Frame)
670    }
671
672    /// Whether it is a heartbeat's: its bytes after the seq are a body,
673    /// never a record.
674    #[must_use]
675    pub const fn is_heartbeat(&self) -> bool {
676        matches!(self.form, Form::Heartbeat)
677    }
678
679    /// Whether it is a snapshot's page: its bytes after the asof are a
680    /// body, never a record.
681    #[must_use]
682    pub const fn is_snapshot(&self) -> bool {
683        matches!(self.form, Form::Snapshot)
684    }
685
686    /// A put's payload read as an envelope, or the first refusal that
687    /// applies. The key is not read, so a frame or a snapshot is accepted
688    /// on any key: [`Envelope::parse_on`] reads its key's kind.
689    ///
690    /// # Errors
691    ///
692    /// [`Refusal::Empty`], [`Refusal::Reserved`], [`Refusal::WrongSample`]
693    /// for a form a put does not carry, or [`Refusal::Short`], in that
694    /// order.
695    pub fn parse(bytes: &'a [u8]) -> Result<Envelope<'a>, Refusal> {
696        Self::read_with(bytes, None)
697    }
698
699    /// [`Envelope::parse`] for a put on a key of the kind `kind`: a frame on
700    /// a key whose kind is not `stream`, or a snapshot on one that is
701    /// neither `state` nor `@state`, is [`Refusal::KeyKind`], after the
702    /// sample's kind and before the stamp (core §7.5).
703    ///
704    /// # Errors
705    ///
706    /// [`Envelope::parse`]'s, and [`Refusal::KeyKind`] after
707    /// [`Refusal::WrongSample`].
708    pub fn parse_on(bytes: &'a [u8], kind: KindToken) -> Result<Envelope<'a>, Refusal> {
709        Self::read_with(bytes, Some(kind))
710    }
711
712    fn read_with(bytes: &'a [u8], kind: Option<KindToken>) -> Result<Envelope<'a>, Refusal> {
713        // An event's stamp is its key's (core 0.101): with none here, the
714        // key gives no occurrence chunk. [`read_event`] reads one.
715        if let Some(&ch) = bytes.first() {
716            let header = Header::from_byte(ch);
717            if header.form == Form::Event {
718                read_header(bytes, SampleKind::Put, kind)?;
719                return Err(Refusal::KeyStamp { wide: header.wide });
720            }
721        }
722        let (header, stamp, record) = read(bytes, SampleKind::Put, kind)?;
723        Ok(Envelope {
724            form: header.form,
725            tag: header.tag,
726            stamp,
727            record,
728        })
729    }
730
731    /// Its CH: its form, the width the run takes, and its tag.
732    #[must_use]
733    pub const fn header(&self) -> Header {
734        Header {
735            form: self.form,
736            wide: self.stamp.run.is_wide(),
737            tag: self.tag,
738        }
739    }
740
741    /// Its bytes: 6 over the record or the body, or 8 with a 32-bit run.
742    /// A value's write as a mutation's do.
743    #[must_use]
744    pub fn write(&self) -> Vec<u8> {
745        let mut out = Vec::with_capacity(self.stamp.envelope_bytes() + self.record.len());
746        out.push(self.header().byte());
747        self.stamp.write_to(&mut out);
748        out.extend_from_slice(self.record);
749        out
750    }
751}
752
753/// A delete's attachment under the envelope: `CH · run · seq`, with tag 0
754/// and no record. It keeps CH, which states the run's width and lets a
755/// reader refuse an attachment that is not an envelope.
756#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
757pub struct DeleteStamp {
758    pub stamp: Stamp,
759}
760
761impl DeleteStamp {
762    /// A delete's attachment read as an envelope, or the first refusal
763    /// that applies.
764    ///
765    /// # Errors
766    ///
767    /// [`Refusal::Empty`], [`Refusal::Reserved`], [`Refusal::WrongSample`]
768    /// for any form but a delete, [`Refusal::DeleteTag`], [`Refusal::Short`]
769    /// or [`Refusal::Trailing`], in that order.
770    pub fn parse(bytes: &[u8]) -> Result<DeleteStamp, Refusal> {
771        let (_, stamp, rest) = read(bytes, SampleKind::Delete, None)?;
772        if !rest.is_empty() {
773            return Err(Refusal::Trailing(rest.len()));
774        }
775        Ok(DeleteStamp { stamp })
776    }
777
778    /// Its CH: a delete, the width the run takes, and tag 0.
779    #[must_use]
780    pub const fn header(&self) -> Header {
781        Header {
782            form: Form::Delete,
783            wide: self.stamp.run.is_wide(),
784            tag: Tag::NONE,
785        }
786    }
787
788    /// Its bytes: 6, or 8 with a 32-bit run.
789    #[must_use]
790    pub fn write(&self) -> Vec<u8> {
791        let mut out = Vec::with_capacity(self.stamp.envelope_bytes());
792        out.push(self.header().byte());
793        self.stamp.write_to(&mut out);
794        out
795    }
796}
797
798/// A call's request, a query's payload: `CH · record` (core 0.92 §7.5).
799/// CH is a value's, form 2, with its width bit 0 and its operation's
800/// `request` type's tag. It carries no run and no seq: its caller need not
801/// be an owner.
802#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
803pub struct Request<'a> {
804    /// Its operation's `request` type's tag: 0 unless that type's kind
805    /// defines one.
806    pub tag: Tag,
807    /// Every byte after CH, possibly none, read as the `request` type says.
808    pub record: &'a [u8],
809}
810
811impl<'a> Request<'a> {
812    /// A request: its record under CH.
813    #[must_use]
814    pub const fn new(tag: Tag, record: &'a [u8]) -> Request<'a> {
815        Request { tag, record }
816    }
817
818    /// Its CH: a value, width bit 0, and its tag.
819    #[must_use]
820    pub const fn header(&self) -> Header {
821        Header {
822            form: Form::Value,
823            wide: false,
824            tag: self.tag,
825        }
826    }
827
828    /// Its bytes: 1 over the record.
829    #[must_use]
830    pub fn write(&self) -> Vec<u8> {
831        let mut out = Vec::with_capacity(1 + self.record.len());
832        out.push(self.header().byte());
833        out.extend_from_slice(self.record);
834        out
835    }
836}
837
838/// A call's query payload read as a request, or the first refusal that
839/// applies (core 0.92 §7.5). The `Encoding` is not read: a form travels
840/// under `zenoh/bytes` ([`ENCODING`]), which the caller tells.
841///
842/// # Errors
843///
844/// [`Refusal::Empty`], [`Refusal::Reserved`], [`Refusal::WrongSample`]
845/// for any form but a value, or [`Refusal::RequestRun`], in that order.
846pub fn read_query(payload: &[u8]) -> Result<Request<'_>, Refusal> {
847    let (header, record) = read_header(payload, SampleKind::Query, None)?;
848    Ok(Request {
849        tag: header.tag,
850        record,
851    })
852}
853
854/// A call's reply payload read as a value, or the first refusal that
855/// applies (core 0.92 §7.5). A GET's reply that represents a put is a put
856/// ([`Envelope::parse`]), never this. The `Encoding` is not read.
857///
858/// # Errors
859///
860/// [`Refusal::Empty`], [`Refusal::Reserved`], [`Refusal::WrongSample`]
861/// for any form but a value, or [`Refusal::Short`], in that order.
862pub fn read_reply(payload: &[u8]) -> Result<Envelope<'_>, Refusal> {
863    let (header, stamp, record) = read(payload, SampleKind::Reply, None)?;
864    Ok(Envelope {
865        form: header.form,
866        tag: header.tag,
867        stamp,
868        record,
869    })
870}
871
872/// A call's `reply_err` payload read as an error, or the first refusal
873/// that applies (core 0.92 §7.5): CH, the stamp, then the error's byte, its
874/// message and its detail, the detail's bytes unread. The `Encoding` is not
875/// read: [`ErrorForm::read`] gates on it.
876///
877/// # Errors
878///
879/// [`Refusal::Empty`], [`Refusal::Reserved`], [`Refusal::WrongSample`]
880/// for any form but an error, [`Refusal::Short`], then on the error's byte
881/// [`Refusal::Cause`], [`Refusal::Detail`], [`Refusal::Extension`],
882/// [`Refusal::MessageShort`], [`Refusal::Utf8`] or [`Refusal::Trailing`],
883/// in that order.
884pub fn read_reply_err(payload: &[u8]) -> Result<ErrorForm<'_>, Refusal> {
885    let (header, stamp, rest) = read(payload, SampleKind::ReplyErr, None)?;
886    ErrorForm::after_stamp(header.tag, stamp, rest)
887}
888
889/// The Encoding a sample that carries an envelope or a call's form has
890/// (§7.5), as zenoh writes it: its default, with no schema. A raw media
891/// type zenoh does not predefine travels as its custom encoding, which
892/// zenoh writes as the media type itself (§7.2), so it is never this.
893pub const ENCODING: &str = "zenoh/bytes";
894
895/// A call's reply payload read by its `Encoding` (observer §7.3, "A call's
896/// forms first"): under `zenoh/bytes` ([`ENCODING`], exactly) as the value
897/// form ([`read_reply`]). A reply refused, by its bytes or by another
898/// `Encoding`, is malformed, undecodable and never read as a record with
899/// no form, and an answer all the same: it came on the call's key (core
900/// §5.1, "Reading a value", "Retries").
901///
902/// # Errors
903///
904/// [`FormRefusal::Encoding`] under any other `Encoding`, a schema suffix
905/// included (core 0.99 removed the bare wire, #985's C4d), else
906/// [`read_reply`]'s refusal.
907pub fn read_value<'a>(encoding: &str, payload: &'a [u8]) -> Result<Envelope<'a>, FormRefusal> {
908    if encoding != ENCODING {
909        return Err(FormRefusal::Encoding(encoding.to_owned()));
910    }
911    read_reply(payload).map_err(FormRefusal::Form)
912}
913
914/// Whether `key` is a zk2 data key whose kind is a stream, state or an
915/// event (§1.1, by the grammar alone, with no contract): the keys whose
916/// samples may carry an envelope ([`enveloped_kind`]). An operation's
917/// (`@op`) and every control key (`@zk`) keep their wire.
918#[must_use]
919pub fn enveloped_key(key: &str) -> bool {
920    enveloped_kind(key).is_some()
921}
922
923/// The kind token of a key whose samples may carry an envelope: a zk2 data
924/// key whose kind is a stream, state or an event, by the grammar alone.
925/// `None` for an operation's key, every control key (`@zk`), a foreign key
926/// and a key the grammar refuses. The kind picks how two seqs of one run
927/// compare ([`crate::seed::Order::of_kind`]).
928///
929/// A session in a namespace hears a key base-relative, and one in none
930/// hears it with the namespace in front (§1.6), which is any chunks: the
931/// key is read from its first `zk2` chunk from which the grammar parses a
932/// zk2 key, so another deployment's key reads as its own.
933#[must_use]
934pub fn enveloped_kind(key: &str) -> Option<KindToken> {
935    let mut rest = Some(key);
936    while let Some(k) = rest {
937        if k.starts_with("zk2/") {
938            match parse(k) {
939                Ok(ZkKey::Data { kind, .. }) => {
940                    return (kind != KindToken::Op).then_some(kind);
941                }
942                Ok(_) => return None,
943                Err(_) => {}
944            }
945        }
946        rest = k.split_once('/').map(|(_, r)| r);
947    }
948    None
949}
950
951/// Whether a sample carries an envelope: its key is a zk2 data key whose
952/// kind is a stream, state or an event ([`enveloped_key`]), and its
953/// Encoding is `zenoh/bytes` ([`ENCODING`]). An owner sends `zenoh/bytes`
954/// on such a key only with an envelope (core §7.2 asks the predefined
955/// Encoding of every other sample, and a raw type keeps its media type), so
956/// the test tells the two wires apart. Every other sample is read as one
957/// with no envelope (observer §7.3, "Every other sample").
958#[must_use]
959pub fn carries(key: &str, encoding: &str) -> bool {
960    encoding == ENCODING && enveloped_key(key)
961}
962
963/// What a put's payload reads as ([`read_put`]).
964#[derive(Debug, Clone, Copy, PartialEq, Eq)]
965pub enum Reading<'a> {
966    /// The sample carries no envelope ([`carries`]): its payload is read as
967    /// it arrived, by observer §7.3's decode order.
968    Plain,
969    /// A mutation's envelope: its stamp orders the sample, and its record is
970    /// the payload every later step reads (decode, a schema check, a
971    /// rendering, a profile's reader).
972    Enveloped(Envelope<'a>),
973    /// A frame (core 0.83 §7.7, form 5) on a plain stream's key: its body
974    /// is read with its frame resource's declaration
975    /// ([`crate::frame::Frame::parse`]), never decoded as a record of the
976    /// key's type. Its stamp is its record 0's.
977    Framed(Envelope<'a>),
978    /// A heartbeat (core 0.81, form 6): its body is read with its covered
979    /// revision ([`crate::heartbeat::Heartbeat::parse`]), never decoded as
980    /// a record of the key's type. Its stamp is its key's.
981    Heartbeat(Envelope<'a>),
982    /// An event (core 0.101, form 4) on an `events` key whose last chunk
983    /// is an occurrence chunk: its time, then its record, which every later
984    /// step reads as a mutation's; its stamp is its key's.
985    Event(Event<'a>),
986    /// A snapshot's page (core 0.97, form 7) on a `state` or `@state`
987    /// key, a GET reply's: its body is read by
988    /// [`crate::collection::Page::read`], never decoded as a record of the
989    /// key's type. Its stamp is the owner's run and the snapshot's asof.
990    Snapshot(Envelope<'a>),
991    /// An envelope refused: the sample is undecodable, with the refusal's
992    /// token as its reason ([`Refusal::reason`]). It is counted and shown
993    /// as such, never decoded or sniffed as a payload with no envelope
994    /// (observer §7.3's MUST NOT), and never ordered.
995    Refused(Refusal),
996}
997
998/// A put's payload read as its key and Encoding say ([`carries`]).
999#[must_use]
1000pub fn read_put<'a>(key: &str, encoding: &str, payload: &'a [u8]) -> Reading<'a> {
1001    if !carries(key, encoding) {
1002        return Reading::Plain;
1003    }
1004    if let Some(event) = read_event(key, payload) {
1005        return match event {
1006            Ok(e) => Reading::Event(e),
1007            Err(r) => Reading::Refused(r),
1008        };
1009    }
1010    let parsed = match enveloped_kind(key) {
1011        Some(kind) => Envelope::parse_on(payload, kind),
1012        None => Envelope::parse(payload),
1013    };
1014    match parsed {
1015        Ok(e) if e.is_frame() => Reading::Framed(e),
1016        Ok(e) if e.is_heartbeat() => Reading::Heartbeat(e),
1017        Ok(e) if e.is_snapshot() => Reading::Snapshot(e),
1018        Ok(e) => Reading::Enveloped(e),
1019        Err(r) => Reading::Refused(r),
1020    }
1021}
1022
1023/// An event, a put's payload on an `events` key (core 0.101 §7.5's form
1024/// 4; #980's C2a): `CH · t32 · ms16 · record`. Its stamp is its key's
1025/// occurrence chunk ([`crate::chunk::occurrence`]), CH's width bit the
1026/// chunk's, and it carries the occurrence's time in the stamp's place.
1027#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1028pub struct Event<'a> {
1029    /// The record's type's: 0 unless its type kind defines a tag.
1030    pub tag: Tag,
1031    /// Its key's occurrence chunk.
1032    pub stamp: Stamp,
1033    /// The occurrence's time, from the deployment epoch (§7.6), or unknown.
1034    pub time: crate::collection::Time,
1035    /// Every byte after the time, possibly none, read as the resource's
1036    /// type says.
1037    pub record: &'a [u8],
1038}
1039
1040impl Event<'_> {
1041    /// Its CH: an event's form, its stamp's width, and its tag.
1042    #[must_use]
1043    pub const fn header(&self) -> Header {
1044        Header {
1045            form: Form::Event,
1046            wide: self.stamp.run.is_wide(),
1047            tag: self.tag,
1048        }
1049    }
1050
1051    /// Its key's last chunk: its stamp's occurrence chunk.
1052    #[must_use]
1053    pub fn chunk(&self) -> String {
1054        crate::chunk::write_occurrence(self.stamp)
1055    }
1056
1057    /// Its bytes: 7 over the record. `None` for a time no reading accepts
1058    /// (an ms above 999, or a t32 of all ones known).
1059    #[must_use]
1060    pub fn write(&self) -> Option<Vec<u8>> {
1061        let (s, ms) = self.time.fields().ok()?;
1062        let mut out = Vec::with_capacity(7 + self.record.len());
1063        out.push(self.header().byte());
1064        out.extend_from_slice(&s.to_be_bytes());
1065        out.extend_from_slice(&ms.to_be_bytes());
1066        out.extend_from_slice(self.record);
1067        Some(out)
1068    }
1069}
1070
1071/// A put's payload on `key` read as an event (core 0.101 §7.5's form 4),
1072/// or the first refusal that applies, in §7.5's order: CH's checks
1073/// (`short`, `sample_kind`, `key_kind` on a key whose kind token is not
1074/// `events`), then `key_stamp` (the key's last chunk is no occurrence
1075/// chunk of CH's width), `short` (fewer than 7 bytes) and `time`. `None`
1076/// for a payload whose CH is not form 4's, or that has no byte, which
1077/// [`Envelope::parse_on`] reads.
1078#[must_use]
1079pub fn read_event<'a>(key: &str, bytes: &'a [u8]) -> Option<Result<Event<'a>, Refusal>> {
1080    let &ch = bytes.first()?;
1081    if Header::from_byte(ch).form != Form::Event {
1082        return None;
1083    }
1084    Some(event(key, bytes))
1085}
1086
1087fn event<'a>(key: &str, bytes: &'a [u8]) -> Result<Event<'a>, Refusal> {
1088    let (header, rest) = read_header(bytes, SampleKind::Put, enveloped_kind(key))?;
1089    let stamp = key
1090        .rsplit('/')
1091        .next()
1092        .and_then(crate::chunk::occurrence)
1093        .filter(|s| s.run.is_wide() == header.wide)
1094        .ok_or(Refusal::KeyStamp { wide: header.wide })?;
1095    if rest.len() < 6 {
1096        return Err(Refusal::Short {
1097            need: 7,
1098            have: bytes.len(),
1099        });
1100    }
1101    let (t, record) = rest.split_at(6);
1102    let time = crate::collection::Time::of_fields(
1103        u32::from_be_bytes([t[0], t[1], t[2], t[3]]),
1104        u16::from_be_bytes([t[4], t[5]]),
1105    )
1106    .map_err(|_| Refusal::Time)?;
1107    Ok(Event {
1108        tag: header.tag,
1109        stamp,
1110        time,
1111        record,
1112    })
1113}
1114
1115/// A delete's in-band stamp: on a key whose samples may carry an envelope
1116/// ([`enveloped_key`]), an attachment that parses as a delete's envelope.
1117/// A delete whose attachment is absent or does not parse is read as one
1118/// with no envelope, by its Zenoh timestamp (core §4.2): an archive's or a
1119/// profile's attachment (`telemetry.v1`'s Epoch) is never refused here.
1120#[must_use]
1121pub fn read_delete(key: &str, attachment: Option<&[u8]>) -> Option<Stamp> {
1122    let a = attachment?;
1123    if !enveloped_key(key) {
1124        return None;
1125    }
1126    DeleteStamp::parse(a).ok().map(|d| d.stamp)
1127}
1128
1129impl Refusal {
1130    /// Why a refused envelope's sample is undecodable, for a person and a
1131    /// script alike: the refusal's token after a fixed prefix,
1132    /// `zk2c envelope refused: short`.
1133    #[must_use]
1134    pub fn reason(&self) -> String {
1135        format!("zk2c envelope refused: {}", self.token())
1136    }
1137}
1138
1139#[cfg(test)]
1140mod tests {
1141    use super::*;
1142
1143    #[test]
1144    fn every_byte_is_a_header_and_writes_back() {
1145        for ch in 0..=u8::MAX {
1146            let h = Header::from_byte(ch);
1147            assert_eq!(h.byte(), ch);
1148            assert_eq!(h.form.code(), ch >> 5);
1149            assert_eq!(Form::from_code(h.form.code()), Some(h.form));
1150        }
1151        assert_eq!(Form::from_code(8), None);
1152    }
1153
1154    #[test]
1155    fn the_worked_bytes() {
1156        let h = Header::from_byte(0x1b);
1157        assert_eq!((h.form, h.wide, h.tag.get()), (Form::Mutation, true, 11));
1158        assert_eq!(Header::from_byte(0x20).form, Form::Delete);
1159        assert!(!Header::from_byte(0x20).wide);
1160    }
1161
1162    #[test]
1163    fn bounds_by_construction() {
1164        assert_eq!(Tag::new(15).map(Tag::get), Some(15));
1165        assert_eq!(Tag::new(16), None);
1166        assert_eq!(Seq::new(0x00ff_ffff), Some(Seq::MAX));
1167        assert_eq!(Seq::new(0x0100_0000), None);
1168    }
1169
1170    #[test]
1171    fn sizes() {
1172        let narrow = Stamp {
1173            run: Run::U16(7),
1174            seq: Seq::MAX,
1175        };
1176        let wide = Stamp {
1177            run: Run::U32(7),
1178            seq: Seq::MAX,
1179        };
1180        let record = [1, 2, 3];
1181        for (stamp, over) in [(narrow, 6), (wide, 8)] {
1182            let e = Envelope {
1183                form: Form::Mutation,
1184                tag: Tag::NONE,
1185                stamp,
1186                record: &record,
1187            };
1188            let bytes = e.write();
1189            assert_eq!(bytes.len(), over + record.len());
1190            assert_eq!(Envelope::parse(&bytes), Ok(e));
1191            let d = DeleteStamp { stamp };
1192            let bytes = d.write();
1193            assert_eq!(bytes.len(), over);
1194            assert_eq!(DeleteStamp::parse(&bytes), Ok(d));
1195        }
1196    }
1197
1198    /// A run as a descriptor states it (core §3.3): 4 lowercase hex digits
1199    /// for a 16-bit run, 8 for a 32-bit one, and nothing else read back.
1200    #[test]
1201    fn a_run_as_a_descriptor_states_it() {
1202        assert_eq!(Run::U16(3).hex(), "0003");
1203        assert_eq!(Run::U16(0xa1).hex(), "00a1");
1204        assert_eq!(Run::U32(0xa1).hex(), "000000a1");
1205        assert_eq!(Run::U32(u32::MAX).hex(), "ffffffff");
1206        for r in [
1207            Run::U16(0),
1208            Run::U16(u16::MAX),
1209            Run::U32(0),
1210            Run::U32(0xdead_beef),
1211        ] {
1212            assert_eq!(Run::from_hex(&r.hex()), Some(r));
1213        }
1214        assert_eq!(Run::from_hex("00a1"), Some(Run::U16(0xa1)));
1215        assert_eq!(Run::from_hex("000000a1"), Some(Run::U32(0xa1)));
1216        for bad in [
1217            "",
1218            "1a2b3",
1219            "ABCD",
1220            "00A1",
1221            "abc",
1222            "+0a1",
1223            "-001",
1224            "000000a1f",
1225            " 0a1",
1226            "g000",
1227        ] {
1228            assert_eq!(Run::from_hex(bad), None, "{bad:?}");
1229        }
1230    }
1231
1232    #[test]
1233    fn each_kind_refuses_the_others_form() {
1234        let d = DeleteStamp {
1235            stamp: Stamp {
1236                run: Run::U16(1),
1237                seq: Seq::default(),
1238            },
1239        }
1240        .write();
1241        assert_eq!(
1242            Envelope::parse(&d),
1243            Err(Refusal::WrongSample {
1244                form: Form::Delete,
1245                sample: SampleKind::Put
1246            })
1247        );
1248        let m = Envelope {
1249            form: Form::Mutation,
1250            tag: Tag::NONE,
1251            stamp: Stamp {
1252                run: Run::U16(1),
1253                seq: Seq::default(),
1254            },
1255            record: &[],
1256        }
1257        .write();
1258        assert_eq!(
1259            DeleteStamp::parse(&m).map_err(|r| r.token()),
1260            Err("sample_kind")
1261        );
1262    }
1263
1264    /// Rule 1 (#976's A2): a stream, state or event key of the grammar,
1265    /// under `zenoh/bytes`, and nothing else.
1266    #[test]
1267    fn a_sample_carries_an_envelope_by_its_key_kind_and_its_encoding() {
1268        for key in [
1269            "zk2/h/s/i.v1/stream/pose",
1270            "zk2/h/s/i.v1/@stream/frames/f1",
1271            "zk2/h/s/i.v1/state/mode",
1272            "zk2/h/s/i.v1/@state/tracks/t1",
1273            "zk2/h/s/i.v1/events/fault/002g0009",
1274            // A session in no namespace hears the namespace in front.
1275            "prod/zk2/h/s/i.v1/state/mode",
1276            "site/a/zk2/h/s/i.v1/stream/pose",
1277            // A namespace whose own chunk is `zk2`: the first suffix the
1278            // grammar parses decides.
1279            "zk2/zk2/h/s/i.v1/state/mode",
1280        ] {
1281            assert!(enveloped_key(key), "{key}");
1282            assert!(enveloped_kind(key).is_some(), "{key}");
1283            assert!(carries(key, ENCODING), "{key}");
1284            for other in [
1285                "application/json",
1286                "application/cbor",
1287                "application/protobuf",
1288                "zenoh/bytes;x",
1289                "image/x-portable-anymap",
1290                "",
1291            ] {
1292                assert!(!carries(key, other), "{key} under {other:?}");
1293            }
1294        }
1295        for key in [
1296            "zk2/h/s/i.v1/@op/reset",
1297            "zk2/h/s/@zk/instance/0a1b2c3d4e5f6071",
1298            "zk2/@zk/contract/i.v1/0000000000000000000000000000000000000000000000000000000000000000",
1299            "demo/tick",
1300            "seedtest/state/health",
1301            "zk2/h/s/i.v1",
1302            "zk2",
1303            "",
1304        ] {
1305            assert!(!enveloped_key(key), "{key}");
1306            assert_eq!(enveloped_kind(key), None, "{key}");
1307            assert!(!carries(key, ENCODING), "{key}");
1308        }
1309        assert_eq!(
1310            enveloped_kind("prod/zk2/h/s/i.v1/@stream/frames/f1"),
1311            Some(KindToken::ExplicitStream)
1312        );
1313        assert_eq!(
1314            enveloped_kind("zk2/h/s/i.v1/events/fault/002g0009"),
1315            Some(KindToken::Events)
1316        );
1317        assert_eq!(
1318            enveloped_kind("zk2/h/s/i.v1/events/fault/01arz3ndektsv4rrffq69g5fav"),
1319            None,
1320            "a ULID's key is no zk2 key (core 0.103 §1.2)"
1321        );
1322    }
1323
1324    #[test]
1325    fn a_put_reads_plain_enveloped_or_refused() {
1326        let key = "zk2/h/s/i.v1/state/mode";
1327        let stamp = Stamp {
1328            run: Run::U16(7),
1329            seq: Seq::new(3).unwrap(),
1330        };
1331        let bytes = Envelope {
1332            form: Form::Mutation,
1333            tag: Tag::NONE,
1334            stamp,
1335            record: br#"{"up":true}"#,
1336        }
1337        .write();
1338        // Today's wire: the predefined Encoding, read as it is.
1339        assert_eq!(read_put(key, "application/json", &bytes), Reading::Plain);
1340        let Reading::Enveloped(e) = read_put(key, ENCODING, &bytes) else {
1341            panic!("an envelope")
1342        };
1343        assert_eq!((e.stamp, e.record), (stamp, &br#"{"up":true}"#[..]));
1344        // A legacy payload under `zenoh/bytes` is refused, never read: `{`
1345        // is form 3, an error, which a put does not carry (core 0.92).
1346        let refused = read_put(key, ENCODING, br#"{"up":true}"#);
1347        assert_eq!(
1348            refused,
1349            Reading::Refused(Refusal::WrongSample {
1350                form: Form::Error,
1351                sample: SampleKind::Put
1352            })
1353        );
1354        let Reading::Refused(r) = refused else {
1355            unreachable!()
1356        };
1357        assert_eq!(r.reason(), "zk2c envelope refused: sample_kind");
1358        assert_eq!(
1359            read_put(key, ENCODING, &[]),
1360            Reading::Refused(Refusal::Empty)
1361        );
1362        // A foreign key under `zenoh/bytes` is its own bytes.
1363        assert_eq!(read_put("demo/tick", ENCODING, &bytes), Reading::Plain);
1364    }
1365
1366    /// Rule 3: a delete's attachment that parses carries its stamp; any
1367    /// other is read as one with no envelope.
1368    #[test]
1369    fn a_delete_carries_its_stamp_in_its_attachment_or_none() {
1370        let key = "zk2/h/s/i.v1/state/mode";
1371        let stamp = Stamp {
1372            run: Run::U32(0xdead_beef),
1373            seq: Seq::new(9).unwrap(),
1374        };
1375        let att = DeleteStamp { stamp }.write();
1376        assert_eq!(read_delete(key, Some(&att)), Some(stamp));
1377        assert_eq!(read_delete(key, None), None);
1378        // An archive's JSON, or a mutation's bytes, is no delete stamp.
1379        assert_eq!(read_delete(key, Some(br#"{"confirmed":true}"#)), None);
1380        assert_eq!(read_delete(key, Some(&[0x00, 0, 7, 0, 0, 9])), None);
1381        assert_eq!(read_delete("demo/tick", Some(&att)), None);
1382        assert_eq!(read_delete("zk2/h/s/i.v1/@op/reset", Some(&att)), None);
1383    }
1384
1385    /// A call's reply by its `Encoding` (observer §7.3, "A call's forms
1386    /// first"; core §5.1, "Reading a value"): under `zenoh/bytes` the
1387    /// value form, refused by its bytes alone, and under any other no
1388    /// form, however its bytes would parse.
1389    #[test]
1390    fn a_reply_is_a_value_form_under_zenoh_bytes_alone() {
1391        let stamp = Stamp {
1392            run: Run::U16(1),
1393            seq: Seq::new(7).unwrap(),
1394        };
1395        let bytes = Envelope::value(Tag::NONE, stamp, br#"{"up":true}"#).write();
1396        let v = read_value(ENCODING, &bytes).expect("a value");
1397        assert_eq!(
1398            (v.form, v.stamp, v.record),
1399            (Form::Value, stamp, &br#"{"up":true}"#[..])
1400        );
1401        // `{` is 0x7b, form 3: an error, which a reply does not carry.
1402        assert_eq!(
1403            read_value(ENCODING, br#"{"up":true}"#),
1404            Err(FormRefusal::Form(Refusal::WrongSample {
1405                form: Form::Error,
1406                sample: SampleKind::Reply
1407            }))
1408        );
1409        // The same bytes on another Encoding, a schema suffix included,
1410        // carry no form.
1411        for other in ["application/json", "zenoh/bytes;x", "zenoh/string"] {
1412            let r = read_value(other, &bytes);
1413            assert_eq!(r, Err(FormRefusal::Encoding(other.to_owned())), "{other}");
1414            assert_eq!(r.unwrap_err().token(), "encoding");
1415        }
1416    }
1417}