use std::collections::BTreeMap;
use std::sync::Arc;
use datumesh_core::json::{self, Value};
use datumesh_core::{
format_uri, lexical, parse_uri, Arg, Args, Cell, CellRef, ErrorCode, FunctionDescriptor, Scalar, Type,
};
use datumesh_formula::{canonical_ast, Code, Env, Node, Op, ReadArg, Signature as FSignature};
#[derive(Clone, Debug)]
pub struct Bound {
pub fn_hash: String,
pub since: String,
pub descriptor: Arc<FunctionDescriptor>,
pub signature: Arc<Value>,
}
impl Bound {
pub fn new(fn_hash: impl Into<String>, since: impl Into<String>, descriptor: Arc<FunctionDescriptor>) -> Bound {
let signature = Arc::new(descriptor.signature.to_value());
Bound { fn_hash: fn_hash.into(), since: since.into(), descriptor, signature }
}
}
pub trait Bindings {
fn binding(&self, fn_name: &str, asof: &str) -> Result<Option<Arc<Bound>>, ErrorCode>;
fn cached(&self, fn_hash: &str, rest: &str) -> Option<Arc<Target>> {
let _ = (fn_hash, rest);
None
}
fn remember(&self, rest: &str, target: &Arc<Target>) {
let _ = (rest, target);
}
}
#[derive(Clone, Debug)]
pub struct Target {
pub uri: String,
pub reference: CellRef,
pub cell: Cell,
id: std::sync::OnceLock<String>,
key: std::sync::OnceLock<String>,
pub bound: Arc<Bound>,
}
impl Target {
pub fn fn_name(&self) -> String {
format!("{}/{}", self.reference.ns, self.reference.fn_name)
}
pub fn cell_id(&self) -> &str {
self.id.get_or_init(|| self.cell.id())
}
pub fn cell_key(&self) -> &str {
self.key.get_or_init(|| {
let rest = self.rest();
let base = match self.asof() {
Some(a) => &rest[..rest.len() - a.len() - "asof=".len() - 1],
None => rest,
};
format!("{} {}", self.bound.fn_hash, base)
})
}
pub fn asof(&self) -> Option<&str> {
self.reference.asof.as_deref()
}
pub fn rest(&self) -> &str {
&self.uri["cell://".len()..]
}
pub fn rest_asof(&self, asof: &str) -> String {
let rest = self.rest();
let base = match self.reference.asof.as_deref() {
Some(a) => &rest[..rest.len() - a.len() - "asof=".len() - 1],
None => rest,
};
let sep = if base.contains('?') { '&' } else { '?' };
format!("{base}{sep}asof={asof}")
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Rejection {
BadRequest(ErrorCode),
NotCovered,
Error(ErrorCode),
}
pub fn is_call(rest: &str) -> bool {
let path = rest.split('?').next().unwrap_or("");
path.contains('(') || path.contains('%') || path.starts_with('@')
}
pub fn resolve(
rest: &str,
now: &str,
aliases: &BTreeMap<String, String>,
bindings: &dyn Bindings,
slice: bool,
) -> Result<Arc<Target>, Rejection> {
if is_call(rest) {
resolve_call(rest, now, aliases, bindings, slice)
} else {
resolve_uri(rest, now, bindings, slice)
}
}
fn params(query: &str) -> Vec<(&str, &str)> {
if query.is_empty() {
return vec![];
}
query.split('&').map(|p| p.split_once('=').unwrap_or((p, ""))).collect()
}
pub fn resolve_uri(rest: &str, now: &str, bindings: &dyn Bindings, slice: bool) -> Result<Arc<Target>, Rejection> {
let (path, query) = match rest.split_once('?') {
Some((p, q)) => (p, Some(q)),
None => (rest, None),
};
let last = query.map(|q| q.rsplit('&').next().unwrap_or(q));
let asof = match last.and_then(|p| p.strip_prefix("asof=")) {
Some(v) if lexical::check_instant(v, "$").is_ok() => v,
_ => now,
};
let bound = if lexical::check_function_name(path, "$").is_ok() && !path.contains('#') {
bindings.binding(path, asof).map_err(Rejection::Error)?
} else {
None
};
if let Some(b) = &bound {
if let Some(t) = bindings.cached(&b.fn_hash, rest) {
if t.reference.args.values().any(|a| matches!(a, Arg::Slice)) == slice {
return Ok(t);
}
}
}
let uri = format!("cell://{rest}");
let ps = params(query.unwrap_or(""));
let Some(bound) = bound else {
let mut sig = Vec::new();
for (name, _) in &ps {
if *name != "asof" {
sig.push((name.to_string(), Value::Object(vec![("type".into(), Value::String("string".into()))])));
}
}
let signature = Value::Object(vec![("args".into(), Value::Object(sig))]);
return match parse_uri(&uri, &signature) {
Err(e)
if matches!(
e.code(),
ErrorCode::ParseUri
| ErrorCode::CanonName
| ErrorCode::CanonArgName
| ErrorCode::CanonArgDuplicate
| ErrorCode::CanonArgOrder
| ErrorCode::CanonPercent
| ErrorCode::CanonInstant
) =>
{
Err(Rejection::BadRequest(e.code()))
}
_ => Err(Rejection::NotCovered),
};
};
let reference = parse_uri(&uri, &bound.signature).map_err(|e| {
if crate::envelope::is_request_code(e.code()) {
Rejection::BadRequest(e.code())
} else {
Rejection::Error(ErrorCode::EvalUnavailable)
}
})?;
let has_slice = reference.args.values().any(|a| matches!(a, Arg::Slice));
if has_slice != slice {
return Err(Rejection::BadRequest(ErrorCode::ParseUri));
}
let cell = Cell {
ns: reference.ns.clone(),
fn_name: reference.fn_name.clone(),
fn_hash: bound.fn_hash.clone(),
args: reference.args.clone(),
};
let t = Arc::new(Target {
uri,
reference,
cell,
id: std::sync::OnceLock::new(),
key: std::sync::OnceLock::new(),
bound,
});
bindings.remember(rest, &t);
Ok(t)
}
fn url_decode(s: &str) -> Option<String> {
let b = s.as_bytes();
let mut out = Vec::with_capacity(b.len());
let mut i = 0;
while i < b.len() {
if b[i] == b'%' {
let h = std::str::from_utf8(b.get(i + 1..i + 3)?).ok()?;
out.push(u8::from_str_radix(h, 16).ok()?);
i += 3;
} else {
out.push(b[i]);
i += 1;
}
}
String::from_utf8(out).ok()
}
fn formula_code(c: Code) -> ErrorCode {
match c {
Code::ArgUnknown => ErrorCode::ArgUnknown,
Code::ArgMissing => ErrorCode::ArgMissing,
Code::ArgDuplicate => ErrorCode::CanonArgDuplicate,
Code::Number => ErrorCode::CanonNumber,
Code::String => ErrorCode::CanonString,
Code::Date => ErrorCode::CanonDate,
Code::Instant => ErrorCode::CanonInstant,
_ => ErrorCode::ParseUri,
}
}
fn literal(ast: &datumesh_formula::Ast, id: datumesh_formula::NodeId, ty: Type) -> Result<Scalar, ErrorCode> {
let (kind, text) = match ast.node(id) {
Node::Num { value, unit: None } => (Type::Number, value.clone()),
Node::Op { op: Op::Neg, args } if args.len() == 1 => match ast.node(args[0]) {
Node::Num { value, unit: None } => (Type::Number, format!("-{value}")),
_ => return Err(ErrorCode::ParseUri),
},
Node::Str(s) => (if ty == Type::Blob { Type::Blob } else { Type::String }, s.clone()),
Node::Bool(b) => (Type::Boolean, b.to_string()),
Node::Date(d) => (Type::Date, d.clone()),
Node::Instant(t) => (Type::Instant, t.clone()),
_ => return Err(ErrorCode::ParseUri),
};
if kind != ty {
return Err(ErrorCode::CanonType);
}
Scalar::from_lexical(ty, &text).map_err(|e| e.code())
}
pub fn resolve_call(
rest: &str,
now: &str,
aliases: &BTreeMap<String, String>,
bindings: &dyn Bindings,
slice: bool,
) -> Result<Arc<Target>, Rejection> {
let bad = Rejection::BadRequest(ErrorCode::ParseUri);
let (path, query) = match rest.split_once('?') {
Some((p, q)) => (p, Some(q)),
None => (rest, None),
};
let asof = match query {
None => None,
Some(q) => match q.strip_prefix("asof=") {
Some(v) if !v.contains('&') => {
lexical::check_instant(v, "$").map_err(|e| Rejection::BadRequest(e.code()))?;
Some(v.to_string())
}
_ => return Err(bad),
},
};
let text = url_decode(path).ok_or(Rejection::BadRequest(ErrorCode::CanonPercent))?;
let open = text.find('(').ok_or(bad)?;
let callee = text[..open].trim();
let name = match callee.strip_prefix('@') {
Some(alias) => match aliases.get(alias) {
Some(n) => n.clone(),
None => return Err(Rejection::NotCovered),
},
None => {
lexical::check_function_name(callee, "$").map_err(|_| Rejection::BadRequest(ErrorCode::CanonName))?;
callee.to_string()
}
};
let at = asof.as_deref().unwrap_or(now);
let bound = bindings.binding(&name, at).map_err(Rejection::Error)?.ok_or(Rejection::NotCovered)?;
let sig = FSignature::from_value(
&json::parse(br#"{"args":{},"returns":{"type":"number","unit":"EUR"}}"#)
.map_err(|_| Rejection::Error(ErrorCode::EvalUnavailable))?,
)
.map_err(|_| Rejection::Error(ErrorCode::EvalUnavailable))?;
let mut env = Env::new("datumesh.invalid/call", sig);
env.add_function(&name, &bound.descriptor.to_value()).map_err(|_| Rejection::Error(ErrorCode::EvalUnavailable))?;
for (a, n) in aliases {
env.aliases.insert(a.clone(), n.clone());
}
let ast = canonical_ast(&text, Some(&env)).map_err(|e| Rejection::BadRequest(formula_code(e.code)))?;
let Node::Read { fn_name, args } = ast.node(ast.root()) else {
return Err(bad);
};
if *fn_name != name {
return Err(bad);
}
let (ns, f) = name.rsplit_once('/').ok_or(bad)?;
let mut out = Args::new();
for (arg, a) in args {
let ty = bound
.descriptor
.signature
.args
.get(arg)
.map(|d| d.ty)
.ok_or(Rejection::BadRequest(ErrorCode::ArgUnknown))?;
let v = match a {
ReadArg::Open if slice => Arg::Slice,
ReadArg::Open | ReadArg::Range(..) => return Err(bad),
ReadArg::Expr(id) => Arg::Value(literal(&ast, *id, ty).map_err(Rejection::BadRequest)?),
};
out.insert(arg.clone(), v);
}
let reference = CellRef { ns: ns.to_string(), fn_name: f.to_string(), args: out, asof };
let uri = format_uri(&reference);
resolve_uri(&uri["cell://".len()..], now, bindings, slice)
}