use std::collections::BTreeMap;
use std::sync::Arc;
use datumesh_core::json::Value;
use datumesh_core::{
format_reference, lexical, parse_reference, Arg, Cell, CellRef, ErrorCode, FunctionDescriptor, Reference,
};
#[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);
}
fn pinned(&self, fn_hash: &str) -> Result<Option<Arc<Bound>>, ErrorCode> {
let _ = fn_hash;
Ok(None)
}
fn alias(&self, alias: &str) -> Option<String> {
let _ = alias;
None
}
}
#[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>,
pub pin: Option<String>,
}
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 pinned_reference(&self) -> Reference {
let mut r = Reference::from(self.reference.clone());
r.fn_hash = self.pin.clone();
r
}
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()
}
fn structural(code: ErrorCode) -> bool {
matches!(
code,
ErrorCode::ParseUri
| ErrorCode::CanonName
| ErrorCode::CanonArgName
| ErrorCode::CanonArgDuplicate
| ErrorCode::CanonArgOrder
| ErrorCode::CanonPercent
| ErrorCode::CanonInstant
| ErrorCode::CanonHex
)
}
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 ps = params(query.unwrap_or(""));
let mut rest_ps: &[(&str, &str)] = &ps;
let mut asof = now;
if let Some((("asof", v), before)) = rest_ps.split_last() {
if lexical::check_instant(v, "$").is_ok() {
asof = v;
}
rest_ps = before;
}
let pin = match rest_ps.last() {
Some(("fn_hash", v)) if lexical::check_hex(v, 64, "$").is_ok() => Some(v.to_string()),
_ => None,
};
let name_ok = lexical::check_function_name(path, "$").is_ok() && !path.contains('#');
let bound = match (&pin, name_ok) {
(Some(p), true) => bindings.pinned(p).map_err(Rejection::Error)?,
(None, true) => bindings.binding(path, asof).map_err(Rejection::Error)?,
(_, false) => 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 Some(bound) = bound else {
let mut sig = Vec::new();
for (name, _) in &ps {
if *name != "asof" && *name != "fn_hash" {
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_reference(&uri, &signature) {
Err(e) if structural(e.code()) => Err(Rejection::BadRequest(e.code())),
_ if pin.is_some() || !name_ok => Err(Rejection::NotCovered),
_ => Err(Rejection::Error(ErrorCode::NameUnbound)),
};
};
let reference = parse_reference(&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::SliceAtCell));
}
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 pin = reference.fn_hash.clone();
let cell_ref = CellRef { ns: reference.ns, fn_name: reference.fn_name, args: reference.args, asof: reference.asof };
let t = Arc::new(Target {
uri,
reference: cell_ref,
cell,
id: std::sync::OnceLock::new(),
key: std::sync::OnceLock::new(),
bound,
pin,
});
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()
}
struct Env<'a> {
bindings: &'a dyn Bindings,
aliases: &'a BTreeMap<String, String>,
now: &'a str,
}
impl datumesh_formula::call::CallEnv for Env<'_> {
fn alias(&self, alias: &str) -> Result<Option<String>, String> {
Ok(self.aliases.get(alias).cloned().or_else(|| self.bindings.alias(alias)))
}
fn bound(&self, name: &str, asof: Option<&str>) -> Result<Option<FunctionDescriptor>, String> {
match self.bindings.binding(name, asof.unwrap_or(self.now)) {
Ok(b) => Ok(b.map(|b| (*b.descriptor).clone())),
Err(c) => Err(c.as_str().to_string()),
}
}
fn pinned(&self, fn_hash: &str) -> Result<Option<FunctionDescriptor>, String> {
match self.bindings.pinned(fn_hash) {
Ok(b) => Ok(b.map(|b| (*b.descriptor).clone())),
Err(c) => Err(c.as_str().to_string()),
}
}
}
pub fn resolve_call(
rest: &str,
now: &str,
aliases: &BTreeMap<String, String>,
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 mut text = url_decode(path).ok_or(Rejection::BadRequest(ErrorCode::CanonPercent))?;
if let Some(q) = query {
text.push('?');
text.push_str(q);
}
let env = Env { bindings, aliases, now };
let call = datumesh_formula::call::parse_call(text.trim_start(), &env).map_err(|e| match e {
datumesh_formula::call::CallError::Code(c, _) => match ErrorCode::from_code(c) {
Some(ErrorCode::NameUnbound) => Rejection::Error(ErrorCode::NameUnbound),
Some(ErrorCode::FnUnavailable) => Rejection::NotCovered,
Some(code) if crate::envelope::is_request_code(code) => Rejection::BadRequest(code),
_ => Rejection::BadRequest(ErrorCode::ParseUri),
},
datumesh_formula::call::CallError::Env(m) => {
Rejection::Error(ErrorCode::from_code(&m).unwrap_or(ErrorCode::InputUnavailable))
}
_ => Rejection::Error(ErrorCode::EvalUnavailable),
})?;
let uri = call.uri();
if !slice && call.cell.args.values().any(|a| matches!(a, Arg::Slice)) {
return Err(Rejection::BadRequest(ErrorCode::SliceAtCell));
}
resolve_uri(&uri["cell://".len()..], now, bindings, slice)
}
pub fn format_pinned(reference: &Reference) -> String {
format_reference(reference)
}