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}
132
133impl fmt::Display for EvalError {
134    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
135        match self {
136            EvalError::NoRuntime { lang } => write!(f, "no runtime for language {lang}"),
137            EvalError::UndeclaredInput { fn_name } => write!(f, "{fn_name} is not a declared input"),
138            EvalError::Cycle { cell_id } => write!(f, "cycle: cell {cell_id} depends on itself"),
139            EvalError::DepthExceeded { limit } => write!(f, "evaluation deeper than the limit of {limit}"),
140            EvalError::BudgetExceeded { fuel } => write!(f, "evaluation needs more than its fuel of {fuel}"),
141            EvalError::NameUnresolved { fn_name, asof } => write!(f, "{fn_name} has no binding as of {asof}"),
142            EvalError::Store(e) => e.fmt(f),
143            EvalError::Runtime(m) => write!(f, "runtime: {m}"),
144            EvalError::Suspended => f.write_str("evaluation suspended until an input is available"),
145            EvalError::InputNotCovered { cell_id } => write!(f, "input cell {cell_id} has no value as of the asof"),
146            EvalError::InvalidInput(e) => write!(f, "invalid input cell: {e}"),
147            EvalError::Fault(c) => write!(f, "evaluation fault {c}"),
148        }
149    }
150}
151
152impl std::error::Error for EvalError {
153    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
154        match self {
155            EvalError::Store(e) => Some(e),
156            EvalError::InvalidInput(e) => Some(e),
157            _ => None,
158        }
159    }
160}
161
162/// What [`Engine::get`](crate::Engine::get) can fail with. For how each maps to a response
163/// envelope, see the crate documentation.
164#[non_exhaustive]
165#[derive(Clone, Debug)]
166pub enum EngineError {
167    /// No runtime is configured for a function's `code.lang`.
168    NoRuntime {
169        /// The language.
170        lang: String,
171        /// The function's hash.
172        fn_hash: String,
173    },
174    /// A function read a function its descriptor does not declare in `inputs`.
175    UndeclaredInput {
176        /// The fully qualified name read.
177        fn_name: String,
178    },
179    /// A cell depends on itself.
180    Cycle {
181        /// The cell that reappeared on the evaluation stack.
182        cell_id: String,
183    },
184    /// The evaluation stack reached the depth limit.
185    DepthExceeded {
186        /// The limit.
187        limit: usize,
188    },
189    /// The request's fuel ran out: its normative fuel (SPEC 15.12) exceeds the limit. Nothing
190    /// was stored for the request.
191    BudgetExceeded {
192        /// The fuel the request had.
193        fuel: u64,
194    },
195    /// The request's work ran out: every evaluation attempt (those a restart discarded
196    /// included) and the engine's validation reads, which bound its total cost beyond the
197    /// normative fuel ([`EngineBuilder::work_limit`](crate::EngineBuilder::work_limit)).
198    /// Nothing was stored for the request. Since 0.3.0.
199    WorkExceeded {
200        /// The work limit.
201        limit: u64,
202    },
203    /// An input's function name has no binding as of the request's asof.
204    NameUnresolved {
205        /// The fully qualified name.
206        fn_name: String,
207        /// The asof.
208        asof: String,
209    },
210    /// The store failed.
211    Store(StoreError),
212    /// A runtime failed, or broke its contract (returned a value of another type than the
213    /// function declares, or `Suspended` without a pending input).
214    Runtime {
215        /// The cell being evaluated.
216        cell_id: String,
217        /// What happened.
218        message: String,
219    },
220    /// The request is malformed: an asof that is not an instant, a slice, arguments that do
221    /// not match the function's signature; or a runtime read such an input. The core's error
222    /// carries the code (`E_CANON_INSTANT`, `E_SLICE`, `E_ARG_UNKNOWN`, ...). Added to the
223    /// brief's list.
224    Invalid(datumesh_core::Error),
225    /// A computed receipt could not be signed: the core refused its members. In practice an
226    /// input whose `asof` is later than the engine's clock (`E_TIME_ORDER`: `asof <= issued`).
227    /// Added to the brief's list.
228    Sign(datumesh_core::Error),
229}
230
231impl fmt::Display for EngineError {
232    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
233        match self {
234            EngineError::NoRuntime { lang, fn_hash } => {
235                write!(f, "no runtime for language {lang} (function {fn_hash})")
236            }
237            EngineError::UndeclaredInput { fn_name } => write!(f, "{fn_name} is not a declared input"),
238            EngineError::Cycle { cell_id } => write!(f, "cycle: cell {cell_id} depends on itself"),
239            EngineError::DepthExceeded { limit } => write!(f, "evaluation deeper than the limit of {limit}"),
240            EngineError::BudgetExceeded { fuel } => {
241                write!(f, "evaluation needs more than its fuel of {fuel}; nothing was stored")
242            }
243            EngineError::WorkExceeded { limit } => {
244                write!(f, "evaluation needs more work than its limit of {limit}; nothing was stored")
245            }
246            EngineError::NameUnresolved { fn_name, asof } => write!(f, "{fn_name} has no binding as of {asof}"),
247            EngineError::Store(e) => e.fmt(f),
248            EngineError::Runtime { cell_id, message } => write!(f, "runtime, evaluating cell {cell_id}: {message}"),
249            EngineError::Invalid(e) => write!(f, "invalid request: {e}"),
250            EngineError::Sign(e) => write!(f, "cannot sign the computed receipt: {e}"),
251        }
252    }
253}
254
255impl std::error::Error for EngineError {
256    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
257        match self {
258            EngineError::Store(e) => Some(e),
259            EngineError::Invalid(e) | EngineError::Sign(e) => Some(e),
260            _ => None,
261        }
262    }
263}
264
265impl From<StoreError> for EngineError {
266    fn from(e: StoreError) -> EngineError {
267        EngineError::Store(e)
268    }
269}
270
271/// Why an engine could not be built ([`EngineBuilder::build`](crate::EngineBuilder::build)).
272#[non_exhaustive]
273#[derive(Debug)]
274pub enum ConfigError {
275    /// The mesh host is not a DNS name.
276    Host(datumesh_core::Error),
277    /// No signing key was given.
278    NoSigningKey,
279    /// The signing key's seed file could not be read, or does not hold a seed (32 bytes, or
280    /// 64 hex digits with an optional final newline).
281    KeyFile(String),
282    /// The licence for computed receipts is not an SPDX identifier or an https URL.
283    Licence(datumesh_core::Error),
284    /// The store holds no key document for the mesh host, or the document has no key with the
285    /// signing key's id and public key: the store would refuse every computed receipt.
286    KeyNotPublished {
287        /// The mesh host.
288        host: String,
289        /// The signing key's id.
290        key_id: String,
291    },
292    /// Reading the mesh host's key document from the store failed.
293    Store(StoreError),
294    /// Two runtimes for one language, or a runtime for `stored`, which the engine answers
295    /// itself.
296    Runtime(String),
297}
298
299impl fmt::Display for ConfigError {
300    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
301        match self {
302            ConfigError::Host(e) => write!(f, "mesh host: {e}"),
303            ConfigError::NoSigningKey => f.write_str("no signing key"),
304            ConfigError::KeyFile(m) => write!(f, "signing key file: {m}"),
305            ConfigError::Licence(e) => write!(f, "licence: {e}"),
306            ConfigError::KeyNotPublished { host, key_id } => {
307                write!(f, "the store holds no key document of {host} publishing key {key_id}")
308            }
309            ConfigError::Store(e) => e.fmt(f),
310            ConfigError::Runtime(m) => write!(f, "runtimes: {m}"),
311        }
312    }
313}
314
315impl std::error::Error for ConfigError {
316    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
317        match self {
318            ConfigError::Host(e) | ConfigError::Licence(e) => Some(e),
319            ConfigError::Store(e) => Some(e),
320            _ => None,
321        }
322    }
323}