Files
clean-architecture-frontend…/tests/integration/http-execution-v3-envelope.test.ts
T
DongHyeonka 326120867c fix(http): 거절의 적용 여부를 백엔드 기준 표 하나로 V2·V3가 판정한다
문제
계약 문서 6.1절(ed0e4b1, 백엔드 5786126c 코드 기준)은 400·409·422 code마다
쓰기 전 거절인지를 정했다. 쓰기 전이라 적용 안 됨인 것은 400
VALIDATION_FAILED(details 모양과 상관없음), 400 IDEMPOTENCY_KEY_INVALID,
422 IDEMPOTENT_REQUEST_MISMATCH뿐이고, 표에 없는 400·409·422는 쓰기 뒤에도
나올 수 있어 결과 불명이다. 지금 판정은 이 표와 세 곳이 다르다.
- V2: 필드 목록 없는 400 VALIDATION_FAILED({cause}, details 없음,
  {field, code})에 effect가 없다. 결과 불명으로 붙들려 다시 저장할 수 없다.
- V2: 422는 code와 상관없이 적용 안 됨이다. fileserver의 422
  INTEGRITY_MISMATCH·MALWARE_DETECTED는 레코드를 쓴 뒤 던진다.
- V3 Envelope operation(7db32e1): 위 V2 규칙을 같이 쓰고, 표 밖 400·409·422는
  classifyProblem에 맡긴다. 400·422를 모두 적용 안 됨으로 보는 분류기면
  BAD_PARAMETER·도메인 400이 틀린다.

고른 방법
- backend-envelope.ts에 표 REFUSED_BEFORE_WRITE(code → status, 진단
  reason)를 하나 두고 V2 client.ts, V3 실행기가 envelopeFailureEffect로
  같이 읽는다. 표에 있으면 NOT_APPLIED, 그 밖의 400·409·422와 503
  IDEMPOTENCY_UNAVAILABLE은 MAYBE_APPLIED, 나머지 status는 undefined
  (V2는 effect 없음, V3는 classifyProblem)다. 진단 reason도 같은 표에서
  읽는다.
- kind와 validationIssues 판정(isFieldValidationFailure)은 그대로 둔다.
  필드 목록 없는 400 VALIDATION_FAILED는 UNKNOWN_CLIENT_FAILURE, 422는
  VALIDATION_REJECTED다. 적용 여부만 바뀐다.
- V3 Envelope operation에서는 400·409·422를 표가 정하고 classifyProblem이
  바꾸지 못한다.

버린 대안
- V2와 V3에 표를 따로 두기: 7db32e1 전처럼 두 벌이 갈라진다.
- 표 밖 400·409·422를 classifyProblem에 맡기기: 6.1절이 표 밖은
  MAYBE_APPLIED로 정했고, 적용 안 됨을 잘못 내면 다음 저장이 새 키를 써
  같은 작업이 두 번 적용된다. 잘못된 MAYBE_APPLIED는 결과 불명 화면만 남긴다.
- 422 전부를 필드 검증(적용 안 됨)으로 남기기: 짝 백엔드는 필드 검증을
  400으로 보내고, fileserver 422는 쓴 뒤 던진다.
- V3 참조 기능 분류기 고치기: 참조 기능은 Envelope operation이 아니고
  fixture가 problem details라 이 표의 대상이 아니다. 고치지 않았다.

위험·한계
- 필드 검증을 422로 보내는 다른 백엔드를 V2로 쓰는 프로젝트는 422 뒤에
  폼에서 다시 저장할 수 없다(결과 불명). 프론트 계약 문서 4.2절의 "422
  field validation" 행과 어긋난다. 그 문서는 이 커밋에서 고치지 않았다.
- 표는 백엔드 5786126c 기준이다. 백엔드가 쓰기 전 거절 code를 새로 만들면
  6.1절과 이 표를 함께 고쳐야 한다. 두 repo를 비교하는 검사는 없다.
- 6.1절의 남은 위험: 백엔드가 use case 안에서 VALIDATION_FAILED를 내게 되면
  적용 안 됨 판정이 틀린다.

검증
- RED: 바뀐 행 8건 실패. tests/integration/http-client.test.ts 필드 목록
  없는 400 VALIDATION_FAILED 3모양의 effect, http-diagnostics.test.ts의
  "unrelated 422"(effect NOT_APPLIED), http-execution-v3-envelope.test.ts의
  고정 판정 2건(VALIDATION_FAILED 3모양 NOT_APPLIED, BAD_PARAMETER·도메인
  409·fileserver 422 MAYBE_APPLIED), form-foundation.test.tsx 2건({cause}
  실패 뒤 다시 저장, 422 뒤 저장 버튼 꺼짐).
