Skip to content

A full-featured download manager.

fix(finalize): stabilize Windows suffix renames and recover quarantines (#2512)

Dr_rOot6119bfad3226
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 25926808..758d7ce8 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -432,6 +432,7 @@ jobs:
run: >-
pnpm exec vitest run
src/core/task/direct-task-retry.integration.test.ts
+ src/core/task/http-finalize.integration.test.ts
src/core/engine/aria2/aria2-session-identity-recovery.integration.test.ts
src/core/engine/aria2/aria2-parent-lifecycle.integration.test.ts
src/core/legacy-import/http-activation.integration.test.ts
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 3e069832..3f75786f 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -263,6 +263,7 @@ jobs:
run: >-
pnpm exec vitest run
src/core/task/direct-task-retry.integration.test.ts
+ src/core/task/http-finalize.integration.test.ts
src/core/engine/aria2/aria2-session-identity-recovery.integration.test.ts
src/core/legacy-import/http-activation.integration.test.ts
src/core/plugin/finalize/native-artifact-operations.integration.test.ts
diff --git a/packages/finalize-fs/src/platform/mod.rs b/packages/finalize-fs/src/platform/mod.rs
index 5d1be1aa..9023ed29 100644
--- a/packages/finalize-fs/src/platform/mod.rs
+++ b/packages/finalize-fs/src/platform/mod.rs
@@ -23,6 +23,17 @@ mod windows;
#[cfg(any(windows, test))]
mod windows_policy;
+#[cfg(windows)]
+pub(crate) use windows::open_rename_guard;
+
+#[cfg(not(windows))]
+pub(crate) fn open_rename_guard(
+ _: &RootHandle,
+ _: &str,
+) -> std::io::Result<Option<(ArtifactHandle, String)>> {
+ Ok(None)
+}
+
#[cfg(unix)]
pub(crate) use unix::{
ArtifactHandle, RootHandle, copy_opened, copy_selected_file, create_private_root,
diff --git a/packages/finalize-fs/src/platform/windows/metadata.rs b/packages/finalize-fs/src/platform/windows/metadata.rs
index a11b85ef..5ca2105b 100644
--- a/packages/finalize-fs/src/platform/windows/metadata.rs
+++ b/packages/finalize-fs/src/platform/windows/metadata.rs
@@ -33,6 +33,12 @@ pub(super) struct FileStamp {
pub(super) directory: bool,
}
+impl FileStamp {
+ pub(super) fn same_file_and_size(&self, other: &Self) -> bool {
+ self.volume == other.volume && self.file_id == other.file_id && self.size == other.size
+ }
+}
+
#[derive(Clone, Debug, Eq, PartialEq)]
pub(super) struct EntrySnapshot {
pub(super) name: Vec<u16>,
@@ -119,6 +125,21 @@ pub(super) fn query_stamp(handle: &OwnedHandle) -> io::Result<FileStamp> {
})
}
+pub(super) fn change_time(handle: &OwnedHandle) -> io::Result<i64> {
+ Ok(query::<FILE_BASIC_INFO>(handle, FileBasicInfo)?.ChangeTime)
+}
+
+/// The journal uses Node's decimal volume serial and 64-bit file index.
+pub(super) fn journal_file_id(handle: &OwnedHandle) -> io::Result<Option<String>> {
+ let mut info = BY_HANDLE_FILE_INFORMATION::default();
+ if unsafe { GetFileInformationByHandle(handle.as_raw_handle(), &mut info) } == 0 {
+ return Err(io::Error::last_os_error());
+ }
+ let index = u64::from(info.nFileIndexHigh) << 32 | u64::from(info.nFileIndexLow);
+ Ok((info.dwVolumeSerialNumber != 0 && index != 0)
+ .then(|| format!("{}:{index}", info.dwVolumeSerialNumber)))
+}
+
pub(super) fn query_identity(handle: &OwnedHandle) -> io::Result<(u64, FileIdentity)> {
query_identity_with(handle, query::<FILE_ID_INFO>(handle, FileIdInfo))
}
diff --git a/packages/finalize-fs/src/platform/windows/mod.rs b/packages/finalize-fs/src/platform/windows/mod.rs
index bd7fa37a..3c22a906 100644
--- a/packages/finalize-fs/src/platform/windows/mod.rs
+++ b/packages/finalize-fs/src/platform/windows/mod.rs
@@ -41,6 +41,7 @@ pub(crate) struct ArtifactHandle {
snapshot: Option<ArtifactSnapshot>,
stamp: metadata::FileStamp,
rename_budget: RenameRetryBudget,
+ rename_guard: bool,
}
pub(crate) fn open_root(path: &str) -> io::Result<RootHandle> {
@@ -103,13 +104,91 @@ fn open_artifact_internal(
snapshot,
stamp,
rename_budget,
+ rename_guard: false,
})
}
+/// Flush data before establishing the durable source stamp. The read handle
+/// outlives the handle which performs the rename, so delayed change-time
+/// updates from closing the renamer are observable while writes remain excluded.
+pub(crate) fn open_rename_guard(
+ root: &RootHandle,
+ relative: &str,
+) -> io::Result<Option<(ArtifactHandle, String)>> {
+ let parts = validate_relative(relative)?;
+ let (parent, name) = open_parent(&root.handle, &parts)?;
+ let budget = RenameRetryBudget::default();
+ let writer = budget.run("open_flush_file", "not_attempted", || {
+ nt::open_flush_file(&parent, &name)
+ })?;
+ let flushed = query_stamp(&writer)?;
+ nt::flush(&writer)?;
+ let change_time = metadata::change_time(&writer)?;
+ drop(writer);
+ let handle = budget.run("open_guard", "not_attempted", || {
+ nt::open_selected(&parent, &name)
+ })?;
+ let stamp = query_stamp(&handle)?;
+ if !stamp.same_file_and_size(&flushed) {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidData,
+ "source changed during flush handoff",
+ ));
+ }
+ if stamp != flushed || metadata::change_time(&handle)? != change_time {
+ // No journal exists yet. Verify content when this volume cannot
+ // attest an uninterrupted flush-to-reader handoff using metadata.
+ return Ok(None);
+ }
+ let Some(file_id) = metadata::journal_file_id(&handle)? else {
+ return Ok(None);
+ };
+ ensure_named_entry(&handle, &parent, &name)?;
+ Ok(Some((
+ ArtifactHandle {
+ handle,
+ parent,
+ name,
+ stamp,
+ rename_budget: budget,
+ snapshot: None,
+ rename_guard: true,
+ },
+ file_id,
+ )))
+}
+
pub(crate) fn rename_opened_no_replace(
artifact: &ArtifactHandle,
target: &RootHandle,
target_relative: &str,
+) -> io::Result<RenameOutcome> {
+ if artifact.rename_guard {
+ let renamer = artifact
+ .rename_budget
+ .run("open_source", "not_attempted", || {
+ nt::open_rename_file(&artifact.parent, &artifact.name)
+ })?;
+ metadata::ensure_same_opened(&artifact.handle, &renamer)
+ .map_err(|e| operation_error(e, "validate_source", "not_attempted", None))?;
+ let result = rename_with_handle(artifact, &renamer, target, target_relative)?;
+ drop(renamer);
+ let verify_target = || {
+ let parts = validate_relative(target_relative)?;
+ let (parent, name) = open_parent(&target.handle, &parts)?;
+ ensure_named_entry(&artifact.handle, &parent, &name)
+ };
+ verify_target().map_err(|e| operation_error(e, "verify_target", "applied", None))?;
+ return Ok(result);
+ }
+ rename_with_handle(artifact, &artifact.handle, target, target_relative)
+}
+
+fn rename_with_handle(
+ artifact: &ArtifactHandle,
+ renamer: &OwnedHandle,
+ target: &RootHandle,
+ target_relative: &str,
) -> io::Result<RenameOutcome> {
let (target_parent, target_name, same_parent) = (|| {
if let Some(snapshot) = &artifact.snapshot {
@@ -128,7 +207,7 @@ pub(crate) fn rename_opened_no_replace(
})()
.map_err(|e| operation_error(e, "validate_source", "not_attempted", None))?;
nt::rename_no_replace_with_retry(
- &artifact.handle,
+ renamer,
&target_parent,
&target_name,
&artifact.rename_budget,
diff --git a/packages/finalize-fs/src/platform/windows/nt.rs b/packages/finalize-fs/src/platform/windows/nt.rs
index dc6e3df4..00dcac82 100644
--- a/packages/finalize-fs/src/platform/windows/nt.rs
+++ b/packages/finalize-fs/src/platform/windows/nt.rs
@@ -164,6 +164,25 @@ pub(super) fn open_selected(parent: &OwnedHandle, name: &[u16]) -> io::Result<Ow
)
}
+fn open_regular(parent: &OwnedHandle, name: &[u16], access: u32) -> io::Result<OwnedHandle> {
+ nt_create(
+ parent,
+ name,
+ access | FILE_READ_ATTRIBUTES | SYNCHRONIZE,
+ SHARE_HELD_ARTIFACT,
+ FILE_OPEN,
+ OPEN_COMMON | FILE_NON_DIRECTORY_FILE,
+ )
+}
+
+pub(super) fn open_flush_file(parent: &OwnedHandle, name: &[u16]) -> io::Result<OwnedHandle> {
+ open_regular(parent, name, FILE_WRITE_DATA)
+}
+
+pub(super) fn open_rename_file(parent: &OwnedHandle, name: &[u16]) -> io::Result<OwnedHandle> {
+ open_regular(parent, name, FILE_READ_DATA | DELETE)
+}
+
pub(super) fn open_existing(parent: &OwnedHandle, name: &[u16]) -> io::Result<OwnedHandle> {
match nt_create(
parent,
diff --git a/packages/finalize-fs/src/platform/windows/operations.rs b/packages/finalize-fs/src/platform/windows/operations.rs
index d4e5391b..3cc1d4c3 100644
--- a/packages/finalize-fs/src/platform/windows/operations.rs
+++ b/packages/finalize-fs/src/platform/windows/operations.rs
@@ -52,6 +52,7 @@ pub(crate) fn open_selected_file(root: &RootHandle, relative: &str) -> io::Resul
snapshot: None,
stamp,
rename_budget: Default::default(),
+ rename_guard: false,
};
if file.stamp.directory || File::from(file.handle.try_clone()?).metadata()?.len() == 0 {
return Err(io::Error::new(
diff --git a/packages/finalize-fs/src/platform/windows/tests.rs b/packages/finalize-fs/src/platform/windows/tests.rs
index df4a32cc..e7c63c1d 100644
--- a/packages/finalize-fs/src/platform/windows/tests.rs
+++ b/packages/finalize-fs/src/platform/windows/tests.rs
@@ -197,6 +197,28 @@ fn rename_only_file_excludes_writers_until_the_published_handle_closes() {
fs::OpenOptions::new().write(true).open(&target).unwrap();
}
+#[test]
+fn synced_guard_preserves_the_post_close_stamp_and_excludes_late_writers() {
+ let scratch = Scratch::new("synced-guard");
+ let source = scratch.path().join("app.zip.motrix");
+ let target = scratch.path().join("app.zip");
+ fs::write(&source, b"download").unwrap();
+ let root = open_root(scratch.path().to_str().unwrap()).unwrap();
+ let (guard, _) = super::open_rename_guard(&root, "app.zip.motrix")
+ .unwrap()
+ .expect("NTFS guard");
+ assert!(fs::OpenOptions::new().write(true).open(&source).is_err());
+ rename_opened_no_replace(&guard, &root, "app.zip").unwrap();
+ assert!(fs::OpenOptions::new().write(true).open(&target).is_err());
+ let installed = super::metadata::change_time(&guard.handle).unwrap();
+ drop(guard);
+ let reopened =
+ super::nt::open_selected(&root.handle, &super::nt::wide_name("app.zip").unwrap()).unwrap();
+ assert_eq!(super::metadata::change_time(&reopened).unwrap(), installed);
+ assert_eq!(fs::read(target).unwrap(), b"download");
+ assert!(!source.exists());
+}
+
#[test]
fn rename_admission_rejects_an_existing_writer_even_when_it_shares_delete() {
use std::os::windows::fs::OpenOptionsExt;
diff --git a/packages/finalize-fs/src/protocol.rs b/packages/finalize-fs/src/protocol.rs
index afbcc668..3a4222d6 100644
--- a/packages/finalize-fs/src/protocol.rs
+++ b/packages/finalize-fs/src/protocol.rs
@@ -50,6 +50,11 @@ pub(crate) enum Request {
#[serde(default)]
rename_only: bool,
},
+ OpenRenameGuard {
+ request_id: u64,
+ root: u64,
+ relative: String,
+ },
OpenRemoval {
request_id: u64,
root: u64,
@@ -143,6 +148,7 @@ impl Request {
Self::SanitizeName { .. } => "sanitize_name",
Self::OpenRoot { .. } => "open_root",
Self::OpenArtifact { .. } => "open_artifact",
+ Self::OpenRenameGuard { .. } => "open_rename_guard",
Self::OpenRemoval { .. } => "open_removal",
Self::RenameOpenedNoReplace { .. } => "rename_opened_no_replace",
Self::LinkOpenedNoReplace { .. } => "link_opened_no_replace",
@@ -185,6 +191,8 @@ pub(crate) struct Response<'a> {
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) held_file_write_exclusion: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
+ pub(crate) synced_rename_guard: Option<bool>,
+ #[serde(skip_serializing_if = "Option::is_none")]
pub(crate) reserved_exfat_rename: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) token_exfat_reservation: Option<bool>,
@@ -223,6 +231,7 @@ impl<'a> Response<'a> {
directory_sync: None,
held_artifacts: None,
held_file_write_exclusion: None,
+ synced_rename_guard: None,
reserved_exfat_rename: None,
token_exfat_reservation: None,
volume_id: None,
diff --git a/packages/finalize-fs/src/state.rs b/packages/finalize-fs/src/state.rs
index 52d84deb..02bc1643 100644
--- a/packages/finalize-fs/src/state.rs
+++ b/packages/finalize-fs/src/state.rs
@@ -173,6 +173,25 @@ impl State {
}
}
}
+ Request::OpenRenameGuard {
+ request_id,
+ root,
+ relative,
+ } => {
+ let Some(root) = self.roots.get(&root) else {
+ return Response::error(Some(request_id), "invalid_handle", "unknown root");
+ };
+ match crate::platform::open_rename_guard(root, &relative) {
+ Ok(Some((artifact, file_id))) => {
+ let mut response = Response::ok(Some(request_id));
+ response.handle = Some(self.insert_artifact(artifact));
+ response.platform_file_id = Some(file_id);
+ response
+ }
+ Ok(None) => Response::ok(Some(request_id)),
+ Err(error) => Response::filesystem_error(request_id, error),
+ }
+ }
Request::OpenRemoval {
request_id,
root,
@@ -542,6 +561,7 @@ impl State {
response.directory_sync = Some(cfg!(any(unix, windows)));
response.held_artifacts = Some(cfg!(any(unix, windows)));
response.held_file_write_exclusion = Some(cfg!(windows));
+ response.synced_rename_guard = Some(cfg!(windows));
response.reserved_exfat_rename = Some(cfg!(target_os = "macos"));
response.token_exfat_reservation = Some(cfg!(target_os = "macos"));
response
diff --git a/src/core/plugin/finalize/filesystem-adapter.ts b/src/core/plugin/finalize/filesystem-adapter.ts
index 30598689..4ad85afb 100644
--- a/src/core/plugin/finalize/filesystem-adapter.ts
+++ b/src/core/plugin/finalize/filesystem-adapter.ts
@@ -45,6 +45,7 @@ export interface FinalizeFsCapabilities {
heldArtifacts: boolean
/** Held regular-file handles exclude writers, including writable mappings. */
heldFileWriteExclusion?: boolean
+ syncedRenameGuard?: boolean
reservedExfatRename?: boolean
tokenExfatReservation?: boolean
}
@@ -69,6 +70,7 @@ interface WireResponse {
directory_sync?: boolean
held_artifacts?: boolean
held_file_write_exclusion?: boolean
+ synced_rename_guard?: boolean
reserved_exfat_rename?: boolean
token_exfat_reservation?: boolean
volume_id?: string
@@ -129,6 +131,10 @@ export interface FinalizeFilesystemAdapter {
relativePath: string,
intent?: 'rename'
): Promise<FinalizeArtifactHandle>
+ openRenameGuard?(
+ root: FinalizeRootHandle,
+ name: string
+ ): Promise<{ handle: FinalizeArtifactHandle; platformFileId: string } | null>
openRemoval?(
root: FinalizeRootHandle,
relativePath: string,
@@ -257,6 +263,7 @@ export class NativeFinalizeFilesystemAdapter
directorySync: response.directory_sync === true,
heldArtifacts: response.held_artifacts === true,
heldFileWriteExclusion: response.held_file_write_exclusion === true,
+ syncedRenameGuard: response.synced_rename_guard === true,
reservedExfatRename: response.reserved_exfat_rename === true,
tokenExfatReservation: response.token_exfat_reservation === true,
}
@@ -398,6 +405,22 @@ export class NativeFinalizeFilesystemAdapter
}
}
+ async openRenameGuard(root: FinalizeRootHandle, name: string) {
+ const generation = this.generation
+ const result = await this.request({
+ op: 'open_rename_guard',
+ root: this.nativeId(root),
+ relative: name,
+ })
+ if (result.handle === undefined) return null
+ const handle = this.heldHandle(result.handle, generation)
+ if (!result.platform_file_id) {
+ await this.close(handle)
+ throw new Error('rename guard omitted its file ID')
+ }
+ return { handle, platformFileId: result.platform_file_id }
+ }
+
async openArtifact(
root: FinalizeRootHandle,
relativePath: string,
diff --git a/src/core/plugin/finalize/finalize-committer.test.ts b/src/core/plugin/finalize/finalize-committer.test.ts
index 8e9328ee..53142c2a 100644
--- a/src/core/plugin/finalize/finalize-committer.test.ts
+++ b/src/core/plugin/finalize/finalize-committer.test.ts
@@ -401,7 +401,7 @@ describe('FinalizeCommitter', () => {
expect(fs.actions.some((action) => action.startsWith('copy:'))).toBe(false)
})
- it('quarantines an identity mismatch without deleting unknown bytes', async () => {
+ it('reports a pre-journal identity mismatch without deleting unknown bytes', async () => {
const fs = new FakeFilesystem()
const plan = makePlan()
fs.artifacts.set(plan.sourcePath, {
@@ -410,9 +410,9 @@ describe('FinalizeCommitter', () => {
})
const { repository, quarantines } = makeRepository()
await expect(makeCommitter(fs, repository).commit(plan)).rejects.toThrow(
- 'quarantined'
+ 'source identity changed'
)
- expect(quarantines).toHaveLength(1)
+ expect(quarantines).toHaveLength(0)
expect(fs.actions.some((action) => action.startsWith('remove:'))).toBe(
false
)
diff --git a/src/core/plugin/finalize/finalize-committer.ts b/src/core/plugin/finalize/finalize-committer.ts
index 9e2814a9..78156ebd 100644
--- a/src/core/plugin/finalize/finalize-committer.ts
+++ b/src/core/plugin/finalize/finalize-committer.ts
@@ -1,7 +1,9 @@
import { createHash, randomBytes } from 'node:crypto'
import path from 'node:path'
+import { getLogger } from '@core/logger'
import {
type ArtifactIdentity,
+ ArtifactIdentityError,
type FileArtifactIdentity,
type RenameFileArtifactIdentity,
renameFileArtifactIdentitySchema,
@@ -131,6 +133,12 @@ export interface FinalizeJournalRepository {
resumeQuarantined?(record: FinalizeJournalRecord): Promise<void>
}
+export interface PreparedFileRename {
+ sourceIdentity: RenameFileArtifactIdentity
+ publish(): Promise<RenameFileArtifactIdentity>
+ close(): Promise<void>
+}
+
export interface FinalizeArtifactOperations {
reservedRenameSupported?(): Promise<boolean>
reservedVolumeIdentity?(directoryPath: string): Promise<string | null>
@@ -144,9 +152,10 @@ export interface FinalizeArtifactOperations {
): Promise<FileArtifactIdentity>
/** Validate the actual roots and flush source data before journaled mutation. */
preflight?(sourcePath: string, targetPath: string): Promise<void>
- renameIdentity?(
- artifactPath: string
- ): Promise<RenameFileArtifactIdentity | null>
+ prepareFileRename?(
+ sourcePath: string,
+ targetPath: string
+ ): Promise<PreparedFileRename | null>
identity(
artifactPath: string,
expected?: ArtifactIdentity
@@ -216,7 +225,8 @@ export class FinalizeCommitter {
async commit(
plan: HookPlan,
- existingLease?: ArtifactMutationLease
+ existingLease?: ArtifactMutationLease,
+ held?: PreparedFileRename
): Promise<FinalizeCommitResult> {
assertValidHookPlan(plan)
const lease =
@@ -230,27 +240,31 @@ export class FinalizeCommitter {
}
let prepared = false
try {
- await this.requireExactIdentity(
- plan.sourcePath,
- plan.sourceIdentity,
- record
- )
+ await this.requireExactIdentity(plan.sourcePath, plan.sourceIdentity)
if (plan.replacement) {
await this.requireExactIdentity(
plan.replacement.stagedPath,
- plan.replacement.identity,
- record
+ plan.replacement.identity
)
}
record.publicationMode = await this.selectPublicationMode(plan)
- await this.options.fs.preflight?.(
- plan.replacement?.stagedPath ?? plan.sourcePath,
- plan.targetPath
+ if (
+ held &&
+ (record.publicationMode !== 'move' ||
+ !isOrdinarySuffixRemoval(plan) ||
+ !this.options.exactIdentity(held.sourceIdentity, plan.sourceIdentity))
)
+ throw new Error('held rename does not match its journal plan')
+ if (!held)
+ await this.options.fs.preflight?.(
+ plan.replacement?.stagedPath ?? plan.sourcePath,
+ plan.targetPath
+ )
await this.options.repository.prepare(record)
prepared = true
- return await this.commitPrepared(record, lease)
+ return await this.commitPrepared(record, lease, held)
} catch (error) {
+ await held?.close()
if (error instanceof FinalizeQuarantinedError) throw error
if (prepared) await this.compensate(record, lease, error)
throw error
@@ -261,7 +275,8 @@ export class FinalizeCommitter {
private async commitPrepared(
record: FinalizeJournalRecord,
- _lease: ArtifactMutationLease
+ _lease: ArtifactMutationLease,
+ held?: PreparedFileRename
): Promise<FinalizeCommitResult> {
const { plan } = record
const selectedPath = plan.replacement?.stagedPath ?? plan.sourcePath
@@ -281,12 +296,14 @@ export class FinalizeCommitter {
// moveNoReplace validates the expected source identity while holding the
// artifact and both roots. Avoid hashing large artifacts once more here.
try {
- publishedIdentity = await this.publish(
- record,
- plan.sourcePath,
- plan.sourceIdentity,
- plan.targetPath
- )
+ publishedIdentity = held
+ ? await held.publish()
+ : await this.publish(
+ record,
+ plan.sourcePath,
+ plan.sourceIdentity,
+ plan.targetPath
+ )
} catch (error) {
// st_dev is only a hint: bind mounts and OverlayFS can return EXDEV
// even when both paths report the same device. Reconcile the names
@@ -321,7 +338,9 @@ export class FinalizeCommitter {
})
record.targetIdentity = publishedIdentity
}
- await this.options.fs.makeDurable(plan.targetPath)
+ // The guard already flushed this file and its rename synced the parent.
+ // Reopening the target for writing here conflicts with the guard itself.
+ if (!held) await this.options.fs.makeDurable(plan.targetPath)
} else {
if (samePath) {
record.rollbackPath = this.options.rollbackPathFor(plan)
@@ -548,6 +567,17 @@ export class FinalizeCommitter {
rollForwardTargetInstalled: false,
}).recover(record, lease)
} catch (compensationError) {
+ getLogger('finalize').error(
+ {
+ taskId: record.plan.taskId,
+ journalId: record.journalId,
+ phase: record.phase,
+ err: cause,
+ rollbackError: compensationError,
+ ...(cause instanceof FinalizeFsError ? cause.details : {}),
+ },
+ 'finalize_commit_and_recovery_failed'
+ )
const failures = new AggregateError(
[cause, compensationError],
'finalize failed and rollback needs recovery'
@@ -590,11 +620,16 @@ export class FinalizeCommitter {
private async requireExactIdentity(
artifactPath: string,
expected: ArtifactIdentity,
- record: FinalizeJournalRecord
+ record?: FinalizeJournalRecord
): Promise<ArtifactIdentity> {
const actual = await this.options.fs.identity(artifactPath, expected)
if (!actual || !this.options.exactIdentity(actual, expected)) {
- await this.quarantine(record, `identity mismatch at ${artifactPath}`)
+ if (record)
+ await this.quarantine(record, `identity mismatch at ${artifactPath}`)
+ throw new ArtifactIdentityError(
+ 'artifact_mutated',
+ 'source identity changed before finalize journal preparation'
+ )
}
return actual as ArtifactIdentity
}
diff --git a/src/core/plugin/finalize/finalize-recovery-errors.ts b/src/core/plugin/finalize/finalize-recovery-errors.ts
index ebbcfae0..ddc38d2a 100644
--- a/src/core/plugin/finalize/finalize-recovery-errors.ts
+++ b/src/core/plugin/finalize/finalize-recovery-errors.ts
@@ -2,6 +2,10 @@ import { constants } from 'node:os'
import { ArtifactIdentityError } from './artifact-identity'
import { FinalizeFsError } from './filesystem-adapter'
+export const RENAMED_SOURCE_CHANGED = 'renamed source stamp changed'
+
+export class FinalizeSourceVerificationError extends Error {}
+
/** Storage absence must block this task's retry without blocking app startup. */
export class FinalizeRecoveryDeferredError extends Error {
constructor(message: string) {
diff --git a/src/core/plugin/finalize/finalize-recovery.test.ts b/src/core/plugin/finalize/finalize-recovery.test.ts
index 28351366..eb367a1f 100644
--- a/src/core/plugin/finalize/finalize-recovery.test.ts
+++ b/src/core/plugin/finalize/finalize-recovery.test.ts
@@ -123,6 +123,30 @@ describe('rename-only finalize recovery', () => {
return pending
}
+ it.each([true, false])(
+ 'rechecks a committed target before reopening a legacy source quarantine (match=%s)',
+ async (matches) => {
+ const pending = pendingRecord('db_committed')
+ pending.quarantineReason = 'renamed source stamp changed'
+ const actual = matches ? installed : { ...installed, ctimeNs: '999' }
+ const state = fixture({ [pending.plan.targetPath]: actual })
+ const resume = vi.fn()
+ state.repository.resumeQuarantined = resume
+ if (matches) {
+ await state.recovery.recover(pending)
+ expect(resume).toHaveBeenCalledOnce()
+ expect(state.phases).toEqual(['cleaned'])
+ } else {
+ await expect(state.recovery.recover(pending)).rejects.toThrow(
+ 'quarantined'
+ )
+ expect(resume).not.toHaveBeenCalled()
+ expect(state.phases).toEqual([])
+ }
+ expect(state.artifacts.get(pending.plan.targetPath)).toEqual(actual)
+ }
+ )
+
it('preserves an installed target whose post-rename stamp was never checkpointed', async () => {
const pending = pendingRecord('prepared')
const state = fixture(
diff --git a/src/core/plugin/finalize/finalize-recovery.ts b/src/core/plugin/finalize/finalize-recovery.ts
index c88895db..f85d25ad 100644
--- a/src/core/plugin/finalize/finalize-recovery.ts
+++ b/src/core/plugin/finalize/finalize-recovery.ts
@@ -17,6 +17,7 @@ import {
import {
FinalizeRecoveryDeferredError,
isUnavailableArtifactError,
+ RENAMED_SOURCE_CHANGED,
} from './finalize-recovery-errors'
import {
linkPublicationConfirmed,
@@ -86,7 +87,12 @@ export class FinalizeRecovery {
try {
assertRenameFileJournal(record)
if (record.plan.sourceIdentity.kind === 'rename-file') {
- if (record.quarantineReason) return
+ if (
+ record.quarantineReason &&
+ (record.quarantineReason !== RENAMED_SOURCE_CHANGED ||
+ !record.targetIdentity)
+ )
+ return
await this.recoverRenameFile(record)
return
}
@@ -334,6 +340,24 @@ export class FinalizeRecovery {
throw new FinalizeRecoveryDeferredError(
'rename artifacts are unavailable; retry recovery'
)
+ if (record.quarantineReason) {
+ if (!this.options.repository.resumeQuarantined) return
+ const owned =
+ source && !target
+ ? record.phase !== 'db_committed' &&
+ this.options.exactIdentity(source, expectedSource)
+ : !source &&
+ target &&
+ record.targetIdentity &&
+ this.options.exactIdentity(target, record.targetIdentity)
+ if (!owned)
+ throw new FinalizeQuarantinedError(
+ record.journalId,
+ 'surviving files do not match the durable rename checkpoint'
+ )
+ await this.options.repository.resumeQuarantined(record)
+ record.quarantineReason = undefined
+ }
if (source && target)
return this.quarantine(
record,
@@ -343,8 +367,21 @@ export class FinalizeRecovery {
if (
record.phase === 'db_committed' ||
!this.options.exactIdentity(source, expectedSource)
- )
- return this.quarantine(record, 'renamed source stamp changed')
+ ) {
+ getLogger('finalize').warn(
+ {
+ taskId: record.plan.taskId,
+ journalId: record.journalId,
+ phase: record.phase,
+ changedFields: Object.keys(expectedSource).filter(
+ (key) =>
+ Reflect.get(source, key) !== Reflect.get(expectedSource, key)
+ ),
+ },
+ 'finalize_source_stamp_mismatch'
+ )
+ return this.quarantine(record, RENAMED_SOURCE_CHANGED)
+ }
await this.options.fs.makeDurable(record.plan.sourcePath)
await this.options.repository.advance(record.journalId, 'cleaned')
return
@@ -372,25 +409,46 @@ export class FinalizeRecovery {
await this.options.repository.advance(record.journalId, 'cleaned')
return
}
- const restored = await this.options.fs.moveNoReplace(
+ const held = await this.options.fs.prepareFileRename?.(
record.plan.targetPath,
- expectedTarget,
record.plan.sourcePath
)
- if (restored?.kind !== 'rename-file')
- return this.quarantine(record, 'rollback omitted the restored file stamp')
- await this.options.repository.checkpoint(record.journalId, {
- restoredSourceIdentity: restored,
- })
- record.restoredSourceIdentity = restored
- await this.options.fs.makeDurable(record.plan.sourcePath)
- const current = await this.options.fs.identity(
- record.plan.sourcePath,
- restored
- )
- if (!current || !this.options.exactIdentity(current, restored))
- return this.quarantine(record, 'restored source stamp changed')
- await this.options.repository.advance(record.journalId, 'cleaned')
+ try {
+ if (
+ held &&
+ !this.options.exactIdentity(held.sourceIdentity, expectedTarget)
+ )
+ return await this.quarantine(
+ record,
+ 'rollback target changed before rename'
+ )
+ const restored = held
+ ? await held.publish()
+ : await this.options.fs.moveNoReplace(
+ record.plan.targetPath,
+ expectedTarget,
+ record.plan.sourcePath
+ )
+ if (restored?.kind !== 'rename-file')
+ return await this.quarantine(
+ record,
+ 'rollback omitted the restored file stamp'
+ )
+ await this.options.repository.checkpoint(record.journalId, {
+ restoredSourceIdentity: restored,
+ })
+ record.restoredSourceIdentity = restored
+ if (!held) await this.options.fs.makeDurable(record.plan.sourcePath)
+ const current = await this.options.fs.identity(
+ record.plan.sourcePath,
+ restored
+ )
+ if (!current || !this.options.exactIdentity(current, restored))
+ return await this.quarantine(record, 'restored source stamp changed')
+ await this.options.repository.advance(record.journalId, 'cleaned')
+ } finally {
+ await held?.close()
+ }
}
private async recoverReserved(record: FinalizeJournalRecord): Promise<void> {
diff --git a/src/core/plugin/finalize/finalize-smb-recovery.integration.test.ts b/src/core/plugin/finalize/finalize-smb-recovery.integration.test.ts
index bb9a144a..aabec34a 100644
--- a/src/core/plugin/finalize/finalize-smb-recovery.integration.test.ts
+++ b/src/core/plugin/finalize/finalize-smb-recovery.integration.test.ts
@@ -155,8 +155,10 @@ describe.runIf(existsSync(binary))('SMB finalize failure recovery', () => {
expect(await readFile(s.input.sourcePath, 'utf8')).toBe('complete download')
})
- it('retains both I/O errors and retries a failed rollback without restarting', async () => {
+ it('recovers a failed content-verified directory flush without restarting', async () => {
const s = await setup()
+ // This protocol uses caller-owned directory syncs on older helpers.
+ vi.spyOn(s.fs, 'prepareFileRename').mockResolvedValue(null)
const realSync = s.adapter.syncRoot.bind(s.adapter)
let calls = 0
const injected = vi
@@ -188,6 +190,39 @@ describe.runIf(existsSync(binary))('SMB finalize failure recovery', () => {
expect(existsSync(s.input.sourcePath)).toBe(false)
})
+ it('recovers a lost install checkpoint and a failed rollback checkpoint', async () => {
+ const s = await setup()
+ const prototype = SqliteFinalizeJournalRepository.prototype
+ const advance = prototype.advance
+ const fault = vi
+ .spyOn(prototype, 'advance')
+ .mockImplementation(async function (
+ this: SqliteFinalizeJournalRepository,
+ ...args: Parameters<typeof advance>
+ ) {
+ if (args[1] === 'target_installed' || args[1] === 'cleaned')
+ throw new Error(`checkpoint unavailable: ${args[1]}`)
+ return advance.apply(this, args)
+ })
+ const failure = await s.runtime.commit(s.input).catch((e: unknown) => e)
+ expect(failure).toBeInstanceOf(AggregateError)
+ expect((failure as AggregateError).errors.map(String)).toEqual([
+ 'Error: checkpoint unavailable: target_installed',
+ 'Error: checkpoint unavailable: cleaned',
+ ])
+ expect(s.row()).toMatchObject({
+ phase: 'prepared',
+ quarantine_reason: null,
+ })
+ expect(await readFile(s.input.sourcePath, 'utf8')).toBe('complete download')
+ expect(existsSync(s.input.targetPath)).toBe(false)
+ fault.mockRestore()
+ await s.runtime.commit(s.input)
+ expect(s.row()).toMatchObject({ phase: 'cleaned' })
+ expect(await readFile(s.input.targetPath, 'utf8')).toBe('complete download')
+ expect(existsSync(s.input.sourcePath)).toBe(false)
+ })
+
it.each([false, true])(
'recovers a legacy quarantine with targetInstalled=%s before task restore',
async (installed) => {
diff --git a/src/core/plugin/finalize/native-artifact-operations.integration.test.ts b/src/core/plugin/finalize/native-artifact-operations.integration.test.ts
index 1d948c17..759cf229 100644
--- a/src/core/plugin/finalize/native-artifact-operations.integration.test.ts
+++ b/src/core/plugin/finalize/native-artifact-operations.integration.test.ts
@@ -1,3 +1,4 @@
+import { createHash } from 'node:crypto'
import { existsSync } from 'node:fs'
import {
chmod,
@@ -16,6 +17,11 @@ import {
} from 'node:fs/promises'
import os from 'node:os'
import path from 'node:path'
+import { DurableFinalizeRuntime } from '@core/session/durable-finalize-runtime'
+import { SqliteFinalizeJournalRepository } from '@core/session/finalize-journal-repository'
+import { migrate } from '@core/session/migrations'
+import { makeDownloadTask } from '@test-utils/task'
+import Database from 'better-sqlite3'
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
artifactContentEquals,
@@ -282,6 +288,191 @@ describe.runIf(existsSync(binary))(
}
})
+ it('publishes a synced suffix rename with no payload reads or writable reopen', async () => {
+ const { root, adapter, operations } = await setup()
+ const source = path.join(root, 'archive.zip.motrix')
+ const target = path.join(root, 'archive.zip')
+ await writeFile(source, 'payload')
+ if (process.platform !== 'win32') {
+ const caps = await adapter.capabilities()
+ vi.spyOn(adapter, 'capabilities').mockResolvedValue({
+ ...caps,
+ platform: 'windows',
+ syncedRenameGuard: true,
+ heldFileWriteExclusion: true,
+ })
+ vi.spyOn(adapter, 'openRenameGuard').mockImplementation(
+ async (heldRoot, name) => {
+ // Model a settled write time becoming visible when the flush handle closes.
+ await utimes(source, 100, 100)
+ const identity = await readRenameFileIdentity(source)
+ const artifact = await adapter.openArtifact(
+ heldRoot,
+ name,
+ 'rename'
+ )
+ return { handle: artifact, platformFileId: identity.platformFileId }
+ }
+ )
+ }
+ const hash = vi.spyOn(hashing, 'hashOpenedFile')
+ const writableSync = vi.spyOn(operations, 'makeDurable')
+ try {
+ const held = await operations.prepareFileRename(source, target)
+ if (!held) throw new Error('missing synced rename guard')
+ try {
+ const committer = new FinalizeCommitter({
+ fs: operations,
+ leases: new ArtifactMutationLeaseCoordinator([]),
+ repository: {
+ prepare: vi.fn(),
+ checkpoint: vi.fn(),
+ advance: vi.fn(),
+ commitTerminal: vi.fn(),
+ quarantine: vi.fn(),
+ listRecoverable: async () => [],
+ },
+ privatePathFor: () => '',
+ rollbackPathFor: () => '',
+ exactIdentity: artifactIdentityEquals,
+ sameContent: artifactContentEquals,
+ })
+ const result = await committer.commit(
+ {
+ planId: 'guarded',
+ taskId: 'guarded',
+ saveDir: root,
+ sourcePath: source,
+ targetPath: target,
+ sourceIdentity: held.sourceIdentity,
+ contributors: [],
+ metadataOps: [],
+ },
+ undefined,
+ held
+ )
+ await held.close()
+ expect(result.targetIdentity).toEqual(
+ await readRenameFileIdentity(target)
+ )
+ expect(await readFile(target, 'utf8')).toBe('payload')
+ expect(existsSync(source)).toBe(false)
+ expect(hash).not.toHaveBeenCalled()
+ expect(writableSync).not.toHaveBeenCalled()
+ } finally {
+ await held.close()
+ }
+ } finally {
+ await adapter.dispose()
+ }
+ })
+
+ it.each([
+ 'exact',
+ 'digest',
+ 'missing-digest',
+ 'wrong-digest',
+ 'both-names',
+ ] as const)(
+ 'retries an actual v2.3.0 SQLite source quarantine (%s)',
+ async (scenario) => {
+ const { root, adapter, operations } = await setup()
+ const db = new Database(':memory:')
+ migrate(db)
+ const source = path.join(root, 'download.zip.motrix')
+ const target = path.join(root, 'download.zip')
+ const payload = 'complete payload'
+ await writeFile(source, payload)
+ const original = await readRenameFileIdentity(source)
+ const repository = new SqliteFinalizeJournalRepository(db, {
+ commitTerminalBoundary: vi.fn(),
+ })
+ await repository.prepare({
+ journalId: 'old',
+ phase: 'prepared',
+ publicationMode: 'move',
+ plan: {
+ planId: 'old',
+ taskId: 'task',
+ saveDir: root,
+ sourcePath: source,
+ targetPath: target,
+ sourceIdentity: original,
+ contributors: [],
+ metadataOps: [],
+ },
+ })
+ await repository.quarantine('old', 'renamed source stamp changed')
+ if (scenario !== 'exact') {
+ const later = new Date(Date.now() + 10000)
+ await utimes(source, later, later)
+ }
+ if (scenario === 'both-names') await writeFile(target, 'other download')
+ const terminal = vi.fn((mutation: { journalId: string }) => {
+ db.prepare(
+ "UPDATE plugin_finalize_journals SET phase='db_committed', plan_json=json_set(plan_json, '$.phase', 'db_committed') WHERE plan_id=?"
+ ).run(mutation.journalId)
+ })
+ const runtime = new DurableFinalizeRuntime({
+ db,
+ fs: operations,
+ session: {
+ persistFinalizedArtifact: async (
+ _task,
+ _occurrence,
+ _input,
+ commit
+ ) => commit(terminal),
+ },
+ })
+ try {
+ const digest = createHash('sha256').update(payload).digest('hex')
+ const output = runtime.commit({
+ task: makeDownloadTask({ id: 'task', saveDir: root }),
+ occurrence: null,
+ sourcePath: source,
+ targetPath: target,
+ contributors: [],
+ metadataOps: [],
+ postDeliveries: [],
+ recoverySha256:
+ scenario === 'digest'
+ ? digest
+ : scenario === 'wrong-digest'
+ ? '0'.repeat(64)
+ : undefined,
+ })
+ if (scenario === 'exact' || scenario === 'digest') {
+ await expect(output).resolves.toMatchObject({
+ targetIdentity: { kind: 'file', sha256: digest },
+ })
+ expect(existsSync(source)).toBe(false)
+ expect(await readFile(target, 'utf8')).toBe(payload)
+ expect(terminal).toHaveBeenCalledOnce()
+ expect(await runtime.hasPendingFinalization('task')).toBe(false)
+ } else {
+ await expect(output).rejects.toThrow(
+ scenario === 'both-names'
+ ? 'final name already exists'
+ : 'SHA-256'
+ )
+ expect(await readFile(source, 'utf8')).toBe(payload)
+ expect(terminal).not.toHaveBeenCalled()
+ expect(
+ db
+ .prepare('SELECT plan_id,phase FROM plugin_finalize_journals')
+ .all()
+ ).toEqual([{ plan_id: 'old', phase: 'quarantined' }])
+ if (scenario === 'both-names')
+ expect(await readFile(target, 'utf8')).toBe('other download')
+ }
+ } finally {
+ db.close()
+ await adapter.dispose()
+ }
+ }
+ )
+
it.each([
{ platform: 'windows', heldFileWriteExclusion: undefined },
{ platform: 'windows', heldFileWriteExclusion: false },
diff --git a/src/core/plugin/finalize/native-artifact-operations.ts b/src/core/plugin/finalize/native-artifact-operations.ts
index 0dbac1fd..1617a59f 100644
--- a/src/core/plugin/finalize/native-artifact-operations.ts
+++ b/src/core/plugin/finalize/native-artifact-operations.ts
@@ -2,6 +2,7 @@ import { constants } from 'node:fs'
import { lstat, mkdtemp, open, readdir, rmdir, stat } from 'node:fs/promises'
import path from 'node:path'
import { ensureDirectory } from '@core/fs/ensure-directory'
+import { getLogger } from '@core/logger'
import {
type ArtifactIdentity,
ArtifactIdentityCache,
@@ -23,6 +24,7 @@ import type {
FinalizeIsolation,
FinalizeRemovalIntent,
FinalizeRemovalSurvivor,
+ PreparedFileRename,
} from './finalize-committer'
import {
reservationMatches,
@@ -189,6 +191,93 @@ export class NativeFinalizeArtifactOperations
}
}
+ async prepareFileRename(
+ sourcePath: string,
+ targetPath: string
+ ): Promise<PreparedFileRename | null> {
+ const caps = await this.adapter.capabilities()
+ if (
+ caps.platform !== 'windows' ||
+ !caps.heldFileWriteExclusion ||
+ !caps.syncedRenameGuard ||
+ !this.adapter.openRenameGuard
+ )
+ return null
+ if (
+ (sourcePath !== `${targetPath}.motrix` &&
+ targetPath !== `${sourcePath}.motrix`) ||
+ path.dirname(sourcePath) !== path.dirname(targetPath)
+ )
+ throw new Error('expected a same-directory suffix rename')
+ const entry = await lstat(sourcePath).catch((err) => {
+ if (err.code === 'ENOENT') return null
+ throw err
+ })
+ if (!entry?.isFile() || entry.isSymbolicLink()) return null
+ await this.assertSupported()
+ const root = await this.adapter.openRoot(path.dirname(sourcePath))
+ let guard: Awaited<
+ ReturnType<NonNullable<FinalizeFilesystemAdapter['openRenameGuard']>>
+ > = null
+ let transferred = false
+ let closed = false
+ const close = async () => {
+ if (closed) return
+ closed = true
+ // A dead sidecar releases its handles. A transport error closing a
+ // handle must not demote an already committed task or hide the cause.
+ for (const handle of [guard?.handle, root]) {
+ if (handle)
+ await this.adapter.close(handle).catch((err) => {
+ getLogger('finalize').warn({ err }, 'finalize_guard_close_failed')
+ })
+ }
+ }
+ try {
+ guard = await this.adapter
+ .openRenameGuard(root, path.basename(sourcePath))
+ .catch((error) => {
+ if (error instanceof FinalizeFsError && error.code === 'unsupported')
+ return null
+ throw error
+ })
+ if (!guard) return null
+ const sourceIdentity = await this.renameIdentity(sourcePath)
+ if (!sourceIdentity) return null
+ if (guard.platformFileId !== sourceIdentity.platformFileId)
+ throw new ArtifactIdentityError(
+ 'artifact_mutated',
+ 'source path does not identify the held file'
+ )
+ await this.adapter.syncRoot(root)
+ const artifact = guard.handle
+ transferred = true
+ return {
+ sourceIdentity,
+ close,
+ publish: async () => {
+ await this.requireIdentity(sourcePath, sourceIdentity)
+ const result = await this.adapter.renameOpenedNoReplace(
+ artifact,
+ root,
+ path.basename(targetPath)
+ )
+ if (!result)
+ throw new Error('held rename omitted directory durability')
+ const installed = await readRenameFileIdentity(targetPath)
+ if (!renameFileIdentityMatches(installed, sourceIdentity))
+ throw new ArtifactIdentityError(
+ 'artifact_mutated',
+ 'published name does not identify the held file'
+ )
+ return installed
+ },
+ }
+ } finally {
+ if (!transferred) await close()
+ }
+ }
+
private async supportsRenameIdentity(): Promise<boolean> {
const capabilities = await this.adapter.capabilities()
return (
diff --git a/src/core/session/durable-finalize-runtime.test.ts b/src/core/session/durable-finalize-runtime.test.ts
index 68467e3e..9e4f538e 100644
--- a/src/core/session/durable-finalize-runtime.test.ts
+++ b/src/core/session/durable-finalize-runtime.test.ts
@@ -185,9 +185,20 @@ describe('DurableFinalizeRuntime', () => {
])
const events: string[] = []
const fs = {
- renameIdentity: vi.fn(async () => {
+ prepareFileRename: vi.fn(async () => {
events.push('capture')
- return renameIdentity
+ return {
+ sourceIdentity: renameIdentity,
+ publish: async () => {
+ artifacts.delete(sourcePath)
+ artifacts.set(targetPath, installedIdentity)
+ events.push('publish')
+ return installedIdentity
+ },
+ close: async () => {
+ events.push('close')
+ },
+ }
}),
identity: vi.fn(
async (artifactPath: string, expected?: ArtifactIdentity) => {
@@ -197,17 +208,8 @@ describe('DurableFinalizeRuntime', () => {
),
sameFilesystem: async () => true,
materializePrivate: vi.fn(),
- moveNoReplace: vi.fn(
- async (
- _source: string,
- _expected: ArtifactIdentity,
- target: string
- ) => {
- artifacts.delete(sourcePath)
- artifacts.set(target, installedIdentity)
- return installedIdentity
- }
- ),
+ moveNoReplace: vi.fn(),
+ preflight: vi.fn(),
makeDurable: vi.fn(async () => undefined),
removeKnown: vi.fn(),
} satisfies FinalizeArtifactOperations
@@ -246,8 +248,20 @@ describe('DurableFinalizeRuntime', () => {
postDeliveries: [],
})
expect(result.targetIdentity).toEqual(installedIdentity)
- expect(events).toEqual(['quiesce', 'capture', 'release'])
- expect(fs.renameIdentity).toHaveBeenCalledExactlyOnceWith(sourcePath)
+ expect(events).toEqual([
+ 'quiesce',
+ 'capture',
+ 'publish',
+ 'close',
+ 'release',
+ ])
+ expect(fs.prepareFileRename).toHaveBeenCalledExactlyOnceWith(
+ sourcePath,
+ targetPath
+ )
+ expect(fs.preflight).not.toHaveBeenCalled()
+ expect(fs.makeDurable).not.toHaveBeenCalled()
+ expect(fs.moveNoReplace).not.toHaveBeenCalled()
expect(fs.materializePrivate).not.toHaveBeenCalled()
expect(fs.removeKnown).not.toHaveBeenCalled()
expect(
@@ -288,9 +302,7 @@ describe('DurableFinalizeRuntime', () => {
sha256: 'a'.repeat(64),
}
const fs = {
- renameIdentity: vi.fn(async () =>
- scenario === 'unsupported' ? null : renameIdentity
- ),
+ prepareFileRename: vi.fn(async () => null),
identity: vi.fn(async () => fullIdentity),
sameFilesystem: vi.fn(),
materializePrivate: vi.fn(),
@@ -338,7 +350,7 @@ describe('DurableFinalizeRuntime', () => {
postDeliveries: [],
})
).rejects.toThrow('captured content identity')
- expect(fs.renameIdentity).toHaveBeenCalledTimes(
+ expect(fs.prepareFileRename).toHaveBeenCalledTimes(
scenario === 'unsupported' ? 1 : 0
)
expect(fs.identity).toHaveBeenCalledWith(sourcePath)
diff --git a/src/core/session/durable-finalize-runtime.ts b/src/core/session/durable-finalize-runtime.ts
index f2284302..43558bd6 100644
--- a/src/core/session/durable-finalize-runtime.ts
+++ b/src/core/session/durable-finalize-runtime.ts
@@ -8,12 +8,17 @@ import {
artifactIdentityEquals,
} from '@core/plugin/finalize/artifact-identity'
import { ArtifactMutationLeaseCoordinator } from '@core/plugin/finalize/artifact-mutation-lease'
-import type { FinalizeArtifactOperations } from '@core/plugin/finalize/finalize-committer'
+import type {
+ FinalizeArtifactOperations,
+ FinalizeJournalRecord,
+ PreparedFileRename,
+} from '@core/plugin/finalize/finalize-committer'
import {
type FinalizeCommitResult,
FinalizeCommitter,
} from '@core/plugin/finalize/finalize-committer'
import { FinalizeRecovery } from '@core/plugin/finalize/finalize-recovery'
+import { FinalizeSourceVerificationError } from '@core/plugin/finalize/finalize-recovery-errors'
import {
assertFinalizePaths,
freezeHookPlan,
@@ -32,6 +37,7 @@ export interface DurableFinalizeArtifactInput {
occurrence: TaskOccurrence | null
sourcePath: string
targetPath: string
+ recoverySha256?: string
replacement?: { pluginId: string; stagedPath: string }
metadataOps: readonly StagedMetadataOp[]
contributors: readonly string[]
@@ -111,12 +117,32 @@ export class DurableFinalizeRuntime {
throw err
}
const lease = await this.leases.acquire(input.task.id)
+ let held: PreparedFileRename | null | undefined
try {
- await this.createRecovery().recoverTask(input.task.id, lease)
+ // A supplied digest authorizes only the old source quarantine. Avoid
+ // replaying an unrelated journal before proving this retry applies.
+ if (!input.recoverySha256)
+ await this.createRecovery().recoverTask(input.task.id, lease)
await input.verifySource?.()
- const pending = (
- await this.createRepository().listRecoverable(input.task.id)
- ).find((record) => record.publicationIntent?.method === 'reserved_rename')
+ const journals = this.createRepository()
+ const quarantined = journals.quarantinedSource(input.task.id)
+ if (input.recoverySha256 && !quarantined)
+ throw new Error('no quarantined source is awaiting verification')
+ if (
+ quarantined &&
+ (quarantined.plan.sourcePath !== input.sourcePath ||
+ quarantined.plan.targetPath !== targetPath ||
+ quarantined.plan.saveDir !== input.task.saveDir ||
+ input.replacement ||
+ input.contributors.length ||
+ input.metadataOps.length)
+ )
+ throw new Error(
+ 'source quarantine does not match the current finalize plan'
+ )
+ const pending = (await journals.listRecoverable(input.task.id)).find(
+ (record) => record.publicationIntent?.method === 'reserved_rename'
+ )
if (
pending &&
(!isOrdinarySuffixRemoval(pending.plan) ||
@@ -129,15 +155,32 @@ export class DurableFinalizeRuntime {
throw new Error('pending reserved publication does not match the retry')
// H8: identity capture is inside the mutation lease, after every
// engine/Host writer has successfully quiesced.
- const sourceIdentity =
- pending?.plan.sourceIdentity ??
- (!input.replacement &&
+ if (
+ !pending &&
+ !input.replacement &&
input.contributors.length === 0 &&
input.metadataOps.length === 0 &&
input.sourcePath === `${targetPath}.motrix` &&
path.dirname(input.sourcePath) === path.dirname(targetPath)
- ? await this.options.fs.renameIdentity?.(input.sourcePath)
- : undefined) ??
+ ) {
+ held = await this.options.fs.prepareFileRename?.(
+ input.sourcePath,
+ targetPath
+ )
+ }
+ const verifiedSource = quarantined
+ ? await this.verifyQuarantinedSource(quarantined, input.recoverySha256)
+ : undefined
+ if (quarantined && held) {
+ // Content authority survives closing the guard and is rechecked under
+ // the native publication handle. Keep its digest in the new journal.
+ await held.close()
+ held = null
+ }
+ const sourceIdentity =
+ verifiedSource ??
+ pending?.plan.sourceIdentity ??
+ held?.sourceIdentity ??
(await this.captureIdentity(input.sourcePath))
const replacement = input.replacement
? {
@@ -180,6 +223,7 @@ export class DurableFinalizeRuntime {
this.options.db,
{
now: this.now,
+ verifiedQuarantine: quarantined ?? undefined,
commitTerminalBoundary: (record) => {
if (!record.targetIdentity) {
throw new Error('finalize target identity is missing')
@@ -241,7 +285,7 @@ export class DurableFinalizeRuntime {
sameContent: artifactContentEquals,
})
input.beforeCommit?.()
- const result = await committer.commit(plan, lease)
+ const result = await committer.commit(plan, lease, held ?? undefined)
// SQLite's outer durable transaction has committed, but the session
// persistence lane is still held. Publish before queued autosaves.
input.onCommitted?.()
@@ -249,8 +293,53 @@ export class DurableFinalizeRuntime {
}
)
} finally {
- await lease.release()
+ try {
+ await held?.close()
+ } finally {
+ await lease.release()
+ }
+ }
+ }
+
+ private async verifyQuarantinedSource(
+ record: FinalizeJournalRecord,
+ sha256?: string
+ ) {
+ const { sourceIdentity: original, sourcePath, targetPath } = record.plan
+ if (original.kind !== 'rename-file')
+ throw new Error('invalid quarantined source')
+ if (await this.options.fs.identity(targetPath, original))
+ throw new Error('final name already exists; inspect it before retrying')
+ const checkStamp = async () => {
+ const current = await this.options.fs.identity(sourcePath, original)
+ if (
+ current?.kind !== 'rename-file' ||
+ current.platformFileId !== original.platformFileId ||
+ current.size !== original.size ||
+ current.birthtimeNs !== original.birthtimeNs
+ )
+ throw new Error(
+ 'the original temporary file is missing or was replaced; inspect both names'
+ )
+ if (!sha256 && !artifactIdentityEquals(current, original))
+ throw new FinalizeSourceVerificationError(
+ 'temporary file preserved; verify against the publisher’s SHA-256 or download to a new path'
+ )
}
+ await checkStamp()
+ const verified = await this.captureIdentity(sourcePath)
+ if (
+ verified.kind !== 'file' ||
+ verified.platformFileId !== original.platformFileId ||
+ verified.size !== original.size
+ )
+ throw new Error('source changed during quarantine verification')
+ if (sha256 && verified.sha256 !== sha256)
+ throw new FinalizeSourceVerificationError(
+ 'SHA-256 mismatch; temporary file preserved'
+ )
+ await checkStamp()
+ return verified
}
private async captureIdentity(artifactPath: string) {
diff --git a/src/core/session/finalize-journal-repository.test.ts b/src/core/session/finalize-journal-repository.test.ts
index 2f41eabc..d1abc122 100644
--- a/src/core/session/finalize-journal-repository.test.ts
+++ b/src/core/session/finalize-journal-repository.test.ts
@@ -32,6 +32,40 @@ describe('SqliteFinalizeJournalRepository', () => {
return record
}
+ it('exposes a quarantined rename to normal recovery only when it has a target checkpoint', async () => {
+ const repository = new SqliteFinalizeJournalRepository(db, {
+ commitTerminalBoundary: vi.fn(),
+ })
+ const record = renameRecord()
+ await repository.prepare(record)
+ await repository.quarantine(
+ record.journalId,
+ 'renamed source stamp changed'
+ )
+ expect(await repository.listRecoverable()).toEqual([])
+ expect(repository.quarantinedSource(record.plan.taskId)).toEqual(record)
+ db.prepare(
+ "UPDATE plugin_finalize_journals SET phase='prepared', quarantine_reason=NULL WHERE plan_id=?"
+ ).run(record.journalId)
+ const targetIdentity = {
+ ...(record.plan.sourceIdentity as RenameFileArtifactIdentity),
+ ctimeNs: '999',
+ }
+ await repository.advance(record.journalId, 'target_installed', {
+ targetIdentity,
+ })
+ await repository.quarantine(
+ record.journalId,
+ 'renamed source stamp changed'
+ )
+ const [candidate] = await repository.listRecoverable()
+ expect(candidate.targetIdentity).toEqual(targetIdentity)
+ await repository.resumeQuarantined(candidate)
+ expect((await repository.listRecoverable())[0].phase).toBe(
+ 'target_installed'
+ )
+ })
+
it('round-trips metadata-only identities and the changed stamp after rename', async () => {
const repository = new SqliteFinalizeJournalRepository(db, {
commitTerminalBoundary: vi.fn(),
diff --git a/src/core/session/finalize-journal-repository.ts b/src/core/session/finalize-journal-repository.ts
index a85a1268..d3018e16 100644
--- a/src/core/session/finalize-journal-repository.ts
+++ b/src/core/session/finalize-journal-repository.ts
@@ -10,6 +10,7 @@ import {
finalizePathsEquivalent,
} from '@core/plugin/finalize/finalize-committer'
import { isRetryableMoveQuarantine } from '@core/plugin/finalize/finalize-recovery'
+import { RENAMED_SOURCE_CHANGED } from '@core/plugin/finalize/finalize-recovery-errors'
import {
assertValidHookPlan,
isOrdinarySuffixRemoval,
@@ -35,6 +36,7 @@ interface RawFinalizeJournal {
export interface SqliteFinalizeJournalRepositoryOptions {
now?: () => number
+ verifiedQuarantine?: FinalizeJournalRecord
/**
* Must execute the complete task terminal transaction and move this journal
* from target_installed to db_committed within that same transaction.
@@ -74,7 +76,20 @@ export class SqliteFinalizeJournalRepository
| { plan_id: string; phase: RawFinalizeJournal['phase'] }
| undefined
if (prior) {
- if (prior.phase !== 'cleaned') {
+ const expected = this.options.verifiedQuarantine
+ if (expected) {
+ const current = this.quarantinedSource(record.plan.taskId)
+ if (
+ !current ||
+ JSON.stringify(current) !== JSON.stringify(expected) ||
+ current.plan.sourcePath !== record.plan.sourcePath ||
+ current.plan.targetPath !== record.plan.targetPath ||
+ record.plan.sourceIdentity.kind !== 'file' ||
+ !isOrdinarySuffixRemoval(record.plan) ||
+ record.publicationMode !== 'move'
+ )
+ throw new Error('verified source quarantine changed before retry')
+ } else if (prior.phase !== 'cleaned') {
throw new Error(
`task already has an unfinished finalize journal: ${prior.plan_id}`
)
@@ -82,10 +97,11 @@ export class SqliteFinalizeJournalRepository
this.db
.prepare(
`DELETE FROM plugin_finalize_journals
- WHERE task_id=? AND phase='cleaned'`
+ WHERE task_id=? AND plan_id=? AND phase=?`
)
- .run(record.plan.taskId)
- }
+ .run(record.plan.taskId, prior.plan_id, prior.phase)
+ } else if (this.options.verifiedQuarantine)
+ throw new Error('verified source quarantine disappeared before retry')
this.db
.prepare(
`INSERT INTO plugin_finalize_journals (
@@ -262,6 +278,25 @@ export class SqliteFinalizeJournalRepository
return records
}
+ /** This legacy row still owns the task until prepare atomically replaces it. */
+ quarantinedSource(taskId: string): FinalizeJournalRecord | null {
+ const raw = this.db
+ .prepare(
+ "SELECT * FROM plugin_finalize_journals WHERE task_id=? AND phase='quarantined' AND quarantine_reason=?"
+ )
+ .get(taskId, RENAMED_SOURCE_CHANGED) as RawFinalizeJournal | undefined
+ if (!raw) return null
+ const record = parseRecord({ ...raw, phase: 'prepared' })
+ if (
+ record.plan.sourceIdentity.kind !== 'rename-file' ||
+ record.targetIdentity ||
+ raw.target_identity_json !== null ||
+ record.restoredSourceIdentity
+ )
+ throw new Error('source quarantine has a conflicting target checkpoint')
+ return record
+ }
+
async resumeQuarantined(record: FinalizeJournalRecord): Promise<void> {
this.durableTransaction(() => {
const raw = this.readRaw(record.journalId)
@@ -320,9 +355,12 @@ export class SqliteFinalizeJournalRepository
function parseQuarantinedMove(
raw: RawFinalizeJournal
): FinalizeJournalRecord | null {
+ const sourceChanged = raw.quarantine_reason === RENAMED_SOURCE_CHANGED
if (
raw.phase !== 'quarantined' ||
- !raw.quarantine_reason?.startsWith('compensation failed after ')
+ !raw.quarantine_reason ||
+ (!sourceChanged &&
+ !raw.quarantine_reason.startsWith('compensation failed after '))
)
return null
const value: unknown = JSON.parse(raw.plan_json)
@@ -330,13 +368,20 @@ function parseQuarantinedMove(
!value ||
typeof value !== 'object' ||
!('phase' in value) ||
- (value.phase !== 'prepared' && value.phase !== 'target_installed')
+ (value.phase !== 'prepared' &&
+ value.phase !== 'target_installed' &&
+ value.phase !== 'db_committed')
)
return null
const record = {
...parseRecord({ ...raw, phase: value.phase }),
quarantineReason: raw.quarantine_reason,
}
+ if (sourceChanged)
+ return record.plan.sourceIdentity.kind === 'rename-file' &&
+ record.targetIdentity
+ ? record
+ : null
return isRetryableMoveQuarantine(record) ? record : null
}
diff --git a/src/core/task/actions/finalize-task.ts b/src/core/task/actions/finalize-task.ts
index 21ad5fe9..082e5243 100644
--- a/src/core/task/actions/finalize-task.ts
+++ b/src/core/task/actions/finalize-task.ts
@@ -6,6 +6,7 @@ import {
isInactiveLegacyTask,
} from '@core/legacy-import/legacy-task-policy'
import { newEngineTaskId } from '@core/lib/ids'
+import { FinalizeSourceVerificationError } from '@core/plugin/finalize/finalize-recovery-errors'
import type { HookAuditLog } from '@core/plugin/hooks/audit-log'
import type { HookOrchestrator } from '@core/plugin/hooks/hook-orchestrator'
import type { StagedMetadataOp } from '@core/plugin/hooks/staged-effects'
@@ -165,6 +166,7 @@ export interface FinalizeTaskDeps {
* that never publish an unsafe name can omit it.
*/
finalNamePicker?: Pick<FinalNamePicker, 'pick'>
+ recoverySha256?: string
commitFinalizedArtifact?: (
input: FinalizeArtifactCommitRequest
) => Promise<void>
@@ -175,6 +177,7 @@ export interface FinalizeArtifactCommitRequest {
occurrence: TaskOccurrence | null
sourcePath: string
targetPath: string
+ recoverySha256?: string
replacement?: { pluginId: string; stagedPath: string }
metadataOps: readonly StagedMetadataOp[]
contributors: readonly string[]
@@ -394,7 +397,10 @@ async function finalizeHttp(
const errorMessage = `Failed to commit finalized file: ${cause}`
await failFinalize(task, deps, {
errorMessage,
- errorDetailKey: 'task.error.detail.renameFileFailed',
+ errorDetailKey:
+ e instanceof FinalizeSourceVerificationError
+ ? 'task.error.detail.sourceHash'
+ : 'task.error.detail.renameFileFailed',
errorDetailParams: { cause },
hookCode: 'TASK_FINALIZE_RENAME_FAILED',
})
@@ -487,6 +493,7 @@ async function commitHttpArtifactDurably(
occurrence,
sourcePath: renameSource,
targetPath: desiredFinalPath,
+ ...(deps.recoverySha256 ? { recoverySha256: deps.recoverySha256 } : {}),
replacement: finalizeOutcome.replacement,
metadataOps: finalizeOutcome.metadataOps,
contributors: finalizeOutcome.contributors,
diff --git a/src/core/task/actions/re-add-task.ts b/src/core/task/actions/re-add-task.ts
index 2392c0c9..f4b5dc89 100644
--- a/src/core/task/actions/re-add-task.ts
+++ b/src/core/task/actions/re-add-task.ts
@@ -9,6 +9,7 @@ import type { DownloadTask } from '@shared/types/task'
import {
TaskInstancePhase,
TaskStatus,
+ TaskType,
TransitionPhase,
} from '@shared/types/task'
import {
@@ -50,7 +51,7 @@ import type { TorrentMetaStore } from '../torrent-meta-store'
import { commitTaskUpdate, getTaskOrWarn, type TaskActionDeps } from './shared'
export interface ReAddTaskDeps extends TaskActionDeps {
- recoverFinalization?: (taskId: string) => Promise<void>
+ recoverFinalization?: (taskId: string, sha256?: string) => Promise<void>
runTaskMutation: NonNullable<TaskActionDeps['runTaskMutation']>
persistTask: NonNullable<TaskActionDeps['persistTask']>
torrentMetaStore: TorrentMetaStore
@@ -500,10 +501,20 @@ async function handleFailedEngineAdd(
*/
export async function reAddTask(
taskId: string,
- deps: ReAddTaskDeps
+ deps: ReAddTaskDeps,
+ sha256?: string
): Promise<void> {
const task = deps.taskManager.getById(taskId)
if (task) assertLegacyTaskNotRecreated(task)
+ if (
+ sha256 &&
+ (task?.type !== TaskType.Http ||
+ task.transitionPhase !== TransitionPhase.Renaming)
+ )
+ throw new AppError(
+ ErrorCode.TaskNotRetryable,
+ 'no HTTP source is awaiting verification'
+ )
if (
task &&
(task.transitionPhase === TransitionPhase.Renaming ||
@@ -516,7 +527,8 @@ export async function reAddTask(
)
}
await deps.authorizeTaskWrite?.(task)
- await deps.recoverFinalization(taskId)
+ if (sha256) await deps.recoverFinalization(taskId, sha256)
+ else await deps.recoverFinalization(taskId)
return
}
const run = (
diff --git a/src/core/task/http-finalize.integration.test.ts b/src/core/task/http-finalize.integration.test.ts
new file mode 100644
index 00000000..703dc24f
--- /dev/null
+++ b/src/core/task/http-finalize.integration.test.ts
@@ -0,0 +1,127 @@
+import { execFile } from 'node:child_process'
+import { existsSync } from 'node:fs'
+import { mkdtemp, readFile, realpath, rm } from 'node:fs/promises'
+import { createServer } from 'node:http'
+import os from 'node:os'
+import path from 'node:path'
+import { promisify } from 'node:util'
+import { NativeFinalizeFilesystemAdapter } from '@core/plugin/finalize/filesystem-adapter'
+import { NativeFinalizeArtifactOperations } from '@core/plugin/finalize/native-artifact-operations'
+import { DurableFinalizeRuntime } from '@core/session/durable-finalize-runtime'
+import { migrate } from '@core/session/migrations'
+import {
+ bundledAria2Exists,
+ canBindLoopbackTcp,
+ resolveBundledAria2,
+} from '@test-utils/aria2'
+import { makeDownloadTask } from '@test-utils/task'
+import Database from 'better-sqlite3'
+import { expect, it } from 'vitest'
+
+const helper =
+ process.env.MOTRIX_FINALIZE_FS_TEST_BIN ??
+ path.resolve(
+ 'packages/finalize-fs/target/debug',
+ process.platform === 'win32'
+ ? 'motrix-finalize-fs.exe'
+ : 'motrix-finalize-fs'
+ )
+
+// Packaging supplies both native binaries. A missing configured binary must
+// fail that job; source-only checkouts can run the filesystem suite separately.
+it.runIf(
+ process.env.MOTRIX_ARIA2_TEST_BIN ||
+ (bundledAria2Exists() && existsSync(helper) && canBindLoopbackTcp())
+)(
+ 'publishes completed aria2 HTTP downloads through the SQLite journal',
+ async () => {
+ const root = await realpath(
+ await mkdtemp(path.join(os.tmpdir(), 'motrix-http-finalize-'))
+ )
+ const adapter = new NativeFinalizeFilesystemAdapter(path.resolve(helper))
+ const db = new Database(':memory:')
+ const bytes = Buffer.alloc(512 * 1024, 0x51)
+ const server = createServer((_request, response) => {
+ response.writeHead(200, {
+ 'Content-Length': bytes.length,
+ 'Last-Modified': new Date(100000).toUTCString(),
+ })
+ response.end(bytes)
+ })
+ try {
+ migrate(db)
+ const runtime = new DurableFinalizeRuntime({
+ db,
+ fs: new NativeFinalizeArtifactOperations(adapter),
+ session: {
+ persistFinalizedArtifact: async (
+ _task,
+ _occurrence,
+ _input,
+ install
+ ) =>
+ install(({ journalId }) => {
+ db.prepare(
+ "UPDATE plugin_finalize_journals SET phase='db_committed', plan_json=json_set(plan_json,'$.phase','db_committed') WHERE plan_id=? AND phase='target_installed'"
+ ).run(journalId)
+ }),
+ },
+ })
+ await new Promise<void>((resolve, reject) => {
+ server.once('error', reject)
+ server.listen(0, '127.0.0.1', resolve)
+ })
+ const address = server.address()
+ if (!address || typeof address === 'string')
+ throw new Error('expected listener port')
+ for (const name of ['installer.exe', 'archive.zip']) {
+ const targetPath = path.join(root, name)
+ const sourcePath = `${targetPath}.motrix`
+ await promisify(execFile)(
+ resolveBundledAria2(),
+ [
+ '--no-conf',
+ '--file-allocation=none',
+ '--remote-time=true',
+ '--dir',
+ root,
+ '--out',
+ `${name}.motrix`,
+ `http://127.0.0.1:${address.port}/${name}`,
+ ],
+ { timeout: 15000 }
+ )
+ const result = await runtime.commit({
+ task: makeDownloadTask({
+ id: name,
+ saveDir: root,
+ diskPath: sourcePath,
+ finalPath: targetPath,
+ }),
+ occurrence: null,
+ sourcePath,
+ targetPath,
+ contributors: [],
+ metadataOps: [],
+ postDeliveries: [],
+ })
+ expect(existsSync(sourcePath)).toBe(false)
+ expect(await readFile(targetPath)).toEqual(bytes)
+ expect(
+ db
+ .prepare(
+ 'SELECT phase FROM plugin_finalize_journals WHERE plan_id=?'
+ )
+ .get(result.journalId)
+ ).toEqual({ phase: 'cleaned' })
+ }
+ } finally {
+ if (server.listening)
+ await new Promise<void>((resolve) => server.close(() => resolve()))
+ await adapter.dispose()
+ db.close()
+ await rm(root, { recursive: true, force: true })
+ }
+ },
+ 45000
+)
diff --git a/src/core/task/task-recovery-service.ts b/src/core/task/task-recovery-service.ts
index e18055c0..d2d3ee79 100644
--- a/src/core/task/task-recovery-service.ts
+++ b/src/core/task/task-recovery-service.ts
@@ -131,7 +131,7 @@ export interface RecoveryDeps {
adapter: Pick<EngineAdapter, 'listActiveAndWaiting'>
fs: RecoveryFs
activityRecorder: TaskActivityRecorder
- finalizeTask: (taskId: string) => Promise<void>
+ finalizeTask: (taskId: string, sha256?: string) => Promise<void>
/** Defer ownership and completion to the journal before interpreting path existence. */
hasPendingFinalization?: (taskId: string) => Promise<boolean>
/**
@@ -187,11 +187,17 @@ export class TaskRecoveryServiceImpl implements TaskRecoveryService {
return this.recover()
}
- async recoverTaskById(taskId: string): Promise<RecoveryReport> {
- return this.recover(taskId)
+ async recoverTaskById(
+ taskId: string,
+ sha256?: string
+ ): Promise<RecoveryReport> {
+ return this.recover(taskId, sha256)
}
- private async recover(taskId?: string): Promise<RecoveryReport> {
+ private async recover(
+ taskId?: string,
+ sha256?: string
+ ): Promise<RecoveryReport> {
const start = Date.now()
const report: RecoveryReport = {
totalScanned: 0,
@@ -268,7 +274,8 @@ export class TaskRecoveryServiceImpl implements TaskRecoveryService {
byInfoHash,
ownerByGid,
taskIdsByInfoHash,
- report
+ report,
+ sha256
)
} catch (error) {
// Publish failure while still holding the same task mutation lock.
@@ -341,20 +348,24 @@ export class TaskRecoveryServiceImpl implements TaskRecoveryService {
byInfoHash: Map<string, Set<string>>,
ownerByGid: Map<string, string>,
taskIdsByInfoHash: Map<string, Set<string>>,
- report: RecoveryReport
+ report: RecoveryReport,
+ sha256?: string
): Promise<void> {
if (
task.transitionPhase === TransitionPhase.Renaming &&
!isMediaKind(task.kind) &&
(await this.deps.hasPendingFinalization?.(task.id))
) {
- await this.deps.finalizeTask(task.id)
+ if (sha256) await this.deps.finalizeTask(task.id, sha256)
+ else await this.deps.finalizeTask(task.id)
report.recovered.push({
taskId: task.id,
action: RecoveryAction.ResumeFromRename,
})
return
}
+ if (sha256)
+ throw new Error('no pending finalize journal for checksum verification')
const fsState = await this.inspectFs(task)
const matchingGid = this.selectMatchingGid(
task,
diff --git a/src/main/index.ts b/src/main/index.ts
index e95dd2e4..6fd96bf3 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -1468,7 +1468,8 @@ async function startEngineAndRestore(
listActiveAndWaiting: () => adapter.listActiveAndWaiting(),
},
fs: defaultRecoveryFs,
- finalizeTask: (taskId) => finalizeTask(taskId, finalizeDepsFactory()),
+ finalizeTask: (taskId, recoverySha256) =>
+ finalizeTask(taskId, { ...finalizeDepsFactory(), recoverySha256 }),
activityRecorder: requireTaskActivityService(),
recordTransition: (input: RuntimeTransitionInput) =>
taskInspectorActivityRuntime?.recordTransition(input),
@@ -3052,10 +3053,10 @@ async function initializeMainProcess(): Promise<void> {
bindTaskRetry: (fn) => {
dnsFallbackRetry = fn
},
- recoverFinalization: async (taskId) => {
+ recoverFinalization: async (taskId, sha256) => {
if (!recoveryService) throw new Error('Task recovery is not ready')
try {
- const report = await recoveryService.recoverTaskById(taskId)
+ const report = await recoveryService.recoverTaskById(taskId, sha256)
if (report.errors.length > 0) throw new Error(report.errors[0].issue)
} finally {
publishTaskUpdateNow()
diff --git a/src/main/ipc/commands.ts b/src/main/ipc/commands.ts
index a141ac20..b0e93b7c 100644
--- a/src/main/ipc/commands.ts
+++ b/src/main/ipc/commands.ts
@@ -119,6 +119,7 @@ import {
import { appImageNativeHostActionSchema } from '@shared/schemas/appimage-native-host'
import { btStorageRequestSchema } from '@shared/schemas/bt-storage'
import {
+ reAddTaskPayloadSchema,
removeTasksPayloadSchema,
taskIdsPayloadSchema,
} from '@shared/schemas/bulk-task-command'
@@ -210,7 +211,7 @@ export interface CommandContext {
* paths cannot drift. Called synchronously during handler construction.
*/
bindTaskRetry?: (fn: (taskId: string) => Promise<unknown>) => void
- recoverFinalization?: (taskId: string) => Promise<void>
+ recoverFinalization?: (taskId: string, sha256?: string) => Promise<void>
sessionManager: SessionManager
settingsManager: SettingsManager
applyLocale?: (language: string) => Promise<void>
@@ -933,8 +934,9 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {
return { ok: true }
},
- [Commands.ReAddTask]: async (taskId: string) => {
- await reAddTask(taskId, reAddDeps)
+ [Commands.ReAddTask]: async (rawPayload: unknown) => {
+ const { taskId, sha256 } = reAddTaskPayloadSchema.parse(rawPayload)
+ await reAddTask(taskId, reAddDeps, sha256)
return { ok: true }
},
diff --git a/src/renderer/routes/downloads/inspector/overview-tab.test.tsx b/src/renderer/routes/downloads/inspector/overview-tab.test.tsx
index a98c8c53..bd5d3737 100644
--- a/src/renderer/routes/downloads/inspector/overview-tab.test.tsx
+++ b/src/renderer/routes/downloads/inspector/overview-tab.test.tsx
@@ -249,6 +249,30 @@ describe('OverviewTab', () => {
])
})
+ it('submits the publisher digest only with the quarantined task retry', async () => {
+ renderOverviewTab({
+ ...task,
+ id: 'quarantined',
+ status: TaskStatus.Error,
+ type: TaskType.Http,
+ kind: TaskKind.Direct,
+ transitionPhase: TransitionPhase.Renaming,
+ errorDetailKey: 'task.error.detail.sourceHash',
+ })
+ const input = screen.getByRole('textbox')
+ const retry = screen.getByRole('button', { name: 'Retry' })
+ expect(retry).toBeDisabled()
+ fireEvent.change(input, { target: { value: 'abc' } })
+ expect(retry).toBeDisabled()
+ const digest = 'ac'.repeat(32)
+ fireEvent.change(input, { target: { value: digest } })
+ await userEvent.click(retry)
+ expect(transport.invoke).toHaveBeenCalledWith(Commands.ReAddTask, {
+ taskId: 'quarantined',
+ sha256: digest,
+ })
+ })
+
it('adds Retry to the timeout Alert for unresolved magnet metadata', () => {
renderOverviewTab({
...task,
diff --git a/src/renderer/routes/downloads/inspector/overview-tab.tsx b/src/renderer/routes/downloads/inspector/overview-tab.tsx
index 64b73076..f354c097 100644
--- a/src/renderer/routes/downloads/inspector/overview-tab.tsx
+++ b/src/renderer/routes/downloads/inspector/overview-tab.tsx
@@ -7,6 +7,7 @@ import {
AlertTitle,
} from '@renderer/components/ui/alert'
import { Button } from '@renderer/components/ui/button'
+import { Input } from '@renderer/components/ui/input'
import {
Tooltip,
TooltipContent,
@@ -26,6 +27,7 @@ import {
isMediaTask,
mediaProgressPercent,
} from '@shared/utils/media-progress'
+import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { StatusPill } from '../status-pill'
import { getTaskEta, getTaskSpeed } from '../task-column-values'
@@ -74,6 +76,9 @@ function Row({
function ErrorPanel({ task }: { task: DownloadTask }) {
const { t, i18n } = useTranslation()
const { onRetry } = useTaskActions([task])
+ const [sha256, setSha256] = useState('')
+ const [verifying, setVerifying] = useState(false)
+ const needsDigest = task.errorDetailKey === 'task.error.detail.sourceHash'
const failure = resolveFailureReason(
{
errorCode: task.errorCode,
@@ -100,7 +105,38 @@ function ErrorPanel({ task }: { task: DownloadTask }) {
)}
</AlertDescription>
)}
- {showRetry && (
+ {needsDigest && showRetry && (
+ <form
+ className="col-start-2 flex items-center gap-2"
+ onSubmit={async (event) => {
+ event.preventDefault()
+ if (verifying || !/^[0-9a-f]{64}$/i.test(sha256.trim())) return
+ setVerifying(true)
+ try {
+ await onRetry({ alt: false, sha256: sha256.trim() })
+ } finally {
+ setVerifying(false)
+ }
+ }}
+ >
+ <Input
+ aria-label={t('task.error.detail.sourceHash')}
+ placeholder="SHA-256"
+ value={sha256}
+ onChange={(event) => setSha256(event.target.value)}
+ autoComplete="off"
+ spellCheck={false}
+ />
+ <Button
+ size="xs"
+ type="submit"
+ disabled={verifying || !/^[0-9a-f]{64}$/i.test(sha256.trim())}
+ >
+ {t('panel.downloads.action.retry')}
+ </Button>
+ </form>
+ )}
+ {showRetry && !needsDigest && (
<AlertAction>
<Button
size="xs"
@@ -138,7 +174,9 @@ export function OverviewTab({
const isBt = task.type === TaskType.Bt || task.type === TaskType.Magnet
return (
<div className="flex flex-col gap-3">
- {task.status === TaskStatus.Error && <ErrorPanel task={task} />}
+ {task.status === TaskStatus.Error && (
+ <ErrorPanel key={task.id} task={task} />
+ )}
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">
<Card title={t('panel.downloads.inspector.overview.transfer')}>
<Row
diff --git a/src/renderer/routes/downloads/inspector/use-task-actions.ts b/src/renderer/routes/downloads/inspector/use-task-actions.ts
index a92c48bb..a144f3eb 100644
--- a/src/renderer/routes/downloads/inspector/use-task-actions.ts
+++ b/src/renderer/routes/downloads/inspector/use-task-actions.ts
@@ -169,7 +169,7 @@ export interface TaskActionsState {
onResume: () => Promise<void>
onStopSeeding: () => Promise<void>
onReseed: (modifier?: { alt: boolean }) => Promise<void>
- onRetry: (modifier?: { alt: boolean }) => Promise<void>
+ onRetry: (modifier?: { alt: boolean; sha256?: string }) => Promise<void>
onRedownload: (modifier?: { alt: boolean }) => Promise<void>
closeRedownloadOverwriteDialog: () => void
confirmRedownloadOverwrite: () => Promise<void>
@@ -370,10 +370,24 @@ export function useTaskActions(
)
const onRetry = useCallback(
- async (modifier?: { alt: boolean }) => {
+ async (modifier?: { alt: boolean; sha256?: string }) => {
if (!readyToWrite()) return
const sessionEpoch = useOperatorSession.getState().epoch
let targets = resolveLatest(selected)
+ if (modifier?.sha256) {
+ const [task] = targets
+ if (targets.length !== 1 || !task || !canOfferRetry(task)) return
+ try {
+ await transport.invoke(Commands.ReAddTask, {
+ taskId: task.id,
+ sha256: modifier.sha256,
+ })
+ invalidateTaskList()
+ } catch (error) {
+ reportPartial([{ ok: false, task, reason: errMsg(error) }])
+ }
+ return
+ }
const candidates = modifier?.alt
? []
: targets.filter(
diff --git a/src/server/index.ts b/src/server/index.ts
index 80f06d1f..97bacc54 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -1252,10 +1252,10 @@ async function main() {
bindTaskRetry: (fn) => {
dnsFallbackRetry = fn
},
- recoverFinalization: async (taskId) => {
+ recoverFinalization: async (taskId, sha256) => {
if (!recoveryService) throw new Error('Task recovery is not ready')
try {
- const report = await recoveryService.recoverTaskById(taskId)
+ const report = await recoveryService.recoverTaskById(taskId, sha256)
if (report.errors.length > 0) throw new Error(report.errors[0].issue)
} finally {
publishTaskUpdateNow()
@@ -1742,7 +1742,8 @@ async function main() {
listActiveAndWaiting: () => adapter.listActiveAndWaiting(),
},
fs: defaultRecoveryFs,
- finalizeTask: (taskId) => finalizeTask(taskId, buildFinalizeDeps()),
+ finalizeTask: (taskId, recoverySha256) =>
+ finalizeTask(taskId, { ...buildFinalizeDeps(), recoverySha256 }),
activityRecorder: taskActivityService,
recordTransition: (input: RuntimeTransitionInput) =>
taskInspectorActivityRuntime.recordTransition(input),
diff --git a/src/server/ipc/commands.ts b/src/server/ipc/commands.ts
index 57dcf83e..503e77b2 100644
--- a/src/server/ipc/commands.ts
+++ b/src/server/ipc/commands.ts
@@ -89,6 +89,7 @@ import type { CommandHandlerMap } from '@shared/protocol/handler-types'
import { taskCreateRequestSchema } from '@shared/schemas/add-task'
import { btStorageRequestSchema } from '@shared/schemas/bt-storage'
import {
+ reAddTaskPayloadSchema,
removeTasksPayloadSchema,
taskIdsPayloadSchema,
} from '@shared/schemas/bulk-task-command'
@@ -148,7 +149,7 @@ export interface ServerCommandContext {
* paths cannot drift. Called synchronously during handler construction.
*/
bindTaskRetry?: (fn: (taskId: string) => Promise<unknown>) => void
- recoverFinalization?: (taskId: string) => Promise<void>
+ recoverFinalization?: (taskId: string, sha256?: string) => Promise<void>
rpcClient: Aria2RpcClient
adapter: EngineAdapter
trackerManager: TrackerManager
@@ -810,8 +811,9 @@ export function buildServerCommandHandlers(
return { ok: true }
},
- [Commands.ReAddTask]: async (taskId: string) => {
- await reAddTask(taskId, reAddDeps)
+ [Commands.ReAddTask]: async (rawPayload: unknown) => {
+ const { taskId, sha256 } = reAddTaskPayloadSchema.parse(rawPayload)
+ await reAddTask(taskId, reAddDeps, sha256)
return { ok: true }
},
diff --git a/src/shared/locales/ar.json b/src/shared/locales/ar.json
index 5e402987..16c0e2e0 100644
--- a/src/shared/locales/ar.json
+++ b/src/shared/locales/ar.json
@@ -2984,6 +2984,7 @@
"recoveryFailed": "تعذّرت استعادة التنزيل: {{cause}}",
"recoveryOutputConflict": "يوجد الملف المؤقت والنهائي معًا؛ حُفظ كلاهما للمراجعة اليدوية",
"renameDirFailed": "تعذّرت إعادة تسمية المجلد: {{cause}}",
+ "sourceHash": "SHA-256 من الناشر",
"renameFileFailed": "تعذّرت إعادة تسمية الملف: {{cause}}"
},
"hint": {
diff --git a/src/shared/locales/bg.json b/src/shared/locales/bg.json
index f868243b..6acae19f 100644
--- a/src/shared/locales/bg.json
+++ b/src/shared/locales/bg.json
@@ -2900,6 +2900,7 @@
"recoveryFailed": "Изтеглянето не можа да бъде възстановено: {{cause}}",
"recoveryOutputConflict": "Съществуват както временният, така и крайният файл; и двата са запазени за ръчна проверка",
"renameDirFailed": "Папката не можа да бъде преименувана: {{cause}}",
+ "sourceHash": "SHA-256 от издателя",
"renameFileFailed": "Файлът не можа да бъде преименуван: {{cause}}"
},
"hint": {
diff --git a/src/shared/locales/ca.json b/src/shared/locales/ca.json
index 6043bee5..c9b85137 100644
--- a/src/shared/locales/ca.json
+++ b/src/shared/locales/ca.json
@@ -2921,6 +2921,7 @@
"recoveryFailed": "No s'ha pogut recuperar la baixada: {{cause}}",
"recoveryOutputConflict": "Existeixen tant el fitxer temporal com el final; s'han conservat tots dos per revisar-los manualment",
"renameDirFailed": "No s'ha pogut canviar el nom de la carpeta: {{cause}}",
+ "sourceHash": "SHA-256 de l’editor",
"renameFileFailed": "No s'ha pogut canviar el nom del fitxer: {{cause}}"
},
"hint": {
diff --git a/src/shared/locales/de.json b/src/shared/locales/de.json
index ad926d25..6714a855 100644
--- a/src/shared/locales/de.json
+++ b/src/shared/locales/de.json
@@ -1189,6 +1189,7 @@
"recoveryFailed": "Der Download konnte nicht wiederhergestellt werden: {{cause}}",
"recoveryOutputConflict": "Sowohl die temporäre als auch die endgültige Datei sind vorhanden; beide wurden zur manuellen Prüfung beibehalten",
"filesMissing": "Nach dem Neustart der Anwendung fehlen Dateien",
+ "sourceHash": "SHA-256 des Herausgebers",
"renameFileFailed": "Die Datei konnte nicht umbenannt werden: {{cause}}",
"renameDirFailed": "Der Ordner konnte nicht umbenannt werden: {{cause}}",
"pluginChainAborted": "Plugin-Kette abgebrochen: {{cause}}",
diff --git a/src/shared/locales/el.json b/src/shared/locales/el.json
index ed67df8f..addeeb98 100644
--- a/src/shared/locales/el.json
+++ b/src/shared/locales/el.json
@@ -2900,6 +2900,7 @@
"recoveryFailed": "Δεν ήταν δυνατή η ανάκτηση της λήψης: {{cause}}",
"recoveryOutputConflict": "Υπάρχουν και το προσωρινό και το τελικό αρχείο· διατηρήθηκαν και τα δύο για χειροκίνητο έλεγχο",
"renameDirFailed": "Δεν ήταν δυνατή η μετονομασία του φακέλου: {{cause}}",
+ "sourceHash": "SHA-256 του εκδότη",
"renameFileFailed": "Δεν ήταν δυνατή η μετονομασία του αρχείου: {{cause}}"
},
"hint": {
diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.json
index acbcf695..a0dd8065 100644
--- a/src/shared/locales/en-US.json
+++ b/src/shared/locales/en-US.json
@@ -1189,6 +1189,7 @@
"recoveryFailed": "Could not recover the download: {{cause}}",
"recoveryOutputConflict": "Both the temporary and final files exist; both were preserved for manual review",
"filesMissing": "Files are missing after the app restarted",
+ "sourceHash": "Publisher’s SHA-256",
"renameFileFailed": "Failed to rename the file: {{cause}}",
"renameDirFailed": "Failed to rename the directory: {{cause}}",
"pluginChainAborted": "Plugin chain aborted: {{cause}}",
diff --git a/src/shared/locales/es.json b/src/shared/locales/es.json
index 4a9ae305..48ef5a68 100644
--- a/src/shared/locales/es.json
+++ b/src/shared/locales/es.json
@@ -1203,6 +1203,7 @@
"recoveryFailed": "No se pudo recuperar la descarga: {{cause}}",
"recoveryOutputConflict": "Existen tanto el archivo temporal como el final; ambos se conservaron para su revisión manual",
"filesMissing": "Faltan archivos tras reiniciar la aplicación",
+ "sourceHash": "SHA-256 del editor",
"renameFileFailed": "No se pudo cambiar el nombre del archivo: {{cause}}",
"renameDirFailed": "No se pudo cambiar el nombre de la carpeta: {{cause}}",
"pluginChainAborted": "Cadena de plugins interrumpida: {{cause}}",
diff --git a/src/shared/locales/fa.json b/src/shared/locales/fa.json
index 7160b58e..8ff061b2 100644
--- a/src/shared/locales/fa.json
+++ b/src/shared/locales/fa.json
@@ -2900,6 +2900,7 @@
"recoveryFailed": "بازیابی دانلود ممکن نشد: {{cause}}",
"recoveryOutputConflict": "هم فایل موقت و هم فایل نهایی وجود دارند؛ هر دو برای بررسی دستی حفظ شدند",
"renameDirFailed": "تغییر نام پوشه ناموفق بود: {{cause}}",
+ "sourceHash": "SHA-256 ناشر",
"renameFileFailed": "تغییر نام فایل ناموفق بود: {{cause}}"
},
"hint": {
diff --git a/src/shared/locales/fr.json b/src/shared/locales/fr.json
index 361d5100..8af3dd52 100644
--- a/src/shared/locales/fr.json
+++ b/src/shared/locales/fr.json
@@ -2921,6 +2921,7 @@
"recoveryFailed": "Impossible de récupérer le téléchargement : {{cause}}",
"recoveryOutputConflict": "Le fichier temporaire et le fichier final existent tous deux ; ils ont été conservés pour vérification manuelle",
"renameDirFailed": "Impossible de renommer le dossier : {{cause}}",
+ "sourceHash": "SHA-256 de l’éditeur",
"renameFileFailed": "Impossible de renommer le fichier : {{cause}}"
},
"hint": {
diff --git a/src/shared/locales/hu.json b/src/shared/locales/hu.json
index 594f9a46..87e6b500 100644
--- a/src/shared/locales/hu.json
+++ b/src/shared/locales/hu.json
@@ -1189,6 +1189,7 @@
"recoveryFailed": "Nem sikerült helyreállítani a letöltést: {{cause}}",
"recoveryOutputConflict": "Az ideiglenes és a végleges fájl is létezik; mindkettő megmaradt kézi ellenőrzésre",
"filesMissing": "Az alkalmazás újraindítása után egyes fájlok hiányoznak",
+ "sourceHash": "A kiadó SHA-256 értéke",
"renameFileFailed": "Nem sikerült átnevezni a fájlt: {{cause}}",
"renameDirFailed": "Nem sikerült átnevezni a mappát: {{cause}}",
"pluginChainAborted": "A bővítménylánc megszakadt: {{cause}}",
diff --git a/src/shared/locales/id.json b/src/shared/locales/id.json
index 4c99b4c5..8846e220 100644
--- a/src/shared/locales/id.json
+++ b/src/shared/locales/id.json
@@ -1175,6 +1175,7 @@
"recoveryFailed": "Unduhan tidak dapat dipulihkan: {{cause}}",
"recoveryOutputConflict": "Berkas sementara dan berkas akhir sama-sama ada; keduanya tetap disimpan untuk diperiksa secara manual",
"filesMissing": "Berkas tidak ditemukan setelah aplikasi dimulai ulang",
+ "sourceHash": "SHA-256 dari penerbit",
"renameFileFailed": "Gagal mengganti nama berkas: {{cause}}",
"renameDirFailed": "Gagal mengganti nama direktori: {{cause}}",
"pluginChainAborted": "Rangkaian plugin dihentikan: {{cause}}",
diff --git a/src/shared/locales/it.json b/src/shared/locales/it.json
index b2d6f857..ac1f069e 100644
--- a/src/shared/locales/it.json
+++ b/src/shared/locales/it.json
@@ -1203,6 +1203,7 @@
"recoveryFailed": "Impossibile recuperare il download: {{cause}}",
"recoveryOutputConflict": "Sono presenti sia il file temporaneo sia quello finale; entrambi sono stati conservati per la verifica manuale",
"filesMissing": "Mancano dei file dopo il riavvio dell’app",
+ "sourceHash": "SHA-256 dell’editore",
"renameFileFailed": "Impossibile rinominare il file: {{cause}}",
"renameDirFailed": "Impossibile rinominare la cartella: {{cause}}",
"pluginChainAborted": "Catena di plugin interrotta: {{cause}}",
diff --git a/src/shared/locales/ja.json b/src/shared/locales/ja.json
index 0fcf64d0..5d1b56ae 100644
--- a/src/shared/locales/ja.json
+++ b/src/shared/locales/ja.json
@@ -1175,6 +1175,7 @@
"recoveryFailed": "ダウンロードを復元できませんでした: {{cause}}",
"recoveryOutputConflict": "一時ファイルと最終ファイルの両方が存在します。手動で確認できるよう、両方を保持しました",
"filesMissing": "アプリの再起動後にファイルが見つかりません",
+ "sourceHash": "配布元の SHA-256",
"renameFileFailed": "ファイル名を変更できませんでした: {{cause}}",
"renameDirFailed": "フォルダー名を変更できませんでした: {{cause}}",
"pluginChainAborted": "プラグインの処理チェーンが中止されました: {{cause}}",
diff --git a/src/shared/locales/ko.json b/src/shared/locales/ko.json
index d48cb4a5..b70a6ccb 100644
--- a/src/shared/locales/ko.json
+++ b/src/shared/locales/ko.json
@@ -1175,6 +1175,7 @@
"recoveryFailed": "다운로드를 복구하지 못했습니다: {{cause}}",
"recoveryOutputConflict": "임시 파일과 최종 파일이 모두 존재하여 직접 확인할 수 있도록 둘 다 보존했습니다",
"filesMissing": "앱 재시작 후 파일을 찾을 수 없습니다",
+ "sourceHash": "배포자의 SHA-256",
"renameFileFailed": "파일 이름을 변경하지 못했습니다: {{cause}}",
"renameDirFailed": "폴더 이름을 변경하지 못했습니다: {{cause}}",
"pluginChainAborted": "플러그인 처리 체인이 중단되었습니다: {{cause}}",
diff --git a/src/shared/locales/nb.json b/src/shared/locales/nb.json
index 0121a9e9..e3602c7a 100644
--- a/src/shared/locales/nb.json
+++ b/src/shared/locales/nb.json
@@ -2900,6 +2900,7 @@
"recoveryFailed": "Kunne ikke gjenopprette nedlastingen: {{cause}}",
"recoveryOutputConflict": "Både den midlertidige og den endelige filen finnes; begge er beholdt for manuell gjennomgang",
"renameDirFailed": "Kunne ikke endre mappenavnet: {{cause}}",
+ "sourceHash": "Utgiverens SHA-256",
"renameFileFailed": "Kunne ikke endre filnavnet: {{cause}}"
},
"hint": {
diff --git a/src/shared/locales/nl.json b/src/shared/locales/nl.json
index 1ca0594b..5298f7f2 100644
--- a/src/shared/locales/nl.json
+++ b/src/shared/locales/nl.json
@@ -2900,6 +2900,7 @@
"recoveryFailed": "De download kon niet worden hersteld: {{cause}}",
"recoveryOutputConflict": "Zowel het tijdelijke als het definitieve bestand bestaat; beide zijn bewaard voor handmatige controle",
"renameDirFailed": "De map kon niet worden hernoemd: {{cause}}",
+ "sourceHash": "SHA-256 van de uitgever",
"renameFileFailed": "Het bestand kon niet worden hernoemd: {{cause}}"
},
"hint": {
diff --git a/src/shared/locales/pl.json b/src/shared/locales/pl.json
index 6d10df66..89a9ee7e 100644
--- a/src/shared/locales/pl.json
+++ b/src/shared/locales/pl.json
@@ -1217,6 +1217,7 @@
"recoveryFailed": "Nie udało się przywrócić pobierania: {{cause}}",
"recoveryOutputConflict": "Istnieją zarówno plik tymczasowy, jak i końcowy; oba zachowano do ręcznego sprawdzenia",
"filesMissing": "Brakuje plików po ponownym uruchomieniu aplikacji",
+ "sourceHash": "SHA-256 od wydawcy",
"renameFileFailed": "Nie udało się zmienić nazwy pliku: {{cause}}",
"renameDirFailed": "Nie udało się zmienić nazwy folderu: {{cause}}",
"pluginChainAborted": "Przerwano łańcuch wtyczek: {{cause}}",
diff --git a/src/shared/locales/pt-BR.json b/src/shared/locales/pt-BR.json
index 89d5c67e..ccb853e8 100644
--- a/src/shared/locales/pt-BR.json
+++ b/src/shared/locales/pt-BR.json
@@ -1203,6 +1203,7 @@
"recoveryFailed": "Não foi possível recuperar o download: {{cause}}",
"recoveryOutputConflict": "Os arquivos temporário e final existem; ambos foram preservados para revisão manual",
"filesMissing": "Há arquivos ausentes após a reinicialização do aplicativo",
+ "sourceHash": "SHA-256 do distribuidor",
"renameFileFailed": "Não foi possível renomear o arquivo: {{cause}}",
"renameDirFailed": "Não foi possível renomear a pasta: {{cause}}",
"pluginChainAborted": "Cadeia de plugins interrompida: {{cause}}",
diff --git a/src/shared/locales/ro.json b/src/shared/locales/ro.json
index a020eea2..21456693 100644
--- a/src/shared/locales/ro.json
+++ b/src/shared/locales/ro.json
@@ -2921,6 +2921,7 @@
"recoveryFailed": "Descărcarea nu a putut fi recuperată: {{cause}}",
"recoveryOutputConflict": "Există atât fișierul temporar, cât și cel final; ambele au fost păstrate pentru verificare manuală",
"renameDirFailed": "Dosarul nu a putut fi redenumit: {{cause}}",
+ "sourceHash": "SHA-256 de la editor",
"renameFileFailed": "Fișierul nu a putut fi redenumit: {{cause}}"
},
"hint": {
diff --git a/src/shared/locales/ru.json b/src/shared/locales/ru.json
index 3c2e3385..9caeab8d 100644
--- a/src/shared/locales/ru.json
+++ b/src/shared/locales/ru.json
@@ -1217,6 +1217,7 @@
"recoveryFailed": "Не удалось восстановить загрузку: {{cause}}",
"recoveryOutputConflict": "Существуют и временный, и итоговый файл; оба сохранены для ручной проверки",
"filesMissing": "После перезапуска приложения файлы отсутствуют",
+ "sourceHash": "SHA-256 от издателя",
"renameFileFailed": "Не удалось переименовать файл: {{cause}}",
"renameDirFailed": "Не удалось переименовать папку: {{cause}}",
"pluginChainAborted": "Цепочка плагинов прервана: {{cause}}",
diff --git a/src/shared/locales/th.json b/src/shared/locales/th.json
index 0e588312..588f1edc 100644
--- a/src/shared/locales/th.json
+++ b/src/shared/locales/th.json
@@ -2879,6 +2879,7 @@
"recoveryFailed": "กู้คืนการดาวน์โหลดไม่ได้: {{cause}}",
"recoveryOutputConflict": "มีทั้งไฟล์ชั่วคราวและไฟล์สุดท้าย เก็บทั้งสองไฟล์ไว้เพื่อตรวจสอบด้วยตนเอง",
"renameDirFailed": "เปลี่ยนชื่อโฟลเดอร์ไม่ได้: {{cause}}",
+ "sourceHash": "SHA-256 จากผู้เผยแพร่",
"renameFileFailed": "เปลี่ยนชื่อไฟล์ไม่ได้: {{cause}}"
},
"hint": {
diff --git a/src/shared/locales/tr.json b/src/shared/locales/tr.json
index 72a91562..299260f6 100644
--- a/src/shared/locales/tr.json
+++ b/src/shared/locales/tr.json
@@ -1189,6 +1189,7 @@
"recoveryFailed": "İndirme kurtarılamadı: {{cause}}",
"recoveryOutputConflict": "Hem geçici hem de son dosya mevcut; elle incelenmeleri için ikisi de korundu",
"filesMissing": "Uygulama yeniden başlatıldıktan sonra dosyalar bulunamadı",
+ "sourceHash": "Yayıncının SHA-256 değeri",
"renameFileFailed": "Dosya yeniden adlandırılamadı: {{cause}}",
"renameDirFailed": "Klasör yeniden adlandırılamadı: {{cause}}",
"pluginChainAborted": "Eklenti zinciri durduruldu: {{cause}}",
diff --git a/src/shared/locales/uk.json b/src/shared/locales/uk.json
index 56d90627..dbaa23b6 100644
--- a/src/shared/locales/uk.json
+++ b/src/shared/locales/uk.json
@@ -2942,6 +2942,7 @@
"recoveryFailed": "Не вдалося відновити завантаження: {{cause}}",
"recoveryOutputConflict": "Існують і тимчасовий, і кінцевий файли; обидва збережено для ручної перевірки",
"renameDirFailed": "Не вдалося перейменувати теку: {{cause}}",
+ "sourceHash": "SHA-256 від видавця",
"renameFileFailed": "Не вдалося перейменувати файл: {{cause}}"
},
"hint": {
diff --git a/src/shared/locales/vi.json b/src/shared/locales/vi.json
index f75102c4..12146d27 100644
--- a/src/shared/locales/vi.json
+++ b/src/shared/locales/vi.json
@@ -1175,6 +1175,7 @@
"recoveryFailed": "Không thể khôi phục lượt tải xuống: {{cause}}",
"recoveryOutputConflict": "Cả tệp tạm và tệp cuối cùng đều tồn tại; cả hai được giữ lại để kiểm tra thủ công",
"filesMissing": "Thiếu tệp sau khi ứng dụng khởi động lại",
+ "sourceHash": "SHA-256 của nhà phát hành",
"renameFileFailed": "Không thể đổi tên tệp: {{cause}}",
"renameDirFailed": "Không thể đổi tên thư mục: {{cause}}",
"pluginChainAborted": "Chuỗi tiện ích đã bị hủy: {{cause}}",
diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.json
index d7319c97..6b838541 100644
--- a/src/shared/locales/zh-CN.json
+++ b/src/shared/locales/zh-CN.json
@@ -1175,6 +1175,7 @@
"recoveryFailed": "无法恢复下载:{{cause}}",
"recoveryOutputConflict": "临时文件和最终文件同时存在,已保留两者以供人工检查",
"filesMissing": "应用重启后文件缺失",
+ "sourceHash": "发布方的 SHA-256",
"renameFileFailed": "重命名文件失败:{{cause}}",
"renameDirFailed": "重命名目录失败:{{cause}}",
"pluginChainAborted": "插件链已中止:{{cause}}",
diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.json
index ac8cff13..5ebe5473 100644
--- a/src/shared/locales/zh-TW.json
+++ b/src/shared/locales/zh-TW.json
@@ -1175,6 +1175,7 @@
"recoveryFailed": "無法恢復下載:{{cause}}",
"recoveryOutputConflict": "暫存檔與最終檔案皆存在,兩者均已保留以供手動檢查",
"filesMissing": "應用程式重新啟動後找不到檔案",
+ "sourceHash": "發行者的 SHA-256",
"renameFileFailed": "無法重新命名檔案:{{cause}}",
"renameDirFailed": "無法重新命名目錄:{{cause}}",
"pluginChainAborted": "外掛程式鏈已中止:{{cause}}",
diff --git a/src/shared/schemas/bulk-task-command.ts b/src/shared/schemas/bulk-task-command.ts
index 053827d0..64ed635e 100644
--- a/src/shared/schemas/bulk-task-command.ts
+++ b/src/shared/schemas/bulk-task-command.ts
@@ -3,6 +3,24 @@ import { z } from 'zod'
/** Payload of plural task-id commands, including Commands.RetryTasks. */
export const taskIdsPayloadSchema = z.array(z.string().min(1)).min(1)
+/** Older clients send only the ID. An explicit digest is scoped to one retry. */
+export const reAddTaskPayloadSchema = z.union([
+ z
+ .string()
+ .min(1)
+ .transform((taskId) => ({ taskId, sha256: undefined })),
+ z
+ .object({
+ taskId: z.string().min(1),
+ sha256: z
+ .string()
+ .trim()
+ .regex(/^[0-9a-f]{64}$/i)
+ .toLowerCase(),
+ })
+ .strict(),
+])
+
/** Payload of Commands.RemoveTasks. */
export const removeTasksPayloadSchema = z.object({
taskIds: taskIdsPayloadSchema,