1use std::collections::BTreeMap;
30use std::sync::Arc;
31
32use datumesh_core::json::Value;
33use datumesh_core::{
34 format_reference, lexical, parse_reference, Arg, Cell, CellRef, ErrorCode, FunctionDescriptor, Reference,
35};
36
37#[derive(Clone, Debug)]
39pub struct Bound {
40 pub fn_hash: String,
42 pub since: String,
44 pub descriptor: Arc<FunctionDescriptor>,
46 pub signature: Arc<Value>,
48}
49
50impl Bound {
51 pub fn new(fn_hash: impl Into<String>, since: impl Into<String>, descriptor: Arc<FunctionDescriptor>) -> Bound {
53 let signature = Arc::new(descriptor.signature.to_value());
54 Bound { fn_hash: fn_hash.into(), since: since.into(), descriptor, signature }
55 }
56}
57
58pub trait Bindings {
61 fn binding(&self, fn_name: &str, asof: &str) -> Result<Option<Arc<Bound>>, ErrorCode>;
64
65 fn cached(&self, fn_hash: &str, rest: &str) -> Option<Arc<Target>> {
68 let _ = (fn_hash, rest);
69 None
70 }
71
72 fn remember(&self, rest: &str, target: &Arc<Target>) {
74 let _ = (rest, target);
75 }
76
77 fn pinned(&self, fn_hash: &str) -> Result<Option<Arc<Bound>>, ErrorCode> {
80 let _ = fn_hash;
81 Ok(None)
82 }
83
84 fn alias(&self, alias: &str) -> Option<String> {
86 let _ = alias;
87 None
88 }
89}
90
91#[derive(Clone, Debug)]
93pub struct Target {
94 pub uri: String,
96 pub reference: CellRef,
98 pub cell: Cell,
100 id: std::sync::OnceLock<String>,
101 key: std::sync::OnceLock<String>,
102 pub bound: Arc<Bound>,
104 pub pin: Option<String>,
106}
107
108impl Target {
109 pub fn fn_name(&self) -> String {
111 format!("{}/{}", self.reference.ns, self.reference.fn_name)
112 }
113
114 pub fn cell_id(&self) -> &str {
116 self.id.get_or_init(|| self.cell.id())
117 }
118
119 pub fn cell_key(&self) -> &str {
121 self.key.get_or_init(|| {
122 let rest = self.rest();
123 let base = match self.asof() {
124 Some(a) => &rest[..rest.len() - a.len() - "asof=".len() - 1],
125 None => rest,
126 };
127 format!("{} {}", self.bound.fn_hash, base)
128 })
129 }
130
131 pub fn pinned_reference(&self) -> Reference {
133 let mut r = Reference::from(self.reference.clone());
134 r.fn_hash = self.pin.clone();
135 r
136 }
137
138 pub fn asof(&self) -> Option<&str> {
140 self.reference.asof.as_deref()
141 }
142
143 pub fn rest(&self) -> &str {
145 &self.uri["cell://".len()..]
146 }
147
148 pub fn rest_asof(&self, asof: &str) -> String {
150 let rest = self.rest();
151 let base = match self.reference.asof.as_deref() {
152 Some(a) => &rest[..rest.len() - a.len() - "asof=".len() - 1],
154 None => rest,
155 };
156 let sep = if base.contains('?') { '&' } else { '?' };
157 format!("{base}{sep}asof={asof}")
158 }
159}
160
161#[derive(Clone, Copy, Debug, PartialEq, Eq)]
163pub enum Rejection {
164 BadRequest(ErrorCode),
166 NotCovered,
168 Error(ErrorCode),
172}
173
174pub fn is_call(rest: &str) -> bool {
178 let path = rest.split('?').next().unwrap_or("");
179 path.contains('(') || path.contains('%') || path.starts_with('@')
180}
181
182pub fn resolve(
186 rest: &str,
187 now: &str,
188 aliases: &BTreeMap<String, String>,
189 bindings: &dyn Bindings,
190 slice: bool,
191) -> Result<Arc<Target>, Rejection> {
192 if is_call(rest) {
193 resolve_call(rest, now, aliases, bindings, slice)
194 } else {
195 resolve_uri(rest, now, bindings, slice)
196 }
197}
198
199fn params(query: &str) -> Vec<(&str, &str)> {
202 if query.is_empty() {
203 return vec![];
204 }
205 query.split('&').map(|p| p.split_once('=').unwrap_or((p, ""))).collect()
206}
207
208fn structural(code: ErrorCode) -> bool {
212 matches!(
213 code,
214 ErrorCode::ParseUri
215 | ErrorCode::CanonName
216 | ErrorCode::CanonArgName
217 | ErrorCode::CanonArgDuplicate
218 | ErrorCode::CanonArgOrder
219 | ErrorCode::CanonPercent
220 | ErrorCode::CanonInstant
221 | ErrorCode::CanonHex
222 )
223}
224
225pub fn resolve_uri(rest: &str, now: &str, bindings: &dyn Bindings, slice: bool) -> Result<Arc<Target>, Rejection> {
227 let (path, query) = match rest.split_once('?') {
228 Some((p, q)) => (p, Some(q)),
229 None => (rest, None),
230 };
231 let ps = params(query.unwrap_or(""));
232 let mut rest_ps: &[(&str, &str)] = &ps;
235 let mut asof = now;
236 if let Some((("asof", v), before)) = rest_ps.split_last() {
237 if lexical::check_instant(v, "$").is_ok() {
238 asof = v;
239 }
240 rest_ps = before;
241 }
242 let pin = match rest_ps.last() {
243 Some(("fn_hash", v)) if lexical::check_hex(v, 64, "$").is_ok() => Some(v.to_string()),
244 _ => None,
245 };
246 let name_ok = lexical::check_function_name(path, "$").is_ok() && !path.contains('#');
247 let bound = match (&pin, name_ok) {
248 (Some(p), true) => bindings.pinned(p).map_err(Rejection::Error)?,
249 (None, true) => bindings.binding(path, asof).map_err(Rejection::Error)?,
250 (_, false) => None,
251 };
252 if let Some(b) = &bound {
253 if let Some(t) = bindings.cached(&b.fn_hash, rest) {
254 if t.reference.args.values().any(|a| matches!(a, Arg::Slice)) == slice {
255 return Ok(t);
256 }
257 }
258 }
259 let uri = format!("cell://{rest}");
260 let Some(bound) = bound else {
261 let mut sig = Vec::new();
264 for (name, _) in &ps {
265 if *name != "asof" && *name != "fn_hash" {
266 sig.push((name.to_string(), Value::Object(vec![("type".into(), Value::String("string".into()))])));
267 }
268 }
269 let signature = Value::Object(vec![("args".into(), Value::Object(sig))]);
270 return match parse_reference(&uri, &signature) {
271 Err(e) if structural(e.code()) => Err(Rejection::BadRequest(e.code())),
272 _ if pin.is_some() || !name_ok => Err(Rejection::NotCovered),
273 _ => Err(Rejection::Error(ErrorCode::NameUnbound)),
274 };
275 };
276 let reference = parse_reference(&uri, &bound.signature).map_err(|e| {
277 if crate::envelope::is_request_code(e.code()) {
278 Rejection::BadRequest(e.code())
279 } else {
280 Rejection::Error(ErrorCode::EvalUnavailable)
281 }
282 })?;
283 let has_slice = reference.args.values().any(|a| matches!(a, Arg::Slice));
284 if has_slice && !slice {
285 return Err(Rejection::BadRequest(ErrorCode::SliceAtCell));
286 }
287 if !has_slice && slice {
288 return Err(Rejection::BadRequest(ErrorCode::ParseUri));
290 }
291 let cell = Cell {
292 ns: reference.ns.clone(),
293 fn_name: reference.fn_name.clone(),
294 fn_hash: bound.fn_hash.clone(),
295 args: reference.args.clone(),
296 };
297 let pin = reference.fn_hash.clone();
298 let cell_ref = CellRef { ns: reference.ns, fn_name: reference.fn_name, args: reference.args, asof: reference.asof };
299 let t = Arc::new(Target {
301 uri,
302 reference: cell_ref,
303 cell,
304 id: std::sync::OnceLock::new(),
305 key: std::sync::OnceLock::new(),
306 bound,
307 pin,
308 });
309 bindings.remember(rest, &t);
310 Ok(t)
311}
312
313fn url_decode(s: &str) -> Option<String> {
315 let b = s.as_bytes();
316 let mut out = Vec::with_capacity(b.len());
317 let mut i = 0;
318 while i < b.len() {
319 if b[i] == b'%' {
320 let h = std::str::from_utf8(b.get(i + 1..i + 3)?).ok()?;
321 out.push(u8::from_str_radix(h, 16).ok()?);
322 i += 3;
323 } else {
324 out.push(b[i]);
325 i += 1;
326 }
327 }
328 String::from_utf8(out).ok()
329}
330
331struct Env<'a> {
334 bindings: &'a dyn Bindings,
335 aliases: &'a BTreeMap<String, String>,
336 now: &'a str,
337}
338
339impl datumesh_formula::call::CallEnv for Env<'_> {
340 fn alias(&self, alias: &str) -> Result<Option<String>, String> {
341 Ok(self.aliases.get(alias).cloned().or_else(|| self.bindings.alias(alias)))
342 }
343 fn bound(&self, name: &str, asof: Option<&str>) -> Result<Option<FunctionDescriptor>, String> {
344 match self.bindings.binding(name, asof.unwrap_or(self.now)) {
345 Ok(b) => Ok(b.map(|b| (*b.descriptor).clone())),
346 Err(c) => Err(c.as_str().to_string()),
347 }
348 }
349 fn pinned(&self, fn_hash: &str) -> Result<Option<FunctionDescriptor>, String> {
350 match self.bindings.pinned(fn_hash) {
351 Ok(b) => Ok(b.map(|b| (*b.descriptor).clone())),
352 Err(c) => Err(c.as_str().to_string()),
353 }
354 }
355}
356
357pub fn resolve_call(
359 rest: &str,
360 now: &str,
361 aliases: &BTreeMap<String, String>,
362 bindings: &dyn Bindings,
363 slice: bool,
364) -> Result<Arc<Target>, Rejection> {
365 let (path, query) = match rest.split_once('?') {
366 Some((p, q)) => (p, Some(q)),
367 None => (rest, None),
368 };
369 let mut text = url_decode(path).ok_or(Rejection::BadRequest(ErrorCode::CanonPercent))?;
370 if let Some(q) = query {
371 text.push('?');
372 text.push_str(q);
373 }
374 let env = Env { bindings, aliases, now };
375 let call = datumesh_formula::call::parse_call(text.trim_start(), &env).map_err(|e| match e {
376 datumesh_formula::call::CallError::Code(c, _) => match ErrorCode::from_code(c) {
377 Some(ErrorCode::NameUnbound) => Rejection::Error(ErrorCode::NameUnbound),
378 Some(ErrorCode::FnUnavailable) => Rejection::NotCovered,
379 Some(code) if crate::envelope::is_request_code(code) => Rejection::BadRequest(code),
380 _ => Rejection::BadRequest(ErrorCode::ParseUri),
381 },
382 datumesh_formula::call::CallError::Env(m) => {
383 Rejection::Error(ErrorCode::from_code(&m).unwrap_or(ErrorCode::InputUnavailable))
384 }
385 _ => Rejection::Error(ErrorCode::EvalUnavailable),
386 })?;
387 let uri = call.uri();
388 if !slice && call.cell.args.values().any(|a| matches!(a, Arg::Slice)) {
389 return Err(Rejection::BadRequest(ErrorCode::SliceAtCell));
390 }
391 resolve_uri(&uri["cell://".len()..], now, bindings, slice)
392}
393
394pub fn format_pinned(reference: &Reference) -> String {
396 format_reference(reference)
397}