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        if self.content_type != JSON {
69            return None;
70        }
71        const KEY: &[u8] = b"\"outcome\":\"";
72        let at = self.body.windows(KEY.len()).position(|w| w == KEY)? + KEY.len();
73        let end = self.body[at..].iter().position(|b| *b == b'"')?;
74        std::str::from_utf8(&self.body[at..at + end]).ok().map(str::to_string)
75    }
76}
77
78/// A JSON number (the envelope's integers: SPEC 5.5 writes them `0` or `[1-9][0-9]*`).
79pub(crate) fn num(n: u64) -> Value {
80    json::parse(n.to_string().as_bytes()).unwrap_or(Value::Null)
81}
82
83fn s(v: &str) -> Value {
84    Value::String(v.to_string())
85}
86
87fn object(members: Vec<(&str, Value)>) -> Value {
88    Value::Object(members.into_iter().map(|(k, v)| (k.to_string(), v)).collect())
89}
90
91/// The canonical bytes of an envelope.
92fn bytes(v: Value) -> Vec<u8> {
93    v.to_jcs()
94}
95
96/// `trust` for a receipt this mesh serves (SPEC 5.5): `primary` exactly when the signer's
97/// host is the namespace's host and there are no inputs; `verified` for a receipt this mesh
98/// computed (`computed_by` its own host); `unverified` otherwise.
99pub fn trust_of(receipt: &Receipt, mesh_host: &str) -> Trust {
100    let ns_host = receipt.cell().ns.split('/').next().unwrap_or("");
101    if receipt.signer_host() == ns_host && receipt.inputs().is_empty() {
102        Trust::Primary
103    } else if receipt.signer_host() == mesh_host {
104        Trust::Verified
105    } else {
106        Trust::Unverified
107    }
108}
109
110/// An `ok` envelope around the receipt's bytes (its JSON, unchanged).
111pub fn ok(receipt: &[u8], trust: Trust) -> Vec<u8> {
112    let r = json::parse(receipt).unwrap_or(Value::Null);
113    bytes(object(vec![("outcome", s("ok")), ("receipt", r), ("trust", s(trust.as_str()))]))
114}
115
116/// A `stale` envelope.
117pub fn stale(receipt: &[u8], trust: Trust, age_seconds: u64) -> Vec<u8> {
118    let r = json::parse(receipt).unwrap_or(Value::Null);
119    bytes(object(vec![
120        ("age_seconds", num(age_seconds)),
121        ("outcome", s("stale")),
122        ("receipt", r),
123        ("trust", s(trust.as_str())),
124    ]))
125}
126
127/// A `not_covered` envelope, with the evaluation's fault if it faulted.
128pub fn not_covered(fault: Option<Fault>) -> Vec<u8> {
129    let mut m = vec![("outcome", s("not_covered"))];
130    if let Some(f) = fault {
131        m.push(("fault", s(f.as_str())));
132    }
133    bytes(object(m))
134}
135
136/// An `unlicensed` envelope.
137pub fn unlicensed() -> Vec<u8> {
138    bytes(object(vec![("outcome", s("unlicensed"))]))
139}
140
141/// A `payment_required` envelope.
142pub fn payment_required(amount: &str, currency: &str, authorise: &str) -> Vec<u8> {
143    bytes(object(vec![
144        ("outcome", s("payment_required")),
145        ("quote", object(vec![("amount", s(amount)), ("authorise", s(authorise)), ("currency", s(currency))])),
146    ]))
147}
148
149/// A `rate_limited` envelope.
150pub fn rate_limited(retry_after_seconds: u64) -> Vec<u8> {
151    bytes(object(vec![("outcome", s("rate_limited")), ("retry_after_seconds", num(retry_after_seconds))]))
152}
153
154/// A `bad_request` envelope.
155pub fn bad_request(code: ErrorCode) -> Vec<u8> {
156    bytes(object(vec![("error", s(code.as_str())), ("outcome", s("bad_request"))]))
157}
158
159/// An `error` envelope.
160pub fn error(code: ErrorCode) -> Vec<u8> {
161    bytes(object(vec![("error", s(code.as_str())), ("outcome", s("error"))]))
162}
163
164/// A `pending` envelope.
165pub fn pending(p: &Pending) -> Vec<u8> {
166    p.to_json()
167}
168
169/// The parse codes a `bad_request` may carry at `/cell` (SPEC 5.5).
170pub const BAD_REQUEST_CODES: &[ErrorCode] = &[
171    ErrorCode::ParseUri,
172    ErrorCode::CanonName,
173    ErrorCode::CanonArgName,
174    ErrorCode::CanonArgDuplicate,
175    ErrorCode::CanonArgOrder,
176    ErrorCode::CanonPercent,
177    ErrorCode::CanonType,
178    ErrorCode::CanonNumber,
179    ErrorCode::CanonDate,
180    ErrorCode::CanonInstant,
181    ErrorCode::CanonString,
182    ErrorCode::CanonBlob,
183    ErrorCode::CanonLimit,
184    ErrorCode::ArgUnknown,
185    ErrorCode::ArgMissing,
186];
187
188/// Whether `code` may be a `bad_request`'s `error` at `/cell`.
189pub fn is_request_code(code: ErrorCode) -> bool {
190    BAD_REQUEST_CODES.contains(&code)
191}
192
193/// Whether `code` may be an `error` envelope's `error`: any code of 10.2 but `E_ENVELOPE` and
194/// `E_JOB_UNKNOWN`.
195pub fn is_error_code(code: ErrorCode) -> bool {
196    !matches!(code, ErrorCode::Envelope | ErrorCode::JobUnknown)
197}
198
199/// The HTTP status of an `error` envelope with `code`: 503 when something the mesh depends on
200/// is unavailable (the store, another mesh, a key document), 500 otherwise.
201pub fn error_status(code: ErrorCode) -> u16 {
202    match code {
203        ErrorCode::InputUnavailable | ErrorCode::KeyUnavailable | ErrorCode::MeshDoc | ErrorCode::EvalUnavailable => {
204            503
205        }
206        _ => 500,
207    }
208}
209
210/// The reply of an `error` envelope.
211pub fn error_reply(code: ErrorCode) -> Reply {
212    Reply::json(error_status(code), error(code), Cache::NoStore)
213}
214
215/// The reply of a `bad_request` envelope.
216pub fn bad_request_reply(code: ErrorCode) -> Reply {
217    Reply::json(400, bad_request(code), Cache::Public(60))
218}
219
220/// The reply of a `rate_limited` envelope.
221pub fn rate_limited_reply(retry_after_seconds: u64) -> Reply {
222    let mut r = Reply::json(429, rate_limited(retry_after_seconds), Cache::NoStore);
223    r.retry_after = Some(retry_after_seconds);
224    r
225}