From c761fc6c1722be024c3d45571743dae9ef1fe5a1 Mon Sep 17 00:00:00 2001 From: Thomas Durieux <5577568+tdurieux@users.noreply.github.com> Date: Sun, 29 Nov 2026 09:28:53 +0000 Subject: [PATCH] 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 --- src/core/AnonymizedFile.ts | 40 +++----- src/core/AnonymousError.ts | 4 + src/core/logger.ts | 2 + src/server/routes/repository-public.ts | 34 +++---- src/server/routes/route-utils.ts | 59 ++++++++---- src/streamer/route.ts | 19 ++-- test/error-log-level.test.js | 122 +++++++++++++++++++++++++ 7 files changed, 209 insertions(+), 71 deletions(-) create mode 100644 test/error-log-level.test.js diff --git a/src/core/AnonymizedFile.ts b/src/core/AnonymizedFile.ts index 6f9acca..f9ee60f 100644 --- a/src/core/AnonymizedFile.ts +++ b/src/core/AnonymizedFile.ts @@ -59,14 +59,16 @@ function defaultMaskCandidateRegex(value: string): RegExp { // generic 404. Without this, a corrupt cache, a 5xx from the streamer, an // LFS pointer issue, and a missing file all surface to the user as the // same `file_not_found` — which makes incidents impossible to triage. +// The request's handleError logs the result once. When the streamer answered, +// it already logged its side under the same requestId. function streamerErrorToAnonymous( - err: Error & { response?: { statusCode?: number; body?: unknown } }, - context: { repoId: string; filePath: string } + err: Error & { response?: { statusCode?: number; body?: unknown } } ): { error: AnonymousError; upstreamStatus?: number; upstreamBody?: string } { const upstreamStatus = err?.response?.statusCode; let errCode = "file_not_found"; let httpStatus = 404; let upstreamBody: string | undefined; + let streamerCode = false; if (err?.response?.body != null) { try { @@ -84,6 +86,7 @@ function streamerErrorToAnonymous( const parsed = JSON.parse(upstreamBody); if (parsed && typeof parsed.error === "string") { errCode = parsed.error; + streamerCode = true; } } catch { // body wasn't JSON — keep the default code @@ -105,27 +108,14 @@ function streamerErrorToAnonymous( httpStatus = 502; } - logger.warn("streamer fetch failed", { - code: errCode, + const error = new AnonymousError(errCode, { httpStatus, - repoId: context.repoId, - filePath: context.filePath, - upstreamStatus, - upstreamBody: upstreamBody?.slice(0, 500), - url: config.STREAMER_ENTRYPOINT - ? join(config.STREAMER_ENTRYPOINT, "api") - : undefined, - err: serializeError(err), + cause: err, }); - - return { - error: new AnonymousError(errCode, { - httpStatus, - cause: err, - }), - upstreamStatus, - upstreamBody, - }; + error.upstreamStatus = upstreamStatus; + // A coded body comes from the streamer's handleError, which logged it. + error.upstreamLogged = streamerCode && typeof upstreamStatus === "number"; + return { error, upstreamStatus, upstreamBody }; } /** @@ -434,7 +424,7 @@ export default class AnonymizedFile { }, })); content.on("error", err => { - const { error } = streamerErrorToAnonymous(err, { repoId: this.repository.repoId, filePath: this.anonymizedPath }); + const { error } = streamerErrorToAnonymous(err); void notifyOwnerAccessProblem(this.repository.owner.id, error, { kind: "repository", id: String(this.repository.model._id) }); }); return content; @@ -493,7 +483,7 @@ export default class AnonymizedFile { headersDone(true); const { error } = streamerErrorToAnonymous(err as Error & { response?: { statusCode?: number; body?: unknown }; - }, { repoId: this.repository.repoId, filePath: this.anonymizedPath }); + }); void notifyOwnerAccessProblem(this.repository.owner.id, error, { kind: "repository", id: String(this.repository.model._id) }); error.value = this; throw error; @@ -540,10 +530,6 @@ export default class AnonymizedFile { const { error } = streamerErrorToAnonymous( err as Error & { response?: { statusCode?: number; body?: unknown }; - }, - { - repoId: this.repository.repoId, - filePath: this.anonymizedPath, } ); void notifyOwnerAccessProblem(this.repository.owner.id, error, { kind: "repository", id: String(this.repository.model._id) }); diff --git a/src/core/AnonymousError.ts b/src/core/AnonymousError.ts index b1a7ab7..a80a621 100644 --- a/src/core/AnonymousError.ts +++ b/src/core/AnonymousError.ts @@ -12,6 +12,10 @@ export default class AnonymousError extends CustomError { value?: unknown; httpStatus?: number; cause?: Error; + /** Status of the internal service response this error relays. */ + upstreamStatus?: number; + /** The internal service that answered already logged this failure. */ + upstreamLogged?: boolean; private explicitUrl?: string; constructor( diff --git a/src/core/logger.ts b/src/core/logger.ts index 1d0a990..d260442 100644 --- a/src/core/logger.ts +++ b/src/core/logger.ts @@ -325,6 +325,7 @@ type ErrorLike = { stack?: string; status?: number; httpStatus?: number; + upstreamStatus?: number; code?: string | number; cause?: unknown; request?: { url?: string; method?: string }; @@ -353,6 +354,7 @@ export function serializeError(err: unknown, seen = new WeakSet(), depth // AnonymousError carries an httpStatus and an inner cause. if (typeof e.httpStatus === "number") out.httpStatus = e.httpStatus; + if (typeof e.upstreamStatus === "number") out.upstreamStatus = e.upstreamStatus; // Octokit's deprecated `code` getter emits a stack on every read. Only // inspect data properties so logging never invokes that getter. const code = Object.getOwnPropertyDescriptor(e, "code")?.value; diff --git a/src/server/routes/repository-public.ts b/src/server/routes/repository-public.ts index 5c8a61f..32ac343 100644 --- a/src/server/routes/repository-public.ts +++ b/src/server/routes/repository-public.ts @@ -17,13 +17,10 @@ import { RepositoryStatus } from "../../core/types"; import User from "../../core/User"; import { streamAnonymizedZip } from "../../core/zipStream"; import FileModel from "../../core/model/files/files.model"; -import { createLogger, serializeError } from "../../core/logger"; import { githubTokenForStreamer } from "../../core/github-token-context"; import gh = require("parse-github-url"); import { requestHeaders, startStage } from "../../core/request-monitoring"; -const logger = createLogger("repository-public"); - const router = express.Router(); router.get( @@ -94,6 +91,7 @@ router.get( headersDone(true); const upstreamStatus = err?.response?.statusCode; let upstreamBody: string | undefined; + let streamerCode = false; let errCode = "zip_not_available"; let httpStatus = 502; if (err?.response?.body != null) { @@ -112,6 +110,7 @@ router.get( const parsed = JSON.parse(upstreamBody); if (parsed && typeof parsed.error === "string") { errCode = parsed.error; + streamerCode = true; } } catch { /* not JSON */ @@ -121,26 +120,17 @@ router.get( if (typeof upstreamStatus === "number") { httpStatus = upstreamStatus >= 500 ? 502 : upstreamStatus; } - logger.warn("streamer zip fetch failed", { - code: errCode, - httpStatus, - repoId: repo.repoId, - upstreamStatus, - upstreamBody: upstreamBody?.slice(0, 500), - url: config.STREAMER_ENTRYPOINT - ? join(config.STREAMER_ENTRYPOINT, "api/download") - : undefined, - err: serializeError(err), - }); const streaming = res.headersSent; - handleError( - new AnonymousError(errCode, { - url: req.originalUrl, - httpStatus, - cause: err, - }), - res - ); + const error = new AnonymousError(errCode, { + url: req.originalUrl, + httpStatus, + cause: err, + }); + error.upstreamStatus = upstreamStatus; + // A coded body comes from the streamer's handleError, which + // already logged this failure under the same requestId. + error.upstreamLogged = streamerCode && typeof upstreamStatus === "number"; + handleError(error, res); // Once ZIP bytes have been sent, handleError cannot send JSON. // Terminate the truncated response so the client reports failure // instead of waiting forever for the ZIP's central directory. diff --git a/src/server/routes/route-utils.ts b/src/server/routes/route-utils.ts index 9010635..db90661 100644 --- a/src/server/routes/route-utils.ts +++ b/src/server/routes/route-utils.ts @@ -184,8 +184,44 @@ export function explicitErrorStatus(error: unknown): number | undefined { .find(status => Number.isInteger(status) && status! >= 400 && status! <= 599); } +// Request end states that need no operator action: the visitor asked for +// something that is gone, expired, unsupported or not theirs. They are logged +// at info so the admin Errors page (warn and error) keeps to faults. Rate +// limits, expired owner tokens and upstream failures are left out on purpose. +export const EXPECTED_CLIENT_ERRORS: ReadonlySet = new Set([ + "repo_not_found", "repository_not_found", "commit_not_found", "branch_not_found", + "file_not_found", "folder_not_supported", "file_not_supported", "file_too_big", + "readme_not_available", "submodule_not_available", + "repository_expired", "repository_archived", "repository_not_ready", "is_removed", + "github_app_access_required", "not_connected", "not_authorized", + "page_not_activated", "page_not_supported_on_different_branch", "download_not_enabled", + "gist_not_found", "gist_expired", "gist_not_ready", + "pull_request_not_found", "pull_request_expired", "pull_request_not_ready", + "conf_not_found", "conference_not_found", "repoId_already_used", "invalid_repoId", +]); + +export type ErrorLogOptions = { + /** The reply goes to another service that logs the request's end state. */ + internal?: boolean; +}; + +type LogLevel = "debug" | "info" | "warn" | "error"; + +/** One record per failed request, at a level that matches who has to act. */ +export function errorLogLevel(error: unknown, options: ErrorLogOptions = {}): LogLevel { + const status = explicitErrorStatus(error); + let level: LogLevel = status !== undefined && status < 500 ? "warn" : "error"; + if (error instanceof AnonymousError) { + // The internal service that answered logged the failure at its own level. + if (error.upstreamLogged) level = "info"; + else if (level === "warn" && EXPECTED_CLIENT_ERRORS.has(error.message)) level = "info"; + } + return level === "info" && options.internal ? "debug" : level; +} + // eslint-disable-next-line @typescript-eslint/no-explicit-any -function printError(error: any, req?: express.Request) { +function printError(error: any, req?: express.Request, options: ErrorLogOptions = {}) { + const level = errorLogLevel(error, options); if (error instanceof AnonymousError) { if (req?.originalUrl === "/api/repo/undefined/options") return; const payload: Record = serializeError(error); @@ -194,20 +230,11 @@ function printError(error: any, req?: express.Request) { // Errors page surfaces something meaningful (e.g. "repoId_already_used") // instead of a generic "anonymous error" wrapper. const summary = error.message || error.name || "AnonymousError"; - // 4xx are expected client errors (not_found, expired, not_connected) — - // route them to warn so the admin Errors page can split server faults - // (5xx) from client misuse (4xx) cleanly. - const status = explicitErrorStatus(error); - if (typeof status === "number" && status >= 400 && status < 500) { - logger.warn(summary, payload); - } else { - logger.error(summary, payload); - } + logger[level](summary, payload); } else if (error instanceof HTTPError) { const payload: Record = serializeError(error); ensureUrl(payload, req); - const status = explicitErrorStatus(error); - logger[status && status < 500 ? "warn" : "error"](error.code || error.name || "HTTPError", payload); + logger[level](error.code || error.name || "HTTPError", payload); } else { // Unhandled errors: use the error class name (SyntaxError, TypeError, // RangeError, ...) as the summary so the admin page shows @@ -225,8 +252,7 @@ function printError(error: any, req?: express.Request) { ((error as { name?: string }).name || (error as { message?: string }).message)) || "UnhandledError"; - const status = explicitErrorStatus(error); - logger[status && status < 500 ? "warn" : "error"](summary, serialized); + logger[level](summary, serialized); } } @@ -234,10 +260,11 @@ export function handleError( // eslint-disable-next-line @typescript-eslint/no-explicit-any error: any, res?: express.Response, - req?: express.Request + req?: express.Request, + options?: ErrorLogOptions ) { if (isResponseCancellation(error, res)) return; - printError(error, req); + printError(error, req, options); let errorCode = error; if (error instanceof Error) { errorCode = error.message; diff --git a/src/streamer/route.ts b/src/streamer/route.ts index 19e14ed..c5dd0ca 100644 --- a/src/streamer/route.ts +++ b/src/streamer/route.ts @@ -6,10 +6,17 @@ import { AnonymizeTransformer, isTextFile, } from "../core/anonymize-utils"; +import AnonymousError from "../core/AnonymousError"; import { handleError } from "../server/routes/route-utils"; import { lookup } from "mime-types"; import { streamAnonymizedZip } from "../core/zipStream"; +// The API relays these replies and logs each request's end state, so expected +// outcomes are only debug here. Faults keep their level and streamer stack. +function replyError(error: unknown, res: express.Response) { + handleError(error, res, undefined, { internal: true }); +} + export const router = express.Router(); router.post( @@ -18,7 +25,7 @@ router.post( req.body = req.body || {}; const token: string = req.body.token; if (typeof req.body.repoFullName !== "string" || typeof token !== "string") { - return res.status(400).json({ error: "invalid_request" }); + return replyError(new AnonymousError("invalid_request", { httpStatus: 400 }), res); } const repoFullName = req.body.repoFullName.split("/"); const repoId = req.body.repoId; @@ -42,7 +49,7 @@ router.post( ); } catch (error) { const streaming = res.headersSent; - handleError(error, res); + replyError(error, res); if (streaming && !res.writableEnded) res.destroy(); } } @@ -51,7 +58,7 @@ router.post("/", async (req: express.Request, res: express.Response) => { req.body = req.body || {}; const token: string = req.body.token; if (typeof req.body.repoFullName !== "string" || typeof token !== "string") { - return res.status(400).json({ error: "invalid_request" }); + return replyError(new AnonymousError("invalid_request", { httpStatus: 400 }), res); } const repoFullName = req.body.repoFullName.split("/"); const repoId = req.body.repoId; @@ -77,7 +84,7 @@ router.post("/", async (req: express.Request, res: express.Response) => { .split(/[\\/]/) .some((segment) => segment === ".." || segment === "") ) { - return res.status(400).json({ error: "invalid_file_path" }); + return replyError(new AnonymousError("invalid_file_path", { httpStatus: 400 }), res); } const source = new GitHubStream({ @@ -123,7 +130,7 @@ router.post("/", async (req: express.Request, res: express.Response) => { content.destroy(); } const streaming = res.headersSent; - handleError(error, res); + replyError(error, res); if (streaming && !res.writableEnded) res.destroy(); anonymizer.destroy(); } @@ -146,7 +153,7 @@ router.post("/", async (req: express.Request, res: express.Response) => { res.status(409).end(); return; } - handleError(error, res); + replyError(error, res); } }); diff --git a/test/error-log-level.test.js b/test/error-log-level.test.js new file mode 100644 index 0000000..59a0a4a --- /dev/null +++ b/test/error-log-level.test.js @@ -0,0 +1,122 @@ +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); + }); +});