1use 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::{
11 keys_from_response, verify, CellRef, ClassDescriptor, ErrorCode, FunctionDescriptor, KeyDoc, Keys, Receipt,
12 SigningKey,
13};
14use datumesh_engine::{Answer, Clock, Engine, EngineError, Runtime, SystemClock};
15use datumesh_formula::runtime::FormulaRuntime;
16use datumesh_store::Store;
17
18use crate::apikeys::Principal;
19use crate::call::{self, Bindings, Bound, Rejection, Target};
20use crate::config::{Config, ConfigError, Rule};
21use crate::envelope::{self, Cache, Reply};
22use crate::foreign::{host_of, CrossMesh, Foreign, ForeignError, KeyCache};
23use crate::jobs::Jobs;
24use crate::limit::Limiter;
25use crate::metrics::Metrics;
26use crate::pool::Pool;
27
28#[derive(Debug)]
30#[non_exhaustive]
31pub enum BuildError {
32 Config(ConfigError),
34 Engine(datumesh_engine::ConfigError),
36 BaseUrl(crate::config::BaseUrlError),
38}
39
40impl std::fmt::Display for BuildError {
41 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42 match self {
43 BuildError::Config(e) => write!(f, "{e}"),
44 BuildError::Engine(e) => write!(f, "engine: {e}"),
45 BuildError::BaseUrl(e) => write!(f, "configuration: base URL: {e}"),
46 }
47 }
48}
49
50impl std::error::Error for BuildError {}
51
52pub struct MeshBuilder {
54 config: Config,
55 store: Arc<dyn Store + Send + Sync>,
56 key: Option<SigningKey>,
57 key_file: Option<PathBuf>,
58 runtimes: Vec<Arc<dyn Runtime>>,
59 formula: bool,
60 clock: Arc<dyn Clock>,
61 fuel: Option<u64>,
62 licence: Option<String>,
63 memo_capacity: Option<usize>,
64}
65
66impl std::fmt::Debug for MeshBuilder {
67 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
68 f.debug_struct("MeshBuilder").field("host", &self.config.host).finish_non_exhaustive()
69 }
70}
71
72impl MeshBuilder {
73 pub fn signing_key(mut self, key: SigningKey) -> Self {
75 self.key = Some(key);
76 self.key_file = None;
77 self
78 }
79
80 pub fn signing_key_file(mut self, path: impl Into<PathBuf>) -> Self {
83 self.key_file = Some(path.into());
84 self.key = None;
85 self
86 }
87
88 pub fn runtime(mut self, runtime: Arc<dyn Runtime>) -> Self {
90 self.runtimes.push(runtime);
91 self
92 }
93
94 pub fn without_formula(mut self) -> Self {
96 self.formula = false;
97 self
98 }
99
100 pub fn clock(mut self, clock: Arc<dyn Clock>) -> Self {
102 self.clock = clock;
103 self
104 }
105
106 pub fn fuel(mut self, fuel: u64) -> Self {
108 self.fuel = Some(fuel);
109 self
110 }
111
112 pub fn licence(mut self, licence: impl Into<String>) -> Self {
114 self.licence = Some(licence.into());
115 self
116 }
117
118 pub fn memo_capacity(mut self, n: usize) -> Self {
120 self.memo_capacity = Some(n);
121 self
122 }
123
124 pub fn build(self) -> Result<Mesh, BuildError> {
127 if let Some(u) = &self.config.base_url {
128 crate::config::check_base_url(&self.config.host, u).map_err(BuildError::BaseUrl)?;
129 }
130 self.config.check().map_err(BuildError::Config)?;
131 let own_key_id = match (&self.key, &self.key_file) {
132 (Some(k), _) => Some(k.key_id().to_string()),
133 (None, Some(p)) => std::fs::read(p)
134 .ok()
135 .and_then(|b| crate::keynames::seed_of_file(&b))
136 .map(|s| datumesh_core::SigningKey::from_seed(&s).key_id().to_string()),
137 (None, None) => None,
138 };
139 let keys = Arc::new(KeyCache::default());
140 let foreign = Arc::new(Foreign::new(&self.config, self.store.clone(), keys.clone(), self.clock.clone()));
141 let mut b = Engine::builder(self.store.clone(), self.config.host.clone()).clock(self.clock.clone());
142 b = match (self.key, &self.key_file) {
143 (Some(k), _) => b.signing_key(k),
144 (None, Some(p)) => {
145 crate::config::read_secret_file(p).map_err(BuildError::Config)?;
146 b.signing_key_file(p.clone())
147 }
148 (None, None) => b,
149 };
150 let mut runtimes = self.runtimes;
151 if self.formula {
152 runtimes.push(Arc::new(FormulaRuntime::new(self.store.clone())));
153 }
154 if self.config.test_cells {
155 crate::testrun::install_test_cases(&*self.store, &self.config.host)
156 .map_err(|e| BuildError::Config(ConfigError::new("DATUMESH_TEST_CELLS", e)))?;
157 runtimes.push(Arc::new(crate::testrun::TestCases { store: self.store.clone() }));
158 }
159 for rt in runtimes {
160 b = b.runtime(Arc::new(CrossMesh::new(rt, foreign.clone())));
161 }
162 if let Some(f) = self.fuel {
163 b = b.fuel(f);
164 }
165 if let Some(l) = self.licence {
166 b = b.licence(l);
167 }
168 if let Some(n) = self.memo_capacity {
169 b = b.memo_capacity(n);
170 }
171 let engine = b.build().map_err(BuildError::Engine)?;
172 let config = self.config;
173 let embed = config.embed_url.as_deref().map(crate::embed::EmbedClient::new);
174 let inner = Inner {
175 generic: RwLock::new(Arc::new(crate::find::stopwords())),
176 embed,
177 reindex: Mutex::new(()),
178 publish_limits: Mutex::new(crate::bundles::Limits::default()),
179 relays: Mutex::new(HashMap::new()),
180 takeover: Mutex::new(None),
181 find: Mutex::new(None),
182 value_counts_at: Mutex::new(Some(Instant::now())),
183 unnamed: Mutex::new(HashSet::new()),
184 series: Mutex::new(crate::series::Memo::default()),
185 catalog: Mutex::new(None),
186 challenges: Mutex::new(crate::keynames::Challenges::default()),
187 keys_lock: Mutex::new(()),
188 own_key_id,
189 pool: Arc::new(Pool::new(config.pool_size)),
190 jobs: Jobs::new(config.ttl.job, config.max_jobs),
191 limiter: Limiter::new(config.rate.clone()),
192 metrics: Metrics::default(),
193 engine: Arc::new(engine),
194 store: self.store,
195 clock: self.clock,
196 keys,
197 foreign,
198 descriptors: Mutex::new(HashMap::new()),
199 last_good: Mutex::new(HashMap::new()),
200 infos: (0..32).map(|_| Mutex::new(HashMap::new())).collect(),
201 by_hash: (0..32).map(|_| Mutex::new(HashMap::new())).collect(),
202 latest: Latest::new(),
203 targets: Targets::new(),
204 slice_bodies: Mutex::new(crate::slice::BodyCache::default()),
205 known: Mutex::new(crate::describe::Index::default()),
206 started: Instant::now(),
207 config,
208 };
209 let mesh = Mesh { inner: Arc::new(inner) };
210 std::thread::scope(|s| {
214 let inner = mesh.inner.clone();
215 let _ = s.spawn(move || crate::find::sync_operator_catalog(&inner)).join();
216 });
217 let weak = Arc::downgrade(&mesh.inner);
220 let delay = mesh.inner.config.index_first_build_delay;
221 if delay.is_zero() {
222 on_scoped_thread(&mesh.inner, Inner::refresh_index);
223 }
224 let spawned = std::thread::Builder::new().name("datumesh-object-index".into()).spawn(move || {
225 let started = Instant::now();
226 loop {
227 let Some(inner) = weak.upgrade() else { break };
228 if started.elapsed() >= delay {
229 inner.refresh_index();
230 }
231 drop(inner);
232 std::thread::sleep(crate::describe::INDEX_TICK);
233 }
234 });
235 if let Err(e) = spawned {
236 tracing::warn!(error = %e, "the object index thread is not started; describe of an object id answers 503");
237 }
238 let weak = Arc::downgrade(&mesh.inner);
241 let (delay, refresh) = (mesh.inner.config.series_first_build_delay, mesh.inner.config.series_refresh);
242 let mut last: Option<Instant> = None;
243 if delay.is_zero() {
244 on_scoped_thread(&mesh.inner, crate::takeover::refresh);
245 last = Some(Instant::now());
246 }
247 let spawned = std::thread::Builder::new().name("datumesh-takeover".into()).spawn(move || {
248 let started = Instant::now();
249 loop {
250 let Some(inner) = weak.upgrade() else { break };
251 if started.elapsed() >= delay && last.is_none_or(|t| t.elapsed() >= refresh) {
252 crate::takeover::refresh(&inner);
253 last = Some(Instant::now());
254 }
255 drop(inner);
256 std::thread::sleep(Duration::from_millis(500));
257 }
258 });
259 if let Err(e) = spawned {
260 tracing::warn!(error = %e, "the takeover thread is not started; the takeover pages answer 503");
261 }
262 let (delay, refresh) = (mesh.inner.config.catalog_first_build_delay, mesh.inner.config.catalog_refresh);
267 let weak = Arc::downgrade(&mesh.inner);
268 let mut wait = delay;
269 let spawned = std::thread::Builder::new().name("datumesh-catalog".into()).spawn(move || loop {
270 std::thread::sleep(wait);
271 let Some(inner) = weak.upgrade() else { break };
272 crate::catalog_view::rebuild(&inner, "background");
273 drop(inner);
274 wait = refresh;
275 });
276 if let Err(e) = spawned {
277 tracing::warn!(error = %e, "the catalogue thread is not started; the catalogue pages are never built");
278 }
279 let weak = Arc::downgrade(&mesh.inner);
282 let delay = mesh.inner.config.find_first_build_delay;
283 let mut last: Option<Instant> = None;
284 if delay.is_zero() {
285 on_scoped_thread(&mesh.inner, crate::find::refresh);
286 last = Some(Instant::now());
287 }
288 let spawned = std::thread::Builder::new().name("datumesh-find".into()).spawn(move || {
289 let started = Instant::now();
290 loop {
291 let Some(inner) = weak.upgrade() else { break };
292 if started.elapsed() >= delay && last.is_none_or(|t| t.elapsed() >= FIND_REFRESH) {
293 crate::find::refresh(&inner);
294 last = Some(Instant::now());
295 }
296 drop(inner);
297 std::thread::sleep(Duration::from_millis(500));
298 }
299 });
300 if let Err(e) = spawned {
301 tracing::warn!(error = %e, "the find thread is not started; the summary and the empty query answer 503");
302 }
303 let weak = Arc::downgrade(&mesh.inner);
306 let spawned = std::thread::Builder::new().name("datumesh-test-names".into()).spawn(move || {
307 if let Some(inner) = weak.upgrade() {
308 crate::testrun::name_old_tests(&inner);
309 }
310 });
311 if let Err(e) = spawned {
312 tracing::warn!(error = %e, "the test naming thread is not started; old tests stay unnamed");
313 }
314 let weak = Arc::downgrade(&mesh.inner);
315 let spawned = std::thread::Builder::new().name("datumesh-index".into()).spawn(move || loop {
316 let Some(inner) = weak.upgrade() else { break };
317 crate::find::reindex(&inner);
318 drop(inner);
319 std::thread::sleep(Duration::from_secs(30));
320 });
321 if let Err(e) = spawned {
322 tracing::warn!(error = %e, "the index thread is not started; find sees the catalogue as it is at start");
323 }
324 if !mesh.inner.config.series.is_empty() {
329 let weak = Arc::downgrade(&mesh.inner);
330 let (delay, refresh) = (mesh.inner.config.series_first_build_delay, mesh.inner.config.series_refresh);
331 if delay.is_zero() {
332 std::thread::scope(|s| {
333 let inner = mesh.inner.clone();
334 let _ = s.spawn(move || crate::series::rebuild(&inner, "background")).join();
335 });
336 }
337 let mut wait = if delay.is_zero() { refresh } else { delay };
338 let spawned = std::thread::Builder::new().name("datumesh-series".into()).spawn(move || loop {
339 std::thread::sleep(wait);
340 let Some(inner) = weak.upgrade() else { break };
341 crate::series::rebuild(&inner, "background");
342 drop(inner);
343 wait = refresh;
344 });
345 if let Err(e) = spawned {
346 tracing::warn!(error = %e, "the series thread is not started; the series overview is never built");
347 }
348 }
349 Ok(mesh)
350 }
351}
352
353fn on_scoped_thread(inner: &Arc<Inner>, f: fn(&Inner)) {
356 std::thread::scope(|s| {
357 let inner = inner.clone();
358 let _ = s.spawn(move || f(&inner)).join();
359 });
360}
361
362const FIND_REFRESH: Duration = Duration::from_secs(300);
364
365struct LastGood {
367 info: Arc<ReceiptInfo>,
368 at: Instant,
369}
370
371pub(crate) struct ReceiptInfo {
374 pub(crate) hash: String,
375 pub(crate) asof: String,
376 pub(crate) receipt: Vec<u8>,
377 pub(crate) parsed: Receipt,
378 pub(crate) trust: datumesh_core::TrustLabel,
379 pub(crate) ok: crate::envelope::Bytes,
381}
382
383pub(crate) struct Inner {
384 pub(crate) config: Config,
385 pub(crate) store: Arc<dyn Store + Send + Sync>,
386 pub(crate) engine: Arc<Engine>,
387 pub(crate) clock: Arc<dyn Clock>,
388 pub(crate) pool: Arc<Pool>,
389 pub(crate) jobs: Jobs,
390 pub(crate) limiter: Limiter,
391 pub(crate) metrics: Metrics,
392 pub(crate) keys: Arc<KeyCache>,
393 pub(crate) foreign: Arc<Foreign>,
394 descriptors: Mutex<HashMap<String, Arc<FunctionDescriptor>>>,
395 last_good: Mutex<HashMap<String, LastGood>>,
396 infos: Vec<Mutex<HashMap<u64, Arc<ReceiptInfo>>>>,
397 by_hash: Vec<Mutex<HashMap<String, Arc<ReceiptInfo>>>>,
398 latest: Latest,
399 targets: Targets,
400 pub(crate) slice_bodies: Mutex<crate::slice::BodyCache>,
402 pub(crate) known: Mutex<crate::describe::Index>,
404 pub(crate) started: Instant,
405 pub(crate) generic: RwLock<Arc<HashSet<String>>>,
407 pub(crate) embed: Option<crate::embed::EmbedClient>,
409 pub(crate) reindex: Mutex<()>,
411 pub(crate) publish_limits: Mutex<crate::bundles::Limits>,
413 pub(crate) relays: Mutex<HashMap<String, (Instant, Option<crate::fnpage::Relay>)>>,
415 pub(crate) takeover: Mutex<Option<Arc<crate::takeover::Lists>>>,
417 pub(crate) find: Mutex<Option<Arc<crate::find::Built>>>,
419 pub(crate) value_counts_at: Mutex<Option<Instant>>,
421 pub(crate) unnamed: Mutex<HashSet<String>>,
424 pub(crate) series: Mutex<crate::series::Memo>,
426 pub(crate) catalog: Mutex<Option<Arc<crate::catalog_view::Built>>>,
428 pub(crate) challenges: Mutex<crate::keynames::Challenges>,
430 pub(crate) keys_lock: Mutex<()>,
432 pub(crate) own_key_id: Option<String>,
434}
435
436#[derive(Clone)]
438pub struct Mesh {
439 pub(crate) inner: Arc<Inner>,
440}
441
442impl std::fmt::Debug for Mesh {
443 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
444 f.debug_struct("Mesh").field("host", &self.inner.config.host).finish_non_exhaustive()
445 }
446}
447
448pub(crate) struct Memo<'a> {
450 inner: &'a Inner,
451 seen: std::borrow::Cow<'a, Seen>,
452}
453
454#[derive(Default)]
458struct SeenEntry {
459 found: std::sync::OnceLock<Option<Arc<Bound>>>,
460 lookup: Mutex<()>,
461}
462
463#[derive(Default)]
465pub(crate) struct Seen(RwLock<HashMap<String, SeenAsofs>>);
466
467type SeenAsofs = Vec<(String, Arc<SeenEntry>)>;
469
470impl Clone for Seen {
471 fn clone(&self) -> Seen {
472 let m = self.0.read().unwrap_or_else(|p| p.into_inner());
473 let copy = m
474 .iter()
475 .map(|(name, v)| {
476 let v = v
477 .iter()
478 .map(|(a, e)| (a.clone(), Arc::new(SeenEntry { found: e.found.clone(), lookup: Mutex::new(()) })))
479 .collect();
480 (name.clone(), v)
481 })
482 .collect();
483 Seen(RwLock::new(copy))
484 }
485}
486
487enum Held {
489 Found(Option<Arc<Bound>>),
490 Entry(Arc<SeenEntry>),
491 Full,
492}
493
494impl Seen {
495 fn held(&self, fn_name: &str, asof: &str) -> Held {
498 if let Some(v) = self.0.read().unwrap_or_else(|p| p.into_inner()).get(fn_name) {
499 if let Some((_, e)) = v.iter().find(|(a, _)| a == asof) {
500 return match e.found.get() {
501 Some(b) => Held::Found(b.clone()),
502 None => Held::Entry(e.clone()),
503 };
504 }
505 }
506 let mut m = self.0.write().unwrap_or_else(|p| p.into_inner());
507 let v = m.entry(fn_name.to_string()).or_default();
508 if let Some((_, e)) = v.iter().find(|(a, _)| a == asof) {
509 return Held::Entry(e.clone());
510 }
511 if v.len() >= 64 {
512 return Held::Full;
513 }
514 let e = Arc::new(SeenEntry::default());
515 v.push((asof.to_string(), e.clone()));
516 Held::Entry(e)
517 }
518
519 pub(crate) fn lookup(
523 &self,
524 fn_name: &str,
525 asof: &str,
526 look: impl FnOnce() -> Result<Option<Arc<Bound>>, ErrorCode>,
527 ) -> Result<Option<Arc<Bound>>, ErrorCode> {
528 let e = match self.held(fn_name, asof) {
529 Held::Found(b) => return Ok(b),
530 Held::Full => return look(),
531 Held::Entry(e) => e,
532 };
533 let _looking = e.lookup.lock().unwrap_or_else(|p| p.into_inner());
534 if let Some(b) = e.found.get() {
535 return Ok(b.clone());
536 }
537 let b = look()?;
538 let _ = e.found.set(b.clone());
539 Ok(b)
540 }
541}
542
543impl<'a> Memo<'a> {
544 pub(crate) fn new(inner: &'a Inner) -> Memo<'a> {
545 Memo { inner, seen: std::borrow::Cow::Owned(Seen::default()) }
546 }
547
548 pub(crate) fn shared(inner: &'a Inner, seen: &'a Seen) -> Memo<'a> {
549 Memo { inner, seen: std::borrow::Cow::Borrowed(seen) }
550 }
551}
552
553impl Bindings for Memo<'_> {
554 fn pinned(&self, fn_hash: &str) -> Result<Option<Arc<Bound>>, ErrorCode> {
555 Bindings::pinned(self.inner, fn_hash)
556 }
557
558 fn alias(&self, alias: &str) -> Option<String> {
559 Bindings::alias(self.inner, alias)
560 }
561
562 fn class(&self, name: &str, asof: &str) -> Result<Option<Arc<call::BoundClass>>, ErrorCode> {
563 Bindings::class(self.inner, name, asof)
564 }
565
566 fn aliases_tx(&self) -> Option<String> {
567 Bindings::aliases_tx(self.inner)
568 }
569
570 fn lookup(&self, class: &str, label: &str, asof: &str) -> Result<Option<String>, ErrorCode> {
571 Bindings::lookup(self.inner, class, label, asof)
572 }
573
574 fn class_name_of(&self, class_hash: &str, asof: &str) -> Result<Option<String>, ErrorCode> {
575 Bindings::class_name_of(self.inner, class_hash, asof)
576 }
577
578 fn class_by_hash(&self, class_hash: &str) -> Result<Option<ClassDescriptor>, ErrorCode> {
579 Bindings::class_by_hash(self.inner, class_hash)
580 }
581
582 fn chain(&self, cell: &CellRef, asof: &str) -> Result<Option<String>, ErrorCode> {
583 Bindings::chain(self.inner, cell, asof)
584 }
585
586 fn cached(&self, fn_hash: &str, rest: &str) -> Option<Arc<Target>> {
587 self.inner.targets.get(fn_hash, rest)
588 }
589
590 fn remember(&self, rest: &str, target: &Arc<Target>) {
591 self.inner.targets.put(rest, target);
592 }
593
594 fn binding(&self, fn_name: &str, asof: &str) -> Result<Option<Arc<Bound>>, ErrorCode> {
595 self.seen.lookup(fn_name, asof, || Bindings::binding(self.inner, fn_name, asof))
596 }
597}
598
599impl Bindings for Inner {
600 fn pinned(&self, fn_hash: &str) -> Result<Option<Arc<Bound>>, ErrorCode> {
601 match self.descriptor(fn_hash) {
602 Ok(d) => Ok(Some(Arc::new(Bound::new(fn_hash, "", d)))),
603 Err(ErrorCode::FnUnavailable) => Ok(None),
604 Err(c) => Err(c),
605 }
606 }
607
608 fn alias(&self, alias: &str) -> Option<String> {
609 self.config.aliases.get(alias).cloned()
610 }
611
612 fn class(&self, name: &str, asof: &str) -> Result<Option<Arc<call::BoundClass>>, ErrorCode> {
613 let c = self.class_binding(name, asof)?;
614 if c.is_some() {
615 self.hear_of_class(name);
616 }
617 Ok(c)
618 }
619
620 fn aliases_tx(&self) -> Option<String> {
622 None
623 }
624
625 fn class_name_of(&self, class_hash: &str, asof: &str) -> Result<Option<String>, ErrorCode> {
626 match self.store.class_names_bound_to(class_hash, asof) {
627 Ok(names) => Ok(names.into_iter().next()),
628 Err(_) => Err(ErrorCode::InputUnavailable),
629 }
630 }
631
632 fn class_by_hash(&self, class_hash: &str) -> Result<Option<ClassDescriptor>, ErrorCode> {
633 match self.store.class(class_hash) {
634 Ok(Some(bytes)) => ClassDescriptor::from_json(&bytes).map(Some).map_err(|_| ErrorCode::InputUnavailable),
635 Ok(None) => Ok(None),
636 Err(_) => Err(ErrorCode::InputUnavailable),
637 }
638 }
639
640 fn chain(&self, cell: &CellRef, asof: &str) -> Result<Option<String>, ErrorCode> {
643 let name = format!("{}/{}", cell.ns, cell.fn_name);
644 let Some(b) = Bindings::binding(self, &name, asof)? else { return Ok(None) };
645 let c = datumesh_core::Cell {
646 ns: cell.ns.clone(),
647 fn_name: cell.fn_name.clone(),
648 fn_hash: b.fn_hash.clone(),
649 args: cell.args.clone(),
650 };
651 match self.engine.get_cell(&c, Some(asof)) {
652 Ok(Answer::Receipt(bytes)) => match Receipt::from_json(&bytes).map(|r| r.value().clone()) {
653 Ok(datumesh_core::Scalar::String(k)) => Ok(Some(k)),
654 _ => Ok(None),
655 },
656 Err(EngineError::Store(_)) => Err(ErrorCode::InputUnavailable),
657 _ => Ok(None),
658 }
659 }
660
661 fn lookup(&self, class: &str, label: &str, asof: &str) -> Result<Option<String>, ErrorCode> {
662 let Some(c) = Bindings::class(self, class, asof)? else { return Ok(None) };
663 let Some(method) = &c.descriptor.lookup else { return Ok(None) };
664 let name = format!("{class}/{method}");
665 let Some(b) = Bindings::binding(self, &name, asof)? else { return Ok(None) };
666 let (ns, fn_name) = name.rsplit_once('/').unwrap_or((&name, ""));
667 let mut args = datumesh_core::Args::new();
668 args.insert("label".into(), datumesh_core::Arg::Value(datumesh_core::Scalar::String(label.to_string())));
669 let cell = datumesh_core::Cell { ns: ns.into(), fn_name: fn_name.into(), fn_hash: b.fn_hash.clone(), args };
670 match self.engine.get_cell(&cell, Some(asof)) {
671 Ok(Answer::Receipt(bytes)) => match Receipt::from_json(&bytes).map(|r| r.value().clone()) {
672 Ok(datumesh_core::Scalar::String(k)) => Ok(Some(k)),
673 _ => Ok(None),
674 },
675 Ok(Answer::Withdrawn { reason, .. }) => {
677 crate::call::set_label_withdrawn(reason);
678 Ok(None)
679 }
680 Err(EngineError::Store(_)) => Err(ErrorCode::InputUnavailable),
681 _ => Ok(None),
682 }
683 }
684
685 fn cached(&self, fn_hash: &str, rest: &str) -> Option<Arc<Target>> {
686 self.targets.get(fn_hash, rest)
687 }
688
689 fn remember(&self, rest: &str, target: &Arc<Target>) {
690 self.targets.put(rest, target);
691 }
692
693 fn binding(&self, fn_name: &str, asof: &str) -> Result<Option<Arc<Bound>>, ErrorCode> {
694 let mut failed = None;
695 if self.foreign.is_foreign(fn_name) {
696 if let Err(e) = self.foreign.ensure_name(fn_name) {
697 tracing::warn!(target: "datumesh_http", name = fn_name, detail = %e.detail, "cross-mesh binding");
698 FOREIGN_DETAIL.with(|d| d.set(e.foreign_detail()));
701 failed = Some(e.code);
702 }
703 }
704 let b = self.store.resolve_binding(fn_name, asof).map_err(|e| {
705 tracing::warn!(target: "datumesh_http", error = %e, "resolve_binding");
706 ErrorCode::InputUnavailable
707 })?;
708 if let (Some(code), None) = (failed, &b) {
711 return Err(code);
712 }
713 match b {
714 None => Ok(None),
715 Some(b) => {
716 let d = self.descriptor(&b.fn_hash)?;
717 Ok(Some(Arc::new(Bound::new(b.fn_hash, b.tx, d))))
718 }
719 }
720 }
721}
722
723thread_local! {
724 static FOREIGN_DETAIL: std::cell::Cell<Option<datumesh_core::ForeignDetail>> = const { std::cell::Cell::new(None) };
727}
728
729type LatestShard = RwLock<HashMap<String, (Arc<ReceiptInfo>, String, String)>>;
731
732struct Latest {
737 shards: Vec<LatestShard>,
738 by_cell: Mutex<HashMap<String, Vec<String>>>,
739}
740
741impl Latest {
742 fn new() -> Latest {
743 Latest { shards: (0..32).map(|_| RwLock::new(HashMap::new())).collect(), by_cell: Mutex::new(HashMap::new()) }
744 }
745
746 fn shard(&self, key: &str) -> &LatestShard {
747 use std::hash::{Hash, Hasher};
748 let mut h = std::collections::hash_map::DefaultHasher::new();
749 key.hash(&mut h);
750 &self.shards[(h.finish() % self.shards.len() as u64) as usize]
751 }
752
753 fn get(&self, key: &str, a: &str) -> Option<Arc<ReceiptInfo>> {
755 let m = self.shard(key).read().unwrap_or_else(|p| p.into_inner());
756 let (info, _, at) = m.get(key)?;
757 (a >= at.as_str()).then(|| info.clone())
758 }
759
760 fn put(&self, key: String, cell_id: String, info: Arc<ReceiptInfo>, at: String) {
761 {
762 let mut b = self.by_cell.lock().unwrap_or_else(|p| p.into_inner());
763 if b.len() > 200_000 {
764 b.clear();
765 for s in &self.shards {
766 s.write().unwrap_or_else(|p| p.into_inner()).clear();
767 }
768 }
769 b.entry(cell_id.clone()).or_default().push(key.clone());
770 }
771 self.shard(&key).write().unwrap_or_else(|p| p.into_inner()).insert(key, (info, cell_id, at));
772 }
773
774 fn forget(&self, cell_id: &str) {
775 let keys = self.by_cell.lock().unwrap_or_else(|p| p.into_inner()).remove(cell_id).unwrap_or_default();
776 for k in keys {
777 self.shard(&k).write().unwrap_or_else(|p| p.into_inner()).remove(&k);
778 }
779 }
780
781 fn clear(&self) {
782 self.by_cell.lock().unwrap_or_else(|p| p.into_inner()).clear();
783 for s in &self.shards {
784 s.write().unwrap_or_else(|p| p.into_inner()).clear();
785 }
786 }
787}
788
789struct Targets {
792 #[allow(clippy::type_complexity)]
793 shards: Vec<RwLock<HashMap<String, HashMap<String, Arc<Target>>>>>,
794}
795
796impl Targets {
797 fn new() -> Targets {
798 Targets { shards: (0..32).map(|_| RwLock::new(HashMap::new())).collect() }
799 }
800
801 #[allow(clippy::type_complexity)]
802 fn shard(&self, rest: &str) -> &RwLock<HashMap<String, HashMap<String, Arc<Target>>>> {
803 use std::hash::{Hash, Hasher};
804 let mut h = std::collections::hash_map::DefaultHasher::new();
805 rest.hash(&mut h);
806 &self.shards[(h.finish() % self.shards.len() as u64) as usize]
807 }
808
809 fn get(&self, fn_hash: &str, rest: &str) -> Option<Arc<Target>> {
810 self.shard(rest).read().unwrap_or_else(|p| p.into_inner()).get(rest)?.get(fn_hash).cloned()
811 }
812
813 fn put(&self, rest: &str, t: &Arc<Target>) {
814 let mut m = self.shard(rest).write().unwrap_or_else(|p| p.into_inner());
815 if m.len() >= 4_096 {
816 m.clear();
817 }
818 let v = m.entry(rest.to_string()).or_default();
819 if v.len() >= 8 {
820 v.clear();
821 }
822 v.insert(t.bound.fn_hash.clone(), t.clone());
823 }
824}
825
826fn last_good_key(t: &Target) -> String {
829 t.cell_key().to_string()
830}
831
832pub(crate) fn engine_code(e: &EngineError) -> (bool, ErrorCode) {
834 match e {
835 EngineError::Invalid(e) if envelope::is_request_code(e.code()) => (true, e.code()),
836 EngineError::Invalid(e) if envelope::is_error_code(e.code()) => (false, e.code()),
837 EngineError::NameUnresolved { .. } => (false, ErrorCode::FnUnavailable),
838 EngineError::UndeclaredInput { .. } => (false, ErrorCode::InputUndeclared),
839 EngineError::Sign(e) if envelope::is_error_code(e.code()) => (false, e.code()),
840 EngineError::Store(_) => (false, ErrorCode::InputUnavailable),
841 _ => (false, ErrorCode::EvalUnavailable),
842 }
843}
844
845impl Inner {
846 pub(crate) fn now(&self) -> String {
847 self.clock.now()
848 }
849
850 pub(crate) fn is_unnamed(&self, fn_hash: &str) -> bool {
852 self.unnamed.lock().unwrap_or_else(|p| p.into_inner()).contains(fn_hash)
853 }
854
855 pub(crate) fn descriptor(&self, fn_hash: &str) -> Result<Arc<FunctionDescriptor>, ErrorCode> {
857 if let Some(d) = self.descriptors.lock().unwrap_or_else(|p| p.into_inner()).get(fn_hash) {
858 return Ok(d.clone());
859 }
860 let bytes = self.store.descriptor(fn_hash).ok_or(ErrorCode::FnUnavailable)?;
861 let d = Arc::new(FunctionDescriptor::from_json(&bytes).map_err(|_| ErrorCode::FnUnavailable)?);
862 let mut m = self.descriptors.lock().unwrap_or_else(|p| p.into_inner());
863 if m.len() > 10_000 {
864 m.clear();
865 }
866 m.insert(fn_hash.to_string(), d.clone());
867 Ok(d)
868 }
869
870 fn ok_reply(
872 &self,
873 target: &Target,
874 info: Arc<ReceiptInfo>,
875 a: &str,
876 now: &str,
877 private: bool,
878 link: bool,
879 ) -> Reply {
880 let mut reply = Reply::json(200, info.ok.clone(), Cache::Immutable);
881 if target.asof().is_none() {
882 let mut lg = self.last_good.lock().unwrap_or_else(|p| p.into_inner());
883 if lg.len() > 100_000 {
884 lg.clear();
885 }
886 lg.insert(last_good_key(target), LastGood { info, at: Instant::now() });
887 }
888 self.cache_rules(&mut reply, target, a, now, private, link);
889 reply
890 }
891
892 fn remember_latest(&self, target: &Target, info: &Arc<ReceiptInfo>, a: &str) {
895 match self.store.latest(target.cell_id()) {
896 Ok(Some(v)) if v.receipt_hash == info.hash => {
897 self.latest.put(
898 target.cell_key().to_string(),
899 target.cell_id().to_string(),
900 info.clone(),
901 a.to_string(),
902 );
903 }
904 _ => {}
905 }
906 }
907
908 pub(crate) fn version_added(&self, cell_id: &str) {
911 self.engine.stored_version_added(cell_id);
912 self.latest.forget(cell_id);
913 self.index_stored_now(cell_id);
914 }
915
916 fn receipt_info(&self, bytes: &[u8]) -> Option<Arc<ReceiptInfo>> {
918 use std::hash::{Hash, Hasher};
919 let mut h = std::collections::hash_map::DefaultHasher::new();
920 bytes.hash(&mut h);
921 let key = h.finish();
922 let shard = &self.infos[(key % self.infos.len() as u64) as usize];
923 if let Some(i) = shard.lock().unwrap_or_else(|p| p.into_inner()).get(&key) {
924 if i.receipt == bytes {
925 return Some(i.clone());
926 }
927 }
928 let r = Receipt::from_json(bytes).ok()?;
929 let trust = envelope::trust_label_of(&r, &self.config.host);
930 let ok = envelope::with_fn_hash(datumesh_core::Answer::ok(r.clone(), trust), Some(&r.cell().fn_hash)).to_json();
931 let info = Arc::new(ReceiptInfo {
932 hash: r.hash().to_string(),
933 asof: r.asof().to_string(),
934 receipt: bytes.to_vec(),
935 parsed: r,
936 trust,
937 ok: ok.into(),
938 });
939 let mut m = shard.lock().unwrap_or_else(|p| p.into_inner());
940 if m.len() >= 4_096 {
941 m.clear();
942 }
943 m.insert(key, info.clone());
944 Some(info)
945 }
946
947 pub(crate) fn receipt_info_by_hash(&self, hash: &str) -> Option<Arc<ReceiptInfo>> {
949 use std::hash::{Hash, Hasher};
950 let mut h = std::collections::hash_map::DefaultHasher::new();
951 hash.hash(&mut h);
952 let shard = &self.by_hash[(h.finish() % self.by_hash.len() as u64) as usize];
953 if let Some(i) = shard.lock().unwrap_or_else(|p| p.into_inner()).get(hash) {
954 return Some(i.clone());
955 }
956 let bytes = self.store.receipt(hash)?;
957 let info = self.receipt_info(&bytes)?;
958 let mut m = shard.lock().unwrap_or_else(|p| p.into_inner());
959 if m.len() >= 2_048 {
960 m.clear();
961 }
962 m.insert(hash.to_string(), info.clone());
963 Some(info)
964 }
965
966 pub(crate) fn rejection(&self, r: Rejection, asof: Option<&str>) -> Reply {
968 match r {
969 Rejection::BadRequest(c) => envelope::bad_request_reply(c),
970 Rejection::NotCovered => {
971 let _ = asof;
972 let fault = crate::call::take_fault();
973 Reply::json(404, envelope::not_covered(fault), Cache::Public(self.config.ttl.latest_max_age.as_secs()))
974 }
975 Rejection::Error(ErrorCode::NameUnbound) => match crate::call::take_label_withdrawn() {
976 Some(reason) => match datumesh_core::Answer::label_withdrawn(&reason) {
977 Ok(a) => envelope::answer_reply(&a, Cache::Public(self.config.ttl.latest_max_age.as_secs())),
978 Err(_) => envelope::name_unbound_reply(self.config.ttl.latest_max_age.as_secs()),
979 },
980 None => envelope::name_unbound_reply(self.config.ttl.latest_max_age.as_secs()),
981 },
982 Rejection::Error(ErrorCode::ForeignUnavailable) => {
983 let d = FOREIGN_DETAIL.with(|d| d.take()).unwrap_or(datumesh_core::ForeignDetail::Network);
985 envelope::answer_reply(&datumesh_core::Answer::foreign_unavailable(d), Cache::NoStore)
986 }
987 Rejection::Error(c) => envelope::error_reply(c),
988 }
989 }
990
991 pub(crate) fn policy(&self, target: &Target, principal: Option<&Principal>) -> (Option<Reply>, bool) {
994 if self.config.policy.rules.is_empty() {
995 return (None, false);
996 }
997 match self.config.policy.rule(&target.fn_name()) {
998 None => (None, false),
999 Some(Rule::Principals(ps)) => {
1000 if principal.is_some_and(|p| ps.contains(&p.id)) {
1001 (None, true)
1002 } else {
1003 let a = envelope::with_fn_hash(datumesh_core::Answer::unlicensed(), Some(&target.bound.fn_hash));
1004 (Some(envelope::answer_reply(&a, Cache::Private)), true)
1005 }
1006 }
1007 Some(Rule::Price { amount, currency }) => {
1008 let authorise = format!("{}/pay/{}", self.config.origin(), target.cell_id());
1009 let quote = datumesh_core::Quote { amount: amount.clone(), currency: currency.clone(), authorise };
1010 let a =
1011 envelope::with_fn_hash(datumesh_core::Answer::payment_required(quote), Some(&target.bound.fn_hash));
1012 (Some(envelope::answer_reply(&a, Cache::Private)), true)
1013 }
1014 }
1015 }
1016
1017 pub(crate) fn answer(
1020 &self,
1021 rest: &str,
1022 principal: Option<&Principal>,
1023 bindings: &dyn Bindings,
1024 now: &str,
1025 on_target: &mut dyn FnMut(&Target),
1026 ) -> Reply {
1027 self.answer_with(rest, principal, bindings, now, on_target, true)
1028 }
1029
1030 pub(crate) fn answer_with(
1033 &self,
1034 rest: &str,
1035 principal: Option<&Principal>,
1036 bindings: &dyn Bindings,
1037 now: &str,
1038 on_target: &mut dyn FnMut(&Target),
1039 link: bool,
1040 ) -> Reply {
1041 let target = match call::resolve(rest, now, &self.config.aliases, bindings, false) {
1042 Ok(t) => t,
1043 Err(Rejection::BadRequest(code @ (ErrorCode::ParseUri | ErrorCode::CanonName)))
1047 if crate::call::url_decode(rest).is_some_and(|d| {
1048 crate::describe::label_form(&d)
1049 .is_some_and(|(class, _, _)| datumesh_core::lexical::check_function_name(&class, "$").is_ok())
1050 }) =>
1051 {
1052 let text = crate::call::url_decode(rest).unwrap_or_default();
1053 if let Some(reply) = self.describe_label(bindings, &text, now) {
1054 return reply;
1055 }
1056 return self.rejection(Rejection::BadRequest(code), None);
1057 }
1058 Err(r) => return self.rejection(r, None),
1059 };
1060 on_target(&target);
1061 let (refused, private) = self.policy(&target, principal);
1062 let reply = match refused {
1063 Some(r) => r,
1064 None => self.answer_target(&target, now, private, link),
1065 };
1066 match &target.resolved {
1068 Some(r) => envelope::with_resolved(reply, r),
1069 None => reply,
1070 }
1071 }
1072
1073 pub(crate) fn answer_target(&self, target: &Target, now: &str, private: bool, link: bool) -> Reply {
1075 let a = target.asof().unwrap_or(now);
1076 let stored = target.bound.descriptor.lang == "stored";
1077 let local = stored && !self.foreign.is_foreign(&target.cell.ns);
1078 if local {
1079 if let Some(info) = self.latest.get(target.cell_key(), a) {
1080 let mut reply = Reply::json(200, info.ok.clone(), Cache::Immutable);
1081 self.cache_rules(&mut reply, target, a, now, private, link);
1082 return reply;
1083 }
1084 }
1085 if let Err(e) = self.foreign.prepare(&target.cell, stored, target.asof()) {
1086 return self.unavailable(target, e);
1087 }
1088 if !stored {
1091 if let Err(e) = self.foreign.ensure_publisher(&target.cell.ns) {
1092 return self.unavailable(target, e);
1093 }
1094 }
1095 let mut attempt = 0;
1096 loop {
1097 let r = self.engine.get_cell(&target.cell, Some(a));
1098 let inval = self.foreign.take_invalidated();
1099 for id in &inval {
1100 self.version_added(id);
1101 }
1102 if !inval.is_empty() && attempt < 2 {
1103 attempt += 1;
1104 continue;
1105 }
1106 if !stored && matches!(r, Ok(Answer::Receipt(_))) {
1108 self.index_cell_now(&target.cell);
1109 }
1110 return match r {
1111 Ok(Answer::Receipt(bytes)) => {
1112 let Some(info) = self.receipt_info(&bytes) else {
1113 return envelope::error_answer_reply(ErrorCode::EvalUnavailable, Some(&target.bound.fn_hash));
1114 };
1115 if attempt < 2 {
1116 match self.foreign.refresh_deps(&info.hash, a) {
1117 Ok(true) => {
1118 for id in self.foreign.take_invalidated() {
1119 self.version_added(&id);
1120 }
1121 attempt += 1;
1122 continue;
1123 }
1124 Ok(false) => {}
1125 Err(e) => return self.unavailable(target, e),
1126 }
1127 }
1128 if local && target.asof().is_none() {
1129 self.remember_latest(target, &info, a);
1130 }
1131 self.ok_reply(target, info, a, now, private, link)
1132 }
1133 Ok(Answer::Withdrawn { receipt, reason: _ }) => {
1134 let built = datumesh_core::Withdrawal::from_json(&receipt).ok().and_then(|w| {
1136 let trust = envelope::trust_label_of_withdrawal(&w, &self.config.host);
1137 datumesh_core::Answer::withdrawn(w, trust).ok()
1138 });
1139 let Some(ans) = built else {
1140 return envelope::error_answer_reply(ErrorCode::EvalUnavailable, Some(&target.bound.fn_hash));
1141 };
1142 let ans = envelope::with_fn_hash(ans, Some(&target.bound.fn_hash));
1143 let mut reply = envelope::answer_reply(&ans, Cache::Public(0));
1144 self.cache_rules(&mut reply, target, a, now, private, link);
1145 if target.asof().is_some() {
1146 reply.cache = if private {
1147 Cache::Private
1148 } else {
1149 Cache::Public(self.config.ttl.latest_max_age.as_secs())
1150 };
1151 }
1152 reply
1153 }
1154 Ok(Answer::NotCovered { fault }) => {
1155 let mut ans =
1156 envelope::with_fn_hash(datumesh_core::Answer::not_covered(), Some(&target.bound.fn_hash));
1157 if let Some(f) = fault {
1158 ans = ans.with_fault(f);
1159 }
1160 let mut reply = envelope::answer_reply(&ans, Cache::Public(0));
1161 self.cache_rules(&mut reply, target, a, now, private, link);
1162 if target.asof().is_some() {
1163 reply.cache = if private {
1164 Cache::Private
1165 } else {
1166 Cache::Public(self.config.ttl.latest_max_age.as_secs())
1167 };
1168 }
1169 reply
1170 }
1171 Ok(_) => envelope::error_answer_reply(ErrorCode::EvalUnavailable, Some(&target.bound.fn_hash)),
1172 Err(EngineError::Unlicensed { cell_id, reason }) => {
1173 tracing::info!(target: "datumesh_http", cell_id = %cell_id, reason = reason.as_str(), "unlicensed");
1176 let a = envelope::with_fn_hash(datumesh_core::Answer::unlicensed(), Some(&target.bound.fn_hash));
1177 let cache =
1178 if private { Cache::Private } else { Cache::Public(self.config.ttl.latest_max_age.as_secs()) };
1179 envelope::answer_reply(&a, cache)
1180 }
1181 Err(EngineError::Cycle { path }) => {
1182 return self.cycle_reply(&path, Some(a), Some(&target.bound.fn_hash))
1183 }
1184 Err(e) => {
1185 let (bad, code) = engine_code(&e);
1186 tracing::info!(target: "datumesh_http", error = %e, code = code.as_str(), "engine");
1187 if code == ErrorCode::ForeignUnavailable {
1188 let detail = match &e {
1190 EngineError::Invalid(c) => {
1191 c.detail().strip_prefix("cross-mesh: ").unwrap_or(c.detail()).to_string()
1192 }
1193 other => other.to_string(),
1194 };
1195 return self.unavailable(target, ForeignError { code, detail });
1196 }
1197 if bad {
1198 envelope::bad_request_reply(code)
1199 } else if code == ErrorCode::InputUnavailable {
1200 self.unavailable(target, ForeignError { code, detail: e.to_string() })
1201 } else {
1202 envelope::error_answer_reply(code, Some(&target.bound.fn_hash))
1203 }
1204 }
1205 };
1206 }
1207 }
1208
1209 fn cache_rules(&self, reply: &mut Reply, target: &Target, a: &str, now: &str, private: bool, link: bool) {
1210 let latest = self.config.ttl.latest_max_age.as_secs();
1211 reply.cache = if private {
1212 Cache::Private
1213 } else {
1214 match target.asof() {
1215 Some(x) if x <= now => Cache::Immutable,
1216 Some(_) => Cache::Public(latest),
1217 None => Cache::Public(latest),
1218 }
1219 };
1220 if link && target.asof().is_none() {
1221 reply.canonical = Some(format!("{}/cell/{}", self.config.origin(), target.rest_asof(a)));
1222 }
1223 }
1224
1225 fn unavailable(&self, target: &Target, e: ForeignError) -> Reply {
1228 tracing::info!(target: "datumesh_http", code = e.code.as_str(), detail = %e.detail, "unavailable");
1229 if e.code == crate::foreign::NAMESPACE_SUSPENDED {
1232 if let Ok(a) = datumesh_core::Answer::not_covered().with_error(ErrorCode::NamespaceSuspended) {
1233 return envelope::answer_reply(&envelope::with_fn_hash(a, Some(&target.bound.fn_hash)), Cache::NoStore);
1234 }
1235 }
1236 let lg = self.last_good.lock().unwrap_or_else(|p| p.into_inner());
1237 if let Some(g) = lg.get(&last_good_key(target)) {
1238 if target.asof().is_none_or(|a| g.info.asof.as_str() <= a) {
1239 let age = g.at.elapsed().as_secs();
1240 let a = datumesh_core::Answer::stale(g.info.parsed.clone(), g.info.trust, age);
1241 let a = envelope::with_fn_hash(a, Some(&g.info.parsed.cell().fn_hash));
1242 return envelope::answer_reply(&a, Cache::NoStore);
1243 }
1244 }
1245 if let Some(d) = e.foreign_detail() {
1246 let a = envelope::with_fn_hash(datumesh_core::Answer::foreign_unavailable(d), Some(&target.bound.fn_hash));
1247 return envelope::answer_reply(&a, Cache::NoStore);
1248 }
1249 envelope::error_answer_reply(e.code, Some(&target.bound.fn_hash))
1250 }
1251
1252 pub(crate) fn keys_for_receipt(&self, receipt: &[u8]) -> Keys {
1256 let mut hosts = std::collections::BTreeSet::new();
1257 if let Ok(v) = json::parse(receipt) {
1258 if let Some(h) = v.get("computed_by").and_then(Value::as_str) {
1259 hosts.insert(h.split('#').next().unwrap_or("").to_string());
1260 }
1261 if let Some(Value::Array(ins)) = v.get("inputs") {
1262 let mut members = Vec::new();
1263 for i in ins.iter().filter_map(Value::as_str).take(10_000) {
1264 if i.starts_with("slice:") {
1265 if let Some(m) =
1266 self.store.manifest(i).and_then(|m| datumesh_core::Manifest::from_json(&m).ok())
1267 {
1268 members.extend(m.members().iter().take(10_000).cloned());
1269 }
1270 } else {
1271 members.push(i.to_string());
1272 }
1273 }
1274 for h in members.iter().take(20_000) {
1275 if let Some(r) = self.store.receipt(h).and_then(|b| Receipt::from_json(&b).ok()) {
1276 hosts.insert(r.signer_host().to_string());
1277 }
1278 }
1279 }
1280 }
1281 let mut keys = Keys::new();
1282 for h in hosts {
1283 if let Some(r) = self.keys.result(&h) {
1284 keys.insert_result(&h, r);
1285 } else if let Some(doc) = self.key_doc(&h) {
1286 keys.insert(doc);
1287 }
1288 }
1289 keys
1290 }
1291
1292 fn key_doc(&self, host: &str) -> Option<KeyDoc> {
1294 if let Some((d, _, _)) = self.keys.get(host) {
1295 return Some(d);
1296 }
1297 let ns = self.store.namespace(host).ok()??;
1298 keys_from_response(host, 200, Some(&ns.keydoc)).ok()
1299 }
1300}
1301
1302fn verified(r: datumesh_core::VerifyResult) -> Verified {
1303 let s = |v: Option<&str>| v.map(|x| Value::String(x.to_string())).unwrap_or(Value::Null);
1304 let body = Value::Object(vec![
1305 ("blob_checked".into(), Value::Bool(r.blob_checked)),
1306 ("code".into(), s(r.code.map(|c| c.as_str()))),
1307 ("computed_by".into(), s(r.computed_by.as_deref())),
1308 ("detail".into(), Value::String(r.detail.clone())),
1309 ("hash".into(), s(r.hash.as_deref())),
1310 ("level".into(), s(r.level.map(|l| l.as_str()))),
1311 ("ok".into(), Value::Bool(r.ok)),
1312 ("path".into(), Value::String(r.path.clone())),
1313 ]);
1314 Verified { body: body.to_jcs() }
1315}
1316
1317#[derive(Clone, Debug, PartialEq, Eq)]
1319pub struct Verified {
1320 pub body: Vec<u8>,
1322}
1323
1324impl Mesh {
1325 pub fn builder(config: Config, store: Arc<dyn Store + Send + Sync>) -> MeshBuilder {
1327 MeshBuilder {
1328 config,
1329 store,
1330 key: None,
1331 key_file: None,
1332 runtimes: Vec::new(),
1333 formula: true,
1334 clock: Arc::new(SystemClock),
1335 fuel: None,
1336 licence: None,
1337 memo_capacity: None,
1338 }
1339 }
1340
1341 pub fn config(&self) -> &Config {
1343 &self.inner.config
1344 }
1345
1346 pub fn engine(&self) -> &Arc<Engine> {
1348 &self.inner.engine
1349 }
1350
1351 pub fn clear_memo(&self) {
1354 self.inner.engine.clear_memo();
1355 self.inner.latest.clear();
1356 }
1357
1358 pub fn foreign(&self) -> &Foreign {
1360 &self.inner.foreign
1361 }
1362
1363 pub fn store(&self) -> &Arc<dyn Store + Send + Sync> {
1365 &self.inner.store
1366 }
1367
1368 pub fn keys(&self) -> &KeyCache {
1371 &self.inner.keys
1372 }
1373
1374 pub fn stored_version_added(&self, cell_id: &str) {
1376 self.inner.version_added(cell_id);
1377 }
1378
1379 pub fn cell(&self, rest: &str, principal: Option<&Principal>) -> Reply {
1383 let now = self.inner.now();
1384 self.inner.answer(rest, principal, &*self.inner, &now, &mut |_| {})
1385 }
1386
1387 pub fn cells(&self, rests: &[String], principal: Option<&Principal>) -> Vec<Reply> {
1389 let now = self.inner.now();
1390 let memo = Memo::new(&self.inner);
1391 rests.iter().map(|r| self.inner.answer(r, principal, &memo, &now, &mut |_| {})).collect()
1392 }
1393
1394 pub fn resolve(&self, rest: &str, slice: bool) -> Result<Arc<Target>, Rejection> {
1396 let now = self.inner.now();
1397 call::resolve(rest, &now, &self.inner.config.aliases, &*self.inner, slice)
1398 }
1399
1400 pub fn describe(&self, id: &str) -> Reply {
1406 self.inner.describe(id)
1407 }
1408
1409 pub(crate) fn whatif(&self, body: &[u8], principal: Option<&Principal>) -> Reply {
1411 self.inner.whatif(body, principal)
1412 }
1413
1414 pub(crate) fn calc(&self, body: &[u8], principal: Option<&Principal>) -> Reply {
1416 self.inner.calc(body, principal)
1417 }
1418
1419 pub fn verify(&self, receipt: &[u8], signed_only: bool, blob: Option<&[u8]>) -> Verified {
1422 let keys = self.inner.keys_for_receipt(receipt);
1423 let resolver: Option<&dyn datumesh_core::Resolver> =
1424 if signed_only { None } else { Some(&*self.inner.engine as &dyn datumesh_core::Resolver) };
1425 verified(verify(receipt, &keys, resolver, blob))
1426 }
1427
1428 pub fn verify_offered(&self, receipt: &[u8], recompute: Option<&Value>, blob: Option<&[u8]>) -> Verified {
1432 let mut keys = self.inner.keys_for_receipt(receipt);
1433 let mut hosts = std::collections::BTreeSet::new();
1435 for (_, r) in recompute.and_then(|rc| rc.get("inputs")).and_then(Value::as_object).unwrap_or(&[]) {
1436 if let Some(h) = r
1437 .as_str()
1438 .and_then(|t| json::parse(t.as_bytes()).ok())
1439 .and_then(|v| v.get("computed_by").and_then(Value::as_str).map(str::to_string))
1440 {
1441 hosts.insert(h.split('#').next().unwrap_or("").to_string());
1442 }
1443 }
1444 for h in hosts {
1445 if let Some(r) = self.inner.keys.result(&h) {
1446 keys.insert_result(&h, r);
1447 } else if let Some(doc) = self.inner.key_doc(&h) {
1448 keys.insert(doc);
1449 }
1450 }
1451 let Some(rc) = recompute else {
1452 return verified(verify(receipt, &keys, None, blob));
1453 };
1454 let mut m = datumesh_core::MapResolver::new();
1455 let cell = json::parse(receipt).ok().and_then(|r| r.get("cell").cloned());
1456 if let (Some(d), Some(h)) =
1457 (rc.get("descriptor"), cell.as_ref().and_then(|c| c.get("fn_hash")).and_then(Value::as_str))
1458 {
1459 m.insert_descriptor(h, d.to_jcs());
1460 }
1461 for (h, r) in rc.get("inputs").and_then(Value::as_object).unwrap_or(&[]) {
1462 m.insert_receipt(h.as_str(), r.as_str().unwrap_or("").as_bytes());
1463 }
1464 for (e, t) in rc.get("manifests").and_then(Value::as_object).unwrap_or(&[]) {
1465 m.insert_manifest(e.as_str(), t.as_str().unwrap_or("").as_bytes());
1466 }
1467 let value = rc.get("value").and_then(|v| datumesh_core::Scalar::from_json(&v.to_jcs()).ok());
1468 if let (Some(value), Some(c)) = (value, cell.as_ref().and_then(|c| datumesh_core::Cell::from_value(c).ok())) {
1469 m.insert_value(c.id(), value);
1470 if let Some(Value::Array(l)) = rc.get("lineage") {
1471 m.insert_lineage(c.id(), l.iter().filter_map(Value::as_str));
1472 }
1473 }
1474 verified(verify(receipt, &keys, Some(&m), blob))
1475 }
1476
1477 pub fn mesh_document(&self) -> Vec<u8> {
1480 let o = self.inner.config.mesh_document_base();
1481 let mut ep: BTreeMap<&str, String> = [
1482 ("blob", format!("{o}/blob/{{sha256}}")),
1483 ("cell", format!("{o}/cell/{{cell}}")),
1484 ("cells", format!("{o}/cells")),
1485 ("x_bundles", format!("{o}/bundles")),
1486 ("x_calc", format!("{o}/x/calc")),
1487 ("x_interval", format!("{o}/x/interval/{{function}}")),
1488 ("describe", format!("{o}/describe/{{id}}")),
1489 ("descriptor", format!("{o}/descriptor/{{hash}}")),
1490 ("explain", format!("{o}/explain/{{cell}}")),
1491 ("find", format!("{o}/find")),
1492 ("jobs", format!("{o}/jobs/{{job}}")),
1493 ("manifest", format!("{o}/manifest/{{slice_id}}/{{members_hash}}")),
1494 ("receipt", format!("{o}/receipt/{{hash}}")),
1495 ("slice", format!("{o}/slice/{{cell}}")),
1496 ("verify", format!("{o}/verify")),
1497 ("whatif", format!("{o}/whatif")),
1498 ("versions", format!("{o}/versions/{{cell}}")),
1499 ]
1500 .into_iter()
1501 .collect();
1502 if self.inner.config.key_names {
1503 ep.insert("x_keys", format!("{o}/x/keys"));
1504 }
1505 Value::Object(vec![
1506 ("bindings".into(), Value::String(format!("{o}/bindings"))),
1507 (
1508 "endpoints".into(),
1509 Value::Object(ep.into_iter().map(|(k, v)| (k.to_string(), Value::String(v))).collect()),
1510 ),
1511 ("host".into(), Value::String(self.inner.config.host.clone())),
1512 ("proto".into(), Value::String("datumesh/1".into())),
1513 ])
1514 .to_jcs()
1515 }
1516
1517 pub fn key_document(&self) -> Option<Vec<u8>> {
1519 self.inner.store.namespace(&self.inner.config.host).ok().flatten().map(|n| n.keydoc)
1520 }
1521
1522 pub fn metrics(&self) -> String {
1524 crate::http::metrics_text(&self.inner)
1525 }
1526
1527 pub fn requests_of(&self, route: &str) -> u64 {
1529 self.inner.metrics.requests_of(route)
1530 }
1531
1532 pub fn host_of(name: &str) -> &str {
1534 host_of(name)
1535 }
1536
1537 pub fn uptime(&self) -> Duration {
1539 self.inner.started.elapsed()
1540 }
1541}
1542
1543impl Inner {
1544 pub(crate) fn class_binding(&self, name: &str, asof: &str) -> Result<Option<Arc<call::BoundClass>>, ErrorCode> {
1547 let store_failed = |e: datumesh_store::Error| {
1548 tracing::warn!(target: "datumesh_http", error = %e, "resolve_class_binding");
1549 ErrorCode::InputUnavailable
1550 };
1551 let Some(b) = self.store.resolve_class_binding(name, asof).map_err(store_failed)? else { return Ok(None) };
1552 let Some(bytes) = self.store.class(&b.class_hash).map_err(store_failed)? else {
1553 return Err(ErrorCode::InputUnavailable);
1554 };
1555 let d = datumesh_core::ClassDescriptor::from_json(&bytes).map_err(|_| ErrorCode::InputUnavailable)?;
1556 Ok(Some(Arc::new(call::BoundClass { class_hash: b.class_hash, since: b.tx, descriptor: Arc::new(d) })))
1557 }
1558}
1559
1560#[cfg(test)]
1561mod tests {
1562 use super::*;
1563 use std::sync::atomic::{AtomicUsize, Ordering};
1564
1565 #[test]
1568 fn a_batch_looks_each_binding_up_once() {
1569 let seen = Seen::default();
1570 let lookups = AtomicUsize::new(0);
1571 let start = std::sync::Barrier::new(6);
1572 let look = || {
1573 lookups.fetch_add(1, Ordering::SeqCst);
1574 std::thread::sleep(Duration::from_millis(50));
1575 Ok(None)
1576 };
1577 std::thread::scope(|s| {
1578 for _ in 0..6 {
1579 s.spawn(|| {
1580 start.wait();
1581 assert!(matches!(seen.lookup("a.example/f", "2026-01-01T00:00:00Z", look), Ok(None)));
1582 });
1583 }
1584 });
1585 assert_eq!(lookups.load(Ordering::SeqCst), 1, "one lookup for six chunks");
1586 assert!(matches!(seen.lookup("a.example/f", "2026-01-01T00:00:00Z", look), Ok(None)));
1588 assert_eq!(lookups.load(Ordering::SeqCst), 1);
1589 assert!(matches!(seen.lookup("a.example/f", "2026-01-02T00:00:00Z", look), Ok(None)));
1591 assert!(matches!(seen.lookup("a.example/g", "2026-01-01T00:00:00Z", look), Ok(None)));
1592 assert_eq!(lookups.load(Ordering::SeqCst), 3);
1593 let fail = || Err(ErrorCode::InputUnavailable);
1595 assert!(matches!(seen.lookup("a.example/h", "2026-01-01T00:00:00Z", fail), Err(ErrorCode::InputUnavailable)));
1596 assert!(matches!(seen.lookup("a.example/h", "2026-01-01T00:00:00Z", look), Ok(None)));
1597 assert_eq!(lookups.load(Ordering::SeqCst), 4);
1598 }
1599}