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}
98
99impl Fault {
100    /// Every fault an envelope may carry, in the order of SPEC 5.5.
101    pub const ALL: &'static [Fault] = &[
102        Fault::DivZero,
103        Fault::Domain,
104        Fault::Range,
105        Fault::Empty,
106        Fault::Absent,
107        Fault::Future,
108        Fault::Key,
109        Fault::DispatchKey,
110    ];
111
112    /// The code as written, e.g. `"E_FORMULA_DIV_ZERO"`.
113    pub const fn as_str(self) -> &'static str {
114        match self {
115            Fault::DivZero => "E_FORMULA_DIV_ZERO",
116            Fault::Domain => "E_FORMULA_DOMAIN",
117            Fault::Range => "E_FORMULA_RANGE",
118            Fault::Empty => "E_FORMULA_EMPTY",
119            Fault::Absent => "E_FORMULA_ABSENT",
120            Fault::Future => "E_FORMULA_FUTURE",
121            Fault::Key => "E_FORMULA_KEY",
122            Fault::DispatchKey => "E_FORMULA_DISPATCH_KEY",
123        }
124    }
125
126    /// Looks a fault up by its code; `None` for any other text (a budget, a cycle or too deep
127    /// an evaluation is not a fault but the mesh's failure, SPEC 5.5).
128    pub fn from_code(text: &str) -> Option<Fault> {
129        Fault::ALL.iter().copied().find(|f| f.as_str() == text)
130    }
131}
132
133impl core::fmt::Display for Fault {
134    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
135        f.write_str(self.as_str())
136    }
137}
138
139/// What failed in reaching a foreign mesh (SPEC 5.5, `spec-0.4.3`): the `detail` member, required
140/// with `E_FOREIGN_UNAVAILABLE` ([`ErrorCode::ForeignUnavailable`]) and forbidden in every other
141/// envelope. The list is closed; it is non-exhaustive only so that later revisions can add to
142/// it.
143#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
144#[non_exhaustive]
145pub enum ForeignDetail {
146    /// `offline`: the asked party has no network, or is configured not to use it.
147    Offline,
148    /// `network`: any other network failure.
149    Network,
150    /// `dns`: the foreign host's name did not resolve.
151    Dns,
152    /// `tls`: the TLS handshake or the certificate failed.
153    Tls,
154    /// `timeout`.
155    Timeout,
156    /// `refused`: the connection was refused.
157    Refused,
158}
159
160impl ForeignDetail {
161    /// Every detail, in the order of SPEC 5.5.
162    pub const ALL: &'static [ForeignDetail] = &[
163        ForeignDetail::Offline,
164        ForeignDetail::Network,
165        ForeignDetail::Dns,
166        ForeignDetail::Tls,
167        ForeignDetail::Timeout,
168        ForeignDetail::Refused,
169    ];
170
171    /// The detail as written in JSON, e.g. `"offline"`.
172    pub const fn as_str(self) -> &'static str {
173        match self {
174            ForeignDetail::Offline => "offline",
175            ForeignDetail::Network => "network",
176            ForeignDetail::Dns => "dns",
177            ForeignDetail::Tls => "tls",
178            ForeignDetail::Timeout => "timeout",
179            ForeignDetail::Refused => "refused",
180        }
181    }
182
183    /// Looks a detail up by its JSON name; `None` for anything else (case included).
184    pub fn from_name(text: &str) -> Option<ForeignDetail> {
185        ForeignDetail::ALL.iter().copied().find(|d| d.as_str() == text)
186    }
187}
188
189impl core::fmt::Display for ForeignDetail {
190    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
191        f.write_str(self.as_str())
192    }
193}
194
195/// The members of a checked envelope that [`Envelope`] has no field for, because they were
196/// added to SPEC 5.5 after it was frozen (0.3.0): see [`check_envelope_extras`].
197#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
198#[non_exhaustive]
199pub struct EnvelopeExtras {
200    /// The formula evaluation fault of a `not_covered` envelope (`spec-0.4.0`).
201    pub fault: Option<Fault>,
202    /// The function the answer is of: the echo of a pin, or the hash the name resolved to
203    /// (`spec-0.4.2`).
204    pub fn_hash: Option<String>,
205    /// What failed in reaching a foreign mesh, with `E_FOREIGN_UNAVAILABLE` (`spec-0.4.3`).
206    pub detail: Option<ForeignDetail>,
207}
208
209/// The `kind` of one resolution of a short call (16.7, `spec-0.5.0`).
210#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
211#[non_exhaustive]
212pub enum ResolutionKind {
213    /// `alias`: a bare name resolved through the mesh's alias map.
214    Alias,
215    /// `default`: an unbound argument took its `"default": "asof"`.
216    Default,
217    /// `lookup`: a label resolved to a key through the class's `lookup` method; the resolution
218    /// carries `asof`, the instant the lookup cell was read as of.
219    Lookup,
220    /// `method`: a method call resolved to the method's function.
221    Method,
222}
223
224impl ResolutionKind {
225    /// Every kind, in the order of 5.5: `alias`, `default`, `lookup`, `method`.
226    pub const ALL: &'static [ResolutionKind] =
227        &[ResolutionKind::Alias, ResolutionKind::Default, ResolutionKind::Lookup, ResolutionKind::Method];
228
229    /// The kind as written: `alias`, `default`, `lookup` or `method`.
230    pub const fn as_str(self) -> &'static str {
231        match self {
232            ResolutionKind::Alias => "alias",
233            ResolutionKind::Default => "default",
234            ResolutionKind::Lookup => "lookup",
235            ResolutionKind::Method => "method",
236        }
237    }
238
239    /// Looks a kind up by its text; `None` for anything else.
240    pub fn from_name(text: &str) -> Option<ResolutionKind> {
241        ResolutionKind::ALL.iter().copied().find(|k| k.as_str() == text)
242    }
243}
244
245/// One entry of [`Resolved::resolutions`]: an object with exactly `from`, `kind` and `to`, all
246/// strings, and `asof` (an instant) exactly when the kind is `lookup`.
247#[derive(Clone, Debug, PartialEq, Eq, Hash)]
248#[non_exhaustive]
249pub struct Resolution {
250    /// What was resolved: an alias, an argument name, a label, or `<class>(...).<method>`.
251    pub from: String,
252    /// The kind of resolution.
253    pub kind: ResolutionKind,
254    /// What it resolved to.
255    pub to: String,
256    /// The instant a `lookup` cell was read as of; `Some` exactly for [`ResolutionKind::Lookup`].
257    pub asof: Option<String>,
258}
259
260impl Resolution {
261    /// A resolution of any kind but `lookup`; `E_ENVELOPE` for `lookup` (use
262    /// [`Resolution::lookup`], which needs the `asof`).
263    pub fn new(from: &str, kind: ResolutionKind, to: &str) -> Result<Resolution> {
264        if kind == ResolutionKind::Lookup {
265            return env_err("$.resolutions", "a lookup resolution carries its asof: Resolution::lookup");
266        }
267        Ok(Resolution { from: from.into(), kind, to: to.into(), asof: None })
268    }
269
270    /// A `lookup` resolution: the label, the key encoding it resolved to, and the instant its
271    /// lookup cell was read as of (`E_ENVELOPE` when `asof` is not an instant).
272    pub fn lookup(label: &str, key: &str, asof: &str) -> Result<Resolution> {
273        lexical::check_instant(asof, "$.resolutions.asof").map_err(|e| e.recode(ErrorCode::Envelope))?;
274        Ok(Resolution { from: label.into(), kind: ResolutionKind::Lookup, to: key.into(), asof: Some(asof.into()) })
275    }
276}
277
278/// The `resolved` member of an envelope (5.5, 16.7, `spec-0.5.0`): what a short call resolved.
279/// Exactly `call`, `resolutions` and optionally `aliases_tx`.
280#[derive(Clone, Debug, PartialEq, Eq, Hash)]
281#[non_exhaustive]
282pub struct Resolved {
283    /// The full canonical call (16.7), a non-empty string.
284    pub call: String,
285    /// What was resolved, in the mesh's order.
286    pub resolutions: Vec<Resolution>,
287    /// The instant of the alias snapshot used.
288    pub aliases_tx: Option<String>,
289}
290
291impl Resolved {
292    /// `call` (non-empty) and its resolutions; `E_ENVELOPE` otherwise.
293    pub fn new(call: &str, resolutions: Vec<Resolution>) -> Result<Resolved> {
294        if call.is_empty() {
295            return env_err("$.resolved.call", "call is a non-empty string");
296        }
297        Ok(Resolved { call: call.into(), resolutions, aliases_tx: None })
298    }
299
300    /// With `aliases_tx`, the instant of the alias snapshot used (`E_ENVELOPE` when it is not
301    /// an instant).
302    pub fn with_aliases_tx(self, instant: &str) -> Result<Resolved> {
303        lexical::check_instant(instant, "$.resolved.aliases_tx").map_err(|e| e.recode(ErrorCode::Envelope))?;
304        Ok(Resolved { aliases_tx: Some(instant.into()), ..self })
305    }
306}
307
308/// The `shadows` member of an envelope (5.5, 16.9, `spec-0.5.0`): the class name this mesh
309/// binds to another hash than the reference class of that name.
310#[derive(Clone, Debug, PartialEq, Eq, Hash)]
311#[non_exhaustive]
312pub struct Shadows {
313    /// A full class name (2.3).
314    pub class: String,
315    /// The reference class's hash: 64 lowercase hex digits.
316    pub reference: String,
317}
318
319impl Shadows {
320    /// Builds `shadows`; `E_ENVELOPE` for a class that is not a full name or a reference that is
321    /// not 64 lowercase hex digits.
322    pub fn new(class: &str, reference: &str) -> Result<Shadows> {
323        lexical::check_function_name(class, "$.shadows.class").map_err(|e| e.recode(ErrorCode::Envelope))?;
324        lexical::check_hex(reference, 64, "$.shadows.reference").map_err(|e| e.recode(ErrorCode::Envelope))?;
325        Ok(Shadows { class: class.into(), reference: reference.into() })
326    }
327}
328
329/// A price quote (`payment_required`).
330#[derive(Clone, Debug, PartialEq, Eq, Hash)]
331pub struct Quote {
332    /// A canonical decimal greater than zero.
333    pub amount: String,
334    /// A currency code from `units.md`.
335    pub currency: String,
336    /// Where to pay: an https URL.
337    pub authorise: String,
338}
339
340/// What the client asked for, for the binding of 5.5 step 5.
341#[derive(Clone, Debug, PartialEq, Eq, Hash)]
342pub struct Request {
343    pub(crate) cell_id: String,
344    pub(crate) asof: Option<String>,
345    pub(crate) job: Option<String>,
346    pub(crate) pin: Option<String>,
347    pub(crate) mesh: Option<String>,
348}
349
350/// A malformed request description (5.5 step 5): the caller's mistake, not an `E_*` code.
351#[derive(Clone, Debug, PartialEq, Eq, Hash)]
352pub struct InvalidRequest(String);
353
354impl core::fmt::Display for InvalidRequest {
355    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
356        write!(f, "invalid request: {}", self.0)
357    }
358}
359
360impl std::error::Error for InvalidRequest {}
361
362impl Request {
363    /// A request for the cell with id `cell_id` (64 lowercase hex digits) as of `asof` (an
364    /// instant) or now. Anything else is [`InvalidRequest`]: SPEC 5.5 makes a malformed
365    /// request the caller's error, reported outside the `E_*` codes.
366    pub fn new(cell_id: &str, asof: Option<&str>) -> core::result::Result<Request, InvalidRequest> {
367        if lexical::check_hex(cell_id, 64, "").is_err() {
368            return Err(InvalidRequest(format!("cell_id must be 64 lowercase hex digits: {cell_id:?}")));
369        }
370        if let Some(a) = asof {
371            if !lexical::is_instant(a) {
372                return Err(InvalidRequest(format!("asof must be an instant: {a:?}")));
373            }
374        }
375        Ok(Request { cell_id: cell_id.into(), asof: asof.map(String::from), job: None, pin: None, mesh: None })
376    }
377
378    /// The request description for `GET` of a job's `poll` URL (5.5, `spec-0.4.1`): the
379    /// original request (`cell_id`, `asof`) and the job polled, 32 to 64 lowercase hex digits
380    /// (otherwise [`InvalidRequest`]). With it, an envelope may be `bad_request` with
381    /// `E_JOB_UNKNOWN`, and a `pending` one must carry this `job`; any other answer is bound
382    /// to the original request, as a `/cell` answer is.
383    pub fn with_job(cell_id: &str, asof: Option<&str>, job: &str) -> core::result::Result<Request, InvalidRequest> {
384        if !is_job(job) {
385            return Err(InvalidRequest(format!("job must be 32 to 64 lowercase hex digits: {job:?}")));
386        }
387        let mut r = Request::new(cell_id, asof)?;
388        r.job = Some(job.into());
389        Ok(r)
390    }
391
392    /// The same request, pinned to the function `fn_hash` (64 lowercase hex digits; otherwise
393    /// [`InvalidRequest`]): the answer must echo it (5.5, `spec-0.4.2`). `cell_id` is then the
394    /// id of the cell of that function.
395    pub fn with_pin(self, fn_hash: &str) -> core::result::Result<Request, InvalidRequest> {
396        if lexical::check_hex(fn_hash, 64, "").is_err() {
397            return Err(InvalidRequest(format!("fn_hash must be 64 lowercase hex digits: {fn_hash:?}")));
398        }
399        Ok(Request { pin: Some(fn_hash.into()), ..self })
400    }
401
402    /// The same request, naming the host it was sent to (a DNS name; otherwise
403    /// [`InvalidRequest`]): `computed` is then checked against the receipt's signer, and
404    /// `poll` against the host (5.5, `spec-0.4.2`). Without it those checks are the caller's.
405    pub fn with_mesh(self, host: &str) -> core::result::Result<Request, InvalidRequest> {
406        if lexical::check_dns_name(host, "").is_err() {
407            return Err(InvalidRequest(format!("mesh must be a DNS name: {host:?}")));
408        }
409        Ok(Request { mesh: Some(host.into()), ..self })
410    }
411
412    /// The pin, for a pinned request ([`Request::with_pin`]).
413    pub fn fn_hash(&self) -> Option<&str> {
414        self.pin.as_deref()
415    }
416
417    /// The host the request was sent to, when given ([`Request::with_mesh`]).
418    pub fn mesh(&self) -> Option<&str> {
419        self.mesh.as_deref()
420    }
421
422    /// The job polled, for a request made at a job URL ([`Request::with_job`]).
423    pub fn job(&self) -> Option<&str> {
424        self.job.as_deref()
425    }
426
427    /// The requested cell id.
428    pub fn cell_id(&self) -> &str {
429        &self.cell_id
430    }
431
432    /// The requested `asof`, if any.
433    pub fn asof(&self) -> Option<&str> {
434        self.asof.as_deref()
435    }
436}
437
438/// A checked envelope.
439#[derive(Clone, Debug, PartialEq, Eq)]
440pub struct Envelope {
441    /// The outcome.
442    pub outcome: Outcome,
443    /// The receipt (`ok`, `stale`), signature-valid and bound to the request.
444    pub receipt: Option<Receipt>,
445    /// The trust label (`ok`, `stale`).
446    pub trust: Option<Trust>,
447    /// Seconds since the mesh last confirmed the receipt (`stale`).
448    pub age_seconds: Option<u64>,
449    /// Hash of a newer receipt for the same cell.
450    pub superseded_by: Option<String>,
451    /// Why the receipt was superseded.
452    pub reason: Option<String>,
453    /// The quote (`payment_required`).
454    pub quote: Option<Quote>,
455    /// Seconds to wait (`rate_limited`).
456    pub retry_after_seconds: Option<u64>,
457    /// The failure code (`bad_request`, `error`).
458    pub error: Option<ErrorCode>,
459}
460
461pub(crate) const BAD_REQUEST_CODES: [ErrorCode; 15] = [
462    ErrorCode::ParseUri,
463    ErrorCode::CanonName,
464    ErrorCode::CanonArgName,
465    ErrorCode::CanonArgDuplicate,
466    ErrorCode::CanonArgOrder,
467    ErrorCode::CanonPercent,
468    ErrorCode::CanonType,
469    ErrorCode::CanonNumber,
470    ErrorCode::CanonDate,
471    ErrorCode::CanonInstant,
472    ErrorCode::CanonString,
473    ErrorCode::CanonBlob,
474    ErrorCode::CanonLimit,
475    ErrorCode::ArgUnknown,
476    ErrorCode::ArgMissing,
477];
478
479pub(crate) fn env_err<T>(path: &str, detail: impl Into<String>) -> Result<T> {
480    err(ErrorCode::Envelope, path, detail)
481}
482
483/// `0` or `[1-9][0-9]*`, at most 2^53 - 1, judged on the number's text.
484pub(crate) fn integer_member(v: &Value, path: &str) -> Result<u64> {
485    let Some(t) = v.as_number_text() else {
486        return env_err(path, "must be a non-negative integer");
487    };
488    let ok =
489        !t.is_empty() && t.bytes().all(|c| c.is_ascii_digit()) && (t == "0" || !t.starts_with('0')) && t.len() <= 16;
490    match (ok, t.parse::<u64>()) {
491        (true, Ok(x)) if x <= limits::BLOB_LENGTH => Ok(x),
492        _ => env_err(path, format!("must be written 0|[1-9][0-9]* and at most 2^53 - 1, not {t}")),
493    }
494}
495
496/// Checks a response envelope (5.5) in the order of its procedure: strict JSON, members,
497/// HTTP status, the receipt through step 6 of 10.1, the binding to `request`, then `trust`
498/// and `superseded_by`. Never touches the network. A `not_covered` envelope's `fault`
499/// (`spec-0.4.0`) is checked and accepted; [`check_envelope_extras`] also returns it.
500pub fn check_envelope(status: u16, body: &[u8], keys: &Keys, request: &Request) -> Result<Envelope> {
501    check_envelope_extras(status, body, keys, request).map(|(env, _)| env)
502}
503
504/// [`check_envelope`], also returning the members [`Envelope`] has no field for
505/// ([`EnvelopeExtras`]): the `fault` of a `not_covered` envelope, one of the six formula
506/// evaluation faults of SPEC 5.5 (`E_ENVELOPE` for any other value, or on another outcome).
507///
508/// Its [`Envelope`] has no `pending` outcome, so a `pending` envelope is `E_ENVELOPE` here, as
509/// in 0.3.4; [`check_envelope_any`] accepts it. Nor has its [`Trust`] `computed` (`spec-0.4.2`):
510/// an envelope with it is `E_ENVELOPE` here and in [`check_envelope_any`], as in 0.3.5;
511/// [`crate::check_answer`] accepts it. Everything else of `spec-0.4.2` (the `fn_hash` echo, in
512/// [`EnvelopeExtras`]; `not_covered`'s `error`; the new codes) is checked as there, and so is
513/// `spec-0.4.3`'s `E_FOREIGN_UNAVAILABLE` (502, with its `detail` in [`EnvelopeExtras`]).
514pub fn check_envelope_extras(
515    status: u16,
516    body: &[u8],
517    keys: &Keys,
518    request: &Request,
519) -> Result<(Envelope, EnvelopeExtras)> {
520    crate::answer::check_answer(status, body, keys, request)?.into_envelope()
521}
522
523/// Checks a response envelope (5.5) of any of the nine outcomes, `pending` included
524/// (`spec-0.4.1`), in the order of its procedure, and binds it to `request`: a `pending`
525/// envelope's echoed request to the request made (and its `job` to the job polled, when
526/// `request` has one), any other outcome to the original request's cell id and `asof`,
527/// whether it answers the `/cell` request or the job URL. `E_JOB_UNKNOWN` is accepted only in a
528/// `bad_request` answering a job URL (`request` with a job). Never touches the network.
529pub fn check_envelope_any(status: u16, body: &[u8], keys: &Keys, request: &Request) -> Result<AnyEnvelope> {
530    let a = crate::answer::check_answer(status, body, keys, request)?;
531    if let Some(p) = a.pending {
532        return Ok(AnyEnvelope::Pending(p));
533    }
534    a.into_envelope().map(|(e, x)| AnyEnvelope::Envelope(e, x))
535}
536
537/// `[0-9a-f]{32,64}`.
538pub(crate) fn is_job(s: &str) -> bool {
539    (32..=64).contains(&s.len()) && s.bytes().all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c))
540}
541
542/// The answer to a request: a [`Pending`] envelope, or one of the eight outcomes an
543/// [`Envelope`] holds, with its [`EnvelopeExtras`] (see [`check_envelope_any`]).
544// Not boxed: one value per checked response, and matching on it stays plain.
545#[allow(clippy::large_enum_variant)]
546#[derive(Clone, Debug, PartialEq, Eq)]
547#[non_exhaustive]
548pub enum AnyEnvelope {
549    /// `ok`, `stale`, `not_covered`, `unlicensed`, `payment_required`, `rate_limited`,
550    /// `bad_request` or `error`.
551    Envelope(Envelope, EnvelopeExtras),
552    /// `pending` (202): the mesh is still computing; the answer will be at `poll`.
553    Pending(Pending),
554}
555
556impl AnyEnvelope {
557    /// The outcome as written in JSON, `"pending"` included.
558    pub fn outcome_str(&self) -> &'static str {
559        match self {
560            AnyEnvelope::Envelope(e, _) => e.outcome.as_str(),
561            AnyEnvelope::Pending(_) => "pending",
562        }
563    }
564}
565
566/// A `pending` envelope (5.5, `spec-0.4.1`): the job, an estimate, the URL to poll and the
567/// original request echoed. Build one with [`Pending::new`] (a mesh), or get one from
568/// [`check_envelope_any`] (a client).
569#[derive(Clone, Debug, PartialEq, Eq, Hash)]
570#[non_exhaustive]
571pub struct Pending {
572    /// The job id: 32 to 64 lowercase hex digits, a capability.
573    pub job: String,
574    /// The mesh's estimate of the seconds until the result is ready; a hint.
575    pub estimate_seconds: u64,
576    /// The job's URL: `https://` and printable ASCII, at most 512 characters, ending
577    /// `/jobs/<job>`.
578    pub poll: String,
579    /// The original request, echoed: its `cell_id`, `asof` and pin (never a job or a mesh).
580    pub request: Request,
581}
582
583impl Pending {
584    /// The HTTP status of a `pending` envelope.
585    pub const STATUS: u16 = 202;
586
587    /// A `pending` envelope answering `request` (its `cell_id`, `asof` and pin are echoed; a
588    /// job or mesh in it is not), checked by the rules of 5.5: `job` 32 to 64 lowercase hex digits,
589    /// `estimate_seconds` at most 2^53 - 1, `poll` an `https://` URL of printable ASCII of at
590    /// most 512 characters whose host (up to the first `/`) is a DNS name (2.1), ending
591    /// `/jobs/<job>`. That `poll` names the mesh's own host is the caller's to ensure. A failure
592    /// is `E_ENVELOPE`, at the member's path.
593    pub fn new(job: &str, estimate_seconds: u64, poll: &str, request: Request) -> Result<Pending> {
594        check_job_and_poll_for(job, poll, request.mesh())?;
595        if estimate_seconds > limits::BLOB_LENGTH {
596            return env_err("$.estimate_seconds", "estimate_seconds is at most 2^53 - 1");
597        }
598        let request = Request { job: None, mesh: None, ..request };
599        Ok(Pending { job: job.into(), estimate_seconds, poll: poll.into(), request })
600    }
601
602    /// The JSON form of the envelope.
603    pub fn to_value(&self) -> Value {
604        // Value has no public number constructor: the canonical text, parsed.
605        json::parse(&self.to_json()).unwrap_or(Value::Null)
606    }
607
608    /// The envelope's body: its canonical JSON text (JCS), served with [`Pending::STATUS`].
609    pub fn to_json(&self) -> Vec<u8> {
610        let mut out = String::new();
611        out.push_str("{\"estimate_seconds\":");
612        out.push_str(&self.estimate_seconds.to_string());
613        out.push_str(",\"job\":");
614        json::write_string(&self.job, &mut out);
615        out.push_str(",\"outcome\":\"pending\",\"poll\":");
616        json::write_string(&self.poll, &mut out);
617        out.push_str(",\"request\":{");
618        if let Some(a) = &self.request.asof {
619            out.push_str("\"asof\":");
620            json::write_string(a, &mut out);
621            out.push(',');
622        }
623        out.push_str("\"cell_id\":");
624        json::write_string(&self.request.cell_id, &mut out);
625        if let Some(p) = &self.request.pin {
626            out.push_str(",\"fn_hash\":");
627            json::write_string(p, &mut out);
628        }
629        out.push_str("}}");
630        out.into_bytes()
631    }
632}
633
634/// Checks a job id and its `poll` URL (5.5). A request sent to `mesh` (`spec-0.5.0`) may have a
635/// loopback `poll` (9.6) only when `mesh` names an unrooted host.
636pub(crate) fn check_job_and_poll_for(job: &str, poll: &str, mesh: Option<&str>) -> Result<()> {
637    if !is_job(job) {
638        return env_err("$.job", "job is 32 to 64 lowercase hex digits");
639    }
640    if poll.starts_with("http://") {
641        if !mesh.is_some_and(lexical::is_unrooted) {
642            return env_err("$.poll", "a loopback poll is only for an unrooted mesh the request names");
643        }
644        if lexical::loopback_origin(poll).is_none() || !poll.ends_with(&format!("/jobs/{job}")) {
645            return env_err("$.poll", "poll is a loopback URL ending /jobs/<job>");
646        }
647        return Ok(());
648    }
649    let url_ok =
650        poll.strip_prefix("https://").is_some_and(|r| !r.is_empty() && r.bytes().all(|c| (0x21..=0x7E).contains(&c)))
651            && poll.len() <= limits::LICENCE_URL;
652    if !url_ok {
653        return env_err("$.poll", "poll is an https URL of printable ASCII, at most 512 characters");
654    }
655    // The text between https:// and the next / is a DNS name (2.1; 3f79313).
656    let host = poll["https://".len()..].split('/').next().unwrap_or("");
657    if !poll["https://".len()..].contains('/') || lexical::check_dns_name(host, "").is_err() {
658        return env_err("$.poll", "poll's host is a DNS name");
659    }
660    if !poll.ends_with(&format!("/jobs/{job}")) {
661        return env_err("$.poll", "poll ends /jobs/<job>");
662    }
663    Ok(())
664}
665
666pub(crate) fn quote(q: &Value) -> Result<Quote> {
667    let m = schema::object_or(q, "$.quote", ErrorCode::Envelope, "quote")?;
668    schema::exact(m, &["amount", "authorise", "currency"], &[], "$.quote", ErrorCode::Envelope)?;
669    let amount = schema::string_or(m, "amount", "$.quote", ErrorCode::Envelope)?;
670    let authorise = schema::string_or(m, "authorise", "$.quote", ErrorCode::Envelope)?;
671    let currency = schema::string_or(m, "currency", "$.quote", ErrorCode::Envelope)?;
672    if lexical::check_number(amount, "").is_err() || amount.starts_with('-') || amount == "0" {
673        return env_err("$.quote.amount", "amount is a canonical decimal greater than zero");
674    }
675    let url_ok = authorise
676        .strip_prefix("https://")
677        .is_some_and(|r| !r.is_empty() && r.bytes().all(|c| (0x21..=0x7E).contains(&c)))
678        && authorise.len() <= limits::LICENCE_URL;
679    if !url_ok {
680        return env_err("$.quote.authorise", "authorise is an https URL");
681    }
682    if !lexical::is_currency(currency) {
683        return env_err("$.quote.currency", "currency is a currency code from units.md");
684    }
685    Ok(Quote { amount: amount.into(), currency: currency.into(), authorise: authorise.into() })
686}