Skip to main content

datumesh_core/
uri.rs

1//! Cell URIs (5.1-5.4) and the HTTPS mapping (5.3).
2
3use crate::error::{err, ErrorCode, Result};
4use crate::json::{jcs_sorted, Value};
5use crate::lexical::{self, limits};
6use crate::model::{check_lexical, unchecked, Arg, Args, CellRef, Type};
7use crate::schema;
8
9fn is_literal(c: u8) -> bool {
10    c.is_ascii_alphanumeric() || matches!(c, b'-' | b'.' | b'_' | b'~' | b':')
11}
12
13fn qpath(name: &str) -> String {
14    format!("uri.query.{name}")
15}
16
17/// Decodes a parameter value (5.2): literal characters as themselves, everything else as
18/// `%` and two uppercase hex digits, and the result UTF-8. Failures are `E_CANON_PERCENT`.
19fn percent_decode(raw: &str, path: &str) -> Result<String> {
20    let b = raw.as_bytes();
21    let mut out = Vec::with_capacity(b.len());
22    let mut i = 0;
23    while i < b.len() {
24        let c = b[i];
25        if c == b'%' {
26            let hex = |x: u8| match x {
27                b'0'..=b'9' => Some(x - b'0'),
28                b'A'..=b'F' => Some(x - b'A' + 10),
29                _ => None,
30            };
31            let (Some(h), Some(l)) = (b.get(i + 1).and_then(|&x| hex(x)), b.get(i + 2).and_then(|&x| hex(x))) else {
32                return err(ErrorCode::CanonPercent, path, "percent-encoding must be % and two uppercase hex digits");
33            };
34            let byte = (h << 4) | l;
35            if is_literal(byte) {
36                return err(
37                    ErrorCode::CanonPercent,
38                    path,
39                    format!("{:?} must not be percent-encoded", char::from(byte)),
40                );
41            }
42            out.push(byte);
43            i += 3;
44        } else if is_literal(c) {
45            out.push(c);
46            i += 1;
47        } else {
48            let shown = raw[i..].chars().next().unwrap_or('?');
49            return err(ErrorCode::CanonPercent, path, format!("{shown:?} must be percent-encoded"));
50        }
51    }
52    String::from_utf8(out).or_else(|_| err(ErrorCode::CanonPercent, path, "decoded bytes are not UTF-8"))
53}
54
55fn percent_encode(s: &str, out: &mut String) {
56    const HEX: &[u8; 16] = b"0123456789ABCDEF";
57    for &c in s.as_bytes() {
58        if is_literal(c) {
59            out.push(char::from(c));
60        } else {
61            out.push('%');
62            out.push(char::from(HEX[usize::from(c >> 4)]));
63            out.push(char::from(HEX[usize::from(c & 0xF)]));
64        }
65    }
66}
67
68/// Parses a cell URI against a function signature (5.4), reporting the first failure in the
69/// order 5.4 defines.
70///
71/// `signature` is the descriptor's `signature` member as JSON. It is taken as given (a
72/// descriptor checked under 7), except that it must be readable: an object with an `args`
73/// object whose members are objects with a string `type` (`E_SCHEMA` otherwise).
74pub fn parse_uri(uri: &str, signature: &Value) -> Result<CellRef> {
75    // 1. Outer grammar.
76    let bad = |d: &str| err(ErrorCode::ParseUri, "$", d.to_string());
77    let Some(rest) = uri.strip_prefix("cell://") else {
78        return bad("not cell://<namespace>/<function>[?<query>]");
79    };
80    if rest.contains('#') {
81        return bad("a cell URI has no fragment");
82    }
83    let (path, query) = match rest.split_once('?') {
84        Some((p, q)) => (p, Some(q)),
85        None => (rest, None),
86    };
87    let authority = path.split('/').next().unwrap_or("");
88    if authority.contains('@') || authority.contains(':') {
89        return bad("a cell URI has no userinfo or port");
90    }
91    let mut params: Vec<(&str, &str)> = Vec::new();
92    if let Some(q) = query {
93        if q.is_empty() {
94            return bad("empty query");
95        }
96        for p in q.split('&') {
97            match p.split_once('=') {
98                Some(kv) => params.push(kv),
99                None => return bad(&format!("parameter without '=': {p:?}")),
100            }
101        }
102    }
103
104    // 2. Namespace and function names.
105    let Some((ns, f)) = path.rsplit_once('/') else {
106        return err(ErrorCode::CanonName, "uri.path", "missing namespace");
107    };
108    lexical::check_namespace(ns, "uri.path")?;
109    lexical::check_name(f, "uri.path")?;
110    if path.len() > limits::FUNCTION_NAME {
111        return err(ErrorCode::CanonLimit, "uri.path", "function name longer than 512 characters");
112    }
113
114    // 3. Parameter names.
115    let asof_raw = match params.last() {
116        Some(&("asof", v)) => {
117            params.pop();
118            Some(v)
119        }
120        _ => None,
121    };
122    let mut prev: Option<&str> = None;
123    for &(name, _) in &params {
124        let p = qpath(name);
125        if name == "asof" {
126            let code = if asof_raw.is_some() { ErrorCode::CanonArgDuplicate } else { ErrorCode::CanonArgOrder };
127            return err(code, &p, "asof is the last parameter, at most once");
128        }
129        lexical::check_arg_name(name, &p)?;
130        if let Some(pr) = prev {
131            if name == pr {
132                return err(ErrorCode::CanonArgDuplicate, &p, "argument repeated");
133            }
134            if name < pr {
135                return err(ErrorCode::CanonArgOrder, &p, "arguments must be sorted by name");
136            }
137        }
138        prev = Some(name);
139    }
140
141    // 4. Count.
142    if params.len() > limits::ARGS {
143        return err(ErrorCode::CanonLimit, "uri.query", "more than 32 arguments");
144    }
145
146    // 5. The signature, then the arguments against it.
147    crate::json::check_value_depth(signature)
148        .map_err(|e| crate::error::Error::new(e.code(), "signature", e.detail()))?;
149    let sig = schema::object(signature, "signature")?;
150    let decls = match schema::opt(sig, "args") {
151        Some(Value::Object(m)) => m,
152        _ => return err(ErrorCode::Schema, "signature.args", "the signature has no args object"),
153    };
154    for (k, d) in jcs_sorted(decls) {
155        let readable = matches!(d.get("type"), Some(Value::String(_))) && d.as_object().is_some();
156        if !readable {
157            return err(
158                ErrorCode::Schema,
159                &format!("signature.args.{k}"),
160                "a declaration is an object with a string type",
161            );
162        }
163    }
164    for &(name, _) in &params {
165        if schema::opt(decls, name).is_none() {
166            return err(ErrorCode::ArgUnknown, &qpath(name), format!("function declares no argument {name:?}"));
167        }
168    }
169    for (k, _) in jcs_sorted(decls) {
170        if !params.iter().any(|&(n, _)| n == k) {
171            return err(ErrorCode::ArgMissing, "uri.query", format!("argument {k:?} absent; use {k}=* for a slice"));
172        }
173    }
174
175    // 6. Values.
176    let mut args = Args::new();
177    for &(name, raw) in &params {
178        let p = qpath(name);
179        if raw == "*" {
180            args.insert(name.into(), Arg::Slice);
181            continue;
182        }
183        let text = percent_decode(raw, &p)?;
184        let tname = schema::get(decls, name).get("type").and_then(Value::as_str).unwrap_or("");
185        let ty = Type::parse(tname, &p)?;
186        check_lexical(ty, &text, &p)?;
187        args.insert(name.into(), Arg::Value(unchecked(ty, &text)));
188    }
189
190    // 7. asof.
191    let asof = match asof_raw {
192        None => None,
193        Some(raw) => {
194            let text = percent_decode(raw, "uri.query.asof")?;
195            lexical::check_instant(&text, "uri.query.asof")?;
196            Some(text)
197        }
198    };
199    Ok(CellRef { ns: ns.into(), fn_name: f.into(), args, asof })
200}
201
202/// Writes the one URI of a cell reference (5.2). `format_uri(&parse_uri(u, s)?) == u` for
203/// every accepted `u`.
204pub fn format_uri(r: &CellRef) -> String {
205    let mut out = format!("cell://{}/{}", r.ns, r.fn_name);
206    let mut first = true;
207    let mut sep = |out: &mut String| {
208        out.push(if first { '?' } else { '&' });
209        first = false;
210    };
211    for (name, arg) in &r.args {
212        sep(&mut out);
213        out.push_str(name);
214        out.push('=');
215        match arg {
216            Arg::Slice => out.push('*'),
217            Arg::Value(s) => percent_encode(s.lexical(), &mut out),
218        }
219    }
220    if let Some(a) = &r.asof {
221        sep(&mut out);
222        out.push_str("asof=");
223        percent_encode(a, &mut out);
224    }
225    out
226}
227
228/// The HTTPS URL of a cell URI on mesh host `mesh` (5.3): `https://<mesh>/cell/<rest>`.
229/// `mesh` must be a DNS name (`E_CANON_NAME`), `uri` must start with `cell://` (`E_PARSE_URI`).
230pub fn https_url(mesh: &str, uri: &str) -> Result<String> {
231    lexical::check_dns_name(mesh, "mesh")?;
232    let Some(rest) = uri.strip_prefix("cell://") else {
233        return err(ErrorCode::ParseUri, "$", "not a cell URI");
234    };
235    Ok(format!("https://{mesh}/cell/{rest}"))
236}
237
238/// The cell URI served at an HTTPS URL on mesh host `mesh` (5.3), by stripping the prefix.
239/// `None` when the URL is not under `https://<mesh>/cell/`.
240pub fn cell_uri_from_https(mesh: &str, url: &str) -> Option<String> {
241    let rest = url.strip_prefix("https://")?.strip_prefix(mesh)?.strip_prefix("/cell/")?;
242    Some(format!("cell://{rest}"))
243}