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

-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');