"use strict"; // The launcher's own fetch of the published corpus (main.cjs serveFromAssetBase), with a watchdog. // // Khaos (F11 #117 #124, 2026-11-17): the client's main process reaches the CDN through this launcher (protocol.handle // "https"), and the launcher's fetch had no signal and no timeout. When the client gave up on a transfer, the // launcher's request stayed open, and it could hang without an answer forever, holding its connection. Now: // - a request that gets no response, or no next bytes, for its budget is stopped (`AssetStallError`): the client asks // for the budget of each transfer in the header `x-khaos-stall-ms` (its own watchdog, // recovered/src/electron/khaos/assetTransfer.js watchedFetch); this one waits 2 s more, so the client's comes first // and this one only frees the connection. Without the header, 60 s; // - the clock also runs while the client reads nothing: a response the client dropped is cancelled in that time; // - a failed fetch answers 504 (stalled) or 502 with the reason in `x-khaos-asset-error`, which the client puts in its // own error and logs (before, a bare 502). // No Electron here: main.cjs passes net.fetch (tests: launcher/asset-fetch.test.mjs in client/release). const STALL_HEADER = "x-khaos-stall-ms"; const ERROR_HEADER = "x-khaos-asset-error"; const DEFAULT_STALL_MS = 60000; const MARGIN_MS = 2000; class AssetStallError extends Error { constructor(phase, idleMs) { super(`no ${phase === "headers" ? "response" : "data"} from the CDN for ${Math.round(idleMs / 1000)} s`); this.name = "AssetStallError"; this.phase = phase; this.idleMs = idleMs; } } /** The budget of one request: the client's (header) plus the margin, else the default. */ function stallBudget(headers) { const text = headers && typeof headers.get === "function" ? headers.get(STALL_HEADER) : null; const asked = typeof text === "string" && /^[0-9]{4,6}$/.test(text) ? Number(text) : NaN; return asked >= 1000 && asked <= 600000 ? asked + MARGIN_MS : DEFAULT_STALL_MS; } /** A header-safe reason (printable ASCII, bounded). */ function reasonText(error) { return String((error && error.message) || error || "network error").replace(/[^\x20-\x7e]/g, " ").trim().slice(0, 300) || "network error"; } function unlessAborted(promise, signal) { if (signal.aborted) { promise.catch(() => {}); return Promise.reject(signal.reason); } return new Promise((resolve, reject) => { const stop = () => reject(signal.reason); signal.addEventListener("abort", stop, { once: true }); promise .then(resolve, reject) .finally(() => signal.removeEventListener("abort", stop)) .catch(() => {}); }); } /** * `fetch(target, init)` whose response must start within `idleMs` and whose body must never sit for `idleMs` without a * chunk passing to the reader (whoever is slow, the CDN or the reader). Rejects with an AssetStallError when no * response came; the body errors with one when it stalls. Either way the request is aborted (its connection freed). */ async function fetchWithWatchdog(fetch, target, init, idleMs, timers = { setTimeout, clearTimeout }) { const watchdog = new AbortController(); let timer = null; let reader = null; const disarm = () => { if (timer !== null) { timers.clearTimeout(timer); timer = null; } }; const arm = (phase) => { disarm(); timer = timers.setTimeout(() => { timer = null; const stall = new AssetStallError(phase, idleMs); watchdog.abort(stall); // nobody may be reading: the response body goes now (the fetch's abort alone may leave it open) if (reader) void reader.cancel(stall).catch(() => {}); }, idleMs); if (timer && typeof timer.unref === "function") timer.unref(); }; arm("headers"); const pending = Promise.resolve().then(() => fetch(target, { ...init, signal: watchdog.signal })); let upstream; try { upstream = await unlessAborted(pending, watchdog.signal); } catch (error) { disarm(); if (watchdog.signal.aborted) { void pending.then( (late) => late && late.body && late.body.cancel().catch(() => {}), () => {}, ); throw watchdog.signal.reason; } throw error; } if (!upstream.body) { disarm(); return upstream; } // from here the clock measures the time since the last chunk passed (or since the response came) reader = upstream.body.getReader(); arm("body"); const body = new ReadableStream( { async pull(destination) { let part; let failure = null; try { part = await unlessAborted(reader.read(), watchdog.signal); } catch (error) { failure = error; } // a read that ended because the watchdog cancelled the body is a failure, not the end of the file if (failure === null && watchdog.signal.aborted) failure = watchdog.signal.reason; if (failure !== null) { disarm(); const reason = watchdog.signal.aborted ? watchdog.signal.reason : failure; watchdog.abort(reason); void reader.cancel(reason).catch(() => {}); destination.error(reason); return; } if (part.done) { disarm(); destination.close(); return; } arm("body"); destination.enqueue(part.value); }, cancel(reason) { disarm(); watchdog.abort(reason); return reader.cancel(reason).catch(() => {}); }, }, { highWaterMark: 0 }, ); return new Response(body, { status: upstream.status, statusText: upstream.statusText, headers: upstream.headers }); } /** The answer to a request the launcher could not fetch: 504 when the CDN stalled, 502 otherwise, with the reason. */ function failedFetchResponse(error, headers) { const status = error && error.name === "AssetStallError" ? 504 : 502; return new Response(null, { status, headers: { ...headers, [ERROR_HEADER]: reasonText(error) } }); } module.exports = { AssetStallError, DEFAULT_STALL_MS, ERROR_HEADER, MARGIN_MS, STALL_HEADER, failedFetchResponse, fetchWithWatchdog, reasonText, stallBudget };