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//!   Not accepted (reserved by SPEC 15.15 for classes, 1.3b): method chaining
21//!   (`f(...).g(...)`), key literals (`EUR`, `1M`) and class-typed keys; nor expressions,
22//!   ranges or units: `E_PARSE_URI`.
23//!
24//! An unbound name (or alias) is `not_covered` with `E_NAME_UNBOUND`
25//! ([`Rejection::Error`]`(ErrorCode::NameUnbound)`, which the mesh answers so); a pin no
26//! descriptor of the mesh has is a plain `not_covered` ([`Rejection::NotCovered`]); a slice
27//! marker at `/cell` is `E_SLICE_AT_CELL`.
28
29use 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/// A function bound to a name as of an instant.
38#[derive(Clone, Debug)]
39pub struct Bound {
40    /// The function hash.
41    pub fn_hash: String,
42    /// When the binding began.
43    pub since: String,
44    /// The descriptor.
45    pub descriptor: Arc<FunctionDescriptor>,
46    /// The descriptor's signature as JSON (what `parse_uri` reads).
47    pub signature: Arc<Value>,
48}
49
50impl Bound {
51    /// A binding of `fn_hash` since `since` to `descriptor`.
52    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
58/// Where names are looked up: the mesh's store (and, for names under other hosts, the
59/// cross-mesh resolver in front of it).
60pub trait Bindings {
61    /// The binding of `fn_name` as of `asof`; `Ok(None)` when it has none. An `Err` is the
62    /// code of an `error` envelope (the store or another mesh failed).
63    fn binding(&self, fn_name: &str, asof: &str) -> Result<Option<Arc<Bound>>, ErrorCode>;
64
65    /// A target resolved before for the cell URI rest `rest` under function hash `fn_hash`
66    /// (parsing depends on nothing else). Provided: none.
67    fn cached(&self, fn_hash: &str, rest: &str) -> Option<Arc<Target>> {
68        let _ = (fn_hash, rest);
69        None
70    }
71
72    /// Remembers a resolved target for [`Bindings::cached`]. Provided: nothing.
73    fn remember(&self, rest: &str, target: &Arc<Target>) {
74        let _ = (rest, target);
75    }
76
77    /// The descriptor whose function hash is `fn_hash` (a pin, spec-0.4.2), as a binding of
78    /// no time (`since` empty); `Ok(None)` when the mesh has none. Provided: none.
79    fn pinned(&self, fn_hash: &str) -> Result<Option<Arc<Bound>>, ErrorCode> {
80        let _ = fn_hash;
81        Ok(None)
82    }
83
84    /// The fully qualified name an alias (without `@`) stands for. Provided: none.
85    fn alias(&self, alias: &str) -> Option<String> {
86        let _ = alias;
87        None
88    }
89}
90
91/// A request resolved to its cell (or slice, at `/slice`).
92#[derive(Clone, Debug)]
93pub struct Target {
94    /// The canonical cell URI, `asof` included when the request had one.
95    pub uri: String,
96    /// The reference (`asof` included).
97    pub reference: CellRef,
98    /// The cell, with the function hash the name is bound to as of the asof.
99    pub cell: Cell,
100    id: std::sync::OnceLock<String>,
101    key: std::sync::OnceLock<String>,
102    /// The binding (for a pinned request, the pinned descriptor).
103    pub bound: Arc<Bound>,
104    /// The pin (spec-0.4.2): the function hash the request named, if it named one.
105    pub pin: Option<String>,
106}
107
108impl Target {
109    /// The function's fully qualified name.
110    pub fn fn_name(&self) -> String {
111        format!("{}/{}", self.reference.ns, self.reference.fn_name)
112    }
113
114    /// The cell's id (SPEC 4.4), computed once.
115    pub fn cell_id(&self) -> &str {
116        self.id.get_or_init(|| self.cell.id())
117    }
118
119    /// The cell's key: its function hash and its URI without `asof` (computed once).
120    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    /// The reference with its pin (spec-0.4.2): what the request denotes.
132    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    /// The requested asof, if any.
139    pub fn asof(&self) -> Option<&str> {
140        self.reference.asof.as_deref()
141    }
142
143    /// The cell URI's `<rest>` (SPEC 5.3), without `cell://`.
144    pub fn rest(&self) -> &str {
145        &self.uri["cell://".len()..]
146    }
147
148    /// The rest with `asof` set to `asof` (replacing one there).
149    pub fn rest_asof(&self, asof: &str) -> String {
150        let rest = self.rest();
151        let base = match self.reference.asof.as_deref() {
152            // `asof` is the last parameter of a canonical URI.
153            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/// Why a request names no cell.
162#[derive(Clone, Copy, Debug, PartialEq, Eq)]
163pub enum Rejection {
164    /// `bad_request` with this code.
165    BadRequest(ErrorCode),
166    /// `not_covered`: the mesh does not serve the function (a pin no descriptor of it has).
167    NotCovered,
168    /// `error` with this code: looking the name up failed. `ErrorCode::NameUnbound` stands
169    /// for an unbound name, answered `not_covered` with that code (spec-0.4.2; this enum is
170    /// exhaustive, so 0.1.1 gives that case no variant of its own).
171    Error(ErrorCode),
172}
173
174/// Whether `rest` (the text after `/cell/`, query included, as received) is a call rather
175/// than a cell URI's rest: its path (before the first `?`) has a `(` or a `%`, or starts with
176/// `@`, none of which a cell URI's path (namespace and name) has.
177pub fn is_call(rest: &str) -> bool {
178    let path = rest.split('?').next().unwrap_or("");
179    path.contains('(') || path.contains('%') || path.starts_with('@')
180}
181
182/// Resolves a request: a call or a cell URI's rest (see the module documentation). `now` is
183/// the asof used to look the name up when the request has none. `slice` allows `*` (and
184/// requires one).
185pub 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
199/// The parameters of a URI's query, split leniently (for the asof, the pin and a synthetic
200/// signature; `parse_reference` checks them properly).
201fn 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
208/// The codes `parse_reference` reports before it reads the signature, or independently of
209/// the arguments' types: what a URI whose function the mesh does not know can still be
210/// refused with.
211fn 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
225/// Resolves a cell URI's rest.
226pub 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    // The asof the name is looked up at: the last parameter's, when it is an instant; the pin,
233    // the last remaining one's when it is named fn_hash and is 64 lowercase hex digits.
234    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        // No function to parse against: report what the URI's form alone shows (every
262        // argument read as a string), else not_covered: the name unbound, or the pin unknown.
263        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        // A cell at the slice endpoint: the request names no slice.
289        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    // format(parse(uri)) = uri (SPEC 5.4): the accepted URI is the canonical one.
300    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
313/// Percent-decodes a URL path (any `%XX`, either case; the result must be UTF-8).
314fn 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
331/// [`Bindings`] as the formula crate's call environment: aliases from the mesh's map, names as
332/// of the call's asof (or now), descriptors by pin.
333struct 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
357/// Resolves a call (SPEC 5.8).
358pub 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
394/// The URI of a reference with its pin (core's `format_reference`).
395pub fn format_pinned(reference: &Reference) -> String {
396    format_reference(reference)
397}