Skip to main content

datumesh_http/
call.rs

1//! What a request names: a cell URI's `<rest>` (SPEC 5.3) or a call (SPEC 5.8), resolved to
2//! one canonical reference, pinned to a function hash or not (spec-0.4.2).
3//!
4//! # The forms `/cell` accepts
5//!
6//! * **A cell URI's rest**, byte for byte (SPEC 5.3):
7//!   `/cell/ecb.europa.eu/fx_rate?base=EUR&date=2024-03-15&quote=USD`, then optionally
8//!   `&fn_hash=<64 hex digits>` (a pin, 5.1) and `&asof=<instant>`. It is parsed by the core's
9//!   `parse_reference` against the signature of the function the pin names, or else the one
10//!   the name is bound to as of that asof (or now), so every code of SPEC 5.4 is reported as it
11//!   defines.
12//! * **A call** (5.8), percent-encoded as any URL path is
13//!   (`/cell/rates.example.org/fx_rate(%22EUR%22,%20%22USD%22,%202024-03-15)`), with an optional
14//!   query `?asof=<instant>` and nothing else: a read of the formula dialect whose arguments
15//!   are literals, the callee a full name or an `@alias` of the configured map, optionally
16//!   pinned (`name@<fn_hash>(...)`). It is parsed by the formula crate's
17//!   `datumesh_formula::call::parse_call` in 5.8's order and codes, written as its cell URI and
18//!   resolved as above: a call and its URI are one request.
19//!
20//!   Since 0.2.2 (spec-0.5.0, 5.8, 16.3, 16.7) the call is also a **method call**
21//!   (`N(keys).m(args)`, the same request as the plain read `N/m(keys, args)`), takes **unquoted
22//!   values** by the position's type, **labels** (`N[label]`, through the class's `lookup`), the
23//!   `asof` **default** (the call's `asof`, or the mesh's now, in the cell URI) and a **bare name**
24//!   through the alias map. What it resolved is [`Target::resolved`], the answer's `resolved`
25//!   (5.5). A key not canonical under its normalisation is `E_KEY_NORMALISATION`, a malformed
26//!   encoding `E_KEY_ENCODING` (both `bad_request`). Not accepted: expressions, ranges or units
27//!   (`E_PARSE_URI`).
28//!
29//! An unbound name (or alias) is `not_covered` with `E_NAME_UNBOUND`
30//! ([`Rejection::Error`]`(ErrorCode::NameUnbound)`, which the mesh answers so); a pin no
31//! descriptor of the mesh has is a plain `not_covered` ([`Rejection::NotCovered`]); a slice
32//! marker at `/cell` is `E_SLICE_AT_CELL`.
33
34use 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/// A function bound to a name as of an instant.
44#[derive(Clone, Debug)]
45pub struct Bound {
46    /// The function hash.
47    pub fn_hash: String,
48    /// When the binding began.
49    pub since: String,
50    /// The descriptor.
51    pub descriptor: Arc<FunctionDescriptor>,
52    /// The descriptor's signature as JSON (what `parse_uri` reads).
53    pub signature: Arc<Value>,
54}
55
56impl Bound {
57    /// A binding of `fn_hash` since `since` to `descriptor`.
58    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/// A class name's binding as of an instant (spec-0.5.0, 9.7): the class hash and the
65/// flattened descriptor.
66#[derive(Clone, Debug)]
67pub struct BoundClass {
68    /// The class hash.
69    pub class_hash: String,
70    /// When the binding began.
71    pub since: String,
72    /// The flattened class descriptor.
73    pub descriptor: Arc<ClassDescriptor>,
74}
75
76/// Where names are looked up: the mesh's store (and, for names under other hosts, the
77/// cross-mesh resolver in front of it).
78pub trait Bindings {
79    /// The binding of `fn_name` as of `asof`; `Ok(None)` when it has none. An `Err` is the
80    /// code of an `error` envelope (the store or another mesh failed).
81    fn binding(&self, fn_name: &str, asof: &str) -> Result<Option<Arc<Bound>>, ErrorCode>;
82
83    /// A target resolved before for the cell URI rest `rest` under function hash `fn_hash`
84    /// (parsing depends on nothing else). Provided: none.
85    fn cached(&self, fn_hash: &str, rest: &str) -> Option<Arc<Target>> {
86        let _ = (fn_hash, rest);
87        None
88    }
89
90    /// Remembers a resolved target for [`Bindings::cached`]. Provided: nothing.
91    fn remember(&self, rest: &str, target: &Arc<Target>) {
92        let _ = (rest, target);
93    }
94
95    /// The descriptor whose function hash is `fn_hash` (a pin, spec-0.4.2), as a binding of
96    /// no time (`since` empty); `Ok(None)` when the mesh has none. Provided: none.
97    fn pinned(&self, fn_hash: &str) -> Result<Option<Arc<Bound>>, ErrorCode> {
98        let _ = fn_hash;
99        Ok(None)
100    }
101
102    /// The fully qualified name an alias (without `@`) stands for. Provided: none.
103    fn alias(&self, alias: &str) -> Option<String> {
104        let _ = alias;
105        None
106    }
107
108    /// The class `name` is bound to as of `asof` (spec-0.5.0, 9.7, 16.3); `Ok(None)` when it is
109    /// not a class (a function name, or unbound). Provided: none.
110    fn class(&self, name: &str, asof: &str) -> Result<Option<Arc<BoundClass>>, ErrorCode> {
111        let _ = (name, asof);
112        Ok(None)
113    }
114
115    /// The instant of the alias snapshot [`Bindings::alias`] answers from, for `resolved.aliases_tx`
116    /// (16.7); `None` when there is none (the configured map has no snapshot). Provided: none.
117    fn aliases_tx(&self) -> Option<String> {
118        None
119    }
120
121    /// The key encoding the lookup method of class `class` maps `label` to as of `asof`
122    /// (16.7, D93): the value of the cell `<class>/<lookup>(label: ...)`. `Ok(None)` when the
123    /// class has no lookup or the cell has no value. Provided: none.
124    fn lookup(&self, class: &str, label: &str, asof: &str) -> Result<Option<String>, ErrorCode> {
125        let _ = (class, label, asof);
126        Ok(None)
127    }
128
129    /// The first name the class hash is bound to as of `asof` (K5, the classes round): the name that
130    /// names the defining class of an inherited method, as `super` names its parent (16.3). Provided: none.
131    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    /// The flattened class descriptor held under this class hash, bound or not (K5). Provided: none.
137    fn class_by_hash(&self, class_hash: &str) -> Result<Option<ClassDescriptor>, ErrorCode> {
138        let _ = class_hash;
139        Ok(None)
140    }
141
142    /// The key encoding a chain's cell holds as of `asof` (K10, the classes round): the value of the cell
143    /// `cell` (computed or stored), `None` when it has no value then. Provided: none.
144    fn chain(&self, cell: &CellRef, asof: &str) -> Result<Option<String>, ErrorCode> {
145        let _ = (cell, asof);
146        Ok(None)
147    }
148
149    /// [`Bindings::lookup`] for a read a request makes inside it: `current` when the request named no
150    /// asof (`asof` is then its arrival), so the read is current; a named past asof stores nothing (G10).
151    /// Provided: the plain lookup.
152    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    /// [`Bindings::chain`] for a read a request makes inside it (G10, as [`Bindings::lookup_read`]).
158    /// Provided: the plain chain.
159    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/// A request resolved to its cell (or slice, at `/slice`).
166#[derive(Clone, Debug)]
167pub struct Target {
168    /// The canonical cell URI, `asof` included when the request had one.
169    pub uri: String,
170    /// The reference (`asof` included).
171    pub reference: CellRef,
172    /// The cell, with the function hash the name is bound to as of the asof.
173    pub cell: Cell,
174    id: std::sync::OnceLock<String>,
175    key: std::sync::OnceLock<String>,
176    /// The binding (for a pinned request, the pinned descriptor).
177    pub bound: Arc<Bound>,
178    /// The pin (spec-0.4.2): the function hash the request named, if it named one.
179    pub pin: Option<String>,
180    /// What the request resolved (spec-0.5.0, 5.5, 16.7): an alias, a method, a default or a
181    /// label; none for a plain or pinned call of a full name and for a cell URI.
182    pub resolved: Option<Resolved>,
183}
184
185impl Target {
186    /// The function's fully qualified name.
187    pub fn fn_name(&self) -> String {
188        format!("{}/{}", self.reference.ns, self.reference.fn_name)
189    }
190
191    /// The cell's id (SPEC 4.4), computed once.
192    pub fn cell_id(&self) -> &str {
193        self.id.get_or_init(|| self.cell.id())
194    }
195
196    /// The cell's key: its function hash and its URI without `asof` (computed once).
197    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    /// The reference with its pin (spec-0.4.2): what the request denotes.
209    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    /// The requested asof, if any.
216    pub fn asof(&self) -> Option<&str> {
217        self.reference.asof.as_deref()
218    }
219
220    /// The cell URI's `<rest>` (SPEC 5.3), without `cell://`.
221    pub fn rest(&self) -> &str {
222        &self.uri["cell://".len()..]
223    }
224
225    /// The rest with `asof` set to `asof` (replacing one there).
226    pub fn rest_asof(&self, asof: &str) -> String {
227        let rest = self.rest();
228        let base = match self.reference.asof.as_deref() {
229            // `asof` is the last parameter of a canonical URI.
230            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/// Why a request names no cell.
239#[derive(Clone, Copy, Debug, PartialEq, Eq)]
240pub enum Rejection {
241    /// `bad_request` with this code.
242    BadRequest(ErrorCode),
243    /// `not_covered`: the mesh does not serve the function (a pin no descriptor of it has).
244    NotCovered,
245    /// `error` with this code: looking the name up failed. `ErrorCode::NameUnbound` stands
246    /// for an unbound name, answered `not_covered` with that code (spec-0.4.2; this enum is
247    /// exhaustive, so 0.1.1 gives that case no variant of its own).
248    Error(ErrorCode),
249}
250
251thread_local! {
252    /// The fault of the last request on this thread that was `not_covered` with one (K10, the classes round): a
253    /// chained request's link read a key the method's classes do not hold (`E_FORMULA_DISPATCH_KEY`). [`Rejection`] is
254    /// `not_covered` without it; the mesh takes it with [`take_fault`] when it answers the rejection.
255    static CALL_FAULT: std::cell::Cell<Option<datumesh_core::Fault>> = const { std::cell::Cell::new(None) };
256}
257
258/// The fault the last `not_covered` rejection of this thread carries, if any (taken: it is given once).
259pub(crate) fn take_fault() -> Option<datumesh_core::Fault> {
260    CALL_FAULT.with(|f| f.take())
261}
262
263thread_local! {
264    /// The reason of a label whose lookup cell is withdrawn (R1, SPEC 16.7), set by the lookup of this thread's request.
265    static LABEL_WITHDRAWN: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
266}
267
268/// Records that a label of the request is withdrawn, with its reason (the lookup cell's withdrawal).
269pub(crate) fn set_label_withdrawn(reason: String) {
270    LABEL_WITHDRAWN.with(|l| *l.borrow_mut() = Some(reason));
271}
272
273/// The reason of the withdrawn label of this thread's request, if one was looked up (taken: given once).
274pub(crate) fn take_label_withdrawn() -> Option<String> {
275    LABEL_WITHDRAWN.with(|l| l.borrow_mut().take())
276}
277
278/// Whether `rest` (the text after `/cell/`, query included, as received) is a call rather
279/// than a cell URI's rest: its path (before the first `?`) has a `(` or a `%`, or starts with
280/// `@`, none of which a cell URI's path (namespace and name) has.
281pub fn is_call(rest: &str) -> bool {
282    let path = rest.split('?').next().unwrap_or("");
283    path.contains('(') || path.contains('%') || path.starts_with('@')
284}
285
286/// Resolves a request: a call or a cell URI's rest (see the module documentation). `now` is
287/// the asof used to look the name up when the request has none. `slice` allows `*` (and
288/// requires one).
289pub 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    // The accepted forms of an as-of (instant.rs, CONTRACT-protocol-part1 H3) are read as their canonical instant.
297    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
305/// The parameters of a URI's query, split leniently (for the asof, the pin and a synthetic
306/// signature; `parse_reference` checks them properly).
307fn 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
314/// The codes `parse_reference` reports before it reads the signature, or independently of
315/// the arguments' types: what a URI whose function the mesh does not know can still be
316/// refused with.
317fn 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
331/// Resolves a cell URI's rest.
332pub 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    // The asof the name is looked up at: the last parameter's, when it is an instant; the pin,
339    // the last remaining one's when it is named fn_hash and is 64 lowercase hex digits.
340    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        // No function to parse against: report what the URI's form alone shows (every
368        // argument read as a string), else not_covered: the name unbound, or the pin unknown.
369        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        // A function name core refuses (2.2, 2.3: a segment or the whole name over its limit, a name
377        // that is not canonical) is answered with core's canonical code (spec-0.6.1, 5.4).
378        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        // A cell at the slice endpoint: the request names no slice.
401        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    // format(parse(uri)) = uri (SPEC 5.4): the accepted URI is the canonical one.
412    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
426/// Percent-decodes a URL path (any `%XX`, either case; the result must be UTF-8).
427pub(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
444/// [`Bindings`] as the formula crate's call environment: aliases from the mesh's map, names as
445/// of the call's asof (or now), descriptors by pin.
446struct Env<'a> {
447    bindings: &'a dyn Bindings,
448    aliases: &'a BTreeMap<String, String>,
449    now: &'a str,
450    /// The request named no asof: its reads are current (G10).
451    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
496/// The most methods a chained call names (R11): its links after the first call.
497const MAX_CHAIN_LINKS: usize = 8;
498
499/// The links of a call's chain: the `.` at the top level after its first bracketed group (a name's own dots come before it;
500/// a quoted label or an argument's text has none that count).
501fn 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
524/// Whether a call's reads are current: it names no asof (a request naming one, past or future, stores
525/// nothing; G10, second review B1).
526fn is_current(query: Option<&str>) -> bool {
527    !query.is_some_and(|q| q.split('&').any(|p| p.starts_with("asof=")))
528}
529
530/// Resolves a call (SPEC 5.8).
531pub 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    // At most 8 methods in a chain (R11): each link is a `.` after the first call's own brackets.
548    if chain_links(&text) > MAX_CHAIN_LINKS {
549        return Err(Rejection::BadRequest(ErrorCode::ParseUri));
550    }
551    // A call that names no asof is current: its links and lookups are (G10).
552    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        // The target may come from the cache: the clone carries what this request resolved, and is
579        // not cached.
580        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
589/// The URI of a reference with its pin (core's `format_reference`).
590pub fn format_pinned(reference: &Reference) -> String {
591    format_reference(reference)
592}