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. Listed names are ranked by the same rule: a listed name is described here, not served here.";
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    // The listed names (L4): a listed name joins the subjects of its own listing, and is bound here "or listed"; its first
429    // time is the instant it was listed.
430    let mut listings: BTreeMap<String, datumesh_store::Listing> = BTreeMap::new();
431    for h in store.listed_hosts().map_err(err)? {
432        for l in store.listings_of(&h.host).map_err(err)? {
433            listings.insert(l.name.clone(), l);
434        }
435    }
436    let mut entries: Vec<Entry> = Vec::new();
437    let mut facets: BTreeMap<(String, String), BTreeSet<SubjectKey>> = BTreeMap::new();
438    let mut members: BTreeMap<SubjectKey, Vec<usize>> = BTreeMap::new();
439    // The subjects some name bound here is a member of (a listed-only subject is not).
440    let mut own: BTreeSet<SubjectKey> = BTreeSet::new();
441    for e in &listed {
442        let listing = listings.get(&e.name);
443        let keys: Vec<SubjectKey> = match listing {
444            Some(l) => l
445                .subjects
446                .iter()
447                .map(|s| (s.domain.clone(), s.thing.clone(), s.measure.clone(), s.region.clone()))
448                .collect(),
449            None => subject_keys(&e.facets),
450        };
451        let relay = relay_domain(host, &e.name).is_some();
452        let reach = if e.first_bound.is_some() { g.reach(&e.name)? } else { BTreeSet::new() };
453        let view = !relay && !reach.is_empty();
454        let class = if matches!(e.kind, CatalogKind::Class) { e.hash.clone() } else { None };
455        let ancestors = match &class {
456            Some(h) => ancestors(store, h)?,
457            None => BTreeSet::new(),
458        };
459        let idx = entries.len();
460        entries.push(Entry {
461            name: e.name.clone(),
462            first: match listing {
463                Some(l) => l.listed_at.clone(),
464                None => e.first_bound.clone().unwrap_or_default(),
465            },
466            relay,
467            view,
468            reach,
469            class,
470            ancestors,
471        });
472        let bound = e.first_bound.is_some() || listing.is_some();
473        if e.first_bound.is_some() {
474            own.extend(keys.iter().cloned());
475        }
476        // A facet value's subjects: those of the entry that have the value under its facet (a frequency is no key, so every
477        // subject of an entry that carries it).
478        for (facet, values) in &e.facets {
479            for v in values {
480                let set = facets.entry((facet.clone(), v.clone())).or_default();
481                set.extend(keys.iter().filter(|k| key_has(facet, v, k)).cloned());
482            }
483        }
484        if bound {
485            for k in &keys {
486                members.entry(k.clone()).or_default().push(idx);
487            }
488        }
489    }
490    let mut subjects = BTreeMap::new();
491    for (k, idxs) in &members {
492        let mut domains: BTreeSet<String> = BTreeSet::new();
493        for &i in idxs {
494            let e = &entries[i];
495            if e.relay || e.view {
496                domains.extend(e.reach.iter().cloned());
497            }
498        }
499        let level = |i: usize| -> u8 {
500            let e = &entries[i];
501            if e.relay || e.view {
502                2
503            } else if domains.is_empty() {
504                1
505            } else {
506                let h = e.name.split('/').next().unwrap_or("");
507                if domains.iter().any(|d| h == d || h.ends_with(&format!(".{d}"))) {
508                    1
509                } else {
510                    3
511                }
512            }
513        };
514        let mut base: Vec<(u8, &str, &str, usize)> =
515            idxs.iter().map(|&i| (level(i), entries[i].first.as_str(), entries[i].name.as_str(), i)).collect();
516        base.sort();
517        let order = subclass_order(&base, &entries);
518        let names: Vec<String> = order.iter().take(SOURCES_PER_SUBJECT).map(|&i| entries[i].name.clone()).collect();
519        subjects.insert(k.clone(), names);
520    }
521    // The catalogue lists at most `cap` subjects; the rest are not written. The subjects that hold a member bound here come
522    // first, in key order; the subjects that hold only listed names (B4) go after them, so they never push out this mesh's
523    // own.
524    if subjects.len() > cap {
525        tracing::warn!(target: "datumesh_http", subjects = subjects.len(), cap,
526            "catalogue job: the subjects are cut at DATUMESH_CATALOG_MAX");
527        let mut order: Vec<SubjectKey> = subjects.keys().cloned().collect();
528        order.sort_by(|a, b| (!own.contains(a)).cmp(&!own.contains(b)).then(a.cmp(b)));
529        let keep: BTreeSet<SubjectKey> = order.into_iter().take(cap).collect();
530        subjects.retain(|k, _| keep.contains(k));
531    }
532    // Facet objects count only the subjects that exist (every subject of an entry is one of `members` when it is bound).
533    facets.retain(|_, set| {
534        set.retain(|k| subjects.contains_key(k));
535        true
536    });
537    Ok(Model { subjects, facets })
538}
539
540/// The subjects a name bound here is a member of (its first binding is known): a listing creates the others (B4).
541pub(crate) fn bound_subjects<S: Store + ?Sized>(
542    store: &S,
543) -> Result<BTreeSet<datumesh_store::SubjectKeys>, datumesh_store::Error> {
544    let mut out = BTreeSet::new();
545    for e in store.catalog_entries_with_facets()? {
546        if e.first_bound.is_some() {
547            out.extend(
548                subject_keys(&e.facets)
549                    .into_iter()
550                    .map(|(d, t, m, r)| datumesh_store::SubjectKeys::new(&d, &t, &m, &r)),
551            );
552        }
553    }
554    Ok(out)
555}
556
557/// Whether a subject has the value `v` under the facet `facet`: its domain, thing, measure or region is `v`. A frequency is no
558/// key of a subject, so every subject of an entry that carries it has it.
559fn key_has(facet: &str, v: &str, k: &SubjectKey) -> bool {
560    match facet {
561        "domain" => k.0 == v,
562        "thing" => k.1 == v,
563        "measure" => k.2 == v,
564        "region" => k.3 == v,
565        _ => true,
566    }
567}
568
569/// The subjects of an entry's facets: the cross product of its domain, thing, measure and region names (C3), the first
570/// [`SUBJECTS_PER_ENTRY`] of it (R11).
571fn subject_keys(facets: &Facets) -> Vec<SubjectKey> {
572    let get = |k: &str| facets.get(k).cloned().unwrap_or_default();
573    let (d, t, m, r) = (get("domain"), get("thing"), get("measure"), get("region"));
574    let mut out = Vec::new();
575    'all: for dd in &d {
576        for tt in &t {
577            for mm in &m {
578                for rr in &r {
579                    if out.len() == SUBJECTS_PER_ENTRY {
580                        break 'all;
581                    }
582                    out.push((dd.clone(), tt.clone(), mm.clone(), rr.clone()));
583                }
584            }
585        }
586    }
587    out
588}
589
590/// Whether stored receipt bytes are a withdrawal (a `withdrawn` member, R1).
591fn is_withdrawal(bytes: &[u8]) -> bool {
592    datumesh_core::json::parse(bytes).is_ok_and(|v| v.get("withdrawn").is_some())
593}
594
595pub(crate) fn subject_of_args(args: &BTreeMap<String, String>) -> Option<SubjectKey> {
596    Some((
597        args.get("domain")?.clone(),
598        args.get("thing")?.clone(),
599        args.get("measure")?.clone(),
600        args.get("region")?.clone(),
601    ))
602}
603
604/// The lexical arguments of a cell (its value arguments; an open one is left out).
605pub(crate) fn lexical_args(cell: &Cell) -> BTreeMap<String, String> {
606    cell.args
607        .iter()
608        .filter_map(|(k, a)| match a {
609            Arg::Value(s) => Some((k.clone(), s.lexical().to_string())),
610            Arg::Slice => None,
611        })
612        .collect()
613}
614
615/// A catalogue class as the store holds it now (CONTRACT-0.5.1 H2): its extent and its methods' cells are read in pages
616/// by slice, and by key, never by a read of a whole method.
617pub(crate) struct Class<'a, S: ?Sized> {
618    store: &'a S,
619    name: String,
620    now: String,
621    methods: BTreeMap<String, String>,
622}
623
624impl<'a, S: Store + ?Sized> Class<'a, S> {
625    /// The class `name` as of `now`; `None` when it is not bound.
626    pub(crate) fn open(store: &'a S, name: &str, now: &str) -> Result<Option<Self>, PublishError> {
627        let Some(hash) = store.resolve_class(name, now).map_err(err)? else { return Ok(None) };
628        let bytes = store.class(&hash).map_err(err)?.ok_or_else(|| err(format!("class {hash} is not stored")))?;
629        let cd = ClassDescriptor::from_json(&bytes).map_err(err)?;
630        Ok(Some(Class { store, name: name.to_string(), now: now.to_string(), methods: cd.methods }))
631    }
632
633    /// The next page of the members of method `method` with the arguments `open` open, after the sort key `after`, at most
634    /// `limit` (the store's slice pages, S2). A method the class lacks has no members.
635    pub(crate) fn page(
636        &self,
637        method: &str,
638        open: &[&str],
639        after: Option<&[u8]>,
640        limit: usize,
641    ) -> Result<Vec<SliceValue>, PublishError> {
642        let Some(fh) = self.methods.get(method) else { return Ok(Vec::new()) };
643        let args: datumesh_core::Args = open.iter().map(|k| (k.to_string(), Arg::Slice)).collect();
644        let cell = Cell { ns: self.name.clone(), fn_name: method.to_string(), fn_hash: fh.clone(), args };
645        let slice = Slice::from_value(&cell.to_value()).map_err(err)?;
646        self.store.slice_page(&slice, &self.now, after, limit).map_err(err)
647    }
648
649    /// The value of method `method` at each of `keys` (each a list of argument names and values), as the latest version
650    /// holds it now: `None` for a cell with no value (withdrawn, or never stored). One statement a call, of at most
651    /// `keys.len()` cells.
652    pub(crate) fn values(
653        &self,
654        method: &str,
655        keys: &[Vec<(String, Scalar)>],
656    ) -> Result<Vec<Option<String>>, PublishError> {
657        let Some(fh) = self.methods.get(method) else { return Ok(vec![None; keys.len()]) };
658        let ids: Vec<String> = keys
659            .iter()
660            .map(|k| {
661                let args: datumesh_core::Args = k.iter().map(|(n, s)| (n.clone(), Arg::Value(s.clone()))).collect();
662                Cell { ns: self.name.clone(), fn_name: method.to_string(), fn_hash: fh.clone(), args }.id()
663            })
664            .collect();
665        let refs: Vec<&str> = ids.iter().map(String::as_str).collect();
666        let versions = self.store.latest_many(&refs).map_err(err)?;
667        let live: Vec<&str> =
668            versions.iter().flatten().filter(|v| !v.withdrawn).map(|v| v.receipt_hash.as_str()).collect();
669        let mut bytes = self.store.receipts_many(&live).map_err(err)?.into_iter();
670        let mut out = Vec::with_capacity(versions.len());
671        for v in &versions {
672            let value = match v {
673                Some(v) if !v.withdrawn => match bytes.next().flatten() {
674                    Some(b) if !is_withdrawal(&b) => {
675                        let r = Receipt::from_json(&b).map_err(err)?;
676                        Some(r.value().lexical().to_string())
677                    }
678                    _ => None,
679                },
680                _ => None,
681            };
682            out.push(value);
683        }
684        Ok(out)
685    }
686}
687
688/// A lookup label as the key argument of `from_label`.
689pub(crate) fn label_scalars(l: &str) -> Vec<(String, Scalar)> {
690    vec![("label".to_string(), Scalar::from_lexical(Type::String, l).expect("a string is a scalar"))]
691}
692
693/// The key arguments of a subject, as scalars (for [`Class::values`]), and its rank when given.
694pub(crate) fn subject_scalars(k: &SubjectKey, rank: Option<usize>) -> Vec<(String, Scalar)> {
695    let mut out: Vec<(String, Scalar)> = [("domain", &k.0), ("thing", &k.1), ("measure", &k.2), ("region", &k.3)]
696        .into_iter()
697        .map(|(n, v)| (n.to_string(), Scalar::from_lexical(Type::String, v).expect("a string is a scalar")))
698        .collect();
699    if let Some(r) = rank {
700        out.push(("rank".into(), Scalar::from_lexical(Type::Number, &r.to_string()).expect("a number is a scalar")));
701    }
702    out
703}
704
705/// A cell of the catalogue: its method's full name and its arguments' lexical values.
706type CellKey = (String, BTreeMap<String, String>);
707
708/// A cell the job wants with a value: its method, its arguments, its value and its summary.
709struct Want {
710    fn_name: String,
711    args: BTreeMap<String, String>,
712    typ: &'static str,
713    value: String,
714    summary: &'static str,
715}
716
717impl Want {
718    fn key(&self) -> CellKey {
719        (self.fn_name.clone(), self.args.clone())
720    }
721
722    fn line(&self, licence: &str) -> String {
723        let args: Vec<(&str, &str, Value)> = self
724            .args
725            .iter()
726            .map(|(k, v)| (k.as_str(), if k == "rank" { "number" } else { "string" }, json!(v)))
727            .collect();
728        let value = if self.typ == "boolean" { json!(self.value == "true") } else { json!(self.value) };
729        cell_line(&self.fn_name, args, (self.typ, value), licence, self.summary)
730    }
731}
732
733fn subject_args(s: &SubjectKey) -> BTreeMap<String, String> {
734    [("domain", &s.0), ("thing", &s.1), ("measure", &s.2), ("region", &s.3)]
735        .into_iter()
736        .map(|(k, v)| (k.to_string(), v.clone()))
737        .collect()
738}
739
740/// The line that withdraws a cell (R1): its address and the reason; no value.
741fn withdrawal_line(fn_name: &str, args: &BTreeMap<String, String>, reason: &str, licence: &str) -> String {
742    let a: serde_json::Map<String, Value> = args
743        .iter()
744        .map(|(k, v)| {
745            let t = if k == "rank" { "number" } else { "string" };
746            (k.clone(), json!({"type": t, "value": v}))
747        })
748        .collect();
749    json!({"cell": {"fn": fn_name, "args": a}, "withdrawn": reason, "licence": licence,
750        "summary": "A catalogue cell that no longer has a value."})
751    .to_string()
752}
753
754/// The reason a valued cell the job no longer wants is withdrawn for (R10).
755fn withdrawal_reason(class: &str, fclass: &str, key: &CellKey, prior: &str, m: &Model) -> &'static str {
756    let (fn_name, args) = key;
757    let live = |s: &SubjectKey| m.subjects.contains_key(s);
758    if fn_name == &format!("{class}/from_label") {
759        return match parse_subject_key_any(prior) {
760            Some(s) if live(&s) => LABEL_NO_SUBJECT,
761            _ => GONE,
762        };
763    }
764    if fn_name == &format!("{class}/source") {
765        let s = subject_of_args(args);
766        return match s {
767            Some(s) if live(&s) => PAST,
768            _ => GONE,
769        };
770    }
771    let _ = fclass;
772    GONE
773}
774
775/// The subject a key encoding of any host's subject class names (a label's prior value).
776fn parse_subject_key_any(text: &str) -> Option<SubjectKey> {
777    let open = text.find('(')?;
778    let host = text[..open].strip_suffix("/catalog/subject")?;
779    parse_subject_key(host, text)
780}
781
782/// 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
783/// a withdrawal for each valued cell it no longer wants. A cell that is not stored and is not wanted has no line.
784fn cell_lines<S: Store + ?Sized>(
785    host: &str,
786    licence: &str,
787    m: &Model,
788    store: &S,
789    now: &str,
790) -> Result<Vec<String>, PublishError> {
791    let class = subject_class(host);
792    let fclass = facet_class(host);
793    let mut wants: Vec<Want> = Vec::new();
794    for (s, sources) in &m.subjects {
795        let count = sources.len();
796        let key = |method: &str| format!("{class}/{method}");
797        wants.push(Want {
798            fn_name: key("exists"),
799            args: subject_args(s),
800            typ: "boolean",
801            value: "true".into(),
802            summary: "Whether a catalogue subject exists.",
803        });
804        wants.push(Want {
805            fn_name: key("label"),
806            args: subject_args(s),
807            typ: "string",
808            value: subject_label(s),
809            summary: "The label of a catalogue subject.",
810        });
811        wants.push(Want {
812            fn_name: key("sources"),
813            args: subject_args(s),
814            typ: "number",
815            value: count.to_string(),
816            summary: "The number of sources of a catalogue subject.",
817        });
818        for (i, src) in sources.iter().enumerate() {
819            let mut args = subject_args(s);
820            args.insert("rank".into(), (i + 1).to_string());
821            wants.push(Want {
822                fn_name: key("source"),
823                args,
824                typ: "string",
825                value: src.clone(),
826                summary: "The source of a rank of a catalogue subject.",
827            });
828        }
829    }
830    // The lookup: each label of a live subject that names only it. A label that names two is not stored (C3).
831    let mut by_label: BTreeMap<String, Vec<&SubjectKey>> = BTreeMap::new();
832    for s in m.subjects.keys() {
833        for l in lookup_labels(s) {
834            by_label.entry(l).or_default().push(s);
835        }
836    }
837    for (l, subjects) in &by_label {
838        if let [s] = subjects.as_slice() {
839            wants.push(Want {
840                fn_name: format!("{class}/from_label"),
841                args: [("label".to_string(), l.clone())].into_iter().collect(),
842                typ: "string",
843                value: subject_key_text(host, s),
844                summary: "The subject a label names.",
845            });
846        }
847    }
848    // The facet objects: each value of an entry.
849    for (facet, value) in m.facets.keys() {
850        let subjects = &m.facets[&(facet.clone(), value.clone())];
851        let fargs: BTreeMap<String, String> =
852            [("facet".to_string(), facet.clone()), ("value".to_string(), value.clone())].into_iter().collect();
853        wants.push(Want {
854            fn_name: format!("{fclass}/exists"),
855            args: fargs.clone(),
856            typ: "boolean",
857            value: "true".into(),
858            summary: "Whether a facet value exists.",
859        });
860        wants.push(Want {
861            fn_name: format!("{fclass}/label"),
862            args: fargs.clone(),
863            typ: "string",
864            value: facet_label(facet, value),
865            summary: "The label of a facet value.",
866        });
867        wants.push(Want {
868            fn_name: format!("{fclass}/subjects"),
869            args: fargs,
870            typ: "number",
871            value: subjects.len().to_string(),
872            summary: "The number of subjects that have a facet value.",
873        });
874    }
875    let mut lines: Vec<String> = wants.iter().map(|w| w.line(licence)).collect();
876    let wanted: BTreeSet<CellKey> = wants.iter().map(Want::key).collect();
877    // A valued cell the job no longer wants is withdrawn (R10); the stored cells are read a page at a time (H2).
878    let gone = |key: CellKey, prior: &str| -> Option<String> {
879        if wanted.contains(&key) {
880            return None;
881        }
882        let reason = withdrawal_reason(&class, &fclass, &key, prior, m);
883        Some(withdrawal_line(&key.0, &key.1, reason, licence))
884    };
885    if let Some(sc) = Class::open(store, &class, now)? {
886        let mut after: Option<Vec<u8>> = None;
887        loop {
888            let page = sc.page("exists", &SUBJECT_KEYS, after.as_deref(), PAGE)?;
889            after = page.last().map(|v| v.sort_key.clone());
890            let subjects: Vec<(SubjectKey, String)> = page
891                .iter()
892                .filter_map(|v| Some((subject_of_args(&lexical_args(&v.cell))?, v.value.lexical().to_string())))
893                .collect();
894            let keys: Vec<Vec<(String, Scalar)>> = subjects.iter().map(|(k, _)| subject_scalars(k, None)).collect();
895            for (k, value) in &subjects {
896                lines.extend(gone((format!("{class}/exists"), subject_args(k)), value));
897            }
898            // The lookup labels of these subjects, read by key (H2: never a slice of one argument).
899            let labels_of: Vec<String> = subjects.iter().flat_map(|(k, _)| lookup_labels(k)).collect();
900            for chunk in labels_of.chunks(PAGE) {
901                let lk: Vec<Vec<(String, Scalar)>> = chunk.iter().map(|l| label_scalars(l)).collect();
902                let values = sc.values("from_label", &lk)?;
903                for (l, v) in chunk.iter().zip(&values) {
904                    if let Some(v) = v {
905                        let args: BTreeMap<String, String> = [("label".to_string(), l.clone())].into_iter().collect();
906                        lines.extend(gone((format!("{class}/from_label"), args), v));
907                    }
908                }
909            }
910            let labels = sc.values("label", &keys)?;
911            let counts = sc.values("sources", &keys)?;
912            for (((k, _), label), count) in subjects.iter().zip(&labels).zip(&counts) {
913                if let Some(v) = label {
914                    lines.extend(gone((format!("{class}/label"), subject_args(k)), v));
915                }
916                if let Some(v) = count {
917                    lines.extend(gone((format!("{class}/sources"), subject_args(k)), v));
918                }
919            }
920            // The sources: each rank up to the count the store holds now (before this run's writes), rank by rank.
921            let stored_count = |i: usize| counts[i].as_deref().and_then(|c| c.parse::<usize>().ok()).unwrap_or(0);
922            let most = (0..subjects.len()).map(stored_count).max().unwrap_or(0).min(SOURCES_PER_SUBJECT);
923            for r in 1..=most {
924                let idx: Vec<usize> = (0..subjects.len()).filter(|&i| stored_count(i) >= r).collect();
925                let rank_keys: Vec<Vec<(String, Scalar)>> =
926                    idx.iter().map(|&i| subject_scalars(&subjects[i].0, Some(r))).collect();
927                let values = sc.values("source", &rank_keys)?;
928                for (&i, v) in idx.iter().zip(&values) {
929                    if let Some(v) = v {
930                        let mut args = subject_args(&subjects[i].0);
931                        args.insert("rank".into(), r.to_string());
932                        lines.extend(gone((format!("{class}/source"), args), v));
933                    }
934                }
935            }
936            if page.len() < PAGE {
937                break;
938            }
939        }
940    }
941    if let Some(fc) = Class::open(store, &fclass, now)? {
942        let mut after: Option<Vec<u8>> = None;
943        loop {
944            let page = fc.page("exists", &["facet", "value"], after.as_deref(), PAGE)?;
945            after = page.last().map(|v| v.sort_key.clone());
946            let facets: Vec<(BTreeMap<String, String>, String)> =
947                page.iter().map(|v| (lexical_args(&v.cell), v.value.lexical().to_string())).collect();
948            let keys: Vec<Vec<(String, Scalar)>> = facets
949                .iter()
950                .map(|(a, _)| {
951                    ["facet", "value"]
952                        .into_iter()
953                        .map(|n| {
954                            (n.to_string(), Scalar::from_lexical(Type::String, &a[n]).expect("a string is a scalar"))
955                        })
956                        .collect()
957                })
958                .collect();
959            for (a, value) in &facets {
960                lines.extend(gone((format!("{fclass}/exists"), a.clone()), value));
961            }
962            let labels = fc.values("label", &keys)?;
963            let subjects = fc.values("subjects", &keys)?;
964            for ((a, _), (label, n)) in facets.iter().zip(labels.iter().zip(&subjects)) {
965                if let Some(v) = label {
966                    lines.extend(gone((format!("{fclass}/label"), a.clone()), v));
967                }
968                if let Some(v) = n {
969                    lines.extend(gone((format!("{fclass}/subjects"), a.clone()), v));
970                }
971            }
972            if page.len() < PAGE {
973                break;
974            }
975        }
976    }
977    Ok(lines)
978}
979
980/// Runs the catalogue job (C5): reads the store's faceted entries as of the clock, and writes the classes, the cells and the rule
981/// as one publish under the mesh's key, with the job flag (C1). `licence` is the licence of the cells (`DATUMESH_LICENCE`).
982///
983/// A run over an unchanged catalogue writes nothing (`cells == 0`). Errors are publish's: a refusal names its line.
984pub fn catalog_build_with<S: Store + ?Sized>(
985    store: &S,
986    key: &SigningKey,
987    host: &str,
988    licence: &str,
989    opts: &PublishOptions,
990) -> Result<CatalogBuilt, PublishError> {
991    let now = opts.clock.now();
992    let cap =
993        crate::config::catalog_max_of(std::env::var("DATUMESH_CATALOG_MAX").ok()).map_err(|e| err(format!("{e}")))?;
994    let m = model(store, host, &now, cap)?;
995    let mut lines = vec![subject_class_line(host), facet_class_line(host), rule_line(host)];
996    lines.extend(cell_lines(host, licence, &m, store, &now)?);
997    lines.push(
998        json!({"cell": {"fn": rule_fn(host), "args": {}}, "value": {"blob": RULE_FILE, "media_type": "text/plain"},
999            "licence": licence, "summary": "The rule of the catalogue: how the sources of a subject are ranked."})
1000        .to_string(),
1001    );
1002    let mut blobs = BTreeMap::new();
1003    blobs.insert(RULE_FILE.to_string(), RULE.as_bytes().to_vec());
1004    let owned = vec![host.to_string()];
1005    let published = publish_job(store, key, host, &owned, lines, &blobs, opts)?;
1006    Ok(CatalogBuilt { cells: published.versions as u64, subjects: m.subjects.len() as u64 })
1007}