1use std::collections::BTreeMap;
35use std::sync::Arc;
36
37use datumesh_core::json::Value;
38use datumesh_core::{
39 format_reference, lexical, parse_reference, Arg, Cell, CellRef, ClassDescriptor, ErrorCode, FunctionDescriptor,
40 Reference, Resolved,
41};
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
64#[derive(Clone, Debug)]
67pub struct BoundClass {
68 pub class_hash: String,
70 pub since: String,
72 pub descriptor: Arc<ClassDescriptor>,
74}
75
76pub trait Bindings {
79 fn binding(&self, fn_name: &str, asof: &str) -> Result<Option<Arc<Bound>>, ErrorCode>;
82
83 fn cached(&self, fn_hash: &str, rest: &str) -> Option<Arc<Target>> {
86 let _ = (fn_hash, rest);
87 None
88 }
89
90 fn remember(&self, rest: &str, target: &Arc<Target>) {
92 let _ = (rest, target);
93 }
94
95 fn pinned(&self, fn_hash: &str) -> Result<Option<Arc<Bound>>, ErrorCode> {
98 let _ = fn_hash;
99 Ok(None)
100 }
101
102 fn listing(&self, name: &str) -> Result<Option<datumesh_store::Listing>, crate::listing::ListingError> {
105 let _ = name;
106 Ok(None)
107 }
108
109 fn alias(&self, alias: &str) -> Option<String> {
111 let _ = alias;
112 None
113 }
114
115 fn class(&self, name: &str, asof: &str) -> Result<Option<Arc<BoundClass>>, ErrorCode> {
118 let _ = (name, asof);
119 Ok(None)
120 }
121
122 fn aliases_tx(&self) -> Option<String> {
125 None
126 }
127
128 fn lookup(&self, class: &str, label: &str, asof: &str) -> Result<Option<String>, ErrorCode> {
132 let _ = (class, label, asof);
133 Ok(None)
134 }
135
136 fn class_name_of(&self, class_hash: &str, asof: &str) -> Result<Option<String>, ErrorCode> {
139 let _ = (class_hash, asof);
140 Ok(None)
141 }
142
143 fn class_by_hash(&self, class_hash: &str) -> Result<Option<ClassDescriptor>, ErrorCode> {
145 let _ = class_hash;
146 Ok(None)
147 }
148
149 fn chain(&self, cell: &CellRef, asof: &str) -> Result<Option<String>, ErrorCode> {
152 let _ = (cell, asof);
153 Ok(None)
154 }
155
156 fn lookup_read(&self, class: &str, label: &str, asof: &str, current: bool) -> Result<Option<String>, ErrorCode> {
160 let _ = current;
161 self.lookup(class, label, asof)
162 }
163
164 fn chain_read(&self, cell: &CellRef, asof: &str, current: bool) -> Result<Option<String>, ErrorCode> {
167 let _ = current;
168 self.chain(cell, asof)
169 }
170}
171
172#[derive(Clone, Debug)]
174pub struct Target {
175 pub uri: String,
177 pub reference: CellRef,
179 pub cell: Cell,
181 id: std::sync::OnceLock<String>,
182 key: std::sync::OnceLock<String>,
183 pub bound: Arc<Bound>,
185 pub pin: Option<String>,
187 pub resolved: Option<Resolved>,
190}
191
192impl Target {
193 pub fn fn_name(&self) -> String {
195 format!("{}/{}", self.reference.ns, self.reference.fn_name)
196 }
197
198 pub fn cell_id(&self) -> &str {
200 self.id.get_or_init(|| self.cell.id())
201 }
202
203 pub fn cell_key(&self) -> &str {
205 self.key.get_or_init(|| {
206 let rest = self.rest();
207 let base = match self.asof() {
208 Some(a) => &rest[..rest.len() - a.len() - "asof=".len() - 1],
209 None => rest,
210 };
211 format!("{} {}", self.bound.fn_hash, base)
212 })
213 }
214
215 pub fn pinned_reference(&self) -> Reference {
217 let mut r = Reference::from(self.reference.clone());
218 r.fn_hash = self.pin.clone();
219 r
220 }
221
222 pub fn asof(&self) -> Option<&str> {
224 self.reference.asof.as_deref()
225 }
226
227 pub fn rest(&self) -> &str {
229 &self.uri["cell://".len()..]
230 }
231
232 pub fn rest_asof(&self, asof: &str) -> String {
234 let rest = self.rest();
235 let base = match self.reference.asof.as_deref() {
236 Some(a) => &rest[..rest.len() - a.len() - "asof=".len() - 1],
238 None => rest,
239 };
240 let sep = if base.contains('?') { '&' } else { '?' };
241 format!("{base}{sep}asof={asof}")
242 }
243}
244
245#[derive(Clone, Copy, Debug, PartialEq, Eq)]
247pub enum Rejection {
248 BadRequest(ErrorCode),
250 NotCovered,
252 Error(ErrorCode),
256}
257
258thread_local! {
259 static CALL_FAULT: std::cell::Cell<Option<datumesh_core::Fault>> = const { std::cell::Cell::new(None) };
263}
264
265pub(crate) fn take_fault() -> Option<datumesh_core::Fault> {
267 CALL_FAULT.with(|f| f.take())
268}
269
270thread_local! {
271 static LABEL_WITHDRAWN: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
273}
274
275pub(crate) fn set_label_withdrawn(reason: String) {
277 LABEL_WITHDRAWN.with(|l| *l.borrow_mut() = Some(reason));
278}
279
280pub(crate) fn take_label_withdrawn() -> Option<String> {
282 LABEL_WITHDRAWN.with(|l| l.borrow_mut().take())
283}
284
285pub fn is_call(rest: &str) -> bool {
289 let path = rest.split('?').next().unwrap_or("");
290 path.contains('(') || path.contains('%') || path.starts_with('@')
291}
292
293pub fn resolve(
297 rest: &str,
298 now: &str,
299 aliases: &BTreeMap<String, String>,
300 bindings: &dyn Bindings,
301 slice: bool,
302) -> Result<Arc<Target>, Rejection> {
303 let rest = crate::instant::in_query(rest);
305 if is_call(&rest) {
306 resolve_call(&rest, now, aliases, bindings, slice)
307 } else {
308 resolve_uri(&rest, now, bindings, slice)
309 }
310}
311
312fn params(query: &str) -> Vec<(&str, &str)> {
315 if query.is_empty() {
316 return vec![];
317 }
318 query.split('&').map(|p| p.split_once('=').unwrap_or((p, ""))).collect()
319}
320
321fn structural(code: ErrorCode) -> bool {
325 matches!(
326 code,
327 ErrorCode::ParseUri
328 | ErrorCode::CanonName
329 | ErrorCode::CanonArgName
330 | ErrorCode::CanonArgDuplicate
331 | ErrorCode::CanonArgOrder
332 | ErrorCode::CanonPercent
333 | ErrorCode::CanonInstant
334 | ErrorCode::CanonHex
335 )
336}
337
338pub fn resolve_uri(rest: &str, now: &str, bindings: &dyn Bindings, slice: bool) -> Result<Arc<Target>, Rejection> {
340 let (path, query) = match rest.split_once('?') {
341 Some((p, q)) => (p, Some(q)),
342 None => (rest, None),
343 };
344 let ps = params(query.unwrap_or(""));
345 let mut rest_ps: &[(&str, &str)] = &ps;
348 let mut asof = now;
349 if let Some((("asof", v), before)) = rest_ps.split_last() {
350 if lexical::check_instant(v, "$").is_ok() {
351 asof = v;
352 }
353 rest_ps = before;
354 }
355 let pin = match rest_ps.last() {
356 Some(("fn_hash", v)) if lexical::check_hex(v, 64, "$").is_ok() => Some(v.to_string()),
357 _ => None,
358 };
359 let name_ok = lexical::check_function_name(path, "$").is_ok() && !path.contains('#');
360 let bound = match (&pin, name_ok) {
361 (Some(p), true) => bindings.pinned(p).map_err(Rejection::Error)?,
362 (None, true) => bindings.binding(path, asof).map_err(Rejection::Error)?,
363 (_, false) => None,
364 };
365 if let Some(b) = &bound {
366 if let Some(t) = bindings.cached(&b.fn_hash, rest) {
367 if t.reference.args.values().any(|a| matches!(a, Arg::Slice)) == slice {
368 return Ok(t);
369 }
370 }
371 }
372 let uri = format!("cell://{rest}");
373 let Some(bound) = bound else {
374 let mut sig = Vec::new();
377 for (name, _) in &ps {
378 if *name != "asof" && *name != "fn_hash" {
379 sig.push((name.to_string(), Value::Object(vec![("type".into(), Value::String("string".into()))])));
380 }
381 }
382 let signature = Value::Object(vec![("args".into(), Value::Object(sig))]);
383 let name_error = if path.contains('#') { None } else { lexical::check_function_name(path, "$").err() };
386 return match parse_reference(&uri, &signature) {
387 Err(e) if structural(e.code()) => Err(Rejection::BadRequest(e.code())),
388 _ if name_error.is_some() => {
389 Err(Rejection::BadRequest(name_error.map_or(ErrorCode::CanonName, |e| e.code())))
390 }
391 _ if pin.is_some() || !name_ok => Err(Rejection::NotCovered),
392 _ => Err(Rejection::Error(ErrorCode::NameUnbound)),
393 };
394 };
395 let reference = parse_reference(&uri, &bound.signature).map_err(|e| {
396 if crate::envelope::is_request_code(e.code()) {
397 Rejection::BadRequest(e.code())
398 } else {
399 Rejection::Error(ErrorCode::EvalUnavailable)
400 }
401 })?;
402 let has_slice = reference.args.values().any(|a| matches!(a, Arg::Slice));
403 if has_slice && !slice {
404 return Err(Rejection::BadRequest(ErrorCode::SliceAtCell));
405 }
406 if !has_slice && slice {
407 return Err(Rejection::BadRequest(ErrorCode::ParseUri));
409 }
410 let cell = Cell {
411 ns: reference.ns.clone(),
412 fn_name: reference.fn_name.clone(),
413 fn_hash: bound.fn_hash.clone(),
414 args: reference.args.clone(),
415 };
416 let pin = reference.fn_hash.clone();
417 let cell_ref = CellRef { ns: reference.ns, fn_name: reference.fn_name, args: reference.args, asof: reference.asof };
418 let t = Arc::new(Target {
420 uri,
421 reference: cell_ref,
422 cell,
423 id: std::sync::OnceLock::new(),
424 key: std::sync::OnceLock::new(),
425 bound,
426 pin,
427 resolved: None,
428 });
429 bindings.remember(rest, &t);
430 Ok(t)
431}
432
433pub(crate) fn url_decode(s: &str) -> Option<String> {
435 let b = s.as_bytes();
436 let mut out = Vec::with_capacity(b.len());
437 let mut i = 0;
438 while i < b.len() {
439 if b[i] == b'%' {
440 let h = std::str::from_utf8(b.get(i + 1..i + 3)?).ok()?;
441 out.push(u8::from_str_radix(h, 16).ok()?);
442 i += 3;
443 } else {
444 out.push(b[i]);
445 i += 1;
446 }
447 }
448 String::from_utf8(out).ok()
449}
450
451struct Env<'a> {
454 bindings: &'a dyn Bindings,
455 aliases: &'a BTreeMap<String, String>,
456 now: &'a str,
457 current: bool,
459}
460
461impl datumesh_formula::call::CallEnv for Env<'_> {
462 fn alias(&self, alias: &str) -> Result<Option<String>, String> {
463 Ok(self.aliases.get(alias).cloned().or_else(|| self.bindings.alias(alias)))
464 }
465 fn bound(&self, name: &str, asof: Option<&str>) -> Result<Option<FunctionDescriptor>, String> {
466 match self.bindings.binding(name, asof.unwrap_or(self.now)) {
467 Ok(b) => Ok(b.map(|b| (*b.descriptor).clone())),
468 Err(c) => Err(c.as_str().to_string()),
469 }
470 }
471 fn pinned(&self, fn_hash: &str) -> Result<Option<FunctionDescriptor>, String> {
472 match self.bindings.pinned(fn_hash) {
473 Ok(b) => Ok(b.map(|b| (*b.descriptor).clone())),
474 Err(c) => Err(c.as_str().to_string()),
475 }
476 }
477 fn bound_class(&self, name: &str, asof: Option<&str>) -> Result<Option<ClassDescriptor>, String> {
478 match self.bindings.class(name, asof.unwrap_or(self.now)) {
479 Ok(c) => Ok(c.map(|c| (*c.descriptor).clone())),
480 Err(c) => Err(c.as_str().to_string()),
481 }
482 }
483 fn aliases_tx(&self) -> Result<Option<String>, String> {
484 Ok(self.bindings.aliases_tx())
485 }
486 fn now(&self) -> Result<Option<String>, String> {
487 Ok(Some(self.now.to_string()))
488 }
489 fn lookup(&self, class: &str, label: &str, asof: &str) -> Result<Option<String>, String> {
490 self.bindings.lookup_read(class, label, asof, self.current).map_err(|c| c.as_str().to_string())
491 }
492 fn class_name_of(&self, class_hash: &str, asof: Option<&str>) -> Result<Option<String>, String> {
493 self.bindings.class_name_of(class_hash, asof.unwrap_or(self.now)).map_err(|c| c.as_str().to_string())
494 }
495 fn class_descriptor_of(&self, class_hash: &str, _asof: Option<&str>) -> Result<Option<ClassDescriptor>, String> {
496 self.bindings.class_by_hash(class_hash).map_err(|c| c.as_str().to_string())
497 }
498 fn chain(&self, cell: &CellRef, asof: &str) -> Result<Option<String>, String> {
499 self.bindings.chain_read(cell, asof, self.current).map_err(|c| c.as_str().to_string())
500 }
501}
502
503const MAX_CHAIN_LINKS: usize = 8;
505
506fn chain_links(text: &str) -> usize {
509 let (mut depth, mut quoted, mut seen_group, mut links) = (0i32, false, false, 0usize);
510 for c in text.chars() {
511 if quoted {
512 quoted = c != '"';
513 continue;
514 }
515 match c {
516 '"' => quoted = true,
517 '(' | '[' => depth += 1,
518 ')' | ']' => {
519 depth -= 1;
520 if depth == 0 {
521 seen_group = true;
522 }
523 }
524 '.' if depth == 0 && seen_group => links += 1,
525 _ => {}
526 }
527 }
528 links
529}
530
531fn is_current(query: Option<&str>) -> bool {
534 !query.is_some_and(|q| q.split('&').any(|p| p.starts_with("asof=")))
535}
536
537pub fn resolve_call(
539 rest: &str,
540 now: &str,
541 aliases: &BTreeMap<String, String>,
542 bindings: &dyn Bindings,
543 slice: bool,
544) -> Result<Arc<Target>, Rejection> {
545 let (path, query) = match rest.split_once('?') {
546 Some((p, q)) => (p, Some(q)),
547 None => (rest, None),
548 };
549 let mut text = url_decode(path).ok_or(Rejection::BadRequest(ErrorCode::CanonPercent))?;
550 if let Some(q) = query {
551 text.push('?');
552 text.push_str(q);
553 }
554 if chain_links(&text) > MAX_CHAIN_LINKS {
556 return Err(Rejection::BadRequest(ErrorCode::ParseUri));
557 }
558 let current = is_current(query);
560 let env = Env { bindings, aliases, now, current };
561 CALL_FAULT.with(|f| f.set(None));
562 LABEL_WITHDRAWN.with(|l| *l.borrow_mut() = None);
563 let call = datumesh_formula::call::parse_call(text.trim_start(), &env).map_err(|e| match e {
564 datumesh_formula::call::CallError::Code("E_FORMULA_DISPATCH_KEY", _) => {
565 CALL_FAULT.with(|f| f.set(Some(datumesh_core::Fault::DispatchKey)));
566 Rejection::NotCovered
567 }
568 datumesh_formula::call::CallError::Code(c, _) => match ErrorCode::from_code(c) {
569 Some(ErrorCode::NameUnbound) => Rejection::Error(ErrorCode::NameUnbound),
570 Some(ErrorCode::FnUnavailable) => Rejection::NotCovered,
571 Some(code) if crate::envelope::is_request_code(code) => Rejection::BadRequest(code),
572 _ => Rejection::BadRequest(ErrorCode::ParseUri),
573 },
574 datumesh_formula::call::CallError::Env(m) => {
575 Rejection::Error(ErrorCode::from_code(&m).unwrap_or(ErrorCode::InputUnavailable))
576 }
577 _ => Rejection::Error(ErrorCode::EvalUnavailable),
578 })?;
579 let uri = call.uri();
580 if !slice && call.cell.args.values().any(|a| matches!(a, Arg::Slice)) {
581 return Err(Rejection::BadRequest(ErrorCode::SliceAtCell));
582 }
583 let target = resolve_uri(&uri["cell://".len()..], now, bindings, slice)?;
584 match call.resolved {
585 Some(r) => {
588 let mut t = (*target).clone();
589 t.resolved = Some(r);
590 Ok(Arc::new(t))
591 }
592 None => Ok(target),
593 }
594}
595
596pub fn format_pinned(reference: &Reference) -> String {
598 format_reference(reference)
599}