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 enabled: bool,
195 ttl_binding: Duration,
196 ttl_current: Duration,
197 names: Mutex<HashMap<String, Confirmed>>,
198 cells: Mutex<HashMap<String, Confirmed>>,
199 invalidated: Mutex<Vec<String>>,
200 dirty: std::sync::atomic::AtomicBool,
203 any: std::sync::atomic::AtomicBool,
204 deps: Mutex<HashMap<String, Arc<Vec<Cell>>>>,
205 engine: std::sync::OnceLock<std::sync::Weak<datumesh_engine::Engine>>,
208 budget: Duration,
210 hosted: Mutex<std::collections::HashSet<String>>,
212 pub(crate) fetches: std::sync::atomic::AtomicU64,
214 pub(crate) failures: std::sync::atomic::AtomicU64,
215 pub(crate) imported: std::sync::atomic::AtomicU64,
216}
217
218impl std::fmt::Debug for Foreign {
219 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
220 f.debug_struct("Foreign").field("owned", &self.owned).field("enabled", &self.enabled).finish_non_exhaustive()
221 }
222}
223
224enum Fetched {
225 Receipt(Vec<u8>, Box<Receipt>),
226 NotCovered,
227}
228
229impl Foreign {
230 pub(crate) fn new(
231 config: &Config,
232 store: Arc<dyn Store + Send + Sync>,
233 keys: Arc<KeyCache>,
234 clock: Arc<dyn Clock>,
235 ) -> Foreign {
236 let cc = ClientConfig {
237 peers: config.peers.clone(),
238 allowed: config.cross_mesh_hosts.clone(),
239 timeout: config.peer_timeout,
240 key_ttl: config.ttl.key_doc,
241 key_refetch: config.ttl.key_refetch,
242 mesh_ttl: config.ttl.mesh_doc,
243 };
244 Foreign {
245 engine: std::sync::OnceLock::new(),
246 budget: config.budget,
247 store,
248 client: Client::with_keys(cc, keys),
249 clock,
250 owned: config.namespaces.clone(),
251 enabled: config.cross_mesh,
252 ttl_binding: config.ttl.binding,
253 ttl_current: config.ttl.current,
254 names: Mutex::new(HashMap::new()),
255 cells: Mutex::new(HashMap::new()),
256 invalidated: Mutex::new(Vec::new()),
257 dirty: Default::default(),
258 any: Default::default(),
259 deps: Mutex::new(HashMap::new()),
260 hosted: Mutex::new(Default::default()),
261 fetches: Default::default(),
262 failures: Default::default(),
263 imported: Default::default(),
264 }
265 }
266
267 pub fn client(&self) -> &Client {
269 &self.client
270 }
271
272 pub fn is_foreign(&self, name: &str) -> bool {
275 let host = host_of(name);
276 self.enabled && !self.owned.iter().any(|h| h == host) && self.client.allowed(host) && !self.is_hosted(host)
277 }
278
279 fn is_hosted(&self, host: &str) -> bool {
282 if self.hosted.lock().unwrap_or_else(|p| p.into_inner()).contains(host) {
283 return true;
284 }
285 let key = datumesh_core::sha256_hex(&hosted_marker(host));
286 let hosted = matches!(self.store.blob(&key), Ok(Some(_)));
287 if hosted {
288 self.hosted.lock().unwrap_or_else(|p| p.into_inner()).insert(host.to_string());
289 }
290 hosted
291 }
292
293 pub(crate) fn host(&self, host: &str) -> Result<(), String> {
296 self.store.put_blob(&hosted_marker(host)).map_err(|e| format!("hosted marker of {host}: {e}"))?;
297 self.hosted.lock().unwrap_or_else(|p| p.into_inner()).insert(host.to_string());
298 Ok(())
299 }
300
301 pub fn any_cells(&self) -> bool {
303 self.any.load(std::sync::atomic::Ordering::Acquire)
304 }
305
306 pub fn take_invalidated(&self) -> Vec<String> {
309 if !self.dirty.swap(false, std::sync::atomic::Ordering::AcqRel) {
310 return Vec::new();
311 }
312 std::mem::take(&mut *self.invalidated.lock().unwrap_or_else(|p| p.into_inner()))
313 }
314
315 fn counted<T>(&self, r: Result<T, ForeignError>) -> Result<T, ForeignError> {
316 self.fetches.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
317 if r.is_err() {
318 self.failures.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
319 }
320 r
321 }
322
323 pub fn keys_for(&self, host: &str, refresh: bool) -> Result<KeyDoc, ForeignError> {
325 self.counted(self.client.key_document(host, refresh))
326 }
327
328 pub fn mesh(&self, host: &str) -> Result<MeshDoc, ForeignError> {
330 self.counted(self.client.resolve(host))
331 }
332
333 pub fn ensure_name(&self, name: &str) -> Result<(), ForeignError> {
335 if !self.is_foreign(name) {
336 return Ok(());
337 }
338 if let Some(c) = self.names.lock().unwrap_or_else(|p| p.into_inner()).get(name) {
339 if c.at.elapsed() < self.ttl_binding {
340 return Ok(());
341 }
342 }
343 let now = self.clock.now();
344 let host = host_of(name);
345 let local = self
346 .store
347 .resolve_binding(name, END)
348 .map_err(|e| ForeignError::unavailable(format!("store: {e}")))?
349 .map(|b| (b.fn_hash, b.tx));
350 let mut chain = Vec::new();
351 let mut at: Option<String> = None;
352 while let Some(b) = self.counted(self.client.binding(host, name, at.as_deref()))? {
353 let b = (b.fn_hash, b.since);
354 if Some(&b) == local.as_ref() {
355 break;
356 }
357 if chain.len() >= MAX_WALK {
358 return Err(ForeignError::unavailable(format!("{name}: more than {MAX_WALK} bindings")));
359 }
360 at = Some(before(&b.1).ok_or_else(|| ForeignError::unavailable("a binding at the first instant"))?);
361 let stop = at.as_deref() < Some("0001-01-01T00:00:00.000000Z");
362 chain.push(b);
363 if stop {
364 break;
365 }
366 }
367 if let (Some(oldest), Some(l)) = (chain.last(), &local) {
368 if oldest.1 <= l.1 {
369 return Err(ForeignError::unavailable(format!("{name}: the other mesh's bindings do not extend ours")));
370 }
371 }
372 for (fn_hash, since) in chain.iter().rev() {
373 self.import_descriptor(host, fn_hash)?;
374 self.store.bind_name(name, fn_hash, since).map_err(|e| store_refusal(&format!("bind {name}"), e))?;
375 }
376 self.names
377 .lock()
378 .unwrap_or_else(|p| p.into_inner())
379 .insert(name.to_string(), Confirmed { at: Instant::now(), instant: now });
380 Ok(())
381 }
382
383 fn import_descriptor(&self, host: &str, fn_hash: &str) -> Result<(), ForeignError> {
384 if self.store.descriptor(fn_hash).is_some() {
385 return Ok(());
386 }
387 let body = self.counted(self.client.descriptor(host, fn_hash))?;
388 let h = self
389 .store
390 .put_descriptor(&body)
391 .map_err(|e| ForeignError::new(ErrorCode::FnHashMismatch, e.to_string()))?;
392 if h != fn_hash {
393 return Err(ForeignError::new(ErrorCode::FnHashMismatch, format!("{host} gave the descriptor {h}")));
394 }
395 Ok(())
396 }
397
398 fn fetch_cell(&self, cell: &Cell, asof: Option<&str>) -> Result<Fetched, ForeignError> {
401 let host = host_of(&cell.ns);
402 let reference = CellRef {
403 ns: cell.ns.clone(),
404 fn_name: cell.fn_name.clone(),
405 args: cell.args.clone(),
406 asof: asof.map(str::to_string),
407 };
408 let uri = format_uri(&reference);
409 let request = Request::new(&cell.id(), asof).map_err(|_| ForeignError::unavailable("request"))?;
410 let f = match self.counted(self.client.cell(host, &uri["cell://".len()..], &request)) {
411 Ok(f) => f,
412 Err(e) if e.code == ErrorCode::Envelope => return Err(ForeignError::unavailable(e.detail)),
413 Err(e) => return Err(e),
414 };
415 match (f.answer.outcome.as_str(), f.answer.receipt) {
416 ("ok" | "stale", Some(r)) => {
417 let bytes = datumesh_core::json::parse(&f.body)
418 .ok()
419 .and_then(|v| v.get("receipt").map(datumesh_core::json::Value::to_jcs))
420 .ok_or_else(|| ForeignError::unavailable("receipt"))?;
421 Ok(Fetched::Receipt(bytes, Box::new(r)))
422 }
423 ("not_covered", _) => Ok(Fetched::NotCovered),
424 (o, _) => Err(ForeignError::unavailable(format!("{host}: {o}"))),
425 }
426 }
427
428 fn listed_versions(&self, cell: &Cell, after_tx: Option<&str>) -> Result<Option<Vec<Version>>, ForeignError> {
431 let host = host_of(&cell.ns);
432 let mesh = self.mesh(host)?;
433 if !mesh.endpoints.contains_key("versions") {
434 return Ok(None);
435 }
436 let reference =
437 CellRef { ns: cell.ns.clone(), fn_name: cell.fn_name.clone(), args: cell.args.clone(), asof: None };
438 let uri = format_uri(&reference);
439 let mut rest = uri["cell://".len()..].to_string();
440 if let Some(t) = after_tx
441 .and_then(datumesh_formula::calendar::parse_instant)
442 .and_then(|us| datumesh_formula::calendar::instant_text(us + 1))
443 {
444 rest.push(if rest.contains('?') { '&' } else { '?' });
445 rest.push_str(&format!("from={t}"));
446 }
447 let mut page = self.counted(self.client.versions(host, &rest))?;
448 let mut out = Vec::new();
449 loop {
450 if page.cell.get("fn_hash").and_then(datumesh_core::json::Value::as_str) != Some(cell.fn_hash.as_str()) {
451 return Err(ForeignError::unavailable(format!("{host}: the versions of another function")));
452 }
453 for v in &page.versions {
454 let bytes = self.counted(self.client.receipt(host, &v.receipt))?;
455 let r = Receipt::from_json(&bytes).map_err(|e| ForeignError::new(e.code(), e.to_string()))?;
456 if r.cell().id() != cell.id() || r.tx() != v.tx {
457 return Err(ForeignError::unavailable(format!("{host}: a version of another cell")));
458 }
459 out.push((bytes, Box::new(r)));
460 if out.len() > MAX_WALK {
461 return Err(ForeignError::unavailable(format!("{host}: more than {MAX_WALK} versions")));
462 }
463 }
464 match page.next.clone() {
465 Some(n) => page = self.counted(self.client.versions_at(&n))?,
466 None => break,
467 }
468 }
469 Ok(Some(out))
470 }
471
472 pub fn ensure_cell(&self, cell: &Cell) -> Result<bool, ForeignError> {
475 let id = cell.id();
476 if let Some(c) = self.cells.lock().unwrap_or_else(|p| p.into_inner()).get(&id) {
477 if c.at.elapsed() < self.ttl_current {
478 return Ok(false);
479 }
480 }
481 let now = self.clock.now();
482 let name = cell.function_name();
483 let current = self
484 .store
485 .resolve_binding(&name, &now)
486 .map_err(|e| ForeignError::unavailable(format!("store: {e}")))?
487 .map(|b| b.fn_hash);
488 if current.as_deref() != Some(cell.fn_hash.as_str()) {
489 if self.cells.lock().unwrap_or_else(|p| p.into_inner()).contains_key(&id) {
490 return Ok(false);
492 }
493 return Err(ForeignError::unavailable(format!(
494 "{name}: a cell of an earlier binding is not resolved in 0.1.x"
495 )));
496 }
497 let local = self.store.latest(&id).map_err(|e| ForeignError::unavailable(format!("store: {e}")))?;
498 let chain: Vec<(Vec<u8>, Box<Receipt>)> =
500 match self.listed_versions(cell, local.as_ref().map(|v| v.tx.as_str()))? {
501 Some(listed) => listed,
502 None => {
503 let mut chain: Vec<(Vec<u8>, Box<Receipt>)> = Vec::new();
504 let mut at: Option<String> = None;
505 loop {
506 match self.fetch_cell(cell, at.as_deref())? {
507 Fetched::NotCovered => break,
508 Fetched::Receipt(bytes, r) => {
509 if local.as_ref().is_some_and(|v| v.receipt_hash == r.hash()) {
510 break;
511 }
512 if chain.iter().any(|(_, c)| c.hash() == r.hash()) || chain.len() >= MAX_WALK {
513 return Err(ForeignError::unavailable(format!(
514 "{name}: the other mesh's history does not end"
515 )));
516 }
517 let start = std::cmp::max(r.tx(), r.asof()).to_string();
518 let next = before(&start);
519 chain.push((bytes, r));
520 match next {
521 Some(t) => at = Some(t),
522 None => break,
523 }
524 }
525 }
526 }
527 chain.reverse();
528 chain
529 }
530 };
531 if let (Some((_, oldest)), Some(l)) = (chain.first(), &local) {
532 if oldest.tx() <= l.tx.as_str() {
533 return Err(ForeignError::unavailable(format!("{name}: the other mesh's versions do not extend ours")));
534 }
535 }
536 let added = !chain.is_empty();
537 for (bytes, r) in &chain {
538 self.ensure_namespace(r.signer_host())?;
539 let h = self.store.put_receipt(bytes).map_err(|e| store_refusal("put_receipt", e))?;
540 self.store.put_version(&id, r.tx(), &h).map_err(|e| store_refusal("put_version", e))?;
541 self.imported.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
542 }
543 if added {
544 self.invalidated.lock().unwrap_or_else(|p| p.into_inner()).push(id.clone());
545 self.dirty.store(true, std::sync::atomic::Ordering::Release);
546 }
547 self.cells.lock().unwrap_or_else(|p| p.into_inner()).insert(id, Confirmed { at: Instant::now(), instant: now });
548 self.any.store(true, std::sync::atomic::Ordering::Release);
549 Ok(added)
550 }
551
552 fn ensure_namespace(&self, host: &str) -> Result<(), ForeignError> {
555 if self.owned.iter().any(|h| h == host) {
556 return Ok(());
557 }
558 self.keys_for(host, false)?;
559 self.store_key_document(host)
560 }
561
562 pub fn ensure_publisher(&self, ns: &str) -> Result<(), ForeignError> {
569 if !self.is_foreign(ns) {
570 return Ok(());
571 }
572 let host = host_of(ns);
573 self.counted(self.client.publisher_key_document(host))?;
574 self.store_key_document(host)
575 }
576
577 fn store_key_document(&self, host: &str) -> Result<(), ForeignError> {
579 let bytes = self
580 .client
581 .key_document_bytes(host)
582 .ok_or_else(|| ForeignError::new(ErrorCode::KeyUnavailable, host.to_string()))?;
583 let stored = self.store.namespace(host).map_err(|e| ForeignError::unavailable(format!("store: {e}")))?;
584 if stored.as_ref().map(|n| n.keydoc.as_slice()) != Some(bytes.as_slice()) {
585 self.store
586 .put_namespace(host, &bytes, &self.clock.now())
587 .map_err(|e| ForeignError::new(ErrorCode::KeyDoc, format!("put_namespace {host}: {e}")))?;
588 }
589 Ok(())
590 }
591
592 pub(crate) fn set_engine(&self, engine: std::sync::Weak<datumesh_engine::Engine>) {
596 let _ = self.engine.set(engine);
597 }
598
599 fn foreign_deps(&self, receipt_hash: &str, metrics: Option<&crate::metrics::Metrics>) -> Arc<Vec<Cell>> {
600 if let Some(d) = self.deps.lock().unwrap_or_else(|p| p.into_inner()).get(receipt_hash) {
601 return d.clone();
602 }
603 let mut out = Vec::new();
604 let mut seen = HashSet::new();
605 let mut todo: Vec<(String, Option<String>)> = vec![(receipt_hash.to_string(), None)];
607 let deadline = Instant::now() + self.budget;
608 let engine = self.engine.get().and_then(std::sync::Weak::upgrade);
609 while let Some((h, citing)) = todo.pop() {
610 if !seen.insert(h.clone()) || seen.len() > 100_000 {
611 continue;
612 }
613 if h.starts_with("slice:") {
614 if let Some(e) = &engine {
615 let m = crate::manifest_route::members_for_reader(
616 &*self.store,
617 e,
618 metrics,
619 &h,
620 citing.as_deref(),
621 deadline,
622 );
623 if let Some(m) = m {
624 todo.extend(m.members().iter().map(|x| (x.clone(), citing.clone())));
625 }
626 }
627 continue;
628 }
629 let Some(bytes) = self.store.receipt(&h) else {
630 continue;
631 };
632 let Ok(r) = Receipt::from_json(&bytes) else { continue };
633 if self.is_foreign(&r.cell().ns) && r.inputs().is_empty() {
634 out.push(r.cell().clone());
635 } else {
636 let asof = Some(r.asof().to_string());
637 todo.extend(r.inputs().iter().map(|x| (x.clone(), asof.clone())));
638 }
639 }
640 let d = Arc::new(out);
641 let mut deps = self.deps.lock().unwrap_or_else(|p| p.into_inner());
642 if deps.len() > 100_000 {
643 deps.clear();
644 }
645 deps.insert(receipt_hash.to_string(), d.clone());
646 d
647 }
648
649 pub fn refresh_deps(&self, receipt_hash: &str, asof: &str) -> Result<bool, ForeignError> {
653 self.refresh_deps_counted(receipt_hash, asof, None)
654 }
655
656 pub(crate) fn refresh_deps_counted(
658 &self,
659 receipt_hash: &str,
660 asof: &str,
661 metrics: Option<&crate::metrics::Metrics>,
662 ) -> Result<bool, ForeignError> {
663 if !self.any_cells() {
664 return Ok(false);
665 }
666 let mut added = false;
667 for cell in self.foreign_deps(receipt_hash, metrics).iter() {
668 let stale = match self.cells.lock().unwrap_or_else(|p| p.into_inner()).get(&cell.id()) {
669 Some(c) => c.at.elapsed() >= self.ttl_current && asof > c.instant.as_str(),
670 None => true,
671 };
672 if stale {
673 added |= self.ensure_cell(cell)?;
674 }
675 }
676 Ok(added)
677 }
678
679 pub fn prepare(&self, cell: &Cell, stored: bool, asof: Option<&str>) -> Result<(), ForeignError> {
682 if !self.is_foreign(&cell.function_name()) || !stored {
683 return Ok(());
684 }
685 let fresh = match self.cells.lock().unwrap_or_else(|p| p.into_inner()).get(&cell.id()) {
686 Some(c) => c.at.elapsed() < self.ttl_current || asof.is_some_and(|a| a <= c.instant.as_str()),
687 None => false,
688 };
689 if !fresh {
690 self.ensure_cell(cell)?;
691 }
692 Ok(())
693 }
694}
695
696pub struct CrossMesh {
698 inner: Arc<dyn Runtime>,
699 foreign: Arc<Foreign>,
700}
701
702impl CrossMesh {
703 pub fn new(inner: Arc<dyn Runtime>, foreign: Arc<Foreign>) -> CrossMesh {
705 CrossMesh { inner, foreign }
706 }
707}
708
709impl Runtime for CrossMesh {
710 fn lang(&self) -> &str {
711 self.inner.lang()
712 }
713
714 fn evaluate(
715 &self,
716 descriptor: &FunctionDescriptor,
717 cell: &Cell,
718 inputs: &mut dyn Inputs,
719 budget: &mut Budget,
720 ) -> Result<Scalar, EvalError> {
721 self.foreign.ensure_publisher(&cell.ns).map_err(ForeignError::eval)?;
723 for name in &descriptor.inputs {
724 self.foreign.ensure_name(name).map_err(ForeignError::eval)?;
725 }
726 let mut w = Through { inner: inputs, foreign: &self.foreign };
727 self.inner.evaluate(descriptor, cell, &mut w, budget)
728 }
729
730 fn asof_dependent(&self, descriptor: &FunctionDescriptor) -> bool {
731 self.inner.asof_dependent(descriptor)
732 }
733}
734
735struct Through<'a> {
737 inner: &'a mut dyn Inputs,
738 foreign: &'a Foreign,
739}
740
741impl Through<'_> {
742 fn pre(&mut self, name: &str, args: &Args, at: Option<&str>) -> Result<(), EvalError> {
743 if !self.foreign.is_foreign(name) {
744 return Ok(());
745 }
746 self.foreign.ensure_name(name).map_err(ForeignError::eval)?;
747 let Some(b) = self.inner.binding_peek(name, at)? else {
748 return Ok(());
749 };
750 if b.descriptor.lang != "stored" {
751 return Ok(());
752 }
753 let (ns, f) = name.rsplit_once('/').unwrap_or((name, ""));
754 let cell = Cell { ns: ns.to_string(), fn_name: f.to_string(), fn_hash: b.fn_hash.clone(), args: args.clone() };
755 self.foreign.ensure_cell(&cell).map_err(ForeignError::eval)?;
756 Ok(())
757 }
758}
759
760impl Inputs for Through<'_> {
761 fn read(&mut self, fn_name: &str, args: &Args) -> Result<Scalar, EvalError> {
762 self.pre(fn_name, args, None)?;
763 self.inner.read(fn_name, args)
764 }
765
766 fn read_cell(&mut self, fn_name: &str, args: &Args) -> Result<Input, EvalError> {
767 self.pre(fn_name, args, None)?;
768 self.inner.read_cell(fn_name, args)
769 }
770
771 fn read_asof(&mut self, fn_name: &str, args: &Args, t: &str) -> Result<Input, EvalError> {
772 self.pre(fn_name, args, Some(t))?;
773 self.inner.read_asof(fn_name, args, t)
774 }
775
776 fn read_slice(&mut self, fn_name: &str, pattern: &SlicePattern) -> Result<Vec<Member>, EvalError> {
777 if self.foreign.is_foreign(fn_name) {
778 self.foreign.ensure_name(fn_name).map_err(ForeignError::eval)?;
779 if let Some(b) = self.inner.binding_peek(fn_name, None)? {
780 if b.descriptor.lang == "stored" {
781 return Err(ForeignError::unavailable(format!(
782 "{fn_name}: slices of foreign stored functions are not read in 0.1.0"
783 ))
784 .eval());
785 }
786 }
787 }
788 self.inner.read_slice(fn_name, pattern)
789 }
790
791 fn read_versions(&mut self, fn_name: &str, args: &Args, from: &str, to: &str) -> Result<Vec<Input>, EvalError> {
792 self.pre(fn_name, args, None)?;
793 self.inner.read_versions(fn_name, args, from, to)
794 }
795
796 fn read_pinned(&mut self, fn_name: &str, fn_hash: &str, args: &Args) -> Result<Input, EvalError> {
797 self.inner.read_pinned(fn_name, fn_hash, args)
800 }
801
802 fn binding(&mut self, fn_name: &str, at: Option<&str>) -> Result<Option<FnBinding>, EvalError> {
803 self.foreign.ensure_name(fn_name).map_err(ForeignError::eval)?;
804 self.inner.binding(fn_name, at)
805 }
806
807 fn asof(&mut self) -> String {
808 self.inner.asof()
809 }
810
811 fn binding_peek(&mut self, fn_name: &str, at: Option<&str>) -> Result<Option<FnBinding>, EvalError> {
812 self.foreign.ensure_name(fn_name).map_err(ForeignError::eval)?;
813 self.inner.binding_peek(fn_name, at)
814 }
815
816 fn asof_compare(&mut self, t: &str) -> Result<std::cmp::Ordering, EvalError> {
817 self.inner.asof_compare(t)
818 }
819
820 fn read_blob(&mut self, sha256: &str, length: u64) -> Result<Vec<u8>, EvalError> {
821 self.inner.read_blob(sha256, length)
822 }
823}