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