From c5da3cf0013f0a92f444ad9403dc15b2ea110f58 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 25 Sep 2026 22:27:42 +0900 Subject: [PATCH] fix(http): send a request id and carry the server correlation id to failures (03-03) V3 read the response x-correlation-id and dropped it, and untraced requests sent no id, so a support reference could not be matched to a server log. Each logical execution now sends one x-correlation-id; failures carry the echoed value as requestId and diagnostics record it as correlation_id. Co-Authored-By: Claude Opus 5.5 --- .../api-contract-and-server-state-recovery.md | 8 ++ src/adapters/http/feature-http-binding.ts | 28 +++++++ src/adapters/http/http-execution-v3.ts | 39 ++++++++- src/bootstrap/runtime-adapters.ts | 4 + .../http-execution-v3-observability.test.ts | 28 +++++++ tests/unit/http-execution-v3.test.ts | 84 +++++++++++++++++++ 6 files changed, 189 insertions(+), 2 deletions(-) diff --git a/docs/operations/api-contract-and-server-state-recovery.md b/docs/operations/api-contract-and-server-state-recovery.md index 18f71224..55829a0c 100644 --- a/docs/operations/api-contract-and-server-state-recovery.md +++ b/docs/operations/api-contract-and-server-state-recovery.md @@ -168,6 +168,14 @@ target 점검: 3. cross-origin allow-origin/credentials/method/header/expose가 exact한지 확인한다. 4. wildcard credential, redirect와 unexpected origin을 복구한다. 5. CSRF token/header 값을 ticket에 기록하지 않는다. +6. V3 요청은 논리 실행마다 `x-correlation-id` 하나를 보낸다(재시도도 같은 값, + `src/adapters/http/http-execution-v3.ts` `createRequestId`). cross-origin API면 + preflight `Access-Control-Allow-Headers`에 `x-correlation-id`가 있어야 요청이 + 나간다. 응답의 `x-correlation-id`를 `AppFailure.requestId`와 diagnostics + `correlation_id`로 쓰려면 `Access-Control-Expose-Headers`에도 넣는다 + (`src/adapters/http/feature-http-binding.ts` `projectExecutionOutcome`, + `src/bootstrap/runtime-adapters.ts` `createHttpObservationProjector`). telemetry에는 + 넣지 않는다. ## 6. REST incident diff --git a/src/adapters/http/feature-http-binding.ts b/src/adapters/http/feature-http-binding.ts index 4e083218..718caebb 100644 --- a/src/adapters/http/feature-http-binding.ts +++ b/src/adapters/http/feature-http-binding.ts @@ -284,6 +284,10 @@ export function createFeatureHttpBinding< }); } +/** + * 03-03. A failure carries the server's echoed correlation id as `requestId`, + * so the support reference a user reports points at one server log entry. + */ function projectExecutionOutcome( operationId: string, mapSuccess: (value: WireOutput) => MappingResult, @@ -294,6 +298,30 @@ function projectExecutionOutcome( ) => FeatureHttpProblemMapping | undefined) | undefined, outcome: HttpExecutionOutcome, +): Result { + const projected = projectOutcome(operationId, mapSuccess, mapProblem, outcome); + const requestId = + "metadata" in outcome + ? outcome.metadata?.correlationReference + : undefined; + return projected.ok || requestId === undefined + ? projected + : Object.freeze({ + ok: false as const, + error: Object.freeze({ ...projected.error, requestId }), + }); +} + +function projectOutcome( + operationId: string, + mapSuccess: (value: WireOutput) => MappingResult, + mapProblem: + | (( + problem: Problem, + metadata: SafeResponseMetadata, + ) => FeatureHttpProblemMapping | undefined) + | undefined, + outcome: HttpExecutionOutcome, ): Result { // A throwing feature mapper is a mapping defect, not a transport failure: it // must not reject and lose the effect the server already confirmed. diff --git a/src/adapters/http/http-execution-v3.ts b/src/adapters/http/http-execution-v3.ts index 42d8b5ae..a37af431 100644 --- a/src/adapters/http/http-execution-v3.ts +++ b/src/adapters/http/http-execution-v3.ts @@ -53,7 +53,10 @@ import { } from "../../platform/traffic/concurrency-budget.ts"; import type { TrafficBudget } from "../../platform/traffic/traffic-budget.ts"; import { checkJsonStructure } from "../../platform/validation/bounded-json.ts"; -import { buildTraceHeaders } from "../../platform/telemetry/trace-context.ts"; +import { + buildTraceHeaders, + CORRELATION_ID_HEADER, +} from "../../platform/telemetry/trace-context.ts"; import { responseValidationBudget } from "../../platform/validation/validation-budget.ts"; import { canRetryTransport, @@ -144,11 +147,13 @@ export type HttpExecutionOutcome = }> | Readonly<{ kind: "FORBIDDEN"; + metadata?: SafeResponseMetadata; effect: "NOT_APPLICABLE" | "NOT_APPLIED" | "MAYBE_APPLIED"; }> | Readonly<{ kind: "RATE_LIMITED"; retryAfterMs?: number; + metadata?: SafeResponseMetadata; effect: "NOT_APPLICABLE" | "NOT_APPLIED" | "MAYBE_APPLIED"; }> | Readonly<{ @@ -267,6 +272,11 @@ export type HttpExecutionObservation = Readonly<{ durationMs: number; effect: HttpEffectCertainty; cancellationOwner?: CancellationOwner; + /** + * 03-03. The server's echoed `x-correlation-id`, else the request id this + * execution sent. Diagnostics only; never telemetry. + */ + correlationId?: string; /** * The internal terminal-reason label recorded by the execution site. It is * evidence for the HTTP scenario catalog only; the composition-root @@ -314,6 +324,14 @@ function observationStatus( return "metadata" in outcome ? outcome.metadata?.status : undefined; } +function responseCorrelation( + outcome: HttpExecutionOutcome, +): string | undefined { + return "metadata" in outcome + ? outcome.metadata?.correlationReference + : undefined; +} + export type ContractHttpExecutorDependencies = Readonly<{ baseUrl: string; /** §8.2. `MAX_RETRY_ATTEMPTS` from Runtime Config; the ceiling is still 2. */ @@ -345,6 +363,8 @@ export type ContractHttpExecutorDependencies = Readonly<{ monotonicNow?: () => number; sleep?: (ms: number, signal: AbortSignal) => Promise; random?: () => number; + /** 03-03. One id per logical execution, sent as `x-correlation-id`. */ + createRequestId?: () => string; observe?: (observation: HttpExecutionObservation) => void; }>; @@ -425,6 +445,8 @@ export function createContractHttpExecutor( dependencies.readBoundedResponseBytes ?? readBoundedBytes; const now = dependencies.monotonicNow ?? (() => performance.now()); const random = dependencies.random ?? Math.random; + const createRequestId = + dependencies.createRequestId ?? (() => globalThis.crypto.randomUUID()); const deadlineCeilingMs = dependencies.requestDeadlineCeilingMs; const effectiveDeadlineMs = (contractDeadlineMs: number): number => typeof deadlineCeilingMs === "number" && @@ -564,6 +586,7 @@ export function createContractHttpExecutor( lifetimeController.abort(); }; + let sentRequestId: string | undefined; const finish = ( outcome: HttpExecutionOutcome, terminalReason: string, @@ -571,6 +594,7 @@ export function createContractHttpExecutor( disposeLifetime(); try { const status = observationStatus(outcome); + const correlationId = responseCorrelation(outcome) ?? sentRequestId; dependencies.observe?.( Object.freeze({ routeId: context.routeId, @@ -586,6 +610,7 @@ export function createContractHttpExecutor( ...(terminalCancellation === null ? {} : { cancellationOwner: terminalCancellation }), + ...(correlationId === undefined ? {} : { correlationId }), }), ); } catch { @@ -789,6 +814,10 @@ export function createContractHttpExecutor( if (context.execution?.trace !== undefined) { Object.assign(headers, buildTraceHeaders(context.execution)); } + // 03-03. Every other logical execution still sends its own request id, + // shared by its retries, so a failure can be found in the server log. + headers[CORRELATION_ID_HEADER] ??= createRequestId(); + sentRequestId = headers[CORRELATION_ID_HEADER]; const retryCeiling = Math.min( policy.retryBudget, @@ -1160,7 +1189,10 @@ async function admitResponse( } if (status === 403) { await response.body?.cancel().catch(() => {}); - return settled(forbidden(statusEffect(403), isCommand), "FORBIDDEN"); + return settled( + forbidden(statusEffect(403), isCommand, metadata), + "FORBIDDEN", + ); } if (status === 429) { await response.body?.cancel().catch(() => {}); @@ -1168,6 +1200,7 @@ async function admitResponse( result: Object.freeze({ kind: "RATE_LIMITED" as const, ...(retryAfterMs === null ? {} : { retryAfterMs }), + metadata, effect: normalizeOptionalEffect(statusEffect(429), isCommand), }), certainty: "RATE_LIMITED", @@ -1661,9 +1694,11 @@ function unauthenticated( function forbidden( effect: string, isCommand: boolean, + metadata: SafeResponseMetadata, ): HttpExecutionOutcome { return Object.freeze({ kind: "FORBIDDEN" as const, + metadata, effect: normalizeOptionalEffect(effect, isCommand), }); } diff --git a/src/bootstrap/runtime-adapters.ts b/src/bootstrap/runtime-adapters.ts index 2025e0ed..8e046691 100644 --- a/src/bootstrap/runtime-adapters.ts +++ b/src/bootstrap/runtime-adapters.ts @@ -246,6 +246,10 @@ export function createHttpObservationProjector( ...safeAttributes, operation: observation.diagnosticsOperation, outcome: observation.outcome, + // 03-03. Request-scoped: diagnostics may carry it, telemetry never. + ...(observation.correlationId === undefined + ? {} + : { correlation_id: observation.correlationId }), }, }); } catch { diff --git a/tests/integration/http-execution-v3-observability.test.ts b/tests/integration/http-execution-v3-observability.test.ts index 3a114de4..50d2d328 100644 --- a/tests/integration/http-execution-v3-observability.test.ts +++ b/tests/integration/http-execution-v3-observability.test.ts @@ -182,6 +182,34 @@ describe("V3 HTTP observability projection", () => { expect(sinks.diagnostics).toHaveLength(1); }); + it("records the correlation id in diagnostics only (03-03)", async () => { + const sinks = recordingSinks(); + const executor = createContractHttpExecutor({ + baseUrl: "https://api.example/", + maxRetryAttempts: 0, + attachCredentials: () => ({ kind: "READY" as const, headers: {} }), + fetcher: (async () => + new Response(null, { + status: 503, + headers: { "x-correlation-id": "server-ref-7" }, + })) as unknown as typeof fetch, + observe: sinks.projector, + }); + + await executor.execute( + TEST_LIST_HTTP_CONTRACT, + { limit: 5 }, + { routeId: ROUTE_ID, scope: scopeSnapshot() }, + ); + + expect(sinks.diagnostics[0]?.context).toMatchObject({ + correlation_id: "server-ref-7", + }); + expect(projectDiagnosticRecord(sinks.diagnostics[0]!).success).toBe(true); + expect(sinks.telemetry).toHaveLength(1); + expect(JSON.stringify(sinks.telemetry)).not.toContain("server-ref-7"); + }); + it("does not emit failure telemetry for caller cancellation or scope fencing", async () => { const cancelled = recordingSinks(); const callerController = new AbortController(); diff --git a/tests/unit/http-execution-v3.test.ts b/tests/unit/http-execution-v3.test.ts index 44ba0012..d0e80d37 100644 --- a/tests/unit/http-execution-v3.test.ts +++ b/tests/unit/http-execution-v3.test.ts @@ -992,6 +992,90 @@ describe("terminal owner classification at every wait", () => { ); }); +/** + * 03-03. A support reference must reach the server log: every logical + * execution sends one request id, and a failure carries the server's echoed + * `x-correlation-id` as `requestId`. + */ +describe("request correlation", () => { + it("sends one request id per logical execution, shared by its retries", async () => { + const sent: (string | null)[] = []; + const fetcher = vi.fn(async (_input, init) => { + sent.push(new Headers(init?.headers).get("x-correlation-id")); + return sent.length === 1 + ? new Response(null, { status: 503 }) + : Response.json([{ id: "a", name: "A" }]); + }); + const executor = createContractHttpExecutor({ + baseUrl: "https://api.example/", + maxRetryAttempts: 2, + attachCredentials: () => ({ kind: "READY", headers: {} }), + fetcher, + sleep: async () => {}, + random: () => 0, + }); + const retried = { + ...installed, + frontend: { ...installed.frontend, retryBudget: 1 as const }, + }; + + await executor.execute(retried, { limit: 20 }, { routeId: ROUTE_ID, scope }); + await executor.execute(retried, { limit: 20 }, { routeId: ROUTE_ID, scope }); + + expect(sent).toHaveLength(3); + expect(sent[0]).toMatch(/^[A-Za-z0-9._:-]{1,128}$/u); + expect(sent[1]).toBe(sent[0]); + expect(sent[2]).not.toBe(sent[0]); + }); + + it.each([ + ["a problem", 400, { type: "about:blank", title: "rejected", status: 400 }], + ["an unauthenticated answer", 401, null], + ["a forbidden answer", 403, null], + ["a rate limit", 429, null], + ["a gateway outage", 504, null], + ] as const)("carries the server correlation id on %s", async (_label, status, body) => { + const observations: HttpExecutionObservation[] = []; + const executor = createContractHttpExecutor({ + baseUrl: "https://api.example/", + maxRetryAttempts: 0, + attachCredentials: () => ({ kind: "READY", headers: {} }), + fetcher: vi.fn(async () => + body === null + ? new Response(null, { + status, + headers: { "x-correlation-id": "server-ref-42" }, + }) + : Response.json(body, { + status, + headers: { "x-correlation-id": "server-ref-42" }, + }), + ), + observe: (observation) => observations.push(observation), + }); + const list = defineFeatureHttpOperation({ + contract: TEST_LIST_HTTP_CONTRACT, + routeId: ROUTE_ID, + mapSuccess: (value) => mappingSuccess(value), + }); + const binding = createFeatureHttpBinding( + { + execute: (contract, input, context) => + executor.execute(contract, input, { ...context, scope }), + }, + { [list.operationId]: list }, + ); + + const result = await binding.execute(list.operationId, { limit: 20 }); + + expect(result).toMatchObject({ + ok: false, + error: { requestId: "server-ref-42" }, + }); + expect(observations.at(-1)?.correlationId).toBe("server-ref-42"); + }); +}); + /** * D-2 (03-02). 401, 403 and 429 are admitted before any problem body is read. * The package may classify them by status; without a classifier, or when it