datumesh_engine/error.rs
1//! The engine's errors: [`EvalError`] (what a runtime and [`Inputs`](crate::Inputs) see),
2//! [`EngineError`] (what [`Engine::get`](crate::Engine::get) returns), [`ConfigError`]
3//! (building an engine) and [`StoreError`] (a store failure, in the engine's words).
4
5use std::fmt;
6
7use datumesh_core::Fault;
8use std::sync::Arc;
9
10/// A store failure, as the engine reports it.
11///
12/// It wraps the store's error (its [`source`](std::error::Error::source)), with the engine's
13/// own wording: the store's `Conflict` speaks of signatures, which is not what a conflict
14/// means to the engine (another receipt is already recorded for a version).
15#[derive(Clone, Debug)]
16pub struct StoreError {
17 op: &'static str,
18 inner: Arc<datumesh_store::Error>,
19}
20
21impl StoreError {
22 pub(crate) fn new(op: &'static str, e: datumesh_store::Error) -> StoreError {
23 StoreError { op, inner: Arc::new(e) }
24 }
25
26 /// The store operation that failed (`stored_asof`, `put_receipt`, ...).
27 pub fn operation(&self) -> &str {
28 self.op
29 }
30
31 /// The store's error.
32 pub fn store_error(&self) -> &datumesh_store::Error {
33 &self.inner
34 }
35
36 /// Whether the store refused a write because another receipt is recorded under the same
37 /// key.
38 pub fn is_conflict(&self) -> bool {
39 matches!(*self.inner, datumesh_store::Error::Conflict { .. })
40 }
41}
42
43impl fmt::Display for StoreError {
44 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45 match &*self.inner {
46 datumesh_store::Error::Conflict { hash } => write!(
47 f,
48 "store {}: another receipt is already recorded where receipt {hash} was to go; the recorded one is kept",
49 self.op
50 ),
51 other => write!(f, "store {}: {other}", self.op),
52 }
53 }
54}
55
56impl std::error::Error for StoreError {
57 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
58 Some(&*self.inner)
59 }
60}
61
62/// What evaluating a function can fail with: returned by [`Inputs::read`](crate::Inputs::read)
63/// and [`Budget::charge`](crate::Budget::charge), and by a [`Runtime`](crate::Runtime).
64///
65/// A runtime propagates every error it gets from `Inputs::read` or `Budget::charge`
66/// unchanged (with `?`). The engine does not depend on it: it records each such error when it
67/// happens, and what the runtime returns after it is ignored.
68#[non_exhaustive]
69#[derive(Clone, Debug)]
70pub enum EvalError {
71 /// No runtime is configured for the function's `code.lang`.
72 NoRuntime {
73 /// The language.
74 lang: String,
75 },
76 /// The function read a function its descriptor does not declare in `inputs`.
77 UndeclaredInput {
78 /// The fully qualified name read.
79 fn_name: String,
80 },
81 /// The cell reappeared on the evaluation stack: it depends on itself. The path holds the
82 /// canonical calls in read order, from the cell that reappeared to its second occurrence.
83 Cycle {
84 /// The canonical calls of the cycle (SPEC 5.8), the first and last equal.
85 path: Vec<String>,
86 },
87 /// The evaluation stack reached the engine's depth limit.
88 DepthExceeded {
89 /// The limit.
90 limit: usize,
91 },
92 /// The request's fuel (runtime steps plus input reads) ran out.
93 BudgetExceeded {
94 /// The fuel the request had.
95 fuel: u64,
96 },
97 /// A function name has no binding as of the evaluation's asof.
98 NameUnresolved {
99 /// The fully qualified name.
100 fn_name: String,
101 /// The asof.
102 asof: String,
103 },
104 /// The store failed.
105 Store(StoreError),
106 /// The runtime failed: its own message.
107 Runtime(String),
108 /// The input read is not available yet: the engine evaluates it, then runs the reading
109 /// function again from the start (see [`Inputs`](crate::Inputs)). Added to the brief's
110 /// list: it is how evaluation suspends without native recursion.
111 Suspended,
112 /// The input has no value as of the evaluation's asof (a stored cell with no version
113 /// answering then, or a computed cell one of whose inputs has none). The reading cell has
114 /// no value either ([`Answer::NotCovered`](crate::Answer::NotCovered)), even if the
115 /// runtime catches it: a receipt lists the inputs read, and cannot list an absence, so a
116 /// value computed from one could be neither checked against its inputs nor recomputed.
117 /// Added to the brief's list.
118 InputNotCovered {
119 /// The input cell's id.
120 cell_id: String,
121 },
122 /// The arguments given to `Inputs::read` do not make a cell of the input function (a
123 /// slice, an unknown or missing argument, a type that differs from the signature). Added to
124 /// the brief's list: it is the runtime's mistake, not the engine's or the store's.
125 InvalidInput(datumesh_core::Error),
126 /// A formula evaluation fault (SPEC 15.11, 15.12): the cell has no value, deterministically
127 /// (`E_FORMULA_DIV_ZERO`, `E_FORMULA_DOMAIN`, `E_FORMULA_RANGE`, `E_FORMULA_EMPTY`,
128 /// `E_FORMULA_ABSENT`, `E_FORMULA_FUTURE`). Returned by a runtime, it makes the answer
129 /// [`Answer::NotCovered`](crate::Answer::NotCovered) with the fault, and nothing is
130 /// stored for the cell. Returned by a read (an input that faulted, a computed slice with a
131 /// member without a value, a transaction time after the asof), the runtime may catch it
132 /// where its language allows. Since 0.3.0.
133 Fault(datumesh_core::Fault),
134 /// A blob's content could not be obtained ([`Inputs::read_blob`](crate::Inputs::read_blob)):
135 /// the store has none for its SHA-256, or what it has is not the blob's (another length or
136 /// hash). The evaluator's failure, not a fault of the cell (SPEC 15.12,
137 /// `E_FORMULA_BLOB_UNAVAILABLE`): the request fails with
138 /// [`EngineError::BlobUnavailable`] whatever the runtime returns after it. Since 0.3.2.
139 BlobUnavailable {
140 /// The blob's SHA-256.
141 sha256: String,
142 /// Why: no content, or content of another length or hash.
143 reason: String,
144 },
145}
146
147impl fmt::Display for EvalError {
148 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
149 match self {
150 EvalError::NoRuntime { lang } => write!(f, "no runtime for language {lang}"),
151 EvalError::UndeclaredInput { fn_name } => write!(f, "{fn_name} is not a declared input"),
152 EvalError::Cycle { path } => write!(f, "cycle: {}", path.join(" -> ")),
153 EvalError::DepthExceeded { limit } => write!(f, "evaluation deeper than the limit of {limit}"),
154 EvalError::BudgetExceeded { fuel } => write!(f, "evaluation needs more than its fuel of {fuel}"),
155 EvalError::NameUnresolved { fn_name, asof } => write!(f, "{fn_name} has no binding as of {asof}"),
156 EvalError::Store(e) => e.fmt(f),
157 EvalError::Runtime(m) => write!(f, "runtime: {m}"),
158 EvalError::Suspended => f.write_str("evaluation suspended until an input is available"),
159 EvalError::InputNotCovered { cell_id } => write!(f, "input cell {cell_id} has no value as of the asof"),
160 EvalError::InvalidInput(e) => write!(f, "invalid input cell: {e}"),
161 EvalError::Fault(c) => write!(f, "evaluation fault {c}"),
162 EvalError::BlobUnavailable { sha256, reason } => {
163 write!(f, "the content of blob {sha256} is unavailable: {reason}")
164 }
165 }
166 }
167}
168
169impl std::error::Error for EvalError {
170 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
171 match self {
172 EvalError::Store(e) => Some(e),
173 EvalError::InvalidInput(e) => Some(e),
174 _ => None,
175 }
176 }
177}
178
179/// What [`Engine::get`](crate::Engine::get) can fail with. For how each maps to a response
180/// envelope, see the crate documentation.
181#[non_exhaustive]
182#[derive(Clone, Debug)]
183pub enum EngineError {
184 /// No runtime is configured for a function's `code.lang`.
185 NoRuntime {
186 /// The language.
187 lang: String,
188 /// The function's hash.
189 fn_hash: String,
190 },
191 /// A function read a function its descriptor does not declare in `inputs`.
192 UndeclaredInput {
193 /// The fully qualified name read.
194 fn_name: String,
195 },
196 /// A cell depends on itself. `path` holds the canonical calls of the cycle in read order,
197 /// starting at the cell that reappeared and ending with it again (Build 2 E3: since 0.5.0).
198 Cycle {
199 /// The canonical calls of the cycle (SPEC 5.8).
200 path: Vec<String>,
201 },
202 /// The evaluation stack reached the depth limit. Since 0.5.0 a deeper evaluation splits
203 /// itself instead (Build 2 E4), so this is not raised by the engine's evaluation.
204 DepthExceeded {
205 /// The limit.
206 limit: usize,
207 },
208 /// The request's fuel ran out: its normative fuel (SPEC 15.12) exceeds the limit. Nothing
209 /// was stored for the request.
210 BudgetExceeded {
211 /// The fuel the request had.
212 fuel: u64,
213 },
214 /// The request's work ran out: every evaluation attempt (those a restart discarded
215 /// included) and the engine's validation reads, which bound its total cost beyond the
216 /// normative fuel ([`EngineBuilder::work_limit`](crate::EngineBuilder::work_limit)).
217 /// Nothing was stored for the request. Since 0.3.0.
218 WorkExceeded {
219 /// The work limit.
220 limit: u64,
221 },
222 /// An input's function name has no binding as of the request's asof.
223 NameUnresolved {
224 /// The fully qualified name.
225 fn_name: String,
226 /// The asof.
227 asof: String,
228 },
229 /// The store failed.
230 Store(StoreError),
231 /// A runtime failed, or broke its contract (returned a value of another type than the
232 /// function declares, or `Suspended` without a pending input).
233 Runtime {
234 /// The cell being evaluated.
235 cell_id: String,
236 /// What happened.
237 message: String,
238 },
239 /// A function read a blob whose content the engine could not obtain or check (SPEC 15.7,
240 /// 15.12: `E_FORMULA_BLOB_UNAVAILABLE`, the evaluator's failure). Nothing was stored for
241 /// the request. Since 0.3.2.
242 BlobUnavailable {
243 /// The blob's SHA-256.
244 sha256: String,
245 /// Why: no content, or content of another length or hash.
246 reason: String,
247 },
248 /// The request is malformed: an asof that is not an instant, a slice, arguments that do
249 /// not match the function's signature; or a runtime read such an input. The core's error
250 /// carries the code (`E_CANON_INSTANT`, `E_SLICE`, `E_ARG_UNKNOWN`, ...). Added to the
251 /// brief's list.
252 Invalid(datumesh_core::Error),
253 /// The mesh may not compute the cell under licence inheritance (SPEC 8.5, spec-0.4.3): its
254 /// input licences have no licence in common (`share_alike_conflict`,
255 /// `restricted_conflict`), or a restricted input licence is not declared for the function
256 /// by its publisher, open at the receipt's `issued` (`not_declared`,
257 /// `declaration_not_open`). Nothing was signed or stored for the request. `cell_id` is
258 /// the refused cell: the requested one, or a cell it reads (a reader of a refused cell is
259 /// refused too). The HTTP layer answers `unlicensed` (403, no new code). Since 0.4.1.
260 Unlicensed {
261 /// The cell the rule refused.
262 cell_id: String,
263 /// Why (never one of the reasons that give a licence).
264 reason: datumesh_core::LicenceReason,
265 },
266 /// A write the engine makes is under a suspended namespace (SPEC 9.9, store 0.4.1): the
267 /// store refused it with [`datumesh_store::Error::NamespaceSuspended`], as the mesh's own
268 /// namespace (the signer of its computed receipts) is suspended. Nothing was signed or
269 /// stored for the request; reads, verification and the receipts already stored go on.
270 /// Since 0.4.2.
271 NamespaceSuspended {
272 /// The suspended host.
273 host: String,
274 /// When it was suspended (an instant).
275 suspended_at: String,
276 },
277 /// A computed receipt could not be signed: the core refused its members. In practice an
278 /// input whose `asof` is later than the engine's clock (`E_TIME_ORDER`: `asof <= issued`).
279 /// Added to the brief's list.
280 Sign(datumesh_core::Error),
281 /// A scenario's overrides are not valid (SPEC 5.9, Build 2 E1): the code is `E_CANON_TYPE`
282 /// (a value of another type than the cell's), `E_CANON_ARG_DUPLICATE` (a cell or slice
283 /// overridden twice), `E_SLICE_MEMBER` (a removed cell that is not in the slice, a cell
284 /// both added and removed, an added cell outside the slice or already in it) or
285 /// `E_CANON_LIMIT` (more than 64 overrides). Since 0.5.0.
286 Override(String),
287 /// A scenario's cell has no value, or a fault in its scope (`not_covered`): the fault if
288 /// any, as [`Answer::NotCovered`](crate::Answer::NotCovered). Since 0.5.0.
289 NotCovered {
290 /// The evaluation fault, if the cell has no value because of one.
291 fault: Option<Fault>,
292 },
293 /// A solve found no solution (`E_WHATIF_NO_SOLUTION`): no sign change over the interval,
294 /// or the request's fuel ran out before the bisection converged (never a partial answer).
295 /// Since 0.5.0.
296 WhatifNoSolution,
297}
298
299impl fmt::Display for EngineError {
300 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
301 match self {
302 EngineError::NoRuntime { lang, fn_hash } => {
303 write!(f, "no runtime for language {lang} (function {fn_hash})")
304 }
305 EngineError::UndeclaredInput { fn_name } => write!(f, "{fn_name} is not a declared input"),
306 EngineError::Cycle { path } => write!(f, "cycle: {}", path.join(" -> ")),
307 EngineError::DepthExceeded { limit } => write!(f, "evaluation deeper than the limit of {limit}"),
308 EngineError::BudgetExceeded { fuel } => {
309 write!(f, "evaluation needs more than its fuel of {fuel}; nothing was stored")
310 }
311 EngineError::WorkExceeded { limit } => {
312 write!(f, "evaluation needs more work than its limit of {limit}; nothing was stored")
313 }
314 EngineError::NameUnresolved { fn_name, asof } => write!(f, "{fn_name} has no binding as of {asof}"),
315 EngineError::Store(e) => e.fmt(f),
316 EngineError::Runtime { cell_id, message } => write!(f, "runtime, evaluating cell {cell_id}: {message}"),
317 EngineError::BlobUnavailable { sha256, reason } => {
318 write!(f, "the content of blob {sha256} is unavailable: {reason}; nothing was stored")
319 }
320 EngineError::Unlicensed { cell_id, reason } => {
321 write!(f, "licence inheritance refuses to compute cell {cell_id}: {reason}; nothing was stored")
322 }
323 EngineError::NamespaceSuspended { host, suspended_at } => {
324 write!(f, "the namespace {host} is suspended since {suspended_at}; nothing was signed or stored")
325 }
326 EngineError::Invalid(e) => write!(f, "invalid request: {e}"),
327 EngineError::Sign(e) => write!(f, "cannot sign the computed receipt: {e}"),
328 EngineError::Override(code) => write!(f, "scenario override refused: {code}; nothing was computed"),
329 EngineError::NotCovered { fault: Some(fault) } => write!(f, "not covered in the scenario: {fault}"),
330 EngineError::NotCovered { fault: None } => f.write_str("not covered in the scenario"),
331 EngineError::WhatifNoSolution => {
332 f.write_str("E_WHATIF_NO_SOLUTION: no solution in the interval, or the fuel ran out")
333 }
334 }
335 }
336}
337
338impl std::error::Error for EngineError {
339 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
340 match self {
341 EngineError::Store(e) => Some(e),
342 EngineError::Invalid(e) | EngineError::Sign(e) => Some(e),
343 _ => None,
344 }
345 }
346}
347
348impl From<StoreError> for EngineError {
349 /// A store's refusal of a write under a suspended namespace (SPEC 9.9) is
350 /// [`EngineError::NamespaceSuspended`]; any other store failure is [`EngineError::Store`].
351 fn from(e: StoreError) -> EngineError {
352 match &*e.inner {
353 datumesh_store::Error::NamespaceSuspended { host, suspended_at } => {
354 EngineError::NamespaceSuspended { host: host.clone(), suspended_at: suspended_at.clone() }
355 }
356 _ => EngineError::Store(e),
357 }
358 }
359}
360
361/// Why an engine could not be built ([`EngineBuilder::build`](crate::EngineBuilder::build)).
362#[non_exhaustive]
363#[derive(Debug)]
364pub enum ConfigError {
365 /// The mesh host is not a DNS name.
366 Host(datumesh_core::Error),
367 /// No signing key was given.
368 NoSigningKey,
369 /// The signing key's seed file could not be read, or does not hold a seed (32 bytes, or
370 /// 64 hex digits with an optional final newline).
371 KeyFile(String),
372 /// The licence for computed receipts is not an SPDX identifier or an https URL.
373 Licence(datumesh_core::Error),
374 /// The store holds no key document for the mesh host, or the document has no key with the
375 /// signing key's id and public key: the store would refuse every computed receipt.
376 KeyNotPublished {
377 /// The mesh host.
378 host: String,
379 /// The signing key's id.
380 key_id: String,
381 },
382 /// Reading the mesh host's key document from the store failed.
383 Store(StoreError),
384 /// Two runtimes for one language, or a runtime for `stored`, which the engine answers
385 /// itself.
386 Runtime(String),
387}
388
389impl fmt::Display for ConfigError {
390 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
391 match self {
392 ConfigError::Host(e) => write!(f, "mesh host: {e}"),
393 ConfigError::NoSigningKey => f.write_str("no signing key"),
394 ConfigError::KeyFile(m) => write!(f, "signing key file: {m}"),
395 ConfigError::Licence(e) => write!(f, "licence: {e}"),
396 ConfigError::KeyNotPublished { host, key_id } => {
397 write!(f, "the store holds no key document of {host} publishing key {key_id}")
398 }
399 ConfigError::Store(e) => e.fmt(f),
400 ConfigError::Runtime(m) => write!(f, "runtimes: {m}"),
401 }
402 }
403}
404
405impl std::error::Error for ConfigError {
406 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
407 match self {
408 ConfigError::Host(e) | ConfigError::Licence(e) => Some(e),
409 ConfigError::Store(e) => Some(e),
410 _ => None,
411 }
412 }
413}