A full-featured download manager.
import { DownloadErrorCode } from '@shared/errors'
import type { DownloadTask, TaskInstance } from '@shared/types/task'
import {
makeDefaultBtExtension,
TaskInstancePhase,
TaskStatus,
TransitionPhase,
} from '@shared/types/task'
import { makeRetainedHttpTask } from '@test-utils/direct-retry'
import { makeLegacyHttpTask } from '@test-utils/legacy-http-activation'
import { makeDownloadTask } from '@test-utils/task'
import { describe, expect, it } from 'vitest'
import { mergeEngineTask } from './merge-engine-task'
it('keeps retained HTTP errors visible when the engine restores them paused', () => {
const task = makeRetainedHttpTask()
const engine = makeDownloadTask({
engineTaskId: task.engineTaskId,
status: TaskStatus.Paused,
})
expect(mergeEngineTask(task, engine)).toBe(task)
expect(
mergeEngineTask(task, { ...engine, status: TaskStatus.Downloading }).status
).toBe(TaskStatus.Downloading)
})
const baseTask = (over: Partial<DownloadTask> = {}): DownloadTask =>
makeDownloadTask({ id: 't1', engineTaskId: 'gid1', name: 'a', ...over })
function instance(status: TaskStatus, index = 0): TaskInstance {
return {
instanceId: `instance-${index}`,
motrixId: 't1',
gid: index === 0 ? 'gid1' : null,
phase: TaskInstancePhase.HttpDownload,
status,
progress: 25,
totalBytes: 100,
downloadedBytes: 25,
uploadedBytes: 0,
diskPath: '/downloads/a.motrix',
transitionPhase: TransitionPhase.Idle,
uris: ['https://example.com/a'],
uriHash: null,
payload: { fileIndex: index },
createdAt: 1000,
updatedAt: 2000,
}
}
describe('mergeEngineTask', () => {
it.each([TaskStatus.Downloading, TaskStatus.Seeding])(
'preserves private torrent metadata while polling %s metrics',
(status) => {
const existing = baseTask({
status,
bt: makeDefaultBtExtension({ isPrivate: true }),
})
const engine = baseTask({
status,
totalBytes: 100,
downloadedBytes: 50,
bt: makeDefaultBtExtension({ isPrivate: false, peers: 3 }),
})
const merged = mergeEngineTask(existing, engine)
expect(merged.bt).toMatchObject({ isPrivate: true, peers: 3 })
expect(merged.progress).toBe(0.5)
expect(existing.bt?.peers).toBe(0)
}
)
it('retains the original HTTP migration URI and status until completion is verified', () => {
const existing = makeLegacyHttpTask({ status: TaskStatus.Downloading })
const merged = mergeEngineTask(existing, {
...existing,
status: TaskStatus.Completed,
downloadedBytes: existing.totalBytes,
uris: ['https://redirect.example.com/temporary-signed-url'],
})
expect(merged.uris).toEqual(existing.uris)
expect(merged.instances[0].uris).toEqual(existing.instances[0].uris)
expect(merged.status).toBe(TaskStatus.Downloading)
expect(merged.instances[0].status).toBe(TaskStatus.Downloading)
expect(merged.finishedAt).toBeNull()
expect(merged.downloadedBytes).toBe(existing.totalBytes)
})
it.each([TaskStatus.Completed, TaskStatus.Error])(
'preserves imported %s history against a late paused replay',
(status) => {
const primary = instance(status)
primary.payload = { legacyImport: { version: 99 } }
const existing = baseTask({
status,
progress: 1,
finishedAt: 100,
instances: [primary],
})
const late = baseTask({
status: TaskStatus.Paused,
progress: 0,
finishedAt: null,
})
expect(mergeEngineTask(existing, late)).toBe(existing)
}
)
it.each([
['gid1', 25, 125],
['gid1', 30, 130],
['reseed-gid', 10, 135],
])(
'merges settled upload for %s without double counting',
(gid, upload, expected) => {
const primary = instance(TaskStatus.Error)
primary.payload.btFinalizeUpload = { gid: 'gid1', bytes: 25 }
const existing = baseTask({
uploadedBytesBaseline: 125,
transitionPhase: TransitionPhase.Renaming,
instances: [primary],
})
const merged = mergeEngineTask(
existing,
baseTask({ engineTaskId: gid, uploadedBytes: upload })
)
expect(merged.uploadedBytes).toBe(expected)
}
)
it.each(
[TaskStatus.Queued, TaskStatus.Downloading].flatMap((from) =>
[TaskStatus.Error, TaskStatus.Completed].flatMap((to) =>
[1, 2].map((count) => ({ from, to, count }))
)
)
)(
'synchronizes $count instances for $from → $to without changing the input',
({ from, to, count }) => {
const existing = baseTask({
status: from,
instances: Array.from({ length: count }, (_, i) => instance(from, i)),
})
const before = structuredClone(existing)
for (const entry of existing.instances) Object.freeze(entry)
Object.freeze(existing.instances)
Object.freeze(existing)
const merged = mergeEngineTask(existing, baseTask({ status: to }), 5000)
expect(merged.status).toBe(to)
expect(merged.instances).toEqual(
before.instances.map((entry) => ({ ...entry, status: to }))
)
expect(existing).toEqual(before)
expect(merged.instances).not.toBe(existing.instances)
}
)
it.each([TransitionPhase.Renaming, TransitionPhase.Reseeding])(
'keeps instance states while %s owns the terminal transition',
(phase) => {
const existing = baseTask({
status: TaskStatus.Finalizing,
transitionPhase: phase,
instances: [
{ ...instance(TaskStatus.Finalizing), transitionPhase: phase },
],
})
const merged = mergeEngineTask(
existing,
baseTask({ status: TaskStatus.Completed })
)
expect(merged.status).toBe(TaskStatus.Finalizing)
expect(merged.instances).toEqual(existing.instances)
}
)
it.each([TaskStatus.Paused, TaskStatus.Seeding])(
'leaves per-instance state intact for a nonterminal %s snapshot',
(status) => {
const existing = baseTask({
instances: [instance(TaskStatus.Downloading)],
})
expect(mergeEngineTask(existing, baseTask({ status })).instances).toEqual(
existing.instances
)
}
)
it('preserves existing totalBytes when engine reports zero', () => {
const existing = baseTask({
totalBytes: 1_000_000,
downloadedBytes: 500_000,
})
const engineTask = baseTask({ totalBytes: 0, downloadedBytes: 0 })
const merged = mergeEngineTask(existing, engineTask)
expect(merged.totalBytes).toBe(1_000_000)
expect(merged.downloadedBytes).toBe(500_000)
})
it('derives progress from protected mirror (paused engine reports zero)', () => {
// Regression: engine zero clobbered progress even when totalBytes /
// downloadedBytes survived nonZeroMerge. Restore showed correct
// progress, then the first poll cycle silently zeroed it.
const existing = baseTask({
totalBytes: 1000,
downloadedBytes: 250,
progress: 0.25,
})
const engineTask = baseTask({
totalBytes: 0,
downloadedBytes: 0,
progress: 0,
status: TaskStatus.Paused,
})
const merged = mergeEngineTask(existing, engineTask)
expect(merged.progress).toBe(0.25)
expect(merged.totalBytes).toBe(1000)
expect(merged.downloadedBytes).toBe(250)
})
it('updates progress when engine reports new non-zero downloadedBytes', () => {
const existing = baseTask({
totalBytes: 1000,
downloadedBytes: 250,
progress: 0.25,
})
const engineTask = baseTask({
totalBytes: 1000,
downloadedBytes: 500,
progress: 0.5,
})
const merged = mergeEngineTask(existing, engineTask)
expect(merged.progress).toBe(0.5)
})
it('returns 0 progress when totalBytes is unknown', () => {
const existing = baseTask({ totalBytes: 0, downloadedBytes: 0 })
const engineTask = baseTask({
totalBytes: 0,
downloadedBytes: 0,
status: TaskStatus.FetchingMetadata,
})
const merged = mergeEngineTask(existing, engineTask)
expect(merged.progress).toBe(0)
})
it('derives uploadedBytes as baseline + current gid uploadLength', () => {
const existing = baseTask({
uploadedBytesBaseline: 1_000_000,
uploadedBytes: 1_000_000,
})
const engineTask = baseTask({ uploadedBytes: 250_000 })
const merged = mergeEngineTask(existing, engineTask)
expect(merged.uploadedBytesBaseline).toBe(1_000_000)
expect(merged.uploadedBytes).toBe(1_250_000)
})
it('does not lose baseline when engine reports a small non-zero upload after gid swap', () => {
// Regression: a polling tick after finalize-reseed would write
// newGid.uploadLength (e.g. 1 MB) directly into uploadedBytes via
// nonZeroMerge, clobbering the prior session's accumulated bytes.
// baseline now insulates the accumulator.
const existing = baseTask({
uploadedBytesBaseline: 50_000_000,
uploadedBytes: 50_000_000,
})
const engineTask = baseTask({ uploadedBytes: 1_000_000 })
const merged = mergeEngineTask(existing, engineTask)
expect(merged.uploadedBytes).toBe(51_000_000)
expect(merged.uploadedBytesBaseline).toBe(50_000_000)
})
it('preserves baseline when engine reports zero uploadLength right after reseed', () => {
const existing = baseTask({
uploadedBytesBaseline: 50_000_000,
uploadedBytes: 50_000_000,
})
const engineTask = baseTask({ uploadedBytes: 0 })
const merged = mergeEngineTask(existing, engineTask)
expect(merged.uploadedBytes).toBe(50_000_000)
expect(merged.uploadedBytesBaseline).toBe(50_000_000)
})
it('keeps a restored terminal timestamp stable across same-state polling', () => {
const existing = baseTask({
status: TaskStatus.Completed,
finishedAt: 1234,
})
const engineTask = baseTask({
status: TaskStatus.Completed,
finishedAt: 9999,
})
expect(mergeEngineTask(existing, engineTask, 20_000).finishedAt).toBe(1234)
})
it('records incoming error details on a new terminal transition', () => {
const existing = baseTask({ status: TaskStatus.Downloading })
const engineTask = baseTask({
status: TaskStatus.Error,
finishedAt: null,
errorMessage: 'network failed',
errorCode: DownloadErrorCode.NetworkError,
})
expect(mergeEngineTask(existing, engineTask, 20_000)).toMatchObject({
status: TaskStatus.Error,
finishedAt: 20_000,
errorMessage: 'network failed',
errorCode: DownloadErrorCode.NetworkError,
})
})
it('clears terminal fields when a task returns to seeding', () => {
const existing = baseTask({
status: TaskStatus.Completed,
finishedAt: 1234,
errorMessage: 'old',
errorCode: DownloadErrorCode.Unknown,
})
const engineTask = baseTask({ status: TaskStatus.Seeding })
expect(mergeEngineTask(existing, engineTask, 20_000)).toMatchObject({
status: TaskStatus.Seeding,
finishedAt: null,
errorMessage: null,
errorCode: null,
})
})
it('does not resurrect a quarantined recovery error from a live engine row', () => {
const existing = baseTask({
status: TaskStatus.Error,
transitionPhase: TransitionPhase.Renaming,
finishedAt: 1234,
errorMessage:
'Recovery paused because temporary and final outputs both exist',
})
const engineTask = baseTask({ status: TaskStatus.Seeding })
expect(mergeEngineTask(existing, engineTask, 20_000)).toMatchObject({
status: TaskStatus.Error,
transitionPhase: TransitionPhase.Renaming,
finishedAt: 1234,
errorMessage:
'Recovery paused because temporary and final outputs both exist',
})
})
it('does not publish engine completion while HTTP finalize owns the rename', () => {
const existing = baseTask({
status: TaskStatus.Downloading,
transitionPhase: TransitionPhase.Renaming,
totalBytes: 1_000,
downloadedBytes: 900,
})
const engineTask = baseTask({
status: TaskStatus.Completed,
totalBytes: 1_000,
downloadedBytes: 1_000,
downloadSpeed: 0,
})
expect(mergeEngineTask(existing, engineTask, 20_000)).toMatchObject({
status: TaskStatus.Downloading,
transitionPhase: TransitionPhase.Renaming,
totalBytes: 1_000,
downloadedBytes: 1_000,
progress: 1,
downloadSpeed: 0,
finishedAt: null,
})
})
})
it('keeps share ratio cumulative when a new GID starts from zero upload', () => {
const existing = baseTask({
totalBytes: 1000,
uploadedBytesBaseline: 1500,
bt: makeDefaultBtExtension({ ratio: 1.5 }),
})
const incoming = baseTask({
totalBytes: 1000,
uploadedBytes: 200,
bt: makeDefaultBtExtension({ ratio: 0.2 }),
})
expect(mergeEngineTask(existing, incoming)).toMatchObject({
uploadedBytes: 1700,
bt: { ratio: 1.7 },
})
expect(existing.bt?.ratio).toBe(1.5)
expect(incoming.bt?.ratio).toBe(0.2)
})