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