Resume native editor jobs through verified checkpoints
This commit is contained in:
1 parent
31364ae33e
commit
0abf700817
19 files changed
+2311
-93
No files matched your search
+571
-29
@@ -14,7 +14,9 @@ use std::{
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
use texrra_tex_core::artifacts::{ArtifactLedger, file_version};
|
||||
use texrra_tex_core::execution::{JobTime, SourceFile, SourceProvider, WriteDestination};
|
||||
use texrra_tex_core::execution::{
|
||||
JobTime, NativeSession, SourceFile, SourceProvider, WriteDestination,
|
||||
};
|
||||
use texrra_tex_core::resources::{FileWorld, LoadedResource, ResourceKind, ResourceVersion};
|
||||
|
||||
pub fn job_time() -> Result<JobTime, String> {
|
||||
@@ -81,6 +83,24 @@ pub struct HostPreparationFailure {
|
||||
pub trace: texrra_tex_core::resources::ResourceTrace,
|
||||
pub inputs: std::sync::Arc<texrra_tex_core::resources::InputSnapshot>,
|
||||
}
|
||||
pub(crate) type PreparedInputsCheck<'a> =
|
||||
dyn FnOnce(&FileWorld, &HostPreparation) -> Result<(), String> + 'a;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum EffectMode {
|
||||
Live,
|
||||
Draft,
|
||||
}
|
||||
|
||||
struct DraftEffects {
|
||||
log: DraftArtifact,
|
||||
generated: BTreeMap<PathBuf, DraftArtifact>,
|
||||
ledger_target: DraftDestination,
|
||||
ledger: Option<PreparedOutput>,
|
||||
pdf: DraftDestination,
|
||||
finished: bool,
|
||||
}
|
||||
|
||||
pub struct Files {
|
||||
world: FileWorld,
|
||||
cwd: PathBuf,
|
||||
@@ -90,6 +110,7 @@ pub struct Files {
|
||||
stream_io: StreamJournal,
|
||||
log_path: PathBuf,
|
||||
log: Option<File>,
|
||||
draft: Option<DraftEffects>,
|
||||
protected: Vec<PathBuf>,
|
||||
producer: PathBuf,
|
||||
ledger: ArtifactLedger,
|
||||
@@ -142,6 +163,8 @@ impl Files {
|
||||
terminal: bool,
|
||||
generated_inputs: &GeneratedInputPolicy,
|
||||
preparation: &mut HostPreparation,
|
||||
check_inputs: Option<Box<PreparedInputsCheck<'_>>>,
|
||||
effects: EffectMode,
|
||||
) -> Result<Self, HostPreparationFailure> {
|
||||
preparation.phase = HostPreparationPhase::Environment;
|
||||
let state = preparation
|
||||
@@ -181,6 +204,8 @@ impl Files {
|
||||
terminal,
|
||||
generated_inputs,
|
||||
preparation,
|
||||
check_inputs,
|
||||
effects,
|
||||
)
|
||||
}
|
||||
#[cfg(test)]
|
||||
@@ -198,6 +223,8 @@ impl Files {
|
||||
true,
|
||||
&GeneratedInputPolicy::Live,
|
||||
&mut HostPreparation::default(),
|
||||
None,
|
||||
EffectMode::Live,
|
||||
)
|
||||
.map_err(|f| f.error)
|
||||
}
|
||||
@@ -209,6 +236,8 @@ impl Files {
|
||||
terminal: bool,
|
||||
generated_inputs: &GeneratedInputPolicy,
|
||||
preparation: &mut HostPreparation,
|
||||
check_inputs: Option<Box<PreparedInputsCheck<'_>>>,
|
||||
effects: EffectMode,
|
||||
) -> Result<Self, HostPreparationFailure> {
|
||||
// Keep the world until all fallible preparation has succeeded. Failure
|
||||
// must return its final actual observations rather than an earlier copy.
|
||||
@@ -411,14 +440,51 @@ impl Files {
|
||||
expected.check(&actual)?;
|
||||
}
|
||||
}
|
||||
if let Some(check_inputs) = check_inputs {
|
||||
check_inputs(world, preparation)?;
|
||||
}
|
||||
if effects == EffectMode::Draft
|
||||
&& (world.project().is_none()
|
||||
|| terminal
|
||||
|| preparation.generated_initial.is_none())
|
||||
{
|
||||
return Err(
|
||||
"draft effects require an atomic project, observed generated versions and no terminal sink".into(),
|
||||
);
|
||||
}
|
||||
preparation.phase = HostPreparationPhase::Log;
|
||||
// An input job really opens a transcript/terminal input entry. Keep
|
||||
// the resulting partial-line state; a later log-only diagnostic must
|
||||
// resume both streams from this actual output, even without message.
|
||||
let entry = format!("({}", source.display());
|
||||
let opened = File::create(&log_path);
|
||||
let opened = if effects == EffectMode::Draft {
|
||||
(|| {
|
||||
let pdf = DraftDestination::capture(&pdf)?;
|
||||
let ledger_target = DraftDestination::capture(&ledger_path)?;
|
||||
if ledger_target.version != ledger_input {
|
||||
return Err("native generated-file ledger changed before drafting".into());
|
||||
}
|
||||
let target = DraftDestination::capture(&log_path)?;
|
||||
let (staged, file) = PreparedOutput::draft(&log_path)?;
|
||||
Ok((
|
||||
file,
|
||||
Some(DraftEffects {
|
||||
log: DraftArtifact { target, staged },
|
||||
generated: BTreeMap::new(),
|
||||
ledger_target,
|
||||
ledger: None,
|
||||
pdf,
|
||||
finished: false,
|
||||
}),
|
||||
))
|
||||
})()
|
||||
} else {
|
||||
File::create(&log_path)
|
||||
.map(|file| (file, None))
|
||||
.map_err(|e| format!("native log {}: {e}", log_path.display()))
|
||||
};
|
||||
preparation.operation("open log", &log_path, &opened);
|
||||
let mut log = opened.map_err(|e| format!("native log {}: {e}", log_path.display()))?;
|
||||
let (mut log, draft) = opened?;
|
||||
let written = log.write_all(entry.as_bytes());
|
||||
preparation.operation("write log entry", &log_path, &written);
|
||||
written.map_err(|e| e.to_string())?;
|
||||
@@ -435,6 +501,7 @@ impl Files {
|
||||
stream_io: StreamJournal::default(),
|
||||
log_path,
|
||||
log: Some(log),
|
||||
draft,
|
||||
protected,
|
||||
producer: source.to_owned(),
|
||||
ledger,
|
||||
@@ -475,7 +542,21 @@ impl Files {
|
||||
path: &Path,
|
||||
expected: Option<Option<ResourceVersion>>,
|
||||
) -> Result<Option<ResourceVersion>, String> {
|
||||
let observed = file_version(path);
|
||||
let observed = (|| {
|
||||
let storage = if path == self.ledger_path {
|
||||
self.draft.as_ref().and_then(|draft| draft.ledger.as_ref())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(storage) = storage {
|
||||
return storage.version(path).map(Some);
|
||||
}
|
||||
let mut observed = file_version(self.world.generated_storage(path))?;
|
||||
if let Some(version) = &mut observed {
|
||||
version.path = path.to_owned();
|
||||
}
|
||||
Ok(observed)
|
||||
})();
|
||||
self.runtime_observations.borrow_mut().observations.push(
|
||||
crate::native_host::HostObservation::VersionCheck {
|
||||
path: path.into(),
|
||||
@@ -555,6 +636,20 @@ impl Files {
|
||||
pub fn input_snapshot(&self) -> std::sync::Arc<texrra_tex_core::resources::InputSnapshot> {
|
||||
self.world.input_snapshot()
|
||||
}
|
||||
#[cfg(test)]
|
||||
pub(crate) fn draft_paths(&self) -> BTreeMap<PathBuf, PathBuf> {
|
||||
let draft = self.draft.as_ref().expect("draft-mode host");
|
||||
let mut paths: BTreeMap<_, _> = draft
|
||||
.generated
|
||||
.iter()
|
||||
.map(|(path, draft)| (path.clone(), draft.staged.path.clone()))
|
||||
.collect();
|
||||
paths.insert(self.log_path.clone(), draft.log.staged.path.clone());
|
||||
if let Some(ledger) = &draft.ledger {
|
||||
paths.insert(self.ledger_path.clone(), ledger.path.clone());
|
||||
}
|
||||
paths
|
||||
}
|
||||
pub fn check_layout_manifest_path(
|
||||
&self,
|
||||
layout: &Path,
|
||||
@@ -730,6 +825,13 @@ impl Files {
|
||||
}
|
||||
fn persist_ledger(&mut self) -> Result<(), String> {
|
||||
let path = self.ledger_path.clone();
|
||||
if let Some(draft) = self.draft.as_mut() {
|
||||
draft.ledger_target.verify()?;
|
||||
let staged = PreparedOutput::write(&path, &self.ledger.encode()?)?;
|
||||
self.ledger_current = Some(staged.version(&path)?);
|
||||
draft.ledger = Some(staged);
|
||||
return Ok(());
|
||||
}
|
||||
if self.observe_version(&path, Some(self.ledger_current.clone()))? != self.ledger_current {
|
||||
return Err("native generated-file ledger changed during the job".into());
|
||||
}
|
||||
@@ -750,6 +852,44 @@ impl Files {
|
||||
}
|
||||
self.persist_ledger()
|
||||
}
|
||||
fn open_generated_output(
|
||||
&mut self,
|
||||
path: &Path,
|
||||
before: &Option<ResourceVersion>,
|
||||
) -> Result<File, String> {
|
||||
let Some(draft) = self.draft.as_mut() else {
|
||||
return OpenOptions::new()
|
||||
.create(true)
|
||||
.truncate(true)
|
||||
.write(true)
|
||||
.open(path)
|
||||
.map_err(|e| format!("openout {}: {e}", path.display()));
|
||||
};
|
||||
if let Some(staged) = draft.generated.get(path) {
|
||||
return OpenOptions::new()
|
||||
.truncate(true)
|
||||
.write(true)
|
||||
.open(&staged.staged.path)
|
||||
.map_err(|e| format!("openout {}: {e}", path.display()));
|
||||
}
|
||||
if self.inputs.values().any(|input| input.path == path) {
|
||||
return Err("cannot stage a generated file with a live input handle".into());
|
||||
}
|
||||
let target = DraftDestination::capture(path)?;
|
||||
if &target.version != before {
|
||||
return Err(format!(
|
||||
"generated output changed before drafting: {}",
|
||||
path.display()
|
||||
));
|
||||
}
|
||||
let (staged, file) = PreparedOutput::draft(path)?;
|
||||
self.world.mark_live(path);
|
||||
self.world.stage_generated(path, staged.path.clone())?;
|
||||
draft
|
||||
.generated
|
||||
.insert(path.to_owned(), DraftArtifact { target, staged });
|
||||
Ok(file)
|
||||
}
|
||||
fn handle_id(&mut self) -> u64 {
|
||||
self.next_handle += 1;
|
||||
self.next_handle
|
||||
@@ -811,8 +951,12 @@ impl Files {
|
||||
if destination != WriteDestination::TerminalOnly {
|
||||
if self.log.is_none() {
|
||||
self.log = Some(
|
||||
File::create(&self.log_path)
|
||||
.map_err(|e| format!("native log {}: {e}", self.log_path.display()))?,
|
||||
File::create(
|
||||
self.draft
|
||||
.as_ref()
|
||||
.map_or(&self.log_path, |draft| &draft.log.staged.path),
|
||||
)
|
||||
.map_err(|e| format!("native log {}: {e}", self.log_path.display()))?,
|
||||
);
|
||||
}
|
||||
let log = self.log.as_mut().unwrap();
|
||||
@@ -836,6 +980,9 @@ impl Files {
|
||||
/// Close actual handles and retain partial writes after failure. No normal
|
||||
/// success footer or rollback is invented; cleanup errors remain separate.
|
||||
pub fn finish_failed(&mut self) -> Vec<String> {
|
||||
if let Some(draft) = &mut self.draft {
|
||||
draft.finished = false;
|
||||
}
|
||||
let mut errors = Vec::new();
|
||||
self.cleanup_boundary(ReleaseCause::FailureCleanup);
|
||||
for stream in self.outputs.keys().copied().collect::<Vec<_>>() {
|
||||
@@ -900,8 +1047,78 @@ impl Files {
|
||||
}
|
||||
self.persist_ledger()?;
|
||||
}
|
||||
if let Some(draft) = &mut self.draft {
|
||||
draft.finished = true;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn seal_draft(
|
||||
mut self,
|
||||
pdf: Option<PreparedOutput>,
|
||||
) -> Result<DraftPublication, String> {
|
||||
let draft = self.draft.take().ok_or("native draft host required")?;
|
||||
if !draft.finished {
|
||||
return Err("native draft must finish successfully before publication".into());
|
||||
}
|
||||
if let Some(log) = self.log.take() {
|
||||
log.sync_all()
|
||||
.map_err(|e| format!("sync native draft log: {e}"))?;
|
||||
}
|
||||
let initial = self
|
||||
.preparation
|
||||
.generated_initial
|
||||
.as_ref()
|
||||
.ok_or("native draft lacks generated initial versions")?;
|
||||
for (path, artifact) in &draft.generated {
|
||||
if initial
|
||||
.files()
|
||||
.get(path)
|
||||
.is_some_and(|v| *v != artifact.target.version)
|
||||
{
|
||||
return Err(format!(
|
||||
"native draft output changed after preparation: {}",
|
||||
path.display()
|
||||
));
|
||||
}
|
||||
}
|
||||
let mut untouched = initial
|
||||
.files()
|
||||
.iter()
|
||||
.filter(|(path, _)| !draft.generated.contains_key(*path))
|
||||
.map(|(path, version)| (path.clone(), version.clone()))
|
||||
.collect::<BTreeMap<_, _>>();
|
||||
let mut artifacts: Vec<_> = draft.generated.into_values().collect();
|
||||
for artifact in &artifacts {
|
||||
OpenOptions::new()
|
||||
.write(true)
|
||||
.open(&artifact.staged.path)
|
||||
.and_then(|file| file.sync_all())
|
||||
.map_err(|e| {
|
||||
format!("sync native draft {}: {e}", artifact.target.path.display())
|
||||
})?;
|
||||
}
|
||||
artifacts.push(draft.log);
|
||||
if let Some(staged) = draft.ledger {
|
||||
artifacts.push(DraftArtifact {
|
||||
target: draft.ledger_target,
|
||||
staged,
|
||||
});
|
||||
} else {
|
||||
untouched.insert(draft.ledger_target.path, draft.ledger_target.version);
|
||||
}
|
||||
if let Some(staged) = pdf {
|
||||
artifacts.push(DraftArtifact {
|
||||
target: draft.pdf,
|
||||
staged,
|
||||
});
|
||||
}
|
||||
Ok(DraftPublication {
|
||||
artifacts,
|
||||
untouched,
|
||||
_host: self,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Files {
|
||||
@@ -1075,7 +1292,7 @@ impl SourceProvider for Files {
|
||||
InputStorage::Snapshot(snapshot.version),
|
||||
)
|
||||
} else {
|
||||
let file = File::open(&path).map_err(|e| {
|
||||
let file = File::open(self.world.generated_storage(&path)).map_err(|e| {
|
||||
let error = format!("openin {}: {e}", path.display());
|
||||
self.world.observe_read_error(&path, error.clone());
|
||||
error
|
||||
@@ -1186,13 +1403,9 @@ impl SourceProvider for Files {
|
||||
path.display()
|
||||
));
|
||||
}
|
||||
let opened = OpenOptions::new()
|
||||
.create(true)
|
||||
.truncate(true)
|
||||
.write(true)
|
||||
.open(&path);
|
||||
let opened = self.open_generated_output(&path, &before);
|
||||
self.operation("open output", &path, &opened);
|
||||
let file = opened.map_err(|e| format!("openout {}: {e}", path.display()))?;
|
||||
let file = opened?;
|
||||
let handle = self.handle_id();
|
||||
opened_handle = Some(handle);
|
||||
self.stream_io.push(StreamEffect::OutputOpened {
|
||||
@@ -1301,6 +1514,241 @@ impl SourceProvider for Files {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Eq)]
|
||||
struct DraftFileStamp {
|
||||
bytes: u64,
|
||||
modified: std::time::SystemTime,
|
||||
readonly: bool,
|
||||
#[cfg(unix)]
|
||||
identity: (u64, u64, u32),
|
||||
}
|
||||
|
||||
impl DraftFileStamp {
|
||||
fn from_metadata(metadata: &fs::Metadata) -> io::Result<Self> {
|
||||
Ok(Self {
|
||||
bytes: metadata.len(),
|
||||
modified: metadata.modified()?,
|
||||
readonly: metadata.permissions().readonly(),
|
||||
#[cfg(unix)]
|
||||
identity: {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
(metadata.dev(), metadata.ino(), metadata.mode())
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Eq)]
|
||||
struct DraftDestination {
|
||||
path: PathBuf,
|
||||
parent: PathBuf,
|
||||
#[cfg(unix)]
|
||||
parent_identity: (u64, u64),
|
||||
stamp: Option<DraftFileStamp>,
|
||||
version: Option<ResourceVersion>,
|
||||
}
|
||||
|
||||
impl DraftDestination {
|
||||
fn capture(path: &Path) -> Result<Self, String> {
|
||||
let metadata = (|| -> io::Result<_> {
|
||||
let parent = path
|
||||
.parent()
|
||||
.ok_or(io::ErrorKind::InvalidInput)?
|
||||
.canonicalize()?;
|
||||
let target = match fs::symlink_metadata(path) {
|
||||
Ok(metadata) => Some(metadata),
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => None,
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
if let Some(metadata) = &target {
|
||||
if !metadata.is_file() {
|
||||
return Err(io::Error::other("target is not a regular file"));
|
||||
}
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
if metadata.nlink() != 1 {
|
||||
return Err(io::Error::other("target has file aliases"));
|
||||
}
|
||||
}
|
||||
}
|
||||
let stamp = target
|
||||
.as_ref()
|
||||
.map(DraftFileStamp::from_metadata)
|
||||
.transpose()?;
|
||||
Ok((parent, stamp))
|
||||
})();
|
||||
let (parent, stamp) =
|
||||
metadata.map_err(|e| format!("native draft target {}: {e}", path.display()))?;
|
||||
let version = file_version(path)?;
|
||||
if stamp.as_ref().map(|stamp| stamp.bytes) != version.as_ref().map(|version| version.bytes)
|
||||
{
|
||||
return Err(format!(
|
||||
"native draft target changed during inspection: {}",
|
||||
path.display()
|
||||
));
|
||||
}
|
||||
#[cfg(unix)]
|
||||
let parent_identity = {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
let metadata = fs::metadata(&parent)
|
||||
.map_err(|e| format!("native draft directory {}: {e}", parent.display()))?;
|
||||
(metadata.dev(), metadata.ino())
|
||||
};
|
||||
Ok(Self {
|
||||
path: path.to_owned(),
|
||||
parent,
|
||||
stamp,
|
||||
version,
|
||||
#[cfg(unix)]
|
||||
parent_identity,
|
||||
})
|
||||
}
|
||||
|
||||
fn verify(&self) -> Result<(), String> {
|
||||
if *self == Self::capture(&self.path)? {
|
||||
return Ok(());
|
||||
}
|
||||
Err(format!(
|
||||
"native draft destination changed: {}",
|
||||
self.path.display()
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
struct DraftArtifact {
|
||||
target: DraftDestination,
|
||||
staged: PreparedOutput,
|
||||
}
|
||||
|
||||
pub(crate) struct DraftPublication {
|
||||
artifacts: Vec<DraftArtifact>,
|
||||
untouched: BTreeMap<PathBuf, Option<ResourceVersion>>,
|
||||
// The native project lock covers validation, installation and rollback.
|
||||
_host: Files,
|
||||
}
|
||||
|
||||
impl DraftPublication {
|
||||
/// Install host effects and expose the completed document under one
|
||||
/// session revision gate. The callback must not call the session.
|
||||
pub(crate) fn publish_current<T>(
|
||||
self,
|
||||
session: &NativeSession,
|
||||
revision: u64,
|
||||
expose_document: impl FnOnce() -> T,
|
||||
) -> Result<Option<T>, String> {
|
||||
let Self {
|
||||
artifacts,
|
||||
untouched,
|
||||
_host,
|
||||
} = self;
|
||||
session.publish_current(revision, || {
|
||||
for (path, expected) in untouched {
|
||||
if DraftDestination::capture(&path)?.version != expected {
|
||||
return Err(format!("native draft input changed: {}", path.display()));
|
||||
}
|
||||
}
|
||||
install_draft(
|
||||
artifacts
|
||||
.into_iter()
|
||||
.map(DraftInstall::prepare)
|
||||
.collect::<Result<Vec<_>, _>>()?,
|
||||
)?;
|
||||
Ok(expose_document())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct DraftInstall {
|
||||
artifact: DraftArtifact,
|
||||
installed: DraftFileStamp,
|
||||
backup: Option<PreparedOutput>,
|
||||
}
|
||||
|
||||
impl DraftInstall {
|
||||
fn prepare(artifact: DraftArtifact) -> Result<Self, String> {
|
||||
artifact.target.verify()?;
|
||||
let metadata = fs::symlink_metadata(&artifact.staged.path)
|
||||
.map_err(|e| format!("inspect staged {}: {e}", artifact.target.path.display()))?;
|
||||
if !metadata.is_file() {
|
||||
return Err(format!(
|
||||
"native staged output must be a regular file: {}",
|
||||
artifact.target.path.display()
|
||||
));
|
||||
}
|
||||
let installed = DraftFileStamp::from_metadata(&metadata).map_err(|e| e.to_string())?;
|
||||
let backup = artifact
|
||||
.target
|
||||
.stamp
|
||||
.as_ref()
|
||||
.map(|_| PreparedOutput::backup(&artifact.target.path))
|
||||
.transpose()?;
|
||||
Ok(Self {
|
||||
artifact,
|
||||
installed,
|
||||
backup,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn install_draft(installs: Vec<DraftInstall>) -> Result<(), String> {
|
||||
let mut applied: Vec<(PathBuf, DraftFileStamp, Option<PreparedOutput>)> = Vec::new();
|
||||
for DraftInstall {
|
||||
mut artifact,
|
||||
installed,
|
||||
backup,
|
||||
} in installs
|
||||
{
|
||||
let path = artifact.target.path;
|
||||
let result = match &backup {
|
||||
Some(_) => artifact.staged.replace(&path),
|
||||
None => artifact.staged.link(&path),
|
||||
};
|
||||
if let Err(mut error) = result {
|
||||
while let Some((path, installed, backup)) = applied.pop() {
|
||||
if let Err(rollback) = restore_draft(&path, installed, backup) {
|
||||
error.push_str(&format!("; native draft rollback: {rollback}"));
|
||||
}
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
applied.push((path, installed, backup));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn restore_draft(
|
||||
path: &Path,
|
||||
installed: DraftFileStamp,
|
||||
mut backup: Option<PreparedOutput>,
|
||||
) -> Result<(), String> {
|
||||
let restore = (|| -> io::Result<()> {
|
||||
let metadata = fs::symlink_metadata(path)?;
|
||||
if !metadata.is_file() || DraftFileStamp::from_metadata(&metadata)? != installed {
|
||||
return Err(io::Error::other("installed file changed"));
|
||||
}
|
||||
match &backup {
|
||||
Some(backup) => fs::rename(&backup.path, path),
|
||||
None => fs::remove_file(path),
|
||||
}
|
||||
})();
|
||||
if let Err(error) = restore {
|
||||
if let Some(backup) = &mut backup {
|
||||
let recovery = std::mem::take(&mut backup.path);
|
||||
return Err(format!(
|
||||
"{}: {error}; previous file retained at {}",
|
||||
path.display(),
|
||||
recovery.display()
|
||||
));
|
||||
}
|
||||
return Err(format!("{}: {error}", path.display()));
|
||||
}
|
||||
if let Some(backup) = &mut backup {
|
||||
backup.path.clear();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write complete bytes before publishing the output path.
|
||||
pub struct PreparedOutput {
|
||||
path: PathBuf,
|
||||
@@ -1313,39 +1761,99 @@ impl PreparedOutput {
|
||||
Ok(version)
|
||||
}
|
||||
pub fn write(output: &Path, bytes: &[u8]) -> Result<Self, String> {
|
||||
let (prepared, mut file) = Self::create(output)?;
|
||||
let written = file.write_all(bytes).and_then(|()| file.sync_all());
|
||||
drop(file);
|
||||
written.map_err(|error| format!("stage output {}: {error}", output.display()))?;
|
||||
Ok(prepared)
|
||||
}
|
||||
|
||||
fn draft(output: &Path) -> Result<(Self, File), String> {
|
||||
let existing = match fs::symlink_metadata(output) {
|
||||
Ok(metadata) => {
|
||||
if !metadata.is_file() {
|
||||
return Err(format!(
|
||||
"native draft needs a regular file: {}",
|
||||
output.display()
|
||||
));
|
||||
}
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
if metadata.nlink() != 1 {
|
||||
return Err(format!(
|
||||
"native draft target has aliases: {}",
|
||||
output.display()
|
||||
));
|
||||
}
|
||||
}
|
||||
OpenOptions::new()
|
||||
.write(true)
|
||||
.open(output)
|
||||
.map_err(|e| format!("native draft target {}: {e}", output.display()))?;
|
||||
Some(metadata.permissions())
|
||||
}
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => None,
|
||||
Err(e) => return Err(format!("native draft target {}: {e}", output.display())),
|
||||
};
|
||||
let (prepared, file) = Self::create(output)?;
|
||||
if let Some(permissions) = existing {
|
||||
file.set_permissions(permissions)
|
||||
.map_err(|e| e.to_string())?;
|
||||
}
|
||||
Ok((prepared, file))
|
||||
}
|
||||
|
||||
fn create(output: &Path) -> Result<(Self, File), String> {
|
||||
Self::allocate(output, |path| {
|
||||
fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(path)
|
||||
})
|
||||
}
|
||||
|
||||
fn backup(output: &Path) -> Result<Self, String> {
|
||||
Self::allocate(output, |path| fs::hard_link(output, path)).map(|(backup, ())| backup)
|
||||
}
|
||||
|
||||
fn allocate<T>(
|
||||
output: &Path,
|
||||
create: impl Fn(&Path) -> io::Result<T>,
|
||||
) -> Result<(Self, T), String> {
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
for _ in 0..16 {
|
||||
let id = NEXT.fetch_add(1, Ordering::Relaxed);
|
||||
let path = output.with_file_name(format!(".texrra-{}-{id}.tmp", std::process::id()));
|
||||
if path == output {
|
||||
continue;
|
||||
if path != output {
|
||||
match create(&path) {
|
||||
Ok(value) => return Ok((Self { path }, value)),
|
||||
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
|
||||
Err(error) => {
|
||||
return Err(format!("stage output {}: {error}", output.display()));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut file = match fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&path)
|
||||
{
|
||||
Ok(file) => file,
|
||||
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
|
||||
Err(error) => return Err(format!("stage output {}: {error}", output.display())),
|
||||
};
|
||||
let prepared = Self { path };
|
||||
let written = file.write_all(bytes).and_then(|()| file.sync_all());
|
||||
drop(file);
|
||||
written.map_err(|error| format!("stage output {}: {error}", output.display()))?;
|
||||
return Ok(prepared);
|
||||
}
|
||||
Err(format!("could not stage output {}", output.display()))
|
||||
}
|
||||
|
||||
/// Publish a new format without replacing an existing path.
|
||||
pub fn commit_new(self, output: &Path) -> Result<(), String> {
|
||||
self.link(output)
|
||||
}
|
||||
|
||||
fn link(&self, output: &Path) -> Result<(), String> {
|
||||
fs::hard_link(&self.path, output)
|
||||
.map_err(|error| format!("output {}: {error}", output.display()))
|
||||
}
|
||||
|
||||
pub fn commit(mut self, output: &Path) -> Result<(), String> {
|
||||
self.replace(output)
|
||||
}
|
||||
|
||||
fn replace(&mut self, output: &Path) -> Result<(), String> {
|
||||
fs::rename(&self.path, output)
|
||||
.map_err(|error| format!("output {}: {error}", output.display()))?;
|
||||
self.path.clear();
|
||||
@@ -1557,6 +2065,8 @@ mod generated_file_tests {
|
||||
false,
|
||||
&GeneratedInputPolicy::Live,
|
||||
preparation,
|
||||
None,
|
||||
EffectMode::Live,
|
||||
)
|
||||
}
|
||||
#[test]
|
||||
@@ -1887,6 +2397,38 @@ mod prepared_output_tests {
|
||||
fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_draft_install_restores_replaced_file_and_removes_new_file() {
|
||||
let root =
|
||||
std::env::temp_dir().join(format!("texrra-draft-rollback-{}", std::process::id()));
|
||||
fs::create_dir(&root).unwrap();
|
||||
let replaced = root.join("entry.aux");
|
||||
let new = root.join("entry.log");
|
||||
let unavailable = root.join("entry.pdf");
|
||||
fs::write(&replaced, b"old auxiliary file").unwrap();
|
||||
let expected = DraftDestination::capture(&replaced).unwrap();
|
||||
|
||||
let installs = [&replaced, &new, &unavailable]
|
||||
.into_iter()
|
||||
.map(|path| {
|
||||
DraftInstall::prepare(DraftArtifact {
|
||||
target: DraftDestination::capture(path).unwrap(),
|
||||
staged: PreparedOutput::write(path, b"staged native bytes").unwrap(),
|
||||
})
|
||||
.unwrap()
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
fs::remove_file(&installs[2].artifact.staged.path).unwrap();
|
||||
let error = install_draft(installs).unwrap_err();
|
||||
assert!(error.contains("entry.pdf"), "{error}");
|
||||
expected.verify().unwrap();
|
||||
assert_eq!(fs::read(&replaced).unwrap(), b"old auxiliary file");
|
||||
assert!(!new.exists());
|
||||
assert!(!unavailable.exists());
|
||||
assert_eq!(fs::read_dir(&root).unwrap().count(), 1);
|
||||
fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn staged_output_from_superseded_revision_cannot_replace_destination() {
|
||||
let root =
|
||||
|
||||
Reference in new issue
Block a user