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//!            and all ones but the last bit ahead: the owner's clock guard holds
10//! map        1 bit for each collection of the covered revision, in its order
11//! section    digest32 · members
12//! members    one member: vouched1
13//!            templated:  live (⌈log₂(c + 1)⌉) · sel1 · (bitmap | count · ranks)
14//! ```
15//!
16//! **The collections** ([`Layout::of`]) of a revision are its `state` and
17//! `@state` resources whose resolved `freshness.ttl_s` is above 0, in the
18//! canonical resource order (by kind token, then template). The map's
19//! width and each templated section's widths come from them, so a body is
20//! read with the covered revision ([`Heartbeat::parse`]); CH's tag, the
21//! low 4 bits of the revision's fingerprint ([`Layout::tag`]), is the
22//! check that the reader holds that revision.
23//!
24//! **The digest** ([`Digest`]) of a collection is the XOR over its live
25//! members of the first 4 bytes of the sha256 of the key, a zero byte, the
26//! run's width bit, the run and the seq. It is free of order, so an owner
27//! keeps it at each mutation and a reader computes it over its own view.
28//!
29//! `freshness.v2` (#978's F3, core 0.82) adopts it: an owner of a
30//! contract that uses it sends one heartbeat per interface it serves that
31//! has a collection, on [`key`], at most half the shortest horizon apart
32//! (v2 §2.4), and a reader confirms by it as [`crate::freshness::View`]
33//! reads it (v2 §2.5, `spec/profiles/freshness/conformance/apply.json`).
34//! The refusals' tokens are `spec/conformance/heartbeat/bodies.json`'s.
35//!
36//! **The owner heartbeat** (core 0.108; #1110's H1) is form 6's second
37//! layout: one put for several interfaces an owner serves, a [`Group`]
38//! for each. `freshness.v2` 0.9 adopts it (#1110's H2a): an owner under a
39//! catalog may send one for each [`Class`] of collection it holds, on
40//! [`owner_key`], in place of its interfaces' heartbeats (v2 §2.4), and a
41//! reader confirms by it as [`crate::freshness::Views`] reads it (v2
42//! §2.5).
43//!
44//! ```text
45//! owner heartbeat, a put's payload   CH · run · seq · body      CH: form 6 · run width · tag 0
46//! body       time · groups · that many groups · pad
47//! groups     4 bits: the count of groups, from 1 to 15
48//! group      index10 · tag4 · size · sections
49//! size       unsigned LEB128, each byte the body's next 8 bits: the sections' count of bits
50//! sections   map · a section for each map bit set, as a heartbeat's body between its time and its pad
51//! ```
52//!
53//! It is read in two steps. [`OwnerHeartbeat::parse`] reads the groups
54//! with no contract, each one's sections taken unread, and refuses the
55//! whole put ([`OwnerRefusal`]). [`Group::entry`] then reads a group's
56//! index through the catalog its owner names (core §8.6) and
57//! [`Group::read`] its sections with that revision's [`Layout`], each
58//! refusing that group alone ([`GroupRefusal`]). Nothing in a body tells
59//! the two layouts apart, and CH's tag does only 15 times in 16 (an owner
60//! heartbeat's is 0, a heartbeat's its covered revision's): the key
61//! chooses. So the caller says which one a key carries, and calls
62//! [`Heartbeat::parse`] or [`OwnerHeartbeat::parse`]. The tokens are
63//! `spec/conformance/heartbeat/owner.json`'s.
64//!
65//! **Another form on either key** is refused `form` before a tag or a
66//! body is read (core §7.5): both are `stream` keys, so the envelope's
67//! parse accepts a mutation or a frame there. [`body_of`] is that gate,
68//! and [`OwnerHeartbeat::of`] reads an owner heartbeat's put through it.
69
70use std::time::Duration;
71
72use sha2::{Digest as _, Sha256};
73use thiserror::Error;
74
75use crate::canonical::Fingerprint;
76use crate::catalog::{self, Catalog, CatalogId};
77use crate::collection::{IntegerRefusal, read_integer, write_integer};
78use crate::contract::Contract;
79use crate::freshness::{Horizon, horizon_of};
80use crate::grammar::{IfaceId, KindToken, ZkKey, parse};
81use crate::packed::{BitReader, BitWriter, ReadRefusal, Record};
82use crate::template::Template;
83use crate::wire::{self, Envelope, Form, Run, Stamp, Tag};
84
85/// The profile that adopts the heartbeat (#978's F3), as its key's
86/// interface chunk spells it.
87pub const PROFILE: &str = "freshness.v2";
88
89/// The resource `freshness.v2`'s standard contract declares, its
90/// parameter the covered interface's id (v2 §3).
91pub const RESOURCE: &str = "heartbeat/{iface}";
92
93/// The resource `freshness.v2`'s standard contract declares for the owner
94/// heartbeat since its revision 1.1, its parameter the class (v2 §3).
95pub const OWNER_RESOURCE: &str = "heartbeats/{class}";
96
97/// The width of a heartbeat's time: 32 bits of seconds, then 10 of
98/// milliseconds, as core §7.6's `time` field with `ms`.
99pub const TIME_BITS: u32 = 42;
100
101/// A collection's class (`freshness.v2` §2.4): `link` where its resolved
102/// `link.exposure` reads `link`, as `link.v1` §2.2 reads it, and `host`
103/// otherwise, absent or any other value. An owner heartbeat key is one
104/// class's, and its groups cover the collections of that class.
105#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
106pub enum Class {
107    Link,
108    Host,
109}
110
111impl Class {
112    /// Both classes: an owner puts on no other key (v2 §3).
113    pub const ALL: [Class; 2] = [Class::Link, Class::Host];
114
115    /// `link` or `host`, the owner heartbeat key's last chunk.
116    #[must_use]
117    pub const fn as_str(self) -> &'static str {
118        match self {
119            Class::Link => "link",
120            Class::Host => "host",
121        }
122    }
123
124    /// The class a key's last chunk names, `None` for any other chunk.
125    #[must_use]
126    pub fn from_chunk(chunk: &str) -> Option<Class> {
127        Class::ALL.into_iter().find(|c| c.as_str() == chunk)
128    }
129
130    /// The class of a resource, from its resolved `link.exposure`.
131    #[must_use]
132    pub fn of(r: &crate::contract::Resource) -> Class {
133        match crate::link::exposure_of(r) {
134            crate::link::Exposure::Link => Class::Link,
135            _ => Class::Host,
136        }
137    }
138}
139
140impl std::fmt::Display for Class {
141    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
142        f.write_str(self.as_str())
143    }
144}
145
146/// The base-relative key a heartbeat covering `iface` travels on from the
147/// service at `system/service`: `zk2/<system>/<service>/freshness.v2/stream/heartbeat/<iface>`
148/// (`freshness.v2` §3 declares it). An interface id
149/// is a plain chunk, so it needs no slug.
150#[must_use]
151pub fn key(system: &str, service: &str, iface: &IfaceId) -> String {
152    format!("zk2/{system}/{service}/{PROFILE}/stream/heartbeat/{iface}")
153}
154
155/// The base-relative key an owner heartbeat of `class` travels on from the
156/// service at `system/service`:
157/// `zk2/<system>/<service>/freshness.v2/stream/heartbeats/<class>`
158/// (`freshness.v2` §3, the standard contract's revision 1.1).
159#[must_use]
160pub fn owner_key(system: &str, service: &str, class: Class) -> String {
161    format!("zk2/{system}/{service}/{PROFILE}/stream/heartbeats/{class}")
162}
163
164/// The chunks of a `freshness.v2` stream key after its kind token, with
165/// the address it is put from, read from a key with a namespace in front
166/// or none: `None` for any other key.
167fn profile_stream(key: &str) -> Option<(crate::grammar::Addr, Vec<String>)> {
168    let mut rest = Some(key);
169    while let Some(k) = rest {
170        if k.starts_with("zk2/")
171            && let Ok(ZkKey::Data {
172                addr,
173                iface,
174                kind: KindToken::Stream,
175                resource,
176            }) = parse(k)
177        {
178            return (iface.to_string() == PROFILE).then_some((addr, resource));
179        }
180        rest = k.split_once('/').map(|(_, r)| r);
181    }
182    None
183}
184
185/// The covered interface a heartbeat key names, read from a key with a
186/// namespace in front or none: `None` for any other key.
187#[must_use]
188pub fn covered(key: &str) -> Option<(crate::grammar::Addr, IfaceId)> {
189    let (addr, resource) = profile_stream(key)?;
190    let [h, covered] = resource.as_slice() else {
191        return None;
192    };
193    if h != "heartbeat" {
194        return None;
195    }
196    let (name, major) = covered.rsplit_once(".v")?;
197    Some((addr, IfaceId::new(name, major.parse().ok()?).ok()?))
198}
199
200/// Whether `key` is a heartbeat's key or an owner heartbeat's, with a
201/// namespace in front or none: the two keys that carry form 6 and no
202/// other (core §7.5, "Another form on a heartbeat's key"). A reader of
203/// either refuses any other put on it `form` ([`body_of`]), and one that
204/// holds a put with no envelope, so no [`Envelope`], refuses it the same
205/// way.
206#[must_use]
207pub fn is_key(key: &str) -> bool {
208    covered(key).is_some() || owner_class(key).is_some()
209}
210
211/// The class an owner heartbeat key names, read from a key with a
212/// namespace in front or none: `None` for any other key, one whose last
213/// chunk is no class among them. A reader tells an owner heartbeat from a
214/// heartbeat by this, never by its bytes (core §7.5).
215#[must_use]
216pub fn owner_class(key: &str) -> Option<(crate::grammar::Addr, Class)> {
217    let (addr, resource) = profile_stream(key)?;
218    let [h, class] = resource.as_slice() else {
219        return None;
220    };
221    if h != "heartbeats" {
222        return None;
223    }
224    Some((addr, Class::from_chunk(class)?))
225}
226
227/// ⌈log₂ n⌉ for n ≥ 1, 0 for n ≤ 1: the fewest bits that hold n codes.
228fn bits_for(n: u128) -> u32 {
229    if n <= 1 {
230        0
231    } else {
232        128 - (n - 1).leading_zeros()
233    }
234}
235
236/// One collection of a revision: a `state` or `@state` resource whose
237/// horizon is above 0.
238#[derive(Debug, Clone, PartialEq, Eq)]
239pub struct Collection {
240    pub token: KindToken,
241    pub template: Template,
242    /// Its cardinality when its template has a parameter; `None` for one
243    /// member.
244    pub cardinality: Option<u64>,
245    /// Its horizon, `freshness.ttl_s`.
246    pub ttl: Duration,
247    /// Its class, which of its owner's owner heartbeats covers it
248    /// (`freshness.v2` §2.4).
249    pub class: Class,
250}
251
252impl Collection {
253    /// `<kind token>/<template>`, as the fixtures name it.
254    #[must_use]
255    pub fn resource(&self) -> String {
256        format!("{}/{}", self.token.as_str(), self.template.as_str())
257    }
258
259    /// Whether its template has a parameter.
260    #[must_use]
261    pub fn is_templated(&self) -> bool {
262        self.cardinality.is_some()
263    }
264
265    /// The width of its live count, ⌈log₂(c + 1)⌉; `None` with one member.
266    #[must_use]
267    pub fn live_bits(&self) -> Option<u32> {
268        self.cardinality.map(|c| bits_for(u128::from(c) + 1))
269    }
270}
271
272/// A revision's collections, its fingerprint and the heartbeat's tag: what
273/// a heartbeat covering it is read and written by.
274#[derive(Debug, Clone, PartialEq, Eq)]
275pub struct Layout {
276    pub iface: IfaceId,
277    pub fingerprint: Fingerprint,
278    /// The low 4 bits of the fingerprint's last byte.
279    pub tag: Tag,
280    /// In map order.
281    pub collections: Vec<Collection>,
282    /// Every `state` and `@state` template of the revision, each with its
283    /// collection's index, so a key resolves among them all (§2.2).
284    states: Vec<(KindToken, Template, Option<usize>)>,
285}
286
287impl Layout {
288    /// The layout of a revision.
289    #[must_use]
290    pub fn of(c: &Contract) -> Layout {
291        let fingerprint = Fingerprint::of(c);
292        let mut collections = Vec::new();
293        let mut states = Vec::new();
294        for r in &c.resources {
295            if !matches!(r.token, KindToken::State | KindToken::ExplicitState) {
296                continue;
297            }
298            let index = match horizon_of(r) {
299                Horizon::Within(ttl) => {
300                    collections.push(Collection {
301                        token: r.token,
302                        template: r.template.clone(),
303                        // A templated resource always states one (E013);
304                        // none is read as no ceiling.
305                        cardinality: r
306                            .template
307                            .has_params()
308                            .then(|| r.cardinality.unwrap_or(u64::from(u32::MAX))),
309                        ttl,
310                        class: Class::of(r),
311                    });
312                    Some(collections.len() - 1)
313                }
314                _ => None,
315            };
316            states.push((r.token, r.template.clone(), index));
317        }
318        Layout {
319            iface: c.iface.clone(),
320            tag: Self::tag_of(&fingerprint),
321            fingerprint,
322            collections,
323            states,
324        }
325    }
326
327    /// A heartbeat's tag for a revision: the low 4 bits of its
328    /// fingerprint's last byte, its last hex digit.
329    #[must_use]
330    pub fn tag_of(fp: &Fingerprint) -> Tag {
331        let last = fp.hex().as_str().as_bytes()[63];
332        let v = (last as char)
333            .to_digit(16)
334            .expect("a fingerprint is lowercase hex");
335        Tag::new(v as u8).expect("one hex digit is a tag")
336    }
337
338    /// The shortest horizon among the collections, `None` with none.
339    #[must_use]
340    pub fn horizon(&self) -> Option<Duration> {
341        self.collections.iter().map(|c| c.ttl).min()
342    }
343
344    /// The shortest horizon among the collections of `class`, `None` with
345    /// none: what the revision asks of the period of that class's owner
346    /// heartbeats (`freshness.v2` §2.4).
347    #[must_use]
348    pub fn class_horizon(&self, class: Class) -> Option<Duration> {
349        self.collections
350            .iter()
351            .filter(|c| c.class == class)
352            .map(|c| c.ttl)
353            .min()
354    }
355
356    /// The classes the revision's collections have, `link` first: the
357    /// owner heartbeat keys a group covering it may ride.
358    #[must_use]
359    pub fn classes(&self) -> Vec<Class> {
360        Class::ALL
361            .into_iter()
362            .filter(|c| self.collections.iter().any(|x| x.class == *c))
363            .collect()
364    }
365
366    /// The collection named `<kind token>/<template>`.
367    #[must_use]
368    pub fn index_of(&self, resource: &str) -> Option<usize> {
369        self.collections
370            .iter()
371            .position(|c| c.resource() == resource)
372    }
373
374    /// The collection a member key belongs to: a base-relative state key
375    /// (or one with a namespace in front) of this interface whose winning
376    /// template (§2.2) is a collection's. `None` for any other key.
377    #[must_use]
378    pub fn collection_of(&self, key: &str) -> Option<usize> {
379        let (token, chunks) = self.state_chunks(key)?;
380        let candidates: Vec<&(KindToken, Template, Option<usize>)> =
381            self.states.iter().filter(|(t, _, _)| *t == token).collect();
382        let refs: Vec<&str> = chunks.iter().map(String::as_str).collect();
383        let (i, _) = crate::template::resolve(candidates.iter().map(|(_, t, _)| t), &refs)?;
384        candidates[i].2
385    }
386
387    fn state_chunks(&self, key: &str) -> Option<(KindToken, Vec<String>)> {
388        let k = base_relative(key)?;
389        match parse(k) {
390            Ok(ZkKey::Data {
391                iface,
392                kind,
393                resource,
394                ..
395            }) if iface == self.iface
396                && matches!(kind, KindToken::State | KindToken::ExplicitState) =>
397            {
398                Some((kind, resource))
399            }
400            _ => None,
401        }
402    }
403}
404
405/// A key from its first `zk2/` chunk from which the grammar parses a zk2
406/// key: a session in no namespace hears the namespace in front.
407#[must_use]
408pub fn base_relative(key: &str) -> Option<&str> {
409    let mut rest = Some(key);
410    while let Some(k) = rest {
411        if k.starts_with("zk2/") && parse(k).is_ok() {
412            return Some(k);
413        }
414        rest = k.split_once('/').map(|(_, r)| r);
415    }
416    None
417}
418
419/// A collection's digest: the XOR of each live member's value, 0 with none
420/// live. Toggling a member's value in or out keeps it in O(1).
421#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
422pub struct Digest(u32);
423
424impl Digest {
425    /// No member live.
426    pub const EMPTY: Digest = Digest(0);
427
428    /// A digest as a body carries it.
429    #[must_use]
430    pub const fn from_u32(v: u32) -> Digest {
431        Digest(v)
432    }
433
434    /// Its value.
435    #[must_use]
436    pub const fn get(self) -> u32 {
437        self.0
438    }
439
440    /// A live member's value: the first 4 bytes, big-endian, of the sha256
441    /// of its base-relative key, a zero byte, its run's width bit (0 for a
442    /// 16-bit run, 1 for a 32-bit run), then its run and seq as an envelope
443    /// writes them.
444    #[must_use]
445    pub fn member(key: &str, stamp: Stamp) -> u32 {
446        let mut h = Sha256::new();
447        h.update(key.as_bytes());
448        h.update([0, u8::from(stamp.run.is_wide())]);
449        match stamp.run {
450            Run::U16(v) => h.update(v.to_be_bytes()),
451            Run::U32(v) => h.update(v.to_be_bytes()),
452        }
453        h.update(&stamp.seq.get().to_be_bytes()[1..]);
454        let d = h.finalize();
455        u32::from_be_bytes([d[0], d[1], d[2], d[3]])
456    }
457
458    /// The digest of these live members.
459    #[must_use]
460    pub fn of<'a>(members: impl IntoIterator<Item = (&'a str, Stamp)>) -> Digest {
461        let mut d = Digest::EMPTY;
462        for (k, s) in members {
463            d.toggle(k, s);
464        }
465        d
466    }
467
468    /// A member's value in or out: a put adds the new stamp's and removes
469    /// the old one's, a delete removes it.
470    pub fn toggle(&mut self, key: &str, stamp: Stamp) {
471        self.0 ^= Digest::member(key, stamp);
472    }
473}
474
475impl std::fmt::Display for Digest {
476    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
477        write!(f, "{:08x}", self.0)
478    }
479}
480
481/// The owner's word of its clock when it wrote the heartbeat (core §7.5):
482/// an instant, or one of the two codes that carry none. A reader reads a
483/// time as one of the three, and never the ahead time as either other.
484#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
485pub enum Time {
486    /// All 42 bits set: the owner's clock reads no instant the epoch codes
487    /// (`freshness.v2` §2.4). It says nothing of the clock guard.
488    Unknown,
489    /// The seconds all ones with the millisecond code 1022, the unknown
490    /// time with its last bit clear: the owner's clock guard holds (core
491    /// §4.3, "Ahead"; `freshness.v2` §2.10). It carries no instant.
492    Ahead,
493    /// Seconds from the deployment epoch, then milliseconds below 1000.
494    At { secs: u32, ms: u16 },
495}
496
497/// The unknown time's code: all 42 bits set.
498const UNKNOWN_CODE: u64 = (1 << TIME_BITS) - 1;
499
500/// The ahead time's code, `0x3fffffffffe`: the seconds all ones and the
501/// millisecond code 1022.
502const AHEAD_CODE: u64 = UNKNOWN_CODE - 1;
503
504impl Time {
505    /// Its 42-bit code.
506    #[must_use]
507    pub fn code(self) -> u64 {
508        match self {
509            Time::Unknown => UNKNOWN_CODE,
510            Time::Ahead => AHEAD_CODE,
511            Time::At { secs, ms } => (u64::from(secs) << 10) | u64::from(ms),
512        }
513    }
514
515    /// A 42-bit code read: `code` for an unused millisecond code, which is
516    /// every one from 1000 up but the unknown time's and the ahead time's:
517    /// 1000 to 1021 under any seconds, and 1022 or 1023 under seconds that
518    /// are not all ones.
519    ///
520    /// # Errors
521    /// [`BodyRefusal::Code`].
522    pub fn from_code(code: u64) -> Result<Time, BodyRefusal> {
523        match code {
524            UNKNOWN_CODE => return Ok(Time::Unknown),
525            AHEAD_CODE => return Ok(Time::Ahead),
526            _ => {}
527        }
528        let ms = (code & 0x3ff) as u16;
529        if ms >= 1000 {
530            return Err(BodyRefusal::Code);
531        }
532        Ok(Time::At {
533            secs: (code >> 10) as u32,
534            ms,
535        })
536    }
537
538    /// An instant in milliseconds since the Unix epoch, under the
539    /// deployment epoch `epoch` in seconds (core §7.6): `None` outside the
540    /// epoch's 2^32 seconds.
541    #[must_use]
542    pub fn from_unix_ms(t: i128, epoch: i64) -> Option<Time> {
543        let code = crate::packed::time_code(t, Some(epoch), true).ok()?;
544        Time::from_code(code).ok()
545    }
546
547    /// The time an owner writes (`freshness.v2` §2.4, §2.10): the ahead
548    /// time while its clock guard holds, `guard`, whatever its clock reads;
549    /// otherwise the instant `at`, in milliseconds since the Unix epoch,
550    /// under the deployment epoch `epoch` in seconds, or the unknown time
551    /// for a clock that reads none (`None`) or one the epoch does not code.
552    #[must_use]
553    pub fn written(guard: bool, at: Option<i128>, epoch: i64) -> Time {
554        if guard {
555            return Time::Ahead;
556        }
557        at.and_then(|at| Time::from_unix_ms(at, epoch))
558            .unwrap_or(Time::Unknown)
559    }
560
561    /// The instant in milliseconds since the Unix epoch, `None` for a time
562    /// that carries none: unknown or ahead.
563    #[must_use]
564    pub fn unix_ms(self, epoch: i64) -> Option<i128> {
565        match self {
566            Time::Unknown | Time::Ahead => None,
567            Time::At { .. } => crate::packed::time_value(self.code(), Some(epoch), true).ok(),
568        }
569    }
570
571    /// Whether the time is an instant: the owner's guard did not hold when
572    /// it wrote the heartbeat, and its clock read a time the epoch codes.
573    #[must_use]
574    pub fn is_instant(self) -> bool {
575        matches!(self, Time::At { .. })
576    }
577
578    /// Whether the time is the ahead time: the owner's guard held when it
579    /// wrote the heartbeat.
580    #[must_use]
581    pub fn is_ahead(self) -> bool {
582        self == Time::Ahead
583    }
584}
585
586/// A section's members.
587#[derive(Debug, Clone, PartialEq, Eq, Hash)]
588pub enum Members {
589    /// A collection of one member: whether it is vouched for.
590    One { vouched: bool },
591    /// A templated collection's bitmap: one bit for each live member, in
592    /// key order.
593    Bitmap(Vec<bool>),
594    /// A templated collection's list: its live count, and the ranks vouched
595    /// for, ascending.
596    List { live: u64, ranks: Vec<u64> },
597}
598
599impl Members {
600    /// A templated collection's members as a writer writes them: the list
601    /// only where it is shorter than the bitmap (core §7.5's MUST). The
602    /// ranks are taken in any order, each once, below `live`.
603    #[must_use]
604    pub fn templated(live: u64, vouched: impl IntoIterator<Item = u64>) -> Members {
605        let mut ranks: Vec<u64> = vouched.into_iter().filter(|r| *r < live).collect();
606        ranks.sort_unstable();
607        ranks.dedup();
608        let list = u128::from(bits_for(u128::from(live) + 1))
609            + ranks.len() as u128 * u128::from(bits_for(u128::from(live)));
610        if list < u128::from(live) {
611            Members::List { live, ranks }
612        } else {
613            let mut bits = vec![false; usize::try_from(live).unwrap_or(usize::MAX)];
614            for r in ranks {
615                bits[r as usize] = true;
616            }
617            Members::Bitmap(bits)
618        }
619    }
620
621    /// The live count; `None` with one member.
622    #[must_use]
623    pub fn live(&self) -> Option<u64> {
624        match self {
625            Members::One { .. } => None,
626            Members::Bitmap(b) => Some(b.len() as u64),
627            Members::List { live, .. } => Some(*live),
628        }
629    }
630
631    /// The ranks vouched for, ascending; `[0]` for one member vouched for.
632    #[must_use]
633    pub fn vouched(&self) -> Vec<u64> {
634        match self {
635            Members::One { vouched } => {
636                if *vouched {
637                    vec![0]
638                } else {
639                    vec![]
640                }
641            }
642            Members::Bitmap(b) => (0..b.len() as u64).filter(|i| b[*i as usize]).collect(),
643            Members::List { ranks, .. } => ranks.clone(),
644        }
645    }
646
647    /// `bitmap` or `list` for a templated collection, as the fixtures
648    /// name the form read; `None` with one member.
649    #[must_use]
650    pub fn form(&self) -> Option<&'static str> {
651        match self {
652            Members::One { .. } => None,
653            Members::Bitmap(_) => Some("bitmap"),
654            Members::List { .. } => Some("list"),
655        }
656    }
657}
658
659/// One collection's section.
660#[derive(Debug, Clone, PartialEq, Eq, Hash)]
661pub struct Section {
662    pub digest: Digest,
663    pub members: Members,
664}
665
666/// A heartbeat's body, read: its time, and a section for each collection
667/// whose map bit is set (`None` where it is 0), in map order.
668#[derive(Debug, Clone, PartialEq, Eq, Hash)]
669pub struct Heartbeat {
670    pub time: Time,
671    pub sections: Vec<Option<Section>>,
672}
673
674/// A put on a heartbeat's key or an owner heartbeat's that is not form 6
675/// (core §7.5, "Another form on a heartbeat's key"): a mutation's or a
676/// frame's envelope, which the parse accepts on a `stream` key. It is no
677/// heartbeat and no owner heartbeat, and it confirms nothing. A put with
678/// no envelope on either key is refused the same way, which is its
679/// caller's to say: there is no [`Envelope`] to give [`body_of`].
680#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Error)]
681#[error("form: a {0} on a heartbeat's key, which carries form 6 and no other")]
682pub struct FormRefusal(pub Form);
683
684impl FormRefusal {
685    /// The token `spec/conformance/heartbeat/owner.json`'s `forms` pins:
686    /// what every reader names such a put by, one with no envelope too.
687    pub const TOKEN: &'static str = "form";
688
689    /// [`FormRefusal::TOKEN`].
690    #[must_use]
691    pub const fn token(self) -> &'static str {
692        Self::TOKEN
693    }
694}
695
696/// CH's tag and the body of a put on a heartbeat's key or an owner
697/// heartbeat's, or the refusal of a put of another form (core §7.5): the
698/// first step of both readings, before the tag is compared and before a
699/// bit of the body is read. A mutation whose tag is 0 would otherwise
700/// pass an owner heartbeat's checks, its record read as a body.
701///
702/// # Errors
703/// The [`FormRefusal`], naming the form the envelope carries.
704pub fn body_of<'a>(env: &Envelope<'a>) -> Result<(Tag, &'a [u8]), FormRefusal> {
705    if env.form == Form::Heartbeat {
706        Ok((env.tag, env.record))
707    } else {
708        Err(FormRefusal(env.form))
709    }
710}
711
712/// Why a body is not a heartbeat of its layout, in core §7.5's order.
713#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Error)]
714pub enum BodyRefusal {
715    /// The body ends before a bit its fields need.
716    #[error("short: the body ends before a bit its fields need")]
717    Short,
718    /// A code is unused: an unused millisecond code ([`Time::from_code`]),
719    /// a live count above the cardinality, a count above the live count,
720    /// or a rank not below the live count or not above the one before it.
721    #[error("code: an unused code")]
722    Code,
723    /// A byte after the pad.
724    #[error("trailing: a byte after the pad")]
725    Trailing,
726    /// A bit of the pad is 1.
727    #[error("pad: a bit of the pad is 1")]
728    Pad,
729}
730
731impl BodyRefusal {
732    /// The token `spec/conformance/heartbeat/bodies.json` pins.
733    #[must_use]
734    pub const fn token(self) -> &'static str {
735        match self {
736            BodyRefusal::Short => "short",
737            BodyRefusal::Code => "code",
738            BodyRefusal::Trailing => "trailing",
739            BodyRefusal::Pad => "pad",
740        }
741    }
742}
743
744/// Why a heartbeat value cannot be written under a layout.
745#[derive(Debug, Clone, PartialEq, Eq, Error)]
746pub enum WriteError {
747    #[error("{have} sections for {need} collections")]
748    Sections { need: usize, have: usize },
749    #[error("collection {0}: members of the wrong shape for its template")]
750    Shape(usize),
751    #[error("collection {0}: a live count above its cardinality")]
752    Live(usize),
753    #[error("collection {0}: ranks not ascending below the live count")]
754    Ranks(usize),
755}
756
757/// Bits read in order, `short` where they end: a whole body's, or the
758/// bits of one group's sections, which end where its size says and not at
759/// a byte.
760struct Bits<'a> {
761    r: BitReader<'a>,
762    left: u64,
763}
764
765impl<'a> Bits<'a> {
766    /// Every bit of `bytes`.
767    fn whole(bytes: &'a [u8]) -> Self {
768        Bits {
769            r: BitReader::new(bytes),
770            left: bytes.len() as u64 * 8,
771        }
772    }
773
774    /// A record's bits, its pad left out.
775    fn of(record: &'a Record) -> Self {
776        Bits {
777            r: BitReader::new(&record.bytes),
778            left: record.bits.min(record.bytes.len() as u64 * 8),
779        }
780    }
781
782    fn take(&mut self, width: u32) -> Result<u64, BodyRefusal> {
783        if u64::from(width) > self.left {
784            return Err(BodyRefusal::Short);
785        }
786        self.left -= u64::from(width);
787        self.r.take(width).map_err(|_| BodyRefusal::Short)
788    }
789
790    /// The whole body's end: no byte after its pad, then every pad bit 0.
791    fn end(self) -> Result<(), BodyRefusal> {
792        self.r.end().map_err(|e| match e {
793            ReadRefusal::Pad => BodyRefusal::Pad,
794            _ => BodyRefusal::Trailing,
795        })
796    }
797}
798
799/// A body's map and sections under `layout`, field by field: what a
800/// heartbeat's body holds between its time and its pad, and what a
801/// group's sections are.
802fn read_sections(r: &mut Bits<'_>, layout: &Layout) -> Result<Vec<Option<Section>>, BodyRefusal> {
803    let mut map = Vec::with_capacity(layout.collections.len());
804    for _ in &layout.collections {
805        map.push(r.take(1)? == 1);
806    }
807    let mut sections = Vec::with_capacity(map.len());
808    for (c, on) in layout.collections.iter().zip(map) {
809        if !on {
810            sections.push(None);
811            continue;
812        }
813        let digest = Digest(r.take(32)? as u32);
814        let members = match (c.cardinality, c.live_bits()) {
815            (Some(card), Some(w)) => {
816                let live = r.take(w)?;
817                if live > card {
818                    return Err(BodyRefusal::Code);
819                }
820                if r.take(1)? == 0 {
821                    let mut bits = Vec::new();
822                    for _ in 0..live {
823                        bits.push(r.take(1)? == 1);
824                    }
825                    Members::Bitmap(bits)
826                } else {
827                    let count = r.take(bits_for(u128::from(live) + 1))?;
828                    if count > live {
829                        return Err(BodyRefusal::Code);
830                    }
831                    let rw = bits_for(u128::from(live));
832                    let mut ranks: Vec<u64> = Vec::new();
833                    for _ in 0..count {
834                        let rank = r.take(rw)?;
835                        if rank >= live || ranks.last().is_some_and(|p| rank <= *p) {
836                            return Err(BodyRefusal::Code);
837                        }
838                        ranks.push(rank);
839                    }
840                    Members::List { live, ranks }
841                }
842            }
843            _ => Members::One {
844                vouched: r.take(1)? == 1,
845            },
846        };
847        sections.push(Some(Section { digest, members }));
848    }
849    Ok(sections)
850}
851
852/// The map and sections under `layout`, written: [`read_sections`]'s
853/// inverse.
854fn write_sections(
855    w: &mut BitWriter,
856    layout: &Layout,
857    sections: &[Option<Section>],
858) -> Result<(), WriteError> {
859    if sections.len() != layout.collections.len() {
860        return Err(WriteError::Sections {
861            need: layout.collections.len(),
862            have: sections.len(),
863        });
864    }
865    for s in sections {
866        w.bit(s.is_some());
867    }
868    for (i, (c, s)) in layout.collections.iter().zip(sections).enumerate() {
869        let Some(s) = s else { continue };
870        w.push(u64::from(s.digest.0), 32);
871        match (&s.members, c.cardinality, c.live_bits()) {
872            (Members::One { vouched }, None, _) => w.bit(*vouched),
873            (Members::Bitmap(bits), Some(card), Some(lw)) => {
874                let live = bits.len() as u64;
875                if live > card {
876                    return Err(WriteError::Live(i));
877                }
878                w.push(live, lw);
879                w.bit(false);
880                for b in bits {
881                    w.bit(*b);
882                }
883            }
884            (Members::List { live, ranks }, Some(card), Some(lw)) => {
885                if *live > card {
886                    return Err(WriteError::Live(i));
887                }
888                if ranks.windows(2).any(|p| p[0] >= p[1]) || ranks.iter().any(|r| r >= live) {
889                    return Err(WriteError::Ranks(i));
890                }
891                w.push(*live, lw);
892                w.bit(true);
893                w.push(ranks.len() as u64, bits_for(u128::from(*live) + 1));
894                let rw = bits_for(u128::from(*live));
895                for r in ranks {
896                    w.push(*r, rw);
897                }
898            }
899            _ => return Err(WriteError::Shape(i)),
900        }
901    }
902    Ok(())
903}
904
905impl Heartbeat {
906    /// A body read with its covered revision's layout, or the first
907    /// refusal that applies (core §7.5): the fields in order (`short`,
908    /// `code`), then a byte after the pad (`trailing`), then a pad bit set
909    /// (`pad`). CH's tag is the caller's to compare with
910    /// [`Layout::tag`].
911    ///
912    /// # Errors
913    /// The [`BodyRefusal`].
914    pub fn parse(body: &[u8], layout: &Layout) -> Result<Heartbeat, BodyRefusal> {
915        let mut r = Bits::whole(body);
916        let time = Time::from_code(r.take(TIME_BITS)?)?;
917        let sections = read_sections(&mut r, layout)?;
918        r.end()?;
919        Ok(Heartbeat { time, sections })
920    }
921
922    /// The body's bits and pad under `layout` ([`crate::packed::Record`]).
923    ///
924    /// # Errors
925    /// A [`WriteError`]: a section per collection, each of its
926    /// collection's shape, a live count within the cardinality, and ranks
927    /// ascending below it.
928    pub fn record(&self, layout: &Layout) -> Result<crate::packed::Record, WriteError> {
929        let mut w = BitWriter::new();
930        w.push(self.time.code(), TIME_BITS);
931        write_sections(&mut w, layout, &self.sections)?;
932        Ok(w.finish())
933    }
934
935    /// The body's bytes under `layout`, its pad included.
936    ///
937    /// # Errors
938    /// As [`Heartbeat::record`].
939    pub fn write(&self, layout: &Layout) -> Result<Vec<u8>, WriteError> {
940        self.record(layout).map(|r| r.bytes)
941    }
942
943    /// The heartbeat as a put's payload: CH (form 6, the run's width, the
944    /// layout's tag), the stamp, then the body.
945    ///
946    /// # Errors
947    /// As [`Heartbeat::record`].
948    pub fn envelope(&self, layout: &Layout, stamp: Stamp) -> Result<Vec<u8>, WriteError> {
949        let body = self.write(layout)?;
950        Ok(wire::Envelope {
951            form: wire::Form::Heartbeat,
952            tag: layout.tag,
953            stamp,
954            record: &body,
955        }
956        .write())
957    }
958}
959
960/// The width of an owner heartbeat's count of groups.
961pub const GROUPS_BITS: u32 = 4;
962
963/// The most groups an owner heartbeat holds: its count is 4 bits, and 0 is
964/// unused.
965pub const MAX_GROUPS: usize = 15;
966
967/// The width of a group's index: a deployment catalog holds at most 1,024
968/// entries (core §8.6).
969pub const INDEX_BITS: u32 = 10;
970
971/// The highest index a group names.
972pub const MAX_INDEX: u16 = (1 << INDEX_BITS) - 1;
973
974/// The bits of a collection's longest section (core §7.5): a digest and a
975/// vouched bit for one member (`None`), 33 bits; for a templated one of
976/// cardinality c, the digest, the live count, `sel` and the bitmap with
977/// every member live, 33 + ⌈log₂(c + 1)⌉ + c. The bitmap is the longer
978/// form: a writer writes the list only where it is shorter.
979#[must_use]
980pub fn longest_section_bits(cardinality: Option<u64>) -> u128 {
981    match cardinality {
982        None => 33,
983        Some(c) => 33 + u128::from(bits_for(u128::from(c) + 1)) + u128::from(c),
984    }
985}
986
987/// The bits of a group's size, core §7.5's integer over the `bits` after
988/// it: unsigned LEB128, 8 bits below 128, 16 below 16,384, and so on.
989#[must_use]
990pub fn size_bits(bits: u128) -> u128 {
991    let mut bytes = 1;
992    let mut rest = bits >> 7;
993    while rest > 0 {
994        bytes += 1;
995        rest >>= 7;
996    }
997    bytes * 8
998}
999
1000/// One covered interface's part of an owner heartbeat (core §7.5): the
1001/// covered revision's index in the catalog its owner names, the tag the
1002/// owner wrote with, and the group's sections, unread. Their count of bits
1003/// is the group's size.
1004#[derive(Debug, Clone)]
1005pub struct Group {
1006    /// The covered revision's index in the deployment catalog, at most
1007    /// [`MAX_INDEX`].
1008    pub index: u16,
1009    /// The covered revision's tag, as a heartbeat's CH carries it.
1010    pub tag: Tag,
1011    /// The sections' bits: a map bit for each collection of the covered
1012    /// revision, then a section for each map bit set. A group has no pad
1013    /// of its own, so `sections.bits` is its size whatever the bytes hold
1014    /// after them.
1015    pub sections: Record,
1016}
1017
1018/// Two groups are equal when they write the same bits: their index, their
1019/// tag, their size, and the sections' bits the size counts. What a
1020/// [`Record`]'s bytes hold past `sections.bits` is no part of a group, so
1021/// it is no part of its equality.
1022impl PartialEq for Group {
1023    fn eq(&self, other: &Self) -> bool {
1024        self.index == other.index
1025            && self.tag == other.tag
1026            && self.sections.bits == other.sections.bits
1027            && counted(&self.sections) == counted(&other.sections)
1028    }
1029}
1030
1031impl Eq for Group {}
1032
1033/// The bytes a record's `bits` count, the last one's uncounted low bits
1034/// read as 0: every whole byte, then the counted bits of a partial one.
1035/// A record whose bytes end early gives what it has.
1036fn counted(r: &Record) -> (&[u8], Option<u8>) {
1037    let whole = usize::try_from(r.bits / 8)
1038        .unwrap_or(usize::MAX)
1039        .min(r.bytes.len());
1040    let rest = (r.bits % 8) as u32;
1041    let partial = (rest > 0)
1042        .then(|| r.bytes.get(whole).map(|b| b & (0xff << (8 - rest))))
1043        .flatten();
1044    (&r.bytes[..whole], partial)
1045}
1046
1047/// Why one group of an owner heartbeat is not read, in core §7.5's order.
1048/// It refuses that group alone: every other group reads as it would with
1049/// this one left out.
1050#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Error)]
1051pub enum GroupRefusal {
1052    /// The reader holds neither the catalog its owner names nor one whose
1053    /// lineage holds it, or the owner names none (core §8.6).
1054    #[error("unknown_catalog: no catalog held is or succeeds the one its owner names")]
1055    UnknownCatalog,
1056    /// The index is at or above the count it is read through (core §8.6).
1057    #[error("unknown_index: the index is at or above the count it is read through")]
1058    UnknownIndex,
1059    /// The sections end before a bit their fields need.
1060    #[error("short: the sections end before a bit their fields need")]
1061    Short,
1062    /// A code is unused: a live count above the cardinality, a count above
1063    /// the live count, or a rank not below the live count or not above the
1064    /// one before it.
1065    #[error("code: an unused code")]
1066    Code,
1067    /// A bit after the sections' last field.
1068    #[error("trailing: a bit after the sections' last field")]
1069    Trailing,
1070}
1071
1072impl GroupRefusal {
1073    /// The token `spec/conformance/heartbeat/owner.json` pins.
1074    #[must_use]
1075    pub const fn token(self) -> &'static str {
1076        match self {
1077            GroupRefusal::UnknownCatalog => "unknown_catalog",
1078            GroupRefusal::UnknownIndex => "unknown_index",
1079            GroupRefusal::Short => "short",
1080            GroupRefusal::Code => "code",
1081            GroupRefusal::Trailing => "trailing",
1082        }
1083    }
1084}
1085
1086impl From<catalog::ReadRefusal> for GroupRefusal {
1087    fn from(r: catalog::ReadRefusal) -> Self {
1088        match r {
1089            catalog::ReadRefusal::UnknownCatalog => GroupRefusal::UnknownCatalog,
1090            catalog::ReadRefusal::UnknownIndex => GroupRefusal::UnknownIndex,
1091        }
1092    }
1093}
1094
1095impl Group {
1096    /// A group covering `layout`'s revision at `index`: its tag the
1097    /// layout's, its sections these, one for each collection (`None` for a
1098    /// map bit of 0).
1099    ///
1100    /// # Errors
1101    /// A [`WriteError`], as [`Heartbeat::record`].
1102    pub fn of(
1103        index: u16,
1104        layout: &Layout,
1105        sections: &[Option<Section>],
1106    ) -> Result<Group, WriteError> {
1107        let mut w = BitWriter::new();
1108        write_sections(&mut w, layout, sections)?;
1109        Ok(Group {
1110            index,
1111            tag: layout.tag,
1112            sections: w.finish(),
1113        })
1114    }
1115
1116    /// The group's size: the count of bits in its sections.
1117    #[must_use]
1118    pub fn size(&self) -> u64 {
1119        self.sections.bits
1120    }
1121
1122    /// The revision the group's index names, read through the catalog its
1123    /// owner names among those the reader holds (core §8.6,
1124    /// [`catalog::through`]). A reader then reads the sections with that
1125    /// revision's layout ([`Group::read`]), or skips the group where it
1126    /// does not hold the revision.
1127    ///
1128    /// # Errors
1129    /// [`GroupRefusal::UnknownCatalog`] when the owner names no catalog,
1130    /// or no catalog held is or succeeds the one it names;
1131    /// [`GroupRefusal::UnknownIndex`] at or above the count read through.
1132    pub fn entry<'c>(
1133        &self,
1134        held: &'c [Catalog],
1135        named: Option<CatalogId>,
1136    ) -> Result<&'c catalog::Entry, GroupRefusal> {
1137        let named = named.ok_or(GroupRefusal::UnknownCatalog)?;
1138        Ok(catalog::through(held, named)?.entry(self.index)?)
1139    }
1140
1141    /// Whether the group's tag is `layout`'s. It is a check, as a
1142    /// heartbeat's is: another tag refuses nothing here, the sections read
1143    /// the same, and what a reader concludes is `freshness.v2`'s to say.
1144    #[must_use]
1145    pub fn tag_is(&self, layout: &Layout) -> bool {
1146        self.tag == layout.tag
1147    }
1148
1149    /// The group's sections read with its covered revision's layout, one
1150    /// for each collection (`None` for a map bit of 0), or the first
1151    /// refusal that applies (core §7.5): the fields in order (`short`,
1152    /// `code`), then a bit after the last field (`trailing`). The index is
1153    /// read first, by [`Group::entry`].
1154    ///
1155    /// # Errors
1156    /// [`GroupRefusal::Short`], [`GroupRefusal::Code`] or
1157    /// [`GroupRefusal::Trailing`].
1158    pub fn read(&self, layout: &Layout) -> Result<Vec<Option<Section>>, GroupRefusal> {
1159        let mut r = Bits::of(&self.sections);
1160        // The fields refuse `short` or `code` alone: a group's bits have no
1161        // pad, and what follows their last field is judged below.
1162        let sections = read_sections(&mut r, layout).map_err(|e| match e {
1163            BodyRefusal::Code => GroupRefusal::Code,
1164            _ => GroupRefusal::Short,
1165        })?;
1166        if r.left > 0 {
1167            return Err(GroupRefusal::Trailing);
1168        }
1169        Ok(sections)
1170    }
1171}
1172
1173/// An owner heartbeat's body, read without any contract: its time and its
1174/// groups, in ascending order of their indices.
1175#[derive(Debug, Clone, PartialEq, Eq)]
1176pub struct OwnerHeartbeat {
1177    /// The owner's time when it wrote the put, as a heartbeat's: from the
1178    /// deployment epoch, unknown or ahead: one time for every group.
1179    pub time: Time,
1180    /// Its groups, one for each interface it covers: from 1 to
1181    /// [`MAX_GROUPS`], in ascending order of their indices, none twice.
1182    pub groups: Vec<Group>,
1183}
1184
1185/// Why a put on an owner heartbeat's key is not an owner heartbeat, in
1186/// core §7.5's order. It refuses the whole put, every group with it.
1187#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Error)]
1188pub enum OwnerRefusal {
1189    /// The put is another form's than 6, a mutation's or a frame's
1190    /// ([`FormRefusal`]): refused before its tag or its body is read.
1191    #[error("form: a put of another form than a heartbeat's")]
1192    Form,
1193    /// CH's tag is not 0.
1194    #[error("tag: CH's tag is not 0")]
1195    Tag,
1196    /// The body ends before a bit its fields need, a size's or a group's
1197    /// sections' among them.
1198    #[error("short: the body ends before a bit its fields need")]
1199    Short,
1200    /// A code is unused: an unused millisecond code, as a heartbeat's
1201    /// ([`Time::from_code`]), or a count of 0 groups.
1202    #[error("code: an unused code")]
1203    Code,
1204    /// A group's index is not above the index of the group before it.
1205    #[error("order: a group's index is not above the one before it")]
1206    Order,
1207    /// A size's fifth byte has its high bit set, it is above 2^32 − 1, or
1208    /// it is not in its shortest form.
1209    #[error("leb128: a size that is not LEB128 in its shortest form, at most 2^32 − 1")]
1210    Leb128,
1211    /// A byte after the pad.
1212    #[error("trailing: a byte after the pad")]
1213    Trailing,
1214    /// A bit of the pad is 1.
1215    #[error("pad: a bit of the pad is 1")]
1216    Pad,
1217}
1218
1219impl OwnerRefusal {
1220    /// The token `spec/conformance/heartbeat/owner.json` pins.
1221    #[must_use]
1222    pub const fn token(self) -> &'static str {
1223        match self {
1224            OwnerRefusal::Form => FormRefusal::TOKEN,
1225            OwnerRefusal::Tag => "tag",
1226            OwnerRefusal::Short => "short",
1227            OwnerRefusal::Code => "code",
1228            OwnerRefusal::Order => "order",
1229            OwnerRefusal::Leb128 => "leb128",
1230            OwnerRefusal::Trailing => "trailing",
1231            OwnerRefusal::Pad => "pad",
1232        }
1233    }
1234}
1235
1236impl From<BodyRefusal> for OwnerRefusal {
1237    fn from(r: BodyRefusal) -> Self {
1238        match r {
1239            BodyRefusal::Short => OwnerRefusal::Short,
1240            BodyRefusal::Code => OwnerRefusal::Code,
1241            BodyRefusal::Trailing => OwnerRefusal::Trailing,
1242            BodyRefusal::Pad => OwnerRefusal::Pad,
1243        }
1244    }
1245}
1246
1247impl From<FormRefusal> for OwnerRefusal {
1248    fn from(_: FormRefusal) -> Self {
1249        OwnerRefusal::Form
1250    }
1251}
1252
1253/// Why an owner heartbeat cannot be written (core §7.5's writer's rule).
1254/// A group is named by its position.
1255#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
1256pub enum OwnerWriteError {
1257    /// No group, or more than [`MAX_GROUPS`].
1258    #[error("{0} groups: an owner heartbeat holds from 1 to 15")]
1259    Groups(usize),
1260    /// A group's index is above [`MAX_INDEX`].
1261    #[error("group {0}: an index above 1023")]
1262    Index(usize),
1263    /// A group's index is not above the index of the group before it.
1264    #[error("group {0}: its index is not above the one before it")]
1265    Order(usize),
1266    /// A group's sections are more bits than their bytes hold, or more
1267    /// than 2^32 − 1.
1268    #[error("group {0}: its sections are not a size's count of bits")]
1269    Size(usize),
1270}
1271
1272impl OwnerHeartbeat {
1273    /// A put on an owner heartbeat's key, after the envelope's parse
1274    /// accepted it: refused `form` where the envelope is another form's
1275    /// than 6, before its tag or its body is read (core §7.5), and
1276    /// otherwise [`OwnerHeartbeat::parse`]'s reading of its tag and body.
1277    ///
1278    /// # Errors
1279    /// The [`OwnerRefusal`], [`OwnerRefusal::Form`] first.
1280    pub fn of(env: &Envelope<'_>) -> Result<OwnerHeartbeat, OwnerRefusal> {
1281        let (tag, body) = body_of(env)?;
1282        OwnerHeartbeat::parse(tag, body)
1283    }
1284
1285    /// A form 6 put's body on an owner heartbeat's key, after the
1286    /// envelope's parse gave CH's `tag` and the stamp
1287    /// ([`OwnerHeartbeat::of`] takes the envelope, and refuses another
1288    /// form first): the groups read with no contract and no catalog, each
1289    /// one's sections taken unread, or the first refusal that applies
1290    /// (core §7.5): CH's tag not 0 (`tag`), then the fields in order, each
1291    /// read whole and then judged (`short`, `code`, `order`, `leb128`),
1292    /// then a byte after the pad (`trailing`), then a pad bit set (`pad`).
1293    ///
1294    /// The caller knows the key carries this layout. Nothing in a body
1295    /// tells the two apart: a heartbeat's can read as an owner heartbeat's,
1296    /// and the reverse. CH's tag does 15 times in 16, a heartbeat's being
1297    /// its covered revision's, and under tag 0 the body is read as its
1298    /// bits fall.
1299    ///
1300    /// # Errors
1301    /// The [`OwnerRefusal`], never [`OwnerRefusal::Form`].
1302    pub fn parse(tag: Tag, body: &[u8]) -> Result<OwnerHeartbeat, OwnerRefusal> {
1303        if tag != Tag::NONE {
1304            return Err(OwnerRefusal::Tag);
1305        }
1306        let mut r = Bits::whole(body);
1307        let time = Time::from_code(r.take(TIME_BITS)?)?;
1308        let count = r.take(GROUPS_BITS)?;
1309        if count == 0 {
1310            return Err(OwnerRefusal::Code);
1311        }
1312        let mut groups: Vec<Group> = Vec::with_capacity(count as usize);
1313        for _ in 0..count {
1314            let index = r.take(INDEX_BITS)? as u16;
1315            if groups.last().is_some_and(|g| index <= g.index) {
1316                return Err(OwnerRefusal::Order);
1317            }
1318            let tag = Tag::new(r.take(4)? as u8).expect("four bits are a tag");
1319            let size = read_integer(|| r.take(8).ok().map(|b| b as u8)).map_err(|e| match e {
1320                IntegerRefusal::Short => OwnerRefusal::Short,
1321                IntegerRefusal::Leb128 => OwnerRefusal::Leb128,
1322            })?;
1323            // Never allocated from the size: the bits are copied as the
1324            // body gives them, and it ends where it ends.
1325            let mut sections = BitWriter::new();
1326            let mut left = u64::from(size);
1327            while left > 0 {
1328                let n = left.min(64) as u32;
1329                sections.push(r.take(n)?, n);
1330                left -= u64::from(n);
1331            }
1332            groups.push(Group {
1333                index,
1334                tag,
1335                sections: sections.finish(),
1336            });
1337        }
1338        r.end()?;
1339        Ok(OwnerHeartbeat { time, groups })
1340    }
1341
1342    /// The group of an index, `None` where the owner heartbeat holds none:
1343    /// how a reader bound to one interface finds its own behind the
1344    /// others'.
1345    #[must_use]
1346    pub fn group(&self, index: u16) -> Option<&Group> {
1347        self.groups.iter().find(|g| g.index == index)
1348    }
1349
1350    /// The body's bits and pad ([`Record`]).
1351    ///
1352    /// # Errors
1353    /// An [`OwnerWriteError`]: from 1 to 15 groups, in ascending order of
1354    /// their indices, none above 1023, each one's size the count of bits
1355    /// in its sections.
1356    pub fn record(&self) -> Result<Record, OwnerWriteError> {
1357        if self.groups.is_empty() || self.groups.len() > MAX_GROUPS {
1358            return Err(OwnerWriteError::Groups(self.groups.len()));
1359        }
1360        let mut w = BitWriter::new();
1361        w.push(self.time.code(), TIME_BITS);
1362        w.push(self.groups.len() as u64, GROUPS_BITS);
1363        let mut size = Vec::with_capacity(5);
1364        for (i, g) in self.groups.iter().enumerate() {
1365            if g.index > MAX_INDEX {
1366                return Err(OwnerWriteError::Index(i));
1367            }
1368            if i > 0 && g.index <= self.groups[i - 1].index {
1369                return Err(OwnerWriteError::Order(i));
1370            }
1371            let bits = u32::try_from(g.sections.bits).map_err(|_| OwnerWriteError::Size(i))?;
1372            let mut r = Bits::of(&g.sections);
1373            if r.left != g.sections.bits {
1374                return Err(OwnerWriteError::Size(i));
1375            }
1376            w.push(u64::from(g.index), INDEX_BITS);
1377            w.push(u64::from(g.tag.get()), 4);
1378            size.clear();
1379            write_integer(&mut size, bits);
1380            for b in &size {
1381                w.push(u64::from(*b), 8);
1382            }
1383            while r.left > 0 {
1384                let n = r.left.min(64) as u32;
1385                let v = r.take(n).map_err(|_| OwnerWriteError::Size(i))?;
1386                w.push(v, n);
1387            }
1388        }
1389        Ok(w.finish())
1390    }
1391
1392    /// The body's bytes, its pad included.
1393    ///
1394    /// # Errors
1395    /// As [`OwnerHeartbeat::record`].
1396    pub fn write(&self) -> Result<Vec<u8>, OwnerWriteError> {
1397        self.record().map(|r| r.bytes)
1398    }
1399
1400    /// The owner heartbeat as a put's payload: CH (form 6, the run's
1401    /// width, tag 0), the stamp, then the body.
1402    ///
1403    /// # Errors
1404    /// As [`OwnerHeartbeat::record`].
1405    pub fn envelope(&self, stamp: Stamp) -> Result<Vec<u8>, OwnerWriteError> {
1406        let body = self.write()?;
1407        Ok(wire::Envelope {
1408            form: wire::Form::Heartbeat,
1409            tag: Tag::NONE,
1410            stamp,
1411            record: &body,
1412        }
1413        .write())
1414    }
1415}
1416
1417#[cfg(test)]
1418mod tests {
1419    use super::*;
1420    use crate::wire::Seq;
1421
1422    fn stamp(run: u16, seq: u32) -> Stamp {
1423        Stamp {
1424            run: Run::U16(run),
1425            seq: Seq::new(seq).unwrap(),
1426        }
1427    }
1428
1429    #[test]
1430    fn widths() {
1431        assert_eq!(bits_for(1), 0);
1432        assert_eq!(bits_for(2), 1);
1433        assert_eq!(bits_for(3), 2);
1434        assert_eq!(bits_for(6), 3);
1435        assert_eq!(bits_for(1 << 32), 32);
1436        assert_eq!(bits_for((1 << 32) + 1), 33);
1437    }
1438
1439    /// Core 0.113 §7.5: a time is an instant, unknown or ahead, and the
1440    /// ahead time is never read as either other. Every other millisecond
1441    /// code from 1000 up is unused, whatever the seconds.
1442    #[test]
1443    fn a_time_is_an_instant_unknown_or_ahead_and_every_other_code_unused() {
1444        let all = (1u64 << TIME_BITS) - 1;
1445        assert_eq!(Time::from_code(all), Ok(Time::Unknown));
1446        assert_eq!(Time::from_code(all - 1), Ok(Time::Ahead));
1447        assert_eq!(Time::Ahead.code(), 0x3ff_ffff_fffe);
1448        assert_eq!(Time::Ahead.code() & 0x3ff, 1022, "the millisecond code");
1449        assert_eq!(Time::Ahead.code() >> 10, u64::from(u32::MAX), "the seconds");
1450        assert_eq!(Time::Ahead.unix_ms(0), None, "no instant");
1451        assert!(Time::Ahead.is_ahead() && !Time::Ahead.is_instant());
1452        assert!(!Time::Unknown.is_ahead() && !Time::Unknown.is_instant());
1453        let last = Time::At {
1454            secs: u32::MAX,
1455            ms: 999,
1456        };
1457        assert_eq!(Time::from_code(last.code()), Ok(last), "a known time");
1458        assert!(last.is_instant());
1459        for secs in [0u64, 3600, u64::from(u32::MAX) - 1, u64::from(u32::MAX)] {
1460            for ms in 1000u64..1024 {
1461                let code = (secs << 10) | ms;
1462                let got = Time::from_code(code);
1463                match code {
1464                    c if c == all => assert_eq!(got, Ok(Time::Unknown)),
1465                    c if c == all - 1 => assert_eq!(got, Ok(Time::Ahead)),
1466                    _ => assert_eq!(got, Err(BodyRefusal::Code), "{secs} s, {ms} ms"),
1467                }
1468            }
1469        }
1470    }
1471
1472    /// `freshness.v2` §2.10: while its guard holds an owner writes the
1473    /// ahead time whatever its clock reads, an instant the epoch does not
1474    /// code and no instant at all among them; §2.4 otherwise.
1475    #[test]
1476    fn an_owner_writes_ahead_while_its_guard_holds_whatever_its_clock_reads() {
1477        let e = 1_767_225_600;
1478        let at = 1_794_062_761_123;
1479        assert_eq!(Time::written(true, Some(at), e), Time::Ahead);
1480        assert_eq!(Time::written(true, Some(6_062_192_896_000), e), Time::Ahead);
1481        assert_eq!(Time::written(true, None, e), Time::Ahead);
1482        assert_eq!(
1483            Time::written(false, Some(at), e),
1484            Time::At {
1485                secs: 26_837_161,
1486                ms: 123
1487            }
1488        );
1489        assert_eq!(Time::written(false, None, e), Time::Unknown);
1490        assert_eq!(Time::written(false, Some(0), e), Time::Unknown);
1491    }
1492
1493    #[test]
1494    fn the_writer_writes_the_list_only_where_it_is_shorter() {
1495        assert!(matches!(Members::templated(3, [0, 2]), Members::Bitmap(_)));
1496        assert!(matches!(Members::templated(5, []), Members::List { .. }));
1497        // A tie keeps the bitmap: 1 bit against 1 + 0.
1498        assert!(matches!(Members::templated(1, [0]), Members::Bitmap(_)));
1499        assert_eq!(Members::templated(40, [17, 17, 99]).vouched(), vec![17]);
1500    }
1501
1502    #[test]
1503    fn the_digest_is_free_of_order_and_toggles() {
1504        let a = ("zk2/s/v/i.v1/state/p/a", stamp(1, 1));
1505        let b = ("zk2/s/v/i.v1/state/p/b", stamp(1, 2));
1506        assert_eq!(Digest::of([a, b]), Digest::of([b, a]));
1507        let mut d = Digest::of([a, b]);
1508        d.toggle(b.0, b.1);
1509        assert_eq!(d, Digest::of([a]));
1510        d.toggle(a.0, a.1);
1511        assert_eq!(d, Digest::EMPTY);
1512    }
1513
1514    #[test]
1515    fn a_heartbeat_key_names_its_covered_interface() {
1516        let iface = IfaceId::new("modem", 3).unwrap();
1517        let k = key("h-1", "rf0", &iface);
1518        assert_eq!(k, "zk2/h-1/rf0/freshness.v2/stream/heartbeat/modem.v3");
1519        let (addr, got) = covered(&k).unwrap();
1520        assert_eq!(
1521            (addr.to_string(), got),
1522            ("h-1/rf0".to_owned(), iface.clone())
1523        );
1524        assert_eq!(covered(&format!("prod/{k}")).map(|c| c.1), Some(iface));
1525        assert_eq!(covered("zk2/h/s/health.v1/stream/heartbeat/x.v1"), None);
1526        assert_eq!(covered("zk2/h/s/freshness.v2/state/heartbeat/x.v1"), None);
1527        assert_eq!(covered("demo/tick"), None);
1528    }
1529
1530    /// A string of `0` and `1` as a record's bits.
1531    fn bits(s: &str) -> Record {
1532        let mut w = BitWriter::new();
1533        for c in s.chars() {
1534            w.bit(c == '1');
1535        }
1536        w.finish()
1537    }
1538
1539    fn group(index: u16, sections: &str) -> Group {
1540        Group {
1541            index,
1542            tag: Tag::new((index % 16) as u8).unwrap(),
1543            sections: bits(sections),
1544        }
1545    }
1546
1547    fn owner(groups: Vec<Group>) -> OwnerHeartbeat {
1548        OwnerHeartbeat {
1549            time: Time::At {
1550                secs: 3600,
1551                ms: 250,
1552            },
1553            groups,
1554        }
1555    }
1556
1557    /// A revision with a templated collection of at most 5 and a
1558    /// collection of one member.
1559    fn layout() -> Layout {
1560        let text = r#"
1561[interface]
1562name  = "pair"
1563major = 1
1564minor = 0
1565uses  = ["freshness.v2"]
1566
1567[resources."peer/{peer}"]
1568kind        = "state"
1569type        = { raw = "text/plain" }
1570params      = { peer = "string" }
1571cardinality = 5
1572annotations = { "freshness.ttl_s" = 60 }
1573
1574[resources.status]
1575kind        = "state"
1576type        = { raw = "text/plain" }
1577annotations = { "freshness.ttl_s" = 60 }
1578"#;
1579        let loaded = crate::contract::load_str(text, std::path::Path::new("."), None);
1580        Layout::of(&loaded.contract.expect("the contract loads"))
1581    }
1582
1583    #[test]
1584    fn an_owner_heartbeat_holds_from_1_to_15_groups() {
1585        assert_eq!(owner(vec![]).record(), Err(OwnerWriteError::Groups(0)));
1586        let many = |n: u16| owner((0..n).map(|i| group(i, "1")).collect());
1587        assert!(many(1).record().is_ok());
1588        assert!(many(15).record().is_ok());
1589        assert_eq!(many(16).record(), Err(OwnerWriteError::Groups(16)));
1590        assert_eq!(
1591            many(16).envelope(stamp(7, 1)),
1592            Err(OwnerWriteError::Groups(16))
1593        );
1594    }
1595
1596    #[test]
1597    fn a_writer_refuses_indices_that_do_not_ascend() {
1598        let of = |indices: &[u16]| owner(indices.iter().map(|i| group(*i, "10")).collect());
1599        assert!(of(&[0, 2, 1023]).record().is_ok());
1600        // Descending, and the same index twice: the group at fault named
1601        // by its position.
1602        assert_eq!(of(&[4, 2]).record(), Err(OwnerWriteError::Order(1)));
1603        assert_eq!(of(&[2, 4, 4]).record(), Err(OwnerWriteError::Order(2)));
1604        assert_eq!(of(&[0, 9, 3, 12]).record(), Err(OwnerWriteError::Order(2)));
1605        // An index 10 bits cannot hold is refused, never written modulo
1606        // 1,024.
1607        assert_eq!(of(&[1024]).record(), Err(OwnerWriteError::Index(0)));
1608        assert_eq!(of(&[5, 2000]).record(), Err(OwnerWriteError::Index(1)));
1609    }
1610
1611    #[test]
1612    fn a_writer_refuses_sections_that_are_not_their_bytes_bits() {
1613        let mut g = group(3, "1011");
1614        g.sections.bits = 9;
1615        assert_eq!(owner(vec![g]).record(), Err(OwnerWriteError::Size(0)));
1616        // Bits set after the sections' count are no part of the group.
1617        let mut g = group(3, "1011");
1618        g.sections.bytes[0] |= 0x0f;
1619        let written = owner(vec![g]).write().unwrap();
1620        assert_eq!(written, owner(vec![group(3, "1011")]).write().unwrap());
1621    }
1622
1623    #[test]
1624    fn a_size_is_the_sections_count_of_bits_wherever_it_falls() {
1625        // 46 bits of time and count, 14 of index and tag: the size starts
1626        // at bit 60, on no byte boundary.
1627        let body = owner(vec![group(4, &"1".repeat(128))]).write().unwrap();
1628        // 128 is 0x80 0x01, the low seven bits first.
1629        assert_eq!(body[7] & 0x0f, 0x8);
1630        assert_eq!(body[8], 0x00);
1631        assert_eq!(body[9] >> 4, 0x1);
1632        let read = OwnerHeartbeat::parse(Tag::NONE, &body).unwrap();
1633        assert_eq!(read.groups[0].size(), 128);
1634        assert_eq!(read.group(4), Some(&group(4, &"1".repeat(128))));
1635        assert_eq!(read.group(5), None);
1636    }
1637
1638    /// A xorshift generator: the same owner heartbeats on every run.
1639    struct Rng(u64);
1640
1641    impl Rng {
1642        fn next(&mut self) -> u64 {
1643            self.0 ^= self.0 << 13;
1644            self.0 ^= self.0 >> 7;
1645            self.0 ^= self.0 << 17;
1646            self.0
1647        }
1648
1649        fn below(&mut self, n: u64) -> u64 {
1650            self.next() % n
1651        }
1652    }
1653
1654    /// link.v2 §2.16 counts an owner heartbeat's longest put by
1655    /// [`longest_section_bits`] and [`size_bits`]: the writer's own bits,
1656    /// with every member live and vouched for.
1657    #[test]
1658    fn the_longest_section_and_the_size_are_the_writers() {
1659        let c = crate::contract::load_str(
1660            r#"
1661[interface]
1662name = "mixed"
1663major = 1
1664minor = 0
1665uses = ["freshness.v2", "link.v1"]
1666[resources."peer/{peer}"]
1667kind = "state"
1668type = { raw = "text/plain" }
1669params = { peer = "string" }
1670cardinality = 200
1671annotations = { "freshness.ttl_s" = 120, "link.exposure" = "link" }
1672[resources.status]
1673kind = "state"
1674type = { raw = "text/plain" }
1675annotations = { "freshness.ttl_s" = 60 }
1676"#,
1677            std::path::Path::new("."),
1678            None,
1679        )
1680        .contract
1681        .unwrap();
1682        let l = Layout::of(&c);
1683        assert_eq!(
1684            l.collections.iter().map(|c| c.class).collect::<Vec<_>>(),
1685            vec![Class::Link, Class::Host]
1686        );
1687        let peers = Section {
1688            digest: Digest::EMPTY,
1689            members: Members::templated(200, 0..200),
1690        };
1691        assert!(matches!(peers.members, Members::Bitmap(_)));
1692        let one = Section {
1693            digest: Digest::EMPTY,
1694            members: Members::One { vouched: true },
1695        };
1696        // A `link` group: both map bits, and the `link` collection's section.
1697        let g = Group::of(7, &l, &[Some(peers.clone()), None]).unwrap();
1698        assert_eq!(longest_section_bits(Some(200)), 33 + 8 + 200);
1699        assert_eq!(u128::from(g.size()), 2 + longest_section_bits(Some(200)));
1700        // One member's section.
1701        let h = Group::of(7, &l, &[None, Some(one)]).unwrap();
1702        assert_eq!(u128::from(h.size()), 2 + longest_section_bits(None));
1703        // The size's own bits, as the body holds them.
1704        let body = OwnerHeartbeat {
1705            time: Time::Unknown,
1706            groups: vec![g.clone()],
1707        }
1708        .record()
1709        .unwrap();
1710        let after = u128::from(g.size());
1711        assert_eq!(size_bits(after), 16, "243 bits take two bytes");
1712        assert_eq!(u128::from(body.bits), 46 + 14 + size_bits(after) + after);
1713        for n in [
1714            0u32,
1715            1,
1716            127,
1717            128,
1718            16_383,
1719            16_384,
1720            (1 << 21) - 1,
1721            1 << 21,
1722            u32::MAX,
1723        ] {
1724            assert_eq!(
1725                size_bits(u128::from(n)),
1726                8 * crate::collection::integer_bytes(n) as u128,
1727                "{n}"
1728            );
1729        }
1730        // Past what a size can state, the count still grows.
1731        assert_eq!(size_bits(1 << 35), 48);
1732    }
1733
1734    /// A group's equality reads the bits its size counts, as its writer
1735    /// does: bits past them in the record's bytes are not the group's.
1736    #[test]
1737    fn two_groups_that_write_the_same_bits_are_equal() {
1738        let tag = Tag::new(5).unwrap();
1739        let group = |bytes: &[u8], bits: u64| Group {
1740            index: 3,
1741            tag,
1742            sections: Record {
1743                bytes: bytes.to_vec(),
1744                bits,
1745            },
1746        };
1747        // 11 bits: a whole byte and the top three of the next.
1748        let a = group(&[0b1010_1010, 0b1010_0000], 11);
1749        let stray = group(&[0b1010_1010, 0b1011_1111], 11);
1750        let longer = group(&[0b1010_1010, 0b1010_0000, 0xff], 11);
1751        assert_eq!(a, stray, "bits past the size, in the last counted byte");
1752        assert_eq!(a, longer, "a byte past the size");
1753        let write = |g: &Group| {
1754            OwnerHeartbeat {
1755                time: Time::Unknown,
1756                groups: vec![g.clone()],
1757            }
1758            .write()
1759            .unwrap()
1760        };
1761        assert_eq!(write(&a), write(&stray));
1762        assert_eq!(write(&a), write(&longer));
1763        // A counted bit, the size, the index and the tag each tell two apart.
1764        assert_ne!(a, group(&[0b1010_1010, 0b1000_0000], 11));
1765        assert_ne!(a, group(&[0b0010_1010, 0b1010_0000], 11));
1766        assert_ne!(a, group(&[0b1010_1010, 0b1010_0000], 12));
1767        assert_ne!(a, group(&[0b1010_1010, 0b1010_0000], 8));
1768        assert_ne!(
1769            a,
1770            Group {
1771                index: 4,
1772                ..a.clone()
1773            }
1774        );
1775        assert_ne!(
1776            a,
1777            Group {
1778                tag: Tag::new(6).unwrap(),
1779                ..a.clone()
1780            }
1781        );
1782        // Whole bytes alone, and no bits at all.
1783        assert_eq!(group(&[7, 9], 8), group(&[7], 8));
1784        assert_eq!(group(&[], 0), group(&[0xff], 0));
1785        // The equality an owner heartbeat's rests on.
1786        let hb = |g: &Group| OwnerHeartbeat {
1787            time: Time::Unknown,
1788            groups: vec![g.clone()],
1789        };
1790        assert_eq!(hb(&a), hb(&stray));
1791    }
1792
1793    #[test]
1794    fn every_owner_heartbeat_written_reads_back_and_no_prefix_of_it_does() {
1795        let mut rng = Rng(0x1110_0108_2026_1121);
1796        for round in 0..300 {
1797            let count = 1 + rng.below(15);
1798            let mut indices: Vec<u16> = (0..count).map(|_| rng.below(1024) as u16).collect();
1799            indices.sort_unstable();
1800            indices.dedup();
1801            let groups: Vec<Group> = indices
1802                .iter()
1803                .map(|i| {
1804                    // Sizes on both sides of each LEB128 length: 0, 127,
1805                    // 128 and 16,384 among them.
1806                    let len = match rng.below(8) {
1807                        0 => 0,
1808                        1 => 127 + rng.below(3),
1809                        2 => 16_383 + rng.below(3),
1810                        _ => rng.below(200),
1811                    };
1812                    let s: String = (0..len)
1813                        .map(|_| if rng.below(2) == 1 { '1' } else { '0' })
1814                        .collect();
1815                    Group {
1816                        index: *i,
1817                        tag: Tag::new(rng.below(16) as u8).unwrap(),
1818                        sections: bits(&s),
1819                    }
1820                })
1821                .collect();
1822            let time = if rng.below(10) == 0 {
1823                Time::Unknown
1824            } else {
1825                Time::At {
1826                    secs: rng.next() as u32,
1827                    ms: rng.below(1000) as u16,
1828                }
1829            };
1830            let hb = OwnerHeartbeat { time, groups };
1831            let record = hb.record().unwrap();
1832            let expected: u64 = 46
1833                + hb.groups
1834                    .iter()
1835                    .map(|g| {
1836                        let size = crate::collection::integer_bytes(g.size() as u32) as u64;
1837                        14 + 8 * size + g.size()
1838                    })
1839                    .sum::<u64>();
1840            assert_eq!(record.bits, expected, "round {round}: the body's bits");
1841            assert!(record.pad() < 8);
1842            assert_eq!(
1843                OwnerHeartbeat::parse(Tag::NONE, &record.bytes),
1844                Ok(hb.clone()),
1845                "round {round}: reads back"
1846            );
1847            assert_eq!(
1848                OwnerHeartbeat::parse(Tag::new(1).unwrap(), &record.bytes),
1849                Err(OwnerRefusal::Tag)
1850            );
1851            // A body cut anywhere lacks a bit a field needs: the pad is
1852            // under a byte, so the last byte holds one.
1853            for cut in [0, 1, 5, 6, record.bytes.len() / 2, record.bytes.len() - 1] {
1854                assert_eq!(
1855                    OwnerHeartbeat::parse(Tag::NONE, &record.bytes[..cut]),
1856                    Err(OwnerRefusal::Short),
1857                    "round {round}: cut at {cut}"
1858                );
1859            }
1860            let payload = hb.envelope(stamp(7, round)).unwrap();
1861            let env = wire::Envelope::parse(&payload).unwrap();
1862            assert!(env.is_heartbeat());
1863            assert_eq!((env.tag, env.stamp), (Tag::NONE, stamp(7, round)));
1864            assert_eq!(OwnerHeartbeat::parse(env.tag, env.record), Ok(hb.clone()));
1865            assert_eq!(OwnerHeartbeat::of(&env), Ok(hb));
1866        }
1867    }
1868
1869    /// Core §7.5, "Another form on a heartbeat's key": a mutation or a
1870    /// frame under tag 0 whose record is an owner heartbeat's body would
1871    /// read as one, so its form refuses it first, on either key.
1872    #[test]
1873    fn another_form_on_a_heartbeats_key_is_refused_before_its_tag_and_body() {
1874        let hb = OwnerHeartbeat {
1875            time: Time::Unknown,
1876            groups: vec![Group {
1877                index: 3,
1878                tag: Tag::new(9).unwrap(),
1879                sections: BitWriter::new().finish(),
1880            }],
1881        };
1882        let body = hb.write().unwrap();
1883        let at = stamp(7, 1);
1884        for (env, form) in [
1885            (Envelope::mutation(Tag::NONE, at, &body), Form::Mutation),
1886            (Envelope::frame(Tag::NONE, at, &body), Form::Frame),
1887            // Before `tag`, and before `short`.
1888            (
1889                Envelope::mutation(Tag::new(8).unwrap(), at, &body),
1890                Form::Mutation,
1891            ),
1892            (Envelope::mutation(Tag::NONE, at, &[]), Form::Mutation),
1893        ] {
1894            assert_eq!(body_of(&env), Err(FormRefusal(form)));
1895            assert_eq!(FormRefusal(form).token(), "form");
1896            assert_eq!(OwnerHeartbeat::of(&env), Err(OwnerRefusal::Form));
1897            assert_eq!(OwnerRefusal::Form.token(), "form");
1898        }
1899        // Read past its form, the first would have been an owner heartbeat.
1900        assert_eq!(OwnerHeartbeat::parse(Tag::NONE, &body), Ok(hb.clone()));
1901        // The two keys that carry form 6 alone, a namespace in front or
1902        // none, and no other key of the profile or of any other.
1903        let alpha: IfaceId = "alpha.v1".parse().unwrap();
1904        for k in [
1905            key("lab", "trio", &alpha),
1906            owner_key("lab", "trio", Class::Host),
1907            format!("ns/{}", owner_key("lab", "trio", Class::Link)),
1908        ] {
1909            assert!(is_key(&k), "{k}");
1910        }
1911        for k in [
1912            "zk2/lab/trio/freshness.v2/stream/heartbeats/other",
1913            "zk2/lab/trio/alpha.v1/state/status",
1914            "zk2/lab/trio/freshness.v2/state/heartbeat/alpha.v1",
1915        ] {
1916            assert!(!is_key(k), "{k}");
1917        }
1918        // Form 6 passes the gate with its tag and body, in either layout.
1919        let payload = hb.envelope(at).unwrap();
1920        let env = Envelope::parse(&payload).unwrap();
1921        assert_eq!(body_of(&env), Ok((Tag::NONE, &body[..])));
1922        assert_eq!(OwnerHeartbeat::of(&env), Ok(hb));
1923    }
1924
1925    #[test]
1926    fn a_group_reads_and_writes_its_sections_by_its_revisions_layout() {
1927        let l = layout();
1928        let sections = vec![
1929            Some(Section {
1930                digest: Digest::from_u32(0xdead_beef),
1931                members: Members::templated(3, [0, 2]),
1932            }),
1933            Some(Section {
1934                digest: Digest::from_u32(0x0bad_cafe),
1935                members: Members::One { vouched: true },
1936            }),
1937        ];
1938        let g = Group::of(9, &l, &sections).unwrap();
1939        // The map's 2 bits; 32 + 3 + 1 + 3 for the bitmap; 32 + 1.
1940        assert_eq!(g.size(), 2 + 39 + 33);
1941        assert!(g.tag_is(&l));
1942        assert_eq!(g.read(&l), Ok(sections.clone()));
1943        // A heartbeat's body between its time and its pad is the same
1944        // bits.
1945        let body = Heartbeat {
1946            time: Time::Unknown,
1947            sections: sections.clone(),
1948        }
1949        .record(&l)
1950        .unwrap();
1951        assert_eq!(
1952            body.bit_string()[TIME_BITS as usize..],
1953            g.sections.bit_string()
1954        );
1955        // Every map bit 0 is the map alone, and a section the layout has
1956        // no collection for is the writer's refusal.
1957        let none = Group::of(9, &l, &[None, None]).unwrap();
1958        assert_eq!((none.size(), none.read(&l)), (2, Ok(vec![None, None])));
1959        assert_eq!(
1960            Group::of(9, &l, &sections[..1]),
1961            Err(WriteError::Sections { need: 2, have: 1 })
1962        );
1963    }
1964
1965    #[test]
1966    fn a_refused_group_leaves_the_others_read() {
1967        let l = layout();
1968        let one = [
1969            None,
1970            Some(Section {
1971                digest: Digest::from_u32(1),
1972                members: Members::One { vouched: true },
1973            }),
1974        ];
1975        let good = |index| Group::of(index, &l, &one).unwrap();
1976        let mut long = good(5);
1977        long.sections = bits(&(long.sections.bit_string() + "0"));
1978        let mut cut = good(6);
1979        cut.sections = bits(&cut.sections.bit_string()[..20]);
1980        // Six live where the cardinality is 5.
1981        let over = Group {
1982            index: 7,
1983            tag: l.tag,
1984            sections: bits(&format!("10{}110", "0".repeat(32))),
1985        };
1986        let hb = owner(vec![good(2), long, cut, over, good(8)]);
1987        let read = OwnerHeartbeat::parse(Tag::NONE, &hb.write().unwrap()).unwrap();
1988        let got: Vec<_> = read.groups.iter().map(|g| g.read(&l)).collect();
1989        assert_eq!(
1990            got,
1991            [
1992                Ok(one.to_vec()),
1993                Err(GroupRefusal::Trailing),
1994                Err(GroupRefusal::Short),
1995                Err(GroupRefusal::Code),
1996                Ok(one.to_vec()),
1997            ]
1998        );
1999    }
2000
2001    #[test]
2002    fn a_group_reads_its_index_through_the_catalog_its_owner_names() {
2003        let l = layout();
2004        let mut first = Catalog::new(1_767_225_600).unwrap();
2005        first.push(l.iface.clone(), l.fingerprint.clone()).unwrap();
2006        let named = Some(first.id());
2007        let held = [first];
2008        let g = Group::of(0, &l, &[None, None]).unwrap();
2009        let entry = g.entry(&held, named).unwrap();
2010        assert_eq!((&entry.iface, &entry.contract), (&l.iface, &l.fingerprint));
2011        let mut past = g.clone();
2012        past.index = 1;
2013        assert_eq!(past.entry(&held, named), Err(GroupRefusal::UnknownIndex));
2014        // No catalog named, none held, and another's id: never a guess.
2015        assert_eq!(g.entry(&held, None), Err(GroupRefusal::UnknownCatalog));
2016        assert_eq!(g.entry(&[], named), Err(GroupRefusal::UnknownCatalog));
2017        let other = CatalogId::from_hex("00000000");
2018        assert!(other.is_some());
2019        assert_eq!(g.entry(&held, other), Err(GroupRefusal::UnknownCatalog));
2020    }
2021}