fix(backup): restore from a stable copy of the local archive

This commit is contained in:
Tunglies
2026-12-04 01:48:33 +08:00
parent d2f0f3c0c1
commit 2b02e2de3e
+27 -4
View File
@@ -244,9 +244,9 @@ async fn restore_files(archive: BackupArchive<File>, retry: bool) -> Result<(IPr
}
/// Backup creation strips the WebDAV credentials, so the live ones are kept.
async fn restore_backup_archive(path: PathBuf) -> Result<()> {
async fn restore_backup_archive(file: File) -> Result<()> {
let archive = AsyncHandler::spawn_blocking(move || -> Result<_> {
Ok(BackupArchive::open(File::open(path)?, RECOVERY_ENTRY_NAMES)?)
Ok(BackupArchive::open(file, RECOVERY_ENTRY_NAMES)?)
})
.await
.map_err(|join| anyhow!("backup preflight task failed: {join}"))??;
@@ -284,7 +284,8 @@ pub async fn restore_webdav_backup(filename: String) -> Result<()> {
);
err
})?;
let result = restore_backup_archive(archive).await;
let file = fs::File::open(archive).await?.into_std().await;
let result = restore_backup_archive(file).await;
drop(archive_dir);
result
})
@@ -445,6 +446,13 @@ pub async fn delete_local_backup(filename: String) -> Result<()> {
Ok(())
}
fn snapshot_local_backup(path: &Path) -> Result<File> {
// Both extractions must read the same bytes even if the local ZIP changes during restore.
let mut snapshot = tempfile::tempfile()?;
std::io::copy(&mut File::open(path)?, &mut snapshot)?;
Ok(snapshot)
}
#[tracing::instrument(skip_all, level = "info", fields(filename = %filename))]
pub async fn restore_local_backup(filename: String) -> Result<()> {
let backup_dir = local_backup_dir()?;
@@ -453,7 +461,8 @@ pub async fn restore_local_backup(filename: String) -> Result<()> {
return Err(anyhow!("Backup file not found: {}", filename));
}
restore_backup_archive(target_path).await
let snapshot = AsyncHandler::spawn_blocking(move || snapshot_local_backup(&target_path)).await??;
restore_backup_archive(snapshot).await
}
#[tracing::instrument(skip_all, level = "info", fields(filename = %filename, destination = %destination))]
@@ -482,6 +491,20 @@ mod tests {
use clash_verge_backup_archive::BackupWriter;
use std::io::Write as _;
#[test]
fn local_restore_reads_the_same_archive_after_the_source_changes() -> Result<()> {
let source = tempfile::NamedTempFile::new()?;
let mut writer = BackupWriter::new(source.reopen()?)?;
writer.start_file(PROFILE_YAML)?.write_all(b"items: []")?;
writer.finish()?;
let snapshot = snapshot_local_backup(source.path())?;
std::fs::write(source.path(), b"replaced")?;
let staging = tempfile::tempdir()?;
BackupArchive::open(snapshot, RECOVERY_ENTRY_NAMES)?.extract_to(staging.path())?;
assert_eq!(std::fs::read(staging.path().join(PROFILE_YAML))?, b"items: []");
Ok(())
}
#[tokio::test]
async fn validates_config_before_replacing_live_files() -> Result<()> {
let home = tempfile::tempdir()?;