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