Skip to main content

zenkey_model/
heartbeat.rs

1//! The heartbeat (core §7.5, form 6; #978's F1, epic #975): one put per
2//! interface an owner serves that vouches, by a bit for each member, for
3//! the state it holds, without putting the values again.
4//!
5//! ```text
6//! heartbeat, a put's payload   CH · run · seq · body      CH: form 6 · run width · the revision's tag
7//! body       time · map · a section for each map bit set, in map order · pad
8//! time       42 bits: t32 · ms10 from the deployment epoch; all ones unknown
9//! map        1 bit for each collection of the covered revision, in its order
10//! section    digest32 · members
11//! members    one member: vouched1
12//!            templated:  live (⌈log₂(c + 1)⌉) · sel1 · (bitmap | count · ranks)
13//! ```
14//!
15//! **The collections** ([`Layout::of`]) of a revision are its `state` and
16//! `@state` resources whose resolved `freshness.ttl_s` is above 0, in the
17//! canonical resource order (by kind token, then template). The map's
18//! width and each templated section's widths come from them, so a body is
19//! read with the covered revision ([`Heartbeat::parse`]); CH's tag, the
20//! low 4 bits of the revision's fingerprint ([`Layout::tag`]), is the
21//! check that the reader holds that revision.
22//!
23//! **The digest** ([`Digest`]) of a collection is the XOR over its live
24//! members of the first 4 bytes of the sha256 of the key, a zero byte, the
25//! run's width bit, the run and the seq. It is free of order, so an owner
26//! keeps it at each mutation and a reader computes it over its own view.
27//!
28//! `freshness.v2` (#978's F3, core 0.82) adopts it: an owner of a
29//! contract that uses it sends one heartbeat per interface it serves that
30//! has a collection, on [`key`], at most half the shortest horizon apart
31//! (v2 §2.4), and a reader confirms by it as [`crate::freshness::View`]
32//! reads it (v2 §2.5, `spec/profiles/freshness/conformance/apply.json`).
33//! The refusals' tokens are `spec/conformance/heartbeat/bodies.json`'s.
34
35use std::time::Duration;
36
37use sha2::{Digest as _, Sha256};
38use thiserror::Error;
39
40use crate::canonical::Fingerprint;
41use crate::contract::Contract;
42use crate::freshness::{Horizon, horizon_of};
43use crate::grammar::{IfaceId, KindToken, ZkKey, parse};
44use crate::packed::{BitReader, BitWriter, ReadRefusal};
45use crate::template::Template;
46use crate::wire::{self, Run, Stamp, Tag};
47
48/// The profile that adopts the heartbeat (#978's F3), as its key's
49/// interface chunk spells it.
50pub const PROFILE: &str = "freshness.v2";
51
52/// The resource `freshness.v2`'s standard contract declares, its
53/// parameter the covered interface's id (v2 §3).
54pub const RESOURCE: &str = "heartbeat/{iface}";
55
56/// The width of a heartbeat's time: 32 bits of seconds, then 10 of
57/// milliseconds, as core §7.6's `time` field with `ms`.
58pub const TIME_BITS: u32 = 42;
59
60/// The base-relative key a heartbeat covering `iface` travels on from the
61/// service at `system/service`: `zk2/<system>/<service>/freshness.v2/stream/heartbeat/<iface>`
62/// (`freshness.v2` §3 declares it). An interface id
63/// is a plain chunk, so it needs no slug.
64#[must_use]
65pub fn key(system: &str, service: &str, iface: &IfaceId) -> String {
66    format!("zk2/{system}/{service}/{PROFILE}/stream/heartbeat/{iface}")
67}
68
69/// The covered interface a heartbeat key names, read from a key with a
70/// namespace in front or none: `None` for any other key.
71#[must_use]
72pub fn covered(key: &str) -> Option<(crate::grammar::Addr, IfaceId)> {
73    let mut rest = Some(key);
74    while let Some(k) = rest {
75        if k.starts_with("zk2/")
76            && let Ok(ZkKey::Data {
77                addr,
78                iface,
79                kind: KindToken::Stream,
80                resource,
81            }) = parse(k)
82        {
83            if iface.to_string() != PROFILE {
84                return None;
85            }
86            let [h, covered] = resource.as_slice() else {
87                return None;
88            };
89            if h != "heartbeat" {
90                return None;
91            }
92            let (name, major) = covered.rsplit_once(".v")?;
93            return Some((addr, IfaceId::new(name, major.parse().ok()?).ok()?));
94        }
95        rest = k.split_once('/').map(|(_, r)| r);
96    }
97    None
98}
99
100/// ⌈log₂ n⌉ for n ≥ 1, 0 for n ≤ 1: the fewest bits that hold n codes.
101fn bits_for(n: u128) -> u32 {
102    if n <= 1 {
103        0
104    } else {
105        128 - (n - 1).leading_zeros()
106    }
107}
108
109/// One collection of a revision: a `state` or `@state` resource whose
110/// horizon is above 0.
111#[derive(Debug, Clone, PartialEq, Eq)]
112pub struct Collection {
113    pub token: KindToken,
114    pub template: Template,
115    /// Its cardinality when its template has a parameter; `None` for one
116    /// member.
117    pub cardinality: Option<u64>,
118    /// Its horizon, `freshness.ttl_s`.
119    pub ttl: Duration,
120}
121
122impl Collection {
123    /// `<kind token>/<template>`, as the fixtures name it.
124    #[must_use]
125    pub fn resource(&self) -> String {
126        format!("{}/{}", self.token.as_str(), self.template.as_str())
127    }
128
129    /// Whether its template has a parameter.
130    #[must_use]
131    pub fn is_templated(&self) -> bool {
132        self.cardinality.is_some()
133    }
134
135    /// The width of its live count, ⌈log₂(c + 1)⌉; `None` with one member.
136    #[must_use]
137    pub fn live_bits(&self) -> Option<u32> {
138        self.cardinality.map(|c| bits_for(u128::from(c) + 1))
139    }
140}
141
142/// A revision's collections, its fingerprint and the heartbeat's tag: what
143/// a heartbeat covering it is read and written by.
144#[derive(Debug, Clone, PartialEq, Eq)]
145pub struct Layout {
146    pub iface: IfaceId,
147    pub fingerprint: Fingerprint,
148    /// The low 4 bits of the fingerprint's last byte.
149    pub tag: Tag,
150    /// In map order.
151    pub collections: Vec<Collection>,
152    /// Every `state` and `@state` template of the revision, each with its
153    /// collection's index, so a key resolves among them all (§2.2).
154    states: Vec<(KindToken, Template, Option<usize>)>,
155}
156
157impl Layout {
158    /// The layout of a revision.
159    #[must_use]
160    pub fn of(c: &Contract) -> Layout {
161        let fingerprint = Fingerprint::of(c);
162        let mut collections = Vec::new();
163        let mut states = Vec::new();
164        for r in &c.resources {
165            if !matches!(r.token, KindToken::State | KindToken::ExplicitState) {
166                continue;
167            }
168            let index = match horizon_of(r) {
169                Horizon::Within(ttl) => {
170                    collections.push(Collection {
171                        token: r.token,
172                        template: r.template.clone(),
173                        // A templated resource always states one (E013);
174                        // none is read as no ceiling.
175                        cardinality: r
176                            .template
177                            .has_params()
178                            .then(|| r.cardinality.unwrap_or(u64::from(u32::MAX))),
179                        ttl,
180                    });
181                    Some(collections.len() - 1)
182                }
183                _ => None,
184            };
185            states.push((r.token, r.template.clone(), index));
186        }
187        Layout {
188            iface: c.iface.clone(),
189            tag: Self::tag_of(&fingerprint),
190            fingerprint,
191            collections,
192            states,
193        }
194    }
195
196    /// A heartbeat's tag for a revision: the low 4 bits of its
197    /// fingerprint's last byte, its last hex digit.
198    #[must_use]
199    pub fn tag_of(fp: &Fingerprint) -> Tag {
200        let last = fp.hex().as_str().as_bytes()[63];
201        let v = (last as char)
202            .to_digit(16)
203            .expect("a fingerprint is lowercase hex");
204        Tag::new(v as u8).expect("one hex digit is a tag")
205    }
206
207    /// The shortest horizon among the collections, `None` with none.
208    #[must_use]
209    pub fn horizon(&self) -> Option<Duration> {
210        self.collections.iter().map(|c| c.ttl).min()
211    }
212
213    /// The collection named `<kind token>/<template>`.
214    #[must_use]
215    pub fn index_of(&self, resource: &str) -> Option<usize> {
216        self.collections
217            .iter()
218            .position(|c| c.resource() == resource)
219    }
220
221    /// The collection a member key belongs to: a base-relative state key
222    /// (or one with a namespace in front) of this interface whose winning
223    /// template (§2.2) is a collection's. `None` for any other key.
224    #[must_use]
225    pub fn collection_of(&self, key: &str) -> Option<usize> {
226        let (token, chunks) = self.state_chunks(key)?;
227        let candidates: Vec<&(KindToken, Template, Option<usize>)> =
228            self.states.iter().filter(|(t, _, _)| *t == token).collect();
229        let refs: Vec<&str> = chunks.iter().map(String::as_str).collect();
230        let (i, _) = crate::template::resolve(candidates.iter().map(|(_, t, _)| t), &refs)?;
231        candidates[i].2
232    }
233
234    fn state_chunks(&self, key: &str) -> Option<(KindToken, Vec<String>)> {
235        let k = base_relative(key)?;
236        match parse(k) {
237            Ok(ZkKey::Data {
238                iface,
239                kind,
240                resource,
241                ..
242            }) if iface == self.iface
243                && matches!(kind, KindToken::State | KindToken::ExplicitState) =>
244            {
245                Some((kind, resource))
246            }
247            _ => None,
248        }
249    }
250}
251
252/// A key from its first `zk2/` chunk from which the grammar parses a zk2
253/// key: a session in no namespace hears the namespace in front.
254#[must_use]
255pub fn base_relative(key: &str) -> Option<&str> {
256    let mut rest = Some(key);
257    while let Some(k) = rest {
258        if k.starts_with("zk2/") && parse(k).is_ok() {
259            return Some(k);
260        }
261        rest = k.split_once('/').map(|(_, r)| r);
262    }
263    None
264}
265
266/// A collection's digest: the XOR of each live member's value, 0 with none
267/// live. Toggling a member's value in or out keeps it in O(1).
268#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
269pub struct Digest(u32);
270
271impl Digest {
272    /// No member live.
273    pub const EMPTY: Digest = Digest(0);
274
275    /// A digest as a body carries it.
276    #[must_use]
277    pub const fn from_u32(v: u32) -> Digest {
278        Digest(v)
279    }
280
281    /// Its value.
282    #[must_use]
283    pub const fn get(self) -> u32 {
284        self.0
285    }
286
287    /// A live member's value: the first 4 bytes, big-endian, of the sha256
288    /// of its base-relative key, a zero byte, its run's width bit (0 for a
289    /// 16-bit run, 1 for a 32-bit run), then its run and seq as an envelope
290    /// writes them.
291    #[must_use]
292    pub fn member(key: &str, stamp: Stamp) -> u32 {
293        let mut h = Sha256::new();
294        h.update(key.as_bytes());
295        h.update([0, u8::from(stamp.run.is_wide())]);
296        match stamp.run {
297            Run::U16(v) => h.update(v.to_be_bytes()),
298            Run::U32(v) => h.update(v.to_be_bytes()),
299        }
300        h.update(&stamp.seq.get().to_be_bytes()[1..]);
301        let d = h.finalize();
302        u32::from_be_bytes([d[0], d[1], d[2], d[3]])
303    }
304
305    /// The digest of these live members.
306    #[must_use]
307    pub fn of<'a>(members: impl IntoIterator<Item = (&'a str, Stamp)>) -> Digest {
308        let mut d = Digest::EMPTY;
309        for (k, s) in members {
310            d.toggle(k, s);
311        }
312        d
313    }
314
315    /// A member's value in or out: a put adds the new stamp's and removes
316    /// the old one's, a delete removes it.
317    pub fn toggle(&mut self, key: &str, stamp: Stamp) {
318        self.0 ^= Digest::member(key, stamp);
319    }
320}
321
322impl std::fmt::Display for Digest {
323    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
324        write!(f, "{:08x}", self.0)
325    }
326}
327
328/// The owner's clock when it wrote the heartbeat.
329#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
330pub enum Time {
331    /// All 42 bits set: the owner's clock is unknown.
332    Unknown,
333    /// Seconds from the deployment epoch, then milliseconds below 1000.
334    At { secs: u32, ms: u16 },
335}
336
337impl Time {
338    /// Its 42-bit code.
339    #[must_use]
340    pub fn code(self) -> u64 {
341        match self {
342            Time::Unknown => (1 << TIME_BITS) - 1,
343            Time::At { secs, ms } => (u64::from(secs) << 10) | u64::from(ms),
344        }
345    }
346
347    /// A 42-bit code read: `code` for a millisecond code from 1000 up but
348    /// the unknown time's.
349    ///
350    /// # Errors
351    /// [`BodyRefusal::Code`].
352    pub fn from_code(code: u64) -> Result<Time, BodyRefusal> {
353        if code == (1 << TIME_BITS) - 1 {
354            return Ok(Time::Unknown);
355        }
356        let ms = (code & 0x3ff) as u16;
357        if ms >= 1000 {
358            return Err(BodyRefusal::Code);
359        }
360        Ok(Time::At {
361            secs: (code >> 10) as u32,
362            ms,
363        })
364    }
365
366    /// An instant in milliseconds since the Unix epoch, under the
367    /// deployment epoch `epoch` in seconds (core §7.6): `None` outside the
368    /// epoch's 2^32 seconds.
369    #[must_use]
370    pub fn from_unix_ms(t: i128, epoch: i64) -> Option<Time> {
371        let code = crate::packed::time_code(t, Some(epoch), true).ok()?;
372        Time::from_code(code).ok()
373    }
374
375    /// The instant in milliseconds since the Unix epoch, `None` when
376    /// unknown.
377    #[must_use]
378    pub fn unix_ms(self, epoch: i64) -> Option<i128> {
379        match self {
380            Time::Unknown => None,
381            Time::At { .. } => crate::packed::time_value(self.code(), Some(epoch), true).ok(),
382        }
383    }
384}
385
386/// A section's members.
387#[derive(Debug, Clone, PartialEq, Eq, Hash)]
388pub enum Members {
389    /// A collection of one member: whether it is vouched for.
390    One { vouched: bool },
391    /// A templated collection's bitmap: one bit for each live member, in
392    /// key order.
393    Bitmap(Vec<bool>),
394    /// A templated collection's list: its live count, and the ranks vouched
395    /// for, ascending.
396    List { live: u64, ranks: Vec<u64> },
397}
398
399impl Members {
400    /// A templated collection's members as a writer writes them: the list
401    /// only where it is shorter than the bitmap (core §7.5's MUST). The
402    /// ranks are taken in any order, each once, below `live`.
403    #[must_use]
404    pub fn templated(live: u64, vouched: impl IntoIterator<Item = u64>) -> Members {
405        let mut ranks: Vec<u64> = vouched.into_iter().filter(|r| *r < live).collect();
406        ranks.sort_unstable();
407        ranks.dedup();
408        let list = u128::from(bits_for(u128::from(live) + 1))
409            + ranks.len() as u128 * u128::from(bits_for(u128::from(live)));
410        if list < u128::from(live) {
411            Members::List { live, ranks }
412        } else {
413            let mut bits = vec![false; usize::try_from(live).unwrap_or(usize::MAX)];
414            for r in ranks {
415                bits[r as usize] = true;
416            }
417            Members::Bitmap(bits)
418        }
419    }
420
421    /// The live count; `None` with one member.
422    #[must_use]
423    pub fn live(&self) -> Option<u64> {
424        match self {
425            Members::One { .. } => None,
426            Members::Bitmap(b) => Some(b.len() as u64),
427            Members::List { live, .. } => Some(*live),
428        }
429    }
430
431    /// The ranks vouched for, ascending; `[0]` for one member vouched for.
432    #[must_use]
433    pub fn vouched(&self) -> Vec<u64> {
434        match self {
435            Members::One { vouched } => {
436                if *vouched {
437                    vec![0]
438                } else {
439                    vec![]
440                }
441            }
442            Members::Bitmap(b) => (0..b.len() as u64).filter(|i| b[*i as usize]).collect(),
443            Members::List { ranks, .. } => ranks.clone(),
444        }
445    }
446
447    /// `bitmap` or `list` for a templated collection, as the fixtures
448    /// name the form read; `None` with one member.
449    #[must_use]
450    pub fn form(&self) -> Option<&'static str> {
451        match self {
452            Members::One { .. } => None,
453            Members::Bitmap(_) => Some("bitmap"),
454            Members::List { .. } => Some("list"),
455        }
456    }
457}
458
459/// One collection's section.
460#[derive(Debug, Clone, PartialEq, Eq, Hash)]
461pub struct Section {
462    pub digest: Digest,
463    pub members: Members,
464}
465
466/// A heartbeat's body, read: its time, and a section for each collection
467/// whose map bit is set (`None` where it is 0), in map order.
468#[derive(Debug, Clone, PartialEq, Eq, Hash)]
469pub struct Heartbeat {
470    pub time: Time,
471    pub sections: Vec<Option<Section>>,
472}
473
474/// Why a body is not a heartbeat of its layout, in core §7.5's order.
475#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Error)]
476pub enum BodyRefusal {
477    /// The body ends before a bit its fields need.
478    #[error("short: the body ends before a bit its fields need")]
479    Short,
480    /// A code is unused: a millisecond code from 1000 up but the unknown
481    /// time's, a live count above the cardinality, a count above the live
482    /// count, or a rank not below the live count or not above the one
483    /// before it.
484    #[error("code: an unused code")]
485    Code,
486    /// A byte after the pad.
487    #[error("trailing: a byte after the pad")]
488    Trailing,
489    /// A bit of the pad is 1.
490    #[error("pad: a bit of the pad is 1")]
491    Pad,
492}
493
494impl BodyRefusal {
495    /// The token `spec/conformance/heartbeat/bodies.json` pins.
496    #[must_use]
497    pub const fn token(self) -> &'static str {
498        match self {
499            BodyRefusal::Short => "short",
500            BodyRefusal::Code => "code",
501            BodyRefusal::Trailing => "trailing",
502            BodyRefusal::Pad => "pad",
503        }
504    }
505}
506
507/// Why a heartbeat value cannot be written under a layout.
508#[derive(Debug, Clone, PartialEq, Eq, Error)]
509pub enum WriteError {
510    #[error("{have} sections for {need} collections")]
511    Sections { need: usize, have: usize },
512    #[error("collection {0}: members of the wrong shape for its template")]
513    Shape(usize),
514    #[error("collection {0}: a live count above its cardinality")]
515    Live(usize),
516    #[error("collection {0}: ranks not ascending below the live count")]
517    Ranks(usize),
518}
519
520fn take(r: &mut BitReader<'_>, width: u32) -> Result<u64, BodyRefusal> {
521    r.take(width).map_err(|_| BodyRefusal::Short)
522}
523
524impl Heartbeat {
525    /// A body read with its covered revision's layout, or the first
526    /// refusal that applies (core §7.5): the fields in order (`short`,
527    /// `code`), then a byte after the pad (`trailing`), then a pad bit set
528    /// (`pad`). CH's tag is the caller's to compare with
529    /// [`Layout::tag`].
530    ///
531    /// # Errors
532    /// The [`BodyRefusal`].
533    pub fn parse(body: &[u8], layout: &Layout) -> Result<Heartbeat, BodyRefusal> {
534        let mut r = BitReader::new(body);
535        let time = Time::from_code(take(&mut r, TIME_BITS)?)?;
536        let mut map = Vec::with_capacity(layout.collections.len());
537        for _ in &layout.collections {
538            map.push(take(&mut r, 1)? == 1);
539        }
540        let mut sections = Vec::with_capacity(map.len());
541        for (c, on) in layout.collections.iter().zip(map) {
542            if !on {
543                sections.push(None);
544                continue;
545            }
546            let digest = Digest(take(&mut r, 32)? as u32);
547            let members = match (c.cardinality, c.live_bits()) {
548                (Some(card), Some(w)) => {
549                    let live = take(&mut r, w)?;
550                    if live > card {
551                        return Err(BodyRefusal::Code);
552                    }
553                    if take(&mut r, 1)? == 0 {
554                        let mut bits = Vec::new();
555                        for _ in 0..live {
556                            bits.push(take(&mut r, 1)? == 1);
557                        }
558                        Members::Bitmap(bits)
559                    } else {
560                        let count = take(&mut r, bits_for(u128::from(live) + 1))?;
561                        if count > live {
562                            return Err(BodyRefusal::Code);
563                        }
564                        let rw = bits_for(u128::from(live));
565                        let mut ranks: Vec<u64> = Vec::new();
566                        for _ in 0..count {
567                            let rank = take(&mut r, rw)?;
568                            if rank >= live || ranks.last().is_some_and(|p| rank <= *p) {
569                                return Err(BodyRefusal::Code);
570                            }
571                            ranks.push(rank);
572                        }
573                        Members::List { live, ranks }
574                    }
575                }
576                _ => Members::One {
577                    vouched: take(&mut r, 1)? == 1,
578                },
579            };
580            sections.push(Some(Section { digest, members }));
581        }
582        r.end().map_err(|e| match e {
583            ReadRefusal::Pad => BodyRefusal::Pad,
584            _ => BodyRefusal::Trailing,
585        })?;
586        Ok(Heartbeat { time, sections })
587    }
588
589    /// The body's bits and pad under `layout` ([`crate::packed::Record`]).
590    ///
591    /// # Errors
592    /// A [`WriteError`]: a section per collection, each of its
593    /// collection's shape, a live count within the cardinality, and ranks
594    /// ascending below it.
595    pub fn record(&self, layout: &Layout) -> Result<crate::packed::Record, WriteError> {
596        if self.sections.len() != layout.collections.len() {
597            return Err(WriteError::Sections {
598                need: layout.collections.len(),
599                have: self.sections.len(),
600            });
601        }
602        let mut w = BitWriter::new();
603        w.push(self.time.code(), TIME_BITS);
604        for s in &self.sections {
605            w.bit(s.is_some());
606        }
607        for (i, (c, s)) in layout.collections.iter().zip(&self.sections).enumerate() {
608            let Some(s) = s else { continue };
609            w.push(u64::from(s.digest.0), 32);
610            match (&s.members, c.cardinality, c.live_bits()) {
611                (Members::One { vouched }, None, _) => w.bit(*vouched),
612                (Members::Bitmap(bits), Some(card), Some(lw)) => {
613                    let live = bits.len() as u64;
614                    if live > card {
615                        return Err(WriteError::Live(i));
616                    }
617                    w.push(live, lw);
618                    w.bit(false);
619                    for b in bits {
620                        w.bit(*b);
621                    }
622                }
623                (Members::List { live, ranks }, Some(card), Some(lw)) => {
624                    if *live > card {
625                        return Err(WriteError::Live(i));
626                    }
627                    if ranks.windows(2).any(|p| p[0] >= p[1]) || ranks.iter().any(|r| r >= live) {
628                        return Err(WriteError::Ranks(i));
629                    }
630                    w.push(*live, lw);
631                    w.bit(true);
632                    w.push(ranks.len() as u64, bits_for(u128::from(*live) + 1));
633                    let rw = bits_for(u128::from(*live));
634                    for r in ranks {
635                        w.push(*r, rw);
636                    }
637                }
638                _ => return Err(WriteError::Shape(i)),
639            }
640        }
641        Ok(w.finish())
642    }
643
644    /// The body's bytes under `layout`, its pad included.
645    ///
646    /// # Errors
647    /// As [`Heartbeat::record`].
648    pub fn write(&self, layout: &Layout) -> Result<Vec<u8>, WriteError> {
649        self.record(layout).map(|r| r.bytes)
650    }
651
652    /// The heartbeat as a put's payload: CH (form 6, the run's width, the
653    /// layout's tag), the stamp, then the body.
654    ///
655    /// # Errors
656    /// As [`Heartbeat::record`].
657    pub fn envelope(&self, layout: &Layout, stamp: Stamp) -> Result<Vec<u8>, WriteError> {
658        let body = self.write(layout)?;
659        Ok(wire::Envelope {
660            form: wire::Form::Heartbeat,
661            tag: layout.tag,
662            stamp,
663            record: &body,
664        }
665        .write())
666    }
667}
668
669#[cfg(test)]
670mod tests {
671    use super::*;
672    use crate::wire::Seq;
673
674    fn stamp(run: u16, seq: u32) -> Stamp {
675        Stamp {
676            run: Run::U16(run),
677            seq: Seq::new(seq).unwrap(),
678        }
679    }
680
681    #[test]
682    fn widths() {
683        assert_eq!(bits_for(1), 0);
684        assert_eq!(bits_for(2), 1);
685        assert_eq!(bits_for(3), 2);
686        assert_eq!(bits_for(6), 3);
687        assert_eq!(bits_for(1 << 32), 32);
688        assert_eq!(bits_for((1 << 32) + 1), 33);
689    }
690
691    #[test]
692    fn the_writer_writes_the_list_only_where_it_is_shorter() {
693        assert!(matches!(Members::templated(3, [0, 2]), Members::Bitmap(_)));
694        assert!(matches!(Members::templated(5, []), Members::List { .. }));
695        // A tie keeps the bitmap: 1 bit against 1 + 0.
696        assert!(matches!(Members::templated(1, [0]), Members::Bitmap(_)));
697        assert_eq!(Members::templated(40, [17, 17, 99]).vouched(), vec![17]);
698    }
699
700    #[test]
701    fn the_digest_is_free_of_order_and_toggles() {
702        let a = ("zk2/s/v/i.v1/state/p/a", stamp(1, 1));
703        let b = ("zk2/s/v/i.v1/state/p/b", stamp(1, 2));
704        assert_eq!(Digest::of([a, b]), Digest::of([b, a]));
705        let mut d = Digest::of([a, b]);
706        d.toggle(b.0, b.1);
707        assert_eq!(d, Digest::of([a]));
708        d.toggle(a.0, a.1);
709        assert_eq!(d, Digest::EMPTY);
710    }
711
712    #[test]
713    fn a_heartbeat_key_names_its_covered_interface() {
714        let iface = IfaceId::new("modem", 3).unwrap();
715        let k = key("h-1", "rf0", &iface);
716        assert_eq!(k, "zk2/h-1/rf0/freshness.v2/stream/heartbeat/modem.v3");
717        let (addr, got) = covered(&k).unwrap();
718        assert_eq!(
719            (addr.to_string(), got),
720            ("h-1/rf0".to_owned(), iface.clone())
721        );
722        assert_eq!(covered(&format!("prod/{k}")).map(|c| c.1), Some(iface));
723        assert_eq!(covered("zk2/h/s/health.v1/stream/heartbeat/x.v1"), None);
724        assert_eq!(covered("zk2/h/s/freshness.v2/state/heartbeat/x.v1"), None);
725        assert_eq!(covered("demo/tick"), None);
726    }
727}