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.5.0`).
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`), then `SliceAtCell` and `NameUnbound` (0.3.6,
17        /// `spec-0.4.2`, after `E_MESH_DOC`), then `ForeignUnavailable` (0.3.7, `spec-0.4.3`, last in
18        /// 10.2 too), then, since 0.3.8 (`spec-0.5.0`), in the order of 10.2: `UnrootedInput`,
19        /// `NamespaceSuspended`, the class codes `ClassMember` to `ClassOwner`,
20        /// `KeyNormalisation`, `KeyEncoding`, `ShortIdAmbiguous` and `Describe`. The formula
21        /// codes of SPEC 15.11 are not verification codes
22        /// and have no variant; the envelope's `fault` is a [`crate::Fault`].
23        #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
24        #[non_exhaustive]
25        pub enum ErrorCode {
26            $( $(#[$doc])* $variant, )*
27        }
28
29        impl ErrorCode {
30            /// Every code, in the order of SPEC 10.2 except the codes added within 0.3.x, which
31            /// come last (see [`ErrorCode`]).
32            pub const ALL: &'static [ErrorCode] = &[$(ErrorCode::$variant,)*];
33
34            /// The code as written in the specification, e.g. `"E_SIGNATURE"`.
35            pub const fn as_str(self) -> &'static str {
36                match self { $(ErrorCode::$variant => $text,)* }
37            }
38
39            /// Looks a code up by its text; `None` for anything not in [`ErrorCode::ALL`].
40            pub fn from_code(text: &str) -> Option<ErrorCode> {
41                match text { $($text => Some(ErrorCode::$variant),)* _ => None }
42            }
43        }
44    };
45}
46
47codes! {
48    /// Not strict JSON (6.1).
49    ParseJson = "E_PARSE_JSON",
50    /// A member name repeated in one object.
51    ParseDuplicateKey = "E_PARSE_DUPLICATE_KEY",
52    /// Not a cell URI by the outer grammar (5.1).
53    ParseUri = "E_PARSE_URI",
54    /// Missing or extra member, wrong JSON type, wrong `proto`, null; content for a non-blob.
55    Schema = "E_SCHEMA",
56    /// Invalid DNS name, namespace, function name, code language or key reference.
57    CanonName = "E_CANON_NAME",
58    /// Invalid or reserved argument name.
59    CanonArgName = "E_CANON_ARG_NAME",
60    /// An argument or `asof` repeated in a URI.
61    CanonArgDuplicate = "E_CANON_ARG_DUPLICATE",
62    /// URI arguments out of order, or `asof` not last.
63    CanonArgOrder = "E_CANON_ARG_ORDER",
64    /// Non-canonical percent-encoding or non-UTF-8 bytes.
65    CanonPercent = "E_CANON_PERCENT",
66    /// Unknown type name, value of the wrong JSON type, or a bad valid-time declaration.
67    CanonType = "E_CANON_TYPE",
68    /// Number not in canonical decimal form.
69    CanonNumber = "E_CANON_NUMBER",
70    /// A unit rule of 7.1 or `units.md` broken.
71    CanonUnit = "E_CANON_UNIT",
72    /// Date not `YYYY-MM-DD` or not a calendar day.
73    CanonDate = "E_CANON_DATE",
74    /// Instant not `YYYY-MM-DDTHH:MM:SS.ffffffZ` or not a real time.
75    CanonInstant = "E_CANON_INSTANT",
76    /// Control, unassigned or surrogate code point, not NFC, or empty summary.
77    CanonString = "E_CANON_STRING",
78    /// Blob not `<sha256>:<length>:<media type>`.
79    CanonBlob = "E_CANON_BLOB",
80    /// Hash, key id, signature or slice entry not lowercase hex of the right length.
81    CanonHex = "E_CANON_HEX",
82    /// Licence neither an SPDX identifier nor an `https://` URL.
83    CanonLicence = "E_CANON_LICENCE",
84    /// `inputs`, an extent or manifest members not strictly ascending; `order` not every
85    /// argument exactly once.
86    CanonSet = "E_CANON_SET",
87    /// A limit from 4.5 exceeded.
88    CanonLimit = "E_CANON_LIMIT",
89    /// A slice marker where a single cell is required; a slice object without an open or
90    /// ranged argument.
91    Slice = "E_SLICE",
92    /// `publisher` differs from `cell.ns`.
93    PublisherMismatch = "E_PUBLISHER_MISMATCH",
94    /// `valid` does not echo exactly the valid-time arguments.
95    ValidMismatch = "E_VALID_MISMATCH",
96    /// A time-order rule broken.
97    TimeOrder = "E_TIME_ORDER",
98    /// An argument the function does not declare.
99    ArgUnknown = "E_ARG_UNKNOWN",
100    /// A declared argument not bound.
101    ArgMissing = "E_ARG_MISSING",
102    /// The key document could not be retrieved.
103    KeyUnavailable = "E_KEY_UNAVAILABLE",
104    /// The key document is malformed or breaks a rule of 9.2.
105    KeyDoc = "E_KEY_DOC",
106    /// The key document has no key with that id.
107    KeyUnknown = "E_KEY_UNKNOWN",
108    /// `issued` is outside the key's validity window.
109    KeyNotValid = "E_KEY_NOT_VALID",
110    /// The Ed25519 signature does not verify.
111    Signature = "E_SIGNATURE",
112    /// No descriptor found for `fn_hash`.
113    FnUnavailable = "E_FN_UNAVAILABLE",
114    /// The descriptor does not hash to `fn_hash`.
115    FnHashMismatch = "E_FN_HASH_MISMATCH",
116    /// An argument's type differs from its declaration.
117    ArgType = "E_ARG_TYPE",
118    /// `type` differs from the declared return type.
119    ReturnType = "E_RETURN_TYPE",
120    /// An input receipt cannot be found, or has another hash.
121    InputUnavailable = "E_INPUT_UNAVAILABLE",
122    /// An input receipt is not signature-valid.
123    InputInvalid = "E_INPUT_INVALID",
124    /// An input receipt, or a slice, is of a function not in the descriptor's `inputs`.
125    InputUndeclared = "E_INPUT_UNDECLARED",
126    /// Recomputation gives a different type or value.
127    ValueMismatch = "E_VALUE_MISMATCH",
128    /// Blob content has another length or hash than the blob states.
129    BlobMismatch = "E_BLOB_MISMATCH",
130    /// A response envelope breaks a rule of 5.5.
131    Envelope = "E_ENVELOPE",
132    /// The verifier could not evaluate the function (10.1 step 7.6): no runtime for its
133    /// language, a budget exceeded, or inputs the evaluator cannot obtain. Not a failure: it
134    /// is reported with success at level `signed` (see [`crate::VerifyResult`]). A mesh may
135    /// carry it in an `error` envelope (5.5). In 10.2 since `spec-0.3.0` (RS-28).
136    EvalUnavailable = "E_EVAL_UNAVAILABLE",
137    /// A member receipt does not belong to its slice, or two members of a membership slice
138    /// are one cell (10.1 step 7.5, `spec-0.4.0`).
139    SliceMember = "E_SLICE_MEMBER",
140    /// Recomputation read a later version of an input cell, or other members of an input
141    /// slice (10.1 step 7.6, `spec-0.4.0`): the receipt is historical, not wrong. Not a
142    /// failure: it is reported with success at level `signed`, at path `$.inputs` (see
143    /// [`crate::VerifyResult`]).
144    InputSuperseded = "E_INPUT_SUPERSEDED",
145    /// In a `bad_request` envelope at a job URL: the job is unknown or expired (5.5,
146    /// `spec-0.4.1`). A mesh's code, not a client's or a verification result.
147    JobUnknown = "E_JOB_UNKNOWN",
148    /// The mesh document cannot be retrieved, is malformed, breaks a rule of 9.6, or disagrees
149    /// with the key document on `host` or `proto` ([`crate::resolve_mesh`], `spec-0.4.1`).
150    /// Never a verification result.
151    MeshDoc = "E_MESH_DOC",
152    /// In a `bad_request` envelope: the `/cell` request has a slice marker; slices are read at
153    /// the slice endpoint (5.6, `spec-0.4.2`). A mesh's code.
154    SliceAtCell = "E_SLICE_AT_CELL",
155    /// In a `not_covered` envelope's `error`: the name (or alias) is not bound as of the
156    /// requested `asof`; it may be bound later (5.5, 5.8, `spec-0.4.2`). A mesh's code.
157    NameUnbound = "E_NAME_UNBOUND",
158    /// In an `error` envelope, with HTTP 502 and a `detail` ([`crate::ForeignDetail`]): the cell
159    /// belongs to another mesh, which could not be reached (offline, network, DNS, TLS, timeout,
160    /// a refused connection; 5.5, 9.6, `spec-0.4.3`). A mesh's or resolver's code, never a
161    /// verification result.
162    ForeignUnavailable = "E_FOREIGN_UNAVAILABLE",
163    /// Define's code (2.5, `spec-0.5.0`): a function under a rooted namespace whose `inputs`
164    /// name a function under an unrooted one ([`crate::check_define`]). Never a verification
165    /// result, and never in an envelope.
166    UnrootedInput = "E_UNROOTED_INPUT",
167    /// A write refusal (9.9, `spec-0.5.0`) under a suspended namespace. In a `not_covered`
168    /// envelope's `error` only, for a refused cross-mesh import; never of an `error` envelope
169    /// and never a verification result.
170    NamespaceSuspended = "E_NAMESPACE_SUSPENDED",
171    /// A class descriptor member breaks its rule (16.1, `spec-0.5.0`).
172    ClassMember = "E_CLASS_MEMBER",
173    /// The parent's class descriptor is not known to define (16.2, `spec-0.5.0`).
174    ClassParent = "E_CLASS_PARENT",
175    /// A subclass redeclares a parent key (16.2, `spec-0.5.0`).
176    ClassInherit = "E_CLASS_INHERIT",
177    /// An override changes the method's signature, return type or unit (16.2, `spec-0.5.0`).
178    ClassOverride = "E_CLASS_OVERRIDE",
179    /// A subclass of a `final` class overrides a method not marked `open` (16.2, `spec-0.5.0`).
180    ClassFinal = "E_CLASS_FINAL",
181    /// A method's function is unknown, lacks `order`, or does not take the class keys first
182    /// with their types and normalisations; a `same_as` or `by_` method of the wrong return
183    /// (16.2, `spec-0.5.0`).
184    ClassMethod = "E_CLASS_METHOD",
185    /// `implements` names a class that is not a keyless interface the define knows, or an
186    /// interface method is not implemented with its signature (16.2, `spec-0.5.0`).
187    ClassInterface = "E_CLASS_INTERFACE",
188    /// A namespace defines a class under another namespace (16.2, `spec-0.5.0`).
189    ClassOwner = "E_CLASS_OWNER",
190    /// A string key value is not canonical under its normalisation (16.4, 7, `spec-0.5.0`).
191    KeyNormalisation = "E_KEY_NORMALISATION",
192    /// An object key string is malformed or not its canonical encoding (16.5, `spec-0.5.0`).
193    KeyEncoding = "E_KEY_ENCODING",
194    /// In a `bad_request` envelope: a short id names more than one cell or object (16.8,
195    /// `spec-0.5.0`). A mesh's code.
196    ShortIdAmbiguous = "E_SHORT_ID_AMBIGUOUS",
197    /// A client's check of a describe answer failed (16.8, `spec-0.5.0`).
198    Describe = "E_DESCRIBE",
199}
200
201impl fmt::Display for ErrorCode {
202    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
203        f.write_str(self.as_str())
204    }
205}
206
207/// A failure: its code, the JSON path (or URI part) where it was found, and a human detail.
208#[derive(Clone, Debug, PartialEq, Eq)]
209pub struct Error {
210    code: ErrorCode,
211    path: String,
212    detail: String,
213}
214
215impl Error {
216    /// Builds an error. `path` is a JSONPath-like location such as `$.cell.args.base`.
217    pub fn new(code: ErrorCode, path: impl Into<String>, detail: impl Into<String>) -> Error {
218        Error { code, path: path.into(), detail: detail.into() }
219    }
220
221    /// The code of SPEC 10.2.
222    pub fn code(&self) -> ErrorCode {
223        self.code
224    }
225
226    /// The code as text, e.g. `"E_SIGNATURE"`.
227    pub fn code_str(&self) -> &'static str {
228        self.code.as_str()
229    }
230
231    /// Where the failure was found: `$` is the whole input, `$.a.b[0]` a member.
232    pub fn path(&self) -> &str {
233        &self.path
234    }
235
236    /// A human-readable explanation. Not stable; do not match on it.
237    pub fn detail(&self) -> &str {
238        &self.detail
239    }
240
241    /// The same failure reported under another code (e.g. wrapping as `E_KEY_DOC`).
242    pub(crate) fn recode(self, code: ErrorCode) -> Error {
243        let detail = if self.code == code { self.detail } else { format!("{}: {}", self.code, self.detail) };
244        Error { code, path: self.path, detail }
245    }
246}
247
248impl fmt::Display for Error {
249    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
250        write!(f, "{} at {}: {}", self.code, self.path, self.detail)
251    }
252}
253
254impl std::error::Error for Error {}
255
256/// Shorthand used throughout the crate.
257pub type Result<T> = core::result::Result<T, Error>;
258
259pub(crate) fn err<T>(code: ErrorCode, path: &str, detail: impl Into<String>) -> Result<T> {
260    Err(Error::new(code, path, detail))
261}
262
263/// Appends a member name to a path.
264pub(crate) fn member(path: &str, name: &str) -> String {
265    format!("{path}.{name}")
266}
267
268/// Appends an array index to a path.
269pub(crate) fn index(path: &str, i: usize) -> String {
270    format!("{path}[{i}]")
271}