Skip to main content

datumesh_http/
vectors.rs

1//! `import-vectors`: the spec's vectors' cells into a store (see `deploy/README.md`).
2//!
3//! What it puts, and nothing else: the key documents of the receipt vectors (each retrieved
4//! document) and of the formula vectors' hosts (the test keys of SPEC 11), merged per host;
5//! every descriptor the vectors give (a receipt vector's, every formula and excel vector's
6//! function, valid or not: a pinned request evaluates any of them); every receipt (each
7//! verified by `put_receipt`); the manifests; the names the valid vectors bind (a name bound
8//! to several functions keeps the first, reported), and the names only invalid vectors bind
9//! (their first function); the stored cells' versions.
10
11use std::collections::{BTreeMap, BTreeSet};
12use std::path::Path;
13
14use datumesh_core::json::{self, Value};
15use datumesh_core::{keys_from_response, FunctionDescriptor, Manifest, Receipt, SigningKey};
16use datumesh_store::Store;
17
18use crate::publish::{PublishError, PublishErrorKind};
19
20/// The formula vectors' conventions (SPEC 11): each host's key from the seed
21/// SHA-256("datumesh formula test key: <host>"), valid from 2020-01-01.
22const KEY_FROM: &str = "2020-01-01T00:00:00.000000Z";
23
24fn files(dir: &Path, out: &mut Vec<std::path::PathBuf>) {
25    let Ok(rd) = std::fs::read_dir(dir) else { return };
26    let mut es: Vec<_> = rd.filter_map(Result::ok).map(|e| e.path()).collect();
27    es.sort();
28    for p in es {
29        if p.is_dir() {
30            files(&p, out);
31        } else if p.extension().is_some_and(|e| e == "json") {
32            out.push(p);
33        }
34    }
35}
36
37fn s(v: &str) -> Value {
38    Value::String(v.to_string())
39}
40
41fn num(n: usize) -> Value {
42    json::parse(n.to_string().as_bytes()).unwrap_or(Value::Null)
43}
44
45/// An excel vector's function (SPEC 11): `{"code": {"body": <body>, "lang": "formula"},
46/// "inputs": <the derived inputs>, "signature": <signature>}`, the inputs the names its body
47/// reads.
48pub fn excel_descriptor(v: &Value) -> Option<Value> {
49    let body = v.get("body")?.as_str()?;
50    let ast = datumesh_formula::canonical_ast(body, None).ok()?;
51    // The reads of the canonical AST (its JCS form: objects with "node": "read" and "fn").
52    fn reads(v: &Value, out: &mut BTreeSet<String>) {
53        match v {
54            Value::Object(m) => {
55                if v.get("node").and_then(Value::as_str) == Some("read") {
56                    if let Some(f) = v.get("fn").and_then(Value::as_str) {
57                        out.insert(f.to_string());
58                    }
59                }
60                m.iter().for_each(|(_, x)| reads(x, out));
61            }
62            Value::Array(a) => a.iter().for_each(|x| reads(x, out)),
63            _ => {}
64        }
65    }
66    let mut names = BTreeSet::new();
67    reads(&json::parse(&ast.to_jcs()).ok()?, &mut names);
68    Some(Value::Object(vec![
69        ("code".into(), Value::Object(vec![("body".into(), s(body)), ("lang".into(), s("formula"))])),
70        ("inputs".into(), Value::Array(names.into_iter().map(|n| s(&n)).collect())),
71        ("signature".into(), v.get("signature")?.clone()),
72    ]))
73}
74
75/// Imports the vectors under `dir` (a spec's `vectors/`) into `store` (see the module docs);
76/// a report as JSON: what was put, and what was refused or skipped.
77/// The names the vectors in `dir` would bind: their worlds' functions, classes and class methods,
78/// and the functions of their valid receipts whose descriptor is the receipt's cell's.
79fn bound_names(dir: &Path) -> Vec<String> {
80    let mut paths = Vec::new();
81    files(dir, &mut paths);
82    let mut out = Vec::new();
83    for p in &paths {
84        let Some(v) = std::fs::read(p).ok().and_then(|b| json::parse(&b).ok()) else { continue };
85        let kind = v.get("kind").and_then(Value::as_str).unwrap_or("");
86        if matches!(kind, "formula-eval" | "excel") {
87            if let Some(w) = v.get("world") {
88                for (name, _) in w.get("functions").and_then(Value::as_object).unwrap_or(&[]) {
89                    out.push(name.clone());
90                }
91                for (cname, c) in w.get("classes").and_then(Value::as_object).unwrap_or(&[]) {
92                    out.push(cname.clone());
93                    let methods = c.get("descriptor").and_then(|d| d.get("methods")).and_then(Value::as_object);
94                    for (m, _) in methods.unwrap_or(&[]) {
95                        out.push(format!("{cname}/{m}"));
96                    }
97                }
98            }
99        }
100        if kind == "receipt" && v.get("valid") == Some(&Value::Bool(true)) {
101            let rc = v.get("recompute");
102            let (Some(d), Some(text)) = (rc.and_then(|r| r.get("descriptor")), v.get("input").and_then(Value::as_str))
103            else {
104                continue;
105            };
106            let (Ok(fd), Ok(r)) = (FunctionDescriptor::from_value(d), Receipt::from_json(text.as_bytes())) else {
107                continue;
108            };
109            if fd.hash() == r.cell().fn_hash {
110                out.push(r.cell().function_name());
111            }
112        }
113    }
114    out
115}
116
117/// As [`import`], for a mesh whose own namespaces are `host` and `owned` (`import-vectors`): the
118/// whole import is refused before any write when a name it would bind is under one of them
119/// ([`PublishErrorKind::OwnedVectorName`]). Other names are exempt from rule A.
120pub fn import_in<S: Store + ?Sized>(
121    store: &S,
122    dir: &Path,
123    now: &str,
124    host: &str,
125    owned: &[String],
126) -> Result<Value, PublishError> {
127    let mine = |name: &str| {
128        let h = name.split('/').next().unwrap_or("");
129        h == host || owned.iter().any(|o| o == h)
130    };
131    if let Some(name) = bound_names(dir).into_iter().find(|n| mine(n)) {
132        return Err(PublishError::typed(0, PublishErrorKind::OwnedVectorName(name)));
133    }
134    Ok(import(store, dir, now))
135}
136
137/// Imports the spec's vectors in `dir` into `store`, binding their names at `now` (see the
138/// module documentation). The mesh's own namespaces are not checked: see [`import_in`].
139pub fn import<S: Store + ?Sized>(store: &S, dir: &Path, now: &str) -> Value {
140    let mut paths = Vec::new();
141    files(dir, &mut paths);
142    let vs: Vec<Value> = paths.iter().filter_map(|p| json::parse(&std::fs::read(p).ok()?).ok()).collect();
143    let valid = |v: &Value| v.get("valid") == Some(&Value::Bool(true));
144    let kind = |v: &Value| v.get("kind").and_then(Value::as_str).unwrap_or("").to_string();
145
146    // Key documents: every valid receipt vector's retrieved documents and the formula
147    // vectors' hosts' test keys, merged per host by key id.
148    let mut keys: BTreeMap<String, BTreeMap<String, Value>> = BTreeMap::new();
149    let mut world_hosts = BTreeSet::new();
150    for v in &vs {
151        if kind(v) == "receipt" && valid(v) {
152            for (host, env) in v.get("keys").and_then(Value::as_object).unwrap_or(&[]) {
153                let https = env.get("https");
154                if https.and_then(|h| h.get("status")).and_then(Value::as_number_text) != Some("200") {
155                    continue;
156                }
157                let Some(body) = https.and_then(|h| h.get("body")).and_then(Value::as_str) else { continue };
158                if keys_from_response(host, 200, Some(body.as_bytes())).is_err() {
159                    continue;
160                }
161                let doc = json::parse(body.as_bytes()).unwrap_or(Value::Null);
162                if let Some(Value::Array(ks)) = doc.get("keys") {
163                    for k in ks {
164                        if let Some(id) = k.get("id").and_then(Value::as_str) {
165                            keys.entry(host.clone()).or_default().entry(id.to_string()).or_insert_with(|| k.clone());
166                        }
167                    }
168                }
169            }
170        }
171        if matches!(kind(v).as_str(), "formula-eval" | "excel") {
172            if let Some(w) = v.get("world") {
173                for (name, _) in w.get("functions").and_then(Value::as_object).unwrap_or(&[]) {
174                    world_hosts.insert(name.split('/').next().unwrap_or("").to_string());
175                }
176                if let Some(Value::Array(rs)) = w.get("receipts") {
177                    for r in rs {
178                        if let Some(h) = r.get("computed_by").and_then(Value::as_str) {
179                            world_hosts.insert(h.split('#').next().unwrap_or("").to_string());
180                        }
181                    }
182                }
183            }
184        }
185    }
186    for host in &world_hosts {
187        let key =
188            SigningKey::from_seed(&datumesh_core::sha256(format!("datumesh formula test key: {host}").as_bytes()));
189        let k = Value::Object(vec![
190            ("alg".into(), s("ed25519")),
191            ("id".into(), s(key.key_id())),
192            ("public".into(), s(&datumesh_core::lexical::to_hex(&key.public_key()))),
193            ("valid_from".into(), s(KEY_FROM)),
194        ]);
195        keys.entry(host.clone()).or_default().entry(key.key_id().to_string()).or_insert(k);
196    }
197    let mut namespaces = 0;
198    for (host, ks) in &keys {
199        let doc = Value::Object(vec![
200            ("host".into(), s(host)),
201            ("keys".into(), Value::Array(ks.values().take(64).cloned().collect())),
202            ("proto".into(), s("datumesh/1")),
203        ])
204        .to_jcs();
205        if store.namespace(host).ok().flatten().map(|n| n.keydoc) != Some(doc.clone())
206            && store.put_namespace(host, &doc, now).is_ok()
207        {
208            namespaces += 1;
209        }
210    }
211
212    // Descriptors, receipts, manifests; candidate bindings and versions.
213    let mut descriptors: BTreeMap<String, String> = BTreeMap::new(); // fn_hash -> lang
214    let mut bindings: BTreeMap<String, Vec<(String, String)>> = BTreeMap::new(); // name -> (since, fn_hash)
215    let mut invalid_bindings: BTreeMap<String, Vec<(String, String)>> = BTreeMap::new();
216    let mut versions: BTreeMap<String, Vec<(String, String, String)>> = BTreeMap::new(); // cell id -> (tx, hash, fn_hash)
217    let (mut receipts, mut refused, mut manifests) = (0usize, Vec::new(), 0usize);
218    let mut blobs = 0usize;
219    // Classes a vector world defines: name -> (bound, canonical descriptor bytes); a vector that cannot
220    // be loaded through a store (its class names a method hash the world lacks, by design) is skipped.
221    let mut classes: BTreeMap<String, (String, Vec<u8>)> = BTreeMap::new();
222    let put_descriptor = |d: &Value, descriptors: &mut BTreeMap<String, String>| -> Option<String> {
223        let fd = FunctionDescriptor::from_value(d).ok()?;
224        let h = store.put_descriptor(&fd.canonical()).ok()?;
225        descriptors.insert(h.clone(), fd.lang.clone());
226        Some(h)
227    };
228    let mut put_receipt = |bytes: &[u8], id: &str, versions: &mut BTreeMap<String, Vec<(String, String, String)>>| {
229        // A valued receipt, or a withdrawal (the null version, SPEC 8.1): both are versions of their cell.
230        let parsed = match Receipt::from_json(bytes) {
231            Ok(r) => Ok((r.cell().id(), r.tx().to_string(), r.cell().fn_hash.clone())),
232            Err(e) => match datumesh_core::Withdrawal::from_json(bytes) {
233                Ok(w) => Ok((w.cell().id(), w.tx().to_string(), w.cell().fn_hash.clone())),
234                Err(_) => Err(e),
235            },
236        };
237        match (store.put_receipt(bytes), parsed) {
238            (Ok(h), Ok((cell_id, tx, fn_hash))) => {
239                receipts += 1;
240                versions.entry(cell_id).or_default().push((tx, h, fn_hash));
241            }
242            (Err(e), _) => refused.push(format!("{id}: {e}")),
243            _ => {}
244        }
245    };
246    for v in &vs {
247        let id = v.get("id").and_then(Value::as_str).unwrap_or("?").to_string();
248        match kind(v).as_str() {
249            "receipt" if valid(v) => {
250                let Some(text) = v.get("input").and_then(Value::as_str) else { continue };
251                let rc = v.get("recompute");
252                if let (Some(d), Ok(r)) = (rc.and_then(|r| r.get("descriptor")), Receipt::from_json(text.as_bytes())) {
253                    if let Some(h) = put_descriptor(d, &mut descriptors) {
254                        if h == r.cell().fn_hash {
255                            bindings.entry(r.cell().function_name()).or_default().push((r.tx().to_string(), h));
256                        }
257                    }
258                }
259                for (h, t) in rc.and_then(|r| r.get("inputs")).and_then(Value::as_object).unwrap_or(&[]) {
260                    if let Some(t) = t.as_str() {
261                        put_receipt(t.as_bytes(), &format!("{id} input {h}"), &mut versions);
262                    }
263                }
264                for (_, t) in rc.and_then(|r| r.get("manifests")).and_then(Value::as_object).unwrap_or(&[]) {
265                    if t.as_str().is_some_and(|t| store.put_manifest(t.as_bytes()).is_ok()) {
266                        manifests += 1;
267                    }
268                }
269                put_receipt(text.as_bytes(), &id, &mut versions);
270            }
271            "slice" if valid(v) => {
272                if let Some(t) = v.get("input").and_then(Value::as_str) {
273                    if Manifest::from_json(t.as_bytes()).is_ok() && store.put_manifest(t.as_bytes()).is_ok() {
274                        manifests += 1;
275                    }
276                }
277            }
278            "formula-eval" | "excel" => {
279                let rebound = id == "invalid/formula-eval-class-dispatch-rebound";
280                // Every vector's functions (so a pinned request evaluates it), bound by name
281                // from the valid ones only; an excel vector's function is its printed body
282                // under its signature (SPEC 11), known by hash only.
283                if kind(v) == "excel" {
284                    if let Some(d) = excel_descriptor(v) {
285                        put_descriptor(&d, &mut descriptors);
286                    }
287                }
288                let Some(w) = v.get("world") else { continue };
289                for (_, hex) in w.get("blobs").and_then(Value::as_object).unwrap_or(&[]) {
290                    let bytes: Option<Vec<u8>> = hex.as_str().and_then(|h| {
291                        (0..h.len()).step_by(2).map(|i| u8::from_str_radix(h.get(i..i + 2)?, 16).ok()).collect()
292                    });
293                    if let Some(b) = bytes {
294                        if store.put_blob(&b).is_ok() {
295                            blobs += 1;
296                        }
297                    }
298                }
299                for (name, f) in w.get("functions").and_then(Value::as_object).unwrap_or(&[]) {
300                    let (Some(d), Some(b)) = (f.get("descriptor"), f.get("bound").and_then(Value::as_str)) else {
301                        continue;
302                    };
303                    if let Some(h) = put_descriptor(d, &mut descriptors) {
304                        let to = if valid(v) { &mut bindings } else { &mut invalid_bindings };
305                        to.entry(name.clone()).or_default().push((b.to_string(), h));
306                    }
307                }
308                if !rebound {
309                    for (name, c) in w.get("classes").and_then(Value::as_object).unwrap_or(&[]) {
310                        if let (Some(d), Some(b)) = (c.get("descriptor"), c.get("bound").and_then(Value::as_str)) {
311                            classes.entry(name.clone()).or_insert_with(|| (b.to_string(), d.to_jcs()));
312                        }
313                    }
314                }
315                if let Some(Value::Array(rs)) = w.get("receipts") {
316                    for r in rs {
317                        put_receipt(&r.to_jcs(), &format!("{id} world"), &mut versions);
318                    }
319                }
320            }
321            _ => {}
322        }
323    }
324
325    // Bindings: a name with one function is bound from its earliest instant; a name the
326    // vectors bind to several functions keeps the first (one name means one function at a
327    // time) and the others are reported.
328    let (mut bound, mut skipped) = (0usize, Vec::new());
329    // A class's methods are bound by `bind_class` (in one transaction with the class, at the same
330    // instant a vector binds the function): leave those names to it.
331    let json_of = |b: &[u8]| json::parse(b).unwrap_or(Value::Null);
332    let mut by_class: BTreeSet<(String, String)> = BTreeSet::new();
333    for (cname, (_, bytes)) in &classes {
334        for (m, h) in json_of(bytes).get("methods").and_then(Value::as_object).unwrap_or(&[]) {
335            if let Some(h) = h.as_str() {
336                by_class.insert((format!("{cname}/{m}"), h.to_string()));
337            }
338        }
339    }
340    let method_names: BTreeSet<&String> = by_class.iter().map(|(n, _)| n).collect();
341    bindings.retain(|n, _| !method_names.contains(n));
342    invalid_bindings.retain(|n, _| !method_names.contains(n));
343    for (name, cs) in invalid_bindings {
344        bindings.entry(name).or_insert(cs);
345    }
346    for (name, cs) in &bindings {
347        let hashes: BTreeSet<&String> = cs.iter().map(|(_, h)| h).collect();
348        let (since, h) = cs.iter().filter(|(_, h)| *h == cs[0].1).min().cloned().unwrap_or_default();
349        if hashes.len() > 1 {
350            skipped.push(format!("{name}: {} functions, the first bound", hashes.len()));
351        }
352        match store.resolve_binding(name, "9999-12-31T23:59:59.999999Z") {
353            Ok(Some(b)) if b.fn_hash == h => {}
354            Ok(None) => {
355                if store.bind_name(name, &h, &since).is_ok() {
356                    bound += 1;
357                }
358            }
359            _ => skipped.push(format!("{name}: already bound otherwise")),
360        }
361    }
362    // Classes, after the functions: `put_class` (a parent first: retried until no more are stored) and
363    // `bind_class` from `bound` (it binds the methods too).
364    let mut classes_bound = 0usize;
365    let mut pending: Vec<(String, String, Vec<u8>)> = classes.into_iter().map(|(n, (b, d))| (n, b, d)).collect();
366    loop {
367        let before = pending.len();
368        pending.retain(|(name, since, bytes)| {
369            let Ok(h) = store.put_class(bytes) else { return true };
370            match store.resolve_class(name, "9999-12-31T23:59:59.999999Z") {
371                Ok(Some(b)) if b == h => return false,
372                Ok(None) => {}
373                _ => return true,
374            }
375            match store.bind_class(name, &h, since) {
376                Ok(()) => {
377                    classes_bound += 1;
378                    false
379                }
380                Err(_) => true,
381            }
382        });
383        if pending.is_empty() || pending.len() == before {
384            break;
385        }
386    }
387    skipped.extend(pending.iter().map(|(n, _, _)| format!("{n}: class not stored or bound")));
388    // Versions of stored functions' cells, in tx order (a second receipt at one tx is not a
389    // version).
390    let mut stored_versions = 0usize;
391    for (cell_id, mut vs) in versions {
392        vs.sort();
393        vs.dedup_by(|a, b| a.0 == b.0);
394        for (tx, hash, fn_hash) in vs {
395            if descriptors.get(&fn_hash).map(String::as_str) != Some("stored") {
396                continue;
397            }
398            match store.latest(&cell_id) {
399                Ok(Some(l)) if l.tx >= tx => continue,
400                _ => {}
401            }
402            if store.put_version(&cell_id, &tx, &hash).is_ok() {
403                stored_versions += 1;
404            }
405        }
406    }
407    Value::Object(vec![
408        ("bindings".into(), num(bound)),
409        ("blobs".into(), num(blobs)),
410        ("classes".into(), num(classes_bound)),
411        ("bindings_skipped".into(), Value::Array(skipped.iter().map(|x| s(x)).collect())),
412        ("descriptors".into(), num(descriptors.len())),
413        ("manifests".into(), num(manifests)),
414        ("namespaces".into(), num(namespaces)),
415        ("receipts".into(), num(receipts)),
416        ("receipts_refused".into(), Value::Array(refused.iter().map(|x| s(x)).collect())),
417        ("versions".into(), num(stored_versions)),
418    ])
419}