1use std::collections::{HashMap, HashSet};
55use std::sync::{Arc, Mutex};
56use std::time::{Duration, Instant};
57
58use datumesh_core::{
59 format_uri, keys_from_response, Args, Cell, CellRef, Error as CoreError, ErrorCode, FunctionDescriptor, KeyDoc,
60 MeshDoc, Receipt, Request, Scalar,
61};
62use datumesh_engine::{Budget, Clock, EvalError, FnBinding, Input, Inputs, Member, Runtime, SlicePattern};
63use datumesh_store::Store;
64
65use crate::client::{Client, ClientConfig};
66use crate::config::Config;
67
68type Version = (Vec<u8>, Box<Receipt>);
70
71pub(crate) const NAMESPACE_SUSPENDED: ErrorCode = ErrorCode::NamespaceSuspended;
76
77fn store_refusal(op: &str, e: datumesh_store::Error) -> ForeignError {
80 let code = match e {
81 datumesh_store::Error::NamespaceSuspended { .. } => NAMESPACE_SUSPENDED,
82 _ => ErrorCode::InputUnavailable,
83 };
84 ForeignError::new(code, format!("{op}: {e}"))
85}
86
87const MAX_WALK: usize = 10_000;
89
90const END: &str = "9999-12-31T23:59:59.999999Z";
92
93#[derive(Default)]
96pub struct KeyCache {
97 #[allow(clippy::type_complexity)]
98 docs: Mutex<HashMap<String, (Result<KeyDoc, CoreError>, Vec<u8>, Instant)>>,
99}
100
101impl std::fmt::Debug for KeyCache {
102 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
103 f.debug_struct("KeyCache").field("hosts", &self.docs.lock().map(|d| d.len()).unwrap_or(0)).finish()
104 }
105}
106
107impl KeyCache {
108 pub fn insert(&self, host: &str, doc: &[u8]) -> Result<(), CoreError> {
111 let kd = keys_from_response(host, 200, Some(doc))?;
112 self.docs
113 .lock()
114 .unwrap_or_else(|p| p.into_inner())
115 .insert(host.to_string(), (Ok(kd), doc.to_vec(), Instant::now()));
116 Ok(())
117 }
118
119 pub fn insert_response(&self, host: &str, status: u16, body: Option<&[u8]>) {
122 let r = keys_from_response(host, status, body);
123 self.docs
124 .lock()
125 .unwrap_or_else(|p| p.into_inner())
126 .insert(host.to_string(), (r, body.unwrap_or_default().to_vec(), Instant::now()));
127 }
128
129 pub fn get(&self, host: &str) -> Option<(KeyDoc, Vec<u8>, Instant)> {
131 match self.docs.lock().unwrap_or_else(|p| p.into_inner()).get(host) {
132 Some((Ok(d), b, at)) => Some((d.clone(), b.clone(), *at)),
133 _ => None,
134 }
135 }
136
137 pub fn result(&self, host: &str) -> Option<Result<KeyDoc, CoreError>> {
139 self.docs.lock().unwrap_or_else(|p| p.into_inner()).get(host).map(|(r, _, _)| r.clone())
140 }
141
142 pub fn remove(&self, host: &str) {
144 self.docs.lock().unwrap_or_else(|p| p.into_inner()).remove(host);
145 }
146}
147
148pub(crate) fn hosted_marker(host: &str) -> Vec<u8> {
150 format!("datumesh hosted namespace 1\n{host}\n").into_bytes()
151}
152
153pub type ForeignError = crate::client::ClientError;
156
157impl ForeignError {
158 pub(crate) fn eval(self) -> EvalError {
161 EvalError::InvalidInput(CoreError::new(self.code, "$", format!("cross-mesh: {}", self.detail)))
162 }
163}
164
165pub fn pct(s: &str) -> String {
167 crate::client::pct(s)
168}
169
170fn before(t: &str) -> Option<String> {
172 let us = datumesh_formula::calendar::parse_instant(t)?;
173 datumesh_formula::calendar::instant_text(us - 1)
174}
175
176pub fn host_of(name: &str) -> &str {
178 name.split('/').next().unwrap_or(name)
179}
180
181struct Confirmed {
182 at: Instant,
183 instant: String,
185}
186
187pub struct Foreign {
190 store: Arc<dyn Store + Send + Sync>,
191 client: Client,
192 clock: Arc<dyn Clock>,
193 owned: Vec<String>,
194 listed: Vec<String>,
197 enabled: bool,
198 ttl_binding: Duration,
199 ttl_current: Duration,
200 names: Mutex<HashMap<String, Confirmed>>,
201 cells: Mutex<HashMap<String, Confirmed>>,
202 invalidated: Mutex<Vec<String>>,
203 dirty: std::sync::atomic::AtomicBool,
206 any: std::sync::atomic::AtomicBool,
207 deps: Mutex<HashMap<String, Arc<Vec<Cell>>>>,
208 engine: std::sync::OnceLock<std::sync::Weak<datumesh_engine::Engine>>,
211 budget: Duration,
213 hosted: Mutex<std::collections::HashSet<String>>,
215 pub(crate) fetches: std::sync::atomic::AtomicU64,
217 pub(crate) failures: std::sync::atomic::AtomicU64,
218 pub(crate) imported: std::sync::atomic::AtomicU64,
219}
220
221impl std::fmt::Debug for Foreign {
222 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
223 f.debug_struct("Foreign").field("owned", &self.owned).field("enabled", &self.enabled).finish_non_exhaustive()
224 }
225}
226
227enum Fetched {
228 Receipt(Vec<u8>, Box<Receipt>),
229 NotCovered,
230}
231
232impl Foreign {
233 pub(crate) fn new(
234 config: &Config,
235 store: Arc<dyn Store + Send + Sync>,
236 keys: Arc<KeyCache>,
237 clock: Arc<dyn Clock>,
238 ) -> Foreign {
239 let cc = ClientConfig {
240 peers: config.peers.clone(),
241 allowed: config.cross_mesh_hosts.clone(),
242 timeout: config.peer_timeout,
243 key_ttl: config.ttl.key_doc,
244 key_refetch: config.ttl.key_refetch,
245 mesh_ttl: config.ttl.mesh_doc,
246 };
247 Foreign {
248 engine: std::sync::OnceLock::new(),
249 budget: config.budget,
250 store,
251 client: Client::with_keys(cc, keys),
252 clock,
253 owned: config.namespaces.clone(),
254 listed: config.listed_meshes.clone(),
255 enabled: config.cross_mesh,
256 ttl_binding: config.ttl.binding,
257 ttl_current: config.ttl.current,
258 names: Mutex::new(HashMap::new()),
259 cells: Mutex::new(HashMap::new()),
260 invalidated: Mutex::new(Vec::new()),
261 dirty: Default::default(),
262 any: Default::default(),
263 deps: Mutex::new(HashMap::new()),
264 hosted: Mutex::new(Default::default()),
265 fetches: Default::default(),
266 failures: Default::default(),
267 imported: Default::default(),
268 }
269 }
270
271 pub fn client(&self) -> &Client {
273 &self.client
274 }
275
276 pub fn is_foreign(&self, name: &str) -> bool {
279 let host = host_of(name);
280 self.enabled
281 && !self.owned.iter().any(|h| h == host)
282 && !self.is_listed(host)
283 && self.client.allowed(host)
284 && !self.is_hosted(host)
285 }
286
287 fn is_listed(&self, host: &str) -> bool {
290 self.listed.iter().any(|h| h == host)
291 }
292
293 fn refuse_listed(&self, host: &str) -> Result<(), ForeignError> {
295 if self.is_listed(host) {
296 return Err(ForeignError::unavailable(format!(
297 "{host} is a listed mesh: its names are not resolved across meshes"
298 )));
299 }
300 Ok(())
301 }
302
303 fn is_hosted(&self, host: &str) -> bool {
306 if self.hosted.lock().unwrap_or_else(|p| p.into_inner()).contains(host) {
307 return true;
308 }
309 let key = datumesh_core::sha256_hex(&hosted_marker(host));
310 let hosted = matches!(self.store.blob(&key), Ok(Some(_)));
311 if hosted {
312 self.hosted.lock().unwrap_or_else(|p| p.into_inner()).insert(host.to_string());
313 }
314 hosted
315 }
316
317 pub(crate) fn host(&self, host: &str) -> Result<(), String> {
320 self.store.put_blob(&hosted_marker(host)).map_err(|e| format!("hosted marker of {host}: {e}"))?;
321 self.hosted.lock().unwrap_or_else(|p| p.into_inner()).insert(host.to_string());
322 Ok(())
323 }
324
325 pub fn any_cells(&self) -> bool {
327 self.any.load(std::sync::atomic::Ordering::Acquire)
328 }
329
330 pub fn take_invalidated(&self) -> Vec<String> {
333 if !self.dirty.swap(false, std::sync::atomic::Ordering::AcqRel) {
334 return Vec::new();
335 }
336 std::mem::take(&mut *self.invalidated.lock().unwrap_or_else(|p| p.into_inner()))
337 }
338
339 fn counted<T>(&self, r: Result<T, ForeignError>) -> Result<T, ForeignError> {
340 self.fetches.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
341 if r.is_err() {
342 self.failures.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
343 }
344 r
345 }
346
347 pub fn keys_for(&self, host: &str, refresh: bool) -> Result<KeyDoc, ForeignError> {
349 self.counted(self.client.key_document(host, refresh))
350 }
351
352 pub fn mesh(&self, host: &str) -> Result<MeshDoc, ForeignError> {
354 self.counted(self.client.resolve(host))
355 }
356
357 pub fn ensure_name(&self, name: &str) -> Result<(), ForeignError> {
359 self.refuse_listed(host_of(name))?;
360 if !self.is_foreign(name) {
361 return Ok(());
362 }
363 if let Some(c) = self.names.lock().unwrap_or_else(|p| p.into_inner()).get(name) {
364 if c.at.elapsed() < self.ttl_binding {
365 return Ok(());
366 }
367 }
368 let now = self.clock.now();
369 let host = host_of(name);
370 let local = self
371 .store
372 .resolve_binding(name, END)
373 .map_err(|e| ForeignError::unavailable(format!("store: {e}")))?
374 .map(|b| (b.fn_hash, b.tx));
375 let mut chain = Vec::new();
376 let mut at: Option<String> = None;
377 while let Some(b) = self.counted(self.client.binding(host, name, at.as_deref()))? {
378 let b = (b.fn_hash, b.since);
379 if Some(&b) == local.as_ref() {
380 break;
381 }
382 if chain.len() >= MAX_WALK {
383 return Err(ForeignError::unavailable(format!("{name}: more than {MAX_WALK} bindings")));
384 }
385 at = Some(before(&b.1).ok_or_else(|| ForeignError::unavailable("a binding at the first instant"))?);
386 let stop = at.as_deref() < Some("0001-01-01T00:00:00.000000Z");
387 chain.push(b);
388 if stop {
389 break;
390 }
391 }
392 if let (Some(oldest), Some(l)) = (chain.last(), &local) {
393 if oldest.1 <= l.1 {
394 return Err(ForeignError::unavailable(format!("{name}: the other mesh's bindings do not extend ours")));
395 }
396 }
397 for (fn_hash, since) in chain.iter().rev() {
398 self.import_descriptor(host, fn_hash)?;
399 self.store.bind_name(name, fn_hash, since).map_err(|e| store_refusal(&format!("bind {name}"), e))?;
400 }
401 self.names
402 .lock()
403 .unwrap_or_else(|p| p.into_inner())
404 .insert(name.to_string(), Confirmed { at: Instant::now(), instant: now });
405 Ok(())
406 }
407
408 fn import_descriptor(&self, host: &str, fn_hash: &str) -> Result<(), ForeignError> {
409 if self.store.descriptor(fn_hash).is_some() {
410 return Ok(());
411 }
412 let body = self.counted(self.client.descriptor(host, fn_hash))?;
413 let h = self
414 .store
415 .put_descriptor(&body)
416 .map_err(|e| ForeignError::new(ErrorCode::FnHashMismatch, e.to_string()))?;
417 if h != fn_hash {
418 return Err(ForeignError::new(ErrorCode::FnHashMismatch, format!("{host} gave the descriptor {h}")));
419 }
420 Ok(())
421 }
422
423 fn fetch_cell(&self, cell: &Cell, asof: Option<&str>) -> Result<Fetched, ForeignError> {
426 let host = host_of(&cell.ns);
427 let reference = CellRef {
428 ns: cell.ns.clone(),
429 fn_name: cell.fn_name.clone(),
430 args: cell.args.clone(),
431 asof: asof.map(str::to_string),
432 };
433 let uri = format_uri(&reference);
434 let request = Request::new(&cell.id(), asof).map_err(|_| ForeignError::unavailable("request"))?;
435 let f = match self.counted(self.client.cell(host, &uri["cell://".len()..], &request)) {
436 Ok(f) => f,
437 Err(e) if e.code == ErrorCode::Envelope => return Err(ForeignError::unavailable(e.detail)),
438 Err(e) => return Err(e),
439 };
440 match (f.answer.outcome.as_str(), f.answer.receipt) {
441 ("ok" | "stale", Some(r)) => {
442 let bytes = datumesh_core::json::parse(&f.body)
443 .ok()
444 .and_then(|v| v.get("receipt").map(datumesh_core::json::Value::to_jcs))
445 .ok_or_else(|| ForeignError::unavailable("receipt"))?;
446 Ok(Fetched::Receipt(bytes, Box::new(r)))
447 }
448 ("not_covered", _) => Ok(Fetched::NotCovered),
449 (o, _) => Err(ForeignError::unavailable(format!("{host}: {o}"))),
450 }
451 }
452
453 fn listed_versions(&self, cell: &Cell, after_tx: Option<&str>) -> Result<Option<Vec<Version>>, ForeignError> {
456 let host = host_of(&cell.ns);
457 let mesh = self.mesh(host)?;
458 if !mesh.endpoints.contains_key("versions") {
459 return Ok(None);
460 }
461 let reference =
462 CellRef { ns: cell.ns.clone(), fn_name: cell.fn_name.clone(), args: cell.args.clone(), asof: None };
463 let uri = format_uri(&reference);
464 let mut rest = uri["cell://".len()..].to_string();
465 if let Some(t) = after_tx
466 .and_then(datumesh_formula::calendar::parse_instant)
467 .and_then(|us| datumesh_formula::calendar::instant_text(us + 1))
468 {
469 rest.push(if rest.contains('?') { '&' } else { '?' });
470 rest.push_str(&format!("from={t}"));
471 }
472 let mut page = self.counted(self.client.versions(host, &rest))?;
473 let mut out = Vec::new();
474 loop {
475 if page.cell.get("fn_hash").and_then(datumesh_core::json::Value::as_str) != Some(cell.fn_hash.as_str()) {
476 return Err(ForeignError::unavailable(format!("{host}: the versions of another function")));
477 }
478 for v in &page.versions {
479 let bytes = self.counted(self.client.receipt(host, &v.receipt))?;
480 let r = Receipt::from_json(&bytes).map_err(|e| ForeignError::new(e.code(), e.to_string()))?;
481 if r.cell().id() != cell.id() || r.tx() != v.tx {
482 return Err(ForeignError::unavailable(format!("{host}: a version of another cell")));
483 }
484 out.push((bytes, Box::new(r)));
485 if out.len() > MAX_WALK {
486 return Err(ForeignError::unavailable(format!("{host}: more than {MAX_WALK} versions")));
487 }
488 }
489 match page.next.clone() {
490 Some(n) => page = self.counted(self.client.versions_at(&n))?,
491 None => break,
492 }
493 }
494 Ok(Some(out))
495 }
496
497 pub fn ensure_cell(&self, cell: &Cell) -> Result<bool, ForeignError> {
500 self.refuse_listed(host_of(&cell.function_name()))?;
501 let id = cell.id();
502 if let Some(c) = self.cells.lock().unwrap_or_else(|p| p.into_inner()).get(&id) {
503 if c.at.elapsed() < self.ttl_current {
504 return Ok(false);
505 }
506 }
507 let now = self.clock.now();
508 let name = cell.function_name();
509 let current = self
510 .store
511 .resolve_binding(&name, &now)
512 .map_err(|e| ForeignError::unavailable(format!("store: {e}")))?
513 .map(|b| b.fn_hash);
514 if current.as_deref() != Some(cell.fn_hash.as_str()) {
515 if self.cells.lock().unwrap_or_else(|p| p.into_inner()).contains_key(&id) {
516 return Ok(false);
518 }
519 return Err(ForeignError::unavailable(format!(
520 "{name}: a cell of an earlier binding is not resolved in 0.1.x"
521 )));
522 }
523 let local = self.store.latest(&id).map_err(|e| ForeignError::unavailable(format!("store: {e}")))?;
524 let chain: Vec<(Vec<u8>, Box<Receipt>)> =
526 match self.listed_versions(cell, local.as_ref().map(|v| v.tx.as_str()))? {
527 Some(listed) => listed,
528 None => {
529 let mut chain: Vec<(Vec<u8>, Box<Receipt>)> = Vec::new();
530 let mut at: Option<String> = None;
531 loop {
532 match self.fetch_cell(cell, at.as_deref())? {
533 Fetched::NotCovered => break,
534 Fetched::Receipt(bytes, r) => {
535 if local.as_ref().is_some_and(|v| v.receipt_hash == r.hash()) {
536 break;
537 }
538 if chain.iter().any(|(_, c)| c.hash() == r.hash()) || chain.len() >= MAX_WALK {
539 return Err(ForeignError::unavailable(format!(
540 "{name}: the other mesh's history does not end"
541 )));
542 }
543 let start = std::cmp::max(r.tx(), r.asof()).to_string();
544 let next = before(&start);
545 chain.push((bytes, r));
546 match next {
547 Some(t) => at = Some(t),
548 None => break,
549 }
550 }
551 }
552 }
553 chain.reverse();
554 chain
555 }
556 };
557 if let (Some((_, oldest)), Some(l)) = (chain.first(), &local) {
558 if oldest.tx() <= l.tx.as_str() {
559 return Err(ForeignError::unavailable(format!("{name}: the other mesh's versions do not extend ours")));
560 }
561 }
562 let added = !chain.is_empty();
563 for (bytes, r) in &chain {
564 self.ensure_namespace(r.signer_host())?;
565 let h = self.store.put_receipt(bytes).map_err(|e| store_refusal("put_receipt", e))?;
566 self.store.put_version(&id, r.tx(), &h).map_err(|e| store_refusal("put_version", e))?;
567 self.imported.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
568 }
569 if added {
570 self.invalidated.lock().unwrap_or_else(|p| p.into_inner()).push(id.clone());
571 self.dirty.store(true, std::sync::atomic::Ordering::Release);
572 }
573 self.cells.lock().unwrap_or_else(|p| p.into_inner()).insert(id, Confirmed { at: Instant::now(), instant: now });
574 self.any.store(true, std::sync::atomic::Ordering::Release);
575 Ok(added)
576 }
577
578 fn ensure_namespace(&self, host: &str) -> Result<(), ForeignError> {
581 self.refuse_listed(host)?;
582 if self.owned.iter().any(|h| h == host) {
583 return Ok(());
584 }
585 self.keys_for(host, false)?;
586 self.store_key_document(host)
587 }
588
589 pub fn ensure_publisher(&self, ns: &str) -> Result<(), ForeignError> {
596 self.refuse_listed(host_of(ns))?;
597 if !self.is_foreign(ns) {
598 return Ok(());
599 }
600 let host = host_of(ns);
601 self.counted(self.client.publisher_key_document(host))?;
602 self.store_key_document(host)
603 }
604
605 fn store_key_document(&self, host: &str) -> Result<(), ForeignError> {
607 let bytes = self
608 .client
609 .key_document_bytes(host)
610 .ok_or_else(|| ForeignError::new(ErrorCode::KeyUnavailable, host.to_string()))?;
611 let stored = self.store.namespace(host).map_err(|e| ForeignError::unavailable(format!("store: {e}")))?;
612 if stored.as_ref().map(|n| n.keydoc.as_slice()) != Some(bytes.as_slice()) {
613 self.store
614 .put_namespace(host, &bytes, &self.clock.now())
615 .map_err(|e| ForeignError::new(ErrorCode::KeyDoc, format!("put_namespace {host}: {e}")))?;
616 }
617 Ok(())
618 }
619
620 pub(crate) fn set_engine(&self, engine: std::sync::Weak<datumesh_engine::Engine>) {
624 let _ = self.engine.set(engine);
625 }
626
627 fn foreign_deps(&self, receipt_hash: &str, metrics: Option<&crate::metrics::Metrics>) -> Arc<Vec<Cell>> {
628 if let Some(d) = self.deps.lock().unwrap_or_else(|p| p.into_inner()).get(receipt_hash) {
629 return d.clone();
630 }
631 let mut out = Vec::new();
632 let mut seen = HashSet::new();
633 let mut todo: Vec<(String, Option<String>)> = vec![(receipt_hash.to_string(), None)];
635 let deadline = Instant::now() + self.budget;
636 let engine = self.engine.get().and_then(std::sync::Weak::upgrade);
637 while let Some((h, citing)) = todo.pop() {
638 if !seen.insert(h.clone()) || seen.len() > 100_000 {
639 continue;
640 }
641 if h.starts_with("slice:") {
642 if let Some(e) = &engine {
643 let m = crate::manifest_route::members_for_reader(
644 &*self.store,
645 e,
646 metrics,
647 &h,
648 citing.as_deref(),
649 deadline,
650 );
651 if let Some(m) = m {
652 todo.extend(m.members().iter().map(|x| (x.clone(), citing.clone())));
653 }
654 }
655 continue;
656 }
657 let Some(bytes) = self.store.receipt(&h) else {
658 continue;
659 };
660 let Ok(r) = Receipt::from_json(&bytes) else { continue };
661 if self.is_foreign(&r.cell().ns) && r.inputs().is_empty() {
662 out.push(r.cell().clone());
663 } else {
664 let asof = Some(r.asof().to_string());
665 todo.extend(r.inputs().iter().map(|x| (x.clone(), asof.clone())));
666 }
667 }
668 let d = Arc::new(out);
669 let mut deps = self.deps.lock().unwrap_or_else(|p| p.into_inner());
670 if deps.len() > 100_000 {
671 deps.clear();
672 }
673 deps.insert(receipt_hash.to_string(), d.clone());
674 d
675 }
676
677 pub fn refresh_deps(&self, receipt_hash: &str, asof: &str) -> Result<bool, ForeignError> {
681 self.refresh_deps_counted(receipt_hash, asof, None)
682 }
683
684 pub(crate) fn refresh_deps_counted(
686 &self,
687 receipt_hash: &str,
688 asof: &str,
689 metrics: Option<&crate::metrics::Metrics>,
690 ) -> Result<bool, ForeignError> {
691 if !self.any_cells() {
692 return Ok(false);
693 }
694 let mut added = false;
695 for cell in self.foreign_deps(receipt_hash, metrics).iter() {
696 let stale = match self.cells.lock().unwrap_or_else(|p| p.into_inner()).get(&cell.id()) {
697 Some(c) => c.at.elapsed() >= self.ttl_current && asof > c.instant.as_str(),
698 None => true,
699 };
700 if stale {
701 added |= self.ensure_cell(cell)?;
702 }
703 }
704 Ok(added)
705 }
706
707 pub fn prepare(&self, cell: &Cell, stored: bool, asof: Option<&str>) -> Result<(), ForeignError> {
710 if !self.is_foreign(&cell.function_name()) || !stored {
711 return Ok(());
712 }
713 let fresh = match self.cells.lock().unwrap_or_else(|p| p.into_inner()).get(&cell.id()) {
714 Some(c) => c.at.elapsed() < self.ttl_current || asof.is_some_and(|a| a <= c.instant.as_str()),
715 None => false,
716 };
717 if !fresh {
718 self.ensure_cell(cell)?;
719 }
720 Ok(())
721 }
722}
723
724pub struct CrossMesh {
726 inner: Arc<dyn Runtime>,
727 foreign: Arc<Foreign>,
728}
729
730impl CrossMesh {
731 pub fn new(inner: Arc<dyn Runtime>, foreign: Arc<Foreign>) -> CrossMesh {
733 CrossMesh { inner, foreign }
734 }
735}
736
737impl Runtime for CrossMesh {
738 fn lang(&self) -> &str {
739 self.inner.lang()
740 }
741
742 fn evaluate(
743 &self,
744 descriptor: &FunctionDescriptor,
745 cell: &Cell,
746 inputs: &mut dyn Inputs,
747 budget: &mut Budget,
748 ) -> Result<Scalar, EvalError> {
749 self.foreign.ensure_publisher(&cell.ns).map_err(ForeignError::eval)?;
751 for name in &descriptor.inputs {
752 self.foreign.ensure_name(name).map_err(ForeignError::eval)?;
753 }
754 let mut w = Through { inner: inputs, foreign: &self.foreign };
755 self.inner.evaluate(descriptor, cell, &mut w, budget)
756 }
757
758 fn asof_dependent(&self, descriptor: &FunctionDescriptor) -> bool {
759 self.inner.asof_dependent(descriptor)
760 }
761}
762
763struct Through<'a> {
765 inner: &'a mut dyn Inputs,
766 foreign: &'a Foreign,
767}
768
769impl Through<'_> {
770 fn pre(&mut self, name: &str, args: &Args, at: Option<&str>) -> Result<(), EvalError> {
771 if !self.foreign.is_foreign(name) {
772 return Ok(());
773 }
774 self.foreign.ensure_name(name).map_err(ForeignError::eval)?;
775 let Some(b) = self.inner.binding_peek(name, at)? else {
776 return Ok(());
777 };
778 if b.descriptor.lang != "stored" {
779 return Ok(());
780 }
781 let (ns, f) = name.rsplit_once('/').unwrap_or((name, ""));
782 let cell = Cell { ns: ns.to_string(), fn_name: f.to_string(), fn_hash: b.fn_hash.clone(), args: args.clone() };
783 self.foreign.ensure_cell(&cell).map_err(ForeignError::eval)?;
784 Ok(())
785 }
786}
787
788impl Inputs for Through<'_> {
789 fn read(&mut self, fn_name: &str, args: &Args) -> Result<Scalar, EvalError> {
790 self.pre(fn_name, args, None)?;
791 self.inner.read(fn_name, args)
792 }
793
794 fn read_cell(&mut self, fn_name: &str, args: &Args) -> Result<Input, EvalError> {
795 self.pre(fn_name, args, None)?;
796 self.inner.read_cell(fn_name, args)
797 }
798
799 fn read_asof(&mut self, fn_name: &str, args: &Args, t: &str) -> Result<Input, EvalError> {
800 self.pre(fn_name, args, Some(t))?;
801 self.inner.read_asof(fn_name, args, t)
802 }
803
804 fn read_slice(&mut self, fn_name: &str, pattern: &SlicePattern) -> Result<Vec<Member>, EvalError> {
805 if self.foreign.is_foreign(fn_name) {
806 self.foreign.ensure_name(fn_name).map_err(ForeignError::eval)?;
807 if let Some(b) = self.inner.binding_peek(fn_name, None)? {
808 if b.descriptor.lang == "stored" {
809 return Err(ForeignError::unavailable(format!(
810 "{fn_name}: slices of foreign stored functions are not read in 0.1.0"
811 ))
812 .eval());
813 }
814 }
815 }
816 self.inner.read_slice(fn_name, pattern)
817 }
818
819 fn read_versions(&mut self, fn_name: &str, args: &Args, from: &str, to: &str) -> Result<Vec<Input>, EvalError> {
820 self.pre(fn_name, args, None)?;
821 self.inner.read_versions(fn_name, args, from, to)
822 }
823
824 fn read_pinned(&mut self, fn_name: &str, fn_hash: &str, args: &Args) -> Result<Input, EvalError> {
825 self.inner.read_pinned(fn_name, fn_hash, args)
828 }
829
830 fn binding(&mut self, fn_name: &str, at: Option<&str>) -> Result<Option<FnBinding>, EvalError> {
831 self.foreign.ensure_name(fn_name).map_err(ForeignError::eval)?;
832 self.inner.binding(fn_name, at)
833 }
834
835 fn asof(&mut self) -> String {
836 self.inner.asof()
837 }
838
839 fn binding_peek(&mut self, fn_name: &str, at: Option<&str>) -> Result<Option<FnBinding>, EvalError> {
840 self.foreign.ensure_name(fn_name).map_err(ForeignError::eval)?;
841 self.inner.binding_peek(fn_name, at)
842 }
843
844 fn asof_compare(&mut self, t: &str) -> Result<std::cmp::Ordering, EvalError> {
845 self.inner.asof_compare(t)
846 }
847
848 fn read_blob(&mut self, sha256: &str, length: u64) -> Result<Vec<u8>, EvalError> {
849 self.inner.read_blob(sha256, length)
850 }
851}