Skip to content

A full-featured download manager.

fix(finalize): handle existing download volume roots (#2219)

Dr_rOotf3f004b9fe8f
diff --git a/src/core/fs/ensure-directory.test.ts b/src/core/fs/ensure-directory.test.ts
new file mode 100644
index 00000000..4c023c3a
--- /dev/null
+++ b/src/core/fs/ensure-directory.test.ts
@@ -0,0 +1,76 @@
+import type { Stats } from 'node:fs'
+import { mkdir, stat } from 'node:fs/promises'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { ensureDirectory } from './ensure-directory'
+
+vi.mock('node:fs/promises', () => {
+ const fs = { mkdir: vi.fn(), stat: vi.fn() }
+ return { ...fs, default: fs }
+})
+
+beforeEach(() => {
+ vi.resetAllMocks()
+})
+
+describe('ensureDirectory', () => {
+ it.each([
+ 'D:\\',
+ 'D:/',
+ '\\\\server\\share',
+ '\\\\server\\share\\',
+ '\\\\?\\D:\\',
+ '\\\\?\\UNC\\server\\share\\',
+ '/',
+ '/mnt/nfs/downloads',
+ ])('accepts an existing directory without mkdir: %s', async (directory) => {
+ vi.mocked(stat).mockResolvedValue({ isDirectory: () => true } as Stats)
+ vi.mocked(mkdir).mockRejectedValue(
+ Object.assign(new Error('operation not permitted'), { code: 'EPERM' })
+ )
+
+ await ensureDirectory(directory)
+
+ expect(stat).toHaveBeenCalledWith(directory)
+ expect(mkdir).not.toHaveBeenCalled()
+ })
+
+ it('creates a missing nested directory recursively', async () => {
+ vi.mocked(stat).mockRejectedValue(
+ Object.assign(new Error('missing'), { code: 'ENOENT' })
+ )
+ await ensureDirectory('D:\\Downloads\\Archives')
+ expect(mkdir).toHaveBeenCalledWith('D:\\Downloads\\Archives', {
+ recursive: true,
+ })
+ })
+
+ it.each(['EPERM', 'EACCES', 'EIO', 'ENOTDIR'])(
+ 'propagates %s when inspecting a directory',
+ async (code) => {
+ const error = Object.assign(new Error('stat failed'), { code })
+ vi.mocked(stat).mockRejectedValue(error)
+ await expect(ensureDirectory('D:\\')).rejects.toBe(error)
+ expect(mkdir).not.toHaveBeenCalled()
+ }
+ )
+
+ it.each(['EPERM', 'EACCES'])(
+ 'propagates %s when creating a missing directory',
+ async (code) => {
+ vi.mocked(stat).mockRejectedValue(
+ Object.assign(new Error('missing'), { code: 'ENOENT' })
+ )
+ const error = Object.assign(new Error('mkdir failed'), { code })
+ vi.mocked(mkdir).mockRejectedValue(error)
+ await expect(ensureDirectory('D:\\Downloads')).rejects.toBe(error)
+ }
+ )
+
+ it('preserves mkdir failure for an existing non-directory entry', async () => {
+ vi.mocked(stat).mockResolvedValue({ isDirectory: () => false } as Stats)
+ const error = Object.assign(new Error('file exists'), { code: 'EEXIST' })
+ vi.mocked(mkdir).mockRejectedValue(error)
+ await expect(ensureDirectory('D:\\file.zip')).rejects.toBe(error)
+ expect(mkdir).toHaveBeenCalledWith('D:\\file.zip', { recursive: true })
+ })
+})
diff --git a/src/core/fs/ensure-directory.ts b/src/core/fs/ensure-directory.ts
new file mode 100644
index 00000000..ce4b1807
--- /dev/null
+++ b/src/core/fs/ensure-directory.ts
@@ -0,0 +1,15 @@
+import { mkdir, stat } from 'node:fs/promises'
+
+/** Ensure a directory exists without trying to create an existing volume root. */
+export async function ensureDirectory(directoryPath: string): Promise<void> {
+ try {
+ // On Windows, mkdir of an existing drive root fails with EPERM even with
+ // recursive: true. Checking the directory also handles UNC/namespace roots
+ // without rewriting their IO paths or suppressing permission errors.
+ if ((await stat(directoryPath)).isDirectory()) return
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
+ }
+ // Keep mkdir's errors for non-directory entries and inaccessible parents.
+ await mkdir(directoryPath, { recursive: true })
+}
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 f42eb651..52db91dd 100644
--- a/src/core/plugin/finalize/native-artifact-operations.integration.test.ts
+++ b/src/core/plugin/finalize/native-artifact-operations.integration.test.ts
@@ -26,6 +26,16 @@ import { FinalizeCommitter, removalQuarantinePath } from './finalize-committer'
import * as hashing from './hash-opened-file'
import { NativeFinalizeArtifactOperations } from './native-artifact-operations'
+vi.mock('node:fs/promises', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('node:fs/promises')>()
+ const mkdirMock = vi.fn(actual.mkdir)
+ return {
+ ...actual,
+ mkdir: mkdirMock,
+ default: { ...actual, mkdir: mkdirMock },
+ }
+})
+
const binary = process.env.MOTRIX_FINALIZE_FS_TEST_BIN
? path.resolve(process.env.MOTRIX_FINALIZE_FS_TEST_BIN)
: path.resolve(
@@ -43,6 +53,7 @@ describe.runIf(existsSync(binary))(
afterEach(async () => {
vi.restoreAllMocks()
+ vi.mocked(mkdir).mockReset()
await Promise.all(
roots
.splice(0)
@@ -61,6 +72,29 @@ describe.runIf(existsSync(binary))(
return { root, adapter, operations }
}
+ it('finalizes in an existing directory whose mkdir reports EPERM like a Windows drive root', 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, 'completed download')
+ const identity = await readArtifactIdentity(source)
+ const mkdirMock = vi.mocked(mkdir).mockRejectedValue(
+ Object.assign(new Error(`EPERM: mkdir '${root}'`), {
+ code: 'EPERM',
+ syscall: 'mkdir',
+ })
+ )
+ try {
+ await operations.preflight(source, target)
+ await operations.moveNoReplace(source, identity, target)
+ expect(await readFile(target, 'utf8')).toBe('completed download')
+ expect(existsSync(source)).toBe(false)
+ expect(mkdirMock).not.toHaveBeenCalled()
+ } finally {
+ await adapter.dispose()
+ }
+ })
+
it('finalizes a large file with at most two content reads and metadata-only native rename', async () => {
const { root, adapter, operations } = await setup()
const source = path.join(root, 'large.part')
diff --git a/src/core/plugin/finalize/native-artifact-operations.ts b/src/core/plugin/finalize/native-artifact-operations.ts
index 3cda06d8..093c46e9 100644
--- a/src/core/plugin/finalize/native-artifact-operations.ts
+++ b/src/core/plugin/finalize/native-artifact-operations.ts
@@ -1,14 +1,7 @@
import { constants } from 'node:fs'
-import {
- lstat,
- mkdir,
- mkdtemp,
- open,
- readdir,
- rmdir,
- stat,
-} from 'node:fs/promises'
+import { lstat, mkdtemp, open, readdir, rmdir, stat } from 'node:fs/promises'
import path from 'node:path'
+import { ensureDirectory } from '@core/fs/ensure-directory'
import {
type ArtifactIdentity,
ArtifactIdentityCache,
@@ -506,7 +499,7 @@ export class NativeFinalizeArtifactOperations
private async ensureSafeDirectory(directoryPath: string): Promise<void> {
await assertExistingAncestorsAreDirectories(directoryPath)
- await mkdir(directoryPath, { recursive: true })
+ await ensureDirectory(directoryPath)
const held = await this.adapter.openRoot(directoryPath)
await this.adapter.close(held).catch(() => undefined)
}
diff --git a/src/core/task/create-task-handler.test.ts b/src/core/task/create-task-handler.test.ts
index bbd40352..ad5ff489 100644
--- a/src/core/task/create-task-handler.test.ts
+++ b/src/core/task/create-task-handler.test.ts
@@ -1,3 +1,4 @@
+import path from 'node:path'
import { DirectPipeline } from '@core/bridge-receiver/pipelines/direct-pipeline'
import { SubmitDownloadAdapter } from '@core/bridge-receiver/submit-download-adapter'
import { initLogger } from '@core/logger'
@@ -32,10 +33,10 @@ import {
} from './direct-resource-validator'
import { FinalNamePickerImpl } from './final-name-picker'
-// Stub `mkdir` (and the other `fs.*` calls inadvertently dragged
+// Stub directory preparation (and the other `fs.*` calls inadvertently dragged
// in via TorrentMetaStore) so unit tests don't touch the real
// filesystem. The production code calls
-// `mkdir(<saveDir-or-diskPath>, { recursive: true })`
+// `ensureDirectory(<saveDir-or-diskPath>)`
// with paths like '/d/foo.bin.motrix' which would either fail with
// EACCES or — worse — actually mutate the runner's filesystem. The
// mock also lets us assert WHICH path the production code chose,
@@ -46,12 +47,15 @@ import { FinalNamePickerImpl } from './final-name-picker'
// module scope would be `undefined` when the mock factory runs.
//
// Both `default` and named exports are provided so that TorrentMetaStore's
-// `import fs from 'node:fs/promises'` (default) and createTaskHandler's
-// `import { mkdir } from 'node:fs/promises'` (named) both resolve.
+// `import fs from 'node:fs/promises'` (default) and the directory helper's
+// named imports both resolve.
const { mkdirMock, fsStub } = vi.hoisted(() => {
const mkdirMock = vi.fn(async () => undefined)
const fsStub = {
mkdir: mkdirMock,
+ stat: vi.fn(async (): Promise<{ isDirectory(): boolean }> => {
+ throw Object.assign(new Error('missing directory'), { code: 'ENOENT' })
+ }),
writeFile: vi.fn(async () => undefined),
readFile: vi.fn(async () => Buffer.alloc(0)),
unlink: vi.fn(async () => undefined),
@@ -69,7 +73,8 @@ const logError = vi.fn()
const logDebug = vi.fn()
beforeEach(() => {
- mkdirMock.mockClear()
+ mkdirMock.mockReset()
+ fsStub.stat.mockReset()
logInfo.mockClear()
logWarn.mockClear()
logError.mockClear()
@@ -1956,6 +1961,27 @@ describe('handleCreateTask download paths', () => {
})
describe('handleCreateTask mkdir target by task type', () => {
+ it('dispatches a download in an existing volume root without trying to create it', async () => {
+ const saveDir = path.parse(path.resolve('/')).root
+ fsStub.stat.mockResolvedValue({ isDirectory: () => true })
+ // Model Windows mkdir on a drive root, even on a POSIX test host.
+ mkdirMock.mockRejectedValueOnce(
+ Object.assign(new Error(`EPERM: mkdir '${saveDir}'`), { code: 'EPERM' })
+ )
+ const deps = makeDeps()
+ await handleCreateTask(
+ { ...httpRequest(), saveDir, filename: 'archive.zip' },
+ deps
+ )
+ expect(deps.addUri).toHaveBeenCalledWith(
+ ['https://a/b'],
+ expect.objectContaining({ dir: saveDir, out: 'archive.zip.motrix' })
+ )
+ expect(deps.add).toHaveBeenCalledOnce()
+ expect(logWarn).not.toHaveBeenCalled()
+ expect(mkdirMock).not.toHaveBeenCalled()
+ })
+
// BT/Magnet: `diskPath` is the container directory aria2 populates,
// and aria2.addTorrent writes `<sha1>.torrent` inside it at add time
// — pre-creating the dir is required to keep that write from
diff --git a/src/core/task/create-task-handler.ts b/src/core/task/create-task-handler.ts
index a8de3c4e..f4e506dd 100644
--- a/src/core/task/create-task-handler.ts
+++ b/src/core/task/create-task-handler.ts
@@ -1,4 +1,3 @@
-import { mkdir } from 'node:fs/promises'
import path from 'node:path'
import { stripHopByHopHeaders } from '@core/bridge-receiver/header-replay'
import { ensureMediaExtension } from '@core/bridge-receiver/pipelines/media-final-name'
@@ -13,6 +12,7 @@ import type {
EngineAdapter,
} from '@core/engine/engine-adapter'
import { DIRECT_RESOURCE_METADATA_PROFILE } from '@core/engine/engine-adapter'
+import { ensureDirectory } from '@core/fs/ensure-directory'
import { newEngineTaskId, newTaskId } from '@core/lib/ids'
import { getLogger } from '@core/logger'
import type { HookAuditLog } from '@core/plugin/hooks/audit-log'
@@ -566,7 +566,7 @@ async function handleCreateTaskUnderAdmission(
// container. HTTP keeps its incomplete suffix inside the chosen save root.
const ensureDir = btStoragePlan?.saveDir ?? effectiveSaveDir
try {
- await mkdir(ensureDir, { recursive: true })
+ await ensureDirectory(ensureDir)
} catch (cause) {
log.warn(
{ err: cause, ensureDir, taskType },