Skip to main content

datumesh_http/
mesh.rs

1//! [`Mesh`]: the engine, its store and everything the endpoints share; the blocking
2//! operations each endpoint is built on, usable as library calls.
3
4use std::collections::{BTreeMap, HashMap, HashSet};
5use std::path::PathBuf;
6use std::sync::{Arc, Mutex, RwLock};
7use std::time::{Duration, Instant};
8
9use datumesh_core::json::{self, Value};
10use datumesh_core::{
11    keys_from_response, verify, CellRef, ClassDescriptor, ErrorCode, FunctionDescriptor, KeyDoc, Keys, Receipt,
12    SigningKey,
13};
14use datumesh_engine::{Answer, Clock, Engine, EngineError, Runtime, SystemClock};
15use datumesh_formula::runtime::FormulaRuntime;
16use datumesh_store::Store;
17
18use crate::apikeys::Principal;
19use crate::call::{self, Bindings, Bound, Rejection, Target};
20use crate::config::{Config, ConfigError, Rule};
21use crate::envelope::{self, Cache, Reply};
22use crate::foreign::{host_of, CrossMesh, Foreign, ForeignError, KeyCache};
23use crate::jobs::Jobs;
24use crate::limit::Limiter;
25use crate::metrics::Metrics;
26use crate::pool::Pool;
27
28/// Why a mesh could not be built.
29#[derive(Debug)]
30#[non_exhaustive]
31pub enum BuildError {
32    /// The configuration.
33    Config(ConfigError),
34    /// The engine's configuration (the key, its publication in the store, the runtimes).
35    Engine(datumesh_engine::ConfigError),
36    /// The base URL ([`Config::base_url`]). Since 0.2.0.
37    BaseUrl(crate::config::BaseUrlError),
38}
39
40impl std::fmt::Display for BuildError {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        match self {
43            BuildError::Config(e) => write!(f, "{e}"),
44            BuildError::Engine(e) => write!(f, "engine: {e}"),
45            BuildError::BaseUrl(e) => write!(f, "configuration: base URL: {e}"),
46        }
47    }
48}
49
50impl std::error::Error for BuildError {}
51
52/// Builds a [`Mesh`].
53pub struct MeshBuilder {
54    config: Config,
55    store: Arc<dyn Store + Send + Sync>,
56    key: Option<SigningKey>,
57    key_file: Option<PathBuf>,
58    runtimes: Vec<Arc<dyn Runtime>>,
59    formula: bool,
60    clock: Arc<dyn Clock>,
61    fuel: Option<u64>,
62    licence: Option<String>,
63    memo_capacity: Option<usize>,
64}
65
66impl std::fmt::Debug for MeshBuilder {
67    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
68        f.debug_struct("MeshBuilder").field("host", &self.config.host).finish_non_exhaustive()
69    }
70}
71
72impl MeshBuilder {
73    /// The mesh's signing key.
74    pub fn signing_key(mut self, key: SigningKey) -> Self {
75        self.key = Some(key);
76        self.key_file = None;
77        self
78    }
79
80    /// The mesh's signing key, from a file of its 32-byte seed (32 bytes or 64 hex digits),
81    /// which must have mode 0600.
82    pub fn signing_key_file(mut self, path: impl Into<PathBuf>) -> Self {
83        self.key_file = Some(path.into());
84        self.key = None;
85        self
86    }
87
88    /// Adds a runtime (the formula runtime is added unless [`MeshBuilder::without_formula`]).
89    pub fn runtime(mut self, runtime: Arc<dyn Runtime>) -> Self {
90        self.runtimes.push(runtime);
91        self
92    }
93
94    /// No formula runtime.
95    pub fn without_formula(mut self) -> Self {
96        self.formula = false;
97        self
98    }
99
100    /// The clock (default: the system clock).
101    pub fn clock(mut self, clock: Arc<dyn Clock>) -> Self {
102        self.clock = clock;
103        self
104    }
105
106    /// The engine's fuel per request.
107    pub fn fuel(mut self, fuel: u64) -> Self {
108        self.fuel = Some(fuel);
109        self
110    }
111
112    /// The licence of the receipts the engine signs.
113    pub fn licence(mut self, licence: impl Into<String>) -> Self {
114        self.licence = Some(licence.into());
115        self
116    }
117
118    /// The engine's memo capacity.
119    pub fn memo_capacity(mut self, n: usize) -> Self {
120        self.memo_capacity = Some(n);
121        self
122    }
123
124    /// Checks the configuration, builds the engine (its key must be published in the store's
125    /// namespace record for the host) and the mesh.
126    pub fn build(self) -> Result<Mesh, BuildError> {
127        if let Some(u) = &self.config.base_url {
128            crate::config::check_base_url(&self.config.host, u).map_err(BuildError::BaseUrl)?;
129        }
130        self.config.check().map_err(BuildError::Config)?;
131        let own_key_id = match (&self.key, &self.key_file) {
132            (Some(k), _) => Some(k.key_id().to_string()),
133            (None, Some(p)) => std::fs::read(p)
134                .ok()
135                .and_then(|b| crate::keynames::seed_of_file(&b))
136                .map(|s| datumesh_core::SigningKey::from_seed(&s).key_id().to_string()),
137            (None, None) => None,
138        };
139        let keys = Arc::new(KeyCache::default());
140        let foreign = Arc::new(Foreign::new(&self.config, self.store.clone(), keys.clone(), self.clock.clone()));
141        let mut b = Engine::builder(self.store.clone(), self.config.host.clone()).clock(self.clock.clone());
142        b = match (self.key, &self.key_file) {
143            (Some(k), _) => b.signing_key(k),
144            (None, Some(p)) => {
145                crate::config::read_secret_file(p).map_err(BuildError::Config)?;
146                b.signing_key_file(p.clone())
147            }
148            (None, None) => b,
149        };
150        let mut runtimes = self.runtimes;
151        if self.formula {
152            runtimes.push(Arc::new(FormulaRuntime::new(self.store.clone())));
153        }
154        if self.config.test_cells {
155            crate::testrun::install_test_cases(&*self.store, &self.config.host)
156                .map_err(|e| BuildError::Config(ConfigError::new("DATUMESH_TEST_CELLS", e)))?;
157            runtimes.push(Arc::new(crate::testrun::TestCases { store: self.store.clone() }));
158        }
159        for rt in runtimes {
160            b = b.runtime(Arc::new(CrossMesh::new(rt, foreign.clone())));
161        }
162        if let Some(f) = self.fuel {
163            b = b.fuel(f);
164        }
165        if let Some(l) = self.licence {
166            b = b.licence(l);
167        }
168        if let Some(n) = self.memo_capacity {
169            b = b.memo_capacity(n);
170        }
171        let engine = b.build().map_err(BuildError::Engine)?;
172        let config = self.config;
173        let embed = config.embed_url.as_deref().map(crate::embed::EmbedClient::new);
174        let inner = Inner {
175            generic: RwLock::new(Arc::new(crate::find::stopwords())),
176            embed,
177            reindex: Mutex::new(()),
178            publish_limits: Mutex::new(crate::bundles::Limits::default()),
179            relays: Mutex::new(HashMap::new()),
180            takeover: Mutex::new(None),
181            find: Mutex::new(None),
182            value_counts_at: Mutex::new(Some(Instant::now())),
183            unnamed: Mutex::new(HashSet::new()),
184            series: Mutex::new(crate::series::Memo::default()),
185            catalog: Mutex::new(None),
186            challenges: Mutex::new(crate::keynames::Challenges::default()),
187            keys_lock: Mutex::new(()),
188            own_key_id,
189            pool: Arc::new(Pool::new(config.pool_size)),
190            jobs: Jobs::new(config.ttl.job, config.max_jobs),
191            limiter: Limiter::new(config.rate.clone()),
192            metrics: Metrics::default(),
193            engine: Arc::new(engine),
194            store: self.store,
195            clock: self.clock,
196            keys,
197            foreign,
198            descriptors: Mutex::new(HashMap::new()),
199            last_good: Mutex::new(HashMap::new()),
200            infos: (0..32).map(|_| Mutex::new(HashMap::new())).collect(),
201            by_hash: (0..32).map(|_| Mutex::new(HashMap::new())).collect(),
202            latest: Latest::new(),
203            targets: Targets::new(),
204            slices: Mutex::new(Vec::new()),
205            known: Mutex::new(crate::describe::Index::default()),
206            started: Instant::now(),
207            config,
208        };
209        let mesh = Mesh { inner: Arc::new(inner) };
210        // The operator's catalogue, then the index: now, and every 30 s (a bundle or a publish
211        // from another process reaches the index within that). The thread stops with the mesh.
212        // On a thread of its own: the store's synchronous client must not run on a runtime's thread.
213        std::thread::scope(|s| {
214            let inner = mesh.inner.clone();
215            let _ = s.spawn(move || crate::find::sync_operator_catalog(&inner)).join();
216        });
217        // The object index (describe of an object id, CONTRACT-round-0.7-P HP2, HP3): on a thread of its own, after
218        // its first delay, then every DATUMESH_INDEX_SECS. Requests read the last build.
219        let weak = Arc::downgrade(&mesh.inner);
220        let delay = mesh.inner.config.index_first_build_delay;
221        if delay.is_zero() {
222            on_scoped_thread(&mesh.inner, Inner::refresh_index);
223        }
224        let spawned = std::thread::Builder::new().name("datumesh-object-index".into()).spawn(move || {
225            let started = Instant::now();
226            loop {
227                let Some(inner) = weak.upgrade() else { break };
228                if started.elapsed() >= delay {
229                    inner.refresh_index();
230                }
231                drop(inner);
232                std::thread::sleep(crate::describe::INDEX_TICK);
233            }
234        });
235        if let Err(e) = spawned {
236            tracing::warn!(error = %e, "the object index thread is not started; describe of an object id answers 503");
237        }
238        // The takeover lists (CONTRACT-0.4.9 H2): built after the series' first delay, then every series refresh
239        // interval (the series' knobs, as the takeover lists are read with the series overview).
240        let weak = Arc::downgrade(&mesh.inner);
241        let (delay, refresh) = (mesh.inner.config.series_first_build_delay, mesh.inner.config.series_refresh);
242        let mut last: Option<Instant> = None;
243        if delay.is_zero() {
244            on_scoped_thread(&mesh.inner, crate::takeover::refresh);
245            last = Some(Instant::now());
246        }
247        let spawned = std::thread::Builder::new().name("datumesh-takeover".into()).spawn(move || {
248            let started = Instant::now();
249            loop {
250                let Some(inner) = weak.upgrade() else { break };
251                if started.elapsed() >= delay && last.is_none_or(|t| t.elapsed() >= refresh) {
252                    crate::takeover::refresh(&inner);
253                    last = Some(Instant::now());
254                }
255                drop(inner);
256                std::thread::sleep(Duration::from_millis(500));
257            }
258        });
259        if let Err(e) = spawned {
260            tracing::warn!(error = %e, "the takeover thread is not started; the takeover pages answer 503");
261        }
262        // The catalogue (CONTRACT-classes-round C7 to C9): its root, its `held` text and its pages, built after the catalogue's
263        // first delay (at start when there is none), then every refresh interval, on a thread of its own. Requests read the
264        // last build. Before the find answers, which take the `held` text from it.
265        // The first build is the thread's, never start's (R11): the thread builds at once when there is no delay.
266        let (delay, refresh) = (mesh.inner.config.catalog_first_build_delay, mesh.inner.config.catalog_refresh);
267        let weak = Arc::downgrade(&mesh.inner);
268        let mut wait = delay;
269        let spawned = std::thread::Builder::new().name("datumesh-catalog".into()).spawn(move || loop {
270            std::thread::sleep(wait);
271            let Some(inner) = weak.upgrade() else { break };
272            crate::catalog_view::rebuild(&inner, "background");
273            drop(inner);
274            wait = refresh;
275        });
276        if let Err(e) = spawned {
277            tracing::warn!(error = %e, "the catalogue thread is not started; the catalogue pages are never built");
278        }
279        // The find answers (CONTRACT-0.4.9 H4): the summary and the empty query's listing, built after the first
280        // delay, then every 300 s. Requests read the last build.
281        let weak = Arc::downgrade(&mesh.inner);
282        let delay = mesh.inner.config.find_first_build_delay;
283        let mut last: Option<Instant> = None;
284        if delay.is_zero() {
285            on_scoped_thread(&mesh.inner, crate::find::refresh);
286            last = Some(Instant::now());
287        }
288        let spawned = std::thread::Builder::new().name("datumesh-find".into()).spawn(move || {
289            let started = Instant::now();
290            loop {
291                let Some(inner) = weak.upgrade() else { break };
292                if started.elapsed() >= delay && last.is_none_or(|t| t.elapsed() >= FIND_REFRESH) {
293                    crate::find::refresh(&inner);
294                    last = Some(Instant::now());
295                }
296                drop(inner);
297                std::thread::sleep(Duration::from_millis(500));
298            }
299        });
300        if let Err(e) = spawned {
301            tracing::warn!(error = %e, "the find thread is not started; the summary and the empty query answer 503");
302        }
303        // The names of the stored tests written before 0.4.9 (CONTRACT-0.4.9 H1): once, in batches, on a thread of
304        // its own; the rows written from now on are named when they are written.
305        let weak = Arc::downgrade(&mesh.inner);
306        let spawned = std::thread::Builder::new().name("datumesh-test-names".into()).spawn(move || {
307            if let Some(inner) = weak.upgrade() {
308                crate::testrun::name_old_tests(&inner);
309            }
310        });
311        if let Err(e) = spawned {
312            tracing::warn!(error = %e, "the test naming thread is not started; old tests stay unnamed");
313        }
314        let weak = Arc::downgrade(&mesh.inner);
315        let spawned = std::thread::Builder::new().name("datumesh-index".into()).spawn(move || loop {
316            let Some(inner) = weak.upgrade() else { break };
317            crate::find::reindex(&inner);
318            drop(inner);
319            std::thread::sleep(Duration::from_secs(30));
320        });
321        if let Err(e) = spawned {
322            tracing::warn!(error = %e, "the index thread is not started; find sees the catalogue as it is at start");
323        }
324        // The series overview (G5): the first build at start (unless a delay is set, then after it), then every
325        // refresh interval, on a thread of its own (the store's client is synchronous: the first build runs on a
326        // scoped thread the caller joins, as the catalogue's does). Requests read the last build; the thread stops
327        // with the mesh.
328        if !mesh.inner.config.series.is_empty() {
329            let weak = Arc::downgrade(&mesh.inner);
330            let (delay, refresh) = (mesh.inner.config.series_first_build_delay, mesh.inner.config.series_refresh);
331            if delay.is_zero() {
332                std::thread::scope(|s| {
333                    let inner = mesh.inner.clone();
334                    let _ = s.spawn(move || crate::series::rebuild(&inner, "background")).join();
335                });
336            }
337            let mut wait = if delay.is_zero() { refresh } else { delay };
338            let spawned = std::thread::Builder::new().name("datumesh-series".into()).spawn(move || loop {
339                std::thread::sleep(wait);
340                let Some(inner) = weak.upgrade() else { break };
341                crate::series::rebuild(&inner, "background");
342                drop(inner);
343                wait = refresh;
344            });
345            if let Err(e) = spawned {
346                tracing::warn!(error = %e, "the series thread is not started; the series overview is never built");
347            }
348        }
349        Ok(mesh)
350    }
351}
352
353/// Runs `f` on a thread of its own and waits for it: the first build of a background answer at start, when no
354/// delay is set (the store's client is synchronous, so it does not run on the caller's thread).
355fn on_scoped_thread(inner: &Arc<Inner>, f: fn(&Inner)) {
356    std::thread::scope(|s| {
357        let inner = inner.clone();
358        let _ = s.spawn(move || f(&inner)).join();
359    });
360}
361
362/// How often the find thread builds its answers again (CONTRACT-0.4.9 H4).
363const FIND_REFRESH: Duration = Duration::from_secs(300);
364
365/// The last `ok` receipt served for a cell, for `stale` answers.
366struct LastGood {
367    info: Arc<ReceiptInfo>,
368    at: Instant,
369}
370
371/// What the mesh needs of a receipt it serves, kept by its bytes (content-addressed: never
372/// stale): its hash, `asof`, trust and its `ok` envelope.
373pub(crate) struct ReceiptInfo {
374    pub(crate) hash: String,
375    pub(crate) asof: String,
376    pub(crate) receipt: Vec<u8>,
377    pub(crate) parsed: Receipt,
378    pub(crate) trust: datumesh_core::TrustLabel,
379    /// The `ok` envelope, the function hash echoed.
380    pub(crate) ok: crate::envelope::Bytes,
381}
382
383pub(crate) struct Inner {
384    pub(crate) config: Config,
385    pub(crate) store: Arc<dyn Store + Send + Sync>,
386    pub(crate) engine: Arc<Engine>,
387    pub(crate) clock: Arc<dyn Clock>,
388    pub(crate) pool: Arc<Pool>,
389    pub(crate) jobs: Jobs,
390    pub(crate) limiter: Limiter,
391    pub(crate) metrics: Metrics,
392    pub(crate) keys: Arc<KeyCache>,
393    pub(crate) foreign: Arc<Foreign>,
394    descriptors: Mutex<HashMap<String, Arc<FunctionDescriptor>>>,
395    last_good: Mutex<HashMap<String, LastGood>>,
396    infos: Vec<Mutex<HashMap<u64, Arc<ReceiptInfo>>>>,
397    by_hash: Vec<Mutex<HashMap<String, Arc<ReceiptInfo>>>>,
398    latest: Latest,
399    targets: Targets,
400    #[allow(clippy::type_complexity)]
401    pub(crate) slices: Mutex<Vec<(String, String, Arc<Vec<datumesh_store::SliceValue>>)>>,
402    /// The index of the objects the mesh knows (describe, short ids).
403    pub(crate) known: Mutex<crate::describe::Index>,
404    pub(crate) started: Instant,
405    /// The generic words `find` never matches values by (CONTRACT-build2-part2-read R3).
406    pub(crate) generic: RwLock<Arc<HashSet<String>>>,
407    /// The embedding service, when `DATUMESH_EMBED_URL` is set (R2).
408    pub(crate) embed: Option<crate::embed::EmbedClient>,
409    /// One index pass at a time.
410    pub(crate) reindex: Mutex<()>,
411    /// The attempts at `POST /bundles`, per host and for the mesh (Build 2 Part 4, P1).
412    pub(crate) publish_limits: Mutex<crate::bundles::Limits>,
413    /// Where a relayed function's source was read, by function name and hash (Build 2 Part 5, F5).
414    pub(crate) relays: Mutex<HashMap<String, (Instant, Option<crate::fnpage::Relay>)>>,
415    /// The last build of the takeover thread: the relayed functions of each source domain (CONTRACT-0.4.9 H2).
416    pub(crate) takeover: Mutex<Option<Arc<crate::takeover::Lists>>>,
417    /// The last build of the find thread: the catalogue summary and the empty query's listing (CONTRACT-0.4.9 H4).
418    pub(crate) find: Mutex<Option<Arc<crate::find::Built>>>,
419    /// When the value counts of the catalogue were last refreshed (H4: once per `DATUMESH_VALUE_COUNTS_SECS`).
420    pub(crate) value_counts_at: Mutex<Option<Instant>>,
421    /// The hashes whose stored tests are not all named yet (the naming thread, CONTRACT-0.4.9 H1): their pages read
422    /// their tests by call, not by name, until it is done.
423    pub(crate) unnamed: Mutex<HashSet<String>>,
424    /// The overviews and dictionary orders of the series pages (Build 2 Part 6, G5).
425    pub(crate) series: Mutex<crate::series::Memo>,
426    /// The catalogue's last build: its root, its `held` text and its pages (CONTRACT-classes-round C7 to C9).
427    pub(crate) catalog: Mutex<Option<Arc<crate::catalog_view::Built>>>,
428    /// The challenges of `POST /x/keys` issued and not yet used (QUESTIONS-build2 D39).
429    pub(crate) challenges: Mutex<crate::keynames::Challenges>,
430    /// One registration at a time: the key document is read and written as a whole.
431    pub(crate) keys_lock: Mutex<()>,
432    /// The id of the mesh's own signing key, when the mesh knows it (a key of another id is a registered one).
433    pub(crate) own_key_id: Option<String>,
434}
435
436/// A Datumesh mesh: the engine behind the endpoints. Cheap to clone (shared).
437#[derive(Clone)]
438pub struct Mesh {
439    pub(crate) inner: Arc<Inner>,
440}
441
442impl std::fmt::Debug for Mesh {
443    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
444        f.debug_struct("Mesh").field("host", &self.inner.config.host).finish_non_exhaustive()
445    }
446}
447
448/// Bindings looked up once per name and asof within one batch.
449pub(crate) struct Memo<'a> {
450    inner: &'a Inner,
451    seen: std::borrow::Cow<'a, Seen>,
452}
453
454/// A binding a batch looks up: the lookup's result once one succeeded, and the lock held
455/// during a lookup, so the batch's chunks, which start together and ask for the same names,
456/// make one store round trip per name and asof, not one each.
457#[derive(Default)]
458struct SeenEntry {
459    found: std::sync::OnceLock<Option<Arc<Bound>>>,
460    lookup: Mutex<()>,
461}
462
463/// The bindings a batch has looked up (shared by its chunks), by name, then asof.
464#[derive(Default)]
465pub(crate) struct Seen(RwLock<HashMap<String, SeenAsofs>>);
466
467/// A name's entries in [`Seen`], by asof.
468type SeenAsofs = Vec<(String, Arc<SeenEntry>)>;
469
470impl Clone for Seen {
471    fn clone(&self) -> Seen {
472        let m = self.0.read().unwrap_or_else(|p| p.into_inner());
473        let copy = m
474            .iter()
475            .map(|(name, v)| {
476                let v = v
477                    .iter()
478                    .map(|(a, e)| (a.clone(), Arc::new(SeenEntry { found: e.found.clone(), lookup: Mutex::new(()) })))
479                    .collect();
480                (name.clone(), v)
481            })
482            .collect();
483        Seen(RwLock::new(copy))
484    }
485}
486
487/// What [`Seen`] has of a name as of an asof.
488enum Held {
489    Found(Option<Arc<Bound>>),
490    Entry(Arc<SeenEntry>),
491    Full,
492}
493
494impl Seen {
495    /// The binding of `fn_name` as of `asof` if found, else its entry (made if there is room:
496    /// 64 asofs per name).
497    fn held(&self, fn_name: &str, asof: &str) -> Held {
498        if let Some(v) = self.0.read().unwrap_or_else(|p| p.into_inner()).get(fn_name) {
499            if let Some((_, e)) = v.iter().find(|(a, _)| a == asof) {
500                return match e.found.get() {
501                    Some(b) => Held::Found(b.clone()),
502                    None => Held::Entry(e.clone()),
503                };
504            }
505        }
506        let mut m = self.0.write().unwrap_or_else(|p| p.into_inner());
507        let v = m.entry(fn_name.to_string()).or_default();
508        if let Some((_, e)) = v.iter().find(|(a, _)| a == asof) {
509            return Held::Entry(e.clone());
510        }
511        if v.len() >= 64 {
512            return Held::Full;
513        }
514        let e = Arc::new(SeenEntry::default());
515        v.push((asof.to_string(), e.clone()));
516        Held::Entry(e)
517    }
518
519    /// The binding of `fn_name` as of `asof`: as found before, else looked up by `look`, at
520    /// most one lookup at a time per name and asof (the others wait for its result). A failed
521    /// lookup is not kept: the next request looks the name up again.
522    pub(crate) fn lookup(
523        &self,
524        fn_name: &str,
525        asof: &str,
526        look: impl FnOnce() -> Result<Option<Arc<Bound>>, ErrorCode>,
527    ) -> Result<Option<Arc<Bound>>, ErrorCode> {
528        let e = match self.held(fn_name, asof) {
529            Held::Found(b) => return Ok(b),
530            Held::Full => return look(),
531            Held::Entry(e) => e,
532        };
533        let _looking = e.lookup.lock().unwrap_or_else(|p| p.into_inner());
534        if let Some(b) = e.found.get() {
535            return Ok(b.clone());
536        }
537        let b = look()?;
538        let _ = e.found.set(b.clone());
539        Ok(b)
540    }
541}
542
543impl<'a> Memo<'a> {
544    pub(crate) fn new(inner: &'a Inner) -> Memo<'a> {
545        Memo { inner, seen: std::borrow::Cow::Owned(Seen::default()) }
546    }
547
548    pub(crate) fn shared(inner: &'a Inner, seen: &'a Seen) -> Memo<'a> {
549        Memo { inner, seen: std::borrow::Cow::Borrowed(seen) }
550    }
551}
552
553impl Bindings for Memo<'_> {
554    fn pinned(&self, fn_hash: &str) -> Result<Option<Arc<Bound>>, ErrorCode> {
555        Bindings::pinned(self.inner, fn_hash)
556    }
557
558    fn alias(&self, alias: &str) -> Option<String> {
559        Bindings::alias(self.inner, alias)
560    }
561
562    fn class(&self, name: &str, asof: &str) -> Result<Option<Arc<call::BoundClass>>, ErrorCode> {
563        Bindings::class(self.inner, name, asof)
564    }
565
566    fn aliases_tx(&self) -> Option<String> {
567        Bindings::aliases_tx(self.inner)
568    }
569
570    fn lookup(&self, class: &str, label: &str, asof: &str) -> Result<Option<String>, ErrorCode> {
571        Bindings::lookup(self.inner, class, label, asof)
572    }
573
574    fn class_name_of(&self, class_hash: &str, asof: &str) -> Result<Option<String>, ErrorCode> {
575        Bindings::class_name_of(self.inner, class_hash, asof)
576    }
577
578    fn class_by_hash(&self, class_hash: &str) -> Result<Option<ClassDescriptor>, ErrorCode> {
579        Bindings::class_by_hash(self.inner, class_hash)
580    }
581
582    fn chain(&self, cell: &CellRef, asof: &str) -> Result<Option<String>, ErrorCode> {
583        Bindings::chain(self.inner, cell, asof)
584    }
585
586    fn cached(&self, fn_hash: &str, rest: &str) -> Option<Arc<Target>> {
587        self.inner.targets.get(fn_hash, rest)
588    }
589
590    fn remember(&self, rest: &str, target: &Arc<Target>) {
591        self.inner.targets.put(rest, target);
592    }
593
594    fn binding(&self, fn_name: &str, asof: &str) -> Result<Option<Arc<Bound>>, ErrorCode> {
595        self.seen.lookup(fn_name, asof, || Bindings::binding(self.inner, fn_name, asof))
596    }
597}
598
599impl Bindings for Inner {
600    fn pinned(&self, fn_hash: &str) -> Result<Option<Arc<Bound>>, ErrorCode> {
601        match self.descriptor(fn_hash) {
602            Ok(d) => Ok(Some(Arc::new(Bound::new(fn_hash, "", d)))),
603            Err(ErrorCode::FnUnavailable) => Ok(None),
604            Err(c) => Err(c),
605        }
606    }
607
608    fn alias(&self, alias: &str) -> Option<String> {
609        self.config.aliases.get(alias).cloned()
610    }
611
612    fn class(&self, name: &str, asof: &str) -> Result<Option<Arc<call::BoundClass>>, ErrorCode> {
613        let c = self.class_binding(name, asof)?;
614        if c.is_some() {
615            self.hear_of_class(name);
616        }
617        Ok(c)
618    }
619
620    /// The mesh's configured alias map has no snapshot.
621    fn aliases_tx(&self) -> Option<String> {
622        None
623    }
624
625    fn class_name_of(&self, class_hash: &str, asof: &str) -> Result<Option<String>, ErrorCode> {
626        match self.store.class_names_bound_to(class_hash, asof) {
627            Ok(names) => Ok(names.into_iter().next()),
628            Err(_) => Err(ErrorCode::InputUnavailable),
629        }
630    }
631
632    fn class_by_hash(&self, class_hash: &str) -> Result<Option<ClassDescriptor>, ErrorCode> {
633        match self.store.class(class_hash) {
634            Ok(Some(bytes)) => ClassDescriptor::from_json(&bytes).map(Some).map_err(|_| ErrorCode::InputUnavailable),
635            Ok(None) => Ok(None),
636            Err(_) => Err(ErrorCode::InputUnavailable),
637        }
638    }
639
640    /// A chain's link: the cell read as of `asof` through the engine, computed or stored (K10). Its value is a key
641    /// encoding; a cell with no value is `None`.
642    fn chain(&self, cell: &CellRef, asof: &str) -> Result<Option<String>, ErrorCode> {
643        let name = format!("{}/{}", cell.ns, cell.fn_name);
644        let Some(b) = Bindings::binding(self, &name, asof)? else { return Ok(None) };
645        let c = datumesh_core::Cell {
646            ns: cell.ns.clone(),
647            fn_name: cell.fn_name.clone(),
648            fn_hash: b.fn_hash.clone(),
649            args: cell.args.clone(),
650        };
651        match self.engine.get_cell(&c, Some(asof)) {
652            Ok(Answer::Receipt(bytes)) => match Receipt::from_json(&bytes).map(|r| r.value().clone()) {
653                Ok(datumesh_core::Scalar::String(k)) => Ok(Some(k)),
654                _ => Ok(None),
655            },
656            Err(EngineError::Store(_)) => Err(ErrorCode::InputUnavailable),
657            _ => Ok(None),
658        }
659    }
660
661    fn lookup(&self, class: &str, label: &str, asof: &str) -> Result<Option<String>, ErrorCode> {
662        let Some(c) = Bindings::class(self, class, asof)? else { return Ok(None) };
663        let Some(method) = &c.descriptor.lookup else { return Ok(None) };
664        let name = format!("{class}/{method}");
665        let Some(b) = Bindings::binding(self, &name, asof)? else { return Ok(None) };
666        let (ns, fn_name) = name.rsplit_once('/').unwrap_or((&name, ""));
667        let mut args = datumesh_core::Args::new();
668        args.insert("label".into(), datumesh_core::Arg::Value(datumesh_core::Scalar::String(label.to_string())));
669        let cell = datumesh_core::Cell { ns: ns.into(), fn_name: fn_name.into(), fn_hash: b.fn_hash.clone(), args };
670        match self.engine.get_cell(&cell, Some(asof)) {
671            Ok(Answer::Receipt(bytes)) => match Receipt::from_json(&bytes).map(|r| r.value().clone()) {
672                Ok(datumesh_core::Scalar::String(k)) => Ok(Some(k)),
673                _ => Ok(None),
674            },
675            // The lookup cell is withdrawn (R1, SPEC 16.7): the label is not_covered with the reason, no receipt.
676            Ok(Answer::Withdrawn { reason, .. }) => {
677                crate::call::set_label_withdrawn(reason);
678                Ok(None)
679            }
680            Err(EngineError::Store(_)) => Err(ErrorCode::InputUnavailable),
681            _ => Ok(None),
682        }
683    }
684
685    fn cached(&self, fn_hash: &str, rest: &str) -> Option<Arc<Target>> {
686        self.targets.get(fn_hash, rest)
687    }
688
689    fn remember(&self, rest: &str, target: &Arc<Target>) {
690        self.targets.put(rest, target);
691    }
692
693    fn binding(&self, fn_name: &str, asof: &str) -> Result<Option<Arc<Bound>>, ErrorCode> {
694        let mut failed = None;
695        if self.foreign.is_foreign(fn_name) {
696            if let Err(e) = self.foreign.ensure_name(fn_name) {
697                tracing::warn!(target: "datumesh_http", name = fn_name, detail = %e.detail, "cross-mesh binding");
698                // `Bindings::binding` answers a bare code: the detail of E_FOREIGN_UNAVAILABLE
699                // waits on this thread for `rejection`, which answers on the same thread.
700                FOREIGN_DETAIL.with(|d| d.set(e.foreign_detail()));
701                failed = Some(e.code);
702            }
703        }
704        let b = self.store.resolve_binding(fn_name, asof).map_err(|e| {
705            tracing::warn!(target: "datumesh_http", error = %e, "resolve_binding");
706            ErrorCode::InputUnavailable
707        })?;
708        // The other mesh is unreachable: a binding imported before still names the cell
709        // (whose answer is then stale or an error), else the name cannot be resolved.
710        if let (Some(code), None) = (failed, &b) {
711            return Err(code);
712        }
713        match b {
714            None => Ok(None),
715            Some(b) => {
716                let d = self.descriptor(&b.fn_hash)?;
717                Ok(Some(Arc::new(Bound::new(b.fn_hash, b.tx, d))))
718            }
719        }
720    }
721}
722
723thread_local! {
724    /// Why the other mesh could not be reached, from the last cross-mesh name resolution on
725    /// this thread (see `Inner::binding` and `Inner::rejection`).
726    static FOREIGN_DETAIL: std::cell::Cell<Option<datumesh_core::ForeignDetail>> = const { std::cell::Cell::new(None) };
727}
728
729/// Latest answers by key: the receipt, the cell id and the asof answered at.
730type LatestShard = RwLock<HashMap<String, (Arc<ReceiptInfo>, String, String)>>;
731
732/// The latest answers of local stored cells, as of when they were answered: such an answer
733/// stands for every later asof until a version of the cell is added, which the mesh is told
734/// of ([`Mesh::stored_version_added`]), as the engine's memo is. It saves the engine's work
735/// (the cell id, the memo) on the hottest path: warm gets of stored cells.
736struct Latest {
737    shards: Vec<LatestShard>,
738    by_cell: Mutex<HashMap<String, Vec<String>>>,
739}
740
741impl Latest {
742    fn new() -> Latest {
743        Latest { shards: (0..32).map(|_| RwLock::new(HashMap::new())).collect(), by_cell: Mutex::new(HashMap::new()) }
744    }
745
746    fn shard(&self, key: &str) -> &LatestShard {
747        use std::hash::{Hash, Hasher};
748        let mut h = std::collections::hash_map::DefaultHasher::new();
749        key.hash(&mut h);
750        &self.shards[(h.finish() % self.shards.len() as u64) as usize]
751    }
752
753    /// The answer for `key` as of `a`, if one answered as of `a` or earlier is held.
754    fn get(&self, key: &str, a: &str) -> Option<Arc<ReceiptInfo>> {
755        let m = self.shard(key).read().unwrap_or_else(|p| p.into_inner());
756        let (info, _, at) = m.get(key)?;
757        (a >= at.as_str()).then(|| info.clone())
758    }
759
760    fn put(&self, key: String, cell_id: String, info: Arc<ReceiptInfo>, at: String) {
761        {
762            let mut b = self.by_cell.lock().unwrap_or_else(|p| p.into_inner());
763            if b.len() > 200_000 {
764                b.clear();
765                for s in &self.shards {
766                    s.write().unwrap_or_else(|p| p.into_inner()).clear();
767                }
768            }
769            b.entry(cell_id.clone()).or_default().push(key.clone());
770        }
771        self.shard(&key).write().unwrap_or_else(|p| p.into_inner()).insert(key, (info, cell_id, at));
772    }
773
774    fn forget(&self, cell_id: &str) {
775        let keys = self.by_cell.lock().unwrap_or_else(|p| p.into_inner()).remove(cell_id).unwrap_or_default();
776        for k in keys {
777            self.shard(&k).write().unwrap_or_else(|p| p.into_inner()).remove(&k);
778        }
779    }
780
781    fn clear(&self) {
782        self.by_cell.lock().unwrap_or_else(|p| p.into_inner()).clear();
783        for s in &self.shards {
784            s.write().unwrap_or_else(|p| p.into_inner()).clear();
785        }
786    }
787}
788
789/// Cell URI rests already parsed, by function hash (parsing depends on the signature
790/// alone): resolving a hot cell costs a binding lookup and no parse.
791struct Targets {
792    #[allow(clippy::type_complexity)]
793    shards: Vec<RwLock<HashMap<String, HashMap<String, Arc<Target>>>>>,
794}
795
796impl Targets {
797    fn new() -> Targets {
798        Targets { shards: (0..32).map(|_| RwLock::new(HashMap::new())).collect() }
799    }
800
801    #[allow(clippy::type_complexity)]
802    fn shard(&self, rest: &str) -> &RwLock<HashMap<String, HashMap<String, Arc<Target>>>> {
803        use std::hash::{Hash, Hasher};
804        let mut h = std::collections::hash_map::DefaultHasher::new();
805        rest.hash(&mut h);
806        &self.shards[(h.finish() % self.shards.len() as u64) as usize]
807    }
808
809    fn get(&self, fn_hash: &str, rest: &str) -> Option<Arc<Target>> {
810        self.shard(rest).read().unwrap_or_else(|p| p.into_inner()).get(rest)?.get(fn_hash).cloned()
811    }
812
813    fn put(&self, rest: &str, t: &Arc<Target>) {
814        let mut m = self.shard(rest).write().unwrap_or_else(|p| p.into_inner());
815        if m.len() >= 4_096 {
816            m.clear();
817        }
818        let v = m.entry(rest.to_string()).or_default();
819        if v.len() >= 8 {
820            v.clear();
821        }
822        v.insert(t.bound.fn_hash.clone(), t.clone());
823    }
824}
825
826/// The key of a cell's last good answer: the function hash and the URI (without asof: the
827/// last good answer is kept for requests about now only).
828fn last_good_key(t: &Target) -> String {
829    t.cell_key().to_string()
830}
831
832/// The engine's error as an envelope code (the engine's table, "For the HTTP layer").
833pub(crate) fn engine_code(e: &EngineError) -> (bool, ErrorCode) {
834    match e {
835        EngineError::Invalid(e) if envelope::is_request_code(e.code()) => (true, e.code()),
836        EngineError::Invalid(e) if envelope::is_error_code(e.code()) => (false, e.code()),
837        EngineError::NameUnresolved { .. } => (false, ErrorCode::FnUnavailable),
838        EngineError::UndeclaredInput { .. } => (false, ErrorCode::InputUndeclared),
839        EngineError::Sign(e) if envelope::is_error_code(e.code()) => (false, e.code()),
840        EngineError::Store(_) => (false, ErrorCode::InputUnavailable),
841        _ => (false, ErrorCode::EvalUnavailable),
842    }
843}
844
845impl Inner {
846    pub(crate) fn now(&self) -> String {
847        self.clock.now()
848    }
849
850    /// Whether the stored tests of `fn_hash` are not all named yet (see [`Inner::unnamed`]).
851    pub(crate) fn is_unnamed(&self, fn_hash: &str) -> bool {
852        self.unnamed.lock().unwrap_or_else(|p| p.into_inner()).contains(fn_hash)
853    }
854
855    /// A descriptor by hash (cached: content-addressed).
856    pub(crate) fn descriptor(&self, fn_hash: &str) -> Result<Arc<FunctionDescriptor>, ErrorCode> {
857        if let Some(d) = self.descriptors.lock().unwrap_or_else(|p| p.into_inner()).get(fn_hash) {
858            return Ok(d.clone());
859        }
860        let bytes = self.store.descriptor(fn_hash).ok_or(ErrorCode::FnUnavailable)?;
861        let d = Arc::new(FunctionDescriptor::from_json(&bytes).map_err(|_| ErrorCode::FnUnavailable)?);
862        let mut m = self.descriptors.lock().unwrap_or_else(|p| p.into_inner());
863        if m.len() > 10_000 {
864            m.clear();
865        }
866        m.insert(fn_hash.to_string(), d.clone());
867        Ok(d)
868    }
869
870    /// The `ok` reply with a receipt, remembered for `stale` answers.
871    fn ok_reply(
872        &self,
873        target: &Target,
874        info: Arc<ReceiptInfo>,
875        a: &str,
876        now: &str,
877        private: bool,
878        link: bool,
879    ) -> Reply {
880        let mut reply = Reply::json(200, info.ok.clone(), Cache::Immutable);
881        if target.asof().is_none() {
882            let mut lg = self.last_good.lock().unwrap_or_else(|p| p.into_inner());
883            if lg.len() > 100_000 {
884                lg.clear();
885            }
886            lg.insert(last_good_key(target), LastGood { info, at: Instant::now() });
887        }
888        self.cache_rules(&mut reply, target, a, now, private, link);
889        reply
890    }
891
892    /// Remembers the answer as of now `a` for a local stored cell, when it is the cell's
893    /// latest version (a version with a later `tx` would answer later asofs).
894    fn remember_latest(&self, target: &Target, info: &Arc<ReceiptInfo>, a: &str) {
895        match self.store.latest(target.cell_id()) {
896            Ok(Some(v)) if v.receipt_hash == info.hash => {
897                self.latest.put(
898                    target.cell_key().to_string(),
899                    target.cell_id().to_string(),
900                    info.clone(),
901                    a.to_string(),
902                );
903            }
904            _ => {}
905        }
906    }
907
908    /// A stored version was added for `cell_id`: the engine's memo, the latest answers and
909    /// the slice cache forget what rests on it.
910    pub(crate) fn version_added(&self, cell_id: &str) {
911        self.engine.stored_version_added(cell_id);
912        self.latest.forget(cell_id);
913        self.slices.lock().unwrap_or_else(|p| p.into_inner()).clear();
914        self.index_stored_now(cell_id);
915    }
916
917    /// The receipt's hash, asof, trust and `ok` envelope (cached by its bytes).
918    fn receipt_info(&self, bytes: &[u8]) -> Option<Arc<ReceiptInfo>> {
919        use std::hash::{Hash, Hasher};
920        let mut h = std::collections::hash_map::DefaultHasher::new();
921        bytes.hash(&mut h);
922        let key = h.finish();
923        let shard = &self.infos[(key % self.infos.len() as u64) as usize];
924        if let Some(i) = shard.lock().unwrap_or_else(|p| p.into_inner()).get(&key) {
925            if i.receipt == bytes {
926                return Some(i.clone());
927            }
928        }
929        let r = Receipt::from_json(bytes).ok()?;
930        let trust = envelope::trust_label_of(&r, &self.config.host);
931        let ok = envelope::with_fn_hash(datumesh_core::Answer::ok(r.clone(), trust), Some(&r.cell().fn_hash)).to_json();
932        let info = Arc::new(ReceiptInfo {
933            hash: r.hash().to_string(),
934            asof: r.asof().to_string(),
935            receipt: bytes.to_vec(),
936            parsed: r,
937            trust,
938            ok: ok.into(),
939        });
940        let mut m = shard.lock().unwrap_or_else(|p| p.into_inner());
941        if m.len() >= 4_096 {
942            m.clear();
943        }
944        m.insert(key, info.clone());
945        Some(info)
946    }
947
948    /// A receipt's info by its hash: from the cache, else the store.
949    pub(crate) fn receipt_info_by_hash(&self, hash: &str) -> Option<Arc<ReceiptInfo>> {
950        use std::hash::{Hash, Hasher};
951        let mut h = std::collections::hash_map::DefaultHasher::new();
952        hash.hash(&mut h);
953        let shard = &self.by_hash[(h.finish() % self.by_hash.len() as u64) as usize];
954        if let Some(i) = shard.lock().unwrap_or_else(|p| p.into_inner()).get(hash) {
955            return Some(i.clone());
956        }
957        let bytes = self.store.receipt(hash)?;
958        let info = self.receipt_info(&bytes)?;
959        let mut m = shard.lock().unwrap_or_else(|p| p.into_inner());
960        if m.len() >= 2_048 {
961            m.clear();
962        }
963        m.insert(hash.to_string(), info.clone());
964        Some(info)
965    }
966
967    /// The reply to a request the call parser rejected.
968    pub(crate) fn rejection(&self, r: Rejection, asof: Option<&str>) -> Reply {
969        match r {
970            Rejection::BadRequest(c) => envelope::bad_request_reply(c),
971            Rejection::NotCovered => {
972                let _ = asof;
973                let fault = crate::call::take_fault();
974                Reply::json(404, envelope::not_covered(fault), Cache::Public(self.config.ttl.latest_max_age.as_secs()))
975            }
976            Rejection::Error(ErrorCode::NameUnbound) => match crate::call::take_label_withdrawn() {
977                Some(reason) => match datumesh_core::Answer::label_withdrawn(&reason) {
978                    Ok(a) => envelope::answer_reply(&a, Cache::Public(self.config.ttl.latest_max_age.as_secs())),
979                    Err(_) => envelope::name_unbound_reply(self.config.ttl.latest_max_age.as_secs()),
980                },
981                None => envelope::name_unbound_reply(self.config.ttl.latest_max_age.as_secs()),
982            },
983            Rejection::Error(ErrorCode::ForeignUnavailable) => {
984                // The other mesh could not be reached while resolving the name (spec-0.4.3).
985                let d = FOREIGN_DETAIL.with(|d| d.take()).unwrap_or(datumesh_core::ForeignDetail::Network);
986                envelope::answer_reply(&datumesh_core::Answer::foreign_unavailable(d), Cache::NoStore)
987            }
988            Rejection::Error(c) => envelope::error_reply(c),
989        }
990    }
991
992    /// The licence and payment rules for a target and principal: a refusal, and whether the
993    /// answer depends on who asks.
994    pub(crate) fn policy(&self, target: &Target, principal: Option<&Principal>) -> (Option<Reply>, bool) {
995        if self.config.policy.rules.is_empty() {
996            return (None, false);
997        }
998        match self.config.policy.rule(&target.fn_name()) {
999            None => (None, false),
1000            Some(Rule::Principals(ps)) => {
1001                if principal.is_some_and(|p| ps.contains(&p.id)) {
1002                    (None, true)
1003                } else {
1004                    let a = envelope::with_fn_hash(datumesh_core::Answer::unlicensed(), Some(&target.bound.fn_hash));
1005                    (Some(envelope::answer_reply(&a, Cache::Private)), true)
1006                }
1007            }
1008            Some(Rule::Price { amount, currency }) => {
1009                let authorise = format!("{}/pay/{}", self.config.origin(), target.cell_id());
1010                let quote = datumesh_core::Quote { amount: amount.clone(), currency: currency.clone(), authorise };
1011                let a =
1012                    envelope::with_fn_hash(datumesh_core::Answer::payment_required(quote), Some(&target.bound.fn_hash));
1013                (Some(envelope::answer_reply(&a, Cache::Private)), true)
1014            }
1015        }
1016    }
1017
1018    /// Answers a `/cell` request (blocking; no budget: see [`Mesh::cell`]). `on_target` is
1019    /// told the request description as soon as it is known (for `pending`).
1020    pub(crate) fn answer(
1021        &self,
1022        rest: &str,
1023        principal: Option<&Principal>,
1024        bindings: &dyn Bindings,
1025        now: &str,
1026        on_target: &mut dyn FnMut(&Target),
1027    ) -> Reply {
1028        self.answer_with(rest, principal, bindings, now, on_target, true)
1029    }
1030
1031    /// As [`Inner::answer`]; without the canonical link when `link` is false (a batch's
1032    /// envelopes have no headers).
1033    pub(crate) fn answer_with(
1034        &self,
1035        rest: &str,
1036        principal: Option<&Principal>,
1037        bindings: &dyn Bindings,
1038        now: &str,
1039        on_target: &mut dyn FnMut(&Target),
1040        link: bool,
1041    ) -> Reply {
1042        let target = match call::resolve(rest, now, &self.config.aliases, bindings, false) {
1043            Ok(t) => t,
1044            // `N[label]` with no method is the object's describe (K8, the classes round). A raw `[`/`]` is not
1045            // a name, so the cell URI's name check refuses it as E_CANON_NAME before this form is seen; the
1046            // class part is what must be a name here.
1047            Err(Rejection::BadRequest(code @ (ErrorCode::ParseUri | ErrorCode::CanonName)))
1048                if crate::call::url_decode(rest).is_some_and(|d| {
1049                    crate::describe::label_form(&d)
1050                        .is_some_and(|(class, _, _)| datumesh_core::lexical::check_function_name(&class, "$").is_ok())
1051                }) =>
1052            {
1053                let text = crate::call::url_decode(rest).unwrap_or_default();
1054                if let Some(reply) = self.describe_label(bindings, &text, now) {
1055                    return reply;
1056                }
1057                return self.rejection(Rejection::BadRequest(code), None);
1058            }
1059            Err(r) => return self.rejection(r, None),
1060        };
1061        on_target(&target);
1062        let (refused, private) = self.policy(&target, principal);
1063        let reply = match refused {
1064            Some(r) => r,
1065            None => self.answer_target(&target, now, private, link),
1066        };
1067        // What the request resolved is per request: the answers are built from cached bytes.
1068        match &target.resolved {
1069            Some(r) => envelope::with_resolved(reply, r),
1070            None => reply,
1071        }
1072    }
1073
1074    /// Answers a resolved target as of its asof (or `now`).
1075    pub(crate) fn answer_target(&self, target: &Target, now: &str, private: bool, link: bool) -> Reply {
1076        let a = target.asof().unwrap_or(now);
1077        let stored = target.bound.descriptor.lang == "stored";
1078        let local = stored && !self.foreign.is_foreign(&target.cell.ns);
1079        if local {
1080            if let Some(info) = self.latest.get(target.cell_key(), a) {
1081                let mut reply = Reply::json(200, info.ok.clone(), Cache::Immutable);
1082                self.cache_rules(&mut reply, target, a, now, private, link);
1083                return reply;
1084            }
1085        }
1086        if let Err(e) = self.foreign.prepare(&target.cell, stored, target.asof()) {
1087            return self.unavailable(target, e);
1088        }
1089        // Since 0.2.1: before computing another mesh's function, its publisher's key document
1090        // (its declarations, SPEC 8.5), fetched again after its TTL.
1091        if !stored {
1092            if let Err(e) = self.foreign.ensure_publisher(&target.cell.ns) {
1093                return self.unavailable(target, e);
1094            }
1095        }
1096        let mut attempt = 0;
1097        loop {
1098            let r = self.engine.get_cell(&target.cell, Some(a));
1099            let inval = self.foreign.take_invalidated();
1100            for id in &inval {
1101                self.version_added(id);
1102            }
1103            if !inval.is_empty() && attempt < 2 {
1104                attempt += 1;
1105                continue;
1106            }
1107            // A formula cell answered: the describe index learns of it (CONTRACT-1.8b H4).
1108            if !stored && matches!(r, Ok(Answer::Receipt(_))) {
1109                self.index_cell_now(&target.cell);
1110            }
1111            return match r {
1112                Ok(Answer::Receipt(bytes)) => {
1113                    let Some(info) = self.receipt_info(&bytes) else {
1114                        return envelope::error_answer_reply(ErrorCode::EvalUnavailable, Some(&target.bound.fn_hash));
1115                    };
1116                    if attempt < 2 {
1117                        match self.foreign.refresh_deps(&info.hash, a) {
1118                            Ok(true) => {
1119                                for id in self.foreign.take_invalidated() {
1120                                    self.version_added(&id);
1121                                }
1122                                attempt += 1;
1123                                continue;
1124                            }
1125                            Ok(false) => {}
1126                            Err(e) => return self.unavailable(target, e),
1127                        }
1128                    }
1129                    if local && target.asof().is_none() {
1130                        self.remember_latest(target, &info, a);
1131                    }
1132                    self.ok_reply(target, info, a, now, private, link)
1133                }
1134                Ok(Answer::Withdrawn { receipt, reason: _ }) => {
1135                    // R1: the cell's latest version is a withdrawal: `not_covered` with the withdrawal, its trust and reason.
1136                    let built = datumesh_core::Withdrawal::from_json(&receipt).ok().and_then(|w| {
1137                        let trust = envelope::trust_label_of_withdrawal(&w, &self.config.host);
1138                        datumesh_core::Answer::withdrawn(w, trust).ok()
1139                    });
1140                    let Some(ans) = built else {
1141                        return envelope::error_answer_reply(ErrorCode::EvalUnavailable, Some(&target.bound.fn_hash));
1142                    };
1143                    let ans = envelope::with_fn_hash(ans, Some(&target.bound.fn_hash));
1144                    let mut reply = envelope::answer_reply(&ans, Cache::Public(0));
1145                    self.cache_rules(&mut reply, target, a, now, private, link);
1146                    if target.asof().is_some() {
1147                        reply.cache = if private {
1148                            Cache::Private
1149                        } else {
1150                            Cache::Public(self.config.ttl.latest_max_age.as_secs())
1151                        };
1152                    }
1153                    reply
1154                }
1155                Ok(Answer::NotCovered { fault }) => {
1156                    let mut ans =
1157                        envelope::with_fn_hash(datumesh_core::Answer::not_covered(), Some(&target.bound.fn_hash));
1158                    if let Some(f) = fault {
1159                        ans = ans.with_fault(f);
1160                    }
1161                    let mut reply = envelope::answer_reply(&ans, Cache::Public(0));
1162                    self.cache_rules(&mut reply, target, a, now, private, link);
1163                    if target.asof().is_some() {
1164                        reply.cache = if private {
1165                            Cache::Private
1166                        } else {
1167                            Cache::Public(self.config.ttl.latest_max_age.as_secs())
1168                        };
1169                    }
1170                    reply
1171                }
1172                Ok(_) => envelope::error_answer_reply(ErrorCode::EvalUnavailable, Some(&target.bound.fn_hash)),
1173                Err(EngineError::Unlicensed { cell_id, reason }) => {
1174                    // Licence inheritance refuses the cell (SPEC 8.5, spec-0.4.3): `unlicensed`,
1175                    // no new code. Not immutable: a declaration may come later.
1176                    tracing::info!(target: "datumesh_http", cell_id = %cell_id, reason = reason.as_str(), "unlicensed");
1177                    let a = envelope::with_fn_hash(datumesh_core::Answer::unlicensed(), Some(&target.bound.fn_hash));
1178                    let cache =
1179                        if private { Cache::Private } else { Cache::Public(self.config.ttl.latest_max_age.as_secs()) };
1180                    envelope::answer_reply(&a, cache)
1181                }
1182                Err(EngineError::Cycle { path }) => {
1183                    return self.cycle_reply(&path, Some(a), Some(&target.bound.fn_hash))
1184                }
1185                Err(e) => {
1186                    let (bad, code) = engine_code(&e);
1187                    tracing::info!(target: "datumesh_http", error = %e, code = code.as_str(), "engine");
1188                    if code == ErrorCode::ForeignUnavailable {
1189                        // A cross-mesh fetch inside the evaluation got no response (ForeignError::eval).
1190                        let detail = match &e {
1191                            EngineError::Invalid(c) => {
1192                                c.detail().strip_prefix("cross-mesh: ").unwrap_or(c.detail()).to_string()
1193                            }
1194                            other => other.to_string(),
1195                        };
1196                        return self.unavailable(target, ForeignError { code, detail });
1197                    }
1198                    if bad {
1199                        envelope::bad_request_reply(code)
1200                    } else if code == ErrorCode::InputUnavailable {
1201                        self.unavailable(target, ForeignError { code, detail: e.to_string() })
1202                    } else {
1203                        envelope::error_answer_reply(code, Some(&target.bound.fn_hash))
1204                    }
1205                }
1206            };
1207        }
1208    }
1209
1210    fn cache_rules(&self, reply: &mut Reply, target: &Target, a: &str, now: &str, private: bool, link: bool) {
1211        let latest = self.config.ttl.latest_max_age.as_secs();
1212        reply.cache = if private {
1213            Cache::Private
1214        } else {
1215            match target.asof() {
1216                Some(x) if x <= now => Cache::Immutable,
1217                Some(_) => Cache::Public(latest),
1218                None => Cache::Public(latest),
1219            }
1220        };
1221        if link && target.asof().is_none() {
1222            reply.canonical = Some(format!("{}/cell/{}", self.config.origin(), target.rest_asof(a)));
1223        }
1224    }
1225
1226    /// The answer when something the mesh depends on failed: `stale` with the last receipt
1227    /// it served for the cell, when it has one that answers the request; else `error`.
1228    fn unavailable(&self, target: &Target, e: ForeignError) -> Reply {
1229        tracing::info!(target: "datumesh_http", code = e.code.as_str(), detail = %e.detail, "unavailable");
1230        // A suspended namespace (9.9, 5.5): the import is refused, so `not_covered` with its error,
1231        // and not the last receipt served (a cell served before is served as before, not imported).
1232        if e.code == crate::foreign::NAMESPACE_SUSPENDED {
1233            if let Ok(a) = datumesh_core::Answer::not_covered().with_error(ErrorCode::NamespaceSuspended) {
1234                return envelope::answer_reply(&envelope::with_fn_hash(a, Some(&target.bound.fn_hash)), Cache::NoStore);
1235            }
1236        }
1237        let lg = self.last_good.lock().unwrap_or_else(|p| p.into_inner());
1238        if let Some(g) = lg.get(&last_good_key(target)) {
1239            if target.asof().is_none_or(|a| g.info.asof.as_str() <= a) {
1240                let age = g.at.elapsed().as_secs();
1241                let a = datumesh_core::Answer::stale(g.info.parsed.clone(), g.info.trust, age);
1242                let a = envelope::with_fn_hash(a, Some(&g.info.parsed.cell().fn_hash));
1243                return envelope::answer_reply(&a, Cache::NoStore);
1244            }
1245        }
1246        if let Some(d) = e.foreign_detail() {
1247            let a = envelope::with_fn_hash(datumesh_core::Answer::foreign_unavailable(d), Some(&target.bound.fn_hash));
1248            return envelope::answer_reply(&a, Cache::NoStore);
1249        }
1250        envelope::error_answer_reply(e.code, Some(&target.bound.fn_hash))
1251    }
1252
1253    /// The keys to verify `receipt` with: the documents of its signer and of the signers of
1254    /// its inputs and slice members held in the store, from the cache or the store's
1255    /// namespace records.
1256    pub(crate) fn keys_for_receipt(&self, receipt: &[u8]) -> Keys {
1257        let mut hosts = std::collections::BTreeSet::new();
1258        if let Ok(v) = json::parse(receipt) {
1259            if let Some(h) = v.get("computed_by").and_then(Value::as_str) {
1260                hosts.insert(h.split('#').next().unwrap_or("").to_string());
1261            }
1262            if let Some(Value::Array(ins)) = v.get("inputs") {
1263                let mut members = Vec::new();
1264                for i in ins.iter().filter_map(Value::as_str).take(10_000) {
1265                    if i.starts_with("slice:") {
1266                        if let Some(m) =
1267                            self.store.manifest(i).and_then(|m| datumesh_core::Manifest::from_json(&m).ok())
1268                        {
1269                            members.extend(m.members().iter().take(10_000).cloned());
1270                        }
1271                    } else {
1272                        members.push(i.to_string());
1273                    }
1274                }
1275                for h in members.iter().take(20_000) {
1276                    if let Some(r) = self.store.receipt(h).and_then(|b| Receipt::from_json(&b).ok()) {
1277                        hosts.insert(r.signer_host().to_string());
1278                    }
1279                }
1280            }
1281        }
1282        let mut keys = Keys::new();
1283        for h in hosts {
1284            if let Some(r) = self.keys.result(&h) {
1285                keys.insert_result(&h, r);
1286            } else if let Some(doc) = self.key_doc(&h) {
1287                keys.insert(doc);
1288            }
1289        }
1290        keys
1291    }
1292
1293    /// A host's key document: the cache's, else the store's namespace record.
1294    fn key_doc(&self, host: &str) -> Option<KeyDoc> {
1295        if let Some((d, _, _)) = self.keys.get(host) {
1296            return Some(d);
1297        }
1298        let ns = self.store.namespace(host).ok()??;
1299        keys_from_response(host, 200, Some(&ns.keydoc)).ok()
1300    }
1301}
1302
1303fn verified(r: datumesh_core::VerifyResult) -> Verified {
1304    let s = |v: Option<&str>| v.map(|x| Value::String(x.to_string())).unwrap_or(Value::Null);
1305    let body = Value::Object(vec![
1306        ("blob_checked".into(), Value::Bool(r.blob_checked)),
1307        ("code".into(), s(r.code.map(|c| c.as_str()))),
1308        ("computed_by".into(), s(r.computed_by.as_deref())),
1309        ("detail".into(), Value::String(r.detail.clone())),
1310        ("hash".into(), s(r.hash.as_deref())),
1311        ("level".into(), s(r.level.map(|l| l.as_str()))),
1312        ("ok".into(), Value::Bool(r.ok)),
1313        ("path".into(), Value::String(r.path.clone())),
1314    ]);
1315    Verified { body: body.to_jcs() }
1316}
1317
1318/// What `POST /verify` reports.
1319#[derive(Clone, Debug, PartialEq, Eq)]
1320pub struct Verified {
1321    /// The result as JSON (`ok`, `level`, `code`, `hash`, `computed_by`, `path`, `detail`).
1322    pub body: Vec<u8>,
1323}
1324
1325impl Mesh {
1326    /// A builder for a mesh on `store` with `config`.
1327    pub fn builder(config: Config, store: Arc<dyn Store + Send + Sync>) -> MeshBuilder {
1328        MeshBuilder {
1329            config,
1330            store,
1331            key: None,
1332            key_file: None,
1333            runtimes: Vec::new(),
1334            formula: true,
1335            clock: Arc::new(SystemClock),
1336            fuel: None,
1337            licence: None,
1338            memo_capacity: None,
1339        }
1340    }
1341
1342    /// The configuration.
1343    pub fn config(&self) -> &Config {
1344        &self.inner.config
1345    }
1346
1347    /// The engine.
1348    pub fn engine(&self) -> &Arc<Engine> {
1349        &self.inner.engine
1350    }
1351
1352    /// Forgets every memoised answer (the engine's memo and the mesh's), for a process that
1353    /// wrote versions without telling the mesh.
1354    pub fn clear_memo(&self) {
1355        self.inner.engine.clear_memo();
1356        self.inner.latest.clear();
1357        self.inner.slices.lock().unwrap_or_else(|p| p.into_inner()).clear();
1358    }
1359
1360    /// The cross-mesh resolver.
1361    pub fn foreign(&self) -> &Foreign {
1362        &self.inner.foreign
1363    }
1364
1365    /// The store.
1366    pub fn store(&self) -> &Arc<dyn Store + Send + Sync> {
1367        &self.inner.store
1368    }
1369
1370    /// The key documents the mesh holds for other hosts (fetched, or inserted here): what
1371    /// `POST /verify` verifies with, besides the store's namespace records.
1372    pub fn keys(&self) -> &KeyCache {
1373        &self.inner.keys
1374    }
1375
1376    /// Tells the engine that a stored version was added for `cell_id` outside the mesh.
1377    pub fn stored_version_added(&self, cell_id: &str) {
1378        self.inner.version_added(cell_id);
1379    }
1380
1381    /// The envelope for `rest` (a call or a cell URI's rest, query included, as received at
1382    /// `/cell/`), for `principal`. Blocking, and without a budget: what a `/cell` request
1383    /// gets when it finishes within its budget, or its job's result.
1384    pub fn cell(&self, rest: &str, principal: Option<&Principal>) -> Reply {
1385        let now = self.inner.now();
1386        self.inner.answer(rest, principal, &*self.inner, &now, &mut |_| {})
1387    }
1388
1389    /// The envelopes of a batch, in order (blocking, no budget).
1390    pub fn cells(&self, rests: &[String], principal: Option<&Principal>) -> Vec<Reply> {
1391        let now = self.inner.now();
1392        let memo = Memo::new(&self.inner);
1393        rests.iter().map(|r| self.inner.answer(r, principal, &memo, &now, &mut |_| {})).collect()
1394    }
1395
1396    /// Resolves a request to its cell, as `/cell` does (or to its slice, with `slice`).
1397    pub fn resolve(&self, rest: &str, slice: bool) -> Result<Arc<Target>, Rejection> {
1398        let now = self.inner.now();
1399        call::resolve(rest, &now, &self.inner.config.aliases, &*self.inner, slice)
1400    }
1401
1402    /// The describe answer (SPEC 16.8, 9.6) for `id`: a class name, an object's key encoding, an
1403    /// object id, a cell id or a short id (12 hex digits). A class or an object: the body is a
1404    /// `describe-class` or `describe-object` document, `200`; an id the mesh does not know, `404`;
1405    /// a short id naming more than one object or cell the mesh knows, `400` with
1406    /// `E_SHORT_ID_AMBIGUOUS`. A class hash is not an id (9.6). Blocking. Since 0.2.2.
1407    pub fn describe(&self, id: &str) -> Reply {
1408        self.inner.describe(id)
1409    }
1410
1411    /// `POST /whatif` (5.9): the scenario answer to the request's body (see [`crate::scenario`]).
1412    pub(crate) fn whatif(&self, body: &[u8], principal: Option<&Principal>) -> Reply {
1413        self.inner.whatif(body, principal)
1414    }
1415
1416    /// `POST /x/calc` (Build 2 Part 3, `calc`): see [`crate::calc`].
1417    pub(crate) fn calc(&self, body: &[u8], principal: Option<&Principal>) -> Reply {
1418        self.inner.calc(body, principal)
1419    }
1420
1421    /// Verifies a receipt (SPEC 10.1) with the mesh's keys; at level `recomputed` with the
1422    /// engine as the resolver unless `signed_only`; `blob` is content for step 7.7.
1423    pub fn verify(&self, receipt: &[u8], signed_only: bool, blob: Option<&[u8]>) -> Verified {
1424        let keys = self.inner.keys_for_receipt(receipt);
1425        let resolver: Option<&dyn datumesh_core::Resolver> =
1426            if signed_only { None } else { Some(&*self.inner.engine as &dyn datumesh_core::Resolver) };
1427        verified(verify(receipt, &keys, resolver, blob))
1428    }
1429
1430    /// Verifies a receipt with the mesh's keys and what the caller offers for step 7: a
1431    /// `recompute` object as SPEC 11 describes it (`descriptor`, `inputs`, `manifests`,
1432    /// `lineage`, `value`), the core's `MapResolver` over it. Without one, steps 1-6 only.
1433    pub fn verify_offered(&self, receipt: &[u8], recompute: Option<&Value>, blob: Option<&[u8]>) -> Verified {
1434        let mut keys = self.inner.keys_for_receipt(receipt);
1435        // The signers of the receipts offered for step 7 too.
1436        let mut hosts = std::collections::BTreeSet::new();
1437        for (_, r) in recompute.and_then(|rc| rc.get("inputs")).and_then(Value::as_object).unwrap_or(&[]) {
1438            if let Some(h) = r
1439                .as_str()
1440                .and_then(|t| json::parse(t.as_bytes()).ok())
1441                .and_then(|v| v.get("computed_by").and_then(Value::as_str).map(str::to_string))
1442            {
1443                hosts.insert(h.split('#').next().unwrap_or("").to_string());
1444            }
1445        }
1446        for h in hosts {
1447            if let Some(r) = self.inner.keys.result(&h) {
1448                keys.insert_result(&h, r);
1449            } else if let Some(doc) = self.inner.key_doc(&h) {
1450                keys.insert(doc);
1451            }
1452        }
1453        let Some(rc) = recompute else {
1454            return verified(verify(receipt, &keys, None, blob));
1455        };
1456        let mut m = datumesh_core::MapResolver::new();
1457        let cell = json::parse(receipt).ok().and_then(|r| r.get("cell").cloned());
1458        if let (Some(d), Some(h)) =
1459            (rc.get("descriptor"), cell.as_ref().and_then(|c| c.get("fn_hash")).and_then(Value::as_str))
1460        {
1461            m.insert_descriptor(h, d.to_jcs());
1462        }
1463        for (h, r) in rc.get("inputs").and_then(Value::as_object).unwrap_or(&[]) {
1464            m.insert_receipt(h.as_str(), r.as_str().unwrap_or("").as_bytes());
1465        }
1466        for (e, t) in rc.get("manifests").and_then(Value::as_object).unwrap_or(&[]) {
1467            m.insert_manifest(e.as_str(), t.as_str().unwrap_or("").as_bytes());
1468        }
1469        let value = rc.get("value").and_then(|v| datumesh_core::Scalar::from_json(&v.to_jcs()).ok());
1470        if let (Some(value), Some(c)) = (value, cell.as_ref().and_then(|c| datumesh_core::Cell::from_value(c).ok())) {
1471            m.insert_value(c.id(), value);
1472            if let Some(Value::Array(l)) = rc.get("lineage") {
1473                m.insert_lineage(c.id(), l.iter().filter_map(Value::as_str));
1474            }
1475        }
1476        verified(verify(receipt, &keys, Some(&m), blob))
1477    }
1478
1479    /// The mesh document (SPEC 9.6) this mesh serves: its URLs on the base URL when one is
1480    /// set ([`Config::base_url`]), else on `https://<host>`.
1481    pub fn mesh_document(&self) -> Vec<u8> {
1482        let o = self.inner.config.mesh_document_base();
1483        let mut ep: BTreeMap<&str, String> = [
1484            ("blob", format!("{o}/blob/{{sha256}}")),
1485            ("cell", format!("{o}/cell/{{cell}}")),
1486            ("cells", format!("{o}/cells")),
1487            ("x_bundles", format!("{o}/bundles")),
1488            ("x_calc", format!("{o}/x/calc")),
1489            ("x_interval", format!("{o}/x/interval/{{function}}")),
1490            ("describe", format!("{o}/describe/{{id}}")),
1491            ("descriptor", format!("{o}/descriptor/{{hash}}")),
1492            ("explain", format!("{o}/explain/{{cell}}")),
1493            ("find", format!("{o}/find")),
1494            ("jobs", format!("{o}/jobs/{{job}}")),
1495            ("manifest", format!("{o}/manifest/{{slice_id}}/{{members_hash}}")),
1496            ("receipt", format!("{o}/receipt/{{hash}}")),
1497            ("slice", format!("{o}/slice/{{cell}}")),
1498            ("verify", format!("{o}/verify")),
1499            ("whatif", format!("{o}/whatif")),
1500            ("versions", format!("{o}/versions/{{cell}}")),
1501        ]
1502        .into_iter()
1503        .collect();
1504        if self.inner.config.key_names {
1505            ep.insert("x_keys", format!("{o}/x/keys"));
1506        }
1507        Value::Object(vec![
1508            ("bindings".into(), Value::String(format!("{o}/bindings"))),
1509            (
1510                "endpoints".into(),
1511                Value::Object(ep.into_iter().map(|(k, v)| (k.to_string(), Value::String(v))).collect()),
1512            ),
1513            ("host".into(), Value::String(self.inner.config.host.clone())),
1514            ("proto".into(), Value::String("datumesh/1".into())),
1515        ])
1516        .to_jcs()
1517    }
1518
1519    /// The key document this mesh serves: the store's namespace record for its host.
1520    pub fn key_document(&self) -> Option<Vec<u8>> {
1521        self.inner.store.namespace(&self.inner.config.host).ok().flatten().map(|n| n.keydoc)
1522    }
1523
1524    /// The Prometheus text of `/metrics`.
1525    pub fn metrics(&self) -> String {
1526        crate::http::metrics_text(&self.inner)
1527    }
1528
1529    /// The number of requests counted for a route template (e.g. `/cell/{cell}`).
1530    pub fn requests_of(&self, route: &str) -> u64 {
1531        self.inner.metrics.requests_of(route)
1532    }
1533
1534    /// The host of a function name (its first segment).
1535    pub fn host_of(name: &str) -> &str {
1536        host_of(name)
1537    }
1538
1539    /// How long the mesh has run.
1540    pub fn uptime(&self) -> Duration {
1541        self.inner.started.elapsed()
1542    }
1543}
1544
1545impl Inner {
1546    /// The class `name` is bound to as of `asof`, with its flattened descriptor (not noted for the
1547    /// describe index: see [`Bindings::class`]).
1548    pub(crate) fn class_binding(&self, name: &str, asof: &str) -> Result<Option<Arc<call::BoundClass>>, ErrorCode> {
1549        let store_failed = |e: datumesh_store::Error| {
1550            tracing::warn!(target: "datumesh_http", error = %e, "resolve_class_binding");
1551            ErrorCode::InputUnavailable
1552        };
1553        let Some(b) = self.store.resolve_class_binding(name, asof).map_err(store_failed)? else { return Ok(None) };
1554        let Some(bytes) = self.store.class(&b.class_hash).map_err(store_failed)? else {
1555            return Err(ErrorCode::InputUnavailable);
1556        };
1557        let d = datumesh_core::ClassDescriptor::from_json(&bytes).map_err(|_| ErrorCode::InputUnavailable)?;
1558        Ok(Some(Arc::new(call::BoundClass { class_hash: b.class_hash, since: b.tx, descriptor: Arc::new(d) })))
1559    }
1560}
1561
1562#[cfg(test)]
1563mod tests {
1564    use super::*;
1565    use std::sync::atomic::{AtomicUsize, Ordering};
1566
1567    /// A batch's chunks start together and ask for the same names: one store round trip per
1568    /// name and asof for the whole batch, not one per chunk.
1569    #[test]
1570    fn a_batch_looks_each_binding_up_once() {
1571        let seen = Seen::default();
1572        let lookups = AtomicUsize::new(0);
1573        let start = std::sync::Barrier::new(6);
1574        let look = || {
1575            lookups.fetch_add(1, Ordering::SeqCst);
1576            std::thread::sleep(Duration::from_millis(50));
1577            Ok(None)
1578        };
1579        std::thread::scope(|s| {
1580            for _ in 0..6 {
1581                s.spawn(|| {
1582                    start.wait();
1583                    assert!(matches!(seen.lookup("a.example/f", "2026-01-01T00:00:00Z", look), Ok(None)));
1584                });
1585            }
1586        });
1587        assert_eq!(lookups.load(Ordering::SeqCst), 1, "one lookup for six chunks");
1588        // Found: no lookup.
1589        assert!(matches!(seen.lookup("a.example/f", "2026-01-01T00:00:00Z", look), Ok(None)));
1590        assert_eq!(lookups.load(Ordering::SeqCst), 1);
1591        // Another asof, another name: looked up.
1592        assert!(matches!(seen.lookup("a.example/f", "2026-01-02T00:00:00Z", look), Ok(None)));
1593        assert!(matches!(seen.lookup("a.example/g", "2026-01-01T00:00:00Z", look), Ok(None)));
1594        assert_eq!(lookups.load(Ordering::SeqCst), 3);
1595        // A failed lookup is not kept.
1596        let fail = || Err(ErrorCode::InputUnavailable);
1597        assert!(matches!(seen.lookup("a.example/h", "2026-01-01T00:00:00Z", fail), Err(ErrorCode::InputUnavailable)));
1598        assert!(matches!(seen.lookup("a.example/h", "2026-01-01T00:00:00Z", look), Ok(None)));
1599        assert_eq!(lookups.load(Ordering::SeqCst), 4);
1600    }
1601}