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