Skip to main content

datumesh_http/
listing.rs

1//! Listing another mesh (CONTRACT-http-listing, http 0.6.0): the functions of a mesh this mesh does not host, as
2//! descriptions only, with no cells stored.
3//!
4//! A run for one listed host is two steps, so that the store side is tested without a network:
5//!
6//! * [`fetch`]: read-only HTTP against the host's origin (L2): the key document (SPEC 9: host, keys, validity), the mesh
7//!   document (agreeing on `host` and `proto`), the host's own catalogue cells `<host>/catalog/subject(...)` (each verified
8//!   against the key document, its keys and `source(k)` names taken, the cell dropped), and for each name under `<host>/`,
9//!   `describe` and `/descriptor/<hash>` (the bytes must hash to the function hash), and its label and description from
10//!   `/fn/<name>?format=json` (describe carries neither). Never a cell, slice or receipt of a
11//!   listed function. Within [`Limits`]; past one, what is verified so far is kept and the cut recorded.
12//! * [`apply`]: writes the result into the store (L3, L8): the present state only, nothing when nothing changed.
13//!
14//! [`run_host`] is the two together; the mesh's listing thread calls it for each host of
15//! [`Config::listed_meshes`](crate::Config::listed_meshes) every [`Config::listing_interval`](crate::Config::listing_interval).
16
17use std::collections::{BTreeMap, BTreeSet};
18use std::sync::atomic::Ordering;
19use std::time::{Duration, Instant};
20
21use datumesh_core::json::{self, Value};
22use datumesh_core::lexical;
23use datumesh_core::{KeyDocument, Keys};
24use datumesh_store::{ListedHost, Listing, ListingWrite, Store, SubjectKeys};
25
26use crate::envelope::{Cache, Reply};
27
28/// The default interval between two runs of one host (`DATUMESH_LISTING_INTERVAL_SECS`, six hours).
29pub const DEFAULT_INTERVAL: Duration = Duration::from_secs(21_600);
30
31/// The most hosts `DATUMESH_LISTED_MESHES` may name.
32pub const MAX_HOSTS: usize = 64;
33
34/// How long a host may be unreachable before its listings drop out (L8), counted from the first failed run after the last
35/// success. At exactly seven days it drops out; at six days 23 hours it does not.
36pub const UNREACHABLE_DROP_AFTER: Duration = Duration::from_secs(7 * 86_400);
37
38/// The limits of one run of one host (L2.5).
39#[derive(Clone, Debug, PartialEq, Eq)]
40pub struct Limits {
41    /// The most names listed (default 2,000). Names are taken in byte order of the name.
42    pub names: usize,
43    /// The most bytes of response bodies read, every request of the run counted (default 32 MB = 32 << 20).
44    pub bytes: u64,
45    /// The longest a run takes, from its first request (default 120 s). A request in flight at the limit is abandoned.
46    pub time: Duration,
47}
48
49impl Default for Limits {
50    fn default() -> Self {
51        Limits { names: 2_000, bytes: 32 << 20, time: Duration::from_secs(120) }
52    }
53}
54
55/// Which limit cut a run.
56#[derive(Clone, Copy, Debug, PartialEq, Eq)]
57pub enum Cut {
58    /// [`Limits::names`].
59    Names,
60    /// [`Limits::bytes`].
61    Bytes,
62    /// [`Limits::time`].
63    Time,
64    /// A request for a name did not answer with a result (a 429, a 5xx, no answer, or a page that is not one), or the
65    /// catalogue could not be read on: that name, and the names past it, keep their listings (C1, C2, smaller 7).
66    Unreached,
67}
68
69/// One verified name of a listed host.
70#[derive(Clone, Debug, PartialEq, Eq)]
71pub struct FetchedName {
72    /// The full name, under `<host>/`.
73    pub name: String,
74    /// Its function hash, as `describe` gives it.
75    pub fn_hash: String,
76    /// The subjects the host's catalogue puts it in, ascending and unique.
77    pub subjects: Vec<SubjectKeys>,
78    /// The descriptor's bytes from `/descriptor/<fn_hash>`.
79    pub descriptor: Vec<u8>,
80    /// Its label in the host's catalogue (from the host's function page as JSON, `/fn/<name>?format=json`; may be empty).
81    pub label: String,
82    /// Its description (from the same page).
83    pub description: String,
84}
85
86/// What one fetch of a host gave.
87#[derive(Clone, Debug, PartialEq, Eq)]
88pub enum Fetch {
89    /// The key document and the mesh document passed, and the catalogue was read (perhaps cut).
90    Fetched {
91        /// The id of the key of the key document that verified the host's catalogue cells.
92        key_id: String,
93        /// The names that verified, by name.
94        names: Vec<FetchedName>,
95        /// The names reached and refused (a catalogue cell, describe or descriptor that does not verify), by name.
96        refused: Vec<String>,
97        /// The limit that cut the run, if one did.
98        cut: Option<Cut>,
99    },
100    /// No answer: a connection error, a timeout or a 5xx, of any request of the run (L8: not a withdrawal).
101    Unreachable {
102        /// What failed.
103        detail: String,
104    },
105    /// The key document answered and failed the SPEC 9 checks (another host, no key valid at the run's time, not a key
106    /// document, a 4xx).
107    KeyDocFailed {
108        /// Why.
109        detail: String,
110    },
111    /// The mesh document answered and failed: it disagrees with the key document on `host` or `proto`, or is not one.
112    MeshDocFailed {
113        /// Why.
114        detail: String,
115    },
116}
117
118/// The outcome of a run, as `/metrics` reports it.
119#[derive(Clone, Copy, Debug, PartialEq, Eq)]
120pub enum Outcome {
121    /// Fetched, no limit reached.
122    Ok,
123    /// [`Fetch::KeyDocFailed`].
124    KeyDocFailed,
125    /// [`Fetch::MeshDocFailed`].
126    MeshDocFailed,
127    /// Fetched, cut by a limit.
128    Cut,
129    /// [`Fetch::Unreachable`].
130    Unreachable,
131}
132
133impl Outcome {
134    /// `ok`, `key_document_failed`, `mesh_document_failed`, `cut` or `unreachable`: the `outcome` label of
135    /// `datumesh_listing_outcome`.
136    pub fn as_str(self) -> &'static str {
137        match self {
138            Outcome::Ok => "ok",
139            Outcome::KeyDocFailed => "key_document_failed",
140            Outcome::MeshDocFailed => "mesh_document_failed",
141            Outcome::Cut => "cut",
142            Outcome::Unreachable => "unreachable",
143        }
144    }
145}
146
147/// What [`apply`] did.
148#[derive(Clone, Debug, PartialEq, Eq)]
149#[non_exhaustive]
150pub struct Applied {
151    /// The run's outcome.
152    pub outcome: Outcome,
153    /// The cut, when the outcome is [`Outcome::Cut`].
154    pub cut: Option<Cut>,
155    /// The names newly listed, by name.
156    pub added: Vec<String>,
157    /// The names whose listing changed (hash, descriptor, subjects, label or description), by name.
158    pub changed: Vec<String>,
159    /// The names that dropped out, by name.
160    pub dropped: Vec<String>,
161    /// The names of the host listed after the run.
162    pub listed: usize,
163    /// The rows the run wrote or deleted: listings put (inserted or changed), listings deleted, and the host's row when
164    /// it was written. 0 for a run that changed nothing.
165    pub writes: u64,
166}
167
168impl Applied {
169    /// Whether the run added, changed or dropped a listing (a catalogue job run after it has something to write).
170    pub fn changed_any(&self) -> bool {
171        !(self.added.is_empty() && self.changed.is_empty() && self.dropped.is_empty())
172    }
173}
174
175/// A failure of [`apply`] (the store's), which leaves the store as it was before the failing write.
176#[derive(Debug)]
177pub struct ListingError {
178    detail: String,
179}
180
181impl std::fmt::Display for ListingError {
182    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
183        write!(f, "listing: {}", self.detail)
184    }
185}
186
187impl std::error::Error for ListingError {}
188
189/// Where `host` is reached: its origin in [`Config::peers`](crate::Config::peers) when it has one, else
190/// `https://<host>`.
191pub fn origin_of(config: &crate::Config, host: &str) -> String {
192    match config.peers.get(host) {
193        Some(origin) => origin.clone(),
194        None => format!("https://{host}"),
195    }
196}
197
198/// Why a request of a run stopped it.
199enum Stop {
200    /// No answer, or a 5xx (L8).
201    Unreachable(String),
202    /// The byte limit was passed.
203    Bytes,
204}
205
206/// One run's requests: each one's timeout is the time left, its body counted against the bytes left.
207struct Run {
208    agent: ureq::Agent,
209    started: Instant,
210    limits: Limits,
211    bytes: u64,
212}
213
214impl Run {
215    fn new(limits: &Limits) -> Run {
216        let agent: ureq::Agent = ureq::Agent::config_builder()
217            .max_redirects(0)
218            .http_status_as_error(false)
219            .user_agent(concat!("datumesh-http/", env!("CARGO_PKG_VERSION")))
220            .build()
221            .into();
222        Run { agent, started: Instant::now(), limits: limits.clone(), bytes: 0 }
223    }
224
225    /// The time left of the run, or `None` when it is spent.
226    fn left(&self) -> Option<Duration> {
227        self.limits.time.checked_sub(self.started.elapsed()).filter(|d| !d.is_zero())
228    }
229
230    /// `GET url`: the status and the body, or why it stopped the run.
231    fn get(&mut self, url: &str) -> Result<(u16, Vec<u8>), Stop> {
232        let Some(left) = self.left() else { return Err(Stop::Unreachable("the run's time is spent".into())) };
233        let resp = self
234            .agent
235            .get(url)
236            .config()
237            .timeout_global(Some(left))
238            .build()
239            .call()
240            .map_err(|e| Stop::Unreachable(format!("{url}: {e}")))?;
241        let status = resp.status().as_u16();
242        if status >= 500 {
243            return Err(Stop::Unreachable(format!("{url}: status {status}")));
244        }
245        let room = self.limits.bytes.saturating_sub(self.bytes);
246        let body = resp.into_body().with_config().limit(room.saturating_add(1)).read_to_vec().map_err(|e| match e {
247            ureq::Error::BodyExceedsLimit(_) => Stop::Bytes,
248            e => Stop::Unreachable(format!("{url}: {e}")),
249        })?;
250        self.bytes += body.len() as u64;
251        if self.bytes > self.limits.bytes {
252            return Err(Stop::Bytes);
253        }
254        Ok((status, body))
255    }
256}
257
258/// An instant as a string that compares in time order: `YYYY-MM-DDTHH:MM:SS` and the fraction to nine digits (smaller 6).
259fn instant_key(s: &str) -> String {
260    let s = s.strip_suffix('Z').unwrap_or(s);
261    let (whole, frac) = s.split_once('.').unwrap_or((s, ""));
262    let frac = &frac[..frac.len().min(9)];
263    format!("{whole}.{frac:0<9}")
264}
265
266/// The key of `doc` valid at `now` (`valid_from <= now < valid_to`), if any; instants compare as instants.
267fn key_valid_at(doc: &KeyDocument, now: &str) -> Option<String> {
268    let now = instant_key(now);
269    doc.keys
270        .keys
271        .iter()
272        .find(|k| instant_key(&k.valid_from) <= now && k.valid_to.as_deref().is_none_or(|t| now < instant_key(t)))
273        .map(|k| k.id.clone())
274}
275
276/// The next page of the catalogue, when this run follows it (B2): a path under the host's own slice, relative, or an
277/// `https://<host>` link re-rooted on `origin`. Anything else (another origin, `http://`) is not fetched.
278fn next_page(host: &str, origin: &str, next: &str) -> Option<String> {
279    let slice = format!("/slice/{host}/");
280    if next.starts_with(&slice) {
281        return Some(format!("{origin}{next}"));
282    }
283    let rest = next.strip_prefix(&format!("https://{host}"))?;
284    rest.starts_with(&slice).then(|| format!("{origin}{rest}"))
285}
286
287/// The subjects of each name of a catalogue, by name.
288type Members = BTreeMap<String, BTreeSet<SubjectKeys>>;
289
290/// The function name's subjects and source names, from the host's signed catalogue cells (L2.3): each member's receipt
291/// is verified against the host's key document; a member that does not verify is skipped. Pages are followed. A page
292/// after the first that cannot be read ends the catalogue as a cut (C1, C2), keeping the members read so far. When no
293/// page was read (a 404, a 5xx, no answer, a time-out), the catalogue cannot be read: `Stop::Unreachable` (N1).
294fn catalogue(run: &mut Run, host: &str, origin: &str, doc: &KeyDocument) -> Result<(Members, Option<Cut>), Stop> {
295    let mut keys = Keys::new();
296    keys.insert_document(doc.clone());
297    let mut out: BTreeMap<String, BTreeSet<SubjectKeys>> = BTreeMap::new();
298    let mut url = format!("{origin}/slice/{host}/catalog/subject/source?domain=*&measure=*&rank=*&region=*&thing=*");
299    // The cell of a subject's source: the method `source` of the class `<host>/catalog/subject` (receipt `ns` and `fn`).
300    let source_ns = format!("{host}/catalog/subject");
301    // N1 (re-review): a catalogue none of whose pages was read cannot be read, so the host is unreachable; a stop on a
302    // later page is a cut, keeping the members read.
303    let mut pages = 0usize;
304    loop {
305        let (status, body) = match run.get(&url) {
306            Ok(x) => x,
307            Err(Stop::Bytes) => return Ok((out, Some(Cut::Bytes))),
308            Err(Stop::Unreachable(detail)) => {
309                if pages == 0 {
310                    return Err(Stop::Unreachable(detail));
311                }
312                let cut = if run.left().is_none() { Cut::Time } else { Cut::Unreached };
313                return Ok((out, Some(cut)));
314            }
315        };
316        let page = if status == 200 { json::parse(&body).ok() } else { None };
317        let Some(page) = page else {
318            if pages == 0 {
319                return Err(Stop::Unreachable(format!("{url}: status {status}")));
320            }
321            return Ok((out, Some(Cut::Unreached)));
322        };
323        pages += 1;
324        if let Some(Value::Array(members)) = page.get("members") {
325            for m in members {
326                let Some(receipt) = m.get("receipt") else { continue };
327                let r = datumesh_core::verify(&receipt.to_jcs(), &keys, None, None);
328                if r.error().is_some() {
329                    continue;
330                }
331                let Some(cell) = receipt.get("cell") else { continue };
332                // Only the host's own source cells name sources (smaller 3): their `ns` and `fn`, a rank and the four keys.
333                let is_source = cell.get("fn").and_then(Value::as_str) == Some("source")
334                    && cell.get("ns").and_then(Value::as_str) == Some(source_ns.as_str());
335                if !is_source {
336                    continue;
337                }
338                let arg = |k: &str| -> Option<String> {
339                    cell.get("args")?.get(k)?.get("value")?.as_str().map(str::to_string)
340                };
341                let (Some(d), Some(t), Some(me), Some(rg)) =
342                    (arg("domain"), arg("thing"), arg("measure"), arg("region"))
343                else {
344                    continue;
345                };
346                if cell.get("args").and_then(|a| a.get("rank")).is_none() {
347                    continue;
348                }
349                let value = receipt.get("value");
350                let name = value.and_then(|v| v.as_str().or_else(|| v.get("value").and_then(Value::as_str)));
351                let Some(name) = name else { continue };
352                let under = name.starts_with(&format!("{host}/"));
353                if under && lexical::check_function_name(name, "name").is_ok() {
354                    out.entry(name.to_string()).or_default().insert(SubjectKeys::new(&d, &t, &me, &rg));
355                }
356            }
357        }
358        match page.get("next") {
359            None | Some(Value::Null) => break,
360            Some(Value::String(next)) => match next_page(host, origin, next) {
361                Some(u) => url = u,
362                None => return Ok((out, Some(Cut::Unreached))),
363            },
364            Some(_) => return Ok((out, Some(Cut::Unreached))),
365        }
366    }
367    Ok((out, None))
368}
369
370/// What one name's requests made of it.
371enum NameStep {
372    /// Verified: describe, descriptor and function page (its label and description).
373    Got(FetchedName),
374    /// Reached, and the answer does not verify or the name is gone (describe 404, a hash that does not match): refused.
375    Refused,
376    /// Not reached: a 429, a 5xx or a page that is not an answer (C2, smaller 7). The stored listing stays as it is.
377    NotReached,
378}
379
380/// One name's requests (see [`NameStep`]); a request that stops the run is `Err`.
381fn name_step(run: &mut Run, origin: &str, name: &str, subjects: Vec<SubjectKeys>) -> Result<NameStep, Stop> {
382    let base = format!("{origin}/");
383    let (status, d) = run.get(&format!("{base}describe/{name}"))?;
384    if status == 404 {
385        return Ok(NameStep::Refused);
386    }
387    if status != 200 {
388        return Ok(NameStep::NotReached);
389    }
390    let fn_hash = json::parse(&d)
391        .ok()
392        .and_then(|v| v.get("fn_hash").and_then(Value::as_str).map(str::to_string))
393        .filter(|h| lexical::check_hex(h, 64, "fn_hash").is_ok());
394    let Some(fn_hash) = fn_hash else { return Ok(NameStep::Refused) };
395    let (status, bytes) = run.get(&format!("{base}descriptor/{fn_hash}"))?;
396    if status != 200 {
397        return Ok(NameStep::NotReached);
398    }
399    if datumesh_core::function_hash(&bytes).ok().as_deref() != Some(fn_hash.as_str()) {
400        return Ok(NameStep::Refused);
401    }
402    let (status, f) = run.get(&format!("{base}fn/{name}?format=json"))?;
403    let page = if status == 200 { json::parse(&f).ok() } else { None };
404    let Some(v) = page else { return Ok(NameStep::NotReached) };
405    let label = v.get("label").and_then(Value::as_str).unwrap_or_default().to_string();
406    let description = v.get("description").and_then(Value::as_str).unwrap_or_default().to_string();
407    if description.is_empty() {
408        return Ok(NameStep::NotReached);
409    }
410    Ok(NameStep::Got(FetchedName { name: name.to_string(), fn_hash, subjects, descriptor: bytes, label, description }))
411}
412
413/// Records the first cut of a run (the first limit reached is the one reported).
414fn first_cut(cut: &mut Option<Cut>, c: Cut) {
415    if cut.is_none() {
416        *cut = Some(c);
417    }
418}
419
420/// Fetches `host` at `origin` (L2), read-only, within `limits`; `now` (an instant) is the time the key document's keys
421/// must be valid at.
422pub fn fetch(host: &str, origin: &str, limits: &Limits, now: &str) -> Fetch {
423    let mut run = Run::new(limits);
424    let unreachable = |s: Stop| match s {
425        Stop::Unreachable(detail) => Fetch::Unreachable { detail },
426        Stop::Bytes => Fetch::Unreachable { detail: "the byte limit, before the key document".into() },
427    };
428    // 1. the key document
429    let (status, body) = match run.get(&format!("{origin}/.well-known/datumesh.json")) {
430        Ok(x) => x,
431        Err(s) => return unreachable(s),
432    };
433    let doc = match datumesh_core::key_document_from_response(host, status, Some(&body)) {
434        Ok(d) if status == 200 => d,
435        Ok(_) => return Fetch::KeyDocFailed { detail: format!("status {status}") },
436        Err(e) => return Fetch::KeyDocFailed { detail: e.to_string() },
437    };
438    let Some(key_id) = key_valid_at(&doc, now) else {
439        return Fetch::KeyDocFailed { detail: format!("no key of {host} is valid at {now}") };
440    };
441    let proto = json::parse(&body).ok().and_then(|v| v.get("proto").and_then(Value::as_str).map(str::to_string));
442    // 2. the mesh document, agreeing on host and proto
443    let (status, mbody) = match run.get(&format!("{origin}/.well-known/datumesh-mesh.json")) {
444        Ok(x) => x,
445        Err(s) => return unreachable(s),
446    };
447    if status != 200 {
448        return Fetch::MeshDocFailed { detail: format!("status {status}") };
449    }
450    let Ok(m) = json::parse(&mbody) else { return Fetch::MeshDocFailed { detail: "not JSON".into() } };
451    if m.get("host").and_then(Value::as_str) != Some(host) || m.get("proto").and_then(Value::as_str) != proto.as_deref()
452    {
453        return Fetch::MeshDocFailed { detail: "disagrees with the key document on host or proto".into() };
454    }
455    // 3. the host's own catalogue, verified and not stored (a cut keeps the members read)
456    let (subjects, mut cut) = match catalogue(&mut run, host, origin, &doc) {
457        Ok(x) => x,
458        Err(s) => return unreachable(s),
459    };
460    let mut all: Vec<(String, Vec<SubjectKeys>)> =
461        subjects.into_iter().map(|(n, s)| (n, s.into_iter().collect())).collect();
462    if all.len() > limits.names {
463        all.truncate(limits.names);
464        first_cut(&mut cut, Cut::Names);
465    }
466    // 4. each name: describe, descriptor, and its label and description
467    let mut names = Vec::new();
468    let mut refused = Vec::new();
469    for (name, subjects) in all {
470        if run.left().is_none() {
471            first_cut(&mut cut, Cut::Time);
472            break;
473        }
474        match name_step(&mut run, origin, &name, subjects) {
475            Ok(NameStep::Got(n)) => names.push(n),
476            Ok(NameStep::Refused) => refused.push(name),
477            Ok(NameStep::NotReached) => first_cut(&mut cut, Cut::Unreached),
478            Err(Stop::Bytes) => {
479                first_cut(&mut cut, Cut::Bytes);
480                break;
481            }
482            Err(Stop::Unreachable(_)) => {
483                if run.left().is_none() {
484                    first_cut(&mut cut, Cut::Time);
485                    break;
486                }
487                first_cut(&mut cut, Cut::Unreached);
488            }
489        }
490    }
491    Fetch::Fetched { key_id, names, refused, cut }
492}
493
494/// The most subjects a listed host may create in this mesh's catalogue (B4): a subject no member bound here holds. A name
495/// whose subjects would pass it is cut, in name order.
496const MAX_CREATED_SUBJECTS: usize = 64;
497
498/// Applies a fetch of `host` at `now` (an instant) to the store (L3, L8, the re-review's N1, N3, N4):
499///
500/// * [`Fetch::Fetched`]: each name of `names` whose descriptor hashes to its `fn_hash` is put, with the subjects it has
501///   and, in a cut run, those it held (N4: a cut keeps what a name was in); a name the store refuses (its bounds, or
502///   another source's entry of the name, `Invalid`) is refused, and the run goes on. The subjects this run may create here
503///   are at most `MAX_CREATED_SUBJECTS` (B4), counted across runs: the subjects of the held names a cut run keeps (not
504///   offered, not refused) count from the start, and an offered name counts with the subjects it is put with (N3); a name
505///   over the limit is cut, and the run is a cut (`Cut::Names`). Without a cut, every listing of the host not among the
506///   verified names drops out; with a cut, the `refused` ones drop, and so does a held name the run neither offered nor
507///   refused once it has been unreached for seven days, whatever the cut (its own clock, N1). A verified name's clock is
508///   cleared. The host's row: `last_seen` the day of `now`, `unreachable_since` none, written only when that
509///   changes it.
510/// * [`Fetch::KeyDocFailed`], [`Fetch::MeshDocFailed`]: every listing of the host drops out at once; the host's row is
511///   left as it was.
512/// * [`Fetch::Unreachable`]: the listings stay; the host's `unreachable_since` is written once, at the first failed run;
513///   when `now` is [`UNREACHABLE_DROP_AFTER`] or more after it, every listing of the host drops out.
514///
515/// A run that finds nothing changed writes nothing.
516pub fn apply<S: Store + ?Sized>(store: &S, host: &str, fetch: &Fetch, now: &str) -> Result<Applied, ListingError> {
517    let se = |e: &dyn std::fmt::Display| ListingError { detail: e.to_string() };
518    let mut applied = Applied {
519        outcome: Outcome::Ok,
520        cut: None,
521        added: Vec::new(),
522        changed: Vec::new(),
523        dropped: Vec::new(),
524        listed: 0,
525        writes: 0,
526    };
527    let held: Vec<Listing> = store.listings_of(host).map_err(|e| se(&e))?;
528    let existing: Vec<String> = held.iter().map(|l| l.name.clone()).collect();
529    let mut drop_all = false;
530    let mut drop_set: BTreeSet<String> = BTreeSet::new();
531    match fetch {
532        Fetch::Fetched { key_id, names, refused, cut } => {
533            let mut verified = BTreeSet::new();
534            let offered: BTreeSet<&str> = names.iter().map(|n| n.name.as_str()).collect();
535            let mut refuse: BTreeSet<String> = refused.iter().cloned().collect();
536            let stored: BTreeMap<&str, &Listing> = held.iter().map(|l| (l.name.as_str(), l)).collect();
537            // The subjects no member bound here holds: a listing creates these (B4), at most MAX_CREATED_SUBJECTS. The
538            // held names a cut run keeps (not offered, not refused) count from the start; an offered name counts with the
539            // subjects it is put with, in the loop below, so none is counted twice (N3).
540            let bound = crate::catalog_build::bound_subjects(store).map_err(|e| se(&e))?;
541            let staying =
542                |l: &Listing| cut.is_some() && !offered.contains(l.name.as_str()) && !refused.contains(&l.name);
543            let mut created: BTreeSet<SubjectKeys> = held
544                .iter()
545                .filter(|l| staying(l))
546                .flat_map(|l| l.subjects.iter().cloned())
547                .filter(|s| !bound.contains(s))
548                .collect();
549            let mut cap_cut = false;
550            let mut ordered: Vec<&FetchedName> = names.iter().collect();
551            ordered.sort_by(|a, b| a.name.cmp(&b.name));
552            for n in ordered {
553                let under = n.name.starts_with(&format!("{host}/"));
554                let ok =
555                    under && datumesh_core::function_hash(&n.descriptor).ok().as_deref() == Some(n.fn_hash.as_str());
556                if !ok {
557                    refuse.insert(n.name.clone());
558                    continue;
559                }
560                let mut subjects = n.subjects.clone();
561                if cut.is_some() {
562                    // N4: a cut run may have read only some of the catalogue's pages: the subjects it held stay.
563                    if let Some(s) = stored.get(n.name.as_str()) {
564                        subjects.extend(s.subjects.iter().cloned());
565                    }
566                }
567                subjects.sort();
568                subjects.dedup();
569                let new: Vec<SubjectKeys> =
570                    subjects.iter().filter(|s| !bound.contains(*s) && !created.contains(*s)).cloned().collect();
571                if created.len() + new.len() > MAX_CREATED_SUBJECTS {
572                    cap_cut = true;
573                    continue;
574                }
575                let l = Listing {
576                    host: host.to_string(),
577                    name: n.name.clone(),
578                    fn_hash: n.fn_hash.clone(),
579                    subjects,
580                    descriptor: n.descriptor.clone(),
581                    key_id: key_id.clone(),
582                    label: n.label.clone(),
583                    description: n.description.clone(),
584                    fetched_at: now.to_string(),
585                    listed_at: now.to_string(),
586                };
587                match store.put_listing(&l) {
588                    Ok(ListingWrite::Unchanged) => {}
589                    Ok(ListingWrite::Inserted) => {
590                        applied.added.push(n.name.clone());
591                        applied.writes += 1;
592                    }
593                    Ok(ListingWrite::Changed) => {
594                        applied.changed.push(n.name.clone());
595                        applied.writes += 1;
596                    }
597                    // A name the store refuses (its bounds, or another source's catalogue entry of it) is refused, and the
598                    // run goes on with the others (B3, C3); nothing of it was written.
599                    Err(datumesh_store::Error::Invalid(_)) => {
600                        refuse.insert(n.name.clone());
601                        continue;
602                    }
603                    Err(e) => return Err(se(&e)),
604                }
605                // Reached: its own clock (N1) is cleared, if it had one.
606                if store.set_listing_unreached(&n.name, None).map_err(|e| se(&e))? {
607                    applied.writes += 1;
608                }
609                created.extend(new);
610                verified.insert(n.name.clone());
611            }
612            let cut = cut.or(cap_cut.then_some(Cut::Names));
613            match cut {
614                None => drop_set.extend(existing.iter().filter(|e| !verified.contains(*e)).cloned()),
615                Some(c) => {
616                    drop_set.extend(existing.iter().filter(|e| refuse.contains(*e)).cloned());
617                    // N1, in every cut: a held name the run did not reach (not offered, not refused) has a clock of its own:
618                    // set at the first such run, cleared when it answers, dropped seven days after it was set.
619                    for name in existing.iter().filter(|e| !offered.contains(e.as_str()) && !refuse.contains(*e)) {
620                        let since = match store.listing_unreached(name).map_err(|e| se(&e))? {
621                            Some(since) => since,
622                            None => {
623                                store.set_listing_unreached(name, Some(now)).map_err(|e| se(&e))?;
624                                applied.writes += 1;
625                                now.to_string()
626                            }
627                        };
628                        let due = crate::keynames::add_seconds(&since, UNREACHABLE_DROP_AFTER.as_secs());
629                        if due.is_some_and(|d| d.as_str() <= now) {
630                            drop_set.insert(name.clone());
631                        }
632                    }
633                    applied.cut = Some(c);
634                    applied.outcome = Outcome::Cut;
635                }
636            }
637            let day = &now[..10];
638            let row = ListedHost { host: host.to_string(), last_seen: Some(day.to_string()), unreachable_since: None };
639            if store.put_listed_host(&row).map_err(|e| se(&e))? {
640                applied.writes += 1;
641            }
642        }
643        Fetch::KeyDocFailed { .. } => {
644            applied.outcome = Outcome::KeyDocFailed;
645            drop_all = true;
646        }
647        Fetch::MeshDocFailed { .. } => {
648            applied.outcome = Outcome::MeshDocFailed;
649            drop_all = true;
650        }
651        Fetch::Unreachable { .. } => {
652            applied.outcome = Outcome::Unreachable;
653            let row = store.listed_host(host).map_err(|e| se(&e))?;
654            match row {
655                None => {
656                    let r = ListedHost {
657                        host: host.to_string(),
658                        last_seen: None,
659                        unreachable_since: Some(now.to_string()),
660                    };
661                    store.put_listed_host(&r).map_err(|e| se(&e))?;
662                    applied.writes += 1;
663                }
664                Some(r) => match r.unreachable_since.as_deref() {
665                    None => {
666                        let r2 = ListedHost { unreachable_since: Some(now.to_string()), ..r };
667                        store.put_listed_host(&r2).map_err(|e| se(&e))?;
668                        applied.writes += 1;
669                    }
670                    Some(since) => {
671                        let due = crate::keynames::add_seconds(since, UNREACHABLE_DROP_AFTER.as_secs());
672                        if due.is_some_and(|d| d.as_str() <= now) {
673                            drop_all = true;
674                        }
675                    }
676                },
677            }
678        }
679    }
680    if drop_all {
681        drop_set.extend(existing.iter().cloned());
682    }
683    for name in &drop_set {
684        if store.delete_listing(name).map_err(|e| se(&e))? {
685            applied.dropped.push(name.clone());
686            applied.writes += 1;
687        }
688    }
689    applied.listed = store.listings_of(host).map_err(|e| se(&e))?.len();
690    Ok(applied)
691}
692
693/// [`fetch`] then [`apply`].
694pub fn run_host<S: Store + ?Sized>(
695    store: &S,
696    host: &str,
697    origin: &str,
698    limits: &Limits,
699    now: &str,
700) -> Result<Applied, ListingError> {
701    let f = fetch(host, origin, limits, now);
702    apply(store, host, &f, now)
703}
704
705// ---------------------------------------------------------------------------------------------------------------------
706// What this mesh says about a listed name (L6): refused for every read, described and shown as a page
707
708/// Whether listings are looked up at all: only with `DATUMESH_LISTED_MESHES` naming a host (smaller 1). With the list empty
709/// no request reads the listings table.
710fn active(inner: &crate::mesh::Inner) -> bool {
711    !inner.config.listed_meshes.is_empty()
712}
713
714/// Whether `word` is a name under a host of `DATUMESH_LISTED_MESHES` (N2): only such a word is looked up, so a read of any
715/// other name costs no store lookup.
716fn under_listed(inner: &crate::mesh::Inner, word: &str) -> bool {
717    word.split_once('/').is_some_and(|(host, _)| inner.config.listed_meshes.iter().any(|h| h == host))
718}
719
720/// One counted store lookup of a listing (`datumesh_listing_lookups_total`).
721pub(crate) fn lookup(inner: &crate::mesh::Inner, name: &str) -> Result<Option<Listing>, ListingError> {
722    inner.listing_lookups.fetch_add(1, Ordering::Relaxed);
723    inner.store.listing(name).map_err(|e| ListingError { detail: e.to_string() })
724}
725
726/// The listing of `name` when it is a listed name here. With no listed host nothing is looked up. A store failure is an
727/// error (a read that depends on it fails closed, L6).
728pub(crate) fn checked(inner: &crate::mesh::Inner, name: &str) -> Result<Option<Listing>, ListingError> {
729    if !active(inner) {
730        return Ok(None);
731    }
732    lookup(inner, name)
733}
734
735/// The listing of `name`, or `None` when it is not one (a store failure reads as not listed: for the pages, not for the
736/// refusals, which use [`checked`]).
737pub(crate) fn listed(inner: &crate::mesh::Inner, name: &str) -> Option<Listing> {
738    checked(inner, name).ok().flatten()
739}
740
741/// `text` with a leading alias (`@a` of `@a(...)`, `@a/...`) replaced by its target, when `alias` knows it (B1).
742fn resolve_alias(text: &str, alias: &dyn Fn(&str) -> Option<String>) -> String {
743    let Some(rest) = text.strip_prefix('@') else { return text.to_string() };
744    let end = rest.find(['(', '/', '?', ' ']).unwrap_or(rest.len());
745    match alias(&rest[..end]) {
746        Some(target) => format!("{target}{}", &rest[end..]),
747        None => text.to_string(),
748    }
749}
750
751/// The listed name a read names (B1): `text` is a read's path rest, a call or a name, `name`, `name(args)` or `name?query`,
752/// a series page below a name or an alias of one. Each prefix under a listed host is looked up through `bindings` (N2: a
753/// batch's bindings remember each lookup), the first one returned.
754pub(crate) fn checked_in(
755    inner: &crate::mesh::Inner,
756    bindings: &dyn crate::call::Bindings,
757    alias: &dyn Fn(&str) -> Option<String>,
758    text: &str,
759) -> Result<Option<Listing>, ListingError> {
760    if !active(inner) {
761        return Ok(None);
762    }
763    let text = resolve_alias(text.strip_prefix("cell://").unwrap_or(text), alias);
764    let mut ends: Vec<usize> =
765        text.char_indices().filter(|(_, c)| matches!(c, '/' | '(' | '?' | ' ')).map(|(i, _)| i).collect();
766    ends.push(text.len());
767    for e in ends {
768        if under_listed(inner, &text[..e]) {
769            if let Some(l) = bindings.listing(&text[..e])? {
770                return Ok(Some(l));
771            }
772        }
773    }
774    Ok(None)
775}
776
777/// The listed name a text names among its words (a formula's, or a scenario's body): any word under a listed host that is
778/// one. Each distinct word is looked up once (N2).
779pub(crate) fn checked_words(inner: &crate::mesh::Inner, text: &str) -> Result<Option<Listing>, ListingError> {
780    if !active(inner) {
781        return Ok(None);
782    }
783    let words: BTreeSet<&str> =
784        text.split(|c: char| !(c.is_alphanumeric() || "._/-".contains(c))).filter(|w| under_listed(inner, w)).collect();
785    for w in words {
786        if let Some(l) = lookup(inner, w)? {
787            return Ok(Some(l));
788        }
789    }
790    Ok(None)
791}
792
793/// The listed name a formula (the body of `POST /x/calc`) reads: one of its words is a listed name.
794pub(crate) fn checked_formula(inner: &crate::mesh::Inner, body: &[u8]) -> Result<Option<Listing>, ListingError> {
795    if !active(inner) {
796        return Ok(None);
797    }
798    let formula = json::parse(body).ok().and_then(|v| v.get("formula").and_then(Value::as_str).map(str::to_string));
799    match formula {
800        Some(f) => checked_words(inner, &f),
801        None => Ok(None),
802    }
803}
804
805/// The reply of a read that depends on the listings when the store fails (fail closed, L6): `503`.
806pub(crate) fn unavailable() -> Reply {
807    crate::envelope::error_reply(datumesh_core::ErrorCode::EvalUnavailable)
808}
809
810/// `E_LISTED_ELSEWHERE` (CONTRACT-http-listing L6): a read of a listed name is `not_covered`, with the mesh that holds it.
811/// Spec 0.7 adds the code; until then this mesh writes it itself.
812pub(crate) fn refusal(l: &Listing) -> Reply {
813    let body = Value::Object(vec![
814        ("outcome".into(), Value::String("not_covered".into())),
815        ("error".into(), Value::String("E_LISTED_ELSEWHERE".into())),
816        ("mesh".into(), Value::String(mesh_of(&l.host))),
817        ("name".into(), Value::String(l.name.clone())),
818    ]);
819    Reply::json(404, body.to_jcs(), Cache::NoStore)
820}
821
822/// The host's own origin as a listed answer names it (`https://<host>`, never the peers origin).
823fn mesh_of(host: &str) -> String {
824    format!("https://{host}")
825}
826
827/// The note a page carries about the listed name that ranks first in the subject where `name` (a relay of a source) has its
828/// place (CONTRACT-http-listing L7): the page links to it, with the day it was last seen. `None` when that first name is not
829/// a listed one (or is `name` itself).
830fn first_note(inner: &crate::mesh::Inner, name: &str) -> Option<String> {
831    let built = crate::catalog_view::built(inner)?;
832    let subject = &built.places.get(name)?.subject;
833    let first = built.firsts.get(subject)?;
834    if first == name {
835        return None;
836    }
837    let l = listed(inner, first)?;
838    let last_seen = inner.store.listed_host(&l.host).ok().flatten().and_then(|r| r.last_seen).unwrap_or_default();
839    Some(format!(
840        "<p>The source&#39;s own function is listed here and ranks first in its subject (last seen {}): \
841         <a href=\"{}\"><code>{}</code></a>.</p>\n",
842        escape(&last_seen),
843        escape(&crate::fnpage::page_url(inner, &l.name)),
844        escape(&l.name)
845    ))
846}
847
848/// The note of a relay's function page about its source (CONTRACT-http-listing L7): the listed name that ranks first in the
849/// relay's subject. `d` is the function page's data; `None` when there is none.
850pub(crate) fn relay_note(inner: &crate::mesh::Inner, d: &Value) -> Option<String> {
851    first_note(inner, d.get("name").or_else(|| d.get("fn"))?.as_str()?)
852}
853
854/// The note of a takeover page about its domain (CONTRACT-http-listing L7): [`first_note`] of each of the domain's relays,
855/// each note once.
856pub(crate) fn takeover_note(inner: &crate::mesh::Inner, relays: &[String]) -> String {
857    let mut notes: Vec<String> = Vec::new();
858    for r in relays {
859        if let Some(n) = first_note(inner, r) {
860            if !notes.contains(&n) {
861                notes.push(n);
862            }
863        }
864    }
865    notes.concat()
866}
867
868/// The members a listed name's description carries (describe and the function page as JSON).
869fn listed_members(store: &dyn Store, l: &Listing) -> Vec<(String, Value)> {
870    let last_seen = store.listed_host(&l.host).ok().flatten().and_then(|r| r.last_seen).unwrap_or_default();
871    let descriptor = json::parse(&l.descriptor).unwrap_or(Value::Null);
872    let s = |v: &str| Value::String(v.to_string());
873    vec![
874        ("outcome".into(), s("ok")),
875        ("kind".into(), s("function")),
876        ("fn".into(), s(&l.name)),
877        ("listed".into(), Value::Bool(true)),
878        ("mesh".into(), s(&mesh_of(&l.host))),
879        ("publisher".into(), s(&l.host)),
880        ("address".into(), s(&format!("{}/fn/{}", mesh_of(&l.host), l.name))),
881        ("last_seen".into(), s(&last_seen)),
882        ("fn_hash".into(), s(&l.fn_hash)),
883        ("label".into(), s(&l.label)),
884        ("description".into(), s(&l.description)),
885        ("descriptor".into(), descriptor),
886    ]
887}
888
889/// `describe` of a listed name: its listed descriptor, with `listed: true`, the mesh and the day last seen.
890pub(crate) fn describe_reply(store: &dyn Store, l: &Listing) -> Reply {
891    Reply::json(200, Value::Object(listed_members(store, l)).to_jcs(), Cache::Public(300))
892}
893
894fn escape(s: &str) -> String {
895    s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;")
896}
897
898/// `/fn/<name>` of a listed name: a short page (no script) with the description, the mesh, a link to the name's page there
899/// and the day last seen; as JSON, the members of describe.
900pub(crate) fn fn_reply(store: &dyn Store, l: &Listing, json_form: bool) -> Reply {
901    if json_form {
902        return describe_reply(store, l);
903    }
904    let members = listed_members(store, l);
905    let last_seen = members.iter().find(|(k, _)| k == "last_seen").and_then(|(_, v)| v.as_str()).unwrap_or_default();
906    let address = mesh_of(&l.host) + "/fn/" + &l.name;
907    let html = format!(
908        "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">\
909         <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><title>{name}</title></head>\
910         <body><h1>{name}</h1><p>{description}</p>\
911         <p>Listed from <a href=\"{address}\">{mesh}</a>, last seen {last_seen}. This mesh describes the function; \
912         it does not serve its values.</p></body></html>",
913        name = escape(&l.name),
914        description = escape(&l.description),
915        address = escape(&address),
916        mesh = escape(&mesh_of(&l.host)),
917        last_seen = escape(last_seen),
918    );
919    Reply {
920        status: 200,
921        body: html.into_bytes().into(),
922        content_type: "text/html; charset=utf-8",
923        cache: Cache::Public(300),
924        canonical: None,
925        retry_after: None,
926    }
927}