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