Skip to main content

datumesh_core/
error.rs

1//! Error codes (SPEC 10.2) and the error type every fallible function returns.
2
3use core::fmt;
4
5macro_rules! codes {
6    ($( $(#[$doc:meta])* $variant:ident = $text:literal, )*) => {
7        /// One variant per `E_*` code of SPEC 10.2 (`spec-0.4.1`).
8        /// Non-exhaustive: codes added by later revisions of the specification are additions.
9        ///
10        /// The variants are declared in the order of 10.2, except the codes added within
11        /// 0.3.x, which follow in the order they were added so that [`ErrorCode::ALL`] and the
12        /// derived ordering only grow: `EvalUnavailable` (0.3.0; 10.2 lists it between
13        /// `E_VALUE_MISMATCH` and `E_BLOB_MISMATCH`), then `SliceMember` and `InputSuperseded`
14        /// (0.3.4, `spec-0.4.0`; 10.2 lists them after `E_INPUT_UNDECLARED` and after
15        /// `E_EVAL_UNAVAILABLE`), then `JobUnknown` and `MeshDoc` (0.3.5, `spec-0.4.1`; last in
16        /// 10.2 too, after `E_ENVELOPE`). The formula codes of SPEC 15.11 are not verification codes
17        /// and have no variant; the envelope's `fault` is a [`crate::Fault`].
18        #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
19        #[non_exhaustive]
20        pub enum ErrorCode {
21            $( $(#[$doc])* $variant, )*
22        }
23
24        impl ErrorCode {
25            /// Every code, in the order of SPEC 10.2 except the codes added within 0.3.x, which
26            /// come last (see [`ErrorCode`]).
27            pub const ALL: &'static [ErrorCode] = &[$(ErrorCode::$variant,)*];
28
29            /// The code as written in the specification, e.g. `"E_SIGNATURE"`.
30            pub const fn as_str(self) -> &'static str {
31                match self { $(ErrorCode::$variant => $text,)* }
32            }
33
34            /// Looks a code up by its text; `None` for anything not in [`ErrorCode::ALL`].
35            pub fn from_code(text: &str) -> Option<ErrorCode> {
36                match text { $($text => Some(ErrorCode::$variant),)* _ => None }
37            }
38        }
39    };
40}
41
42codes! {
43    /// Not strict JSON (6.1).
44    ParseJson = "E_PARSE_JSON",
45    /// A member name repeated in one object.
46    ParseDuplicateKey = "E_PARSE_DUPLICATE_KEY",
47    /// Not a cell URI by the outer grammar (5.1).
48    ParseUri = "E_PARSE_URI",
49    /// Missing or extra member, wrong JSON type, wrong `proto`, null; content for a non-blob.
50    Schema = "E_SCHEMA",
51    /// Invalid DNS name, namespace, function name, code language or key reference.
52    CanonName = "E_CANON_NAME",
53    /// Invalid or reserved argument name.
54    CanonArgName = "E_CANON_ARG_NAME",
55    /// An argument or `asof` repeated in a URI.
56    CanonArgDuplicate = "E_CANON_ARG_DUPLICATE",
57    /// URI arguments out of order, or `asof` not last.
58    CanonArgOrder = "E_CANON_ARG_ORDER",
59    /// Non-canonical percent-encoding or non-UTF-8 bytes.
60    CanonPercent = "E_CANON_PERCENT",
61    /// Unknown type name, value of the wrong JSON type, or a bad valid-time declaration.
62    CanonType = "E_CANON_TYPE",
63    /// Number not in canonical decimal form.
64    CanonNumber = "E_CANON_NUMBER",
65    /// A unit rule of 7.1 or `units.md` broken.
66    CanonUnit = "E_CANON_UNIT",
67    /// Date not `YYYY-MM-DD` or not a calendar day.
68    CanonDate = "E_CANON_DATE",
69    /// Instant not `YYYY-MM-DDTHH:MM:SS.ffffffZ` or not a real time.
70    CanonInstant = "E_CANON_INSTANT",
71    /// Control, unassigned or surrogate code point, not NFC, or empty summary.
72    CanonString = "E_CANON_STRING",
73    /// Blob not `<sha256>:<length>:<media type>`.
74    CanonBlob = "E_CANON_BLOB",
75    /// Hash, key id, signature or slice entry not lowercase hex of the right length.
76    CanonHex = "E_CANON_HEX",
77    /// Licence neither an SPDX identifier nor an `https://` URL.
78    CanonLicence = "E_CANON_LICENCE",
79    /// `inputs`, an extent or manifest members not strictly ascending; `order` not every
80    /// argument exactly once.
81    CanonSet = "E_CANON_SET",
82    /// A limit from 4.5 exceeded.
83    CanonLimit = "E_CANON_LIMIT",
84    /// A slice marker where a single cell is required; a slice object without an open or
85    /// ranged argument.
86    Slice = "E_SLICE",
87    /// `publisher` differs from `cell.ns`.
88    PublisherMismatch = "E_PUBLISHER_MISMATCH",
89    /// `valid` does not echo exactly the valid-time arguments.
90    ValidMismatch = "E_VALID_MISMATCH",
91    /// A time-order rule broken.
92    TimeOrder = "E_TIME_ORDER",
93    /// An argument the function does not declare.
94    ArgUnknown = "E_ARG_UNKNOWN",
95    /// A declared argument not bound.
96    ArgMissing = "E_ARG_MISSING",
97    /// The key document could not be retrieved.
98    KeyUnavailable = "E_KEY_UNAVAILABLE",
99    /// The key document is malformed or breaks a rule of 9.2.
100    KeyDoc = "E_KEY_DOC",
101    /// The key document has no key with that id.
102    KeyUnknown = "E_KEY_UNKNOWN",
103    /// `issued` is outside the key's validity window.
104    KeyNotValid = "E_KEY_NOT_VALID",
105    /// The Ed25519 signature does not verify.
106    Signature = "E_SIGNATURE",
107    /// No descriptor found for `fn_hash`.
108    FnUnavailable = "E_FN_UNAVAILABLE",
109    /// The descriptor does not hash to `fn_hash`.
110    FnHashMismatch = "E_FN_HASH_MISMATCH",
111    /// An argument's type differs from its declaration.
112    ArgType = "E_ARG_TYPE",
113    /// `type` differs from the declared return type.
114    ReturnType = "E_RETURN_TYPE",
115    /// An input receipt cannot be found, or has another hash.
116    InputUnavailable = "E_INPUT_UNAVAILABLE",
117    /// An input receipt is not signature-valid.
118    InputInvalid = "E_INPUT_INVALID",
119    /// An input receipt, or a slice, is of a function not in the descriptor's `inputs`.
120    InputUndeclared = "E_INPUT_UNDECLARED",
121    /// Recomputation gives a different type or value.
122    ValueMismatch = "E_VALUE_MISMATCH",
123    /// Blob content has another length or hash than the blob states.
124    BlobMismatch = "E_BLOB_MISMATCH",
125    /// A response envelope breaks a rule of 5.5.
126    Envelope = "E_ENVELOPE",
127    /// The verifier could not evaluate the function (10.1 step 7.6): no runtime for its
128    /// language, a budget exceeded, or inputs the evaluator cannot obtain. Not a failure: it
129    /// is reported with success at level `signed` (see [`crate::VerifyResult`]). A mesh may
130    /// carry it in an `error` envelope (5.5). In 10.2 since `spec-0.3.0` (RS-28).
131    EvalUnavailable = "E_EVAL_UNAVAILABLE",
132    /// A member receipt does not belong to its slice, or two members of a membership slice
133    /// are one cell (10.1 step 7.5, `spec-0.4.0`).
134    SliceMember = "E_SLICE_MEMBER",
135    /// Recomputation read a later version of an input cell, or other members of an input
136    /// slice (10.1 step 7.6, `spec-0.4.0`): the receipt is historical, not wrong. Not a
137    /// failure: it is reported with success at level `signed`, at path `$.inputs` (see
138    /// [`crate::VerifyResult`]).
139    InputSuperseded = "E_INPUT_SUPERSEDED",
140    /// In a `bad_request` envelope at a job URL: the job is unknown or expired (5.5,
141    /// `spec-0.4.1`). A mesh's code, not a client's or a verification result.
142    JobUnknown = "E_JOB_UNKNOWN",
143    /// The mesh document cannot be retrieved, is malformed, breaks a rule of 9.6, or disagrees
144    /// with the key document on `host` or `proto` ([`crate::resolve_mesh`], `spec-0.4.1`).
145    /// Never a verification result.
146    MeshDoc = "E_MESH_DOC",
147}
148
149impl fmt::Display for ErrorCode {
150    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
151        f.write_str(self.as_str())
152    }
153}
154
155/// A failure: its code, the JSON path (or URI part) where it was found, and a human detail.
156#[derive(Clone, Debug, PartialEq, Eq)]
157pub struct Error {
158    code: ErrorCode,
159    path: String,
160    detail: String,
161}
162
163impl Error {
164    /// Builds an error. `path` is a JSONPath-like location such as `$.cell.args.base`.
165    pub fn new(code: ErrorCode, path: impl Into<String>, detail: impl Into<String>) -> Error {
166        Error { code, path: path.into(), detail: detail.into() }
167    }
168
169    /// The code of SPEC 10.2.
170    pub fn code(&self) -> ErrorCode {
171        self.code
172    }
173
174    /// The code as text, e.g. `"E_SIGNATURE"`.
175    pub fn code_str(&self) -> &'static str {
176        self.code.as_str()
177    }
178
179    /// Where the failure was found: `$` is the whole input, `$.a.b[0]` a member.
180    pub fn path(&self) -> &str {
181        &self.path
182    }
183
184    /// A human-readable explanation. Not stable; do not match on it.
185    pub fn detail(&self) -> &str {
186        &self.detail
187    }
188
189    /// The same failure reported under another code (e.g. wrapping as `E_KEY_DOC`).
190    pub(crate) fn recode(self, code: ErrorCode) -> Error {
191        let detail = if self.code == code { self.detail } else { format!("{}: {}", self.code, self.detail) };
192        Error { code, path: self.path, detail }
193    }
194}
195
196impl fmt::Display for Error {
197    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
198        write!(f, "{} at {}: {}", self.code, self.path, self.detail)
199    }
200}
201
202impl std::error::Error for Error {}
203
204/// Shorthand used throughout the crate.
205pub type Result<T> = core::result::Result<T, Error>;
206
207pub(crate) fn err<T>(code: ErrorCode, path: &str, detail: impl Into<String>) -> Result<T> {
208    Err(Error::new(code, path, detail))
209}
210
211/// Appends a member name to a path.
212pub(crate) fn member(path: &str, name: &str) -> String {
213    format!("{path}.{name}")
214}
215
216/// Appends an array index to a path.
217pub(crate) fn index(path: &str, i: usize) -> String {
218    format!("{path}[{i}]")
219}