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}
228
229impl ResolutionKind {
230    /// Every kind, in the order of 5.5: `alias`, `default`, `lookup`, `method`.
231    pub const ALL: &'static [ResolutionKind] =
232        &[ResolutionKind::Alias, ResolutionKind::Default, ResolutionKind::Lookup, ResolutionKind::Method];
233
234    /// The kind as written: `alias`, `default`, `lookup` or `method`.
235    pub const fn as_str(self) -> &'static str {
236        match self {
237            ResolutionKind::Alias => "alias",
238            ResolutionKind::Default => "default",
239            ResolutionKind::Lookup => "lookup",
240            ResolutionKind::Method => "method",
241        }
242    }
243
244    /// Looks a kind up by its text; `None` for anything else.
245    pub fn from_name(text: &str) -> Option<ResolutionKind> {
246        ResolutionKind::ALL.iter().copied().find(|k| k.as_str() == text)
247    }
248}
249
250/// One entry of [`Resolved::resolutions`]: an object with exactly `from`, `kind` and `to`, all
251/// strings, and `asof` (an instant) exactly when the kind is `lookup`.
252#[derive(Clone, Debug, PartialEq, Eq, Hash)]
253#[non_exhaustive]
254pub struct Resolution {
255    /// What was resolved: an alias, an argument name, a label, or `<class>(...).<method>`.
256    pub from: String,
257    /// The kind of resolution.
258    pub kind: ResolutionKind,
259    /// What it resolved to.
260    pub to: String,
261    /// The instant a `lookup` cell was read as of; `Some` exactly for [`ResolutionKind::Lookup`].
262    pub asof: Option<String>,
263}
264
265impl Resolution {
266    /// A resolution of any kind but `lookup`; `E_ENVELOPE` for `lookup` (use
267    /// [`Resolution::lookup`], which needs the `asof`).
268    pub fn new(from: &str, kind: ResolutionKind, to: &str) -> Result<Resolution> {
269        if kind == ResolutionKind::Lookup {
270            return env_err("$.resolutions", "a lookup resolution carries its asof: Resolution::lookup");
271        }
272        Ok(Resolution { from: from.into(), kind, to: to.into(), asof: None })
273    }
274
275    /// A `lookup` resolution: the label, the key encoding it resolved to, and the instant its
276    /// lookup cell was read as of (`E_ENVELOPE` when `asof` is not an instant).
277    pub fn lookup(label: &str, key: &str, asof: &str) -> Result<Resolution> {
278        lexical::check_instant(asof, "$.resolutions.asof").map_err(|e| e.recode(ErrorCode::Envelope))?;
279        Ok(Resolution { from: label.into(), kind: ResolutionKind::Lookup, to: key.into(), asof: Some(asof.into()) })
280    }
281}
282
283/// The `resolved` member of an envelope (5.5, 16.7, `spec-0.5.0`): what a short call resolved.
284/// Exactly `call`, `resolutions` and optionally `aliases_tx`.
285#[derive(Clone, Debug, PartialEq, Eq, Hash)]
286#[non_exhaustive]
287pub struct Resolved {
288    /// The full canonical call (16.7), a non-empty string.
289    pub call: String,
290    /// What was resolved, in the mesh's order.
291    pub resolutions: Vec<Resolution>,
292    /// The instant of the alias snapshot used.
293    pub aliases_tx: Option<String>,
294}
295
296impl Resolved {
297    /// `call` (non-empty) and its resolutions; `E_ENVELOPE` otherwise.
298    pub fn new(call: &str, resolutions: Vec<Resolution>) -> Result<Resolved> {
299        if call.is_empty() {
300            return env_err("$.resolved.call", "call is a non-empty string");
301        }
302        Ok(Resolved { call: call.into(), resolutions, aliases_tx: None })
303    }
304
305    /// With `aliases_tx`, the instant of the alias snapshot used (`E_ENVELOPE` when it is not
306    /// an instant).
307    pub fn with_aliases_tx(self, instant: &str) -> Result<Resolved> {
308        lexical::check_instant(instant, "$.resolved.aliases_tx").map_err(|e| e.recode(ErrorCode::Envelope))?;
309        Ok(Resolved { aliases_tx: Some(instant.into()), ..self })
310    }
311}
312
313/// The `shadows` member of an envelope (5.5, 16.9, `spec-0.5.0`): the class name this mesh
314/// binds to another hash than the reference class of that name.
315#[derive(Clone, Debug, PartialEq, Eq, Hash)]
316#[non_exhaustive]
317pub struct Shadows {
318    /// A full class name (2.3).
319    pub class: String,
320    /// The reference class's hash: 64 lowercase hex digits.
321    pub reference: String,
322}
323
324impl Shadows {
325    /// Builds `shadows`; `E_ENVELOPE` for a class that is not a full name or a reference that is
326    /// not 64 lowercase hex digits.
327    pub fn new(class: &str, reference: &str) -> Result<Shadows> {
328        lexical::check_function_name(class, "$.shadows.class").map_err(|e| e.recode(ErrorCode::Envelope))?;
329        lexical::check_hex(reference, 64, "$.shadows.reference").map_err(|e| e.recode(ErrorCode::Envelope))?;
330        Ok(Shadows { class: class.into(), reference: reference.into() })
331    }
332}
333
334/// A price quote (`payment_required`).
335#[derive(Clone, Debug, PartialEq, Eq, Hash)]
336pub struct Quote {
337    /// A canonical decimal greater than zero.
338    pub amount: String,
339    /// A currency code from `units.md`.
340    pub currency: String,
341    /// Where to pay: an https URL.
342    pub authorise: String,
343}
344
345/// The override array of a `whatif` request or scenario (5.9, `spec-0.6.0`). Held as a JSON value;
346/// equal and hashed by its canonical text (JCS), so that the request keeps its `Eq` and `Hash`
347/// and member order never matters.
348#[derive(Clone, Debug)]
349pub(crate) struct Overrides(pub(crate) Value);
350
351impl PartialEq for Overrides {
352    fn eq(&self, other: &Overrides) -> bool {
353        self.0.to_jcs() == other.0.to_jcs()
354    }
355}
356
357impl Eq for Overrides {}
358
359impl core::hash::Hash for Overrides {
360    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
361        self.0.to_jcs().hash(state);
362    }
363}
364
365/// What the client asked for, for the binding of 5.5 step 5.
366#[derive(Clone, Debug, PartialEq, Eq, Hash)]
367pub struct Request {
368    pub(crate) cell_id: String,
369    pub(crate) asof: Option<String>,
370    pub(crate) job: Option<String>,
371    pub(crate) pin: Option<String>,
372    pub(crate) mesh: Option<String>,
373    pub(crate) overrides: Option<Overrides>,
374    pub(crate) solve: Option<String>,
375}
376
377/// A malformed request description (5.5 step 5): the caller's mistake, not an `E_*` code.
378#[derive(Clone, Debug, PartialEq, Eq, Hash)]
379pub struct InvalidRequest(String);
380
381impl core::fmt::Display for InvalidRequest {
382    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
383        write!(f, "invalid request: {}", self.0)
384    }
385}
386
387impl std::error::Error for InvalidRequest {}
388
389impl Request {
390    /// A request for the cell with id `cell_id` (64 lowercase hex digits) as of `asof` (an
391    /// instant) or now. Anything else is [`InvalidRequest`]: SPEC 5.5 makes a malformed
392    /// request the caller's error, reported outside the `E_*` codes.
393    pub fn new(cell_id: &str, asof: Option<&str>) -> core::result::Result<Request, InvalidRequest> {
394        if lexical::check_hex(cell_id, 64, "").is_err() {
395            return Err(InvalidRequest(format!("cell_id must be 64 lowercase hex digits: {cell_id:?}")));
396        }
397        if let Some(a) = asof {
398            if !lexical::is_instant(a) {
399                return Err(InvalidRequest(format!("asof must be an instant: {a:?}")));
400            }
401        }
402        Ok(Request {
403            cell_id: cell_id.into(),
404            asof: asof.map(String::from),
405            job: None,
406            pin: None,
407            mesh: None,
408            overrides: None,
409            solve: None,
410        })
411    }
412
413    /// The request description for `GET` of a job's `poll` URL (5.5, `spec-0.4.1`): the
414    /// original request (`cell_id`, `asof`) and the job polled, 32 to 64 lowercase hex digits
415    /// (otherwise [`InvalidRequest`]). With it, an envelope may be `bad_request` with
416    /// `E_JOB_UNKNOWN`, and a `pending` one must carry this `job`; any other answer is bound
417    /// to the original request, as a `/cell` answer is.
418    pub fn with_job(cell_id: &str, asof: Option<&str>, job: &str) -> core::result::Result<Request, InvalidRequest> {
419        if !is_job(job) {
420            return Err(InvalidRequest(format!("job must be 32 to 64 lowercase hex digits: {job:?}")));
421        }
422        let mut r = Request::new(cell_id, asof)?;
423        r.job = Some(job.into());
424        Ok(r)
425    }
426
427    /// The same request, pinned to the function `fn_hash` (64 lowercase hex digits; otherwise
428    /// [`InvalidRequest`]): the answer must echo it (5.5, `spec-0.4.2`). `cell_id` is then the
429    /// id of the cell of that function.
430    pub fn with_pin(self, fn_hash: &str) -> core::result::Result<Request, InvalidRequest> {
431        if lexical::check_hex(fn_hash, 64, "").is_err() {
432            return Err(InvalidRequest(format!("fn_hash must be 64 lowercase hex digits: {fn_hash:?}")));
433        }
434        Ok(Request { pin: Some(fn_hash.into()), ..self })
435    }
436
437    /// The same request, naming the host it was sent to (a DNS name; otherwise
438    /// [`InvalidRequest`]): `computed` is then checked against the receipt's signer, and
439    /// `poll` against the host (5.5, `spec-0.4.2`). Without it those checks are the caller's.
440    pub fn with_mesh(self, host: &str) -> core::result::Result<Request, InvalidRequest> {
441        if lexical::check_dns_name(host, "").is_err() {
442            return Err(InvalidRequest(format!("mesh must be a DNS name: {host:?}")));
443        }
444        Ok(Request { mesh: Some(host.into()), ..self })
445    }
446
447    /// The same request as a `whatif` read (5.9, `spec-0.6.0`): `overrides` is the canonical
448    /// override array (at most 64 objects, otherwise [`InvalidRequest`]), and `solve`, when given,
449    /// the id of the cell to vary (64 lowercase hex digits). The answer is a scenario, checked
450    /// against these by [`crate::check_answer`].
451    pub fn with_whatif(self, overrides: &Value, solve: Option<&str>) -> core::result::Result<Request, InvalidRequest> {
452        let Value::Array(items) = overrides else {
453            return Err(InvalidRequest("overrides is an array of overrides".into()));
454        };
455        // 5.9: empty only with solve; at most 64, well formed, canonical order, distinct.
456        if items.is_empty() && solve.is_none() {
457            return Err(InvalidRequest("empty overrides need solve".into()));
458        }
459        crate::answer::check_overrides(overrides).map_err(|e| InvalidRequest(e.to_string()))?;
460        if let Some(v) = solve {
461            if lexical::check_hex(v, 64, "").is_err() {
462                return Err(InvalidRequest(format!("solve must be 64 lowercase hex digits: {v:?}")));
463            }
464        }
465        Ok(Request { overrides: Some(Overrides(overrides.clone())), solve: solve.map(String::from), ..self })
466    }
467
468    /// The overrides of a `whatif` request ([`Request::with_whatif`]).
469    pub fn overrides(&self) -> Option<&Value> {
470        self.overrides.as_ref().map(|o| &o.0)
471    }
472
473    /// The vary cell's id of a `whatif` request's `solve`, when it has one.
474    pub fn solve(&self) -> Option<&str> {
475        self.solve.as_deref()
476    }
477
478    /// The pin, for a pinned request ([`Request::with_pin`]).
479    pub fn fn_hash(&self) -> Option<&str> {
480        self.pin.as_deref()
481    }
482
483    /// The host the request was sent to, when given ([`Request::with_mesh`]).
484    pub fn mesh(&self) -> Option<&str> {
485        self.mesh.as_deref()
486    }
487
488    /// The job polled, for a request made at a job URL ([`Request::with_job`]).
489    pub fn job(&self) -> Option<&str> {
490        self.job.as_deref()
491    }
492
493    /// The requested cell id.
494    pub fn cell_id(&self) -> &str {
495        &self.cell_id
496    }
497
498    /// The requested `asof`, if any.
499    pub fn asof(&self) -> Option<&str> {
500        self.asof.as_deref()
501    }
502}
503
504/// A checked envelope.
505#[derive(Clone, Debug, PartialEq, Eq)]
506pub struct Envelope {
507    /// The outcome.
508    pub outcome: Outcome,
509    /// The receipt (`ok`, `stale`), signature-valid and bound to the request.
510    pub receipt: Option<Receipt>,
511    /// The trust label (`ok`, `stale`).
512    pub trust: Option<Trust>,
513    /// Seconds since the mesh last confirmed the receipt (`stale`).
514    pub age_seconds: Option<u64>,
515    /// Hash of a newer receipt for the same cell.
516    pub superseded_by: Option<String>,
517    /// Why the receipt was superseded.
518    pub reason: Option<String>,
519    /// The quote (`payment_required`).
520    pub quote: Option<Quote>,
521    /// Seconds to wait (`rate_limited`).
522    pub retry_after_seconds: Option<u64>,
523    /// The failure code (`bad_request`, `error`).
524    pub error: Option<ErrorCode>,
525}
526
527pub(crate) const BAD_REQUEST_CODES: [ErrorCode; 15] = [
528    ErrorCode::ParseUri,
529    ErrorCode::CanonName,
530    ErrorCode::CanonArgName,
531    ErrorCode::CanonArgDuplicate,
532    ErrorCode::CanonArgOrder,
533    ErrorCode::CanonPercent,
534    ErrorCode::CanonType,
535    ErrorCode::CanonNumber,
536    ErrorCode::CanonDate,
537    ErrorCode::CanonInstant,
538    ErrorCode::CanonString,
539    ErrorCode::CanonBlob,
540    ErrorCode::CanonLimit,
541    ErrorCode::ArgUnknown,
542    ErrorCode::ArgMissing,
543];
544
545pub(crate) fn env_err<T>(path: &str, detail: impl Into<String>) -> Result<T> {
546    err(ErrorCode::Envelope, path, detail)
547}
548
549/// `0` or `[1-9][0-9]*`, at most 2^53 - 1, judged on the number's text.
550pub(crate) fn integer_member(v: &Value, path: &str) -> Result<u64> {
551    let Some(t) = v.as_number_text() else {
552        return env_err(path, "must be a non-negative integer");
553    };
554    let ok =
555        !t.is_empty() && t.bytes().all(|c| c.is_ascii_digit()) && (t == "0" || !t.starts_with('0')) && t.len() <= 16;
556    match (ok, t.parse::<u64>()) {
557        (true, Ok(x)) if x <= limits::BLOB_LENGTH => Ok(x),
558        _ => env_err(path, format!("must be written 0|[1-9][0-9]* and at most 2^53 - 1, not {t}")),
559    }
560}
561
562/// Checks a response envelope (5.5) in the order of its procedure: strict JSON, members,
563/// HTTP status, the receipt through step 6 of 10.1, the binding to `request`, then `trust`
564/// and `superseded_by`. Never touches the network. A `not_covered` envelope's `fault`
565/// (`spec-0.4.0`) is checked and accepted; [`check_envelope_extras`] also returns it.
566///
567/// Since `spec-0.6.0` this function refuses what it has no field for, as it refuses any unknown
568/// value: a receipt with `source` and the trust `relayed`, the outcome `scenario` (a `whatif`
569/// request's answer), and a `cycle` member. Read those through [`crate::check_answer`]
570/// (`TrustLabel::Relayed`, `AnswerOutcome::Scenario`, [`crate::Cycle`]).
571pub fn check_envelope(status: u16, body: &[u8], keys: &Keys, request: &Request) -> Result<Envelope> {
572    check_envelope_extras(status, body, keys, request).map(|(env, _)| env)
573}
574
575/// [`check_envelope`], also returning the members [`Envelope`] has no field for
576/// ([`EnvelopeExtras`]): the `fault` of a `not_covered` envelope, one of the six formula
577/// evaluation faults of SPEC 5.5 (`E_ENVELOPE` for any other value, or on another outcome).
578///
579/// Its [`Envelope`] has no `pending` outcome, so a `pending` envelope is `E_ENVELOPE` here, as
580/// in 0.3.4; [`check_envelope_any`] accepts it. Nor has its [`Trust`] `computed` (`spec-0.4.2`):
581/// an envelope with it is `E_ENVELOPE` here and in [`check_envelope_any`], as in 0.3.5;
582/// [`crate::check_answer`] accepts it. Everything else of `spec-0.4.2` (the `fn_hash` echo, in
583/// [`EnvelopeExtras`]; `not_covered`'s `error`; the new codes) is checked as there, and so is
584/// `spec-0.4.3`'s `E_FOREIGN_UNAVAILABLE` (502, with its `detail` in [`EnvelopeExtras`]).
585pub fn check_envelope_extras(
586    status: u16,
587    body: &[u8],
588    keys: &Keys,
589    request: &Request,
590) -> Result<(Envelope, EnvelopeExtras)> {
591    crate::answer::check_answer(status, body, keys, request)?.into_envelope()
592}
593
594/// Checks a response envelope (5.5) of any of the nine outcomes, `pending` included
595/// (`spec-0.4.1`), in the order of its procedure, and binds it to `request`: a `pending`
596/// envelope's echoed request to the request made (and its `job` to the job polled, when
597/// `request` has one), any other outcome to the original request's cell id and `asof`,
598/// whether it answers the `/cell` request or the job URL. `E_JOB_UNKNOWN` is accepted only in a
599/// `bad_request` answering a job URL (`request` with a job). Never touches the network.
600pub fn check_envelope_any(status: u16, body: &[u8], keys: &Keys, request: &Request) -> Result<AnyEnvelope> {
601    let a = crate::answer::check_answer(status, body, keys, request)?;
602    if let Some(p) = a.pending {
603        return Ok(AnyEnvelope::Pending(p));
604    }
605    a.into_envelope().map(|(e, x)| AnyEnvelope::Envelope(e, x))
606}
607
608/// `[0-9a-f]{32,64}`.
609pub(crate) fn is_job(s: &str) -> bool {
610    (32..=64).contains(&s.len()) && s.bytes().all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c))
611}
612
613/// The answer to a request: a [`Pending`] envelope, or one of the eight outcomes an
614/// [`Envelope`] holds, with its [`EnvelopeExtras`] (see [`check_envelope_any`]).
615// Not boxed: one value per checked response, and matching on it stays plain.
616#[allow(clippy::large_enum_variant)]
617#[derive(Clone, Debug, PartialEq, Eq)]
618#[non_exhaustive]
619pub enum AnyEnvelope {
620    /// `ok`, `stale`, `not_covered`, `unlicensed`, `payment_required`, `rate_limited`,
621    /// `bad_request` or `error`.
622    Envelope(Envelope, EnvelopeExtras),
623    /// `pending` (202): the mesh is still computing; the answer will be at `poll`.
624    Pending(Pending),
625}
626
627impl AnyEnvelope {
628    /// The outcome as written in JSON, `"pending"` included.
629    pub fn outcome_str(&self) -> &'static str {
630        match self {
631            AnyEnvelope::Envelope(e, _) => e.outcome.as_str(),
632            AnyEnvelope::Pending(_) => "pending",
633        }
634    }
635}
636
637/// A `pending` envelope (5.5, `spec-0.4.1`): the job, an estimate, the URL to poll and the
638/// original request echoed. Build one with [`Pending::new`] (a mesh), or get one from
639/// [`check_envelope_any`] (a client).
640#[derive(Clone, Debug, PartialEq, Eq, Hash)]
641#[non_exhaustive]
642pub struct Pending {
643    /// The job id: 32 to 64 lowercase hex digits, a capability.
644    pub job: String,
645    /// The mesh's estimate of the seconds until the result is ready; a hint.
646    pub estimate_seconds: u64,
647    /// The job's URL: `https://` and printable ASCII, at most 512 characters, ending
648    /// `/jobs/<job>`.
649    pub poll: String,
650    /// The original request, echoed: its `cell_id`, `asof` and pin (never a job or a mesh).
651    pub request: Request,
652}
653
654impl Pending {
655    /// The HTTP status of a `pending` envelope.
656    pub const STATUS: u16 = 202;
657
658    /// A `pending` envelope answering `request` (its `cell_id`, `asof` and pin are echoed; a
659    /// job or mesh in it is not), checked by the rules of 5.5: `job` 32 to 64 lowercase hex digits,
660    /// `estimate_seconds` at most 2^53 - 1, `poll` an `https://` URL of printable ASCII of at
661    /// most 512 characters whose host (up to the first `/`) is a DNS name (2.1), ending
662    /// `/jobs/<job>`. That `poll` names the mesh's own host is the caller's to ensure. A failure
663    /// is `E_ENVELOPE`, at the member's path.
664    pub fn new(job: &str, estimate_seconds: u64, poll: &str, request: Request) -> Result<Pending> {
665        check_job_and_poll_for(job, poll, request.mesh())?;
666        if estimate_seconds > limits::BLOB_LENGTH {
667            return env_err("$.estimate_seconds", "estimate_seconds is at most 2^53 - 1");
668        }
669        let request = Request { job: None, mesh: None, ..request };
670        Ok(Pending { job: job.into(), estimate_seconds, poll: poll.into(), request })
671    }
672
673    /// The JSON form of the envelope.
674    pub fn to_value(&self) -> Value {
675        // Value has no public number constructor: the canonical text, parsed.
676        json::parse(&self.to_json()).unwrap_or(Value::Null)
677    }
678
679    /// The envelope's body: its canonical JSON text (JCS), served with [`Pending::STATUS`].
680    pub fn to_json(&self) -> Vec<u8> {
681        let mut out = String::new();
682        out.push_str("{\"estimate_seconds\":");
683        out.push_str(&self.estimate_seconds.to_string());
684        out.push_str(",\"job\":");
685        json::write_string(&self.job, &mut out);
686        out.push_str(",\"outcome\":\"pending\",\"poll\":");
687        json::write_string(&self.poll, &mut out);
688        out.push_str(",\"request\":{");
689        if let Some(a) = &self.request.asof {
690            out.push_str("\"asof\":");
691            json::write_string(a, &mut out);
692            out.push(',');
693        }
694        out.push_str("\"cell_id\":");
695        json::write_string(&self.request.cell_id, &mut out);
696        if let Some(p) = &self.request.pin {
697            out.push_str(",\"fn_hash\":");
698            json::write_string(p, &mut out);
699        }
700        out.push_str("}}");
701        out.into_bytes()
702    }
703}
704
705/// Checks a job id and its `poll` URL (5.5). A request sent to `mesh` (`spec-0.5.0`) may have a
706/// loopback `poll` (9.6) only when `mesh` names an unrooted host.
707pub(crate) fn check_job_and_poll_for(job: &str, poll: &str, mesh: Option<&str>) -> Result<()> {
708    if !is_job(job) {
709        return env_err("$.job", "job is 32 to 64 lowercase hex digits");
710    }
711    if poll.starts_with("http://") {
712        if !mesh.is_some_and(lexical::is_unrooted) {
713            return env_err("$.poll", "a loopback poll is only for an unrooted mesh the request names");
714        }
715        if lexical::loopback_origin(poll).is_none() || !poll.ends_with(&format!("/jobs/{job}")) {
716            return env_err("$.poll", "poll is a loopback URL ending /jobs/<job>");
717        }
718        return Ok(());
719    }
720    let url_ok =
721        poll.strip_prefix("https://").is_some_and(|r| !r.is_empty() && r.bytes().all(|c| (0x21..=0x7E).contains(&c)))
722            && poll.len() <= limits::LICENCE_URL;
723    if !url_ok {
724        return env_err("$.poll", "poll is an https URL of printable ASCII, at most 512 characters");
725    }
726    // The text between https:// and the next / is a DNS name (2.1; 3f79313).
727    let host = poll["https://".len()..].split('/').next().unwrap_or("");
728    if !poll["https://".len()..].contains('/') || lexical::check_dns_name(host, "").is_err() {
729        return env_err("$.poll", "poll's host is a DNS name");
730    }
731    if !poll.ends_with(&format!("/jobs/{job}")) {
732        return env_err("$.poll", "poll ends /jobs/<job>");
733    }
734    Ok(())
735}
736
737pub(crate) fn quote(q: &Value) -> Result<Quote> {
738    let m = schema::object_or(q, "$.quote", ErrorCode::Envelope, "quote")?;
739    schema::exact(m, &["amount", "authorise", "currency"], &[], "$.quote", ErrorCode::Envelope)?;
740    let amount = schema::string_or(m, "amount", "$.quote", ErrorCode::Envelope)?;
741    let authorise = schema::string_or(m, "authorise", "$.quote", ErrorCode::Envelope)?;
742    let currency = schema::string_or(m, "currency", "$.quote", ErrorCode::Envelope)?;
743    if lexical::check_number(amount, "").is_err() || amount.starts_with('-') || amount == "0" {
744        return env_err("$.quote.amount", "amount is a canonical decimal greater than zero");
745    }
746    let url_ok = authorise
747        .strip_prefix("https://")
748        .is_some_and(|r| !r.is_empty() && r.bytes().all(|c| (0x21..=0x7E).contains(&c)))
749        && authorise.len() <= limits::LICENCE_URL;
750    if !url_ok {
751        return env_err("$.quote.authorise", "authorise is an https URL");
752    }
753    if !lexical::is_currency(currency) {
754        return env_err("$.quote.currency", "currency is a currency code from units.md");
755    }
756    Ok(Quote { amount: amount.into(), currency: currency.into(), authorise: authorise.into() })
757}