fix(logging): give raw GitHub failures an error code, log missing branches as warnings

Overnight, GitHub refusals reached the logs as bare HTTPError/UnknownError
with no code: a ZIP whose archive request was refused became a cut
connection and a 502 zip_not_available, a 401 while checking a file
became an uncoded 401, and an Octokit 403 on /options answered
internal_error.

- codeUpstreamError maps got/Octokit replies to repo_not_accessible,
  github_rate_limit_exceeded, github_unavailable or upstream_error;
  handleError applies it, the streamer file route uses the file-level
  mapping, and programming errors pass through unchanged.
- A ZIP that fails before any byte answers with the code, so the API
  relays it; 4xx archive refusals log at warn.
- branch_not_found (owner deleted the branch) logs at warn.
- Octokit's HttpError is an allowlisted error type.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Thomas DurieuxandClaude Opus 5.5 committed 2026-11-30 07:52:23 +00:00
1 parent 351ed12b28
commit 3f8812c99e
10 files changed
+195 -11

No files matched your search

+2 -1
View File
@@ -777,7 +777,8 @@ export default class Repository {
?.commit;
if (!newCommit) {
logger.error("branch not found", {
// The owner deleted or renamed the branch: their fix, not an operator fault.
logger.warn("branch not found", {
code: "branch_not_found",
httpStatus: 404,
repoId: this.repoId,
+67 -1
View File
@@ -2042,6 +2042,18 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
"build/core/types.js": [
"<anonymous>"
],
"src/core/upstream-error.ts": [
"<anonymous>",
"codeUpstreamError",
"isUpstreamError",
"upstreamStatus"
],
"build/core/upstream-error.js": [
"<anonymous>",
"codeUpstreamError",
"isUpstreamError",
"upstreamStatus"
],
"src/core/url-utils.ts": [
"<anonymous>",
"joinUrl"
@@ -2320,14 +2332,59 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
"main",
"retireFileIndexes"
],
"src/server/admin-error-issues.ts": [
"<anonymous>",
"buildIssues",
"codeOf",
"countBy",
"deriveCause",
"filterRows",
"firstFrame",
"hostLabel",
"issueId",
"issueOptions",
"issueTitle",
"median",
"occurrence",
"plural",
"recordKind",
"seconds",
"statusOf",
"time",
"uncodedSite"
],
"build/server/admin-error-issues.js": [
"<anonymous>",
"buildIssues",
"codeOf",
"countBy",
"deriveCause",
"filterRows",
"firstFrame",
"hostLabel",
"issueId",
"issueOptions",
"issueTitle",
"median",
"occurrence",
"plural",
"recordKind",
"seconds",
"statusOf",
"time",
"uncodedSite"
],
"src/server/admin-log-investigation.ts": [
"<anonymous>",
"collector",
"endpoint",
"grafana",
"identity",
"incidentGroups",
"investigateLogs",
"issueRecords",
"logOptions",
"noiseCounts",
"range",
"read",
"rows",
@@ -2341,9 +2398,12 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
"collector",
"endpoint",
"grafana",
"identity",
"incidentGroups",
"investigateLogs",
"issueRecords",
"logOptions",
"noiseCounts",
"range",
"read",
"rows",
@@ -2473,8 +2533,10 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
"dashboardCache",
"escapeRegex",
"getErrorLogClient",
"historyRows",
"hourKey",
"isSafeSortField",
"issueNames",
"matches",
"parseDateRange",
"parseSort",
@@ -2489,8 +2551,10 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
"dashboardCache",
"escapeRegex",
"getErrorLogClient",
"historyRows",
"hourKey",
"isSafeSortField",
"issueNames",
"matches",
"parseDateRange",
"parseSort",
@@ -3030,15 +3094,17 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
],
"src/streamer/route.ts": [
"<anonymous>",
"fileError",
"handleStreamError",
"replyError"
],
"build/streamer/route.js": [
"<anonymous>",
"fileError",
"handleStreamError",
"replyError"
]
};
export const LOG_ERROR_TYPES = ["Error","TypeError","RangeError","ReferenceError","SyntaxError","URIError","EvalError","AggregateError","AnonymousError","HTTPError","RequestError","MongoServerError","MongoNetworkError","MongoServerSelectionError","ValidationError","TimeoutError","AbortError","UnknownError"];
export const LOG_ERROR_TYPES = ["Error","TypeError","RangeError","ReferenceError","SyntaxError","URIError","EvalError","AggregateError","AnonymousError","HTTPError","HttpError","RequestError","MongoServerError","MongoNetworkError","MongoServerSelectionError","ValidationError","TimeoutError","AbortError","UnknownError"];
export const LOG_ROUTES = ["/","other","/dashboard","/anonymize","/healthcheck","/api/healthcheck","/api","/api/download","/api/stat","/api/stat/history","/api/options","/api/message","/api/user","/api/user/quota","/api/user/dashboard","/api/repo","/api/anonymize-preview","/api/admin/overview","/api/admin/performance","/api/admin/errors","/api/admin/errors/stats","/api/admin/queues","/api/admin/queues/metrics","/github/app/webhook","/api/repo/:repoId","/api/repo/:repoId/file/:path","/api/repo/:repoId/files","/api/repo/:repoId/files/counts","/api/repo/:repoId/files/search","/api/repo/:repoId/zip","/api/repo/:repoId/options","/api/repo/:repoId/refresh","/api/repo/:repoId/coauthors","/api/repo/:repoId/extend","/api/repo/:owner/:repo","/api/repo/:owner/:repo/tree","/api/repo/:owner/:repo/file","/api/repo/:owner/:repo/readme","/api/repo/:owner/:repo/branches","/w/:repoId/:path","/r/:repoId/:path","/api/pr/:id/:path","/api/gist/:id/:path","/assets/:path","/github/:action","/api/admin/:action","/api/user/:action","/api/repo/:id/file/:path","/api/repo/:id/files/counts","/api/repo/:id/files/search","/api/repo/:id/files","/api/repo/:id/zip","/api/repo/:id","/viewer/:id/:path","/api/billing","/api/billing/draft","/api/billing/draft/:id","/api/billing/checkout","/api/billing/portal","/api/billing/refresh","/api/billing/webhook","/api/conferences/plans","/profile","/conference/:id"];
export const LOG_THROWN_ERROR_CODES = ["another_login_required","billing_address_missing","billing_already_paid","billing_busy","billing_checkout_disabled","billing_checkout_in_progress","billing_city_missing","billing_country_missing","billing_customer_mismatch","billing_draft_not_found","billing_email_missing","billing_invalid_conference","billing_invalid_draft","billing_invalid_purchase","billing_invalid_repository_size","billing_invalid_review_window","billing_missing","billing_name_missing","billing_plan_change_not_supported","billing_plan_unavailable","billing_price_misconfigured","billing_recovery_required","billing_review_window_locked","billing_subscription_exists","billing_unavailable","billing_zip_missing","branch_not_found","branch_not_specified","cache_busy","cache_miss","cannot_coauthor_self","commit_not_found","commit_not_specified","conf_end_date_invalid","conf_end_date_missing","conf_id_missing","conf_id_used","conf_name_missing","conf_not_activated","conf_not_found","conf_start_date_invalid","conf_start_date_missing","conference_not_found","conference_payment_required","connection_changed","download_not_enabled","expiration_limit_reached","file_listing_too_large","file_not_accessible","file_not_found","file_not_supported","file_too_big","folder_not_supported","gistId_already_used","gistId_not_specified","gist_expired","gist_not_available","gist_not_found","gist_not_ready","github_app_access_required","github_app_authorization_cancelled","github_app_disabled","github_app_permissions_invalid","github_app_reconnect_required","github_app_refresh_busy","github_grant_revocation_failed","github_identity_mismatch","github_oauth_required","github_rate_limit_exceeded","github_unavailable","github_user_not_found","invalid_auth_state","invalid_billing_expiration","invalid_commit_format","invalid_connection","invalid_cursor","invalid_file_path","invalid_gistId","invalid_github_path","invalid_path","invalid_plan","invalid_preserve_files_format","invalid_project_name","invalid_pullRequestId","invalid_repo","invalid_repoId","invalid_request","invalid_settings","invalid_sort","invalid_status","invalid_terms_format","invalid_token_id","invalid_token_options","is_removed","not_authorized","not_connected","not_owner","oauth_resources_remaining","options_not_provided","page_not_activated","page_not_supported_on_different_branch","path_not_defined","path_not_specified","pullRequestId_already_used","pullRequestId_is_not_a_number","pullRequestId_not_specified","pull_request_expired","pull_request_not_available","pull_request_not_found","pull_request_not_ready","quota_exceeded","quota_repository_limit","quota_storage_limit","rate_limited","readme_not_available","repoId_already_used","repoId_not_defined","repoUrl_not_defined","repo_access_limited","repo_empty","repo_not_accessible","repo_not_found","repo_saml_enforcement","repository_archived","repository_busy","repository_changed","repository_expired","repository_job_cancelled","repository_not_accessible","repository_not_ready","repository_not_specified","repository_tree_incomplete","repository_tree_too_large","s3_config_not_provided","source_not_provided","storage_delete_failed","storage_write_size_mismatch","streamer_route_not_found","streamer_unexpected_response","streamer_unreachable","streamer_upstream_error","submodule_not_available","subscription_required_for_never_expiration","sync_failed","terms_not_specified","token_expired","token_limit_reached","unable_to_connect_user","unable_to_download","upstream_error","user_banned","user_not_found","username_not_defined","zip_not_available","zip_unsafe_entry_path"];
+1 -1
View File
@@ -112,7 +112,7 @@ export function jsDelivrFileUrl(owner: string, repo: string, commit: string, fil
return `https://cdn.jsdelivr.net/gh/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}@${commit}/${path}`;
}
function downloadError(error: Error, filePath: string): AnonymousError {
export function downloadError(error: Error, filePath: string): AnonymousError {
if (error instanceof AnonymousError) return error;
if (error instanceof RateLimitDelayError) return new AnonymousError("github_rate_limit_exceeded", { httpStatus: 429, cause: error });
const response = error as Error & { response?: { statusCode?: number }; status?: number; httpStatus?: number };
+36
View File
@@ -0,0 +1,36 @@
import AnonymousError from "./AnonymousError";
const NETWORK_CODES = new Set([
"ECONNRESET", "ECONNREFUSED", "ETIMEDOUT", "ENOTFOUND", "EAI_AGAIN", "EPIPE",
"ERR_STREAM_PREMATURE_CLOSE", "ERR_GOT_REQUEST_ERROR",
]);
/** HTTP status of a got (`response.statusCode`) or Octokit (`status`) failure. */
export function upstreamStatus(error: unknown): number | undefined {
const value = error as { response?: { statusCode?: number }; status?: number } | null;
const status = value?.response?.statusCode ?? value?.status;
return Number.isInteger(status) && status! >= 400 && status! <= 599 ? status : undefined;
}
/** got's HTTPError/RequestError and Octokit's HttpError: a GitHub or CDN reply, not a bug. */
export function isUpstreamError(error: unknown): boolean {
if (!(error instanceof Error) || error instanceof AnonymousError) return false;
if (["HTTPError", "HttpError", "RequestError"].includes(error.name)) return true;
return NETWORK_CODES.has(String((error as { code?: unknown }).code));
}
/**
* Give a raw GitHub failure (repository level: archive, metadata, branches) an
* error code, so its log record and reply say what happened instead of
* "HTTPError". Anything else is returned unchanged.
*/
export function codeUpstreamError(error: unknown): unknown {
if (!isUpstreamError(error)) return error;
const status = upstreamStatus(error);
const cause = error as Error;
if (status === 401 || status === 403 || status === 404)
return new AnonymousError("repo_not_accessible", { httpStatus: status, cause });
if (status === 429) return new AnonymousError("github_rate_limit_exceeded", { httpStatus: 429, cause });
if (status !== undefined && status >= 500) return new AnonymousError("github_unavailable", { httpStatus: 502, cause });
return new AnonymousError("upstream_error", { httpStatus: 502, cause });
}
+15 -3
View File
@@ -10,6 +10,7 @@ import { boundedZip } from "./bounded-zip";
import GitHubDownload from "./source/GitHubDownload";
import { classifyGitHubMissError } from "./source/GitHubBase";
import AnonymousError from "./AnonymousError";
import { codeUpstreamError } from "./upstream-error";
import {
AnonymizeTransformer,
anonymizePathCompiled,
@@ -169,16 +170,27 @@ export async function streamAnonymizedZip(
output.destroy();
archive.abort();
};
const fail = (error: Error) => {
const fail = (raw: Error) => {
if (stopped) return;
// GitHub refusing or failing the archive is an upstream outcome with a
// code; only 5xx and unexpected errors are faults.
const error = codeUpstreamError(raw) as Error;
const status = (error as { httpStatus?: number }).httpStatus;
recordResponseFailure(res, "unknown", "local_abort");
logger.error("zip stream failed", serializeError(error));
logger[error instanceof AnonymousError && status !== undefined && status < 500 ? "warn" : "error"](
"zip stream failed", serializeError(error));
stop();
const destroyable = res as unknown as {
headersSent?: boolean;
status?: (code: number) => { json: (body: unknown) => void };
destroy?: (err?: Error) => void;
end?: () => void;
};
if (typeof destroyable.destroy === "function") {
// Before any archive byte, answer with the code so the API can relay it
// instead of reporting a cut connection as zip_not_available.
if (destroyable.headersSent === false && typeof destroyable.status === "function" && error instanceof AnonymousError) {
destroyable.status(status || 502).json({ error: error.message });
} else if (typeof destroyable.destroy === "function") {
destroyable.destroy(error);
} else if (typeof destroyable.end === "function") {
destroyable.end();
+4
View File
@@ -6,6 +6,7 @@ import UserModel from "../../core/model/users/users.model";
import User from "../../core/User";
import Repository from "../../core/Repository";
import { HTTPError } from "got";
import { codeUpstreamError } from "../../core/upstream-error";
import { RepositoryStatus } from "../../core/types";
import { createLogger, serializeError } from "../../core/logger";
import { isDisabledAccount } from "./auth-utils";
@@ -307,6 +308,9 @@ export function handleError(
options?: ErrorLogOptions
) {
if (isResponseCancellation(error, res)) return;
// A raw GitHub reply (got or Octokit) is an upstream outcome, not a bug:
// log and answer it with a code instead of "HTTPError"/"internal_error".
error = codeUpstreamError(error);
printError(error, req, options);
let errorCode = error;
if (error instanceof Error) {
+9 -2
View File
@@ -11,6 +11,8 @@ import AnonymousError from "../core/AnonymousError";
import { handleError } from "../server/routes/route-utils";
import { lookup } from "mime-types";
import { streamAnonymizedZip } from "../core/zipStream";
import { isUpstreamError } from "../core/upstream-error";
import { downloadError } from "../core/source/GitHubStream";
// 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.
@@ -18,6 +20,11 @@ function replyError(error: unknown, res: express.Response) {
handleError(error, res, undefined, { internal: true });
}
// A raw GitHub reply that escaped a file download (for example while checking
// an LFS pointer) gets the file-level code the download path would give it.
const fileError = (error: unknown, filePath: string) =>
isUpstreamError(error) ? downloadError(error as Error, filePath) : error;
export const router = express.Router();
router.post(
@@ -133,7 +140,7 @@ router.post("/", async (req: express.Request, res: express.Response) => {
content.destroy();
}
const streaming = res.headersSent;
replyError(error, res);
replyError(fileError(error, filePath), res);
if (streaming && !res.writableEnded) res.destroy();
anonymizer.destroy();
}
@@ -156,7 +163,7 @@ router.post("/", async (req: express.Request, res: express.Response) => {
res.status(409).end();
return;
}
replyError(error, res);
replyError(fileError(error, filePath), res);
}
});