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
107fn bytes(v: Value) -> Vec<u8> {
109 v.to_jcs()
110}
111
112pub fn trust_of(receipt: &Receipt, mesh_host: &str) -> Trust {
116 let ns_host = receipt.cell().ns.split('/').next().unwrap_or("");
117 if receipt.signer_host() == ns_host && receipt.inputs().is_empty() {
118 Trust::Primary
119 } else if receipt.signer_host() == mesh_host {
120 Trust::Verified
121 } else {
122 Trust::Unverified
123 }
124}
125
126pub fn ok(receipt: &[u8], trust: Trust) -> Vec<u8> {
128 let r = json::parse(receipt).unwrap_or(Value::Null);
129 bytes(object(vec![("outcome", s("ok")), ("receipt", r), ("trust", s(trust.as_str()))]))
130}
131
132pub fn stale(receipt: &[u8], trust: Trust, age_seconds: u64) -> Vec<u8> {
134 let r = json::parse(receipt).unwrap_or(Value::Null);
135 bytes(object(vec![
136 ("age_seconds", num(age_seconds)),
137 ("outcome", s("stale")),
138 ("receipt", r),
139 ("trust", s(trust.as_str())),
140 ]))
141}
142
143pub fn not_covered(fault: Option<Fault>) -> Vec<u8> {
145 let mut m = vec![("outcome", s("not_covered"))];
146 if let Some(f) = fault {
147 m.push(("fault", s(f.as_str())));
148 }
149 bytes(object(m))
150}
151
152pub fn unlicensed() -> Vec<u8> {
154 bytes(object(vec![("outcome", s("unlicensed"))]))
155}
156
157pub fn payment_required(amount: &str, currency: &str, authorise: &str) -> Vec<u8> {
159 bytes(object(vec![
160 ("outcome", s("payment_required")),
161 ("quote", object(vec![("amount", s(amount)), ("authorise", s(authorise)), ("currency", s(currency))])),
162 ]))
163}
164
165pub fn rate_limited(retry_after_seconds: u64) -> Vec<u8> {
167 bytes(object(vec![("outcome", s("rate_limited")), ("retry_after_seconds", num(retry_after_seconds))]))
168}
169
170pub fn bad_request(code: ErrorCode) -> Vec<u8> {
172 bytes(object(vec![("error", s(code.as_str())), ("outcome", s("bad_request"))]))
173}
174
175pub fn error(code: ErrorCode) -> Vec<u8> {
177 bytes(object(vec![("error", s(code.as_str())), ("outcome", s("error"))]))
178}
179
180pub fn pending(p: &Pending) -> Vec<u8> {
182 p.to_json()
183}
184
185pub const BAD_REQUEST_CODES: &[ErrorCode] = &[
188 ErrorCode::CanonHex,
189 ErrorCode::ParseUri,
190 ErrorCode::CanonName,
191 ErrorCode::CanonArgName,
192 ErrorCode::CanonArgDuplicate,
193 ErrorCode::CanonArgOrder,
194 ErrorCode::CanonPercent,
195 ErrorCode::CanonType,
196 ErrorCode::CanonNumber,
197 ErrorCode::CanonDate,
198 ErrorCode::CanonInstant,
199 ErrorCode::CanonString,
200 ErrorCode::CanonBlob,
201 ErrorCode::CanonLimit,
202 ErrorCode::ArgUnknown,
203 ErrorCode::ArgMissing,
204];
205
206pub fn is_request_code(code: ErrorCode) -> bool {
209 BAD_REQUEST_CODES.contains(&code) || code == ErrorCode::SliceAtCell
210}
211
212pub fn is_error_code(code: ErrorCode) -> bool {
215 !matches!(code, ErrorCode::Envelope | ErrorCode::JobUnknown | ErrorCode::SliceAtCell | ErrorCode::NameUnbound)
216}
217
218pub fn error_status(code: ErrorCode) -> u16 {
221 match code {
222 ErrorCode::InputUnavailable | ErrorCode::KeyUnavailable | ErrorCode::MeshDoc | ErrorCode::EvalUnavailable => {
223 503
224 }
225 _ => 500,
226 }
227}
228
229pub fn error_reply(code: ErrorCode) -> Reply {
231 Reply::json(error_status(code), error(code), Cache::NoStore)
232}
233
234pub fn bad_request_reply(code: ErrorCode) -> Reply {
236 Reply::json(400, bad_request(code), Cache::Public(60))
237}
238
239pub fn rate_limited_reply(retry_after_seconds: u64) -> Reply {
241 let mut r = Reply::json(429, rate_limited(retry_after_seconds), Cache::NoStore);
242 r.retry_after = Some(retry_after_seconds);
243 r
244}
245
246pub fn trust_label_of(receipt: &Receipt, mesh_host: &str) -> datumesh_core::TrustLabel {
251 let ns_host = receipt.cell().ns.split('/').next().unwrap_or("");
252 if receipt.signer_host() == ns_host && receipt.inputs().is_empty() {
253 datumesh_core::TrustLabel::Primary
254 } else if receipt.signer_host() == mesh_host {
255 datumesh_core::TrustLabel::Computed
256 } else {
257 datumesh_core::TrustLabel::Unverified
258 }
259}
260
261pub fn answer_reply(answer: &datumesh_core::Answer, cache: Cache) -> Reply {
264 Reply::json(answer.status(), answer.to_json(), cache)
265}
266
267pub fn with_fn_hash(answer: datumesh_core::Answer, fn_hash: Option<&str>) -> datumesh_core::Answer {
270 match fn_hash {
271 Some(h) => answer.clone().with_fn_hash(h).unwrap_or(answer),
272 None => answer,
273 }
274}
275
276pub fn error_answer_reply(code: ErrorCode, fn_hash: Option<&str>) -> Reply {
278 match datumesh_core::Answer::error(code) {
279 Ok(a) => {
280 let a = with_fn_hash(a, fn_hash).with_status(error_status(code));
281 answer_reply(&a, Cache::NoStore)
282 }
283 Err(_) => error_reply(ErrorCode::EvalUnavailable),
284 }
285}
286
287pub fn name_unbound_reply(max_age: u64) -> Reply {
289 match datumesh_core::Answer::not_covered().with_error(ErrorCode::NameUnbound) {
290 Ok(a) => answer_reply(&a, Cache::Public(max_age)),
291 Err(_) => Reply::json(404, not_covered(None), Cache::Public(max_age)),
292 }
293}