1use std::collections::BTreeSet;
45use std::io::{BufRead, Write};
46use std::path::{Path, PathBuf};
47use std::sync::Arc;
48
49use datumesh_core::json::{self, Value};
50use datumesh_core::{Arg, Args, Cell, ClassDescriptor, FunctionDescriptor, ReceiptBuilder, Scalar, SigningKey, Type};
51use datumesh_engine::{Clock, SystemClock};
52use datumesh_formula::definition::{Callee, Callees, ClassCallee};
53use datumesh_store::Store;
54
55const END: &str = "9999-12-31T23:59:59.999999Z";
57
58#[non_exhaustive]
60#[derive(Clone, Debug, Default, PartialEq, Eq)]
61pub struct Published {
62 pub functions: usize,
64 pub classes: usize,
66 pub cells: usize,
68 pub receipts: usize,
70 pub versions: usize,
72 pub blobs: usize,
74 pub blob_bytes: u64,
76}
77
78#[derive(Clone)]
80pub struct PublishOptions {
81 pub clock: Arc<dyn Clock + Send + Sync>,
84 pub backfill: Option<PathBuf>,
88}
89
90impl PublishOptions {
91 pub fn system() -> PublishOptions {
93 PublishOptions { clock: Arc::new(SystemClock), backfill: None }
94 }
95}
96
97#[non_exhaustive]
99#[derive(Clone, Debug, PartialEq, Eq)]
100pub enum PublishErrorKind {
101 Line,
103 StartBeforeNow {
105 name: String,
107 start: String,
109 now: String,
111 },
112 Backfill(String),
114 OwnedVectorName(String),
116}
117
118impl std::fmt::Display for PublishErrorKind {
119 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
120 match self {
121 PublishErrorKind::Line => f.write_str("refused"),
122 PublishErrorKind::StartBeforeNow { name, start, now } => {
123 write!(f, "binding start {start} of {name} is earlier than the mesh clock {now} (rule A)")
124 }
125 PublishErrorKind::Backfill(why) => write!(f, "--backfill refused: {why}"),
126 PublishErrorKind::OwnedVectorName(name) => {
127 write!(f, "{name} is under a namespace the mesh owns: import-vectors does not bind it")
128 }
129 }
130 }
131}
132
133#[derive(Clone, Debug, PartialEq, Eq)]
135pub struct PublishError {
136 pub line: usize,
138 pub detail: String,
140 pub kind: PublishErrorKind,
142}
143
144impl PublishError {
145 fn at(line: usize, detail: impl Into<String>) -> PublishError {
146 PublishError { line, detail: detail.into(), kind: PublishErrorKind::Line }
147 }
148
149 pub(crate) fn typed(line: usize, kind: PublishErrorKind) -> PublishError {
150 PublishError { line, detail: kind.to_string(), kind }
151 }
152}
153
154impl std::fmt::Display for PublishError {
155 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
156 write!(f, "line {}: {}", self.line, self.detail)
157 }
158}
159
160impl std::error::Error for PublishError {}
161
162fn s(v: &str) -> Value {
163 Value::String(v.to_string())
164}
165
166fn namespace_of(name: &str) -> &str {
168 name.rsplit_once('/').map(|(ns, _)| ns).unwrap_or("")
169}
170
171fn definer<'a>(name: &'a str, host: &'a str, owned: &[String]) -> &'a str {
174 let host_of_name = name.split('/').next().unwrap_or("");
175 if owned.iter().any(|o| o == host_of_name) {
176 namespace_of(name)
177 } else {
178 host
179 }
180}
181
182fn bound_of(v: &Value, line: usize, now: &str) -> Result<String, PublishError> {
184 match v.get("bound") {
185 None => Ok(now.to_string()),
186 Some(b) => b.as_str().map(str::to_string).ok_or_else(|| PublishError::at(line, "bound is not an instant")),
187 }
188}
189
190#[derive(Default)]
192struct Simulation {
193 functions: std::collections::BTreeMap<String, Vec<(String, String)>>,
195 classes: std::collections::BTreeMap<String, Vec<(String, String)>>,
197 descriptors: std::collections::BTreeMap<String, Vec<u8>>,
199 class_bytes: std::collections::BTreeMap<String, Vec<u8>>,
201}
202
203impl Simulation {
204 fn latest(
206 binds: &std::collections::BTreeMap<String, Vec<(String, String)>>,
207 name: &str,
208 at: &str,
209 ) -> Option<(String, String)> {
210 binds.get(name)?.iter().filter(|(t, _)| t.as_str() <= at).max_by(|a, b| a.0.cmp(&b.0)).cloned()
211 }
212}
213
214struct Callers<'a, S: Store + ?Sized> {
216 store: &'a S,
217 sim: Option<&'a Simulation>,
218}
219
220impl<S: Store + ?Sized> Callers<'_, S> {
221 fn function_bytes(&self, hash: &str) -> Result<Option<Vec<u8>>, String> {
222 if let Some(b) = self.sim.and_then(|s| s.descriptors.get(hash)) {
223 return Ok(Some(b.clone()));
224 }
225 Ok(self.store.descriptor(hash).map(|b| b.into_owned()))
226 }
227
228 fn class_bytes(&self, hash: &str) -> Result<Option<Vec<u8>>, String> {
229 if let Some(b) = self.sim.and_then(|s| s.class_bytes.get(hash)) {
230 return Ok(Some(b.clone()));
231 }
232 self.store.class(hash).map_err(|e| e.to_string())
233 }
234}
235
236impl<S: Store + ?Sized> Callees for Callers<'_, S> {
237 fn callee(&self, name: &str, at: &str) -> Result<Option<Callee>, String> {
238 let stored = self.store.resolve_binding(name, at).map_err(|e| e.to_string())?;
239 let simmed = self.sim.and_then(|s| Simulation::latest(&s.functions, name, at));
240 let (fn_hash, start) = match (stored, simmed) {
241 (Some(b), Some((t, h))) if t >= b.tx => (h, t),
242 (Some(b), _) => (b.fn_hash, b.tx),
243 (None, Some((t, h))) => (h, t),
244 (None, None) => return Ok(None),
245 };
246 let bytes = self.function_bytes(&fn_hash)?.ok_or_else(|| format!("descriptor {fn_hash} is not stored"))?;
247 let descriptor = json::parse(&bytes).map_err(|e| e.to_string())?;
248 Ok(Some(Callee { fn_hash, start, descriptor }))
249 }
250
251 fn bound_class(&self, name: &str, at: &str) -> Result<Option<ClassCallee>, String> {
252 let stored = self.store.resolve_class_binding(name, at).map_err(|e| e.to_string())?;
253 let simmed = self.sim.and_then(|s| Simulation::latest(&s.classes, name, at));
254 let (class_hash, start) = match (stored, simmed) {
255 (Some(b), Some((t, h))) if t >= b.tx => (h, t),
256 (Some(b), _) => (b.class_hash, b.tx),
257 (None, Some((t, h))) => (h, t),
258 (None, None) => return Ok(None),
259 };
260 let bytes = self.class_bytes(&class_hash)?.ok_or_else(|| format!("class {class_hash} is not stored"))?;
261 let descriptor = ClassDescriptor::from_json(&bytes).map_err(|e| e.to_string())?;
262 Ok(Some(ClassCallee { class_hash, start, descriptor }))
263 }
264
265 fn class_descriptor(&self, class_hash: &str) -> Result<Option<ClassDescriptor>, String> {
266 let Some(bytes) = self.class_bytes(class_hash)? else { return Ok(None) };
267 ClassDescriptor::from_json(&bytes).map(Some).map_err(|e| e.to_string())
268 }
269
270 fn function_descriptor(&self, fn_hash: &str) -> Result<Option<Value>, String> {
271 let Some(bytes) = self.function_bytes(fn_hash)? else { return Ok(None) };
272 json::parse(&bytes).map(Some).map_err(|e| e.to_string())
273 }
274}
275
276fn current_function<S: Store + ?Sized>(store: &S, sim: &Simulation, name: &str) -> Result<Option<String>, String> {
278 if let Some((_, h)) = Simulation::latest(&sim.functions, name, END) {
279 return Ok(Some(h));
280 }
281 store.resolve_name(name, END).map_err(|e| e.to_string())
282}
283
284fn current_class<S: Store + ?Sized>(store: &S, sim: &Simulation, name: &str) -> Result<Option<String>, String> {
286 if let Some((_, h)) = Simulation::latest(&sim.classes, name, END) {
287 return Ok(Some(h));
288 }
289 store.resolve_class(name, END).map_err(|e| e.to_string())
290}
291
292struct Bind {
294 line: usize,
295 name: String,
296}
297
298fn record(
300 binds: &mut Vec<Bind>,
301 line: usize,
302 name: &str,
303 start: &str,
304 now: &str,
305 backfill: bool,
306) -> Result<(), PublishError> {
307 if !backfill && start < now {
308 return Err(PublishError::typed(
309 line,
310 PublishErrorKind::StartBeforeNow { name: name.into(), start: start.into(), now: now.into() },
311 ));
312 }
313 binds.push(Bind { line, name: name.into() });
314 Ok(())
315}
316
317#[derive(Default)]
319struct Written {
320 namespaces: BTreeSet<String>,
321 starts: BTreeSet<String>,
322}
323
324impl Written {
325 fn bound(&mut self, name: &str, start: &str) {
326 self.namespaces.insert(namespace_of(name).to_string());
327 self.starts.insert(start.to_string());
328 }
329}
330
331struct Ctx<'a> {
333 host: &'a str,
334 owned: &'a [String],
335 key_from: &'a str,
337 now: &'a str,
339 base: &'a Path,
341}
342
343fn read_lines(path: &Path) -> Result<Vec<(usize, String)>, PublishError> {
345 let file = std::fs::File::open(path).map_err(|e| PublishError::at(0, format!("{}: {e}", path.display())))?;
346 let mut out = Vec::new();
347 for (i, line) in std::io::BufReader::new(file).lines().enumerate() {
348 let n = i + 1;
349 let line = line.map_err(|e| PublishError::at(n, e.to_string()))?;
350 if !line.trim().is_empty() {
351 out.push((n, line));
352 }
353 }
354 Ok(out)
355}
356
357fn plan<S: Store + ?Sized>(
359 store: &S,
360 ctx: &Ctx<'_>,
361 lines: &[(usize, String)],
362 backfill: bool,
363) -> Result<Vec<Bind>, PublishError> {
364 let mut sim = Simulation::default();
365 let mut binds = Vec::new();
366 for (n, text) in lines {
367 let n = *n;
368 let err = |d: String| PublishError::at(n, d);
369 let v = json::parse(text.as_bytes()).map_err(|e| err(e.to_string()))?;
370 if let Some(name) = v.get("class").and_then(Value::as_str) {
371 let descriptor = v.get("descriptor").ok_or_else(|| err("a class without descriptor".into()))?;
372 let start = bound_of(&v, n, ctx.now)?;
373 let def = datumesh_formula::definition::define_class(
374 name,
375 &descriptor.to_jcs(),
376 definer(name, ctx.host, ctx.owned),
377 &Callers { store, sim: Some(&sim) },
378 &start,
379 )
380 .map_err(|e| err(format!("define {name}: {e}")))?;
381 if current_class(store, &sim, name).map_err(err)?.as_deref() != Some(def.class_hash.as_str()) {
382 record(&mut binds, n, name, &start, ctx.now, backfill)?;
383 sim.classes.entry(name.to_string()).or_default().push((start.clone(), def.class_hash.clone()));
384 sim.class_bytes.insert(def.class_hash.clone(), def.bytes.clone());
385 for (m, fh) in &def.descriptor.methods {
387 let mname = format!("{name}/{m}");
388 if current_function(store, &sim, &mname).map_err(err)?.as_deref() != Some(fh.as_str()) {
389 record(&mut binds, n, &mname, &start, ctx.now, backfill)?;
390 sim.functions.entry(mname).or_default().push((start.clone(), fh.clone()));
391 }
392 }
393 }
394 continue;
395 }
396 let function = if let Some(name) = v.get("function").and_then(Value::as_str) {
397 let sig = v.get("signature").ok_or_else(|| err("a function without a signature".into()))?;
398 let start = bound_of(&v, n, ctx.now)?;
399 let d = Value::Object(vec![
400 ("code".into(), Value::Object(vec![("body".into(), s("")), ("lang".into(), s("stored"))])),
401 ("inputs".into(), Value::Array(vec![])),
402 ("signature".into(), sig.clone()),
403 ]);
404 let fd = FunctionDescriptor::from_value(&d).map_err(|e| err(e.to_string()))?;
405 Some((name, start, fd.hash(), fd.canonical()))
406 } else if let Some(name) = v.get("formula").and_then(Value::as_str) {
407 let source =
408 v.get("source").and_then(Value::as_str).ok_or_else(|| err("a formula without source".into()))?;
409 let sig = v.get("signature").ok_or_else(|| err("a formula without a signature".into()))?;
410 let start = bound_of(&v, n, ctx.now)?;
411 let def = datumesh_formula::definition::define_function(
412 name,
413 source,
414 sig,
415 &Default::default(),
416 &Callers { store, sim: Some(&sim) },
417 &start,
418 )
419 .map_err(|e| err(format!("define {name}: {e}")))?;
420 Some((name, start, def.fn_hash, def.bytes))
421 } else if v.get("cell").is_none() {
422 return Err(err("neither a function nor a cell".into()));
423 } else {
424 None
425 };
426 if let Some((name, start, h, bytes)) = function {
427 if current_function(store, &sim, name).map_err(err)?.as_deref() != Some(h.as_str()) {
428 record(&mut binds, n, name, &start, ctx.now, backfill)?;
429 sim.functions.entry(name.to_string()).or_default().push((start, h.clone()));
430 sim.descriptors.insert(h, bytes);
431 }
432 }
433 }
434 Ok(binds)
435}
436
437fn backfill_check<S: Store + ?Sized>(store: &S, binds: &[Bind]) -> Result<(), PublishError> {
440 for b in binds {
441 let refuse = |why: String| PublishError::typed(b.line, PublishErrorKind::Backfill(why));
442 if store.resolve_binding(&b.name, END).map_err(|e| PublishError::at(b.line, e.to_string()))?.is_some() {
443 return Err(refuse(format!("{} has a binding", b.name)));
444 }
445 let ns = namespace_of(&b.name);
446 if store.has_bindings_under(ns).map_err(|e| PublishError::at(b.line, e.to_string()))? {
447 return Err(refuse(format!("{ns} has bindings")));
448 }
449 }
450 Ok(())
451}
452
453fn append_log(log: &Path, written: &Written) -> Result<(), String> {
455 let line = Value::Object(vec![
456 ("at".into(), s(&SystemClock.now())),
457 ("namespaces".into(), Value::Array(written.namespaces.iter().map(|n| s(n)).collect())),
458 ("starts".into(), Value::Array(written.starts.iter().map(|t| s(t)).collect())),
459 ])
460 .to_jcs();
461 let mut opts = std::fs::OpenOptions::new();
462 opts.create(true).append(true);
463 #[cfg(unix)]
464 {
465 use std::os::unix::fs::OpenOptionsExt;
466 opts.mode(0o600);
467 }
468 let mut f = opts.open(log).map_err(|e| format!("{}: {e}", log.display()))?;
469 let mut bytes = line;
470 bytes.push(b'\n');
471 f.write_all(&bytes).map_err(|e| format!("{}: {e}", log.display()))
472}
473
474fn write<S: Store + ?Sized>(
476 store: &S,
477 key: &SigningKey,
478 ctx: &Ctx<'_>,
479 lines: &[(usize, String)],
480) -> Result<(Published, Written), PublishError> {
481 let mut out = Published::default();
482 let mut written = Written::default();
483 for (n, text) in lines {
484 let n = *n;
485 let err = |d: String| PublishError::at(n, d);
486 let v = json::parse(text.as_bytes()).map_err(|e| err(e.to_string()))?;
487 if let Some(name) = v.get("class").and_then(Value::as_str) {
488 let descriptor = v.get("descriptor").ok_or_else(|| err("a class without descriptor".into()))?;
489 let start = bound_of(&v, n, ctx.now)?;
490 let def = datumesh_formula::definition::define_class(
491 name,
492 &descriptor.to_jcs(),
493 definer(name, ctx.host, ctx.owned),
494 &Callers { store, sim: None },
495 &start,
496 )
497 .map_err(|e| err(format!("define {name}: {e}")))?;
498 let bound_hash = store.put_class(&def.bytes).map_err(|e| err(e.to_string()))?;
499 match store.resolve_class(name, END).map_err(|e| err(e.to_string()))? {
500 Some(h) if h == bound_hash => {}
501 _ => {
502 store.bind_class(name, &bound_hash, &start).map_err(|e| err(format!("bind {name}: {e}")))?;
503 out.classes += 1;
504 written.bound(name, &start);
505 for m in def.descriptor.methods.keys() {
506 written.bound(&format!("{name}/{m}"), &start);
507 }
508 }
509 }
510 continue;
511 }
512 if let Some(name) = v.get("function").and_then(Value::as_str) {
513 let sig = v.get("signature").ok_or_else(|| err("a function without a signature".into()))?;
514 let start = bound_of(&v, n, ctx.now)?;
515 let d = Value::Object(vec![
516 ("code".into(), Value::Object(vec![("body".into(), s("")), ("lang".into(), s("stored"))])),
517 ("inputs".into(), Value::Array(vec![])),
518 ("signature".into(), sig.clone()),
519 ]);
520 let fd = FunctionDescriptor::from_value(&d).map_err(|e| err(e.to_string()))?;
521 let h = store.put_descriptor(&fd.canonical()).map_err(|e| err(e.to_string()))?;
522 match store.resolve_binding(name, END).map_err(|e| err(e.to_string()))? {
523 Some(b) if b.fn_hash == h => {}
524 _ => {
525 store.bind_name(name, &h, &start).map_err(|e| err(format!("bind {name}: {e}")))?;
526 out.functions += 1;
527 written.bound(name, &start);
528 }
529 }
530 continue;
531 }
532 if let Some(name) = v.get("formula").and_then(Value::as_str) {
533 let source =
534 v.get("source").and_then(Value::as_str).ok_or_else(|| err("a formula without source".into()))?;
535 let sig = v.get("signature").ok_or_else(|| err("a formula without a signature".into()))?;
536 let start = bound_of(&v, n, ctx.now)?;
537 let def = datumesh_formula::definition::define_function(
538 name,
539 source,
540 sig,
541 &Default::default(),
542 &Callers { store, sim: None },
543 &start,
544 )
545 .map_err(|e| err(format!("define {name}: {e}")))?;
546 let h = store.put_descriptor(&def.bytes).map_err(|e| err(e.to_string()))?;
547 match store.resolve_binding(name, END).map_err(|e| err(e.to_string()))? {
548 Some(b) if b.fn_hash == h => {}
549 _ => {
550 store.bind_name(name, &h, &start).map_err(|e| err(format!("bind {name}: {e}")))?;
551 out.functions += 1;
552 written.bound(name, &start);
553 }
554 }
555 continue;
556 }
557 let cell_v = v.get("cell").ok_or_else(|| err("neither a function nor a cell".into()))?;
558 let name = cell_v.get("fn").and_then(Value::as_str).ok_or_else(|| err("a cell without fn".into()))?;
559 let (ns, f) = name.rsplit_once('/').ok_or_else(|| err(format!("{name}: not a function name")))?;
560 let field =
561 |k: &str| v.get(k).and_then(Value::as_str).map(str::to_string).ok_or_else(|| err(format!("no {k}")));
562 let (tx, asof, licence, summary) = (field("tx")?, field("asof")?, field("licence")?, field("summary")?);
563 let issued = v
564 .get("issued")
565 .and_then(Value::as_str)
566 .map(str::to_string)
567 .unwrap_or_else(|| std::cmp::max(asof.clone(), ctx.key_from.to_string()));
568 let fn_hash = store
569 .resolve_name(name, &tx)
570 .map_err(|e| err(e.to_string()))?
571 .ok_or_else(|| err(format!("{name} is not bound as of {tx}")))?;
572 let d = store.descriptor(&fn_hash).ok_or_else(|| err(format!("no descriptor {fn_hash}")))?;
573 let d = FunctionDescriptor::from_json(&d).map_err(|e| err(e.to_string()))?;
574 let mut args = Args::new();
575 for (k, a) in cell_v.get("args").and_then(Value::as_object).ok_or_else(|| err("a cell without args".into()))? {
576 args.insert(k.clone(), Arg::Value(Scalar::from_json(&a.to_jcs()).map_err(|e| err(format!("{k}: {e}")))?));
577 }
578 let valid: Args = args
579 .iter()
580 .filter(|(k, _)| d.signature.args.get(*k).is_some_and(|x| x.valid))
581 .map(|(k, a)| (k.clone(), a.clone()))
582 .collect();
583 let value_v = v.get("value").ok_or_else(|| err("a cell without value".into()))?;
584 let value = match value_v.get("blob").and_then(Value::as_str) {
585 Some(file) => {
586 let media = value_v.get("media_type").and_then(Value::as_str).unwrap_or("application/octet-stream");
587 let bytes = std::fs::read(ctx.base.join(file)).map_err(|e| err(format!("{file}: {e}")))?;
588 let sha = store.put_blob(&bytes).map_err(|e| err(e.to_string()))?;
589 out.blobs += 1;
590 out.blob_bytes += bytes.len() as u64;
591 Scalar::from_lexical(Type::Blob, &format!("{sha}:{}:{media}", bytes.len()))
592 .map_err(|e| err(e.to_string()))?
593 }
594 None => Scalar::from_json(&value_v.to_jcs()).map_err(|e| err(e.to_string()))?,
595 };
596 let cell = Cell { ns: ns.to_string(), fn_name: f.to_string(), fn_hash, args };
597 let r = ReceiptBuilder::new()
598 .cell(cell.clone())
599 .value(value)
600 .valid(valid)
601 .asof(asof.as_str())
602 .tx(tx.as_str())
603 .issued(issued.as_str())
604 .publisher(ns)
605 .signer_host(ctx.host)
606 .licence(licence.as_str())
607 .summary(summary.as_str())
608 .sign(key)
609 .map_err(|e| err(e.to_string()))?;
610 let h = store.put_receipt(&receipt_json(&r)).map_err(|e| err(e.to_string()))?;
611 out.cells += 1;
612 out.receipts += 1;
613 let id = cell.id();
614 match store.latest(&id).map_err(|e| err(e.to_string()))? {
615 Some(l) if l.tx.as_str() >= tx.as_str() => {
616 if store.version_asof(&id, &tx).ok().flatten().is_none_or(|v| v.receipt_hash != h) {
617 return Err(err(format!("{id} has a version at or after {tx} that is not this receipt")));
618 }
619 }
620 _ => {
621 store.put_version(&id, &tx, &h).map_err(|e| err(e.to_string()))?;
622 out.versions += 1;
623 }
624 }
625 }
626 Ok((out, written))
627}
628
629pub fn receipt_json(r: &datumesh_core::Receipt) -> Vec<u8> {
631 let mut members = vec![("sig".to_string(), Value::String(r.sig().to_string()))];
632 if let Ok(Value::Object(m)) = json::parse(r.payload()) {
633 members.extend(m);
634 }
635 Value::Object(members).to_jcs()
636}
637
638pub fn publish_stored<S: Store + ?Sized>(
642 store: &S,
643 key: &SigningKey,
644 host: &str,
645 path: &Path,
646) -> Result<Published, PublishError> {
647 publish_stored_in(store, key, host, &[host.to_string()], path)
648}
649
650pub fn publish_stored_in<S: Store + ?Sized>(
654 store: &S,
655 key: &SigningKey,
656 host: &str,
657 owned: &[String],
658 path: &Path,
659) -> Result<Published, PublishError> {
660 publish_stored_with(store, key, host, owned, path, &PublishOptions::system())
661}
662
663pub fn publish_stored_with<S: Store + ?Sized>(
669 store: &S,
670 key: &SigningKey,
671 host: &str,
672 owned: &[String],
673 path: &Path,
674 opts: &PublishOptions,
675) -> Result<Published, PublishError> {
676 let lines = read_lines(path)?;
677 let key_from = store
679 .namespace(host)
680 .ok()
681 .flatten()
682 .and_then(|n| json::parse(&n.keydoc).ok())
683 .and_then(|d| match d.get("keys") {
684 Some(Value::Array(ks)) => ks
685 .iter()
686 .find(|k| k.get("id").and_then(Value::as_str) == Some(key.key_id()))
687 .and_then(|k| k.get("valid_from").and_then(Value::as_str).map(str::to_string)),
688 _ => None,
689 })
690 .ok_or_else(|| {
691 PublishError::at(0, format!("the key {} is not in {host}'s key document in the store", key.key_id()))
692 })?;
693 let now = opts.clock.now();
694 let ctx = Ctx { host, owned, key_from: &key_from, now: &now, base: path.parent().unwrap_or(Path::new(".")) };
695 let binds = plan(store, &ctx, &lines, opts.backfill.is_some())?;
696 if opts.backfill.is_some() {
697 backfill_check(store, &binds)?;
698 }
699 let (out, written) = write(store, key, &ctx, &lines)?;
700 if let Some(log) = &opts.backfill {
701 if out.functions + out.classes + out.versions > 0 {
702 append_log(log, &written).map_err(|e| PublishError::at(0, format!("backfill log: {e}")))?;
703 }
704 }
705 Ok(out)
706}