Skip to main content

datumesh_http/
envelope.rs

1//! Envelopes (SPEC 5.5) as the mesh writes them, and [`Reply`]: an HTTP answer before it is
2//! an HTTP response.
3//!
4//! Every envelope is written as canonical JSON (JCS), so the same statement always has the
5//! same bytes (a call and a cell URI for one cell give byte-identical bodies). The embedded
6//! receipt is the stored receipt, unchanged.
7
8pub use axum::body::Bytes;
9use datumesh_core::json::{self, Value};
10use datumesh_core::{ErrorCode, Fault, Pending, Receipt, Trust};
11
12/// How a reply may be cached.
13#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub enum Cache {
15    /// `public, max-age=31536000, immutable`: content-addressed bytes, and answers as of a
16    /// past instant.
17    Immutable,
18    /// `public, max-age=<n>`: answers about "now", and other short-lived statements.
19    Public(u64),
20    /// `private, no-store`: answers that depend on who asks.
21    Private,
22    /// `no-store`: errors, refusals, jobs.
23    NoStore,
24}
25
26impl Cache {
27    /// The `Cache-Control` header value.
28    pub fn header(self) -> String {
29        match self {
30            Cache::Immutable => "public, max-age=31536000, immutable".to_string(),
31            Cache::Public(n) => format!("public, max-age={n}"),
32            Cache::Private => "private, no-store".to_string(),
33            Cache::NoStore => "no-store".to_string(),
34        }
35    }
36}
37
38/// An answer: HTTP status, body and the headers the mesh sets.
39#[derive(Clone, Debug, PartialEq, Eq)]
40pub struct Reply {
41    /// The HTTP status.
42    pub status: u16,
43    /// The body.
44    pub body: Bytes,
45    /// The media type.
46    pub content_type: &'static str,
47    /// Caching.
48    pub cache: Cache,
49    /// A `Link: <...>; rel="canonical"` target: the as-of form of an answer about "now".
50    pub canonical: Option<String>,
51    /// `Retry-After`, in seconds.
52    pub retry_after: Option<u64>,
53}
54
55/// The media type of JSON bodies.
56pub const JSON: &str = "application/json";
57
58impl Reply {
59    /// A JSON reply.
60    pub fn json(status: u16, body: impl Into<Bytes>, cache: Cache) -> Reply {
61        Reply { status, body: body.into(), content_type: JSON, cache, canonical: None, retry_after: None }
62    }
63
64    /// The envelope's `outcome`, when the body is an envelope the mesh wrote. (Its members
65    /// are in JCS order and none before `outcome` holds text, so the first `"outcome":` is
66    /// the envelope's own.)
67    pub fn outcome(&self) -> Option<String> {
68        self.outcome_str().map(str::to_string)
69    }
70
71    /// As [`Reply::outcome`], borrowed. The first `"outcome":"` starts at a quote, so only
72    /// the body's quotes are tried (a byte search), not every position: since spec-0.4.2 the
73    /// members before `outcome` include `fn_hash` (64 hex digits), and a batch looks up the
74    /// outcome of each of its (up to 1,000) envelopes.
75    pub(crate) fn outcome_str(&self) -> Option<&str> {
76        if self.content_type != JSON {
77            return None;
78        }
79        const KEY: &[u8] = b"\"outcome\":\"";
80        let body: &[u8] = &self.body;
81        let mut from = 0;
82        let at = loop {
83            let q = from + body[from..].iter().position(|b| *b == b'"')?;
84            if body[q..].starts_with(KEY) {
85                break q + KEY.len();
86            }
87            from = q + 1;
88        };
89        let end = body[at..].iter().position(|b| *b == b'"')?;
90        std::str::from_utf8(&body[at..at + end]).ok()
91    }
92}
93
94/// A JSON number (the envelope's integers: SPEC 5.5 writes them `0` or `[1-9][0-9]*`).
95pub(crate) fn num(n: u64) -> Value {
96    json::parse(n.to_string().as_bytes()).unwrap_or(Value::Null)
97}
98
99fn s(v: &str) -> Value {
100    Value::String(v.to_string())
101}
102
103fn object(members: Vec<(&str, Value)>) -> Value {
104    Value::Object(members.into_iter().map(|(k, v)| (k.to_string(), v)).collect())
105}
106
107/// `reply` with the `resolved` member (5.5, 16.7) when its envelope may carry one (`ok`, `stale`,
108/// `not_covered`, `unlicensed`, `payment_required`, `error`); any other reply as it is. The member
109/// is core's (`Answer::with_resolved`), written where JCS puts it.
110pub fn with_resolved(mut reply: Reply, resolved: &datumesh_core::Resolved) -> Reply {
111    if !matches!(
112        reply.outcome_str(),
113        Some("ok" | "stale" | "not_covered" | "unlicensed" | "payment_required" | "error")
114    ) {
115        return reply;
116    }
117    let Ok(Value::Object(mut members)) = json::parse(&reply.body) else { return reply };
118    let member = datumesh_core::Answer::not_covered()
119        .with_resolved(resolved.clone())
120        .ok()
121        .and_then(|a| a.to_value().get("resolved").cloned());
122    let Some(member) = member else { return reply };
123    members.retain(|(k, _)| k != "resolved");
124    members.push(("resolved".into(), member));
125    reply.body = Value::Object(members).to_jcs().into();
126    reply
127}
128
129/// The canonical bytes of an envelope.
130fn bytes(v: Value) -> Vec<u8> {
131    v.to_jcs()
132}
133
134/// `trust` for a receipt this mesh serves (SPEC 5.5): `primary` exactly when the signer's
135/// host is the namespace's host and there are no inputs; `verified` for a receipt this mesh
136/// computed (`computed_by` its own host); `unverified` otherwise.
137pub fn trust_of(receipt: &Receipt, mesh_host: &str) -> Trust {
138    let ns_host = receipt.cell().ns.split('/').next().unwrap_or("");
139    if receipt.signer_host() == ns_host && receipt.inputs().is_empty() {
140        Trust::Primary
141    } else if receipt.signer_host() == mesh_host {
142        Trust::Verified
143    } else {
144        Trust::Unverified
145    }
146}
147
148/// An `ok` envelope around the receipt's bytes (its JSON, unchanged).
149pub fn ok(receipt: &[u8], trust: Trust) -> Vec<u8> {
150    let r = json::parse(receipt).unwrap_or(Value::Null);
151    bytes(object(vec![("outcome", s("ok")), ("receipt", r), ("trust", s(trust.as_str()))]))
152}
153
154/// A `stale` envelope.
155pub fn stale(receipt: &[u8], trust: Trust, age_seconds: u64) -> Vec<u8> {
156    let r = json::parse(receipt).unwrap_or(Value::Null);
157    bytes(object(vec![
158        ("age_seconds", num(age_seconds)),
159        ("outcome", s("stale")),
160        ("receipt", r),
161        ("trust", s(trust.as_str())),
162    ]))
163}
164
165/// A `not_covered` envelope, with the evaluation's fault if it faulted.
166pub fn not_covered(fault: Option<Fault>) -> Vec<u8> {
167    let mut m = vec![("outcome", s("not_covered"))];
168    if let Some(f) = fault {
169        m.push(("fault", s(f.as_str())));
170    }
171    bytes(object(m))
172}
173
174/// An `unlicensed` envelope.
175pub fn unlicensed() -> Vec<u8> {
176    bytes(object(vec![("outcome", s("unlicensed"))]))
177}
178
179/// A `payment_required` envelope.
180pub fn payment_required(amount: &str, currency: &str, authorise: &str) -> Vec<u8> {
181    bytes(object(vec![
182        ("outcome", s("payment_required")),
183        ("quote", object(vec![("amount", s(amount)), ("authorise", s(authorise)), ("currency", s(currency))])),
184    ]))
185}
186
187/// A `rate_limited` envelope.
188pub fn rate_limited(retry_after_seconds: u64) -> Vec<u8> {
189    bytes(object(vec![("outcome", s("rate_limited")), ("retry_after_seconds", num(retry_after_seconds))]))
190}
191
192/// A `bad_request` envelope.
193pub fn bad_request(code: ErrorCode) -> Vec<u8> {
194    bytes(object(vec![("error", s(code.as_str())), ("outcome", s("bad_request"))]))
195}
196
197/// An `error` envelope.
198pub fn error(code: ErrorCode) -> Vec<u8> {
199    bytes(object(vec![("error", s(code.as_str())), ("outcome", s("error"))]))
200}
201
202/// A `pending` envelope.
203pub fn pending(p: &Pending) -> Vec<u8> {
204    p.to_json()
205}
206
207/// The parse codes a `bad_request` may carry at `/cell` (SPEC 5.5; `E_CANON_HEX` for a pin since
208/// spec-0.4.2).
209pub const BAD_REQUEST_CODES: &[ErrorCode] = &[
210    ErrorCode::CanonHex,
211    ErrorCode::ParseUri,
212    ErrorCode::CanonName,
213    ErrorCode::CanonArgName,
214    ErrorCode::CanonArgDuplicate,
215    ErrorCode::CanonArgOrder,
216    ErrorCode::CanonPercent,
217    ErrorCode::CanonType,
218    ErrorCode::CanonNumber,
219    ErrorCode::CanonDate,
220    ErrorCode::CanonInstant,
221    ErrorCode::CanonString,
222    ErrorCode::CanonBlob,
223    ErrorCode::CanonLimit,
224    ErrorCode::ArgUnknown,
225    ErrorCode::ArgMissing,
226];
227
228/// The codes a `bad_request` may carry besides [`BAD_REQUEST_CODES`] since spec-0.5.0: a key not
229/// canonical under its normalisation (16.4), a malformed key encoding (16.5) and an ambiguous
230/// short id (16.8).
231pub const CALL_CODES: &[ErrorCode] =
232    &[ErrorCode::KeyNormalisation, ErrorCode::KeyEncoding, ErrorCode::ShortIdAmbiguous];
233
234/// Whether `code` may be a `bad_request`'s `error` at `/cell` (the parse codes of
235/// [`BAD_REQUEST_CODES`] and [`CALL_CODES`], and `E_SLICE_AT_CELL`).
236pub fn is_request_code(code: ErrorCode) -> bool {
237    BAD_REQUEST_CODES.contains(&code) || CALL_CODES.contains(&code) || code == ErrorCode::SliceAtCell
238}
239
240/// Whether `code` may be an `error` envelope's `error`: any code of 10.2 but `E_ENVELOPE` and
241/// the request codes `E_JOB_UNKNOWN`, `E_SLICE_AT_CELL` and `E_NAME_UNBOUND`, and the codes of
242/// spec-0.5.0 no `error` envelope carries (5.5): `E_NAMESPACE_SUSPENDED`, the class codes and
243/// [`CALL_CODES`].
244pub fn is_error_code(code: ErrorCode) -> bool {
245    !matches!(
246        code,
247        ErrorCode::Envelope
248            | ErrorCode::JobUnknown
249            | ErrorCode::SliceAtCell
250            | ErrorCode::NameUnbound
251            | ErrorCode::NamespaceSuspended
252            | ErrorCode::ClassMember
253            | ErrorCode::ClassParent
254            | ErrorCode::ClassInherit
255            | ErrorCode::ClassOverride
256            | ErrorCode::ClassFinal
257            | ErrorCode::ClassMethod
258            | ErrorCode::ClassInterface
259            | ErrorCode::ClassOwner
260            | ErrorCode::KeyNormalisation
261            | ErrorCode::KeyEncoding
262            | ErrorCode::ShortIdAmbiguous
263    )
264}
265
266/// The HTTP status of an `error` envelope with `code`: 503 when something the mesh depends on
267/// is unavailable (the store, another mesh, a key document), 500 otherwise.
268pub fn error_status(code: ErrorCode) -> u16 {
269    match code {
270        ErrorCode::InputUnavailable | ErrorCode::KeyUnavailable | ErrorCode::MeshDoc | ErrorCode::EvalUnavailable => {
271            503
272        }
273        _ => 500,
274    }
275}
276
277/// The reply of an `error` envelope.
278pub fn error_reply(code: ErrorCode) -> Reply {
279    Reply::json(error_status(code), error(code), Cache::NoStore)
280}
281
282/// The reply of a `bad_request` envelope.
283pub fn bad_request_reply(code: ErrorCode) -> Reply {
284    Reply::json(400, bad_request(code), Cache::Public(60))
285}
286
287/// The reply of a `rate_limited` envelope.
288pub fn rate_limited_reply(retry_after_seconds: u64) -> Reply {
289    let mut r = Reply::json(429, rate_limited(retry_after_seconds), Cache::NoStore);
290    r.retry_after = Some(retry_after_seconds);
291    r
292}
293
294/// The trust label of spec-0.4.2 for a receipt this mesh serves (SPEC 5.5): `relayed` when the
295/// receipt has a `source` (spec-0.6.0); `primary` exactly
296/// when the signer's host is the namespace's host and there are no inputs; `computed` when
297/// this mesh signed it (it evaluated the cell); `unverified` otherwise (this mesh does not
298/// recompute other meshes' receipts).
299pub fn trust_label_of(receipt: &Receipt, mesh_host: &str) -> datumesh_core::TrustLabel {
300    let ns_host = receipt.cell().ns.split('/').next().unwrap_or("");
301    if receipt.source().is_some() {
302        // A relayed value (spec-0.6.0, 5.5): the publisher's host signed a value it took from another.
303        datumesh_core::TrustLabel::Relayed
304    } else if receipt.signer_host() == ns_host && receipt.inputs().is_empty() {
305        datumesh_core::TrustLabel::Primary
306    } else if receipt.signer_host() == mesh_host {
307        datumesh_core::TrustLabel::Computed
308    } else {
309        datumesh_core::TrustLabel::Unverified
310    }
311}
312
313/// The reply of an answer built with the core's envelope builder (spec-0.4.2), with its
314/// status.
315pub fn answer_reply(answer: &datumesh_core::Answer, cache: Cache) -> Reply {
316    Reply::json(answer.status(), answer.to_json(), cache)
317}
318
319/// An answer with the function hash echoed (SPEC 5.5: required for a pinned request, allowed
320/// otherwise), when one is given.
321pub fn with_fn_hash(answer: datumesh_core::Answer, fn_hash: Option<&str>) -> datumesh_core::Answer {
322    match fn_hash {
323        Some(h) => answer.clone().with_fn_hash(h).unwrap_or(answer),
324        None => answer,
325    }
326}
327
328/// The reply of an `error` answer with `code`, the function hash echoed.
329pub fn error_answer_reply(code: ErrorCode, fn_hash: Option<&str>) -> Reply {
330    match datumesh_core::Answer::error(code) {
331        Ok(a) => {
332            let a = with_fn_hash(a, fn_hash).with_status(error_status(code));
333            answer_reply(&a, Cache::NoStore)
334        }
335        Err(_) => error_reply(ErrorCode::EvalUnavailable),
336    }
337}
338
339/// The reply of a `not_covered` answer with `E_NAME_UNBOUND` (spec-0.4.2).
340pub fn name_unbound_reply(max_age: u64) -> Reply {
341    match datumesh_core::Answer::not_covered().with_error(ErrorCode::NameUnbound) {
342        Ok(a) => answer_reply(&a, Cache::Public(max_age)),
343        Err(_) => Reply::json(404, not_covered(None), Cache::Public(max_age)),
344    }
345}