- GREEN: 위 4개 파일 128건 통과. V2와 V3에 같은 응답 11가지를 보내 판정을
  비교하는 행이 모두 같다.
- check:types, lint, check:architecture, check:diagnostics, check:ci,
  check:registries, check:adapter-inventory 통과. test:unit 2,604,
  test:integration 209, test:component 245, tests/features·tests/contract
  124건 통과. check:bundle 203,354 / 204,800 B.

Refs: docs/architecture/backend-api-and-server-state-contract.md 6.1 (ed0e4b1),
docs/reviews/2026-11-01-maturity-review/README.md 14.4, 14.6
2026-11-03 20:26:28 +09:00

782 lines
25 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 { createHttpClient } from "../../src/adapters/http/client.ts";
import {
createContractHttpExecutor,
createFeatureHttpBinding,
defineFeatureHttpOperation,
type HttpExecutionObservation,
type InstalledHttpOperationExecutor,
} from "../../src/adapters/http/index.ts";
import { createHttpObservationProjector } from "../../src/bootstrap/runtime-adapters.ts";
import 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 { createDemoSessionAdapter } from "../../src/adapters/auth/external-session-adapter.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 reaches the verdict the V2
* client reaches for the same answer (§2 idempotency, §4 VALIDATION_FAILED).
*/
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,
});
}
/** The same paths as V2 rows; V2 always reads the Envelope. */
const V2_OPERATIONS = Object.freeze({
ENVELOPE_LIST_ITEMS: Object.freeze({
method: "GET",
path: "/api/envelope-items",
operationId: "ENVELOPE_LIST_ITEMS",
auth: "external-session",
timeoutMs: null,
idempotency: "safe",
retry: "runtime",
requestSource: "none",
requestSchema: "EnvelopeTestNoInput",
responseSchema: "EnvelopeTestItemList",
maxResponseBytes: LIST_LIMIT,
owner: "test-fixture",
}),
ENVELOPE_CREATE_ITEM: Object.freeze({
method: "POST",
path: "/api/envelope-items",
operationId: "ENVELOPE_CREATE_ITEM",
auth: "external-session",
timeoutMs: null,
idempotency: "keyed",
retry: "never",
requestSource: "body",
requestSchema: "EnvelopeTestNoInput",
responseSchema: "EnvelopeTestItem",
successStatuses: [201],
maxResponseBytes: LIST_LIMIT,
owner: "test-fixture",
}),
});
const V2_PAYLOADS: Readonly<Record<string, z.ZodType>> = Object.freeze({
EnvelopeTestItemList: z.array(itemSchema).max(100),
EnvelopeTestItem: itemSchema,
});
function v2(
fetcher?: typeof fetch,
diagnostics?: Readonly<{ record(input: DiagnosticRecordInput): void }>,
) {
return createHttpClient({
baseUrl: BASE_URL,
...(fetcher === undefined ? {} : { fetcher }),
...(diagnostics === undefined ? {} : { diagnostics }),
maxRetryAttempts: 0,
clock: { now: () => 0, sleep: async () => {} },
authSession: createDemoSessionAdapter("authenticated"),
getOperation: (operationId: string) =>
V2_OPERATIONS[operationId as keyof typeof V2_OPERATIONS],
validatePayload(schemaId: string, value: unknown) {
const parsed = V2_PAYLOADS[schemaId]?.safeParse(value);
return parsed?.success
? { success: true as const, data: parsed.data }
: { success: false as const, issues: [] };
},
validateRequest: (_schemaId: string, value: unknown) => ({
success: true as const,
data: value,
}),
mapPayload: (_operationId: string, payload: unknown) =>
mappingSuccess(payload),
});
}
/** 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 v2CreateFailure(): Promise<AppFailure> {
const result = await v2().execute("ENVELOPE_CREATE_ITEM", {
body: {},
idempotencyKey: KEY,
});
if (result.ok) throw new Error("V2 create unexpectedly succeeded");
return result.error;
}
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" }],
});
});
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("서버가 보낸 문구");
});
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, as V2 counts maxResponseBytes", 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;
const v3Result = await v3(fetcher).execute(
"ENVELOPE_LIST_ITEMS",
Object.freeze({}),
);
const v2Result = await v2(fetcher).execute("ENVELOPE_LIST_ITEMS", {});
expect(v3Result).toMatchObject({ ok: false, error: { kind: "RESPONSE_BODY_LIMIT" } });
expect(v2Result).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 equal the V2 client's for the same answer", () => {
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) },
],
];
it.each(cases)("%s", async (_label, response) => {
answer("post", "/api/envelope-items", response.body, response);
const v2Verdict = verdict(await v2CreateFailure());
const v3Verdict = verdict(await v3CreateFailure());
expect(v3Verdict).toEqual(v2Verdict);
});
it("pins what those verdicts are", async () => {
const read = async (response: (typeof cases)[number][1]) => {
answer("post", "/api/envelope-items", response.body, response);
return verdict(await v3CreateFailure());
};
const byLabel = new Map(cases);
await expect(read(byLabel.get("409 IDEMPOTENT_IN_FLIGHT")!)).resolves.toMatchObject({
kind: "CONFLICT",
effect: "MAYBE_APPLIED",
retryAfterMs: 2_000,
});
await expect(
read(byLabel.get("422 IDEMPOTENT_REQUEST_MISMATCH")!),
).resolves.toMatchObject({ kind: "VALIDATION_REJECTED", effect: "NOT_APPLIED" });
await expect(read(byLabel.get("400 IDEMPOTENCY_KEY_INVALID")!)).resolves.toMatchObject({
kind: "UNKNOWN_CLIENT_FAILURE",
code: "IDEMPOTENCY_KEY_INVALID",
effect: "NOT_APPLIED",
});
await expect(read(byLabel.get("503 IDEMPOTENCY_UNAVAILABLE")!)).resolves.toMatchObject({
kind: "SERVER_FAILURE",
effect: "MAYBE_APPLIED",
});
await expect(
read(byLabel.get("400 VALIDATION_FAILED with the field list")!),
).resolves.toMatchObject({
kind: "VALIDATION_REJECTED",
effect: "NOT_APPLIED",
validationIssues: [{ path: "name", code: "NOT_BLANK" }],
});
// 1101/14.4. Every VALIDATION_FAILED is raised before a write.
for (const label of [
"400 VALIDATION_FAILED for an unreadable body",
"400 VALIDATION_FAILED without details",
"400 VALIDATION_FAILED for a page parameter",
]) {
await expect(read(byLabel.get(label)!)).resolves.toMatchObject({
kind: "UNKNOWN_CLIENT_FAILURE",
code: "VALIDATION_FAILED",
effect: "NOT_APPLIED",
});
}
// Codes the backend can raise after a write.
for (const label of [
"400 BAD_PARAMETER",
"409 domain conflict",
"422 INTEGRITY_MISMATCH",
]) {
await expect(read(byLabel.get(label)!)).resolves.toMatchObject({
effect: "MAYBE_APPLIED",
});
}
});
// 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",
});
// 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",
});
});
});
// 1101 README 14.4. V2 names an idempotency refusal in diagnostics (`reason`,
// a closed taxonomy). An Envelope operation's executor now knows the backend
// code and names the same ones; any other code stays out of diagnostics.
describe("V3 Envelope diagnostics name what V2 names", () => {
it.each([
["422 IDEMPOTENT_REQUEST_MISMATCH", 422, "IDEMPOTENT_REQUEST_MISMATCH", "IDEMPOTENT_REQUEST_MISMATCH"],
["400 IDEMPOTENCY_KEY_INVALID", 400, "IDEMPOTENCY_KEY_INVALID", "IDEMPOTENCY_KEY_RULE_MISMATCH"],
["409 IDEMPOTENT_IN_FLIGHT", 409, "IDEMPOTENT_IN_FLIGHT", undefined],
["409 domain conflict", 409, "RESOURCE_CONFLICT", undefined],
] as const)("%s", async (_label, status, code, reason) => {
answer("post", "/api/envelope-items", failure(code, "VALIDATION", false), { status });
const v2Records: DiagnosticRecordInput[] = [];
const v3Records: DiagnosticRecordInput[] = [];
const project = createHttpObservationProjector({
diagnostics: { record: (input) => v3Records.push(input) },
telemetry: { emit: () => {} },
});
await v2(undefined, { record: (input) => v2Records.push(input) }).execute(
"ENVELOPE_CREATE_ITEM",
{ body: {}, idempotencyKey: KEY },
);
await v3CreateFailure(
createFeatureHttpBinding(v3Executor(undefined, project), OPERATIONS),
);
expect(v2Records).toHaveLength(1);
expect(v3Records).toHaveLength(1);
expect(v3Records[0]?.context?.reason).toBe(reason);
expect(v3Records[0]?.context?.reason).toBe(v2Records[0]?.context?.reason);
});
});
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" }),
);
});
});