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 for page in missing.chunks(crate::catalog_build::PAGE) {
417 if let Ok(found) = store.latest_many(page) {
418 for (id, v) in page.iter().zip(found) {
419 self.latest_of.insert(id.to_string(), v.map(|v| (v.tx, v.receipt_hash)));
420 }
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 for page in missing.chunks(crate::catalog_build::PAGE) {
431 if let Ok(found) = store.receipts_many(page) {
432 for (h, b) in page.iter().zip(found) {
433 self.receipt_of.insert(h.to_string(), b);
434 }
435 }
436 }
437 }
438}
439
440fn parallel_owned<T: Send, R: Send>(items: Vec<T>, f: impl Fn(T) -> R + Sync) -> Vec<R> {
442 let threads = std::thread::available_parallelism().map_or(1, |n| n.get()).min(items.len());
443 if threads <= 1 {
444 return items.into_iter().map(f).collect();
445 }
446 let size = items.len().div_ceil(threads);
447 let mut parts: Vec<Vec<T>> = Vec::with_capacity(threads);
448 let mut rest = items.into_iter();
449 loop {
450 let part: Vec<T> = rest.by_ref().take(size).collect();
451 if part.is_empty() {
452 break;
453 }
454 parts.push(part);
455 }
456 std::thread::scope(|s| {
457 let handles: Vec<_> = parts
458 .into_iter()
459 .map(|part| {
460 let f = &f;
461 s.spawn(move || part.into_iter().map(f).collect::<Vec<R>>())
462 })
463 .collect();
464 handles.into_iter().flat_map(|h| h.join().unwrap_or_else(|e| std::panic::resume_unwind(e))).collect()
465 })
466}
467
468fn current_function<S: Store + ?Sized>(store: &S, sim: &Simulation, name: &str) -> Result<Option<String>, String> {
470 if let Some((_, h)) = Simulation::latest(&sim.functions, name, END) {
471 return Ok(Some(h));
472 }
473 store.resolve_name(name, END).map_err(|e| e.to_string())
474}
475
476fn current_class<S: Store + ?Sized>(store: &S, sim: &Simulation, name: &str) -> Result<Option<String>, String> {
478 if let Some((_, h)) = Simulation::latest(&sim.classes, name, END) {
479 return Ok(Some(h));
480 }
481 store.resolve_class(name, END).map_err(|e| e.to_string())
482}
483
484fn key_matches(cd: &ClassDescriptor, fd: &FunctionDescriptor, k: &str) -> bool {
487 let (Some(ck), Some(arg)) = (cd.keys.get(k), fd.signature.args.get(k)) else { return false };
488 match ck {
489 datumesh_core::ClassKey::Scalar { ty, .. } => arg.ty == *ty,
490 datumesh_core::ClassKey::Class(c) => {
491 arg.ty == Type::String
492 && fd.arg_extras.get(k).and_then(|x| x.classes.as_ref()).is_some_and(|cs| cs.iter().any(|x| x == c))
493 }
494 _ => false,
495 }
496}
497
498fn function_at<S: Store + ?Sized>(
500 reads: &mut Reads,
501 store: &S,
502 sim: &Simulation,
503 name: &str,
504 at: &str,
505) -> Result<Option<String>, String> {
506 let stored = reads.binding(store, name, at)?;
507 let simmed = Simulation::latest(&sim.functions, name, at);
508 Ok(match (stored, simmed) {
509 (Some(b), Some((t, h))) if t >= b.tx => Some(h),
510 (Some(b), _) => Some(b.fn_hash),
511 (None, Some((_, h))) => Some(h),
512 (None, None) => None,
513 })
514}
515
516fn latest_bind<S: Store + ?Sized>(
518 store: &S,
519 sim: &Simulation,
520 name: &str,
521 class: bool,
522) -> Result<Option<String>, String> {
523 let stored: Option<String> = if class {
524 store.resolve_class_binding(name, END).map_err(|e| e.to_string())?.map(|b| b.tx)
525 } else {
526 store.resolve_binding(name, END).map_err(|e| e.to_string())?.map(|b| b.tx)
527 };
528 let binds = if class { &sim.classes } else { &sim.functions };
529 let planned = binds.get(name).and_then(|v| v.iter().map(|(t, _)| t.clone()).max());
530 Ok(match (stored, planned) {
531 (Some(a), Some(b)) => Some(a.max(b)),
532 (a, b) => a.or(b),
533 })
534}
535
536fn bound_as_other<S: Store + ?Sized>(store: &S, sim: &Simulation, name: &str, class: bool) -> Result<bool, String> {
538 if class {
539 Ok(store.resolve_binding(name, END).map_err(|e| e.to_string())?.is_some() || sim.functions.contains_key(name))
540 } else {
541 Ok(store.resolve_class_binding(name, END).map_err(|e| e.to_string())?.is_some()
542 || sim.classes.contains_key(name))
543 }
544}
545
546fn cell_latest<S: Store + ?Sized>(
548 reads: &mut Reads,
549 store: &S,
550 sim: &Simulation,
551 id: &str,
552) -> Result<Option<(String, String)>, String> {
553 let stored = reads.latest(store, id)?;
554 let planned = sim.versions.get(id).and_then(|v| v.last().cloned());
555 Ok(match (stored, planned) {
556 (Some(a), Some(b)) => Some(if b.0 > a.0 { b } else { a }),
557 (a, b) => a.or(b),
558 })
559}
560
561fn cell_version_asof<S: Store + ?Sized>(
563 store: &S,
564 sim: &Simulation,
565 id: &str,
566 at: &str,
567) -> Result<Option<String>, String> {
568 let stored = store.version_asof(id, at).map_err(|e| e.to_string())?.map(|v| (v.tx, v.receipt_hash));
569 let planned = sim.versions.get(id).and_then(|v| v.iter().rev().find(|(t, _)| t.as_str() <= at).cloned());
570 let latest = match (stored, planned) {
571 (Some(a), Some(b)) => Some(if b.0 > a.0 { b } else { a }),
572 (a, b) => a.or(b),
573 };
574 Ok(latest.map(|x| x.1))
575}
576
577fn function_bytes_of<S: Store + ?Sized>(
579 reads: &mut Reads,
580 store: &S,
581 sim: &Simulation,
582 hash: &str,
583) -> Result<Option<Vec<u8>>, String> {
584 if let Some(b) = sim.descriptors.get(hash) {
585 return Ok(Some(b.clone()));
586 }
587 Ok(reads.descriptor(store, hash))
588}
589
590fn suspended<S: Store + ?Sized>(reads: &mut Reads, store: &S, host: &str, line: usize) -> Result<(), PublishError> {
592 match reads.namespace(store, host) {
593 Ok(Some(n)) if n.suspended_at.is_some() => {
594 Err(PublishError::at(line, format!("{host} is suspended: no new bindings or classes under it")))
595 }
596 Ok(_) => Ok(()),
597 Err(e) => Err(PublishError::at(line, e)),
598 }
599}
600
601struct Bind {
603 line: usize,
604 name: String,
605}
606
607#[derive(Default)]
609struct Written {
610 namespaces: BTreeSet<String>,
611 starts: BTreeSet<String>,
612}
613
614impl Written {
615 fn bound(&mut self, name: &str, start: &str) {
616 self.namespaces.insert(namespace_of(name).to_string());
617 self.starts.insert(start.to_string());
618 }
619}
620
621struct Ctx<'a> {
623 host: &'a str,
624 owned: &'a [String],
625 key_from: &'a str,
627 now: &'a str,
629 base: &'a Path,
631 job: bool,
633 blobs: &'a BTreeMap<String, Vec<u8>>,
635}
636
637enum Op {
639 Descriptor { hash: String, bytes: Vec<u8>, counted: bool },
641 Function { name: String, start: String, hash: String, bytes: Vec<u8>, bind: bool },
643 Class { name: String, start: String, hash: String, bytes: Vec<u8>, bind: bool, methods: Vec<(String, String)> },
646 Cell { tx: String, id: String, receipt: Vec<u8>, blob: Option<Vec<u8>>, version: bool },
648 Close { name: String, at: String },
650 Catalog {
652 entry: datumesh_store::CatalogEntry,
653 dictionaries: Vec<(String, Vec<datumesh_store::KeyValue>)>,
654 open_keys: Vec<String>,
655 extends: Option<String>,
656 facets: datumesh_store::Facets,
657 source_name: Option<String>,
659 },
660}
661
662fn read_lines(path: &Path) -> Result<Vec<(usize, String)>, PublishError> {
664 let file = std::fs::File::open(path).map_err(|e| PublishError::at(0, format!("{}: {e}", path.display())))?;
665 let mut out = Vec::new();
666 for (i, line) in std::io::BufReader::new(file).lines().enumerate() {
667 let n = i + 1;
668 let line = line.map_err(|e| PublishError::at(n, e.to_string()))?;
669 if !line.trim().is_empty() {
670 out.push((n, line));
671 }
672 }
673 Ok(out)
674}
675
676fn index_cell_values<S: Store + ?Sized>(store: &S, ops: &[Op]) -> Result<(), String> {
680 let mut seen = BTreeSet::new();
681 for op in ops {
682 if let Op::Cell { receipt, .. } = op {
683 if let Ok(r) = datumesh_core::Receipt::from_json(receipt) {
684 cell_string_values(&r, &mut seen);
685 }
686 }
687 }
688 store_cell_values(store, seen)
689}
690
691pub(crate) fn cell_string_values(r: &datumesh_core::Receipt, out: &mut BTreeSet<(String, String, String)>) {
693 let cell = r.cell();
694 for (key, arg) in &cell.args {
695 if let datumesh_core::Arg::Value(datumesh_core::Scalar::String(v)) = arg {
696 if !v.is_empty() && v.len() <= 1024 {
697 out.insert((cell.function_name(), key.clone(), v.clone()));
698 }
699 }
700 }
701}
702
703pub(crate) fn dictionary_limit() -> u64 {
707 std::env::var("DATUMESH_DICTIONARY_MAX")
708 .ok()
709 .and_then(|v| v.trim().parse::<u64>().ok())
710 .filter(|n| *n >= 1)
711 .unwrap_or(1000)
712}
713
714pub(crate) fn store_cell_values<S: Store + ?Sized>(
719 store: &S,
720 seen: BTreeSet<(String, String, String)>,
721) -> Result<(), String> {
722 let mut groups: BTreeMap<(String, String), Vec<String>> = BTreeMap::new();
723 for (owner, key, value) in seen {
724 groups.entry((owner, key)).or_default().push(value);
725 }
726 let limit = dictionary_limit();
727 for ((owner, key), values) in groups {
728 if store.key_is_open(&owner, &key).map_err(|e| e.to_string())? {
729 continue;
730 }
731 let fresh: Vec<String> =
732 values.into_iter().filter(|v| !crate::find::has_value(store, &owner, &key, v)).collect();
733 if fresh.is_empty() {
734 continue;
735 }
736 let have = store.key_value_count(&owner, &key).map_err(|e| e.to_string())?;
737 if have + fresh.len() as u64 > limit {
738 store.mark_key_open(&owner, &key).map_err(|e| e.to_string())?;
739 continue;
740 }
741 let kvs: Vec<datumesh_store::KeyValue> = fresh
742 .into_iter()
743 .map(|value| datumesh_store::KeyValue { value, label: String::new(), aliases: Vec::new() })
744 .collect();
745 store.upsert_key_values(&owner, &key, &kvs).map_err(|e| e.to_string())?;
746 }
747 Ok(())
748}
749
750fn row_name(own: Option<usize>, spec: &TestSpec, group: &str) -> String {
753 match own {
754 Some(_) => spec.function.clone(),
755 None => group.to_string(),
756 }
757}
758
759fn is_cell_line(v: &Value) -> bool {
761 v.get("class").and_then(Value::as_str).is_none()
762 && v.get("descriptor").is_none()
763 && v.get("function").and_then(Value::as_str).is_none()
764 && v.get("formula").and_then(Value::as_str).is_none()
765 && v.get("cell").is_some()
766}
767
768struct Pending {
770 line: usize,
771 ns: String,
772 cell: Cell,
773 value: Option<Scalar>,
775 withdrawn: Option<String>,
777 valid: Args,
778 tx: String,
779 asof: String,
780 issued: String,
781 has_tx: bool,
782 licence: String,
783 summary: String,
784 blob: Option<Vec<u8>>,
785 source: Option<Source>,
787}
788
789fn source_of_line(v: &Value) -> Result<Source, String> {
793 let Value::Object(m) = v else { return Err("source is an object".into()) };
794 for (k, x) in m {
795 if !matches!(k.as_str(), "name" | "url" | "retrieved" | "sha256" | "takeover") {
796 return Err(format!("source has no member {k}"));
797 }
798 if !matches!(x, Value::String(_)) {
799 return Err(format!("source.{k} is a string"));
800 }
801 }
802 let text = |k: &str| -> Result<&str, String> {
803 v.get(k).and_then(Value::as_str).ok_or_else(|| format!("source has no {k}"))
804 };
805 let mut out = Source::new(text("name")?, text("url")?, text("retrieved")?);
806 if let Some(h) = v.get("sha256").and_then(Value::as_str) {
807 out = out.with_sha256(h);
808 }
809 if let Some(t) = v.get("takeover").and_then(Value::as_str) {
810 out = out.with_takeover(t);
811 }
812 Ok(out)
813}
814
815impl Pending {
816 fn sign(self, key: &SigningKey, host: &str) -> Result<Signed, PublishError> {
818 let line = self.line;
819 let err = move |d: String| PublishError::at(line, d);
820 let b = ReceiptBuilder::new()
821 .cell(self.cell.clone())
822 .valid(self.valid)
823 .asof(self.asof.as_str())
824 .tx(self.tx.as_str())
825 .issued(self.issued.as_str())
826 .publisher(self.ns.as_str())
827 .signer_host(host)
828 .licence(self.licence.as_str())
829 .summary(self.summary.as_str());
830 let b = match self.source {
831 Some(s) => b.source(s),
832 None => b,
833 };
834 if let Some(reason) = &self.withdrawn {
835 let w = b.withdrawn(reason).sign_withdrawal(key).map_err(|e| err(e.to_string()))?;
837 let id = self.cell.id();
838 return Ok(Signed {
839 line,
840 has_tx: self.has_tx,
841 tx: self.tx,
842 id,
843 hash: w.hash().to_string(),
844 receipt: w.canonical().to_vec(),
845 blob: None,
846 });
847 }
848 let Some(value) = self.value else { return Err(err("a cell without value".into())) };
849 let r = b.value(value).sign(key).map_err(|e| err(e.to_string()))?;
850 let receipt = receipt_json(&r);
851 let hash = Receipt::from_json(&receipt).map_err(|e| err(e.to_string()))?.hash().to_string();
852 let id = self.cell.id();
853 Ok(Signed { line, has_tx: self.has_tx, tx: self.tx, id, hash, receipt, blob: self.blob })
854 }
855}
856
857struct Signed {
859 line: usize,
860 has_tx: bool,
861 tx: String,
862 id: String,
863 hash: String,
864 receipt: Vec<u8>,
865 blob: Option<Vec<u8>>,
866}
867
868struct Planner<'a, S: Store + ?Sized> {
870 store: &'a S,
871 key: &'a SigningKey,
872 ctx: Ctx<'a>,
873 backfill: bool,
874 sim: Simulation,
875 reads: Reads,
876 ops: Vec<Op>,
877 binds: Vec<Bind>,
878 tests: Vec<(usize, TestSpec)>,
880 formulas: Vec<(usize, String, String)>,
882}
883
884impl<S: Store + ?Sized> Planner<'_, S> {
885 fn callers(&self) -> Callers<'_, S> {
886 Callers { store: self.store, sim: Some(&self.sim) }
887 }
888
889 fn run(&mut self, lines: &[(usize, String)]) -> Result<(), PublishError> {
892 let mut cells: Vec<(usize, Value)> = Vec::new();
893 for (n, text) in lines {
894 let n = *n;
895 match json::parse(text.as_bytes()).map_err(|e| PublishError::at(n, e.to_string())) {
896 Ok(v) if is_cell_line(&v) => {
897 if let Some(name) = v.get("cell").and_then(|c| c.get("fn")).and_then(Value::as_str) {
899 crate::reserved::check_for(self.ctx.host, name, None, self.ctx.job)
900 .map_err(|e| PublishError::at(n, e))?;
901 }
902 cells.push((n, v));
903 if cells.len() == CHUNK {
904 self.plan_cells(std::mem::take(&mut cells))?;
905 }
906 }
907 other => {
908 self.plan_cells(std::mem::take(&mut cells))?;
911 self.plan_line(n, &other?)?;
912 }
913 }
914 }
915 self.plan_cells(cells)
916 }
917
918 fn plan_line(&mut self, n: usize, v: &Value) -> Result<(), PublishError> {
920 let err = |d: String| PublishError::at(n, d);
921 let named =
924 v.get("class").or_else(|| v.get("function")).or_else(|| v.get("formula")).or_else(|| v.get("catalog"));
925 if let Some(name) = named.and_then(Value::as_str) {
926 crate::reserved::check_for(self.ctx.host, name, None, self.ctx.job).map_err(err)?;
927 }
928 if let Some(name) = v.get("class").and_then(Value::as_str) {
929 self.class_line(n, name, v)?;
930 } else if let Some(d) = v.get("descriptor") {
931 self.descriptor_line(n, d)?;
932 } else if let Some(name) = v.get("function").and_then(Value::as_str) {
933 let sig = v.get("signature").ok_or_else(|| err("a function without a signature".into()))?;
934 let start = bound_of(v, n, self.ctx.now)?;
935 let fd = FunctionDescriptor::from_value(&stored_value(sig)).map_err(|e| err(e.to_string()))?;
936 self.function(n, name, start, fd.hash(), fd.canonical())?;
937 } else if let Some(name) = v.get("close").and_then(Value::as_str) {
938 if v.as_object().is_some_and(|m| m.len() != 1) {
939 return Err(err(
940 "a close line takes only close: the name's binding ends at the clock of the write".into()
941 ));
942 }
943 self.close_line(n, name)?;
944 } else if v.get("catalog").is_some() {
945 self.catalog_line(n, v)?;
946 } else if let Some(name) = v.get("formula").and_then(Value::as_str) {
947 let source =
948 v.get("source").and_then(Value::as_str).ok_or_else(|| err("a formula without source".into()))?;
949 let sig = v.get("signature").ok_or_else(|| err("a formula without a signature".into()))?;
950 let start = bound_of(v, n, self.ctx.now)?;
951 let def = datumesh_formula::definition::define_function(
952 name,
953 source,
954 sig,
955 &Default::default(),
956 &self.callers(),
957 &start,
958 )
959 .map_err(|e| err(format!("define {name}: {e}")))?;
960 let hash = def.fn_hash.clone();
961 self.function(n, name, start, def.fn_hash, def.bytes)?;
962 self.formulas.push((n, name.to_string(), hash));
963 } else if v.get("test").is_some() {
964 let spec = testrun::parse_test(v).map_err(err)?;
965 self.tests.push((n, spec));
966 } else {
967 return Err(err("neither a function nor a cell".into()));
968 }
969 Ok(())
970 }
971
972 fn close_line(&mut self, n: usize, name: &str) -> Result<(), PublishError> {
976 let err = |d: String| PublishError::at(n, d);
977 let class = current_class(self.store, &self.sim, name).map_err(err)?.is_some();
978 let bound = class || current_function(self.store, &self.sim, name).map_err(err)?.is_some();
979 if !bound {
980 return Err(err(format!("E_NAME_UNBOUND: {name} is not bound, so it cannot be closed")));
981 }
982 if let Some(tx) = latest_bind(self.store, &self.sim, name, class).map_err(err)? {
983 if self.ctx.now <= tx.as_str() {
984 return Err(err(format!(
985 "E_TIME_ORDER: the close of {name} at {} is not later than its binding at {tx}",
986 self.ctx.now
987 )));
988 }
989 }
990 self.ops.push(Op::Close { name: name.to_string(), at: self.ctx.now.to_string() });
991 Ok(())
992 }
993
994 fn catalog_line(&mut self, n: usize, v: &Value) -> Result<(), PublishError> {
998 let err = |d: String| PublishError::at(n, d);
999 let d = crate::catalog::parse(v, "catalog").map_err(err)?;
1000 let host = host_of(&d.name);
1001 if host != self.ctx.host && !self.ctx.owned.iter().any(|o| o == host) {
1002 return Err(err(format!("{} is not under a host this mesh owns", d.name)));
1003 }
1004 let hash = match d.kind {
1005 datumesh_store::CatalogKind::Class => current_class(self.store, &self.sim, &d.name).map_err(err)?,
1006 _ => current_function(self.store, &self.sim, &d.name).map_err(err)?,
1007 };
1008 if hash.is_none() {
1009 return Err(err(format!("{} is bound nowhere", d.name)));
1010 }
1011 if let (Some(class), Some(fh)) = (&d.extends, &hash) {
1012 self.check_extension(class, fh).map_err(err)?;
1013 }
1014 let entry = d.entry(hash, datumesh_store::CatalogSource::Publisher, Some(self.key.key_id().to_string()));
1015 self.ops.push(Op::Catalog {
1016 entry,
1017 dictionaries: d.dictionary,
1018 open_keys: d.open_keys,
1019 extends: d.extends,
1020 facets: d.facets,
1021 source_name: d.source_name,
1022 });
1023 Ok(())
1024 }
1025
1026 fn descriptor_line(&mut self, n: usize, d: &Value) -> Result<(), PublishError> {
1028 let fd = FunctionDescriptor::from_value(d).map_err(|e| PublishError::at(n, e.to_string()))?;
1029 if fd.lang != "stored" || !fd.body.is_empty() || !fd.inputs.is_empty() {
1030 return Err(PublishError::at(
1031 n,
1032 "a descriptor line takes a stored function only: code.lang stored, code.body empty, no inputs",
1033 ));
1034 }
1035 let (hash, bytes) = (fd.hash(), fd.canonical());
1036 self.sim.descriptors.insert(hash.clone(), bytes.clone());
1037 self.ops.push(Op::Descriptor { hash, bytes, counted: true });
1038 Ok(())
1039 }
1040
1041 fn function(
1043 &mut self,
1044 n: usize,
1045 name: &str,
1046 start: String,
1047 hash: String,
1048 bytes: Vec<u8>,
1049 ) -> Result<(), PublishError> {
1050 self.sim.descriptors.insert(hash.clone(), bytes.clone());
1051 let current = current_function(self.store, &self.sim, name).map_err(|e| PublishError::at(n, e))?;
1052 let bind = current.as_deref() != Some(hash.as_str());
1053 if bind {
1054 self.check_bind(n, name, &start, false)?;
1055 self.sim.functions.entry(name.to_string()).or_default().push((start.clone(), hash.clone()));
1056 }
1057 self.ops.push(Op::Function { name: name.to_string(), start, hash, bytes, bind });
1058 Ok(())
1059 }
1060
1061 fn inline_methods(
1068 &mut self,
1069 n: usize,
1070 class: &str,
1071 descriptor: &Value,
1072 start: &str,
1073 ) -> Result<Value, PublishError> {
1074 let err = |d: String| PublishError::at(n, d);
1075 let Some(Value::Object(written)) = descriptor.get("methods") else { return Ok(descriptor.clone()) };
1076 if !written.iter().any(|(_, v)| matches!(v, Value::Object(_))) {
1077 return Ok(descriptor.clone());
1078 }
1079 let mut hashes: BTreeMap<String, String> = BTreeMap::new();
1080 let mut sigs: Vec<(String, Value)> = Vec::new();
1081 let mut formulas: Vec<(String, String, Value)> = Vec::new();
1082 let mut stored: Vec<(String, String, Vec<u8>)> = Vec::new();
1083 for (m, v) in written {
1084 let fq = format!("{class}/{m}");
1085 match v {
1086 Value::String(h) => {
1087 let bytes = function_bytes_of(&mut self.reads, self.store, &self.sim, h)
1088 .map_err(err)?
1089 .ok_or_else(|| err(format!("{fq}: no descriptor {h}")))?;
1090 let d = json::parse(&bytes).map_err(|e| err(e.to_string()))?;
1091 sigs.push((m.clone(), d.get("signature").cloned().unwrap_or(Value::Null)));
1092 hashes.insert(m.clone(), h.clone());
1093 }
1094 Value::Object(o) => {
1095 let get = |k: &str| o.iter().find(|(x, _)| x == k).map(|(_, y)| y);
1096 match (get("stored"), get("formula"), get("signature")) {
1097 (Some(sig), None, None) => {
1098 let fd = FunctionDescriptor::from_value(&stored_value(sig)).map_err(|e| err(format!("{fq}: {e}")))?;
1099 hashes.insert(m.clone(), fd.hash());
1100 sigs.push((m.clone(), sig.clone()));
1101 stored.push((fq, fd.hash(), fd.canonical()));
1102 }
1103 (None, Some(Value::String(src)), Some(sig)) => {
1104 sigs.push((m.clone(), sig.clone()));
1105 formulas.push((m.clone(), src.clone(), sig.clone()));
1106 }
1107 _ => {
1108 return Err(err(format!(
1109 "{fq}: a method is a function hash, {{\"stored\": <signature>}} or {{\"formula\": <source>, \"signature\": <signature>}}"
1110 )))
1111 }
1112 }
1113 }
1114 _ => return Err(err(format!("{fq}: a method is a function hash or an inline definition"))),
1115 }
1116 }
1117 for (fq, hash, bytes) in stored {
1118 self.sim.descriptors.insert(hash.clone(), bytes.clone());
1119 self.ops.push(Op::Function { name: fq, start: start.to_string(), hash, bytes, bind: false });
1120 }
1121 let mut keys: Vec<(String, Value)> = Vec::new();
1123 let mut order: Vec<Value> = Vec::new();
1124 if let Some(p) = descriptor.get("parent").and_then(Value::as_str) {
1125 let bytes = self
1126 .callers()
1127 .class_bytes(p)
1128 .map_err(err)?
1129 .ok_or_else(|| err(format!("{class}: the parent {p} is not stored")))?;
1130 let pv = json::parse(&bytes).map_err(|e| err(e.to_string()))?;
1131 if let Some(Value::Object(ks)) = pv.get("keys") {
1132 keys.extend(ks.iter().cloned());
1133 }
1134 if let Some(Value::Array(os)) = pv.get("order") {
1135 order.extend(os.iter().cloned());
1136 }
1137 }
1138 if let Some(Value::Object(ks)) = descriptor.get("keys") {
1139 for (k, v) in ks {
1140 if !keys.iter().any(|(x, _)| x == k) {
1141 keys.push((k.clone(), v.clone()));
1142 }
1143 }
1144 }
1145 if let Some(Value::Array(os)) = descriptor.get("order") {
1146 for o in os {
1147 if !order.iter().any(|x| x.as_str() == o.as_str()) {
1148 order.push(o.clone());
1149 }
1150 }
1151 }
1152 let mut draft_members = vec![
1153 ("keys".to_string(), Value::Object(keys)),
1154 ("order".to_string(), Value::Array(order)),
1155 ("methods".to_string(), Value::Object(sigs)),
1156 ];
1157 if let Some(p) = descriptor.get("parent") {
1158 draft_members.push(("parent".to_string(), p.clone()));
1159 }
1160 let draft = datumesh_formula::definition::ClassDraft::from_value(&Value::Object(draft_members))
1161 .map_err(|e| err(format!("{class}: {e}")))?;
1162 let defined = {
1163 let callers = self.callers();
1164 let mut defined = Vec::with_capacity(formulas.len());
1165 for (m, src, sig) in &formulas {
1166 let fq = format!("{class}/{m}");
1167 let def =
1168 datumesh_formula::definition::define_method_in_draft(class, &draft, &fq, src, sig, &callers, start)
1169 .map_err(|e| err(format!("define {fq}: {e}")))?;
1170 defined.push((m.clone(), def));
1171 }
1172 defined
1173 };
1174 let names: BTreeSet<String> = defined.iter().map(|(m, _)| m.clone()).collect();
1176 let reads: BTreeMap<String, BTreeSet<String>> = defined
1177 .iter()
1178 .map(|(m, d)| {
1179 let prefix = format!("{class}/");
1180 let rs = d
1181 .callees
1182 .keys()
1183 .filter_map(|c| c.strip_prefix(prefix.as_str()))
1184 .filter(|x| names.contains(*x))
1185 .map(str::to_string)
1186 .collect();
1187 (m.clone(), rs)
1188 })
1189 .collect();
1190 let mut done: BTreeSet<String> = BTreeSet::new();
1191 let mut order: Vec<String> = Vec::new();
1192 while order.len() < defined.len() {
1193 let next = defined
1194 .iter()
1195 .map(|(m, _)| m)
1196 .find(|m| !done.contains(*m) && reads.get(*m).is_none_or(|rs| rs.iter().all(|r| done.contains(r))));
1197 match next {
1198 Some(m) => {
1199 done.insert(m.clone());
1200 order.push(m.clone());
1201 }
1202 None => {
1203 let left: Vec<&str> =
1204 defined.iter().map(|(m, _)| m.as_str()).filter(|m| !done.contains(*m)).collect();
1205 return Err(err(format!(
1206 "{class}: methods read each other with this ({}): refused (16.3)",
1207 left.join(", ")
1208 )));
1209 }
1210 }
1211 }
1212 let mut defined: BTreeMap<String, datumesh_formula::definition::Definition> = defined.into_iter().collect();
1213 for m in order {
1214 let def = defined.remove(&m).ok_or_else(|| err(format!("{class}/{m}: not defined")))?;
1215 let fq = format!("{class}/{m}");
1216 self.sim.descriptors.insert(def.fn_hash.clone(), def.bytes.clone());
1217 self.ops.push(Op::Function {
1218 name: fq.clone(),
1219 start: start.to_string(),
1220 hash: def.fn_hash.clone(),
1221 bytes: def.bytes.clone(),
1222 bind: false,
1223 });
1224 self.formulas.push((n, fq, def.fn_hash.clone()));
1225 hashes.insert(m, def.fn_hash);
1226 }
1227 let methods: Vec<(String, Value)> = written
1228 .iter()
1229 .map(|(m, _)| (m.clone(), Value::String(hashes.get(m).cloned().unwrap_or_default())))
1230 .collect();
1231 let mut out = descriptor.clone();
1232 if let Value::Object(members) = &mut out {
1233 for (k, v) in members.iter_mut() {
1234 if k == "methods" {
1235 *v = Value::Object(methods.clone());
1236 }
1237 }
1238 }
1239 Ok(out)
1240 }
1241
1242 fn check_extension(&mut self, class: &str, fn_hash: &str) -> Result<(), String> {
1245 let chash = current_class(self.store, &self.sim, class)?
1246 .ok_or_else(|| format!("extends {class}: no class of that name is bound on this mesh"))?;
1247 let cbytes = match self.sim.class_bytes.get(&chash) {
1248 Some(b) => b.clone(),
1249 None => self
1250 .store
1251 .class(&chash)
1252 .map_err(|e| e.to_string())?
1253 .ok_or_else(|| format!("class {chash} is not stored"))?,
1254 };
1255 let cd = ClassDescriptor::from_json(&cbytes).map_err(|e| e.to_string())?;
1256 let fbytes = function_bytes_of(&mut self.reads, self.store, &self.sim, fn_hash)?
1257 .ok_or_else(|| format!("no descriptor {fn_hash}"))?;
1258 let fd = FunctionDescriptor::from_json(&fbytes).map_err(|e| e.to_string())?;
1259 let order = fd.order.clone().unwrap_or_default();
1260 let keys_match = order.len() >= cd.order.len()
1261 && order[..cd.order.len()] == cd.order[..]
1262 && cd.order.iter().all(|k| key_matches(&cd, &fd, k));
1263 if !keys_match {
1264 return Err(format!(
1265 "extends {class}: the function does not take the keys of {class} first, with their types"
1266 ));
1267 }
1268 Ok(())
1269 }
1270
1271 fn class_line(&mut self, n: usize, name: &str, v: &Value) -> Result<(), PublishError> {
1272 let err = |d: String| PublishError::at(n, d);
1273 let written = v.get("descriptor").ok_or_else(|| err("a class without descriptor".into()))?;
1274 let start = bound_of(v, n, self.ctx.now)?;
1275 let descriptor = &self.inline_methods(n, name, written, &start)?;
1276 let def = datumesh_formula::definition::define_class(
1277 name,
1278 &descriptor.to_jcs(),
1279 definer(name, self.ctx.host, self.ctx.owned),
1280 &self.callers(),
1281 &start,
1282 )
1283 .map_err(|e| err(format!("define {name}: {e}")))?;
1284 suspended(&mut self.reads, self.store, host_of(&def.descriptor.steward.namespace), n)?;
1288 let hash = def.class_hash.clone();
1289 let methods: Vec<(String, String)> =
1290 def.descriptor.methods.iter().map(|(m, fh)| (format!("{name}/{m}"), fh.clone())).collect();
1291 let bind = current_class(self.store, &self.sim, name).map_err(err)?.as_deref() != Some(hash.as_str());
1292 if bind {
1293 self.check_bind(n, name, &start, true)?;
1294 for (mname, _) in &methods {
1296 self.check_bind(n, mname, &start, false)?;
1297 }
1298 self.sim.classes.entry(name.to_string()).or_default().push((start.clone(), hash.clone()));
1299 for (mname, fh) in &methods {
1300 self.sim.functions.entry(mname.clone()).or_default().push((start.clone(), fh.clone()));
1301 }
1302 }
1303 self.sim.class_bytes.insert(hash.clone(), def.bytes.clone());
1304 self.ops.push(Op::Class { name: name.to_string(), start, hash, bytes: def.bytes, bind, methods });
1305 Ok(())
1306 }
1307
1308 fn check_bind(&mut self, line: usize, name: &str, start: &str, class: bool) -> Result<(), PublishError> {
1310 if !self.backfill && start < self.ctx.now {
1311 return Err(PublishError::typed(
1312 line,
1313 PublishErrorKind::StartBeforeNow { name: name.into(), start: start.into(), now: self.ctx.now.into() },
1314 ));
1315 }
1316 let err = |d: String| PublishError::at(line, d);
1317 if bound_as_other(self.store, &self.sim, name, class).map_err(err)? {
1318 let kind = if class { "function" } else { "class" };
1319 return Err(err(format!("{name} is bound as a {kind}: one namespace of names")));
1320 }
1321 suspended(&mut self.reads, self.store, host_of(name), line)?;
1322 if let Some(latest) = latest_bind(self.store, &self.sim, name, class).map_err(err)? {
1323 if start <= latest.as_str() {
1324 return Err(err(format!("{name} is bound from {latest}: a bind at {start} is not later")));
1325 }
1326 }
1327 self.binds.push(Bind { line, name: name.into() });
1328 Ok(())
1329 }
1330
1331 fn plan_cells(&mut self, lines: Vec<(usize, Value)>) -> Result<(), PublishError> {
1336 if lines.is_empty() {
1337 return Ok(());
1338 }
1339 let mut pending = Vec::with_capacity(lines.len());
1340 let mut failed = None;
1341 for (n, v) in &lines {
1342 match self.prepare_cell(*n, v) {
1343 Ok(p) => pending.push(p),
1344 Err(e) => {
1345 failed = Some(e);
1346 break;
1347 }
1348 }
1349 }
1350 let (key, host) = (self.key, self.ctx.host);
1351 let signed = parallel_owned(pending, |p| p.sign(key, host));
1352 let ids: Vec<&str> = signed.iter().flatten().map(|s| s.id.as_str()).collect();
1353 self.reads.prefetch_latest(self.store, &ids);
1354 let hashes: Vec<String> = signed
1355 .iter()
1356 .flatten()
1357 .filter(|s| !s.has_tx)
1358 .filter_map(|s| self.reads.latest_of.get(&s.id).cloned().flatten())
1359 .map(|(_, h)| h)
1360 .collect();
1361 let hashes: Vec<&str> = hashes.iter().map(String::as_str).collect();
1362 self.reads.prefetch_receipts(self.store, &hashes);
1363 for s in signed {
1364 self.check_cell(s?)?;
1365 }
1366 match failed {
1367 Some(e) => Err(e),
1368 None => Ok(()),
1369 }
1370 }
1371
1372 fn prepare_cell(&mut self, n: usize, v: &Value) -> Result<Pending, PublishError> {
1375 let err = |d: String| PublishError::at(n, d);
1376 let cell_v = v.get("cell").ok_or_else(|| err("a cell without fn".into()))?;
1377 let name = cell_v.get("fn").and_then(Value::as_str).ok_or_else(|| err("a cell without fn".into()))?;
1378 let (ns, f) = name.rsplit_once('/').ok_or_else(|| err(format!("{name}: not a function name")))?;
1379 let field = |k: &str| v.get(k).and_then(Value::as_str).map(str::to_string);
1380 let required = |k: &str| field(k).ok_or_else(|| err(format!("no {k}")));
1381 let (licence, summary) = (required("licence")?, required("summary")?);
1382 let asof = field("asof").unwrap_or_else(|| self.ctx.now.to_string());
1384 let has_tx = field("tx").is_some();
1385 let tx = field("tx").unwrap_or_else(|| self.ctx.now.to_string());
1386 if tx > asof {
1387 return Err(err(format!("tx {tx} is after asof {asof} (SPEC 8)")));
1388 }
1389 let issued = field("issued").unwrap_or_else(|| std::cmp::max(asof.clone(), self.ctx.key_from.to_string()));
1390 if asof > issued {
1391 return Err(err(format!("asof {asof} is after issued {issued} (SPEC 8)")));
1392 }
1393 let fn_hash = function_at(&mut self.reads, self.store, &self.sim, name, &tx)
1394 .map_err(err)?
1395 .ok_or_else(|| err(format!("{name} is not bound as of {tx}")))?;
1396 let d = function_bytes_of(&mut self.reads, self.store, &self.sim, &fn_hash)
1397 .map_err(err)?
1398 .ok_or_else(|| err(format!("no descriptor {fn_hash}")))?;
1399 let d = FunctionDescriptor::from_json(&d).map_err(|e| err(e.to_string()))?;
1400 let mut args = Args::new();
1401 for (k, a) in cell_v.get("args").and_then(Value::as_object).ok_or_else(|| err("a cell without args".into()))? {
1402 args.insert(k.clone(), Arg::Value(Scalar::from_json(&a.to_jcs()).map_err(|e| err(format!("{k}: {e}")))?));
1403 }
1404 for (k, a) in &args {
1406 let rule = d.arg_extras.get(k).and_then(|x| x.key_normalisation);
1407 if let (true, Arg::Value(Scalar::String(text))) = (matches!(rule, Some(KeyNormalisation::LabelFold)), a) {
1408 if datumesh_core::fold_label(text) != *text {
1409 return Err(err(format!("E_KEY_NORMALISATION: {k}: {text:?} is not folded (label_fold)")));
1410 }
1411 }
1412 }
1413 let valid: Args = args
1414 .iter()
1415 .filter(|(k, _)| d.signature.args.get(*k).is_some_and(|x| x.valid))
1416 .map(|(k, a)| (k.clone(), a.clone()))
1417 .collect();
1418 let source = match v.get("source") {
1419 Some(sv) => Some(source_of_line(sv).map_err(err)?),
1420 None => None,
1421 };
1422 let withdrawn = match v.get("withdrawn") {
1424 None => None,
1425 Some(Value::String(reason)) => Some(reason.clone()),
1426 Some(_) => return Err(err("E_SCHEMA: withdrawn is a non-empty string: the reason".into())),
1427 };
1428 if withdrawn.is_some() && v.get("value").is_some() {
1429 return Err(err("E_SCHEMA: a cell line has withdrawn or value, not both".into()));
1430 }
1431 let (value, blob) = if withdrawn.is_some() {
1432 (None, None)
1433 } else {
1434 let value_v = v.get("value").ok_or_else(|| err("a cell without value".into()))?;
1435 let (scalar, blob) = match value_v.get("blob").and_then(Value::as_str) {
1436 Some(file) => {
1437 let media = value_v.get("media_type").and_then(Value::as_str).unwrap_or("application/octet-stream");
1438 let bytes = match self.ctx.blobs.get(file) {
1439 Some(b) => b.clone(),
1440 None => std::fs::read(self.ctx.base.join(file)).map_err(|e| err(format!("{file}: {e}")))?,
1441 };
1442 let sha = sha256_hex(&bytes);
1443 let scalar = Scalar::from_lexical(Type::Blob, &format!("{sha}:{}:{media}", bytes.len()))
1444 .map_err(|e| err(e.to_string()))?;
1445 (scalar, Some(bytes))
1446 }
1447 None => (Scalar::from_json(&value_v.to_jcs()).map_err(|e| err(e.to_string()))?, None),
1448 };
1449 if let Scalar::String(text) = &scalar {
1451 if text.is_empty() && lookup_method(self.store, &self.sim, name).map_err(err)? {
1452 return Err(err(format!(
1453 "E_KEY_NORMALISATION: {name} is a lookup, and its value is not the empty string"
1454 )));
1455 }
1456 }
1457 (Some(scalar), blob)
1458 };
1459 let cell = Cell { ns: ns.to_string(), fn_name: f.to_string(), fn_hash, args };
1460 Ok(Pending {
1461 line: n,
1462 ns: ns.to_string(),
1463 cell,
1464 value,
1465 withdrawn,
1466 valid,
1467 tx,
1468 asof,
1469 issued,
1470 has_tx,
1471 licence,
1472 summary,
1473 blob,
1474 source,
1475 })
1476 }
1477
1478 fn check_cell(&mut self, s: Signed) -> Result<(), PublishError> {
1481 let line = s.line;
1482 let err = |d: String| PublishError::at(line, d);
1483 if !s.has_tx {
1488 if let Some((_, latest)) = cell_latest(&mut self.reads, self.store, &self.sim, &s.id).map_err(err)? {
1489 if let Some(old) = self.reads.receipt(self.store, &latest) {
1490 let old = json::parse(&old).map_err(|e| err(e.to_string()))?;
1491 let new = json::parse(&s.receipt).map_err(|e| err(e.to_string()))?;
1492 if ["type", "value", "withdrawn", "valid", "licence", "summary"]
1493 .iter()
1494 .all(|k| old.get(k) == new.get(k))
1495 {
1496 return Ok(());
1497 }
1498 }
1499 }
1500 }
1501 let version = match cell_latest(&mut self.reads, self.store, &self.sim, &s.id).map_err(err)? {
1502 Some((latest_tx, _)) if latest_tx.as_str() >= s.tx.as_str() => {
1503 if cell_version_asof(self.store, &self.sim, &s.id, &s.tx).map_err(err)?.as_deref()
1504 != Some(s.hash.as_str())
1505 {
1506 return Err(err(format!("{} has a version at or after {} that is not this receipt", s.id, s.tx)));
1507 }
1508 false
1509 }
1510 _ => {
1511 self.sim.versions.entry(s.id.clone()).or_default().push((s.tx.clone(), s.hash.clone()));
1512 true
1513 }
1514 };
1515 self.ops.push(Op::Cell { tx: s.tx, id: s.id, receipt: s.receipt, blob: s.blob, version });
1516 Ok(())
1517 }
1518}
1519
1520fn lookup_method<S: Store + ?Sized>(store: &S, sim: &Simulation, name: &str) -> Result<bool, String> {
1522 let Some((class, method)) = name.rsplit_once('/') else { return Ok(false) };
1523 let Some(hash) = current_class(store, sim, class)? else { return Ok(false) };
1524 let Some(bytes) = store.class(&hash).map_err(|e| e.to_string())? else { return Ok(false) };
1525 let cd = ClassDescriptor::from_json(&bytes).map_err(|e| e.to_string())?;
1526 Ok(cd.lookup.as_deref() == Some(method))
1527}
1528
1529fn stored_value(signature: &Value) -> Value {
1531 Value::Object(vec![
1532 ("code".into(), Value::Object(vec![("body".into(), s("")), ("lang".into(), s("stored"))])),
1533 ("inputs".into(), Value::Array(vec![])),
1534 ("signature".into(), signature.clone()),
1535 ])
1536}
1537
1538fn backfill_check<S: Store + ?Sized>(store: &S, binds: &[Bind]) -> Result<(), PublishError> {
1541 for b in binds {
1542 let refuse = |why: String| PublishError::typed(b.line, PublishErrorKind::Backfill(why));
1543 if store.resolve_binding(&b.name, END).map_err(|e| PublishError::at(b.line, e.to_string()))?.is_some() {
1544 return Err(refuse(format!("{} has a binding", b.name)));
1545 }
1546 let ns = namespace_of(&b.name);
1547 if store.has_bindings_under(ns).map_err(|e| PublishError::at(b.line, e.to_string()))? {
1548 return Err(refuse(format!("{ns} has bindings")));
1549 }
1550 }
1551 Ok(())
1552}
1553
1554fn append_log(log: &Path, written: &Written) -> Result<(), String> {
1556 let line = Value::Object(vec![
1557 ("at".into(), s(&SystemClock.now())),
1558 ("namespaces".into(), Value::Array(written.namespaces.iter().map(|n| s(n)).collect())),
1559 ("starts".into(), Value::Array(written.starts.iter().map(|t| s(t)).collect())),
1560 ])
1561 .to_jcs();
1562 let mut opts = std::fs::OpenOptions::new();
1563 opts.create(true).append(true);
1564 #[cfg(unix)]
1565 {
1566 use std::os::unix::fs::OpenOptionsExt;
1567 opts.mode(0o600);
1568 }
1569 let mut f = opts.open(log).map_err(|e| format!("{}: {e}", log.display()))?;
1570 let mut bytes = line;
1571 bytes.push(b'\n');
1572 f.write_all(&bytes).map_err(|e| format!("{}: {e}", log.display()))
1573}
1574
1575fn write<S: Store + ?Sized>(
1579 store: &S,
1580 ops: &[Op],
1581 cells: impl Fn(&S, &[Op], &mut Published) -> Result<(), String>,
1582) -> Result<(Published, Written), PublishError> {
1583 let mut out = Published::default();
1584 let mut written = Written::default();
1585 let err = |d: String| PublishError::at(0, d);
1586 let mut i = 0;
1587 while i < ops.len() {
1588 match &ops[i] {
1589 Op::Descriptor { hash, bytes, counted } => {
1590 let existed = store.descriptor(hash).is_some();
1591 store.put_descriptor(bytes).map_err(|e| err(e.to_string()))?;
1592 if *counted && !existed {
1593 out.descriptors += 1;
1594 }
1595 }
1596 Op::Function { name, start, hash, bytes, bind } => {
1597 store.put_descriptor(bytes).map_err(|e| err(e.to_string()))?;
1598 if *bind {
1599 store.bind_name(name, hash, start).map_err(|e| err(format!("bind {name}: {e}")))?;
1600 out.functions += 1;
1601 written.bound(name, start);
1602 }
1603 }
1604 Op::Class { name, start, hash, bytes, bind, methods } => {
1605 store.put_class(bytes).map_err(|e| err(e.to_string()))?;
1606 if *bind {
1607 store.bind_class(name, hash, start).map_err(|e| err(format!("bind {name}: {e}")))?;
1608 out.classes += 1;
1609 written.bound(name, start);
1610 for (m, _) in methods {
1611 written.bound(m, start);
1612 }
1613 }
1614 }
1615 Op::Close { name, at } => {
1616 store.close_binding(name, at).map_err(|e| err(format!("close {name}: {e}")))?;
1617 }
1618 Op::Catalog { entry, dictionaries, open_keys, extends, facets, source_name } => {
1619 crate::catalog::store_publisher(
1620 store,
1621 entry,
1622 dictionaries,
1623 open_keys,
1624 extends.as_deref(),
1625 facets,
1626 source_name.as_deref(),
1627 )
1628 .map_err(err)?;
1629 }
1630 Op::Cell { .. } => {
1631 let mut j = i;
1632 while j < ops.len() && j - i < CHUNK && matches!(ops[j], Op::Cell { .. }) {
1633 j += 1;
1634 }
1635 cells(store, &ops[i..j], &mut out).map_err(err)?;
1636 i = j;
1637 continue;
1638 }
1639 }
1640 i += 1;
1641 }
1642 Ok((out, written))
1643}
1644
1645fn write_cells_one_lane<S: Store + ?Sized>(store: &S, group: &[Op], out: &mut Published) -> Result<(), String> {
1649 let items = put_blobs_and_items(store, group, out)?;
1650 let failed = AtomicBool::new(false);
1651 let ks: Vec<usize> = (0..items.len()).collect();
1652 if let Some((_, detail)) = put_lane(store, &items, &ks, &failed) {
1653 return Err(detail);
1654 }
1655 count_cells(group, &items, out);
1656 Ok(())
1657}
1658
1659fn write_cells<S: Store + Sync + ?Sized>(
1665 store: &S,
1666 group: &[Op],
1667 lanes: usize,
1668 out: &mut Published,
1669) -> Result<(), String> {
1670 if lanes <= 1 {
1671 return write_cells_one_lane(store, group, out);
1672 }
1673 let items = put_blobs_and_items(store, group, out)?;
1674 let mut by_lane: Vec<Vec<usize>> = vec![Vec::new(); lanes];
1675 for (k, op) in group.iter().enumerate() {
1676 if let Op::Cell { id, .. } = op {
1677 by_lane[lane_of(id, lanes)].push(k);
1678 }
1679 }
1680 let failed = AtomicBool::new(false);
1681 let failures: Vec<(usize, String)> = std::thread::scope(|scope| {
1682 let handles: Vec<_> = by_lane
1683 .iter()
1684 .map(|ks| {
1685 let (items, failed) = (&items, &failed);
1686 scope.spawn(move || put_lane(store, items, ks, failed))
1687 })
1688 .collect();
1689 handles.into_iter().filter_map(|h| h.join().unwrap_or_else(|p| std::panic::resume_unwind(p))).collect()
1690 });
1691 if let Some((_, detail)) = failures.into_iter().min_by_key(|(k, _)| *k) {
1692 return Err(detail);
1693 }
1694 count_cells(group, &items, out);
1695 Ok(())
1696}
1697
1698fn put_blobs_and_items<'a, S: Store + ?Sized>(
1700 store: &S,
1701 group: &'a [Op],
1702 out: &mut Published,
1703) -> Result<Vec<CellItem<'a>>, String> {
1704 for op in group {
1705 if let Op::Cell { blob: Some(bytes), .. } = op {
1706 store.put_blob(bytes).map_err(|e| e.to_string())?;
1707 out.blobs += 1;
1708 out.blob_bytes += bytes.len() as u64;
1709 }
1710 }
1711 Ok(group
1712 .iter()
1713 .filter_map(|op| match op {
1714 Op::Cell { tx, id, receipt, version, .. } => {
1715 Some((receipt.as_slice(), if *version { Some((id.as_str(), tx.as_str())) } else { None }))
1716 }
1717 _ => None,
1718 })
1719 .collect())
1720}
1721
1722fn count_cells(group: &[Op], items: &[CellItem<'_>], out: &mut Published) {
1724 out.cells += group.len();
1725 out.receipts += group.len();
1726 out.versions += items.iter().filter(|(_, v)| v.is_some()).count();
1727}
1728
1729fn lane_of(id: &str, lanes: usize) -> usize {
1731 id.bytes().next().and_then(|b| (b as char).to_digit(16)).unwrap_or(0) as usize % lanes
1732}
1733
1734type CellItem<'a> = (&'a [u8], Option<(&'a str, &'a str)>);
1736
1737fn put_lane<S: Store + ?Sized>(
1741 store: &S,
1742 items: &[CellItem<'_>],
1743 ks: &[usize],
1744 failed: &AtomicBool,
1745) -> Option<(usize, String)> {
1746 for call in ks.chunks(CHUNK) {
1747 if failed.load(Ordering::SeqCst) {
1748 return None;
1749 }
1750 let writes: Vec<CellWrite<'_>> = call.iter().map(|&k| CellWrite::new(items[k].0, items[k].1)).collect();
1751 if let Err(e) = store.put_cells(&writes) {
1752 failed.store(true, Ordering::SeqCst);
1753 return Some((call[0], e.to_string()));
1754 }
1755 }
1756 None
1757}
1758
1759pub fn receipt_json(r: &datumesh_core::Receipt) -> Vec<u8> {
1761 let mut members = vec![("sig".to_string(), Value::String(r.sig().to_string()))];
1762 if let Ok(Value::Object(m)) = json::parse(r.payload()) {
1763 members.extend(m);
1764 }
1765 Value::Object(members).to_jcs()
1766}
1767
1768pub fn publish_stored<S: Store + ?Sized>(
1773 store: &S,
1774 key: &SigningKey,
1775 host: &str,
1776 path: &Path,
1777) -> Result<Published, PublishError> {
1778 publish_stored_in(store, key, host, &[host.to_string()], path)
1779}
1780
1781pub fn publish_stored_in<S: Store + ?Sized>(
1785 store: &S,
1786 key: &SigningKey,
1787 host: &str,
1788 owned: &[String],
1789 path: &Path,
1790) -> Result<Published, PublishError> {
1791 publish_stored_with(store, key, host, owned, path, &PublishOptions::system())
1792}
1793
1794pub fn publish_stored_with<S: Store + ?Sized>(
1801 store: &S,
1802 key: &SigningKey,
1803 host: &str,
1804 owned: &[String],
1805 path: &Path,
1806 opts: &PublishOptions,
1807) -> Result<Published, PublishError> {
1808 publish_planned(store, key, host, owned, path, opts, false, |s, ops| {
1809 write(s, ops, |s, g, out| write_cells_one_lane(s, g, out))
1810 })
1811}
1812
1813pub fn publish_stored_checked<S: Store + ?Sized>(
1820 store: &S,
1821 key: &SigningKey,
1822 host: &str,
1823 owned: &[String],
1824 path: &Path,
1825 opts: &PublishOptions,
1826) -> Result<Published, PublishError> {
1827 publish_planned(store, key, host, owned, path, opts, true, |s, ops| {
1828 write(s, ops, |s, g, out| write_cells_one_lane(s, g, out))
1829 })
1830}
1831
1832pub fn publish_stored_lanes<S: Store + Sync + ?Sized>(
1837 store: &S,
1838 key: &SigningKey,
1839 host: &str,
1840 owned: &[String],
1841 path: &Path,
1842 opts: &PublishOptions,
1843) -> Result<Published, PublishError> {
1844 let lanes = publish_lanes()?;
1845 publish_planned(store, key, host, owned, path, opts, false, |s, ops| {
1846 write(s, ops, |s, g, out| write_cells(s, g, lanes, out))
1847 })
1848}
1849
1850fn overlay_of(ops: &[Op]) -> Result<Overlay, PublishError> {
1852 let mut overlay = Overlay::default();
1853 for op in ops {
1854 match op {
1855 Op::Function { name, start, hash, bytes, bind } => {
1856 overlay.descriptors.insert(hash.clone(), bytes.clone());
1857 if *bind {
1858 overlay.functions.entry(name.clone()).or_default().push((start.clone(), hash.clone()));
1859 }
1860 }
1861 Op::Descriptor { hash, bytes, .. } => {
1862 overlay.descriptors.insert(hash.clone(), bytes.clone());
1863 }
1864 Op::Cell { receipt, .. } => {
1865 overlay.cell(receipt).map_err(|e| PublishError::at(0, format!("tests: {e}")))?;
1866 }
1867 Op::Class { start, bind, methods, .. } => {
1868 if *bind {
1870 for (m, fh) in methods {
1871 overlay.functions.entry(m.clone()).or_default().push((start.clone(), fh.clone()));
1872 }
1873 }
1874 }
1875 Op::Catalog { .. } | Op::Close { .. } => {}
1876 }
1877 }
1878 Ok(overlay)
1879}
1880
1881#[allow(clippy::too_many_arguments)]
1889pub(crate) fn check_tests<S: Store + ?Sized>(
1890 store: &S,
1891 overlay: &Overlay,
1892 tests: &[(usize, TestSpec)],
1893 formulas: &[(usize, String, String)],
1894 host: &str,
1895 now: &str,
1896 checked: bool,
1897) -> Result<Vec<RowWrite>, PublishError> {
1898 let mut file_tests: Vec<(usize, TestSpec, String)> = Vec::new();
1899 for (n, spec) in tests {
1900 let at = spec.asof.clone().unwrap_or_else(|| now.to_string());
1901 match testrun::binding_of(store, overlay, &spec.function, &at) {
1902 Ok(Some((hash, _))) => file_tests.push((*n, spec.clone(), hash)),
1903 Ok(None) => {
1904 return Err(PublishError::at(
1905 *n,
1906 format!("a test of {}: no function of that name is bound", spec.function),
1907 ))
1908 }
1909 Err(e) => return Err(PublishError::at(*n, e)),
1910 }
1911 }
1912 let mut groups: Vec<(usize, String, String)> = formulas.to_vec();
1914 for (n, spec, hash) in &file_tests {
1915 if !groups.iter().any(|g| &g.2 == hash) {
1916 groups.push((*n, spec.function.clone(), hash.clone()));
1917 }
1918 }
1919 let mut rows = Vec::new();
1920 for (line, name, hash) in &groups {
1921 let own: Vec<(usize, TestSpec)> =
1922 file_tests.iter().filter(|t| &t.2 == hash).map(|t| (t.0, t.1.clone())).collect();
1923 let all_held = testrun::held_of_name(store, hash, name, now).map_err(|e| PublishError::at(*line, e))?;
1925 if !checked && own.is_empty() && all_held.is_empty() {
1926 continue;
1927 }
1928 let mut run = testrun::Run::new(store, overlay, now);
1929 let built = run.built(name, hash).map_err(|e| PublishError::at(*line, format!("{name}: {}", e.0)))?;
1930 if built.compiled.is_some() && !formulas.iter().any(|f| &f.2 == hash) {
1933 continue;
1934 }
1935 let written: BTreeSet<&str> = overlay.cells.iter().filter(|c| &c.name == name).map(|c| c.id.as_str()).collect();
1938 let held: Vec<(FunctionTest, TestSpec, String)> = all_held
1939 .into_iter()
1940 .filter(|(_, _, cell)| built.compiled.is_some() || written.contains(cell.as_str()))
1941 .collect();
1942 let mut specs: Vec<(Option<usize>, TestSpec)> = own.into_iter().map(|(n, s)| (Some(n), s)).collect();
1943 for (_, spec, _) in held {
1944 if !specs.iter().any(|(_, s)| s.case == spec.case) {
1945 specs.push((None, spec));
1946 }
1947 }
1948 let ran: Vec<Ran> = specs.iter().map(|(_, s)| run_test(store, overlay, now, s)).collect();
1949 let Some(compiled) = built.compiled.as_ref() else {
1950 for ((own_n, spec), r) in specs.iter().zip(&ran) {
1953 let (result, detail) = testrun::result_of(spec, r);
1954 rows.push(RowWrite {
1955 fn_hash: hash.clone(),
1956 case: spec.case.clone(),
1957 jcs: spec.jcs.clone(),
1958 signed_by: host.to_string(),
1959 result,
1960 detail,
1961 branches_total: 0,
1962 branches_covered: 0,
1963 fn_name: row_name(*own_n, spec, name),
1964 });
1965 }
1966 continue;
1967 };
1968 if checked {
1969 let mut failing: Vec<(usize, String)> = Vec::new();
1970 for ((n, spec), r) in specs.iter().zip(&ran) {
1971 if let Some(n) = n {
1972 let (result, detail) = testrun::result_of(spec, r);
1973 if result != "pass" {
1974 failing.push((*n, format!("{name}: test {} {detail}", spec.case)));
1975 }
1976 }
1977 }
1978 failing.sort_by_key(|f| f.0);
1979 if let Some((n, detail)) = failing.into_iter().next() {
1980 return Err(PublishError::typed(n, PublishErrorKind::TestsFailing(detail)));
1981 }
1982 let refs: Vec<&Ran> = ran.iter().collect();
1983 let cov = testrun::coverage_of(compiled, &built.function.signature, &refs);
1984 if !cov.uncovered.is_empty() || !cov.unexercised.is_empty() {
1985 let mut text = format!("{name} is missing tests:");
1986 if !cov.uncovered.is_empty() {
1987 let cases: Vec<&str> = cov.uncovered.iter().map(|c| c.0.as_str()).collect();
1988 text += &format!(" uncovered cases {};", cases.join(", "));
1989 }
1990 if !cov.unexercised.is_empty() {
1991 text += &format!(" unexercised branches {}", cov.unexercised.join(", "));
1992 }
1993 return Err(PublishError::typed(
1994 *line,
1995 PublishErrorKind::TestsMissing(text.trim_end_matches(';').to_string()),
1996 ));
1997 }
1998 }
1999 let refs: Vec<&Ran> = ran.iter().collect();
2000 let cov = testrun::coverage_of(compiled, &built.function.signature, &refs);
2001 for ((own_n, spec), r) in specs.iter().zip(&ran) {
2002 let (result, detail) = testrun::result_of(spec, r);
2003 rows.push(RowWrite {
2004 fn_hash: hash.clone(),
2005 case: spec.case.clone(),
2006 jcs: spec.jcs.clone(),
2007 signed_by: host.to_string(),
2008 result,
2009 detail,
2010 branches_total: cov.branches,
2011 branches_covered: cov.covered,
2012 fn_name: row_name(*own_n, spec, name),
2013 });
2014 }
2015 }
2016 Ok(rows)
2017}
2018
2019pub fn publish_stored_checked_lanes<S: Store + Sync + ?Sized>(
2022 store: &S,
2023 key: &SigningKey,
2024 host: &str,
2025 owned: &[String],
2026 path: &Path,
2027 opts: &PublishOptions,
2028) -> Result<Published, PublishError> {
2029 let lanes = publish_lanes()?;
2030 publish_planned(store, key, host, owned, path, opts, true, |s, ops| {
2031 write(s, ops, |s, g, out| write_cells(s, g, lanes, out))
2032 })
2033}
2034
2035#[allow(clippy::too_many_arguments)]
2037fn publish_planned<S: Store + ?Sized>(
2038 store: &S,
2039 key: &SigningKey,
2040 host: &str,
2041 owned: &[String],
2042 path: &Path,
2043 opts: &PublishOptions,
2044 checked: bool,
2045 write_ops: impl FnOnce(&S, &[Op]) -> Result<(Published, Written), PublishError>,
2046) -> Result<Published, PublishError> {
2047 let lines = read_lines(path)?;
2048 let base = path.parent().unwrap_or(Path::new("."));
2049 planned_lines(store, key, host, owned, lines, base, &BTreeMap::new(), false, opts, checked, write_ops)
2050}
2051
2052pub(crate) fn publish_job<S: Store + ?Sized>(
2055 store: &S,
2056 key: &SigningKey,
2057 host: &str,
2058 owned: &[String],
2059 lines: Vec<String>,
2060 blobs: &BTreeMap<String, Vec<u8>>,
2061 opts: &PublishOptions,
2062) -> Result<Published, PublishError> {
2063 let numbered: Vec<(usize, String)> = lines.into_iter().enumerate().map(|(i, l)| (i + 1, l)).collect();
2064 planned_lines(store, key, host, owned, numbered, Path::new("."), blobs, true, opts, false, |s, ops| {
2065 write(s, ops, |s, g, out| write_cells_one_lane(s, g, out))
2066 })
2067}
2068
2069#[allow(clippy::too_many_arguments)]
2071fn planned_lines<S: Store + ?Sized>(
2072 store: &S,
2073 key: &SigningKey,
2074 host: &str,
2075 owned: &[String],
2076 lines: Vec<(usize, String)>,
2077 base: &Path,
2078 blobs: &BTreeMap<String, Vec<u8>>,
2079 job: bool,
2080 opts: &PublishOptions,
2081 checked: bool,
2082 write_ops: impl FnOnce(&S, &[Op]) -> Result<(Published, Written), PublishError>,
2083) -> Result<Published, PublishError> {
2084 let key_from = store
2086 .namespace(host)
2087 .ok()
2088 .flatten()
2089 .and_then(|n| json::parse(&n.keydoc).ok())
2090 .and_then(|d| match d.get("keys") {
2091 Some(Value::Array(ks)) => ks
2092 .iter()
2093 .find(|k| k.get("id").and_then(Value::as_str) == Some(key.key_id()))
2094 .and_then(|k| k.get("valid_from").and_then(Value::as_str).map(str::to_string)),
2095 _ => None,
2096 })
2097 .ok_or_else(|| {
2098 PublishError::at(0, format!("the key {} is not in {host}'s key document in the store", key.key_id()))
2099 })?;
2100 let now = opts.clock.now();
2101 let ctx = Ctx { host, owned, key_from: &key_from, now: &now, base, job, blobs };
2102 let mut planner = Planner {
2103 store,
2104 key,
2105 ctx,
2106 backfill: opts.backfill.is_some(),
2107 sim: Simulation::default(),
2108 reads: Reads::default(),
2109 ops: Vec::new(),
2110 binds: Vec::new(),
2111 tests: Vec::new(),
2112 formulas: Vec::new(),
2113 };
2114 planner.run(&lines)?;
2115 let Planner { ops, binds, tests, formulas, .. } = planner;
2116 if opts.backfill.is_some() {
2117 backfill_check(store, &binds)?;
2118 }
2119 let overlay = overlay_of(&ops)?;
2122 let rows = check_tests(store, &overlay, &tests, &formulas, host, &now, checked)?;
2123 let (out, written) = write_ops(store, &ops)?;
2124 index_cell_values(store, &ops).map_err(|e| PublishError::at(0, format!("catalogue: {e}")))?;
2125 testrun::apply_rows(store, &rows, &now).map_err(|e| PublishError::at(0, format!("tests: {e}")))?;
2126 let rebound: Vec<String> = ops
2127 .iter()
2128 .filter_map(|op| match op {
2129 Op::Function { name, bind: true, .. } => Some(name.clone()),
2130 _ => None,
2131 })
2132 .collect();
2133 testrun::rerun_readers(store, &rebound, &now).map_err(|e| PublishError::at(0, format!("tests: {e}")))?;
2134 let rebound: BTreeSet<String> = rebound.into_iter().collect();
2136 let written_cells: Vec<(String, String)> = overlay.cells.iter().map(|c| (c.name.clone(), c.id.clone())).collect();
2137 testrun::rerun_stored_tests(store, &rebound, &written_cells, &now)
2138 .map_err(|e| PublishError::at(0, format!("tests: {e}")))?;
2139 if let Some(log) = &opts.backfill {
2140 if out.functions + out.classes + out.versions > 0 {
2141 append_log(log, &written).map_err(|e| PublishError::at(0, format!("backfill log: {e}")))?;
2142 }
2143 }
2144 Ok(out)
2145}