Merge pull request #994 from tdurieux/fix/code-upstream-errors

fix(logging): code raw GitHub failures instead of logging bare HTTPError
This commit is contained in:
Thomas Durieux authored and GitHub committed 2026-11-29 23:59:26 -08:00
commit 049195439a
10 files changed
+195 -11

No files matched your search

+2 -2
View File
@@ -108,10 +108,10 @@ if includes(["api", "streamer"], service) {
}
}
# BEGIN GENERATED DIAGNOSTICS
source_functions = {"src/cli/index.ts":["<anonymous>","generateRandomFileName","main"],"build/cli/index.js":["<anonymous>","generateRandomFileName","main"],"src/config.ts":["<anonymous>"],"build/config.js":["<anonymous>"],"src/core/AnonymizedFile.ts":["<anonymous>","anonymizedContent","assertContentFile","cancel","content","defaultMaskCandidateRegex","escapeRegex","extension","forwardHeaders","getFileInfo","handleStreamError","isFileSupported","isImage","originalPath","probe","recoverTruncatedFile","send","sha","size","streamerErrorToAnonymous","visibleFile"],"build/core/AnonymizedFile.js":["<anonymous>","anonymizedContent","assertContentFile","cancel","content","defaultMaskCandidateRegex","escapeRegex","extension","forwardHeaders","getFileInfo","handleStreamError","isFileSupported","isImage","originalPath","probe","recoverTruncatedFile","send","sha","size","streamerErrorToAnonymous","visibleFile"],"src/core/AnonymousError.ts":["<anonymous>","detail","toString","url"],"build/core/AnonymousError.js":["<anonymous>","detail","toString","url"],"src/core/Conference.ts":["<anonymous>","expire","isExpired","remove","repositories","toJSON","updateStatus"],"build/core/Conference.js":["<anonymous>","expire","isExpired","remove","repositories","toJSON","updateStatus"],"src/core/Gist.ts":["<anonymous>","anonymize","check","conference","content","countView","download","downloadContent","downloadWithAccess","expire","getAccess","getToken","isImageFile","markExpired","remove","resetSate","toJSON","updateIfNeeded","updateStatus"],"build/core/Gist.js":["<anonymous>","anonymize","check","conference","content","countView","download","downloadContent","downloadWithAccess","expire","getAccess","getToken","isImageFile","markExpired","remove","resetSate","toJSON","updateIfNeeded","updateStatus"],"src/core/GitHubUtils.ts":["<anonymous>","abortableGateLookup","cancelled","checkToken","ensureRedisGateClient","getRedisGateResetAt","getToken","getTokenGateResetAt","octokit","ownerGitHubAccessRequired","rateLimitDetail","resolveRepositoryToken","run","setRedisGate","setRedisGateFromWorker","setTokenGate","waitForTokenGate"],"build/core/GitHubUtils.js":["<anonymous>","abortableGateLookup","cancelled","checkToken","ensureRedisGateClient","getRedisGateResetAt","getToken","getTokenGateResetAt","octokit","ownerGitHubAccessRequired","rateLimitDetail","resolveRepositoryToken","run","setRedisGate","setRedisGateFromWorker","setTokenGate","waitForTokenGate"],"src/core/PullRequest.ts":["<anonymous>","anonymize","check","commitMessage","conference","content","countView","download","downloadContent","expire","getToken","markExpired","optional","remove","resetSate","reviewThreads","toJSON","updateIfNeeded","updateStatus"],"build/core/PullRequest.js":["<anonymous>","anonymize","check","commitMessage","conference","content","countView","download","downloadContent","expire","getToken","markExpired","optional","remove","resetSate","reviewThreads","toJSON","updateIfNeeded","updateStatus"],"src/core/Repository.ts":["<anonymous>","anonymize","anonymizeTreeRecursive","anonymizedFiles","assertNotArchived","buildPathIndex","check","checkRefreshWrite","cleanupRetiredFileTrees","cleanupStagedFileTree","clearRows","completeRecoveredFileMetadata","computeSize","conference","countView","current","ensureFileTree","expire","fileSnapshotFilter","files","findAnonymizedPath","generateAnonymizeTransformer","getToken","hasEmptyTree","indexPaths","insertBatch","invalidateFileMetadata","isReady","markCachePresent","markExpired","pathKey","readFiles","refresh","refreshFilter","refreshIfNeeded","remove","removeCache","resetSate","searchFiles","snapshotValue","submoduleMounts","toJSON","updateIfNeeded","updateProgressMessage","updateRetiringPathIndex","updateStatus","zip"],"build/core/Repository.js":["<anonymous>","anonymize","anonymizeTreeRecursive","anonymizedFiles","assertNotArchived","buildPathIndex","check","checkRefreshWrite","cleanupRetiredFileTrees","cleanupStagedFileTree","clearRows","completeRecoveredFileMetadata","computeSize","conference","countView","current","ensureFileTree","expire","fileSnapshotFilter","files","findAnonymizedPath","generateAnonymizeTransformer","getToken","hasEmptyTree","indexPaths","insertBatch","invalidateFileMetadata","isReady","markCachePresent","markExpired","pathKey","readFiles","refresh","refreshFilter","refreshIfNeeded","remove","removeCache","resetSate","searchFiles","snapshotValue","submoduleMounts","toJSON","updateIfNeeded","updateProgressMessage","updateRetiringPathIndex","updateStatus","zip"],"src/core/User.ts":["<anonymous>","getAccessToken","getGists","getGitHubRepositories","getPullRequests","getRepositories","markListExpired","quotaRepositories","repositoryMembership","toJSON"],"build/core/User.js":["<anonymous>","getAccessToken","getGists","getGitHubRepositories","getPullRequests","getRepositories","markListExpired","quotaRepositories","repositoryMembership","toJSON"],"src/core/anonymization-errors.ts":["<anonymous>","anonymLine truncated
source_functions = {"src/cli/index.ts":["<anonymous>","generateRandomFileName","main"],"build/cli/index.js":["<anonymous>","generateRandomFileName","main"],"src/config.ts":["<anonymous>"],"build/config.js":["<anonymous>"],"src/core/AnonymizedFile.ts":["<anonymous>","anonymizedContent","assertContentFile","cancel","content","defaultMaskCandidateRegex","escapeRegex","extension","forwardHeaders","getFileInfo","handleStreamError","isFileSupported","isImage","originalPath","probe","recoverTruncatedFile","send","sha","size","streamerErrorToAnonymous","visibleFile"],"build/core/AnonymizedFile.js":["<anonymous>","anonymizedContent","assertContentFile","cancel","content","defaultMaskCandidateRegex","escapeRegex","extension","forwardHeaders","getFileInfo","handleStreamError","isFileSupported","isImage","originalPath","probe","recoverTruncatedFile","send","sha","size","streamerErrorToAnonymous","visibleFile"],"src/core/AnonymousError.ts":["<anonymous>","detail","toString","url"],"build/core/AnonymousError.js":["<anonymous>","detail","toString","url"],"src/core/Conference.ts":["<anonymous>","expire","isExpired","remove","repositories","toJSON","updateStatus"],"build/core/Conference.js":["<anonymous>","expire","isExpired","remove","repositories","toJSON","updateStatus"],"src/core/Gist.ts":["<anonymous>","anonymize","check","conference","content","countView","download","downloadContent","downloadWithAccess","expire","getAccess","getToken","isImageFile","markExpired","remove","resetSate","toJSON","updateIfNeeded","updateStatus"],"build/core/Gist.js":["<anonymous>","anonymize","check","conference","content","countView","download","downloadContent","downloadWithAccess","expire","getAccess","getToken","isImageFile","markExpired","remove","resetSate","toJSON","updateIfNeeded","updateStatus"],"src/core/GitHubUtils.ts":["<anonymous>","abortableGateLookup","cancelled","checkToken","ensureRedisGateClient","getRedisGateResetAt","getToken","getTokenGateResetAt","octokit","ownerGitHubAccessRequired","rateLimitDetail","resolveRepositoryToken","run","setRedisGate","setRedisGateFromWorker","setTokenGate","waitForTokenGate"],"build/core/GitHubUtils.js":["<anonymous>","abortableGateLookup","cancelled","checkToken","ensureRedisGateClient","getRedisGateResetAt","getToken","getTokenGateResetAt","octokit","ownerGitHubAccessRequired","rateLimitDetail","resolveRepositoryToken","run","setRedisGate","setRedisGateFromWorker","setTokenGate","waitForTokenGate"],"src/core/PullRequest.ts":["<anonymous>","anonymize","check","commitMessage","conference","content","countView","download","downloadContent","expire","getToken","markExpired","optional","remove","resetSate","reviewThreads","toJSON","updateIfNeeded","updateStatus"],"build/core/PullRequest.js":["<anonymous>","anonymize","check","commitMessage","conference","content","countView","download","downloadContent","expire","getToken","markExpired","optional","remove","resetSate","reviewThreads","toJSON","updateIfNeeded","updateStatus"],"src/core/Repository.ts":["<anonymous>","anonymize","anonymizeTreeRecursive","anonymizedFiles","assertNotArchived","buildPathIndex","check","checkRefreshWrite","cleanupRetiredFileTrees","cleanupStagedFileTree","clearRows","completeRecoveredFileMetadata","computeSize","conference","countView","current","ensureFileTree","expire","fileSnapshotFilter","files","findAnonymizedPath","generateAnonymizeTransformer","getToken","hasEmptyTree","indexPaths","insertBatch","invalidateFileMetadata","isReady","markCachePresent","markExpired","pathKey","readFiles","refresh","refreshFilter","refreshIfNeeded","remove","removeCache","resetSate","searchFiles","snapshotValue","submoduleMounts","toJSON","updateIfNeeded","updateProgressMessage","updateRetiringPathIndex","updateStatus","zip"],"build/core/Repository.js":["<anonymous>","anonymize","anonymizeTreeRecursive","anonymizedFiles","assertNotArchived","buildPathIndex","check","checkRefreshWrite","cleanupRetiredFileTrees","cleanupStagedFileTree","clearRows","completeRecoveredFileMetadata","computeSize","conference","countView","current","ensureFileTree","expire","fileSnapshotFilter","files","findAnonymizedPath","generateAnonymizeTransformer","getToken","hasEmptyTree","indexPaths","insertBatch","invalidateFileMetadata","isReady","markCachePresent","markExpired","pathKey","readFiles","refresh","refreshFilter","refreshIfNeeded","remove","removeCache","resetSate","searchFiles","snapshotValue","submoduleMounts","toJSON","updateIfNeeded","updateProgressMessage","updateRetiringPathIndex","updateStatus","zip"],"src/core/User.ts":["<anonymous>","getAccessToken","getGists","getGitHubRepositories","getPullRequests","getRepositories","markListExpired","quotaRepositories","repositoryMembership","toJSON"],"build/core/User.js":["<anonymous>","getAccessToken","getGists","getGitHubRepositories","getPullRequests","getRepositories","markListExpired","quotaRepositories","repositoryMembership","toJSON"],"src/core/anonymization-errors.ts":["<anonymous>","anonymLine truncated
for_each(["errorType", "causeType"]) -> |_index, key| {
value = get(record, [key]) ?? null
if includes(["Error","TypeError","RangeError","ReferenceError","SyntaxError","URIError","EvalError","AggregateError","AnonymousError","HTTPError","RequestError","MongoServerError","MongoNetworkError","MongoServerSelectionError","ValidationError","TimeoutError","AbortError","UnknownError"], value) { out = set!(out, [key], value) }
if includes(["Error","TypeError","RangeError","ReferenceError","SyntaxError","URIError","EvalError","AggregateError","AnonymousError","HTTPError","HttpError","RequestError","MongoServerError","MongoNetworkError","MongoServerSelectionError","ValidationError","TimeoutError","AbortError","UnknownError"], value) { out = set!(out, [key], value) }
}
for_each(["errorStack", "causeStack"]) -> |_index, key| {
value = get(record, [key]) ?? null
+1 -1
View File
@@ -37,7 +37,7 @@ function scan(dir) {
}
}
scan('src');
const types=['Error','TypeError','RangeError','ReferenceError','SyntaxError','URIError','EvalError','AggregateError','AnonymousError','HTTPError','RequestError','MongoServerError','MongoNetworkError','MongoServerSelectionError','ValidationError','TimeoutError','AbortError','UnknownError'];
const types=['Error','TypeError','RangeError','ReferenceError','SyntaxError','URIError','EvalError','AggregateError','AnonymousError','HTTPError','HttpError','RequestError','MongoServerError','MongoNetworkError','MongoServerSelectionError','ValidationError','TimeoutError','AbortError','UnknownError'];
const vrl=fs.readFileSync('deploy/logging/sanitize.vrl','utf8');
const routes=JSON.parse(vrl.match(/if includes\((\[.*?\]), record.route\)/)[1]);
const codes=[...thrownCodes].sort();
+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);
}
});
+58
View File
@@ -0,0 +1,58 @@
const { expect } = require("chai");
require("ts-node/register/transpile-only");
const http = require("node:http");
const { PassThrough } = require("node:stream");
const AnonymousError = require("../src/core/AnonymousError").default;
const { codeUpstreamError } = require("../src/core/upstream-error");
const { handleError } = require("../src/server/routes/route-utils");
const { streamAnonymizedZip } = require("../src/core/zipStream");
function octokitError(status) {
return Object.assign(new Error("Resource not accessible"), { name: "HttpError", status });
}
describe("upstream error codes", () => {
it("codes raw GitHub replies and leaves bugs alone", () => {
const denied = codeUpstreamError(octokitError(403));
expect(denied).to.be.instanceOf(AnonymousError);
expect(denied.message).to.equal("repo_not_accessible");
expect(denied.httpStatus).to.equal(403);
const gotError = Object.assign(new Error("Response code 503"), { name: "HTTPError", response: { statusCode: 503 } });
expect(codeUpstreamError(gotError).message).to.equal("github_unavailable");
expect(codeUpstreamError(octokitError(429)).message).to.equal("github_rate_limit_exceeded");
const reset = Object.assign(new Error("socket hang up"), { name: "RequestError", code: "ECONNRESET" });
expect(codeUpstreamError(reset).message).to.equal("upstream_error");
const bug = new TypeError("x is undefined");
expect(codeUpstreamError(bug)).to.equal(bug);
});
it("answers an Octokit failure with its code instead of internal_error", () => {
let status, body;
const res = { headersSent: false, status(code) { status = code; return this; }, json(value) { body = value; } };
handleError(octokitError(403), res);
expect(status).to.equal(403);
expect(body).to.deep.equal({ error: "repo_not_accessible" });
});
it("replies to a refused archive with a code before any ZIP byte", async () => {
const server = http.createServer((req, res) => { res.statusCode = 404; res.end("Not Found"); });
await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));
const { port } = server.address();
const GitHubDownload = require("../src/core/source/GitHubDownload").default;
const original = GitHubDownload.prototype.getZipUrl;
GitHubDownload.prototype.getZipUrl = async () => ({ url: `http://127.0.0.1:${port}/archive.zip` });
const response = new PassThrough();
let replied;
response.headersSent = false;
response.status = code => ({ json: body => { replied = { code, body }; response.end(); } });
try {
await streamAnonymizedZip({ repoId: "test", organization: "owner", repoName: "private", commit: "c0ffee",
getToken: () => "ghs_token", anonymizerOptions: { terms: [] } }, response);
await new Promise(resolve => response.once("finish", resolve).resume());
} finally {
GitHubDownload.prototype.getZipUrl = original;
server.close();
}
expect(replied).to.deep.equal({ code: 404, body: { error: "repo_not_accessible" } });
});
});