Skip to main content

datumesh_core/
answer.rs

1//! Envelopes of `spec-0.4.2` (5.5-5.7): every outcome and trust label, the `fn_hash` echo, slice
2//! pages and batches, checked and built.
3
4use std::collections::BTreeMap;
5
6use crate::descriptor::cmp_lexical;
7use crate::envelope::{
8    check_job_and_poll_for, env_err, integer_member, quote, EnvelopeExtras, Fault, ForeignDetail, Outcome, Overrides,
9    Pending, Quote, Request, Resolution, ResolutionKind, Resolved, Shadows, Trust, BAD_REQUEST_CODES,
10};
11use crate::error::{Error, ErrorCode, Result};
12use crate::json::{self, Value};
13use crate::keys::Keys;
14use crate::lexical::{self, limits};
15use crate::model::{scalar_canonical, Arg, Cell, Scalar, Type};
16use crate::receipt::{AnyReceipt, Receipt, Stored, Withdrawal};
17use crate::schema;
18use crate::slice::Slice;
19use crate::Envelope;
20
21/// The nine outcomes of SPEC 5.5 (`spec-0.4.2`), `pending` included.
22#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
23#[non_exhaustive]
24pub enum AnswerOutcome {
25    /// 200.
26    Ok,
27    /// 200.
28    Stale,
29    /// 404.
30    NotCovered,
31    /// 403.
32    Unlicensed,
33    /// 402.
34    PaymentRequired,
35    /// 429.
36    RateLimited,
37    /// 400.
38    BadRequest,
39    /// 500-599.
40    Error,
41    /// 202.
42    Pending,
43    /// 200 (since `spec-0.6.0`): the answer to a `whatif` request, a scenario (5.9). Never a fact.
44    Scenario,
45}
46
47impl AnswerOutcome {
48    /// The outcome as written in JSON.
49    pub const fn as_str(self) -> &'static str {
50        match self {
51            AnswerOutcome::Ok => "ok",
52            AnswerOutcome::Stale => "stale",
53            AnswerOutcome::NotCovered => "not_covered",
54            AnswerOutcome::Unlicensed => "unlicensed",
55            AnswerOutcome::PaymentRequired => "payment_required",
56            AnswerOutcome::RateLimited => "rate_limited",
57            AnswerOutcome::BadRequest => "bad_request",
58            AnswerOutcome::Error => "error",
59            AnswerOutcome::Pending => "pending",
60            AnswerOutcome::Scenario => "scenario",
61        }
62    }
63
64    /// The outcome of its JSON name.
65    pub fn from_name(s: &str) -> Option<AnswerOutcome> {
66        Some(match s {
67            "ok" => AnswerOutcome::Ok,
68            "stale" => AnswerOutcome::Stale,
69            "not_covered" => AnswerOutcome::NotCovered,
70            "unlicensed" => AnswerOutcome::Unlicensed,
71            "payment_required" => AnswerOutcome::PaymentRequired,
72            "rate_limited" => AnswerOutcome::RateLimited,
73            "bad_request" => AnswerOutcome::BadRequest,
74            "error" => AnswerOutcome::Error,
75            "pending" => AnswerOutcome::Pending,
76            "scenario" => AnswerOutcome::Scenario,
77            _ => return None,
78        })
79    }
80
81    /// The HTTP status a mesh sends with it (500 for `error`, whose exact 5xx is the mesh's).
82    pub const fn status(self) -> u16 {
83        match self {
84            AnswerOutcome::Ok | AnswerOutcome::Stale => 200,
85            AnswerOutcome::NotCovered => 404,
86            AnswerOutcome::Unlicensed => 403,
87            AnswerOutcome::PaymentRequired => 402,
88            AnswerOutcome::RateLimited => 429,
89            AnswerOutcome::BadRequest => 400,
90            AnswerOutcome::Error => 500,
91            AnswerOutcome::Pending => 202,
92            AnswerOutcome::Scenario => 200,
93        }
94    }
95
96    fn status_ok(self, status: u16) -> bool {
97        match self {
98            AnswerOutcome::Error => (500..=599).contains(&status),
99            other => other.status() == status,
100        }
101    }
102
103    fn members(self) -> (&'static [&'static str], &'static [&'static str]) {
104        match self {
105            AnswerOutcome::Ok => {
106                (&["receipt", "trust"], &["superseded_by", "reason", "fn_hash", "resolved", "shadows"])
107            }
108            AnswerOutcome::Stale => {
109                (&["receipt", "trust", "age_seconds"], &["superseded_by", "reason", "fn_hash", "resolved", "shadows"])
110            }
111            // spec-0.7.0: receipt, trust and reason with a withdrawal, reason alone with a label's answer.
112            AnswerOutcome::NotCovered => {
113                (&[], &["fault", "error", "fn_hash", "reason", "receipt", "resolved", "shadows", "trust"])
114            }
115            AnswerOutcome::Unlicensed => (&[], &["fn_hash", "resolved", "shadows"]),
116            AnswerOutcome::PaymentRequired => (&["quote"], &["fn_hash", "resolved", "shadows"]),
117            AnswerOutcome::RateLimited => (&["retry_after_seconds"], &["fn_hash"]),
118            AnswerOutcome::BadRequest => (&["error"], &["fn_hash"]),
119            // spec-0.4.3: detail, with E_FOREIGN_UNAVAILABLE only.
120            // spec-0.6.0: cycle, with E_EVAL_UNAVAILABLE only.
121            AnswerOutcome::Error => (&["error"], &["cycle", "detail", "fn_hash", "resolved", "shadows"]),
122            AnswerOutcome::Pending => (&["estimate_seconds", "job", "poll", "request"], &[]),
123            AnswerOutcome::Scenario => (&["scenario"], &["fn_hash", "resolved"]),
124        }
125    }
126}
127
128/// The four trust labels of SPEC 5.5 (`spec-0.4.2`), `computed` included.
129#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
130#[non_exhaustive]
131pub enum TrustLabel {
132    /// The publisher answered from its own records.
133    Primary,
134    /// Not primary; the mesh asked evaluated the cell and signed the receipt itself.
135    Computed,
136    /// Not primary, signed by another host, and the mesh recomputed it.
137    Verified,
138    /// Not primary, signed by another host, not recomputed.
139    Unverified,
140    /// The publisher's host signed a stored receipt that has a `source` (5.5, `spec-0.6.0`): a
141    /// value the publisher took from another party. Not `computed`, never `primary`.
142    Relayed,
143}
144
145impl TrustLabel {
146    /// The label as written in JSON.
147    pub const fn as_str(self) -> &'static str {
148        match self {
149            TrustLabel::Primary => "primary",
150            TrustLabel::Computed => "computed",
151            TrustLabel::Verified => "verified",
152            TrustLabel::Unverified => "unverified",
153            TrustLabel::Relayed => "relayed",
154        }
155    }
156
157    fn from_name(s: &str) -> Option<TrustLabel> {
158        Some(match s {
159            "primary" => TrustLabel::Primary,
160            "computed" => TrustLabel::Computed,
161            "verified" => TrustLabel::Verified,
162            "unverified" => TrustLabel::Unverified,
163            "relayed" => TrustLabel::Relayed,
164            _ => return None,
165        })
166    }
167}
168
169/// A slice page (5.6): the `ok` answer of the slice endpoint.
170#[derive(Clone, Debug, PartialEq, Eq)]
171#[non_exhaustive]
172pub struct SlicePage {
173    /// The slice object requested, with the function hash its name resolved to (or the pin).
174    pub slice: Slice,
175    /// The member envelopes, `ok` or `stale`, in ascending key order.
176    pub members: Vec<Answer>,
177    /// The URL of the following page; `None` on the last.
178    pub next: Option<String>,
179}
180
181impl SlicePage {
182    /// A page of `members` of `slice`, with `next` when there is a following page. Not checked
183    /// until written and checked back.
184    pub fn new(slice: Slice, members: Vec<Answer>, next: Option<String>) -> SlicePage {
185        SlicePage { slice, members, next }
186    }
187}
188
189/// An envelope of `spec-0.4.2` (5.5), checked or to be written: every outcome, trust label and
190/// member, with a slice page (5.6) for the `ok` answer of the slice endpoint; since 0.3.7
191/// (`spec-0.4.3`) also `E_FOREIGN_UNAVAILABLE` with its `detail` ([`Answer::foreign_unavailable`]). As a builder: one
192/// constructor per outcome, `with_*` for the optional members, [`Answer::to_json`] for the body
193/// and [`Answer::status`] for the HTTP status; check the body back with [`check_answer`] (or
194/// [`check_slice_answer`]) to hold it to every rule.
195#[derive(Clone, Debug, PartialEq, Eq)]
196#[non_exhaustive]
197pub struct Answer {
198    /// The outcome.
199    pub outcome: AnswerOutcome,
200    /// The receipt (`ok`, `stale`; not a slice page's).
201    pub receipt: Option<Receipt>,
202    /// The withdrawal of a `not_covered` answer (5.5, `spec-0.7.0`): the cell's latest version as of the
203    /// `asof` is a withdrawal. Then `receipt` is `None`, and `reason` is the withdrawal's `withdrawn`.
204    pub withdrawn: Option<Withdrawal>,
205    /// The trust label (`ok`, `stale`).
206    pub trust: Option<TrustLabel>,
207    /// Seconds since the mesh last confirmed the receipt (`stale`).
208    pub age_seconds: Option<u64>,
209    /// Hash of a newer receipt for the same cell.
210    pub superseded_by: Option<String>,
211    /// Why the receipt was superseded.
212    pub reason: Option<String>,
213    /// The quote (`payment_required`).
214    pub quote: Option<Quote>,
215    /// Seconds to wait (`rate_limited`).
216    pub retry_after_seconds: Option<u64>,
217    /// The code (`bad_request`, `error`, and `E_NAME_UNBOUND` in `not_covered`).
218    pub error: Option<ErrorCode>,
219    /// The formula evaluation fault (`not_covered`).
220    pub fault: Option<Fault>,
221    /// What failed in reaching a foreign mesh: with `E_FOREIGN_UNAVAILABLE` only, and always
222    /// with it (`error`, 502; `spec-0.4.3`).
223    pub detail: Option<ForeignDetail>,
224    /// The function the answer is of: a pin's echo, or the hash the name resolved to.
225    pub fn_hash: Option<String>,
226    /// The `pending` envelope's members.
227    pub pending: Option<Pending>,
228    /// The slice page (`ok` at the slice endpoint).
229    pub page: Option<SlicePage>,
230    /// What a short call resolved (`ok`, `stale`, `not_covered`, `unlicensed`,
231    /// `payment_required`, `error`; 5.5, `spec-0.5.0`).
232    pub resolved: Option<Resolved>,
233    /// The class this mesh binds to another hash than its reference class (the same outcomes as
234    /// `resolved`; 5.5, 16.9, `spec-0.5.0`).
235    pub shadows: Option<Shadows>,
236    /// The scenario of a `whatif` request (`scenario`, 5.9, `spec-0.6.0`).
237    pub scenario: Option<Scenario>,
238    /// The path of an evaluation cycle (`error` with `E_EVAL_UNAVAILABLE`, 5.5, `spec-0.6.0`).
239    pub cycle: Option<Cycle>,
240    /// The HTTP status to send (`error`'s exact 5xx); checked answers carry the one received.
241    status: u16,
242}
243
244fn bare(outcome: AnswerOutcome) -> Answer {
245    Answer {
246        outcome,
247        receipt: None,
248        withdrawn: None,
249        trust: None,
250        age_seconds: None,
251        superseded_by: None,
252        reason: None,
253        quote: None,
254        retry_after_seconds: None,
255        error: None,
256        fault: None,
257        detail: None,
258        fn_hash: None,
259        pending: None,
260        page: None,
261        resolved: None,
262        shadows: None,
263        scenario: None,
264        cycle: None,
265        status: outcome.status(),
266    }
267}
268
269fn code_allowed(outcome: AnswerOutcome, code: ErrorCode, job_url: bool) -> bool {
270    match outcome {
271        AnswerOutcome::BadRequest => {
272            BAD_REQUEST_CODES.contains(&code)
273                || matches!(
274                    code,
275                    ErrorCode::CanonHex
276                        | ErrorCode::SliceAtCell
277                        | ErrorCode::ShortIdAmbiguous
278                        | ErrorCode::KeyNormalisation
279                        | ErrorCode::KeyEncoding
280                )
281                || (code == ErrorCode::JobUnknown && job_url)
282                // spec-0.6.0: the whatif codes, in a whatif request only (checked by the caller).
283                || matches!(code, ErrorCode::WhatifUnsupported | ErrorCode::SliceMember)
284        }
285        AnswerOutcome::NotCovered => matches!(code, ErrorCode::NameUnbound | ErrorCode::NamespaceSuspended),
286        // 5.5 (spec-0.5.0): every code of 10.2 but exactly these. The define and write codes are
287        // never in a read envelope; the class codes are define's, E_DESCRIBE a client's, and the
288        // two key codes are `bad_request`'s when a call raises them.
289        AnswerOutcome::Error => !matches!(
290            code,
291            ErrorCode::Envelope
292                | ErrorCode::JobUnknown
293                | ErrorCode::SliceAtCell
294                | ErrorCode::NameUnbound
295                | ErrorCode::KeyNormalisation
296                | ErrorCode::KeyEncoding
297                | ErrorCode::UnrootedInput
298                | ErrorCode::NamespaceSuspended
299                | ErrorCode::ClassMember
300                | ErrorCode::ClassParent
301                | ErrorCode::ClassInherit
302                | ErrorCode::ClassOverride
303                | ErrorCode::ClassFinal
304                | ErrorCode::ClassMethod
305                | ErrorCode::ClassInterface
306                | ErrorCode::ClassOwner
307                | ErrorCode::ShortIdAmbiguous
308                | ErrorCode::Describe
309                // spec-0.6.0: the two whatif codes are a bad_request's and a not_covered
310                // fault's, never an error's (5.5; the 10.2 table's "whatif" codes).
311                | ErrorCode::WhatifUnsupported
312                | ErrorCode::WhatifNoSolution
313        ),
314        _ => false,
315    }
316}
317
318impl Answer {
319    /// `ok` (200): `receipt`, served with `trust`.
320    pub fn ok(receipt: Receipt, trust: TrustLabel) -> Answer {
321        Answer { receipt: Some(receipt), trust: Some(trust), ..bare(AnswerOutcome::Ok) }
322    }
323
324    /// `stale` (200): the last receipt known, last confirmed `age_seconds` ago.
325    pub fn stale(receipt: Receipt, trust: TrustLabel, age_seconds: u64) -> Answer {
326        Answer {
327            receipt: Some(receipt),
328            trust: Some(trust),
329            age_seconds: Some(age_seconds),
330            ..bare(AnswerOutcome::Stale)
331        }
332    }
333
334    /// `not_covered` (404).
335    pub fn not_covered() -> Answer {
336        bare(AnswerOutcome::NotCovered)
337    }
338
339    /// `not_covered` (404) with a withdrawal (5.5, `spec-0.7.0`): the cell's latest version as of
340    /// the `asof` is `receipt`, a withdrawal, served with `trust`; its `reason` is the withdrawal's
341    /// `withdrawn` text. `E_ENVELOPE` when `receipt` is not a withdrawal.
342    pub fn withdrawn(withdrawal: Withdrawal, trust: TrustLabel) -> Result<Answer> {
343        let reason = Some(withdrawal.withdrawn().to_string());
344        Ok(Answer { withdrawn: Some(withdrawal), trust: Some(trust), reason, ..bare(AnswerOutcome::NotCovered) })
345    }
346
347    /// `not_covered` (404) with `reason` alone (5.5, 16.7, `spec-0.7.0`): a label whose lookup cell
348    /// is withdrawn, which has no receipt. `E_ENVELOPE` when `reason` is empty or too long.
349    pub fn label_withdrawn(reason: &str) -> Result<Answer> {
350        if reason.is_empty() {
351            return env_err("$.reason", "reason must not be empty");
352        }
353        lexical::check_text(reason, limits::SUMMARY, false, "$.reason").map_err(|e| e.recode(ErrorCode::Envelope))?;
354        Ok(Answer { reason: Some(reason.into()), ..bare(AnswerOutcome::NotCovered) })
355    }
356
357    /// `unlicensed` (403).
358    pub fn unlicensed() -> Answer {
359        bare(AnswerOutcome::Unlicensed)
360    }
361
362    /// `payment_required` (402) with its quote.
363    pub fn payment_required(quote: Quote) -> Answer {
364        Answer { quote: Some(quote), ..bare(AnswerOutcome::PaymentRequired) }
365    }
366
367    /// `rate_limited` (429): retry after this many seconds.
368    pub fn rate_limited(retry_after_seconds: u64) -> Answer {
369        Answer { retry_after_seconds: Some(retry_after_seconds), ..bare(AnswerOutcome::RateLimited) }
370    }
371
372    /// `bad_request` (400) with a code it can carry (5.5: a parse code, `E_CANON_HEX`,
373    /// `E_SLICE_AT_CELL`, `E_SHORT_ID_AMBIGUOUS`, `E_KEY_NORMALISATION` or `E_KEY_ENCODING`
374    /// (since `spec-0.5.0`), or `E_JOB_UNKNOWN` at a job URL); `E_ENVELOPE` otherwise.
375    pub fn bad_request(code: ErrorCode) -> Result<Answer> {
376        if !code_allowed(AnswerOutcome::BadRequest, code, true) {
377            return env_err("$.error", format!("bad_request cannot carry {code}"));
378        }
379        Ok(Answer { error: Some(code), ..bare(AnswerOutcome::BadRequest) })
380    }
381
382    /// `error` (500; see [`Answer::with_status`]) with a code it can carry (any of 10.2 but
383    /// the codes 5.5 refuses in an `error` envelope: `E_ENVELOPE`, `E_DESCRIBE`, the request
384    /// codes, the define and write codes and the class codes, since `spec-0.5.0`).
385    /// `E_FOREIGN_UNAVAILABLE` needs a `detail` and HTTP 502: build it with
386    /// [`Answer::foreign_unavailable`] (here it is `E_ENVELOPE`).
387    pub fn error(code: ErrorCode) -> Result<Answer> {
388        if !code_allowed(AnswerOutcome::Error, code, false) {
389            return env_err("$.error", format!("error cannot carry {code}"));
390        }
391        if code == ErrorCode::ForeignUnavailable {
392            return env_err("$.detail", "E_FOREIGN_UNAVAILABLE needs a detail: Answer::foreign_unavailable");
393        }
394        Ok(Answer { error: Some(code), ..bare(AnswerOutcome::Error) })
395    }
396
397    /// `error` with `E_FOREIGN_UNAVAILABLE` and `detail` (5.5, `spec-0.4.3`), HTTP 502: the cell
398    /// belongs to another mesh, which could not be reached. Answered by a resolver, or by a mesh
399    /// fetching across meshes, when no HTTP response came back from the foreign host. Its
400    /// status must stay 502 ([`Answer::with_status`] to another fails [`check_answer`]).
401    pub fn foreign_unavailable(detail: ForeignDetail) -> Answer {
402        Answer {
403            error: Some(ErrorCode::ForeignUnavailable),
404            detail: Some(detail),
405            status: 502,
406            ..bare(AnswerOutcome::Error)
407        }
408    }
409
410    /// `pending` (202).
411    pub fn pending(p: Pending) -> Answer {
412        Answer { pending: Some(p), ..bare(AnswerOutcome::Pending) }
413    }
414
415    /// The `ok` answer of the slice endpoint (5.6).
416    pub fn page(page: SlicePage) -> Answer {
417        Answer { page: Some(page), ..bare(AnswerOutcome::Ok) }
418    }
419
420    /// `scenario` (200, 5.9, `spec-0.6.0`): the answer to a `whatif` request. It has no receipt
421    /// and no trust; [`check_answer`] accepts it only for a request with overrides.
422    pub fn scenario(scenario: Scenario) -> Answer {
423        Answer { scenario: Some(scenario), ..bare(AnswerOutcome::Scenario) }
424    }
425
426    /// With the `cycle` member (5.5, `spec-0.6.0`): only on `error` with `E_EVAL_UNAVAILABLE`;
427    /// `E_ENVELOPE` otherwise.
428    pub fn with_cycle(self, cycle: Cycle) -> Result<Answer> {
429        if self.outcome != AnswerOutcome::Error || self.error != Some(ErrorCode::EvalUnavailable) {
430            return env_err("$.cycle", "cycle is carried by error with E_EVAL_UNAVAILABLE only");
431        }
432        Ok(Answer { cycle: Some(cycle), ..self })
433    }
434
435    /// With the `fn_hash` echo (64 lowercase hex digits; not on `pending`); `E_ENVELOPE`
436    /// otherwise.
437    pub fn with_fn_hash(self, fn_hash: &str) -> Result<Answer> {
438        if self.outcome == AnswerOutcome::Pending || lexical::check_hex(fn_hash, 64, "").is_err() {
439            return env_err("$.fn_hash", "fn_hash is 64 lowercase hex digits, not on pending");
440        }
441        Ok(Answer { fn_hash: Some(fn_hash.into()), ..self })
442    }
443
444    /// A `not_covered` answer with a formula evaluation fault. Not checked here: a fault with
445    /// `error`, or on another outcome, fails [`check_answer`].
446    pub fn with_fault(self, fault: Fault) -> Answer {
447        Answer { fault: Some(fault), ..self }
448    }
449
450    /// A `not_covered` answer with `error` (only `E_NAME_UNBOUND`, and not with a fault);
451    /// `E_ENVELOPE` otherwise.
452    pub fn with_error(self, code: ErrorCode) -> Result<Answer> {
453        if self.outcome != AnswerOutcome::NotCovered || self.fault.is_some() || !code_allowed(self.outcome, code, false)
454        {
455            return env_err("$.error", "not_covered carries E_NAME_UNBOUND or E_NAMESPACE_SUSPENDED, not with a fault");
456        }
457        Ok(Answer { error: Some(code), ..self })
458    }
459
460    /// With the `resolved` member (`spec-0.5.0`): allowed on `ok`, `stale`, `not_covered`,
461    /// `unlicensed`, `payment_required` and `error`; `E_ENVELOPE` on `rate_limited`,
462    /// `bad_request` and `pending`.
463    pub fn with_resolved(self, resolved: Resolved) -> Result<Answer> {
464        if !outcome_has_resolved(self.outcome) {
465            return env_err("$.resolved", format!("{} carries no resolved", self.outcome.as_str()));
466        }
467        Ok(Answer { resolved: Some(resolved), ..self })
468    }
469
470    /// With the `shadows` member (`spec-0.5.0`), on the same outcomes as
471    /// [`with_resolved`](Self::with_resolved); `E_ENVELOPE` otherwise.
472    pub fn with_shadows(self, shadows: Shadows) -> Result<Answer> {
473        if !outcome_has_resolved(self.outcome) {
474            return env_err("$.shadows", format!("{} carries no shadows", self.outcome.as_str()));
475        }
476        Ok(Answer { shadows: Some(shadows), ..self })
477    }
478
479    /// An `ok` or `stale` answer pointing to a newer receipt, with an optional reason.
480    pub fn with_superseded(self, superseded_by: &str, reason: Option<&str>) -> Answer {
481        Answer { superseded_by: Some(superseded_by.into()), reason: reason.map(String::from), ..self }
482    }
483
484    /// The HTTP status to send, for an `error` within 500-599 (other outcomes have one status).
485    pub fn with_status(self, status: u16) -> Answer {
486        Answer { status, ..self }
487    }
488
489    /// The HTTP status: the outcome's, or for a checked answer the one received.
490    pub fn status(&self) -> u16 {
491        self.status
492    }
493
494    /// The JSON form of the envelope.
495    pub fn to_value(&self) -> Value {
496        if let Some(p) = &self.pending {
497            return p.to_value();
498        }
499        let mut m: Vec<(String, Value)> = vec![("outcome".into(), Value::String(self.outcome.as_str().into()))];
500        let s = |x: &str| Value::String(x.into());
501        let n = |x: u64| json::parse(x.to_string().as_bytes()).unwrap_or(Value::Null);
502        if let Some(r) = &self.receipt {
503            m.push(("receipt".into(), receipt_value(r.payload(), r.sig())));
504        }
505        if let Some(w) = &self.withdrawn {
506            m.push(("receipt".into(), receipt_value(w.payload(), w.sig())));
507        }
508        if let Some(t) = self.trust {
509            m.push(("trust".into(), s(t.as_str())));
510        }
511        if let Some(a) = self.age_seconds {
512            m.push(("age_seconds".into(), n(a)));
513        }
514        if let Some(x) = &self.superseded_by {
515            m.push(("superseded_by".into(), s(x)));
516        }
517        if let Some(x) = &self.reason {
518            m.push(("reason".into(), s(x)));
519        }
520        if let Some(q) = &self.quote {
521            m.push((
522                "quote".into(),
523                Value::Object(vec![
524                    ("amount".into(), s(&q.amount)),
525                    ("authorise".into(), s(&q.authorise)),
526                    ("currency".into(), s(&q.currency)),
527                ]),
528            ));
529        }
530        if let Some(a) = self.retry_after_seconds {
531            m.push(("retry_after_seconds".into(), n(a)));
532        }
533        if let Some(e) = self.error {
534            m.push(("error".into(), s(e.as_str())));
535        }
536        if let Some(f) = self.fault {
537            m.push(("fault".into(), s(f.as_str())));
538        }
539        if let Some(d) = self.detail {
540            m.push(("detail".into(), s(d.as_str())));
541        }
542        if let Some(h) = &self.fn_hash {
543            m.push(("fn_hash".into(), s(h)));
544        }
545        if let Some(r) = &self.resolved {
546            let mut rm = vec![
547                ("call".to_string(), s(&r.call)),
548                (
549                    "resolutions".to_string(),
550                    Value::Array(
551                        r.resolutions
552                            .iter()
553                            .map(|x| {
554                                let mut xm = vec![
555                                    ("from".to_string(), s(&x.from)),
556                                    ("kind".to_string(), s(x.kind.as_str())),
557                                    ("to".to_string(), s(&x.to)),
558                                ];
559                                if let Some(a) = &x.asof {
560                                    xm.push(("asof".into(), s(a)));
561                                }
562                                Value::Object(xm)
563                            })
564                            .collect(),
565                    ),
566                ),
567            ];
568            if let Some(t) = &r.aliases_tx {
569                rm.push(("aliases_tx".into(), s(t)));
570            }
571            m.push(("resolved".into(), Value::Object(rm)));
572        }
573        if let Some(sh) = &self.shadows {
574            m.push((
575                "shadows".into(),
576                Value::Object(vec![("class".into(), s(&sh.class)), ("reference".into(), s(&sh.reference))]),
577            ));
578        }
579        if let Some(sc) = &self.scenario {
580            m.push(("scenario".into(), sc.to_value()));
581        }
582        if let Some(c) = &self.cycle {
583            m.push(("cycle".into(), c.to_value()));
584        }
585        if let Some(p) = &self.page {
586            m.push(("slice".into(), p.slice.to_value()));
587            m.push(("members".into(), Value::Array(p.members.iter().map(Answer::to_value).collect())));
588            if let Some(x) = &p.next {
589                m.push(("next".into(), s(x)));
590            }
591        }
592        Value::Object(m)
593    }
594
595    /// The envelope's body: its canonical JSON text (JCS).
596    pub fn to_json(&self) -> Vec<u8> {
597        self.to_value().to_jcs()
598    }
599
600    /// The `spec-0.4.1` form, for the 0.3.x functions: not `pending`, not `computed`.
601    pub(crate) fn into_envelope(self) -> Result<(Envelope, EnvelopeExtras)> {
602        // spec-0.6.0 members are read by check_answer only: the 0.3.x envelope refuses them.
603        if self.cycle.is_some() {
604            return env_err("$.cycle", "cycle is read by check_answer");
605        }
606        if self.withdrawn.is_some() {
607            return env_err("$.receipt", "a withdrawal is read by check_answer");
608        }
609        let outcome = match self.outcome {
610            AnswerOutcome::Ok => Outcome::Ok,
611            AnswerOutcome::Stale => Outcome::Stale,
612            AnswerOutcome::NotCovered => Outcome::NotCovered,
613            AnswerOutcome::Unlicensed => Outcome::Unlicensed,
614            AnswerOutcome::PaymentRequired => Outcome::PaymentRequired,
615            AnswerOutcome::RateLimited => Outcome::RateLimited,
616            AnswerOutcome::BadRequest => Outcome::BadRequest,
617            AnswerOutcome::Error => Outcome::Error,
618            AnswerOutcome::Pending => return env_err("$.outcome", "unknown outcome \"pending\""),
619            AnswerOutcome::Scenario => return env_err("$.outcome", "unknown outcome \"scenario\""),
620        };
621        let trust = match self.trust {
622            None => None,
623            Some(TrustLabel::Primary) => Some(Trust::Primary),
624            Some(TrustLabel::Verified) => Some(Trust::Verified),
625            Some(TrustLabel::Unverified) => Some(Trust::Unverified),
626            Some(_) => return env_err("$.trust", "trust is primary, verified or unverified"),
627        };
628        let env = Envelope {
629            outcome,
630            receipt: self.receipt,
631            trust,
632            age_seconds: self.age_seconds,
633            superseded_by: self.superseded_by,
634            reason: self.reason,
635            quote: self.quote,
636            retry_after_seconds: self.retry_after_seconds,
637            error: self.error,
638        };
639        Ok((env, EnvelopeExtras { fault: self.fault, fn_hash: self.fn_hash, detail: self.detail }))
640    }
641}
642
643fn receipt_value(payload: &[u8], sig: &str) -> Value {
644    let mut members = json::parse(payload).ok().and_then(|v| v.as_object().map(<[_]>::to_vec)).unwrap_or_default();
645    members.push(("sig".into(), Value::String(sig.into())));
646    Value::Object(members)
647}
648
649/// What an envelope is checked against: a cell request, the slice endpoint's request, or
650/// nothing (a batch's refusal).
651enum Ctx<'a> {
652    Cell(&'a Request),
653    Slice(&'a SliceRequest),
654    None,
655}
656
657impl Ctx<'_> {
658    fn pin(&self) -> Option<&str> {
659        match self {
660            Ctx::Cell(r) => r.pin.as_deref(),
661            Ctx::Slice(s) => s.pin.as_deref(),
662            Ctx::None => None,
663        }
664    }
665
666    fn mesh(&self) -> Option<&str> {
667        match self {
668            Ctx::Cell(r) => r.mesh.as_deref(),
669            Ctx::Slice(s) => s.mesh.as_deref(),
670            Ctx::None => None,
671        }
672    }
673
674    fn job_url(&self) -> bool {
675        matches!(self, Ctx::Cell(r) if r.job.is_some())
676    }
677
678    /// A `whatif` request: one with overrides (5.9, `spec-0.6.0`).
679    fn whatif(&self) -> bool {
680        matches!(self, Ctx::Cell(r) if r.overrides.is_some())
681    }
682
683    fn solve(&self) -> Option<&str> {
684        match self {
685            Ctx::Cell(r) => r.solve.as_deref(),
686            _ => None,
687        }
688    }
689}
690
691/// The whatif codes a `bad_request` carries only in a whatif request (5.5, 5.9): with
692/// `E_WHATIF_UNSUPPORTED`, a request with `solve`. `E_SLICE_MEMBER` is not checked against the
693/// request: a request whose members are malformed (members with add) cannot be built as a
694/// whatif request at all, and the mesh's refusal of it is the answer the client checks (5.5).
695fn whatif_code_ok(outcome: AnswerOutcome, code: ErrorCode, ctx: &Ctx<'_>) -> bool {
696    match (outcome, code) {
697        (AnswerOutcome::BadRequest, ErrorCode::WhatifUnsupported) => ctx.solve().is_some(),
698        _ => true,
699    }
700}
701
702/// Checks an envelope (5.5) answering a `/cell` request or a job URL, of any outcome and trust
703/// label, in the order of 5.5: strict JSON, members, HTTP status, the receipt through step 6 of
704/// 10.1, the binding to `request` (cell id, `asof`, the pin and its echo, the echoed request
705/// and job of `pending`), then `trust` (with `computed` against the signer and `poll` against
706/// the host when `request` names the mesh asked) and `superseded_by`. Never touches the
707/// network.
708pub fn check_answer(status: u16, body: &[u8], keys: &Keys, request: &Request) -> Result<Answer> {
709    let v = json::parse(body)?;
710    check_value(status, &v, keys, &Ctx::Cell(request), "$")
711}
712
713/// A slice request (5.6): the slice id asked for, the `asof`, the pin, the host asked, and for
714/// a following page the key of the last member received (`after`).
715#[derive(Clone, Debug, PartialEq, Eq, Hash)]
716pub struct SliceRequest {
717    slice_id: String,
718    asof: Option<String>,
719    pin: Option<String>,
720    mesh: Option<String>,
721    after: Option<BTreeMap<String, Scalar>>,
722}
723
724impl SliceRequest {
725    /// A request for the slice with id `slice_id` (64 lowercase hex digits) as of `asof` (an
726    /// instant) or now; anything else is [`crate::InvalidRequest`].
727    pub fn new(slice_id: &str, asof: Option<&str>) -> core::result::Result<SliceRequest, crate::InvalidRequest> {
728        let r = Request::new(slice_id, asof)?;
729        Ok(SliceRequest { slice_id: r.cell_id, asof: r.asof, pin: None, mesh: None, after: None })
730    }
731
732    /// Pinned to `fn_hash` (64 lowercase hex digits).
733    pub fn with_pin(self, fn_hash: &str) -> core::result::Result<SliceRequest, crate::InvalidRequest> {
734        let r = Request::new(&self.slice_id, None)?.with_pin(fn_hash)?;
735        Ok(SliceRequest { pin: r.pin, ..self })
736    }
737
738    /// Naming the host asked (a DNS name): `next` and `computed` are then checked against it.
739    pub fn with_mesh(self, host: &str) -> core::result::Result<SliceRequest, crate::InvalidRequest> {
740        let r = Request::new(&self.slice_id, None)?.with_mesh(host)?;
741        Ok(SliceRequest { mesh: r.mesh, ..self })
742    }
743
744    /// For a following page: the key of the last member received, from each open argument's
745    /// name to its value. Other names are ignored; a cursor lacking an open argument, or whose
746    /// value has another type than the members' key, cannot be ordered against (`E_ENVELOPE`
747    /// from [`check_slice_answer`]).
748    pub fn with_after(self, after: BTreeMap<String, Scalar>) -> SliceRequest {
749        SliceRequest { after: Some(after), ..self }
750    }
751
752    /// The slice id asked for.
753    pub fn slice_id(&self) -> &str {
754        &self.slice_id
755    }
756
757    /// The `asof` asked for.
758    pub fn asof(&self) -> Option<&str> {
759        self.asof.as_deref()
760    }
761
762    /// The pin.
763    pub fn fn_hash(&self) -> Option<&str> {
764        self.pin.as_deref()
765    }
766
767    /// The host asked.
768    pub fn mesh(&self) -> Option<&str> {
769        self.mesh.as_deref()
770    }
771
772    /// The key after which this page's members come.
773    pub fn after(&self) -> Option<&BTreeMap<String, Scalar>> {
774        self.after.as_ref()
775    }
776}
777
778/// Checks an answer of the slice endpoint (5.6) against `request`: `stale` and `pending` are
779/// not answers there; `ok` is a page, checked as 5.6 says (its members, the slice id, `next`,
780/// then each member's receipt through step 6 of 10.1, membership, `asof`, trust and key order
781/// after `after`); every other outcome as in 5.5.
782pub fn check_slice_answer(status: u16, body: &[u8], keys: &Keys, request: &SliceRequest) -> Result<Answer> {
783    let v = json::parse(body)?;
784    check_value(status, &v, keys, &Ctx::Slice(request), "$")
785}
786
787/// The answer to a batch (5.7).
788#[derive(Clone, Debug, PartialEq, Eq)]
789#[non_exhaustive]
790pub enum Batch {
791    /// 200: one result per request, in request order; a failing item is its error, in place.
792    Items(Vec<Result<Answer>>),
793    /// The whole batch refused: one envelope (`unlicensed`, `payment_required`, `rate_limited`,
794    /// `bad_request` or `error`).
795    Refused(Box<Answer>),
796}
797
798/// Checks the answer to a batch (5.7) of `requests`: for 200, an array with one
799/// `{envelope, status}` per request (`status` an integer 100-599), else `E_ENVELOPE` for the
800/// whole; then each item as an envelope (5.5) with its status against its own request, a
801/// failing item reported in its place. Any other status is one envelope of a refusal outcome,
802/// with nothing to bind.
803pub fn check_batch(status: u16, body: &[u8], keys: &Keys, requests: &[Request]) -> Result<Batch> {
804    let v = json::parse(body)?;
805    if status != 200 {
806        if !matches!(v, Value::Object(_)) {
807            return env_err("$", "a refused batch is one envelope");
808        }
809        let a = check_value(status, &v, keys, &Ctx::None, "$")?;
810        if !matches!(
811            a.outcome,
812            AnswerOutcome::Unlicensed
813                | AnswerOutcome::PaymentRequired
814                | AnswerOutcome::RateLimited
815                | AnswerOutcome::BadRequest
816                | AnswerOutcome::Error
817        ) {
818            return env_err(
819                "$.outcome",
820                "a batch is refused with unlicensed, payment_required, rate_limited, bad_request or error",
821            );
822        }
823        return Ok(Batch::Refused(Box::new(a)));
824    }
825    let Value::Array(items) = &v else { return env_err("$", "a batch answer is an array") };
826    if items.len() != requests.len() {
827        return env_err("$", format!("{} items for {} requests", items.len(), requests.len()));
828    }
829    let mut parts = Vec::with_capacity(items.len());
830    for (i, item) in items.iter().enumerate() {
831        let p = format!("$[{i}]");
832        let m = schema::object_or(item, &p, ErrorCode::Envelope, "an item")?;
833        schema::exact(m, &["envelope", "status"], &[], &p, ErrorCode::Envelope)?;
834        let st = integer_member(schema::get(m, "status"), &format!("{p}.status"))?;
835        if !(100..=599).contains(&st) {
836            return env_err(&format!("{p}.status"), "an item's status is 100-599");
837        }
838        parts.push((schema::get(m, "envelope"), st as u16));
839    }
840    Ok(Batch::Items(
841        parts
842            .into_iter()
843            .zip(requests)
844            .enumerate()
845            .map(|(i, ((env, st), req))| check_value(st, env, keys, &Ctx::Cell(req), &format!("$[{i}].envelope")))
846            .collect(),
847    ))
848}
849
850/// A batch answer's body (5.7): one `{envelope, status}` per answer, in order.
851pub fn batch_body(items: &[(u16, Answer)]) -> Vec<u8> {
852    let n = |x: u16| json::parse(x.to_string().as_bytes()).unwrap_or(Value::Null);
853    Value::Array(
854        items
855            .iter()
856            .map(|(st, a)| Value::Object(vec![("envelope".into(), a.to_value()), ("status".into(), n(*st))]))
857            .collect(),
858    )
859    .to_jcs()
860}
861
862fn nested(e: Error, prefix: &str) -> Error {
863    if prefix == "$" {
864        return e;
865    }
866    let inner = e.path().strip_prefix('$').unwrap_or(e.path());
867    Error::new(e.code(), format!("{prefix}{inner}"), e.detail())
868}
869
870fn check_value(status: u16, v: &Value, keys: &Keys, ctx: &Ctx<'_>, at: &str) -> Result<Answer> {
871    check_inner(status, v, keys, ctx).map_err(|e| nested(e, at))
872}
873
874/// A URL `https://<DNS name>/<path>` of printable ASCII, at most 512 characters.
875fn url_host(u: &str) -> Option<&str> {
876    let rest = u.strip_prefix("https://")?;
877    if u.len() > limits::LICENCE_URL || !rest.bytes().all(|c| (0x21..=0x7E).contains(&c)) {
878        return None;
879    }
880    let (host, _) = rest.split_once('/')?;
881    lexical::check_dns_name(host, "").ok().map(|()| host)
882}
883
884fn check_inner(status: u16, v: &Value, keys: &Keys, ctx: &Ctx<'_>) -> Result<Answer> {
885    // 2.
886    let m = match v {
887        Value::Object(m) if matches!(schema::opt(m, "outcome"), Some(Value::String(_))) => m,
888        _ => return env_err("$", "an envelope is an object with a string outcome"),
889    };
890    let oname = schema::get(m, "outcome").as_str().unwrap_or("");
891    let Some(outcome) = AnswerOutcome::from_name(oname) else {
892        return env_err("$.outcome", format!("unknown outcome {oname:?}"));
893    };
894    let slice_ctx = matches!(ctx, Ctx::Slice(_));
895    if slice_ctx && matches!(outcome, AnswerOutcome::Stale | AnswerOutcome::Pending) {
896        return env_err("$.outcome", "stale and pending are not answers of the slice endpoint");
897    }
898    // 5.9 (spec-0.6.0): with overrides, ok, stale and pending are not answers; scenario is only
899    // an answer to a request with overrides.
900    let whatif = ctx.whatif();
901    if whatif && matches!(outcome, AnswerOutcome::Ok | AnswerOutcome::Stale | AnswerOutcome::Pending) {
902        return env_err("$.outcome", format!("{oname} is not an answer to a whatif request"));
903    }
904    if outcome == AnswerOutcome::Scenario && !whatif {
905        return env_err("$.outcome", "scenario is the answer to a request with overrides");
906    }
907    if outcome == AnswerOutcome::Pending {
908        return check_pending(status, m, ctx);
909    }
910    let is_page = slice_ctx && outcome == AnswerOutcome::Ok;
911    let mut a = check_members(m, outcome, ctx, is_page)?;
912    // spec-0.7.0 (5.5): a not_covered carries receipt and trust together, or neither; with a
913    // withdrawal it carries reason and no fault or error; without one, a label's reason alone.
914    if outcome == AnswerOutcome::NotCovered {
915        let has_receipt = schema::opt(m, "receipt").is_some();
916        if has_receipt != a.trust.is_some() {
917            return env_err("$.trust", "receipt and trust are both given or neither");
918        }
919        if has_receipt && (a.reason.is_none() || a.error.is_some() || a.fault.is_some()) {
920            return env_err("$.reason", "a withdrawal in not_covered carries reason, and no error or fault");
921        }
922        if !has_receipt && a.reason.is_some() && (a.error.is_some() || a.fault.is_some()) {
923            return env_err("$.reason", "a label's reason is given alone");
924        }
925    }
926    // 3.
927    if !outcome.status_ok(status) {
928        return env_err("$.outcome", format!("status {status} does not match outcome {oname}"));
929    }
930    // spec-0.4.3: E_FOREIGN_UNAVAILABLE is answered with 502 exactly.
931    if a.error == Some(ErrorCode::ForeignUnavailable) && status != 502 {
932        return env_err("$.outcome", format!("E_FOREIGN_UNAVAILABLE is answered with 502, not {status}"));
933    }
934    a.status = status;
935    // 3a. What the request decides without the receipt: the pin echo (E_JOB_UNKNOWN only at
936    // a job URL was checked with the members; pending is checked apart).
937    pin_echo(&a, ctx.pin(), "$.fn_hash")?;
938    if is_page {
939        let Ctx::Slice(req) = ctx else { return env_err("$", "a page answers a slice request") };
940        return check_page(m, a, keys, req);
941    }
942    // 5 for a scenario (5.9): the scenario binds to the request, and holds no receipt.
943    if outcome == AnswerOutcome::Scenario {
944        if let Ctx::Cell(req) = ctx {
945            bind_scenario(&a, req)?;
946        }
947        return Ok(a);
948    }
949    // 4.
950    if let Some(rv) = schema::opt(m, "receipt") {
951        // spec-0.7.0: the `withdrawn` member decides which kind of receipt this is, before it is parsed.
952        // A withdrawal answers not_covered, and not_covered carries only a withdrawal.
953        match (outcome, member_stored(rv, keys, "$.receipt")?) {
954            (AnswerOutcome::NotCovered, AnyReceipt::Withdrawal(w)) => {
955                if a.reason.as_deref() != Some(w.withdrawn()) {
956                    return env_err("$.reason", "reason is the withdrawal's reason");
957                }
958                a.withdrawn = Some(w);
959            }
960            (AnswerOutcome::NotCovered, AnyReceipt::Value(_)) => {
961                return env_err("$.receipt", "not_covered carries a withdrawal receipt, or none");
962            }
963            (_, AnyReceipt::Withdrawal(_)) => return env_err("$.receipt", "a withdrawal answers not_covered"),
964            (_, AnyReceipt::Value(r)) => a.receipt = Some(r),
965        }
966    }
967    // 5.
968    if let Ctx::Cell(req) = ctx {
969        bind_cell(&a, req)?;
970    }
971    // 6.
972    if let Some(r) = a.stored() {
973        trust_check(&a, r, ctx.mesh(), "$")?;
974    }
975    Ok(a)
976}
977
978fn member_stored(rv: &Value, keys: &Keys, path: &str) -> Result<AnyReceipt> {
979    crate::verify::signature_valid_value(rv, keys).map_err(|(e, _)| {
980        let inner = e.path().strip_prefix('$').unwrap_or(e.path());
981        Error::new(e.code(), format!("{path}{inner}"), e.detail())
982    })
983}
984
985fn member_receipt(rv: &Value, keys: &Keys, path: &str) -> Result<Receipt> {
986    match member_stored(rv, keys, path)? {
987        AnyReceipt::Value(r) => Ok(r),
988        AnyReceipt::Withdrawal(_) => env_err(path, "a withdrawal is not a receipt of this outcome"),
989    }
990}
991
992impl Answer {
993    /// The receipt or withdrawal the answer carries, for the checks that read either.
994    fn stored(&self) -> Option<&dyn Stored> {
995        match (&self.receipt, &self.withdrawn) {
996            (Some(r), _) => Some(r),
997            (None, Some(w)) => Some(w),
998            (None, None) => None,
999        }
1000    }
1001}
1002
1003/// 5.5 step 2 for every outcome but `pending`; for a page, its own members.
1004/// The outcomes that carry `resolved` and `shadows` (5.5 table, `spec-0.5.0`).
1005fn outcome_has_resolved(outcome: AnswerOutcome) -> bool {
1006    matches!(
1007        outcome,
1008        AnswerOutcome::Ok
1009            | AnswerOutcome::Stale
1010            | AnswerOutcome::NotCovered
1011            | AnswerOutcome::Unlicensed
1012            | AnswerOutcome::PaymentRequired
1013            | AnswerOutcome::Error
1014            | AnswerOutcome::Scenario
1015    )
1016}
1017
1018/// The `resolved` member (5.5, 16.7): exactly `call` (a non-empty string), `resolutions` and
1019/// optionally `aliases_tx` (an instant); each resolution exactly `from`, `kind` and `to`, plus
1020/// `asof` (an instant) exactly when its kind is `lookup` or `chain`.
1021fn resolved_of(v: &Value) -> Result<Resolved> {
1022    let m = schema::object_or(v, "$.resolved", ErrorCode::Envelope, "resolved")?;
1023    schema::exact(m, &["call", "resolutions"], &["aliases_tx"], "$.resolved", ErrorCode::Envelope)?;
1024    let call = schema::string_or(m, "call", "$.resolved", ErrorCode::Envelope)?;
1025    let Value::Array(items) = schema::get(m, "resolutions") else {
1026        return env_err("$.resolved.resolutions", "resolutions is an array");
1027    };
1028    let mut resolutions = Vec::with_capacity(items.len());
1029    for (i, item) in items.iter().enumerate() {
1030        let p = format!("$.resolved.resolutions[{i}]");
1031        let rm = schema::object_or(item, &p, ErrorCode::Envelope, "a resolution")?;
1032        let (required, optional): (&[&str], &[&str]) = match schema::opt(rm, "kind").and_then(Value::as_str) {
1033            Some("lookup" | "chain") => (&["from", "kind", "to", "asof"], &[]),
1034            _ => (&["from", "kind", "to"], &[]),
1035        };
1036        schema::exact(rm, required, optional, &p, ErrorCode::Envelope)?;
1037        let from = schema::string_or(rm, "from", &p, ErrorCode::Envelope)?;
1038        let kind_text = schema::string_or(rm, "kind", &p, ErrorCode::Envelope)?;
1039        let to = schema::string_or(rm, "to", &p, ErrorCode::Envelope)?;
1040        let Some(kind) = ResolutionKind::from_name(kind_text) else {
1041            return env_err(&p, format!("kind {kind_text:?} is not a resolution kind"));
1042        };
1043        let resolution = match kind {
1044            ResolutionKind::Lookup => {
1045                let asof = schema::string_or(rm, "asof", &p, ErrorCode::Envelope)?;
1046                Resolution::lookup(from, to, asof)
1047            }
1048            ResolutionKind::Chain => {
1049                let asof = schema::string_or(rm, "asof", &p, ErrorCode::Envelope)?;
1050                Resolution::chain(from, to, asof)
1051            }
1052            _ => Resolution::new(from, kind, to),
1053        };
1054        resolutions.push(resolution.map_err(|e| e.recode(ErrorCode::Envelope))?);
1055    }
1056    let mut out = Resolved::new(call, resolutions).map_err(|e| e.recode(ErrorCode::Envelope))?;
1057    if let Some(t) = schema::opt(m, "aliases_tx") {
1058        let t = t.as_str().unwrap_or("");
1059        out = out.with_aliases_tx(t).map_err(|e| e.recode(ErrorCode::Envelope))?;
1060    }
1061    Ok(out)
1062}
1063
1064fn check_members(m: &[(String, Value)], outcome: AnswerOutcome, ctx: &Ctx<'_>, is_page: bool) -> Result<Answer> {
1065    let (req, opt): (&[&str], &[&str]) =
1066        if is_page { (&["members", "slice"], &["next", "fn_hash"]) } else { outcome.members() };
1067    let mut allowed: Vec<&str> = vec!["outcome"];
1068    allowed.extend_from_slice(req);
1069    schema::exact(m, &allowed, opt, "$", ErrorCode::Envelope)?;
1070    let mut a = bare(outcome);
1071    if let Some(r) = schema::opt(m, "receipt") {
1072        if !matches!(r, Value::Object(_)) {
1073            return env_err("$.receipt", "receipt is a receipt object");
1074        }
1075    }
1076    if let Some(t) = schema::opt(m, "trust") {
1077        a.trust = match t.as_str().and_then(TrustLabel::from_name) {
1078            Some(t) => Some(t),
1079            None => return env_err("$.trust", "trust is primary, computed, verified or unverified"),
1080        };
1081    }
1082    if let Some(x) = schema::opt(m, "age_seconds") {
1083        a.age_seconds = Some(integer_member(x, "$.age_seconds")?);
1084    }
1085    if let Some(x) = schema::opt(m, "retry_after_seconds") {
1086        a.retry_after_seconds = Some(integer_member(x, "$.retry_after_seconds")?);
1087    }
1088    if let Some(s) = schema::opt(m, "superseded_by") {
1089        let s = s.as_str().unwrap_or("");
1090        lexical::check_hex(s, 64, "$.superseded_by").map_err(|e| e.recode(ErrorCode::Envelope))?;
1091        a.superseded_by = Some(s.into());
1092    }
1093    if let Some(r) = schema::opt(m, "reason") {
1094        let Some(r) = r.as_str() else { return env_err("$.reason", "reason must be a string") };
1095        // spec-0.7.0: or not_covered, with a withdrawal's reason or a label's.
1096        if schema::opt(m, "superseded_by").is_none() && outcome != AnswerOutcome::NotCovered {
1097            return env_err("$.reason", "reason is only present with superseded_by");
1098        }
1099        lexical::check_text(r, limits::SUMMARY, false, "$.reason").map_err(|e| e.recode(ErrorCode::Envelope))?;
1100        if r.is_empty() {
1101            return env_err("$.reason", "reason must not be empty");
1102        }
1103        a.reason = Some(r.into());
1104    }
1105    if let Some(q) = schema::opt(m, "quote") {
1106        a.quote = Some(quote(q)?);
1107    }
1108    if let Some(e) = schema::opt(m, "error") {
1109        let code = e.as_str().and_then(ErrorCode::from_code);
1110        match code {
1111            Some(c) if code_allowed(outcome, c, ctx.job_url()) && whatif_code_ok(outcome, c, ctx) => a.error = Some(c),
1112            _ => return env_err("$.error", format!("{e:?} is not a code this outcome can carry")),
1113        }
1114    }
1115    if let Some(sc) = schema::opt(m, "scenario") {
1116        a.scenario = Some(scenario_of(sc)?);
1117    }
1118    if let Some(c) = schema::opt(m, "cycle") {
1119        let cycle = cycle_of(c)?;
1120        a = a.with_cycle(cycle)?;
1121    }
1122    // spec-0.4.3: detail, one of the closed list, present exactly with E_FOREIGN_UNAVAILABLE.
1123    if let Some(r) = schema::opt(m, "resolved") {
1124        a.resolved = Some(resolved_of(r)?);
1125    }
1126    if let Some(sh) = schema::opt(m, "shadows") {
1127        let sm = schema::object_or(sh, "$.shadows", ErrorCode::Envelope, "shadows")?;
1128        schema::exact(sm, &["class", "reference"], &[], "$.shadows", ErrorCode::Envelope)?;
1129        let class = schema::string_or(sm, "class", "$.shadows", ErrorCode::Envelope)?;
1130        let reference = schema::string_or(sm, "reference", "$.shadows", ErrorCode::Envelope)?;
1131        a.shadows = Some(Shadows::new(class, reference).map_err(|e| e.recode(ErrorCode::Envelope))?);
1132    }
1133    if let Some(d) = schema::opt(m, "detail") {
1134        let Some(detail) = d.as_str().and_then(ForeignDetail::from_name) else {
1135            return env_err("$.detail", format!("{d:?} is not a detail of E_FOREIGN_UNAVAILABLE"));
1136        };
1137        a.detail = Some(detail);
1138    }
1139    if (a.error == Some(ErrorCode::ForeignUnavailable)) != a.detail.is_some() {
1140        return env_err("$.detail", "detail is present exactly when error is E_FOREIGN_UNAVAILABLE");
1141    }
1142    if let Some(f) = schema::opt(m, "fault") {
1143        let Some(fault) = f.as_str().and_then(Fault::from_code) else {
1144            return env_err("$.fault", format!("{f:?} is not a formula evaluation fault"));
1145        };
1146        if a.error.is_some() {
1147            return env_err("$.fault", "not_covered carries a fault or an error, not both");
1148        }
1149        // 5.9: E_WHATIF_NO_SOLUTION is the fault of a whatif request with solve, and no other.
1150        if fault == Fault::WhatifNoSolution && ctx.solve().is_none() {
1151            return env_err("$.fault", "E_WHATIF_NO_SOLUTION answers a whatif request with solve");
1152        }
1153        a.fault = Some(fault);
1154    }
1155    if let Some(h) = schema::opt(m, "fn_hash") {
1156        let h = h.as_str().unwrap_or("");
1157        lexical::check_hex(h, 64, "$.fn_hash").map_err(|e| e.recode(ErrorCode::Envelope))?;
1158        a.fn_hash = Some(h.into());
1159    }
1160    if let Some(n) = schema::opt(m, "next") {
1161        let shape = n.as_str().is_some_and(|u| url_host(u).is_some() || lexical::loopback_origin(u).is_some());
1162        if !shape {
1163            return env_err(
1164                "$.next",
1165                "next is https://, a DNS name, then a path, or a loopback URL, at most 512 characters",
1166            );
1167        }
1168    }
1169    Ok(a)
1170}
1171
1172/// The receipt answers the request (5.5 step 5).
1173fn bind_cell(a: &Answer, req: &Request) -> Result<()> {
1174    let Some(r) = a.stored() else { return Ok(()) };
1175    if r.cell().id() != req.cell_id {
1176        return env_err("$.receipt.cell", "the receipt is for another cell than the one requested");
1177    }
1178    if let Some(asked) = &req.asof {
1179        if r.asof() > asked.as_str() {
1180            return env_err("$.receipt.asof", "the receipt's asof is after the requested asof");
1181        }
1182    }
1183    Ok(())
1184}
1185
1186/// The pin echo (5.5 step 3a): with a pin, `fn_hash` required (but on `rate_limited` and
1187/// `bad_request`) and equal to it.
1188fn pin_echo(a: &Answer, pin: Option<&str>, path: &str) -> Result<()> {
1189    if let Some(p) = pin {
1190        match &a.fn_hash {
1191            Some(h) if h != p => return env_err(path, "the fn_hash echo is not the pin"),
1192            None if !matches!(a.outcome, AnswerOutcome::RateLimited | AnswerOutcome::BadRequest) => {
1193                return env_err(path, "an answer to a pinned request echoes the pin");
1194            }
1195            _ => {}
1196        }
1197    }
1198    Ok(())
1199}
1200
1201/// 5.5 step 6: trust against the receipt (and the host asked, when known), then `fn_hash`
1202/// against the receipt's `cell.fn_hash`, then `superseded_by`.
1203fn trust_check(a: &Answer, r: &dyn Stored, mesh: Option<&str>, at: &str) -> Result<()> {
1204    let p = |m: &str| format!("{at}.{m}");
1205    // 5.5 step 6 (spec-0.6.0): primary and relayed are the publisher's own, with no inputs; the
1206    // receipt's source tells them apart.
1207    let own = r.signer_host() == lexical::host_of(&r.cell().ns) && r.inputs().is_empty();
1208    let primary = own && r.source().is_none();
1209    let relayed = own && r.source().is_some();
1210    let t = a.trust.unwrap_or(TrustLabel::Unverified);
1211    if (t == TrustLabel::Primary) != primary {
1212        return env_err(
1213            &p("trust"),
1214            if primary { "a primary receipt is labelled primary" } else { "the receipt is not primary" },
1215        );
1216    }
1217    if (t == TrustLabel::Relayed) != relayed {
1218        return env_err(
1219            &p("trust"),
1220            if relayed { "a relayed receipt is labelled relayed" } else { "the receipt is not relayed" },
1221        );
1222    }
1223    if let Some(host) = mesh {
1224        match t {
1225            TrustLabel::Computed if r.signer_host() != host => {
1226                return env_err(&p("trust"), "computed: the receipt is signed by another host than the one asked");
1227            }
1228            TrustLabel::Verified | TrustLabel::Unverified if r.signer_host() == host => {
1229                return env_err(&p("trust"), "the mesh asked signed this receipt: its trust is computed");
1230            }
1231            _ => {}
1232        }
1233    }
1234    if a.fn_hash.as_deref().is_some_and(|h| h != r.cell().fn_hash) {
1235        return env_err(&p("fn_hash"), "fn_hash differs from the receipt's cell.fn_hash");
1236    }
1237    if a.superseded_by.as_deref() == Some(r.hash()) {
1238        return env_err(&p("superseded_by"), "a receipt cannot supersede itself");
1239    }
1240    Ok(())
1241}
1242
1243fn check_pending(status: u16, m: &[(String, Value)], ctx: &Ctx<'_>) -> Result<Answer> {
1244    // 2.
1245    schema::exact(m, &["estimate_seconds", "job", "outcome", "poll", "request"], &[], "$", ErrorCode::Envelope)?;
1246    let estimate = integer_member(schema::get(m, "estimate_seconds"), "$.estimate_seconds")?;
1247    let Some(job) = schema::get(m, "job").as_str() else { return env_err("$.job", "job must be a string") };
1248    let Some(poll) = schema::get(m, "poll").as_str() else { return env_err("$.poll", "poll must be a string") };
1249    check_job_and_poll_for(job, poll, ctx.mesh())?;
1250    let rm = schema::object_or(schema::get(m, "request"), "$.request", ErrorCode::Envelope, "request")?;
1251    schema::exact(rm, &["cell_id"], &["asof", "fn_hash"], "$.request", ErrorCode::Envelope)?;
1252    let cell_id = schema::string_or(rm, "cell_id", "$.request", ErrorCode::Envelope)?;
1253    let opt = |name: &str| -> Result<Option<&str>> {
1254        match schema::opt(rm, name) {
1255            None => Ok(None),
1256            Some(_) => schema::string_or(rm, name, "$.request", ErrorCode::Envelope).map(Some),
1257        }
1258    };
1259    let invalid = |e: crate::InvalidRequest| Error::new(ErrorCode::Envelope, "$.request", e.to_string());
1260    let mut echoed = Request::new(cell_id, opt("asof")?).map_err(invalid)?;
1261    if let Some(p) = opt("fn_hash")? {
1262        echoed = echoed.with_pin(p).map_err(invalid)?;
1263    }
1264    // 3.
1265    if status != Pending::STATUS {
1266        return env_err("$.outcome", format!("status {status} does not match outcome pending"));
1267    }
1268    // 5.
1269    let Ctx::Cell(request) = ctx else { return env_err("$.outcome", "pending answers a cell request") };
1270    if echoed.cell_id != request.cell_id || echoed.asof != request.asof || echoed.pin != request.pin {
1271        return env_err("$.request", "the echoed request is not the request made");
1272    }
1273    if let Some(polled) = &request.job {
1274        if job != polled {
1275            return env_err("$.job", "the envelope is for another job than the one polled");
1276        }
1277    }
1278    // 6. poll on the host asked (a loopback poll was checked with the unrooted mesh asked).
1279    if let (Some(host), false) = (&request.mesh, poll.starts_with("http://")) {
1280        if url_host(poll) != Some(host.as_str()) {
1281            return env_err("$.poll", "poll is on another host than the one asked");
1282        }
1283    }
1284    // The mesh asked is named to Pending::new, which checks the poll (a loopback one only for it);
1285    // the echoed request does not carry it.
1286    let with_mesh = Request { mesh: request.mesh.clone(), ..echoed };
1287    let p = Pending::new(job, estimate, poll, with_mesh)?;
1288    Ok(Answer { pending: Some(p), ..bare(AnswerOutcome::Pending) })
1289}
1290
1291/// The key of a member: its values of the slice's open (and ranged) arguments, by name.
1292fn key_of(r: &Receipt, names: &[String]) -> Vec<Scalar> {
1293    names.iter().filter_map(|n| r.cell().args.get(n).and_then(Arg::scalar).cloned()).collect()
1294}
1295
1296fn cmp_keys(a: &[Scalar], b: &[Scalar]) -> core::cmp::Ordering {
1297    for (x, y) in a.iter().zip(b) {
1298        let o = if x.ty() == y.ty() { cmp_lexical(x.ty(), x.lexical(), y.lexical()) } else { x.ty().cmp(&y.ty()) };
1299        if o != core::cmp::Ordering::Equal {
1300            return o;
1301        }
1302    }
1303    a.len().cmp(&b.len())
1304}
1305
1306/// 5.6: a page bound to its request, the page first, then each member completely.
1307fn check_page(m: &[(String, Value)], mut a: Answer, keys: &Keys, req: &SliceRequest) -> Result<Answer> {
1308    let Value::Array(items) = schema::get(m, "members") else {
1309        return env_err("$.members", "members is an array of envelopes");
1310    };
1311    let slice = Slice::from_value(schema::get(m, "slice")).map_err(|e| e.recode(ErrorCode::Envelope))?;
1312    let next = schema::opt(m, "next").and_then(Value::as_str).map(String::from);
1313    // 2. The page: the slice, its fn_hash, next, the cursor.
1314    if slice.id() != req.slice_id {
1315        return env_err("$.slice", "the page is of another slice than the one requested");
1316    }
1317    if a.fn_hash.as_deref().is_some_and(|h| h != slice.fn_hash()) {
1318        return env_err("$.fn_hash", "fn_hash differs from the slice's");
1319    }
1320    if let Some(n) = &next {
1321        if n.starts_with("http://") {
1322            // A loopback next only when the request names the unrooted mesh asked (5.6, 9.6).
1323            if !req.mesh.as_deref().is_some_and(lexical::is_unrooted) {
1324                return env_err("$.next", "a loopback next is only for an unrooted mesh the request names");
1325            }
1326        } else if let Some(host) = &req.mesh {
1327            if url_host(n) != Some(host.as_str()) {
1328                return env_err("$.next", "next is on another host than the one asked");
1329            }
1330        }
1331    }
1332    // The cursor on the open arguments only; other names are ignored.
1333    let names = slice.key_names();
1334    let mut last: Option<Vec<Scalar>> = match &req.after {
1335        None => None,
1336        Some(after) => {
1337            let key: Vec<Scalar> = names.iter().filter_map(|n| after.get(n).cloned()).collect();
1338            if key.len() != names.len() {
1339                return env_err("$", "the cursor lacks an open argument of the slice");
1340            }
1341            Some(key)
1342        }
1343    };
1344    // 3. Each member, completely, in order.
1345    let mut out = Vec::with_capacity(items.len());
1346    for (i, item) in items.iter().enumerate() {
1347        let p = format!("$.members[{i}]");
1348        let mm = match item {
1349            Value::Object(mm) => mm,
1350            _ => return env_err(&p, "a member is an envelope"),
1351        };
1352        let o = match schema::get(mm, "outcome").as_str().and_then(AnswerOutcome::from_name) {
1353            Some(o @ (AnswerOutcome::Ok | AnswerOutcome::Stale)) => o,
1354            _ => return env_err(&p, "a member is an ok or stale envelope"),
1355        };
1356        let mut ma = check_members(mm, o, &Ctx::None, false).map_err(|e| nested(e, &p))?;
1357        let r = member_receipt(schema::get(mm, "receipt"), keys, &format!("{p}.receipt"))?;
1358        if !slice.contains(&r) {
1359            return env_err(&p, "the member's cell is not a member of the slice");
1360        }
1361        if let Some(asked) = &req.asof {
1362            if r.asof() > asked.as_str() {
1363                return env_err(&format!("{p}.receipt.asof"), "the member's asof is after the requested asof");
1364            }
1365        }
1366        trust_check(&ma, &r, req.mesh.as_deref(), &p)?;
1367        let key = key_of(&r, &names);
1368        if let Some(prev) = &last {
1369            if key.len() != prev.len() || key.iter().zip(prev).any(|(x, y)| x.ty() != y.ty()) {
1370                return env_err(&p, "the member's key has other types than the previous key (or the cursor)");
1371            }
1372            if cmp_keys(&key, prev) != core::cmp::Ordering::Greater {
1373                return env_err(&p, "members are in strictly ascending key order, after the cursor");
1374            }
1375        }
1376        last = Some(key);
1377        ma.receipt = Some(r);
1378        out.push(ma);
1379    }
1380    a.page = Some(SlicePage { slice, members: out, next });
1381    Ok(a)
1382}
1383
1384/// A fix a cycle admits (5.5, 15.12; `spec-0.6.0`), in the order 5.5 lists them.
1385#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1386#[non_exhaustive]
1387pub enum CycleFix {
1388    /// `asof`: read the cell as of an earlier instant, `asof(c, T)`.
1389    Asof,
1390    /// `lag`: read the previous period.
1391    Lag,
1392    /// `step`: add an iteration argument.
1393    Step,
1394    /// `solver`: use `whatif` with `solve` (5.9).
1395    Solver,
1396}
1397
1398impl CycleFix {
1399    /// Every fix, in the order of 5.5: `asof`, `lag`, `step`, `solver`.
1400    pub const ALL: &'static [CycleFix] = &[CycleFix::Asof, CycleFix::Lag, CycleFix::Step, CycleFix::Solver];
1401
1402    /// The fix as written in JSON.
1403    pub const fn as_str(self) -> &'static str {
1404        match self {
1405            CycleFix::Asof => "asof",
1406            CycleFix::Lag => "lag",
1407            CycleFix::Step => "step",
1408            CycleFix::Solver => "solver",
1409        }
1410    }
1411
1412    /// The fix of its JSON name; `None` for anything else (case included).
1413    pub fn from_name(s: &str) -> Option<CycleFix> {
1414        CycleFix::ALL.iter().copied().find(|f| f.as_str() == s)
1415    }
1416}
1417
1418/// The `cycle` member of an `error` envelope (5.5, 15.12; `spec-0.6.0`): the path of calls
1419/// around the cycle, and the fixes it admits. Exactly `path` and `fixes`.
1420#[derive(Clone, Debug, PartialEq, Eq, Hash)]
1421#[non_exhaustive]
1422pub struct Cycle {
1423    path: Vec<String>,
1424    fixes: Vec<CycleFix>,
1425}
1426
1427impl Cycle {
1428    /// A cycle: `path` of at least two calls whose first and last are equal (`E_ENVELOPE`
1429    /// otherwise), and `fixes`, non-empty, distinct and in the order of [`CycleFix::ALL`].
1430    pub fn new(path: Vec<String>, fixes: Vec<CycleFix>) -> Result<Cycle> {
1431        if path.len() < 2 {
1432            return env_err("$.cycle.path", "a cycle's path has at least two calls");
1433        }
1434        if path.first() != path.last() {
1435            return env_err("$.cycle.path", "a cycle's path starts and ends with the same call");
1436        }
1437        if path.iter().any(String::is_empty) {
1438            return env_err("$.cycle.path", "a call is a non-empty string");
1439        }
1440        if fixes.is_empty() {
1441            return env_err("$.cycle.fixes", "a cycle names at least one fix");
1442        }
1443        if fixes.windows(2).any(|w| w[0] >= w[1]) {
1444            return env_err("$.cycle.fixes", "fixes are distinct and in the order asof, lag, step, solver");
1445        }
1446        Ok(Cycle { path, fixes })
1447    }
1448
1449    /// The calls around the cycle, the first and last equal.
1450    pub fn path(&self) -> &[String] {
1451        &self.path
1452    }
1453
1454    /// The fixes the cycle admits.
1455    pub fn fixes(&self) -> &[CycleFix] {
1456        &self.fixes
1457    }
1458
1459    fn to_value(&self) -> Value {
1460        let strings = |xs: Vec<&str>| Value::Array(xs.into_iter().map(|x| Value::String(x.into())).collect());
1461        Value::Object(vec![
1462            ("path".into(), strings(self.path.iter().map(String::as_str).collect())),
1463            ("fixes".into(), strings(self.fixes.iter().map(|f| f.as_str()).collect())),
1464        ])
1465    }
1466}
1467
1468/// The `solved` member of a scenario (5.9; `spec-0.6.0`): the value found for `vary`, and the
1469/// target's value under it.
1470#[derive(Clone, Debug, PartialEq, Eq)]
1471#[non_exhaustive]
1472pub struct Solved {
1473    vary: Cell,
1474    value: Scalar,
1475}
1476
1477impl Solved {
1478    /// The cell varied.
1479    pub fn vary(&self) -> &Cell {
1480        &self.vary
1481    }
1482
1483    /// The value found for it: a number.
1484    pub fn value(&self) -> &Scalar {
1485        &self.value
1486    }
1487}
1488
1489/// A scenario (5.9; `spec-0.6.0`): the value a cell would have under overrides. It is a
1490/// statement of what-if, never a receipt: it has no signer, no trust and no hash, and cannot be
1491/// turned into one. Built with [`Scenario::new`] and checked back by [`check_answer`] against
1492/// the request.
1493#[derive(Clone, Debug, PartialEq, Eq)]
1494#[non_exhaustive]
1495pub struct Scenario {
1496    cell: Cell,
1497    value: Scalar,
1498    asof: String,
1499    overrides: Overrides,
1500    solved: Option<Solved>,
1501}
1502
1503impl Scenario {
1504    /// A scenario of `cell` with `value`, as of `asof` (an instant), under `overrides` (the
1505    /// canonical array: value overrides and slice overrides, sorted by cell or slice id, at most
1506    /// 64). `E_ENVELOPE` for anything else.
1507    pub fn new(cell: Cell, value: Scalar, asof: &str, overrides: &Value) -> Result<Scenario> {
1508        lexical::check_instant(asof, "$.scenario.asof").map_err(|e| e.recode(ErrorCode::Envelope))?;
1509        check_overrides(overrides)?;
1510        Ok(Scenario { cell, value, asof: asof.into(), overrides: Overrides(overrides.clone()), solved: None })
1511    }
1512
1513    /// With `solved`: the value found for `vary` (a cell, not a slice) and the target's value
1514    /// under it, a number. `E_ENVELOPE` otherwise.
1515    pub fn with_solved(self, vary: Cell, value: Scalar) -> Result<Scenario> {
1516        if vary.is_slice() {
1517            return env_err("$.scenario.solved.vary", "the varied cell is one cell, not a slice");
1518        }
1519        if value.ty() != Type::Number {
1520            return env_err("$.scenario.solved.value", "the value found is a number");
1521        }
1522        Ok(Scenario { solved: Some(Solved { vary, value }), ..self })
1523    }
1524
1525    /// The cell answered.
1526    pub fn cell(&self) -> &Cell {
1527        &self.cell
1528    }
1529
1530    /// The scenario's value.
1531    pub fn value(&self) -> &Scalar {
1532        &self.value
1533    }
1534
1535    /// The value's type.
1536    pub fn ty(&self) -> Type {
1537        self.value.ty()
1538    }
1539
1540    /// The instant evaluated as of.
1541    pub fn asof(&self) -> &str {
1542        &self.asof
1543    }
1544
1545    /// The overrides, canonical.
1546    pub fn overrides(&self) -> &Value {
1547        &self.overrides.0
1548    }
1549
1550    /// The value found by `solve`, when the request had one.
1551    pub fn solved(&self) -> Option<&Solved> {
1552        self.solved.as_ref()
1553    }
1554
1555    fn to_value(&self) -> Value {
1556        let raw = match &self.value {
1557            Scalar::Boolean(b) => Value::Bool(*b),
1558            other => Value::String(other.lexical().to_string()),
1559        };
1560        let mut m = vec![
1561            ("asof".to_string(), Value::String(self.asof.clone())),
1562            ("cell".to_string(), self.cell.to_value()),
1563            ("overrides".to_string(), self.overrides.0.clone()),
1564            ("type".to_string(), Value::String(self.value.ty().as_str().into())),
1565            ("value".to_string(), raw),
1566        ];
1567        if let Some(x) = &self.solved {
1568            m.push((
1569                "solved".into(),
1570                Value::Object(vec![("vary".into(), x.vary.to_value()), ("value".into(), x.value.to_value())]),
1571            ));
1572        }
1573        Value::Object(m)
1574    }
1575}
1576
1577fn cell_of(v: &Value, path: &str) -> Result<Cell> {
1578    let c = Cell::from_value(v).map_err(|e| e.recode(ErrorCode::Envelope))?;
1579    if c.is_slice() {
1580        return env_err(path, "a cell, not a slice");
1581    }
1582    Ok(c)
1583}
1584
1585/// A value of a scenario, read in its declared type: a boolean or a lexical string.
1586fn typed_value(ty: Type, v: &Value, path: &str) -> Result<Scalar> {
1587    match (ty, v) {
1588        (Type::Boolean, Value::Bool(b)) => Ok(Scalar::Boolean(*b)),
1589        (Type::Boolean, _) => env_err(path, "a boolean value is true or false"),
1590        (t, Value::String(text)) => Scalar::from_lexical(t, text).map_err(|e| e.recode(ErrorCode::Envelope)),
1591        _ => env_err(path, "a value is a string in its type's lexical form"),
1592    }
1593}
1594
1595/// Keeps `id` strictly after the previous id in `prev` (5.9: sorted, distinct).
1596fn ascending(prev: &mut Option<String>, id: String, path: &str) -> Result<()> {
1597    if prev.as_deref().is_some_and(|q| q >= id.as_str()) {
1598        return env_err(path, "entries are distinct and sorted by cell id");
1599    }
1600    *prev = Some(id);
1601    Ok(())
1602}
1603
1604/// The id an override is sorted by, after its shape is checked (5.9): a value override's cell,
1605/// or a slice override's slice.
1606fn override_id(item: &Value, p: &str) -> Result<String> {
1607    let m = schema::object_or(item, p, ErrorCode::Envelope, "an override")?;
1608    if schema::opt(m, "slice").is_none() {
1609        schema::exact(m, &["cell", "value"], &[], p, ErrorCode::Envelope)?;
1610        let cell = cell_of(schema::get(m, "cell"), &format!("{p}.cell"))?;
1611        scalar_canonical(schema::get(m, "value"), &format!("{p}.value")).map_err(|e| e.recode(ErrorCode::Envelope))?;
1612        return Ok(cell.id());
1613    }
1614    if schema::opt(m, "members").is_some() {
1615        // spec-0.7.0 (R3, 5.9): the slice's whole member set, `members` alone, sorted by cell id,
1616        // each cell once; it may be empty.
1617        schema::exact(m, &["members", "slice"], &[], p, ErrorCode::Envelope)?;
1618        let slice = Slice::from_value(schema::get(m, "slice")).map_err(|e| e.recode(ErrorCode::Envelope))?;
1619        let Value::Array(members) = schema::get(m, "members") else {
1620            return env_err(p, "members is an array of members");
1621        };
1622        let mut prev = None;
1623        for (i, x) in members.iter().enumerate() {
1624            let mp = format!("{p}.members[{i}]");
1625            let mm = schema::object_or(x, &mp, ErrorCode::Envelope, "a member")?;
1626            schema::exact(mm, &["cell", "value"], &[], &mp, ErrorCode::Envelope)?;
1627            let cell = cell_of(schema::get(mm, "cell"), &format!("{mp}.cell"))?;
1628            scalar_canonical(schema::get(mm, "value"), &format!("{mp}.value"))
1629                .map_err(|e| e.recode(ErrorCode::Envelope))?;
1630            ascending(&mut prev, cell.id(), &mp)?;
1631        }
1632        return Ok(slice.id().to_string());
1633    }
1634    schema::exact(m, &["add", "remove", "slice"], &[], p, ErrorCode::Envelope)?;
1635    let slice = Slice::from_value(schema::get(m, "slice")).map_err(|e| e.recode(ErrorCode::Envelope))?;
1636    let Value::Array(added) = schema::get(m, "add") else { return env_err(p, "add is an array of members") };
1637    let mut prev = None;
1638    for (i, a) in added.iter().enumerate() {
1639        let ap = format!("{p}.add[{i}]");
1640        let am = schema::object_or(a, &ap, ErrorCode::Envelope, "an added member")?;
1641        schema::exact(am, &["cell", "value"], &[], &ap, ErrorCode::Envelope)?;
1642        let cell = cell_of(schema::get(am, "cell"), &format!("{ap}.cell"))?;
1643        scalar_canonical(schema::get(am, "value"), &format!("{ap}.value"))
1644            .map_err(|e| e.recode(ErrorCode::Envelope))?;
1645        ascending(&mut prev, cell.id(), &ap)?;
1646    }
1647    let Value::Array(removed) = schema::get(m, "remove") else { return env_err(p, "remove is an array of cells") };
1648    let mut prev = None;
1649    for (i, r) in removed.iter().enumerate() {
1650        let rp = format!("{p}.remove[{i}]");
1651        let cell = cell_of(r, &rp)?;
1652        ascending(&mut prev, cell.id(), &rp)?;
1653    }
1654    Ok(slice.id().to_string())
1655}
1656
1657/// The overrides of a scenario or a request (5.9): an array of at most 64 overrides, sorted by
1658/// their cell or slice id and distinct.
1659pub(crate) fn check_overrides(v: &Value) -> Result<()> {
1660    let Value::Array(items) = v else { return env_err("$.overrides", "overrides is an array") };
1661    if items.len() > 64 {
1662        return env_err("$.overrides", "at most 64 overrides");
1663    }
1664    let mut prev = None;
1665    for (i, item) in items.iter().enumerate() {
1666        let p = format!("$.overrides[{i}]");
1667        let id = override_id(item, &p)?;
1668        ascending(&mut prev, id, &p)?;
1669    }
1670    Ok(())
1671}
1672
1673/// A `scenario` member, read and checked by [`Scenario::new`] and [`Scenario::with_solved`].
1674fn scenario_of(v: &Value) -> Result<Scenario> {
1675    let m = schema::object_or(v, "$.scenario", ErrorCode::Envelope, "scenario")?;
1676    schema::exact(m, &["asof", "cell", "overrides", "type", "value"], &["solved"], "$.scenario", ErrorCode::Envelope)?;
1677    let cell = cell_of(schema::get(m, "cell"), "$.scenario.cell")?;
1678    let ty_name = schema::string_or(m, "type", "$.scenario", ErrorCode::Envelope)?;
1679    let Some(ty) = Type::from_name(ty_name) else {
1680        return env_err("$.scenario.type", format!("{ty_name:?} is not a type"));
1681    };
1682    let value = typed_value(ty, schema::get(m, "value"), "$.scenario.value")?;
1683    let asof = schema::string_or(m, "asof", "$.scenario", ErrorCode::Envelope)?;
1684    let mut sc = Scenario::new(cell, value, asof, schema::get(m, "overrides"))?;
1685    if let Some(sv) = schema::opt(m, "solved") {
1686        let sm = schema::object_or(sv, "$.scenario.solved", ErrorCode::Envelope, "solved")?;
1687        schema::exact(sm, &["vary", "value"], &[], "$.scenario.solved", ErrorCode::Envelope)?;
1688        let vary = cell_of(schema::get(sm, "vary"), "$.scenario.solved.vary")?;
1689        let value = scalar_canonical(schema::get(sm, "value"), "$.scenario.solved.value")
1690            .map_err(|e| e.recode(ErrorCode::Envelope))?;
1691        sc = sc.with_solved(vary, value)?;
1692    }
1693    Ok(sc)
1694}
1695
1696/// A `cycle` member, read and checked by [`Cycle::new`].
1697fn cycle_of(v: &Value) -> Result<Cycle> {
1698    let m = schema::object_or(v, "$.cycle", ErrorCode::Envelope, "cycle")?;
1699    schema::exact(m, &["fixes", "path"], &[], "$.cycle", ErrorCode::Envelope)?;
1700    let Value::Array(calls) = schema::get(m, "path") else { return env_err("$.cycle.path", "path is an array") };
1701    let mut path = Vec::with_capacity(calls.len());
1702    for (i, c) in calls.iter().enumerate() {
1703        let Some(t) = c.as_str() else { return env_err(&format!("$.cycle.path[{i}]"), "a call is a string") };
1704        path.push(t.to_string());
1705    }
1706    let Value::Array(names) = schema::get(m, "fixes") else { return env_err("$.cycle.fixes", "fixes is an array") };
1707    let mut fixes = Vec::with_capacity(names.len());
1708    for (i, f) in names.iter().enumerate() {
1709        match f.as_str().and_then(CycleFix::from_name) {
1710            Some(fix) => fixes.push(fix),
1711            None => return env_err(&format!("$.cycle.fixes[{i}]"), "a fix is asof, lag, step or solver"),
1712        }
1713    }
1714    Cycle::new(path, fixes)
1715}
1716
1717/// 5.9 step 5 for a scenario: its cell is the one requested, its asof the requested one when
1718/// one was sent, its overrides the request's byte for byte after canonical JSON, and `solved`
1719/// present exactly when `solve` was sent, with `vary` the requested cell.
1720fn bind_scenario(a: &Answer, req: &Request) -> Result<()> {
1721    let Some(s) = &a.scenario else { return Ok(()) };
1722    if s.cell.id() != req.cell_id {
1723        return env_err("$.scenario.cell", "the scenario is for another cell than the one requested");
1724    }
1725    if req.asof.as_deref().is_some_and(|asked| asked != s.asof) {
1726        return env_err("$.scenario.asof", "the scenario's asof is not the requested asof");
1727    }
1728    let asked = req.overrides.as_ref().map(|o| o.0.to_jcs()).unwrap_or_default();
1729    if s.overrides.0.to_jcs() != asked {
1730        return env_err("$.scenario.overrides", "the scenario's overrides are not the request's");
1731    }
1732    match (&s.solved, req.solve.as_deref()) {
1733        (Some(x), Some(v)) if x.vary.id() == v => Ok(()),
1734        (None, None) => Ok(()),
1735        _ => env_err("$.scenario.solved", "solved is present exactly when solve was sent, for the vary cell"),
1736    }
1737}