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