Skip to main content

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    /// On an unrooted host, licence inheritance would compute the cell over restricted input
267    /// licences, but some of them are not in the engine's accepted set (engine 0.6.1, E1; see
268    /// [`EngineBuilder::accepted_licences`](crate::EngineBuilder::accepted_licences)). Nothing
269    /// was signed or stored. `licences` are the restricted input licences not accepted, sorted,
270    /// each once. Only where core's refusal would be overridden by acceptance (`not_declared`,
271    /// `declaration_not_open`, `restricted_conflict`); a rooted host gives `Unlicensed` as
272    /// before. Since 0.6.1.
273    NotAccepted {
274        /// The cell the rule refused: as for `Unlicensed`.
275        cell_id: String,
276        /// The restricted licences not accepted.
277        licences: Vec<String>,
278    },
279    /// A write the engine makes is under a suspended namespace (SPEC 9.9, store 0.4.1): the
280    /// store refused it with [`datumesh_store::Error::NamespaceSuspended`], as the mesh's own
281    /// namespace (the signer of its computed receipts) is suspended. Nothing was signed or
282    /// stored for the request; reads, verification and the receipts already stored go on.
283    /// Since 0.4.2.
284    NamespaceSuspended {
285        /// The suspended host.
286        host: String,
287        /// When it was suspended (an instant).
288        suspended_at: String,
289    },
290    /// The store did not answer within its time bound: a read waited behind a writer (the barrier
291    /// of a request, or a read of a store that has a timeout). Nothing was signed or stored for the
292    /// request; the mesh answers 503 `E_INPUT_UNAVAILABLE` (CONTRACT-guard-patch, second review B2).
293    /// Since 0.6.2.
294    InputUnavailable {
295        /// The store operation that timed out.
296        what: String,
297    },
298    /// A computed receipt could not be signed: the core refused its members. In practice an
299    /// input whose `asof` is later than the engine's clock (`E_TIME_ORDER`: `asof <= issued`).
300    /// Added to the brief's list.
301    Sign(datumesh_core::Error),
302    /// A scenario's overrides are not valid (SPEC 5.9, Build 2 E1): the code is `E_CANON_TYPE`
303    /// (a value of another type than the cell's), `E_CANON_ARG_DUPLICATE` (a cell or slice
304    /// overridden twice), `E_SLICE_MEMBER` (a removed cell that is not in the slice, a cell
305    /// both added and removed, an added cell outside the slice or already in it) or
306    /// `E_CANON_LIMIT` (more than 64 overrides). Since 0.5.0.
307    Override(String),
308    /// A scenario's cell has no value, or a fault in its scope (`not_covered`): the fault if
309    /// any, as [`Answer::NotCovered`](crate::Answer::NotCovered). Since 0.5.0.
310    NotCovered {
311        /// The evaluation fault, if the cell has no value because of one.
312        fault: Option<Fault>,
313    },
314    /// A solve found no solution (`E_WHATIF_NO_SOLUTION`): no sign change over the interval,
315    /// or the request's fuel ran out before the bisection converged (never a partial answer).
316    /// Since 0.5.0.
317    WhatifNoSolution,
318}
319
320impl fmt::Display for EngineError {
321    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
322        match self {
323            EngineError::NoRuntime { lang, fn_hash } => {
324                write!(f, "no runtime for language {lang} (function {fn_hash})")
325            }
326            EngineError::UndeclaredInput { fn_name } => write!(f, "{fn_name} is not a declared input"),
327            EngineError::Cycle { path } => write!(f, "cycle: {}", path.join(" -> ")),
328            EngineError::DepthExceeded { limit } => write!(f, "evaluation deeper than the limit of {limit}"),
329            EngineError::BudgetExceeded { fuel } => {
330                write!(f, "evaluation needs more than its fuel of {fuel}; nothing was stored")
331            }
332            EngineError::WorkExceeded { limit } => {
333                write!(f, "evaluation needs more work than its limit of {limit}; nothing was stored")
334            }
335            EngineError::NameUnresolved { fn_name, asof } => write!(f, "{fn_name} has no binding as of {asof}"),
336            EngineError::Store(e) => e.fmt(f),
337            EngineError::Runtime { cell_id, message } => write!(f, "runtime, evaluating cell {cell_id}: {message}"),
338            EngineError::BlobUnavailable { sha256, reason } => {
339                write!(f, "the content of blob {sha256} is unavailable: {reason}; nothing was stored")
340            }
341            EngineError::Unlicensed { cell_id, reason } => {
342                write!(f, "licence inheritance refuses to compute cell {cell_id}: {reason}; nothing was stored")
343            }
344            EngineError::NotAccepted { cell_id, licences } => write!(
345                f,
346                "licence inheritance refuses to compute cell {cell_id}: not accepted: {}; nothing was stored",
347                licences.join(", ")
348            ),
349            EngineError::NamespaceSuspended { host, suspended_at } => {
350                write!(f, "the namespace {host} is suspended since {suspended_at}; nothing was signed or stored")
351            }
352            EngineError::InputUnavailable { what } => {
353                write!(f, "the store did not answer in time ({what}); nothing was signed or stored")
354            }
355            EngineError::Invalid(e) => write!(f, "invalid request: {e}"),
356            EngineError::Sign(e) => write!(f, "cannot sign the computed receipt: {e}"),
357            EngineError::Override(code) => write!(f, "scenario override refused: {code}; nothing was computed"),
358            EngineError::NotCovered { fault: Some(fault) } => write!(f, "not covered in the scenario: {fault}"),
359            EngineError::NotCovered { fault: None } => f.write_str("not covered in the scenario"),
360            EngineError::WhatifNoSolution => {
361                f.write_str("E_WHATIF_NO_SOLUTION: no solution in the interval, or the fuel ran out")
362            }
363        }
364    }
365}
366
367impl std::error::Error for EngineError {
368    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
369        match self {
370            EngineError::Store(e) => Some(e),
371            EngineError::Invalid(e) | EngineError::Sign(e) => Some(e),
372            _ => None,
373        }
374    }
375}
376
377impl From<StoreError> for EngineError {
378    /// A store's refusal of a write under a suspended namespace (SPEC 9.9) is
379    /// [`EngineError::NamespaceSuspended`]; any other store failure is [`EngineError::Store`].
380    fn from(e: StoreError) -> EngineError {
381        match &*e.inner {
382            datumesh_store::Error::NamespaceSuspended { host, suspended_at } => {
383                EngineError::NamespaceSuspended { host: host.clone(), suspended_at: suspended_at.clone() }
384            }
385            datumesh_store::Error::Timeout(_) => EngineError::InputUnavailable { what: e.op.to_string() },
386            _ => EngineError::Store(e),
387        }
388    }
389}
390
391/// Why an engine could not be built ([`EngineBuilder::build`](crate::EngineBuilder::build)).
392#[non_exhaustive]
393#[derive(Debug)]
394pub enum ConfigError {
395    /// The mesh host is not a DNS name.
396    Host(datumesh_core::Error),
397    /// No signing key was given.
398    NoSigningKey,
399    /// The signing key's seed file could not be read, or does not hold a seed (32 bytes, or
400    /// 64 hex digits with an optional final newline).
401    KeyFile(String),
402    /// The licence for computed receipts is not an SPDX identifier or an https URL.
403    Licence(datumesh_core::Error),
404    /// The store holds no key document for the mesh host, or the document has no key with the
405    /// signing key's id and public key: the store would refuse every computed receipt.
406    KeyNotPublished {
407        /// The mesh host.
408        host: String,
409        /// The signing key's id.
410        key_id: String,
411    },
412    /// Reading the mesh host's key document from the store failed.
413    Store(StoreError),
414    /// Two runtimes for one language, or a runtime for `stored`, which the engine answers
415    /// itself.
416    Runtime(String),
417}
418
419impl fmt::Display for ConfigError {
420    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
421        match self {
422            ConfigError::Host(e) => write!(f, "mesh host: {e}"),
423            ConfigError::NoSigningKey => f.write_str("no signing key"),
424            ConfigError::KeyFile(m) => write!(f, "signing key file: {m}"),
425            ConfigError::Licence(e) => write!(f, "licence: {e}"),
426            ConfigError::KeyNotPublished { host, key_id } => {
427                write!(f, "the store holds no key document of {host} publishing key {key_id}")
428            }
429            ConfigError::Store(e) => e.fmt(f),
430            ConfigError::Runtime(m) => write!(f, "runtimes: {m}"),
431        }
432    }
433}
434
435impl std::error::Error for ConfigError {
436    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
437        match self {
438            ConfigError::Host(e) | ConfigError::Licence(e) => Some(e),
439            ConfigError::Store(e) => Some(e),
440            _ => None,
441        }
442    }
443}