Skip to main content

zenkey_model/
collection.rs

1//! A collection's snapshot (core §7.5's form 7, 0.97; #977's E1): one
2//! `state` or `@state` resource's members, their values and tombstones, in
3//! the pages of a GET's reply. An owner answers a state GET with one per
4//! collection (core §4.2, #977's E3), and a reader merges its entries per
5//! key ([`Page::members`]), holds its pages ([`hear`]), and applies the
6//! omission rule over a complete one ([`omit`]), mapping its index with
7//! the revision the owner's descriptor names ([`collection_at`]).
8//!
9//! ```text
10//! page        CH · run · asof · body          a GET reply's payload, CH's tag the collection's type's
11//! body        time · page · coll · live · tombs
12//! time        t32 · ms16: when the owner built the snapshot
13//! page        an integer: the page's index × 2, plus 1 when a later page follows
14//! coll        an integer: the collection's index
15//! live        an integer, their count · that many live entries
16//! tombs       an integer, their count · that many tombstones
17//! live entry  id · flags · [run] · seq · [conf] · length · record
18//! tombstone   id · flags · [run] · seq
19//! id          an integer, its length in bytes · that many bytes
20//! flags       bit 7 own run · bits 6–5 confirmation · bit 4 run width · bits 3–0 zero
21//! ```
22//!
23//! An integer is unsigned LEB128, at most 5 bytes and at most 2^32 − 1, in
24//! its shortest form. The fixed fields are big-endian. An id is empty, or
25//! plain chunks (§1.2) joined by `/`, below the reply's key.
26//!
27//! The envelope is [`crate::wire`]'s: a snapshot is a put's to the parser
28//! ([`crate::wire::SampleKind::Put`]), its asof in the seq's place, its body
29//! unread there. [`Page::parse`] reads a page's bytes, envelope and body,
30//! and [`Page::read`] a body after its envelope; both refuse for the first
31//! [`BodyRefusal`] that applies, reading the fields in order, as
32//! `spec/conformance/snapshot/bodies.json` pins. [`Page::write`] writes
33//! nothing that reading refuses, and every page accepted writes back to its
34//! bytes. [`Snapshot::paginate`] cuts a snapshot into pages under a page
35//! size, and [`Snapshot::complete`] assembles a complete set of pages.
36
37use thiserror::Error;
38
39use crate::chunk::is_plain_chunk;
40use crate::contract::{Contract, Resource};
41use crate::grammar::{KindToken, ZkKey, parse};
42use crate::template::{Segment, Template};
43use crate::wire::{self, Envelope, Form, Header, Run, Seq, Stamp, Tag};
44
45/// The greatest integer the body holds: 2^32 − 1, in at most 5 bytes.
46pub const INTEGER_MAX: u32 = u32::MAX;
47
48/// A time, `t32 · ms16`: seconds and milliseconds since the deployment
49/// epoch E (core §7.6), or unknown.
50#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
51pub enum Time {
52    /// t32 all ones with ms16 0: the owner's clock is unknown.
53    Unknown,
54    /// t32 seconds and ms16 milliseconds since the deployment epoch. A
55    /// writer refuses an ms16 above 999, and a t32 all ones, which reads as
56    /// unknown with ms16 0 and is unused with any other (`time`).
57    Known { s: u32, ms: u16 },
58}
59
60impl Time {
61    /// The time of an instant `t`, in milliseconds since the Unix epoch,
62    /// under the deployment epoch `epoch` in seconds: t32 = ⌊(t − 1000 ×
63    /// E) / 1000⌋ and ms16 = (t − 1000 × E) modulo 1000. `None` before the
64    /// epoch, and from t32 all ones on, which no known time takes.
65    #[must_use]
66    pub fn from_unix_ms(t: i128, epoch: i64) -> Option<Time> {
67        // Unsigned, so `None` before the epoch.
68        let since = u128::try_from(t - i128::from(epoch) * 1000).ok()?;
69        let s = u32::try_from(since / 1000)
70            .ok()
71            .filter(|&s| s != u32::MAX)?;
72        let ms = u16::try_from(since % 1000).ok()?;
73        Some(Time::Known { s, ms })
74    }
75
76    /// The instant, in milliseconds since the Unix epoch, under the
77    /// deployment epoch `epoch` in seconds; `None` when unknown.
78    #[must_use]
79    pub fn unix_ms(self, epoch: i64) -> Option<i128> {
80        match self {
81            Time::Unknown => None,
82            Time::Known { s, ms } => {
83                Some(i128::from(epoch) * 1000 + i128::from(s) * 1000 + i128::from(ms))
84            }
85        }
86    }
87
88    /// Its two fields, as a writer writes them, or `time` for one the
89    /// reading would refuse or read as another.
90    pub(crate) fn fields(self) -> Result<(u32, u16), BodyRefusal> {
91        match self {
92            Time::Unknown => Ok((u32::MAX, 0)),
93            Time::Known { s, ms } if s != u32::MAX && ms <= 999 => Ok((s, ms)),
94            Time::Known { .. } => Err(BodyRefusal::Time),
95        }
96    }
97
98    /// The two fields read: unknown, known, or `time` for an unused ms16
99    /// (above 999, or any but 0 with t32 all ones).
100    pub(crate) fn of_fields(s: u32, ms: u16) -> Result<Time, BodyRefusal> {
101        match (s, ms) {
102            (u32::MAX, 0) => Ok(Time::Unknown),
103            (u32::MAX, _) => Err(BodyRefusal::Time),
104            (_, ms) if ms > 999 => Err(BodyRefusal::Time),
105            (s, ms) => Ok(Time::Known { s, ms }),
106        }
107    }
108}
109
110/// When the owner last vouched for a live entry: the flags' bits 6–5.
111#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
112pub enum Confirmation {
113    /// 0: the collection has no horizon. A tombstone's is always 0.
114    None,
115    /// 1: the owner vouches for the member as it builds the snapshot, at
116    /// the snapshot's time, as a heartbeat sent then would.
117    AtTime,
118    /// 2: the owner does not vouch for it now; `conf` follows, its last
119    /// confirmation, the later of its last mutation and the last heartbeat
120    /// that vouched for it. Unknown when the owner's clock was.
121    At(Time),
122}
123
124impl Confirmation {
125    /// Its code, 0, 1 or 2. 3 is unused.
126    #[must_use]
127    pub const fn code(self) -> u8 {
128        match self {
129            Confirmation::None => 0,
130            Confirmation::AtTime => 1,
131            Confirmation::At(_) => 2,
132        }
133    }
134}
135
136/// A live entry: a member whose last mutation as of asof is a put.
137#[derive(Debug, Clone, PartialEq, Eq, Hash)]
138pub struct Entry {
139    /// Below the reply's key: empty for the key itself, else plain chunks
140    /// joined by `/`.
141    pub id: String,
142    /// Its own run, when its last mutation was under a run other than the
143    /// header's; `None` for the header's.
144    pub run: Option<Run>,
145    /// The put's seq.
146    pub seq: Seq,
147    pub confirmation: Confirmation,
148    /// The put's record, without its envelope; a packed record whole, its
149    /// pad included.
150    pub record: Vec<u8>,
151}
152
153/// A tombstone: a member the owner deleted within the window (S3).
154#[derive(Debug, Clone, PartialEq, Eq, Hash)]
155pub struct Tombstone {
156    /// As an [`Entry`]'s.
157    pub id: String,
158    /// As an [`Entry`]'s.
159    pub run: Option<Run>,
160    /// The delete's seq.
161    pub seq: Seq,
162}
163
164/// One page of a snapshot: a GET reply's payload.
165#[derive(Debug, Clone, PartialEq, Eq, Hash)]
166pub struct Page {
167    /// CH's tag: the collection's type's, as a mutation's is.
168    pub tag: Tag,
169    /// The owner's run when it built the snapshot.
170    pub run: Run,
171    /// A seq of that run, in the seq's place: the snapshot reflects every
172    /// state mutation of its run at or below it.
173    pub asof: Seq,
174    /// When the owner built the snapshot; no confirmation.
175    pub time: Time,
176    /// The page's index, from 0.
177    pub index: u32,
178    /// Whether a later page of the snapshot follows.
179    pub more: bool,
180    /// The collection's index among the interface's resources of the reply
181    /// key's kind token, in the canonical form's order (§9.5).
182    pub coll: u32,
183    /// In the byte order of their ids.
184    pub live: Vec<Entry>,
185    /// In the byte order of their ids, none of them live.
186    pub tombs: Vec<Tombstone>,
187}
188
189/// A snapshot: a page without its index and more bit, every entry of the
190/// collection as of asof.
191#[derive(Debug, Clone, PartialEq, Eq, Hash)]
192pub struct Snapshot {
193    pub tag: Tag,
194    pub run: Run,
195    pub asof: Seq,
196    pub time: Time,
197    pub coll: u32,
198    pub live: Vec<Entry>,
199    pub tombs: Vec<Tombstone>,
200}
201
202/// Why a page's body is refused, by its reading or by a writer, which
203/// writes nothing the reading refuses (core §7.5, "Reading a snapshot's
204/// body"). The variants are in §7.5's order, the first that applies
205/// reading the fields in order, and for one field the first in this
206/// order.
207#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Error)]
208pub enum BodyRefusal {
209    /// The body ends before a byte a field needs, an integer's last byte
210    /// included.
211    #[error("the body ends before a byte a field needs")]
212    Short,
213    /// An integer whose fifth byte has its high bit set, one above 2^32 −
214    /// 1, or one not in its shortest form.
215    #[error("an integer that is not LEB128 in its shortest form, at most 2^32 − 1")]
216    Leb128,
217    /// A time or a conf whose ms16 is unused: above 999, or any but 0 with
218    /// t32 all ones.
219    #[error("a time whose ms16 is unused")]
220    Time,
221    /// An id that is neither empty nor plain chunks joined by `/`.
222    #[error("an id that is neither empty nor plain chunks joined by /")]
223    Id,
224    /// An id not above the one before it in its list, or a tombstone's id
225    /// that a live entry of the body has.
226    #[error("an id out of order, or both live and a tombstone")]
227    Order,
228    /// A flags byte with a bit from 3 to 0 set, bit 4 without bit 7,
229    /// confirmation 3, or a tombstone's confirmation other than 0.
230    #[error("a flags byte this version leaves unused")]
231    Flags,
232    /// An entry's own run that is the header's, in width and value.
233    #[error("an entry's own run is the header's")]
234    Run,
235    /// A byte after the last tombstone.
236    #[error("bytes after the last tombstone")]
237    Trailing,
238}
239
240impl BodyRefusal {
241    /// The token `spec/conformance/snapshot/bodies.json` pins: `short`,
242    /// `leb128`, `time`, `id`, `order`, `flags`, `run` or `trailing`.
243    #[must_use]
244    pub const fn token(self) -> &'static str {
245        match self {
246            BodyRefusal::Short => "short",
247            BodyRefusal::Leb128 => "leb128",
248            BodyRefusal::Time => "time",
249            BodyRefusal::Id => "id",
250            BodyRefusal::Order => "order",
251            BodyRefusal::Flags => "flags",
252            BodyRefusal::Run => "run",
253            BodyRefusal::Trailing => "trailing",
254        }
255    }
256}
257
258/// Why a page's bytes are not read: its envelope refused by §7.5's parse
259/// on a put, an envelope of another form, or its body refused.
260#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
261pub enum PageRefusal {
262    #[error("its envelope is refused: {0}")]
263    Envelope(wire::Refusal),
264    #[error("its envelope is a {0}, not a snapshot")]
265    NotSnapshot(Form),
266    #[error("its body is refused: {0}")]
267    Body(BodyRefusal),
268}
269
270const RUN_FOLLOWS: u8 = 0x80;
271const CONFIRMATION_SHIFT: u8 = 5;
272const WIDE_RUN: u8 = 0x10;
273const UNUSED_FLAGS: u8 = 0x0f;
274
275/// The bytes an integer takes in LEB128's shortest form: 1 to 5.
276#[must_use]
277pub const fn integer_bytes(v: u32) -> usize {
278    match v {
279        0..=0x7f => 1,
280        0x80..=0x3fff => 2,
281        0x4000..=0x1f_ffff => 3,
282        0x20_0000..=0x0fff_ffff => 4,
283        _ => 5,
284    }
285}
286
287/// An integer's bytes in LEB128's shortest form, appended to `out`: the
288/// one writer of a snapshot's integers and of an owner heartbeat's sizes
289/// ([`crate::heartbeat::OwnerHeartbeat`]).
290pub(crate) fn write_integer(out: &mut Vec<u8>, mut v: u32) {
291    loop {
292        let byte = (v & 0x7f) as u8;
293        v >>= 7;
294        if v == 0 {
295            out.push(byte);
296            return;
297        }
298        out.push(byte | 0x80);
299    }
300}
301
302/// Why an integer does not read ([`read_integer`]).
303#[derive(Debug, Clone, Copy, PartialEq, Eq)]
304pub(crate) enum IntegerRefusal {
305    /// The bytes end before the integer's last byte.
306    Short,
307    /// Its fifth byte has its high bit set, it is above 2^32 − 1, or it is
308    /// not in its shortest form.
309    Leb128,
310}
311
312/// An integer read a byte at a time from `next`, which gives `None` where
313/// the bytes end: unsigned LEB128, stopping at the fifth byte, whose high
314/// bit set is `leb128` whatever follows it. The one reader of a snapshot's
315/// integers and of an owner heartbeat's sizes, whose bytes fall on no byte
316/// boundary ([`crate::heartbeat::OwnerHeartbeat::parse`]).
317pub(crate) fn read_integer(mut next: impl FnMut() -> Option<u8>) -> Result<u32, IntegerRefusal> {
318    let mut v: u64 = 0;
319    for i in 0..5 {
320        let b = next().ok_or(IntegerRefusal::Short)?;
321        v |= u64::from(b & 0x7f) << (7 * i);
322        if b & 0x80 == 0 {
323            if b == 0 && i > 0 {
324                return Err(IntegerRefusal::Leb128);
325            }
326            return u32::try_from(v).map_err(|_| IntegerRefusal::Leb128);
327        }
328    }
329    Err(IntegerRefusal::Leb128)
330}
331
332/// A length as an integer, `leb128` above 2^32 − 1.
333fn length(n: usize) -> Result<u32, BodyRefusal> {
334    u32::try_from(n).map_err(|_| BodyRefusal::Leb128)
335}
336
337/// A length or a count as an integer for its size alone, 2^32 − 1 above
338/// it: LEB128 takes 5 bytes there either way, and a writer refuses such a
339/// length ([`length`]) before any size is relied on.
340fn saturating(n: usize) -> u32 {
341    u32::try_from(n).unwrap_or(u32::MAX)
342}
343
344/// Whether an id is empty, or plain chunks joined by `/`.
345fn id_valid(id: &[u8]) -> bool {
346    id.is_empty() || std::str::from_utf8(id).is_ok_and(|s| s.split('/').all(is_plain_chunk))
347}
348
349/// The flags byte of an entry: its own run, its confirmation's code.
350fn flags(run: Option<Run>, confirmation: u8) -> u8 {
351    let run_bits = match run {
352        None => 0,
353        Some(r) if r.is_wide() => RUN_FOLLOWS | WIDE_RUN,
354        Some(_) => RUN_FOLLOWS,
355    };
356    run_bits | (confirmation << CONFIRMATION_SHIFT)
357}
358
359fn write_run(out: &mut Vec<u8>, run: Run) {
360    match run {
361        Run::U16(v) => out.extend_from_slice(&v.to_be_bytes()),
362        Run::U32(v) => out.extend_from_slice(&v.to_be_bytes()),
363    }
364}
365
366fn write_seq(out: &mut Vec<u8>, seq: Seq) {
367    out.extend_from_slice(&seq.get().to_be_bytes()[1..]);
368}
369
370fn write_time(out: &mut Vec<u8>, (s, ms): (u32, u16)) {
371    out.extend_from_slice(&s.to_be_bytes());
372    out.extend_from_slice(&ms.to_be_bytes());
373}
374
375/// A writer's checks on an entry's id, as the reading makes them: `id`,
376/// then `order` against `before`, the id before it in its list, and for a
377/// tombstone against `live`, the body's live entries in order.
378fn check_id(id: &str, before: Option<&str>, live: Option<&[Entry]>) -> Result<(), BodyRefusal> {
379    if !id_valid(id.as_bytes()) {
380        return Err(BodyRefusal::Id);
381    }
382    if before.is_some_and(|b| id.as_bytes() <= b.as_bytes()) {
383        return Err(BodyRefusal::Order);
384    }
385    if live.is_some_and(|l| {
386        l.binary_search_by(|e| e.id.as_bytes().cmp(id.as_bytes()))
387            .is_ok()
388    }) {
389        return Err(BodyRefusal::Order);
390    }
391    Ok(())
392}
393
394fn check_run(own: Option<Run>, header: Run) -> Result<(), BodyRefusal> {
395    if own == Some(header) {
396        return Err(BodyRefusal::Run);
397    }
398    Ok(())
399}
400
401impl Entry {
402    /// Its bytes in a body: id, flags, its own run, seq, conf, length and
403    /// record.
404    fn write_to(&self, out: &mut Vec<u8>) -> Result<(), BodyRefusal> {
405        write_integer(out, length(self.id.len())?);
406        out.extend_from_slice(self.id.as_bytes());
407        out.push(flags(self.run, self.confirmation.code()));
408        if let Some(r) = self.run {
409            write_run(out, r);
410        }
411        write_seq(out, self.seq);
412        if let Confirmation::At(t) = self.confirmation {
413            write_time(out, t.fields()?);
414        }
415        write_integer(out, length(self.record.len())?);
416        out.extend_from_slice(&self.record);
417        Ok(())
418    }
419
420    /// Its bytes in a body, computed without writing it.
421    fn size(&self) -> usize {
422        integer_bytes(saturating(self.id.len()))
423            + self.id.len()
424            + 1
425            + self.run.map_or(0, Run::width_bytes)
426            + 3
427            + 6 * usize::from(matches!(self.confirmation, Confirmation::At(_)))
428            + integer_bytes(saturating(self.record.len()))
429            + self.record.len()
430    }
431}
432
433impl Tombstone {
434    fn write_to(&self, out: &mut Vec<u8>) -> Result<(), BodyRefusal> {
435        write_integer(out, length(self.id.len())?);
436        out.extend_from_slice(self.id.as_bytes());
437        out.push(flags(self.run, 0));
438        if let Some(r) = self.run {
439            write_run(out, r);
440        }
441        write_seq(out, self.seq);
442        Ok(())
443    }
444
445    fn size(&self) -> usize {
446        integer_bytes(saturating(self.id.len()))
447            + self.id.len()
448            + 1
449            + self.run.map_or(0, Run::width_bytes)
450            + 3
451    }
452}
453
454/// A body's bytes, read a field at a time.
455struct Reader<'a> {
456    bytes: &'a [u8],
457}
458
459impl<'a> Reader<'a> {
460    fn take(&mut self, n: usize) -> Result<&'a [u8], BodyRefusal> {
461        if self.bytes.len() < n {
462            return Err(BodyRefusal::Short);
463        }
464        let (head, rest) = self.bytes.split_at(n);
465        self.bytes = rest;
466        Ok(head)
467    }
468
469    fn byte(&mut self) -> Result<u8, BodyRefusal> {
470        Ok(self.take(1)?[0])
471    }
472
473    /// An integer, by [`read_integer`] over the body's next bytes.
474    fn integer(&mut self) -> Result<u32, BodyRefusal> {
475        read_integer(|| self.byte().ok()).map_err(|e| match e {
476            IntegerRefusal::Short => BodyRefusal::Short,
477            IntegerRefusal::Leb128 => BodyRefusal::Leb128,
478        })
479    }
480
481    fn time(&mut self) -> Result<Time, BodyRefusal> {
482        let t = self.take(6)?;
483        Time::of_fields(
484            u32::from_be_bytes([t[0], t[1], t[2], t[3]]),
485            u16::from_be_bytes([t[4], t[5]]),
486        )
487    }
488
489    fn id(&mut self) -> Result<&'a [u8], BodyRefusal> {
490        let n = self.integer()?;
491        let id = self.take(n as usize)?;
492        if !id_valid(id) {
493            return Err(BodyRefusal::Id);
494        }
495        Ok(id)
496    }
497
498    /// An entry's flags, then its own run: `(run, confirmation)`.
499    fn flags_and_run(
500        &mut self,
501        header: Run,
502        tombstone: bool,
503    ) -> Result<(Option<Run>, u8), BodyRefusal> {
504        let f = self.byte()?;
505        let confirmation = (f >> CONFIRMATION_SHIFT) & 0x03;
506        let follows = f & RUN_FOLLOWS != 0;
507        let wide = f & WIDE_RUN != 0;
508        if f & UNUSED_FLAGS != 0
509            || (wide && !follows)
510            || confirmation == 3
511            || (tombstone && confirmation != 0)
512        {
513            return Err(BodyRefusal::Flags);
514        }
515        let run = if !follows {
516            None
517        } else if wide {
518            let r = self.take(4)?;
519            Some(Run::U32(u32::from_be_bytes([r[0], r[1], r[2], r[3]])))
520        } else {
521            let r = self.take(2)?;
522            Some(Run::U16(u16::from_be_bytes([r[0], r[1]])))
523        };
524        check_run(run, header)?;
525        Ok((run, confirmation))
526    }
527
528    fn seq(&mut self) -> Result<Seq, BodyRefusal> {
529        let s = self.take(3)?;
530        Ok(Seq::new(u32::from_be_bytes([0, s[0], s[1], s[2]])).expect("24 bits"))
531    }
532}
533
534/// An id read as text: [`Reader::id`] has checked it is ASCII.
535fn id_text(id: &[u8]) -> String {
536    std::str::from_utf8(id)
537        .expect("plain chunks are ASCII")
538        .to_owned()
539}
540
541impl Page {
542    /// A page's bytes, CH to its last tombstone: the envelope by §7.5's
543    /// parse on a put, which must be a snapshot's, then its body
544    /// ([`Page::read`]). The key's kind is not read here:
545    /// [`crate::wire::read_put`] refuses a snapshot off a state key.
546    ///
547    /// # Errors
548    ///
549    /// The envelope's refusal, a form other than a snapshot, or the
550    /// body's first refusal.
551    pub fn parse(bytes: &[u8]) -> Result<Page, PageRefusal> {
552        let e = Envelope::parse(bytes).map_err(PageRefusal::Envelope)?;
553        Page::read(&e)
554    }
555
556    /// A snapshot's envelope with its body read: the body's fields in
557    /// order, with the header's run, refused for the first that applies
558    /// (core §7.5, "Reading a snapshot's body").
559    ///
560    /// # Errors
561    ///
562    /// [`PageRefusal::NotSnapshot`] for an envelope of another form, and
563    /// [`PageRefusal::Body`] with the first [`BodyRefusal`] that applies.
564    pub fn read(envelope: &Envelope<'_>) -> Result<Page, PageRefusal> {
565        if envelope.form != Form::Snapshot {
566            return Err(PageRefusal::NotSnapshot(envelope.form));
567        }
568        Page::read_body(envelope.tag, envelope.stamp, envelope.record).map_err(PageRefusal::Body)
569    }
570
571    fn read_body(tag: Tag, stamp: Stamp, body: &[u8]) -> Result<Page, BodyRefusal> {
572        let header = stamp.run;
573        let mut r = Reader { bytes: body };
574        let time = r.time()?;
575        let page = r.integer()?;
576        let coll = r.integer()?;
577        let live_count = r.integer()?;
578        // Never `with_capacity` from a count: it comes from the wire, up to
579        // 2^32 − 1, and only the entries that follow it bound it. The
580        // vectors grow with the entries read, so a short body is refused
581        // before it holds more than its bytes.
582        let mut live: Vec<Entry> = Vec::new();
583        for _ in 0..live_count {
584            let id = r.id()?;
585            if live.last().is_some_and(|b| id <= b.id.as_bytes()) {
586                return Err(BodyRefusal::Order);
587            }
588            let (run, c) = r.flags_and_run(header, false)?;
589            let seq = r.seq()?;
590            let confirmation = match c {
591                0 => Confirmation::None,
592                1 => Confirmation::AtTime,
593                _ => Confirmation::At(r.time()?),
594            };
595            let n = r.integer()?;
596            let record = r.take(n as usize)?.to_vec();
597            live.push(Entry {
598                id: id_text(id),
599                run,
600                seq,
601                confirmation,
602                record,
603            });
604        }
605        let tomb_count = r.integer()?;
606        let mut tombs: Vec<Tombstone> = Vec::new();
607        for _ in 0..tomb_count {
608            let id = r.id()?;
609            if tombs.last().is_some_and(|b| id <= b.id.as_bytes())
610                || live.binary_search_by(|e| e.id.as_bytes().cmp(id)).is_ok()
611            {
612                return Err(BodyRefusal::Order);
613            }
614            let (run, _) = r.flags_and_run(header, true)?;
615            let seq = r.seq()?;
616            tombs.push(Tombstone {
617                id: id_text(id),
618                run,
619                seq,
620            });
621        }
622        if !r.bytes.is_empty() {
623            return Err(BodyRefusal::Trailing);
624        }
625        Ok(Page {
626            tag,
627            run: header,
628            asof: stamp.seq,
629            time,
630            index: page >> 1,
631            more: page & 1 == 1,
632            coll,
633            live,
634            tombs,
635        })
636    }
637
638    /// Its CH: a snapshot, the width the run takes, and its tag.
639    #[must_use]
640    pub const fn header(&self) -> Header {
641        Header {
642            form: Form::Snapshot,
643            wide: self.run.is_wide(),
644            tag: self.tag,
645        }
646    }
647
648    /// The page's bytes, CH to its last tombstone, or the refusal its
649    /// reading would give, the first in reading order: a writer writes no
650    /// page the reading refuses (core §7.5).
651    ///
652    /// # Errors
653    ///
654    /// `time`, `id`, `order` or `run` for a field the reading would
655    /// refuse, and `leb128` for an index, a count or a length above 2^32 −
656    /// 1 as an integer.
657    pub fn write(&self) -> Result<Vec<u8>, BodyRefusal> {
658        let page = self
659            .index
660            .checked_mul(2)
661            .and_then(|p| p.checked_add(u32::from(self.more)))
662            .ok_or(BodyRefusal::Leb128)?;
663        let mut out = Vec::with_capacity(self.size());
664        out.push(self.header().byte());
665        Stamp {
666            run: self.run,
667            seq: self.asof,
668        }
669        .write_to(&mut out);
670        write_time(&mut out, self.time.fields()?);
671        write_integer(&mut out, page);
672        write_integer(&mut out, self.coll);
673        write_integer(&mut out, length(self.live.len())?);
674        let mut before: Option<&str> = None;
675        for e in &self.live {
676            check_id(&e.id, before, None)?;
677            check_run(e.run, self.run)?;
678            e.write_to(&mut out)?;
679            before = Some(&e.id);
680        }
681        write_integer(&mut out, length(self.tombs.len())?);
682        let mut before: Option<&str> = None;
683        for t in &self.tombs {
684            check_id(&t.id, before, Some(&self.live))?;
685            check_run(t.run, self.run)?;
686            t.write_to(&mut out)?;
687            before = Some(&t.id);
688        }
689        Ok(out)
690    }
691
692    /// Its bytes' count, CH to its last tombstone, as [`Page::write`]
693    /// writes them.
694    #[must_use]
695    pub fn size(&self) -> usize {
696        page_size(
697            self.run,
698            self.index,
699            self.coll,
700            self.live.len(),
701            self.live.iter().map(Entry::size).sum(),
702            self.tombs.len(),
703            self.tombs.iter().map(Tombstone::size).sum(),
704        )
705    }
706}
707
708/// A page's bytes: CH, the run, asof, the time, the page integer (whose
709/// more bit never changes its size), coll, the two counts and the entries.
710fn page_size(
711    run: Run,
712    index: u32,
713    coll: u32,
714    live: usize,
715    live_bytes: usize,
716    tombs: usize,
717    tomb_bytes: usize,
718) -> usize {
719    1 + run.width_bytes()
720        + 3
721        + 6
722        + integer_bytes(index.saturating_mul(2))
723        + integer_bytes(coll)
724        + integer_bytes(saturating(live))
725        + live_bytes
726        + integer_bytes(saturating(tombs))
727        + tomb_bytes
728}
729
730/// One of a snapshot's entries, live or a tombstone, as the pages take
731/// them: together, in the byte order of their ids.
732#[derive(Clone, Copy)]
733enum Item<'a> {
734    Live(&'a Entry),
735    Tomb(&'a Tombstone),
736}
737
738impl<'a> Item<'a> {
739    fn id(self) -> &'a str {
740        match self {
741            Item::Live(e) => &e.id,
742            Item::Tomb(t) => &t.id,
743        }
744    }
745}
746
747impl Snapshot {
748    /// The snapshot as one page, index 0 and the last: what its pages
749    /// write, checked whole.
750    fn as_page(&self) -> Page {
751        Page {
752            tag: self.tag,
753            run: self.run,
754            asof: self.asof,
755            time: self.time,
756            index: 0,
757            more: false,
758            coll: self.coll,
759            live: self.live.clone(),
760            tombs: self.tombs.clone(),
761        }
762    }
763
764    /// The snapshot cut into pages under a page size of `page_bytes`
765    /// (core §7.5, "Pages"): its live entries and tombstones together, in
766    /// the byte order of their ids, fill page 0, then page 1. A page takes
767    /// the next entry when it holds none yet, or when its bytes with that
768    /// entry, CH to its last tombstone, are within the page size. The last
769    /// page's more bit is 0, and a snapshot with no entry is one page.
770    ///
771    /// # Errors
772    ///
773    /// The refusal [`Page::write`] gives the snapshot as one page: a
774    /// writer cuts no snapshot it could not write.
775    pub fn paginate(&self, page_bytes: usize) -> Result<Vec<Page>, BodyRefusal> {
776        self.as_page().write()?;
777        let mut items: Vec<Item<'_>> = self
778            .live
779            .iter()
780            .map(Item::Live)
781            .chain(self.tombs.iter().map(Item::Tomb))
782            .collect();
783        items.sort_by_key(|i| i.id().as_bytes());
784        let empty = |index: u32| Page {
785            tag: self.tag,
786            run: self.run,
787            asof: self.asof,
788            time: self.time,
789            index,
790            more: false,
791            coll: self.coll,
792            live: Vec::new(),
793            tombs: Vec::new(),
794        };
795        let mut pages = vec![empty(0)];
796        let (mut live_bytes, mut tomb_bytes) = (0usize, 0usize);
797        for item in items {
798            let (dl, dt, size) = match item {
799                Item::Live(e) => (1, 0, e.size()),
800                Item::Tomb(t) => (0, 1, t.size()),
801            };
802            let page = pages.last().expect("a page");
803            let held = page.live.len() + page.tombs.len();
804            let with = page_size(
805                self.run,
806                page.index,
807                self.coll,
808                page.live.len() + dl,
809                live_bytes + dl * size,
810                page.tombs.len() + dt,
811                tomb_bytes + dt * size,
812            );
813            if held > 0 && with > page_bytes {
814                let index = page.index.checked_add(1).ok_or(BodyRefusal::Leb128)?;
815                pages.last_mut().expect("a page").more = true;
816                pages.push(empty(index));
817                live_bytes = 0;
818                tomb_bytes = 0;
819            }
820            let page = pages.last_mut().expect("a page");
821            match item {
822                Item::Live(e) => {
823                    page.live.push(e.clone());
824                    live_bytes += size;
825                }
826                Item::Tomb(t) => {
827                    page.tombs.push(t.clone());
828                    tomb_bytes += size;
829                }
830            }
831        }
832        Ok(pages)
833    }
834
835    /// The snapshot a complete set of pages holds (core §7.5,
836    /// "Complete"): one page of each index from 0 to a page whose more bit
837    /// is 0, all with one CH, run, asof, time and coll, in any order.
838    /// `None` when they are not complete.
839    #[must_use]
840    pub fn complete(pages: &[Page]) -> Option<Snapshot> {
841        let mut sorted: Vec<&Page> = pages.iter().collect();
842        sorted.sort_by_key(|p| p.index);
843        let first = sorted.first()?;
844        let last = sorted.last()?;
845        let same = |p: &Page| {
846            (p.tag, p.run, p.asof, p.time, p.coll)
847                == (first.tag, first.run, first.asof, first.time, first.coll)
848        };
849        let whole = sorted.iter().enumerate().all(|(i, p)| {
850            u32::try_from(i).is_ok_and(|i| p.index == i)
851                && p.more == (p.index != last.index)
852                && same(p)
853        });
854        if !whole {
855            return None;
856        }
857        Some(Snapshot {
858            tag: first.tag,
859            run: first.run,
860            asof: first.asof,
861            time: first.time,
862            coll: first.coll,
863            live: sorted.iter().flat_map(|p| p.live.iter().cloned()).collect(),
864            tombs: sorted
865                .iter()
866                .flat_map(|p| p.tombs.iter().cloned())
867                .collect(),
868        })
869    }
870}
871
872/// A member's key in a page heard on `key`: `key`, then `/` and the id;
873/// `key` itself for the empty id (core §7.5).
874#[must_use]
875pub fn member_key(key: &str, id: &str) -> String {
876    if id.is_empty() {
877        key.to_owned()
878    } else {
879        format!("{key}/{id}")
880    }
881}
882
883/// One entry of a page as the per-key reply it stands for (core §4.2's
884/// "What a profile reads"): on its member's key,
885/// with its stamp, a live entry the put of its record and a tombstone the
886/// delete. A reader that reads per-key replies reads these the same way:
887/// [`Member::payload`] is the bytes the mutation put, and
888/// [`Member::attachment`] the delete's.
889#[derive(Debug, Clone, PartialEq, Eq, Hash)]
890pub struct Member {
891    /// The page's key, then `/` and the id ([`member_key`]).
892    pub key: String,
893    /// Its own run, else the page's, and its seq.
894    pub stamp: Stamp,
895    /// CH's tag: the page's, the collection's type's, as the mutation's.
896    pub tag: Tag,
897    /// A live entry's confirmation; a tombstone's is
898    /// [`Confirmation::None`].
899    pub confirmation: Confirmation,
900    /// A live entry's record; `None` for a tombstone.
901    pub record: Option<Vec<u8>>,
902}
903
904impl Member {
905    /// Whether it is a tombstone: a delete within the window (S3).
906    #[must_use]
907    pub const fn is_tombstone(&self) -> bool {
908        self.record.is_none()
909    }
910
911    /// A live entry's put, as the owner's per-key reply carries it:
912    /// `CH · run · seq · record`, CH a mutation's with the page's tag and
913    /// the width its run takes. `None` for a tombstone.
914    #[must_use]
915    pub fn payload(&self) -> Option<Vec<u8>> {
916        let record = self.record.as_deref()?;
917        Some(Envelope::mutation(self.tag, self.stamp, record).write())
918    }
919
920    /// A tombstone's delete, as the owner's `reply_del` carries it in its
921    /// attachment: `CH · run · seq`. `None` for a live entry.
922    #[must_use]
923    pub fn attachment(&self) -> Option<Vec<u8>> {
924        self.is_tombstone()
925            .then(|| wire::DeleteStamp { stamp: self.stamp }.write())
926    }
927}
928
929impl Page {
930    /// Its entries as the per-key replies they stand for, live entries and
931    /// tombstones together in the byte order of their ids, each on its
932    /// member's key below `key`, the key the page was heard on.
933    #[must_use]
934    pub fn members(&self, key: &str) -> Vec<Member> {
935        let stamp = |run: Option<Run>, seq| Stamp {
936            run: run.unwrap_or(self.run),
937            seq,
938        };
939        let mut out: Vec<Member> = self
940            .live
941            .iter()
942            .map(|e| Member {
943                key: member_key(key, &e.id),
944                stamp: stamp(e.run, e.seq),
945                tag: self.tag,
946                confirmation: e.confirmation,
947                record: Some(e.record.clone()),
948            })
949            .chain(self.tombs.iter().map(|t| Member {
950                key: member_key(key, &t.id),
951                stamp: stamp(t.run, t.seq),
952                tag: self.tag,
953                confirmation: Confirmation::None,
954                record: None,
955            }))
956            .collect();
957        out.sort_by(|a, b| a.key.as_bytes().cmp(b.key.as_bytes()));
958        out
959    }
960}
961
962/// One snapshot as a reader holds it, from the pages it heard (core §7.5,
963/// "Complete"): the pages of one key, CH's tag, run, asof, time and coll,
964/// and which indices it holds.
965#[derive(Debug, Clone, PartialEq, Eq, Hash)]
966pub struct Heard {
967    /// The key its pages were heard on: the snapshot key of a collection
968    /// read, a member's key of a member read.
969    pub key: String,
970    pub tag: Tag,
971    pub run: Run,
972    pub asof: Seq,
973    pub time: Time,
974    pub coll: u32,
975    /// The indices held, each once however often it was heard.
976    pub pages: std::collections::BTreeSet<u32>,
977    /// The indices held whose more bit is 0.
978    pub last: std::collections::BTreeSet<u32>,
979}
980
981impl Heard {
982    /// The snapshot `page`, heard on `key`, is a page of, holding none of
983    /// its pages yet.
984    #[must_use]
985    pub fn of(key: &str, page: &Page) -> Heard {
986        Heard {
987            key: key.to_owned(),
988            tag: page.tag,
989            run: page.run,
990            asof: page.asof,
991            time: page.time,
992            coll: page.coll,
993            pages: std::collections::BTreeSet::new(),
994            last: std::collections::BTreeSet::new(),
995        }
996    }
997
998    /// Whether `page`, heard on `key`, is one of its pages: one key, CH's
999    /// tag, run (its width included), asof, time and coll.
1000    #[must_use]
1001    pub fn holds(&self, key: &str, page: &Page) -> bool {
1002        self.key == key
1003            && (self.tag, self.run, self.asof, self.time, self.coll)
1004                == (page.tag, page.run, page.asof, page.time, page.coll)
1005    }
1006
1007    /// Holds `page`, one of its pages; whether it held none of its index
1008    /// before.
1009    pub fn add(&mut self, page: &Page) -> bool {
1010        if !page.more {
1011            self.last.insert(page.index);
1012        }
1013        self.pages.insert(page.index)
1014    }
1015
1016    /// Whether it is complete (core §7.5): one page of each index from 0
1017    /// to a page whose more bit is 0, and no other, so that it holds every
1018    /// entry the snapshot has.
1019    #[must_use]
1020    pub fn complete(&self) -> bool {
1021        let Some(&last) = self.last.first() else {
1022            return false;
1023        };
1024        self.last.len() == 1
1025            && self.pages.last() == Some(&last)
1026            && u64::try_from(self.pages.len()).is_ok_and(|n| n == u64::from(last) + 1)
1027    }
1028}
1029
1030/// Adds `page`, heard on `key`, to the snapshot of `heard` it is a page of,
1031/// or to a new one at the end: one GET's snapshots, in the order of their
1032/// first page. Returns that snapshot's place, and whether this page made it
1033/// complete: complete now, and not before.
1034pub fn hear(heard: &mut Vec<Heard>, key: &str, page: &Page) -> (usize, bool) {
1035    let at = match heard.iter().position(|h| h.holds(key, page)) {
1036        Some(at) => at,
1037        None => {
1038            heard.push(Heard::of(key, page));
1039            heard.len() - 1
1040        }
1041    };
1042    let h = &mut heard[at];
1043    let was = h.complete();
1044    h.add(page);
1045    (at, !was && h.complete())
1046}
1047
1048/// The collection's index of `resource`, a `state` or `@state` resource of
1049/// `contract`: its place, from 0, among the contract's resources of its
1050/// kind token, in the canonical form's order (core §7.5, §9.5), the order
1051/// [`Contract::resources`] keeps. `None` for any other kind, and for a
1052/// resource the contract does not hold.
1053#[must_use]
1054pub fn coll_of(contract: &Contract, resource: &Resource) -> Option<u32> {
1055    if !matches!(resource.token, KindToken::State | KindToken::ExplicitState) {
1056        return None;
1057    }
1058    let at = contract
1059        .resources
1060        .iter()
1061        .filter(|r| r.token == resource.token)
1062        .position(|r| r.template == resource.template)?;
1063    u32::try_from(at).ok()
1064}
1065
1066/// The resource a snapshot's coll names, heard on a key whose kind token
1067/// is `kind` (`state` or `@state`): [`coll_of`]'s inverse. `None` when the
1068/// contract has no such collection, which a reader without the contract
1069/// cannot tell either (core §7.5, "Why no contract").
1070#[must_use]
1071pub fn collection_of(contract: &Contract, kind: KindToken, coll: u32) -> Option<&Resource> {
1072    if !matches!(kind, KindToken::State | KindToken::ExplicitState) {
1073        return None;
1074    }
1075    contract
1076        .resources
1077        .iter()
1078        .filter(|r| r.token == kind)
1079        .nth(usize::try_from(coll).ok()?)
1080}
1081
1082/// A collection's snapshot key below its kind token (core §4.2,
1083/// "Answering a state GET"): its template's chunks before its
1084/// first parameter, the whole template when it has none. `None` for a
1085/// template whose first chunk is a parameter, which has no snapshot key.
1086#[must_use]
1087pub fn snapshot_prefix(template: &Template) -> Option<Vec<&str>> {
1088    let prefix: Vec<&str> = template
1089        .segments()
1090        .iter()
1091        .map_while(|s| match s {
1092            Segment::Literal(l) => Some(l.as_str()),
1093            Segment::Param(_) | Segment::Rest(_) => None,
1094        })
1095        .collect();
1096    (!prefix.is_empty()).then_some(prefix)
1097}
1098
1099/// Whether `key` is a member's key of `resource`'s collection: a zk2 data
1100/// key of the resource's kind token whose resource chunks its template
1101/// matches, each parameter one chunk. A key with a namespace in front is
1102/// read from its first `zk2` chunk from which the grammar parses a data
1103/// key, as [`wire::enveloped_kind`] reads one. The address and interface
1104/// are not read: the caller asks of keys at or under one page's key.
1105#[must_use]
1106pub fn is_member(resource: &Resource, key: &str) -> bool {
1107    data_of(key).is_some_and(|(kind, chunks)| {
1108        let refs: Vec<&str> = chunks.iter().map(String::as_str).collect();
1109        kind == resource.token && resource.template.matches(&refs).is_some()
1110    })
1111}
1112
1113/// Whether a resource of `token`, with resolved `annotations`, in a
1114/// revision whose `uses` lists the profiles `uses` says, is a **per-key
1115/// resource** (core §4.2, "A per-key resource"): a state §4.3's table
1116/// lists, read by a profile for the time its replies carry.
1117///
1118/// - a state that declares `freshness.ttl_s` above 0, of a revision that
1119///   does not use `freshness.v2`;
1120/// - a desired resource, its annotations holding `desired.target_param`,
1121///   of a revision that does not use `desired.v2` (core 0.112: a
1122///   `desired.v2` one is answered by snapshot, its version its in-band
1123///   stamp);
1124/// - a metric resource of `telemetry.v1` or `telemetry.v2` (a key of its
1125///   vocabulary), of a revision that uses one;
1126/// - every state of a revision that uses `redundancy.v1`; a state of one
1127///   that uses `redundancy.v2` is a collection like any other
1128///   (`redundancy.v2` §2.6, core 0.119).
1129///
1130/// Its owner answers each member a GET reaches with a reply of its own,
1131/// and one it deleted within the window with a `reply_del` (S2, S3). Every
1132/// other state is a collection its owner answers by snapshot.
1133#[must_use]
1134pub fn per_key_in(
1135    token: KindToken,
1136    annotations: &std::collections::BTreeMap<String, serde_json::Value>,
1137    uses: impl Fn(&str) -> bool,
1138) -> bool {
1139    use crate::authoring::Kind;
1140    if !matches!(token, KindToken::State | KindToken::ExplicitState) {
1141        return false;
1142    }
1143    let horizon = crate::freshness::horizon(Kind::State, annotations)
1144        .ttl()
1145        .is_some()
1146        && !uses(crate::freshness::PROFILE_V2);
1147    let desired = annotations.contains_key(crate::desired::TARGET_PARAM)
1148        && !uses(crate::desired::v2::PROFILE);
1149    let metric = (uses(crate::telemetry::PROFILE) || uses(crate::telemetry::PROFILE_V2))
1150        && crate::telemetry::VOCABULARY
1151            .iter()
1152            .any(|k| annotations.contains_key(&format!("telemetry.{k}")));
1153    let governed = uses(crate::redundancy::PROFILE);
1154    horizon || desired || metric || governed
1155}
1156
1157/// [`per_key_in`] of `resource`, a resource of `contract`.
1158#[must_use]
1159pub fn per_key(contract: &Contract, resource: &Resource) -> bool {
1160    per_key_in(resource.token, &resource.annotations, |p| {
1161        contract.uses.iter().any(|u| u.to_string() == p)
1162    })
1163}
1164
1165/// What a state GET's reader refuses a **stray `reply_del`** as
1166/// ([`stray_reply_del`]; #977's E4): its form, `form`, as a reader of
1167/// mutations refuses a snapshot's page. An owner answers a member of a
1168/// collection by snapshot, one it deleted within the window as a
1169/// tombstone, and sends a `reply_del` only for a per-key resource's member
1170/// (core S2, S3). So a `reply_del` on a collection's member is no owner's
1171/// answer: the reader counts it undecodable, and never merges it as a
1172/// deletion. The text names no reading for one; this is the reference's.
1173pub const STRAY_REPLY_DEL: wire::Refusal = wire::Refusal::Reserved(Form::Delete);
1174
1175/// Whether a `reply_del` heard on `key`, a state GET's reply, is a stray
1176/// one, read with `contract`, the revision of the key's interface the
1177/// reader holds: `key` is a member's key of a state of `contract`, and no
1178/// state of `contract` it is a member of is a per-key resource
1179/// ([`per_key`]). Its reader refuses it as [`STRAY_REPLY_DEL`]. `false`
1180/// for a per-key resource's member, and for a key of another interface or
1181/// of no state of `contract`, which `contract` cannot judge. A key with a
1182/// namespace in front is read as [`is_member`] reads one.
1183#[must_use]
1184pub fn stray_reply_del(contract: &Contract, key: &str) -> bool {
1185    let Some(ZkKey::Data {
1186        iface,
1187        kind,
1188        resource,
1189        ..
1190    }) = data_key_of(key)
1191    else {
1192        return false;
1193    };
1194    if iface != contract.iface {
1195        return false;
1196    }
1197    let refs: Vec<&str> = resource.iter().map(String::as_str).collect();
1198    let mut of = contract
1199        .resources
1200        .iter()
1201        .filter(|r| r.token == kind && r.template.matches(&refs).is_some())
1202        .peekable();
1203    of.peek().is_some() && of.all(|r| !per_key(contract, r))
1204}
1205
1206/// A state GET, as its owner answers it (core §4.2, "Answering a state
1207/// GET"), for the conditional read's rule ([`answers_held`]).
1208#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1209pub enum StateRead {
1210    /// A member read of one concrete key, on a collection the owner
1211    /// answers by snapshot: the one GET that can be a conditional read.
1212    Member,
1213    /// A member read whose selector is not one concrete key: it holds a
1214    /// `*`, a `**` or a `$*` chunk.
1215    Wildcard,
1216    /// A collection read: a selector that includes the snapshot key
1217    /// followed by `/**`.
1218    Collection,
1219    /// A read of a per-key resource ([`per_key`]), answered with a reply
1220    /// per key.
1221    PerKey,
1222}
1223
1224impl StateRead {
1225    /// `member`, `wildcard`, `collection` or `per_key`, as
1226    /// `spec/conformance/envelope/held.json`'s `answers` spell it.
1227    #[must_use]
1228    pub const fn as_str(self) -> &'static str {
1229        match self {
1230            StateRead::Member => "member",
1231            StateRead::Wildcard => "wildcard",
1232            StateRead::Collection => "collection",
1233            StateRead::PerKey => "per_key",
1234        }
1235    }
1236}
1237
1238/// An owner's answer to a conditional read (core 0.110 §4.2, "A
1239/// conditional read"): the held stamp it answers alone, or `None` where it
1240/// answers whole, as it answers a GET with no payload.
1241///
1242/// `Some` exactly when the GET is a member read of one concrete key
1243/// ([`StateRead::Member`]), its payload carries a held stamp that §7.5's
1244/// parse accepts ([`wire::read_get`], `encoding` the payload's), and the
1245/// member's last mutation, `last`, carries exactly that stamp: the same
1246/// run, in width and value, and the same seq. `last` is the stamp a
1247/// snapshot would list for the member: its last put's, or its delete's
1248/// within the window, `None` where the owner holds no member there. The
1249/// reply's payload is then the held stamp the GET carried
1250/// ([`wire::HeldStamp::write`]), on the member's key.
1251///
1252/// An owner MUST NOT answer a held stamp in any other case: another seq,
1253/// another run or the same run's value at the other width, no member held,
1254/// a payload §7.5 refuses (never refused, never left unanswered), and
1255/// every other kind of GET, whose held stamp is ignored. The run the owner
1256/// writes under now is not read.
1257#[must_use]
1258pub fn answers_held(
1259    read: StateRead,
1260    encoding: &str,
1261    payload: Option<&[u8]>,
1262    last: Option<wire::Stamp>,
1263) -> Option<wire::HeldStamp> {
1264    if read != StateRead::Member {
1265        return None;
1266    }
1267    answers_carried(read, wire::read_get(encoding, payload).ok().flatten(), last)
1268}
1269
1270/// [`answers_held`] of a GET whose payload its owner already read
1271/// ([`wire::read_get`]): `carried` is the held stamp it carries, `None`
1272/// for no payload and for one §7.5 refuses. An owner that also keeps what
1273/// each GET carried parses the payload once.
1274#[must_use]
1275pub fn answers_carried(
1276    read: StateRead,
1277    carried: Option<wire::HeldStamp>,
1278    last: Option<wire::Stamp>,
1279) -> Option<wire::HeldStamp> {
1280    carried.filter(|held| read == StateRead::Member && last == Some(held.stamp))
1281}
1282
1283/// The collection read of a GET on `selector`, a key expression over one
1284/// resource's members (core §4.2, "A collection read"): its snapshot key
1285/// followed by `/**`, where every parameter from its template's first on
1286/// is a wildcard, so the GET asks for the collection whole.
1287/// `None` for a selector that binds a parameter, which reads members, and
1288/// for a template whose first chunk is a parameter, which has no snapshot
1289/// key.
1290#[must_use]
1291pub fn collection_read(selector: &str, template: &Template) -> Option<String> {
1292    let prefix = snapshot_prefix(template)?;
1293    let n = template.segments().len();
1294    if n == prefix.len() {
1295        // No parameter: the member's key is the snapshot key, and its
1296        // member read is answered by snapshot already.
1297        return None;
1298    }
1299    let chunks: Vec<&str> = selector.split('/').collect();
1300    let tail = chunks.len().checked_sub(n - prefix.len())?;
1301    let head = tail.checked_sub(prefix.len())?;
1302    // Past the prefix, each parameter a wildcard and each literal itself.
1303    let rest = chunks[tail..]
1304        .iter()
1305        .zip(&template.segments()[prefix.len()..])
1306        .all(|(c, g)| match g {
1307            Segment::Literal(l) => c == l,
1308            Segment::Param(_) => *c == "*",
1309            Segment::Rest(_) => *c == "**",
1310        });
1311    (chunks[head..tail] == prefix[..] && rest).then(|| format!("{}/**", chunks[..tail].join("/")))
1312}
1313
1314/// A zk2 data key's kind token and resource chunks, read from its first
1315/// `zk2` chunk from which the grammar parses a data key, a namespace in
1316/// front skipped (as [`is_member`] reads one).
1317fn data_of(key: &str) -> Option<(KindToken, Vec<String>)> {
1318    match data_key_of(key)? {
1319        ZkKey::Data { kind, resource, .. } => Some((kind, resource)),
1320        _ => None,
1321    }
1322}
1323
1324/// [`data_of`]'s data key whole.
1325fn data_key_of(key: &str) -> Option<ZkKey> {
1326    let mut rest = Some(key);
1327    while let Some(k) = rest {
1328        if k.starts_with("zk2/")
1329            && let Ok(d @ ZkKey::Data { .. }) = parse(k)
1330        {
1331            return Some(d);
1332        }
1333        rest = k.split_once('/').map(|(_, r)| r);
1334    }
1335    None
1336}
1337
1338/// The collection a snapshot heard on `key` with index `coll` is, read
1339/// with `contract`, the revision the owner's descriptor names (core §4.2,
1340/// "The owner's revision maps the index"; #977's E3, F-497): the state
1341/// resource of the reply key's kind token at `coll`, where `key` is its
1342/// snapshot key or one of its members' keys. `None` where the revision has
1343/// no such resource at the index, or has one of which `key` is neither:
1344/// the reader then applies no omission rule over the snapshot, and its
1345/// entries still merge on their keys.
1346#[must_use]
1347pub fn collection_at<'c>(contract: &'c Contract, key: &str, coll: u32) -> Option<&'c Resource> {
1348    let (kind, chunks) = data_of(key)?;
1349    let r = collection_of(contract, kind, coll)?;
1350    let refs: Vec<&str> = chunks.iter().map(String::as_str).collect();
1351    let at_snapshot_key = snapshot_prefix(&r.template).is_some_and(|p| p == refs);
1352    (at_snapshot_key || r.template.matches(&refs).is_some()).then_some(r)
1353}
1354
1355/// The omission rule over a snapshot a reader holds complete in `pages`,
1356/// heard on `key`, read with `contract`, the revision the owner's
1357/// descriptor names (core §4.2; #977's E3): the keys of `held` it drops,
1358/// [`crate::seed::apply_snapshot`] over the collection
1359/// [`collection_at`] names. Nothing where the pages are not one complete
1360/// snapshot, or the index names no collection of `key`.
1361#[must_use]
1362pub fn omit<'a>(
1363    contract: &Contract,
1364    key: &str,
1365    pages: &[Page],
1366    held: impl IntoIterator<Item = crate::seed::HeldMember<'a>>,
1367) -> Vec<&'a str> {
1368    let Some(snapshot) = Snapshot::complete(pages) else {
1369        return Vec::new();
1370    };
1371    let Some(r) = collection_at(contract, key, snapshot.coll) else {
1372        return Vec::new();
1373    };
1374    crate::seed::apply_snapshot(&snapshot, key, |k| is_member(r, k), held)
1375}
1376
1377#[cfg(test)]
1378mod tests {
1379    use super::*;
1380
1381    #[test]
1382    fn integers_round_trip_in_their_shortest_form() {
1383        for v in [
1384            0,
1385            1,
1386            127,
1387            128,
1388            16_383,
1389            16_384,
1390            0x0fff_ffff,
1391            0x1000_0000,
1392            u32::MAX,
1393        ] {
1394            let mut out = Vec::new();
1395            write_integer(&mut out, v);
1396            assert_eq!(out.len(), integer_bytes(v), "{v}");
1397            let mut r = Reader { bytes: &out };
1398            assert_eq!(r.integer(), Ok(v));
1399            assert!(r.bytes.is_empty());
1400        }
1401        let refused = |b: &[u8]| Reader { bytes: b }.integer();
1402        assert_eq!(refused(&[0x80, 0x00][..]), Err(BodyRefusal::Leb128));
1403        assert_eq!(
1404            refused(&[0xff, 0xff, 0xff, 0xff, 0x10][..]),
1405            Err(BodyRefusal::Leb128)
1406        );
1407        assert_eq!(
1408            refused(&[0x80, 0x80, 0x80, 0x80, 0x80][..]),
1409            Err(BodyRefusal::Leb128)
1410        );
1411        assert_eq!(
1412            refused(&[0x80, 0x80, 0x80, 0x80][..]),
1413            Err(BodyRefusal::Short)
1414        );
1415    }
1416
1417    #[test]
1418    fn a_time_from_the_unix_clock() {
1419        let epoch = 1_767_225_600;
1420        let t = i128::from(epoch) * 1000 + 3_600_250;
1421        assert_eq!(
1422            Time::from_unix_ms(t, epoch),
1423            Some(Time::Known { s: 3600, ms: 250 })
1424        );
1425        assert_eq!(Time::Known { s: 3600, ms: 250 }.unix_ms(epoch), Some(t));
1426        assert_eq!(Time::from_unix_ms(t - 3_600_251, epoch), None);
1427        assert_eq!(Time::Unknown.unix_ms(epoch), None);
1428    }
1429
1430    /// A page's entries are the per-key replies they stand for: a live
1431    /// entry the bytes its mutation put, which §7.5's parse reads back to
1432    /// its stamp and record, a tombstone a delete's attachment; an entry's
1433    /// own run beside the header's.
1434    #[test]
1435    fn a_pages_entries_are_their_members_replies() {
1436        let page = Page {
1437            tag: Tag::new(3).unwrap(),
1438            run: Run::U16(5),
1439            asof: Seq::new(9).unwrap(),
1440            time: Time::Unknown,
1441            index: 0,
1442            more: false,
1443            coll: 1,
1444            live: vec![
1445                Entry {
1446                    id: "a".into(),
1447                    run: Some(Run::U32(7)),
1448                    seq: Seq::new(2).unwrap(),
1449                    confirmation: Confirmation::AtTime,
1450                    record: b"r".to_vec(),
1451                },
1452                Entry {
1453                    id: "c".into(),
1454                    run: None,
1455                    seq: Seq::new(4).unwrap(),
1456                    confirmation: Confirmation::None,
1457                    record: Vec::new(),
1458                },
1459            ],
1460            tombs: vec![Tombstone {
1461                id: "b".into(),
1462                run: None,
1463                seq: Seq::new(3).unwrap(),
1464            }],
1465        };
1466        let m = page.members("zk2/h/s/i.v1/state/x");
1467        let keys: Vec<&str> = m.iter().map(|m| m.key.as_str()).collect();
1468        assert_eq!(
1469            keys,
1470            [
1471                "zk2/h/s/i.v1/state/x/a",
1472                "zk2/h/s/i.v1/state/x/b",
1473                "zk2/h/s/i.v1/state/x/c"
1474            ]
1475        );
1476        let bytes = m[0].payload().unwrap();
1477        let put = Envelope::parse(&bytes).unwrap();
1478        assert_eq!(
1479            (put.form, put.tag, put.record),
1480            (Form::Mutation, page.tag, &b"r"[..])
1481        );
1482        assert_eq!(put.stamp.run, Run::U32(7), "its own run");
1483        assert!(m[1].is_tombstone() && m[1].payload().is_none());
1484        let del = wire::DeleteStamp::parse(&m[1].attachment().unwrap()).unwrap();
1485        assert_eq!(
1486            del.stamp,
1487            Stamp {
1488                run: Run::U16(5),
1489                seq: Seq::new(3).unwrap()
1490            }
1491        );
1492        assert_eq!(m[2].attachment(), None);
1493        assert_eq!(member_key("k", ""), "k");
1494    }
1495
1496    /// Pages are held by snapshot, and one is complete at one page of each
1497    /// index to a last, and no other: out of order, twice, a page lost, two
1498    /// last pages, or two times apart.
1499    #[test]
1500    fn a_snapshot_is_complete_at_every_index_to_its_last() {
1501        let page = |index, more| Page {
1502            tag: Tag::NONE,
1503            run: Run::U16(1),
1504            asof: Seq::new(9).unwrap(),
1505            time: Time::Known { s: 1, ms: 2 },
1506            index,
1507            more,
1508            coll: 0,
1509            live: Vec::new(),
1510            tombs: Vec::new(),
1511        };
1512        let mut heard = Vec::new();
1513        assert_eq!(hear(&mut heard, "k", &page(2, false)), (0, false));
1514        assert_eq!(hear(&mut heard, "k", &page(0, true)), (0, false));
1515        assert_eq!(hear(&mut heard, "k", &page(0, true)), (0, false), "twice");
1516        assert_eq!(
1517            hear(&mut heard, "k", &page(1, true)),
1518            (0, true),
1519            "complete now"
1520        );
1521        assert_eq!(
1522            hear(&mut heard, "k", &page(1, true)),
1523            (0, false),
1524            "and not newly"
1525        );
1526        assert!(heard[0].complete());
1527        let mut other = page(0, false);
1528        other.time = Time::Unknown;
1529        assert_eq!(
1530            hear(&mut heard, "k", &other),
1531            (1, true),
1532            "another time, another snapshot"
1533        );
1534        assert_eq!(
1535            hear(&mut heard, "j", &page(0, false)),
1536            (2, true),
1537            "another key"
1538        );
1539        let mut lost = Vec::new();
1540        hear(&mut lost, "k", &page(0, true));
1541        hear(&mut lost, "k", &page(2, false));
1542        assert!(!lost[0].complete(), "page 1 lost");
1543        let mut two = Vec::new();
1544        hear(&mut two, "k", &page(0, false));
1545        hear(&mut two, "k", &page(1, false));
1546        assert!(!two[0].complete(), "two last pages");
1547    }
1548
1549    /// A collection's index is its place among its kind token's resources
1550    /// in canonical order; its snapshot key the template's chunks before its
1551    /// first parameter; and its members the keys its template matches.
1552    #[test]
1553    fn a_collections_index_snapshot_key_and_members() {
1554        let l = crate::contract::load_str(
1555            r#"[interface]
1556name = "c"
1557major = 1
1558minor = 0
1559
1560[resources."b/{x}"]
1561kind = "state"
1562type = { raw = "text/plain" }
1563params = { x = "string" }
1564cardinality = 4
1565
1566[resources.a]
1567kind = "state"
1568type = { raw = "text/plain" }
1569
1570[resources."{y}/z"]
1571kind = "state"
1572explicit = true
1573type = { raw = "text/plain" }
1574params = { y = "string" }
1575cardinality = 4
1576
1577[resources.s]
1578kind = "stream"
1579type = { raw = "text/plain" }
1580"#,
1581            std::path::Path::new("."),
1582            None,
1583        );
1584        let c = l.contract.unwrap_or_else(|| panic!("{}", l.report));
1585        let by = |t: &str| {
1586            c.resources
1587                .iter()
1588                .find(|r| r.template.as_str() == t)
1589                .unwrap()
1590        };
1591        assert_eq!(coll_of(&c, by("a")), Some(0));
1592        assert_eq!(coll_of(&c, by("b/{x}")), Some(1));
1593        assert_eq!(coll_of(&c, by("{y}/z")), Some(0), "@state counts apart");
1594        assert_eq!(coll_of(&c, by("s")), None, "a stream is no collection");
1595        let named = |k, i| collection_of(&c, k, i).map(|r| r.template.as_str());
1596        assert_eq!(named(KindToken::State, 1), Some("b/{x}"));
1597        assert_eq!(named(KindToken::ExplicitState, 0), Some("{y}/z"));
1598        assert_eq!(named(KindToken::State, 2), None);
1599        assert_eq!(named(KindToken::Stream, 0), None);
1600        assert_eq!(snapshot_prefix(&by("b/{x}").template), Some(vec!["b"]));
1601        assert_eq!(snapshot_prefix(&by("a").template), Some(vec!["a"]));
1602        assert_eq!(snapshot_prefix(&by("{y}/z").template), None);
1603        assert!(is_member(by("b/{x}"), "zk2/h/s/c.v1/state/b/one"));
1604        assert!(
1605            is_member(by("b/{x}"), "prod/zk2/h/s/c.v1/state/b/one"),
1606            "namespaced"
1607        );
1608        assert!(
1609            !is_member(by("b/{x}"), "zk2/h/s/c.v1/state/b"),
1610            "the snapshot key"
1611        );
1612        assert!(!is_member(by("b/{x}"), "zk2/h/s/c.v1/state/b/one/two"));
1613        assert!(
1614            !is_member(by("b/{x}"), "zk2/h/s/c.v1/@state/b/one"),
1615            "another kind"
1616        );
1617        assert!(is_member(by("a"), "zk2/h/s/c.v1/state/a"));
1618    }
1619
1620    /// #977's E4: a `reply_del` is an owner's answer only on a per-key
1621    /// resource's member (core S2, S3): here `fresh`, whose horizon is
1622    /// `freshness.v1`'s, a state §4.3's table lists. On a member of a
1623    /// collection answered by snapshot it is stray; on a key the contract
1624    /// holds no state at, or another interface's, the contract cannot
1625    /// judge it.
1626    #[test]
1627    fn a_reply_del_answers_only_a_per_key_resources_member() {
1628        let l = crate::contract::load_str(
1629            r#"[interface]
1630name = "c"
1631major = 1
1632minor = 0
1633uses = ["freshness.v1"]
1634
1635[resources."b/{x}"]
1636kind = "state"
1637type = { raw = "text/plain" }
1638params = { x = "string" }
1639cardinality = 4
1640
1641[resources.fresh]
1642kind = "state"
1643type = { raw = "text/plain" }
1644annotations = { "freshness.ttl_s" = 60 }
1645
1646[resources.s]
1647kind = "stream"
1648type = { raw = "text/plain" }
1649"#,
1650            std::path::Path::new("."),
1651            None,
1652        );
1653        let c = l.contract.unwrap_or_else(|| panic!("{}", l.report));
1654        let by = |t: &str| {
1655            c.resources
1656                .iter()
1657                .find(|r| r.template.as_str() == t)
1658                .unwrap()
1659        };
1660        assert!(per_key(&c, by("fresh")), "a freshness.v1 horizon");
1661        assert!(!per_key(&c, by("b/{x}")), "answered by snapshot");
1662        assert!(!per_key(&c, by("s")), "a stream is no state");
1663        assert!(stray_reply_del(&c, "zk2/h/s/c.v1/state/b/one"));
1664        assert!(
1665            stray_reply_del(&c, "prod/zk2/h/s/c.v1/state/b/one"),
1666            "namespaced"
1667        );
1668        assert!(!stray_reply_del(&c, "zk2/h/s/c.v1/state/fresh"));
1669        assert!(
1670            !stray_reply_del(&c, "zk2/h/s/c.v1/state/b"),
1671            "no member's key"
1672        );
1673        assert!(
1674            !stray_reply_del(&c, "zk2/h/s/d.v1/state/b/one"),
1675            "another interface"
1676        );
1677        assert_eq!(STRAY_REPLY_DEL.token(), "form");
1678    }
1679
1680    #[test]
1681    fn an_empty_snapshot_is_one_sixteen_byte_page() {
1682        let s = Snapshot {
1683            tag: Tag::NONE,
1684            run: Run::U16(1),
1685            asof: Seq::new(9).unwrap(),
1686            time: Time::Known { s: 3600, ms: 250 },
1687            coll: 0,
1688            live: Vec::new(),
1689            tombs: Vec::new(),
1690        };
1691        let pages = s.paginate(1).unwrap();
1692        assert_eq!(pages.len(), 1);
1693        let bytes = pages[0].write().unwrap();
1694        assert_eq!(bytes.len(), 16);
1695        assert_eq!(pages[0].size(), 16);
1696        assert_eq!(Page::parse(&bytes).as_ref(), Ok(&pages[0]));
1697        assert_eq!(Snapshot::complete(&pages), Some(s));
1698    }
1699
1700    #[test]
1701    fn a_selector_over_every_member_reads_the_collection_whole() {
1702        let t = crate::template::Template::parse("sdu/endpoint/{endpoint}").unwrap();
1703        assert_eq!(
1704            super::collection_read("zk2/h/rf0/modem.v3/state/sdu/endpoint/*", &t).as_deref(),
1705            Some("zk2/h/rf0/modem.v3/state/sdu/endpoint/**")
1706        );
1707        assert_eq!(
1708            super::collection_read("zk2/h/rf0/modem.v3/state/sdu/endpoint/a", &t),
1709            None
1710        );
1711        let lead = crate::template::Template::parse("{peer}/route").unwrap();
1712        assert_eq!(
1713            super::collection_read("zk2/h/s/i.v1/state/*/route", &lead),
1714            None
1715        );
1716        let one = crate::template::Template::parse("oper").unwrap();
1717        assert_eq!(
1718            super::collection_read("zk2/h/s/i.v1/state/oper", &one),
1719            None
1720        );
1721        let two = crate::template::Template::parse("a/{x}/b/{y}").unwrap();
1722        assert_eq!(
1723            super::collection_read("zk2/h/s/i.v1/state/a/X/b/*", &two),
1724            None
1725        );
1726        assert_eq!(
1727            super::collection_read("zk2/h/s/i.v1/state/a/*/b/*", &two).as_deref(),
1728            Some("zk2/h/s/i.v1/state/a/**")
1729        );
1730        // Another resource's selector of as many chunks reads nothing whole.
1731        assert_eq!(
1732            super::collection_read("zk2/h/s/i.v1/state/plans/*", &t),
1733            None
1734        );
1735    }
1736}