문제
HTTP 실행 경로가 둘이다. V3 실행기(createContractHttpExecutor)가 모든 기능을
실행하고, V2 클라이언트(createHttpClient)는 bootstrap의
createRuntimeHttpClient에서만 만들어지는데 그 함수를 앱 안에서 부르는 곳이
없다(테스트만 부른다). tech-log·memento도 같다. 그런데도 V2는 초기 청크에
들어가고, 짝 백엔드 해석(7db32e1~3261208)과 테스트를 두 벌로 유지하게 했다.
사용자 지시: 레거시를 두지 말고 최신 경로 하나만 남긴다.
고른 방법
- src/adapters/http/의 client.ts, bounded-json.ts, request-builder.ts,
resource-mapper.ts, retry-policy.ts, schema-registry.ts를 지웠다. Envelope
스키마는 backend-envelope.ts로 옮겼다. V3가 retry-policy.ts에서 쓰던
parseRetryAfter는 그것이 감싸던 platform/retry-after.ts의
parseRetryAfterDelay를 직접 부른다.
- 배럴의 V2 export와 bootstrap의 createRuntimeHttpClient·RuntimeHttpContract를
지웠다.
- V2 전용 테스트(http-client, http-diagnostics, auth-recovery,
legacy-http-credential-authority, bounded-json-compatibility,
request-builder, retry-policy)와 tests/helpers/http-contract-fixture.ts를
지웠다. 섞인 파일(http-execution-contract, runtime-adapters,
boundary-mapper)은 V2 블록만 지웠다.
- V2로 돌던 폼 테스트(form-foundation)는 Envelope을 읽는 V3 keyed create
계약으로 옮겼다. 400 VALIDATION_FAILED 필드 오류, {cause} 뒤 다시 저장,
422 뒤 저장 꺼짐을 그대로 검사한다. http-execution-v3-envelope 테스트는 V2와
비교하던 행을 기대 판정을 직접 적는 행으로 바꿨다.
- drill:runbook FE-RB-003은 V2 shouldRetry 대신 V3 실행기를 실제로 돌려
보낸 요청 수를 센다(NEVER 503: 1회, SAFE 503: 재시도, SAFE 스키마 불일치:
1회).
- check:diagnostics의 http 이벤트 생산자, registry-governance의 오류 표 소비자,
risk-coverage 고위험 경로, 아키텍처 금지 fixture, adapter INVENTORY, 문서의
경로를 V3 파일로 바꿨다.
버린 대안
- V2를 @deprecated로 한 릴리스 남기기: 템플릿과 두 다운스트림 모두 부르는
곳이 없어 옮겨 갈 사용자가 없다. 남기면 초기 JS와 두 벌 유지 비용만 남는다.
위험·한계
- BREAKING: 배럴과 bootstrap의 V2 이름을 쓰던 제품 코드는 컴파일이 깨진다.
CHANGELOG에 옮기는 방법을 적었다.
- V2에만 있던 동작이 사라졌다: 401 뒤 세션 복구 후 한 번 재전송, KEYED 503
자동 재시도. V3는 401을 UNAUTHENTICATED로 넘기고 KEYED 요청은 보낸 뒤
재시도하지 않는다.
- 기능마다 적는 V2 API 행(*-api-contract.ts, check:registries가 읽음)은 이
커밋에서 지우지 않았다. 다음 커밋이 지운다.
검증
- check:types, lint, check:architecture(금지 fixture 9건 거절),
check:adapter-inventory(140 files), check:diagnostics, check:registries,
check:ci, verify:documentation 통과.
- test:unit 2,585, test:integration 114, test:component 245, test:contract 23,
test:runtime-schema 56, tests/features 101 통과.
- drill:runbook FE-RB-003: no local check failed.
- check:bundle 통과. 초기 JS 203,354 → 201,598 B(−1,756 B).
BREAKING CHANGE: src/adapters/http/index.ts가 createHttpClient, HttpClient,
HttpClientDependencies, HttpFailure, HttpResult, LegacyHttpInput, Scheduler,
OperationRequestInput를, src/bootstrap/runtime-adapters.ts가
createRuntimeHttpClient, RuntimeHttpContract를 내보내지 않는다. 그 operation의
V3 descriptor를 만들어 createFeatureHttpBinding으로 실행한다.
674 lines
22 KiB
TypeScript
674 lines
22 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 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" }],
|
|
});
|
|
});
|
|
|
|
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", 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,
|
|
},
|
|
"422 IDEMPOTENT_REQUEST_MISMATCH": { kind: "VALIDATION_REJECTED", 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" },
|
|
"422 INTEGRITY_MISMATCH": { kind: "VALIDATION_REJECTED", 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",
|
|
});
|
|
|
|
// 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. 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", () => {
|
|
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 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);
|
|
});
|
|
});
|
|
|
|
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" }),
|
|
);
|
|
});
|
|
});
|