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