1pub use axum::body::Bytes;
9use datumesh_core::json::{self, Value};
10use datumesh_core::{ErrorCode, Fault, Pending, Receipt, Trust};
11
12#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub enum Cache {
15 Immutable,
18 Public(u64),
20 Private,
22 NoStore,
24}
25
26impl Cache {
27 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#[derive(Clone, Debug, PartialEq, Eq)]
40pub struct Reply {
41 pub status: u16,
43 pub body: Bytes,
45 pub content_type: &'static str,
47 pub cache: Cache,
49 pub canonical: Option<String>,
51 pub retry_after: Option<u64>,
53}
54
55pub const JSON: &str = "application/json";
57
58impl Reply {
59 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 pub fn outcome(&self) -> Option<String> {
68 self.outcome_str().map(str::to_string)
69 }
70
71 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
94pub(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
107pub 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
129fn bytes(v: Value) -> Vec<u8> {
131 v.to_jcs()
132}
133
134pub 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
148pub 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
154pub 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
165pub 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
174pub fn unlicensed() -> Vec<u8> {
176 bytes(object(vec![("outcome", s("unlicensed"))]))
177}
178
179pub 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
187pub 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
192pub fn bad_request(code: ErrorCode) -> Vec<u8> {
194 bytes(object(vec![("error", s(code.as_str())), ("outcome", s("bad_request"))]))
195}
196
197pub fn error(code: ErrorCode) -> Vec<u8> {
199 bytes(object(vec![("error", s(code.as_str())), ("outcome", s("error"))]))
200}
201
202pub fn pending(p: &Pending) -> Vec<u8> {
204 p.to_json()
205}
206
207pub 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
228pub const CALL_CODES: &[ErrorCode] =
232 &[ErrorCode::KeyNormalisation, ErrorCode::KeyEncoding, ErrorCode::ShortIdAmbiguous];
233
234pub fn is_request_code(code: ErrorCode) -> bool {
237 BAD_REQUEST_CODES.contains(&code) || CALL_CODES.contains(&code) || code == ErrorCode::SliceAtCell
238}
239
240pub 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
266pub 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
277pub fn error_reply(code: ErrorCode) -> Reply {
279 Reply::json(error_status(code), error(code), Cache::NoStore)
280}
281
282pub fn bad_request_reply(code: ErrorCode) -> Reply {
284 Reply::json(400, bad_request(code), Cache::Public(60))
285}
286
287pub 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
294pub fn trust_label_of(receipt: &Receipt, mesh_host: &str) -> datumesh_core::TrustLabel {
299 let ns_host = receipt.cell().ns.split('/').next().unwrap_or("");
300 if receipt.signer_host() == ns_host && receipt.inputs().is_empty() {
301 datumesh_core::TrustLabel::Primary
302 } else if receipt.signer_host() == mesh_host {
303 datumesh_core::TrustLabel::Computed
304 } else {
305 datumesh_core::TrustLabel::Unverified
306 }
307}
308
309pub fn answer_reply(answer: &datumesh_core::Answer, cache: Cache) -> Reply {
312 Reply::json(answer.status(), answer.to_json(), cache)
313}
314
315pub fn with_fn_hash(answer: datumesh_core::Answer, fn_hash: Option<&str>) -> datumesh_core::Answer {
318 match fn_hash {
319 Some(h) => answer.clone().with_fn_hash(h).unwrap_or(answer),
320 None => answer,
321 }
322}
323
324pub fn error_answer_reply(code: ErrorCode, fn_hash: Option<&str>) -> Reply {
326 match datumesh_core::Answer::error(code) {
327 Ok(a) => {
328 let a = with_fn_hash(a, fn_hash).with_status(error_status(code));
329 answer_reply(&a, Cache::NoStore)
330 }
331 Err(_) => error_reply(ErrorCode::EvalUnavailable),
332 }
333}
334
335pub fn name_unbound_reply(max_age: u64) -> Reply {
337 match datumesh_core::Answer::not_covered().with_error(ErrorCode::NameUnbound) {
338 Ok(a) => answer_reply(&a, Cache::Public(max_age)),
339 Err(_) => Reply::json(404, not_covered(None), Cache::Public(max_age)),
340 }
341}