Files
clean-architecture-frontend…/tests/integration/http-execution-v3-envelope.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

1056 lines
36 KiB
TypeScript

import { HttpResponse, http, type JsonBodyType } from "msw";
import { setupServer } from "msw/node";
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
import { z } from "zod";
import {
createContractHttpExecutor,
createFeatureHttpBinding,
defineFeatureHttpOperation,
type HttpExecutionObservation,
type InstalledHttpOperationExecutor,
} from "../../src/adapters/http/index.ts";
import { createHttpObservationProjector } from "../../src/bootstrap/runtime-adapters.ts";
import {
projectDiagnosticRecord,
type DiagnosticRecordInput,
} from "../../src/contracts/diagnostics.ts";
import { mappingSuccess } from "../../src/contracts/boundary-mapper.ts";
import type { AppFailure } from "../../src/contracts/errors.ts";
import {
composeContractContributions,
type CommandEffectDescriptor,
type InstalledHttpContract,
} from "../../src/contracts/external-contract-runtime.ts";
import { zodValidator } from "../../src/contracts/zod-validator.ts";
import { TEST_CONTRACT_CONTRIBUTION } from "../helpers/external-contract-fixture.ts";
import { createHttpScenarioHandler } from "../mocks/handlers/http-scenarios.ts";
/**
* 1101 README 14.3. The paired backend answers every JSON body as an Envelope
* (clean-architecture-backend-template docs/web/http-contract.md §1) and drops
* a null field together with its key. A V3 operation that declares
* `responseEnvelope: "ENVELOPE_V1"` reads it, and judges whether a refusal
* applied by the backend's own table (frontend contract 6.1).
*/
const BASE_URL = "https://api.test";
const LIST_LIMIT = 2_048;
const itemSchema = z
.object({
id: z.string().min(1),
name: z.string().min(1),
// The backend drops a null field with its key.
description: z.string().optional(),
})
.strip();
/** What the scaffold generates as the problem: the Envelope's `error`. */
const errorSchema = z
.object({
code: z.string().regex(/^[A-Z0-9_]{1,64}$/u),
category: z.string().min(1).max(64).optional(),
retryable: z.boolean().optional(),
details: z.unknown().optional(),
})
.strip();
type EnvelopeProblem = z.output<typeof errorSchema>;
const problemValidator = zodValidator("EnvelopeTestProblem", errorSchema);
const noInput = zodValidator("EnvelopeTestNoInput", z.object({}).strict());
function readPolicy(policyId: string) {
return Object.freeze({
policyId,
requestByteLimit: 0,
responseByteLimit: LIST_LIMIT,
totalDeadlineMs: 10_000,
retryBudget: 0 as const,
authProfileId: "ANONYMOUS",
diagnosticsOperation: "envelope.read",
});
}
const LIST_CONTRACT = Object.freeze({
contract: Object.freeze({
operationId: "ENVELOPE_LIST_ITEMS",
method: "GET" as const,
pathTemplate: "/api/envelope-items",
inputValidator: noInput,
outputValidator: zodValidator(
"EnvelopeTestItemList",
z.array(itemSchema).max(100),
),
problemValidator,
acceptedStatuses: Object.freeze([200]),
emptyBodyStatuses: Object.freeze([]),
retrySemantics: "SAFE" as const,
requestBody: "NONE" as const,
responseBody: "REQUIRED_JSON" as const,
responseEnvelope: "ENVELOPE_V1" as const,
commandRecovery: null,
commandEffect: null,
projectRequest: () =>
Object.freeze({
pathValues: Object.freeze({}),
queryEntries: Object.freeze([]),
body: null,
}),
}),
frontend: readPolicy("ENVELOPE_LIST_V1"),
}) satisfies InstalledHttpContract<
Readonly<Record<never, never>>,
readonly z.output<typeof itemSchema>[],
EnvelopeProblem
>;
/** A success whose `data` is null: the backend sends no `data` key. */
const ARCHIVE_CONTRACT = Object.freeze({
contract: Object.freeze({
...LIST_CONTRACT.contract,
operationId: "ENVELOPE_ARCHIVE_ITEMS",
method: "POST" as const,
pathTemplate: "/api/envelope-items/archive",
outputValidator: zodValidator("EnvelopeTestNull", z.null()),
retrySemantics: "KEYED" as const,
requestBody: "JSON" as const,
commandRecovery: Object.freeze({
mode: "IDEMPOTENCY_REPLAY" as const,
operationIdentityField: "idempotencyKey",
}),
commandEffect: Object.freeze({
successEffect: "APPLIED_CONFIRMED" as const,
classifyProblem: () => "MAYBE_APPLIED" as const,
}) satisfies CommandEffectDescriptor<EnvelopeProblem>,
}),
frontend: Object.freeze({
...readPolicy("ENVELOPE_ARCHIVE_V1"),
requestByteLimit: 1_024,
diagnosticsOperation: "envelope.archive",
}),
}) satisfies InstalledHttpContract<
Readonly<Record<never, never>>,
null,
EnvelopeProblem
>;
/**
* The most conservative package classifier: every problem may have applied.
* What the V3 run then says NOT_APPLIED comes from the backend's own
* operation-independent refusals.
*/
const CREATE_CONTRACT = Object.freeze({
contract: Object.freeze({
...ARCHIVE_CONTRACT.contract,
operationId: "ENVELOPE_CREATE_ITEM",
pathTemplate: "/api/envelope-items",
outputValidator: zodValidator("EnvelopeTestItem", itemSchema),
acceptedStatuses: Object.freeze([201]),
}),
frontend: Object.freeze({
...ARCHIVE_CONTRACT.frontend,
policyId: "ENVELOPE_CREATE_V1",
diagnosticsOperation: "envelope.create",
}),
}) satisfies InstalledHttpContract<
Readonly<Record<never, never>>,
z.output<typeof itemSchema>,
EnvelopeProblem
>;
/** A package that reads every problem as refused untouched. */
const CREATE_LENIENT_CONTRACT = Object.freeze({
...CREATE_CONTRACT,
contract: Object.freeze({
...CREATE_CONTRACT.contract,
commandEffect: Object.freeze({
successEffect: "APPLIED_CONFIRMED" as const,
classifyProblem: () => "NOT_APPLIED" as const,
}) satisfies CommandEffectDescriptor<EnvelopeProblem>,
}),
});
const OPERATIONS = Object.freeze({
ENVELOPE_LIST_ITEMS: defineFeatureHttpOperation({
contract: LIST_CONTRACT,
routeId: "ENVELOPE_ROUTE",
mapSuccess: (value) => mappingSuccess(value),
}),
ENVELOPE_ARCHIVE_ITEMS: defineFeatureHttpOperation({
contract: ARCHIVE_CONTRACT,
routeId: "ENVELOPE_ROUTE",
mapSuccess: (value) => mappingSuccess(value),
}),
ENVELOPE_CREATE_ITEM: defineFeatureHttpOperation({
contract: CREATE_CONTRACT,
routeId: "ENVELOPE_ROUTE",
mapSuccess: (value) => mappingSuccess(value),
}),
});
const LENIENT_OPERATIONS = Object.freeze({
ENVELOPE_CREATE_ITEM: defineFeatureHttpOperation({
contract: CREATE_LENIENT_CONTRACT,
routeId: "ENVELOPE_ROUTE",
mapSuccess: (value) => mappingSuccess(value),
}),
});
const META = Object.freeze({
requestId: "req-1",
traceId: "0af7651916cd43dd8448eb211c80319c",
correlationId: "corr-1",
});
function success(data: JsonBodyType, meta: JsonBodyType = META) {
return { success: true, ...(data === null ? {} : { data }), meta };
}
function failure(
code: string,
category: string,
retryable: boolean,
details?: JsonBodyType,
) {
return {
success: false,
error: {
code,
category,
message: "서버가 보낸 문구",
retryable,
...(details === undefined ? {} : { details }),
},
meta: META,
};
}
const server = setupServer();
beforeAll(() => server.listen({ onUnhandledRequest: "error" }));
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
function answer(
method: "get" | "post",
path: string,
body: JsonBodyType,
init: Readonly<{ status?: number; headers?: Record<string, string> }> = {},
) {
server.use(
http[method](`${BASE_URL}${path}`, () =>
HttpResponse.json(body, {
status: init.status ?? 200,
...(init.headers === undefined ? {} : { headers: init.headers }),
}),
),
);
}
function scope() {
return Object.freeze({
generation: 1,
fingerprint: "envelope-scope",
identities: Object.freeze({}) as never,
signal: new AbortController().signal,
isCurrent: () => true,
});
}
function v3Executor(
fetcher?: typeof fetch,
observe?: (observation: HttpExecutionObservation) => void,
): InstalledHttpOperationExecutor {
const executor = createContractHttpExecutor({
baseUrl: BASE_URL,
...(fetcher === undefined ? {} : { fetcher }),
...(observe === undefined ? {} : { observe }),
maxRetryAttempts: 0,
attachCredentials: () => ({ kind: "READY" as const, headers: {} }),
random: () => 0,
});
return Object.freeze({
execute(contract, input, context) {
return executor.execute(contract, input, {
routeId: context.routeId,
scope: scope(),
...(context.intent === undefined ? {} : { intent: context.intent }),
});
},
});
}
function v3(fetcher?: typeof fetch) {
return createFeatureHttpBinding(v3Executor(fetcher), OPERATIONS);
}
const KEY = "envelope-key-1";
function intent(operationId: string) {
return Object.freeze({
intentId: `intent-${operationId}`,
operationId,
canonicalInputIdentity: "{}",
idempotencyKey: KEY,
createdAtMonotonicMs: 0,
});
}
/** What the mutation coordinator reads (`mutationFailureWithEffect`). */
function verdict(error: AppFailure) {
return {
kind: error.kind,
code: error.code,
httpStatus: error.httpStatus,
effect:
error.effect === undefined || error.effect === "NOT_APPLICABLE"
? "MAYBE_APPLIED"
: error.effect,
retryAfterMs: error.retryAfterMs,
validationIssues: error.validationIssues,
};
}
async function v3CreateFailure(
binding: Pick<ReturnType<typeof v3>, "execute"> = v3(),
): Promise<AppFailure> {
const result = await binding.execute(
"ENVELOPE_CREATE_ITEM",
Object.freeze({}),
{ intent: intent("ENVELOPE_CREATE_ITEM") },
);
if (result.ok) throw new Error("V3 create unexpectedly succeeded");
return result.error;
}
describe("V3 operation that reads the paired backend's Envelope", () => {
it("reads the success data and ignores meta keys it does not know", async () => {
answer(
"get",
"/api/envelope-items",
success([{ id: "item-1", name: "First" }], {
...META,
page: { number: 0, size: 20, total: 1, sort: null },
}),
);
await expect(
v3().execute("ENVELOPE_LIST_ITEMS", Object.freeze({})),
).resolves.toEqual({
ok: true,
value: [{ id: "item-1", name: "First" }],
});
});
// 1103/03-02. The paired backend's page list carries the total and the
// page under meta.page (http-contract.md §1); the binding hands it to
// mapSuccess next to the data.
it("hands the backend's meta.page to mapSuccess", async () => {
answer(
"get",
"/api/envelope-items",
success([{ id: "item-1", name: "First" }], {
...META,
page: { number: 2, size: 20, total: 137, sort: "createdAt,desc" },
}),
);
const seen: unknown[] = [];
const binding = createFeatureHttpBinding(
v3Executor(),
Object.freeze({
ENVELOPE_LIST_ITEMS: defineFeatureHttpOperation({
contract: LIST_CONTRACT,
routeId: "ENVELOPE_ROUTE",
mapSuccess: (value, context) => {
seen.push(context);
return mappingSuccess({ items: value, total: context.page?.total });
},
}),
}),
);
await expect(
binding.execute("ENVELOPE_LIST_ITEMS", Object.freeze({})),
).resolves.toEqual({
ok: true,
value: { items: [{ id: "item-1", name: "First" }], total: 137 },
});
expect(seen).toEqual([
{ page: { number: 2, size: 20, total: 137, sort: "createdAt,desc" } },
]);
});
it.each([
["an unsorted page", { number: 0, size: 20, total: 0, sort: null }, { number: 0, size: 20, total: 0 }],
["a page without sort", { number: 0, size: 100, total: 3 }, { number: 0, size: 100, total: 3 }],
["a size over the backend cap", { number: 0, size: 500, total: 3 }, undefined],
["a negative page number", { number: -1, size: 20, total: 3 }, undefined],
["a fractional total", { number: 0, size: 20, total: 1.5 }, undefined],
] as const)("reads %s", async (_label, page, expected) => {
const fetcher = (async () =>
Response.json(success([], { ...META, page }))) as typeof fetch;
const executor = createContractHttpExecutor({
baseUrl: BASE_URL,
fetcher,
maxRetryAttempts: 0,
attachCredentials: () => ({ kind: "READY" as const, headers: {} }),
});
const outcome = await executor.execute(LIST_CONTRACT, Object.freeze({}), {
routeId: "ENVELOPE_ROUTE",
scope: scope(),
});
// A page the backend could not have sent is dropped, not the answer.
expect(outcome).toMatchObject({ kind: "SUCCESS", value: [] });
expect(outcome.kind === "SUCCESS" ? outcome.page : "not a success").toEqual(expected);
});
it("reads keys the backend dropped as null: a DTO field, the meta ids and the data", async () => {
answer("get", "/api/envelope-items", success([{ id: "item-1", name: "First" }], {}));
await expect(
v3().execute("ENVELOPE_LIST_ITEMS", Object.freeze({})),
).resolves.toEqual({ ok: true, value: [{ id: "item-1", name: "First" }] });
answer("post", "/api/envelope-items/archive", success(null));
await expect(
v3().execute("ENVELOPE_ARCHIVE_ITEMS", Object.freeze({}), {
intent: intent("ENVELOPE_ARCHIVE_ITEMS"),
}),
).resolves.toEqual({ ok: true, value: null });
});
it("reads the failure error's code and keeps the backend message out", async () => {
answer("get", "/api/envelope-items", failure("NOT_FOUND", "NOT_FOUND", false), {
status: 404,
});
const result = await v3().execute(
"ENVELOPE_LIST_ITEMS",
Object.freeze({}),
);
expect(result).toMatchObject({
ok: false,
error: { kind: "NOT_FOUND", code: "NOT_FOUND", httpStatus: 404 },
});
expect(JSON.stringify(result)).not.toContain("서버가 보낸 문구");
});
// 1103/03-06. The failure carries the backend's trace id, so support can
// find the server's trace from the failure a user reports.
it("carries the failure Envelope's meta.traceId on the failure", async () => {
answer("get", "/api/envelope-items", failure("NOT_FOUND", "NOT_FOUND", false), {
status: 404,
});
await expect(
v3().execute("ENVELOPE_LIST_ITEMS", Object.freeze({})),
).resolves.toMatchObject({
ok: false,
error: { code: "NOT_FOUND", traceId: META.traceId },
});
answer(
"get",
"/api/envelope-items",
{ ...failure("NOT_FOUND", "NOT_FOUND", false), meta: {} },
{ status: 404 },
);
const untraced = await v3().execute("ENVELOPE_LIST_ITEMS", Object.freeze({}));
expect(untraced.ok ? undefined : untraced.error).not.toHaveProperty("traceId");
});
it.each([
["a bare DTO", [{ id: "item-1", name: "First" }]],
["a failure Envelope", failure("NOT_FOUND", "NOT_FOUND", false)],
["a success Envelope that also carries error", { ...success([]), error: { code: "X" } }],
])("rejects %s on a success status as an Envelope mismatch", async (_label, body) => {
answer("get", "/api/envelope-items", body as JsonBodyType);
await expect(
v3().execute("ENVELOPE_LIST_ITEMS", Object.freeze({})),
).resolves.toMatchObject({
ok: false,
error: { kind: "ENVELOPE_MISMATCH", code: "ENVELOPE_MISMATCH" },
});
});
it("counts the whole Envelope against the byte limit", async () => {
// The data alone fits the limit; with its frame it does not.
const name = "n".repeat(LIST_LIMIT - 120);
const data = [{ id: "item-1", name }];
expect(JSON.stringify(data).length).toBeLessThan(LIST_LIMIT);
expect(JSON.stringify(success(data)).length).toBeGreaterThan(LIST_LIMIT);
// A native Response, as http-execution-contract.test.ts uses: MSW never
// settles a cancel() on a body it is still streaming.
const fetcher = (async () => Response.json(success(data))) as typeof fetch;
await expect(
v3(fetcher).execute("ENVELOPE_LIST_ITEMS", Object.freeze({})),
).resolves.toMatchObject({ ok: false, error: { kind: "RESPONSE_BODY_LIMIT" } });
});
it("applies the structure budget to the whole Envelope, not only data", async () => {
let deep: JsonBodyType = "leaf";
for (let depth = 0; depth < 70; depth += 1) deep = { nested: deep };
answer("get", "/api/envelope-items", success([], { ...META, deep }));
await expect(
v3().execute("ENVELOPE_LIST_ITEMS", Object.freeze({})),
).resolves.toMatchObject({
ok: false,
error: { kind: "RESPONSE_BODY_LIMIT", code: "RESPONSE_TOO_LARGE" },
});
});
});
describe("V3 Envelope verdicts follow the backend's refusal table", () => {
const cases: readonly (readonly [
string,
Readonly<{ status: number; body: JsonBodyType; headers?: Record<string, string> }>,
])[] = [
[
"409 IDEMPOTENT_IN_FLIGHT",
{
status: 409,
body: failure("IDEMPOTENT_IN_FLIGHT", "CONFLICT", true),
headers: { "Retry-After": "2" },
},
],
[
"422 IDEMPOTENT_REQUEST_MISMATCH",
{ status: 422, body: failure("IDEMPOTENT_REQUEST_MISMATCH", "VALIDATION", false) },
],
[
"400 IDEMPOTENCY_KEY_INVALID",
{
status: 400,
body: failure("IDEMPOTENCY_KEY_INVALID", "VALIDATION", false, {
reason: "MALFORMED",
}),
},
],
[
"503 IDEMPOTENCY_UNAVAILABLE",
{
status: 503,
body: failure("IDEMPOTENCY_UNAVAILABLE", "TRANSIENT_DEPENDENCY", true),
},
],
[
"400 VALIDATION_FAILED with the field list",
{
status: 400,
body: failure("VALIDATION_FAILED", "VALIDATION", false, [
{ field: "name", code: "NOT_BLANK", message: "비어 있으면 안 됩니다" },
]),
},
],
[
"400 VALIDATION_FAILED for an unreadable body",
{
status: 400,
body: failure("VALIDATION_FAILED", "VALIDATION", false, {
cause: "JsonParseException",
}),
},
],
[
"400 VALIDATION_FAILED without details",
{ status: 400, body: failure("VALIDATION_FAILED", "VALIDATION", false) },
],
[
"400 VALIDATION_FAILED for a page parameter",
{
status: 400,
body: failure("VALIDATION_FAILED", "VALIDATION", false, {
field: "size",
code: "MAX",
}),
},
],
[
"400 BAD_PARAMETER",
{ status: 400, body: failure("BAD_PARAMETER", "VALIDATION", false) },
],
[
"409 domain conflict",
{ status: 409, body: failure("RESOURCE_CONFLICT", "CONFLICT", false) },
],
[
"422 INTEGRITY_MISMATCH",
{ status: 422, body: failure("INTEGRITY_MISMATCH", "VALIDATION", false) },
],
];
// 1101/14.4. Frontend contract 6.1: only the three codes the backend raises
// before it writes are not applied; every other 400, 409 and 422 may be.
const expected: Readonly<Record<string, Readonly<Record<string, unknown>>>> = {
"409 IDEMPOTENT_IN_FLIGHT": {
kind: "CONFLICT",
code: "IDEMPOTENT_IN_FLIGHT",
effect: "MAYBE_APPLIED",
retryAfterMs: 2_000,
},
// 08-05. The same key went out with another body: nothing for the user
// to correct in the input.
"422 IDEMPOTENT_REQUEST_MISMATCH": { kind: "UNKNOWN_CLIENT_FAILURE", effect: "NOT_APPLIED" },
"400 IDEMPOTENCY_KEY_INVALID": { kind: "UNKNOWN_CLIENT_FAILURE", effect: "NOT_APPLIED" },
"503 IDEMPOTENCY_UNAVAILABLE": { kind: "SERVER_FAILURE", effect: "MAYBE_APPLIED" },
"400 VALIDATION_FAILED with the field list": {
kind: "VALIDATION_REJECTED",
effect: "NOT_APPLIED",
validationIssues: [{ path: "name", code: "NOT_BLANK" }],
},
"400 VALIDATION_FAILED for an unreadable body": {
kind: "UNKNOWN_CLIENT_FAILURE",
effect: "NOT_APPLIED",
},
"400 VALIDATION_FAILED without details": {
kind: "UNKNOWN_CLIENT_FAILURE",
effect: "NOT_APPLIED",
},
"400 VALIDATION_FAILED for a page parameter": {
kind: "UNKNOWN_CLIENT_FAILURE",
effect: "NOT_APPLIED",
},
"400 BAD_PARAMETER": { kind: "UNKNOWN_CLIENT_FAILURE", effect: "MAYBE_APPLIED" },
"409 domain conflict": { kind: "CONFLICT", effect: "MAYBE_APPLIED" },
// 08-05. A 422 without a field list is no input error either.
"422 INTEGRITY_MISMATCH": { kind: "UNKNOWN_CLIENT_FAILURE", effect: "MAYBE_APPLIED" },
};
it.each(cases)("%s", async (label, response) => {
answer("post", "/api/envelope-items", response.body, response);
await expect(v3CreateFailure().then(verdict)).resolves.toMatchObject({
httpStatus: response.status,
...expected[label],
});
});
// 1101/14.4. For an Envelope operation the table decides 400, 409 and 422
// (frontend contract 6.1) and 503 IDEMPOTENCY_UNAVAILABLE; the package
// classifies every other status.
it("keeps 400, 409, 422 outside the table and an idempotency 503 uncertain even when the package calls them not applied", async () => {
const conflict = createFeatureHttpBinding(v3Executor(), LENIENT_OPERATIONS);
answer(
"post",
"/api/envelope-items",
failure("IDEMPOTENT_IN_FLIGHT", "CONFLICT", true),
{ status: 409, headers: { "Retry-After": "2" } },
);
await expect(v3CreateFailure(conflict)).resolves.toMatchObject({
effect: "MAYBE_APPLIED",
});
answer(
"post",
"/api/envelope-items",
failure("IDEMPOTENCY_UNAVAILABLE", "TRANSIENT_DEPENDENCY", true),
{ status: 503 },
);
await expect(v3CreateFailure(conflict)).resolves.toMatchObject({
effect: "MAYBE_APPLIED",
});
answer("post", "/api/envelope-items", failure("RESOURCE_CONFLICT", "CONFLICT", false), {
status: 409,
});
await expect(v3CreateFailure(conflict)).resolves.toMatchObject({
effect: "MAYBE_APPLIED",
});
answer("post", "/api/envelope-items", failure("BAD_PARAMETER", "VALIDATION", false), {
status: 400,
});
await expect(v3CreateFailure(conflict)).resolves.toMatchObject({
effect: "MAYBE_APPLIED",
});
// 1103/10-02. Fileserver writes the record before it answers this 422.
answer(
"post",
"/api/envelope-items",
failure("INTEGRITY_MISMATCH", "VALIDATION", false),
{ status: 422 },
);
await expect(v3CreateFailure(conflict)).resolves.toMatchObject({
effect: "MAYBE_APPLIED",
});
// 1103/03-04. The backend's other idempotency failures and its async
// request timeout say the command may have run (http-contract.md §2, §4).
for (const [status, code] of [
[503, "IDEMPOTENCY_COMPLETION_UNKNOWN"],
[500, "IDEMPOTENCY_RECOVERY_REQUIRED"],
[503, "REQUEST_TIMEOUT"],
] as const) {
answer("post", "/api/envelope-items", failure(code, "TRANSIENT_DEPENDENCY", true), {
status,
});
await expect(v3CreateFailure(conflict)).resolves.toMatchObject({
httpStatus: status,
code,
effect: "MAYBE_APPLIED",
});
}
// A 404 is the package's to classify.
answer("post", "/api/envelope-items", failure("NOT_FOUND", "NOT_FOUND", false), {
status: 404,
});
await expect(v3CreateFailure(conflict)).resolves.toMatchObject({
effect: "NOT_APPLIED",
});
});
});
// 1103/03-01. The paired backend scaffold's create checks the name before
// its transaction and answers 400 <FEATURE>_INVALID; the sample answers 409
// POSTER_ALREADY_EXISTS the same way. The operation that knows this declares
// those codes, and only those codes, as refused before the write.
describe("an operation's declared pre-write refusals", () => {
const CREATE_DECLARING_CONTRACT = Object.freeze({
...CREATE_CONTRACT,
contract: Object.freeze({
...CREATE_CONTRACT.contract,
commandEffect: Object.freeze({
...CREATE_CONTRACT.contract.commandEffect,
refusedBeforeWrite: Object.freeze(["WORKLOG_INVALID", "POSTER_ALREADY_EXISTS"]),
}) satisfies CommandEffectDescriptor<EnvelopeProblem>,
}),
});
const declaring = () =>
createFeatureHttpBinding(
v3Executor(),
Object.freeze({
ENVELOPE_CREATE_ITEM: defineFeatureHttpOperation({
contract: CREATE_DECLARING_CONTRACT,
routeId: "ENVELOPE_ROUTE",
mapSuccess: (value) => mappingSuccess(value),
}),
}),
);
it.each([
[400, "WORKLOG_INVALID", "UNKNOWN_CLIENT_FAILURE"],
[409, "POSTER_ALREADY_EXISTS", "CONFLICT"],
] as const)("reads a declared %i %s as not applied", async (status, code, kind) => {
answer("post", "/api/envelope-items", failure(code, "VALIDATION", false), { status });
await expect(v3CreateFailure(declaring()).then(verdict)).resolves.toMatchObject({
kind,
code,
httpStatus: status,
effect: "NOT_APPLIED",
});
});
it("keeps an undeclared business code and the in-flight 409 maybe applied", async () => {
answer("post", "/api/envelope-items", failure("WORKLOG_CONFLICT", "CONFLICT", false), {
status: 409,
});
await expect(v3CreateFailure(declaring())).resolves.toMatchObject({
effect: "MAYBE_APPLIED",
});
answer(
"post",
"/api/envelope-items",
failure("IDEMPOTENT_IN_FLIGHT", "CONFLICT", true),
{ status: 409, headers: { "Retry-After": "2" } },
);
await expect(v3CreateFailure(declaring())).resolves.toMatchObject({
effect: "MAYBE_APPLIED",
});
});
it("applies the list the composition installed", async () => {
answer("post", "/api/envelope-items", failure("WORKLOG_INVALID", "VALIDATION", false), {
status: 400,
});
const composed = composeContractContributions([
Object.freeze({
contributionId: "envelope-test-http-v1",
featureId: "envelope-test",
source: TEST_CONTRACT_CONTRIBUTION.source,
http: Object.freeze([CREATE_DECLARING_CONTRACT]) as never,
events: Object.freeze([]),
}),
]);
const installed = composed.httpByOperationId.get("ENVELOPE_CREATE_ITEM")!;
const executor = createContractHttpExecutor({
baseUrl: BASE_URL,
maxRetryAttempts: 0,
attachCredentials: () => ({ kind: "READY" as const, headers: {} }),
});
await expect(
executor.execute(installed, Object.freeze({}), {
routeId: "ENVELOPE_ROUTE",
scope: scope(),
intent: intent("ENVELOPE_CREATE_ITEM"),
}),
).resolves.toMatchObject({ kind: "PROBLEM", effect: "NOT_APPLIED" });
});
});
// 1101 README 14.4. An Envelope operation's executor knows the backend code
// and names an idempotency refusal in diagnostics (`reason`, a closed
// taxonomy); any other code stays out of diagnostics.
describe("V3 Envelope diagnostics name idempotency refusals", () => {
// 1103/03-05. An unknown result names its cause too, and every record
// carries the effect, so an in-flight 409 and a business 409 no longer
// read the same.
it.each([
["422 IDEMPOTENT_REQUEST_MISMATCH", 422, "IDEMPOTENT_REQUEST_MISMATCH", "IDEMPOTENT_REQUEST_MISMATCH", "NOT_APPLIED"],
["400 IDEMPOTENCY_KEY_INVALID", 400, "IDEMPOTENCY_KEY_INVALID", "IDEMPOTENCY_KEY_RULE_MISMATCH", "NOT_APPLIED"],
["400 VALIDATION_FAILED", 400, "VALIDATION_FAILED", undefined, "NOT_APPLIED"],
["409 IDEMPOTENT_IN_FLIGHT", 409, "IDEMPOTENT_IN_FLIGHT", "IN_FLIGHT", "MAYBE_APPLIED"],
["409 domain conflict", 409, "RESOURCE_CONFLICT", "STAGE_UNKNOWN", "MAYBE_APPLIED"],
["503 IDEMPOTENCY_UNAVAILABLE", 503, "IDEMPOTENCY_UNAVAILABLE", "IDEMPOTENCY_UNAVAILABLE", "MAYBE_APPLIED"],
["503 IDEMPOTENCY_COMPLETION_UNKNOWN", 503, "IDEMPOTENCY_COMPLETION_UNKNOWN", "COMPLETION_UNKNOWN", "MAYBE_APPLIED"],
["500 IDEMPOTENCY_RECOVERY_REQUIRED", 500, "IDEMPOTENCY_RECOVERY_REQUIRED", "RECOVERY_REQUIRED", "MAYBE_APPLIED"],
["503 REQUEST_TIMEOUT", 503, "REQUEST_TIMEOUT", "SERVER_TIMEOUT", "MAYBE_APPLIED"],
] as const)("%s", async (_label, status, code, reason, effect) => {
answer("post", "/api/envelope-items", failure(code, "VALIDATION", false), { status });
const records: DiagnosticRecordInput[] = [];
const project = createHttpObservationProjector({
diagnostics: { record: (input) => records.push(input) },
telemetry: { emit: () => {} },
});
await v3CreateFailure(
createFeatureHttpBinding(v3Executor(undefined, project), OPERATIONS),
);
expect(records).toHaveLength(1);
expect(records[0]?.context?.reason).toBe(reason);
expect(records[0]?.context?.effect_certainty).toBe(effect);
expect(projectDiagnosticRecord(records[0]!).success).toBe(true);
});
});
// §8.3 of the runtime design: a KEYED command is resent automatically only
// on a known answer that says resending is safe, never after a lost response.
// The paired backend's 503 IDEMPOTENCY_UNAVAILABLE is one (http-contract.md
// §2): refused before the command ran, resend with the same key.
describe("KEYED resend on the backend's pre-execution refusal", () => {
const RETRYING_CREATE = Object.freeze({
contract: CREATE_CONTRACT.contract,
frontend: Object.freeze({ ...CREATE_CONTRACT.frontend, retryBudget: 1 as const }),
});
async function run(
answers: readonly (() => Response)[],
contract: InstalledHttpContract<
Readonly<Record<never, never>>,
z.output<typeof itemSchema>,
EnvelopeProblem
>["contract"] = CREATE_CONTRACT.contract,
) {
const keys: (string | null)[] = [];
server.use(
http.post(`${BASE_URL}/api/envelope-items`, ({ request }) => {
keys.push(request.headers.get("idempotency-key"));
const next = answers[Math.min(keys.length - 1, answers.length - 1)]!;
return next();
}),
);
const executor = createContractHttpExecutor({
baseUrl: BASE_URL,
maxRetryAttempts: 2,
attachCredentials: () => ({ kind: "READY" as const, headers: {} }),
sleep: async () => {},
random: () => 0,
});
const outcome = await executor.execute({ ...RETRYING_CREATE, contract }, Object.freeze({}), {
routeId: "ENVELOPE_ROUTE",
scope: scope(),
intent: intent("ENVELOPE_CREATE_ITEM"),
});
return { outcome, keys };
}
const unavailable = () =>
HttpResponse.json(failure("IDEMPOTENCY_UNAVAILABLE", "TRANSIENT_DEPENDENCY", true), {
status: 503,
});
const created = () =>
HttpResponse.json(success({ id: "item-1", name: "First" }), { status: 201 });
it("resends once with the same key and takes the second answer", async () => {
const { outcome, keys } = await run([unavailable, created]);
expect(outcome).toMatchObject({ kind: "SUCCESS", effect: "APPLIED_CONFIRMED" });
expect(keys).toEqual([KEY, KEY]);
});
it("keeps the key and an unknown result when the budget runs out", async () => {
const { outcome, keys } = await run([unavailable]);
expect(outcome).toMatchObject({ kind: "PROBLEM", effect: "MAYBE_APPLIED" });
expect(keys).toEqual([KEY, KEY]);
});
// 1103/10-02 (03-08 M7). A same-key request that is still running is the
// user's to resend after Retry-After; the executor does not wait on it.
it("does not resend a 409 IDEMPOTENT_IN_FLIGHT on its own", async () => {
const { outcome, keys } = await run([
() =>
HttpResponse.json(failure("IDEMPOTENT_IN_FLIGHT", "CONFLICT", true), {
status: 409,
headers: { "Retry-After": "2" },
}),
created,
]);
expect(outcome).toMatchObject({ kind: "PROBLEM", effect: "MAYBE_APPLIED" });
expect(keys).toEqual([KEY]);
});
// 1103/03-04. "May be applied, resend later with the same key": the key
// is kept for the user's resend, and nothing is sent again on its own, even
// by a package that reads every problem as refused.
it.each([
[503, "IDEMPOTENCY_COMPLETION_UNKNOWN"],
[500, "IDEMPOTENCY_RECOVERY_REQUIRED"],
[503, "REQUEST_TIMEOUT"],
] as const)("keeps the key and does not resend %i %s", async (status, code) => {
const { outcome, keys } = await run(
[
() =>
HttpResponse.json(failure(code, "TRANSIENT_DEPENDENCY", true), {
status,
}),
created,
],
CREATE_LENIENT_CONTRACT.contract,
);
expect(outcome).toMatchObject({ kind: "PROBLEM", effect: "MAYBE_APPLIED" });
expect(keys).toEqual([KEY]);
});
it("does not resend a 503 the backend did not mark as a pre-execution refusal", async () => {
const { outcome, keys } = await run([
() =>
HttpResponse.json(failure("REQUEST_TIMEOUT", "TRANSIENT_DEPENDENCY", true), {
status: 503,
}),
created,
]);
expect(outcome).toMatchObject({ kind: "PROBLEM", effect: "MAYBE_APPLIED" });
expect(keys).toEqual([KEY]);
});
});
// 1103/10-02. A failure Envelope is read under the operation's own response
// limit and media type, not only the problem ceiling. Native Responses: MSW
// never settles a cancel() on a body it is still streaming.
describe("failure Envelope admission bounds", () => {
const conflictBody = (details?: JsonBodyType) =>
JSON.stringify(failure("RESOURCE_CONFLICT", "CONFLICT", false, details));
it("refuses a failure Envelope above the operation's response limit", async () => {
// Over the operation's 2 KiB, well under the 64 KiB problem ceiling.
const body = conflictBody({ note: "n".repeat(LIST_LIMIT) });
expect(body.length).toBeGreaterThan(LIST_LIMIT);
expect(body.length).toBeLessThan(16 * 1024);
const fetcher = (async () =>
new Response(body, {
status: 409,
headers: { "content-type": "application/json" },
})) as typeof fetch;
await expect(
v3CreateFailure(createFeatureHttpBinding(v3Executor(fetcher), OPERATIONS)),
).resolves.toMatchObject({
kind: "SCHEMA_MISMATCH",
code: "PROBLEM_SCHEMA_INVALID",
httpStatus: 409,
effect: "MAYBE_APPLIED",
});
});
it("refuses a failure Envelope that is not sent as JSON", async () => {
const fetcher = (async () =>
new Response(conflictBody(), {
status: 409,
headers: { "content-type": "text/plain" },
})) as typeof fetch;
await expect(
v3CreateFailure(createFeatureHttpBinding(v3Executor(fetcher), OPERATIONS)),
).resolves.toMatchObject({
kind: "CONTENT_TYPE_MISMATCH",
code: "CONTENT_TYPE_MISMATCH",
httpStatus: 409,
effect: "MAYBE_APPLIED",
});
});
});
describe("shared MSW scenarios for an Envelope operation", () => {
it.each([
["success", { ok: true, value: [{ id: "item-1", name: "First" }] }],
["empty", { ok: true, value: [] }],
["not-found-404", { ok: false, error: { kind: "NOT_FOUND", code: "NOT_FOUND" } }],
[
"server-terminal-503",
{ ok: false, error: { kind: "SERVER_FAILURE", code: "SERVER_FAILURE" } },
],
[
"envelope-mismatch",
{ ok: false, error: { kind: "ENVELOPE_MISMATCH", code: "ENVELOPE_MISMATCH" } },
],
[
"schema-mismatch",
{ ok: false, error: { kind: "SCHEMA_MISMATCH", code: "SUCCESS_SCHEMA_INVALID" } },
],
] as const)("answers %s in the backend's frame", async (scenario, expected) => {
server.use(
createHttpScenarioHandler(LIST_CONTRACT, {
scenario,
payload: [{ id: "item-1", name: "First" }],
}),
);
await expect(
v3().execute("ENVELOPE_LIST_ITEMS", Object.freeze({})),
).resolves.toMatchObject(expected);
});
});
describe("Envelope declaration at composition", () => {
function contribution(responseEnvelope: unknown) {
return Object.freeze({
contributionId: "envelope-test-http-v1",
featureId: "envelope-test",
source: TEST_CONTRACT_CONTRIBUTION.source,
http: Object.freeze([
Object.freeze({
...LIST_CONTRACT,
contract: Object.freeze({ ...LIST_CONTRACT.contract, responseEnvelope }),
}),
]) as never,
events: Object.freeze([]),
});
}
it("installs an operation that declares the Envelope and keeps the declaration", () => {
const composed = composeContractContributions([contribution("ENVELOPE_V1")]);
expect(
composed.httpByOperationId.get("ENVELOPE_LIST_ITEMS")?.contract.responseEnvelope,
).toBe("ENVELOPE_V1");
});
it("refuses a framing it does not know", () => {
expect(() => composeContractContributions([contribution("PROBLEM_JSON")])).toThrow(
expect.objectContaining({ reason: "envelope-test/ENVELOPE_LIST_ITEMS: responseEnvelope" }),
);
});
});