Skip to main content

datumesh_store/
listings.rs

1//! Listings (0.7.0, CONTRACT-http-listing L3): the functions of another mesh that this mesh lists,
2//! as descriptions only. A listing is not a binding: `name_bindings`, the namespace checks, `cells`,
3//! `receipts` and `versions` are never touched by it.
4//!
5//! * `listings`: the present state only, one row per name (no history). [`Store::put_listing`]
6//!   writes nothing when the row is unchanged.
7//! * `listed_hosts`: one row per listed host, with the day it was last seen and the instant it was
8//!   first unreachable (none while reachable).
9//!
10//! A listing's descriptor is also kept in `descriptors` (so `/descriptor/<hash>` answers it), and the
11//! listing has a catalogue entry of source [`CatalogSource::Listed`](crate::CatalogSource::Listed)
12//! (kind function, `signed_by` the host), which the store writes and removes with the listing.
13//!
14//! [`Store::put_listing`]: crate::Store::put_listing
15
16use std::collections::{BTreeMap, BTreeSet};
17
18use datumesh_core::json::{self, Value};
19use datumesh_core::lexical::{check_date, check_dns_name, check_function_name, check_hex, check_instant, check_name};
20
21use crate::catalogue::{facets_json, invalid, Facets, FACET_MAX};
22use crate::error::Result;
23
24/// The most subjects one listing names (as the catalogue job keeps at most 256 subjects of one entry).
25pub const LISTING_SUBJECTS_MAX: usize = 256;
26
27/// The four keys of a catalogue subject (`<host>/catalog/subject`): domain, thing, measure, region.
28/// Ordered by the keys in that order.
29#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
30pub struct SubjectKeys {
31    /// The `domain` key.
32    pub domain: String,
33    /// The `thing` key.
34    pub thing: String,
35    /// The `measure` key.
36    pub measure: String,
37    /// The `region` key.
38    pub region: String,
39}
40
41impl SubjectKeys {
42    /// The subject of these four keys.
43    pub fn new(domain: &str, thing: &str, measure: &str, region: &str) -> SubjectKeys {
44        SubjectKeys {
45            domain: domain.to_string(),
46            thing: thing.to_string(),
47            measure: measure.to_string(),
48            region: region.to_string(),
49        }
50    }
51}
52
53/// One listed function: a name of another mesh, its descriptor and the subjects that mesh's own
54/// catalogue puts it in.
55#[derive(Clone, Debug, PartialEq, Eq)]
56pub struct Listing {
57    /// The listed host (a DNS name; the first segment of `name`).
58    pub host: String,
59    /// The full function name, under `<host>/`.
60    pub name: String,
61    /// The function hash: the hash of `descriptor`.
62    pub fn_hash: String,
63    /// The subjects the host's catalogue puts the name in: 1 to [`LISTING_SUBJECTS_MAX`], ascending
64    /// and unique, each key a name (SPEC 2.2) of at most 32 bytes.
65    pub subjects: Vec<SubjectKeys>,
66    /// The descriptor's bytes as fetched.
67    pub descriptor: Vec<u8>,
68    /// The key id of the key document that verified the host (1 to 256 bytes).
69    pub key_id: String,
70    /// The label of the name in the host's catalogue (at most 120 bytes; may be empty).
71    pub label: String,
72    /// Its description (1 to 1024 bytes).
73    pub description: String,
74    /// When the row was last written (an instant): the run's time of the insert or of the last change.
75    pub fetched_at: String,
76    /// When the name was first listed (an instant). Kept by the store across changes: a change
77    /// ignores the given value and keeps the stored one.
78    pub listed_at: String,
79}
80
81/// What [`Store::put_listing`](crate::Store::put_listing) did.
82#[derive(Clone, Copy, Debug, PartialEq, Eq)]
83pub enum ListingWrite {
84    /// The row was already exactly this (every field but `fetched_at` and `listed_at`): nothing was
85    /// written, not even `fetched_at`.
86    Unchanged,
87    /// A new row.
88    Inserted,
89    /// The row replaced one of the same name that differed.
90    Changed,
91}
92
93/// The state of one listed host.
94#[derive(Clone, Debug, PartialEq, Eq)]
95pub struct ListedHost {
96    /// The host.
97    pub host: String,
98    /// The day (`YYYY-MM-DD`) of the last successful fetch; `None` before the first.
99    pub last_seen: Option<String>,
100    /// The instant of the first failed run after the last success; `None` while reachable.
101    pub unreachable_since: Option<String>,
102}
103
104// ---- Shared checks and forms (both backends) ----------------------------------------------------
105
106/// A listed name's bounds and forms (the checks [`Store::put_listing`](crate::Store::put_listing) lists).
107/// Nothing is written before all of them pass.
108pub(crate) fn check_listing(l: &Listing) -> Result<()> {
109    check_dns_name(&l.host, "host")?;
110    check_function_name(&l.name, "name")?;
111    if l.name.split_once('/').map(|(host, _)| host) != Some(l.host.as_str()) {
112        return Err(invalid("name", "a listed name is under its host"));
113    }
114    check_hex(&l.fn_hash, 64, "fn_hash")?;
115    let hash = datumesh_core::function_hash(&l.descriptor)?;
116    if hash != l.fn_hash {
117        return Err(invalid("descriptor", "the descriptor does not hash to fn_hash"));
118    }
119    if l.subjects.is_empty() || l.subjects.len() > LISTING_SUBJECTS_MAX {
120        return Err(invalid("subjects", "a listing has 1 to 256 subjects"));
121    }
122    for s in &l.subjects {
123        for key in [&s.domain, &s.thing, &s.measure, &s.region] {
124            check_name(key, "subjects")?;
125            if key.len() > 32 {
126                return Err(invalid("subjects", "a subject key has at most 32 bytes"));
127            }
128        }
129    }
130    if l.subjects.windows(2).any(|w| w[0] >= w[1]) {
131        return Err(invalid("subjects", "the subjects are ascending and unique"));
132    }
133    if l.key_id.is_empty() || l.key_id.len() > 256 {
134        return Err(invalid("key_id", "a key id has 1 to 256 bytes"));
135    }
136    if l.label.len() > 120 {
137        return Err(invalid("label", "a label has at most 120 bytes"));
138    }
139    if l.description.is_empty() || l.description.len() > 1024 {
140        return Err(invalid("description", "a description has 1 to 1024 bytes"));
141    }
142    check_instant(&l.fetched_at, "fetched_at")?;
143    check_instant(&l.listed_at, "listed_at")?;
144    Ok(())
145}
146
147/// The checks of a listed host's row.
148pub(crate) fn check_listed_host(h: &ListedHost) -> Result<()> {
149    check_dns_name(&h.host, "host")?;
150    if let Some(day) = &h.last_seen {
151        check_date(day, "last_seen")?;
152    }
153    if let Some(at) = &h.unreachable_since {
154        check_instant(at, "unreachable_since")?;
155    }
156    Ok(())
157}
158
159/// Whether two listings are the same in every field but `fetched_at` and `listed_at`.
160pub(crate) fn same_listing(a: &Listing, b: &Listing) -> bool {
161    a.host == b.host
162        && a.name == b.name
163        && a.fn_hash == b.fn_hash
164        && a.subjects == b.subjects
165        && a.descriptor == b.descriptor
166        && a.key_id == b.key_id
167        && a.label == b.label
168        && a.description == b.description
169}
170
171/// The subjects as canonical JSON: an array of `[domain, thing, measure, region]`.
172pub(crate) fn subjects_json(subjects: &[SubjectKeys]) -> String {
173    let items = subjects
174        .iter()
175        .map(|s| {
176            let keys = [&s.domain, &s.thing, &s.measure, &s.region];
177            Value::Array(keys.iter().map(|k| Value::String(k.to_string())).collect())
178        })
179        .collect();
180    String::from_utf8(Value::Array(items).to_jcs()).unwrap_or_default()
181}
182
183/// The subjects from their stored JSON.
184pub(crate) fn parse_subjects(text: &str) -> Result<Vec<SubjectKeys>> {
185    let corrupt = || invalid("subjects", "a stored listing has bad subjects");
186    let Value::Array(items) = json::parse(text.as_bytes())? else { return Err(corrupt()) };
187    items
188        .iter()
189        .map(|item| {
190            let Value::Array(keys) = item else { return Err(corrupt()) };
191            let keys: Vec<&str> = keys.iter().map(|k| k.as_str().ok_or_else(corrupt)).collect::<Result<_>>()?;
192            match keys[..] {
193                [d, t, m, r] => Ok(SubjectKeys::new(d, t, m, r)),
194                _ => Err(corrupt()),
195            }
196        })
197        .collect()
198}
199
200/// The facets of a listing: each subject key's distinct values, ascending, at most 8 per key, as
201/// canonical JSON.
202pub(crate) fn listing_facets_json(subjects: &[SubjectKeys]) -> String {
203    let mut by_key: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
204    for s in subjects {
205        for (key, value) in [("domain", &s.domain), ("thing", &s.thing), ("measure", &s.measure), ("region", &s.region)]
206        {
207            by_key.entry(key).or_default().insert(value.as_str());
208        }
209    }
210    let facets: Facets = by_key
211        .into_iter()
212        .map(|(k, values)| (k.to_string(), values.into_iter().take(FACET_MAX).map(str::to_string).collect()))
213        .collect();
214    facets_json(&facets)
215}