Merge remote-tracking branch 'origin/main' into fix/expected-errors-info

This commit is contained in:
Thomas Durieux committed 2026-11-29 11:44:26 +00:00
commit 5509b30b1b
8 files changed
+248 -14

No files matched your search

+108
View File
@@ -0,0 +1,108 @@
const { strict: assert } = require("node:assert");
const { promises: fs } = require("node:fs");
const http = require("node:http");
const { tmpdir } = require("node:os");
const { join } = require("node:path");
const { PassThrough, Readable, Writable } = require("node:stream");
const { pipeline } = require("node:stream/promises");
const { setTimeout } = require("node:timers");
const { createHash } = require("node:crypto");
const express = require("express");
require("ts-node/register/transpile-only");
const config = require("../src/config").default;
const { sharedBlobCache, closeBlobCaches } = require("../src/core/blob-cache");
const { watchClientClose, isResponseCancellation } = require("../src/core/response-cancellation");
const streamer = require("../src/streamer/route").default;
const body = Buffer.alloc(8 * 1024 * 1024, 7);
const sha = createHash("sha1").update(`blob ${body.length}\0`).update(body).digest("hex");
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
/** Collect the structured records a test run writes to stdout. */
function captureLogs() {
const records = [];
const write = process.stdout.write;
process.stdout.write = function (chunk, ...rest) {
for (const line of String(chunk).split("\n")) {
try { const record = JSON.parse(line); if (record && record.severity) { records.push(record); continue; } } catch { /* not a record */ }
if (line) write.call(process.stdout, line + "\n");
}
const callback = rest.find((arg) => typeof arg === "function");
if (callback) callback();
return true;
};
return { records, restore: () => { process.stdout.write = write; } };
}
describe("cached response cancellation", function () {
this.timeout(15000);
let root, old;
beforeEach(async () => {
old = { ...config }; closeBlobCaches();
root = await fs.mkdtemp(join(tmpdir(), "cached-cancel-"));
Object.assign(config, { STORAGE: "filesystem", FOLDER: root, SHARED_CACHE_ENABLED: true,
SHARED_CACHE_PATH: join(root, "cache"), SHARED_CACHE_BYTES: 64 * 1024 ** 2,
SHARED_CACHE_RESULT_BYTES: 32 * 1024 ** 2, SHARED_CACHE_MAX_FILE_BYTES: 16 * 1024 ** 2,
SHARED_CACHE_FREE_BYTES: 0, BILLING_ENABLED: false });
});
afterEach(async () => {
closeBlobCaches(); Object.assign(config, old);
await fs.rm(root, { recursive: true, force: true });
});
it("does not log a client that stops a cached download as a server error", async () => {
const seeded = await sharedBlobCache().getOrFill(`git-${sha}`, async () => Readable.from([body]), async () => `git-${sha}`, body.length);
for await (const chunk of seeded) void chunk;
const app = express(); app.use(express.json()); app.use("/api", streamer);
const server = await new Promise((resolve) => { const s = app.listen(0, "127.0.0.1", () => resolve(s)); });
const logs = captureLogs();
try {
await new Promise((resolve) => {
const req = http.request({ host: "127.0.0.1", port: server.address().port, path: "/api", method: "POST",
headers: { "content-type": "application/json" } }, (res) => {
res.once("data", () => req.destroy());
res.on("error", () => undefined);
res.on("close", resolve);
});
req.on("error", resolve);
req.end(JSON.stringify({ token: "", repoFullName: "owner/repo", repoId: "anon", sha, size: body.length,
filePath: "video.bin", anonymizerOptions: { terms: [], filePath: "video.bin" } }));
});
await wait(300);
} finally {
logs.restore();
server.closeAllConnections();
await new Promise((resolve) => server.close(resolve));
}
const faults = logs.records.filter((record) => record.severity === "error" || record.severity === "warn");
assert.deepEqual(faults, []);
});
it("names a client disconnect but keeps a source that ended early as a failure", async () => {
const attribute = async (closeFirst) => {
const source = new PassThrough();
// The "late" response never acknowledges its write, like a slow socket.
const response = new Writable({ write(_chunk, _encoding, done) { if (closeFirst !== "late") done(); } });
const clientClosed = watchClientClose(response, source);
const piping = pipeline(source, response);
source.write("partial");
if (closeFirst === "late") source.end();
await wait(5);
if (closeFirst !== "source") response.destroy();
else source.destroy();
const error = await piping.then(() => undefined, (failure) => failure);
return { error, clientClosed: clientClosed(), cancellation: isResponseCancellation(error, response) };
};
const client = await attribute("client");
assert.equal(client.error.code, "ERR_STREAM_PREMATURE_CLOSE");
assert.equal(client.clientClosed, true);
// The source was fully read but the response had not flushed yet.
const late = await attribute("late");
assert.equal(late.error.code, "ERR_STREAM_PREMATURE_CLOSE");
assert.equal(late.clientClosed, true);
const source = await attribute("source");
assert.equal(source.error.code, "ERR_STREAM_PREMATURE_CLOSE");
assert.equal(source.clientClosed, false);
assert.equal(source.cancellation, false);
});
});
+66
View File
@@ -0,0 +1,66 @@
const { strict: assert } = require("node:assert");
const fs = require("node:fs");
const path = require("node:path");
const ts = require("typescript");
require("ts-node/register/transpile-only");
const { logRecord, LOG_ERROR_CODES } = require("../src/core/log-record");
const { serializeError } = require("../src/core/logger");
const { billingError } = require("../src/core/billing/config");
const { consumeFlow } = require("../src/server/routes/github-app");
const root = path.join(__dirname, "..");
const vrl = fs.readFileSync(path.join(root, "deploy/logging/sanitize.vrl"), "utf8");
const collectorCodes = new Set(JSON.parse(vrl.match(/if includes\((\[.*?\]), record\.errorCode\)/)[1]));
// Independent of the generator: string codes passed straight to the error
// factories anywhere under src/.
function thrownCodes() {
const codes = new Map();
const literals = (node, file) => {
if (!node) return;
if (ts.isStringLiteralLike(node)) { if (/^[A-Za-z][A-Za-z0-9]*(?:_[A-Za-z0-9]+)+$/.test(node.text)) codes.set(node.text, file); }
else if (ts.isConditionalExpression(node)) { literals(node.whenTrue, file); literals(node.whenFalse, file); }
else if (ts.isParenthesizedExpression(node)) literals(node.expression, file);
};
const walk = (dir) => {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const file = path.join(dir, entry.name);
if (entry.isDirectory()) { walk(file); continue; }
if (!file.endsWith(".ts") || file.endsWith(".d.ts")) continue;
const source = ts.createSourceFile(file, fs.readFileSync(file, "utf8"), ts.ScriptTarget.Latest, true);
(function visit(node) {
if ((ts.isNewExpression(node) || ts.isCallExpression(node)) && ts.isIdentifier(node.expression) &&
["AnonymousError", "billingError", "appError"].includes(node.expression.text) && node.arguments?.length) {
literals(node.arguments[0], path.relative(root, file));
}
ts.forEachChild(node, visit);
})(source);
}
};
walk(path.join(root, "src"));
return codes;
}
describe("thrown error codes reach the logs", () => {
it("keeps the billing expiration and GitHub App state codes", () => {
const billing = logRecord("warn", "route", [serializeError(billingError("invalid_billing_expiration"))]);
assert.equal(billing.errorCode, "invalid_billing_expiration");
let state;
try { consumeFlow(undefined, "state"); } catch (error) { state = error; }
assert.equal(state.message, "invalid_auth_state");
assert.equal(logRecord("warn", "route", [serializeError(state)]).errorCode, "invalid_auth_state");
for (const code of ["invalid_billing_expiration", "invalid_auth_state", "streamer_unreachable"]) {
assert.ok(collectorCodes.has(code), `${code} is missing from sanitize.vrl`);
}
});
it("allowlists every code passed to an error factory", () => {
const missing = [...thrownCodes()].filter(([code]) => !LOG_ERROR_CODES.has(code) || !collectorCodes.has(code))
.map(([code, file]) => `${code} (${file})`);
assert.deepEqual(missing, [], "run node scripts/generate-log-diagnostics.js");
});
it("lets the collector keep every code the logger emits", () => {
assert.deepEqual([...LOG_ERROR_CODES].filter((code) => !collectorCodes.has(code)), []);
});
});