diff --git a/TODO.md b/TODO.md
index 0101bac..756ef87 100644
--- a/TODO.md
+++ b/TODO.md
@@ -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.
diff --git a/e2e.spec.ts b/e2e.spec.ts
index 3d03f53..a7a0be5 100644
--- a/e2e.spec.ts
+++ b/e2e.spec.ts
@@ -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 = { 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 Promise> = {
@@ -52,12 +56,28 @@ const MODES: Record Promise> = {
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) {
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,
+) {
+ 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);
diff --git a/src/App.vue b/src/App.vue
index 48ec591..65e181e 100644
--- a/src/App.vue
+++ b/src/App.vue
@@ -24,12 +24,10 @@ const receiveCode = ref('');
const check = ref();
const confirmSend = ref<() => void>();
-const download = ref<{ name: string; url: string }>();
const log = ref([]);
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() {