1use 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
20const 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
45pub 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 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
75fn 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
117pub 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
137pub 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 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 let mut descriptors: BTreeMap<String, String> = BTreeMap::new(); let mut bindings: BTreeMap<String, Vec<(String, String)>> = BTreeMap::new(); let mut invalid_bindings: BTreeMap<String, Vec<(String, String)>> = BTreeMap::new();
216 let mut versions: BTreeMap<String, Vec<(String, String, String)>> = BTreeMap::new(); let (mut receipts, mut refused, mut manifests) = (0usize, Vec::new(), 0usize);
218 let mut blobs = 0usize;
219 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 =
229 |bytes: &[u8], id: &str, versions: &mut BTreeMap<String, Vec<(String, String, String)>>| match (
230 store.put_receipt(bytes),
231 Receipt::from_json(bytes),
232 ) {
233 (Ok(h), Ok(r)) => {
234 receipts += 1;
235 versions.entry(r.cell().id()).or_default().push((r.tx().to_string(), h, r.cell().fn_hash.clone()));
236 }
237 (Err(e), _) => refused.push(format!("{id}: {e}")),
238 _ => {}
239 };
240 for v in &vs {
241 let id = v.get("id").and_then(Value::as_str).unwrap_or("?").to_string();
242 match kind(v).as_str() {
243 "receipt" if valid(v) => {
244 let Some(text) = v.get("input").and_then(Value::as_str) else { continue };
245 let rc = v.get("recompute");
246 if let (Some(d), Ok(r)) = (rc.and_then(|r| r.get("descriptor")), Receipt::from_json(text.as_bytes())) {
247 if let Some(h) = put_descriptor(d, &mut descriptors) {
248 if h == r.cell().fn_hash {
249 bindings.entry(r.cell().function_name()).or_default().push((r.tx().to_string(), h));
250 }
251 }
252 }
253 for (h, t) in rc.and_then(|r| r.get("inputs")).and_then(Value::as_object).unwrap_or(&[]) {
254 if let Some(t) = t.as_str() {
255 put_receipt(t.as_bytes(), &format!("{id} input {h}"), &mut versions);
256 }
257 }
258 for (_, t) in rc.and_then(|r| r.get("manifests")).and_then(Value::as_object).unwrap_or(&[]) {
259 if t.as_str().is_some_and(|t| store.put_manifest(t.as_bytes()).is_ok()) {
260 manifests += 1;
261 }
262 }
263 put_receipt(text.as_bytes(), &id, &mut versions);
264 }
265 "slice" if valid(v) => {
266 if let Some(t) = v.get("input").and_then(Value::as_str) {
267 if Manifest::from_json(t.as_bytes()).is_ok() && store.put_manifest(t.as_bytes()).is_ok() {
268 manifests += 1;
269 }
270 }
271 }
272 "formula-eval" | "excel" => {
273 let rebound = id == "invalid/formula-eval-class-dispatch-rebound";
274 if kind(v) == "excel" {
278 if let Some(d) = excel_descriptor(v) {
279 put_descriptor(&d, &mut descriptors);
280 }
281 }
282 let Some(w) = v.get("world") else { continue };
283 for (_, hex) in w.get("blobs").and_then(Value::as_object).unwrap_or(&[]) {
284 let bytes: Option<Vec<u8>> = hex.as_str().and_then(|h| {
285 (0..h.len()).step_by(2).map(|i| u8::from_str_radix(h.get(i..i + 2)?, 16).ok()).collect()
286 });
287 if let Some(b) = bytes {
288 if store.put_blob(&b).is_ok() {
289 blobs += 1;
290 }
291 }
292 }
293 for (name, f) in w.get("functions").and_then(Value::as_object).unwrap_or(&[]) {
294 let (Some(d), Some(b)) = (f.get("descriptor"), f.get("bound").and_then(Value::as_str)) else {
295 continue;
296 };
297 if let Some(h) = put_descriptor(d, &mut descriptors) {
298 let to = if valid(v) { &mut bindings } else { &mut invalid_bindings };
299 to.entry(name.clone()).or_default().push((b.to_string(), h));
300 }
301 }
302 if !rebound {
303 for (name, c) in w.get("classes").and_then(Value::as_object).unwrap_or(&[]) {
304 if let (Some(d), Some(b)) = (c.get("descriptor"), c.get("bound").and_then(Value::as_str)) {
305 classes.entry(name.clone()).or_insert_with(|| (b.to_string(), d.to_jcs()));
306 }
307 }
308 }
309 if let Some(Value::Array(rs)) = w.get("receipts") {
310 for r in rs {
311 put_receipt(&r.to_jcs(), &format!("{id} world"), &mut versions);
312 }
313 }
314 }
315 _ => {}
316 }
317 }
318
319 let (mut bound, mut skipped) = (0usize, Vec::new());
323 let json_of = |b: &[u8]| json::parse(b).unwrap_or(Value::Null);
326 let mut by_class: BTreeSet<(String, String)> = BTreeSet::new();
327 for (cname, (_, bytes)) in &classes {
328 for (m, h) in json_of(bytes).get("methods").and_then(Value::as_object).unwrap_or(&[]) {
329 if let Some(h) = h.as_str() {
330 by_class.insert((format!("{cname}/{m}"), h.to_string()));
331 }
332 }
333 }
334 let method_names: BTreeSet<&String> = by_class.iter().map(|(n, _)| n).collect();
335 bindings.retain(|n, _| !method_names.contains(n));
336 invalid_bindings.retain(|n, _| !method_names.contains(n));
337 for (name, cs) in invalid_bindings {
338 bindings.entry(name).or_insert(cs);
339 }
340 for (name, cs) in &bindings {
341 let hashes: BTreeSet<&String> = cs.iter().map(|(_, h)| h).collect();
342 let (since, h) = cs.iter().filter(|(_, h)| *h == cs[0].1).min().cloned().unwrap_or_default();
343 if hashes.len() > 1 {
344 skipped.push(format!("{name}: {} functions, the first bound", hashes.len()));
345 }
346 match store.resolve_binding(name, "9999-12-31T23:59:59.999999Z") {
347 Ok(Some(b)) if b.fn_hash == h => {}
348 Ok(None) => {
349 if store.bind_name(name, &h, &since).is_ok() {
350 bound += 1;
351 }
352 }
353 _ => skipped.push(format!("{name}: already bound otherwise")),
354 }
355 }
356 let mut classes_bound = 0usize;
359 let mut pending: Vec<(String, String, Vec<u8>)> = classes.into_iter().map(|(n, (b, d))| (n, b, d)).collect();
360 loop {
361 let before = pending.len();
362 pending.retain(|(name, since, bytes)| {
363 let Ok(h) = store.put_class(bytes) else { return true };
364 match store.resolve_class(name, "9999-12-31T23:59:59.999999Z") {
365 Ok(Some(b)) if b == h => return false,
366 Ok(None) => {}
367 _ => return true,
368 }
369 match store.bind_class(name, &h, since) {
370 Ok(()) => {
371 classes_bound += 1;
372 false
373 }
374 Err(_) => true,
375 }
376 });
377 if pending.is_empty() || pending.len() == before {
378 break;
379 }
380 }
381 skipped.extend(pending.iter().map(|(n, _, _)| format!("{n}: class not stored or bound")));
382 let mut stored_versions = 0usize;
385 for (cell_id, mut vs) in versions {
386 vs.sort();
387 vs.dedup_by(|a, b| a.0 == b.0);
388 for (tx, hash, fn_hash) in vs {
389 if descriptors.get(&fn_hash).map(String::as_str) != Some("stored") {
390 continue;
391 }
392 match store.latest(&cell_id) {
393 Ok(Some(l)) if l.tx >= tx => continue,
394 _ => {}
395 }
396 if store.put_version(&cell_id, &tx, &hash).is_ok() {
397 stored_versions += 1;
398 }
399 }
400 }
401 Value::Object(vec![
402 ("bindings".into(), num(bound)),
403 ("blobs".into(), num(blobs)),
404 ("classes".into(), num(classes_bound)),
405 ("bindings_skipped".into(), Value::Array(skipped.iter().map(|x| s(x)).collect())),
406 ("descriptors".into(), num(descriptors.len())),
407 ("manifests".into(), num(manifests)),
408 ("namespaces".into(), num(namespaces)),
409 ("receipts".into(), num(receipts)),
410 ("receipts_refused".into(), Value::Array(refused.iter().map(|x| s(x)).collect())),
411 ("versions".into(), num(stored_versions)),
412 ])
413}