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