Skip to main content

zenkey_model/
catalog.rs

1//! The deployment catalog (core §8.6; #980 C1a).
2//!
3//! A catalog is a file a deployment provisions to its owners and to the far
4//! side of a constrained face. It states the deployment epoch, which core
5//! §7.6's `time` fields count from, and gives each contract revision it
6//! lists an index, which a later form carries in place of the interface id
7//! and the fingerprint. It is never fetched and never served on the bus.
8//!
9//! - [`Catalog::parse`] is §8.6's reading, refusing a document for the first
10//!   [`Reason`] that applies, in the text's order.
11//! - [`Catalog::id`] is the first 4 bytes of the sha256 of its JCS bytes.
12//! - [`Catalog::succeeds`] is the succession checker, and
13//!   [`Catalog::successor`] with [`Catalog::push`] what `zk2 catalog add`
14//!   writes.
15//! - [`through`] and [`epoch_of`] are a reader's resolution: the catalog an
16//!   owner names, or a held one whose lineage holds it, below that item's
17//!   count.
18//!
19//! `spec/catalog.schema.json` is generated from [`Document`] (schemars). The
20//! reading states more than JSON Schema can: an index at its position, no
21//! pair twice, a lineage's counts. `spec/conformance/catalog/` pins it.
22
23use std::collections::BTreeSet;
24use std::fmt;
25use std::str::FromStr;
26
27use schemars::JsonSchema;
28use serde::{Deserialize, Serialize};
29use serde_json::{Map, Value};
30use sha2::{Digest, Sha256};
31
32use crate::canonical::Fingerprint;
33use crate::chunk::is_lower_hex;
34use crate::grammar::IfaceId;
35use crate::schema::jcs;
36
37/// The format tag of this version of the document.
38pub const FORMAT: &str = "zk2-catalog/1";
39
40/// At most this many entries: a later form carries an index in 10 bits.
41pub const MAX_ENTRIES: usize = 1024;
42
43/// The largest epoch: 2^53 − 1 seconds, an integer every JSON reader holds
44/// exactly.
45pub const MAX_EPOCH: i64 = (1 << 53) - 1;
46
47/// The deployment epoch where no catalog is in force (core §7.6, §8.6): 0,
48/// the Unix epoch, so a `time` field's 32 bits are Unix seconds.
49pub const EPOCH_WITHOUT_CATALOG: i64 = 0;
50
51/// A catalog's id: the first 4 bytes of the sha256 of its JCS bytes, spelled
52/// as 8 lowercase hex digits.
53#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
54pub struct CatalogId([u8; 4]);
55
56impl CatalogId {
57    /// The id of a document's JCS bytes.
58    #[must_use]
59    pub fn of_jcs(bytes: &[u8]) -> Self {
60        let d = Sha256::digest(bytes);
61        Self([d[0], d[1], d[2], d[3]])
62    }
63
64    /// Exactly 8 lowercase hex digits, as a descriptor's `catalog` and a
65    /// lineage item's `id` spell one; `None` otherwise.
66    #[must_use]
67    pub fn from_hex(s: &str) -> Option<Self> {
68        if !is_lower_hex(s, 8) {
69            return None;
70        }
71        let v = u32::from_str_radix(s, 16).ok()?;
72        Some(Self(v.to_be_bytes()))
73    }
74
75    /// The 8 lowercase hex digits.
76    #[must_use]
77    pub fn hex(self) -> String {
78        format!("{:08x}", u32::from_be_bytes(self.0))
79    }
80
81    /// The 4 bytes, as a later form carries them.
82    #[must_use]
83    pub fn bytes(self) -> [u8; 4] {
84        self.0
85    }
86}
87
88impl fmt::Display for CatalogId {
89    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90        f.write_str(&self.hex())
91    }
92}
93
94impl FromStr for CatalogId {
95    type Err = String;
96    fn from_str(s: &str) -> Result<Self, String> {
97        Self::from_hex(s).ok_or_else(|| format!("{s:?} is not 8 lowercase hex digits"))
98    }
99}
100
101/// One contract revision a catalog lists, at its index.
102#[derive(Debug, Clone, PartialEq, Eq, Hash)]
103pub struct Entry {
104    pub iface: IfaceId,
105    pub contract: Fingerprint,
106}
107
108/// A catalog this one succeeds: its id and its count of entries.
109#[derive(Debug, Clone, Copy, PartialEq, Eq)]
110pub struct Ancestor {
111    pub id: CatalogId,
112    pub entries: u16,
113}
114
115/// Why a reading refused a document (core §8.6), in the text's order.
116#[derive(Debug, Clone, Copy, PartialEq, Eq)]
117pub enum Reason {
118    /// Not strict JSON: RFC 8259, with no member twice in one object.
119    Json,
120    /// Not an object whose `format` is the string `zk2-catalog/1`.
121    Format,
122    /// A member missing, or one this version does not name: at the top, in
123    /// an entry or in a lineage item.
124    Member,
125    /// `epoch` is not an integer from 0 to 2^53 − 1.
126    Epoch,
127    /// `entries` is not an array of objects, or holds more than 1,024.
128    Entries,
129    /// An entry's `index` is not the integer of its position.
130    Index,
131    /// An entry's `iface` is not a string holding an interface id.
132    Iface,
133    /// An entry's `contract` is not a string holding a fingerprint.
134    Contract,
135    /// An entry's pair is an earlier entry's.
136    Duplicate,
137    /// `lineage` is not a non-empty array of objects; or an item's `id` is
138    /// not 8 lowercase hex digits, or is an earlier item's or the
139    /// catalog's own; or its `entries` is not an integer, is below the
140    /// item before it's, or above the catalog's count.
141    Lineage,
142}
143
144impl Reason {
145    /// The fixtures' token (`spec/conformance/catalog/documents.json`).
146    #[must_use]
147    pub fn token(self) -> &'static str {
148        match self {
149            Self::Json => "json",
150            Self::Format => "format",
151            Self::Member => "member",
152            Self::Epoch => "epoch",
153            Self::Entries => "entries",
154            Self::Index => "index",
155            Self::Iface => "iface",
156            Self::Contract => "contract",
157            Self::Duplicate => "duplicate",
158            Self::Lineage => "lineage",
159        }
160    }
161}
162
163/// A refused document: the reason, where, and what was found.
164#[derive(Debug, Clone, PartialEq, Eq)]
165pub struct Refusal {
166    pub reason: Reason,
167    /// `catalog`, `epoch`, `entries[3]`, `lineage[0]`…
168    pub at: String,
169    pub detail: String,
170}
171
172impl Refusal {
173    fn new(reason: Reason, at: impl Into<String>, detail: impl Into<String>) -> Self {
174        Self {
175            reason,
176            at: at.into(),
177            detail: detail.into(),
178        }
179    }
180
181    /// The fixtures' token.
182    #[must_use]
183    pub fn token(&self) -> &'static str {
184        self.reason.token()
185    }
186}
187
188impl fmt::Display for Refusal {
189    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
190        write!(f, "{}: {} ({})", self.at, self.detail, self.token())
191    }
192}
193
194impl std::error::Error for Refusal {}
195
196/// Why a catalog does not succeed another (core §8.6), the first in the
197/// checker's order.
198#[derive(Debug, Clone, Copy, PartialEq, Eq)]
199pub enum Succession {
200    /// The successor's epoch is not its predecessor's.
201    EpochMoved,
202    /// This index, below the predecessor's count, holds another pair.
203    Reassigned(u16),
204    /// This index of the predecessor is gone.
205    Removed(u16),
206    /// The successor's lineage is not its predecessor's, followed by the
207    /// predecessor's id and count.
208    Lineage,
209}
210
211impl Succession {
212    /// The fixtures' token (`spec/conformance/catalog/succession.json`).
213    #[must_use]
214    pub fn token(self) -> &'static str {
215        match self {
216            Self::EpochMoved => "epoch_moved",
217            Self::Reassigned(_) => "reassigned",
218            Self::Removed(_) => "removed",
219            Self::Lineage => "lineage",
220        }
221    }
222}
223
224impl fmt::Display for Succession {
225    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
226        match self {
227            Self::EpochMoved => f.write_str("the epoch moved"),
228            Self::Reassigned(i) => write!(f, "index {i} holds another pair"),
229            Self::Removed(i) => write!(f, "index {i} is gone"),
230            Self::Lineage => {
231                f.write_str("the lineage is not the predecessor's, followed by its id and count")
232            }
233        }?;
234        write!(f, " ({})", self.token())
235    }
236}
237
238/// Why a reader refused an index or an epoch (core §8.6).
239#[derive(Debug, Clone, Copy, PartialEq, Eq)]
240pub enum ReadRefusal {
241    /// It holds neither the catalog named nor one whose lineage holds it;
242    /// or an index came with no catalog named.
243    UnknownCatalog,
244    /// The index is at or above the count read through.
245    UnknownIndex,
246}
247
248impl ReadRefusal {
249    /// The fixtures' token.
250    #[must_use]
251    pub fn token(self) -> &'static str {
252        match self {
253            Self::UnknownCatalog => "unknown_catalog",
254            Self::UnknownIndex => "unknown_index",
255        }
256    }
257}
258
259impl fmt::Display for ReadRefusal {
260    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
261        f.write_str(self.token())
262    }
263}
264
265impl std::error::Error for ReadRefusal {}
266
267/// A deployment catalog, read and checked (core §8.6).
268#[derive(Debug, Clone, PartialEq, Eq)]
269pub struct Catalog {
270    epoch: i64,
271    entries: Vec<Entry>,
272    lineage: Vec<Ancestor>,
273    id: CatalogId,
274}
275
276/// What [`Catalog::push`] did.
277#[derive(Debug, Clone, Copy, PartialEq, Eq)]
278pub enum Pushed {
279    /// The pair is new, at this index.
280    Added(u16),
281    /// The catalog already held the pair, at this index.
282    Held(u16),
283}
284
285impl Pushed {
286    /// The pair's index, either way.
287    #[must_use]
288    pub fn index(self) -> u16 {
289        match self {
290            Self::Added(i) | Self::Held(i) => i,
291        }
292    }
293}
294
295/// An integer as §8.6 reads one: a JSON number written as digits alone,
296/// with no sign, fraction or exponent. The strict reader keeps such a
297/// number as a `u64`; anything else, `-0` and an integer past `u64` among
298/// them, it holds as a negative or a float.
299fn digits(v: &Value) -> Option<u64> {
300    v.as_u64()
301}
302
303const TOP: [&str; 4] = ["format", "epoch", "entries", "lineage"];
304const ENTRY: [&str; 3] = ["index", "iface", "contract"];
305const ITEM: [&str; 2] = ["id", "entries"];
306
307/// Exactly these members: every `required`, and no member outside `allowed`.
308fn members(m: &Map<String, Value>, required: &[&str], allowed: &[&str]) -> bool {
309    required.iter().all(|k| m.contains_key(*k)) && m.keys().all(|k| allowed.contains(&k.as_str()))
310}
311
312impl Catalog {
313    /// An empty first catalog, of this epoch.
314    ///
315    /// # Errors
316    /// `epoch` outside 0 to 2^53 − 1 ([`Reason::Epoch`]).
317    pub fn new(epoch: i64) -> Result<Self, Refusal> {
318        if !(0..=MAX_EPOCH).contains(&epoch) {
319            return Err(Refusal::new(
320                Reason::Epoch,
321                "epoch",
322                format!("{epoch} is not from 0 to 2^53 - 1"),
323            ));
324        }
325        let mut c = Self {
326            epoch,
327            entries: Vec::new(),
328            lineage: Vec::new(),
329            id: CatalogId([0; 4]),
330        };
331        c.id = c.compute_id();
332        Ok(c)
333    }
334
335    /// Reads a catalog's bytes: UTF-8, then [`Catalog::parse`].
336    ///
337    /// # Errors
338    /// [`Reason::Json`] for bytes that are not UTF-8, else as `parse`.
339    pub fn parse_bytes(bytes: &[u8]) -> Result<Self, Refusal> {
340        let text = std::str::from_utf8(bytes)
341            .map_err(|e| Refusal::new(Reason::Json, "catalog", format!("not UTF-8: {e}")))?;
342        Self::parse(text)
343    }
344
345    /// Reads a catalog as core §8.6 does, refusing it for the first reason
346    /// that applies, in the text's order.
347    ///
348    /// # Errors
349    /// The first [`Refusal`].
350    pub fn parse(text: &str) -> Result<Self, Refusal> {
351        let v = crate::strict::parse_json(text)
352            .map_err(|e| Refusal::new(Reason::Json, "catalog", format!("not strict JSON: {e}")))?;
353        let top = v
354            .as_object()
355            .filter(|m| m.get("format").and_then(Value::as_str) == Some(FORMAT))
356            .ok_or_else(|| {
357                Refusal::new(
358                    Reason::Format,
359                    "format",
360                    format!("not an object whose format is {FORMAT:?}"),
361                )
362            })?;
363        if !members(top, &["epoch", "entries"], &TOP) {
364            return Err(Refusal::new(
365                Reason::Member,
366                "catalog",
367                "epoch or entries missing, or a member besides format, epoch, entries and lineage",
368            ));
369        }
370        let epoch = digits(&top["epoch"])
371            .and_then(|e| i64::try_from(e).ok())
372            .filter(|e| *e <= MAX_EPOCH)
373            .ok_or_else(|| {
374                Refusal::new(
375                    Reason::Epoch,
376                    "epoch",
377                    format!("{} is not an integer from 0 to 2^53 - 1", top["epoch"]),
378                )
379            })?;
380        let items = top["entries"]
381            .as_array()
382            .filter(|a| a.len() <= MAX_ENTRIES && a.iter().all(Value::is_object))
383            .ok_or_else(|| {
384                Refusal::new(
385                    Reason::Entries,
386                    "entries",
387                    format!("not an array of at most {MAX_ENTRIES} objects"),
388                )
389            })?;
390        let mut entries = Vec::with_capacity(items.len());
391        let mut seen = BTreeSet::new();
392        for (i, item) in items.iter().enumerate() {
393            entries.push(Self::read_entry(i, item, &mut seen)?);
394        }
395        let id = CatalogId::of_jcs(&jcs(&v));
396        let lineage = match top.get("lineage") {
397            None => Vec::new(),
398            Some(l) => Self::read_lineage(l, entries.len(), id)?,
399        };
400        let c = Self {
401            epoch,
402            entries,
403            lineage,
404            id,
405        };
406        debug_assert_eq!(
407            c.id,
408            c.compute_id(),
409            "the document read writes back to its own bytes"
410        );
411        Ok(c)
412    }
413
414    fn read_entry(
415        i: usize,
416        item: &Value,
417        seen: &mut BTreeSet<(String, String)>,
418    ) -> Result<Entry, Refusal> {
419        let at = format!("entries[{i}]");
420        let m = item.as_object().expect("entries checked as objects");
421        if !members(m, &ENTRY, &ENTRY) {
422            return Err(Refusal::new(
423                Reason::Member,
424                at,
425                "not exactly index, iface and contract",
426            ));
427        }
428        if digits(&m["index"]) != Some(i as u64) {
429            return Err(Refusal::new(
430                Reason::Index,
431                at,
432                format!("index {} is not its position, {i}", m["index"]),
433            ));
434        }
435        let iface = m["iface"]
436            .as_str()
437            .and_then(|s| s.parse::<IfaceId>().ok())
438            .ok_or_else(|| {
439                Refusal::new(
440                    Reason::Iface,
441                    &at,
442                    format!("iface {} is not an interface id", m["iface"]),
443                )
444            })?;
445        let contract = m["contract"]
446            .as_str()
447            .and_then(|s| Fingerprint::parse(s).ok())
448            .ok_or_else(|| {
449                Refusal::new(
450                    Reason::Contract,
451                    &at,
452                    format!("contract {} is not a fingerprint", m["contract"]),
453                )
454            })?;
455        if !seen.insert((iface.to_string(), contract.to_string())) {
456            return Err(Refusal::new(
457                Reason::Duplicate,
458                at,
459                format!("{iface} at {contract} is an earlier entry's pair"),
460            ));
461        }
462        Ok(Entry { iface, contract })
463    }
464
465    fn read_lineage(l: &Value, count: usize, own: CatalogId) -> Result<Vec<Ancestor>, Refusal> {
466        let items = l
467            .as_array()
468            .filter(|a| !a.is_empty() && a.iter().all(Value::is_object))
469            .ok_or_else(|| {
470                Refusal::new(
471                    Reason::Lineage,
472                    "lineage",
473                    "not a non-empty array of objects",
474                )
475            })?;
476        let mut out: Vec<Ancestor> = Vec::with_capacity(items.len());
477        for (k, item) in items.iter().enumerate() {
478            let at = format!("lineage[{k}]");
479            let m = item.as_object().expect("lineage checked as objects");
480            if !members(m, &ITEM, &ITEM) {
481                return Err(Refusal::new(
482                    Reason::Member,
483                    at,
484                    "not exactly id and entries",
485                ));
486            }
487            let id = m["id"]
488                .as_str()
489                .and_then(CatalogId::from_hex)
490                .ok_or_else(|| {
491                    Refusal::new(
492                        Reason::Lineage,
493                        &at,
494                        format!("id {} is not 8 lowercase hex digits", m["id"]),
495                    )
496                })?;
497            if id == own || out.iter().any(|a| a.id == id) {
498                return Err(Refusal::new(
499                    Reason::Lineage,
500                    at,
501                    format!("id {id} is an earlier item's or the catalog's own"),
502                ));
503            }
504            let floor = out.last().map_or(0, |a| u64::from(a.entries));
505            let entries = digits(&m["entries"])
506                .filter(|n| *n >= floor && *n <= count as u64)
507                .and_then(|n| u16::try_from(n).ok())
508                .ok_or_else(|| {
509                    Refusal::new(
510                        Reason::Lineage,
511                        &at,
512                        format!(
513                            "entries {} is not an integer from {floor} to the catalog's {count}",
514                            m["entries"]
515                        ),
516                    )
517                })?;
518            out.push(Ancestor { id, entries });
519        }
520        Ok(out)
521    }
522
523    /// The deployment epoch, in whole seconds since the Unix epoch.
524    #[must_use]
525    pub fn epoch(&self) -> i64 {
526        self.epoch
527    }
528
529    /// The entries, each at its index.
530    #[must_use]
531    pub fn entries(&self) -> &[Entry] {
532        &self.entries
533    }
534
535    /// The catalogs this one succeeds, oldest first.
536    #[must_use]
537    pub fn lineage(&self) -> &[Ancestor] {
538        &self.lineage
539    }
540
541    /// The catalog's id.
542    #[must_use]
543    pub fn id(&self) -> CatalogId {
544        self.id
545    }
546
547    /// The entry at an index, if the catalog holds one there.
548    #[must_use]
549    pub fn entry(&self, index: u16) -> Option<&Entry> {
550        self.entries.get(usize::from(index))
551    }
552
553    /// The index of a revision, if the catalog lists it: what an owner
554    /// writes for its interface and fingerprint.
555    #[must_use]
556    pub fn index_of(&self, iface: &IfaceId, contract: &Fingerprint) -> Option<u16> {
557        self.entries
558            .iter()
559            .position(|e| &e.iface == iface && &e.contract == contract)
560            .map(|i| u16::try_from(i).expect("at most 1,024 entries"))
561    }
562
563    /// The count a reader holding this catalog reads data named `id`
564    /// through: its own when `id` is its own, a lineage item's when its
565    /// lineage holds `id`, else `None`.
566    #[must_use]
567    pub fn holds(&self, id: CatalogId) -> Option<u16> {
568        if id == self.id {
569            return Some(self.count());
570        }
571        self.lineage.iter().find(|a| a.id == id).map(|a| a.entries)
572    }
573
574    fn count(&self) -> u16 {
575        u16::try_from(self.entries.len()).expect("at most 1,024 entries")
576    }
577
578    /// Whether this catalog succeeds `previous` (core §8.6): its lineage is
579    /// `previous`'s followed by `previous`'s id and count, its epoch is
580    /// `previous`'s, and `previous`'s entries are its first ones.
581    ///
582    /// # Errors
583    /// The first [`Succession`] refusal, in the checker's order.
584    pub fn succeeds(&self, previous: &Catalog) -> Result<(), Succession> {
585        if self.epoch != previous.epoch {
586            return Err(Succession::EpochMoved);
587        }
588        for (i, e) in previous.entries.iter().enumerate() {
589            let i = u16::try_from(i).expect("at most 1,024 entries");
590            match self.entry(i) {
591                Some(mine) if mine != e => return Err(Succession::Reassigned(i)),
592                Some(_) => {}
593                None => return Err(Succession::Removed(i)),
594            }
595        }
596        let mut want = previous.lineage.clone();
597        want.push(Ancestor {
598            id: previous.id,
599            entries: previous.count(),
600        });
601        if self.lineage != want {
602            return Err(Succession::Lineage);
603        }
604        Ok(())
605    }
606
607    /// The catalog that succeeds this one with no entry added: its lineage
608    /// extended by this one's id and count. [`Catalog::push`] then appends.
609    #[must_use]
610    pub fn successor(&self) -> Self {
611        let mut c = self.clone();
612        c.lineage.push(Ancestor {
613            id: self.id,
614            entries: self.count(),
615        });
616        c.id = c.compute_id();
617        c
618    }
619
620    /// Appends a revision at the next index, or finds it already held.
621    ///
622    /// # Errors
623    /// [`Reason::Entries`] when the catalog holds 1,024 entries;
624    /// [`Reason::Lineage`] when the new id would be a lineage item's, a
625    /// 32-bit collision. Either way the catalog is unchanged.
626    pub fn push(&mut self, iface: IfaceId, contract: Fingerprint) -> Result<Pushed, Refusal> {
627        if let Some(i) = self.index_of(&iface, &contract) {
628            return Ok(Pushed::Held(i));
629        }
630        if self.entries.len() >= MAX_ENTRIES {
631            return Err(Refusal::new(
632                Reason::Entries,
633                "entries",
634                format!("the catalog holds {MAX_ENTRIES} entries already"),
635            ));
636        }
637        self.entries.push(Entry { iface, contract });
638        let id = self.compute_id();
639        if self.lineage.iter().any(|a| a.id == id) {
640            self.entries.pop();
641            return Err(Refusal::new(
642                Reason::Lineage,
643                "lineage",
644                format!("the new id {id} is a lineage item's"),
645            ));
646        }
647        self.id = id;
648        Ok(Pushed::Added(self.count() - 1))
649    }
650
651    /// The document, as [`Document`] spells it.
652    #[must_use]
653    pub fn document(&self) -> Document {
654        Document {
655            format: FORMAT.to_owned(),
656            epoch: u64::try_from(self.epoch).expect("an epoch is from 0"),
657            entries: self
658                .entries
659                .iter()
660                .enumerate()
661                .map(|(i, e)| DocumentEntry {
662                    index: u16::try_from(i).expect("at most 1,024 entries"),
663                    iface: e.iface.to_string(),
664                    contract: e.contract.to_string(),
665                })
666                .collect(),
667            lineage: (!self.lineage.is_empty()).then(|| {
668                self.lineage
669                    .iter()
670                    .map(|a| DocumentAncestor {
671                        id: a.id.hex(),
672                        entries: a.entries,
673                    })
674                    .collect()
675            }),
676        }
677    }
678
679    /// The document as a JSON value.
680    #[must_use]
681    pub fn to_value(&self) -> Value {
682        serde_json::to_value(self.document()).expect("a catalog always serializes")
683    }
684
685    /// The document's JCS bytes, which its id hashes and `zk2 catalog`
686    /// writes.
687    #[must_use]
688    pub fn to_jcs(&self) -> Vec<u8> {
689        jcs(&self.to_value())
690    }
691
692    fn compute_id(&self) -> CatalogId {
693        CatalogId::of_jcs(&self.to_jcs())
694    }
695}
696
697/// What a reader reads an index or a time through (core §8.6): a held
698/// catalog, and the count of its entries the named catalog had.
699#[derive(Debug, Clone, Copy)]
700pub struct Through<'a> {
701    catalog: &'a Catalog,
702    count: u16,
703}
704
705impl<'a> Through<'a> {
706    /// The catalog held.
707    #[must_use]
708    pub fn catalog(&self) -> &'a Catalog {
709        self.catalog
710    }
711
712    /// How many of its entries data under the named catalog can index.
713    #[must_use]
714    pub fn count(&self) -> u16 {
715        self.count
716    }
717
718    /// The epoch to count times from: the held catalog's, which a
719    /// successor keeps.
720    #[must_use]
721    pub fn epoch(&self) -> i64 {
722        self.catalog.epoch
723    }
724
725    /// The entry at an index.
726    ///
727    /// # Errors
728    /// [`ReadRefusal::UnknownIndex`] at or above the count.
729    pub fn entry(&self, index: u16) -> Result<&'a Entry, ReadRefusal> {
730        if index >= self.count {
731            return Err(ReadRefusal::UnknownIndex);
732        }
733        self.catalog.entry(index).ok_or(ReadRefusal::UnknownIndex)
734    }
735}
736
737/// Resolves the catalog an owner names among those a reader holds: the
738/// named one itself where it is held, else the first whose lineage holds
739/// its id, for the indices below that item's count.
740///
741/// # Errors
742/// [`ReadRefusal::UnknownCatalog`] when no held catalog is or succeeds it.
743pub fn through(held: &[Catalog], named: CatalogId) -> Result<Through<'_>, ReadRefusal> {
744    held.iter()
745        .find(|c| c.id == named)
746        .or_else(|| held.iter().find(|c| c.holds(named).is_some()))
747        .and_then(|catalog| catalog.holds(named).map(|count| Through { catalog, count }))
748        .ok_or(ReadRefusal::UnknownCatalog)
749}
750
751/// The deployment epoch a reader counts an owner's times from: the epoch of
752/// the catalog it names, read [`through`] what is held, or
753/// [`EPOCH_WITHOUT_CATALOG`] when it names none.
754///
755/// # Errors
756/// [`ReadRefusal::UnknownCatalog`] as [`through`].
757pub fn epoch_of(held: &[Catalog], named: Option<CatalogId>) -> Result<i64, ReadRefusal> {
758    named.map_or(Ok(EPOCH_WITHOUT_CATALOG), |id| {
759        through(held, id).map(|t| t.epoch())
760    })
761}
762
763/// A deployment catalog (core §8.6), as `zk2 catalog` writes it. This
764/// schema cannot state all of §8.6's reading: an entry's index at its
765/// position, no pair twice, a lineage's ids and counts, and an integer
766/// written as digits alone are the reading's alone.
767#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
768#[serde(deny_unknown_fields)]
769#[schemars(title = "Catalog")]
770pub struct Document {
771    /// `zk2-catalog/1`.
772    #[schemars(extend("const" = "zk2-catalog/1"))]
773    pub format: String,
774    /// The deployment epoch: whole seconds since the Unix epoch, which core
775    /// §7.6's `time` fields count from.
776    #[schemars(range(max = 9_007_199_254_740_991_u64))]
777    pub epoch: u64,
778    /// The revisions, each at the index of its position: at most 1,024, and
779    /// no pair twice. An interface appears once per revision.
780    #[schemars(length(max = 1024))]
781    pub entries: Vec<DocumentEntry>,
782    /// Every catalog this one succeeds, oldest first. Absent for a first
783    /// catalog, and never empty.
784    #[serde(default, skip_serializing_if = "Option::is_none")]
785    #[schemars(with = "Vec<DocumentAncestor>", length(min = 1))]
786    pub lineage: Option<Vec<DocumentAncestor>>,
787}
788
789/// One revision at its index.
790#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
791#[serde(deny_unknown_fields)]
792pub struct DocumentEntry {
793    /// Its position in `entries`, from 0.
794    #[schemars(range(max = 1023))]
795    pub index: u16,
796    /// The interface id, `<name>.v<major>`.
797    pub iface: String,
798    /// The revision's fingerprint, `sha256:` and 64 lowercase hex digits.
799    #[schemars(extend("pattern" = "^sha256:[0-9a-f]{64}$"))]
800    pub contract: String,
801}
802
803/// A catalog this one succeeds.
804#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
805#[serde(deny_unknown_fields)]
806pub struct DocumentAncestor {
807    /// Its id: 8 lowercase hex digits.
808    #[schemars(extend("pattern" = "^[0-9a-f]{8}$"))]
809    pub id: String,
810    /// Its count of entries: at least the item before it's, and at most this
811    /// catalog's.
812    #[schemars(range(max = 1024))]
813    pub entries: u16,
814}
815
816#[cfg(test)]
817mod tests {
818    use super::*;
819
820    fn fp(n: u32) -> Fingerprint {
821        Fingerprint::parse(&format!("sha256:{n:064x}")).unwrap()
822    }
823
824    fn iface(s: &str) -> IfaceId {
825        s.parse().unwrap()
826    }
827
828    /// The bound is 1,024 entries: the largest catalog reads, one more is
829    /// refused for the count, and a push past it changes nothing.
830    #[test]
831    fn a_catalog_holds_at_most_1024_entries() {
832        let mut c = Catalog::new(0).unwrap();
833        for major in 0..1024 {
834            assert_eq!(
835                c.push(iface(&format!("a.v{major}")), fp(1)).unwrap(),
836                Pushed::Added(u16::try_from(major).unwrap())
837            );
838        }
839        let text = String::from_utf8(c.to_jcs()).unwrap();
840        let read = Catalog::parse(&text).unwrap();
841        assert_eq!(read, c);
842        assert_eq!(read.entry(1023).unwrap().iface, iface("a.v1023"));
843        let before = c.clone();
844        let r = c.push(iface("b.v1"), fp(1)).unwrap_err();
845        assert_eq!(r.token(), "entries");
846        assert_eq!(c, before);
847        let over = text.replacen("\"entries\":[", "\"entries\":[{},", 1);
848        assert_eq!(Catalog::parse(&over).unwrap_err().token(), "entries");
849    }
850
851    /// What `zk2 catalog add` writes: a successor that reads back, succeeds
852    /// its predecessor, and indexes data under it below its count.
853    #[test]
854    fn a_successor_reads_back_and_succeeds() {
855        let mut a = Catalog::new(1_767_225_600).unwrap();
856        a.push(iface("modem.v3"), fp(1)).unwrap();
857        a.push(iface("config.v1"), fp(2)).unwrap();
858        assert_eq!(a.push(iface("modem.v3"), fp(1)).unwrap(), Pushed::Held(0));
859        let mut b = a.successor();
860        assert_eq!(b.succeeds(&a), Ok(()));
861        assert_eq!(b.push(iface("health.v1"), fp(3)).unwrap(), Pushed::Added(2));
862        assert_eq!(b.push(iface("modem.v3"), fp(4)).unwrap(), Pushed::Added(3));
863        assert_eq!(b.succeeds(&a), Ok(()));
864        assert_eq!(a.succeeds(&b), Err(Succession::Removed(2)));
865        assert_eq!(a.succeeds(&a), Err(Succession::Lineage));
866        let read = Catalog::parse(std::str::from_utf8(&b.to_jcs()).unwrap()).unwrap();
867        assert_eq!(read, b);
868        assert_eq!(read.id(), b.id());
869        assert_eq!(read.index_of(&iface("modem.v3"), &fp(4)), Some(3));
870        assert_eq!(read.index_of(&iface("modem.v3"), &fp(9)), None);
871
872        let held = [b.clone()];
873        let t = through(&held, a.id()).unwrap();
874        assert_eq!(t.count(), 2);
875        assert_eq!(t.entry(1).unwrap().iface, iface("config.v1"));
876        assert_eq!(t.entry(2).unwrap_err(), ReadRefusal::UnknownIndex);
877        assert_eq!(
878            through(&[a.clone()], b.id()).unwrap_err(),
879            ReadRefusal::UnknownCatalog
880        );
881        assert_eq!(epoch_of(&held, Some(a.id())), Ok(1_767_225_600));
882        assert_eq!(epoch_of(&held, None), Ok(EPOCH_WITHOUT_CATALOG));
883    }
884
885    /// A lineage item may not carry the catalog's own id. A document that
886    /// does needs a 32-bit collision, so the check is reached here through
887    /// the lineage reader directly.
888    #[test]
889    fn a_lineage_never_holds_the_catalogs_own_id() {
890        let own = CatalogId::from_hex("0a90fd61").unwrap();
891        let l = serde_json::json!([{"id": "0a90fd61", "entries": 0}]);
892        let r = Catalog::read_lineage(&l, 0, own).unwrap_err();
893        assert_eq!(r.token(), "lineage");
894        let other = CatalogId::from_hex("0a90fd62").unwrap();
895        assert_eq!(
896            Catalog::read_lineage(&l, 0, other).unwrap(),
897            [Ancestor {
898                id: own,
899                entries: 0
900            }]
901        );
902    }
903
904    #[test]
905    fn an_id_is_8_lowercase_hex_digits() {
906        assert_eq!(CatalogId::from_hex("0a90fd61").unwrap().hex(), "0a90fd61");
907        assert_eq!(
908            CatalogId::from_hex("0a90fd61").unwrap().bytes(),
909            [0x0a, 0x90, 0xfd, 0x61]
910        );
911        for bad in ["0A90FD61", "0a90fd6", "0a90fd611", "+a90fd61", "0x90fd61"] {
912            assert!(CatalogId::from_hex(bad).is_none(), "{bad}");
913        }
914        assert!(Catalog::new(-1).is_err());
915        assert!(Catalog::new(MAX_EPOCH + 1).is_err());
916        assert!(Catalog::new(MAX_EPOCH).is_ok());
917    }
918}