Overlap durable sync for interactive document drafts

This commit is contained in:
gloamxun committed 2026-11-19 16:01:20 +08:00
1 parent 062a2b9f60
commit 5163fc9854
3 files changed
+101 -20

No files matched your search

+88 -19
View File
@@ -1132,10 +1132,7 @@ impl Files {
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 log = self.log.take();
let initial = self
.preparation
.generated_initial
@@ -1160,15 +1157,46 @@ impl Files {
.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())
let sync_pdf = || -> Result<(), String> {
if let Some(file) = pdf.as_ref().and_then(|pdf| pdf.pending_sync.as_ref()) {
file.sync_all().map_err(|error| {
format!("sync native draft {}: {error}", draft.pdf.path.display())
})?;
}
}
Ok(())
};
let sync_log = || -> Result<(), String> {
if let Some(file) = &log {
file.sync_all()
.map_err(|error| format!("sync native draft log: {error}"))?;
}
Ok(())
};
// Flush independent files concurrently, then finish collecting all
// results before the revision gate can install any artifact.
std::thread::scope(|scope| {
let pdf_worker = pdf.as_ref().and_then(|pdf| pdf.pending_sync.as_ref())
.and_then(|_| std::thread::Builder::new().spawn_scoped(scope, sync_pdf).ok());
let log_worker = log.as_ref()
.and_then(|_| std::thread::Builder::new().spawn_scoped(scope, sync_log).ok());
let generated = artifacts.iter().try_for_each(|artifact| {
OpenOptions::new()
.write(true)
.open(&artifact.staged.path)
.and_then(|file| file.sync_all())
.map_err(|error| {
format!("sync native draft {}: {error}", artifact.target.path.display())
})
});
let pdf_result = pdf_worker.map_or_else(sync_pdf, |worker| {
worker.join().map_err(|_| "native draft PDF sync thread panicked".to_owned())?
});
let log_result = log_worker.map_or_else(sync_log, |worker| {
worker.join().map_err(|_| "native draft log sync thread panicked".to_owned())?
});
pdf_result.and(log_result).and(generated)
})?;
drop(log);
artifacts.push(draft.log);
let untouched_ledger = if let Some(DraftLedger { file, staged }) = draft.ledger {
let target = &draft.ledger_target.path;
@@ -1195,7 +1223,8 @@ impl Files {
} else {
Some(draft.ledger_target)
};
if let Some(staged) = pdf {
if let Some(mut staged) = pdf {
drop(staged.pending_sync.take());
artifacts.push(DraftArtifact {
target: draft.pdf,
staged,
@@ -1846,6 +1875,7 @@ fn restore_draft(
/// Write complete bytes before publishing the output path.
pub struct PreparedOutput {
path: PathBuf,
pending_sync: Option<File>,
}
impl PreparedOutput {
@@ -1864,14 +1894,31 @@ impl PreparedOutput {
output: &Path,
write: impl FnOnce(&mut File) -> Result<(), String>,
) -> Result<Self, String> {
let (prepared, mut file) = Self::create(output)?;
let written = write(&mut file)
.and_then(|()| file.sync_all().map_err(|error| error.to_string()));
let (prepared, file) = Self::write_staged(output, write)?;
let synced = file.sync_all();
drop(file);
written.map_err(|error| format!("stage output {}: {error}", output.display()))?;
synced.map_err(|error| format!("stage output {}: {error}", output.display()))?;
Ok(prepared)
}
pub(crate) fn write_for_draft(output: &Path, bytes: &[u8]) -> Result<Self, String> {
let (mut prepared, file) = Self::write_staged(output, |file| {
file.write_all(bytes).map_err(|error| error.to_string())
})?;
prepared.pending_sync = Some(file);
Ok(prepared)
}
fn write_staged(
output: &Path,
write: impl FnOnce(&mut File) -> Result<(), String>,
) -> Result<(Self, File), String> {
let (prepared, mut file) = Self::create(output)?;
write(&mut file)
.map_err(|error| format!("stage output {}: {error}", output.display()))?;
Ok((prepared, file))
}
fn draft(output: &Path) -> Result<(Self, File), String> {
let existing = match fs::symlink_metadata(output) {
Ok(metadata) => {
@@ -1932,7 +1979,7 @@ impl PreparedOutput {
let path = output.with_file_name(format!(".texrra-{}-{id}.tmp", std::process::id()));
if path != output {
match create(&path) {
Ok(value) => return Ok((Self { path }, value)),
Ok(value) => return Ok((Self { path, pending_sync: None }, value)),
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
Err(error) => {
return Err(format!("stage output {}: {error}", output.display()));
@@ -1967,6 +2014,7 @@ impl PreparedOutput {
impl Drop for PreparedOutput {
fn drop(&mut self) {
drop(self.pending_sync.take());
if !self.path.as_os_str().is_empty() {
let _ = fs::remove_file(&self.path);
}
@@ -2107,7 +2155,28 @@ mod generated_file_tests {
assert!(error.contains("native staged ledger changed"), "{error}");
assert!(!staged.exists());
assert_eq!(fs::read(&ledger_path).unwrap(), original_ledger);
assert_eq!(fs::read(generated).unwrap(), b"original");
assert_eq!(fs::read(&generated).unwrap(), b"original");
#[cfg(unix)]
{
let output = root.join("job.pdf");
let log = root.join("job.log");
fs::write(&output, b"already published PDF").unwrap();
let original_log = fs::read(&log).unwrap();
let mut host = draft();
write(&mut host, "actual.aux", "another draft");
host.finish().unwrap();
let mut pdf = PreparedOutput::write_for_draft(&output, b"new PDF").unwrap();
let path = pdf.path.clone();
pdf.pending_sync = Some(File::open("/dev/null").unwrap());
let error = host.seal_draft(Some(pdf)).err().unwrap();
assert!(error.contains("sync native draft") && error.contains("job.pdf"), "{error}");
assert!(!path.exists());
assert_eq!(fs::read(&output).unwrap(), b"already published PDF");
assert_eq!(fs::read(&log).unwrap(), original_log);
assert_eq!(fs::read(&generated).unwrap(), b"original");
assert_eq!(fs::read(&ledger_path).unwrap(), original_ledger);
}
fs::remove_dir_all(root).unwrap();
}