Files
clean-architecture-frontend…/tests/integration/http-execution-v3-observability.test.ts
T
DongHyeonka 39c1de2e5e feat(diagnostics): 결과 불명 쓰기의 effect와 원인을 진단에 싣는다
문제
실행 관측(HttpExecutionObservation)에는 effect가 있지만 조립 루트 projector는
진단에도 텔레메트리에도 싣지 않는다. 진단 허용 키에 effect가 없고 status는
묶음(4xx)만 남는다. 그래서 진단 버퍼에서 결과 불명과 적용 안 됨, 처리 중
409와 업무 409, 503 IDEMPOTENCY_UNAVAILABLE 재전송 소진이 같은 줄이 된다.
텔레메트리로는 결과 불명 쓰기의 비율을 셀 수 없다. 03-01이 고쳐져도 업무
거절은 선언 전까지 결과 불명이라 이 구분이 필요하다.

고른 방법
- effect_certainty 키: 진단·텔레메트리(api.request.failed 선택 속성) 모두
  HttpEffectCertainty 다섯 값만 받는 닫힌 value policy(isEffectCertainty)를
  쓴다. cardinality는 bounded. projector가 두 sink에 싣는다.
- 결과 불명 원인: Envelope 명령에서 표가 MAYBE_APPLIED를 줄 때 닫힌
  UnknownEffectReason을 진단 reason으로 싣는다. IN_FLIGHT(409 처리 중),
  IDEMPOTENCY_UNAVAILABLE, COMPLETION_UNKNOWN, RECOVERY_REQUIRED,
  SERVER_TIMEOUT(503 REQUEST_TIMEOUT), STAGE_UNKNOWN(단계를 모르는 400·409·
  422). 텔레메트리에는 싣지 않는다(VD-07: reason은 진단 전용).
- VD-07 5-1의 projector 키 목록과 reason 값 목록을 고쳤다. 남아 있던
  "effect_certainty는 필요해지면 더한다" 문장은 지웠다.

버린 대안
- 백엔드 error.code 원문을 진단에 싣기: cardinality 결정(1101 README 14.6)이
  먼저다. 닫힌 원인 집합이면 그 결정과 무관하다.
- 원인도 텔레메트리에: 텔레메트리 reason은 전달 실패용 닫힌 집합이라 뜻이
  섞인다. 비율은 effect_certainty로 센다.

위험·한계
- Envelope가 아닌 operation의 MAYBE_APPLIED는 원인 없이 effect만 남는다.
  응답을 잃은 경우는 outcome(TRANSPORT_FAILURE)이 원인을 보인다.
- 텔레메트리 수집기가 속성 목록을 고정해 두었다면 새 선택 속성을 받도록
  맞춰야 한다.

검증
- RED: envelope 진단 9행(effect·reason), observability 1건, cardinality
  8건 실패.
- GREEN: 처리 중 409는 reason IN_FLIGHT, 업무 409는 STAGE_UNKNOWN, 둘 다
  effect_certainty MAYBE_APPLIED. 진단 투영이 모두 통과한다.
  tests/unit·integration·component·features·contract·runtime-schema·platform
  282파일 중 281파일 통과. 남은 1건은 provider-guardian-transaction의 inotify
  한도(ENOSPC)로 이 변경과 무관하다.
- check:diagnostics, check:types, lint, verify:documentation 통과.

Refs: docs/reviews/2026-11-03-maturity-review/03-adapters-http-state.md 03-05
2026-11-04 20:54:24 +09:00

563 lines
18 KiB
TypeScript

