fix(logging): tell our cancellations from upstream resets, keep codes, catch cut bodies

- A request we destroy ourselves is ABORT_ERR, not ECONNRESET, and a
  fetch abort is ABORT_ERR rather than upstream_error.
- undici and DNS codes the schema lacks (UND_ERR_SOCKET, EAI_AGAIN, ...)
  fold into the closest kept code, so a failure always has one.
- node:http records are written when the body ends: a stream cut after
  its headers logs ECONNRESET with its status instead of a plain 200.
- Successful storage reads log at debug to keep info volume down.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Thomas DurieuxandClaude Opus 5.5 committed 2026-11-29 13:05:23 +00:00
1 parent 7c9e803fbd
commit c9342e4b7d
2 files changed
+96 -16

No files matched your search

+62 -15
View File
@@ -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<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 === 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<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 {
@@ -56,19 +81,16 @@ export function externalRequestFields(request: ExternalRequest): Record<string,
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 === 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<object, Pending>();
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 };