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
130#[derive(Clone, Debug)]
132pub struct Target {
133 pub uri: String,
135 pub reference: CellRef,
137 pub cell: Cell,
139 id: std::sync::OnceLock<String>,
140 key: std::sync::OnceLock<String>,
141 pub bound: Arc<Bound>,
143 pub pin: Option<String>,
145 pub resolved: Option<Resolved>,
148}
149
150impl Target {
151 pub fn fn_name(&self) -> String {
153 format!("{}/{}", self.reference.ns, self.reference.fn_name)
154 }
155
156 pub fn cell_id(&self) -> &str {
158 self.id.get_or_init(|| self.cell.id())
159 }
160
161 pub fn cell_key(&self) -> &str {
163 self.key.get_or_init(|| {
164 let rest = self.rest();
165 let base = match self.asof() {
166 Some(a) => &rest[..rest.len() - a.len() - "asof=".len() - 1],
167 None => rest,
168 };
169 format!("{} {}", self.bound.fn_hash, base)
170 })
171 }
172
173 pub fn pinned_reference(&self) -> Reference {
175 let mut r = Reference::from(self.reference.clone());
176 r.fn_hash = self.pin.clone();
177 r
178 }
179
180 pub fn asof(&self) -> Option<&str> {
182 self.reference.asof.as_deref()
183 }
184
185 pub fn rest(&self) -> &str {
187 &self.uri["cell://".len()..]
188 }
189
190 pub fn rest_asof(&self, asof: &str) -> String {
192 let rest = self.rest();
193 let base = match self.reference.asof.as_deref() {
194 Some(a) => &rest[..rest.len() - a.len() - "asof=".len() - 1],
196 None => rest,
197 };
198 let sep = if base.contains('?') { '&' } else { '?' };
199 format!("{base}{sep}asof={asof}")
200 }
201}
202
203#[derive(Clone, Copy, Debug, PartialEq, Eq)]
205pub enum Rejection {
206 BadRequest(ErrorCode),
208 NotCovered,
210 Error(ErrorCode),
214}
215
216pub fn is_call(rest: &str) -> bool {
220 let path = rest.split('?').next().unwrap_or("");
221 path.contains('(') || path.contains('%') || path.starts_with('@')
222}
223
224pub fn resolve(
228 rest: &str,
229 now: &str,
230 aliases: &BTreeMap<String, String>,
231 bindings: &dyn Bindings,
232 slice: bool,
233) -> Result<Arc<Target>, Rejection> {
234 if is_call(rest) {
235 resolve_call(rest, now, aliases, bindings, slice)
236 } else {
237 resolve_uri(rest, now, bindings, slice)
238 }
239}
240
241fn params(query: &str) -> Vec<(&str, &str)> {
244 if query.is_empty() {
245 return vec![];
246 }
247 query.split('&').map(|p| p.split_once('=').unwrap_or((p, ""))).collect()
248}
249
250fn structural(code: ErrorCode) -> bool {
254 matches!(
255 code,
256 ErrorCode::ParseUri
257 | ErrorCode::CanonName
258 | ErrorCode::CanonArgName
259 | ErrorCode::CanonArgDuplicate
260 | ErrorCode::CanonArgOrder
261 | ErrorCode::CanonPercent
262 | ErrorCode::CanonInstant
263 | ErrorCode::CanonHex
264 )
265}
266
267pub fn resolve_uri(rest: &str, now: &str, bindings: &dyn Bindings, slice: bool) -> Result<Arc<Target>, Rejection> {
269 let (path, query) = match rest.split_once('?') {
270 Some((p, q)) => (p, Some(q)),
271 None => (rest, None),
272 };
273 let ps = params(query.unwrap_or(""));
274 let mut rest_ps: &[(&str, &str)] = &ps;
277 let mut asof = now;
278 if let Some((("asof", v), before)) = rest_ps.split_last() {
279 if lexical::check_instant(v, "$").is_ok() {
280 asof = v;
281 }
282 rest_ps = before;
283 }
284 let pin = match rest_ps.last() {
285 Some(("fn_hash", v)) if lexical::check_hex(v, 64, "$").is_ok() => Some(v.to_string()),
286 _ => None,
287 };
288 let name_ok = lexical::check_function_name(path, "$").is_ok() && !path.contains('#');
289 let bound = match (&pin, name_ok) {
290 (Some(p), true) => bindings.pinned(p).map_err(Rejection::Error)?,
291 (None, true) => bindings.binding(path, asof).map_err(Rejection::Error)?,
292 (_, false) => None,
293 };
294 if let Some(b) = &bound {
295 if let Some(t) = bindings.cached(&b.fn_hash, rest) {
296 if t.reference.args.values().any(|a| matches!(a, Arg::Slice)) == slice {
297 return Ok(t);
298 }
299 }
300 }
301 let uri = format!("cell://{rest}");
302 let Some(bound) = bound else {
303 let mut sig = Vec::new();
306 for (name, _) in &ps {
307 if *name != "asof" && *name != "fn_hash" {
308 sig.push((name.to_string(), Value::Object(vec![("type".into(), Value::String("string".into()))])));
309 }
310 }
311 let signature = Value::Object(vec![("args".into(), Value::Object(sig))]);
312 return match parse_reference(&uri, &signature) {
313 Err(e) if structural(e.code()) => Err(Rejection::BadRequest(e.code())),
314 _ if pin.is_some() || !name_ok => Err(Rejection::NotCovered),
315 _ => Err(Rejection::Error(ErrorCode::NameUnbound)),
316 };
317 };
318 let reference = parse_reference(&uri, &bound.signature).map_err(|e| {
319 if crate::envelope::is_request_code(e.code()) {
320 Rejection::BadRequest(e.code())
321 } else {
322 Rejection::Error(ErrorCode::EvalUnavailable)
323 }
324 })?;
325 let has_slice = reference.args.values().any(|a| matches!(a, Arg::Slice));
326 if has_slice && !slice {
327 return Err(Rejection::BadRequest(ErrorCode::SliceAtCell));
328 }
329 if !has_slice && slice {
330 return Err(Rejection::BadRequest(ErrorCode::ParseUri));
332 }
333 let cell = Cell {
334 ns: reference.ns.clone(),
335 fn_name: reference.fn_name.clone(),
336 fn_hash: bound.fn_hash.clone(),
337 args: reference.args.clone(),
338 };
339 let pin = reference.fn_hash.clone();
340 let cell_ref = CellRef { ns: reference.ns, fn_name: reference.fn_name, args: reference.args, asof: reference.asof };
341 let t = Arc::new(Target {
343 uri,
344 reference: cell_ref,
345 cell,
346 id: std::sync::OnceLock::new(),
347 key: std::sync::OnceLock::new(),
348 bound,
349 pin,
350 resolved: None,
351 });
352 bindings.remember(rest, &t);
353 Ok(t)
354}
355
356pub(crate) fn url_decode(s: &str) -> Option<String> {
358 let b = s.as_bytes();
359 let mut out = Vec::with_capacity(b.len());
360 let mut i = 0;
361 while i < b.len() {
362 if b[i] == b'%' {
363 let h = std::str::from_utf8(b.get(i + 1..i + 3)?).ok()?;
364 out.push(u8::from_str_radix(h, 16).ok()?);
365 i += 3;
366 } else {
367 out.push(b[i]);
368 i += 1;
369 }
370 }
371 String::from_utf8(out).ok()
372}
373
374struct Env<'a> {
377 bindings: &'a dyn Bindings,
378 aliases: &'a BTreeMap<String, String>,
379 now: &'a str,
380}
381
382impl datumesh_formula::call::CallEnv for Env<'_> {
383 fn alias(&self, alias: &str) -> Result<Option<String>, String> {
384 Ok(self.aliases.get(alias).cloned().or_else(|| self.bindings.alias(alias)))
385 }
386 fn bound(&self, name: &str, asof: Option<&str>) -> Result<Option<FunctionDescriptor>, String> {
387 match self.bindings.binding(name, asof.unwrap_or(self.now)) {
388 Ok(b) => Ok(b.map(|b| (*b.descriptor).clone())),
389 Err(c) => Err(c.as_str().to_string()),
390 }
391 }
392 fn pinned(&self, fn_hash: &str) -> Result<Option<FunctionDescriptor>, String> {
393 match self.bindings.pinned(fn_hash) {
394 Ok(b) => Ok(b.map(|b| (*b.descriptor).clone())),
395 Err(c) => Err(c.as_str().to_string()),
396 }
397 }
398 fn bound_class(&self, name: &str, asof: Option<&str>) -> Result<Option<ClassDescriptor>, String> {
399 match self.bindings.class(name, asof.unwrap_or(self.now)) {
400 Ok(c) => Ok(c.map(|c| (*c.descriptor).clone())),
401 Err(c) => Err(c.as_str().to_string()),
402 }
403 }
404 fn aliases_tx(&self) -> Result<Option<String>, String> {
405 Ok(self.bindings.aliases_tx())
406 }
407 fn now(&self) -> Result<Option<String>, String> {
408 Ok(Some(self.now.to_string()))
409 }
410 fn lookup(&self, class: &str, label: &str, asof: &str) -> Result<Option<String>, String> {
411 self.bindings.lookup(class, label, asof).map_err(|c| c.as_str().to_string())
412 }
413}
414
415pub fn resolve_call(
417 rest: &str,
418 now: &str,
419 aliases: &BTreeMap<String, String>,
420 bindings: &dyn Bindings,
421 slice: bool,
422) -> Result<Arc<Target>, Rejection> {
423 let (path, query) = match rest.split_once('?') {
424 Some((p, q)) => (p, Some(q)),
425 None => (rest, None),
426 };
427 let mut text = url_decode(path).ok_or(Rejection::BadRequest(ErrorCode::CanonPercent))?;
428 if let Some(q) = query {
429 text.push('?');
430 text.push_str(q);
431 }
432 let env = Env { bindings, aliases, now };
433 let call = datumesh_formula::call::parse_call(text.trim_start(), &env).map_err(|e| match e {
434 datumesh_formula::call::CallError::Code(c, _) => match ErrorCode::from_code(c) {
435 Some(ErrorCode::NameUnbound) => Rejection::Error(ErrorCode::NameUnbound),
436 Some(ErrorCode::FnUnavailable) => Rejection::NotCovered,
437 Some(code) if crate::envelope::is_request_code(code) => Rejection::BadRequest(code),
438 _ => Rejection::BadRequest(ErrorCode::ParseUri),
439 },
440 datumesh_formula::call::CallError::Env(m) => {
441 Rejection::Error(ErrorCode::from_code(&m).unwrap_or(ErrorCode::InputUnavailable))
442 }
443 _ => Rejection::Error(ErrorCode::EvalUnavailable),
444 })?;
445 let uri = call.uri();
446 if !slice && call.cell.args.values().any(|a| matches!(a, Arg::Slice)) {
447 return Err(Rejection::BadRequest(ErrorCode::SliceAtCell));
448 }
449 let target = resolve_uri(&uri["cell://".len()..], now, bindings, slice)?;
450 match call.resolved {
451 Some(r) => {
454 let mut t = (*target).clone();
455 t.resolved = Some(r);
456 Ok(Arc::new(t))
457 }
458 None => Ok(target),
459 }
460}
461
462pub fn format_pinned(reference: &Reference) -> String {
464 format_reference(reference)
465}