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