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 alias(&self, alias: &str) -> Option<String> {
104 let _ = alias;
105 None
106 }
107
108 fn class(&self, name: &str, asof: &str) -> Result<Option<Arc<BoundClass>>, ErrorCode> {
111 let _ = (name, asof);
112 Ok(None)
113 }
114
115 fn aliases_tx(&self) -> Option<String> {
118 None
119 }
120
121 fn lookup(&self, class: &str, label: &str, asof: &str) -> Result<Option<String>, ErrorCode> {
125 let _ = (class, label, asof);
126 Ok(None)
127 }
128
129 fn class_name_of(&self, class_hash: &str, asof: &str) -> Result<Option<String>, ErrorCode> {
132 let _ = (class_hash, asof);
133 Ok(None)
134 }
135
136 fn class_by_hash(&self, class_hash: &str) -> Result<Option<ClassDescriptor>, ErrorCode> {
138 let _ = class_hash;
139 Ok(None)
140 }
141
142 fn chain(&self, cell: &CellRef, asof: &str) -> Result<Option<String>, ErrorCode> {
145 let _ = (cell, asof);
146 Ok(None)
147 }
148
149 fn lookup_read(&self, class: &str, label: &str, asof: &str, current: bool) -> Result<Option<String>, ErrorCode> {
153 let _ = current;
154 self.lookup(class, label, asof)
155 }
156
157 fn chain_read(&self, cell: &CellRef, asof: &str, current: bool) -> Result<Option<String>, ErrorCode> {
160 let _ = current;
161 self.chain(cell, asof)
162 }
163}
164
165#[derive(Clone, Debug)]
167pub struct Target {
168 pub uri: String,
170 pub reference: CellRef,
172 pub cell: Cell,
174 id: std::sync::OnceLock<String>,
175 key: std::sync::OnceLock<String>,
176 pub bound: Arc<Bound>,
178 pub pin: Option<String>,
180 pub resolved: Option<Resolved>,
183}
184
185impl Target {
186 pub fn fn_name(&self) -> String {
188 format!("{}/{}", self.reference.ns, self.reference.fn_name)
189 }
190
191 pub fn cell_id(&self) -> &str {
193 self.id.get_or_init(|| self.cell.id())
194 }
195
196 pub fn cell_key(&self) -> &str {
198 self.key.get_or_init(|| {
199 let rest = self.rest();
200 let base = match self.asof() {
201 Some(a) => &rest[..rest.len() - a.len() - "asof=".len() - 1],
202 None => rest,
203 };
204 format!("{} {}", self.bound.fn_hash, base)
205 })
206 }
207
208 pub fn pinned_reference(&self) -> Reference {
210 let mut r = Reference::from(self.reference.clone());
211 r.fn_hash = self.pin.clone();
212 r
213 }
214
215 pub fn asof(&self) -> Option<&str> {
217 self.reference.asof.as_deref()
218 }
219
220 pub fn rest(&self) -> &str {
222 &self.uri["cell://".len()..]
223 }
224
225 pub fn rest_asof(&self, asof: &str) -> String {
227 let rest = self.rest();
228 let base = match self.reference.asof.as_deref() {
229 Some(a) => &rest[..rest.len() - a.len() - "asof=".len() - 1],
231 None => rest,
232 };
233 let sep = if base.contains('?') { '&' } else { '?' };
234 format!("{base}{sep}asof={asof}")
235 }
236}
237
238#[derive(Clone, Copy, Debug, PartialEq, Eq)]
240pub enum Rejection {
241 BadRequest(ErrorCode),
243 NotCovered,
245 Error(ErrorCode),
249}
250
251thread_local! {
252 static CALL_FAULT: std::cell::Cell<Option<datumesh_core::Fault>> = const { std::cell::Cell::new(None) };
256}
257
258pub(crate) fn take_fault() -> Option<datumesh_core::Fault> {
260 CALL_FAULT.with(|f| f.take())
261}
262
263thread_local! {
264 static LABEL_WITHDRAWN: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
266}
267
268pub(crate) fn set_label_withdrawn(reason: String) {
270 LABEL_WITHDRAWN.with(|l| *l.borrow_mut() = Some(reason));
271}
272
273pub(crate) fn take_label_withdrawn() -> Option<String> {
275 LABEL_WITHDRAWN.with(|l| l.borrow_mut().take())
276}
277
278pub fn is_call(rest: &str) -> bool {
282 let path = rest.split('?').next().unwrap_or("");
283 path.contains('(') || path.contains('%') || path.starts_with('@')
284}
285
286pub fn resolve(
290 rest: &str,
291 now: &str,
292 aliases: &BTreeMap<String, String>,
293 bindings: &dyn Bindings,
294 slice: bool,
295) -> Result<Arc<Target>, Rejection> {
296 let rest = crate::instant::in_query(rest);
298 if is_call(&rest) {
299 resolve_call(&rest, now, aliases, bindings, slice)
300 } else {
301 resolve_uri(&rest, now, bindings, slice)
302 }
303}
304
305fn params(query: &str) -> Vec<(&str, &str)> {
308 if query.is_empty() {
309 return vec![];
310 }
311 query.split('&').map(|p| p.split_once('=').unwrap_or((p, ""))).collect()
312}
313
314fn structural(code: ErrorCode) -> bool {
318 matches!(
319 code,
320 ErrorCode::ParseUri
321 | ErrorCode::CanonName
322 | ErrorCode::CanonArgName
323 | ErrorCode::CanonArgDuplicate
324 | ErrorCode::CanonArgOrder
325 | ErrorCode::CanonPercent
326 | ErrorCode::CanonInstant
327 | ErrorCode::CanonHex
328 )
329}
330
331pub fn resolve_uri(rest: &str, now: &str, bindings: &dyn Bindings, slice: bool) -> Result<Arc<Target>, Rejection> {
333 let (path, query) = match rest.split_once('?') {
334 Some((p, q)) => (p, Some(q)),
335 None => (rest, None),
336 };
337 let ps = params(query.unwrap_or(""));
338 let mut rest_ps: &[(&str, &str)] = &ps;
341 let mut asof = now;
342 if let Some((("asof", v), before)) = rest_ps.split_last() {
343 if lexical::check_instant(v, "$").is_ok() {
344 asof = v;
345 }
346 rest_ps = before;
347 }
348 let pin = match rest_ps.last() {
349 Some(("fn_hash", v)) if lexical::check_hex(v, 64, "$").is_ok() => Some(v.to_string()),
350 _ => None,
351 };
352 let name_ok = lexical::check_function_name(path, "$").is_ok() && !path.contains('#');
353 let bound = match (&pin, name_ok) {
354 (Some(p), true) => bindings.pinned(p).map_err(Rejection::Error)?,
355 (None, true) => bindings.binding(path, asof).map_err(Rejection::Error)?,
356 (_, false) => None,
357 };
358 if let Some(b) = &bound {
359 if let Some(t) = bindings.cached(&b.fn_hash, rest) {
360 if t.reference.args.values().any(|a| matches!(a, Arg::Slice)) == slice {
361 return Ok(t);
362 }
363 }
364 }
365 let uri = format!("cell://{rest}");
366 let Some(bound) = bound else {
367 let mut sig = Vec::new();
370 for (name, _) in &ps {
371 if *name != "asof" && *name != "fn_hash" {
372 sig.push((name.to_string(), Value::Object(vec![("type".into(), Value::String("string".into()))])));
373 }
374 }
375 let signature = Value::Object(vec![("args".into(), Value::Object(sig))]);
376 let name_error = if path.contains('#') { None } else { lexical::check_function_name(path, "$").err() };
379 return match parse_reference(&uri, &signature) {
380 Err(e) if structural(e.code()) => Err(Rejection::BadRequest(e.code())),
381 _ if name_error.is_some() => {
382 Err(Rejection::BadRequest(name_error.map_or(ErrorCode::CanonName, |e| e.code())))
383 }
384 _ if pin.is_some() || !name_ok => Err(Rejection::NotCovered),
385 _ => Err(Rejection::Error(ErrorCode::NameUnbound)),
386 };
387 };
388 let reference = parse_reference(&uri, &bound.signature).map_err(|e| {
389 if crate::envelope::is_request_code(e.code()) {
390 Rejection::BadRequest(e.code())
391 } else {
392 Rejection::Error(ErrorCode::EvalUnavailable)
393 }
394 })?;
395 let has_slice = reference.args.values().any(|a| matches!(a, Arg::Slice));
396 if has_slice && !slice {
397 return Err(Rejection::BadRequest(ErrorCode::SliceAtCell));
398 }
399 if !has_slice && slice {
400 return Err(Rejection::BadRequest(ErrorCode::ParseUri));
402 }
403 let cell = Cell {
404 ns: reference.ns.clone(),
405 fn_name: reference.fn_name.clone(),
406 fn_hash: bound.fn_hash.clone(),
407 args: reference.args.clone(),
408 };
409 let pin = reference.fn_hash.clone();
410 let cell_ref = CellRef { ns: reference.ns, fn_name: reference.fn_name, args: reference.args, asof: reference.asof };
411 let t = Arc::new(Target {
413 uri,
414 reference: cell_ref,
415 cell,
416 id: std::sync::OnceLock::new(),
417 key: std::sync::OnceLock::new(),
418 bound,
419 pin,
420 resolved: None,
421 });
422 bindings.remember(rest, &t);
423 Ok(t)
424}
425
426pub(crate) fn url_decode(s: &str) -> Option<String> {
428 let b = s.as_bytes();
429 let mut out = Vec::with_capacity(b.len());
430 let mut i = 0;
431 while i < b.len() {
432 if b[i] == b'%' {
433 let h = std::str::from_utf8(b.get(i + 1..i + 3)?).ok()?;
434 out.push(u8::from_str_radix(h, 16).ok()?);
435 i += 3;
436 } else {
437 out.push(b[i]);
438 i += 1;
439 }
440 }
441 String::from_utf8(out).ok()
442}
443
444struct Env<'a> {
447 bindings: &'a dyn Bindings,
448 aliases: &'a BTreeMap<String, String>,
449 now: &'a str,
450 current: bool,
452}
453
454impl datumesh_formula::call::CallEnv for Env<'_> {
455 fn alias(&self, alias: &str) -> Result<Option<String>, String> {
456 Ok(self.aliases.get(alias).cloned().or_else(|| self.bindings.alias(alias)))
457 }
458 fn bound(&self, name: &str, asof: Option<&str>) -> Result<Option<FunctionDescriptor>, String> {
459 match self.bindings.binding(name, asof.unwrap_or(self.now)) {
460 Ok(b) => Ok(b.map(|b| (*b.descriptor).clone())),
461 Err(c) => Err(c.as_str().to_string()),
462 }
463 }
464 fn pinned(&self, fn_hash: &str) -> Result<Option<FunctionDescriptor>, String> {
465 match self.bindings.pinned(fn_hash) {
466 Ok(b) => Ok(b.map(|b| (*b.descriptor).clone())),
467 Err(c) => Err(c.as_str().to_string()),
468 }
469 }
470 fn bound_class(&self, name: &str, asof: Option<&str>) -> Result<Option<ClassDescriptor>, String> {
471 match self.bindings.class(name, asof.unwrap_or(self.now)) {
472 Ok(c) => Ok(c.map(|c| (*c.descriptor).clone())),
473 Err(c) => Err(c.as_str().to_string()),
474 }
475 }
476 fn aliases_tx(&self) -> Result<Option<String>, String> {
477 Ok(self.bindings.aliases_tx())
478 }
479 fn now(&self) -> Result<Option<String>, String> {
480 Ok(Some(self.now.to_string()))
481 }
482 fn lookup(&self, class: &str, label: &str, asof: &str) -> Result<Option<String>, String> {
483 self.bindings.lookup_read(class, label, asof, self.current).map_err(|c| c.as_str().to_string())
484 }
485 fn class_name_of(&self, class_hash: &str, asof: Option<&str>) -> Result<Option<String>, String> {
486 self.bindings.class_name_of(class_hash, asof.unwrap_or(self.now)).map_err(|c| c.as_str().to_string())
487 }
488 fn class_descriptor_of(&self, class_hash: &str, _asof: Option<&str>) -> Result<Option<ClassDescriptor>, String> {
489 self.bindings.class_by_hash(class_hash).map_err(|c| c.as_str().to_string())
490 }
491 fn chain(&self, cell: &CellRef, asof: &str) -> Result<Option<String>, String> {
492 self.bindings.chain_read(cell, asof, self.current).map_err(|c| c.as_str().to_string())
493 }
494}
495
496const MAX_CHAIN_LINKS: usize = 8;
498
499fn chain_links(text: &str) -> usize {
502 let (mut depth, mut quoted, mut seen_group, mut links) = (0i32, false, false, 0usize);
503 for c in text.chars() {
504 if quoted {
505 quoted = c != '"';
506 continue;
507 }
508 match c {
509 '"' => quoted = true,
510 '(' | '[' => depth += 1,
511 ')' | ']' => {
512 depth -= 1;
513 if depth == 0 {
514 seen_group = true;
515 }
516 }
517 '.' if depth == 0 && seen_group => links += 1,
518 _ => {}
519 }
520 }
521 links
522}
523
524fn is_current(query: Option<&str>) -> bool {
527 !query.is_some_and(|q| q.split('&').any(|p| p.starts_with("asof=")))
528}
529
530pub fn resolve_call(
532 rest: &str,
533 now: &str,
534 aliases: &BTreeMap<String, String>,
535 bindings: &dyn Bindings,
536 slice: bool,
537) -> Result<Arc<Target>, Rejection> {
538 let (path, query) = match rest.split_once('?') {
539 Some((p, q)) => (p, Some(q)),
540 None => (rest, None),
541 };
542 let mut text = url_decode(path).ok_or(Rejection::BadRequest(ErrorCode::CanonPercent))?;
543 if let Some(q) = query {
544 text.push('?');
545 text.push_str(q);
546 }
547 if chain_links(&text) > MAX_CHAIN_LINKS {
549 return Err(Rejection::BadRequest(ErrorCode::ParseUri));
550 }
551 let current = is_current(query);
553 let env = Env { bindings, aliases, now, current };
554 CALL_FAULT.with(|f| f.set(None));
555 LABEL_WITHDRAWN.with(|l| *l.borrow_mut() = None);
556 let call = datumesh_formula::call::parse_call(text.trim_start(), &env).map_err(|e| match e {
557 datumesh_formula::call::CallError::Code("E_FORMULA_DISPATCH_KEY", _) => {
558 CALL_FAULT.with(|f| f.set(Some(datumesh_core::Fault::DispatchKey)));
559 Rejection::NotCovered
560 }
561 datumesh_formula::call::CallError::Code(c, _) => match ErrorCode::from_code(c) {
562 Some(ErrorCode::NameUnbound) => Rejection::Error(ErrorCode::NameUnbound),
563 Some(ErrorCode::FnUnavailable) => Rejection::NotCovered,
564 Some(code) if crate::envelope::is_request_code(code) => Rejection::BadRequest(code),
565 _ => Rejection::BadRequest(ErrorCode::ParseUri),
566 },
567 datumesh_formula::call::CallError::Env(m) => {
568 Rejection::Error(ErrorCode::from_code(&m).unwrap_or(ErrorCode::InputUnavailable))
569 }
570 _ => Rejection::Error(ErrorCode::EvalUnavailable),
571 })?;
572 let uri = call.uri();
573 if !slice && call.cell.args.values().any(|a| matches!(a, Arg::Slice)) {
574 return Err(Rejection::BadRequest(ErrorCode::SliceAtCell));
575 }
576 let target = resolve_uri(&uri["cell://".len()..], now, bindings, slice)?;
577 match call.resolved {
578 Some(r) => {
581 let mut t = (*target).clone();
582 t.resolved = Some(r);
583 Ok(Arc::new(t))
584 }
585 None => Ok(target),
586 }
587}
588
589pub fn format_pinned(reference: &Reference) -> String {
591 format_reference(reference)
592}