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 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
78pub(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
91fn bytes(v: Value) -> Vec<u8> {
93 v.to_jcs()
94}
95
96pub 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
110pub 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
116pub 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
127pub 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
136pub fn unlicensed() -> Vec<u8> {
138 bytes(object(vec![("outcome", s("unlicensed"))]))
139}
140
141pub 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
149pub 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
154pub fn bad_request(code: ErrorCode) -> Vec<u8> {
156 bytes(object(vec![("error", s(code.as_str())), ("outcome", s("bad_request"))]))
157}
158
159pub fn error(code: ErrorCode) -> Vec<u8> {
161 bytes(object(vec![("error", s(code.as_str())), ("outcome", s("error"))]))
162}
163
164pub fn pending(p: &Pending) -> Vec<u8> {
166 p.to_json()
167}
168
169pub 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
188pub fn is_request_code(code: ErrorCode) -> bool {
190 BAD_REQUEST_CODES.contains(&code)
191}
192
193pub fn is_error_code(code: ErrorCode) -> bool {
196 !matches!(code, ErrorCode::Envelope | ErrorCode::JobUnknown)
197}
198
199pub 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
210pub fn error_reply(code: ErrorCode) -> Reply {
212 Reply::json(error_status(code), error(code), Cache::NoStore)
213}
214
215pub fn bad_request_reply(code: ErrorCode) -> Reply {
217 Reply::json(400, bad_request(code), Cache::Public(60))
218}
219
220pub 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}