Merge remote-tracking branch 'origin/feat/external-request-logs' into HEAD

# Conflicts:
#	deploy/logging/sanitize.vrl
#	public/asset-manifest.json
#	public/script/vendor.min.js
#	src/core/log-record.ts
This commit is contained in:
Thomas Durieux committed 2026-11-29 13:11:41 +00:00
commit cc5e06022f
42 files changed
+4638 -353

No files matched your search

+60 -8
View File
@@ -15,7 +15,16 @@ import { IAnonymizedGistDocument } from "./model/anonymizedGists/anonymizedGists
import AnonymizedGistModel from "./model/anonymizedGists/anonymizedGists.model";
import config from "../config";
import { octokit, ownerGitHubAccessRequired } from "./GitHubUtils";
import { ContentAnonimizer } from "./anonymize-utils";
import { ContentAnonimizer, classifyByName } from "./anonymize-utils";
// Images are the only binary gist files kept: other binaries (PDF, Office,
// archives) carry metadata the text anonymizer cannot reach, so they are
// listed but never stored or served. The whole gist is one MongoDB document
// (16 MB max, base64 adds a third), so images share one budget.
const GIST_IMAGE_LIMIT = 4 * 1024 * 1024;
const GIST_IMAGE_BUDGET = 8 * 1024 * 1024;
const GIST_RAW_ORIGIN = "https://gist.githubusercontent.com/";
const isImageFile = (name: string) => /\.(png|jpe?g|gif|webp|bmp|ico|avif|tiff?)$/i.test(name || "");
import { createLogger } from "./logger";
const logger = createLogger("gist");
@@ -32,6 +41,8 @@ type GistPayload = {
language?: string;
size: number;
type?: string;
encoding?: "base64";
tooLarge?: boolean;
}[];
comments: {
body: string;
@@ -107,9 +118,32 @@ export default class Gist {
}),
]);
let imageBudget = GIST_IMAGE_BUDGET;
const files = await Promise.all(Object.values(gistInfo.data.files || {})
.filter((f): f is NonNullable<typeof f> => !!f)
.map(async (f) => {
// Binary files cannot be anonymized as text, and UTF-8 decoding
// corrupts them: images keep their bytes as base64, others none.
if (f.filename && classifyByName(f.filename) === false) {
const size = f.size || 0;
const meta = { filename: f.filename, language: f.language || undefined, size, type: f.type || undefined, encoding: "base64" as const, content: "" };
if (!isImageFile(f.filename)) return meta;
// Reserve before the await so concurrent downloads share the budget.
if (size > GIST_IMAGE_LIMIT || size > imageBudget) return { ...meta, tooLarge: true };
imageBudget -= size;
if (!f.raw_url?.startsWith(GIST_RAW_ORIGIN)) return meta;
try {
const raw = await fetch(f.raw_url, { signal: AbortSignal.timeout(30000) });
if (!raw.ok) throw new Error(`status ${raw.status}`);
const bytes = Buffer.from(await raw.arrayBuffer());
if (bytes.length > GIST_IMAGE_LIMIT) return { ...meta, tooLarge: true };
return { ...meta, content: bytes.toString("base64") };
} catch (error) {
// One unreadable image must not make the whole gist unavailable.
logger.warn("gist image unavailable", { code: "gist_file_unavailable", errorType: error instanceof Error ? error.name : undefined });
return meta;
}
}
let content = (f as typeof f & { encoding?: string }).encoding === "base64"
? Buffer.from(f.content || "", "base64").toString("utf8")
: f.content || "";
@@ -335,13 +369,29 @@ export default class Gist {
output.ownerLogin = anonymizer.anonymize(g?.ownerLogin || "");
}
if (this.options.content) {
output.files = (g?.files || []).map((f) => ({
filename: anonymizer.anonymize(f.filename),
content: anonymizer.anonymize(f.content),
language: f.language,
size: f.size,
type: f.type,
}));
output.files = (g?.files || []).map((f) => {
if (f.encoding !== "base64") return {
filename: anonymizer.anonymize(f.filename),
content: anonymizer.anonymize(f.content),
language: f.language,
size: f.size,
type: f.type,
};
// Images follow "Display images" as in repositories (off unless set);
// other binaries are never served, even if stored by an older version.
const image = isImageFile(f.filename);
const hidden = image && !this.options.image;
return {
filename: anonymizer.anonymize(f.filename),
content: f.tooLarge || hidden || !image || !f.content ? undefined : f.content,
language: f.language,
size: f.size,
type: f.type,
encoding: "base64",
tooLarge: f.tooLarge || undefined,
hidden: hidden || undefined,
};
});
}
if (this.options.comments) {
output.comments = g?.comments?.map((comment) => {
@@ -417,6 +467,8 @@ export default class Gist {
language: f.language,
size: f.size,
type: f.type,
encoding: f.encoding,
tooLarge: f.tooLarge,
})),
comments: (g.comments || []).map((c) => ({
body: c.body,
+136 -1
View File
@@ -17,6 +17,48 @@ import { createLogger } from "./logger";
const logger = createLogger("pull-request");
type ReviewComment = NonNullable<IAnonymizedPullRequestDocument["pullRequest"]["reviewComments"]>[number];
/**
* Group inline review comments into threads: each reply joins the thread of the
* comment it answers. Threads keep the order of their first comment; GitHub
* comment ids never leave the server.
*/
export function reviewThreads(comments: ReviewComment[]) {
const threads: { path: string; line?: number; side?: "LEFT" | "RIGHT"; comments: ReviewComment[] }[] = [];
const byId = new Map<number, (typeof threads)[number]>();
const sorted = [...comments].sort((a, b) => new Date(a.creationDate).getTime() - new Date(b.creationDate).getTime());
for (const comment of sorted) {
let thread = comment.inReplyTo != null ? byId.get(comment.inReplyTo) : undefined;
if (!thread) {
thread = { path: comment.path, line: comment.line ?? undefined, side: comment.side, comments: [] };
threads.push(thread);
}
thread.comments.push(comment);
if (comment.commentId != null) byId.set(comment.commentId, thread);
}
return threads;
}
/**
* Remove what identifies people from a commit message before the term
* anonymizer runs: trailers (Signed-off-by, Co-authored-by, ...), e-mail
* addresses, and the fork owner in merge headlines. Without the origin option,
* merge headlines also lose their branch names.
*/
export function commitMessage(message: string, opts: { origin: boolean }) {
const lines = message.split(/\r?\n/)
.filter((line) => !/^\s*[A-Za-z][A-Za-z-]*-by\s*:/i.test(line))
.map((line) => line.replace(/<?[^\s<>@]+@[^\s<>@]+\.[^\s<>@]+>?/g, "").replace(/\s+$/, ""));
const merge = lines[0]?.match(/^Merge pull request (#\d+) from (\S+)/);
if (merge) lines[0] = opts.origin ? `Merge pull request ${merge[1]} from ${merge[2].replace(/^[^/]+\//, "")}` : `Merge pull request ${merge[1]}`;
else if (/^Merge (remote-tracking )?branch/.test(lines[0] || "")) {
lines[0] = opts.origin ? lines[0].replace(/ of \S+/, "") : "Merge branch";
}
while (lines.length && !lines[lines.length - 1].trim()) lines.pop();
return lines.join("\n");
}
export default class PullRequest {
private _model: IAnonymizedPullRequestDocument;
owner: User;
@@ -101,7 +143,40 @@ export default class PullRequest {
mediaType: { format: "diff" },
});
const [comments, diff] = await Promise.all([commentsPromise, diffPromise]);
// Commits and inline review comments are optional extras: a failure keeps
// the pull request readable without them.
const optional = <T>(label: string, promise: Promise<T[]>) =>
promise.catch((err): T[] => {
logger.warn(`PR ${label} unavailable, continuing without them`, {
code: `pr_${label.replace(/ /g, "_")}_unavailable`,
httpStatus: (err as { status?: number }).status,
pr: `${owner}/${repo}#${pull_number}`,
});
return [];
});
const commitsPromise = optional<{
commit?: { message?: string; author?: { date?: string } | null };
author?: { login?: string } | null;
}>("commits", oct.paginate("GET /repos/{owner}/{repo}/pulls/{pull_number}/commits", {
owner, repo, pull_number, per_page: 100,
}));
const reviewCommentsPromise = optional<{
id: number;
in_reply_to_id?: number;
path?: string;
line?: number | null;
side?: "LEFT" | "RIGHT" | null;
body?: string;
created_at: string;
updated_at: string;
user?: { login?: string } | null;
}>("review comments", oct.paginate("GET /repos/{owner}/{repo}/pulls/{pull_number}/comments", {
owner, repo, pull_number, per_page: 100,
}));
const [comments, diff, commits, reviewComments] = await Promise.all([
commentsPromise, diffPromise, commitsPromise, reviewCommentsPromise,
]);
this._model.pullRequest = {
diff: diff.data as unknown as string,
@@ -117,6 +192,28 @@ export default class PullRequest {
state: prInfo.data.state,
baseRepositoryFullName: prInfo.data.base.repo.full_name,
headRepositoryFullName: prInfo.data.head.repo?.full_name,
author: prInfo.data.user?.login || "",
baseRef: prInfo.data.base.ref,
headRef: prInfo.data.head.ref,
commits: commits.map((c) => ({
message: c.commit?.message || "",
author: c.author?.login || "",
date: c.commit?.author?.date ? new Date(c.commit.author.date) : undefined,
})),
reviewComments: reviewComments.map((c) => ({
commentId: c.id,
inReplyTo: c.in_reply_to_id,
path: c.path || "",
// An outdated comment has no line in the current diff; its
// original_line would point at an unrelated line, so it goes at the
// end of its file instead.
line: c.line ?? undefined,
side: c.line != null && c.side ? c.side : undefined,
body: c.body || "",
author: c.user?.login || "",
creationDate: new Date(c.created_at),
updatedDate: new Date(c.updated_at),
})),
comments: comments.map((comment) => ({
body: comment.body || "",
creationDate: new Date(comment.created_at),
@@ -362,8 +459,46 @@ export default class PullRequest {
return o;
});
}
if (this.options.username && this._model.pullRequest.author) {
output.author = anonymizer.anonymize(this._model.pullRequest.author);
}
// Branch names often carry a username or lab name ("asmith/fix"), so they
// are part of the origin, like the repository names.
if (this.options.origin) {
if (this._model.pullRequest.baseRef) output.baseRef = anonymizer.anonymize(this._model.pullRequest.baseRef);
if (this._model.pullRequest.headRef) output.headRef = anonymizer.anonymize(this._model.pullRequest.headRef);
}
if (this.options.diff) {
output.diff = anonymizer.anonymize(this._model.pullRequest.diff);
// Pull requests downloaded before commits were stored have none.
if (this._model.pullRequest.commits?.length) {
// No SHAs: a commit hash identifies the source repository.
output.commits = this._model.pullRequest.commits.map((commit) => {
const o: Record<string, unknown> = {
message: anonymizer.anonymize(commitMessage(commit.message || "", { origin: !!this.options.origin })),
};
if (this.options.username) o.author = anonymizer.anonymize(commit.author || "");
if (this.options.date) o.date = commit.date;
return o;
});
}
}
if (this.options.comments && this._model.pullRequest.reviewComments?.length) {
output.reviewComments = reviewThreads(this._model.pullRequest.reviewComments).map((thread) => ({
path: anonymizer.anonymize(thread.path),
line: thread.line,
side: thread.side,
comments: thread.comments.map((comment) => {
const o: Record<string, unknown> = {};
if (this.options.body) o.body = anonymizer.anonymize(comment.body);
if (this.options.username) o.author = anonymizer.anonymize(comment.author);
if (this.options.date) {
o.updatedDate = comment.updatedDate;
o.creationDate = comment.creationDate;
}
return o;
}),
}));
}
if (this.options.origin) {
output.baseRepositoryFullName =
+168
View File
@@ -0,0 +1,168 @@
import { subscribe } from "diagnostics_channel";
import { isIP } from "net";
import config from "../config";
import { logContext, LogContext } from "./log-context";
import { createLogger } from "./logger";
import { UPSTREAM_ENDPOINT_SEGMENTS } from "./log-schema";
const logger = createLogger("external-request");
// Literal path segments that may appear in an endpoint label. Every other
// segment becomes a placeholder, so a label never carries a repository, owner,
// file path, token or identifier.
const SEGMENTS = new Set(UPSTREAM_ENDPOINT_SEGMENTS);
// The segment after one of these is always an identifier.
const ID_AFTER = new Set(["users", "gists", "applications", "installations", "repositories", "pulls", "issues", "orgs", "commits", "branches"]);
// Anything below these is a ref or file path; only the endpoint matters.
const TAIL_AFTER = new Set(["contents", "trees", "blobs", "refs", "zipball", "tarball", "readme"]);
/** A fixed label for a GitHub endpoint, e.g. "/repos/{owner}/{repo}/contents/*". */
export function githubEndpoint(path: string): string {
const segments = path.split(/[?#]/, 1)[0].split("/").filter(Boolean);
const out: string[] = [];
for (let i = 0; i < segments.length && out.length < 8; i++) {
const segment = segments[i];
if (i === 0 && segment === "repos") { out.push("repos", "{owner}", "{repo}"); i += 2; continue; }
if (i > 0 && ID_AFTER.has(segments[i - 1]) && out[out.length - 1] === segments[i - 1]) { out.push("{id}"); continue; }
if (!SEGMENTS.has(segment)) { out.push("{id}"); continue; }
out.push(segment);
if (TAIL_AFTER.has(segment) && i < segments.length - 1) { out.push("*"); break; }
}
return "/" + out.join("/");
}
const KNOWN_HOSTS = ["github.com", "api.github.com", "codeload.github.com", "raw.githubusercontent.com",
"media.githubusercontent.com", "gist.githubusercontent.com", "objects.githubusercontent.com",
"cdn.jsdelivr.net", "api.resend.com", "api.stripe.com"];
const hostOf = (value: string | null | undefined): string | undefined => {
if (!value) return undefined;
try { return new URL(value).hostname.toLowerCase(); } catch { return undefined; }
};
// Config hosts are read on every request: parse each value once.
const configHosts = new Map<string, string | undefined>();
const configHost = (value: string | null | undefined) => {
if (!value) return undefined;
if (!configHosts.has(value)) configHosts.set(value, hostOf(value));
return configHosts.get(value);
};
/** Internal hops (streamer, databases, log store) are not external services. */
function isInternal(host: string): boolean {
const bare = host.replace(/^\[|\]$/g, "");
return !bare.includes(".") || isIP(bare) !== 0 || /\.(?:local|internal|localhost|svc|cluster\.local)$/.test(bare) ||
bare === configHost(config.STREAMER_ENTRYPOINT);
}
export interface ExternalRequest { method: string; host: string; path: string; status?: number; error?: unknown; ms: number; cancelled?: boolean }
// Transport codes the log schema keeps; others are folded into the closest one,
// so a record never loses its code (undici's UND_ERR_* are not in the schema).
const CODE_ALIASES: Record<string, string> = {
ECONNRESET: "ECONNRESET", ECONNREFUSED: "ECONNREFUSED", ETIMEDOUT: "ETIMEDOUT", ENOTFOUND: "ENOTFOUND", EPIPE: "EPIPE", ABORT_ERR: "ABORT_ERR",
UND_ERR_SOCKET: "ECONNRESET", ECONNABORTED: "ECONNRESET", UND_ERR_CLOSED: "ECONNRESET",
UND_ERR_CONNECT_TIMEOUT: "ETIMEDOUT", UND_ERR_HEADERS_TIMEOUT: "ETIMEDOUT", UND_ERR_BODY_TIMEOUT: "ETIMEDOUT",
EAI_AGAIN: "ENOTFOUND", UND_ERR_ABORTED: "ABORT_ERR",
};
/** The code logged for a failed outbound request. Our own cancellation is ABORT_ERR, never a reset. */
export function externalErrorCode(error: unknown, cancelled = false): string {
if (cancelled) return "ABORT_ERR";
const e = error as { code?: unknown; name?: unknown; cause?: { code?: unknown } } | null;
if (e?.name === "AbortError") return "ABORT_ERR";
if (e?.name === "TimeoutError") return "ETIMEDOUT";
const code = typeof e?.code === "string" ? e.code : typeof e?.cause?.code === "string" ? e.cause.code : undefined;
return (code && CODE_ALIASES[code]) || "upstream_error";
}
/** The record written for one outbound request, or null for an internal hop. */
export function externalRequestFields(request: ExternalRequest): Record<string, unknown> | null {
const host = request.host.toLowerCase().replace(/:\d+$/, "");
if (isInternal(host)) return null;
const method = request.method.toUpperCase();
const fields: Record<string, unknown> = {
upstreamMethod: ["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"].includes(method) ? method : "OTHER",
hostname: KNOWN_HOSTS.includes(host) ? host : host === configHost(config.S3_ENDPOINT) ? "storage" : "other",
ms: Math.round(request.ms),
};
if (host === "api.github.com" || host === "github.com") fields.upstreamEndpoint = githubEndpoint(request.path);
if (request.status !== undefined) fields.upstreamStatus = request.status;
if (request.error || request.cancelled) fields.code = externalErrorCode(request.error, request.cancelled);
return fields;
}
interface Pending { method: string; host: string; path: string; started: number; context?: LogContext; cancelled?: boolean }
const pending = new WeakMap<object, Pending>();
function finish(key: object, status?: number, error?: unknown) {
const entry = pending.get(key);
if (!entry) return;
pending.delete(key);
const fields = externalRequestFields({ ...entry, status, error, ms: performance.now() - entry.started });
if (!fields) return;
// Successful storage reads are as frequent as file views: keep them out of
// info. Failures and every other host stay at info.
const quiet = fields.hostname === "storage" && !fields.code && typeof status === "number" && status < 400;
// Diagnostics callbacks may run outside the caller's async context.
const log = () => quiet ? logger.debug("external request", fields) : logger.info("external request", fields);
if (entry.context) logContext.run(entry.context, log); else log();
}
let installed = false;
/** Log one record per outbound HTTP request (fetch and node:http clients). */
export function installExternalRequestLogging() {
if (installed) return;
installed = true;
const start = (key: object, method: string, host: string, path: string) =>
pending.set(key, { method, host, path, started: performance.now(), context: logContext.getStore() });
// Global fetch (Octokit, GitHub App and OAuth calls). The status is the one in
// the response headers: a body that fails later is not reported here.
subscribe("undici:request:create", (message) => {
const { request } = message as { request: { origin?: string | URL; method?: string; path?: string } };
const host = hostOf(String(request.origin ?? ""));
if (host) start(request, request.method || "GET", host, request.path || "/");
});
subscribe("undici:request:headers", (message) => {
const { request, response } = message as { request: object; response: { statusCode?: number } };
finish(request, response.statusCode);
});
subscribe("undici:request:error", (message) => {
const { request, error } = message as { request: object; error: unknown };
finish(request, undefined, error);
});
// node:http and node:https (got, the Stripe and AWS clients). The record is
// written when the body ends, so a stream cut after its headers is a failure,
// not a 200; a request we destroy ourselves is a cancellation (ABORT_ERR).
type ClientRequest = { method?: string; host?: string; path?: string; destroy: (error?: Error) => unknown };
subscribe("http.client.request.start", (message) => {
const { request } = message as { request: ClientRequest };
if (!request.host) return;
start(request, request.method || "GET", request.host, request.path || "/");
const destroy = request.destroy;
request.destroy = function (this: ClientRequest, error?: Error) {
const entry = pending.get(request);
// Node destroys the request itself after a socket error; that path
// passes the error, which keeps its own code.
if (entry && (!error || (error as { name?: string }).name === "AbortError")) entry.cancelled = true;
return destroy.call(this, error);
};
});
subscribe("http.client.response.finish", (message) => {
const { request, response } = message as {
request: object;
response: { statusCode?: number; complete?: boolean; once: (event: string, listener: () => void) => unknown };
};
const status = response.statusCode;
response.once("end", () => finish(request, status));
response.once("close", () => {
if (response.complete) return finish(request, status);
const entry = pending.get(request);
finish(request, status, entry?.cancelled ? undefined : Object.assign(new Error("response body incomplete"), { code: "ECONNRESET" }));
});
});
subscribe("http.client.request.error", (message) => {
const { request, error } = message as { request: object; error: unknown };
finish(request, undefined, error);
});
}
+34
View File
@@ -105,6 +105,7 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
"expire",
"getAccess",
"getToken",
"isImageFile",
"markExpired",
"remove",
"resetSate",
@@ -125,6 +126,7 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
"expire",
"getAccess",
"getToken",
"isImageFile",
"markExpired",
"remove",
"resetSate",
@@ -174,6 +176,7 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
"<anonymous>",
"anonymize",
"check",
"commitMessage",
"conference",
"content",
"countView",
@@ -182,8 +185,10 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
"expire",
"getToken",
"markExpired",
"optional",
"remove",
"resetSate",
"reviewThreads",
"toJSON",
"updateIfNeeded",
"updateStatus"
@@ -192,6 +197,7 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
"<anonymous>",
"anonymize",
"check",
"commitMessage",
"conference",
"content",
"countView",
@@ -200,8 +206,10 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
"expire",
"getToken",
"markExpired",
"optional",
"remove",
"resetSate",
"reviewThreads",
"toJSON",
"updateIfNeeded",
"updateStatus"
@@ -908,6 +916,32 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
"get",
"set"
],
"src/core/external-request-logging.ts": [
"<anonymous>",
"configHost",
"externalErrorCode",
"externalRequestFields",
"finish",
"githubEndpoint",
"hostOf",
"installExternalRequestLogging",
"isInternal",
"log",
"start"
],
"build/core/external-request-logging.js": [
"<anonymous>",
"configHost",
"externalErrorCode",
"externalRequestFields",
"finish",
"githubEndpoint",
"hostOf",
"installExternalRequestLogging",
"isInternal",
"log",
"start"
],
"src/core/file-submodules.ts": [
"<anonymous>",
"hasVisibleSubmodules"
+9 -3
View File
@@ -2,7 +2,7 @@ import { ANONYMIZATION_ERRORS } from "./anonymization-errors";
import { requestReproduction, safeReproductionPath } from "./log-reproduction";
import { safeDiagnosticFields, errorDiagnostics } from "./log-diagnostics";
import { LOG_ROUTES, LOG_THROWN_ERROR_CODES } from "./log-diagnostic-schema";
import { LOG_MODULES, ERROR_CODES, LOG_EVENTS } from "./log-schema";
import { LOG_MODULES, ERROR_CODES, LOG_EVENTS, UPSTREAM_ENDPOINT_SEGMENTS } from "./log-schema";
import { randomUUID } from "crypto";
import { logContext, logIdentity, validTraceId } from "./log-context";
@@ -25,6 +25,9 @@ export const LOG_ERROR_CODES: ReadonlySet<string> = new Set([
"ECONNRESET", "ECONNREFUSED", "ETIMEDOUT", "ENOTFOUND", "EPIPE", "ABORT_ERR",
"upstream_error", "upstream_timeout", "invalid_signature", "webhook_processing_failed",
]);
const UPSTREAM_HOSTS = ["github.com", "api.github.com", "codeload.github.com", "raw.githubusercontent.com", "media.githubusercontent.com",
"gist.githubusercontent.com", "objects.githubusercontent.com", "cdn.jsdelivr.net", "api.resend.com", "api.stripe.com", "storage"];
const UPSTREAM_ENDPOINT = new RegExp(`^/(?:(?:${UPSTREAM_ENDPOINT_SEGMENTS.join("|")}|\\{owner\\}|\\{repo\\}|\\{id\\}|\\*)(?:/|$)){0,8}$`);
export const LOG_NUMBERS = ["memoryUsedBytes", "memoryFileCacheBytes", "memoryWorkingSetBytes", "memoryWorkingSetRatio", "quotaUsedRepositories", "quotaRepositoryLimit", "quotaUsedBytes", "quotaRequestedBytes", "quotaProjectedBytes", "quotaStorageLimit", "restartMs", "exitCode","droppedLogsInterval","expectedBytes", "measuredMs", "unattributedMs", "overlapMs","status", "httpStatus", "ms", "firstByteMs", "responseMs", "bytes", "bytesPerSecond",
"attempt", "rss", "memoryLimitBytes", "memoryRatio", "uptime", "activeRequests", "waiting", "active", "delayed", "failed",
"oldestWaitingMs", "droppedLogs", "loopP95Ms", "upstreamStatus"];
@@ -33,7 +36,7 @@ export function logRecord(level: string, module: string, args: unknown[]) {
const context = logContext.getStore() || {};
const details: Record<string, unknown> = {};
const keys = [...LOG_NUMBERS, "requestId", "jobId", "hopId", "parentHopId", "deploymentId", "deploymentOperation", "deploymentPhase", "deploymentOutcome", "cancellationOrigin", "cancellationEvidence", "endpointKind", "stageCounts", "stageOpen", "code", "message", "outcome", "method", "route", "queue",
"errorType", "errorStack", "causeType", "causeStack", "requestPath", "repoId", "stages", "reason", "phase", "event", "deliveryId", "hostname", "service"];
"errorType", "errorStack", "causeType", "causeStack", "requestPath", "repoId", "stages", "reason", "phase", "event", "deliveryId", "hostname", "service", "upstreamMethod", "upstreamEndpoint"];
// Do not traverse arbitrary objects or invoke error getters while logging.
for (const arg of args.slice(0, 8)) if (arg && typeof arg === "object") {
for (const key of keys) {
@@ -64,12 +67,15 @@ export function logRecord(level: string, module: string, args: unknown[]) {
if (allowed(["parse", "find_grant_owners", "reconcile_grant", "persist_installation_block", "reconcile_installation"], details.phase)) record.phase = details.phase;
if (allowed(["github_app_authorization", "installation", "installation_repositories"], details.event)) record.webhookEvent = details.event;
if (validTraceId(details.deliveryId)) record.deliveryId = details.deliveryId;
if (allowed(["github.com", "api.github.com", "codeload.github.com", "raw.githubusercontent.com", "media.githubusercontent.com"], details.hostname)) record.upstreamHost = details.hostname;
if (allowed(UPSTREAM_HOSTS, details.hostname)) record.upstreamHost = details.hostname;
else if (details.hostname) record.upstreamHost = "other";
for (const [key, values] of Object.entries({ deploymentOperation: ["deploy", "rollback"], deploymentPhase: ["start", "restart", "finish"], deploymentOutcome: ["started", "completed", "failed", "unchanged"], cancellationOrigin: ["unknown", "api", "streamer", "timeout", "upstream"],
cancellationEvidence: ["response_close", "request_aborted", "upstream_error", "timeout", "local_abort"], endpointKind: ["public", "internal"] })) {
if (allowed(values, details[key])) record[key] = details[key];
}
if (allowed(["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "OTHER"], details.upstreamMethod)) record.upstreamMethod = details.upstreamMethod;
// Built only from literal segments and placeholders (see githubEndpoint).
if (typeof details.upstreamEndpoint === "string" && UPSTREAM_ENDPOINT.test(details.upstreamEndpoint)) record.upstreamEndpoint = details.upstreamEndpoint;
if (allowed(["completed", "interrupted"], details.outcome)) record.outcome = details.outcome;
if (allowed(["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "OTHER"], details.method)) record.method = details.method;
// Only fixed route labels survive; never raw URLs or request parameters.
+5 -1
View File
@@ -1,5 +1,5 @@
// Reviewed literal diagnostics. Never extend this list from runtime data.
export const LOG_MODULES = ["admin", "anonymized-file", "auth", "billing", "dailyStats", "file-tree", "fs", "gh-stream", "gist", "github", "github-app-webhook", "owner-notifications", "process", "pull-request", "queue", "queue:cache", "queue:download", "queue:remove", "repository", "repository-public", "requests", "route", "route:repo", "s3", "schedule", "server", "streamer", "temporary-storage", "token-auth", "user", "zip-stream"];
export const LOG_MODULES = ["admin", "anonymized-file", "auth", "billing", "dailyStats", "external-request", "file-tree", "fs", "gh-stream", "gist", "github", "github-app-webhook", "owner-notifications", "process", "pull-request", "queue", "queue:cache", "queue:download", "queue:remove", "repository", "repository-public", "requests", "route", "route:repo", "s3", "schedule", "server", "streamer", "temporary-storage", "token-auth", "user", "zip-stream"];
export const ERROR_CODES = ["billing_address_missing", "billing_city_missing", "billing_country_missing", "billing_email_missing", "billing_missing", "billing_name_missing", "billing_zip_missing", "branch_not_found", "branch_not_specified", "cache_busy", "cache_miss", "cannot_coauthor_self", "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", "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_found", "gist_not_ready", "github_app_access_required", "github_identity_mismatch", "github_rate_limit_exceeded", "github_user_not_found", "invalid_commit_format", "invalid_cursor", "invalid_file_path", "invalid_gistId", "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", "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_found", "pull_request_not_ready", "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_changed", "repository_expired", "repository_job_cancelled", "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", "submodule_not_available", "terms_not_specified", "token_expired", "token_limit_reached", "unable_to_connect_user", "unable_to_download", "upstream_error", "user_not_found", "username_not_defined"];
export const LOG_EVENTS: Record<string, string> = {
"quota admission denied": "quota_denied",
@@ -31,6 +31,7 @@ export const LOG_EVENTS: Record<string, string> = {
"duplicate Stripe customer requires review": "duplicate_stripe_customer_requires_review",
"ensureTodaySnapshot failed": "ensuretodaysnapshot_failed",
"error log redis connect failed": "error_log_redis_connect_failed",
"external request": "external_request",
"expired repository cleanup failed": "expired_repository_cleanup_failed",
"failed removal recovery failed": "failed_removal_recovery_failed",
"failed to persist ERROR status": "failed_to_persist_error_status",
@@ -120,3 +121,6 @@ export const LOG_EVENTS: Record<string, string> = {
"write failed": "write_failed",
"zip stream failed": "zip_stream_failed"
};
// Literal path segments allowed in an external endpoint label (see githubEndpoint).
export const UPSTREAM_ENDPOINT_SEGMENTS = ["repos", "contents", "commits", "branches", "readme", "pages", "zipball", "tarball", "git", "trees", "blobs", "refs", "pulls", "issues", "comments", "user", "emails", "installations", "installation", "repositories", "applications", "token", "grant", "app", "access_tokens", "gists", "rate_limit", "users", "login", "oauth", "access_token", "authorizations", "orgs", "members", "collaborators", "releases", "languages"];
@@ -60,6 +60,9 @@ const AnonymizedGistSchema = new Schema({
// nested `{ type: String }` the whole object is compiled as an array
// of strings and file objects are silently dropped on save.
type: { type: String },
// Binary files are listed; only images keep their bytes, as base64.
encoding: String,
tooLarge: Boolean,
},
],
comments: [
@@ -42,6 +42,8 @@ export interface IAnonymizedGist {
language?: string;
size?: number;
type?: string;
encoding?: "base64";
tooLarge?: boolean;
}[];
comments?: {
body: string;
@@ -59,6 +59,32 @@ const AnonymizedPullRequestSchema = new Schema({
state: String,
baseRepositoryFullName: String,
headRepositoryFullName: String,
author: String,
baseRef: String,
headRef: String,
commits: [
{
_id: false,
message: String,
author: String,
date: Date,
},
],
reviewComments: [
{
_id: false,
commentId: Number,
inReplyTo: Number,
path: String,
line: Number,
/** LEFT: a removed line (old numbering); RIGHT: an added or context line. */
side: String,
body: String,
author: String,
creationDate: Date,
updatedDate: Date,
},
],
comments: [
{
body: String,
@@ -45,6 +45,25 @@ export interface IAnonymizedPullRequest {
state?: string;
baseRepositoryFullName?: string;
headRepositoryFullName?: string;
author?: string;
baseRef?: string;
headRef?: string;
commits?: {
message: string;
author: string;
date?: Date;
}[];
reviewComments?: {
commentId: number;
inReplyTo?: number;
path: string;
line?: number;
side?: "LEFT" | "RIGHT";
body: string;
author: string;
creationDate: Date;
updatedDate: Date;
}[];
comments?: {
body: string;
creationDate: Date;
+2
View File
@@ -1,5 +1,6 @@
import { logMemory } from "./log-memory";
import { createLogger, serializeError, reportOutputDrops } from "./logger";
import { installExternalRequestLogging } from "./external-request-logging";
/** Observe fatal errors without overriding Node's default exit behavior. */
export function installFatalErrorLogging(service: "api" | "streamer") {
@@ -8,6 +9,7 @@ export function installFatalErrorLogging(service: "api" | "streamer") {
...serializeError(error), code: "process_fatal_error", service, origin,
});
logger.info("process started", { service });
installExternalRequestLogging();
const heartbeat = setInterval(() => {
void logMemory().then(memory => reportOutputDrops(drops => logger.info("process heartbeat", {
service, uptime: process.uptime(), ...memory, ...drops })));
+3
View File
@@ -4,8 +4,11 @@ import { SandboxedJob } from "bullmq";
import { logContext, validProjectId, validTraceId, validUserId } from "../core/log-context";
import { createLogger, reportOutputDrops } from "../core/logger";
import type { RepoJobData } from "./index";
import { installExternalRequestLogging } from "../core/external-request-logging";
const logger = createLogger("queue");
export function loggedJob(queue: "download" | "remove" | "cache", work: (job: SandboxedJob<RepoJobData, void>) => Promise<void>) {
// Sandboxed processors run in their own process.
installExternalRequestLogging();
return (job: SandboxedJob<RepoJobData, void>) => logContext.run({
service: "worker", jobId: validTraceId(job.data.logJobId) ? job.data.logJobId : randomUUID(),
requestId: validTraceId(job.data.requestId) ? job.data.requestId : undefined,
+1 -1
View File
@@ -5,7 +5,7 @@ import { LOG_EVENTS } from "../core/log-schema";
import { LOG_ROUTES } from "../core/log-diagnostic-schema";
const services = ["api", "streamer", "worker", "nginx", "mongodb", "redis", "backup"];
const events = new Set([...Object.values(LOG_EVENTS), "deployment", "application_log", "webhook_log", "request_completed", "request_slow", "request_cancelled", "process_fatal_error", "process_started", "process_heartbeat", "job_started", "job_completed", "job_failed", "job_stalled", "queue_heartbeat", "edge_request", "infrastructure_log"]);
const events = new Set([...Object.values(LOG_EVENTS), "deployment", "application_log", "webhook_log", "request_completed", "request_slow", "request_cancelled", "process_fatal_error", "process_started", "process_heartbeat", "job_started", "job_completed", "job_failed", "job_stalled", "queue_heartbeat", "edge_request", "infrastructure_log", "external_request"]);
const windows: Record<string, number> = { "15m": 15, "1h": 60, "6h": 360, "24h": 1440 };
let active = 0;
export class InvalidLogQuery extends Error {}