Files
anonymous_github/test/error-log-level.test.js
T
Thomas DurieuxandClaude Opus 5.5 c761fc6c17 fix: log each failed file request once, expected outcomes at info
A streamer error such as repo_not_found produced three warnings: the
streamer's handleError, the API's streamer_fetch_failed and the API's
handleError. Expected client outcomes (repo_not_found, repository_expired,
file_not_found, github_app_access_required, ...) were all logged at warn,
which filled the admin Errors page.

- handleError picks the level with errorLogLevel: codes in
  EXPECTED_CLIENT_ERRORS with a 4xx status log at info; other 4xx (rate
  limits, token_expired, validation) stay warn and 5xx stay error.
- The streamer passes { internal: true }: expected outcomes drop to debug
  there because the API logs the request's end state. Faults keep their
  level and the streamer-side stack. Its direct 400 replies now go through
  handleError so they are logged too.
- The API no longer logs streamer_fetch_failed or streamer_zip_fetch_failed.
  The relayed error carries upstreamStatus, and when the streamer's coded
  reply shows it already logged the failure, the API logs it at info.

Every record keeps requestId, so the chain can still be found by request.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 09:29:14 +00:00

123 lines
6.4 KiB
JavaScript

const { strict: assert } = require("node:assert");
const { setTimeout } = require("node:timers");
const express = require("express");
require("ts-node/register/transpile-only");
const config = require("../src/config").default;
const AnonymousError = require("../src/core/AnonymousError").default;
const File = require("../src/core/AnonymizedFile").default;
const GitHubStream = require("../src/core/source/GitHubStream").default;
const { AnonymizeTransformer } = require("../src/core/anonymize-utils");
const { errorLogLevel, handleError } = require("../src/server/routes/route-utils");
const streamer = require("../src/streamer/route").default;
const got = require("got");
const error = (code, httpStatus, extra = {}) => Object.assign(new AnonymousError(code, { httpStatus }), extra);
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
/** Collect the structured records written to stdout while `run` executes. */
async function captureLogs(run) {
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;
};
try { await run(); } finally { process.stdout.write = write; }
return records;
}
describe("error log levels", () => {
it("logs expected client outcomes at info and faults at warn or error", () => {
for (const [code, status] of [["repo_not_found", 404], ["repository_expired", 410], ["file_not_found", 404],
["github_app_access_required", 403], ["repository_archived", 410], ["folder_not_supported", 404], ["is_removed", 410]]) {
assert.equal(errorLogLevel(error(code, status)), "info", code);
}
assert.equal(errorLogLevel(error("token_expired", 401)), "warn");
assert.equal(errorLogLevel(error("rate_limited", 429)), "warn");
assert.equal(errorLogLevel(error("github_rate_limit_exceeded", 429)), "warn");
assert.equal(errorLogLevel(error("invalid_file_path", 400)), "warn");
assert.equal(errorLogLevel(error("upstream_error", 502)), "error");
assert.equal(errorLogLevel(error("streamer_unreachable", 502)), "error");
assert.equal(errorLogLevel(new Error("boom")), "error");
// A known code with a server status is still a fault.
assert.equal(errorLogLevel(error("file_not_found", 500)), "error");
});
it("leaves a relayed failure to the service that logged it", () => {
assert.equal(errorLogLevel(error("upstream_error", 502, { upstreamStatus: 502, upstreamLogged: true })), "info");
assert.equal(errorLogLevel(error("streamer_upstream_error", 502, { upstreamStatus: 502 })), "error");
});
it("drops expected outcomes to debug when another service logs the end state", () => {
assert.equal(errorLogLevel(error("repo_not_found", 404), { internal: true }), "debug");
assert.equal(errorLogLevel(error("token_expired", 401), { internal: true }), "warn");
assert.equal(errorLogLevel(error("upstream_error", 502), { internal: true }), "error");
});
});
describe("streamer file failures", function () {
this.timeout(10000);
let old, original, streamerServer, apiServer, base;
beforeEach(async () => {
old = { ...config };
original = GitHubStream.prototype.getFileContentCache;
const streamerApp = express(); streamerApp.use(express.json()); streamerApp.use("/api", streamer);
streamerServer = await new Promise((resolve) => { const s = streamerApp.listen(0, "127.0.0.1", () => resolve(s)); });
Object.assign(config, { STREAMER_ENTRYPOINT: `http://127.0.0.1:${streamerServer.address().port}/`, SHARED_CACHE_ENABLED: false });
const api = express();
api.get("/file", async (req, res) => {
const file = new File({ repository: {
repoId: "anon", owner: { id: "507f1f77bcf86cd799439011" }, options: { terms: [] },
model: { _id: "507f1f77bcf86cd799439012", source: { repositoryName: "owner/gone" } },
getToken: async () => "token",
generateAnonymizeTransformer: (filePath) => new AnonymizeTransformer({ terms: [], filePath }),
}, anonymizedPath: "README.md" });
file._file = { name: "README.md", path: "", sha: "sha", size: 10 };
try { await file.send(res); } catch (failure) { handleError(failure, res, req); }
});
apiServer = await new Promise((resolve) => { const s = api.listen(0, "127.0.0.1", () => resolve(s)); });
base = `http://127.0.0.1:${apiServer.address().port}`;
});
afterEach(async () => {
GitHubStream.prototype.getFileContentCache = original;
await new Promise((resolve) => apiServer.close(resolve));
await new Promise((resolve) => streamerServer.close(resolve));
Object.assign(config, old);
});
const request = async (failure) => {
GitHubStream.prototype.getFileContentCache = async () => { throw failure; };
let response;
const records = await captureLogs(async () => {
response = await got(`${base}/file`, { throwHttpErrors: false, retry: 0 });
await wait(50);
});
return { response, records: records.filter((record) => record.severity !== "debug") };
};
it("logs a missing source repository once, at info", async () => {
const { response, records } = await request(new AnonymousError("repo_not_found", { httpStatus: 404 }));
assert.equal(response.statusCode, 404);
assert.equal(records.length, 1, JSON.stringify(records));
assert.equal(records[0].severity, "info");
assert.equal(records[0].errorCode, "repo_not_found");
assert.equal(records[0].upstreamStatus, 404);
});
it("keeps a single fault record from the streamer", async () => {
const { response, records } = await request(new AnonymousError("upstream_error", { httpStatus: 502 }));
assert.equal(response.statusCode, 502);
const faults = records.filter((record) => record.severity === "warn" || record.severity === "error");
assert.equal(faults.length, 1, JSON.stringify(records));
assert.equal(faults[0].errorCode, "upstream_error");
// The streamer's own record, not the API relay (which carries upstreamStatus).
assert.equal(faults[0].upstreamStatus, undefined);
assert.equal(records.filter((record) => record.upstreamStatus === 502).length, 1);
});
});