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