1use std::collections::BTreeMap;
35use std::sync::Arc;
36
37use datumesh_core::json::{self, Value};
38use datumesh_core::{
39 format_uri, lexical, parse_uri, Arg, Args, Cell, CellRef, ErrorCode, FunctionDescriptor, Scalar, Type,
40};
41use datumesh_formula::{canonical_ast, Code, Env, Node, Op, ReadArg, Signature as FSignature};
42
43#[derive(Clone, Debug)]
45pub struct Bound {
46 pub fn_hash: String,
48 pub since: String,
50 pub descriptor: Arc<FunctionDescriptor>,
52 pub signature: Arc<Value>,
54}
55
56impl Bound {
57 pub fn new(fn_hash: impl Into<String>, since: impl Into<String>, descriptor: Arc<FunctionDescriptor>) -> Bound {
59 let signature = Arc::new(descriptor.signature.to_value());
60 Bound { fn_hash: fn_hash.into(), since: since.into(), descriptor, signature }
61 }
62}
63
64pub trait Bindings {
67 fn binding(&self, fn_name: &str, asof: &str) -> Result<Option<Arc<Bound>>, ErrorCode>;
70
71 fn cached(&self, fn_hash: &str, rest: &str) -> Option<Arc<Target>> {
74 let _ = (fn_hash, rest);
75 None
76 }
77
78 fn remember(&self, rest: &str, target: &Arc<Target>) {
80 let _ = (rest, target);
81 }
82}
83
84#[derive(Clone, Debug)]
86pub struct Target {
87 pub uri: String,
89 pub reference: CellRef,
91 pub cell: Cell,
93 id: std::sync::OnceLock<String>,
94 key: std::sync::OnceLock<String>,
95 pub bound: Arc<Bound>,
97}
98
99impl Target {
100 pub fn fn_name(&self) -> String {
102 format!("{}/{}", self.reference.ns, self.reference.fn_name)
103 }
104
105 pub fn cell_id(&self) -> &str {
107 self.id.get_or_init(|| self.cell.id())
108 }
109
110 pub fn cell_key(&self) -> &str {
112 self.key.get_or_init(|| {
113 let rest = self.rest();
114 let base = match self.asof() {
115 Some(a) => &rest[..rest.len() - a.len() - "asof=".len() - 1],
116 None => rest,
117 };
118 format!("{} {}", self.bound.fn_hash, base)
119 })
120 }
121
122 pub fn asof(&self) -> Option<&str> {
124 self.reference.asof.as_deref()
125 }
126
127 pub fn rest(&self) -> &str {
129 &self.uri["cell://".len()..]
130 }
131
132 pub fn rest_asof(&self, asof: &str) -> String {
134 let rest = self.rest();
135 let base = match self.reference.asof.as_deref() {
136 Some(a) => &rest[..rest.len() - a.len() - "asof=".len() - 1],
138 None => rest,
139 };
140 let sep = if base.contains('?') { '&' } else { '?' };
141 format!("{base}{sep}asof={asof}")
142 }
143}
144
145#[derive(Clone, Copy, Debug, PartialEq, Eq)]
147pub enum Rejection {
148 BadRequest(ErrorCode),
150 NotCovered,
152 Error(ErrorCode),
154}
155
156pub fn is_call(rest: &str) -> bool {
160 let path = rest.split('?').next().unwrap_or("");
161 path.contains('(') || path.contains('%') || path.starts_with('@')
162}
163
164pub fn resolve(
167 rest: &str,
168 now: &str,
169 aliases: &BTreeMap<String, String>,
170 bindings: &dyn Bindings,
171 slice: bool,
172) -> Result<Arc<Target>, Rejection> {
173 if is_call(rest) {
174 resolve_call(rest, now, aliases, bindings, slice)
175 } else {
176 resolve_uri(rest, now, bindings, slice)
177 }
178}
179
180fn params(query: &str) -> Vec<(&str, &str)> {
183 if query.is_empty() {
184 return vec![];
185 }
186 query.split('&').map(|p| p.split_once('=').unwrap_or((p, ""))).collect()
187}
188
189pub fn resolve_uri(rest: &str, now: &str, bindings: &dyn Bindings, slice: bool) -> Result<Arc<Target>, Rejection> {
191 let (path, query) = match rest.split_once('?') {
192 Some((p, q)) => (p, Some(q)),
193 None => (rest, None),
194 };
195 let last = query.map(|q| q.rsplit('&').next().unwrap_or(q));
197 let asof = match last.and_then(|p| p.strip_prefix("asof=")) {
198 Some(v) if lexical::check_instant(v, "$").is_ok() => v,
199 _ => now,
200 };
201 let bound = if lexical::check_function_name(path, "$").is_ok() && !path.contains('#') {
202 bindings.binding(path, asof).map_err(Rejection::Error)?
203 } else {
204 None
205 };
206 if let Some(b) = &bound {
207 if let Some(t) = bindings.cached(&b.fn_hash, rest) {
208 if t.reference.args.values().any(|a| matches!(a, Arg::Slice)) == slice {
209 return Ok(t);
210 }
211 }
212 }
213 let uri = format!("cell://{rest}");
214 let ps = params(query.unwrap_or(""));
215 let Some(bound) = bound else {
216 let mut sig = Vec::new();
219 for (name, _) in &ps {
220 if *name != "asof" {
221 sig.push((name.to_string(), Value::Object(vec![("type".into(), Value::String("string".into()))])));
222 }
223 }
224 let signature = Value::Object(vec![("args".into(), Value::Object(sig))]);
225 return match parse_uri(&uri, &signature) {
226 Err(e)
227 if matches!(
228 e.code(),
229 ErrorCode::ParseUri
230 | ErrorCode::CanonName
231 | ErrorCode::CanonArgName
232 | ErrorCode::CanonArgDuplicate
233 | ErrorCode::CanonArgOrder
234 | ErrorCode::CanonPercent
235 | ErrorCode::CanonInstant
236 ) =>
237 {
238 Err(Rejection::BadRequest(e.code()))
239 }
240 _ => Err(Rejection::NotCovered),
241 };
242 };
243 let reference = parse_uri(&uri, &bound.signature).map_err(|e| {
244 if crate::envelope::is_request_code(e.code()) {
245 Rejection::BadRequest(e.code())
246 } else {
247 Rejection::Error(ErrorCode::EvalUnavailable)
248 }
249 })?;
250 let has_slice = reference.args.values().any(|a| matches!(a, Arg::Slice));
251 if has_slice != slice {
252 return Err(Rejection::BadRequest(ErrorCode::ParseUri));
256 }
257 let cell = Cell {
258 ns: reference.ns.clone(),
259 fn_name: reference.fn_name.clone(),
260 fn_hash: bound.fn_hash.clone(),
261 args: reference.args.clone(),
262 };
263 let t = Arc::new(Target {
265 uri,
266 reference,
267 cell,
268 id: std::sync::OnceLock::new(),
269 key: std::sync::OnceLock::new(),
270 bound,
271 });
272 bindings.remember(rest, &t);
273 Ok(t)
274}
275
276fn url_decode(s: &str) -> Option<String> {
278 let b = s.as_bytes();
279 let mut out = Vec::with_capacity(b.len());
280 let mut i = 0;
281 while i < b.len() {
282 if b[i] == b'%' {
283 let h = std::str::from_utf8(b.get(i + 1..i + 3)?).ok()?;
284 out.push(u8::from_str_radix(h, 16).ok()?);
285 i += 3;
286 } else {
287 out.push(b[i]);
288 i += 1;
289 }
290 }
291 String::from_utf8(out).ok()
292}
293
294fn formula_code(c: Code) -> ErrorCode {
295 match c {
296 Code::ArgUnknown => ErrorCode::ArgUnknown,
297 Code::ArgMissing => ErrorCode::ArgMissing,
298 Code::ArgDuplicate => ErrorCode::CanonArgDuplicate,
299 Code::Number => ErrorCode::CanonNumber,
300 Code::String => ErrorCode::CanonString,
301 Code::Date => ErrorCode::CanonDate,
302 Code::Instant => ErrorCode::CanonInstant,
303 _ => ErrorCode::ParseUri,
304 }
305}
306
307fn literal(ast: &datumesh_formula::Ast, id: datumesh_formula::NodeId, ty: Type) -> Result<Scalar, ErrorCode> {
309 let (kind, text) = match ast.node(id) {
310 Node::Num { value, unit: None } => (Type::Number, value.clone()),
311 Node::Op { op: Op::Neg, args } if args.len() == 1 => match ast.node(args[0]) {
312 Node::Num { value, unit: None } => (Type::Number, format!("-{value}")),
313 _ => return Err(ErrorCode::ParseUri),
314 },
315 Node::Str(s) => (if ty == Type::Blob { Type::Blob } else { Type::String }, s.clone()),
316 Node::Bool(b) => (Type::Boolean, b.to_string()),
317 Node::Date(d) => (Type::Date, d.clone()),
318 Node::Instant(t) => (Type::Instant, t.clone()),
319 _ => return Err(ErrorCode::ParseUri),
320 };
321 if kind != ty {
322 return Err(ErrorCode::CanonType);
323 }
324 Scalar::from_lexical(ty, &text).map_err(|e| e.code())
325}
326
327pub fn resolve_call(
329 rest: &str,
330 now: &str,
331 aliases: &BTreeMap<String, String>,
332 bindings: &dyn Bindings,
333 slice: bool,
334) -> Result<Arc<Target>, Rejection> {
335 let bad = Rejection::BadRequest(ErrorCode::ParseUri);
336 let (path, query) = match rest.split_once('?') {
337 Some((p, q)) => (p, Some(q)),
338 None => (rest, None),
339 };
340 let asof = match query {
341 None => None,
342 Some(q) => match q.strip_prefix("asof=") {
343 Some(v) if !v.contains('&') => {
344 lexical::check_instant(v, "$").map_err(|e| Rejection::BadRequest(e.code()))?;
345 Some(v.to_string())
346 }
347 _ => return Err(bad),
348 },
349 };
350 let text = url_decode(path).ok_or(Rejection::BadRequest(ErrorCode::CanonPercent))?;
351 let open = text.find('(').ok_or(bad)?;
352 let callee = text[..open].trim();
353 let name = match callee.strip_prefix('@') {
354 Some(alias) => match aliases.get(alias) {
355 Some(n) => n.clone(),
356 None => return Err(Rejection::NotCovered),
357 },
358 None => {
359 lexical::check_function_name(callee, "$").map_err(|_| Rejection::BadRequest(ErrorCode::CanonName))?;
360 callee.to_string()
361 }
362 };
363 let at = asof.as_deref().unwrap_or(now);
364 let bound = bindings.binding(&name, at).map_err(Rejection::Error)?.ok_or(Rejection::NotCovered)?;
365 let sig = FSignature::from_value(
368 &json::parse(br#"{"args":{},"returns":{"type":"number","unit":"EUR"}}"#)
369 .map_err(|_| Rejection::Error(ErrorCode::EvalUnavailable))?,
370 )
371 .map_err(|_| Rejection::Error(ErrorCode::EvalUnavailable))?;
372 let mut env = Env::new("datumesh.invalid/call", sig);
373 env.add_function(&name, &bound.descriptor.to_value()).map_err(|_| Rejection::Error(ErrorCode::EvalUnavailable))?;
374 for (a, n) in aliases {
375 env.aliases.insert(a.clone(), n.clone());
376 }
377 let ast = canonical_ast(&text, Some(&env)).map_err(|e| Rejection::BadRequest(formula_code(e.code)))?;
378 let Node::Read { fn_name, args } = ast.node(ast.root()) else {
379 return Err(bad);
380 };
381 if *fn_name != name {
382 return Err(bad);
383 }
384 let (ns, f) = name.rsplit_once('/').ok_or(bad)?;
385 let mut out = Args::new();
386 for (arg, a) in args {
387 let ty = bound
388 .descriptor
389 .signature
390 .args
391 .get(arg)
392 .map(|d| d.ty)
393 .ok_or(Rejection::BadRequest(ErrorCode::ArgUnknown))?;
394 let v = match a {
395 ReadArg::Open if slice => Arg::Slice,
396 ReadArg::Open | ReadArg::Range(..) => return Err(bad),
397 ReadArg::Expr(id) => Arg::Value(literal(&ast, *id, ty).map_err(Rejection::BadRequest)?),
398 };
399 out.insert(arg.clone(), v);
400 }
401 let reference = CellRef { ns: ns.to_string(), fn_name: f.to_string(), args: out, asof };
402 let uri = format_uri(&reference);
403 resolve_uri(&uri["cell://".len()..], now, bindings, slice)
404}