A full-featured download manager.
fix(engine): recover conflicting magnet session identities (#2141)
Dr_rOot97861dfc9594
diff --git a/src/core/engine/aria2/aria2-config-builder.test.ts b/src/core/engine/aria2/aria2-config-builder.test.tsindex ea06bb05..f45511e3 100644--- a/src/core/engine/aria2/aria2-config-builder.test.ts+++ b/src/core/engine/aria2/aria2-config-builder.test.ts@@ -2,12 +2,14 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'// ─── Mock node:fs/promises ───────────────────────────────────-const { mockAccess, mockCopyFile, mockMkdir, mockRename } = vi.hoisted(() => ({- mockAccess: vi.fn(),- mockCopyFile: vi.fn(),- mockMkdir: vi.fn(),- mockRename: vi.fn(),-}))+const { mockAccess, mockCopyFile, mockMkdir, mockRename, mockReadFile } =+ vi.hoisted(() => ({+ mockAccess: vi.fn(),+ mockCopyFile: vi.fn(),+ mockMkdir: vi.fn(),+ mockRename: vi.fn(),+ mockReadFile: vi.fn(),+ }))vi.mock('node:fs/promises', () => ({default: {@@ -15,11 +17,13 @@ vi.mock('node:fs/promises', () => ({copyFile: mockCopyFile,mkdir: mockMkdir,rename: mockRename,+ readFile: mockReadFile,},access: mockAccess,copyFile: mockCopyFile,mkdir: mockMkdir,rename: mockRename,+ readFile: mockReadFile,}))import type { Aria2ProxyOptions } from '@core/proxy/serializers'@@ -68,6 +72,7 @@ describe('Aria2ConfigBuilder', () => {beforeEach(() => {vi.clearAllMocks()+ mockReadFile.mockResolvedValue('')builder = new Aria2ConfigBuilder('/app/extra/aria2.conf','/home/user/.config/motrix'@@ -108,6 +113,52 @@ describe('Aria2ConfigBuilder', () => {})})+ it.each([true, false])(+ 'clears a configured input-file when text loading is disabled (SQLite=%s)',+ async (sqlite3Persistence) => {+ mockReadFile.mockResolvedValue(' input-file=/old/missing.session\n')+ await builder.ensureUserConfig()+ const args = buildArgs(+ makeEngineSettings({ sqlite3Persistence }),+ true,+ null,+ { download: 0, upload: 0 }+ )+ expect(args).toContain('--input-file=')+ expect(+ args.filter((arg) => arg.startsWith('--input-file='))+ ).toHaveLength(1)+ }+ )++ it('overrides configured input with an available managed text session', async () => {+ mockReadFile.mockResolvedValue('input-file=/old/session\n')+ await builder.ensureUserConfig()+ expect(+ buildArgs(+ makeEngineSettings({ sqlite3Persistence: false }),+ true,+ null,+ { download: 0, upload: 0 },+ true+ )+ ).toContain('--input-file=/home/user/.config/motrix/aria2.session')+ })++ it('refreshes configured input-file detection on every start', async () => {+ mockReadFile+ .mockResolvedValueOnce('input-file=/old/session\n')+ .mockResolvedValueOnce('# input-file=/commented/session\n')+ await builder.ensureUserConfig()+ await builder.ensureUserConfig()+ expect(+ buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, {+ download: 0,+ upload: 0,+ }).some((arg) => arg.startsWith('--input-file='))+ ).toBe(false)+ })+describe('hasSavedSession', () => {it('returns true when the text session exists', async () => {mockAccess.mockResolvedValue(undefined)diff --git a/src/core/engine/aria2/aria2-config-builder.ts b/src/core/engine/aria2/aria2-config-builder.tsindex a7ae1185..48a3ec8f 100644--- a/src/core/engine/aria2/aria2-config-builder.ts+++ b/src/core/engine/aria2/aria2-config-builder.ts@@ -1,5 +1,5 @@import { randomUUID } from 'node:crypto'-import { access, copyFile, mkdir, rename } from 'node:fs/promises'+import { access, copyFile, mkdir, readFile, rename } from 'node:fs/promises'import path from 'node:path'import {extractAria2ProxyCredentials,@@ -20,6 +20,7 @@ export class Aria2ConfigBuilder {private readonly dhtFilePath: stringprivate readonly dht6FilePath: stringprivate readonly rpcListenAll: boolean+ private configuredInputFile = falseconstructor(private templatePath: string,@@ -37,13 +38,17 @@ export class Aria2ConfigBuilder {async ensureUserConfig(): Promise<string> {try {await access(this.userConfPath)- return this.userConfPath} catch {// File does not exist — copy from templateawait mkdir(this.userConfigDir, { recursive: true })await copyFile(this.templatePath, this.userConfPath)- return this.userConfPath}+ // aria2.conf remains user-owned. An omitted CLI flag would inherit its+ // input-file, so explicitly clear that value when this startup uses no+ // text input. Ordinary first launches still omit the flag entirely.+ const config = await readFile(this.userConfPath, 'utf8')+ this.configuredInputFile = /^\s*input-file\s*=/m.test(config)+ return this.userConfPath}/**@@ -182,6 +187,8 @@ export class Aria2ConfigBuilder {}if (loadTextSession && !sqliteActive) {args.push(`--input-file=${this.saveSessionPath}`)+ } else if (this.configuredInputFile) {+ args.push('--input-file=')}if (hasSqlitePersistence) {const dbPath = settings.sqlite3DbPath?.trim() || this.defaultDbPathdiff --git a/src/core/engine/aria2/aria2-session-identity-recovery.integration.test.ts b/src/core/engine/aria2/aria2-session-identity-recovery.integration.test.tsnew file mode 100644index 00000000..9191ec28--- /dev/null+++ b/src/core/engine/aria2/aria2-session-identity-recovery.integration.test.ts@@ -0,0 +1,336 @@+// @vitest-environment node+import { createHash } from 'node:crypto'+import { once } from 'node:events'+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'+import { createServer as createHttpServer } from 'node:http'+import { type AddressInfo, createServer } from 'node:net'+import { tmpdir } from 'node:os'+import path from 'node:path'+import { DEFAULT_ENGINE_SETTINGS } from '@core/settings/validators'+import {+ type Aria2Handle,+ bundledAria2Exists,+ canBindLoopbackTcp,+ connectAdapter,+ spawnAria2ForTest,+} from '@test-utils/aria2'+import Database from 'better-sqlite3'+import { describe, expect, it, vi } from 'vitest'+import { Aria2ConfigBuilder } from './aria2-config-builder'+import { recoverAria2SessionIdentity } from './aria2-session-identity-recovery'++type Encodable = number | string | Uint8Array | { [key: string]: Encodable }+function encode(value: Encodable): Buffer {+ if (typeof value === 'number') return Buffer.from(`i${value}e`)+ if (typeof value === 'string') return encode(Buffer.from(value))+ if (value instanceof Uint8Array)+ return Buffer.concat([Buffer.from(`${value.length}:`), value])+ return Buffer.concat([+ Buffer.from('d'),+ ...Object.keys(value)+ .sort()+ .flatMap((key) => [encode(key), encode(value[key])]),+ Buffer.from('e'),+ ])+}++async function availablePort(): Promise<number> {+ const server = createServer()+ server.listen(0, '127.0.0.1')+ await once(server, 'listening')+ const port = (server.address() as AddressInfo).port+ await new Promise<void>((resolve) => server.close(() => resolve()))+ return port+}++function snapshot(file: string) {+ const db = new Database(file, { readonly: true, fileMustExist: true })+ try {+ return {+ rows: db+ .prepare('SELECT gid, state, serialized FROM task')+ .all() as Array<{ gid: string; state: string; serialized: string }>,+ progress: db+ .prepare('SELECT gid, bitfield FROM task_progress')+ .all() as Array<{ gid: string; bitfield: Buffer }>,+ integrity: db.pragma('integrity_check', { simple: true }),+ }+ } finally {+ db.close()+ }+}++describe.skipIf(!bundledAria2Exists() || !canBindLoopbackTcp())(+ 'session recovery with the released aria2 binary',+ () => {+ it.each(['SIGTERM', 'SIGKILL'] as const)(+ 'resumes the original payload through two restarts after %s',+ async (signal) => {+ const root = await mkdtemp(+ path.join(tmpdir(), 'motrix-magnet-restart-')+ )+ const seedDir = path.join(root, 'seed')+ const downloadDir = path.join(root, 'downloads')+ await mkdir(seedDir)+ await mkdir(downloadDir)+ const payload = Buffer.alloc(1024 * 1024, 0x61)+ const pieceLength = 16384+ const pieceHash = createHash('sha1')+ .update(payload.subarray(0, pieceLength))+ .digest()+ const info = {+ name: 'payload.bin',+ length: payload.length,+ 'piece length': pieceLength,+ pieces: Buffer.concat(+ Array.from(+ { length: payload.length / pieceLength },+ () => pieceHash+ )+ ),+ }+ const infoHash = createHash('sha1').update(encode(info)).digest('hex')+ const seedPort = await availablePort()+ const compactPeer = Buffer.from([+ 127,+ 0,+ 0,+ 1,+ seedPort >> 8,+ seedPort & 255,+ ])+ const tracker = createHttpServer((_req, res) => {+ const response = encode({+ interval: 1,+ complete: 1,+ incomplete: 0,+ peers: compactPeer,+ })+ res.writeHead(200, { 'Content-Length': response.length })+ res.end(response)+ })+ tracker.listen(0, '127.0.0.1')+ await once(tracker, 'listening')+ const trackerUrl = `http://127.0.0.1:${(tracker.address() as AddressInfo).port}/announce`+ const torrent = encode({ announce: trackerUrl, info })+ const dbPath = path.join(downloadDir, 'aria2.db')+ const common = [+ '--enable-dht6=false',+ '--bt-enable-lpd=false',+ '--enable-peer-exchange=false',+ '--seed-ratio=0',+ '--bt-exclude-tracker=*',+ `--bt-tracker=${trackerUrl}`,+ '--force-save=true',+ ]+ const args = [+ ...common,+ '--enable-sqlite3-persistence=true',+ `--sqlite3-db-path=${dbPath}`,+ `--save-session=${downloadDir}/aria2.session`,+ '--save-session-interval=1',+ '--auto-save-interval=1',+ '--max-download-limit=64K',+ '--seed-time=0',+ `--listen-port=${await availablePort()}`,+ ]+ let seed: Aria2Handle | undefined+ let download: Aria2Handle | undefined+ let seeder: Awaited<ReturnType<typeof connectAdapter>> | undefined+ let downloader: Awaited<ReturnType<typeof connectAdapter>> | undefined+ try {+ await writeFile(path.join(seedDir, 'payload.bin'), payload)+ seed = await spawnAria2ForTest({+ baseDir: seedDir,+ port: await availablePort(),+ extraArgs: [+ ...common,+ `--listen-port=${seedPort}`,+ '--seed-time=60',+ ],+ })+ seeder = await connectAdapter(seed)+ await seeder.rpc.addTorrent(torrent.toString('base64'), [], {+ 'bt-seed-unverified': 'true',+ })+ download = await spawnAria2ForTest({+ baseDir: downloadDir,+ port: await availablePort(),+ extraArgs: args,+ })+ downloader = await connectAdapter(download)+ const metadataGid = await downloader.rpc.addUri([+ `magnet:?xt=urn:btih:${infoHash}&tr=${encodeURIComponent(trackerUrl)}`,+ ])+ let payloadGid = ''+ await vi.waitFor(+ async () => {+ payloadGid =+ (await downloader!.rpc.tellStatus(metadataGid))+ .followedBy?.[0] ?? ''+ expect(payloadGid).not.toBe('')+ },+ { timeout: 20000, interval: 100 }+ )+ await vi.waitFor(+ async () => {+ expect(+ Number(+ (await downloader!.rpc.tellStatus(payloadGid)).completedLength+ )+ ).toBeGreaterThanOrEqual(pieceLength)+ expect(+ snapshot(dbPath).progress.some(+ (row) =>+ row.gid === payloadGid &&+ row.bitfield.some((byte) => byte !== 0)+ )+ ).toBe(true)+ },+ { timeout: 20000, interval: 100 }+ )+ if (signal === 'SIGTERM') {+ await downloader.rpc.forcePause(payloadGid)+ await vi.waitFor(async () =>+ expect(+ (await downloader!.rpc.tellStatus(payloadGid)).status+ ).toBe('paused')+ )+ }+ await downloader.rpc.saveSession()+ downloader.disconnect()+ if (signal === 'SIGKILL') {+ const exit = once(download.proc, 'exit')+ download.proc.kill(signal)+ await exit+ } else await download.kill()++ const before = snapshot(dbPath)+ expect(before.integrity).toBe('ok')+ expect(+ before.rows.find((row) => row.gid === payloadGid)?.serialized+ ).toContain(`gid=${metadataGid}`)+ const result = await recoverAria2SessionIdentity(dbPath)+ expect(result?.repairedGids).toEqual([payloadGid])+ expect(result?.retiredMetadataGids).toEqual([metadataGid])+ expect(+ snapshot(dbPath).progress.find((row) => row.gid === payloadGid)+ ).toEqual(before.progress.find((row) => row.gid === payloadGid))++ download = await spawnAria2ForTest({+ baseDir: downloadDir,+ port: await availablePort(),+ extraArgs: args,+ })+ downloader = await connectAdapter(download)+ await vi.waitFor(async () => {+ const task = await downloader!.rpc.tellStatus(payloadGid)+ expect(task.infoHash).toBe(infoHash)+ // Paused local torrents defer file initialization until unpause.+ if (signal === 'SIGKILL')+ expect(task.totalLength).toBe(String(payload.length))+ expect(task.status).toBe(signal === 'SIGTERM' ? 'paused' : 'active')+ })+ const current = [+ ...(await downloader.rpc.tellActive()),+ ...(await downloader.rpc.tellWaiting(0, 100)),+ ]+ expect(current.map((row) => row.gid)).toEqual([payloadGid])+ // A second startup must remain healthy after the unchanged engine saves+ // the repaired local-torrent entry itself.+ if (signal === 'SIGKILL') {+ await downloader.rpc.forcePause(payloadGid)+ await vi.waitFor(async () =>+ expect(+ (await downloader!.rpc.tellStatus(payloadGid)).status+ ).toBe('paused')+ )+ }+ await downloader.rpc.saveSession()+ downloader.disconnect()+ await download.kill()+ expect(await recoverAria2SessionIdentity(dbPath)).toBeNull()+ download = await spawnAria2ForTest({+ baseDir: downloadDir,+ port: await availablePort(),+ extraArgs: args,+ })+ downloader = await connectAdapter(download)+ expect((await downloader.rpc.tellStatus(payloadGid)).status).toBe(+ 'paused'+ )+ await downloader.rpc.changeOption(payloadGid, {+ 'max-download-limit': '0',+ })+ await downloader.rpc.unpause(payloadGid)+ await vi.waitFor(+ async () => {+ const task = await downloader!.rpc.tellStatus(payloadGid)+ expect(task.completedLength).toBe(String(payload.length))+ expect(task.errorCode ?? '0').toBe('0')+ },+ { timeout: 30000, interval: 100 }+ )+ expect(await readFile(path.join(downloadDir, 'payload.bin'))).toEqual(+ payload+ )+ } finally {+ downloader?.disconnect()+ seeder?.disconnect()+ await download?.kill()+ await seed?.kill()+ tracker.closeAllConnections()+ await new Promise<void>((resolve) => tracker.close(() => resolve()))+ await rm(root, { recursive: true, force: true })+ }+ },+ 90000+ )++ it.each([false, true])(+ 'clears inherited input-file without requiring a session file (SQLite=%s)',+ async (sqlite3Persistence) => {+ const root = await mkdtemp(path.join(tmpdir(), 'motrix-input-file-'))+ let handle: Aria2Handle | undefined+ try {+ await writeFile(+ path.join(root, 'aria2.conf'),+ `input-file=${root}/missing.session\n`+ )+ const builder = new Aria2ConfigBuilder('unused', root)+ await builder.ensureUserConfig()+ expect(await builder.hasSavedSession()).toBe(false)+ const port = await availablePort()+ const settings = {+ ...DEFAULT_ENGINE_SETTINGS,+ sqlite3Persistence,+ rpcPort: port,+ rpcSecret: 'test_secret',+ dhtEnabled: false,+ listenPort: await availablePort(),+ }+ const args = builder.buildArgs(+ settings,+ true,+ null,+ { download: 0, upload: 0 },+ root,+ false+ )+ expect(args).toContain('--input-file=')+ handle = await spawnAria2ForTest({+ baseDir: root,+ port,+ extraArgs: ['--no-conf=false', ...args],+ })+ const connected = await connectAdapter(handle)+ expect(await connected.rpc.tellActive()).toEqual([])+ connected.disconnect()+ } finally {+ await handle?.kill()+ await rm(root, { recursive: true, force: true })+ }+ }+ )+ }+)diff --git a/src/core/engine/aria2/aria2-session-identity-recovery.test.ts b/src/core/engine/aria2/aria2-session-identity-recovery.test.tsnew file mode 100644index 00000000..4160b11e--- /dev/null+++ b/src/core/engine/aria2/aria2-session-identity-recovery.test.ts@@ -0,0 +1,302 @@+// @vitest-environment node+import { createHash } from 'node:crypto'+import {+ mkdtemp,+ readdir,+ readFile,+ rm,+ unlink,+ writeFile,+} from 'node:fs/promises'+import { tmpdir } from 'node:os'+import path from 'node:path'+import Database from 'better-sqlite3'+import parseTorrent from 'parse-torrent'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { recoverAria2SessionIdentity } from './aria2-session-identity-recovery'++const PARENT = '1111111111111111'+const CHILD = '2222222222222222'+const OTHER = '3333333333333333'+const folders: string[] = []++async function setup(state = 'paused') {+ const root = await mkdtemp(path.join(tmpdir(), 'motrix-identity-'))+ folders.push(root)+ const file = path.join(root, 'aria2.db')+ const bytes = await readFile(+ path.resolve('src/core/torrent/__fixtures__/test.torrent')+ )+ const parsed = await parseTorrent(new Uint8Array(bytes))+ const metadataPath = path.join(root, `${parsed.infoHash}.torrent`)+ await writeFile(metadataPath, bytes)+ const source = `magnet:?xt=urn:btih:${parsed.infoHash}`+ const entry = (gid: string, paused = false) =>+ `${source}\n gid=${gid}\n dir=${root}\n${paused ? ' pause=true\n' : ''} select-file=1\n index-out=1=renamed.bin\n header=Cookie: private\n`+ const db = new Database(file)+ db.pragma('foreign_keys = ON')+ db.pragma('journal_mode = WAL')+ db.pragma('user_version = 2')+ db.exec(`+ CREATE TABLE task(gid TEXT PRIMARY KEY, state TEXT, serialized TEXT,+ digest BLOB, bt_local_path TEXT, updated_at INTEGER, queue_position INTEGER);+ CREATE TABLE task_progress(gid TEXT PRIMARY KEY REFERENCES task(gid) ON DELETE CASCADE, bitfield BLOB);+ CREATE TABLE task_cookie_context(gid TEXT PRIMARY KEY REFERENCES task(gid) ON DELETE CASCADE, secret TEXT);+ CREATE TABLE download_history(id INTEGER PRIMARY KEY, gid TEXT, status TEXT, followed_by TEXT);+ `)+ const insert = db.prepare('INSERT INTO task VALUES (?, ?, ?, ?, NULL, 0, ?)')+ insert.run(PARENT, 'waiting', entry(PARENT), Buffer.from('parent-digest'), 0)+ insert.run(+ CHILD,+ state,+ entry(PARENT, state === 'paused'),+ Buffer.from('child-digest'),+ 1+ )+ insert.run(+ OTHER,+ 'waiting',+ 'https://example.test/file\n gid=3333333333333333\n',+ Buffer.from('other-digest'),+ 2+ )+ db.prepare('INSERT INTO task_progress VALUES (?, ?)').run(+ CHILD,+ Buffer.from([0xaa, 0xc0])+ )+ db.prepare('INSERT INTO task_cookie_context VALUES (?, ?)').run(+ CHILD,+ 'private-cookie'+ )+ db.prepare('INSERT INTO download_history VALUES (1, ?, ?, ?)').run(+ PARENT,+ 'complete',+ JSON.stringify([CHILD])+ )+ const rows = () =>+ db.prepare('SELECT * FROM task ORDER BY queue_position').all()+ return { root, file, bytes, metadataPath, db, rows, entry }+}++afterEach(async () => {+ vi.restoreAllMocks()+ await Promise.all(+ folders+ .splice(0)+ .map((folder) => rm(folder, { recursive: true, force: true }))+ )+})++describe('aria2 persisted task identity recovery', () => {+ it.each(['waiting', 'paused'])(+ 'preserves task identity, options and progress (%s)',+ async (state) => {+ const h = await setup(state)+ try {+ const before = h.rows()+ const result = await recoverAria2SessionIdentity(h.file)+ expect(result?.repairedGids).toEqual([CHILD])+ expect(result?.retiredMetadataGids).toEqual([PARENT])+ const backup = new Database(result!.backupPath, { readonly: true })+ try {+ expect(+ backup.prepare('SELECT * FROM task ORDER BY queue_position').all()+ ).toEqual(before)+ expect(backup.pragma('integrity_check', { simple: true })).toBe('ok')+ } finally {+ backup.close()+ }+ const child = h.db+ .prepare('SELECT * FROM task WHERE gid = ?')+ .get(CHILD) as {+ serialized: string+ bt_local_path: string+ digest: Buffer+ state: string+ }+ expect(child.state).toBe(state)+ expect(child.serialized).toContain(`\n gid=${CHILD}\n`)+ expect(child.serialized).toContain(+ ' select-file=1\n index-out=1=renamed.bin\n header=Cookie: private\n'+ )+ expect(child.serialized.includes(' pause=true\n')).toBe(+ state === 'paused'+ )+ expect(child.digest).toEqual(+ createHash('sha1').update(child.serialized).update(state).digest()+ )+ expect(await readFile(child.bt_local_path)).toEqual(h.bytes)+ expect(child.serialized.startsWith(`${child.bt_local_path}\n`)).toBe(+ true+ )+ expect(h.db.prepare('SELECT * FROM task_progress').all()).toEqual([+ { gid: CHILD, bitfield: Buffer.from([0xaa, 0xc0]) },+ ])+ expect(h.db.prepare('SELECT * FROM task_cookie_context').all()).toEqual(+ [{ gid: CHILD, secret: 'private-cookie' }]+ )+ expect(h.rows().at(-1)).toEqual(before.at(-1))+ expect(await recoverAria2SessionIdentity(h.file)).toBeNull()+ expect(+ (await readdir(h.root)).filter((name) =>+ name.includes('identity-recovery-')+ )+ ).toHaveLength(1)+ } finally {+ h.db.close()+ }+ }+ )++ it('does not create a database on first launch', async () => {+ const root = await mkdtemp(path.join(tmpdir(), 'motrix-identity-empty-'))+ folders.push(root)+ expect(+ await recoverAria2SessionIdentity(path.join(root, 'aria2.db'))+ ).toBeNull()+ expect(await readdir(root)).toEqual([])+ })++ it('uses durable absolute torrent paths with a relative v1 database path', async () => {+ const h = await setup()+ try {+ h.db.pragma('user_version = 1')+ const result = await recoverAria2SessionIdentity(+ path.relative(process.cwd(), h.file)+ )+ expect(result?.repairedGids).toEqual([CHILD])+ const child = h.db+ .prepare('SELECT serialized FROM task WHERE gid = ?')+ .get(CHILD) as { serialized: string }+ expect(path.isAbsolute(child.serialized.split('\n')[0])).toBe(true)+ expect(h.db.pragma('user_version', { simple: true })).toBe(1)+ } finally {+ h.db.close()+ }+ })++ it.each(['missing', 'invalid', 'mismatched'])(+ 'leaves the entire session untouched when metadata is %s',+ async (variant) => {+ const h = await setup()+ try {+ const before = h.rows()+ if (variant === 'missing') await unlink(h.metadataPath)+ if (variant === 'invalid')+ await writeFile(h.metadataPath, 'not bencode')+ if (variant === 'mismatched')+ await writeFile(+ h.metadataPath,+ await readFile('scripts/poc/fixtures/multi.torrent')+ )+ await expect(recoverAria2SessionIdentity(h.file)).rejects.toThrow(+ 'matching saved torrent metadata is unavailable'+ )+ expect(h.rows()).toEqual(before)+ expect(+ (await readdir(h.root)).some((name) =>+ name.includes('identity-recovery-')+ )+ ).toBe(false)+ } finally {+ h.db.close()+ }+ }+ )++ it('does not retire an ancestor without a matching completed history link', async () => {+ const h = await setup()+ try {+ h.db+ .prepare('UPDATE download_history SET followed_by = ?')+ .run(JSON.stringify([OTHER]))+ const before = h.rows()+ await expect(recoverAria2SessionIdentity(h.file)).rejects.toThrow(+ 'metadata ancestry could not be verified'+ )+ expect(h.rows()).toEqual(before)+ } finally {+ h.db.close()+ }+ })++ it('repairs the payload if the old metadata row was already removed', async () => {+ const h = await setup()+ try {+ h.db.prepare('DELETE FROM task WHERE gid = ?').run(PARENT)+ const result = await recoverAria2SessionIdentity(h.file)+ expect(result?.repairedGids).toEqual([CHILD])+ expect(result?.retiredMetadataGids).toEqual([])+ } finally {+ h.db.close()+ }+ })++ it('rolls back the payload update when ancestor retirement fails', async () => {+ const h = await setup()+ try {+ h.db.exec(+ `CREATE TRIGGER refuse_delete BEFORE DELETE ON task BEGIN SELECT RAISE(ABORT, 'injected failure'); END`+ )+ const before = h.rows()+ await expect(recoverAria2SessionIdentity(h.file)).rejects.toThrow(+ 'injected failure'+ )+ expect(h.rows()).toEqual(before)+ expect(h.db.prepare('SELECT * FROM task_progress').all()).toHaveLength(1)+ } finally {+ h.db.close()+ }+ })++ it('aborts when a separate connection changes the database during backup', async () => {+ const h = await setup()+ const original = Database.prototype.backup+ vi.spyOn(Database.prototype, 'backup').mockImplementation(async function (+ this: Database.Database,+ ...args+ ) {+ const result = await original.apply(this, args)+ h.db+ .prepare('UPDATE task SET state = ? WHERE gid = ?')+ .run('waiting', CHILD)+ return result+ })+ try {+ await expect(recoverAria2SessionIdentity(h.file)).rejects.toThrow(+ 'session changed during recovery'+ )+ expect(+ h.db.prepare('SELECT serialized FROM task WHERE gid = ?').get(CHILD)+ ).toEqual({ serialized: h.entry(PARENT, true) })+ expect(h.rows()).toHaveLength(3)+ } finally {+ h.db.close()+ }+ })++ it('does not write when engine shutdown or another start cancels recovery', async () => {+ const h = await setup()+ try {+ const before = h.rows()+ await expect(+ recoverAria2SessionIdentity(h.file, () => false)+ ).rejects.toThrow('requires a stopped engine')+ expect(h.rows()).toEqual(before)+ } finally {+ h.db.close()+ }+ })++ it('leaves an unfamiliar future schema unchanged', async () => {+ const h = await setup()+ try {+ h.db.pragma('user_version = 3')+ const before = h.rows()+ expect(await recoverAria2SessionIdentity(h.file)).toBeNull()+ expect(h.rows()).toEqual(before)+ } finally {+ h.db.close()+ }+ })+})diff --git a/src/core/engine/aria2/aria2-session-identity-recovery.ts b/src/core/engine/aria2/aria2-session-identity-recovery.tsnew file mode 100644index 00000000..9ce362d0--- /dev/null+++ b/src/core/engine/aria2/aria2-session-identity-recovery.ts@@ -0,0 +1,225 @@+import { createHash } from 'node:crypto'+import { chmod, mkdtemp, readFile, stat } from 'node:fs/promises'+import path from 'node:path'+import { MAX_TORRENT_BASE64_SIZE } from '@shared/lib/torrent-meta'+import Database from 'better-sqlite3'+import parseTorrent from 'parse-torrent'+import writeFileAtomic from 'write-file-atomic'+import { z } from 'zod'++const gidSchema = z.string().regex(/^[0-9a-f]{16}$/)+const rowSchema = z.object({+ gid: gidSchema,+ state: z.string(),+ serialized: z.string(),+})+type Row = z.infer<typeof rowSchema>++interface Entry {+ source: string+ gid: string+ directory: string+ options: string[]+ paused: boolean+}++/** Parse only the single-entry format emitted by aria2's session writer. */+function parseEntry(text: string): Entry | null {+ const lines = text.split(/\r?\n/).filter((line) => line.trim())+ const source = lines.shift()+ if (!source?.startsWith('magnet:') || /\t/.test(source)) return null+ const options = new Map<string, string>()+ for (const line of lines) {+ const match = /^[ \t]+([^=\s]+)=(.*)$/.exec(line)+ if (!match) return null+ const [, key, value] = match+ if (['gid', 'dir', 'pause'].includes(key) && options.has(key)) return null+ options.set(key, value)+ }+ const gid = gidSchema.safeParse(options.get('gid'))+ const directory = options.get('dir')+ if (!gid.success || !directory || !path.isAbsolute(directory)) return null+ return {+ source,+ gid: gid.data,+ directory,+ options: lines,+ paused: options.get('pause') === 'true',+ }+}++function failure(gid: string, reason: string): Error {+ // Do not include serialized options, which may contain cookies or tokens.+ return new Error(`aria2 session recovery for GID ${gid}: ${reason}`)+}++export interface SessionIdentityRecovery {+ backupPath: string+ repairedGids: string[]+ retiredMetadataGids: string[]+}++/**+ * Repair the v1/v2 fork's metadata-ancestor GID serialization before spawn.+ * The actual row key remains the owner of progress, cookies and app identity.+ * A verified local torrent replaces the magnet so aria2 recreates that exact+ * payload task directly. No engine schema, setting or download data changes.+ */+export async function recoverAria2SessionIdentity(+ databasePath: string,+ canRepair: () => boolean = () => true+): Promise<SessionIdentityRecovery | null> {+ try {+ await stat(databasePath)+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null+ throw error+ }+ const db = new Database(databasePath, { fileMustExist: true, timeout: 0 })+ try {+ const schemaVersion = db.pragma('user_version', { simple: true })+ if (schemaVersion !== 1 && schemaVersion !== 2) return null+ const dataVersion = db.pragma('data_version', { simple: true })+ const rows = z+ .array(rowSchema)+ .parse(db.prepare('SELECT gid, state, serialized FROM task').all())+ const candidates = rows.flatMap((row) => {+ const entry = parseEntry(row.serialized)+ return entry && row.gid !== entry.gid ? [{ row, entry }] : []+ })+ if (candidates.length === 0) return null+ if (!canRepair())+ throw new Error('aria2 session recovery requires a stopped engine')++ const retiredMetadataGids = new Set<string>()+ const plans: Array<{ row: Row; entry: Entry; bytes: Buffer }> = []+ for (const { row, entry } of candidates) {+ if (!['waiting', 'paused'].includes(row.state))+ throw failure(row.gid, 'unsupported task state')+ const parent = rows.find((candidate) => candidate.gid === entry.gid)+ if (parent) {+ const parentEntry = parseEntry(parent.serialized)+ const history = db+ .prepare(+ 'SELECT status, followed_by FROM download_history WHERE gid = ? ORDER BY id DESC LIMIT 1'+ )+ .get(parent.gid) as+ | { status: string; followed_by: string | null }+ | undefined+ let children: string[] = []+ try {+ children = z+ .array(gidSchema)+ .parse(JSON.parse(history?.followed_by ?? 'null'))+ } catch {+ // Retire only a proven completed metadata ancestor.+ }+ if (+ parentEntry?.source !== entry.source ||+ parentEntry.gid !== parent.gid ||+ history?.status !== 'complete' ||+ !children.includes(row.gid)+ )+ throw failure(row.gid, 'metadata ancestry could not be verified')+ retiredMetadataGids.add(parent.gid)+ }++ let bytes: Buffer+ try {+ const magnet = await parseTorrent(entry.source)+ if (!magnet.infoHash || !/^[a-f0-9]{40}$/.test(magnet.infoHash))+ throw new Error('invalid infohash')+ const metadataPath = path.join(+ entry.directory,+ `${magnet.infoHash}.torrent`+ )+ const metadataStat = await stat(metadataPath)+ if (+ !metadataStat.isFile() ||+ metadataStat.size > (MAX_TORRENT_BASE64_SIZE * 3) / 4+ )+ throw new Error('invalid metadata size')+ bytes = await readFile(metadataPath)+ const torrent = await parseTorrent(new Uint8Array(bytes))+ if (torrent.infoHash !== magnet.infoHash || !torrent.files?.length)+ throw new Error('metadata does not match magnet')+ } catch {+ throw failure(+ row.gid,+ 'matching saved torrent metadata is unavailable; session was not changed'+ )+ }+ plans.push({ row, entry, bytes })+ }++ if (!canRepair())+ throw new Error('aria2 session recovery requires a stopped engine')+ const recoveryDir = await mkdtemp(+ `${path.resolve(databasePath)}.identity-recovery-`+ )+ const backupPath = path.join(recoveryDir, 'aria2.db')+ // SQLite's backup API includes committed WAL pages; a raw file copy does not.+ await db.backup(backupPath)+ await chmod(backupPath, 0o600)+ const changes: Array<{+ row: Row+ serialized: string+ metadataPath: string+ }> = []+ for (const { row, entry, bytes } of plans) {+ const metadataPath = path.join(recoveryDir, `${row.gid}.torrent`)+ if (/[\r\n\t]/.test(metadataPath))+ throw failure(+ row.gid,+ 'metadata path cannot be represented in an aria2 session'+ )+ // Keep recovery independent of cleanup of the original metadata file.+ await writeFileAtomic(metadataPath, bytes, { mode: 0o600 })+ const options = entry.options.filter(+ (line) => !/^[ \t]+(?:gid|pause|torrent-file)=/.test(line)+ )+ const serialized = `${metadataPath}\n gid=${row.gid}\n${row.state === 'paused' || entry.paused ? ' pause=true\n' : ''}${options.join('\n')}\n`+ changes.push({ row, serialized, metadataPath })+ }++ db.pragma('foreign_keys = ON')+ db.transaction(() => {+ if (+ !canRepair() ||+ db.pragma('data_version', { simple: true }) !== dataVersion+ )+ throw new Error(+ 'aria2 session changed during recovery; retry with the engine stopped'+ )+ const update = db.prepare(+ 'UPDATE task SET serialized = ?, digest = ?, bt_local_path = ?, updated_at = ? WHERE gid = ? AND serialized = ? AND state = ?'+ )+ for (const { row, serialized, metadataPath } of changes) {+ const digest = createHash('sha1')+ .update(serialized)+ .update(row.state)+ .digest()+ const result = update.run(+ serialized,+ digest,+ metadataPath,+ Date.now(),+ row.gid,+ row.serialized,+ row.state+ )+ if (result.changes !== 1)+ throw failure(row.gid, 'task changed during recovery')+ }+ const remove = db.prepare('DELETE FROM task WHERE gid = ?')+ for (const gid of retiredMetadataGids) remove.run(gid)+ }).immediate()+ return {+ backupPath,+ repairedGids: plans.map(({ row }) => row.gid),+ retiredMetadataGids: [...retiredMetadataGids],+ }+ } finally {+ db.close()+ }+}diff --git a/src/core/engine/engine-supervisor.test.ts b/src/core/engine/engine-supervisor.test.tsindex 0ddec8de..67cf681e 100644--- a/src/core/engine/engine-supervisor.test.ts+++ b/src/core/engine/engine-supervisor.test.ts@@ -27,8 +27,13 @@ import { DIRECT_RESOURCE_METADATA_PROFILE } from './engine-adapter'import { EngineSupervisor } from './engine-supervisor'import { checkPort } from './port-check'-const { probePreciseMock } = vi.hoisted(() => ({+const { probePreciseMock, recoverSessionMock } = vi.hoisted(() => ({probePreciseMock: vi.fn(),+ recoverSessionMock: vi.fn().mockResolvedValue(null),+}))++vi.mock('./aria2/aria2-session-identity-recovery', () => ({+ recoverAria2SessionIdentity: recoverSessionMock,}))vi.mock('../probe/disk-probe', () => ({@@ -112,6 +117,7 @@ function createMockConfigBuilder(): Aria2ConfigBuilder {return {ensureUserConfig: vi.fn().mockResolvedValue('/tmp/aria2.conf'),hasSavedSession: vi.fn().mockResolvedValue(false),+ resolveSqliteDbPath: vi.fn().mockReturnValue('/tmp/aria2.db'),quarantineSqliteDatabase: vi.fn().mockResolvedValue({databasePath: '/tmp/aria2.db',quarantineBasePath: '/tmp/aria2.db.corrupt-test',@@ -839,6 +845,54 @@ describe('EngineSupervisor', () => {})})+ it('repairs persisted identities before the completed-task guard and spawn', async () => {+ const prepare = vi.fn().mockResolvedValue(null)+ supervisor.setStartupGuard({ prepare })+ await supervisor.start('/usr/bin/aria2c')+ expect(recoverSessionMock).toHaveBeenCalledWith(+ '/tmp/aria2.db',+ expect.any(Function)+ )+ expect(recoverSessionMock.mock.invocationCallOrder.at(-1)).toBeLessThan(+ prepare.mock.invocationCallOrder[0]!+ )+ expect(prepare.mock.invocationCallOrder[0]).toBeLessThan(+ vi.mocked(processManager.spawn).mock.invocationCallOrder[0]!+ )+ })++ it('does not repair or spawn when the RPC port is occupied', async () => {+ vi.mocked(checkPort).mockResolvedValueOnce(false)+ const calls = recoverSessionMock.mock.calls.length+ await supervisor.start('/usr/bin/aria2c')+ expect(recoverSessionMock).toHaveBeenCalledTimes(calls)+ expect(processManager.spawn).not.toHaveBeenCalled()+ })++ it('does not spawn when identity recovery fails', async () => {+ recoverSessionMock.mockRejectedValueOnce(+ new Error('saved metadata unavailable')+ )+ await supervisor.start('/usr/bin/aria2c')+ expect(supervisor.getState()).toBe(EngineState.Failed)+ expect(processManager.spawn).not.toHaveBeenCalled()+ expect(supervisor.getLastError()).toBe('saved metadata unavailable')+ })++ it('preserves only the GID conflict diagnostic when RPC fails', async () => {+ vi.mocked(rpcClient.connect).mockRejectedValueOnce(+ new Error('ECONNREFUSED')+ )+ vi.mocked(processManager.getRecentStderr).mockReturnValue(+ 'private-url\nGID 283f007637e2399d is not unique.\nCookie: private'+ )+ await supervisor.start('/usr/bin/aria2c')+ expect(supervisor.getLastError()).toBe(+ 'GID 283f007637e2399d is not unique.'+ )+ expect(configBuilder.quarantineSqliteDatabase).not.toHaveBeenCalled()+ })+describe('start — probe failure', () => {it('transitions to Failed when probe rejects', async () => {vi.mocked(processManager.probe).mockRejectedValue(diff --git a/src/core/engine/engine-supervisor.ts b/src/core/engine/engine-supervisor.tsindex 4a82968d..ddf3c146 100644--- a/src/core/engine/engine-supervisor.ts+++ b/src/core/engine/engine-supervisor.ts@@ -33,6 +33,7 @@ import type { Aria2Adapter } from './aria2/aria2-adapter'import type { Aria2ConfigBuilder } from './aria2/aria2-config-builder'import type { Aria2ProcessManager } from './aria2/aria2-process-manager'import type { Aria2RpcClient } from './aria2/aria2-rpc-client'+import { recoverAria2SessionIdentity } from './aria2/aria2-session-identity-recovery'import { isSqliteCorruptionDiagnostic } from './aria2/aria2-sqlite-recovery'import type { Aria2TrustStore } from './aria2/aria2-trust-store'import { recommend } from './aria2/aria2-tuning'@@ -526,6 +527,17 @@ export class EngineSupervisor {return}+ // Repair known fork session identities only after the RPC ownership+ // check, and before the completed-task guard reads persisted run intent.+ if (sqliteActive) {+ const recovery = await recoverAria2SessionIdentity(+ this.configBuilder.resolveSqliteDbPath(engineSettings),+ () => !this.stopping && !this.processManager.isRunning()+ )+ if (recovery)+ log.warn(recovery, 'repaired aria2 metadata task identities')+ }+// Step 4: Spawn process (abort if stop() was called during earlier awaits)if (this.stopping) returnphase = 'spawn'@@ -634,6 +646,12 @@ export class EngineSupervisor {} catch (err) {this.lastError = err instanceof Error ? err.message : String(err)const stderr = this.processManager.getRecentStderr?.() ?? ''+ // Preserve the startup identity failure instead of its later connection+ // refusal. Only capture the fixed diagnostic, never raw task options.+ const gidConflict = stderr.match(+ /\bGID [0-9a-f]{16} is not unique\./i+ )?.[0]+ if (phase === 'rpc' && gidConflict) this.lastError = gidConflict// A process can be alive even though RPC connection failed. Always// tear down a process spawned by this supervisor before entering Failed;diff --git a/src/server/index.ts b/src/server/index.tsindex 0ceea2c7..7ce4dffc 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -179,6 +179,7 @@ import {runServerStartup,type ServerShutdownActions,} from './shutdown'+import { startServerEngine } from './start-engine'import { createServerPersistTask } from './task-persistence'let requestActiveServerExit: ((code: number) => Promise<void>) | null = null@@ -1498,13 +1499,9 @@ async function main() {durableFinalizeRuntime.recoverAll())- try {- await pluginStartup.startEngine(() =>- supervisor.start(platform.aria2BinaryPath)- )- } catch (err) {- log.error({ err }, 'engine start failed')- }+ await pluginStartup.startEngine(() =>+ startServerEngine(supervisor, platform.aria2BinaryPath)+ )if (!shellAsyncWork.isAccepting()) returnawait appliedDownloadProxyPolicy.runWithSnapshot(diff --git a/src/server/start-engine.test.ts b/src/server/start-engine.test.tsnew file mode 100644index 00000000..98c9b201--- /dev/null+++ b/src/server/start-engine.test.ts@@ -0,0 +1,48 @@+import { ErrorCode } from '@shared/errors'+import { EngineState } from '@shared/types/engine'+import { describe, expect, it, vi } from 'vitest'+import { startServerEngine } from './start-engine'++describe('server engine startup', () => {+ it('does not run dependent recovery when start resolves as Failed', async () => {+ const restore = vi.fn()+ const supervisor = {+ start: vi.fn().mockResolvedValue(undefined),+ getState: () => EngineState.Failed,+ getLastError: () => 'GID 283f007637e2399d is not unique.',+ }+ await expect(+ startServerEngine(supervisor, '/app/bin/aria2c').then(restore)+ ).rejects.toMatchObject({+ code: ErrorCode.EngineStartFailed,+ message: 'GID 283f007637e2399d is not unique.',+ })+ expect(restore).not.toHaveBeenCalled()+ })++ it('allows recovery only after Ready', async () => {+ const supervisor = {+ start: vi.fn().mockResolvedValue(undefined),+ getState: () => EngineState.Ready,+ getLastError: () => null,+ }+ await expect(+ startServerEngine(supervisor, '/app/bin/aria2c')+ ).resolves.toBeUndefined()+ expect(supervisor.start).toHaveBeenCalledWith('/app/bin/aria2c')+ })++ it('preserves a rejected startup error', async () => {+ const cause = new Error('spawn failed')+ await expect(+ startServerEngine(+ {+ start: vi.fn().mockRejectedValue(cause),+ getState: () => EngineState.Failed,+ getLastError: () => null,+ },+ '/app/bin/aria2c'+ )+ ).rejects.toBe(cause)+ })+})diff --git a/src/server/start-engine.ts b/src/server/start-engine.tsnew file mode 100644index 00000000..ddbce929--- /dev/null+++ b/src/server/start-engine.ts@@ -0,0 +1,17 @@+import type { EngineSupervisor } from '@core/engine/engine-supervisor'+import { AppError, ErrorCode } from '@shared/errors'+import { EngineState } from '@shared/types/engine'++/** Server recovery requires RPC; start() can resolve in the Failed state. */+export async function startServerEngine(+ supervisor: Pick<EngineSupervisor, 'start' | 'getState' | 'getLastError'>,+ binaryPath: string+): Promise<void> {+ await supervisor.start(binaryPath)+ if (supervisor.getState() !== EngineState.Ready) {+ throw new AppError(+ ErrorCode.EngineStartFailed,+ supervisor.getLastError() ?? ErrorCode.EngineStartFailed+ )+ }+}