1use 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
54pub(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
67const RULE_FILE: &str = "rule.txt";
69
70#[derive(Clone, Debug, PartialEq, Eq)]
73#[non_exhaustive]
74pub struct CatalogBuilt {
75 pub cells: u64,
77 pub subjects: u64,
79}
80
81pub(crate) type SubjectKey = (String, String, String, String);
83
84pub(crate) fn subject_class(host: &str) -> String {
86 format!("{host}/catalog/subject")
87}
88
89pub(crate) fn facet_class(host: &str) -> String {
91 format!("{host}/catalog/facet")
92}
93
94pub(crate) fn rule_fn(host: &str) -> String {
96 format!("{host}/catalog/rule")
97}
98
99pub(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
104pub(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
126pub(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
136pub(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
142pub(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
151fn 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
165pub(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
177fn 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
192fn 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
198fn 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
208fn 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
235fn 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
253fn rule_line(host: &str) -> String {
255 json!({"function": rule_fn(host), "signature": {"args": {}, "order": [], "returns": "blob"}}).to_string()
256}
257
258struct 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 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 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
321pub(crate) const SUBJECTS_PER_ENTRY: usize = 256;
324
325pub(crate) const SOURCES_PER_SUBJECT: usize = 20;
327
328pub(crate) const STORED_CELLS_READ: usize = 1 << 20;
330
331pub(crate) const GONE: &str = "the subject is no longer in the catalogue";
333pub(crate) const PAST: &str = "rank past the count of sources";
335pub(crate) const LABEL_NO_SUBJECT: &str = "the label names no single subject";
337
338struct Entry {
340 name: String,
341 first: String,
342 relay: bool,
343 view: bool,
344 reach: BTreeSet<String>,
345 class: Option<String>,
347 ancestors: BTreeSet<String>,
349}
350
351struct Model {
353 subjects: BTreeMap<SubjectKey, Vec<String>>,
354 facets: BTreeMap<(String, String), BTreeSet<SubjectKey>>,
355}
356
357fn 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 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
374fn 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 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 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 facets.retain(|_, set| {
490 set.retain(|k| subjects.contains_key(k));
491 true
492 });
493 Ok(Model { subjects, facets })
494}
495
496fn 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
508fn 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
529pub(crate) type CellRow = (BTreeMap<String, String>, Option<String>);
532
533fn is_withdrawal(bytes: &[u8]) -> bool {
535 datumesh_core::json::parse(bytes).is_ok_and(|v| v.get("withdrawn").is_some())
536}
537
538pub(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
580type CellKey = (String, BTreeMap<String, String>);
582
583#[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
613struct 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
645fn 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
659fn 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
680fn 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
687fn 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 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 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
786pub 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}