diff --git a/scripts/build-npm-launcher.test.ts b/scripts/build-npm-launcher.test.ts index 78cb8dab5c0cc..7403023461de3 100644 --- a/scripts/build-npm-launcher.test.ts +++ b/scripts/build-npm-launcher.test.ts @@ -12,12 +12,15 @@ import * as NodeChildProcess from "node:child_process"; import * as NodeCrypto from "node:crypto"; import * as NodeEvents from "node:events"; import * as NodeHttp from "node:http"; +import * as NodeStream from "node:stream"; import { npmReleaseDatabaseMigration } from "@t3tools/shared/cliRelease"; import { buildNpmLauncher } from "./build-npm-launcher.ts"; const VERSION = "1.2.3"; +const MAX_ARCHIVE_BYTES = 256 * 1024 * 1024; +const CURRENT_ARCHIVE_BYTES = 183 * 1024 * 1024; const decodeManifest = Schema.decodeEffect( Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)), ); @@ -74,6 +77,14 @@ exit 7 const archive = yield* fs.readFile(path.join(root, "release", archiveName)); let checksum = NodeCrypto.createHash("sha256").update(archive).digest("hex"); const requests: Array = []; + let archiveMode: "normal" | "current-size" | "declared-overflow" | "streamed-overflow" = "normal"; + function* archiveChunks(size: number) { + yield archive; + const padding = new Uint8Array(64 * 1024); + for (let remaining = size - archive.length; remaining > 0; remaining -= padding.length) { + yield padding.subarray(0, remaining); + } + } const failures: Array = []; const server = NodeHttp.createServer((request, response) => { requests.push(request.url ?? ""); @@ -83,7 +94,21 @@ exit 7 } else if (request.url === `/v${VERSION}/SHA256SUMS`) { response.end(`${checksum} ${archiveName}\n`); } else if (request.url === `/v${VERSION}/${archiveName}`) { - response.writeHead(200, { "Content-Length": archive.length }).end(archive); + const size = + archiveMode === "current-size" + ? CURRENT_ARCHIVE_BYTES + : archiveMode === "normal" + ? archive.length + : MAX_ARCHIVE_BYTES + 1; + response.writeHead(200, { + ...(archiveMode === "streamed-overflow" ? {} : { "Content-Length": size }), + Connection: "close", + }); + const body = NodeStream.Readable.from( + archiveChunks(archiveMode === "declared-overflow" ? archive.length : size), + ); + response.once("close", () => body.destroy()); + body.pipe(response); } else { response.writeHead(404).end(); } @@ -102,6 +127,16 @@ exit 7 return { baseUrl: `http://127.0.0.1:${address.port}`, requests, + setArchiveMode: (mode: typeof archiveMode) => { + archiveMode = mode; + const hash = NodeCrypto.createHash("sha256"); + for (const chunk of archiveChunks( + mode === "current-size" ? CURRENT_ARCHIVE_BYTES : archive.length, + )) { + hash.update(chunk); + } + checksum = hash.digest("hex"); + }, corruptChecksum: () => { checksum = "0".repeat(64); }, @@ -175,6 +210,34 @@ it.layer(NodeServices.layer)("build-npm-launcher", (it) => { [VERSION], ); + release.setArchiveMode("current-size"); + const currentSize = yield* run(process.execPath, [launcher, "--version"], { + cwd: root, + env: { + ...env, + T3CODE_HOME: path.join(root, "current-size-home"), + T3CODE_TEST_CALLS: undefined, + }, + }); + assert.equal(currentSize.exitCode, 0, currentSize.stderr); + assert.equal(currentSize.stdout.trim(), VERSION); + + for (const mode of ["declared-overflow", "streamed-overflow"] as const) { + release.setArchiveMode(mode); + const oversizedHome = path.join(root, mode); + const oversized = yield* run(process.execPath, [launcher, "--version"], { + cwd: root, + env: { ...env, T3CODE_HOME: oversizedHome }, + }); + assert.equal(oversized.exitCode, 1); + assert.include(oversized.stderr, `${MAX_ARCHIVE_BYTES}-byte limit`); + assert.deepStrictEqual( + yield* fs.readDirectory(path.join(oversizedHome, "runtime/versions")), + [], + ); + } + release.setArchiveMode("normal"); + const requestsAfterFirst = release.requests.length; const second = yield* run(process.execPath, [launcher, "--version"], { cwd: root, env }); assert.equal(second.exitCode, 0); diff --git a/scripts/npm-launcher/t3.mjs b/scripts/npm-launcher/t3.mjs index bcc16dfb8ad84..cc0b88c0a5402 100644 --- a/scripts/npm-launcher/t3.mjs +++ b/scripts/npm-launcher/t3.mjs @@ -10,6 +10,10 @@ const { version } = JSON.parse( fs.readFileSync(path.join(import.meta.dirname, "../package.json"), "utf8"), ); +// Leave room above current releases while bounding the compressed download. +// Extraction and other installer writes are separate costs. +const MAX_DOWNLOAD_BYTES = 256 * 1024 * 1024; + const SUPPORTED = ["darwin-arm64", "linux-arm64", "linux-x64", "win32-arm64", "win32-x64"]; function t3Home() { @@ -22,11 +26,11 @@ function t3Home() { const isTransient = (status) => status === 408 || status === 429 || status >= 500; -async function get(url) { +async function get(url, options) { let response; for (let attempt = 1; ; attempt++) { try { - response = await fetch(url); + response = await fetch(url, options); if (attempt === 4 || !isTransient(response.status)) break; await response.body?.cancel(); } catch (error) { @@ -44,18 +48,34 @@ async function get(url) { } async function download(url, file) { - const response = await get(url); - const total = Number(response.headers.get("content-length")) || 0; - const hash = crypto.createHash("sha256"); - const out = fs.openSync(file, "w"); + const controller = new AbortController(); const tty = process.stderr.isTTY; - let received = 0; - let shown = -1; + let out; + let identity; + let complete = false; try { + const response = await get(url, { signal: controller.signal }); + const total = Number(response.headers.get("content-length")) || 0; + if (total > MAX_DOWNLOAD_BYTES) { + throw new Error(`download exceeds ${MAX_DOWNLOAD_BYTES}-byte limit`); + } + const hash = crypto.createHash("sha256"); + out = fs.openSync(file, "wx"); + identity = fs.fstatSync(out, { bigint: true }); + let received = 0; + let shown = -1; for await (const chunk of response.body) { + if (chunk.byteLength > MAX_DOWNLOAD_BYTES - received) { + throw new Error(`download exceeds ${MAX_DOWNLOAD_BYTES}-byte limit`); + } + let offset = 0; + while (offset < chunk.byteLength) { + const written = fs.writeSync(out, chunk, offset, chunk.byteLength - offset); + if (written === 0) throw new Error(`could not write ${file}`); + offset += written; + received += written; + } hash.update(chunk); - fs.writeSync(out, chunk); - received += chunk.byteLength; // Redraw once per percent (or per MB without a length), not per chunk. const step = total ? Math.floor((received * 100) / total) : Math.floor(received / 1048576); if (tty && step !== shown) { @@ -66,11 +86,35 @@ async function download(url, file) { ); } } - } finally { + const digest = hash.digest("hex"); fs.closeSync(out); - if (tty) process.stderr.write("\r\x1b[2K"); + out = undefined; + complete = true; + return digest; + } finally { + if (!complete) controller.abort(); + try { + if (out !== undefined) fs.closeSync(out); + } finally { + if (identity && !complete) { + let current; + try { + current = fs.lstatSync(file, { bigint: true }); + } catch { + // Leave an unidentifiable path to the private staging owner. + } + if ( + current?.isFile() && + identity.ino > 0n && + current.dev === identity.dev && + current.ino === identity.ino + ) { + fs.rmSync(file, { force: true }); + } + } + if (tty) process.stderr.write("\r\x1b[2K"); + } } - return hash.digest("hex"); } async function install(dir, key) {