1use 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
56pub(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
69const RULE_FILE: &str = "rule.txt";
71
72#[derive(Clone, Debug, PartialEq, Eq)]
75#[non_exhaustive]
76pub struct CatalogBuilt {
77 pub cells: u64,
79 pub subjects: u64,
81}
82
83pub(crate) type SubjectKey = (String, String, String, String);
85
86pub(crate) fn subject_class(host: &str) -> String {
88 format!("{host}/catalog/subject")
89}
90
91pub(crate) fn facet_class(host: &str) -> String {
93 format!("{host}/catalog/facet")
94}
95
96pub(crate) fn rule_fn(host: &str) -> String {
98 format!("{host}/catalog/rule")
99}
100
101pub(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
106pub(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
128pub(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
138pub(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
144pub(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
153pub(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
167pub(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
179fn 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
194fn 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
200fn 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
210fn 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
237fn 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
255fn rule_line(host: &str) -> String {
257 json!({"function": rule_fn(host), "signature": {"args": {}, "order": [], "returns": "blob"}}).to_string()
258}
259
260struct 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 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 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
323pub(crate) const SUBJECTS_PER_ENTRY: usize = 256;
326
327pub(crate) const SOURCES_PER_SUBJECT: usize = 20;
329
330pub(crate) const PAGE: usize = 1000;
333
334pub const DEFAULT_CATALOG_MAX: usize = 100_000;
336
337pub(crate) const SUBJECT_KEYS: [&str; 4] = ["domain", "thing", "measure", "region"];
339
340pub(crate) const GONE: &str = "the subject is no longer in the catalogue";
342pub(crate) const PAST: &str = "rank past the count of sources";
344pub(crate) const LABEL_NO_SUBJECT: &str = "the label names no single subject";
346
347struct Entry {
349 name: String,
350 first: String,
351 relay: bool,
352 view: bool,
353 reach: BTreeSet<String>,
354 class: Option<String>,
356 ancestors: BTreeSet<String>,
358}
359
360struct Model {
362 subjects: BTreeMap<SubjectKey, Vec<String>>,
363 facets: BTreeMap<(String, String), BTreeSet<SubjectKey>>,
364}
365
366fn 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 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
383fn 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 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 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 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 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 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 facets.retain(|_, set| {
534 set.retain(|k| subjects.contains_key(k));
535 true
536 });
537 Ok(Model { subjects, facets })
538}
539
540pub(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
557fn 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
569fn 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
590fn 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
604pub(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
615pub(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 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 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 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
688pub(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
693pub(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
705type CellKey = (String, BTreeMap<String, String>);
707
708struct 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
740fn 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
754fn 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
775fn 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
782fn 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 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 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 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 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 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
980pub 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}