A full-featured download manager.
fix(finalize): support paragon ntfs publication on macos (#2464)
TozyZuo185285b9cbda
diff --git a/packages/finalize-fs/README.md b/packages/finalize-fs/README.mdindex 9d1d3834..5c63afa4 100644--- a/packages/finalize-fs/README.md+++ b/packages/finalize-fs/README.md@@ -2,7 +2,7 @@The sidecar performs handle-relative, identity-checked file publication andremoval. No-replace operations never replace an existing destination. The-separate macOS exFAT compatibility operation replaces a journaled reservation+separate macOS exFAT/Paragon NTFS compatibility operation replaces a journaled reservationunder the ownership assumptions below. Reparse points andunsafe path components remain rejected on Windows.@@ -132,16 +132,30 @@ it does not assert support for every FUSE driver, network server, kernel, ormount configuration. Synchronization success remains subject to the storageimplementation; tmpfs, in particular, is volatile across system restart.-## macOS local exFAT+## macOS local exFAT and Paragon NTFSSome FSKit exFAT volumes reject exclusive rename with `ENOTSUP` (45), whichdiffers from `EOPNOTSUPP` (102) on Darwin, and do not support hard links.Ordinary download suffix removal can use `reserve_exfat_target` followed by`rename_opened_reserved`. The original no-replace operation keeps its strictcontract. This compatibility route requires a regular file, the same parent,-an exact `.motrix` suffix removal, a local exFAT mount, and no plugin replacement+an exact `.motrix` suffix removal, a local exFAT or `ufsd_NTFS` mount, and no plugin replacementor staged metadata. Permission, space, I/O and other errors do not enable it.+Paragon NTFS also rejects exclusive rename with `ENOTSUP`. Its volume UUID+attribute query returns `EINVAL`, so the sidecar obtains that persistent UUID+from the system Disk Arbitration description of the held mount's BSD device.+Unknown NTFS/FUSE implementations and nonlocal mounts remain unsupported by+this compatibility route. The existing `exfat_*` wire operation names are+retained for protocol compatibility.++Paragon initializes file timestamps at whole-second precision and can quickly+reuse a reservation's inode after publication. All ownership markers have the+same size, which can make a new marker alias the previous marker's entry in+the host's inode/size/time digest cache. Newly created NTFS reservations receive+an explicit high-resolution modification time before their identity is read+or synced. Only the private marker is timestamped; download metadata is unchanged.+The host durably journals a version-3 intent containing a random reservationtoken and the volume UUID before creating the final name with`O_CREAT|O_EXCL|O_NOFOLLOW`. The small, nonempty marker contains the token;@@ -203,6 +217,21 @@ cargo test --manifest-path packages/finalize-fs/Cargo.toml --locked -- --ignoredpnpm exec vitest run src/core/plugin/finalize/finalize-exfat.integration.test.ts```+For a writable Paragon NTFS volume, set `MOTRIX_FINALIZE_NTFS_ROOT` instead of+the exFAT root variable. The native suite verifies reservation ownership,+conflicts, empty and Unicode files; the same application suite exercises+successive publication with a shared digest cache and interrupted-publication+recovery using a real sidecar and SQLite database. These tests create only+unique scratch directories and never detach an NTFS volume:++```sh+MOTRIX_FINALIZE_NTFS_ROOT=/Volumes/ntfs-test cargo test \+ --manifest-path packages/finalize-fs/Cargo.toml --locked \+ ntfs_reservations_preserve_conflicts_and_publish_held_files -- --ignored+MOTRIX_FINALIZE_NTFS_ROOT=/Volumes/ntfs-test pnpm exec vitest run \+ src/core/plugin/finalize/finalize-exfat.integration.test.ts+```+## Windows and SMBWindows rename retries transient sharing conflicts with exponential backoff,diff --git a/packages/finalize-fs/src/platform/unix/reserved.rs b/packages/finalize-fs/src/platform/unix/reserved.rsindex 16fdce00..8ab0b3b4 100644--- a/packages/finalize-fs/src/platform/unix/reserved.rs+++ b/packages/finalize-fs/src/platform/unix/reserved.rs@@ -1,5 +1,5 @@-//! Compatibility publication for local macOS exFAT downloads. The final name-//! must remain application-owned between its last check and ordinary rename.+//! Compatibility publication for local macOS exFAT and Paragon NTFS downloads.+//! The final name must remain application-owned between its last check and ordinary rename.//! This deliberately does not implement the atomic no-replace contract.use super::metadata::{artifact_stamp, ensure_same_entry, stat_named, stat_opened};@@ -11,6 +11,16 @@ use std::io::{self, Write};use std::os::fd::AsRawFd;use std::os::unix::fs::FileExt;+mod ntfs_volume;++fn supported_filesystem(fs: &libc::statfs) -> bool {+ fs.f_flags & libc::MNT_LOCAL as u32 != 0+ && matches!(+ unsafe { CStr::from_ptr(fs.f_fstypename.as_ptr()) }.to_bytes(),+ b"exfat" | b"ufsd_NTFS"+ )+}+fn identity(stat: &libc::stat) -> String {// Node BigIntStats exposes inode through a signed 64-bit slot. FSKit's// synthetic empty-file IDs set the high bit; preserve the host's existing@@ -25,11 +35,14 @@ pub(crate) fn exfat_volume_identity(root: &RootHandle) -> io::Result<Option<Strireturn Err(io::Error::last_os_error());}let fs = unsafe { fs.assume_init() };- if fs.f_flags & libc::MNT_LOCAL as u32 == 0- || unsafe { CStr::from_ptr(fs.f_fstypename.as_ptr()) }.to_bytes() != b"exfat"- {+ if !supported_filesystem(&fs) {return Ok(None);}+ // Paragon rejects ATTR_VOL_UUID with EINVAL. Disk Arbitration supplies the+ // same persistent volume UUID without relying on transient st_dev values.+ if unsafe { CStr::from_ptr(fs.f_fstypename.as_ptr()) }.to_bytes() == b"ufsd_NTFS" {+ return ntfs_volume::volume_uuid(&fs).map(Some);+ }let mut attributes = libc::attrlist {bitmapcount: libc::ATTR_BIT_MAP_COUNT,reserved: 0,@@ -100,17 +113,15 @@ fn validate_scope(return Err(io::Error::last_os_error());}let fs = unsafe { fs.assume_init() };- let fs_name = unsafe { CStr::from_ptr(fs.f_fstypename.as_ptr()) };if from.st_dev != to.st_dev|| from.st_ino != to.st_ino- || fs.f_flags & libc::MNT_LOCAL as u32 == 0- || fs_name.to_bytes() != b"exfat"+ || !supported_filesystem(&fs)|| source.name.to_bytes().strip_suffix(b".motrix") != Some(name.to_bytes())|| name.to_bytes().is_empty(){return Err(io::Error::new(io::ErrorKind::Unsupported,- "reserved rename requires same-directory suffix removal on local exFAT",+ "reserved rename requires same-directory suffix removal on local exFAT or Paragon NTFS",));}unchanged(source)?;@@ -192,6 +203,20 @@ pub(crate) fn reserve_exfat_target(if created && let Some(contents) = &contents {std::fs::File::from(artifact.try_clone()?).write_all(contents)?;}+ if created {+ let mut fs = std::mem::MaybeUninit::<libc::statfs>::uninit();+ if unsafe { libc::fstatfs(root.0.as_raw_fd(), fs.as_mut_ptr()) } != 0 {+ return Err(io::Error::last_os_error());+ }+ let fs = unsafe { fs.assume_init() };+ if unsafe { CStr::from_ptr(fs.f_fstypename.as_ptr()) }.to_bytes() == b"ufsd_NTFS" {+ // Paragon defaults to whole-second timestamps and immediately+ // reuses the overwritten reservation inode. Give each new marker+ // a precise mtime so the host's inode/size/time digest cache cannot+ // mistake it for the preceding task's different ownership token.+ std::fs::File::from(artifact.try_clone()?).set_modified(std::time::SystemTime::now())?;+ }+ }// Never unlink on a failure: an unacknowledged reservation must be retained.let stat = ensure_same_entry(artifact.as_raw_fd(), root.0.as_raw_fd(), &name)?;let id = identity(&stat);@@ -360,6 +385,34 @@ mod tests {fn exfat_reservations_preserve_conflicts_and_publish_held_files() {let parent =PathBuf::from(std::env::var("MOTRIX_FINALIZE_EXFAT_ROOT").expect("exFAT test root"));+ check_reservations(parent);+ }++ #[test]+ #[ignore = "requires MOTRIX_FINALIZE_NTFS_ROOT on a writable Paragon NTFS volume"]+ fn ntfs_reservations_preserve_conflicts_and_publish_held_files() {+ let parent =+ PathBuf::from(std::env::var("MOTRIX_FINALIZE_NTFS_ROOT").expect("NTFS test root"));+ let root = super::super::open_root(parent.to_str().unwrap()).unwrap();+ let mut fs = std::mem::MaybeUninit::<libc::statfs>::uninit();+ assert_eq!(+ unsafe { libc::fstatfs(root.0.as_raw_fd(), fs.as_mut_ptr()) },+ 0+ );+ let fs = unsafe { fs.assume_init() };+ assert_eq!(+ unsafe { CStr::from_ptr(fs.f_fstypename.as_ptr()) }.to_bytes(),+ b"ufsd_NTFS",+ "NTFS test root must use the Paragon driver"+ );+ let uuid = exfat_volume_identity(&root)+ .unwrap()+ .expect("persistent NTFS UUID");+ assert_eq!(uuid.len(), 32);+ check_reservations(parent);+ }++ fn check_reservations(parent: PathBuf) {let dir = scratch(parent.clone());// Also exercise a held volume root, with names unique to this fixture.let root_name = dir.0.file_name().unwrap().to_str().unwrap().to_owned() + "-payload";@@ -377,6 +430,7 @@ mod tests {for (name, contents) in [("empty", b"".as_slice()),("download", b"complete download".as_slice()),+ ("中文视频.mp4", b"unicode download".as_slice()),] {let source_name = format!("{name}.motrix");std::fs::write(dir.0.join(&source_name), contents).unwrap();diff --git a/packages/finalize-fs/src/platform/unix/reserved/ntfs_volume.rs b/packages/finalize-fs/src/platform/unix/reserved/ntfs_volume.rsnew file mode 100644index 00000000..208ebc72--- /dev/null+++ b/packages/finalize-fs/src/platform/unix/reserved/ntfs_volume.rs@@ -0,0 +1,78 @@+//! Read the persistent NTFS volume UUID from the system Disk Arbitration API.+use std::ffi::{CStr, c_char, c_void};+use std::io;++type CFRef = *const c_void;++#[repr(C)]+struct UuidBytes {+ bytes: [u8; 16],+}++#[link(name = "CoreFoundation", kind = "framework")]+unsafe extern "C" {+ fn CFRelease(value: CFRef);+ fn CFGetTypeID(value: CFRef) -> usize;+ fn CFDictionaryGetValue(dictionary: CFRef, key: CFRef) -> CFRef;+ fn CFUUIDGetTypeID() -> usize;+ fn CFUUIDGetUUIDBytes(uuid: CFRef) -> UuidBytes;+}++#[link(name = "DiskArbitration", kind = "framework")]+unsafe extern "C" {+ fn DASessionCreate(allocator: CFRef) -> CFRef;+ fn DADiskCreateFromBSDName(allocator: CFRef, session: CFRef, name: *const c_char) -> CFRef;+ fn DADiskCopyDescription(disk: CFRef) -> CFRef;+ static kDADiskDescriptionVolumeUUIDKey: CFRef;+}++struct Owned(CFRef);++impl Owned {+ fn checked(value: CFRef) -> io::Result<Self> {+ if value.is_null() {+ Err(io::Error::new(+ io::ErrorKind::NotFound,+ "NTFS volume is unavailable",+ ))+ } else {+ Ok(Self(value))+ }+ }+}++impl Drop for Owned {+ fn drop(&mut self) {+ unsafe { CFRelease(self.0) };+ }+}++pub(super) fn volume_uuid(fs: &libc::statfs) -> io::Result<String> {+ let device = unsafe { CStr::from_ptr(fs.f_mntfromname.as_ptr()) };+ if !device.to_bytes().starts_with(b"/dev/disk") {+ return Err(io::Error::new(+ io::ErrorKind::Unsupported,+ "NTFS source is not a local disk",+ ));+ }+ let session = Owned::checked(unsafe { DASessionCreate(std::ptr::null()) })?;+ let disk = Owned::checked(unsafe {+ DADiskCreateFromBSDName(std::ptr::null(), session.0, device.as_ptr())+ })?;+ let description = Owned::checked(unsafe { DADiskCopyDescription(disk.0) })?;+ let uuid = unsafe { CFDictionaryGetValue(description.0, kDADiskDescriptionVolumeUUIDKey) };+ if uuid.is_null() || unsafe { CFGetTypeID(uuid) != CFUUIDGetTypeID() } {+ return Err(io::Error::new(+ io::ErrorKind::Unsupported,+ "missing NTFS volume UUID",+ ));+ }+ let bytes = unsafe { CFUUIDGetUUIDBytes(uuid) }.bytes;+ if bytes.iter().all(|byte| *byte == 0) {+ return Err(io::Error::new(+ io::ErrorKind::Unsupported,+ "empty NTFS volume UUID",+ ));+ }+ Ok(bytes.iter().map(|byte| format!("{byte:02x}")).collect())+}diff --git a/src/core/plugin/finalize/finalize-exfat.integration.test.ts b/src/core/plugin/finalize/finalize-exfat.integration.test.tsindex f559a779..0936a48c 100644--- a/src/core/plugin/finalize/finalize-exfat.integration.test.ts+++ b/src/core/plugin/finalize/finalize-exfat.integration.test.ts@@ -30,9 +30,13 @@ import {import { NativeFinalizeArtifactOperations } from './native-artifact-operations'import { reservationMarker } from './reserved-identity'-const volume = process.env.MOTRIX_FINALIZE_EXFAT_ROOT+const volume =+ process.env.MOTRIX_FINALIZE_EXFAT_ROOT ??+ process.env.MOTRIX_FINALIZE_NTFS_ROOT// Set only by the disposable-image harness; never detach a user-supplied volume.-const image = process.env.MOTRIX_FINALIZE_EXFAT_TEST_IMAGE+const image = process.env.MOTRIX_FINALIZE_EXFAT_ROOT+ ? process.env.MOTRIX_FINALIZE_EXFAT_TEST_IMAGE+ : undefined// Disk Arbitration can take several seconds per attach/detach on CI runners.const diskImageCommandOptions = { timeout: 20_000 }const binary = path.resolve(@@ -42,7 +46,7 @@ const binary = path.resolve(describe.runIf(process.platform === 'darwin' && Boolean(volume) && existsSync(binary)-)('macOS exFAT publication and recovery', () => {+)('macOS exFAT/Paragon NTFS publication and recovery', () => {const cleanup: (() => Promise<void>)[] = []afterEach(async () => {vi.restoreAllMocks()@@ -206,6 +210,32 @@ describe.runIf(expect(s.db.pragma('synchronous', { simple: true })).toBe(1)})+ it('publishes successive downloads without reusing a stale marker digest', async () => {+ const s = await setup()+ for (let index = 0; index < 24; index++) {+ const targetPath = path.join(s.root, `successive-${index}.bin`)+ const sourcePath = `${targetPath}.motrix`+ const content = `complete download ${index}`+ await writeFile(sourcePath, content)+ await s.runtime.commit({+ ...s.input,+ task: makeDownloadTask({+ id: `successive-${index}`,+ saveDir: s.root,+ diskPath: sourcePath,+ finalPath: targetPath,+ status: TaskStatus.Finalizing,+ transitionPhase: TransitionPhase.Renaming,+ }),+ sourcePath,+ targetPath,+ })+ expect(await readFile(targetPath, 'utf8')).toBe(content)+ expect(existsSync(sourcePath)).toBe(false)+ }+ expect(s.commits()).toBe(24)+ }, 30_000)+it('preserves an existing target without creating a reservation', async () => {const s = await setup()await writeFile(s.input.targetPath, 'unrelated file')