1use std::borrow::Cow;
4use std::collections::{BTreeSet, HashMap};
5use std::fmt;
6use std::path::PathBuf;
7use std::sync::{Arc, Mutex, RwLock};
8
9use datumesh_core::{
10 lexical, Cell, CellRef, Evaluation, Fault, FunctionDescriptor, KeyDoc, Resolver, Scalar, SigningKey,
11};
12use datumesh_store::Store;
13
14use crate::cache::{Cache, Parsed};
15use crate::check::{check_args, check_no_slice};
16use crate::clock::{Clock, SystemClock};
17use crate::error::{ConfigError, EngineError, EvalError, StoreError};
18use crate::eval::{is_instant, parse_stored, Done, Req, Use};
19use crate::memo::Memo;
20use crate::runtime::Runtime;
21
22pub const DEFAULT_DEPTH_LIMIT: usize = 10_000;
24pub const DEFAULT_FUEL: u64 = 10_000_000;
26pub const DEFAULT_WORK_FACTOR: u64 = 16;
28pub const DEFAULT_MEMO_CAPACITY: usize = 1_000_000;
30
31#[non_exhaustive]
33#[derive(Clone, Debug, PartialEq, Eq)]
34pub enum Answer {
35 Receipt(Vec<u8>),
38 NotCovered {
45 fault: Option<Fault>,
47 },
48 Withdrawn {
54 receipt: Vec<u8>,
56 reason: String,
58 },
59}
60
61impl Answer {
62 pub const NOT_COVERED: Answer = Answer::NotCovered { fault: None };
64}
65
66pub type SummaryFn = dyn Fn(&Cell) -> String + Send + Sync;
68
69pub struct EngineBuilder {
71 pub(crate) store: Arc<dyn Store + Send + Sync>,
72 pub(crate) host: String,
73 pub(crate) key: Option<SigningKey>,
74 pub(crate) key_file: Option<PathBuf>,
75 pub(crate) runtimes: Vec<Arc<dyn Runtime>>,
76 pub(crate) depth_limit: usize,
77 pub(crate) fuel: u64,
78 pub(crate) work_limit: Option<u64>,
79 pub(crate) memo_capacity: usize,
80 pub(crate) licence: String,
81 pub(crate) summary: Option<Arc<SummaryFn>>,
82 pub(crate) clock: Arc<dyn Clock>,
83 pub(crate) accepted: BTreeSet<String>,
84}
85
86impl EngineBuilder {
87 pub fn signing_key(mut self, key: SigningKey) -> Self {
89 self.key = Some(key);
90 self.key_file = None;
91 self
92 }
93
94 pub fn signing_key_file(mut self, path: impl Into<PathBuf>) -> Self {
97 self.key_file = Some(path.into());
98 self.key = None;
99 self
100 }
101
102 pub fn runtime(mut self, runtime: Arc<dyn Runtime>) -> Self {
104 self.runtimes.push(runtime);
105 self
106 }
107
108 pub fn depth_limit(mut self, limit: usize) -> Self {
110 self.depth_limit = limit;
111 self
112 }
113
114 pub fn fuel(mut self, fuel: u64) -> Self {
116 self.fuel = fuel;
117 self
118 }
119
120 pub fn work_limit(mut self, units: u64) -> Self {
125 self.work_limit = Some(units);
126 self
127 }
128
129 pub fn memo_capacity(mut self, entries: usize) -> Self {
132 self.memo_capacity = entries;
133 self
134 }
135
136 pub fn licence(mut self, licence: impl Into<String>) -> Self {
142 self.licence = licence.into();
143 self
144 }
145
146 pub fn summary(mut self, f: impl Fn(&Cell) -> String + Send + Sync + 'static) -> Self {
149 self.summary = Some(Arc::new(f));
150 self
151 }
152
153 pub fn clock(mut self, clock: Arc<dyn Clock>) -> Self {
155 self.clock = clock;
156 self
157 }
158
159 pub fn accepted_licences(mut self, licences: impl IntoIterator<Item = String>) -> Self {
165 self.accepted = licences.into_iter().collect();
166 self
167 }
168
169 pub fn build(self) -> Result<Engine, ConfigError> {
171 lexical::check_dns_name(&self.host, "$.host").map_err(ConfigError::Host)?;
172 let key = match (self.key, &self.key_file) {
173 (Some(k), _) => k,
174 (None, Some(path)) => read_seed(path)?,
175 (None, None) => return Err(ConfigError::NoSigningKey),
176 };
177 lexical::check_licence(&self.licence, "$.licence").map_err(ConfigError::Licence)?;
178 let mut runtimes: HashMap<String, Arc<dyn Runtime>> = HashMap::new();
179 for rt in self.runtimes {
180 let lang = rt.lang().to_string();
181 if lang == STORED {
182 return Err(ConfigError::Runtime("stored is answered by the engine, not a runtime".into()));
183 }
184 if runtimes.insert(lang.clone(), rt).is_some() {
185 return Err(ConfigError::Runtime(format!("two runtimes for {lang}")));
186 }
187 }
188 let published = match self.store.namespace(&self.host) {
189 Ok(Some(ns)) => KeyDoc::from_json(&self.host, &ns.keydoc)
190 .ok()
191 .and_then(|doc| doc.key(key.key_id()).map(|k| k.public == key.public_key()))
192 .unwrap_or(false),
193 Ok(None) => false,
194 Err(e) => return Err(ConfigError::Store(StoreError::new("namespace", e))),
195 };
196 if !published {
197 return Err(ConfigError::KeyNotPublished { host: self.host, key_id: key.key_id().to_string() });
198 }
199 Ok(Engine {
200 store: self.store,
201 host: self.host,
202 key,
203 runtimes,
204 depth_limit: self.depth_limit,
205 fuel: self.fuel,
206 work_limit: self.work_limit.unwrap_or(self.fuel.saturating_mul(DEFAULT_WORK_FACTOR)),
207 licence: self.licence,
208 summary: self.summary,
209 clock: self.clock,
210 accepted: RwLock::new(self.accepted),
211 memo: Memo::new(self.memo_capacity),
212 descriptors: Cache::new(DESCRIPTOR_CACHE),
213 receipts: Cache::new(RECEIPT_CACHE),
214 asof_dependent: Cache::new(DESCRIPTOR_CACHE),
215 evaluator: Mutex::new(()),
216 })
217 }
218}
219
220impl fmt::Debug for EngineBuilder {
221 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
222 f.debug_struct("EngineBuilder").field("host", &self.host).finish_non_exhaustive()
223 }
224}
225
226pub struct Engine {
228 pub(crate) store: Arc<dyn Store + Send + Sync>,
229 pub(crate) host: String,
230 pub(crate) key: SigningKey,
231 pub(crate) runtimes: HashMap<String, Arc<dyn Runtime>>,
232 pub(crate) depth_limit: usize,
233 pub(crate) fuel: u64,
234 pub(crate) work_limit: u64,
235 pub(crate) licence: String,
236 pub(crate) summary: Option<Arc<SummaryFn>>,
237 pub(crate) clock: Arc<dyn Clock>,
238 pub(crate) accepted: RwLock<BTreeSet<String>>,
241 pub(crate) memo: Memo,
242 pub(crate) descriptors: Cache<Arc<FunctionDescriptor>>,
244 pub(crate) receipts: Cache<Arc<Parsed>>,
246 pub(crate) asof_dependent: Cache<bool>,
249 pub(crate) evaluator: Mutex<()>,
251}
252
253pub(crate) const STORED: &str = "stored";
255const DESCRIPTOR_CACHE: usize = 10_000;
256const RECEIPT_CACHE: usize = 100_000;
257
258fn read_seed(path: &std::path::Path) -> Result<SigningKey, ConfigError> {
260 let bytes = std::fs::read(path).map_err(|e| ConfigError::KeyFile(format!("{}: {e}", path.display())))?;
261 if let Ok(seed) = <[u8; 32]>::try_from(bytes.as_slice()) {
262 return Ok(SigningKey::from_seed(&seed));
263 }
264 let text = bytes.strip_suffix(b"\n").unwrap_or(&bytes);
265 let hex = |c: u8| match c {
266 b'0'..=b'9' => Some(c - b'0'),
267 b'a'..=b'f' => Some(c - b'a' + 10),
268 _ => None,
269 };
270 if text.len() == 64 {
271 let mut seed = [0u8; 32];
272 let mut ok = true;
273 for (i, pair) in text.chunks(2).enumerate() {
274 match (hex(pair[0]), hex(pair[1])) {
275 (Some(h), Some(l)) => seed[i] = h << 4 | l,
276 _ => ok = false,
277 }
278 }
279 if ok {
280 return Ok(SigningKey::from_seed(&seed));
281 }
282 }
283 Err(ConfigError::KeyFile(format!("{}: not a seed (32 bytes, or 64 lowercase hex digits)", path.display())))
284}
285
286impl fmt::Debug for Engine {
287 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
288 f.debug_struct("Engine").finish_non_exhaustive()
289 }
290}
291
292#[non_exhaustive]
294#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
295pub struct MemoStats {
296 pub entries: usize,
298 pub cells: usize,
300 pub dependent_edges: usize,
302 pub dirty: usize,
304 pub stale: usize,
307 pub slice_patterns: usize,
310 pub approx_bytes: usize,
312}
313
314impl Engine {
315 pub fn builder(store: Arc<dyn Store + Send + Sync>, host: impl Into<String>) -> EngineBuilder {
317 EngineBuilder {
318 store,
319 host: host.into(),
320 key: None,
321 key_file: None,
322 runtimes: Vec::new(),
323 depth_limit: DEFAULT_DEPTH_LIMIT,
324 fuel: DEFAULT_FUEL,
325 work_limit: None,
326 memo_capacity: DEFAULT_MEMO_CAPACITY,
327 licence: "CC-BY-4.0".into(),
328 summary: None,
329 clock: Arc::new(SystemClock),
330 accepted: BTreeSet::new(),
331 }
332 }
333
334 pub fn set_accepted_licences(&self, licences: BTreeSet<String>) {
341 let _evaluating = self.evaluator.lock().unwrap_or_else(|p| p.into_inner());
342 let mut accepted = self.accepted.write().unwrap_or_else(|p| p.into_inner());
343 if *accepted != licences {
344 *accepted = licences;
345 self.memo.clear();
346 }
347 }
348
349 pub fn get(&self, cell: &CellRef, asof: Option<&str>) -> Result<Answer, EngineError> {
354 let now = self.clock.now();
355 let a = asof.or(cell.asof.as_deref()).unwrap_or(&now).to_string();
356 lexical::check_instant(&a, "$.asof").map_err(EngineError::Invalid)?;
357 check_no_slice(&cell.args)?;
358 let fn_name = format!("{}/{}", cell.ns, cell.fn_name);
359 let Some(fn_hash) = self.store.resolve_name(&fn_name, &a).map_err(|e| StoreError::new("resolve_name", e))?
360 else {
361 return Ok(Answer::NOT_COVERED);
362 };
363 let resolved = cell.resolve(&fn_hash).map_err(EngineError::Invalid)?;
364 self.answer(&resolved, &a, &now)
365 }
366
367 pub fn resolve(&self, cell: &CellRef, asof: Option<&str>) -> Result<Option<Cell>, EngineError> {
373 let now;
374 let a = match asof.or(cell.asof.as_deref()) {
375 Some(a) => a,
376 None => {
377 now = self.clock.now();
378 &now
379 }
380 };
381 lexical::check_instant(a, "$.asof").map_err(EngineError::Invalid)?;
382 check_no_slice(&cell.args)?;
383 let fn_name = format!("{}/{}", cell.ns, cell.fn_name);
384 let Some(fn_hash) = self.store.resolve_name(&fn_name, a).map_err(|e| StoreError::new("resolve_name", e))?
385 else {
386 return Ok(None);
387 };
388 cell.resolve(&fn_hash).map(Some).map_err(EngineError::Invalid)
389 }
390
391 pub fn get_cell(&self, cell: &Cell, asof: Option<&str>) -> Result<Answer, EngineError> {
395 let now = self.clock.now();
396 let a = asof.unwrap_or(&now).to_string();
397 lexical::check_instant(&a, "$.asof").map_err(EngineError::Invalid)?;
398 check_no_slice(&cell.args)?;
399 self.answer(cell, &a, &now)
400 }
401
402 fn answer(&self, cell: &Cell, a: &str, now: &str) -> Result<Answer, EngineError> {
404 let Some(desc) = self.descriptor_of(&cell.fn_hash)? else {
405 return Ok(Answer::NOT_COVERED);
406 };
407 check_args(cell, &desc).map_err(EngineError::Invalid)?;
408 let id = cell.id();
409 let store_err = |e: EvalError| match e {
410 EvalError::Store(e) => e.into(),
411 other => EngineError::Runtime { cell_id: id.clone(), message: other.to_string() },
412 };
413 let done = match Req::new(self, a, now).memo_done(&id, a).map_err(store_err)? {
415 Some(d) => d,
416 None if desc.lang == STORED => {
417 let start = self.memo.begin();
418 let mut req = Req::new(self, a, now);
419 match req.stored(cell, &id, a) {
420 Ok(d) => {
421 self.memo.end(start, &req.learned);
422 d
423 }
424 Err(e) => {
425 self.memo.abort(start);
426 return Err(store_err(e));
427 }
428 }
429 }
430 None => {
431 let _single = self.evaluator.lock().unwrap_or_else(|p| p.into_inner());
432 self.evaluate_cell(cell, desc, a, now, false)?
433 }
434 };
435 Ok(match done {
436 Done::Value(ans) => Answer::Receipt(ans.bytes.to_vec()),
437 Done::Fault(fa) => Answer::NotCovered { fault: Some(fa.fault) },
438 Done::Withdrawn(w) => Answer::Withdrawn { receipt: w.bytes.to_vec(), reason: w.reason.clone() },
439 Done::NotCovered | Done::Unsigned(..) => Answer::NOT_COVERED,
440 })
441 }
442
443 fn evaluate_cell(
447 &self,
448 cell: &Cell,
449 desc: Arc<FunctionDescriptor>,
450 a: &str,
451 now: &str,
452 unsigned: bool,
453 ) -> Result<Done, EngineError> {
454 let start = self.memo.begin();
455 let mut req = Req::new(self, a, now);
456 let result = (|| {
457 if !unsigned {
458 if let Some(done) =
459 req.memo_done(&cell.id(), &req.asof()).map_err(|e| crate::eval::engine_error(e, &cell.id()))?
460 {
461 return Ok(done);
462 }
463 }
464 let done = req.run(cell.clone(), desc, unsigned)?;
465 req.flush()?;
466 Ok(done)
467 })();
468 match &result {
469 Ok(_) => self.memo.end(start, &req.learned),
470 Err(_) => self.memo.abort(start),
471 }
472 result
473 }
474
475 pub(crate) fn parsed(&self, hash: &str, bytes: &[u8]) -> Result<Arc<Parsed>, StoreError> {
477 if let Some(p) = self.receipts.get(hash) {
478 return Ok(p);
479 }
480 let p = Arc::new(parse_stored(hash, bytes)?);
481 self.receipts.insert(hash.to_string(), p.clone());
482 Ok(p)
483 }
484
485 fn evaluate_value(&self, cell: &Cell, asof: &str) -> Result<Option<Evaluation>, EngineError> {
488 if !is_instant(asof) || cell.is_slice() {
489 return Ok(None);
490 }
491 let Some(desc) = self.descriptor_of(&cell.fn_hash)? else { return Ok(None) };
492 if check_args(cell, &desc).is_err() {
493 return Ok(None);
494 }
495 let now = self.clock.now();
496 let done = if desc.lang == STORED {
497 Req::new(self, asof, &now)
498 .stored(cell, &cell.id(), asof)
499 .map_err(|e| EngineError::Runtime { cell_id: cell.id(), message: e.to_string() })?
500 } else {
501 let _single = self.evaluator.lock().unwrap_or_else(|p| p.into_inner());
502 let suspended = self.store.namespace(&self.host).map_err(|e| StoreError::new("namespace", e))?;
506 if suspended.is_some_and(|n| n.suspended_at.is_some()) {
507 match self.evaluate_cell(cell, desc, asof, &now, false)? {
508 Done::Value(ans) => {
509 let lineage: BTreeSet<String> = ans
510 .inputs
511 .iter()
512 .map(|u| match u {
513 Use::Cell { hash, .. } => hash.clone(),
514 Use::Slice(s) => s.entry.clone(),
515 })
516 .collect();
517 return Ok(Some(Evaluation::with_lineage(ans.value.clone(), lineage.into_iter().collect())));
518 }
519 _ => return Ok(None),
520 }
521 }
522 self.evaluate_cell(cell, desc, asof, &now, true)?
523 };
524 Ok(match done {
525 Done::Value(ans) => Some(Evaluation::new(ans.value.clone())),
526 Done::Unsigned(v, lineage) => Some(Evaluation::with_lineage(v, lineage)),
527 Done::NotCovered | Done::Fault(_) | Done::Withdrawn(_) => None,
528 })
529 }
530
531 pub(crate) fn asof_dependent(&self, fn_hash: &str, desc: &FunctionDescriptor) -> bool {
534 if let Some(b) = self.asof_dependent.get(fn_hash) {
535 return b;
536 }
537 let b = self.runtimes.get(&desc.lang).is_some_and(|rt| rt.asof_dependent(desc));
538 self.asof_dependent.insert(fn_hash.to_string(), b);
539 b
540 }
541
542 pub(crate) fn descriptor_of(&self, fn_hash: &str) -> Result<Option<Arc<FunctionDescriptor>>, EngineError> {
544 if let Some(d) = self.descriptors.get(fn_hash) {
545 return Ok(Some(d));
546 }
547 let Some(bytes) = self.store.descriptor(fn_hash) else { return Ok(None) };
548 let d = Arc::new(FunctionDescriptor::from_json(&bytes).map_err(EngineError::Invalid)?);
549 self.descriptors.insert(fn_hash.to_string(), d.clone());
550 Ok(Some(d))
551 }
552
553 pub fn stored_version_added(&self, cell_id: &str) {
562 let receipt = if self.memo.wants_receipts() {
563 self.store
564 .latest(cell_id)
565 .ok()
566 .flatten()
567 .filter(|v| !v.withdrawn)
570 .and_then(|v| self.store.receipt(&v.receipt_hash).map(|b| b.into_owned()))
571 .and_then(|b| datumesh_core::Receipt::from_json(&b).ok())
572 .map(Arc::new)
573 } else {
574 None
575 };
576 self.memo.invalidate(cell_id, receipt);
577 }
578
579 pub fn clear_memo(&self) {
581 self.memo.clear();
582 }
583
584 pub fn memo_stats(&self) -> MemoStats {
586 self.memo.stats()
587 }
588}
589
590impl Resolver for Engine {
591 fn descriptor(&self, fn_hash: &str) -> Option<Cow<'_, [u8]>> {
592 self.store.descriptor(fn_hash)
593 }
594
595 fn receipt(&self, hash: &str) -> Option<Cow<'_, [u8]>> {
596 self.store.receipt(hash)
597 }
598
599 fn manifest(&self, entry: &str) -> Option<Cow<'_, [u8]>> {
602 self.store.manifest(entry)
603 }
604
605 fn evaluate(&self, cell: &Cell, asof: &str) -> Option<Scalar> {
611 self.evaluation(cell, asof).map(|e| e.value)
612 }
613
614 fn evaluation(&self, cell: &Cell, asof: &str) -> Option<Evaluation> {
619 match self.evaluate_value(cell, asof) {
620 Ok(v) => v,
621 Err(e) => {
622 tracing::debug!(target: "datumesh_engine", cell_id = %cell.id(), asof, error = %e, "evaluate failed");
623 None
624 }
625 }
626 }
627}