pub use axum::body::Bytes;
use datumesh_core::json::{self, Value};
use datumesh_core::{ErrorCode, Fault, Pending, Receipt, Trust};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Cache {
Immutable,
Public(u64),
Private,
NoStore,
}
impl Cache {
pub fn header(self) -> String {
match self {
Cache::Immutable => "public, max-age=31536000, immutable".to_string(),
Cache::Public(n) => format!("public, max-age={n}"),
Cache::Private => "private, no-store".to_string(),
Cache::NoStore => "no-store".to_string(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Reply {
pub status: u16,
pub body: Bytes,
pub content_type: &'static str,
pub cache: Cache,
pub canonical: Option<String>,
pub retry_after: Option<u64>,
}
pub const JSON: &str = "application/json";
impl Reply {
pub fn json(status: u16, body: impl Into<Bytes>, cache: Cache) -> Reply {
Reply { status, body: body.into(), content_type: JSON, cache, canonical: None, retry_after: None }
}
pub fn outcome(&self) -> Option<String> {
self.outcome_str().map(str::to_string)
}
pub(crate) fn outcome_str(&self) -> Option<&str> {
if self.content_type != JSON {
return None;
}
const KEY: &[u8] = b"\"outcome\":\"";
let body: &[u8] = &self.body;
let mut from = 0;
let at = loop {
let q = from + body[from..].iter().position(|b| *b == b'"')?;
if body[q..].starts_with(KEY) {
break q + KEY.len();
}
from = q + 1;
};
let end = body[at..].iter().position(|b| *b == b'"')?;
std::str::from_utf8(&body[at..at + end]).ok()
}
}
pub(crate) fn num(n: u64) -> Value {
json::parse(n.to_string().as_bytes()).unwrap_or(Value::Null)
}
fn s(v: &str) -> Value {
Value::String(v.to_string())
}
fn object(members: Vec<(&str, Value)>) -> Value {
Value::Object(members.into_iter().map(|(k, v)| (k.to_string(), v)).collect())
}
pub fn with_resolved(mut reply: Reply, resolved: &datumesh_core::Resolved) -> Reply {
if !matches!(
reply.outcome_str(),
Some("ok" | "stale" | "not_covered" | "unlicensed" | "payment_required" | "error")
) {
return reply;
}
let Ok(Value::Object(mut members)) = json::parse(&reply.body) else { return reply };
let member = datumesh_core::Answer::not_covered()
.with_resolved(resolved.clone())
.ok()
.and_then(|a| a.to_value().get("resolved").cloned());
let Some(member) = member else { return reply };
members.retain(|(k, _)| k != "resolved");
members.push(("resolved".into(), member));
reply.body = Value::Object(members).to_jcs().into();
reply
}
fn bytes(v: Value) -> Vec<u8> {
v.to_jcs()
}
pub fn trust_of(receipt: &Receipt, mesh_host: &str) -> Trust {
let ns_host = receipt.cell().ns.split('/').next().unwrap_or("");
if receipt.signer_host() == ns_host && receipt.inputs().is_empty() {
Trust::Primary
} else if receipt.signer_host() == mesh_host {
Trust::Verified
} else {
Trust::Unverified
}
}
pub fn ok(receipt: &[u8], trust: Trust) -> Vec<u8> {
let r = json::parse(receipt).unwrap_or(Value::Null);
bytes(object(vec![("outcome", s("ok")), ("receipt", r), ("trust", s(trust.as_str()))]))
}
pub fn stale(receipt: &[u8], trust: Trust, age_seconds: u64) -> Vec<u8> {
let r = json::parse(receipt).unwrap_or(Value::Null);
bytes(object(vec![
("age_seconds", num(age_seconds)),
("outcome", s("stale")),
("receipt", r),
("trust", s(trust.as_str())),
]))
}
pub fn not_covered(fault: Option<Fault>) -> Vec<u8> {
let mut m = vec![("outcome", s("not_covered"))];
if let Some(f) = fault {
m.push(("fault", s(f.as_str())));
}
bytes(object(m))
}
pub fn unlicensed() -> Vec<u8> {
bytes(object(vec![("outcome", s("unlicensed"))]))
}
pub fn payment_required(amount: &str, currency: &str, authorise: &str) -> Vec<u8> {
bytes(object(vec![
("outcome", s("payment_required")),
("quote", object(vec![("amount", s(amount)), ("authorise", s(authorise)), ("currency", s(currency))])),
]))
}
pub fn rate_limited(retry_after_seconds: u64) -> Vec<u8> {
bytes(object(vec![("outcome", s("rate_limited")), ("retry_after_seconds", num(retry_after_seconds))]))
}
pub fn bad_request(code: ErrorCode) -> Vec<u8> {
bytes(object(vec![("error", s(code.as_str())), ("outcome", s("bad_request"))]))
}
pub fn error(code: ErrorCode) -> Vec<u8> {
bytes(object(vec![("error", s(code.as_str())), ("outcome", s("error"))]))
}
pub fn pending(p: &Pending) -> Vec<u8> {
p.to_json()
}
pub const BAD_REQUEST_CODES: &[ErrorCode] = &[
ErrorCode::CanonHex,
ErrorCode::ParseUri,
ErrorCode::CanonName,
ErrorCode::CanonArgName,
ErrorCode::CanonArgDuplicate,
ErrorCode::CanonArgOrder,
ErrorCode::CanonPercent,
ErrorCode::CanonType,
ErrorCode::CanonNumber,
ErrorCode::CanonDate,
ErrorCode::CanonInstant,
ErrorCode::CanonString,
ErrorCode::CanonBlob,
ErrorCode::CanonLimit,
ErrorCode::ArgUnknown,
ErrorCode::ArgMissing,
];
pub const CALL_CODES: &[ErrorCode] =
&[ErrorCode::KeyNormalisation, ErrorCode::KeyEncoding, ErrorCode::ShortIdAmbiguous];
pub fn is_request_code(code: ErrorCode) -> bool {
BAD_REQUEST_CODES.contains(&code) || CALL_CODES.contains(&code) || code == ErrorCode::SliceAtCell
}
pub fn is_error_code(code: ErrorCode) -> bool {
!matches!(
code,
ErrorCode::Envelope
| ErrorCode::JobUnknown
| ErrorCode::SliceAtCell
| ErrorCode::NameUnbound
| ErrorCode::NamespaceSuspended
| ErrorCode::ClassMember
| ErrorCode::ClassParent
| ErrorCode::ClassInherit
| ErrorCode::ClassOverride
| ErrorCode::ClassFinal
| ErrorCode::ClassMethod
| ErrorCode::ClassInterface
| ErrorCode::ClassOwner
| ErrorCode::KeyNormalisation
| ErrorCode::KeyEncoding
| ErrorCode::ShortIdAmbiguous
)
}
pub fn error_status(code: ErrorCode) -> u16 {
match code {
ErrorCode::InputUnavailable | ErrorCode::KeyUnavailable | ErrorCode::MeshDoc | ErrorCode::EvalUnavailable => {
503
}
_ => 500,
}
}
pub fn error_reply(code: ErrorCode) -> Reply {
Reply::json(error_status(code), error(code), Cache::NoStore)
}
pub fn bad_request_reply(code: ErrorCode) -> Reply {
Reply::json(400, bad_request(code), Cache::Public(60))
}
pub fn rate_limited_reply(retry_after_seconds: u64) -> Reply {
let mut r = Reply::json(429, rate_limited(retry_after_seconds), Cache::NoStore);
r.retry_after = Some(retry_after_seconds);
r
}
pub fn trust_label_of(receipt: &Receipt, mesh_host: &str) -> datumesh_core::TrustLabel {
let ns_host = receipt.cell().ns.split('/').next().unwrap_or("");
if receipt.signer_host() == ns_host && receipt.inputs().is_empty() {
datumesh_core::TrustLabel::Primary
} else if receipt.signer_host() == mesh_host {
datumesh_core::TrustLabel::Computed
} else {
datumesh_core::TrustLabel::Unverified
}
}
pub fn answer_reply(answer: &datumesh_core::Answer, cache: Cache) -> Reply {
Reply::json(answer.status(), answer.to_json(), cache)
}
pub fn with_fn_hash(answer: datumesh_core::Answer, fn_hash: Option<&str>) -> datumesh_core::Answer {
match fn_hash {
Some(h) => answer.clone().with_fn_hash(h).unwrap_or(answer),
None => answer,
}
}
pub fn error_answer_reply(code: ErrorCode, fn_hash: Option<&str>) -> Reply {
match datumesh_core::Answer::error(code) {
Ok(a) => {
let a = with_fn_hash(a, fn_hash).with_status(error_status(code));
answer_reply(&a, Cache::NoStore)
}
Err(_) => error_reply(ErrorCode::EvalUnavailable),
}
}
pub fn name_unbound_reply(max_age: u64) -> Reply {
match datumesh_core::Answer::not_covered().with_error(ErrorCode::NameUnbound) {
Ok(a) => answer_reply(&a, Cache::Public(max_age)),
Err(_) => Reply::json(404, not_covered(None), Cache::Public(max_age)),
}
}