Fix large file download
This commit is contained in:
1 parent
aea75fff92
commit
ff7b84af02
4 files changed
+403
-146
No files matched your search
+228
-32
@@ -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);
|
||||
|
||||
Reference in new issue
Block a user