diff --git a/src/core/external-request-logging.ts b/src/core/external-request-logging.ts index 7737c66..9bc22fb 100644 --- a/src/core/external-request-logging.ts +++ b/src/core/external-request-logging.ts @@ -39,15 +39,40 @@ 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(); +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 === hostOf(config.STREAMER_ENTRYPOINT); + bare === configHost(config.STREAMER_ENTRYPOINT); } -export interface ExternalRequest { method: string; host: string; path: string; status?: number; error?: unknown; ms: number } +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 = { + 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 | null { @@ -56,19 +81,16 @@ export function externalRequestFields(request: ExternalRequest): Record = { upstreamMethod: ["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"].includes(method) ? method : "OTHER", - hostname: KNOWN_HOSTS.includes(host) ? host : host === hostOf(config.S3_ENDPOINT) ? "storage" : "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) { - const code = (request.error as { code?: unknown }).code; - fields.code = typeof code === "string" ? code : "upstream_error"; - } + 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 } +interface Pending { method: string; host: string; path: string; started: number; context?: LogContext; cancelled?: boolean } const pending = new WeakMap(); function finish(key: object, status?: number, error?: unknown) { @@ -77,8 +99,11 @@ function finish(key: object, status?: number, error?: unknown) { 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 = () => logger.info("external request", fields); + const log = () => quiet ? logger.debug("external request", fields) : logger.info("external request", fields); if (entry.context) logContext.run(entry.context, log); else log(); } @@ -90,7 +115,8 @@ export function installExternalRequestLogging() { 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). + // 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 ?? "")); @@ -105,14 +131,35 @@ export function installExternalRequestLogging() { finish(request, undefined, error); }); - // node:http and node:https (got, the Stripe and AWS clients). + // 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: { method?: string; host?: string; path?: string } }; - if (request.host) start(request, request.method || "GET", request.host, request.path || "/"); + 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 } }; - finish(request, response.statusCode); + 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 }; diff --git a/test/external-request-logging.test.js b/test/external-request-logging.test.js index e76a4fc..7bb211e 100644 --- a/test/external-request-logging.test.js +++ b/test/external-request-logging.test.js @@ -6,7 +6,7 @@ const { Agent } = require("undici"); const got = require("got"); require("ts-node/register/transpile-only"); const { logContext } = require("../src/core/log-context"); -const { installExternalRequestLogging, githubEndpoint } = require("../src/core/external-request-logging"); +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)); @@ -41,6 +41,9 @@ describe("external request logging", function () { 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" })); }); @@ -124,6 +127,36 @@ describe("external request logging", function () { 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 });