Fix large file download

This commit is contained in:
Schluffe committed 2026-10-22 22:57:41 +02:00
1 parent aea75fff92
commit ff7b84af02
4 files changed
+403 -146

No files matched your search

+15 -48
View File
@@ -1,57 +1,24 @@
# TODO
## Next: service worker streaming download
## Ideas
Stream received bytes straight into the browser's download manager instead of staging them in OPFS.
Needs one new file (service workers can only be registered from a real same-origin script).
- Removes the OPFS staging copy, so the file no longer takes twice the disk space.
- Removes the OPFS quota cap (~10 GiB per site, 2000 MiB in Chromium incognito).
- Fixes "Opening another tab breaks existing downloads" below completely.
## Review findings
### [P2] Opening another tab breaks existing downloads
`clearStorage()` runs on startup and deletes every OPFS entry. OPFS is shared by all tabs of the
origin, so it also deletes the file behind another tab's not yet clicked download link.
- Real fix: Web Locks. Each tab holds a lock named after every file it received (released by the
browser when the tab closes or crashes). Cleanup only removes entries whose lock is free
(`navigator.locks.request(name, { ifAvailable: true }, ...)`).
- Fixed by the service worker download: no OPFS staging, nothing to clean up.
### [P2] Disk writes have no flow control
Chunks go data channel → main thread → worker message queue → disk without waiting for writes. If
storage is slower than the network (SD card, HDD, throttled background tab), queued buffers grow
without bound in RAM.
- Real fix: application level acknowledgements. The receiving side cannot pause a data channel,
so the worker reports its written offset, the receiver sends it to the sender over the data
channel, and the sender keeps at most a fixed window (e.g. 8 MiB) unacknowledged, on top of the
existing `bufferedAmount` check.
- Not fixed by the service worker: stream backpressure stops at the receiver, it still has to
reach the sender.
- Bonus: the acknowledged offset is the basis for resuming interrupted transfers.
### [P2] Storage failures don't stop the transfer
A write failure is only logged on the receiver. The sender keeps sending and reports "sent", which
only means "handed to the send buffer".
- Real fix:
1. Check `navigator.storage.estimate()` against the announced size before accepting, optionally
`navigator.storage.persist()` (raises Firefox's limit after a prompt).
2. Report errors to the sender (`{ error }` message or closing the channel), sender stops.
3. Receiver sends "done" only after the final flush, sender shows "delivered" only then.
- Partly fixed by the service worker: the quota failure goes away, but download errors and user
cancels still have to be reported to the sender.
- Points 2 and 3 share the receiver → sender control channel with the flow control fix, build them
together.
- Resume interrupted transfers: the receiver already reports how much the download manager has
read (`{ read }`), which is where a new connection could continue. The browser can't append to a
finished or failed download though, so a resume would have to start a new one.
## Open observations
- Firefox ignores an errored service worker response stream: when the sender vanishes, the receiver
logs "download failed: connection lost", but the download stays "in progress" until the user
cancels it. Closing the stream instead is worse, Firefox then reports the truncated file as
complete despite `Content-Length`. Chromium fails the download, but only once the connection
counts as failed (~16 s), because its data channel never fires `close` for a vanished peer.
- Firefox also saves a truncated file as complete when it stops the service worker in the middle of
a download (after 30 s without events). The receiver's pings (`KEEPALIVE`) prevent that, covered by
`large: firefox survives a 40 s stall`. A browser that stops it anyway would still never show
"download complete" or "delivered", only its download manager would be wrong.
- `large: firefox sends 2.5 GiB` hit the 5 minute timeout once (first run after the normal suite),
not reproduced in 3 runs since. The report was lost; the attached logs will show the cause if it
happens again.
+228 -32
View File
@@ -1,15 +1,19 @@
import { createHash, randomBytes } from 'node:crypto';
import { createReadStream } from 'node:fs';
import { open as openFile, writeFile } from 'node:fs/promises';
import { open as openFile, readFile, writeFile } from 'node:fs/promises';
import { chromium, expect, firefox, test, type Browser, type BrowserType, type Page } from '@playwright/test';
import { createServer, type ViteDevServer } from 'vite';
// Runs against the real public trackers and STUN servers from src/main.ts.
const BROWSERS: Record<string, BrowserType> = { chromium, firefox };
const SIZE = 5_000_000;
// Opt-in with LARGE=1: beyond the 2000 MiB Chromium stores in incognito-like contexts, and far
// beyond what the old in-memory receiver handled.
// Opt-in with LARGE=1: beyond what fits comfortably in RAM and beyond the 2000 MiB the old OPFS
// staging could store in incognito-like contexts.
const LARGE_SIZE = 2.5 * 2 ** 30;
// Big enough that the transfer still runs while a test updates sw.js, cancels or disconnects.
const RUNNING_SIZE = 100_000_000;
// WINDOW in src/main.ts.
const WINDOW = 8 * 2 ** 20;
// Each mode connects a sender page that already picked a file to a receiver page.
const MODES: Record<string, (sender: Page, receiver: Page) => Promise<void>> = {
@@ -52,12 +56,28 @@ const MODES: Record<string, (sender: Page, receiver: Page) => Promise<void>> = {
let server: ViteDevServer;
let url: string;
const browsers: Browser[] = [];
// Appended to sw.js, so raising it makes the browser see an update, like a deploy.
let swVersion = 0;
test.describe.configure({ mode: 'parallel' });
test.setTimeout(60_000);
test.beforeAll(async () => {
server = await createServer({ logLevel: 'silent', server: { port: 0 } });
server = await createServer({
logLevel: 'silent',
server: { port: 0 },
plugins: [
{
name: 'sw-version',
configureServer({ middlewares }) {
middlewares.use('/sw.js', async (_, res) => {
res.setHeader('Content-Type', 'text/javascript');
res.end(`${await readFile('public/sw.js', 'utf8')}\n// ${swVersion}\n`);
});
},
},
],
});
await server.listen();
url = server.resolvedUrls!.local[0]!;
});
@@ -67,11 +87,13 @@ test.afterAll(async () => {
await server.close();
});
async function open(name: string, sockets: string[]) {
// init runs in the page before the app.
async function open(name: string, sockets: string[], init?: () => void) {
const browser = await BROWSERS[name]!.launch();
browsers.push(browser);
const page = await (await browser.newContext()).newPage();
page.on('websocket', (ws) => sockets.push(ws.url()));
if (init) await page.addInitScript(init);
await page.goto(url);
return page;
}
@@ -84,39 +106,115 @@ async function hash(path: string) {
const log = (page: Page) => page.locator('#log').textContent();
// Sends the file at source and verifies security check, OPFS storage and the downloaded bytes.
async function transfer(mode: string, sender: Page, receiver: Page, source: string, size: number) {
// Init script for a receiver: holds back its { read } reports to the sender until release(), as if
// the download manager read nothing, and counts the bytes that arrive. It runs in the hidden frames
// too, only the app's own window counts.
function holdReads() {
if (window !== window.top) return;
const page = window as unknown as { received: number; release: () => void };
const held: [RTCDataChannel, string][] = [];
let holding = true;
page.received = 0;
const send = RTCDataChannel.prototype.send as (this: RTCDataChannel, data: unknown) => void;
RTCDataChannel.prototype.send = function (this: RTCDataChannel, data: unknown) {
if (holding && typeof data === 'string' && data.includes('"read"')) return void held.push([this, data]);
send.call(this, data);
};
// Registered before the app's handlers, so the chunks are counted before it transfers them away.
const PeerConnection = RTCPeerConnection;
window.RTCPeerConnection = class extends PeerConnection {
constructor(config?: RTCConfiguration) {
super(config);
this.addEventListener('datachannel', ({ channel }) =>
channel.addEventListener('message', ({ data }) => (page.received += data.byteLength ?? 0)),
);
}
};
page.release = () => {
holding = false;
for (const [channel, data] of held) send.call(channel, data);
};
}
const received = (page: Page) => page.evaluate(() => (window as unknown as { received: number }).received);
const release = (page: Page) => page.evaluate(() => (window as unknown as { release: () => void }).release());
// Changes sw.js and has the page's browser install it, as after a deploy while the tab is open.
async function updateWorker(page: Page) {
await expect
.poll(() => page.evaluate(async () => !!(await navigator.serviceWorker.getRegistration('download/'))?.active))
.toBe(true);
swVersion++;
await page.evaluate(async () => {
const registration = (await navigator.serviceWorker.getRegistration('download/'))!;
Object.assign(window, { previous: registration.active });
await registration.update();
});
}
// Whether the updated sw.js took over from the one that was active when updateWorker ran.
const updated = (page: Page) =>
page.evaluate(
async () =>
(await navigator.serviceWorker.getRegistration('download/'))!.active !==
(window as { previous?: ServiceWorker }).previous,
);
// Runs fn and attaches both logs to the report, also when it fails. A closed page has none left.
async function withLogs(sender: Page, receiver: Page, fn: () => Promise<void>) {
try {
await sender.setInputFiles('input[type=file]', source);
await MODES[mode]!(sender, receiver);
await fn();
} finally {
for (const [name, page] of [['sender', sender], ['receiver', receiver]] as const) {
await test.info().attach(`${name} log`, { body: (await log(page).catch(() => null)) ?? '' });
}
}
}
const check = (page: Page, side: string) => page.locator(`#check-${side}`).textContent();
await expect(sender.locator('#check-local')).toHaveText(/^([0-9A-F]{2} ){4}[0-9A-F]{2}$/, {
timeout: 45_000,
});
await expect(receiver.locator('#check-remote')).toHaveText((await check(sender, 'local'))!);
await expect(receiver.locator('#check-local')).toHaveText((await check(sender, 'remote'))!);
await expect(sender.locator('#log')).toContainText('waiting for the security check');
await expect(receiver.locator('#log')).not.toContainText('receiving');
await sender.click('#confirm');
await expect(receiver.locator('#download')).toBeVisible({ timeout: test.info().timeout });
// Connects, verifies the security check and confirms it. Returns the download, which starts on its
// own as soon as the file is announced, and the receiver log at that moment.
async function start(mode: string, sender: Page, receiver: Page, source: string) {
await sender.setInputFiles('input[type=file]', source);
await MODES[mode]!(sender, receiver);
// The receiver must have written the file to OPFS, not collected it in RAM.
const stored = await receiver.evaluate(async () => {
const sizes = [];
const root = await navigator.storage.getDirectory();
for await (const handle of root.values()) sizes.push((await (handle as FileSystemFileHandle).getFile()).size);
return sizes;
});
expect(stored).toEqual([size]);
const check = (page: Page, side: string) => page.locator(`#check-${side}`).textContent();
await expect(sender.locator('#check-local')).toHaveText(/^([0-9A-F]{2} ){4}[0-9A-F]{2}$/, {
timeout: 45_000,
});
await expect(receiver.locator('#check-remote')).toHaveText((await check(sender, 'local'))!);
await expect(receiver.locator('#check-local')).toHaveText((await check(sender, 'remote'))!);
await expect(sender.locator('#log')).toContainText('waiting for the security check');
await expect(receiver.locator('#log')).not.toContainText('receiving');
const started = receiver
.waitForEvent('download', { timeout: test.info().timeout })
.then(async (download) => ({ download, logAtStart: await log(receiver) }));
await sender.click('#confirm');
return started;
}
// Sends the file at source and verifies the downloaded bytes. during runs once the download started.
async function transfer(
mode: string,
sender: Page,
receiver: Page,
source: string,
size: number,
during?: () => Promise<void>,
) {
await withLogs(sender, receiver, async () => {
const { download, logAtStart } = await start(mode, sender, receiver, source);
// Streamed, not staged: 2.5 GiB can't arrive before the download manager takes over.
if (size === LARGE_SIZE) expect(logAtStart).not.toContain('received');
await during?.();
const [download] = await Promise.all([receiver.waitForEvent('download'), receiver.click('#download')]);
expect(download.suggestedFilename()).toBe(source.split('/').pop());
expect(await hash(await download.path())).toBe(await hash(source));
} finally {
await test.info().attach('sender log', { body: (await log(sender)) ?? '' });
await test.info().attach('receiver log', { body: (await log(receiver)) ?? '' });
}
await expect(receiver.locator('#log')).toContainText('download complete');
await expect(sender.locator('#log')).toContainText('delivered');
// Removed hidden pages release the service worker for updates.
await expect(receiver.locator('iframe')).toHaveCount(0);
});
}
for (const mode of Object.keys(MODES)) {
@@ -138,6 +236,104 @@ for (const mode of Object.keys(MODES)) {
}
for (const name of Object.keys(BROWSERS)) {
test(`update: ${name} receives after sw.js changed`, async () => {
const [sender, receiver] = await Promise.all([open(name, []), open(name, [])]);
const source = test.info().outputPath('payload.bin');
await writeFile(source, randomBytes(SIZE));
await updateWorker(receiver);
await expect.poll(() => updated(receiver)).toBe(true);
await transfer('offline', sender!, receiver!, source, SIZE);
});
test(`update: ${name} keeps a running download when sw.js changes`, async () => {
const [sender, receiver] = await Promise.all([open(name, []), open(name, [], holdReads)]);
const source = test.info().outputPath('payload.bin');
await writeFile(source, randomBytes(RUNNING_SIZE));
await transfer('offline', sender!, receiver!, source, RUNNING_SIZE, async () => {
// Paused at the window, so the transfer is guaranteed to still run during the update.
await expect.poll(() => received(receiver!)).toBe(WINDOW);
await updateWorker(receiver!);
// The update has to wait instead of replacing the worker that feeds the download.
await expect
.poll(() => receiver.evaluate(async () => !!(await navigator.serviceWorker.getRegistration('download/'))?.waiting))
.toBe(true);
expect(await updated(receiver!)).toBe(false);
await release(receiver!);
});
// Released once the download is complete, so the update takes over.
await expect.poll(() => updated(receiver)).toBe(true);
});
test(`cancel: ${name} stops receiving when the download is cancelled`, async () => {
const [sender, receiver] = await Promise.all([open(name, []), open(name, [])]);
const source = test.info().outputPath('payload.bin');
await writeFile(source, Buffer.alloc(RUNNING_SIZE));
await withLogs(sender!, receiver!, async () => {
const { download } = await start('offline', sender!, receiver!, source);
await download.cancel();
// A transfer that already finished would report no failure.
expect(await download.failure()).toBe('canceled');
await expect(receiver!.locator('#log')).toContainText('download cancelled');
await expect(receiver!.locator('iframe')).toHaveCount(0);
expect(await log(receiver!)).not.toContain('download complete');
// The window keeps the sender from having sent everything before it hears about the cancel.
await expect(sender!.locator('#log')).toContainText('receiver stopped: download cancelled');
expect(await log(sender!)).not.toMatch(/ sent$/m);
});
});
test(`flow: ${name} sender waits while the download manager reads nothing`, async () => {
const [sender, receiver] = await Promise.all([open(name, []), open(name, [], holdReads)]);
const source = test.info().outputPath('payload.bin');
await writeFile(source, randomBytes(RUNNING_SIZE));
await transfer('offline', sender!, receiver!, source, RUNNING_SIZE, async () => {
await expect.poll(() => received(receiver!)).toBe(WINDOW);
// Proving that nothing more comes needs a moment, the sender fills the window in milliseconds.
await receiver!.waitForTimeout(1000);
expect(await received(receiver!)).toBe(WINDOW);
await release(receiver!);
});
});
test(`disconnect: ${name} fails the download when the sender vanishes`, async () => {
const [sender, receiver] = await Promise.all([open(name, []), open(name, [])]);
const source = test.info().outputPath('payload.bin');
await writeFile(source, Buffer.alloc(RUNNING_SIZE));
await withLogs(sender!, receiver!, async () => {
const { download } = await start('offline', sender!, receiver!, source);
await sender!.context().close();
// Chromium only notices once the connection counts as failed, after ~16 s.
await expect(receiver!.locator('#log')).toContainText('download failed: connection lost', {
timeout: 30_000,
});
await expect(receiver!.locator('iframe')).toHaveCount(0);
// Firefox leaves the download stalled instead of failing it, see TODO.md.
if (name === 'chromium') expect(await download.failure()).not.toBeNull();
});
});
}
for (const name of Object.keys(BROWSERS)) {
test(`large: ${name} survives a 40 s stall`, async () => {
test.skip(!process.env.LARGE, 'set LARGE=1');
test.setTimeout(120_000);
const [sender, receiver] = await Promise.all([open(name, []), open(name, [], holdReads)]);
const source = test.info().outputPath('payload.bin');
await writeFile(source, randomBytes(RUNNING_SIZE));
await transfer('offline', sender!, receiver!, source, RUNNING_SIZE, async () => {
await expect.poll(() => received(receiver!)).toBe(WINDOW);
// Past the 30 s after which Firefox stops a service worker without events.
await receiver!.waitForTimeout(40_000);
await release(receiver!);
});
});
test(`large: ${name} sends 2.5 GiB`, async () => {
test.skip(!process.env.LARGE, 'set LARGE=1');
test.setTimeout(300_000);
-4
View File
@@ -24,12 +24,10 @@ const receiveCode = ref('');
const check = ref<Check>();
const confirmSend = ref<() => void>();
const download = ref<{ name: string; url: string }>();
const log = ref<string[]>([]);
const events: Events = {
log: (message) => log.value.push(`${new Date().toISOString().slice(11, 23)} ${message}`),
file: (name, url) => (download.value = { name, url }),
check: (result, confirm) => {
check.value = result;
confirmSend.value = confirm;
@@ -116,8 +114,6 @@ function onReceive() {
<button v-if="confirmSend" id="confirm" @click="onConfirm">Codes match, send</button>
</p>
<p v-if="download"><a id="download" :href="download.url" :download="download.name">{{ download.name }}</a></p>
<h2>Log</h2>
<pre id="log">{{ log.join('\n') }}</pre>
</main>
+160 -62
View File
@@ -16,6 +16,12 @@ export const settings = { stun: true };
const CHUNK_SIZE = 16 * 1024;
const MAX_BUFFERED = 1024 * 1024;
// The receiving side can't pause a data channel, so it reports how much the download manager has
// read and the sender keeps at most this much unread, else a slow disk fills the receiver's RAM.
const WINDOW = 8 * 1024 * 1024;
// Firefox stops a service worker after 30 s without events, also in the middle of a download, and
// then saves the truncated file as complete. A stalled transfer sends no chunks, so the receiver pings.
const KEEPALIVE = 10_000;
const ICE_GRACE = 300;
const ICE_TIMEOUT = 5000;
@@ -23,7 +29,6 @@ export type Check = { local: string; remote: string };
export type Events = {
log: (message: string) => void;
file: (name: string, url: string) => void;
// confirm is only passed on the sender side, the file is sent once it is called.
check: (check: Check, confirm?: () => void) => void;
};
@@ -95,93 +100,186 @@ function connected(pc: RTCPeerConnection, via: string, events: Events, confirm =
return new Promise<void>((resolve) => events.check(securityCheck(pc), confirm ? resolve : undefined));
}
async function sendFile(channel: RTCDataChannel, file: File, events: Events) {
// The receiver answers with { read } progress, { done } once the download manager read the last
// byte, or { error } when its download was cancelled or failed.
async function sendFile(pc: RTCPeerConnection, channel: RTCDataChannel, file: File, events: Events) {
if (channel.readyState !== 'open') {
await new Promise((resolve) => channel.addEventListener('open', resolve, { once: true }));
}
let read = 0;
let stopped = false;
// Every event the send loop can wait for calls this.
let wake = () => {};
const stop = (message: string) => {
if (stopped) return;
stopped = true;
events.log(message);
wake();
};
channel.onmessage = ({ data }) => {
const message = JSON.parse(data);
if (message.read) read = message.read;
if (message.done) {
events.log('delivered');
// Finished, a later close is no loss.
stopped = true;
}
if (message.error) stop(`receiver stopped: ${message.error}`);
wake();
};
// A vanished peer only closes the channel in Firefox, Chromium just fails the connection.
channel.addEventListener('close', () => stop('connection lost'));
pc.addEventListener('connectionstatechange', () => pc.connectionState === 'failed' && stop('connection lost'));
channel.addEventListener('bufferedamountlow', () => wake());
events.log(`sending ${file.name} (${file.size} bytes)`);
channel.bufferedAmountLowThreshold = MAX_BUFFERED / 2;
channel.send(JSON.stringify({ name: file.name, size: file.size }));
for (let offset = 0; offset < file.size; offset += CHUNK_SIZE) {
if (channel.bufferedAmount > MAX_BUFFERED) {
await new Promise((resolve) => channel.addEventListener('bufferedamountlow', resolve, { once: true }));
while (!stopped && (offset - read >= WINDOW || channel.bufferedAmount > MAX_BUFFERED)) {
await new Promise<void>((resolve) => (wake = resolve));
}
channel.send(await file.slice(offset, offset + CHUNK_SIZE).arrayBuffer());
const chunk = await file.slice(offset, offset + CHUNK_SIZE).arrayBuffer();
if (stopped) return;
channel.send(chunk);
}
events.log('sent');
}
// Runs in a dedicated worker, because OPFS sync access handles only exist there. It is started from
// a Blob URL so the app stays one script, which means it must not use anything outside its body.
function storageWorker() {
type SyncHandle = { write(data: ArrayBuffer, options: { at: number }): number; flush(): void; close(): void };
let handle: SyncHandle;
let offset = 0;
let queue = Promise.resolve();
// Received files are streamed into the browser's download manager by public/sw.js, so a file never
// has to fit in RAM or site storage. Its scope is only the download URLs, it sees no app requests.
const downloads = registerDownloads();
// Opening is async, the queue keeps chunks from overtaking it and each other.
self.onmessage = ({ data }: MessageEvent) => {
queue = queue
.then(async () => {
if (data.open) {
const root = await navigator.storage.getDirectory();
const file = await root.getFileHandle(data.open, { create: true });
handle = await (file as unknown as { createSyncAccessHandle(): Promise<SyncHandle> }).createSyncAccessHandle();
} else if (data.chunk) {
// Over quota some browsers write less instead of throwing.
const written = handle.write(data.chunk, { at: offset });
offset += written;
if (written !== data.chunk.byteLength) throw new Error(`storage full after ${offset} bytes`);
} else {
handle.flush();
handle.close();
self.postMessage({ done: true });
}
})
.catch((error) => {
self.postMessage({ error: String(error) });
self.close();
});
};
// Only the first visit has to wait here, updates are picked up per transfer by holdWorker.
async function registerDownloads() {
const registration = await navigator.serviceWorker.register('./sw.js', { scope: './download/' });
const pending = registration.installing ?? registration.waiting;
if (!registration.active && pending) {
await new Promise((resolve) =>
pending.addEventListener('statechange', () => ['activated', 'redundant'].includes(pending.state) && resolve(0)),
);
}
if (!registration.active) throw new Error('service worker did not activate');
}
const STORAGE_WORKER = URL.createObjectURL(new Blob([`(${storageWorker})()`], { type: 'text/javascript' }));
// Received files are written to OPFS instead of RAM and stay there until the next visit, because the
// download link reads from them.
async function clearStorage() {
const root = await navigator.storage.getDirectory();
for await (const name of root.keys()) await root.removeEntry(name);
// Awaited before receiving starts, so a browser without service workers fails before connecting.
function downloadsReady(events: Events) {
return downloads.catch((error) => {
events.log(`downloads unavailable: ${error}`);
throw error;
});
}
function receiveFile(channel: RTCDataChannel, events: Events) {
// A hidden page in the service worker's scope, open for the whole transfer. The worker controlling
// it gets the chunks, and while it is open the browser can't activate an updated sw.js and stop that
// worker in the middle of the download.
async function holdWorker() {
await downloads;
const frame = document.createElement('iframe');
frame.hidden = true;
frame.src = 'download/';
document.body.append(frame);
await new Promise((resolve) => frame.addEventListener('load', resolve, { once: true }));
const worker = frame.contentWindow!.navigator.serviceWorker.controller;
if (!worker) {
frame.remove();
throw new Error('service worker did not take over');
}
return { frame, worker };
}
function receiveFile(pc: RTCPeerConnection, channel: RTCDataChannel, events: Events) {
const id = crypto.randomUUID();
const frames: HTMLIFrameElement[] = [];
let meta: { name: string; size: number } | undefined;
let worker: Worker | undefined;
let received = 0;
let ended = false;
// Chunks can arrive before the worker is held, chaining every post on this keeps them in order.
let worker: Promise<ServiceWorker | void> = Promise.resolve();
const post = (message: object, transfer: Transferable[] = []) =>
worker.then((worker) => worker?.postMessage({ id, ...message }, transfer));
// To the sender, see sendFile.
const reply = (message: object) => channel.readyState === 'open' && channel.send(JSON.stringify(message));
async function stored() {
worker!.terminate();
const root = await navigator.storage.getDirectory();
const file = await (await root.getFileHandle(id)).getFile();
events.log('received');
events.file(meta!.name, URL.createObjectURL(file));
let keepalive: ReturnType<typeof setInterval> | undefined;
// Releases the worker, so a waiting update can take over.
function release() {
clearInterval(keepalive);
for (const frame of frames) frame.remove();
}
// The worker answers with failed, only then the frames go: removed earlier, Chromium keeps the
// download running instead of failing it.
function fail(reason: string) {
if (ended) return;
ended = true;
post({ error: reason });
reply({ error: reason });
events.log(`download failed: ${reason}`);
}
function startDownload() {
worker = holdWorker().then(({ frame, worker }) => {
frames.push(frame);
keepalive = setInterval(() => post({ ping: true }), KEEPALIVE);
// Only if something else than an update stops it, e.g. clearing the site data. It can't answer.
worker.addEventListener('statechange', () => {
if (worker.state !== 'redundant') return;
fail('service worker stopped');
release();
});
const { port1, port2 } = new MessageChannel();
port1.onmessage = ({ data }) => {
if (typeof data === 'number') return reply({ read: data });
if (data === 'ready' && !ended) {
// A navigation, not fetch(): only navigations hand the response to the download manager.
const download = document.createElement('iframe');
download.hidden = true;
download.src = `download/${id}`;
document.body.append(download);
frames.push(download);
return;
}
if (data === 'finished') {
events.log('download complete');
reply({ done: true });
}
if (data === 'cancelled' && !ended) {
events.log('download cancelled');
reply({ error: 'download cancelled' });
}
ended = true;
release();
};
worker.postMessage({ id, ...meta }, [port2]);
return worker;
}, (error) => fail(String(error)));
}
channel.binaryType = 'arraybuffer';
channel.onmessage = ({ data }) => {
if (ended) return;
if (typeof data === 'string') {
meta = JSON.parse(data);
events.log(`receiving ${meta!.name} (${meta!.size} bytes)`);
worker = new Worker(STORAGE_WORKER);
worker.onmessage = ({ data }) => (data.error ? events.log(`storage failed: ${data.error}`) : stored());
worker.postMessage({ open: id });
startDownload();
} else {
received += data.byteLength;
worker!.postMessage({ chunk: data }, [data]);
post({ chunk: data }, [data]);
}
if (meta && received === meta.size) {
post({ done: true });
events.log('received');
}
if (meta && received === meta.size) worker!.postMessage({ done: true });
};
// Fails the download instead of leaving it stalled (Firefox still does, see TODO.md). A vanished
// peer only closes the channel in Firefox, Chromium just fails the connection.
function lost() {
if (meta && received < meta.size) fail('connection lost');
}
channel.addEventListener('close', lost);
pc.addEventListener('connectionstatechange', () => pc.connectionState === 'failed' && lost());
}
// Manual signaling: the SDP itself is the code, exchanged over any channel the users trust.
@@ -191,7 +289,7 @@ export async function createOffer(file: File, events: Events) {
const channel = pc.createDataChannel('file');
channel.onopen = async () => {
await connected(pc, 'manual exchange', events, true);
sendFile(channel, file, events);
sendFile(pc, channel, file, events);
};
await pc.setLocalDescription();
await gatherIce(pc);
@@ -203,10 +301,11 @@ export async function createOffer(file: File, events: Events) {
}
export async function answerOffer(offer: string, events: Events) {
await downloadsReady(events);
const pc = createPeerConnection();
pc.ondatachannel = ({ channel }) => {
connected(pc, 'manual exchange', events);
receiveFile(channel, events);
receiveFile(pc, channel, events);
};
await pc.setRemoteDescription({ type: 'offer', sdp: atob(offer.trim()) });
await pc.setLocalDescription();
@@ -235,7 +334,7 @@ export async function sendViaTracker(file: File, events: Events) {
const peer = (pc = createPeerConnection());
peer.ondatachannel = async ({ channel }) => {
await connected(peer, url, events, true);
sendFile(channel, file, events);
sendFile(peer, channel, file, events);
};
await peer.setRemoteDescription(msg.offer);
await peer.setLocalDescription();
@@ -254,6 +353,7 @@ export async function sendViaTracker(file: File, events: Events) {
// Receiver sends one offer per tracker; the first data channel that opens wins.
export async function receiveViaTracker(code: string, events: Events) {
await downloadsReady(events);
const hash = await infoHash(code);
const peerId = randomBinary(20);
let isConnected = false;
@@ -267,7 +367,7 @@ export async function receiveViaTracker(code: string, events: Events) {
isConnected = true;
connected(pc, url, events);
};
receiveFile(channel, events);
receiveFile(pc, channel, events);
pc.setLocalDescription()
.then(() => gatherIce(pc))
@@ -293,7 +393,5 @@ export async function receiveViaTracker(code: string, events: Events) {
}
}
clearStorage();
// Mounted last: App.vue imports the core from this module.
createApp(App).mount('#app');