mirror of
https://github.com/tdurieux/anonymous_github.git
synced 2026-12-02 17:13:33 +01:00
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>
This commit is contained in:
1 parent
111870b6e2
commit
c761fc6c17
7 files changed
+209
-71
No files matched your search
+13
-27
@@ -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) });
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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<object>(), 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;
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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<string> = 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<string, unknown> = 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<string, unknown> = 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;
|
||||
|
||||
+13
-6
@@ -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);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
Reference in new issue
Block a user