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