import { describe, expect, it, vi } from "vitest";
import { createContractHttpExecutor } from "../../src/adapters/http/http-execution-v3.ts";
import type {
HttpExecutionObservation,
} from "../../src/adapters/http/http-execution-v3.ts";
import { createHttpObservationProjector } from "../../src/bootstrap/runtime-adapters.ts";
import {
DIAGNOSTIC_CONTEXT_ALLOWLIST,
projectDiagnosticRecord,
type DiagnosticRecordInput,
} from "../../src/contracts/diagnostics.ts";
import {
projectTelemetryEvent,
type TelemetryEventName,
} from "../../src/contracts/telemetry.ts";
import {
TEST_CREATE_HTTP_CONTRACT,
TEST_LIST_HTTP_CONTRACT,
} from "../helpers/external-contract-fixture.ts";
const ROUTE_ID = "TEST_ROUTE";
function scopeSnapshot(isCurrent: () => boolean = () => true) {
return Object.freeze({
generation: 1,
fingerprint: "scope-1",
identities: Object.freeze({}) as never,
signal: new AbortController().signal,
isCurrent,
});
}
type RecordedDiagnostic = DiagnosticRecordInput;
type RecordedTelemetry = Readonly<{
eventName: TelemetryEventName;
attributes: Readonly<Record<string, unknown>>;
}>;
function recordingSinks() {
const diagnostics: RecordedDiagnostic[] = [];
const telemetry: RecordedTelemetry[] = [];
return {
diagnostics,
telemetry,
projector: createHttpObservationProjector({
diagnostics: {
record(input: DiagnosticRecordInput) {
diagnostics.push(input);
},
},
telemetry: {
emit(
eventName: TelemetryEventName,
attributes: Record<string, unknown>,
) {
telemetry.push(Object.freeze({ eventName, attributes }));
},
},
}),
};
}
describe("V3 HTTP observability projection", () => {
it("projects every V3 terminal outcome through the closed diagnostics allowlist", async () => {
const sinks = recordingSinks();
const cases: readonly Readonly<{
label: string;
fetcher: typeof fetch;
}>[] = [
{
label: "SUCCESS",
fetcher: (async () =>
Response.json([{ id: "a", name: "A" }])) as unknown as typeof fetch,
},
{
label: "PROBLEM",
fetcher: (async () =>
Response.json(
{ type: "about:blank", title: "nope", status: 400 },
{ status: 400 },
)) as unknown as typeof fetch,
},
{
label: "TRANSPORT_FAILURE",
fetcher: (async () => {
throw new TypeError("network down");
}) as unknown as typeof fetch,
},
{
label: "CONTRACT_VIOLATION",
fetcher: (async () =>
new Response("<html/>", {
status: 200,
headers: { "content-type": "text/html" },
})) as unknown as typeof fetch,
},
];
for (const testCase of cases) {
const executor = createContractHttpExecutor({
baseUrl: "https://api.example/",
maxRetryAttempts: 0,
attachCredentials: () => ({
kind: "READY" as const,
headers: {},
}),
fetcher: testCase.fetcher,
observe: sinks.projector,
});
await executor.execute(
TEST_LIST_HTTP_CONTRACT,
{ limit: 5 },
{ routeId: ROUTE_ID, scope: scopeSnapshot() },
);
}
expect(sinks.diagnostics).toHaveLength(cases.length);
for (const recorded of sinks.diagnostics) {
expect(recorded.eventId).toBe("http.request.completed");
const contextKeys = Object.keys(recorded.context ?? {});
expect(contextKeys).toEqual(
expect.arrayContaining([
"route_id",
"operation_id",
"operation",
"outcome",
"error_kind",
"http_status_group",
"attempt_count_bucket",
"duration_bucket",
"effect_certainty",
]),
);
for (const key of contextKeys) {
expect(DIAGNOSTIC_CONTEXT_ALLOWLIST).toContain(key);
}
expect(contextKeys).not.toContain("attempts");
expect(contextKeys).not.toContain("certainty");
const projection = projectDiagnosticRecord(recorded);
expect(projection.success).toBe(true);
}
});
it("emits one failure telemetry event for a non-abort terminal failure", async () => {
const sinks = recordingSinks();
const executor = createContractHttpExecutor({
baseUrl: "https://api.example/",
maxRetryAttempts: 0,
attachCredentials: () => ({
kind: "READY" as const,
headers: {},
}),
fetcher: (async () => {
throw new TypeError("network down");
}) as unknown as typeof fetch,
observe: sinks.projector,
});
const outcome = await executor.execute(
TEST_LIST_HTTP_CONTRACT,
{ limit: 5 },
{ routeId: ROUTE_ID, scope: scopeSnapshot() },
);
expect(outcome.kind).toBe("TRANSPORT_FAILURE");
expect(sinks.telemetry).toHaveLength(1);
const emitted = sinks.telemetry[0];
expect(emitted?.eventName).toBe("api.request.failed");
expect(emitted?.attributes).toMatchObject({
route_id: ROUTE_ID,
operation_id: "TEST_LIST_ENTITIES",
error_kind: "NETWORK_FAILURE",
http_status_group: "none",
attempt_count_bucket: "1",
});
const projected = projectTelemetryEvent(
emitted?.eventName ?? "api.request.failed",
emitted?.attributes ?? {},
);
expect(projected.success).toBe(true);
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");
});
// 1101/03-06. A reflected id outside the request id grammar (a proxy's
// text, an overlong value) is not what the server logged: the sent id
// stands in for it, in the outcome and in diagnostics.
it.each([
["a value with spaces and markup", "<b>proxy ref</b>"],
["an overlong value", "r".repeat(129)],
])("drops a reflected correlation id that is %s", async (_label, reflected) => {
const sinks = recordingSinks();
const outcome = await createContractHttpExecutor({
baseUrl: "https://api.example/",
maxRetryAttempts: 0,
attachCredentials: () => ({ kind: "READY" as const, headers: {} }),
createRequestId: () => "sent-request-1",
fetcher: (async () =>
new Response(null, {
status: 503,
headers: { "x-correlation-id": reflected },
})) as unknown as typeof fetch,
observe: sinks.projector,
}).execute(
TEST_LIST_HTTP_CONTRACT,
{ limit: 5 },
{ routeId: ROUTE_ID, scope: scopeSnapshot() },
);
expect("metadata" in outcome ? outcome.metadata : undefined).not.toHaveProperty(
"correlationReference",
);
expect(outcome.sentRequestId).toBe("sent-request-1");
expect(sinks.diagnostics[0]?.context).toMatchObject({
correlation_id: "sent-request-1",
});
expect(JSON.stringify(sinks.diagnostics)).not.toContain(reflected);
});
/**
* 03-05. A package problem classifier that throws, or answers outside the
* closed set, fails safe to MAYBE_APPLIED. Diagnostics must still tell that
* apart from a classifier that really answered MAYBE_APPLIED; telemetry stays
* on `error_kind` alone.
*/
it("keeps MAYBE_APPLIED and records a failed problem classifier in diagnostics only (03-05)", async () => {
async function runWithClassifier(classifyProblem: () => unknown) {
const sinks = recordingSinks();
const contract = {
...TEST_CREATE_HTTP_CONTRACT,
contract: {
...TEST_CREATE_HTTP_CONTRACT.contract,
commandEffect: {
...TEST_CREATE_HTTP_CONTRACT.contract.commandEffect!,
classifyProblem,
} as NonNullable<
typeof TEST_CREATE_HTTP_CONTRACT.contract.commandEffect
>,
},
};
const outcome = await createContractHttpExecutor({
baseUrl: "https://api.example/",
maxRetryAttempts: 0,
attachCredentials: () => ({ kind: "READY" as const, headers: {} }),
fetcher: (async () =>
Response.json(
{ type: "about:blank", title: "conflict", status: 409 },
{ status: 409 },
)) as unknown as typeof fetch,
observe: sinks.projector,
}).execute(
contract,
{ name: "Created" },
{
routeId: ROUTE_ID,
scope: scopeSnapshot(),
intent: Object.freeze({
intentId: "intent-1",
operationId: "TEST_CREATE_ENTITY",
canonicalInputIdentity: "opaque-input-identity",
idempotencyKey: "key-1",
createdAtMonotonicMs: 1,
}),
},
);
expect(sinks.diagnostics).toHaveLength(1);
expect(projectDiagnosticRecord(sinks.diagnostics[0]!).success).toBe(true);
expect(sinks.telemetry).toHaveLength(1);
return {
kind: outcome.kind,
effect: outcome.effect,
reason: sinks.diagnostics[0]?.context?.reason,
telemetryKeys: Object.keys(sinks.telemetry[0]?.attributes ?? {}),
};
}
const answered = await runWithClassifier(() => "MAYBE_APPLIED");
const thrown = await runWithClassifier(() => {
throw new Error("package classifier defect");
});
const unknownAnswer = await runWithClassifier(() => "NOT_STARTED");
expect(answered).toMatchObject({
kind: "PROBLEM",
effect: "MAYBE_APPLIED",
reason: undefined,
});
for (const failed of [thrown, unknownAnswer]) {
expect(failed).toMatchObject({
kind: "PROBLEM",
effect: "MAYBE_APPLIED",
reason: "CLASSIFIER_FAILED",
});
expect(failed.telemetryKeys).toEqual(answered.telemetryKeys);
}
});
/**
* 03-02 (E6c). A path template and a `projectRequest` that disagree are
* refused before dispatch. The cause reaches diagnostics, not telemetry.
*/
it("names a refused request's assembly cause in diagnostics only (03-02)", async () => {
const sinks = recordingSinks();
const fetcher = vi.fn();
const mismatched = {
...TEST_LIST_HTTP_CONTRACT,
contract: {
...TEST_LIST_HTTP_CONTRACT.contract,
pathTemplate: "/api/test-entities/{id}",
projectRequest: () =>
Object.freeze({
pathValues: Object.freeze({ entityId: "entity-1" }),
queryEntries: Object.freeze([]),
body: null,
}),
},
};
const outcome = await createContractHttpExecutor({
baseUrl: "https://api.example/",
maxRetryAttempts: 0,
attachCredentials: () => ({ kind: "READY" as const, headers: {} }),
fetcher: fetcher as unknown as typeof fetch,
observe: sinks.projector,
}).execute(
mismatched,
{ limit: 5 },
{ routeId: ROUTE_ID, scope: scopeSnapshot() },
);
expect(fetcher).not.toHaveBeenCalled();
expect(outcome).toMatchObject({
kind: "CONTRACT_VIOLATION",
effect: "NOT_APPLICABLE",
violation: {
kind: "FINAL_REQUEST_INVARIANT_FAILED",
reason: "PATH_PLACEHOLDER_MISSING",
},
});
expect(sinks.diagnostics).toHaveLength(1);
expect(sinks.diagnostics[0]?.context).toMatchObject({
error_kind: "FINAL_REQUEST_INVARIANT_FAILED",
reason: "PATH_PLACEHOLDER_MISSING",
});
expect(projectDiagnosticRecord(sinks.diagnostics[0]!).success).toBe(true);
expect(JSON.stringify(sinks.telemetry)).not.toContain(
"PATH_PLACEHOLDER_MISSING",
);
});
/**
* 03-02 / P-03-05 (E3). The deadline can run out between the attempt's
* budget read and the final invariant check. Nothing was sent and nothing is
* wrong with the request: it is a timeout, like the budget read itself.
*/
it("ends a deadline that expires at the final invariant check as a timeout (P-03-05)", async () => {
let clockReads = 0;
let jumpAtRead = Number.POSITIVE_INFINITY;
const monotonicNow = () => {
clockReads += 1;
return clockReads >= jumpAtRead ? 1_000_000 : 0;
};
const run = (fetcher: typeof fetch) =>
createContractHttpExecutor({
baseUrl: "https://api.example/",
maxRetryAttempts: 0,
attachCredentials: () => ({ kind: "READY" as const, headers: {} }),
fetcher,
monotonicNow,
}).execute(
TEST_LIST_HTTP_CONTRACT,
{ limit: 5 },
{ routeId: ROUTE_ID, scope: scopeSnapshot() },
);
// Probe: the last clock read before fetch is the final invariant check's
// deadline read, because nothing else reads the clock in between.
let readsBeforeFetch = 0;
await run((async () => {
readsBeforeFetch = clockReads;
return Response.json([]);
}) as unknown as typeof fetch);
clockReads = 0;
jumpAtRead = readsBeforeFetch;
const fetcher = vi.fn();
const outcome = await run(fetcher as unknown as typeof fetch);
expect(fetcher).not.toHaveBeenCalled();
expect(outcome).toMatchObject({
kind: "TRANSPORT_FAILURE",
failure: { kind: "TIMEOUT" },
});
});
it("keeps a never-sent unauthenticated request out of telemetry (03-07)", async () => {
const sinks = recordingSinks();
const fetcher = vi.fn();
const executor = createContractHttpExecutor({
baseUrl: "https://api.example/",
maxRetryAttempts: 0,
attachCredentials: () => ({ kind: "UNAUTHENTICATED" as const }),
fetcher: fetcher as unknown as typeof fetch,
observe: sinks.projector,
});
const outcome = await executor.execute(
TEST_LIST_HTTP_CONTRACT,
{ limit: 5 },
{ routeId: ROUTE_ID, scope: scopeSnapshot() },
);
expect(outcome.kind).toBe("UNAUTHENTICATED");
expect(fetcher).not.toHaveBeenCalled();
expect(sinks.diagnostics).toHaveLength(1);
expect(sinks.telemetry).toHaveLength(0);
// A server 401 is still an API failure.
const answered = recordingSinks();
await createContractHttpExecutor({
baseUrl: "https://api.example/",
maxRetryAttempts: 0,
attachCredentials: () => ({ kind: "READY" as const, headers: {} }),
fetcher: (async () => new Response(null, { status: 401 })) as unknown as typeof fetch,
observe: answered.projector,
}).execute(
TEST_LIST_HTTP_CONTRACT,
{ limit: 5 },
{ routeId: ROUTE_ID, scope: scopeSnapshot() },
);
expect(answered.telemetry).toHaveLength(1);
});
it("does not emit failure telemetry for caller cancellation or scope fencing", async () => {
const cancelled = recordingSinks();
const callerController = new AbortController();
callerController.abort();
const cancelledExecutor = createContractHttpExecutor({
baseUrl: "https://api.example/",
maxRetryAttempts: 0,
attachCredentials: () => ({
kind: "READY" as const,
headers: {},
}),
fetcher: (async () =>
Response.json([{ id: "a", name: "A" }])) as unknown as typeof fetch,
observe: cancelled.projector,
});
const cancelledOutcome = await cancelledExecutor.execute(
TEST_LIST_HTTP_CONTRACT,
{ limit: 5 },
{
routeId: ROUTE_ID,
scope: scopeSnapshot(),
signal: callerController.signal,
},
);
expect(cancelledOutcome.kind).toBe("CANCELLED");
expect(cancelled.diagnostics).toHaveLength(1);
expect(cancelled.telemetry).toHaveLength(0);
const fenced = recordingSinks();
const fencedExecutor = createContractHttpExecutor({
baseUrl: "https://api.example/",
maxRetryAttempts: 0,
attachCredentials: () => ({
kind: "READY" as const,
headers: {},
}),
fetcher: (async () =>
Response.json([{ id: "a", name: "A" }])) as unknown as typeof fetch,
observe: fenced.projector,
});
const fencedOutcome = await fencedExecutor.execute(
TEST_LIST_HTTP_CONTRACT,
{ limit: 5 },
{ routeId: ROUTE_ID, scope: scopeSnapshot(() => false) },
);
expect(fencedOutcome.kind).toBe("CONTRACT_VIOLATION");
expect(fenced.diagnostics).toHaveLength(1);
expect(fenced.telemetry).toHaveLength(0);
});
it("cannot change the HTTP result when diagnostics or telemetry throws", async () => {
const projector = createHttpObservationProjector({
diagnostics: {
record() {
throw new Error("diagnostics sink exploded");
},
},
telemetry: {
emit() {
throw new Error("telemetry sink exploded");
},
},
});
const observe = vi.fn((observation: HttpExecutionObservation) => {
projector(observation);
});
const executor = createContractHttpExecutor({
baseUrl: "https://api.example/",
maxRetryAttempts: 0,
attachCredentials: () => ({
kind: "READY" as const,
headers: {},
}),
fetcher: (async () =>
Response.json({ id: "created", name: "Created" }, {
status: 201,
})) as unknown as typeof fetch,
observe,
});
const outcome = await executor.execute(
TEST_CREATE_HTTP_CONTRACT,
{ name: "Created" },
{
routeId: ROUTE_ID,
scope: scopeSnapshot(),
intent: Object.freeze({
intentId: "intent-1",
operationId: "TEST_CREATE_ENTITY",
canonicalInputIdentity: "opaque-input-identity",
idempotencyKey: "key-1",
createdAtMonotonicMs: 1,
}),
},
);
expect(outcome.kind).toBe("SUCCESS");
expect(observe).toHaveBeenCalledTimes(1);
});
});