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