Speed up downloads by combining multiple network connections in parallel
TypeScript bandwidth-aggregationcross-platformdesktop-appdownloaderdownloadmanagerlinuxmacosmulticonnectionparallel-downloadswindows
fix: zero chunk speed on retry and stop duplicate speed tickers
Anmol Kapil8f33a22f7b50
diff --git a/src/main/download/downloadManager.ts b/src/main/download/downloadManager.tsindex 473ba04..ac337e7 100644--- a/src/main/download/downloadManager.ts+++ b/src/main/download/downloadManager.ts@@ -82,8 +82,22 @@ const SPEED_WINDOW_MS = 3000// Appends a sample and returns the average byte rate over SPEED_WINDOW_MS.function pushSpeedSample(samples: SpeedSample[], bytes: number, time: number): number {+ if (samples.length > 0 && time - samples[samples.length - 1].time > SPEED_WINDOW_MS) {+ samples.length = 0+ }samples.push({ bytes, time })+ return calculateCurrentSpeed(samples, time)+}++function calculateCurrentSpeed(samples: SpeedSample[] | undefined, time: number): number {+ if (!samples || samples.length === 0) return 0++ const latest = samples[samples.length - 1]+ if (time - latest.time > SPEED_WINDOW_MS) {+ return 0+ }+const cutoff = time - SPEED_WINDOW_MSwhile (samples.length > 2 && samples[1].time <= cutoff) {samples.shift()@@ -91,7 +105,7 @@ function pushSpeedSample(samples: SpeedSample[], bytes: number, time: number): nconst oldest = samples[0]const deltaSeconds = (time - oldest.time) / 1000- return deltaSeconds > 0 ? (bytes - oldest.bytes) / deltaSeconds : 0+ return deltaSeconds > 0 ? (latest.bytes - oldest.bytes) / deltaSeconds : 0}// Defensive cap independent of whatever the renderer sends — chunks are@@ -140,9 +154,13 @@ function trimBlockAttribution(block: BlockState, keepBytes: number, lastWriter?:}/** Total live speed across a download's worker connections (bounded by MAX_CHUNKS, unlike blocks). */-function sumChunkSpeeds(runtime: DownloadRuntime): number {+function sumChunkSpeeds(runtime: DownloadRuntime, now = Date.now()): number {let total = 0for (const chunk of runtime.state.chunks) {+ if (chunk.status === 'downloading') {+ const samples = runtime.speedSamplesByChunk.get(chunk.id)+ chunk.speedBytesPerSec = calculateCurrentSpeed(samples, now)+ }total += chunk.speedBytesPerSec}return total@@ -768,9 +786,28 @@ export class DownloadManager {)}- while (active.size > 0) {- const finishedId = await Promise.race(active.values())- active.delete(finishedId)+ const speedTicker = setInterval(() => {+ // Only the `finally` below stops this ticker — self-clearing on status here would let a+ // fast pause/resume start a second runChunksToCompletion (and ticker) while this one is+ // still winding down, and it would never see 'downloading' flip back on its own.+ if (runtime.state.status !== 'downloading') return+ const now = Date.now()+ const prevSpeed = runtime.state.speedBytesPerSec+ const newSpeed = sumChunkSpeeds(runtime, now)+ if (newSpeed !== prevSpeed) {+ runtime.state.speedBytesPerSec = newSpeed+ this.scheduleUpdate(runtime)+ }+ }, 500)+ speedTicker.unref()++ try {+ while (active.size > 0) {+ const finishedId = await Promise.race(active.values())+ active.delete(finishedId)+ }+ } finally {+ clearInterval(speedTicker)}if (runtime.state.status !== 'downloading') {@@ -1011,6 +1048,7 @@ export class DownloadManager {}chunk.status = 'retrying'+ chunk.speedBytesPerSec = 0this.scheduleUpdate(runtime)await delay(retryDelayMs(attempt), controller.signal).catch(() => {})const statusAfterDelay = runtime.state.status as DownloadStatusdiff --git a/src/renderer/src/components/NetworkRow.tsx b/src/renderer/src/components/NetworkRow.tsxindex a306587..84e4567 100644--- a/src/renderer/src/components/NetworkRow.tsx+++ b/src/renderer/src/components/NetworkRow.tsx@@ -142,7 +142,7 @@ export function NetworkRow({aria-expanded={expanded}className="h-auto cursor-pointer rounded-[4px] border-[0.5px] bg-card px-[7px] py-[3px] font-mono text-[10.5px] leading-none font-medium text-[var(--text-secondary)] aria-expanded:bg-secondary dark:bg-card">- {group.chunks.length} streams+ {group.chunks.length} {group.chunks.length === 1 ? 'stream' : 'streams'}<span aria-hidden className="text-[7.5px] opacity-75">{expanded ? '▲' : '▼'}</span>diff --git a/src/renderer/src/screens/IdleScreen.tsx b/src/renderer/src/screens/IdleScreen.tsxindex 151bee4..f73b4e9 100644--- a/src/renderer/src/screens/IdleScreen.tsx+++ b/src/renderer/src/screens/IdleScreen.tsx@@ -299,7 +299,7 @@ export function IdleScreen(): React.JSX.Element {<>{' · '}<span className="font-semibold text-foreground">{totalChunks}</span> total- parallel streams+ parallel {totalChunks === 1 ? 'stream' : 'streams'}</>)}</>diff --git a/src/renderer/src/utils/format.ts b/src/renderer/src/utils/format.tsindex 8af59eb..7b391f8 100644--- a/src/renderer/src/utils/format.ts+++ b/src/renderer/src/utils/format.ts@@ -4,8 +4,12 @@ const UNITS = ['B', 'KB', 'MB', 'GB', 'TB']export function formatBytes(bytes: number): string {if (!Number.isFinite(bytes) || bytes <= 0) return '0 B'- const exponent = Math.min(Math.floor(Math.log(bytes) / Math.log(1024)), UNITS.length - 1)- const value = bytes / 1024 ** exponent+ let exponent = Math.min(Math.floor(Math.log(bytes) / Math.log(1024)), UNITS.length - 1)+ let value = bytes / 1024 ** exponent+ if (exponent < UNITS.length - 1 && Number(value.toFixed(exponent === 0 ? 0 : 1)) >= 1024) {+ exponent += 1+ value = bytes / 1024 ** exponent+ }return `${value.toFixed(exponent === 0 ? 0 : 1)} ${UNITS[exponent]}`}@@ -17,11 +21,14 @@ export function formatEta(remainingBytes: number, bytesPerSec: number): string {if (bytesPerSec <= 0 || remainingBytes <= 0) return '—'const seconds = remainingBytes / bytesPerSecif (!Number.isFinite(seconds)) return '—'- if (seconds < 60) return `${Math.ceil(seconds)}s`- const minutes = Math.floor(seconds / 60)- if (minutes < 60) return `${minutes}m ${Math.round(seconds % 60)}s`- const hours = Math.floor(minutes / 60)- return `${hours}h ${minutes % 60}m`+ if (seconds < 60) return `${Math.max(1, Math.ceil(seconds))}s`+ const totalSec = Math.round(seconds)+ const mins = Math.floor(totalSec / 60)+ const secs = totalSec % 60+ if (mins < 60) return `${mins}m ${secs}s`+ const hrs = Math.floor(mins / 60)+ const remMins = mins % 60+ return `${hrs}h ${remMins}m`}export function formatPercent(bytesDownloaded: number, totalBytes: number): number {@@ -33,15 +40,16 @@ export function fileNameFromPath(path: string): string {return path.split(/[\\/]/).pop() ?? path}-/** Short uppercase file-type badge from a name's extension, e.g. "Xcode_16.2.xip" -> "XIP". */+/** Short uppercase file-type badge from a name's extension, e.g. "Xcode_16.2.xip" -> "XIP", "photo.jpeg" -> "JPEG". */export function fileExtensionBadge(fileName: string): string {const dotIndex = fileName.lastIndexOf('.')if (dotIndex <= 0 || dotIndex === fileName.length - 1) return 'FILE'- return fileName.slice(dotIndex + 1, dotIndex + 4).toUpperCase()+ return fileName.slice(dotIndex + 1, dotIndex + 5).toUpperCase()}/** m:ss, or h:mm:ss past an hour. */export function formatDuration(seconds: number): string {+ if (!Number.isFinite(seconds) || seconds <= 0) return '0:00'const total = Math.max(0, Math.round(seconds))const hrs = Math.floor(total / 3600)const mins = Math.floor((total % 3600) / 60)