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
150#[derive(Clone, Debug)]
152pub struct Target {
153 pub uri: String,
155 pub reference: CellRef,
157 pub cell: Cell,
159 id: std::sync::OnceLock<String>,
160 key: std::sync::OnceLock<String>,
161 pub bound: Arc<Bound>,
163 pub pin: Option<String>,
165 pub resolved: Option<Resolved>,
168}
169
170impl Target {
171 pub fn fn_name(&self) -> String {
173 format!("{}/{}", self.reference.ns, self.reference.fn_name)
174 }
175
176 pub fn cell_id(&self) -> &str {
178 self.id.get_or_init(|| self.cell.id())
179 }
180
181 pub fn cell_key(&self) -> &str {
183 self.key.get_or_init(|| {
184 let rest = self.rest();
185 let base = match self.asof() {
186 Some(a) => &rest[..rest.len() - a.len() - "asof=".len() - 1],
187 None => rest,
188 };
189 format!("{} {}", self.bound.fn_hash, base)
190 })
191 }
192
193 pub fn pinned_reference(&self) -> Reference {
195 let mut r = Reference::from(self.reference.clone());
196 r.fn_hash = self.pin.clone();
197 r
198 }
199
200 pub fn asof(&self) -> Option<&str> {
202 self.reference.asof.as_deref()
203 }
204
205 pub fn rest(&self) -> &str {
207 &self.uri["cell://".len()..]
208 }
209
210 pub fn rest_asof(&self, asof: &str) -> String {
212 let rest = self.rest();
213 let base = match self.reference.asof.as_deref() {
214 Some(a) => &rest[..rest.len() - a.len() - "asof=".len() - 1],
216 None => rest,
217 };
218 let sep = if base.contains('?') { '&' } else { '?' };
219 format!("{base}{sep}asof={asof}")
220 }
221}
222
223#[derive(Clone, Copy, Debug, PartialEq, Eq)]
225pub enum Rejection {
226 BadRequest(ErrorCode),
228 NotCovered,
230 Error(ErrorCode),
234}
235
236thread_local! {
237 static CALL_FAULT: std::cell::Cell<Option<datumesh_core::Fault>> = const { std::cell::Cell::new(None) };
241}
242
243pub(crate) fn take_fault() -> Option<datumesh_core::Fault> {
245 CALL_FAULT.with(|f| f.take())
246}
247
248thread_local! {
249 static LABEL_WITHDRAWN: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
251}
252
253pub(crate) fn set_label_withdrawn(reason: String) {
255 LABEL_WITHDRAWN.with(|l| *l.borrow_mut() = Some(reason));
256}
257
258pub(crate) fn take_label_withdrawn() -> Option<String> {
260 LABEL_WITHDRAWN.with(|l| l.borrow_mut().take())
261}
262
263pub fn is_call(rest: &str) -> bool {
267 let path = rest.split('?').next().unwrap_or("");
268 path.contains('(') || path.contains('%') || path.starts_with('@')
269}
270
271pub fn resolve(
275 rest: &str,
276 now: &str,
277 aliases: &BTreeMap<String, String>,
278 bindings: &dyn Bindings,
279 slice: bool,
280) -> Result<Arc<Target>, Rejection> {
281 let rest = crate::instant::in_query(rest);
283 if is_call(&rest) {
284 resolve_call(&rest, now, aliases, bindings, slice)
285 } else {
286 resolve_uri(&rest, now, bindings, slice)
287 }
288}
289
290fn params(query: &str) -> Vec<(&str, &str)> {
293 if query.is_empty() {
294 return vec![];
295 }
296 query.split('&').map(|p| p.split_once('=').unwrap_or((p, ""))).collect()
297}
298
299fn structural(code: ErrorCode) -> bool {
303 matches!(
304 code,
305 ErrorCode::ParseUri
306 | ErrorCode::CanonName
307 | ErrorCode::CanonArgName
308 | ErrorCode::CanonArgDuplicate
309 | ErrorCode::CanonArgOrder
310 | ErrorCode::CanonPercent
311 | ErrorCode::CanonInstant
312 | ErrorCode::CanonHex
313 )
314}
315
316pub fn resolve_uri(rest: &str, now: &str, bindings: &dyn Bindings, slice: bool) -> Result<Arc<Target>, Rejection> {
318 let (path, query) = match rest.split_once('?') {
319 Some((p, q)) => (p, Some(q)),
320 None => (rest, None),
321 };
322 let ps = params(query.unwrap_or(""));
323 let mut rest_ps: &[(&str, &str)] = &ps;
326 let mut asof = now;
327 if let Some((("asof", v), before)) = rest_ps.split_last() {
328 if lexical::check_instant(v, "$").is_ok() {
329 asof = v;
330 }
331 rest_ps = before;
332 }
333 let pin = match rest_ps.last() {
334 Some(("fn_hash", v)) if lexical::check_hex(v, 64, "$").is_ok() => Some(v.to_string()),
335 _ => None,
336 };
337 let name_ok = lexical::check_function_name(path, "$").is_ok() && !path.contains('#');
338 let bound = match (&pin, name_ok) {
339 (Some(p), true) => bindings.pinned(p).map_err(Rejection::Error)?,
340 (None, true) => bindings.binding(path, asof).map_err(Rejection::Error)?,
341 (_, false) => None,
342 };
343 if let Some(b) = &bound {
344 if let Some(t) = bindings.cached(&b.fn_hash, rest) {
345 if t.reference.args.values().any(|a| matches!(a, Arg::Slice)) == slice {
346 return Ok(t);
347 }
348 }
349 }
350 let uri = format!("cell://{rest}");
351 let Some(bound) = bound else {
352 let mut sig = Vec::new();
355 for (name, _) in &ps {
356 if *name != "asof" && *name != "fn_hash" {
357 sig.push((name.to_string(), Value::Object(vec![("type".into(), Value::String("string".into()))])));
358 }
359 }
360 let signature = Value::Object(vec![("args".into(), Value::Object(sig))]);
361 let name_error = if path.contains('#') { None } else { lexical::check_function_name(path, "$").err() };
364 return match parse_reference(&uri, &signature) {
365 Err(e) if structural(e.code()) => Err(Rejection::BadRequest(e.code())),
366 _ if name_error.is_some() => {
367 Err(Rejection::BadRequest(name_error.map_or(ErrorCode::CanonName, |e| e.code())))
368 }
369 _ if pin.is_some() || !name_ok => Err(Rejection::NotCovered),
370 _ => Err(Rejection::Error(ErrorCode::NameUnbound)),
371 };
372 };
373 let reference = parse_reference(&uri, &bound.signature).map_err(|e| {
374 if crate::envelope::is_request_code(e.code()) {
375 Rejection::BadRequest(e.code())
376 } else {
377 Rejection::Error(ErrorCode::EvalUnavailable)
378 }
379 })?;
380 let has_slice = reference.args.values().any(|a| matches!(a, Arg::Slice));
381 if has_slice && !slice {
382 return Err(Rejection::BadRequest(ErrorCode::SliceAtCell));
383 }
384 if !has_slice && slice {
385 return Err(Rejection::BadRequest(ErrorCode::ParseUri));
387 }
388 let cell = Cell {
389 ns: reference.ns.clone(),
390 fn_name: reference.fn_name.clone(),
391 fn_hash: bound.fn_hash.clone(),
392 args: reference.args.clone(),
393 };
394 let pin = reference.fn_hash.clone();
395 let cell_ref = CellRef { ns: reference.ns, fn_name: reference.fn_name, args: reference.args, asof: reference.asof };
396 let t = Arc::new(Target {
398 uri,
399 reference: cell_ref,
400 cell,
401 id: std::sync::OnceLock::new(),
402 key: std::sync::OnceLock::new(),
403 bound,
404 pin,
405 resolved: None,
406 });
407 bindings.remember(rest, &t);
408 Ok(t)
409}
410
411pub(crate) fn url_decode(s: &str) -> Option<String> {
413 let b = s.as_bytes();
414 let mut out = Vec::with_capacity(b.len());
415 let mut i = 0;
416 while i < b.len() {
417 if b[i] == b'%' {
418 let h = std::str::from_utf8(b.get(i + 1..i + 3)?).ok()?;
419 out.push(u8::from_str_radix(h, 16).ok()?);
420 i += 3;
421 } else {
422 out.push(b[i]);
423 i += 1;
424 }
425 }
426 String::from_utf8(out).ok()
427}
428
429struct Env<'a> {
432 bindings: &'a dyn Bindings,
433 aliases: &'a BTreeMap<String, String>,
434 now: &'a str,
435}
436
437impl datumesh_formula::call::CallEnv for Env<'_> {
438 fn alias(&self, alias: &str) -> Result<Option<String>, String> {
439 Ok(self.aliases.get(alias).cloned().or_else(|| self.bindings.alias(alias)))
440 }
441 fn bound(&self, name: &str, asof: Option<&str>) -> Result<Option<FunctionDescriptor>, String> {
442 match self.bindings.binding(name, asof.unwrap_or(self.now)) {
443 Ok(b) => Ok(b.map(|b| (*b.descriptor).clone())),
444 Err(c) => Err(c.as_str().to_string()),
445 }
446 }
447 fn pinned(&self, fn_hash: &str) -> Result<Option<FunctionDescriptor>, String> {
448 match self.bindings.pinned(fn_hash) {
449 Ok(b) => Ok(b.map(|b| (*b.descriptor).clone())),
450 Err(c) => Err(c.as_str().to_string()),
451 }
452 }
453 fn bound_class(&self, name: &str, asof: Option<&str>) -> Result<Option<ClassDescriptor>, String> {
454 match self.bindings.class(name, asof.unwrap_or(self.now)) {
455 Ok(c) => Ok(c.map(|c| (*c.descriptor).clone())),
456 Err(c) => Err(c.as_str().to_string()),
457 }
458 }
459 fn aliases_tx(&self) -> Result<Option<String>, String> {
460 Ok(self.bindings.aliases_tx())
461 }
462 fn now(&self) -> Result<Option<String>, String> {
463 Ok(Some(self.now.to_string()))
464 }
465 fn lookup(&self, class: &str, label: &str, asof: &str) -> Result<Option<String>, String> {
466 self.bindings.lookup(class, label, asof).map_err(|c| c.as_str().to_string())
467 }
468 fn class_name_of(&self, class_hash: &str, asof: Option<&str>) -> Result<Option<String>, String> {
469 self.bindings.class_name_of(class_hash, asof.unwrap_or(self.now)).map_err(|c| c.as_str().to_string())
470 }
471 fn class_descriptor_of(&self, class_hash: &str, _asof: Option<&str>) -> Result<Option<ClassDescriptor>, String> {
472 self.bindings.class_by_hash(class_hash).map_err(|c| c.as_str().to_string())
473 }
474 fn chain(&self, cell: &CellRef, asof: &str) -> Result<Option<String>, String> {
475 self.bindings.chain(cell, asof).map_err(|c| c.as_str().to_string())
476 }
477}
478
479const MAX_CHAIN_LINKS: usize = 8;
481
482fn chain_links(text: &str) -> usize {
485 let (mut depth, mut quoted, mut seen_group, mut links) = (0i32, false, false, 0usize);
486 for c in text.chars() {
487 if quoted {
488 quoted = c != '"';
489 continue;
490 }
491 match c {
492 '"' => quoted = true,
493 '(' | '[' => depth += 1,
494 ')' | ']' => {
495 depth -= 1;
496 if depth == 0 {
497 seen_group = true;
498 }
499 }
500 '.' if depth == 0 && seen_group => links += 1,
501 _ => {}
502 }
503 }
504 links
505}
506
507pub fn resolve_call(
509 rest: &str,
510 now: &str,
511 aliases: &BTreeMap<String, String>,
512 bindings: &dyn Bindings,
513 slice: bool,
514) -> Result<Arc<Target>, Rejection> {
515 let (path, query) = match rest.split_once('?') {
516 Some((p, q)) => (p, Some(q)),
517 None => (rest, None),
518 };
519 let mut text = url_decode(path).ok_or(Rejection::BadRequest(ErrorCode::CanonPercent))?;
520 if let Some(q) = query {
521 text.push('?');
522 text.push_str(q);
523 }
524 if chain_links(&text) > MAX_CHAIN_LINKS {
526 return Err(Rejection::BadRequest(ErrorCode::ParseUri));
527 }
528 let env = Env { bindings, aliases, now };
529 CALL_FAULT.with(|f| f.set(None));
530 LABEL_WITHDRAWN.with(|l| *l.borrow_mut() = None);
531 let call = datumesh_formula::call::parse_call(text.trim_start(), &env).map_err(|e| match e {
532 datumesh_formula::call::CallError::Code("E_FORMULA_DISPATCH_KEY", _) => {
533 CALL_FAULT.with(|f| f.set(Some(datumesh_core::Fault::DispatchKey)));
534 Rejection::NotCovered
535 }
536 datumesh_formula::call::CallError::Code(c, _) => match ErrorCode::from_code(c) {
537 Some(ErrorCode::NameUnbound) => Rejection::Error(ErrorCode::NameUnbound),
538 Some(ErrorCode::FnUnavailable) => Rejection::NotCovered,
539 Some(code) if crate::envelope::is_request_code(code) => Rejection::BadRequest(code),
540 _ => Rejection::BadRequest(ErrorCode::ParseUri),
541 },
542 datumesh_formula::call::CallError::Env(m) => {
543 Rejection::Error(ErrorCode::from_code(&m).unwrap_or(ErrorCode::InputUnavailable))
544 }
545 _ => Rejection::Error(ErrorCode::EvalUnavailable),
546 })?;
547 let uri = call.uri();
548 if !slice && call.cell.args.values().any(|a| matches!(a, Arg::Slice)) {
549 return Err(Rejection::BadRequest(ErrorCode::SliceAtCell));
550 }
551 let target = resolve_uri(&uri["cell://".len()..], now, bindings, slice)?;
552 match call.resolved {
553 Some(r) => {
556 let mut t = (*target).clone();
557 t.resolved = Some(r);
558 Ok(Arc::new(t))
559 }
560 None => Ok(target),
561 }
562}
563
564pub fn format_pinned(reference: &Reference) -> String {
566 format_reference(reference)
567}