Skip to content

armgit / plexo

Public Imported from GitHub
0

Speed up downloads by combining multiple network connections in parallel

fix: second network gets no work when a file has fewer blocks than streams

Anmol Kapil3f3129b4e8e1
diff --git a/README.md b/README.md
index d355901..f98b39a 100644
--- a/README.md
+++ b/README.md
@@ -48,7 +48,7 @@ File ──→ Split ─────┼── Ethernet (IP: 10.0.0.12) ───
## Features
-- 🚀 **Multi-interface, multi-connection downloads** — splits files into fixed 8 MB chunks and fans them out across worker connections bound to specific network interfaces (up to 8 parallel connections per interface, 32 total).
+- 🚀 **Multi-interface, multi-connection downloads** — splits files into chunks of up to 8 MB and fans them out across worker connections bound to specific network interfaces (up to 8 parallel connections per interface, 32 total).
- 🔌 **Hardware interface detection** — queries Windows adapters via PowerShell `Get-NetAdapter` and macOS hardware ports via `networksetup` so Wi-Fi, Ethernet, tethered iPhones, and Thunderbolt bridges are labeled by real device names instead of bare BSD names (`en0`, `en6`).
- ⚖️ **Dynamic work-stealing queue** — chunks are leased from a shared pending queue; faster networks pull more chunks instead of waiting for slower connections to finish.
- ⏸️ **Resumable downloads** — cleanly pause or retry failed downloads without losing progress, preserving completed `part-N` chunk files on disk.
@@ -60,7 +60,7 @@ File ──→ Split ─────┼── Ethernet (IP: 10.0.0.12) ───
- 💾 **Upfront disk-space verification** — verifies free disk space before writing any temporary part files.
- 🔀 **Mid-download redirect handling** — transparently follows 3xx HTTP redirects (up to 5 hops) during probing and individual chunk downloads.
- 📊 **Real-time telemetry** — live throughput graphs, rolling-window ETA calculation, and per-connection transfer stats.
-- 🗺️ **Interactive progress grid** — 1:1 visual map of individual 8 MB chunks, color-coded by the network interface that fetched each chunk with accurate per-network byte attribution.
+- 🗺️ **Interactive progress grid** — 1:1 visual map of individual chunks, color-coded by the network interface that fetched each chunk with accurate per-network byte attribution.
- 🎨 **Network customization** — rename and recolor physical network interfaces with persistent user preferences.
- 🌓 **Light & Dark modes** — full theme support with an instant toggle between light and dark modes.
@@ -120,9 +120,9 @@ If you statically divide a 6 GB file into equal shares (e.g. 3 GB on Wi-Fi and 3
Instead, Plexo uses a **dynamic work-stealing queue**:
-1. The file is split into fixed **8 MB chunks**.
+1. The file is split into **chunks of up to 8 MB** (smaller for small files, so every network gets a share).
2. All chunks enter a centralized pending queue.
-3. A pool of worker connections (up to 8 per interface, 32 total) continuously lease the next chunk from the queue as soon as they become free.
+3. A pool of worker connections (up to 8 per interface, 32 total, never more than there are chunks to work on) continuously lease the next chunk from the queue as soon as they become free. Connections start interleaved across networks, so each network is served before any is served twice.
4. Faster interfaces finish chunks quicker and immediately pick up new ones; slower interfaces pull fewer chunks.
```text
@@ -169,7 +169,7 @@ cancelling or removing a download still deletes its partial data.
A **chunk** is the atomic unit of work in Plexo:
-- **Size**: Exactly 8 MB (with the final chunk sized to the remaining bytes).
+- **Size**: Up to 8 MB, with the final chunk sized to the remaining bytes. A file that is small next to its connection count gets smaller chunks (never under 1 MB) — at least two per connection — so a fast network can out-pull a slow one instead of being stuck behind it.
- **Transport**: One independent HTTP range request (`Range: bytes=START-END`).
- **Storage**: Written directly to an isolated `part-N` file in the download's temp directory.
- **Assignment**: Leased to an individual worker socket bound to a specific network interface.
@@ -180,9 +180,9 @@ Chunk #1 → Range: bytes=8388608-16777215 → part-1 (Ethernet)
Chunk #2 → Range: bytes=16777216-25165823 → part-2 (USB Tether)
```
-### Why 8 MB?
+### Why up to 8 MB?
-8 MB provides the optimal balance: large enough to minimize HTTP connection overhead and TLS handshakes, yet small enough to keep the work-stealing queue fluid, ensure fine-grained load balancing across mismatched connections, and keep retries cheap (a failed or stalled connection only discards at most 8 MB).
+8 MB provides the optimal balance: large enough to minimize HTTP connection overhead and TLS handshakes, yet small enough to keep the work-stealing queue fluid, ensure fine-grained load balancing across mismatched connections, and keep retries cheap (a failed or stalled connection only discards at most 8 MB). Below about 1 MB a request costs more in round trips than splitting saves, so that is the floor; a file that small is one chunk.
---
@@ -190,7 +190,7 @@ Chunk #2 → Range: bytes=16777216-25165823 → part-2 (USB Tether)
The progress grid provides a real-time visual map of the entire download.
-Every 8 MB chunk maps **1:1 to its own square** in the grid. Square #N directly corresponds to the **Chunk #N** badge shown in the active streams table, allowing you to cross-reference active connections with their location in the file.
+Every chunk maps **1:1 to its own square** in the grid. Square #N directly corresponds to the **Chunk #N** badge shown in the active streams table, allowing you to cross-reference active connections with their location in the file.
```text
Active Streams:
diff --git a/e2e/plan.spec.ts b/e2e/plan.spec.ts
new file mode 100644
index 0000000..346e96f
--- /dev/null
+++ b/e2e/plan.spec.ts
@@ -0,0 +1,153 @@
+import { expect, test } from '@playwright/test'
+import fc from 'fast-check'
+import {
+ DEFAULT_MAX_BLOCK_BYTES,
+ interleave,
+ MAX_BLOCKS,
+ MAX_STREAMS,
+ MAX_STREAMS_PER_NETWORK,
+ MIN_BLOCK_BYTES,
+ planDownload
+} from '../src/shared/plan'
+
+// I. How a download is cut into blocks and streams. Pure, so it's checked over the whole input
+// space instead of hand-picked sizes.
+
+const MIB = 1024 * 1024
+
+const splittable = fc.record({
+ totalBytes: fc.integer({ min: 1, max: 2 ** 42 }),
+ splittable: fc.constant(true),
+ networkCount: fc.integer({ min: 1, max: 6 }),
+ streamsPerNetwork: fc.integer({ min: 1, max: 12 })
+})
+
+test.describe('download plan', () => {
+ test('blocks tile the file exactly, within the size limits', () => {
+ fc.assert(
+ fc.property(splittable, (request) => {
+ const plan = planDownload(request)
+ const { blockSizeBytes, blockCount } = plan
+ expect(blockSizeBytes * blockCount).toBeGreaterThanOrEqual(request.totalBytes)
+ expect(blockSizeBytes * (blockCount - 1)).toBeLessThan(request.totalBytes)
+ expect(blockCount).toBeLessThanOrEqual(MAX_BLOCKS)
+ expect(blockSizeBytes).toBeGreaterThanOrEqual(Math.min(MIN_BLOCK_BYTES, request.totalBytes))
+ expect(blockSizeBytes).toBeLessThanOrEqual(
+ Math.max(DEFAULT_MAX_BLOCK_BYTES, Math.ceil(request.totalBytes / MAX_BLOCKS))
+ )
+ })
+ )
+ })
+
+ test('every network gets a stream, and never one with no block to claim', () => {
+ fc.assert(
+ fc.property(splittable, (request) => {
+ const { streamNetworks, blockCount } = planDownload(request)
+ const perNetwork = new Map<number, number>()
+ for (const network of streamNetworks) {
+ perNetwork.set(network, (perNetwork.get(network) ?? 0) + 1)
+ }
+ expect(perNetwork.size).toBe(request.networkCount)
+ expect(streamNetworks.length).toBeLessThanOrEqual(MAX_STREAMS)
+ for (const count of perNetwork.values()) {
+ expect(count).toBeLessThanOrEqual(request.streamsPerNetwork)
+ expect(count).toBeLessThanOrEqual(MAX_STREAMS_PER_NETWORK)
+ // Streams beyond the block count would idle — except the one each network keeps.
+ expect(count).toBeLessThanOrEqual(
+ Math.max(1, Math.ceil(blockCount / request.networkCount))
+ )
+ }
+ })
+ )
+ })
+
+ test('streams start fairly: no network is ever more than one ahead of another', () => {
+ fc.assert(
+ fc.property(splittable, (request) => {
+ const { streamNetworks } = planDownload(request)
+ const started = new Array<number>(request.networkCount).fill(0)
+ for (const network of streamNetworks) {
+ started[network]++
+ expect(Math.max(...started) - Math.min(...started)).toBeLessThanOrEqual(1)
+ }
+ })
+ )
+ })
+
+ test('the first stream on each network starts before any network gets a second', () => {
+ const plan = planDownload({
+ totalBytes: 50.8 * MIB,
+ splittable: true,
+ networkCount: 2,
+ streamsPerNetwork: 8
+ })
+ expect(plan.streamNetworks.slice(0, 4)).toEqual([0, 1, 0, 1])
+ })
+
+ test('a file too small to split is one block, with every network still listed', () => {
+ const plan = planDownload({
+ totalBytes: 300 * 1024,
+ splittable: true,
+ networkCount: 2,
+ streamsPerNetwork: 8
+ })
+ expect(plan.blockCount).toBe(1)
+ expect(plan.streamNetworks).toEqual([0, 1])
+ })
+
+ test('a large file keeps 8 MB blocks', () => {
+ const plan = planDownload({
+ totalBytes: 4 * 1024 * MIB,
+ splittable: true,
+ networkCount: 2,
+ streamsPerNetwork: 4
+ })
+ expect(plan.blockSizeBytes).toBe(DEFAULT_MAX_BLOCK_BYTES)
+ })
+
+ test('a mid-size file is cut so a fast network can out-pull a slow one', () => {
+ const plan = planDownload({
+ totalBytes: 12 * MIB,
+ splittable: true,
+ networkCount: 2,
+ streamsPerNetwork: 2
+ })
+ // Two 8 MB-ish blocks would pin a third of the file to whichever network is slower.
+ expect(plan.blockCount).toBeGreaterThanOrEqual(8)
+ })
+
+ test('the test knob for block size still applies', () => {
+ const plan = planDownload({
+ totalBytes: 40 * 64 * 1024,
+ splittable: true,
+ networkCount: 1,
+ streamsPerNetwork: 4,
+ maxBlockBytes: 64 * 1024
+ })
+ expect(plan.blockSizeBytes).toBe(64 * 1024)
+ expect(plan.blockCount).toBe(40)
+ })
+
+ test('no range support or unknown size: one stream on the first network', () => {
+ for (const request of [
+ { totalBytes: 10 * MIB, splittable: false },
+ { totalBytes: 0, splittable: true }
+ ]) {
+ const plan = planDownload({ ...request, networkCount: 3, streamsPerNetwork: 8 })
+ expect(plan.blockCount).toBe(1)
+ expect(plan.streamNetworks).toEqual([0])
+ }
+ })
+
+ test('interleave keeps each group in order', () => {
+ fc.assert(
+ fc.property(fc.array(fc.tuple(fc.integer({ min: 0, max: 3 }), fc.nat())), (items) => {
+ const out = interleave(items, ([group]) => group)
+ expect(out).toHaveLength(items.length)
+ for (const group of new Set(items.map(([g]) => g))) {
+ expect(out.filter(([g]) => g === group)).toEqual(items.filter(([g]) => g === group))
+ }
+ })
+ )
+ })
+})
diff --git a/e2e/sim.spec.ts b/e2e/sim.spec.ts
index a4d8ca0..2692e5a 100644
--- a/e2e/sim.spec.ts
+++ b/e2e/sim.spec.ts
@@ -42,6 +42,42 @@ test.describe('simulated downloads @smoke', () => {
expect(state.chunks.reduce((sum, chunk) => sum + chunk.retryCount, 0)).toBeGreaterThan(0)
})
+ test('a file with fewer blocks than streams still gives every network work', async ({
+ plexo,
+ dirs
+ }) => {
+ // 7 blocks against 16 requested streams: the first network's streams used to claim every
+ // block before the second network's had started, leaving it idle for the whole download.
+ const bytes = seededBytes(7 * BLOCK, 3)
+ const path = join(dirs.userData, '..', 'source-small.bin')
+ await writeFile(path, bytes)
+ await plexo.startSimulated(
+ {
+ sourceFilePath: path,
+ networks: [network('one'), network('two')],
+ chunkCount: 16,
+ connectionsPerNetwork: 8
+ },
+ sha256(bytes)
+ )
+ const state = await plexo.waitForStatus('completed')
+
+ const delivered = new Map<string, number>()
+ for (const chunk of state.chunks) delivered.set(chunk.interfaceId, 0)
+ for (const block of state.blocks ?? []) {
+ for (const [id, size] of Object.entries(block.bytesByInterface)) {
+ delivered.set(id, (delivered.get(id) ?? 0) + size)
+ }
+ }
+ expect(delivered.size, 'both networks are listed').toBe(2)
+ for (const [id, size] of delivered) expect(size, `${id} delivered bytes`).toBeGreaterThan(0)
+ // 16 streams were asked for, but a stream with no block to claim would only idle: each
+ // network gets as many as its share of the 7 blocks (4).
+ for (const id of delivered.keys()) {
+ expect(state.chunks.filter((chunk) => chunk.interfaceId === id)).toHaveLength(4)
+ }
+ })
+
test('a part that goes wrong during assembly fails the download and leaves nothing behind', async ({
plexo,
dirs
diff --git a/src/main/download/downloadManager.ts b/src/main/download/downloadManager.ts
index 8ea756b..5f71e28 100644
--- a/src/main/download/downloadManager.ts
+++ b/src/main/download/downloadManager.ts
@@ -26,6 +26,7 @@ import type {
StartDownloadRequest,
StartSimulatedDownloadRequest
} from '../../shared/types'
+import { interleave, planDownload } from '../../shared/plan'
import { downloadChunk, fetchRange, RemoteChangedError } from './chunkDownloader'
import { compareVersion, type FileVersion } from './fileVersion'
import { testKnobs } from '../testKnobs'
@@ -120,10 +121,6 @@ function calculateCurrentSpeed(samples: SpeedSample[] | undefined, time: number)
return (latest.bytes - oldest.bytes) / deltaSeconds
}
-// Defensive cap independent of whatever the renderer sends — chunks are
-// distributed round-robin across interfaces, not tied 1:1 to them anymore.
-const MAX_CHUNKS = 32
-
const MAX_CHUNK_RETRIES = 5
const RETRY_BASE_DELAY_MS = testKnobs.retryBaseDelayMs
const RETRY_MAX_DELAY_MS = 15_000
@@ -509,98 +506,63 @@ export class DownloadManager {
throw error
}
- const connectionsPerNetwork = Math.max(
- 1,
- Math.min(
- 8,
+ const plan = planDownload({
+ totalBytes: requestPayload.totalBytes,
+ splittable: requestPayload.supportsRanges,
+ networkCount: interfaces.length,
+ streamsPerNetwork:
requestPayload.connectionsPerNetwork ??
- Math.max(1, Math.round(requestPayload.chunkCount / interfaces.length))
- )
- )
- const canSplit = requestPayload.supportsRanges && requestPayload.totalBytes > 0
-
- // Block size stays fixed regardless of file size, so work granularity — and
- // therefore resumability and load-balancing across workers — doesn't degrade
- // on huge files. MAX_REAL_BLOCKS is only a safety valve for pathologically
- // large files (multi-TB) so the block array doesn't blow up; it grows the
- // block size instead of the count once a file is big enough to hit it.
- // The UI caps how many cells it renders separately (see BlockGrid), by
- // bucketing these blocks rather than by shrinking their count here.
- const BASE_BLOCK_BYTES = testKnobs.blockBytes // 8 MB outside tests
- const MAX_REAL_BLOCKS = 4096
-
- let blockSizeBytes = 0
- const blocks: BlockState[] = []
+ Math.round(requestPayload.chunkCount / interfaces.length),
+ maxBlockBytes: testKnobs.blockBytes // 8 MB outside tests
+ })
- if (canSplit) {
- blockSizeBytes = Math.max(
- BASE_BLOCK_BYTES,
- Math.ceil(requestPayload.totalBytes / MAX_REAL_BLOCKS)
- )
- let offset = 0
- let bIdx = 0
- while (offset < requestPayload.totalBytes) {
- const bEnd = Math.min(offset + blockSizeBytes - 1, requestPayload.totalBytes - 1)
+ // The UI caps how many cells it renders separately (see BlockGrid), by bucketing these
+ // blocks rather than by shrinking their count here.
+ const blocks: BlockState[] = []
+ if (requestPayload.totalBytes > 0) {
+ const { blockSizeBytes } = plan
+ for (
+ let rangeStart = 0;
+ rangeStart < requestPayload.totalBytes;
+ rangeStart += blockSizeBytes
+ ) {
blocks.push({
- index: bIdx++,
- rangeStart: offset,
- rangeEnd: bEnd,
+ index: blocks.length,
+ rangeStart,
+ rangeEnd: Math.min(rangeStart + blockSizeBytes, requestPayload.totalBytes) - 1,
status: 'pending',
bytesDownloaded: 0,
bytesByInterface: {}
})
- offset = bEnd + 1
}
} else {
- blockSizeBytes = requestPayload.totalBytes > 0 ? requestPayload.totalBytes : 0
+ // Size unknown: one open-ended block, to end of file.
blocks.push({
index: 0,
rangeStart: 0,
- rangeEnd: requestPayload.totalBytes > 0 ? requestPayload.totalBytes - 1 : null,
+ rangeEnd: null,
status: 'pending',
bytesDownloaded: 0,
bytesByInterface: {}
})
}
- const chunks: ChunkState[] = []
- const activeInterfaces: NetworkInterfaceInfo[] = []
- let workerIdCounter = 0
-
- if (canSplit) {
- for (const iface of interfaces) {
- for (let connIdx = 0; connIdx < connectionsPerNetwork; connIdx++) {
- if (chunks.length >= MAX_CHUNKS) break
- activeInterfaces.push(iface)
- chunks.push({
- id: workerIdCounter++,
- interfaceId: iface.id,
- interfaceLabel: iface.displayName,
- interfaceKind: iface.kind,
- rangeStart: 0,
- rangeEnd: null,
- bytesDownloaded: 0,
- speedBytesPerSec: 0,
- status: 'pending',
- retryCount: 0
- })
- }
- }
- } else {
- activeInterfaces.push(interfaces[0])
- chunks.push({
- id: 0,
- interfaceId: interfaces[0].id,
- interfaceLabel: interfaces[0].displayName,
- interfaceKind: interfaces[0].kind,
+ const chunks: ChunkState[] = plan.streamNetworks.map((networkIndex, id) => {
+ const iface = interfaces[networkIndex]
+ return {
+ id,
+ interfaceId: iface.id,
+ interfaceLabel: iface.displayName,
+ interfaceKind: iface.kind,
rangeStart: 0,
- rangeEnd: requestPayload.totalBytes > 0 ? requestPayload.totalBytes - 1 : null,
+ rangeEnd: null,
bytesDownloaded: 0,
speedBytesPerSec: 0,
status: 'pending',
retryCount: 0
- })
- }
+ }
+ })
+ const activeInterfaces = [...new Set(plan.streamNetworks)].map((index) => interfaces[index])
const state: DownloadState = {
id,
@@ -614,7 +576,7 @@ export class DownloadManager {
chunks,
blocks,
totalBlocks: blocks.length,
- blockSizeBytes,
+ blockSizeBytes: plan.blockSizeBytes,
startedAt: Date.now()
}
@@ -753,8 +715,14 @@ export class DownloadManager {
}
this.pushUpdate(runtime)
+ // Streams start in the order given, and each claims a block on the spot: interleaved, so a
+ // paused download saved before that was the rule can't hand every block to one network.
const pending = runtime.state.chunks.filter((chunk) => chunk.status !== 'completed')
- void this.runChunksToCompletion(runtime, pending.length > 0 ? pending : runtime.state.chunks)
+ const toRun = pending.length > 0 ? pending : runtime.state.chunks
+ void this.runChunksToCompletion(
+ runtime,
+ interleave(toRun, (chunk) => chunk.interfaceId)
+ )
}
cancel(id: string): void {
diff --git a/src/renderer/src/screens/IdleScreen.tsx b/src/renderer/src/screens/IdleScreen.tsx
index f73b4e9..4835443 100644
--- a/src/renderer/src/screens/IdleScreen.tsx
+++ b/src/renderer/src/screens/IdleScreen.tsx
@@ -1,3 +1,4 @@
+import { planDownload } from '@shared/plan'
import type { ProbeResult } from '@shared/types'
import { cn } from 'cn'
import { AlertTriangle, ClipboardPaste } from 'lucide-react'
@@ -94,7 +95,17 @@ export function IdleScreen(): React.JSX.Element {
const selectedInterfaceIds = isSingleStreamOnly ? enabledIds.slice(0, 1) : enabledIds
const connectionsPerNetwork = isSingleStreamOnly ? 1 : chunksPerNetwork
- const totalChunks = isSingleStreamOnly ? 1 : selectedInterfaceIds.length * chunksPerNetwork
+ // A small file gets fewer streams than asked for — one with no block to claim would only
+ // idle — so once the file's size is known the count comes from the same plan the download
+ // will use.
+ const totalChunks = ready
+ ? planDownload({
+ totalBytes: ready.totalBytes ?? 0,
+ splittable: multiChunkAllowed,
+ networkCount: selectedInterfaceIds.length,
+ streamsPerNetwork: chunksPerNetwork
+ }).streamNetworks.length
+ : selectedInterfaceIds.length * chunksPerNetwork
const startLabel = starting ? 'Starting…' : probe.status === 'probing' ? 'Checking…' : 'Start'
const canStart =
probe.status === 'ready' &&
diff --git a/src/shared/plan.ts b/src/shared/plan.ts
new file mode 100644
index 0000000..230c305
--- /dev/null
+++ b/src/shared/plan.ts
@@ -0,0 +1,103 @@
+// How a download is cut into blocks and how many streams work on them. Pure, and shared, so the
+// main process (which does the cutting) and the start screen (which previews the stream count)
+// cannot disagree about it.
+
+const MIB = 1024 * 1024
+
+/** The largest block, for any file the block-count cap doesn't force bigger. */
+export const DEFAULT_MAX_BLOCK_BYTES = 8 * MIB
+
+/** No block is planned smaller than this: each block is its own request, and below about a
+ * megabyte the round trips cost more than splitting the file saves. */
+export const MIN_BLOCK_BYTES = MIB
+
+/** Only a safety valve for multi-terabyte files, so the block list stays a sane size. Past it,
+ * blocks grow instead of multiplying. */
+export const MAX_BLOCKS = 4096
+
+export const MAX_STREAMS_PER_NETWORK = 8
+export const MAX_STREAMS = 32
+
+/** Blocks planned per stream, at least. Streams pull blocks as they free up, so a fast network
+ * takes more of them — but only if there are more blocks than streams to begin with. With one
+ * block each, a stream on a slow network would hold its block while the rest sat idle. */
+const BLOCKS_PER_STREAM = 2
+/** …and never fewer than this many per network, whatever the stream count. */
+const MIN_BLOCKS_PER_NETWORK = 4
+
+export interface DownloadPlan {
+ /** Bytes per block; the last block holds the remainder. */
+ blockSizeBytes: number
+ blockCount: number
+ /** The network (an index into the selected networks) each stream runs on, in the order the
+ * streams start — interleaved, so every network is served before any is served twice. */
+ streamNetworks: number[]
+}
+
+export interface PlanRequest {
+ /** 0 when unknown. */
+ totalBytes: number
+ /** false when the server can't serve byte ranges. */
+ splittable: boolean
+ networkCount: number
+ /** Streams wanted on each network. */
+ streamsPerNetwork: number
+ maxBlockBytes?: number
+}
+
+/** Lays `items` out one from each group in turn (a, b, a, b, …), keeping each group's own
+ * order. Groups are visited in order of first appearance. */
+export function interleave<T>(items: readonly T[], groupOf: (item: T) => unknown): T[] {
+ const lanes = new Map<unknown, T[]>()
+ for (const item of items) {
+ const lane = lanes.get(groupOf(item))
+ if (lane) lane.push(item)
+ else lanes.set(groupOf(item), [item])
+ }
+
+ const out: T[] = []
+ for (let round = 0; out.length < items.length; round++) {
+ for (const lane of lanes.values()) {
+ if (round < lane.length) out.push(lane[round])
+ }
+ }
+ return out
+}
+
+const clamp = (value: number, min: number, max: number): number =>
+ Math.min(Math.max(value, min), max)
+
+export function planDownload(request: PlanRequest): DownloadPlan {
+ const { totalBytes, splittable } = request
+ const networkCount = Math.max(1, Math.floor(request.networkCount))
+
+ // One request has to carry the whole file, so one stream, on the first network.
+ if (!splittable || totalBytes <= 0) {
+ return { blockSizeBytes: Math.max(totalBytes, 0), blockCount: 1, streamNetworks: [0] }
+ }
+
+ const maxBlockBytes = request.maxBlockBytes ?? DEFAULT_MAX_BLOCK_BYTES
+ const requested = clamp(Math.floor(request.streamsPerNetwork), 1, MAX_STREAMS_PER_NETWORK)
+
+ const targetBlocks =
+ networkCount * Math.max(MIN_BLOCKS_PER_NETWORK, requested * BLOCKS_PER_STREAM)
+ const blockSizeBytes = Math.max(
+ clamp(
+ Math.ceil(totalBytes / targetBlocks),
+ Math.min(MIN_BLOCK_BYTES, maxBlockBytes),
+ maxBlockBytes
+ ),
+ Math.ceil(totalBytes / MAX_BLOCKS)
+ )
+ const blockCount = Math.ceil(totalBytes / blockSizeBytes)
+
+ // A stream with no block to claim would only sit idle, so a small file gets fewer of them —
+ // but every network keeps one, so it still shows up and can take over a block that fails.
+ const perNetwork = Math.max(1, Math.min(requested, Math.ceil(blockCount / networkCount)))
+ const streamNetworks = interleave(
+ Array.from({ length: networkCount * perNetwork }, (_, i) => Math.floor(i / perNetwork)),
+ (network) => network
+ ).slice(0, MAX_STREAMS)
+
+ return { blockSizeBytes, blockCount, streamNetworks }
+}