Skip to main content

datumesh_http/
catalog_build.rs

1//! The catalogue job (CONTRACT-classes-round C3 to C5): `datumesh-mesh catalog-build` writes the classes `catalog/subject` and
2//! `catalog/facet` (their methods inline, K7), and the cells of their objects, as stored cells signed by the mesh's key with the
3//! licence the job is given; and the rule text (`catalog/rule()`, the page `/catalog/rule`).
4//!
5//! The job reads the store's catalogue entries that have facets (as of its clock). A rerun over an unchanged catalogue writes
6//! nothing: each cell line has no `tx`, so publish's skip rule keeps a cell whose latest version states the same thing. A subject
7//! that disappears has every method cell withdrawn with the reason "the subject is no longer in the catalogue" (R1, R10), its
8//! labels too, and so does a facet value that disappears; `source(rank)` past the count of sources is withdrawn ("rank past the
9//! count of sources"). A withdrawal is a cell's null version, never `false` or `""`. A cell never stored and not wanted has no line,
10//! so a label that names two subjects is absent, not withdrawn.
11//!
12//! At most 256 subjects come from one entry, and a subject keeps at most 20 sources (R11).
13//!
14//! # The rank (C5)
15//!
16//! Per subject, each entry of the subject is level 1, 2 or 3:
17//! * a *relay* is a name `<host>/relay/<domain>/...`; its domain is `<domain>` (level 2);
18//! * a *view* is a function or class that is not a relay and whose inputs read a relay directly or through other views, to any
19//!   depth, through any named function or class (level 2). Its source domains are the domains of the relays it reaches;
20//! * the subject's source domains are the domains of its relays and of the relays its views reach;
21//! * any other entry is level 1 when its publisher's host (the first segment of its name) equals one of those domains or is a
22//!   sub-domain of one; when the subject has no source domain, every such entry is level 1 (its own host is its source domain);
23//! * otherwise level 3.
24//!
25//! Within a level (R5): a source whose class is a subclass of another source's class (at any depth) comes before it; the rest
26//! by the instant the name was first bound (a class's own class binding), then the name, ascending. The rank one source is the
27//! first of that order, and `source(k)` is the k-th.
28//!
29//! # What is written, and what it is called
30//!
31//! * the class `<host>/catalog/subject`: keys `domain`, `thing`, `measure`, `region` (`none`), in that order; the lookup
32//!   `from_label` (`label_fold`); the methods `exists`, `label`, `sources`, `source(rank)` (`rank` a number of unit `1`, default
33//!   `1`, K13), `from_label`; the extent `keys` is `exists`;
34//! * the class `<host>/catalog/facet`: keys `facet`, `value`; the methods `exists`, `label`, `subjects`; the extent `keys` is
35//!   `exists`;
36//! * the function `<host>/catalog/rule` (no argument, a blob: the text of the rule).
37//!
38//! The labels of a subject: `label()` is its facet values with `_` as a space, measure, thing, region, domain, joined by
39//! ` · `, a `none` value left out, the region written out (`ea` euro area, `gb` United Kingdom, `us` United States, `world`
40//! world). The lookup's labels are the folded `label()`, and `<measure> <region>` and `<thing> <measure> <region>` (folded), each
41//! only when it names exactly one subject; a label that names two is not stored.
42//!
43//! Choices where the contract is silent (each is in the report): a subject needs all four keys (an entry without one has no
44//! subjects); `subjects()` of a `frequency` value is the number of subjects of the entries that carry it.
45
46use std::collections::{BTreeMap, BTreeSet};
47
48use datumesh_core::{
49    fold_label, Arg, Cell, ClassDescriptor, FunctionDescriptor, Receipt, Scalar, SigningKey, Slice, Type,
50};
51use datumesh_store::{CatalogKind, Facets, SliceValue, Store};
52use serde_json::{json, Value};
53
54use crate::publish::{publish_job, PublishError, PublishOptions};
55
56/// The rule of the catalogue (C5, R5, R7): the text of the page `/catalog/rule` and of the blob `catalog/rule()`.
57pub(crate) const RULE: &str = "How the catalogue ranks the sources of a subject. \
58A source is level one when it is published under the domain of the data: its publisher host is that domain or a sub-domain of it. A parent \
59domain does not count, and no public suffix list is used. A source is level two when it is a relay of the data, a name under the relay path of the domain of the data and trusted \
60as relayed, or a view built on such a relay: a function or a class whose inputs read a relay, directly or through other views. \
61Every other source is level three. Within a level, a source whose class is a subclass of the class of another source, at any depth, \
62ranks above that parent class. Then the source whose name was first bound comes first, and a tie on the time of the first binding \
63is broken by the name, in ascending order. The rank one source of a subject is the first source in this order, and source of \
64rank k is the k-th; a subject keeps at most twenty sources. A subject with no relay and no view has no source domain, so its sources \
65are level one under their own hosts. The job that writes the catalogue applies this rule to the facets the publishers give. \
66Addresses: a cell address and a class name carry no facet value and no rank; a page path may carry a facet value, as \
67the domain pages of the catalogue do.";
68
69/// The file name of the rule text in the job's blobs.
70const RULE_FILE: &str = "rule.txt";
71
72/// The job's result: `cells` is the number of cell versions the run wrote (the classes, methods and bindings are not counted), and
73/// `subjects` the subjects that exist now.
74#[derive(Clone, Debug, PartialEq, Eq)]
75#[non_exhaustive]
76pub struct CatalogBuilt {
77    /// Cell versions written by the run.
78    pub cells: u64,
79    /// Subjects that exist as of the run.
80    pub subjects: u64,
81}
82
83/// A subject: its four keys, `(domain, thing, measure, region)`.
84pub(crate) type SubjectKey = (String, String, String, String);
85
86/// `<host>/catalog/subject`.
87pub(crate) fn subject_class(host: &str) -> String {
88    format!("{host}/catalog/subject")
89}
90
91/// `<host>/catalog/facet`.
92pub(crate) fn facet_class(host: &str) -> String {
93    format!("{host}/catalog/facet")
94}
95
96/// `<host>/catalog/rule`.
97pub(crate) fn rule_fn(host: &str) -> String {
98    format!("{host}/catalog/rule")
99}
100
101/// The key encoding of a subject (16.5: the names in ascending order, no space).
102pub(crate) fn subject_key_text(host: &str, k: &SubjectKey) -> String {
103    format!(r#"{}(domain:"{}",measure:"{}",region:"{}",thing:"{}")"#, subject_class(host), k.0, k.2, k.3, k.1)
104}
105
106/// The subject a key encoding names, when it is one of this host's subjects written as [`subject_key_text`] writes it.
107pub(crate) fn parse_subject_key(host: &str, text: &str) -> Option<SubjectKey> {
108    let body = text.strip_prefix(&format!("{}(", subject_class(host)))?.strip_suffix(')')?;
109    let mut got: BTreeMap<&str, &str> = BTreeMap::new();
110    for part in body.split(',') {
111        let (k, v) = part.split_once(':')?;
112        let v = v.strip_prefix('"')?.strip_suffix('"')?;
113        if v.contains('"') || got.insert(k, v).is_some() {
114            return None;
115        }
116    }
117    if got.len() != 4 {
118        return None;
119    }
120    Some((
121        got.get("domain")?.to_string(),
122        got.get("thing")?.to_string(),
123        got.get("measure")?.to_string(),
124        got.get("region")?.to_string(),
125    ))
126}
127
128/// A subject's words as its label (C3, C4): `_` as a space, the region written out, `none` left out.
129pub(crate) fn region_text(code: &str) -> String {
130    match code {
131        "ea" => "euro area".into(),
132        "gb" => "United Kingdom".into(),
133        "us" => "United States".into(),
134        other => other.replace('_', " "),
135    }
136}
137
138/// The label of a subject: measure, thing, region, domain, joined by ` · `.
139pub(crate) fn subject_label(k: &SubjectKey) -> String {
140    let parts = [k.2.replace('_', " "), k.1.replace('_', " "), region_text(&k.3), k.0.replace('_', " ")];
141    parts.into_iter().filter(|p| p != "none").collect::<Vec<_>>().join(" \u{b7} ")
142}
143
144/// The label of a facet object: its value with `_` as a space; a region's code written out.
145pub(crate) fn facet_label(facet: &str, value: &str) -> String {
146    if facet == "region" {
147        region_text(value)
148    } else {
149        value.replace('_', " ")
150    }
151}
152
153/// The folded lookup labels of a subject: the folded `label()`, and `<measure> <region>` and `<thing> <measure> <region>` where
154/// the region is not `none`, and the thing is not `none` for the last.
155pub(crate) fn lookup_labels(k: &SubjectKey) -> Vec<String> {
156    let mut out = vec![fold_label(&subject_label(k))];
157    if k.3 != "none" {
158        let m = k.2.replace('_', " ");
159        out.push(fold_label(&format!("{m} {}", region_text(&k.3))));
160        if k.1 != "none" {
161            out.push(fold_label(&format!("{} {m} {}", k.1.replace('_', " "), region_text(&k.3))));
162        }
163    }
164    out
165}
166
167/// The relay domain of a name `<host>/relay/<domain>/<more>`.
168pub(crate) fn relay_domain(host: &str, name: &str) -> Option<String> {
169    let rest = name.strip_prefix(host)?.strip_prefix('/')?;
170    let mut it = rest.split('/');
171    if it.next()? != "relay" {
172        return None;
173    }
174    let domain = it.next()?;
175    it.next()?;
176    Some(domain.to_string())
177}
178
179/// One cell line of the job: a stored cell of a method, its arguments as typed values, its value and its licence.
180fn cell_line(
181    fn_name: &str,
182    args: Vec<(&str, &str, Value)>,
183    value: (&str, Value),
184    licence: &str,
185    summary: &str,
186) -> String {
187    let a: serde_json::Map<String, Value> =
188        args.into_iter().map(|(k, t, v)| (k.to_string(), json!({"type": t, "value": v}))).collect();
189    json!({"cell": {"fn": fn_name, "args": a}, "value": {"type": value.0, "value": value.1},
190        "licence": licence, "summary": summary})
191    .to_string()
192}
193
194/// The key arguments of a method: strings that are not normalised (an absent `key_normalisation` is `none`, 16.4), not valid
195/// times.
196fn key_args(keys: &[&str]) -> serde_json::Map<String, Value> {
197    keys.iter().map(|k| (k.to_string(), json!({"type": "string", "valid": false}))).collect()
198}
199
200/// The keys of a class as its descriptor has them.
201fn class_keys(keys: &[&str]) -> serde_json::Map<String, Value> {
202    keys.iter().map(|k| (k.to_string(), json!({"key_normalisation": "none", "type": "string"}))).collect()
203}
204
205fn stored_hash(sig: &Value) -> String {
206    let text = json!({"code": {"body": "", "lang": "stored"}, "inputs": [], "signature": sig}).to_string();
207    FunctionDescriptor::from_json(text.as_bytes()).expect("a stored descriptor").hash()
208}
209
210/// The class `subject`'s descriptor, as an author writes it (K7: the methods inline, the extent is `exists`).
211fn subject_class_line(host: &str) -> String {
212    let class = subject_class(host);
213    let keys = ["domain", "thing", "measure", "region"];
214    let mut rank = key_args(&keys);
215    rank.insert("rank".into(), json!({"type": "number", "unit": "1", "valid": false, "default": "1"}));
216    let mut order_rank: Vec<&str> = keys.to_vec();
217    order_rank.push("rank");
218    let exists = json!({"args": key_args(&keys), "order": keys, "returns": "boolean"});
219    let label = json!({"args": key_args(&keys), "order": keys, "returns": "string"});
220    let sources = json!({"args": key_args(&keys), "order": keys, "returns": {"type": "number", "unit": "1"}});
221    let source = json!({"args": rank, "order": order_rank, "returns": "string"});
222    let from_label = json!({"args": {"label": {"key_normalisation": "label_fold", "type": "string", "valid": false}},
223        "order": ["label"], "returns": {"classes": [class], "type": "string"}});
224    let extent = stored_hash(&exists);
225    let descriptor = json!({
226        "keys": class_keys(&keys),
227        "order": keys,
228        "lookup": "from_label",
229        "methods": {"exists": {"stored": exists}, "from_label": {"stored": from_label}, "label": {"stored": label},
230            "source": {"stored": source}, "sources": {"stored": sources}},
231        "extent": {"keys": extent},
232        "steward": {"namespace": host, "process": format!("https://{host}/classes/change")},
233    });
234    json!({"class": class, "descriptor": descriptor}).to_string()
235}
236
237/// The class `facet`'s descriptor (C4).
238fn facet_class_line(host: &str) -> String {
239    let class = facet_class(host);
240    let keys = ["facet", "value"];
241    let exists = json!({"args": key_args(&keys), "order": keys, "returns": "boolean"});
242    let label = json!({"args": key_args(&keys), "order": keys, "returns": "string"});
243    let subjects = json!({"args": key_args(&keys), "order": keys, "returns": {"type": "number", "unit": "1"}});
244    let extent = stored_hash(&exists);
245    let descriptor = json!({
246        "keys": class_keys(&keys),
247        "order": keys,
248        "methods": {"exists": {"stored": exists}, "label": {"stored": label}, "subjects": {"stored": subjects}},
249        "extent": {"keys": extent},
250        "steward": {"namespace": host, "process": format!("https://{host}/classes/change")},
251    });
252    json!({"class": class, "descriptor": descriptor}).to_string()
253}
254
255/// The function `catalog/rule` (no argument, a blob).
256fn rule_line(host: &str) -> String {
257    json!({"function": rule_fn(host), "signature": {"args": {}, "order": [], "returns": "blob"}}).to_string()
258}
259
260/// The entries of the graph: what each name reads, and the relays it reaches (C5), memoised.
261struct Graph<'a, S: ?Sized> {
262    store: &'a S,
263    host: &'a str,
264    now: &'a str,
265    reads: BTreeMap<String, Vec<String>>,
266    reach: BTreeMap<String, BTreeSet<String>>,
267    visiting: BTreeSet<String>,
268}
269
270fn err<E: std::fmt::Display>(e: E) -> PublishError {
271    PublishError { line: 0, detail: format!("catalogue: {e}"), kind: crate::publish::PublishErrorKind::Line }
272}
273
274impl<S: Store + ?Sized> Graph<'_, S> {
275    /// The names a name reads: a function's inputs, or a class's methods' inputs.
276    fn reads_of(&mut self, name: &str) -> Result<Vec<String>, PublishError> {
277        if let Some(r) = self.reads.get(name) {
278            return Ok(r.clone());
279        }
280        let mut out: BTreeSet<String> = BTreeSet::new();
281        let mut fns: Vec<String> = Vec::new();
282        if let Some(b) = self.store.resolve_binding(name, self.now).map_err(err)? {
283            fns.push(b.fn_hash);
284        } else if let Some(c) = self.store.resolve_class(name, self.now).map_err(err)? {
285            if let Some(bytes) = self.store.class(&c).map_err(err)? {
286                let cd = ClassDescriptor::from_json(&bytes).map_err(err)?;
287                fns.extend(cd.methods.values().cloned());
288            }
289        }
290        for h in fns {
291            if let Some(bytes) = self.store.descriptor(&h) {
292                let fd = FunctionDescriptor::from_json(&bytes).map_err(err)?;
293                out.extend(fd.inputs);
294            }
295        }
296        let out: Vec<String> = out.into_iter().collect();
297        self.reads.insert(name.to_string(), out.clone());
298        Ok(out)
299    }
300
301    /// The relay domains a name reaches: its own, for a relay; else those of what it reads (through views, to any depth).
302    fn reach(&mut self, name: &str) -> Result<BTreeSet<String>, PublishError> {
303        if let Some(r) = self.reach.get(name) {
304            return Ok(r.clone());
305        }
306        if !self.visiting.insert(name.to_string()) {
307            return Ok(BTreeSet::new());
308        }
309        let mut out = BTreeSet::new();
310        if let Some(d) = relay_domain(self.host, name) {
311            out.insert(d);
312        } else {
313            for m in self.reads_of(name)? {
314                out.extend(self.reach(&m)?);
315            }
316        }
317        self.visiting.remove(name);
318        self.reach.insert(name.to_string(), out.clone());
319        Ok(out)
320    }
321}
322
323/// The most subjects one catalogue entry gives (R11): its facet product is cut to the first of this many, in the order of the
324/// product (domain, thing, measure, region).
325pub(crate) const SUBJECTS_PER_ENTRY: usize = 256;
326
327/// The most sources a subject keeps (R11): `sources()` is at most this, and the ranks past it have no cell.
328pub(crate) const SOURCES_PER_SUBJECT: usize = 20;
329
330/// The subjects one page of the catalogue reads (CONTRACT-0.5.1 H2): a statement of the job or the view visits at most this
331/// many subjects' cells of one method.
332pub(crate) const PAGE: usize = 1000;
333
334/// The default most subjects the catalogue lists (`DATUMESH_CATALOG_MAX`, CONTRACT-0.5.1 H2).
335pub const DEFAULT_CATALOG_MAX: usize = 100_000;
336
337/// The arguments of a subject class's keys, in the order of the class.
338pub(crate) const SUBJECT_KEYS: [&str; 4] = ["domain", "thing", "measure", "region"];
339
340/// The reason of a withdrawal of a subject or facet value that is gone (R10).
341pub(crate) const GONE: &str = "the subject is no longer in the catalogue";
342/// The reason of a withdrawal of a rank past the count of sources (R10).
343pub(crate) const PAST: &str = "rank past the count of sources";
344/// The reason of a withdrawal of a label that names no single subject any more (R10).
345pub(crate) const LABEL_NO_SUBJECT: &str = "the label names no single subject";
346
347/// An entry of the catalogue with a binding, as the rank sees it.
348struct Entry {
349    name: String,
350    first: String,
351    relay: bool,
352    view: bool,
353    reach: BTreeSet<String>,
354    /// The class hash of a class entry.
355    class: Option<String>,
356    /// The hashes of the classes the entry's class extends, at any depth (R5).
357    ancestors: BTreeSet<String>,
358}
359
360/// The live part of the catalogue: its subjects with their sources in rank order, and the facet objects with their subjects.
361struct Model {
362    subjects: BTreeMap<SubjectKey, Vec<String>>,
363    facets: BTreeMap<(String, String), BTreeSet<SubjectKey>>,
364}
365
366/// The parent classes of a class, at any depth (R5): the hashes its `parent` chain names.
367fn ancestors<S: Store + ?Sized>(store: &S, class_hash: &str) -> Result<BTreeSet<String>, PublishError> {
368    let mut out = BTreeSet::new();
369    let mut cur = class_hash.to_string();
370    // a class chain is acyclic (a parent is stored before its child); the bound is a guard
371    for _ in 0..64 {
372        let Some(bytes) = store.class(&cur).map_err(err)? else { break };
373        let cd = ClassDescriptor::from_json(&bytes).map_err(err)?;
374        let Some(p) = cd.parent else { break };
375        if !out.insert(p.clone()) {
376            break;
377        }
378        cur = p;
379    }
380    Ok(out)
381}
382
383/// The order of a subject's entries (R5): `base` is sorted by level, first binding and name; then an entry whose class is a
384/// subclass of another entry's class in the same level comes before it, the rest keeping the base order (a topological order
385/// with the base order as the priority, so an unrelated entry keeps its place). Returns the entries' indices.
386fn subclass_order(base: &[(u8, &str, &str, usize)], entries: &[Entry]) -> Vec<usize> {
387    let n = base.len();
388    let mut succ: Vec<Vec<usize>> = vec![Vec::new(); n];
389    let mut left = vec![0usize; n];
390    for i in 0..n {
391        let (li, _, _, ei) = base[i];
392        let anc = &entries[ei].ancestors;
393        if anc.is_empty() {
394            continue;
395        }
396        for j in 0..n {
397            let (lj, _, _, ej) = base[j];
398            if i == j || lj != li {
399                continue;
400            }
401            if entries[ej].class.as_ref().is_some_and(|c| anc.contains(c)) {
402                succ[i].push(j);
403                left[j] += 1;
404            }
405        }
406    }
407    let mut avail: BTreeSet<usize> = (0..n).filter(|&i| left[i] == 0).collect();
408    let mut done = vec![false; n];
409    let mut out = Vec::with_capacity(n);
410    while let Some(i) = avail.pop_first() {
411        done[i] = true;
412        out.push(base[i].3);
413        for &j in &succ[i] {
414            left[j] -= 1;
415            if left[j] == 0 && !done[j] {
416                avail.insert(j);
417            }
418        }
419    }
420    // a class chain is acyclic, so every entry is placed; the guard keeps any left in base order
421    out.extend((0..n).filter(|&i| !done[i]).map(|i| base[i].3));
422    out
423}
424
425fn model<S: Store + ?Sized>(store: &S, host: &str, now: &str, cap: usize) -> Result<Model, PublishError> {
426    let mut g = Graph { store, host, now, reads: BTreeMap::new(), reach: BTreeMap::new(), visiting: BTreeSet::new() };
427    let listed = store.catalog_entries_with_facets().map_err(err)?;
428    let mut entries: Vec<Entry> = Vec::new();
429    let mut facets: BTreeMap<(String, String), BTreeSet<SubjectKey>> = BTreeMap::new();
430    let mut members: BTreeMap<SubjectKey, Vec<usize>> = BTreeMap::new();
431    for e in &listed {
432        let keys = subject_keys(&e.facets);
433        let relay = relay_domain(host, &e.name).is_some();
434        let reach = if e.first_bound.is_some() { g.reach(&e.name)? } else { BTreeSet::new() };
435        let view = !relay && !reach.is_empty();
436        let class = if matches!(e.kind, CatalogKind::Class) { e.hash.clone() } else { None };
437        let ancestors = match &class {
438            Some(h) => ancestors(store, h)?,
439            None => BTreeSet::new(),
440        };
441        let idx = entries.len();
442        entries.push(Entry {
443            name: e.name.clone(),
444            first: e.first_bound.clone().unwrap_or_default(),
445            relay,
446            view,
447            reach,
448            class,
449            ancestors,
450        });
451        let bound = e.first_bound.is_some();
452        // A facet value's subjects: those of the entry that have the value under its facet (a frequency is no key, so every
453        // subject of an entry that carries it).
454        for (facet, values) in &e.facets {
455            for v in values {
456                let set = facets.entry((facet.clone(), v.clone())).or_default();
457                set.extend(keys.iter().filter(|k| key_has(facet, v, k)).cloned());
458            }
459        }
460        if bound {
461            for k in &keys {
462                members.entry(k.clone()).or_default().push(idx);
463            }
464        }
465    }
466    let mut subjects = BTreeMap::new();
467    for (k, idxs) in &members {
468        let mut domains: BTreeSet<String> = BTreeSet::new();
469        for &i in idxs {
470            let e = &entries[i];
471            if e.relay || e.view {
472                domains.extend(e.reach.iter().cloned());
473            }
474        }
475        let level = |i: usize| -> u8 {
476            let e = &entries[i];
477            if e.relay || e.view {
478                2
479            } else if domains.is_empty() {
480                1
481            } else {
482                let h = e.name.split('/').next().unwrap_or("");
483                if domains.iter().any(|d| h == d || h.ends_with(&format!(".{d}"))) {
484                    1
485                } else {
486                    3
487                }
488            }
489        };
490        let mut base: Vec<(u8, &str, &str, usize)> =
491            idxs.iter().map(|&i| (level(i), entries[i].first.as_str(), entries[i].name.as_str(), i)).collect();
492        base.sort();
493        let order = subclass_order(&base, &entries);
494        let names: Vec<String> = order.iter().take(SOURCES_PER_SUBJECT).map(|&i| entries[i].name.clone()).collect();
495        subjects.insert(k.clone(), names);
496    }
497    // The catalogue lists at most `cap` subjects, the first in key order (H2); the rest are not written.
498    if subjects.len() > cap {
499        tracing::warn!(target: "datumesh_http", subjects = subjects.len(), cap,
500            "catalogue job: the subjects are cut at DATUMESH_CATALOG_MAX");
501        let kept = subjects.split_off(&subjects.keys().nth(cap).cloned().unwrap_or_default());
502        drop(kept);
503    }
504    // Facet objects count only the subjects that exist (every subject of an entry is one of `members` when it is bound).
505    facets.retain(|_, set| {
506        set.retain(|k| subjects.contains_key(k));
507        true
508    });
509    Ok(Model { subjects, facets })
510}
511
512/// Whether a subject has the value `v` under the facet `facet`: its domain, thing, measure or region is `v`. A frequency is no
513/// key of a subject, so every subject of an entry that carries it has it.
514fn key_has(facet: &str, v: &str, k: &SubjectKey) -> bool {
515    match facet {
516        "domain" => k.0 == v,
517        "thing" => k.1 == v,
518        "measure" => k.2 == v,
519        "region" => k.3 == v,
520        _ => true,
521    }
522}
523
524/// The subjects of an entry's facets: the cross product of its domain, thing, measure and region names (C3), the first
525/// [`SUBJECTS_PER_ENTRY`] of it (R11).
526fn subject_keys(facets: &Facets) -> Vec<SubjectKey> {
527    let get = |k: &str| facets.get(k).cloned().unwrap_or_default();
528    let (d, t, m, r) = (get("domain"), get("thing"), get("measure"), get("region"));
529    let mut out = Vec::new();
530    'all: for dd in &d {
531        for tt in &t {
532            for mm in &m {
533                for rr in &r {
534                    if out.len() == SUBJECTS_PER_ENTRY {
535                        break 'all;
536                    }
537                    out.push((dd.clone(), tt.clone(), mm.clone(), rr.clone()));
538                }
539            }
540        }
541    }
542    out
543}
544
545/// Whether stored receipt bytes are a withdrawal (a `withdrawn` member, R1).
546fn is_withdrawal(bytes: &[u8]) -> bool {
547    datumesh_core::json::parse(bytes).is_ok_and(|v| v.get("withdrawn").is_some())
548}
549
550pub(crate) fn subject_of_args(args: &BTreeMap<String, String>) -> Option<SubjectKey> {
551    Some((
552        args.get("domain")?.clone(),
553        args.get("thing")?.clone(),
554        args.get("measure")?.clone(),
555        args.get("region")?.clone(),
556    ))
557}
558
559/// The lexical arguments of a cell (its value arguments; an open one is left out).
560pub(crate) fn lexical_args(cell: &Cell) -> BTreeMap<String, String> {
561    cell.args
562        .iter()
563        .filter_map(|(k, a)| match a {
564            Arg::Value(s) => Some((k.clone(), s.lexical().to_string())),
565            Arg::Slice => None,
566        })
567        .collect()
568}
569
570/// A catalogue class as the store holds it now (CONTRACT-0.5.1 H2): its extent and its methods' cells are read in pages
571/// by slice, and by key, never by a read of a whole method.
572pub(crate) struct Class<'a, S: ?Sized> {
573    store: &'a S,
574    name: String,
575    now: String,
576    methods: BTreeMap<String, String>,
577}
578
579impl<'a, S: Store + ?Sized> Class<'a, S> {
580    /// The class `name` as of `now`; `None` when it is not bound.
581    pub(crate) fn open(store: &'a S, name: &str, now: &str) -> Result<Option<Self>, PublishError> {
582        let Some(hash) = store.resolve_class(name, now).map_err(err)? else { return Ok(None) };
583        let bytes = store.class(&hash).map_err(err)?.ok_or_else(|| err(format!("class {hash} is not stored")))?;
584        let cd = ClassDescriptor::from_json(&bytes).map_err(err)?;
585        Ok(Some(Class { store, name: name.to_string(), now: now.to_string(), methods: cd.methods }))
586    }
587
588    /// The next page of the members of method `method` with the arguments `open` open, after the sort key `after`, at most
589    /// `limit` (the store's slice pages, S2). A method the class lacks has no members.
590    pub(crate) fn page(
591        &self,
592        method: &str,
593        open: &[&str],
594        after: Option<&[u8]>,
595        limit: usize,
596    ) -> Result<Vec<SliceValue>, PublishError> {
597        let Some(fh) = self.methods.get(method) else { return Ok(Vec::new()) };
598        let args: datumesh_core::Args = open.iter().map(|k| (k.to_string(), Arg::Slice)).collect();
599        let cell = Cell { ns: self.name.clone(), fn_name: method.to_string(), fn_hash: fh.clone(), args };
600        let slice = Slice::from_value(&cell.to_value()).map_err(err)?;
601        self.store.slice_page(&slice, &self.now, after, limit).map_err(err)
602    }
603
604    /// The value of method `method` at each of `keys` (each a list of argument names and values), as the latest version
605    /// holds it now: `None` for a cell with no value (withdrawn, or never stored). One statement a call, of at most
606    /// `keys.len()` cells.
607    pub(crate) fn values(
608        &self,
609        method: &str,
610        keys: &[Vec<(String, Scalar)>],
611    ) -> Result<Vec<Option<String>>, PublishError> {
612        let Some(fh) = self.methods.get(method) else { return Ok(vec![None; keys.len()]) };
613        let ids: Vec<String> = keys
614            .iter()
615            .map(|k| {
616                let args: datumesh_core::Args = k.iter().map(|(n, s)| (n.clone(), Arg::Value(s.clone()))).collect();
617                Cell { ns: self.name.clone(), fn_name: method.to_string(), fn_hash: fh.clone(), args }.id()
618            })
619            .collect();
620        let refs: Vec<&str> = ids.iter().map(String::as_str).collect();
621        let versions = self.store.latest_many(&refs).map_err(err)?;
622        let live: Vec<&str> =
623            versions.iter().flatten().filter(|v| !v.withdrawn).map(|v| v.receipt_hash.as_str()).collect();
624        let mut bytes = self.store.receipts_many(&live).map_err(err)?.into_iter();
625        let mut out = Vec::with_capacity(versions.len());
626        for v in &versions {
627            let value = match v {
628                Some(v) if !v.withdrawn => match bytes.next().flatten() {
629                    Some(b) if !is_withdrawal(&b) => {
630                        let r = Receipt::from_json(&b).map_err(err)?;
631                        Some(r.value().lexical().to_string())
632                    }
633                    _ => None,
634                },
635                _ => None,
636            };
637            out.push(value);
638        }
639        Ok(out)
640    }
641}
642
643/// A lookup label as the key argument of `from_label`.
644pub(crate) fn label_scalars(l: &str) -> Vec<(String, Scalar)> {
645    vec![("label".to_string(), Scalar::from_lexical(Type::String, l).expect("a string is a scalar"))]
646}
647
648/// The key arguments of a subject, as scalars (for [`Class::values`]), and its rank when given.
649pub(crate) fn subject_scalars(k: &SubjectKey, rank: Option<usize>) -> Vec<(String, Scalar)> {
650    let mut out: Vec<(String, Scalar)> = [("domain", &k.0), ("thing", &k.1), ("measure", &k.2), ("region", &k.3)]
651        .into_iter()
652        .map(|(n, v)| (n.to_string(), Scalar::from_lexical(Type::String, v).expect("a string is a scalar")))
653        .collect();
654    if let Some(r) = rank {
655        out.push(("rank".into(), Scalar::from_lexical(Type::Number, &r.to_string()).expect("a number is a scalar")));
656    }
657    out
658}
659
660/// A cell of the catalogue: its method's full name and its arguments' lexical values.
661type CellKey = (String, BTreeMap<String, String>);
662
663/// A cell the job wants with a value: its method, its arguments, its value and its summary.
664struct Want {
665    fn_name: String,
666    args: BTreeMap<String, String>,
667    typ: &'static str,
668    value: String,
669    summary: &'static str,
670}
671
672impl Want {
673    fn key(&self) -> CellKey {
674        (self.fn_name.clone(), self.args.clone())
675    }
676
677    fn line(&self, licence: &str) -> String {
678        let args: Vec<(&str, &str, Value)> = self
679            .args
680            .iter()
681            .map(|(k, v)| (k.as_str(), if k == "rank" { "number" } else { "string" }, json!(v)))
682            .collect();
683        let value = if self.typ == "boolean" { json!(self.value == "true") } else { json!(self.value) };
684        cell_line(&self.fn_name, args, (self.typ, value), licence, self.summary)
685    }
686}
687
688fn subject_args(s: &SubjectKey) -> BTreeMap<String, String> {
689    [("domain", &s.0), ("thing", &s.1), ("measure", &s.2), ("region", &s.3)]
690        .into_iter()
691        .map(|(k, v)| (k.to_string(), v.clone()))
692        .collect()
693}
694
695/// The line that withdraws a cell (R1): its address and the reason; no value.
696fn withdrawal_line(fn_name: &str, args: &BTreeMap<String, String>, reason: &str, licence: &str) -> String {
697    let a: serde_json::Map<String, Value> = args
698        .iter()
699        .map(|(k, v)| {
700            let t = if k == "rank" { "number" } else { "string" };
701            (k.clone(), json!({"type": t, "value": v}))
702        })
703        .collect();
704    json!({"cell": {"fn": fn_name, "args": a}, "withdrawn": reason, "licence": licence,
705        "summary": "A catalogue cell that no longer has a value."})
706    .to_string()
707}
708
709/// The reason a valued cell the job no longer wants is withdrawn for (R10).
710fn withdrawal_reason(class: &str, fclass: &str, key: &CellKey, prior: &str, m: &Model) -> &'static str {
711    let (fn_name, args) = key;
712    let live = |s: &SubjectKey| m.subjects.contains_key(s);
713    if fn_name == &format!("{class}/from_label") {
714        return match parse_subject_key_any(prior) {
715            Some(s) if live(&s) => LABEL_NO_SUBJECT,
716            _ => GONE,
717        };
718    }
719    if fn_name == &format!("{class}/source") {
720        let s = subject_of_args(args);
721        return match s {
722            Some(s) if live(&s) => PAST,
723            _ => GONE,
724        };
725    }
726    let _ = fclass;
727    GONE
728}
729
730/// The subject a key encoding of any host's subject class names (a label's prior value).
731fn parse_subject_key_any(text: &str) -> Option<SubjectKey> {
732    let open = text.find('(')?;
733    let host = text[..open].strip_suffix("/catalog/subject")?;
734    parse_subject_key(host, text)
735}
736
737/// The cell lines of the catalogue as the store should hold them now (C3, C4, R10): every cell the job wants with its value, and
738/// a withdrawal for each valued cell it no longer wants. A cell that is not stored and is not wanted has no line.
739fn cell_lines<S: Store + ?Sized>(
740    host: &str,
741    licence: &str,
742    m: &Model,
743    store: &S,
744    now: &str,
745) -> Result<Vec<String>, PublishError> {
746    let class = subject_class(host);
747    let fclass = facet_class(host);
748    let mut wants: Vec<Want> = Vec::new();
749    for (s, sources) in &m.subjects {
750        let count = sources.len();
751        let key = |method: &str| format!("{class}/{method}");
752        wants.push(Want {
753            fn_name: key("exists"),
754            args: subject_args(s),
755            typ: "boolean",
756            value: "true".into(),
757            summary: "Whether a catalogue subject exists.",
758        });
759        wants.push(Want {
760            fn_name: key("label"),
761            args: subject_args(s),
762            typ: "string",
763            value: subject_label(s),
764            summary: "The label of a catalogue subject.",
765        });
766        wants.push(Want {
767            fn_name: key("sources"),
768            args: subject_args(s),
769            typ: "number",
770            value: count.to_string(),
771            summary: "The number of sources of a catalogue subject.",
772        });
773        for (i, src) in sources.iter().enumerate() {
774            let mut args = subject_args(s);
775            args.insert("rank".into(), (i + 1).to_string());
776            wants.push(Want {
777                fn_name: key("source"),
778                args,
779                typ: "string",
780                value: src.clone(),
781                summary: "The source of a rank of a catalogue subject.",
782            });
783        }
784    }
785    // The lookup: each label of a live subject that names only it. A label that names two is not stored (C3).
786    let mut by_label: BTreeMap<String, Vec<&SubjectKey>> = BTreeMap::new();
787    for s in m.subjects.keys() {
788        for l in lookup_labels(s) {
789            by_label.entry(l).or_default().push(s);
790        }
791    }
792    for (l, subjects) in &by_label {
793        if let [s] = subjects.as_slice() {
794            wants.push(Want {
795                fn_name: format!("{class}/from_label"),
796                args: [("label".to_string(), l.clone())].into_iter().collect(),
797                typ: "string",
798                value: subject_key_text(host, s),
799                summary: "The subject a label names.",
800            });
801        }
802    }
803    // The facet objects: each value of an entry.
804    for (facet, value) in m.facets.keys() {
805        let subjects = &m.facets[&(facet.clone(), value.clone())];
806        let fargs: BTreeMap<String, String> =
807            [("facet".to_string(), facet.clone()), ("value".to_string(), value.clone())].into_iter().collect();
808        wants.push(Want {
809            fn_name: format!("{fclass}/exists"),
810            args: fargs.clone(),
811            typ: "boolean",
812            value: "true".into(),
813            summary: "Whether a facet value exists.",
814        });
815        wants.push(Want {
816            fn_name: format!("{fclass}/label"),
817            args: fargs.clone(),
818            typ: "string",
819            value: facet_label(facet, value),
820            summary: "The label of a facet value.",
821        });
822        wants.push(Want {
823            fn_name: format!("{fclass}/subjects"),
824            args: fargs,
825            typ: "number",
826            value: subjects.len().to_string(),
827            summary: "The number of subjects that have a facet value.",
828        });
829    }
830    let mut lines: Vec<String> = wants.iter().map(|w| w.line(licence)).collect();
831    let wanted: BTreeSet<CellKey> = wants.iter().map(Want::key).collect();
832    // A valued cell the job no longer wants is withdrawn (R10); the stored cells are read a page at a time (H2).
833    let gone = |key: CellKey, prior: &str| -> Option<String> {
834        if wanted.contains(&key) {
835            return None;
836        }
837        let reason = withdrawal_reason(&class, &fclass, &key, prior, m);
838        Some(withdrawal_line(&key.0, &key.1, reason, licence))
839    };
840    if let Some(sc) = Class::open(store, &class, now)? {
841        let mut after: Option<Vec<u8>> = None;
842        loop {
843            let page = sc.page("exists", &SUBJECT_KEYS, after.as_deref(), PAGE)?;
844            after = page.last().map(|v| v.sort_key.clone());
845            let subjects: Vec<(SubjectKey, String)> = page
846                .iter()
847                .filter_map(|v| Some((subject_of_args(&lexical_args(&v.cell))?, v.value.lexical().to_string())))
848                .collect();
849            let keys: Vec<Vec<(String, Scalar)>> = subjects.iter().map(|(k, _)| subject_scalars(k, None)).collect();
850            for (k, value) in &subjects {
851                lines.extend(gone((format!("{class}/exists"), subject_args(k)), value));
852            }
853            // The lookup labels of these subjects, read by key (H2: never a slice of one argument).
854            let labels_of: Vec<String> = subjects.iter().flat_map(|(k, _)| lookup_labels(k)).collect();
855            for chunk in labels_of.chunks(PAGE) {
856                let lk: Vec<Vec<(String, Scalar)>> = chunk.iter().map(|l| label_scalars(l)).collect();
857                let values = sc.values("from_label", &lk)?;
858                for (l, v) in chunk.iter().zip(&values) {
859                    if let Some(v) = v {
860                        let args: BTreeMap<String, String> = [("label".to_string(), l.clone())].into_iter().collect();
861                        lines.extend(gone((format!("{class}/from_label"), args), v));
862                    }
863                }
864            }
865            let labels = sc.values("label", &keys)?;
866            let counts = sc.values("sources", &keys)?;
867            for (((k, _), label), count) in subjects.iter().zip(&labels).zip(&counts) {
868                if let Some(v) = label {
869                    lines.extend(gone((format!("{class}/label"), subject_args(k)), v));
870                }
871                if let Some(v) = count {
872                    lines.extend(gone((format!("{class}/sources"), subject_args(k)), v));
873                }
874            }
875            // The sources: each rank up to the count the store holds now (before this run's writes), rank by rank.
876            let stored_count = |i: usize| counts[i].as_deref().and_then(|c| c.parse::<usize>().ok()).unwrap_or(0);
877            let most = (0..subjects.len()).map(stored_count).max().unwrap_or(0).min(SOURCES_PER_SUBJECT);
878            for r in 1..=most {
879                let idx: Vec<usize> = (0..subjects.len()).filter(|&i| stored_count(i) >= r).collect();
880                let rank_keys: Vec<Vec<(String, Scalar)>> =
881                    idx.iter().map(|&i| subject_scalars(&subjects[i].0, Some(r))).collect();
882                let values = sc.values("source", &rank_keys)?;
883                for (&i, v) in idx.iter().zip(&values) {
884                    if let Some(v) = v {
885                        let mut args = subject_args(&subjects[i].0);
886                        args.insert("rank".into(), r.to_string());
887                        lines.extend(gone((format!("{class}/source"), args), v));
888                    }
889                }
890            }
891            if page.len() < PAGE {
892                break;
893            }
894        }
895    }
896    if let Some(fc) = Class::open(store, &fclass, now)? {
897        let mut after: Option<Vec<u8>> = None;
898        loop {
899            let page = fc.page("exists", &["facet", "value"], after.as_deref(), PAGE)?;
900            after = page.last().map(|v| v.sort_key.clone());
901            let facets: Vec<(BTreeMap<String, String>, String)> =
902                page.iter().map(|v| (lexical_args(&v.cell), v.value.lexical().to_string())).collect();
903            let keys: Vec<Vec<(String, Scalar)>> = facets
904                .iter()
905                .map(|(a, _)| {
906                    ["facet", "value"]
907                        .into_iter()
908                        .map(|n| {
909                            (n.to_string(), Scalar::from_lexical(Type::String, &a[n]).expect("a string is a scalar"))
910                        })
911                        .collect()
912                })
913                .collect();
914            for (a, value) in &facets {
915                lines.extend(gone((format!("{fclass}/exists"), a.clone()), value));
916            }
917            let labels = fc.values("label", &keys)?;
918            let subjects = fc.values("subjects", &keys)?;
919            for ((a, _), (label, n)) in facets.iter().zip(labels.iter().zip(&subjects)) {
920                if let Some(v) = label {
921                    lines.extend(gone((format!("{fclass}/label"), a.clone()), v));
922                }
923                if let Some(v) = n {
924                    lines.extend(gone((format!("{fclass}/subjects"), a.clone()), v));
925                }
926            }
927            if page.len() < PAGE {
928                break;
929            }
930        }
931    }
932    Ok(lines)
933}
934
935/// Runs the catalogue job (C5): reads the store's faceted entries as of the clock, and writes the classes, the cells and the rule
936/// as one publish under the mesh's key, with the job flag (C1). `licence` is the licence of the cells (`DATUMESH_LICENCE`).
937///
938/// A run over an unchanged catalogue writes nothing (`cells == 0`). Errors are publish's: a refusal names its line.
939pub fn catalog_build_with<S: Store + ?Sized>(
940    store: &S,
941    key: &SigningKey,
942    host: &str,
943    licence: &str,
944    opts: &PublishOptions,
945) -> Result<CatalogBuilt, PublishError> {
946    let now = opts.clock.now();
947    let cap =
948        crate::config::catalog_max_of(std::env::var("DATUMESH_CATALOG_MAX").ok()).map_err(|e| err(format!("{e}")))?;
949    let m = model(store, host, &now, cap)?;
950    let mut lines = vec![subject_class_line(host), facet_class_line(host), rule_line(host)];
951    lines.extend(cell_lines(host, licence, &m, store, &now)?);
952    lines.push(
953        json!({"cell": {"fn": rule_fn(host), "args": {}}, "value": {"blob": RULE_FILE, "media_type": "text/plain"},
954            "licence": licence, "summary": "The rule of the catalogue: how the sources of a subject are ranked."})
955        .to_string(),
956    );
957    let mut blobs = BTreeMap::new();
958    blobs.insert(RULE_FILE.to_string(), RULE.as_bytes().to_vec());
959    let owned = vec![host.to_string()];
960    let published = publish_job(store, key, host, &owned, lines, &blobs, opts)?;
961    Ok(CatalogBuilt { cells: published.versions as u64, subjects: m.subjects.len() as u64 })
962}