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::{fold_label, Arg, ClassDescriptor, FunctionDescriptor, Receipt, SigningKey, Withdrawal};
49use datumesh_store::{CatalogKind, Facets, Store};
50use serde_json::{json, Value};
51
52use crate::publish::{publish_job, PublishError, PublishOptions};
53
54/// The rule of the catalogue (C5, R5, R7): the text of the page `/catalog/rule` and of the blob `catalog/rule()`.
55pub(crate) const RULE: &str = "How the catalogue ranks the sources of a subject. \
56A source is level one when it is published under the domain of the data: its publisher host is that domain or one of its parent \
57domains. 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 \
58as relayed, or a view built on such a relay: a function or a class whose inputs read a relay, directly or through other views. \
59Every other source is level three. Within a level, a source whose class is a subclass of the class of another source, at any depth, \
60ranks above that parent class. Then the source whose name was first bound comes first, and a tie on the time of the first binding \
61is broken by the name, in ascending order. The rank one source of a subject is the first source in this order, and source of \
62rank 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 \
63are level one under their own hosts. The job that writes the catalogue applies this rule to the facets the publishers give. \
64Addresses: a cell address and a class name carry no facet value and no rank; a page path may carry a facet value, as \
65the domain pages of the catalogue do.";
66
67/// The file name of the rule text in the job's blobs.
68const RULE_FILE: &str = "rule.txt";
69
70/// The job's result: `cells` is the number of cell versions the run wrote (the classes, methods and bindings are not counted), and
71/// `subjects` the subjects that exist now.
72#[derive(Clone, Debug, PartialEq, Eq)]
73#[non_exhaustive]
74pub struct CatalogBuilt {
75    /// Cell versions written by the run.
76    pub cells: u64,
77    /// Subjects that exist as of the run.
78    pub subjects: u64,
79}
80
81/// A subject: its four keys, `(domain, thing, measure, region)`.
82pub(crate) type SubjectKey = (String, String, String, String);
83
84/// `<host>/catalog/subject`.
85pub(crate) fn subject_class(host: &str) -> String {
86    format!("{host}/catalog/subject")
87}
88
89/// `<host>/catalog/facet`.
90pub(crate) fn facet_class(host: &str) -> String {
91    format!("{host}/catalog/facet")
92}
93
94/// `<host>/catalog/rule`.
95pub(crate) fn rule_fn(host: &str) -> String {
96    format!("{host}/catalog/rule")
97}
98
99/// The key encoding of a subject (16.5: the names in ascending order, no space).
100pub(crate) fn subject_key_text(host: &str, k: &SubjectKey) -> String {
101    format!(r#"{}(domain:"{}",measure:"{}",region:"{}",thing:"{}")"#, subject_class(host), k.0, k.2, k.3, k.1)
102}
103
104/// The subject a key encoding names, when it is one of this host's subjects written as [`subject_key_text`] writes it.
105pub(crate) fn parse_subject_key(host: &str, text: &str) -> Option<SubjectKey> {
106    let body = text.strip_prefix(&format!("{}(", subject_class(host)))?.strip_suffix(')')?;
107    let mut got: BTreeMap<&str, &str> = BTreeMap::new();
108    for part in body.split(',') {
109        let (k, v) = part.split_once(':')?;
110        let v = v.strip_prefix('"')?.strip_suffix('"')?;
111        if v.contains('"') || got.insert(k, v).is_some() {
112            return None;
113        }
114    }
115    if got.len() != 4 {
116        return None;
117    }
118    Some((
119        got.get("domain")?.to_string(),
120        got.get("thing")?.to_string(),
121        got.get("measure")?.to_string(),
122        got.get("region")?.to_string(),
123    ))
124}
125
126/// A subject's words as its label (C3, C4): `_` as a space, the region written out, `none` left out.
127pub(crate) fn region_text(code: &str) -> String {
128    match code {
129        "ea" => "euro area".into(),
130        "gb" => "United Kingdom".into(),
131        "us" => "United States".into(),
132        other => other.replace('_', " "),
133    }
134}
135
136/// The label of a subject: measure, thing, region, domain, joined by ` · `.
137pub(crate) fn subject_label(k: &SubjectKey) -> String {
138    let parts = [k.2.replace('_', " "), k.1.replace('_', " "), region_text(&k.3), k.0.replace('_', " ")];
139    parts.into_iter().filter(|p| p != "none").collect::<Vec<_>>().join(" \u{b7} ")
140}
141
142/// The label of a facet object: its value with `_` as a space; a region's code written out.
143pub(crate) fn facet_label(facet: &str, value: &str) -> String {
144    if facet == "region" {
145        region_text(value)
146    } else {
147        value.replace('_', " ")
148    }
149}
150
151/// The folded lookup labels of a subject: the folded `label()`, and `<measure> <region>` and `<thing> <measure> <region>` where
152/// the region is not `none`, and the thing is not `none` for the last.
153fn lookup_labels(k: &SubjectKey) -> Vec<String> {
154    let mut out = vec![fold_label(&subject_label(k))];
155    if k.3 != "none" {
156        let m = k.2.replace('_', " ");
157        out.push(fold_label(&format!("{m} {}", region_text(&k.3))));
158        if k.1 != "none" {
159            out.push(fold_label(&format!("{} {m} {}", k.1.replace('_', " "), region_text(&k.3))));
160        }
161    }
162    out
163}
164
165/// The relay domain of a name `<host>/relay/<domain>/<more>`.
166pub(crate) fn relay_domain(host: &str, name: &str) -> Option<String> {
167    let rest = name.strip_prefix(host)?.strip_prefix('/')?;
168    let mut it = rest.split('/');
169    if it.next()? != "relay" {
170        return None;
171    }
172    let domain = it.next()?;
173    it.next()?;
174    Some(domain.to_string())
175}
176
177/// One cell line of the job: a stored cell of a method, its arguments as typed values, its value and its licence.
178fn cell_line(
179    fn_name: &str,
180    args: Vec<(&str, &str, Value)>,
181    value: (&str, Value),
182    licence: &str,
183    summary: &str,
184) -> String {
185    let a: serde_json::Map<String, Value> =
186        args.into_iter().map(|(k, t, v)| (k.to_string(), json!({"type": t, "value": v}))).collect();
187    json!({"cell": {"fn": fn_name, "args": a}, "value": {"type": value.0, "value": value.1},
188        "licence": licence, "summary": summary})
189    .to_string()
190}
191
192/// The key arguments of a method: strings that are not normalised (an absent `key_normalisation` is `none`, 16.4), not valid
193/// times.
194fn key_args(keys: &[&str]) -> serde_json::Map<String, Value> {
195    keys.iter().map(|k| (k.to_string(), json!({"type": "string", "valid": false}))).collect()
196}
197
198/// The keys of a class as its descriptor has them.
199fn class_keys(keys: &[&str]) -> serde_json::Map<String, Value> {
200    keys.iter().map(|k| (k.to_string(), json!({"key_normalisation": "none", "type": "string"}))).collect()
201}
202
203fn stored_hash(sig: &Value) -> String {
204    let text = json!({"code": {"body": "", "lang": "stored"}, "inputs": [], "signature": sig}).to_string();
205    FunctionDescriptor::from_json(text.as_bytes()).expect("a stored descriptor").hash()
206}
207
208/// The class `subject`'s descriptor, as an author writes it (K7: the methods inline, the extent is `exists`).
209fn subject_class_line(host: &str) -> String {
210    let class = subject_class(host);
211    let keys = ["domain", "thing", "measure", "region"];
212    let mut rank = key_args(&keys);
213    rank.insert("rank".into(), json!({"type": "number", "unit": "1", "valid": false, "default": "1"}));
214    let mut order_rank: Vec<&str> = keys.to_vec();
215    order_rank.push("rank");
216    let exists = json!({"args": key_args(&keys), "order": keys, "returns": "boolean"});
217    let label = json!({"args": key_args(&keys), "order": keys, "returns": "string"});
218    let sources = json!({"args": key_args(&keys), "order": keys, "returns": {"type": "number", "unit": "1"}});
219    let source = json!({"args": rank, "order": order_rank, "returns": "string"});
220    let from_label = json!({"args": {"label": {"key_normalisation": "label_fold", "type": "string", "valid": false}},
221        "order": ["label"], "returns": {"classes": [class], "type": "string"}});
222    let extent = stored_hash(&exists);
223    let descriptor = json!({
224        "keys": class_keys(&keys),
225        "order": keys,
226        "lookup": "from_label",
227        "methods": {"exists": {"stored": exists}, "from_label": {"stored": from_label}, "label": {"stored": label},
228            "source": {"stored": source}, "sources": {"stored": sources}},
229        "extent": {"keys": extent},
230        "steward": {"namespace": host, "process": format!("https://{host}/classes/change")},
231    });
232    json!({"class": class, "descriptor": descriptor}).to_string()
233}
234
235/// The class `facet`'s descriptor (C4).
236fn facet_class_line(host: &str) -> String {
237    let class = facet_class(host);
238    let keys = ["facet", "value"];
239    let exists = json!({"args": key_args(&keys), "order": keys, "returns": "boolean"});
240    let label = json!({"args": key_args(&keys), "order": keys, "returns": "string"});
241    let subjects = json!({"args": key_args(&keys), "order": keys, "returns": {"type": "number", "unit": "1"}});
242    let extent = stored_hash(&exists);
243    let descriptor = json!({
244        "keys": class_keys(&keys),
245        "order": keys,
246        "methods": {"exists": {"stored": exists}, "label": {"stored": label}, "subjects": {"stored": subjects}},
247        "extent": {"keys": extent},
248        "steward": {"namespace": host, "process": format!("https://{host}/classes/change")},
249    });
250    json!({"class": class, "descriptor": descriptor}).to_string()
251}
252
253/// The function `catalog/rule` (no argument, a blob).
254fn rule_line(host: &str) -> String {
255    json!({"function": rule_fn(host), "signature": {"args": {}, "order": [], "returns": "blob"}}).to_string()
256}
257
258/// The entries of the graph: what each name reads, and the relays it reaches (C5), memoised.
259struct Graph<'a, S: ?Sized> {
260    store: &'a S,
261    host: &'a str,
262    now: &'a str,
263    reads: BTreeMap<String, Vec<String>>,
264    reach: BTreeMap<String, BTreeSet<String>>,
265    visiting: BTreeSet<String>,
266}
267
268fn err<E: std::fmt::Display>(e: E) -> PublishError {
269    PublishError { line: 0, detail: format!("catalogue: {e}"), kind: crate::publish::PublishErrorKind::Line }
270}
271
272impl<S: Store + ?Sized> Graph<'_, S> {
273    /// The names a name reads: a function's inputs, or a class's methods' inputs.
274    fn reads_of(&mut self, name: &str) -> Result<Vec<String>, PublishError> {
275        if let Some(r) = self.reads.get(name) {
276            return Ok(r.clone());
277        }
278        let mut out: BTreeSet<String> = BTreeSet::new();
279        let mut fns: Vec<String> = Vec::new();
280        if let Some(b) = self.store.resolve_binding(name, self.now).map_err(err)? {
281            fns.push(b.fn_hash);
282        } else if let Some(c) = self.store.resolve_class(name, self.now).map_err(err)? {
283            if let Some(bytes) = self.store.class(&c).map_err(err)? {
284                let cd = ClassDescriptor::from_json(&bytes).map_err(err)?;
285                fns.extend(cd.methods.values().cloned());
286            }
287        }
288        for h in fns {
289            if let Some(bytes) = self.store.descriptor(&h) {
290                let fd = FunctionDescriptor::from_json(&bytes).map_err(err)?;
291                out.extend(fd.inputs);
292            }
293        }
294        let out: Vec<String> = out.into_iter().collect();
295        self.reads.insert(name.to_string(), out.clone());
296        Ok(out)
297    }
298
299    /// The relay domains a name reaches: its own, for a relay; else those of what it reads (through views, to any depth).
300    fn reach(&mut self, name: &str) -> Result<BTreeSet<String>, PublishError> {
301        if let Some(r) = self.reach.get(name) {
302            return Ok(r.clone());
303        }
304        if !self.visiting.insert(name.to_string()) {
305            return Ok(BTreeSet::new());
306        }
307        let mut out = BTreeSet::new();
308        if let Some(d) = relay_domain(self.host, name) {
309            out.insert(d);
310        } else {
311            for m in self.reads_of(name)? {
312                out.extend(self.reach(&m)?);
313            }
314        }
315        self.visiting.remove(name);
316        self.reach.insert(name.to_string(), out.clone());
317        Ok(out)
318    }
319}
320
321/// The most subjects one catalogue entry gives (R11): its facet product is cut to the first of this many, in the order of the
322/// product (domain, thing, measure, region).
323pub(crate) const SUBJECTS_PER_ENTRY: usize = 256;
324
325/// The most sources a subject keeps (R11): `sources()` is at most this, and the ranks past it have no cell.
326pub(crate) const SOURCES_PER_SUBJECT: usize = 20;
327
328/// The most stored cells of one method the job and the view read (the receipts of the latest versions, lowest cell id first).
329pub(crate) const STORED_CELLS_READ: usize = 1 << 20;
330
331/// The reason of a withdrawal of a subject or facet value that is gone (R10).
332pub(crate) const GONE: &str = "the subject is no longer in the catalogue";
333/// The reason of a withdrawal of a rank past the count of sources (R10).
334pub(crate) const PAST: &str = "rank past the count of sources";
335/// The reason of a withdrawal of a label that names no single subject any more (R10).
336pub(crate) const LABEL_NO_SUBJECT: &str = "the label names no single subject";
337
338/// An entry of the catalogue with a binding, as the rank sees it.
339struct Entry {
340    name: String,
341    first: String,
342    relay: bool,
343    view: bool,
344    reach: BTreeSet<String>,
345    /// The class hash of a class entry.
346    class: Option<String>,
347    /// The hashes of the classes the entry's class extends, at any depth (R5).
348    ancestors: BTreeSet<String>,
349}
350
351/// The live part of the catalogue: its subjects with their sources in rank order, and the facet objects with their subjects.
352struct Model {
353    subjects: BTreeMap<SubjectKey, Vec<String>>,
354    facets: BTreeMap<(String, String), BTreeSet<SubjectKey>>,
355}
356
357/// The parent classes of a class, at any depth (R5): the hashes its `parent` chain names.
358fn ancestors<S: Store + ?Sized>(store: &S, class_hash: &str) -> Result<BTreeSet<String>, PublishError> {
359    let mut out = BTreeSet::new();
360    let mut cur = class_hash.to_string();
361    // a class chain is acyclic (a parent is stored before its child); the bound is a guard
362    for _ in 0..64 {
363        let Some(bytes) = store.class(&cur).map_err(err)? else { break };
364        let cd = ClassDescriptor::from_json(&bytes).map_err(err)?;
365        let Some(p) = cd.parent else { break };
366        if !out.insert(p.clone()) {
367            break;
368        }
369        cur = p;
370    }
371    Ok(out)
372}
373
374/// The order of a subject's entries (R5): `base` is sorted by level, first binding and name; then an entry whose class is a
375/// subclass of another entry's class in the same level comes before it, the rest keeping the base order (a topological order
376/// with the base order as the priority, so an unrelated entry keeps its place). Returns the entries' indices.
377fn subclass_order(base: &[(u8, &str, &str, usize)], entries: &[Entry]) -> Vec<usize> {
378    let n = base.len();
379    let mut succ: Vec<Vec<usize>> = vec![Vec::new(); n];
380    let mut left = vec![0usize; n];
381    for i in 0..n {
382        let (li, _, _, ei) = base[i];
383        let anc = &entries[ei].ancestors;
384        if anc.is_empty() {
385            continue;
386        }
387        for j in 0..n {
388            let (lj, _, _, ej) = base[j];
389            if i == j || lj != li {
390                continue;
391            }
392            if entries[ej].class.as_ref().is_some_and(|c| anc.contains(c)) {
393                succ[i].push(j);
394                left[j] += 1;
395            }
396        }
397    }
398    let mut avail: BTreeSet<usize> = (0..n).filter(|&i| left[i] == 0).collect();
399    let mut done = vec![false; n];
400    let mut out = Vec::with_capacity(n);
401    while let Some(i) = avail.pop_first() {
402        done[i] = true;
403        out.push(base[i].3);
404        for &j in &succ[i] {
405            left[j] -= 1;
406            if left[j] == 0 && !done[j] {
407                avail.insert(j);
408            }
409        }
410    }
411    // a class chain is acyclic, so every entry is placed; the guard keeps any left in base order
412    out.extend((0..n).filter(|&i| !done[i]).map(|i| base[i].3));
413    out
414}
415
416fn model<S: Store + ?Sized>(store: &S, host: &str, now: &str) -> Result<Model, PublishError> {
417    let mut g = Graph { store, host, now, reads: BTreeMap::new(), reach: BTreeMap::new(), visiting: BTreeSet::new() };
418    let listed = store.catalog_entries_with_facets().map_err(err)?;
419    let mut entries: Vec<Entry> = Vec::new();
420    let mut facets: BTreeMap<(String, String), BTreeSet<SubjectKey>> = BTreeMap::new();
421    let mut members: BTreeMap<SubjectKey, Vec<usize>> = BTreeMap::new();
422    for e in &listed {
423        let keys = subject_keys(&e.facets);
424        let relay = relay_domain(host, &e.name).is_some();
425        let reach = if e.first_bound.is_some() { g.reach(&e.name)? } else { BTreeSet::new() };
426        let view = !relay && !reach.is_empty();
427        let class = if matches!(e.kind, CatalogKind::Class) { e.hash.clone() } else { None };
428        let ancestors = match &class {
429            Some(h) => ancestors(store, h)?,
430            None => BTreeSet::new(),
431        };
432        let idx = entries.len();
433        entries.push(Entry {
434            name: e.name.clone(),
435            first: e.first_bound.clone().unwrap_or_default(),
436            relay,
437            view,
438            reach,
439            class,
440            ancestors,
441        });
442        let bound = e.first_bound.is_some();
443        // A facet value's subjects: those of the entry that have the value under its facet (a frequency is no key, so every
444        // subject of an entry that carries it).
445        for (facet, values) in &e.facets {
446            for v in values {
447                let set = facets.entry((facet.clone(), v.clone())).or_default();
448                set.extend(keys.iter().filter(|k| key_has(facet, v, k)).cloned());
449            }
450        }
451        if bound {
452            for k in &keys {
453                members.entry(k.clone()).or_default().push(idx);
454            }
455        }
456    }
457    let mut subjects = BTreeMap::new();
458    for (k, idxs) in &members {
459        let mut domains: BTreeSet<String> = BTreeSet::new();
460        for &i in idxs {
461            let e = &entries[i];
462            if e.relay || e.view {
463                domains.extend(e.reach.iter().cloned());
464            }
465        }
466        let level = |i: usize| -> u8 {
467            let e = &entries[i];
468            if e.relay || e.view {
469                2
470            } else if domains.is_empty() {
471                1
472            } else {
473                let h = e.name.split('/').next().unwrap_or("");
474                if domains.iter().any(|d| h == d || h.ends_with(&format!(".{d}"))) {
475                    1
476                } else {
477                    3
478                }
479            }
480        };
481        let mut base: Vec<(u8, &str, &str, usize)> =
482            idxs.iter().map(|&i| (level(i), entries[i].first.as_str(), entries[i].name.as_str(), i)).collect();
483        base.sort();
484        let order = subclass_order(&base, &entries);
485        let names: Vec<String> = order.iter().take(SOURCES_PER_SUBJECT).map(|&i| entries[i].name.clone()).collect();
486        subjects.insert(k.clone(), names);
487    }
488    // Facet objects count only the subjects that exist (every subject of an entry is one of `members` when it is bound).
489    facets.retain(|_, set| {
490        set.retain(|k| subjects.contains_key(k));
491        true
492    });
493    Ok(Model { subjects, facets })
494}
495
496/// Whether a subject has the value `v` under the facet `facet`: its domain, thing, measure or region is `v`. A frequency is no
497/// key of a subject, so every subject of an entry that carries it has it.
498fn key_has(facet: &str, v: &str, k: &SubjectKey) -> bool {
499    match facet {
500        "domain" => k.0 == v,
501        "thing" => k.1 == v,
502        "measure" => k.2 == v,
503        "region" => k.3 == v,
504        _ => true,
505    }
506}
507
508/// The subjects of an entry's facets: the cross product of its domain, thing, measure and region names (C3), the first
509/// [`SUBJECTS_PER_ENTRY`] of it (R11).
510fn subject_keys(facets: &Facets) -> Vec<SubjectKey> {
511    let get = |k: &str| facets.get(k).cloned().unwrap_or_default();
512    let (d, t, m, r) = (get("domain"), get("thing"), get("measure"), get("region"));
513    let mut out = Vec::new();
514    'all: for dd in &d {
515        for tt in &t {
516            for mm in &m {
517                for rr in &r {
518                    if out.len() == SUBJECTS_PER_ENTRY {
519                        break 'all;
520                    }
521                    out.push((dd.clone(), tt.clone(), mm.clone(), rr.clone()));
522                }
523            }
524        }
525    }
526    out
527}
528
529/// One stored cell of a catalogue method: its args' lexical values, and the value's lexical form; `None` for a withdrawal
530/// (R1), the cell having no value from its `asof` on.
531pub(crate) type CellRow = (BTreeMap<String, String>, Option<String>);
532
533/// Whether stored receipt bytes are a withdrawal (a `withdrawn` member, R1).
534fn is_withdrawal(bytes: &[u8]) -> bool {
535    datumesh_core::json::parse(bytes).is_ok_and(|v| v.get("withdrawn").is_some())
536}
537
538/// The receipts of a method's stored cells, as the args' lexical values and the value's lexical form (`None` when withdrawn).
539pub(crate) fn cells_of<S: Store + ?Sized>(
540    store: &S,
541    class: &str,
542    class_hash: Option<&str>,
543    method: &str,
544) -> Result<Vec<CellRow>, PublishError> {
545    let Some(hash) = class_hash else { return Ok(Vec::new()) };
546    let bytes = store.class(hash).map_err(err)?.ok_or_else(|| err(format!("class {hash} is not stored")))?;
547    let cd = ClassDescriptor::from_json(&bytes).map_err(err)?;
548    let Some(fh) = cd.methods.get(method) else { return Ok(Vec::new()) };
549    let ns = class.to_string();
550    let rows = store.stored_receipts_of(&ns, method, fh, STORED_CELLS_READ).map_err(err)?;
551    let mut out = Vec::with_capacity(rows.len());
552    for bytes in rows {
553        let (cell, value) = if is_withdrawal(&bytes) {
554            let w = Withdrawal::from_json(&bytes).map_err(err)?;
555            (w.cell().clone(), None)
556        } else {
557            let r = Receipt::from_json(&bytes).map_err(err)?;
558            (r.cell().clone(), Some(r.value().lexical().to_string()))
559        };
560        let mut args = BTreeMap::new();
561        for (k, a) in &cell.args {
562            if let Arg::Value(s) = a {
563                args.insert(k.clone(), s.lexical().to_string());
564            }
565        }
566        out.push((args, value));
567    }
568    Ok(out)
569}
570
571pub(crate) fn subject_of_args(args: &BTreeMap<String, String>) -> Option<SubjectKey> {
572    Some((
573        args.get("domain")?.clone(),
574        args.get("thing")?.clone(),
575        args.get("measure")?.clone(),
576        args.get("region")?.clone(),
577    ))
578}
579
580/// A cell of the catalogue: its method's full name and its arguments' lexical values.
581type CellKey = (String, BTreeMap<String, String>);
582
583/// What the store holds now: the valued cells of the catalogue's methods, with their values (R10: the ones the job must
584/// withdraw when it no longer wants them).
585#[derive(Default)]
586struct Known {
587    valued: BTreeMap<CellKey, String>,
588}
589
590fn known<S: Store + ?Sized>(store: &S, host: &str, now: &str) -> Result<Known, PublishError> {
591    let subject_hash = store.resolve_class(&subject_class(host), now).map_err(err)?;
592    let facet_hash = store.resolve_class(&facet_class(host), now).map_err(err)?;
593    let mut k = Known::default();
594    let class = subject_class(host);
595    for method in ["exists", "label", "sources", "source", "from_label"] {
596        for (args, value) in cells_of(store, &class, subject_hash.as_deref(), method)? {
597            if let Some(v) = value {
598                k.valued.insert((format!("{class}/{method}"), args), v);
599            }
600        }
601    }
602    let fclass = facet_class(host);
603    for method in ["exists", "label", "subjects"] {
604        for (args, value) in cells_of(store, &fclass, facet_hash.as_deref(), method)? {
605            if let Some(v) = value {
606                k.valued.insert((format!("{fclass}/{method}"), args), v);
607            }
608        }
609    }
610    Ok(k)
611}
612
613/// A cell the job wants with a value: its method, its arguments, its value and its summary.
614struct Want {
615    fn_name: String,
616    args: BTreeMap<String, String>,
617    typ: &'static str,
618    value: String,
619    summary: &'static str,
620}
621
622impl Want {
623    fn key(&self) -> CellKey {
624        (self.fn_name.clone(), self.args.clone())
625    }
626
627    fn line(&self, licence: &str) -> String {
628        let args: Vec<(&str, &str, Value)> = self
629            .args
630            .iter()
631            .map(|(k, v)| (k.as_str(), if k == "rank" { "number" } else { "string" }, json!(v)))
632            .collect();
633        let value = if self.typ == "boolean" { json!(self.value == "true") } else { json!(self.value) };
634        cell_line(&self.fn_name, args, (self.typ, value), licence, self.summary)
635    }
636}
637
638fn subject_args(s: &SubjectKey) -> BTreeMap<String, String> {
639    [("domain", &s.0), ("thing", &s.1), ("measure", &s.2), ("region", &s.3)]
640        .into_iter()
641        .map(|(k, v)| (k.to_string(), v.clone()))
642        .collect()
643}
644
645/// The line that withdraws a cell (R1): its address and the reason; no value.
646fn withdrawal_line(fn_name: &str, args: &BTreeMap<String, String>, reason: &str, licence: &str) -> String {
647    let a: serde_json::Map<String, Value> = args
648        .iter()
649        .map(|(k, v)| {
650            let t = if k == "rank" { "number" } else { "string" };
651            (k.clone(), json!({"type": t, "value": v}))
652        })
653        .collect();
654    json!({"cell": {"fn": fn_name, "args": a}, "withdrawn": reason, "licence": licence,
655        "summary": "A catalogue cell that no longer has a value."})
656    .to_string()
657}
658
659/// The reason a valued cell the job no longer wants is withdrawn for (R10).
660fn withdrawal_reason(class: &str, fclass: &str, key: &CellKey, prior: &str, m: &Model) -> &'static str {
661    let (fn_name, args) = key;
662    let live = |s: &SubjectKey| m.subjects.contains_key(s);
663    if fn_name == &format!("{class}/from_label") {
664        return match parse_subject_key_any(prior) {
665            Some(s) if live(&s) => LABEL_NO_SUBJECT,
666            _ => GONE,
667        };
668    }
669    if fn_name == &format!("{class}/source") {
670        let s = subject_of_args(args);
671        return match s {
672            Some(s) if live(&s) => PAST,
673            _ => GONE,
674        };
675    }
676    let _ = fclass;
677    GONE
678}
679
680/// The subject a key encoding of any host's subject class names (a label's prior value).
681fn parse_subject_key_any(text: &str) -> Option<SubjectKey> {
682    let open = text.find('(')?;
683    let host = text[..open].strip_suffix("/catalog/subject")?;
684    parse_subject_key(host, text)
685}
686
687/// 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
688/// a withdrawal for each valued cell it no longer wants. A cell that is not stored and is not wanted has no line.
689fn cell_lines(host: &str, licence: &str, m: &Model, k: &Known) -> Vec<String> {
690    let class = subject_class(host);
691    let fclass = facet_class(host);
692    let mut wants: Vec<Want> = Vec::new();
693    for (s, sources) in &m.subjects {
694        let count = sources.len();
695        let key = |method: &str| format!("{class}/{method}");
696        wants.push(Want {
697            fn_name: key("exists"),
698            args: subject_args(s),
699            typ: "boolean",
700            value: "true".into(),
701            summary: "Whether a catalogue subject exists.",
702        });
703        wants.push(Want {
704            fn_name: key("label"),
705            args: subject_args(s),
706            typ: "string",
707            value: subject_label(s),
708            summary: "The label of a catalogue subject.",
709        });
710        wants.push(Want {
711            fn_name: key("sources"),
712            args: subject_args(s),
713            typ: "number",
714            value: count.to_string(),
715            summary: "The number of sources of a catalogue subject.",
716        });
717        for (i, src) in sources.iter().enumerate() {
718            let mut args = subject_args(s);
719            args.insert("rank".into(), (i + 1).to_string());
720            wants.push(Want {
721                fn_name: key("source"),
722                args,
723                typ: "string",
724                value: src.clone(),
725                summary: "The source of a rank of a catalogue subject.",
726            });
727        }
728    }
729    // The lookup: each label of a live subject that names only it. A label that names two is not stored (C3).
730    let mut by_label: BTreeMap<String, Vec<&SubjectKey>> = BTreeMap::new();
731    for s in m.subjects.keys() {
732        for l in lookup_labels(s) {
733            by_label.entry(l).or_default().push(s);
734        }
735    }
736    for (l, subjects) in &by_label {
737        if let [s] = subjects.as_slice() {
738            wants.push(Want {
739                fn_name: format!("{class}/from_label"),
740                args: [("label".to_string(), l.clone())].into_iter().collect(),
741                typ: "string",
742                value: subject_key_text(host, s),
743                summary: "The subject a label names.",
744            });
745        }
746    }
747    // The facet objects: each value of an entry.
748    for (facet, value) in m.facets.keys() {
749        let subjects = &m.facets[&(facet.clone(), value.clone())];
750        let fargs: BTreeMap<String, String> =
751            [("facet".to_string(), facet.clone()), ("value".to_string(), value.clone())].into_iter().collect();
752        wants.push(Want {
753            fn_name: format!("{fclass}/exists"),
754            args: fargs.clone(),
755            typ: "boolean",
756            value: "true".into(),
757            summary: "Whether a facet value exists.",
758        });
759        wants.push(Want {
760            fn_name: format!("{fclass}/label"),
761            args: fargs.clone(),
762            typ: "string",
763            value: facet_label(facet, value),
764            summary: "The label of a facet value.",
765        });
766        wants.push(Want {
767            fn_name: format!("{fclass}/subjects"),
768            args: fargs,
769            typ: "number",
770            value: subjects.len().to_string(),
771            summary: "The number of subjects that have a facet value.",
772        });
773    }
774    let mut lines: Vec<String> = wants.iter().map(|w| w.line(licence)).collect();
775    let wanted: BTreeSet<CellKey> = wants.iter().map(Want::key).collect();
776    for (key, prior) in &k.valued {
777        if wanted.contains(key) {
778            continue;
779        }
780        let reason = withdrawal_reason(&class, &fclass, key, prior, m);
781        lines.push(withdrawal_line(&key.0, &key.1, reason, licence));
782    }
783    lines
784}
785
786/// Runs the catalogue job (C5): reads the store's faceted entries as of the clock, and writes the classes, the cells and the rule
787/// as one publish under the mesh's key, with the job flag (C1). `licence` is the licence of the cells (`DATUMESH_LICENCE`).
788///
789/// A run over an unchanged catalogue writes nothing (`cells == 0`). Errors are publish's: a refusal names its line.
790pub fn catalog_build_with<S: Store + ?Sized>(
791    store: &S,
792    key: &SigningKey,
793    host: &str,
794    licence: &str,
795    opts: &PublishOptions,
796) -> Result<CatalogBuilt, PublishError> {
797    let now = opts.clock.now();
798    let m = model(store, host, &now)?;
799    let k = known(store, host, &now)?;
800    let mut lines = vec![subject_class_line(host), facet_class_line(host), rule_line(host)];
801    lines.extend(cell_lines(host, licence, &m, &k));
802    lines.push(
803        json!({"cell": {"fn": rule_fn(host), "args": {}}, "value": {"blob": RULE_FILE, "media_type": "text/plain"},
804            "licence": licence, "summary": "The rule of the catalogue: how the sources of a subject are ranked."})
805        .to_string(),
806    );
807    let mut blobs = BTreeMap::new();
808    blobs.insert(RULE_FILE.to_string(), RULE.as_bytes().to_vec());
809    let owned = vec![host.to_string()];
810    let published = publish_job(store, key, host, &owned, lines, &blobs, opts)?;
811    Ok(CatalogBuilt { cells: published.versions as u64, subjects: m.subjects.len() as u64 })
812}