1use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
62use std::io::{BufRead, Write};
63use std::path::{Path, PathBuf};
64use std::sync::atomic::{AtomicBool, Ordering};
65use std::sync::Arc;
66
67use datumesh_core::json::{self, Value};
68use datumesh_core::{
69 sha256_hex, Arg, Args, Cell, ClassDescriptor, FunctionDescriptor, KeyNormalisation, Receipt, ReceiptBuilder,
70 Scalar, SigningKey, Source, Type,
71};
72use datumesh_engine::{Clock, SystemClock};
73use datumesh_formula::definition::{Callee, Callees, ClassCallee};
74use datumesh_store::{Binding, CellWrite, FunctionTest, Namespace, Store};
75
76use crate::testrun::{self, run_test, Overlay, Ran, RowWrite, TestSpec};
77
78use crate::config::ConfigError;
79
80const END: &str = "9999-12-31T23:59:59.999999Z";
82
83const CHUNK: usize = 1_000;
85
86const LANES_VAR: &str = "DATUMESH_PUBLISH_LANES";
88
89fn publish_lanes() -> Result<usize, PublishError> {
92 let bad = |detail: String| PublishError::at(0, ConfigError::new(LANES_VAR, detail).to_string());
93 match std::env::var(LANES_VAR) {
94 Err(std::env::VarError::NotPresent) => Ok(std::thread::available_parallelism().map_or(1, |n| n.get()).min(4)),
95 Ok(v) => match v.parse::<usize>() {
96 Ok(n) if n > 0 => Ok(n),
97 _ => Err(bad(format!("must be a positive integer, not {v:?}"))),
98 },
99 Err(e) => Err(bad(e.to_string())),
100 }
101}
102
103#[non_exhaustive]
105#[derive(Clone, Debug, Default, PartialEq, Eq)]
106pub struct Published {
107 pub functions: usize,
109 pub classes: usize,
111 pub cells: usize,
113 pub receipts: usize,
115 pub versions: usize,
117 pub blobs: usize,
119 pub blob_bytes: u64,
121 pub descriptors: u64,
123}
124
125#[derive(Clone)]
127pub struct PublishOptions {
128 pub clock: Arc<dyn Clock + Send + Sync>,
131 pub backfill: Option<PathBuf>,
135}
136
137impl PublishOptions {
138 pub fn system() -> PublishOptions {
140 PublishOptions { clock: Arc::new(SystemClock), backfill: None }
141 }
142}
143
144#[non_exhaustive]
146#[derive(Clone, Debug, PartialEq, Eq)]
147pub enum PublishErrorKind {
148 Line,
150 StartBeforeNow {
152 name: String,
154 start: String,
156 now: String,
158 },
159 Backfill(String),
161 OwnedVectorName(String),
163 TestsMissing(String),
166 TestsFailing(String),
169}
170
171impl std::fmt::Display for PublishErrorKind {
172 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
173 match self {
174 PublishErrorKind::Line => f.write_str("refused"),
175 PublishErrorKind::StartBeforeNow { name, start, now } => {
176 write!(f, "binding start {start} of {name} is earlier than the mesh clock {now} (rule A)")
177 }
178 PublishErrorKind::Backfill(why) => write!(f, "--backfill refused: {why}"),
179 PublishErrorKind::OwnedVectorName(name) => {
180 write!(f, "{name} is under a namespace the mesh owns: import-vectors does not bind it")
181 }
182 PublishErrorKind::TestsMissing(text) => write!(f, "E_TESTS_MISSING: {text}"),
183 PublishErrorKind::TestsFailing(text) => write!(f, "E_TESTS_FAILING: {text}"),
184 }
185 }
186}
187
188#[derive(Clone, Debug, PartialEq, Eq)]
190pub struct PublishError {
191 pub line: usize,
193 pub detail: String,
195 pub kind: PublishErrorKind,
197}
198
199impl PublishError {
200 fn at(line: usize, detail: impl Into<String>) -> PublishError {
201 PublishError { line, detail: detail.into(), kind: PublishErrorKind::Line }
202 }
203
204 pub(crate) fn typed(line: usize, kind: PublishErrorKind) -> PublishError {
205 PublishError { line, detail: kind.to_string(), kind }
206 }
207}
208
209impl std::fmt::Display for PublishError {
210 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
211 write!(f, "line {}: {}", self.line, self.detail)
212 }
213}
214
215impl std::error::Error for PublishError {}
216
217fn s(v: &str) -> Value {
218 Value::String(v.to_string())
219}
220
221fn namespace_of(name: &str) -> &str {
223 name.rsplit_once('/').map(|(ns, _)| ns).unwrap_or("")
224}
225
226fn host_of(name: &str) -> &str {
228 name.split('/').next().unwrap_or("")
229}
230
231fn definer<'a>(name: &'a str, host: &'a str, owned: &[String]) -> &'a str {
234 let host_of_name = name.split('/').next().unwrap_or("");
235 if owned.iter().any(|o| o == host_of_name) {
236 namespace_of(name)
237 } else {
238 host
239 }
240}
241
242fn bound_of(v: &Value, line: usize, now: &str) -> Result<String, PublishError> {
244 match v.get("bound") {
245 None => Ok(now.to_string()),
246 Some(b) => b.as_str().map(str::to_string).ok_or_else(|| PublishError::at(line, "bound is not an instant")),
247 }
248}
249
250#[derive(Default)]
253struct Simulation {
254 functions: BTreeMap<String, Vec<(String, String)>>,
256 classes: BTreeMap<String, Vec<(String, String)>>,
258 descriptors: BTreeMap<String, Vec<u8>>,
260 class_bytes: BTreeMap<String, Vec<u8>>,
262 versions: BTreeMap<String, Vec<(String, String)>>,
264}
265
266impl Simulation {
267 fn latest(binds: &BTreeMap<String, Vec<(String, String)>>, name: &str, at: &str) -> Option<(String, String)> {
269 binds.get(name)?.iter().filter(|(t, _)| t.as_str() <= at).max_by(|a, b| a.0.cmp(&b.0)).cloned()
270 }
271}
272
273struct Callers<'a, S: Store + ?Sized> {
275 store: &'a S,
276 sim: Option<&'a Simulation>,
277}
278
279impl<S: Store + ?Sized> Callers<'_, S> {
280 fn function_bytes(&self, hash: &str) -> Result<Option<Vec<u8>>, String> {
281 if let Some(b) = self.sim.and_then(|s| s.descriptors.get(hash)) {
282 return Ok(Some(b.clone()));
283 }
284 Ok(self.store.descriptor(hash).map(|b| b.into_owned()))
285 }
286
287 fn class_bytes(&self, hash: &str) -> Result<Option<Vec<u8>>, String> {
288 if let Some(b) = self.sim.and_then(|s| s.class_bytes.get(hash)) {
289 return Ok(Some(b.clone()));
290 }
291 self.store.class(hash).map_err(|e| e.to_string())
292 }
293}
294
295impl<S: Store + ?Sized> Callees for Callers<'_, S> {
296 fn class_name(&self, class_hash: &str) -> Result<Option<String>, String> {
299 let names = self
300 .store
301 .class_names_bound_to(class_hash, datumesh_formula::definition::LATEST)
302 .map_err(|e| e.to_string())?;
303 if let Some(n) = names.into_iter().next() {
304 return Ok(Some(n));
305 }
306 Ok(self.sim.and_then(|s| {
307 s.classes.iter().find(|(_, v)| v.iter().any(|(_, h)| h == class_hash)).map(|(n, _)| n.clone())
308 }))
309 }
310
311 fn callee(&self, name: &str, at: &str) -> Result<Option<Callee>, String> {
312 let stored = self.store.resolve_binding(name, at).map_err(|e| e.to_string())?;
313 let simmed = self.sim.and_then(|s| Simulation::latest(&s.functions, name, at));
314 let (fn_hash, start) = match (stored, simmed) {
315 (Some(b), Some((t, h))) if t >= b.tx => (h, t),
316 (Some(b), _) => (b.fn_hash, b.tx),
317 (None, Some((t, h))) => (h, t),
318 (None, None) => return Ok(None),
319 };
320 let bytes = self.function_bytes(&fn_hash)?.ok_or_else(|| format!("descriptor {fn_hash} is not stored"))?;
321 let descriptor = json::parse(&bytes).map_err(|e| e.to_string())?;
322 Ok(Some(Callee { fn_hash, start, descriptor }))
323 }
324
325 fn bound_class(&self, name: &str, at: &str) -> Result<Option<ClassCallee>, String> {
326 let stored = self.store.resolve_class_binding(name, at).map_err(|e| e.to_string())?;
327 let simmed = self.sim.and_then(|s| Simulation::latest(&s.classes, name, at));
328 let (class_hash, start) = match (stored, simmed) {
329 (Some(b), Some((t, h))) if t >= b.tx => (h, t),
330 (Some(b), _) => (b.class_hash, b.tx),
331 (None, Some((t, h))) => (h, t),
332 (None, None) => return Ok(None),
333 };
334 let bytes = self.class_bytes(&class_hash)?.ok_or_else(|| format!("class {class_hash} is not stored"))?;
335 let descriptor = ClassDescriptor::from_json(&bytes).map_err(|e| e.to_string())?;
336 Ok(Some(ClassCallee { class_hash, start, descriptor }))
337 }
338
339 fn class_descriptor(&self, class_hash: &str) -> Result<Option<ClassDescriptor>, String> {
340 let Some(bytes) = self.class_bytes(class_hash)? else { return Ok(None) };
341 ClassDescriptor::from_json(&bytes).map(Some).map_err(|e| e.to_string())
342 }
343
344 fn function_descriptor(&self, fn_hash: &str) -> Result<Option<Value>, String> {
345 let Some(bytes) = self.function_bytes(fn_hash)? else { return Ok(None) };
346 json::parse(&bytes).map(Some).map_err(|e| e.to_string())
347 }
348}
349
350#[derive(Default)]
355struct Reads {
356 bindings: HashMap<(String, String), Result<Option<Binding>, String>>,
357 descriptors: HashMap<String, Option<Vec<u8>>>,
358 namespaces: HashMap<String, Result<Option<Namespace>, String>>,
359 latest_of: HashMap<String, Option<(String, String)>>,
361 receipt_of: HashMap<String, Option<Vec<u8>>>,
363}
364
365impl Reads {
366 fn binding<S: Store + ?Sized>(&mut self, store: &S, name: &str, at: &str) -> Result<Option<Binding>, String> {
367 let key = (name.to_string(), at.to_string());
368 if let Some(r) = self.bindings.get(&key) {
369 return r.clone();
370 }
371 let r = store.resolve_binding(name, at).map_err(|e| e.to_string());
372 self.bindings.insert(key, r.clone());
373 r
374 }
375
376 fn descriptor<S: Store + ?Sized>(&mut self, store: &S, hash: &str) -> Option<Vec<u8>> {
377 if let Some(b) = self.descriptors.get(hash) {
378 return b.clone();
379 }
380 let b = store.descriptor(hash).map(|b| b.into_owned());
381 self.descriptors.insert(hash.to_string(), b.clone());
382 b
383 }
384
385 fn namespace<S: Store + ?Sized>(&mut self, store: &S, host: &str) -> Result<Option<Namespace>, String> {
386 if let Some(r) = self.namespaces.get(host) {
387 return r.clone();
388 }
389 let r = store.namespace(host).map_err(|e| e.to_string());
390 self.namespaces.insert(host.to_string(), r.clone());
391 r
392 }
393
394 fn latest<S: Store + ?Sized>(&mut self, store: &S, id: &str) -> Result<Option<(String, String)>, String> {
396 if let Some(l) = self.latest_of.get(id) {
397 return Ok(l.clone());
398 }
399 store.latest(id).map(|v| v.map(|v| (v.tx, v.receipt_hash))).map_err(|e| e.to_string())
400 }
401
402 fn receipt<S: Store + ?Sized>(&mut self, store: &S, hash: &str) -> Option<Vec<u8>> {
404 if let Some(b) = self.receipt_of.get(hash) {
405 return b.clone();
406 }
407 store.receipt(hash).map(|b| b.into_owned())
408 }
409
410 fn prefetch_latest<S: Store + ?Sized>(&mut self, store: &S, ids: &[&str]) {
412 let mut seen = HashSet::new();
413 let missing: Vec<&str> =
414 ids.iter().copied().filter(|id| !self.latest_of.contains_key(*id) && seen.insert(*id)).collect();
415 if missing.is_empty() {
416 return;
417 }
418 if let Ok(found) = store.latest_many(&missing) {
419 for (id, v) in missing.iter().zip(found) {
420 self.latest_of.insert(id.to_string(), v.map(|v| (v.tx, v.receipt_hash)));
421 }
422 }
423 }
424
425 fn prefetch_receipts<S: Store + ?Sized>(&mut self, store: &S, hashes: &[&str]) {
427 let mut seen = HashSet::new();
428 let missing: Vec<&str> =
429 hashes.iter().copied().filter(|h| !self.receipt_of.contains_key(*h) && seen.insert(*h)).collect();
430 if missing.is_empty() {
431 return;
432 }
433 if let Ok(found) = store.receipts_many(&missing) {
434 for (h, b) in missing.iter().zip(found) {
435 self.receipt_of.insert(h.to_string(), b);
436 }
437 }
438 }
439}
440
441fn parallel_owned<T: Send, R: Send>(items: Vec<T>, f: impl Fn(T) -> R + Sync) -> Vec<R> {
443 let threads = std::thread::available_parallelism().map_or(1, |n| n.get()).min(items.len());
444 if threads <= 1 {
445 return items.into_iter().map(f).collect();
446 }
447 let size = items.len().div_ceil(threads);
448 let mut parts: Vec<Vec<T>> = Vec::with_capacity(threads);
449 let mut rest = items.into_iter();
450 loop {
451 let part: Vec<T> = rest.by_ref().take(size).collect();
452 if part.is_empty() {
453 break;
454 }
455 parts.push(part);
456 }
457 std::thread::scope(|s| {
458 let handles: Vec<_> = parts
459 .into_iter()
460 .map(|part| {
461 let f = &f;
462 s.spawn(move || part.into_iter().map(f).collect::<Vec<R>>())
463 })
464 .collect();
465 handles.into_iter().flat_map(|h| h.join().unwrap_or_else(|e| std::panic::resume_unwind(e))).collect()
466 })
467}
468
469fn current_function<S: Store + ?Sized>(store: &S, sim: &Simulation, name: &str) -> Result<Option<String>, String> {
471 if let Some((_, h)) = Simulation::latest(&sim.functions, name, END) {
472 return Ok(Some(h));
473 }
474 store.resolve_name(name, END).map_err(|e| e.to_string())
475}
476
477fn current_class<S: Store + ?Sized>(store: &S, sim: &Simulation, name: &str) -> Result<Option<String>, String> {
479 if let Some((_, h)) = Simulation::latest(&sim.classes, name, END) {
480 return Ok(Some(h));
481 }
482 store.resolve_class(name, END).map_err(|e| e.to_string())
483}
484
485fn key_matches(cd: &ClassDescriptor, fd: &FunctionDescriptor, k: &str) -> bool {
488 let (Some(ck), Some(arg)) = (cd.keys.get(k), fd.signature.args.get(k)) else { return false };
489 match ck {
490 datumesh_core::ClassKey::Scalar { ty, .. } => arg.ty == *ty,
491 datumesh_core::ClassKey::Class(c) => {
492 arg.ty == Type::String
493 && fd.arg_extras.get(k).and_then(|x| x.classes.as_ref()).is_some_and(|cs| cs.iter().any(|x| x == c))
494 }
495 _ => false,
496 }
497}
498
499fn function_at<S: Store + ?Sized>(
501 reads: &mut Reads,
502 store: &S,
503 sim: &Simulation,
504 name: &str,
505 at: &str,
506) -> Result<Option<String>, String> {
507 let stored = reads.binding(store, name, at)?;
508 let simmed = Simulation::latest(&sim.functions, name, at);
509 Ok(match (stored, simmed) {
510 (Some(b), Some((t, h))) if t >= b.tx => Some(h),
511 (Some(b), _) => Some(b.fn_hash),
512 (None, Some((_, h))) => Some(h),
513 (None, None) => None,
514 })
515}
516
517fn latest_bind<S: Store + ?Sized>(
519 store: &S,
520 sim: &Simulation,
521 name: &str,
522 class: bool,
523) -> Result<Option<String>, String> {
524 let stored: Option<String> = if class {
525 store.resolve_class_binding(name, END).map_err(|e| e.to_string())?.map(|b| b.tx)
526 } else {
527 store.resolve_binding(name, END).map_err(|e| e.to_string())?.map(|b| b.tx)
528 };
529 let binds = if class { &sim.classes } else { &sim.functions };
530 let planned = binds.get(name).and_then(|v| v.iter().map(|(t, _)| t.clone()).max());
531 Ok(match (stored, planned) {
532 (Some(a), Some(b)) => Some(a.max(b)),
533 (a, b) => a.or(b),
534 })
535}
536
537fn bound_as_other<S: Store + ?Sized>(store: &S, sim: &Simulation, name: &str, class: bool) -> Result<bool, String> {
539 if class {
540 Ok(store.resolve_binding(name, END).map_err(|e| e.to_string())?.is_some() || sim.functions.contains_key(name))
541 } else {
542 Ok(store.resolve_class_binding(name, END).map_err(|e| e.to_string())?.is_some()
543 || sim.classes.contains_key(name))
544 }
545}
546
547fn cell_latest<S: Store + ?Sized>(
549 reads: &mut Reads,
550 store: &S,
551 sim: &Simulation,
552 id: &str,
553) -> Result<Option<(String, String)>, String> {
554 let stored = reads.latest(store, id)?;
555 let planned = sim.versions.get(id).and_then(|v| v.last().cloned());
556 Ok(match (stored, planned) {
557 (Some(a), Some(b)) => Some(if b.0 > a.0 { b } else { a }),
558 (a, b) => a.or(b),
559 })
560}
561
562fn cell_version_asof<S: Store + ?Sized>(
564 store: &S,
565 sim: &Simulation,
566 id: &str,
567 at: &str,
568) -> Result<Option<String>, String> {
569 let stored = store.version_asof(id, at).map_err(|e| e.to_string())?.map(|v| (v.tx, v.receipt_hash));
570 let planned = sim.versions.get(id).and_then(|v| v.iter().rev().find(|(t, _)| t.as_str() <= at).cloned());
571 let latest = match (stored, planned) {
572 (Some(a), Some(b)) => Some(if b.0 > a.0 { b } else { a }),
573 (a, b) => a.or(b),
574 };
575 Ok(latest.map(|x| x.1))
576}
577
578fn function_bytes_of<S: Store + ?Sized>(
580 reads: &mut Reads,
581 store: &S,
582 sim: &Simulation,
583 hash: &str,
584) -> Result<Option<Vec<u8>>, String> {
585 if let Some(b) = sim.descriptors.get(hash) {
586 return Ok(Some(b.clone()));
587 }
588 Ok(reads.descriptor(store, hash))
589}
590
591fn suspended<S: Store + ?Sized>(reads: &mut Reads, store: &S, host: &str, line: usize) -> Result<(), PublishError> {
593 match reads.namespace(store, host) {
594 Ok(Some(n)) if n.suspended_at.is_some() => {
595 Err(PublishError::at(line, format!("{host} is suspended: no new bindings or classes under it")))
596 }
597 Ok(_) => Ok(()),
598 Err(e) => Err(PublishError::at(line, e)),
599 }
600}
601
602struct Bind {
604 line: usize,
605 name: String,
606}
607
608#[derive(Default)]
610struct Written {
611 namespaces: BTreeSet<String>,
612 starts: BTreeSet<String>,
613}
614
615impl Written {
616 fn bound(&mut self, name: &str, start: &str) {
617 self.namespaces.insert(namespace_of(name).to_string());
618 self.starts.insert(start.to_string());
619 }
620}
621
622struct Ctx<'a> {
624 host: &'a str,
625 owned: &'a [String],
626 key_from: &'a str,
628 now: &'a str,
630 base: &'a Path,
632 job: bool,
634 blobs: &'a BTreeMap<String, Vec<u8>>,
636}
637
638enum Op {
640 Descriptor { hash: String, bytes: Vec<u8>, counted: bool },
642 Function { name: String, start: String, hash: String, bytes: Vec<u8>, bind: bool },
644 Class { name: String, start: String, hash: String, bytes: Vec<u8>, bind: bool, methods: Vec<(String, String)> },
647 Cell { tx: String, id: String, receipt: Vec<u8>, blob: Option<Vec<u8>>, version: bool },
649 Close { name: String, at: String },
651 Catalog {
653 entry: datumesh_store::CatalogEntry,
654 dictionaries: Vec<(String, Vec<datumesh_store::KeyValue>)>,
655 open_keys: Vec<String>,
656 extends: Option<String>,
657 facets: datumesh_store::Facets,
658 source_name: Option<String>,
660 },
661}
662
663fn read_lines(path: &Path) -> Result<Vec<(usize, String)>, PublishError> {
665 let file = std::fs::File::open(path).map_err(|e| PublishError::at(0, format!("{}: {e}", path.display())))?;
666 let mut out = Vec::new();
667 for (i, line) in std::io::BufReader::new(file).lines().enumerate() {
668 let n = i + 1;
669 let line = line.map_err(|e| PublishError::at(n, e.to_string()))?;
670 if !line.trim().is_empty() {
671 out.push((n, line));
672 }
673 }
674 Ok(out)
675}
676
677fn index_cell_values<S: Store + ?Sized>(store: &S, ops: &[Op]) -> Result<(), String> {
681 let mut seen = BTreeSet::new();
682 for op in ops {
683 if let Op::Cell { receipt, .. } = op {
684 if let Ok(r) = datumesh_core::Receipt::from_json(receipt) {
685 cell_string_values(&r, &mut seen);
686 }
687 }
688 }
689 store_cell_values(store, seen)
690}
691
692pub(crate) fn cell_string_values(r: &datumesh_core::Receipt, out: &mut BTreeSet<(String, String, String)>) {
694 let cell = r.cell();
695 for (key, arg) in &cell.args {
696 if let datumesh_core::Arg::Value(datumesh_core::Scalar::String(v)) = arg {
697 if !v.is_empty() && v.len() <= 1024 {
698 out.insert((cell.function_name(), key.clone(), v.clone()));
699 }
700 }
701 }
702}
703
704pub(crate) fn dictionary_limit() -> u64 {
708 std::env::var("DATUMESH_DICTIONARY_MAX")
709 .ok()
710 .and_then(|v| v.trim().parse::<u64>().ok())
711 .filter(|n| *n >= 1)
712 .unwrap_or(1000)
713}
714
715pub(crate) fn store_cell_values<S: Store + ?Sized>(
720 store: &S,
721 seen: BTreeSet<(String, String, String)>,
722) -> Result<(), String> {
723 let mut groups: BTreeMap<(String, String), Vec<String>> = BTreeMap::new();
724 for (owner, key, value) in seen {
725 groups.entry((owner, key)).or_default().push(value);
726 }
727 let limit = dictionary_limit();
728 for ((owner, key), values) in groups {
729 if store.key_is_open(&owner, &key).map_err(|e| e.to_string())? {
730 continue;
731 }
732 let fresh: Vec<String> =
733 values.into_iter().filter(|v| !crate::find::has_value(store, &owner, &key, v)).collect();
734 if fresh.is_empty() {
735 continue;
736 }
737 let have = store.key_value_count(&owner, &key).map_err(|e| e.to_string())?;
738 if have + fresh.len() as u64 > limit {
739 store.mark_key_open(&owner, &key).map_err(|e| e.to_string())?;
740 continue;
741 }
742 let kvs: Vec<datumesh_store::KeyValue> = fresh
743 .into_iter()
744 .map(|value| datumesh_store::KeyValue { value, label: String::new(), aliases: Vec::new() })
745 .collect();
746 store.upsert_key_values(&owner, &key, &kvs).map_err(|e| e.to_string())?;
747 }
748 Ok(())
749}
750
751fn row_name(own: Option<usize>, spec: &TestSpec, group: &str) -> String {
754 match own {
755 Some(_) => spec.function.clone(),
756 None => group.to_string(),
757 }
758}
759
760fn is_cell_line(v: &Value) -> bool {
762 v.get("class").and_then(Value::as_str).is_none()
763 && v.get("descriptor").is_none()
764 && v.get("function").and_then(Value::as_str).is_none()
765 && v.get("formula").and_then(Value::as_str).is_none()
766 && v.get("cell").is_some()
767}
768
769struct Pending {
771 line: usize,
772 ns: String,
773 cell: Cell,
774 value: Option<Scalar>,
776 withdrawn: Option<String>,
778 valid: Args,
779 tx: String,
780 asof: String,
781 issued: String,
782 has_tx: bool,
783 licence: String,
784 summary: String,
785 blob: Option<Vec<u8>>,
786 source: Option<Source>,
788}
789
790fn source_of_line(v: &Value) -> Result<Source, String> {
794 let Value::Object(m) = v else { return Err("source is an object".into()) };
795 for (k, x) in m {
796 if !matches!(k.as_str(), "name" | "url" | "retrieved" | "sha256" | "takeover") {
797 return Err(format!("source has no member {k}"));
798 }
799 if !matches!(x, Value::String(_)) {
800 return Err(format!("source.{k} is a string"));
801 }
802 }
803 let text = |k: &str| -> Result<&str, String> {
804 v.get(k).and_then(Value::as_str).ok_or_else(|| format!("source has no {k}"))
805 };
806 let mut out = Source::new(text("name")?, text("url")?, text("retrieved")?);
807 if let Some(h) = v.get("sha256").and_then(Value::as_str) {
808 out = out.with_sha256(h);
809 }
810 if let Some(t) = v.get("takeover").and_then(Value::as_str) {
811 out = out.with_takeover(t);
812 }
813 Ok(out)
814}
815
816impl Pending {
817 fn sign(self, key: &SigningKey, host: &str) -> Result<Signed, PublishError> {
819 let line = self.line;
820 let err = move |d: String| PublishError::at(line, d);
821 let b = ReceiptBuilder::new()
822 .cell(self.cell.clone())
823 .valid(self.valid)
824 .asof(self.asof.as_str())
825 .tx(self.tx.as_str())
826 .issued(self.issued.as_str())
827 .publisher(self.ns.as_str())
828 .signer_host(host)
829 .licence(self.licence.as_str())
830 .summary(self.summary.as_str());
831 let b = match self.source {
832 Some(s) => b.source(s),
833 None => b,
834 };
835 if let Some(reason) = &self.withdrawn {
836 let w = b.withdrawn(reason).sign_withdrawal(key).map_err(|e| err(e.to_string()))?;
838 let id = self.cell.id();
839 return Ok(Signed {
840 line,
841 has_tx: self.has_tx,
842 tx: self.tx,
843 id,
844 hash: w.hash().to_string(),
845 receipt: w.canonical().to_vec(),
846 blob: None,
847 });
848 }
849 let Some(value) = self.value else { return Err(err("a cell without value".into())) };
850 let r = b.value(value).sign(key).map_err(|e| err(e.to_string()))?;
851 let receipt = receipt_json(&r);
852 let hash = Receipt::from_json(&receipt).map_err(|e| err(e.to_string()))?.hash().to_string();
853 let id = self.cell.id();
854 Ok(Signed { line, has_tx: self.has_tx, tx: self.tx, id, hash, receipt, blob: self.blob })
855 }
856}
857
858struct Signed {
860 line: usize,
861 has_tx: bool,
862 tx: String,
863 id: String,
864 hash: String,
865 receipt: Vec<u8>,
866 blob: Option<Vec<u8>>,
867}
868
869struct Planner<'a, S: Store + ?Sized> {
871 store: &'a S,
872 key: &'a SigningKey,
873 ctx: Ctx<'a>,
874 backfill: bool,
875 sim: Simulation,
876 reads: Reads,
877 ops: Vec<Op>,
878 binds: Vec<Bind>,
879 tests: Vec<(usize, TestSpec)>,
881 formulas: Vec<(usize, String, String)>,
883}
884
885impl<S: Store + ?Sized> Planner<'_, S> {
886 fn callers(&self) -> Callers<'_, S> {
887 Callers { store: self.store, sim: Some(&self.sim) }
888 }
889
890 fn run(&mut self, lines: &[(usize, String)]) -> Result<(), PublishError> {
893 let mut cells: Vec<(usize, Value)> = Vec::new();
894 for (n, text) in lines {
895 let n = *n;
896 match json::parse(text.as_bytes()).map_err(|e| PublishError::at(n, e.to_string())) {
897 Ok(v) if is_cell_line(&v) => {
898 if let Some(name) = v.get("cell").and_then(|c| c.get("fn")).and_then(Value::as_str) {
900 crate::reserved::check_for(self.ctx.host, name, None, self.ctx.job)
901 .map_err(|e| PublishError::at(n, e))?;
902 }
903 cells.push((n, v));
904 if cells.len() == CHUNK {
905 self.plan_cells(std::mem::take(&mut cells))?;
906 }
907 }
908 other => {
909 self.plan_cells(std::mem::take(&mut cells))?;
912 self.plan_line(n, &other?)?;
913 }
914 }
915 }
916 self.plan_cells(cells)
917 }
918
919 fn plan_line(&mut self, n: usize, v: &Value) -> Result<(), PublishError> {
921 let err = |d: String| PublishError::at(n, d);
922 let named =
925 v.get("class").or_else(|| v.get("function")).or_else(|| v.get("formula")).or_else(|| v.get("catalog"));
926 if let Some(name) = named.and_then(Value::as_str) {
927 crate::reserved::check_for(self.ctx.host, name, None, self.ctx.job).map_err(err)?;
928 }
929 if let Some(name) = v.get("class").and_then(Value::as_str) {
930 self.class_line(n, name, v)?;
931 } else if let Some(d) = v.get("descriptor") {
932 self.descriptor_line(n, d)?;
933 } else if let Some(name) = v.get("function").and_then(Value::as_str) {
934 let sig = v.get("signature").ok_or_else(|| err("a function without a signature".into()))?;
935 let start = bound_of(v, n, self.ctx.now)?;
936 let fd = FunctionDescriptor::from_value(&stored_value(sig)).map_err(|e| err(e.to_string()))?;
937 self.function(n, name, start, fd.hash(), fd.canonical())?;
938 } else if let Some(name) = v.get("close").and_then(Value::as_str) {
939 if v.as_object().is_some_and(|m| m.len() != 1) {
940 return Err(err(
941 "a close line takes only close: the name's binding ends at the clock of the write".into()
942 ));
943 }
944 self.close_line(n, name)?;
945 } else if v.get("catalog").is_some() {
946 self.catalog_line(n, v)?;
947 } else if let Some(name) = v.get("formula").and_then(Value::as_str) {
948 let source =
949 v.get("source").and_then(Value::as_str).ok_or_else(|| err("a formula without source".into()))?;
950 let sig = v.get("signature").ok_or_else(|| err("a formula without a signature".into()))?;
951 let start = bound_of(v, n, self.ctx.now)?;
952 let def = datumesh_formula::definition::define_function(
953 name,
954 source,
955 sig,
956 &Default::default(),
957 &self.callers(),
958 &start,
959 )
960 .map_err(|e| err(format!("define {name}: {e}")))?;
961 let hash = def.fn_hash.clone();
962 self.function(n, name, start, def.fn_hash, def.bytes)?;
963 self.formulas.push((n, name.to_string(), hash));
964 } else if v.get("test").is_some() {
965 let spec = testrun::parse_test(v).map_err(err)?;
966 self.tests.push((n, spec));
967 } else {
968 return Err(err("neither a function nor a cell".into()));
969 }
970 Ok(())
971 }
972
973 fn close_line(&mut self, n: usize, name: &str) -> Result<(), PublishError> {
977 let err = |d: String| PublishError::at(n, d);
978 let class = current_class(self.store, &self.sim, name).map_err(err)?.is_some();
979 let bound = class || current_function(self.store, &self.sim, name).map_err(err)?.is_some();
980 if !bound {
981 return Err(err(format!("E_NAME_UNBOUND: {name} is not bound, so it cannot be closed")));
982 }
983 if let Some(tx) = latest_bind(self.store, &self.sim, name, class).map_err(err)? {
984 if self.ctx.now <= tx.as_str() {
985 return Err(err(format!(
986 "E_TIME_ORDER: the close of {name} at {} is not later than its binding at {tx}",
987 self.ctx.now
988 )));
989 }
990 }
991 self.ops.push(Op::Close { name: name.to_string(), at: self.ctx.now.to_string() });
992 Ok(())
993 }
994
995 fn catalog_line(&mut self, n: usize, v: &Value) -> Result<(), PublishError> {
999 let err = |d: String| PublishError::at(n, d);
1000 let d = crate::catalog::parse(v, "catalog").map_err(err)?;
1001 let host = host_of(&d.name);
1002 if host != self.ctx.host && !self.ctx.owned.iter().any(|o| o == host) {
1003 return Err(err(format!("{} is not under a host this mesh owns", d.name)));
1004 }
1005 let hash = match d.kind {
1006 datumesh_store::CatalogKind::Class => current_class(self.store, &self.sim, &d.name).map_err(err)?,
1007 _ => current_function(self.store, &self.sim, &d.name).map_err(err)?,
1008 };
1009 if hash.is_none() {
1010 return Err(err(format!("{} is bound nowhere", d.name)));
1011 }
1012 if let (Some(class), Some(fh)) = (&d.extends, &hash) {
1013 self.check_extension(class, fh).map_err(err)?;
1014 }
1015 let entry = d.entry(hash, datumesh_store::CatalogSource::Publisher, Some(self.key.key_id().to_string()));
1016 self.ops.push(Op::Catalog {
1017 entry,
1018 dictionaries: d.dictionary,
1019 open_keys: d.open_keys,
1020 extends: d.extends,
1021 facets: d.facets,
1022 source_name: d.source_name,
1023 });
1024 Ok(())
1025 }
1026
1027 fn descriptor_line(&mut self, n: usize, d: &Value) -> Result<(), PublishError> {
1029 let fd = FunctionDescriptor::from_value(d).map_err(|e| PublishError::at(n, e.to_string()))?;
1030 if fd.lang != "stored" || !fd.body.is_empty() || !fd.inputs.is_empty() {
1031 return Err(PublishError::at(
1032 n,
1033 "a descriptor line takes a stored function only: code.lang stored, code.body empty, no inputs",
1034 ));
1035 }
1036 let (hash, bytes) = (fd.hash(), fd.canonical());
1037 self.sim.descriptors.insert(hash.clone(), bytes.clone());
1038 self.ops.push(Op::Descriptor { hash, bytes, counted: true });
1039 Ok(())
1040 }
1041
1042 fn function(
1044 &mut self,
1045 n: usize,
1046 name: &str,
1047 start: String,
1048 hash: String,
1049 bytes: Vec<u8>,
1050 ) -> Result<(), PublishError> {
1051 self.sim.descriptors.insert(hash.clone(), bytes.clone());
1052 let current = current_function(self.store, &self.sim, name).map_err(|e| PublishError::at(n, e))?;
1053 let bind = current.as_deref() != Some(hash.as_str());
1054 if bind {
1055 self.check_bind(n, name, &start, false)?;
1056 self.sim.functions.entry(name.to_string()).or_default().push((start.clone(), hash.clone()));
1057 }
1058 self.ops.push(Op::Function { name: name.to_string(), start, hash, bytes, bind });
1059 Ok(())
1060 }
1061
1062 fn inline_methods(
1069 &mut self,
1070 n: usize,
1071 class: &str,
1072 descriptor: &Value,
1073 start: &str,
1074 ) -> Result<Value, PublishError> {
1075 let err = |d: String| PublishError::at(n, d);
1076 let Some(Value::Object(written)) = descriptor.get("methods") else { return Ok(descriptor.clone()) };
1077 if !written.iter().any(|(_, v)| matches!(v, Value::Object(_))) {
1078 return Ok(descriptor.clone());
1079 }
1080 let mut hashes: BTreeMap<String, String> = BTreeMap::new();
1081 let mut sigs: Vec<(String, Value)> = Vec::new();
1082 let mut formulas: Vec<(String, String, Value)> = Vec::new();
1083 let mut stored: Vec<(String, String, Vec<u8>)> = Vec::new();
1084 for (m, v) in written {
1085 let fq = format!("{class}/{m}");
1086 match v {
1087 Value::String(h) => {
1088 let bytes = function_bytes_of(&mut self.reads, self.store, &self.sim, h)
1089 .map_err(err)?
1090 .ok_or_else(|| err(format!("{fq}: no descriptor {h}")))?;
1091 let d = json::parse(&bytes).map_err(|e| err(e.to_string()))?;
1092 sigs.push((m.clone(), d.get("signature").cloned().unwrap_or(Value::Null)));
1093 hashes.insert(m.clone(), h.clone());
1094 }
1095 Value::Object(o) => {
1096 let get = |k: &str| o.iter().find(|(x, _)| x == k).map(|(_, y)| y);
1097 match (get("stored"), get("formula"), get("signature")) {
1098 (Some(sig), None, None) => {
1099 let fd = FunctionDescriptor::from_value(&stored_value(sig)).map_err(|e| err(format!("{fq}: {e}")))?;
1100 hashes.insert(m.clone(), fd.hash());
1101 sigs.push((m.clone(), sig.clone()));
1102 stored.push((fq, fd.hash(), fd.canonical()));
1103 }
1104 (None, Some(Value::String(src)), Some(sig)) => {
1105 sigs.push((m.clone(), sig.clone()));
1106 formulas.push((m.clone(), src.clone(), sig.clone()));
1107 }
1108 _ => {
1109 return Err(err(format!(
1110 "{fq}: a method is a function hash, {{\"stored\": <signature>}} or {{\"formula\": <source>, \"signature\": <signature>}}"
1111 )))
1112 }
1113 }
1114 }
1115 _ => return Err(err(format!("{fq}: a method is a function hash or an inline definition"))),
1116 }
1117 }
1118 for (fq, hash, bytes) in stored {
1119 self.sim.descriptors.insert(hash.clone(), bytes.clone());
1120 self.ops.push(Op::Function { name: fq, start: start.to_string(), hash, bytes, bind: false });
1121 }
1122 let mut keys: Vec<(String, Value)> = Vec::new();
1124 let mut order: Vec<Value> = Vec::new();
1125 if let Some(p) = descriptor.get("parent").and_then(Value::as_str) {
1126 let bytes = self
1127 .callers()
1128 .class_bytes(p)
1129 .map_err(err)?
1130 .ok_or_else(|| err(format!("{class}: the parent {p} is not stored")))?;
1131 let pv = json::parse(&bytes).map_err(|e| err(e.to_string()))?;
1132 if let Some(Value::Object(ks)) = pv.get("keys") {
1133 keys.extend(ks.iter().cloned());
1134 }
1135 if let Some(Value::Array(os)) = pv.get("order") {
1136 order.extend(os.iter().cloned());
1137 }
1138 }
1139 if let Some(Value::Object(ks)) = descriptor.get("keys") {
1140 for (k, v) in ks {
1141 if !keys.iter().any(|(x, _)| x == k) {
1142 keys.push((k.clone(), v.clone()));
1143 }
1144 }
1145 }
1146 if let Some(Value::Array(os)) = descriptor.get("order") {
1147 for o in os {
1148 if !order.iter().any(|x| x.as_str() == o.as_str()) {
1149 order.push(o.clone());
1150 }
1151 }
1152 }
1153 let mut draft_members = vec![
1154 ("keys".to_string(), Value::Object(keys)),
1155 ("order".to_string(), Value::Array(order)),
1156 ("methods".to_string(), Value::Object(sigs)),
1157 ];
1158 if let Some(p) = descriptor.get("parent") {
1159 draft_members.push(("parent".to_string(), p.clone()));
1160 }
1161 let draft = datumesh_formula::definition::ClassDraft::from_value(&Value::Object(draft_members))
1162 .map_err(|e| err(format!("{class}: {e}")))?;
1163 let defined = {
1164 let callers = self.callers();
1165 let mut defined = Vec::with_capacity(formulas.len());
1166 for (m, src, sig) in &formulas {
1167 let fq = format!("{class}/{m}");
1168 let def =
1169 datumesh_formula::definition::define_method_in_draft(class, &draft, &fq, src, sig, &callers, start)
1170 .map_err(|e| err(format!("define {fq}: {e}")))?;
1171 defined.push((m.clone(), def));
1172 }
1173 defined
1174 };
1175 let names: BTreeSet<String> = defined.iter().map(|(m, _)| m.clone()).collect();
1177 let reads: BTreeMap<String, BTreeSet<String>> = defined
1178 .iter()
1179 .map(|(m, d)| {
1180 let prefix = format!("{class}/");
1181 let rs = d
1182 .callees
1183 .keys()
1184 .filter_map(|c| c.strip_prefix(prefix.as_str()))
1185 .filter(|x| names.contains(*x))
1186 .map(str::to_string)
1187 .collect();
1188 (m.clone(), rs)
1189 })
1190 .collect();
1191 let mut done: BTreeSet<String> = BTreeSet::new();
1192 let mut order: Vec<String> = Vec::new();
1193 while order.len() < defined.len() {
1194 let next = defined
1195 .iter()
1196 .map(|(m, _)| m)
1197 .find(|m| !done.contains(*m) && reads.get(*m).is_none_or(|rs| rs.iter().all(|r| done.contains(r))));
1198 match next {
1199 Some(m) => {
1200 done.insert(m.clone());
1201 order.push(m.clone());
1202 }
1203 None => {
1204 let left: Vec<&str> =
1205 defined.iter().map(|(m, _)| m.as_str()).filter(|m| !done.contains(*m)).collect();
1206 return Err(err(format!(
1207 "{class}: methods read each other with this ({}): refused (16.3)",
1208 left.join(", ")
1209 )));
1210 }
1211 }
1212 }
1213 let mut defined: BTreeMap<String, datumesh_formula::definition::Definition> = defined.into_iter().collect();
1214 for m in order {
1215 let def = defined.remove(&m).ok_or_else(|| err(format!("{class}/{m}: not defined")))?;
1216 let fq = format!("{class}/{m}");
1217 self.sim.descriptors.insert(def.fn_hash.clone(), def.bytes.clone());
1218 self.ops.push(Op::Function {
1219 name: fq.clone(),
1220 start: start.to_string(),
1221 hash: def.fn_hash.clone(),
1222 bytes: def.bytes.clone(),
1223 bind: false,
1224 });
1225 self.formulas.push((n, fq, def.fn_hash.clone()));
1226 hashes.insert(m, def.fn_hash);
1227 }
1228 let methods: Vec<(String, Value)> = written
1229 .iter()
1230 .map(|(m, _)| (m.clone(), Value::String(hashes.get(m).cloned().unwrap_or_default())))
1231 .collect();
1232 let mut out = descriptor.clone();
1233 if let Value::Object(members) = &mut out {
1234 for (k, v) in members.iter_mut() {
1235 if k == "methods" {
1236 *v = Value::Object(methods.clone());
1237 }
1238 }
1239 }
1240 Ok(out)
1241 }
1242
1243 fn check_extension(&mut self, class: &str, fn_hash: &str) -> Result<(), String> {
1246 let chash = current_class(self.store, &self.sim, class)?
1247 .ok_or_else(|| format!("extends {class}: no class of that name is bound on this mesh"))?;
1248 let cbytes = match self.sim.class_bytes.get(&chash) {
1249 Some(b) => b.clone(),
1250 None => self
1251 .store
1252 .class(&chash)
1253 .map_err(|e| e.to_string())?
1254 .ok_or_else(|| format!("class {chash} is not stored"))?,
1255 };
1256 let cd = ClassDescriptor::from_json(&cbytes).map_err(|e| e.to_string())?;
1257 let fbytes = function_bytes_of(&mut self.reads, self.store, &self.sim, fn_hash)?
1258 .ok_or_else(|| format!("no descriptor {fn_hash}"))?;
1259 let fd = FunctionDescriptor::from_json(&fbytes).map_err(|e| e.to_string())?;
1260 let order = fd.order.clone().unwrap_or_default();
1261 let keys_match = order.len() >= cd.order.len()
1262 && order[..cd.order.len()] == cd.order[..]
1263 && cd.order.iter().all(|k| key_matches(&cd, &fd, k));
1264 if !keys_match {
1265 return Err(format!(
1266 "extends {class}: the function does not take the keys of {class} first, with their types"
1267 ));
1268 }
1269 Ok(())
1270 }
1271
1272 fn class_line(&mut self, n: usize, name: &str, v: &Value) -> Result<(), PublishError> {
1273 let err = |d: String| PublishError::at(n, d);
1274 let written = v.get("descriptor").ok_or_else(|| err("a class without descriptor".into()))?;
1275 let start = bound_of(v, n, self.ctx.now)?;
1276 let descriptor = &self.inline_methods(n, name, written, &start)?;
1277 let def = datumesh_formula::definition::define_class(
1278 name,
1279 &descriptor.to_jcs(),
1280 definer(name, self.ctx.host, self.ctx.owned),
1281 &self.callers(),
1282 &start,
1283 )
1284 .map_err(|e| err(format!("define {name}: {e}")))?;
1285 suspended(&mut self.reads, self.store, host_of(&def.descriptor.steward.namespace), n)?;
1289 let hash = def.class_hash.clone();
1290 let methods: Vec<(String, String)> =
1291 def.descriptor.methods.iter().map(|(m, fh)| (format!("{name}/{m}"), fh.clone())).collect();
1292 let bind = current_class(self.store, &self.sim, name).map_err(err)?.as_deref() != Some(hash.as_str());
1293 if bind {
1294 self.check_bind(n, name, &start, true)?;
1295 for (mname, _) in &methods {
1297 self.check_bind(n, mname, &start, false)?;
1298 }
1299 self.sim.classes.entry(name.to_string()).or_default().push((start.clone(), hash.clone()));
1300 for (mname, fh) in &methods {
1301 self.sim.functions.entry(mname.clone()).or_default().push((start.clone(), fh.clone()));
1302 }
1303 }
1304 self.sim.class_bytes.insert(hash.clone(), def.bytes.clone());
1305 self.ops.push(Op::Class { name: name.to_string(), start, hash, bytes: def.bytes, bind, methods });
1306 Ok(())
1307 }
1308
1309 fn check_bind(&mut self, line: usize, name: &str, start: &str, class: bool) -> Result<(), PublishError> {
1311 if !self.backfill && start < self.ctx.now {
1312 return Err(PublishError::typed(
1313 line,
1314 PublishErrorKind::StartBeforeNow { name: name.into(), start: start.into(), now: self.ctx.now.into() },
1315 ));
1316 }
1317 let err = |d: String| PublishError::at(line, d);
1318 if bound_as_other(self.store, &self.sim, name, class).map_err(err)? {
1319 let kind = if class { "function" } else { "class" };
1320 return Err(err(format!("{name} is bound as a {kind}: one namespace of names")));
1321 }
1322 suspended(&mut self.reads, self.store, host_of(name), line)?;
1323 if let Some(latest) = latest_bind(self.store, &self.sim, name, class).map_err(err)? {
1324 if start <= latest.as_str() {
1325 return Err(err(format!("{name} is bound from {latest}: a bind at {start} is not later")));
1326 }
1327 }
1328 self.binds.push(Bind { line, name: name.into() });
1329 Ok(())
1330 }
1331
1332 fn plan_cells(&mut self, lines: Vec<(usize, Value)>) -> Result<(), PublishError> {
1337 if lines.is_empty() {
1338 return Ok(());
1339 }
1340 let mut pending = Vec::with_capacity(lines.len());
1341 let mut failed = None;
1342 for (n, v) in &lines {
1343 match self.prepare_cell(*n, v) {
1344 Ok(p) => pending.push(p),
1345 Err(e) => {
1346 failed = Some(e);
1347 break;
1348 }
1349 }
1350 }
1351 let (key, host) = (self.key, self.ctx.host);
1352 let signed = parallel_owned(pending, |p| p.sign(key, host));
1353 let ids: Vec<&str> = signed.iter().flatten().map(|s| s.id.as_str()).collect();
1354 self.reads.prefetch_latest(self.store, &ids);
1355 let hashes: Vec<String> = signed
1356 .iter()
1357 .flatten()
1358 .filter(|s| !s.has_tx)
1359 .filter_map(|s| self.reads.latest_of.get(&s.id).cloned().flatten())
1360 .map(|(_, h)| h)
1361 .collect();
1362 let hashes: Vec<&str> = hashes.iter().map(String::as_str).collect();
1363 self.reads.prefetch_receipts(self.store, &hashes);
1364 for s in signed {
1365 self.check_cell(s?)?;
1366 }
1367 match failed {
1368 Some(e) => Err(e),
1369 None => Ok(()),
1370 }
1371 }
1372
1373 fn prepare_cell(&mut self, n: usize, v: &Value) -> Result<Pending, PublishError> {
1376 let err = |d: String| PublishError::at(n, d);
1377 let cell_v = v.get("cell").ok_or_else(|| err("a cell without fn".into()))?;
1378 let name = cell_v.get("fn").and_then(Value::as_str).ok_or_else(|| err("a cell without fn".into()))?;
1379 let (ns, f) = name.rsplit_once('/').ok_or_else(|| err(format!("{name}: not a function name")))?;
1380 let field = |k: &str| v.get(k).and_then(Value::as_str).map(str::to_string);
1381 let required = |k: &str| field(k).ok_or_else(|| err(format!("no {k}")));
1382 let (licence, summary) = (required("licence")?, required("summary")?);
1383 let asof = field("asof").unwrap_or_else(|| self.ctx.now.to_string());
1385 let has_tx = field("tx").is_some();
1386 let tx = field("tx").unwrap_or_else(|| self.ctx.now.to_string());
1387 if tx > asof {
1388 return Err(err(format!("tx {tx} is after asof {asof} (SPEC 8)")));
1389 }
1390 let issued = field("issued").unwrap_or_else(|| std::cmp::max(asof.clone(), self.ctx.key_from.to_string()));
1391 if asof > issued {
1392 return Err(err(format!("asof {asof} is after issued {issued} (SPEC 8)")));
1393 }
1394 let fn_hash = function_at(&mut self.reads, self.store, &self.sim, name, &tx)
1395 .map_err(err)?
1396 .ok_or_else(|| err(format!("{name} is not bound as of {tx}")))?;
1397 let d = function_bytes_of(&mut self.reads, self.store, &self.sim, &fn_hash)
1398 .map_err(err)?
1399 .ok_or_else(|| err(format!("no descriptor {fn_hash}")))?;
1400 let d = FunctionDescriptor::from_json(&d).map_err(|e| err(e.to_string()))?;
1401 let mut args = Args::new();
1402 for (k, a) in cell_v.get("args").and_then(Value::as_object).ok_or_else(|| err("a cell without args".into()))? {
1403 args.insert(k.clone(), Arg::Value(Scalar::from_json(&a.to_jcs()).map_err(|e| err(format!("{k}: {e}")))?));
1404 }
1405 for (k, a) in &args {
1407 let rule = d.arg_extras.get(k).and_then(|x| x.key_normalisation);
1408 if let (true, Arg::Value(Scalar::String(text))) = (matches!(rule, Some(KeyNormalisation::LabelFold)), a) {
1409 if datumesh_core::fold_label(text) != *text {
1410 return Err(err(format!("E_KEY_NORMALISATION: {k}: {text:?} is not folded (label_fold)")));
1411 }
1412 }
1413 }
1414 let valid: Args = args
1415 .iter()
1416 .filter(|(k, _)| d.signature.args.get(*k).is_some_and(|x| x.valid))
1417 .map(|(k, a)| (k.clone(), a.clone()))
1418 .collect();
1419 let source = match v.get("source") {
1420 Some(sv) => Some(source_of_line(sv).map_err(err)?),
1421 None => None,
1422 };
1423 let withdrawn = match v.get("withdrawn") {
1425 None => None,
1426 Some(Value::String(reason)) => Some(reason.clone()),
1427 Some(_) => return Err(err("E_SCHEMA: withdrawn is a non-empty string: the reason".into())),
1428 };
1429 if withdrawn.is_some() && v.get("value").is_some() {
1430 return Err(err("E_SCHEMA: a cell line has withdrawn or value, not both".into()));
1431 }
1432 let (value, blob) = if withdrawn.is_some() {
1433 (None, None)
1434 } else {
1435 let value_v = v.get("value").ok_or_else(|| err("a cell without value".into()))?;
1436 let (scalar, blob) = match value_v.get("blob").and_then(Value::as_str) {
1437 Some(file) => {
1438 let media = value_v.get("media_type").and_then(Value::as_str).unwrap_or("application/octet-stream");
1439 let bytes = match self.ctx.blobs.get(file) {
1440 Some(b) => b.clone(),
1441 None => std::fs::read(self.ctx.base.join(file)).map_err(|e| err(format!("{file}: {e}")))?,
1442 };
1443 let sha = sha256_hex(&bytes);
1444 let scalar = Scalar::from_lexical(Type::Blob, &format!("{sha}:{}:{media}", bytes.len()))
1445 .map_err(|e| err(e.to_string()))?;
1446 (scalar, Some(bytes))
1447 }
1448 None => (Scalar::from_json(&value_v.to_jcs()).map_err(|e| err(e.to_string()))?, None),
1449 };
1450 if let Scalar::String(text) = &scalar {
1452 if text.is_empty() && lookup_method(self.store, &self.sim, name).map_err(err)? {
1453 return Err(err(format!(
1454 "E_KEY_NORMALISATION: {name} is a lookup, and its value is not the empty string"
1455 )));
1456 }
1457 }
1458 (Some(scalar), blob)
1459 };
1460 let cell = Cell { ns: ns.to_string(), fn_name: f.to_string(), fn_hash, args };
1461 Ok(Pending {
1462 line: n,
1463 ns: ns.to_string(),
1464 cell,
1465 value,
1466 withdrawn,
1467 valid,
1468 tx,
1469 asof,
1470 issued,
1471 has_tx,
1472 licence,
1473 summary,
1474 blob,
1475 source,
1476 })
1477 }
1478
1479 fn check_cell(&mut self, s: Signed) -> Result<(), PublishError> {
1482 let line = s.line;
1483 let err = |d: String| PublishError::at(line, d);
1484 if !s.has_tx {
1489 if let Some((_, latest)) = cell_latest(&mut self.reads, self.store, &self.sim, &s.id).map_err(err)? {
1490 if let Some(old) = self.reads.receipt(self.store, &latest) {
1491 let old = json::parse(&old).map_err(|e| err(e.to_string()))?;
1492 let new = json::parse(&s.receipt).map_err(|e| err(e.to_string()))?;
1493 if ["type", "value", "withdrawn", "valid", "licence", "summary"]
1494 .iter()
1495 .all(|k| old.get(k) == new.get(k))
1496 {
1497 return Ok(());
1498 }
1499 }
1500 }
1501 }
1502 let version = match cell_latest(&mut self.reads, self.store, &self.sim, &s.id).map_err(err)? {
1503 Some((latest_tx, _)) if latest_tx.as_str() >= s.tx.as_str() => {
1504 if cell_version_asof(self.store, &self.sim, &s.id, &s.tx).map_err(err)?.as_deref()
1505 != Some(s.hash.as_str())
1506 {
1507 return Err(err(format!("{} has a version at or after {} that is not this receipt", s.id, s.tx)));
1508 }
1509 false
1510 }
1511 _ => {
1512 self.sim.versions.entry(s.id.clone()).or_default().push((s.tx.clone(), s.hash.clone()));
1513 true
1514 }
1515 };
1516 self.ops.push(Op::Cell { tx: s.tx, id: s.id, receipt: s.receipt, blob: s.blob, version });
1517 Ok(())
1518 }
1519}
1520
1521fn lookup_method<S: Store + ?Sized>(store: &S, sim: &Simulation, name: &str) -> Result<bool, String> {
1523 let Some((class, method)) = name.rsplit_once('/') else { return Ok(false) };
1524 let Some(hash) = current_class(store, sim, class)? else { return Ok(false) };
1525 let Some(bytes) = store.class(&hash).map_err(|e| e.to_string())? else { return Ok(false) };
1526 let cd = ClassDescriptor::from_json(&bytes).map_err(|e| e.to_string())?;
1527 Ok(cd.lookup.as_deref() == Some(method))
1528}
1529
1530fn stored_value(signature: &Value) -> Value {
1532 Value::Object(vec![
1533 ("code".into(), Value::Object(vec![("body".into(), s("")), ("lang".into(), s("stored"))])),
1534 ("inputs".into(), Value::Array(vec![])),
1535 ("signature".into(), signature.clone()),
1536 ])
1537}
1538
1539fn backfill_check<S: Store + ?Sized>(store: &S, binds: &[Bind]) -> Result<(), PublishError> {
1542 for b in binds {
1543 let refuse = |why: String| PublishError::typed(b.line, PublishErrorKind::Backfill(why));
1544 if store.resolve_binding(&b.name, END).map_err(|e| PublishError::at(b.line, e.to_string()))?.is_some() {
1545 return Err(refuse(format!("{} has a binding", b.name)));
1546 }
1547 let ns = namespace_of(&b.name);
1548 if store.has_bindings_under(ns).map_err(|e| PublishError::at(b.line, e.to_string()))? {
1549 return Err(refuse(format!("{ns} has bindings")));
1550 }
1551 }
1552 Ok(())
1553}
1554
1555fn append_log(log: &Path, written: &Written) -> Result<(), String> {
1557 let line = Value::Object(vec![
1558 ("at".into(), s(&SystemClock.now())),
1559 ("namespaces".into(), Value::Array(written.namespaces.iter().map(|n| s(n)).collect())),
1560 ("starts".into(), Value::Array(written.starts.iter().map(|t| s(t)).collect())),
1561 ])
1562 .to_jcs();
1563 let mut opts = std::fs::OpenOptions::new();
1564 opts.create(true).append(true);
1565 #[cfg(unix)]
1566 {
1567 use std::os::unix::fs::OpenOptionsExt;
1568 opts.mode(0o600);
1569 }
1570 let mut f = opts.open(log).map_err(|e| format!("{}: {e}", log.display()))?;
1571 let mut bytes = line;
1572 bytes.push(b'\n');
1573 f.write_all(&bytes).map_err(|e| format!("{}: {e}", log.display()))
1574}
1575
1576fn write<S: Store + ?Sized>(
1580 store: &S,
1581 ops: &[Op],
1582 cells: impl Fn(&S, &[Op], &mut Published) -> Result<(), String>,
1583) -> Result<(Published, Written), PublishError> {
1584 let mut out = Published::default();
1585 let mut written = Written::default();
1586 let err = |d: String| PublishError::at(0, d);
1587 let mut i = 0;
1588 while i < ops.len() {
1589 match &ops[i] {
1590 Op::Descriptor { hash, bytes, counted } => {
1591 let existed = store.descriptor(hash).is_some();
1592 store.put_descriptor(bytes).map_err(|e| err(e.to_string()))?;
1593 if *counted && !existed {
1594 out.descriptors += 1;
1595 }
1596 }
1597 Op::Function { name, start, hash, bytes, bind } => {
1598 store.put_descriptor(bytes).map_err(|e| err(e.to_string()))?;
1599 if *bind {
1600 store.bind_name(name, hash, start).map_err(|e| err(format!("bind {name}: {e}")))?;
1601 out.functions += 1;
1602 written.bound(name, start);
1603 }
1604 }
1605 Op::Class { name, start, hash, bytes, bind, methods } => {
1606 store.put_class(bytes).map_err(|e| err(e.to_string()))?;
1607 if *bind {
1608 store.bind_class(name, hash, start).map_err(|e| err(format!("bind {name}: {e}")))?;
1609 out.classes += 1;
1610 written.bound(name, start);
1611 for (m, _) in methods {
1612 written.bound(m, start);
1613 }
1614 }
1615 }
1616 Op::Close { name, at } => {
1617 store.close_binding(name, at).map_err(|e| err(format!("close {name}: {e}")))?;
1618 }
1619 Op::Catalog { entry, dictionaries, open_keys, extends, facets, source_name } => {
1620 crate::catalog::store_publisher(
1621 store,
1622 entry,
1623 dictionaries,
1624 open_keys,
1625 extends.as_deref(),
1626 facets,
1627 source_name.as_deref(),
1628 )
1629 .map_err(err)?;
1630 }
1631 Op::Cell { .. } => {
1632 let mut j = i;
1633 while j < ops.len() && j - i < CHUNK && matches!(ops[j], Op::Cell { .. }) {
1634 j += 1;
1635 }
1636 cells(store, &ops[i..j], &mut out).map_err(err)?;
1637 i = j;
1638 continue;
1639 }
1640 }
1641 i += 1;
1642 }
1643 Ok((out, written))
1644}
1645
1646fn write_cells_one_lane<S: Store + ?Sized>(store: &S, group: &[Op], out: &mut Published) -> Result<(), String> {
1650 let items = put_blobs_and_items(store, group, out)?;
1651 let failed = AtomicBool::new(false);
1652 let ks: Vec<usize> = (0..items.len()).collect();
1653 if let Some((_, detail)) = put_lane(store, &items, &ks, &failed) {
1654 return Err(detail);
1655 }
1656 count_cells(group, &items, out);
1657 Ok(())
1658}
1659
1660fn write_cells<S: Store + Sync + ?Sized>(
1666 store: &S,
1667 group: &[Op],
1668 lanes: usize,
1669 out: &mut Published,
1670) -> Result<(), String> {
1671 if lanes <= 1 {
1672 return write_cells_one_lane(store, group, out);
1673 }
1674 let items = put_blobs_and_items(store, group, out)?;
1675 let mut by_lane: Vec<Vec<usize>> = vec![Vec::new(); lanes];
1676 for (k, op) in group.iter().enumerate() {
1677 if let Op::Cell { id, .. } = op {
1678 by_lane[lane_of(id, lanes)].push(k);
1679 }
1680 }
1681 let failed = AtomicBool::new(false);
1682 let failures: Vec<(usize, String)> = std::thread::scope(|scope| {
1683 let handles: Vec<_> = by_lane
1684 .iter()
1685 .map(|ks| {
1686 let (items, failed) = (&items, &failed);
1687 scope.spawn(move || put_lane(store, items, ks, failed))
1688 })
1689 .collect();
1690 handles.into_iter().filter_map(|h| h.join().unwrap_or_else(|p| std::panic::resume_unwind(p))).collect()
1691 });
1692 if let Some((_, detail)) = failures.into_iter().min_by_key(|(k, _)| *k) {
1693 return Err(detail);
1694 }
1695 count_cells(group, &items, out);
1696 Ok(())
1697}
1698
1699fn put_blobs_and_items<'a, S: Store + ?Sized>(
1701 store: &S,
1702 group: &'a [Op],
1703 out: &mut Published,
1704) -> Result<Vec<CellItem<'a>>, String> {
1705 for op in group {
1706 if let Op::Cell { blob: Some(bytes), .. } = op {
1707 store.put_blob(bytes).map_err(|e| e.to_string())?;
1708 out.blobs += 1;
1709 out.blob_bytes += bytes.len() as u64;
1710 }
1711 }
1712 Ok(group
1713 .iter()
1714 .filter_map(|op| match op {
1715 Op::Cell { tx, id, receipt, version, .. } => {
1716 Some((receipt.as_slice(), if *version { Some((id.as_str(), tx.as_str())) } else { None }))
1717 }
1718 _ => None,
1719 })
1720 .collect())
1721}
1722
1723fn count_cells(group: &[Op], items: &[CellItem<'_>], out: &mut Published) {
1725 out.cells += group.len();
1726 out.receipts += group.len();
1727 out.versions += items.iter().filter(|(_, v)| v.is_some()).count();
1728}
1729
1730fn lane_of(id: &str, lanes: usize) -> usize {
1732 id.bytes().next().and_then(|b| (b as char).to_digit(16)).unwrap_or(0) as usize % lanes
1733}
1734
1735type CellItem<'a> = (&'a [u8], Option<(&'a str, &'a str)>);
1737
1738fn put_lane<S: Store + ?Sized>(
1742 store: &S,
1743 items: &[CellItem<'_>],
1744 ks: &[usize],
1745 failed: &AtomicBool,
1746) -> Option<(usize, String)> {
1747 for call in ks.chunks(CHUNK) {
1748 if failed.load(Ordering::SeqCst) {
1749 return None;
1750 }
1751 let writes: Vec<CellWrite<'_>> = call.iter().map(|&k| CellWrite::new(items[k].0, items[k].1)).collect();
1752 if let Err(e) = store.put_cells(&writes) {
1753 failed.store(true, Ordering::SeqCst);
1754 return Some((call[0], e.to_string()));
1755 }
1756 }
1757 None
1758}
1759
1760pub fn receipt_json(r: &datumesh_core::Receipt) -> Vec<u8> {
1762 let mut members = vec![("sig".to_string(), Value::String(r.sig().to_string()))];
1763 if let Ok(Value::Object(m)) = json::parse(r.payload()) {
1764 members.extend(m);
1765 }
1766 Value::Object(members).to_jcs()
1767}
1768
1769pub fn publish_stored<S: Store + ?Sized>(
1774 store: &S,
1775 key: &SigningKey,
1776 host: &str,
1777 path: &Path,
1778) -> Result<Published, PublishError> {
1779 publish_stored_in(store, key, host, &[host.to_string()], path)
1780}
1781
1782pub fn publish_stored_in<S: Store + ?Sized>(
1786 store: &S,
1787 key: &SigningKey,
1788 host: &str,
1789 owned: &[String],
1790 path: &Path,
1791) -> Result<Published, PublishError> {
1792 publish_stored_with(store, key, host, owned, path, &PublishOptions::system())
1793}
1794
1795pub fn publish_stored_with<S: Store + ?Sized>(
1802 store: &S,
1803 key: &SigningKey,
1804 host: &str,
1805 owned: &[String],
1806 path: &Path,
1807 opts: &PublishOptions,
1808) -> Result<Published, PublishError> {
1809 publish_planned(store, key, host, owned, path, opts, false, |s, ops| {
1810 write(s, ops, |s, g, out| write_cells_one_lane(s, g, out))
1811 })
1812}
1813
1814pub fn publish_stored_checked<S: Store + ?Sized>(
1821 store: &S,
1822 key: &SigningKey,
1823 host: &str,
1824 owned: &[String],
1825 path: &Path,
1826 opts: &PublishOptions,
1827) -> Result<Published, PublishError> {
1828 publish_planned(store, key, host, owned, path, opts, true, |s, ops| {
1829 write(s, ops, |s, g, out| write_cells_one_lane(s, g, out))
1830 })
1831}
1832
1833pub fn publish_stored_lanes<S: Store + Sync + ?Sized>(
1838 store: &S,
1839 key: &SigningKey,
1840 host: &str,
1841 owned: &[String],
1842 path: &Path,
1843 opts: &PublishOptions,
1844) -> Result<Published, PublishError> {
1845 let lanes = publish_lanes()?;
1846 publish_planned(store, key, host, owned, path, opts, false, |s, ops| {
1847 write(s, ops, |s, g, out| write_cells(s, g, lanes, out))
1848 })
1849}
1850
1851fn overlay_of(ops: &[Op]) -> Result<Overlay, PublishError> {
1853 let mut overlay = Overlay::default();
1854 for op in ops {
1855 match op {
1856 Op::Function { name, start, hash, bytes, bind } => {
1857 overlay.descriptors.insert(hash.clone(), bytes.clone());
1858 if *bind {
1859 overlay.functions.entry(name.clone()).or_default().push((start.clone(), hash.clone()));
1860 }
1861 }
1862 Op::Descriptor { hash, bytes, .. } => {
1863 overlay.descriptors.insert(hash.clone(), bytes.clone());
1864 }
1865 Op::Cell { receipt, .. } => {
1866 overlay.cell(receipt).map_err(|e| PublishError::at(0, format!("tests: {e}")))?;
1867 }
1868 Op::Class { start, bind, methods, .. } => {
1869 if *bind {
1871 for (m, fh) in methods {
1872 overlay.functions.entry(m.clone()).or_default().push((start.clone(), fh.clone()));
1873 }
1874 }
1875 }
1876 Op::Catalog { .. } | Op::Close { .. } => {}
1877 }
1878 }
1879 Ok(overlay)
1880}
1881
1882#[allow(clippy::too_many_arguments)]
1890pub(crate) fn check_tests<S: Store + ?Sized>(
1891 store: &S,
1892 overlay: &Overlay,
1893 tests: &[(usize, TestSpec)],
1894 formulas: &[(usize, String, String)],
1895 host: &str,
1896 now: &str,
1897 checked: bool,
1898) -> Result<Vec<RowWrite>, PublishError> {
1899 let mut file_tests: Vec<(usize, TestSpec, String)> = Vec::new();
1900 for (n, spec) in tests {
1901 let at = spec.asof.clone().unwrap_or_else(|| now.to_string());
1902 match testrun::binding_of(store, overlay, &spec.function, &at) {
1903 Ok(Some((hash, _))) => file_tests.push((*n, spec.clone(), hash)),
1904 Ok(None) => {
1905 return Err(PublishError::at(
1906 *n,
1907 format!("a test of {}: no function of that name is bound", spec.function),
1908 ))
1909 }
1910 Err(e) => return Err(PublishError::at(*n, e)),
1911 }
1912 }
1913 let mut groups: Vec<(usize, String, String)> = formulas.to_vec();
1915 for (n, spec, hash) in &file_tests {
1916 if !groups.iter().any(|g| &g.2 == hash) {
1917 groups.push((*n, spec.function.clone(), hash.clone()));
1918 }
1919 }
1920 let mut rows = Vec::new();
1921 for (line, name, hash) in &groups {
1922 let own: Vec<(usize, TestSpec)> =
1923 file_tests.iter().filter(|t| &t.2 == hash).map(|t| (t.0, t.1.clone())).collect();
1924 let all_held = testrun::held_of_name(store, hash, name, now).map_err(|e| PublishError::at(*line, e))?;
1926 if !checked && own.is_empty() && all_held.is_empty() {
1927 continue;
1928 }
1929 let mut run = testrun::Run::new(store, overlay, now);
1930 let built = run.built(name, hash).map_err(|e| PublishError::at(*line, format!("{name}: {}", e.0)))?;
1931 if built.compiled.is_some() && !formulas.iter().any(|f| &f.2 == hash) {
1934 continue;
1935 }
1936 let written: BTreeSet<&str> = overlay.cells.iter().filter(|c| &c.name == name).map(|c| c.id.as_str()).collect();
1939 let held: Vec<(FunctionTest, TestSpec, String)> = all_held
1940 .into_iter()
1941 .filter(|(_, _, cell)| built.compiled.is_some() || written.contains(cell.as_str()))
1942 .collect();
1943 let mut specs: Vec<(Option<usize>, TestSpec)> = own.into_iter().map(|(n, s)| (Some(n), s)).collect();
1944 for (_, spec, _) in held {
1945 if !specs.iter().any(|(_, s)| s.case == spec.case) {
1946 specs.push((None, spec));
1947 }
1948 }
1949 let ran: Vec<Ran> = specs.iter().map(|(_, s)| run_test(store, overlay, now, s)).collect();
1950 let Some(compiled) = built.compiled.as_ref() else {
1951 for ((own_n, spec), r) in specs.iter().zip(&ran) {
1954 let (result, detail) = testrun::result_of(spec, r);
1955 rows.push(RowWrite {
1956 fn_hash: hash.clone(),
1957 case: spec.case.clone(),
1958 jcs: spec.jcs.clone(),
1959 signed_by: host.to_string(),
1960 result,
1961 detail,
1962 branches_total: 0,
1963 branches_covered: 0,
1964 fn_name: row_name(*own_n, spec, name),
1965 });
1966 }
1967 continue;
1968 };
1969 if checked {
1970 let mut failing: Vec<(usize, String)> = Vec::new();
1971 for ((n, spec), r) in specs.iter().zip(&ran) {
1972 if let Some(n) = n {
1973 let (result, detail) = testrun::result_of(spec, r);
1974 if result != "pass" {
1975 failing.push((*n, format!("{name}: test {} {detail}", spec.case)));
1976 }
1977 }
1978 }
1979 failing.sort_by_key(|f| f.0);
1980 if let Some((n, detail)) = failing.into_iter().next() {
1981 return Err(PublishError::typed(n, PublishErrorKind::TestsFailing(detail)));
1982 }
1983 let refs: Vec<&Ran> = ran.iter().collect();
1984 let cov = testrun::coverage_of(compiled, &built.function.signature, &refs);
1985 if !cov.uncovered.is_empty() || !cov.unexercised.is_empty() {
1986 let mut text = format!("{name} is missing tests:");
1987 if !cov.uncovered.is_empty() {
1988 let cases: Vec<&str> = cov.uncovered.iter().map(|c| c.0.as_str()).collect();
1989 text += &format!(" uncovered cases {};", cases.join(", "));
1990 }
1991 if !cov.unexercised.is_empty() {
1992 text += &format!(" unexercised branches {}", cov.unexercised.join(", "));
1993 }
1994 return Err(PublishError::typed(
1995 *line,
1996 PublishErrorKind::TestsMissing(text.trim_end_matches(';').to_string()),
1997 ));
1998 }
1999 }
2000 let refs: Vec<&Ran> = ran.iter().collect();
2001 let cov = testrun::coverage_of(compiled, &built.function.signature, &refs);
2002 for ((own_n, spec), r) in specs.iter().zip(&ran) {
2003 let (result, detail) = testrun::result_of(spec, r);
2004 rows.push(RowWrite {
2005 fn_hash: hash.clone(),
2006 case: spec.case.clone(),
2007 jcs: spec.jcs.clone(),
2008 signed_by: host.to_string(),
2009 result,
2010 detail,
2011 branches_total: cov.branches,
2012 branches_covered: cov.covered,
2013 fn_name: row_name(*own_n, spec, name),
2014 });
2015 }
2016 }
2017 Ok(rows)
2018}
2019
2020pub fn publish_stored_checked_lanes<S: Store + Sync + ?Sized>(
2023 store: &S,
2024 key: &SigningKey,
2025 host: &str,
2026 owned: &[String],
2027 path: &Path,
2028 opts: &PublishOptions,
2029) -> Result<Published, PublishError> {
2030 let lanes = publish_lanes()?;
2031 publish_planned(store, key, host, owned, path, opts, true, |s, ops| {
2032 write(s, ops, |s, g, out| write_cells(s, g, lanes, out))
2033 })
2034}
2035
2036#[allow(clippy::too_many_arguments)]
2038fn publish_planned<S: Store + ?Sized>(
2039 store: &S,
2040 key: &SigningKey,
2041 host: &str,
2042 owned: &[String],
2043 path: &Path,
2044 opts: &PublishOptions,
2045 checked: bool,
2046 write_ops: impl FnOnce(&S, &[Op]) -> Result<(Published, Written), PublishError>,
2047) -> Result<Published, PublishError> {
2048 let lines = read_lines(path)?;
2049 let base = path.parent().unwrap_or(Path::new("."));
2050 planned_lines(store, key, host, owned, lines, base, &BTreeMap::new(), false, opts, checked, write_ops)
2051}
2052
2053pub(crate) fn publish_job<S: Store + ?Sized>(
2056 store: &S,
2057 key: &SigningKey,
2058 host: &str,
2059 owned: &[String],
2060 lines: Vec<String>,
2061 blobs: &BTreeMap<String, Vec<u8>>,
2062 opts: &PublishOptions,
2063) -> Result<Published, PublishError> {
2064 let numbered: Vec<(usize, String)> = lines.into_iter().enumerate().map(|(i, l)| (i + 1, l)).collect();
2065 planned_lines(store, key, host, owned, numbered, Path::new("."), blobs, true, opts, false, |s, ops| {
2066 write(s, ops, |s, g, out| write_cells_one_lane(s, g, out))
2067 })
2068}
2069
2070#[allow(clippy::too_many_arguments)]
2072fn planned_lines<S: Store + ?Sized>(
2073 store: &S,
2074 key: &SigningKey,
2075 host: &str,
2076 owned: &[String],
2077 lines: Vec<(usize, String)>,
2078 base: &Path,
2079 blobs: &BTreeMap<String, Vec<u8>>,
2080 job: bool,
2081 opts: &PublishOptions,
2082 checked: bool,
2083 write_ops: impl FnOnce(&S, &[Op]) -> Result<(Published, Written), PublishError>,
2084) -> Result<Published, PublishError> {
2085 let key_from = store
2087 .namespace(host)
2088 .ok()
2089 .flatten()
2090 .and_then(|n| json::parse(&n.keydoc).ok())
2091 .and_then(|d| match d.get("keys") {
2092 Some(Value::Array(ks)) => ks
2093 .iter()
2094 .find(|k| k.get("id").and_then(Value::as_str) == Some(key.key_id()))
2095 .and_then(|k| k.get("valid_from").and_then(Value::as_str).map(str::to_string)),
2096 _ => None,
2097 })
2098 .ok_or_else(|| {
2099 PublishError::at(0, format!("the key {} is not in {host}'s key document in the store", key.key_id()))
2100 })?;
2101 let now = opts.clock.now();
2102 let ctx = Ctx { host, owned, key_from: &key_from, now: &now, base, job, blobs };
2103 let mut planner = Planner {
2104 store,
2105 key,
2106 ctx,
2107 backfill: opts.backfill.is_some(),
2108 sim: Simulation::default(),
2109 reads: Reads::default(),
2110 ops: Vec::new(),
2111 binds: Vec::new(),
2112 tests: Vec::new(),
2113 formulas: Vec::new(),
2114 };
2115 planner.run(&lines)?;
2116 let Planner { ops, binds, tests, formulas, .. } = planner;
2117 if opts.backfill.is_some() {
2118 backfill_check(store, &binds)?;
2119 }
2120 let overlay = overlay_of(&ops)?;
2123 let rows = check_tests(store, &overlay, &tests, &formulas, host, &now, checked)?;
2124 let (out, written) = write_ops(store, &ops)?;
2125 index_cell_values(store, &ops).map_err(|e| PublishError::at(0, format!("catalogue: {e}")))?;
2126 testrun::apply_rows(store, &rows, &now).map_err(|e| PublishError::at(0, format!("tests: {e}")))?;
2127 let rebound: Vec<String> = ops
2128 .iter()
2129 .filter_map(|op| match op {
2130 Op::Function { name, bind: true, .. } => Some(name.clone()),
2131 _ => None,
2132 })
2133 .collect();
2134 testrun::rerun_readers(store, &rebound, &now).map_err(|e| PublishError::at(0, format!("tests: {e}")))?;
2135 let rebound: BTreeSet<String> = rebound.into_iter().collect();
2137 let written_cells: Vec<(String, String)> = overlay.cells.iter().map(|c| (c.name.clone(), c.id.clone())).collect();
2138 testrun::rerun_stored_tests(store, &rebound, &written_cells, &now)
2139 .map_err(|e| PublishError::at(0, format!("tests: {e}")))?;
2140 if let Some(log) = &opts.backfill {
2141 if out.functions + out.classes + out.versions > 0 {
2142 append_log(log, &written).map_err(|e| PublishError::at(0, format!("backfill log: {e}")))?;
2143 }
2144 }
2145 Ok(out)
2146}