Skip to main content

datumesh_core/
envelope.rs

1//! Response envelopes (5.5): the mesh's unsigned statement around a receipt.
2
3use crate::error::{err, ErrorCode, Result};
4use crate::json::{self, Value};
5use crate::keys::Keys;
6use crate::lexical::{self, limits};
7use crate::receipt::Receipt;
8use crate::schema;
9
10/// The eight outcomes of 5.5.
11#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
12pub enum Outcome {
13    /// 200: the receipt answers the cell as of the requested `asof`: its `asof` is at or
14    /// before the requested one, and the mesh asserts it is the cell's latest version known
15    /// as of then.
16    Ok,
17    /// 200: as `Ok`, except that the mesh cannot assert the receipt is current; it serves the
18    /// last receipt it knows.
19    Stale,
20    /// 404: no receipt for this cell. With a `fault` (`spec-0.4.0`, see
21    /// [`check_envelope_extras`]), the cell is a computed cell whose evaluation faulted.
22    NotCovered,
23    /// 403: the requester may not receive this cell.
24    Unlicensed,
25    /// 402: available for the quoted price.
26    PaymentRequired,
27    /// 429: too many requests.
28    RateLimited,
29    /// 400: the cell URI does not parse.
30    BadRequest,
31    /// 5xx: the mesh failed.
32    Error,
33}
34
35impl Outcome {
36    /// The outcome as written in JSON.
37    pub const fn as_str(self) -> &'static str {
38        match self {
39            Outcome::Ok => "ok",
40            Outcome::Stale => "stale",
41            Outcome::NotCovered => "not_covered",
42            Outcome::Unlicensed => "unlicensed",
43            Outcome::PaymentRequired => "payment_required",
44            Outcome::RateLimited => "rate_limited",
45            Outcome::BadRequest => "bad_request",
46            Outcome::Error => "error",
47        }
48    }
49}
50
51/// The mesh's trust label (5.5).
52#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
53pub enum Trust {
54    /// Signed by the namespace's host, with no inputs.
55    Primary,
56    /// The mesh says it recomputed the receipt.
57    Verified,
58    /// Neither.
59    Unverified,
60}
61
62impl Trust {
63    /// The label as written in JSON.
64    pub const fn as_str(self) -> &'static str {
65        match self {
66            Trust::Primary => "primary",
67            Trust::Verified => "verified",
68            Trust::Unverified => "unverified",
69        }
70    }
71}
72
73/// A formula evaluation fault (SPEC 5.5, 15.11; `spec-0.4.0`): the optional `fault` member
74/// of a `not_covered` envelope. The cell has no value, deterministically; this is not
75/// missing data. These are formula codes, not verification codes, so they are not
76/// [`ErrorCode`]s.
77#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
78#[non_exhaustive]
79pub enum Fault {
80    /// `E_FORMULA_DIV_ZERO`
81    DivZero,
82    /// `E_FORMULA_DOMAIN`
83    Domain,
84    /// `E_FORMULA_RANGE`
85    Range,
86    /// `E_FORMULA_EMPTY`
87    Empty,
88    /// `E_FORMULA_ABSENT`
89    Absent,
90    /// `E_FORMULA_FUTURE`
91    Future,
92    /// `E_FORMULA_KEY` (since `spec-0.5.0`): a computed key argument not canonical under its
93    /// normalisation (16.4).
94    Key,
95    /// `E_FORMULA_DISPATCH_KEY` (since `spec-0.5.0`): a value outside the dispatch set (16.6).
96    DispatchKey,
97    /// `E_WHATIF_NO_SOLUTION` (since `spec-0.6.0`, 5.9): a `whatif` request with `solve` found no
98    /// value of `vary` within its bounds and fuel. A request fault, not a formula fault.
99    WhatifNoSolution,
100}
101
102impl Fault {
103    /// Every fault an envelope may carry, in the order of SPEC 5.5.
104    pub const ALL: &'static [Fault] = &[
105        Fault::DivZero,
106        Fault::Domain,
107        Fault::Range,
108        Fault::Empty,
109        Fault::Absent,
110        Fault::Future,
111        Fault::Key,
112        Fault::DispatchKey,
113        Fault::WhatifNoSolution,
114    ];
115
116    /// The code as written, e.g. `"E_FORMULA_DIV_ZERO"`.
117    pub const fn as_str(self) -> &'static str {
118        match self {
119            Fault::DivZero => "E_FORMULA_DIV_ZERO",
120            Fault::Domain => "E_FORMULA_DOMAIN",
121            Fault::Range => "E_FORMULA_RANGE",
122            Fault::Empty => "E_FORMULA_EMPTY",
123            Fault::Absent => "E_FORMULA_ABSENT",
124            Fault::Future => "E_FORMULA_FUTURE",
125            Fault::Key => "E_FORMULA_KEY",
126            Fault::DispatchKey => "E_FORMULA_DISPATCH_KEY",
127            Fault::WhatifNoSolution => "E_WHATIF_NO_SOLUTION",
128        }
129    }
130
131    /// Looks a fault up by its code; `None` for any other text (a budget, a cycle or too deep
132    /// an evaluation is not a fault but the mesh's failure, SPEC 5.5).
133    pub fn from_code(text: &str) -> Option<Fault> {
134        Fault::ALL.iter().copied().find(|f| f.as_str() == text)
135    }
136}
137
138impl core::fmt::Display for Fault {
139    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
140        f.write_str(self.as_str())
141    }
142}
143
144/// What failed in reaching a foreign mesh (SPEC 5.5, `spec-0.4.3`): the `detail` member, required
145/// with `E_FOREIGN_UNAVAILABLE` ([`ErrorCode::ForeignUnavailable`]) and forbidden in every other
146/// envelope. The list is closed; it is non-exhaustive only so that later revisions can add to
147/// it.
148#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
149#[non_exhaustive]
150pub enum ForeignDetail {
151    /// `offline`: the asked party has no network, or is configured not to use it.
152    Offline,
153    /// `network`: any other network failure.
154    Network,
155    /// `dns`: the foreign host's name did not resolve.
156    Dns,
157    /// `tls`: the TLS handshake or the certificate failed.
158    Tls,
159    /// `timeout`.
160    Timeout,
161    /// `refused`: the connection was refused.
162    Refused,
163}
164
165impl ForeignDetail {
166    /// Every detail, in the order of SPEC 5.5.
167    pub const ALL: &'static [ForeignDetail] = &[
168        ForeignDetail::Offline,
169        ForeignDetail::Network,
170        ForeignDetail::Dns,
171        ForeignDetail::Tls,
172        ForeignDetail::Timeout,
173        ForeignDetail::Refused,
174    ];
175
176    /// The detail as written in JSON, e.g. `"offline"`.
177    pub const fn as_str(self) -> &'static str {
178        match self {
179            ForeignDetail::Offline => "offline",
180            ForeignDetail::Network => "network",
181            ForeignDetail::Dns => "dns",
182            ForeignDetail::Tls => "tls",
183            ForeignDetail::Timeout => "timeout",
184            ForeignDetail::Refused => "refused",
185        }
186    }
187
188    /// Looks a detail up by its JSON name; `None` for anything else (case included).
189    pub fn from_name(text: &str) -> Option<ForeignDetail> {
190        ForeignDetail::ALL.iter().copied().find(|d| d.as_str() == text)
191    }
192}
193
194impl core::fmt::Display for ForeignDetail {
195    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
196        f.write_str(self.as_str())
197    }
198}
199
200/// The members of a checked envelope that [`Envelope`] has no field for, because they were
201/// added to SPEC 5.5 after it was frozen (0.3.0): see [`check_envelope_extras`].
202#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
203#[non_exhaustive]
204pub struct EnvelopeExtras {
205    /// The formula evaluation fault of a `not_covered` envelope (`spec-0.4.0`).
206    pub fault: Option<Fault>,
207    /// The function the answer is of: the echo of a pin, or the hash the name resolved to
208    /// (`spec-0.4.2`).
209    pub fn_hash: Option<String>,
210    /// What failed in reaching a foreign mesh, with `E_FOREIGN_UNAVAILABLE` (`spec-0.4.3`).
211    pub detail: Option<ForeignDetail>,
212}
213
214/// The `kind` of one resolution of a short call (16.7, `spec-0.5.0`).
215#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
216#[non_exhaustive]
217pub enum ResolutionKind {
218    /// `alias`: a bare name resolved through the mesh's alias map.
219    Alias,
220    /// `default`: an unbound argument took its `"default": "asof"`.
221    Default,
222    /// `lookup`: a label resolved to a key through the class's `lookup` method; the resolution
223    /// carries `asof`, the instant the lookup cell was read as of.
224    Lookup,
225    /// `method`: a method call resolved to the method's function.
226    Method,
227    /// `chain` (5.8, 16.7, the classes round): a link of a chained request, `N(k).m(a).n(b)`: the method
228    /// after the first, called on the key the previous one returned. The resolution carries `asof`, the
229    /// instant the cell of the link was read as of, as a lookup does.
230    Chain,
231}
232
233impl ResolutionKind {
234    /// Every kind, in the order of 5.5: `alias`, `default`, `lookup`, `method`, then `chain`.
235    pub const ALL: &'static [ResolutionKind] = &[
236        ResolutionKind::Alias,
237        ResolutionKind::Default,
238        ResolutionKind::Lookup,
239        ResolutionKind::Method,
240        ResolutionKind::Chain,
241    ];
242
243    /// The kind as written: `alias`, `default`, `lookup`, `method` or `chain`.
244    pub const fn as_str(self) -> &'static str {
245        match self {
246            ResolutionKind::Alias => "alias",
247            ResolutionKind::Default => "default",
248            ResolutionKind::Lookup => "lookup",
249            ResolutionKind::Method => "method",
250            ResolutionKind::Chain => "chain",
251        }
252    }
253
254    /// Looks a kind up by its text; `None` for anything else.
255    pub fn from_name(text: &str) -> Option<ResolutionKind> {
256        ResolutionKind::ALL.iter().copied().find(|k| k.as_str() == text)
257    }
258}
259
260/// One entry of [`Resolved::resolutions`]: an object with exactly `from`, `kind` and `to`, all
261/// strings, and `asof` (an instant) exactly when the kind is `lookup` or `chain`.
262#[derive(Clone, Debug, PartialEq, Eq, Hash)]
263#[non_exhaustive]
264pub struct Resolution {
265    /// What was resolved: an alias, an argument name, a label, or `<class>(...).<method>`.
266    pub from: String,
267    /// The kind of resolution.
268    pub kind: ResolutionKind,
269    /// What it resolved to.
270    pub to: String,
271    /// The instant a `lookup` or `chain` cell was read as of; `Some` exactly for [`ResolutionKind::Lookup`]
272    /// and [`ResolutionKind::Chain`].
273    pub asof: Option<String>,
274}
275
276impl Resolution {
277    /// A resolution of any kind but `lookup` and `chain`; `E_ENVELOPE` for those (use
278    /// [`Resolution::lookup`] or [`Resolution::chain`], which need the `asof`).
279    pub fn new(from: &str, kind: ResolutionKind, to: &str) -> Result<Resolution> {
280        if matches!(kind, ResolutionKind::Lookup | ResolutionKind::Chain) {
281            return env_err("$.resolutions", "a lookup or chain resolution carries its asof");
282        }
283        Ok(Resolution { from: from.into(), kind, to: to.into(), asof: None })
284    }
285
286    /// A `lookup` resolution: the label, the key encoding it resolved to, and the instant its
287    /// lookup cell was read as of (`E_ENVELOPE` when `asof` is not an instant).
288    pub fn lookup(label: &str, key: &str, asof: &str) -> Result<Resolution> {
289        lexical::check_instant(asof, "$.resolutions.asof").map_err(|e| e.recode(ErrorCode::Envelope))?;
290        Ok(Resolution { from: label.into(), kind: ResolutionKind::Lookup, to: key.into(), asof: Some(asof.into()) })
291    }
292
293    /// A `chain` resolution (5.8, 16.7): the method as written, the key encoding the link read, and the
294    /// instant the link's cell was read as of (`E_ENVELOPE` when `asof` is not an instant).
295    pub fn chain(from: &str, to: &str, asof: &str) -> Result<Resolution> {
296        lexical::check_instant(asof, "$.resolutions.asof").map_err(|e| e.recode(ErrorCode::Envelope))?;
297        Ok(Resolution { from: from.into(), kind: ResolutionKind::Chain, to: to.into(), asof: Some(asof.into()) })
298    }
299}
300
301/// The `resolved` member of an envelope (5.5, 16.7, `spec-0.5.0`): what a short call resolved.
302/// Exactly `call`, `resolutions` and optionally `aliases_tx`.
303#[derive(Clone, Debug, PartialEq, Eq, Hash)]
304#[non_exhaustive]
305pub struct Resolved {
306    /// The full canonical call (16.7), a non-empty string.
307    pub call: String,
308    /// What was resolved, in the mesh's order.
309    pub resolutions: Vec<Resolution>,
310    /// The instant of the alias snapshot used.
311    pub aliases_tx: Option<String>,
312}
313
314impl Resolved {
315    /// `call` (non-empty) and its resolutions; `E_ENVELOPE` otherwise.
316    pub fn new(call: &str, resolutions: Vec<Resolution>) -> Result<Resolved> {
317        if call.is_empty() {
318            return env_err("$.resolved.call", "call is a non-empty string");
319        }
320        Ok(Resolved { call: call.into(), resolutions, aliases_tx: None })
321    }
322
323    /// With `aliases_tx`, the instant of the alias snapshot used (`E_ENVELOPE` when it is not
324    /// an instant).
325    pub fn with_aliases_tx(self, instant: &str) -> Result<Resolved> {
326        lexical::check_instant(instant, "$.resolved.aliases_tx").map_err(|e| e.recode(ErrorCode::Envelope))?;
327        Ok(Resolved { aliases_tx: Some(instant.into()), ..self })
328    }
329}
330
331/// The `shadows` member of an envelope (5.5, 16.9, `spec-0.5.0`): the class name this mesh
332/// binds to another hash than the reference class of that name.
333#[derive(Clone, Debug, PartialEq, Eq, Hash)]
334#[non_exhaustive]
335pub struct Shadows {
336    /// A full class name (2.3).
337    pub class: String,
338    /// The reference class's hash: 64 lowercase hex digits.
339    pub reference: String,
340}
341
342impl Shadows {
343    /// Builds `shadows`; `E_ENVELOPE` for a class that is not a full name or a reference that is
344    /// not 64 lowercase hex digits.
345    pub fn new(class: &str, reference: &str) -> Result<Shadows> {
346        lexical::check_function_name(class, "$.shadows.class").map_err(|e| e.recode(ErrorCode::Envelope))?;
347        lexical::check_hex(reference, 64, "$.shadows.reference").map_err(|e| e.recode(ErrorCode::Envelope))?;
348        Ok(Shadows { class: class.into(), reference: reference.into() })
349    }
350}
351
352/// A price quote (`payment_required`).
353#[derive(Clone, Debug, PartialEq, Eq, Hash)]
354pub struct Quote {
355    /// A canonical decimal greater than zero.
356    pub amount: String,
357    /// A currency code from `units.md`.
358    pub currency: String,
359    /// Where to pay: an https URL.
360    pub authorise: String,
361}
362
363/// The override array of a `whatif` request or scenario (5.9, `spec-0.6.0`). Held as a JSON value;
364/// equal and hashed by its canonical text (JCS), so that the request keeps its `Eq` and `Hash`
365/// and member order never matters.
366#[derive(Clone, Debug)]
367pub(crate) struct Overrides(pub(crate) Value);
368
369impl PartialEq for Overrides {
370    fn eq(&self, other: &Overrides) -> bool {
371        self.0.to_jcs() == other.0.to_jcs()
372    }
373}
374
375impl Eq for Overrides {}
376
377impl core::hash::Hash for Overrides {
378    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
379        self.0.to_jcs().hash(state);
380    }
381}
382
383/// What the client asked for, for the binding of 5.5 step 5.
384#[derive(Clone, Debug, PartialEq, Eq, Hash)]
385pub struct Request {
386    pub(crate) cell_id: String,
387    pub(crate) asof: Option<String>,
388    pub(crate) job: Option<String>,
389    pub(crate) pin: Option<String>,
390    pub(crate) mesh: Option<String>,
391    pub(crate) overrides: Option<Overrides>,
392    pub(crate) solve: Option<String>,
393}
394
395/// A malformed request description (5.5 step 5): the caller's mistake, not an `E_*` code.
396#[derive(Clone, Debug, PartialEq, Eq, Hash)]
397pub struct InvalidRequest(String);
398
399impl core::fmt::Display for InvalidRequest {
400    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
401        write!(f, "invalid request: {}", self.0)
402    }
403}
404
405impl std::error::Error for InvalidRequest {}
406
407impl Request {
408    /// A request for the cell with id `cell_id` (64 lowercase hex digits) as of `asof` (an
409    /// instant) or now. Anything else is [`InvalidRequest`]: SPEC 5.5 makes a malformed
410    /// request the caller's error, reported outside the `E_*` codes.
411    pub fn new(cell_id: &str, asof: Option<&str>) -> core::result::Result<Request, InvalidRequest> {
412        if lexical::check_hex(cell_id, 64, "").is_err() {
413            return Err(InvalidRequest(format!("cell_id must be 64 lowercase hex digits: {cell_id:?}")));
414        }
415        if let Some(a) = asof {
416            if !lexical::is_instant(a) {
417                return Err(InvalidRequest(format!("asof must be an instant: {a:?}")));
418            }
419        }
420        Ok(Request {
421            cell_id: cell_id.into(),
422            asof: asof.map(String::from),
423            job: None,
424            pin: None,
425            mesh: None,
426            overrides: None,
427            solve: None,
428        })
429    }
430
431    /// The request description for `GET` of a job's `poll` URL (5.5, `spec-0.4.1`): the
432    /// original request (`cell_id`, `asof`) and the job polled, 32 to 64 lowercase hex digits
433    /// (otherwise [`InvalidRequest`]). With it, an envelope may be `bad_request` with
434    /// `E_JOB_UNKNOWN`, and a `pending` one must carry this `job`; any other answer is bound
435    /// to the original request, as a `/cell` answer is.
436    pub fn with_job(cell_id: &str, asof: Option<&str>, job: &str) -> core::result::Result<Request, InvalidRequest> {
437        if !is_job(job) {
438            return Err(InvalidRequest(format!("job must be 32 to 64 lowercase hex digits: {job:?}")));
439        }
440        let mut r = Request::new(cell_id, asof)?;
441        r.job = Some(job.into());
442        Ok(r)
443    }
444
445    /// The same request, pinned to the function `fn_hash` (64 lowercase hex digits; otherwise
446    /// [`InvalidRequest`]): the answer must echo it (5.5, `spec-0.4.2`). `cell_id` is then the
447    /// id of the cell of that function.
448    pub fn with_pin(self, fn_hash: &str) -> core::result::Result<Request, InvalidRequest> {
449        if lexical::check_hex(fn_hash, 64, "").is_err() {
450            return Err(InvalidRequest(format!("fn_hash must be 64 lowercase hex digits: {fn_hash:?}")));
451        }
452        Ok(Request { pin: Some(fn_hash.into()), ..self })
453    }
454
455    /// The same request, naming the host it was sent to (a DNS name; otherwise
456    /// [`InvalidRequest`]): `computed` is then checked against the receipt's signer, and
457    /// `poll` against the host (5.5, `spec-0.4.2`). Without it those checks are the caller's.
458    pub fn with_mesh(self, host: &str) -> core::result::Result<Request, InvalidRequest> {
459        if lexical::check_dns_name(host, "").is_err() {
460            return Err(InvalidRequest(format!("mesh must be a DNS name: {host:?}")));
461        }
462        Ok(Request { mesh: Some(host.into()), ..self })
463    }
464
465    /// The same request as a `whatif` read (5.9, `spec-0.6.0`): `overrides` is the canonical
466    /// override array (at most 64 objects, otherwise [`InvalidRequest`]), and `solve`, when given,
467    /// the id of the cell to vary (64 lowercase hex digits). The answer is a scenario, checked
468    /// against these by [`crate::check_answer`].
469    pub fn with_whatif(self, overrides: &Value, solve: Option<&str>) -> core::result::Result<Request, InvalidRequest> {
470        let Value::Array(items) = overrides else {
471            return Err(InvalidRequest("overrides is an array of overrides".into()));
472        };
473        // 5.9: empty only with solve; at most 64, well formed, canonical order, distinct.
474        if items.is_empty() && solve.is_none() {
475            return Err(InvalidRequest("empty overrides need solve".into()));
476        }
477        crate::answer::check_overrides(overrides).map_err(|e| InvalidRequest(e.to_string()))?;
478        if let Some(v) = solve {
479            if lexical::check_hex(v, 64, "").is_err() {
480                return Err(InvalidRequest(format!("solve must be 64 lowercase hex digits: {v:?}")));
481            }
482        }
483        Ok(Request { overrides: Some(Overrides(overrides.clone())), solve: solve.map(String::from), ..self })
484    }
485
486    /// The overrides of a `whatif` request ([`Request::with_whatif`]).
487    pub fn overrides(&self) -> Option<&Value> {
488        self.overrides.as_ref().map(|o| &o.0)
489    }
490
491    /// The vary cell's id of a `whatif` request's `solve`, when it has one.
492    pub fn solve(&self) -> Option<&str> {
493        self.solve.as_deref()
494    }
495
496    /// The pin, for a pinned request ([`Request::with_pin`]).
497    pub fn fn_hash(&self) -> Option<&str> {
498        self.pin.as_deref()
499    }
500
501    /// The host the request was sent to, when given ([`Request::with_mesh`]).
502    pub fn mesh(&self) -> Option<&str> {
503        self.mesh.as_deref()
504    }
505
506    /// The job polled, for a request made at a job URL ([`Request::with_job`]).
507    pub fn job(&self) -> Option<&str> {
508        self.job.as_deref()
509    }
510
511    /// The requested cell id.
512    pub fn cell_id(&self) -> &str {
513        &self.cell_id
514    }
515
516    /// The requested `asof`, if any.
517    pub fn asof(&self) -> Option<&str> {
518        self.asof.as_deref()
519    }
520}
521
522/// A checked envelope.
523#[derive(Clone, Debug, PartialEq, Eq)]
524pub struct Envelope {
525    /// The outcome.
526    pub outcome: Outcome,
527    /// The receipt (`ok`, `stale`), signature-valid and bound to the request.
528    pub receipt: Option<Receipt>,
529    /// The trust label (`ok`, `stale`).
530    pub trust: Option<Trust>,
531    /// Seconds since the mesh last confirmed the receipt (`stale`).
532    pub age_seconds: Option<u64>,
533    /// Hash of a newer receipt for the same cell.
534    pub superseded_by: Option<String>,
535    /// Why the receipt was superseded.
536    pub reason: Option<String>,
537    /// The quote (`payment_required`).
538    pub quote: Option<Quote>,
539    /// Seconds to wait (`rate_limited`).
540    pub retry_after_seconds: Option<u64>,
541    /// The failure code (`bad_request`, `error`).
542    pub error: Option<ErrorCode>,
543}
544
545pub(crate) const BAD_REQUEST_CODES: [ErrorCode; 15] = [
546    ErrorCode::ParseUri,
547    ErrorCode::CanonName,
548    ErrorCode::CanonArgName,
549    ErrorCode::CanonArgDuplicate,
550    ErrorCode::CanonArgOrder,
551    ErrorCode::CanonPercent,
552    ErrorCode::CanonType,
553    ErrorCode::CanonNumber,
554    ErrorCode::CanonDate,
555    ErrorCode::CanonInstant,
556    ErrorCode::CanonString,
557    ErrorCode::CanonBlob,
558    ErrorCode::CanonLimit,
559    ErrorCode::ArgUnknown,
560    ErrorCode::ArgMissing,
561];
562
563pub(crate) fn env_err<T>(path: &str, detail: impl Into<String>) -> Result<T> {
564    err(ErrorCode::Envelope, path, detail)
565}
566
567/// `0` or `[1-9][0-9]*`, at most 2^53 - 1, judged on the number's text.
568pub(crate) fn integer_member(v: &Value, path: &str) -> Result<u64> {
569    let Some(t) = v.as_number_text() else {
570        return env_err(path, "must be a non-negative integer");
571    };
572    let ok =
573        !t.is_empty() && t.bytes().all(|c| c.is_ascii_digit()) && (t == "0" || !t.starts_with('0')) && t.len() <= 16;
574    match (ok, t.parse::<u64>()) {
575        (true, Ok(x)) if x <= limits::BLOB_LENGTH => Ok(x),
576        _ => env_err(path, format!("must be written 0|[1-9][0-9]* and at most 2^53 - 1, not {t}")),
577    }
578}
579
580/// Checks a response envelope (5.5) in the order of its procedure: strict JSON, members,
581/// HTTP status, the receipt through step 6 of 10.1, the binding to `request`, then `trust`
582/// and `superseded_by`. Never touches the network. A `not_covered` envelope's `fault`
583/// (`spec-0.4.0`) is checked and accepted; [`check_envelope_extras`] also returns it.
584///
585/// Since `spec-0.6.0` this function refuses what it has no field for, as it refuses any unknown
586/// value: a receipt with `source` and the trust `relayed`, the outcome `scenario` (a `whatif`
587/// request's answer), and a `cycle` member. Read those through [`crate::check_answer`]
588/// (`TrustLabel::Relayed`, `AnswerOutcome::Scenario`, [`crate::Cycle`]).
589pub fn check_envelope(status: u16, body: &[u8], keys: &Keys, request: &Request) -> Result<Envelope> {
590    check_envelope_extras(status, body, keys, request).map(|(env, _)| env)
591}
592
593/// [`check_envelope`], also returning the members [`Envelope`] has no field for
594/// ([`EnvelopeExtras`]): the `fault` of a `not_covered` envelope, one of the six formula
595/// evaluation faults of SPEC 5.5 (`E_ENVELOPE` for any other value, or on another outcome).
596///
597/// Its [`Envelope`] has no `pending` outcome, so a `pending` envelope is `E_ENVELOPE` here, as
598/// in 0.3.4; [`check_envelope_any`] accepts it. Nor has its [`Trust`] `computed` (`spec-0.4.2`):
599/// an envelope with it is `E_ENVELOPE` here and in [`check_envelope_any`], as in 0.3.5;
600/// [`crate::check_answer`] accepts it. Everything else of `spec-0.4.2` (the `fn_hash` echo, in
601/// [`EnvelopeExtras`]; `not_covered`'s `error`; the new codes) is checked as there, and so is
602/// `spec-0.4.3`'s `E_FOREIGN_UNAVAILABLE` (502, with its `detail` in [`EnvelopeExtras`]).
603pub fn check_envelope_extras(
604    status: u16,
605    body: &[u8],
606    keys: &Keys,
607    request: &Request,
608) -> Result<(Envelope, EnvelopeExtras)> {
609    crate::answer::check_answer(status, body, keys, request)?.into_envelope()
610}
611
612/// Checks a response envelope (5.5) of any of the nine outcomes, `pending` included
613/// (`spec-0.4.1`), in the order of its procedure, and binds it to `request`: a `pending`
614/// envelope's echoed request to the request made (and its `job` to the job polled, when
615/// `request` has one), any other outcome to the original request's cell id and `asof`,
616/// whether it answers the `/cell` request or the job URL. `E_JOB_UNKNOWN` is accepted only in a
617/// `bad_request` answering a job URL (`request` with a job). Never touches the network.
618pub fn check_envelope_any(status: u16, body: &[u8], keys: &Keys, request: &Request) -> Result<AnyEnvelope> {
619    let a = crate::answer::check_answer(status, body, keys, request)?;
620    if let Some(p) = a.pending {
621        return Ok(AnyEnvelope::Pending(p));
622    }
623    a.into_envelope().map(|(e, x)| AnyEnvelope::Envelope(e, x))
624}
625
626/// `[0-9a-f]{32,64}`.
627pub(crate) fn is_job(s: &str) -> bool {
628    (32..=64).contains(&s.len()) && s.bytes().all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c))
629}
630
631/// The answer to a request: a [`Pending`] envelope, or one of the eight outcomes an
632/// [`Envelope`] holds, with its [`EnvelopeExtras`] (see [`check_envelope_any`]).
633// Not boxed: one value per checked response, and matching on it stays plain.
634#[allow(clippy::large_enum_variant)]
635#[derive(Clone, Debug, PartialEq, Eq)]
636#[non_exhaustive]
637pub enum AnyEnvelope {
638    /// `ok`, `stale`, `not_covered`, `unlicensed`, `payment_required`, `rate_limited`,
639    /// `bad_request` or `error`.
640    Envelope(Envelope, EnvelopeExtras),
641    /// `pending` (202): the mesh is still computing; the answer will be at `poll`.
642    Pending(Pending),
643}
644
645impl AnyEnvelope {
646    /// The outcome as written in JSON, `"pending"` included.
647    pub fn outcome_str(&self) -> &'static str {
648        match self {
649            AnyEnvelope::Envelope(e, _) => e.outcome.as_str(),
650            AnyEnvelope::Pending(_) => "pending",
651        }
652    }
653}
654
655/// A `pending` envelope (5.5, `spec-0.4.1`): the job, an estimate, the URL to poll and the
656/// original request echoed. Build one with [`Pending::new`] (a mesh), or get one from
657/// [`check_envelope_any`] (a client).
658#[derive(Clone, Debug, PartialEq, Eq, Hash)]
659#[non_exhaustive]
660pub struct Pending {
661    /// The job id: 32 to 64 lowercase hex digits, a capability.
662    pub job: String,
663    /// The mesh's estimate of the seconds until the result is ready; a hint.
664    pub estimate_seconds: u64,
665    /// The job's URL: `https://` and printable ASCII, at most 512 characters, ending
666    /// `/jobs/<job>`.
667    pub poll: String,
668    /// The original request, echoed: its `cell_id`, `asof` and pin (never a job or a mesh).
669    pub request: Request,
670}
671
672impl Pending {
673    /// The HTTP status of a `pending` envelope.
674    pub const STATUS: u16 = 202;
675
676    /// A `pending` envelope answering `request` (its `cell_id`, `asof` and pin are echoed; a
677    /// job or mesh in it is not), checked by the rules of 5.5: `job` 32 to 64 lowercase hex digits,
678    /// `estimate_seconds` at most 2^53 - 1, `poll` an `https://` URL of printable ASCII of at
679    /// most 512 characters whose host (up to the first `/`) is a DNS name (2.1), ending
680    /// `/jobs/<job>`. That `poll` names the mesh's own host is the caller's to ensure. A failure
681    /// is `E_ENVELOPE`, at the member's path.
682    pub fn new(job: &str, estimate_seconds: u64, poll: &str, request: Request) -> Result<Pending> {
683        check_job_and_poll_for(job, poll, request.mesh())?;
684        if estimate_seconds > limits::BLOB_LENGTH {
685            return env_err("$.estimate_seconds", "estimate_seconds is at most 2^53 - 1");
686        }
687        let request = Request { job: None, mesh: None, ..request };
688        Ok(Pending { job: job.into(), estimate_seconds, poll: poll.into(), request })
689    }
690
691    /// The JSON form of the envelope.
692    pub fn to_value(&self) -> Value {
693        // Value has no public number constructor: the canonical text, parsed.
694        json::parse(&self.to_json()).unwrap_or(Value::Null)
695    }
696
697    /// The envelope's body: its canonical JSON text (JCS), served with [`Pending::STATUS`].
698    pub fn to_json(&self) -> Vec<u8> {
699        let mut out = String::new();
700        out.push_str("{\"estimate_seconds\":");
701        out.push_str(&self.estimate_seconds.to_string());
702        out.push_str(",\"job\":");
703        json::write_string(&self.job, &mut out);
704        out.push_str(",\"outcome\":\"pending\",\"poll\":");
705        json::write_string(&self.poll, &mut out);
706        out.push_str(",\"request\":{");
707        if let Some(a) = &self.request.asof {
708            out.push_str("\"asof\":");
709            json::write_string(a, &mut out);
710            out.push(',');
711        }
712        out.push_str("\"cell_id\":");
713        json::write_string(&self.request.cell_id, &mut out);
714        if let Some(p) = &self.request.pin {
715            out.push_str(",\"fn_hash\":");
716            json::write_string(p, &mut out);
717        }
718        out.push_str("}}");
719        out.into_bytes()
720    }
721}
722
723/// Checks a job id and its `poll` URL (5.5). A request sent to `mesh` (`spec-0.5.0`) may have a
724/// loopback `poll` (9.6) only when `mesh` names an unrooted host.
725pub(crate) fn check_job_and_poll_for(job: &str, poll: &str, mesh: Option<&str>) -> Result<()> {
726    if !is_job(job) {
727        return env_err("$.job", "job is 32 to 64 lowercase hex digits");
728    }
729    if poll.starts_with("http://") {
730        if !mesh.is_some_and(lexical::is_unrooted) {
731            return env_err("$.poll", "a loopback poll is only for an unrooted mesh the request names");
732        }
733        if lexical::loopback_origin(poll).is_none() || !poll.ends_with(&format!("/jobs/{job}")) {
734            return env_err("$.poll", "poll is a loopback URL ending /jobs/<job>");
735        }
736        return Ok(());
737    }
738    let url_ok =
739        poll.strip_prefix("https://").is_some_and(|r| !r.is_empty() && r.bytes().all(|c| (0x21..=0x7E).contains(&c)))
740            && poll.len() <= limits::LICENCE_URL;
741    if !url_ok {
742        return env_err("$.poll", "poll is an https URL of printable ASCII, at most 512 characters");
743    }
744    // The text between https:// and the next / is a DNS name (2.1; 3f79313).
745    let host = poll["https://".len()..].split('/').next().unwrap_or("");
746    if !poll["https://".len()..].contains('/') || lexical::check_dns_name(host, "").is_err() {
747        return env_err("$.poll", "poll's host is a DNS name");
748    }
749    if !poll.ends_with(&format!("/jobs/{job}")) {
750        return env_err("$.poll", "poll ends /jobs/<job>");
751    }
752    Ok(())
753}
754
755pub(crate) fn quote(q: &Value) -> Result<Quote> {
756    let m = schema::object_or(q, "$.quote", ErrorCode::Envelope, "quote")?;
757    schema::exact(m, &["amount", "authorise", "currency"], &[], "$.quote", ErrorCode::Envelope)?;
758    let amount = schema::string_or(m, "amount", "$.quote", ErrorCode::Envelope)?;
759    let authorise = schema::string_or(m, "authorise", "$.quote", ErrorCode::Envelope)?;
760    let currency = schema::string_or(m, "currency", "$.quote", ErrorCode::Envelope)?;
761    if lexical::check_number(amount, "").is_err() || amount.starts_with('-') || amount == "0" {
762        return env_err("$.quote.amount", "amount is a canonical decimal greater than zero");
763    }
764    let url_ok = authorise
765        .strip_prefix("https://")
766        .is_some_and(|r| !r.is_empty() && r.bytes().all(|c| (0x21..=0x7E).contains(&c)))
767        && authorise.len() <= limits::LICENCE_URL;
768    if !url_ok {
769        return env_err("$.quote.authorise", "authorise is an https URL");
770    }
771    if !lexical::is_currency(currency) {
772        return env_err("$.quote.currency", "currency is a currency code from units.md");
773    }
774    Ok(Quote { amount: amount.into(), currency: currency.into(), authorise: authorise.into() })
775}