mirror of
https://github.com/tdurieux/anonymous_github.git
synced 2026-12-02 09:03:37 +01:00
Merge pull request #990 from tdurieux/feat/external-request-logs
feat(logging): log each GitHub and external call with its status
This commit is contained in:
9 files changed
+390
-8
No files matched your search
@@ -43,11 +43,13 @@ if service == "mongodb" {
|
||||
if is_string(record.release) && match(string!(record.release), r'^[a-f0-9]{7,40}$') { out.release = record.release }
|
||||
if is_string(record.instance) && match(string!(record.instance), r'^[a-f0-9-]{36}$') { out.instance = record.instance }
|
||||
if includes(["repo_renamed", "preparation_interrupted", "commit_not_found", "zip_not_available", "ABORT_ERR", "ECONNREFUSED", "ECONNRESET", "ENOTFOUND", "EPIPE", "ETIMEDOUT", "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_app_reconnect_required", "github_identity_mismatch", "github_rate_limit_exceeded", "github_token_invalid", "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_signature", "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", "token_refresh_failed", "anonymized_output_too_large", "anonymization_memory_budget_exceeded", "anonymization_queue_full", "anonymization_queue_timeout", "anonymization_cancelled", "anonymization_worker_exited", "anonymization_deadline_exceeded", "anonymization_spool_budget_exceeded", "anonymization_worker_failed", "anonymization_storage_full", "anonymization_io_failed", "zip_unsafe_entry_path", "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_changed", "repository_expired", "repository_job_cancelled", "repository_not_found", "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", "upstream_timeout", "user_not_found", "username_not_defined", "webhook_processing_failed", "another_login_required", "billing_already_paid", "billing_busy", "billing_checkout_disabled", "billing_checkout_in_progress", "billing_customer_mismatch", "billing_draft_not_found", "billing_invalid_conference", "billing_invalid_draft", "billing_invalid_purchase", "billing_invalid_repository_size", "billing_invalid_review_window", "billing_plan_change_not_supported", "billing_plan_unavailable", "billing_price_misconfigured", "billing_recovery_required", "billing_review_window_locked", "billing_subscription_exists", "billing_unavailable", "conference_payment_required", "gist_not_available", "github_app_authorization_cancelled", "github_app_disabled", "github_app_permissions_invalid", "github_app_refresh_busy", "github_grant_revocation_failed", "github_oauth_required", "github_unavailable", "invalid_auth_state", "invalid_billing_expiration", "invalid_connection", "invalid_github_path", "not_owner", "oauth_resources_remaining", "pull_request_not_available", "repository_busy", "repository_not_accessible", "streamer_unreachable", "streamer_upstream_error", "subscription_required_for_never_expiration", "user_banned", "sync_failed", "streamer_route_not_found", "streamer_unexpected_response"], record.errorCode) { out.errorCode = record.errorCode }
|
||||
if includes(["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"], record.module) { out.module = record.module }
|
||||
if includes(["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"], record.module) { out.module = record.module }
|
||||
if includes(["protocol", "credentials", "port", "host"], record.reason) { out.reason = record.reason }
|
||||
if includes(["parse", "find_grant_owners", "reconcile_grant", "persist_installation_block", "reconcile_installation"], record.phase) { out.phase = record.phase }
|
||||
if includes(["github_app_authorization", "installation", "installation_repositories"], record.webhookEvent) { out.webhookEvent = record.webhookEvent }
|
||||
if includes(["github.com", "api.github.com", "codeload.github.com", "raw.githubusercontent.com", "media.githubusercontent.com", "other"], record.upstreamHost) { out.upstreamHost = record.upstreamHost }
|
||||
if includes(["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", "other"], record.upstreamHost) { out.upstreamHost = record.upstreamHost }
|
||||
if includes(["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "OTHER"], record.upstreamMethod) { out.upstreamMethod = record.upstreamMethod }
|
||||
if is_string(record.upstreamEndpoint) && match(string!(record.upstreamEndpoint), r'^/(?:(?: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|\{owner\}|\{repo\}|\{id\}|\*)(?:/|$)){0,8}$') { out.upstreamEndpoint = record.upstreamEndpoint }
|
||||
if includes(["download", "remove", "cache"], record.queue) { out.queue = record.queue }
|
||||
if includes(["unknown", "api", "streamer", "timeout", "upstream"], record.cancellationOrigin) { out.cancellationOrigin = record.cancellationOrigin }
|
||||
if includes(["response_close", "request_aborted", "upstream_error", "timeout", "local_abort"], record.cancellationEvidence) { out.cancellationEvidence = record.cancellationEvidence }
|
||||
@@ -81,7 +83,7 @@ if includes(["/", "other", "/dashboard", "/anonymize", "/healthcheck", "/api/hea
|
||||
}
|
||||
}
|
||||
# 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","markExpired","remove","resetSate","toJSON","updateIfNeeded","updateStatus"],"build/core/Gist.js":["<anonymous>","anonymize","check","conference","content","countView","download","downloadContent","downloadWithAccess","expire","getAccess","getToken","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","conference","content","countView","download","downloadContent","expire","getToken","markExpired","remove","resetSate","toJSON","updateIfNeeded","updateStatus"],"build/core/PullRequest.js":["<anonymous>","anonymize","check","conference","content","countView","download","downloadContent","expire","getToken","markExpired","remove","resetSate","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>","anonymizationErrorCode","data"],"build/core/anonymization-errors.js":["<anonymous>","anonymizationErrorCode","data"],"srLine 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) }
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
}
|
||||
@@ -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,28 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
|
||||
"get",
|
||||
"set"
|
||||
],
|
||||
"src/core/external-request-logging.ts": [
|
||||
"<anonymous>",
|
||||
"externalRequestFields",
|
||||
"finish",
|
||||
"githubEndpoint",
|
||||
"hostOf",
|
||||
"installExternalRequestLogging",
|
||||
"isInternal",
|
||||
"log",
|
||||
"start"
|
||||
],
|
||||
"build/core/external-request-logging.js": [
|
||||
"<anonymous>",
|
||||
"externalRequestFields",
|
||||
"finish",
|
||||
"githubEndpoint",
|
||||
"hostOf",
|
||||
"installExternalRequestLogging",
|
||||
"isInternal",
|
||||
"log",
|
||||
"start"
|
||||
],
|
||||
"src/core/file-submodules.ts": [
|
||||
"<anonymous>",
|
||||
"hasVisibleSubmodules"
|
||||
|
||||
@@ -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, 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", "stages", "reason", "phase", "event", "deliveryId", "hostname", "service"];
|
||||
"errorType", "errorStack", "causeType", "causeStack", "requestPath", "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.
|
||||
|
||||
@@ -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"];
|
||||
@@ -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 })));
|
||||
|
||||
@@ -4,8 +4,11 @@ import { SandboxedJob } from "bullmq";
|
||||
import { logContext, validTraceId } 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,
|
||||
|
||||
@@ -4,7 +4,7 @@ import { logContext, validTraceId } from "../core/log-context";
|
||||
import { LOG_EVENTS } from "../core/log-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 {}
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
const { strict: assert } = require("node:assert");
|
||||
const http = require("node:http");
|
||||
const { randomUUID } = require("node:crypto");
|
||||
const { setTimeout } = require("node:timers");
|
||||
const { Agent } = require("undici");
|
||||
const got = require("got");
|
||||
require("ts-node/register/transpile-only");
|
||||
const { logContext } = require("../src/core/log-context");
|
||||
const { installExternalRequestLogging, githubEndpoint, externalErrorCode } = require("../src/core/external-request-logging");
|
||||
|
||||
const localAgent = new http.Agent({ lookup: (host, options, callback) => lookup(host, options, callback) });
|
||||
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
// Resolve every name to the local fixture so requests look like they go to GitHub.
|
||||
const lookup = (_host, options, callback) => {
|
||||
if (typeof options === "function") callback = options;
|
||||
if (options && options.all) callback(null, [{ address: "127.0.0.1", family: 4 }]);
|
||||
else callback(null, "127.0.0.1", 4);
|
||||
};
|
||||
|
||||
async function captureLogs(run) {
|
||||
const records = [];
|
||||
const write = process.stdout.write;
|
||||
process.stdout.write = function (chunk, ...rest) {
|
||||
for (const line of String(chunk).split("\n")) {
|
||||
try { const record = JSON.parse(line); if (record && record.severity) { records.push(record); continue; } } catch { /* not a record */ }
|
||||
if (line) write.call(process.stdout, line + "\n");
|
||||
}
|
||||
const callback = rest.find((arg) => typeof arg === "function");
|
||||
if (callback) callback();
|
||||
return true;
|
||||
};
|
||||
try { await run(); await wait(50); } finally { process.stdout.write = write; }
|
||||
return records.filter((record) => record.event === "external_request");
|
||||
}
|
||||
|
||||
describe("external request logging", function () {
|
||||
this.timeout(10000);
|
||||
let server, port;
|
||||
before(async () => {
|
||||
installExternalRequestLogging();
|
||||
server = http.createServer((req, res) => {
|
||||
req.resume();
|
||||
if (req.url.startsWith("/login/oauth")) { res.writeHead(200, { "content-type": "application/json" }); res.end("{}"); return; }
|
||||
if (req.url.startsWith("/slow")) return; // never answers
|
||||
if (req.url.startsWith("/reset")) { req.socket.destroy(); return; }
|
||||
if (req.url.startsWith("/cut")) { res.writeHead(200, { "content-length": "100" }); res.write("partial"); setTimeout(() => req.socket.destroy(), 20); return; }
|
||||
res.writeHead(404, { "content-type": "application/json" });
|
||||
res.end(JSON.stringify({ message: "Not Found" }));
|
||||
});
|
||||
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
port = server.address().port;
|
||||
});
|
||||
after(() => new Promise((resolve) => server.close(resolve)));
|
||||
|
||||
it("labels GitHub endpoints without owners, repositories, paths or identifiers", () => {
|
||||
assert.equal(githubEndpoint("/repos/secret-owner/secret-repo/contents/private/notes.md?ref=main"), "/repos/{owner}/{repo}/contents/*");
|
||||
assert.equal(githubEndpoint("/repos/secret-owner/secret-repo"), "/repos/{owner}/{repo}");
|
||||
assert.equal(githubEndpoint("/repos/o/r/git/trees/abc123?recursive=1"), "/repos/{owner}/{repo}/git/trees/*");
|
||||
assert.equal(githubEndpoint("/repos/o/r/pulls/12"), "/repos/{owner}/{repo}/pulls/{id}");
|
||||
assert.equal(githubEndpoint("/user/repos?per_page=100&page=2"), "/user/repos");
|
||||
assert.equal(githubEndpoint("/applications/Iv1.client/token"), "/applications/{id}/token");
|
||||
assert.equal(githubEndpoint("/app/installations/42/access_tokens"), "/app/installations/{id}/access_tokens");
|
||||
assert.equal(githubEndpoint("/login/oauth/access_token"), "/login/oauth/access_token");
|
||||
assert.equal(githubEndpoint("/secret-owner/secret-repo.git/info/refs"), "/{id}/{id}/{id}/refs");
|
||||
});
|
||||
|
||||
it("keeps only fixed endpoint labels in the logger and the collector", () => {
|
||||
const { logRecord } = require("../src/core/log-record");
|
||||
const { UPSTREAM_ENDPOINT_SEGMENTS } = require("../src/core/log-schema");
|
||||
const endpoint = (value) => logRecord("info", "external-request", ["external request", { upstreamEndpoint: value }]).upstreamEndpoint;
|
||||
assert.equal(endpoint("/repos/{owner}/{repo}/contents/*"), "/repos/{owner}/{repo}/contents/*");
|
||||
assert.equal(endpoint("/repos/secretowner/secretrepo"), undefined);
|
||||
assert.equal(endpoint("/user/reposx"), undefined);
|
||||
const vrl = require("node:fs").readFileSync(require("node:path").join(__dirname, "../deploy/logging/sanitize.vrl"), "utf8");
|
||||
const segments = /record\.upstreamEndpoint\), r'\^\/\(\?:\(\?:([a-z_|]+)\|/.exec(vrl);
|
||||
assert.ok(segments, "collector rule for upstreamEndpoint");
|
||||
assert.deepEqual(segments[1].split("|"), UPSTREAM_ENDPOINT_SEGMENTS);
|
||||
});
|
||||
|
||||
it("logs a got request to GitHub with its status and the caller's requestId", async () => {
|
||||
const requestId = randomUUID();
|
||||
let status;
|
||||
const records = await captureLogs(() => logContext.run({ requestId }, async () => {
|
||||
const response = await got(`http://api.github.com:${port}/repos/secret-owner/secret-repo/contents/private.md?ref=main`,
|
||||
{ agent: { http: localAgent }, throwHttpErrors: false, retry: 0 });
|
||||
status = response.statusCode;
|
||||
}));
|
||||
assert.equal(status, 404);
|
||||
assert.equal(records.length, 1, JSON.stringify(records));
|
||||
assert.equal(records[0].severity, "info");
|
||||
assert.equal(records[0].requestId, requestId);
|
||||
assert.equal(records[0].upstreamHost, "api.github.com");
|
||||
assert.equal(records[0].upstreamMethod, "GET");
|
||||
assert.equal(records[0].upstreamStatus, 404);
|
||||
assert.equal(records[0].upstreamEndpoint, "/repos/{owner}/{repo}/contents/*");
|
||||
assert.equal(typeof records[0].ms, "number");
|
||||
assert.ok(!JSON.stringify(records).includes("secret"), JSON.stringify(records));
|
||||
});
|
||||
|
||||
it("logs a fetch request (the Octokit transport)", async () => {
|
||||
const requestId = randomUUID();
|
||||
const records = await captureLogs(() => logContext.run({ requestId }, async () => {
|
||||
const response = await globalThis.fetch(`http://github.com:${port}/login/oauth/access_token?code=secret-code`,
|
||||
{ method: "POST", body: "client_secret=secret", dispatcher: new Agent({ connect: { lookup } }) });
|
||||
await response.text();
|
||||
}));
|
||||
assert.equal(records.length, 1, JSON.stringify(records));
|
||||
assert.equal(records[0].requestId, requestId);
|
||||
assert.equal(records[0].upstreamHost, "github.com");
|
||||
assert.equal(records[0].upstreamMethod, "POST");
|
||||
assert.equal(records[0].upstreamStatus, 200);
|
||||
assert.equal(records[0].upstreamEndpoint, "/login/oauth/access_token");
|
||||
assert.ok(!JSON.stringify(records).includes("secret"), JSON.stringify(records));
|
||||
});
|
||||
|
||||
it("logs a connection failure with its code and no status", async () => {
|
||||
const closed = http.createServer();
|
||||
await new Promise((resolve) => closed.listen(0, "127.0.0.1", resolve));
|
||||
const closedPort = closed.address().port;
|
||||
await new Promise((resolve) => closed.close(resolve));
|
||||
const records = await captureLogs(() => got(`http://codeload.github.com:${closedPort}/o/r/zip/main`,
|
||||
{ agent: { http: localAgent }, retry: 0 }).catch(() => undefined));
|
||||
assert.equal(records.length, 1, JSON.stringify(records));
|
||||
assert.equal(records[0].upstreamHost, "codeload.github.com");
|
||||
assert.equal(records[0].errorCode, "ECONNREFUSED");
|
||||
assert.equal(records[0].upstreamStatus, undefined);
|
||||
assert.equal(records[0].upstreamEndpoint, undefined);
|
||||
});
|
||||
|
||||
it("logs our own cancellation as ABORT_ERR, not a reset by GitHub", async () => {
|
||||
const records = await captureLogs(async () => {
|
||||
const stream = got.stream(`http://api.github.com:${port}/slow`, { agent: { http: localAgent }, retry: 0 });
|
||||
stream.on("error", () => {});
|
||||
await wait(50);
|
||||
stream.destroy();
|
||||
});
|
||||
assert.equal(records.length, 1, JSON.stringify(records));
|
||||
assert.equal(records[0].errorCode, "ABORT_ERR");
|
||||
});
|
||||
|
||||
it("keeps a code for undici socket errors", async () => {
|
||||
const records = await captureLogs(() => globalThis.fetch(`http://api.github.com:${port}/reset`,
|
||||
{ dispatcher: new Agent({ connect: { lookup } }) }).catch(() => undefined));
|
||||
assert.equal(records.length, 1, JSON.stringify(records));
|
||||
assert.equal(records[0].errorCode, "ECONNRESET");
|
||||
assert.equal(externalErrorCode({ code: "UND_ERR_HEADERS_TIMEOUT" }), "ETIMEDOUT");
|
||||
assert.equal(externalErrorCode({ code: "EAI_AGAIN" }), "ENOTFOUND");
|
||||
assert.equal(externalErrorCode({ code: "SOMETHING_NEW" }), "upstream_error");
|
||||
assert.equal(externalErrorCode({ name: "AbortError" }), "ABORT_ERR");
|
||||
});
|
||||
|
||||
it("reports a body cut after its headers as a failure, not a 200", async () => {
|
||||
const records = await captureLogs(() => got(`http://codeload.github.com:${port}/cut`,
|
||||
{ agent: { http: localAgent }, retry: 0 }).catch(() => undefined));
|
||||
assert.equal(records.length, 1, JSON.stringify(records));
|
||||
assert.equal(records[0].upstreamStatus, 200);
|
||||
assert.equal(records[0].errorCode, "ECONNRESET");
|
||||
});
|
||||
|
||||
it("skips internal hops such as the streamer", async () => {
|
||||
const records = await captureLogs(async () => {
|
||||
await got(`http://127.0.0.1:${port}/api/file`, { throwHttpErrors: false, retry: 0 });
|
||||
await got(`http://streamer:${port}/api/file`, { agent: { http: localAgent }, throwHttpErrors: false, retry: 0 });
|
||||
});
|
||||
assert.deepEqual(records, []);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user