Skip to content

A full-featured download manager.

fix(bt): keep single-file torrent metadata out of downloads (#2209)

Dr_rOota426739e7dad
diff --git a/e2e/downloads-seeding.spec.ts b/e2e/downloads-seeding.spec.ts
index d723d92a..d7de0b62 100644
--- a/e2e/downloads-seeding.spec.ts
+++ b/e2e/downloads-seeding.spec.ts
@@ -1,4 +1,5 @@
import { createHash } from 'node:crypto'
+import { readdir, readFile } from 'node:fs/promises'
import path from 'node:path'
import type { Page } from '@playwright/test'
import { Commands } from '@shared/protocol/commands'
@@ -62,6 +63,26 @@ test('unlimited BT seeding, inspector metrics and re-seeding survive engine rest
})
const readTask = async (page = mainWindow) =>
((await invoke(page, Queries.ListTasks)) as DownloadTask[])[0]
+ const expectInternalTorrentStorage = async (task: DownloadTask) => {
+ expect(task.saveDir).toBe(path.join(userDataDir, 'downloads'))
+ const metadataPath = path.join(
+ userDataDir,
+ 'torrents',
+ `${task.id}.torrent`
+ )
+ expect(task.torrentMetaPath).toBe(metadataPath)
+ const bytes = Buffer.from(torrent, 'base64')
+ expect(await readFile(metadataPath)).toEqual(bytes)
+ const rpcMetadataName = `${createHash('sha1').update(bytes).digest('hex')}.torrent`
+ expect(
+ await readFile(path.join(`${metadataPath}.state`, rpcMetadataName))
+ ).toEqual(bytes)
+ expect(
+ (await readdir(task.saveDir)).filter((name) =>
+ name.endsWith('.torrent')
+ )
+ ).toEqual([])
+ }
const readActivity = async (page = mainWindow) => {
const result = (await invoke(page, Queries.GetTaskInspectorActivity, {
taskId: (await readTask(page)).id,
@@ -82,6 +103,7 @@ test('unlimited BT seeding, inspector metrics and re-seeding survive engine rest
const first = await readTask()
expect(first.progress).toBe(1)
expect(await fixture.verifyFile(first.finalPath)).toBe(true)
+ await expectInternalTorrentStorage(first)
// Inspector Activity publishes durable checkpoints every 30 seconds.
await expect.poll(() => seedingMs(), { timeout: 40_000 }).toBeGreaterThan(0)
await mainWindow
@@ -115,6 +137,7 @@ test('unlimited BT seeding, inspector metrics and re-seeding survive engine rest
await invoke(mainWindow, Commands.ReAddTask, first.id)
await expect.poll(async () => (await readTask()).status).toBe('seeding')
expect((await readTask()).engineTaskId).not.toBe(first.engineTaskId)
+ await expectInternalTorrentStorage(await readTask())
await mainWindow.waitForTimeout(2500)
const beforeRestart = await seedingMs()
await electronApp.close()
@@ -126,6 +149,7 @@ test('unlimited BT seeding, inspector metrics and re-seeding survive engine rest
timeout: 15_000,
})
.toBe('seeding')
+ await expectInternalTorrentStorage(await readTask(nextWindow))
const afterRestart = await seedingMs(nextWindow)
expect(afterRestart).toBeGreaterThanOrEqual(beforeRestart)
expect(afterRestart).toBeGreaterThan(stoppedMs)
diff --git a/src/core/session/session-manager.test.ts b/src/core/session/session-manager.test.ts
index 936672c2..17265de9 100644
--- a/src/core/session/session-manager.test.ts
+++ b/src/core/session/session-manager.test.ts
@@ -4445,7 +4445,7 @@ it('re-adds an interrupted indexed BT download with its original payload mapping
}
})
-it('restores a paused direct BT download at its exact final filename', async () => {
+it('restores an existing paused direct BT download with internal engine metadata and the same final filename', async () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'motrix-readd-layout-'))
try {
const bytes = buildSingleFileTorrent('movie.mkv')
@@ -4454,7 +4454,8 @@ it('restores a paused direct BT download at its exact final filename', async ()
const parsed = await parseBtFileLayout(bytes)
const plan = createBtDirectStoragePlan(
path.join(root, 'chosen.mkv'),
- parsed
+ parsed,
+ metadata
)
const tm = new TaskManager()
const db = createMockDb()
@@ -4473,7 +4474,8 @@ it('restores a paused direct BT download at its exact final filename', async ()
await new SessionManager(tm, createMockRpc(), db, adapter).restore()
expect(adapter.addTorrent).toHaveBeenCalledWith(
expect.objectContaining({
- saveDir: root,
+ saveDir: `${metadata}.state`,
+ outputRoot: root,
outputFilePaths: [{ fileIndex: 0, relativePath: 'chosen.mkv' }],
pause: true,
checkIntegrity: true,
diff --git a/src/core/task/actions/finalize-task.test.ts b/src/core/task/actions/finalize-task.test.ts
index adf38c6d..9abffa42 100644
--- a/src/core/task/actions/finalize-task.test.ts
+++ b/src/core/task/actions/finalize-task.test.ts
@@ -713,7 +713,13 @@ describe('finalizeTask BT branch', () => {
buildSingleFileTorrent('original.iso')
)
await expect(finalizeTask('t1', deps)).resolves.toBeUndefined()
- expect(deps.adapter.addTorrent).toHaveBeenCalled()
+ expect(deps.adapter.addTorrent).toHaveBeenCalledWith(
+ expect.objectContaining({
+ saveDir: `${task.torrentMetaPath}.state`,
+ outputRoot: '/d',
+ outputFilePaths: [{ fileIndex: 0, relativePath: 'movie.iso' }],
+ })
+ )
expect(task.status).toBe(TaskStatus.Seeding)
expect(deps.fs.renameAtomic).not.toHaveBeenCalled()
expect(task.transitionPhase).toBe(TransitionPhase.Idle)
diff --git a/src/core/task/actions/re-add-task.test.ts b/src/core/task/actions/re-add-task.test.ts
index 075f00d2..8ca9e185 100644
--- a/src/core/task/actions/re-add-task.test.ts
+++ b/src/core/task/actions/re-add-task.test.ts
@@ -137,7 +137,8 @@ describe('reAddTask (BT path)', () => {
await reAddTask('t1', deps)
expect(deps.adapter.addTorrent).toHaveBeenCalledWith(
expect.objectContaining({
- saveDir: '/tmp',
+ saveDir: '/sidecar/sample.torrent.state',
+ outputRoot: '/tmp',
outputFilePaths: [{ fileIndex: 0, relativePath: 'chosen.iso' }],
checkIntegrity: true,
})
diff --git a/src/core/task/bt-direct-storage.integration.test.ts b/src/core/task/bt-direct-storage.integration.test.ts
index b18a832d..a859184d 100644
--- a/src/core/task/bt-direct-storage.integration.test.ts
+++ b/src/core/task/bt-direct-storage.integration.test.ts
@@ -9,6 +9,7 @@ import {
rm,
writeFile,
} from 'node:fs/promises'
+import { createServer } from 'node:http'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { TaskStatus } from '@shared/types/task'
@@ -24,6 +25,7 @@ import {
createBtDirectStoragePlan,
parseBtFileLayout,
} from './bt-storage-layout'
+import { TorrentMetaStoreImpl } from './torrent-meta-store'
type BencodeValue =
| string
@@ -128,6 +130,13 @@ describe.skipIf(!bundledAria2Exists() || !canBindLoopbackTcp())(
})
.toBe(TaskStatus.Seeding)
const files = await wired.adapter.getTaskFiles(gid)
+ const metadataName = `${createHash('sha1').update(metadata).digest('hex')}.torrent`
+ expect(await readFile(path.join(plan.saveDir, metadataName))).toEqual(
+ metadata
+ )
+ expect(
+ (await readdir(root)).filter((name) => name.endsWith('.torrent'))
+ ).toEqual([])
expect(files.map((file) => file.path)).toEqual(
multiFile
? [
@@ -162,6 +171,161 @@ describe.skipIf(!bundledAria2Exists() || !canBindLoopbackTcp())(
}
)
+it.skipIf(!bundledAria2Exists() || !canBindLoopbackTcp()).each([false, true])(
+ 'downloads and restores a single file without exposing torrent metadata (sqlite=%s)',
+ async (sqlite) => {
+ const root = await mkdtemp(path.join(tmpdir(), 'motrix-bt-metadata-'))
+ let handle: Aria2Handle | undefined
+ let disconnect: (() => void) | undefined
+ const payload = Buffer.alloc(128 * 1024, 42)
+ let requests = 0
+ const server = createServer((request, response) => {
+ const range = /^bytes=(\d+)-(\d*)$/.exec(request.headers.range ?? '')
+ if (request.url !== '/original.bin' || !range) {
+ response.writeHead(400).end()
+ return
+ }
+ requests++
+ const start = Number(range[1])
+ const end = Math.min(
+ Number(range[2] || payload.length - 1),
+ payload.length - 1
+ )
+ response.writeHead(206, {
+ 'content-length': end - start + 1,
+ 'content-range': `bytes ${start}-${end}/${payload.length}`,
+ })
+ response.end(payload.subarray(start, end + 1))
+ })
+ try {
+ 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('Missing server address')
+ const metadata = encode({
+ info: {
+ name: 'original.bin',
+ length: payload.length,
+ 'piece length': 16384,
+ pieces: Buffer.concat(
+ Array.from({ length: payload.length / 16384 }, () =>
+ createHash('sha1').update(payload.subarray(0, 16384)).digest()
+ )
+ ),
+ },
+ 'url-list': [`http://127.0.0.1:${address.port}/original.bin`],
+ })
+ const downloads = path.join(root, 'downloads')
+ await mkdir(downloads)
+ const finalPath = path.join(downloads, 'Chosen 文件.bin')
+ const store = new TorrentMetaStoreImpl(
+ path.join(root, 'app-data', 'torrents')
+ )
+ const metadataPath = await store.persist('task', metadata)
+ const plan = createBtDirectStoragePlan(
+ finalPath,
+ await parseBtFileLayout(metadata),
+ metadataPath
+ )
+ const sessionPath = path.join(root, 'aria2.session')
+ const startEngine = async (restart = false) => {
+ handle = await spawnAria2ForTest({
+ baseDir: root,
+ extraArgs: [
+ '--enable-dht6=false',
+ '--bt-enable-lpd=false',
+ '--bt-tracker=',
+ '--all-proxy=',
+ '--http-proxy=',
+ '--https-proxy=',
+ '--no-proxy=*',
+ '--force-save=true',
+ '--auto-save-interval=1',
+ `--enable-sqlite3-persistence=${sqlite}`,
+ `--sqlite3-db-path=${path.join(root, 'aria2.db')}`,
+ `--save-session=${sessionPath}`,
+ ...(!sqlite && restart ? [`--input-file=${sessionPath}`] : []),
+ ],
+ })
+ const wired = await connectAdapter(handle)
+ disconnect = wired.disconnect
+ return wired
+ }
+ let wired = await startEngine()
+ const params = { metadata, ...plan, seedTime: 60, seedRatio: 0 }
+ const gid = await wired.adapter.addTorrent(params)
+ await expect
+ .poll(async () => (await wired.adapter.getTaskStatus(gid))?.status, {
+ timeout: 10000,
+ })
+ .toBe(TaskStatus.Seeding)
+ expect(requests).toBeGreaterThan(0)
+ expect(await readFile(finalPath)).toEqual(payload)
+ expect(
+ (await readdir(downloads)).filter((name) => name.endsWith('.torrent'))
+ ).toEqual([])
+ const metadataName = `${createHash('sha1').update(metadata).digest('hex')}.torrent`
+ expect(await readFile(path.join(plan.saveDir, metadataName))).toEqual(
+ metadata
+ )
+ await wired.adapter.pauseTask(gid)
+ await expect
+ .poll(async () => (await wired.adapter.getTaskStatus(gid))?.status)
+ .toBe(TaskStatus.Paused)
+ disconnect?.()
+ if (sqlite && handle) {
+ // SQLite must recover the paused owner without a shutdown flush.
+ const proc = handle.proc
+ await new Promise<void>((resolve) => {
+ proc.once('exit', () => resolve())
+ proc.kill('SIGKILL')
+ })
+ } else await handle?.kill()
+ wired = await startEngine(true)
+ await expect
+ .poll(async () => (await wired.adapter.getTaskStatus(gid))?.status)
+ .toBe(TaskStatus.Paused)
+ expect(
+ (await wired.adapter.getTaskFiles(gid)).map((file) => file.path)
+ ).toEqual([finalPath])
+ await wired.adapter.resumeTask(gid)
+ await expect
+ .poll(async () => (await wired.adapter.getTaskStatus(gid))?.status, {
+ timeout: 10000,
+ })
+ .toBe(TaskStatus.Seeding)
+ await wired.adapter.forceRemoveTask(gid)
+ await wired.adapter.removeDownloadResult(gid)
+ const reseedGid = await wired.adapter.addTorrent({
+ ...params,
+ metadata: await store.read(metadataPath),
+ checkIntegrity: true,
+ })
+ await expect
+ .poll(
+ async () => (await wired.adapter.getTaskStatus(reseedGid))?.status,
+ { timeout: 10000 }
+ )
+ .toBe(TaskStatus.Seeding)
+ expect(await readFile(finalPath)).toEqual(payload)
+ expect(
+ (await readdir(downloads)).filter((name) => name.endsWith('.torrent'))
+ ).toEqual([])
+ expect(await store.read(metadataPath)).toEqual(new Uint8Array(metadata))
+ } finally {
+ disconnect?.()
+ await handle?.kill()
+ server.closeAllConnections()
+ await new Promise<void>((resolve) => server.close(() => resolve()))
+ await rm(root, { recursive: true, force: true })
+ }
+ },
+ 30000
+)
+
it.skipIf(!bundledAria2Exists() || !canBindLoopbackTcp())(
'seeds payload whose name matches an aria2 control file',
async () => {
diff --git a/src/core/task/bt-storage-layout.test.ts b/src/core/task/bt-storage-layout.test.ts
index 4183c507..12be9423 100644
--- a/src/core/task/bt-storage-layout.test.ts
+++ b/src/core/task/bt-storage-layout.test.ts
@@ -115,9 +115,13 @@ describe('legacy BT indexed storage layout', () => {
})
describe('direct BT storage layout', () => {
- it('writes a single file at its chosen final name from the start', async () => {
+ it('separates single-file payloads from engine metadata at their chosen final name', async () => {
const parsed = await parseBtFileLayout(singleFileTorrent('original.iso'))
- const plan = createBtDirectStoragePlan('/downloads/chosen.iso', parsed)
+ const plan = createBtDirectStoragePlan(
+ '/downloads/chosen.iso',
+ parsed,
+ '/metadata/task.torrent'
+ )
expect(plan).toEqual({
layout: {
version: 2,
@@ -126,11 +130,19 @@ describe('direct BT storage layout', () => {
multiFile: false,
finalized: false,
},
- saveDir: '/downloads',
+ saveDir: '/metadata/task.torrent.state',
+ outputRoot: '/downloads',
outputFilePaths: [{ fileIndex: 0, relativePath: 'chosen.iso' }],
})
})
+ it('requires durable metadata before placing a single-file engine task', async () => {
+ const parsed = await parseBtFileLayout(singleFileTorrent('original.iso'))
+ expect(() =>
+ createBtDirectStoragePlan('/downloads/chosen.iso', parsed)
+ ).toThrow('BT requires a durable torrent metadata path')
+ })
+
it('separates multi-file payloads from engine control files', async () => {
const parsed = await parseBtFileLayout(
new Uint8Array(readFileSync(FIXTURE_PATH))
diff --git a/src/core/task/bt-storage-layout.ts b/src/core/task/bt-storage-layout.ts
index 8570b179..9d12c168 100644
--- a/src/core/task/bt-storage-layout.ts
+++ b/src/core/task/bt-storage-layout.ts
@@ -55,15 +55,17 @@ export function buildBtDirectOutputPaths(
outputFilePaths?: BtOutputFilePath[]
} {
if (!parsed) return { saveDir: finalPath }
+ if (!torrentMetaPath)
+ throw new Error('BT requires a durable torrent metadata path')
+ const saveDir = `${torrentMetaPath}.state`
if (!parsed.multiFile)
return {
- saveDir: path.dirname(finalPath),
+ saveDir,
+ outputRoot: path.dirname(finalPath),
outputFilePaths: buildFinalOutputFilePaths(parsed, finalPath),
}
- if (!torrentMetaPath)
- throw new Error('Multi-file BT requires a durable torrent metadata path')
return {
- saveDir: `${torrentMetaPath}.state`,
+ saveDir,
outputRoot: finalPath,
outputFilePaths: parsed.files.map((file) => {
if (!file.pathInsideRoot)
diff --git a/src/core/task/create-task-handler.test.ts b/src/core/task/create-task-handler.test.ts
index fd94d619..bbd40352 100644
--- a/src/core/task/create-task-handler.test.ts
+++ b/src/core/task/create-task-handler.test.ts
@@ -1156,8 +1156,8 @@ describe('handleCreateTask', () => {
})
const [, , options] = deps.addTorrent.mock.calls[0]
expect(options).toMatchObject({
- dir: '/d',
- 'index-out': ['1=ubuntu-25.10-desktop-amd64.iso'],
+ dir: `${task.torrentMetaPath}.state`,
+ 'index-out': ['1=/d/ubuntu-25.10-desktop-amd64.iso'],
})
expect(options).not.toHaveProperty('bt-prioritize-piece')
})
diff --git a/src/core/task/create-task-handler.ts b/src/core/task/create-task-handler.ts
index 55b55835..a8de3c4e 100644
--- a/src/core/task/create-task-handler.ts
+++ b/src/core/task/create-task-handler.ts
@@ -561,10 +561,9 @@ async function handleCreateTaskUnderAdmission(
}
// Create the engine's directory before admission so aria2 can persist its
- // torrent metadata. Multi-file BT uses its private metadata directory and
- // maps every payload into the final output root. Single-file BT uses the
- // destination parent; unresolved BT uses the final container. HTTP keeps
- // its incomplete suffix inside the chosen save root.
+ // torrent metadata. Parsed BT maps payloads from its private metadata
+ // directory into their final locations; unresolved BT uses the final
+ // container. HTTP keeps its incomplete suffix inside the chosen save root.
const ensureDir = btStoragePlan?.saveDir ?? effectiveSaveDir
try {
await mkdir(ensureDir, { recursive: true })
diff --git a/src/core/torrent/swap-magnet-metadata-for-bt.test.ts b/src/core/torrent/swap-magnet-metadata-for-bt.test.ts
index 36654d7d..265047b0 100644
--- a/src/core/torrent/swap-magnet-metadata-for-bt.test.ts
+++ b/src/core/torrent/swap-magnet-metadata-for-bt.test.ts
@@ -1268,7 +1268,8 @@ describe('swapMagnetMetadataForBt', () => {
)
const params = adapter.addTorrent.mock.calls[0][0]
- expect(params.saveDir).toBe('/Selected')
+ expect(params.saveDir).toBe('/u/torrents/m-mag.torrent.state')
+ expect(params.outputRoot).toBe('/Selected')
expect(db.getTask('m-mag')?.instances[0].diskPath).toBe(
'/Selected/User friendly name.iso'
)