1use std::borrow::Cow;
4use std::collections::{BTreeSet, HashMap};
5use std::fmt;
6use std::path::PathBuf;
7use std::sync::{Arc, Mutex};
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}
84
85impl EngineBuilder {
86 pub fn signing_key(mut self, key: SigningKey) -> Self {
88 self.key = Some(key);
89 self.key_file = None;
90 self
91 }
92
93 pub fn signing_key_file(mut self, path: impl Into<PathBuf>) -> Self {
96 self.key_file = Some(path.into());
97 self.key = None;
98 self
99 }
100
101 pub fn runtime(mut self, runtime: Arc<dyn Runtime>) -> Self {
103 self.runtimes.push(runtime);
104 self
105 }
106
107 pub fn depth_limit(mut self, limit: usize) -> Self {
109 self.depth_limit = limit;
110 self
111 }
112
113 pub fn fuel(mut self, fuel: u64) -> Self {
115 self.fuel = fuel;
116 self
117 }
118
119 pub fn work_limit(mut self, units: u64) -> Self {
124 self.work_limit = Some(units);
125 self
126 }
127
128 pub fn memo_capacity(mut self, entries: usize) -> Self {
131 self.memo_capacity = entries;
132 self
133 }
134
135 pub fn licence(mut self, licence: impl Into<String>) -> Self {
141 self.licence = licence.into();
142 self
143 }
144
145 pub fn summary(mut self, f: impl Fn(&Cell) -> String + Send + Sync + 'static) -> Self {
148 self.summary = Some(Arc::new(f));
149 self
150 }
151
152 pub fn clock(mut self, clock: Arc<dyn Clock>) -> Self {
154 self.clock = clock;
155 self
156 }
157
158 pub fn build(self) -> Result<Engine, ConfigError> {
160 lexical::check_dns_name(&self.host, "$.host").map_err(ConfigError::Host)?;
161 let key = match (self.key, &self.key_file) {
162 (Some(k), _) => k,
163 (None, Some(path)) => read_seed(path)?,
164 (None, None) => return Err(ConfigError::NoSigningKey),
165 };
166 lexical::check_licence(&self.licence, "$.licence").map_err(ConfigError::Licence)?;
167 let mut runtimes: HashMap<String, Arc<dyn Runtime>> = HashMap::new();
168 for rt in self.runtimes {
169 let lang = rt.lang().to_string();
170 if lang == STORED {
171 return Err(ConfigError::Runtime("stored is answered by the engine, not a runtime".into()));
172 }
173 if runtimes.insert(lang.clone(), rt).is_some() {
174 return Err(ConfigError::Runtime(format!("two runtimes for {lang}")));
175 }
176 }
177 let published = match self.store.namespace(&self.host) {
178 Ok(Some(ns)) => KeyDoc::from_json(&self.host, &ns.keydoc)
179 .ok()
180 .and_then(|doc| doc.key(key.key_id()).map(|k| k.public == key.public_key()))
181 .unwrap_or(false),
182 Ok(None) => false,
183 Err(e) => return Err(ConfigError::Store(StoreError::new("namespace", e))),
184 };
185 if !published {
186 return Err(ConfigError::KeyNotPublished { host: self.host, key_id: key.key_id().to_string() });
187 }
188 Ok(Engine {
189 store: self.store,
190 host: self.host,
191 key,
192 runtimes,
193 depth_limit: self.depth_limit,
194 fuel: self.fuel,
195 work_limit: self.work_limit.unwrap_or(self.fuel.saturating_mul(DEFAULT_WORK_FACTOR)),
196 licence: self.licence,
197 summary: self.summary,
198 clock: self.clock,
199 memo: Memo::new(self.memo_capacity),
200 descriptors: Cache::new(DESCRIPTOR_CACHE),
201 receipts: Cache::new(RECEIPT_CACHE),
202 asof_dependent: Cache::new(DESCRIPTOR_CACHE),
203 evaluator: Mutex::new(()),
204 })
205 }
206}
207
208impl fmt::Debug for EngineBuilder {
209 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
210 f.debug_struct("EngineBuilder").field("host", &self.host).finish_non_exhaustive()
211 }
212}
213
214pub struct Engine {
216 pub(crate) store: Arc<dyn Store + Send + Sync>,
217 pub(crate) host: String,
218 pub(crate) key: SigningKey,
219 pub(crate) runtimes: HashMap<String, Arc<dyn Runtime>>,
220 pub(crate) depth_limit: usize,
221 pub(crate) fuel: u64,
222 pub(crate) work_limit: u64,
223 pub(crate) licence: String,
224 pub(crate) summary: Option<Arc<SummaryFn>>,
225 pub(crate) clock: Arc<dyn Clock>,
226 pub(crate) memo: Memo,
227 pub(crate) descriptors: Cache<Arc<FunctionDescriptor>>,
229 pub(crate) receipts: Cache<Arc<Parsed>>,
231 pub(crate) asof_dependent: Cache<bool>,
234 pub(crate) evaluator: Mutex<()>,
236}
237
238pub(crate) const STORED: &str = "stored";
240const DESCRIPTOR_CACHE: usize = 10_000;
241const RECEIPT_CACHE: usize = 100_000;
242
243fn read_seed(path: &std::path::Path) -> Result<SigningKey, ConfigError> {
245 let bytes = std::fs::read(path).map_err(|e| ConfigError::KeyFile(format!("{}: {e}", path.display())))?;
246 if let Ok(seed) = <[u8; 32]>::try_from(bytes.as_slice()) {
247 return Ok(SigningKey::from_seed(&seed));
248 }
249 let text = bytes.strip_suffix(b"\n").unwrap_or(&bytes);
250 let hex = |c: u8| match c {
251 b'0'..=b'9' => Some(c - b'0'),
252 b'a'..=b'f' => Some(c - b'a' + 10),
253 _ => None,
254 };
255 if text.len() == 64 {
256 let mut seed = [0u8; 32];
257 let mut ok = true;
258 for (i, pair) in text.chunks(2).enumerate() {
259 match (hex(pair[0]), hex(pair[1])) {
260 (Some(h), Some(l)) => seed[i] = h << 4 | l,
261 _ => ok = false,
262 }
263 }
264 if ok {
265 return Ok(SigningKey::from_seed(&seed));
266 }
267 }
268 Err(ConfigError::KeyFile(format!("{}: not a seed (32 bytes, or 64 lowercase hex digits)", path.display())))
269}
270
271impl fmt::Debug for Engine {
272 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
273 f.debug_struct("Engine").finish_non_exhaustive()
274 }
275}
276
277#[non_exhaustive]
279#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
280pub struct MemoStats {
281 pub entries: usize,
283 pub cells: usize,
285 pub dependent_edges: usize,
287 pub dirty: usize,
289 pub stale: usize,
292 pub slice_patterns: usize,
295 pub approx_bytes: usize,
297}
298
299impl Engine {
300 pub fn builder(store: Arc<dyn Store + Send + Sync>, host: impl Into<String>) -> EngineBuilder {
302 EngineBuilder {
303 store,
304 host: host.into(),
305 key: None,
306 key_file: None,
307 runtimes: Vec::new(),
308 depth_limit: DEFAULT_DEPTH_LIMIT,
309 fuel: DEFAULT_FUEL,
310 work_limit: None,
311 memo_capacity: DEFAULT_MEMO_CAPACITY,
312 licence: "CC-BY-4.0".into(),
313 summary: None,
314 clock: Arc::new(SystemClock),
315 }
316 }
317
318 pub fn get(&self, cell: &CellRef, asof: Option<&str>) -> Result<Answer, EngineError> {
323 let now = self.clock.now();
324 let a = asof.or(cell.asof.as_deref()).unwrap_or(&now).to_string();
325 lexical::check_instant(&a, "$.asof").map_err(EngineError::Invalid)?;
326 check_no_slice(&cell.args)?;
327 let fn_name = format!("{}/{}", cell.ns, cell.fn_name);
328 let Some(fn_hash) = self.store.resolve_name(&fn_name, &a).map_err(|e| StoreError::new("resolve_name", e))?
329 else {
330 return Ok(Answer::NOT_COVERED);
331 };
332 let resolved = cell.resolve(&fn_hash).map_err(EngineError::Invalid)?;
333 self.answer(&resolved, &a, &now)
334 }
335
336 pub fn resolve(&self, cell: &CellRef, asof: Option<&str>) -> Result<Option<Cell>, EngineError> {
342 let now;
343 let a = match asof.or(cell.asof.as_deref()) {
344 Some(a) => a,
345 None => {
346 now = self.clock.now();
347 &now
348 }
349 };
350 lexical::check_instant(a, "$.asof").map_err(EngineError::Invalid)?;
351 check_no_slice(&cell.args)?;
352 let fn_name = format!("{}/{}", cell.ns, cell.fn_name);
353 let Some(fn_hash) = self.store.resolve_name(&fn_name, a).map_err(|e| StoreError::new("resolve_name", e))?
354 else {
355 return Ok(None);
356 };
357 cell.resolve(&fn_hash).map(Some).map_err(EngineError::Invalid)
358 }
359
360 pub fn get_cell(&self, cell: &Cell, asof: Option<&str>) -> Result<Answer, EngineError> {
364 let now = self.clock.now();
365 let a = asof.unwrap_or(&now).to_string();
366 lexical::check_instant(&a, "$.asof").map_err(EngineError::Invalid)?;
367 check_no_slice(&cell.args)?;
368 self.answer(cell, &a, &now)
369 }
370
371 fn answer(&self, cell: &Cell, a: &str, now: &str) -> Result<Answer, EngineError> {
373 let Some(desc) = self.descriptor_of(&cell.fn_hash)? else {
374 return Ok(Answer::NOT_COVERED);
375 };
376 check_args(cell, &desc).map_err(EngineError::Invalid)?;
377 let id = cell.id();
378 let store_err = |e: EvalError| match e {
379 EvalError::Store(e) => e.into(),
380 other => EngineError::Runtime { cell_id: id.clone(), message: other.to_string() },
381 };
382 let done = match Req::new(self, a, now).memo_done(&id, a).map_err(store_err)? {
384 Some(d) => d,
385 None if desc.lang == STORED => {
386 let start = self.memo.begin();
387 let mut req = Req::new(self, a, now);
388 match req.stored(cell, &id, a) {
389 Ok(d) => {
390 self.memo.end(start, &req.learned);
391 d
392 }
393 Err(e) => {
394 self.memo.abort(start);
395 return Err(store_err(e));
396 }
397 }
398 }
399 None => {
400 let _single = self.evaluator.lock().unwrap_or_else(|p| p.into_inner());
401 self.evaluate_cell(cell, desc, a, now, false)?
402 }
403 };
404 Ok(match done {
405 Done::Value(ans) => Answer::Receipt(ans.bytes.to_vec()),
406 Done::Fault(fa) => Answer::NotCovered { fault: Some(fa.fault) },
407 Done::Withdrawn(w) => Answer::Withdrawn { receipt: w.bytes.to_vec(), reason: w.reason.clone() },
408 Done::NotCovered | Done::Unsigned(..) => Answer::NOT_COVERED,
409 })
410 }
411
412 fn evaluate_cell(
416 &self,
417 cell: &Cell,
418 desc: Arc<FunctionDescriptor>,
419 a: &str,
420 now: &str,
421 unsigned: bool,
422 ) -> Result<Done, EngineError> {
423 let start = self.memo.begin();
424 let mut req = Req::new(self, a, now);
425 let result = (|| {
426 if !unsigned {
427 if let Some(done) =
428 req.memo_done(&cell.id(), &req.asof()).map_err(|e| crate::eval::engine_error(e, &cell.id()))?
429 {
430 return Ok(done);
431 }
432 }
433 let done = req.run(cell.clone(), desc, unsigned)?;
434 req.flush()?;
435 Ok(done)
436 })();
437 match &result {
438 Ok(_) => self.memo.end(start, &req.learned),
439 Err(_) => self.memo.abort(start),
440 }
441 result
442 }
443
444 pub(crate) fn parsed(&self, hash: &str, bytes: &[u8]) -> Result<Arc<Parsed>, StoreError> {
446 if let Some(p) = self.receipts.get(hash) {
447 return Ok(p);
448 }
449 let p = Arc::new(parse_stored(hash, bytes)?);
450 self.receipts.insert(hash.to_string(), p.clone());
451 Ok(p)
452 }
453
454 fn evaluate_value(&self, cell: &Cell, asof: &str) -> Result<Option<Evaluation>, EngineError> {
457 if !is_instant(asof) || cell.is_slice() {
458 return Ok(None);
459 }
460 let Some(desc) = self.descriptor_of(&cell.fn_hash)? else { return Ok(None) };
461 if check_args(cell, &desc).is_err() {
462 return Ok(None);
463 }
464 let now = self.clock.now();
465 let done = if desc.lang == STORED {
466 Req::new(self, asof, &now)
467 .stored(cell, &cell.id(), asof)
468 .map_err(|e| EngineError::Runtime { cell_id: cell.id(), message: e.to_string() })?
469 } else {
470 let _single = self.evaluator.lock().unwrap_or_else(|p| p.into_inner());
471 let suspended = self.store.namespace(&self.host).map_err(|e| StoreError::new("namespace", e))?;
475 if suspended.is_some_and(|n| n.suspended_at.is_some()) {
476 match self.evaluate_cell(cell, desc, asof, &now, false)? {
477 Done::Value(ans) => {
478 let lineage: BTreeSet<String> = ans
479 .inputs
480 .iter()
481 .map(|u| match u {
482 Use::Cell { hash, .. } => hash.clone(),
483 Use::Slice(s) => s.entry.clone(),
484 })
485 .collect();
486 return Ok(Some(Evaluation::with_lineage(ans.value.clone(), lineage.into_iter().collect())));
487 }
488 _ => return Ok(None),
489 }
490 }
491 self.evaluate_cell(cell, desc, asof, &now, true)?
492 };
493 Ok(match done {
494 Done::Value(ans) => Some(Evaluation::new(ans.value.clone())),
495 Done::Unsigned(v, lineage) => Some(Evaluation::with_lineage(v, lineage)),
496 Done::NotCovered | Done::Fault(_) | Done::Withdrawn(_) => None,
497 })
498 }
499
500 pub(crate) fn asof_dependent(&self, fn_hash: &str, desc: &FunctionDescriptor) -> bool {
503 if let Some(b) = self.asof_dependent.get(fn_hash) {
504 return b;
505 }
506 let b = self.runtimes.get(&desc.lang).is_some_and(|rt| rt.asof_dependent(desc));
507 self.asof_dependent.insert(fn_hash.to_string(), b);
508 b
509 }
510
511 pub(crate) fn descriptor_of(&self, fn_hash: &str) -> Result<Option<Arc<FunctionDescriptor>>, EngineError> {
513 if let Some(d) = self.descriptors.get(fn_hash) {
514 return Ok(Some(d));
515 }
516 let Some(bytes) = self.store.descriptor(fn_hash) else { return Ok(None) };
517 let d = Arc::new(FunctionDescriptor::from_json(&bytes).map_err(EngineError::Invalid)?);
518 self.descriptors.insert(fn_hash.to_string(), d.clone());
519 Ok(Some(d))
520 }
521
522 pub fn stored_version_added(&self, cell_id: &str) {
531 let receipt = if self.memo.wants_receipts() {
532 self.store
533 .latest(cell_id)
534 .ok()
535 .flatten()
536 .filter(|v| !v.withdrawn)
539 .and_then(|v| self.store.receipt(&v.receipt_hash).map(|b| b.into_owned()))
540 .and_then(|b| datumesh_core::Receipt::from_json(&b).ok())
541 .map(Arc::new)
542 } else {
543 None
544 };
545 self.memo.invalidate(cell_id, receipt);
546 }
547
548 pub fn clear_memo(&self) {
550 self.memo.clear();
551 }
552
553 pub fn memo_stats(&self) -> MemoStats {
555 self.memo.stats()
556 }
557}
558
559impl Resolver for Engine {
560 fn descriptor(&self, fn_hash: &str) -> Option<Cow<'_, [u8]>> {
561 self.store.descriptor(fn_hash)
562 }
563
564 fn receipt(&self, hash: &str) -> Option<Cow<'_, [u8]>> {
565 self.store.receipt(hash)
566 }
567
568 fn manifest(&self, entry: &str) -> Option<Cow<'_, [u8]>> {
571 self.store.manifest(entry)
572 }
573
574 fn evaluate(&self, cell: &Cell, asof: &str) -> Option<Scalar> {
580 self.evaluation(cell, asof).map(|e| e.value)
581 }
582
583 fn evaluation(&self, cell: &Cell, asof: &str) -> Option<Evaluation> {
588 match self.evaluate_value(cell, asof) {
589 Ok(v) => v,
590 Err(e) => {
591 tracing::debug!(target: "datumesh_engine", cell_id = %cell.id(), asof, error = %e, "evaluate failed");
592 None
593 }
594 }
595 }
596}