문제 짝 백엔드는 이제 값이 null인 필드를 키째 뺀다(백엔드 docs/web/http-contract.md §1). V2 Envelope 스키마 (src/adapters/http/schema-registry.ts)는 두 곳에서 "키 없음"을 null과 다르게 읽는다. - 성공 응답의 data: z.unknown()은 키가 없으면 거절한다(zod 4). 백엔드가 data:null을 빼고 보낸 성공이 ENVELOPE_MISMATCH 실패가 된다. data:null은 그대로 통과한다. - meta.requestId·traceId가 필수다. 백엔드는 요청 id 필터 앞에서 끊긴 응답(보안 entry point 등)에서 이 키를 뺄 수 있다고 적는다. 그러면 실패 Envelope 전체가 거절되어 백엔드 error.code가 HTTP_FAILURE로 바뀐다. error.details(키 없음 허용), meta.correlationId(선택), meta.page(strip)는 이미 키가 없어도 받는다. 고른 방법 - data를 z.unknown().default(null)로 둔다. 키가 없으면 스키마가 null을 채우므로 client.ts의 "data" in 검사와 payload 검증이 data:null과 같은 길을 탄다. 정규화가 wire 스키마 한 곳에 있다. - meta.requestId·traceId를 optional로 둔다. safeMeta()는 이미 키가 없는 경우를 처리한다. 버린 대안 - client.ts에서 "data" in 검사를 빼고 data ?? null로 읽기: 스키마와 클라이언트 두 곳이 같은 규칙을 나눠 갖는다. - 성공의 error:null, 실패의 data:null도 다시 받기: 백엔드가 더는 보내지 않는 모양이다. 최상위 strict는 그대로 둔다. 위험·한계 - meta id가 없는 Envelope도 이제 유효하다. 그런 응답의 HttpResult.meta와 AppFailure에는 requestId·traceId가 없다(이전에는 응답 전체가 거절됐다). - V3 실행기는 Envelope를 읽지 않는다(DTO 자체를 검증). 이 변경은 V2 경로만 바꾼다. bulk Envelope(results)는 프론트에 쓰는 곳이 없어 다루지 않았다. 검증 - RED: tests/integration/http-client.test.ts "envelope keys the paired backend omits" 5행 중 2행 실패. data 키 없는 성공이 ok:false, id 키 없는 403이 code HTTP_FAILURE. - GREEN: 같은 5행 통과. tests/integration/http-client·http-diagnostics· http-execution-contract·auth-recovery·legacy-http-credential-authority, tests/runtime-schema 8 files 150 tests 통과. tsc app·test 통과, 바꾼 파일 eslint 통과. Refs: clean-architecture-backend-template docs/reviews/2026-11-01-maturity-review/README.md 14.3, 15
577 lines
18 KiB
TypeScript
577 lines
18 KiB
TypeScript
import { HttpResponse, http } from "msw";
|
|
import { setupServer } from "msw/node";
|
|
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
|
|
|
|
import { createHttpClient } from "../../src/adapters/http/client.ts";
|
|
import { mappingSuccess } from "../../src/contracts/boundary-mapper.ts";
|
|
import {
|
|
TEST_HTTP_CONTRACT,
|
|
TEST_OPERATIONS,
|
|
} from "../helpers/http-contract-fixture.ts";
|
|
|
|
let attempts = 0;
|
|
const server = setupServer(
|
|
http.get("https://api.test/api/entities", () => {
|
|
attempts += 1;
|
|
if (attempts < 3) {
|
|
return HttpResponse.json(
|
|
{ success: false, error: { code: "TEMPORARY" } },
|
|
{ status: 503 },
|
|
);
|
|
}
|
|
return HttpResponse.json({
|
|
success: true,
|
|
data: [{ id: "resource-1", name: "Example" }],
|
|
meta: { requestId: "request-1", traceId: "trace-1" },
|
|
});
|
|
}),
|
|
);
|
|
|
|
beforeAll(() => server.listen({ onUnhandledRequest: "error" }));
|
|
afterEach(() => {
|
|
attempts = 0;
|
|
server.resetHandlers();
|
|
});
|
|
afterAll(() => server.close());
|
|
|
|
const clock = {
|
|
now: () => 0,
|
|
sleep: async () => {},
|
|
};
|
|
|
|
type HttpDependencies = Parameters<typeof createHttpClient>[0];
|
|
|
|
function testClient(options: HttpDependencies) {
|
|
return createHttpClient({ ...TEST_HTTP_CONTRACT, ...options });
|
|
}
|
|
|
|
describe("shared HTTP client", () => {
|
|
it("retries a safe request at most twice and returns validated data", async () => {
|
|
const client = testClient({
|
|
baseUrl: "https://api.test",
|
|
clock,
|
|
random: () => 0,
|
|
});
|
|
|
|
await expect(
|
|
client.execute("LIST_ENTITIES", { routeId: "TEST_ROUTE" }),
|
|
).resolves.toMatchObject({
|
|
ok: true,
|
|
value: [{ id: "resource-1", displayName: "Example" }],
|
|
meta: { requestId: "request-1" },
|
|
});
|
|
expect(attempts).toBe(3);
|
|
});
|
|
|
|
it.each(["", " ", "bad\u0000key", "x".repeat(513)])(
|
|
"rejects invalid keyed command key %j before credentials and fetch",
|
|
async (idempotencyKey) => {
|
|
let fetched = 0;
|
|
let credentialAttempts = 0;
|
|
server.use(
|
|
http.post("https://api.test/api/entities", () => {
|
|
fetched += 1;
|
|
return HttpResponse.json({ success: true, data: {} });
|
|
}),
|
|
);
|
|
const client = testClient({
|
|
baseUrl: "https://api.test",
|
|
clock,
|
|
authSession: {
|
|
getState: () => "authenticated",
|
|
getSubject: () => "user-a",
|
|
subscribe: () => () => {},
|
|
beginSignIn: async () => {},
|
|
signOut: async () => {},
|
|
async credentialPatch() {
|
|
credentialAttempts += 1;
|
|
return { headers: {} };
|
|
},
|
|
recover: async () => "no-session" as const,
|
|
onUnauthenticated: () => {},
|
|
},
|
|
});
|
|
|
|
await expect(
|
|
client.execute("CREATE_ENTITY", {
|
|
body: { name: "n" },
|
|
idempotencyKey,
|
|
}),
|
|
).resolves.toMatchObject({
|
|
ok: false,
|
|
error: {
|
|
kind: "VALIDATION_REJECTED",
|
|
code: "IDEMPOTENCY_KEY_INVALID",
|
|
// The repository reports attempt counts as 1-based; the invariant
|
|
// proved below is that no physical attempt happened at all.
|
|
attemptCount: 1,
|
|
},
|
|
});
|
|
expect(fetched).toBe(0);
|
|
expect(credentialAttempts).toBe(0);
|
|
},
|
|
);
|
|
|
|
it("bounds a non-cooperative legacy credential owner by total deadline", async () => {
|
|
let fetched = 0;
|
|
let observedSignal: AbortSignal | undefined;
|
|
server.use(
|
|
http.get("https://api.test/api/entities", () => {
|
|
fetched += 1;
|
|
return HttpResponse.json({ success: true, data: [] });
|
|
}),
|
|
);
|
|
const client = testClient({
|
|
baseUrl: "https://api.test",
|
|
timeoutMs: 5,
|
|
clock: { now: () => 0, sleep: async () => {} },
|
|
authSession: {
|
|
getState: () => "authenticated",
|
|
getSubject: () => "user-a",
|
|
subscribe: () => () => {},
|
|
beginSignIn: async () => {},
|
|
signOut: async () => {},
|
|
credentialPatch: (_binding, context) => {
|
|
observedSignal = context?.signal;
|
|
// Never settles on its own.
|
|
return new Promise<never>(() => {});
|
|
},
|
|
recover: async () => "no-session" as const,
|
|
onUnauthenticated: () => {},
|
|
},
|
|
});
|
|
|
|
const result = await client.execute("LIST_ENTITIES");
|
|
expect(result).toMatchObject({ ok: false });
|
|
expect(fetched).toBe(0);
|
|
expect(observedSignal).toBeDefined();
|
|
});
|
|
|
|
it("rejects a non-JSON response without exposing its body", async () => {
|
|
server.use(
|
|
http.get(
|
|
"https://api.test/api/entities",
|
|
() => new HttpResponse("<secret>raw body</secret>", { status: 200 }),
|
|
),
|
|
);
|
|
const client = testClient({ baseUrl: "https://api.test", clock });
|
|
const result = await client.execute("LIST_ENTITIES");
|
|
|
|
expect(result).toMatchObject({
|
|
ok: false,
|
|
error: { kind: "CONTENT_TYPE_MISMATCH" },
|
|
});
|
|
expect(JSON.stringify(result)).not.toContain("raw body");
|
|
});
|
|
|
|
// Q-6.3-3b. A gateway 5xx/408/425 with an HTML, empty or broken body is a
|
|
// server outage, not a contract breach: it keeps its status and the V2
|
|
// SERVER_FAILURE retry rule (408/425/502/503/504, R3-1).
|
|
it.each([
|
|
{ status: 502, contentType: "text/html", body: "<secret>raw body</secret>", fetches: 3 },
|
|
{ status: 503, contentType: "application/json", body: "", fetches: 3 },
|
|
{ status: 504, contentType: "application/json", body: "{", fetches: 3 },
|
|
{ status: 408, contentType: "text/plain", body: "timeout", fetches: 3 },
|
|
{ status: 425, contentType: "text/html", body: "<p>too early</p>", fetches: 3 },
|
|
])(
|
|
"keeps a $status gateway body as a server failure with its status",
|
|
async ({ status, contentType, body, fetches }) => {
|
|
let fetched = 0;
|
|
server.use(
|
|
http.get("https://api.test/api/entities", () => {
|
|
fetched += 1;
|
|
return new HttpResponse(body, {
|
|
status,
|
|
headers: { "Content-Type": contentType },
|
|
});
|
|
}),
|
|
);
|
|
const client = testClient({
|
|
baseUrl: "https://api.test",
|
|
clock,
|
|
random: () => 0,
|
|
});
|
|
const result = await client.execute("LIST_ENTITIES");
|
|
|
|
expect(result).toMatchObject({
|
|
ok: false,
|
|
error: { kind: "SERVER_FAILURE", httpStatus: status },
|
|
});
|
|
expect(fetched).toBe(fetches);
|
|
expect(JSON.stringify(result)).not.toContain("raw body");
|
|
},
|
|
);
|
|
|
|
const errorEnvelope = {
|
|
success: false,
|
|
error: { code: "UPSTREAM_BUSY" },
|
|
meta: { requestId: "request-1", traceId: "trace-1" },
|
|
};
|
|
|
|
// A gateway body (not an envelope) or a valid V2 error envelope.
|
|
function busyResponse(
|
|
status: number,
|
|
envelope: boolean,
|
|
headers: Record<string, string> = {},
|
|
) {
|
|
return envelope
|
|
? HttpResponse.json(errorEnvelope, { status, headers })
|
|
: new HttpResponse("busy", {
|
|
status,
|
|
headers: { "Content-Type": "text/plain", ...headers },
|
|
});
|
|
}
|
|
|
|
const busyCases = [408, 425, 503].flatMap((status) => [
|
|
{ status, envelope: false },
|
|
{ status, envelope: true },
|
|
]);
|
|
|
|
// R3-1. A 408/425 with a valid error envelope is a server failure in V2 and
|
|
// keeps the backend code the envelope carries.
|
|
it.each([408, 425, 503])(
|
|
"retries a safe request on a %i error envelope and keeps its code",
|
|
async (status) => {
|
|
let fetched = 0;
|
|
server.use(
|
|
http.get("https://api.test/api/entities", () => {
|
|
fetched += 1;
|
|
return busyResponse(status, true);
|
|
}),
|
|
);
|
|
const client = testClient({
|
|
baseUrl: "https://api.test",
|
|
clock,
|
|
random: () => 0,
|
|
});
|
|
|
|
await expect(client.execute("LIST_ENTITIES")).resolves.toMatchObject({
|
|
ok: false,
|
|
error: {
|
|
kind: "SERVER_FAILURE",
|
|
code: "UPSTREAM_BUSY",
|
|
httpStatus: status,
|
|
requestId: "request-1",
|
|
},
|
|
});
|
|
expect(fetched).toBe(3);
|
|
},
|
|
);
|
|
|
|
// R3-1. 408/425/503 follow the retry rule of the operation: a keyed command
|
|
// may replay, a non-idempotent command is never replayed.
|
|
it.each(
|
|
busyCases.flatMap((busy) => [
|
|
{ ...busy, idempotency: "none" as const, fetches: 1 },
|
|
{ ...busy, idempotency: "keyed" as const, fetches: 3 },
|
|
]),
|
|
)(
|
|
"sends a $idempotency command $fetches time(s) on $status (envelope: $envelope)",
|
|
async ({ status, envelope, idempotency, fetches }) => {
|
|
let fetched = 0;
|
|
server.use(
|
|
http.post("https://api.test/api/entities", () => {
|
|
fetched += 1;
|
|
return busyResponse(status, envelope);
|
|
}),
|
|
);
|
|
const client = testClient({
|
|
baseUrl: "https://api.test",
|
|
clock,
|
|
random: () => 0,
|
|
getOperation: () => ({ ...TEST_OPERATIONS.CREATE_ENTITY, idempotency }),
|
|
});
|
|
const result = await client.execute("CREATE_ENTITY", {
|
|
body: { name: "n" },
|
|
...(idempotency === "keyed" ? { idempotencyKey: "key-1" } : {}),
|
|
});
|
|
|
|
expect(result).toMatchObject({
|
|
ok: false,
|
|
error: { kind: "SERVER_FAILURE", httpStatus: status },
|
|
});
|
|
expect(fetched).toBe(fetches);
|
|
},
|
|
);
|
|
|
|
function retryAfterClient(delays: number[]) {
|
|
return testClient({
|
|
baseUrl: "https://api.test",
|
|
clock: {
|
|
now: () => 0,
|
|
sleep: async (ms: number) => {
|
|
delays.push(ms);
|
|
},
|
|
},
|
|
random: () => 0.5, // local backoff for the first retry: 125ms
|
|
});
|
|
}
|
|
|
|
function listAfter(first: () => Response) {
|
|
let fetched = 0;
|
|
server.use(
|
|
http.get("https://api.test/api/entities", () => {
|
|
fetched += 1;
|
|
return fetched === 1
|
|
? first()
|
|
: HttpResponse.json({
|
|
success: true,
|
|
data: [],
|
|
meta: { requestId: "request-1", traceId: "trace-1" },
|
|
});
|
|
}),
|
|
);
|
|
}
|
|
|
|
// R3-1. The retry waits at least the Retry-After of a 408/425/503, under
|
|
// the same 30s ceiling as a 429.
|
|
it.each(busyCases)(
|
|
"waits for the Retry-After of a $status (envelope: $envelope)",
|
|
async ({ status, envelope }) => {
|
|
listAfter(() => busyResponse(status, envelope, { "Retry-After": "2" }));
|
|
const delays: number[] = [];
|
|
await expect(
|
|
retryAfterClient(delays).execute("LIST_ENTITIES"),
|
|
).resolves.toMatchObject({ ok: true });
|
|
expect(delays).toEqual([2_000]);
|
|
},
|
|
);
|
|
|
|
// R3-1. 502/504 keep the local backoff whatever Retry-After says.
|
|
it.each([502, 504])(
|
|
"ignores the Retry-After of a %i",
|
|
async (status) => {
|
|
listAfter(() => busyResponse(status, true, { "Retry-After": "2" }));
|
|
const delays: number[] = [];
|
|
await expect(
|
|
retryAfterClient(delays).execute("LIST_ENTITIES"),
|
|
).resolves.toMatchObject({ ok: true });
|
|
expect(delays).toEqual([125]);
|
|
},
|
|
);
|
|
|
|
it.each(busyCases)(
|
|
"does not retry a $status whose Retry-After exceeds 30 seconds (envelope: $envelope)",
|
|
async ({ status, envelope }) => {
|
|
let fetched = 0;
|
|
server.use(
|
|
http.get("https://api.test/api/entities", () => {
|
|
fetched += 1;
|
|
return busyResponse(status, envelope, { "Retry-After": "31" });
|
|
}),
|
|
);
|
|
const delays: number[] = [];
|
|
await expect(
|
|
retryAfterClient(delays).execute("LIST_ENTITIES"),
|
|
).resolves.toMatchObject({
|
|
ok: false,
|
|
error: { kind: "SERVER_FAILURE", httpStatus: status, retryAfterMs: 31_000 },
|
|
});
|
|
expect(fetched).toBe(1);
|
|
expect(delays).toEqual([]);
|
|
},
|
|
);
|
|
|
|
// R3-1. Retry-After goes through the platform kernel parser: delta-seconds
|
|
// or an IMF-fixdate only. Anything else falls back to the local backoff.
|
|
it.each([
|
|
{ value: "2", delay: 2_000 },
|
|
{ value: " 2 ", delay: 2_000 },
|
|
{ value: "Thu, 01 Jan 1970 00:00:05 GMT", delay: 5_000 },
|
|
{ value: "", delay: 125 },
|
|
{ value: " ", delay: 125 },
|
|
{ value: "1e3", delay: 125 },
|
|
{ value: "1.5", delay: 125 },
|
|
{ value: "0x10", delay: 125 },
|
|
{ value: "-1", delay: 125 },
|
|
{ value: "2099-01-01T00:00:00Z", delay: 125 },
|
|
{ value: "Thursday, 01-Jan-70 00:00:05 GMT", delay: 125 },
|
|
])("parses a 429 Retry-After of $value as $delay ms", async ({ value, delay }) => {
|
|
let fetched = 0;
|
|
server.use(
|
|
http.get("https://api.test/api/entities", () => {
|
|
fetched += 1;
|
|
return fetched === 1
|
|
? HttpResponse.json(
|
|
{
|
|
success: false,
|
|
error: { code: "RATE_LIMITED" },
|
|
meta: { requestId: "request-1", traceId: "trace-1" },
|
|
},
|
|
{ status: 429, headers: { "Retry-After": value } },
|
|
)
|
|
: HttpResponse.json({
|
|
success: true,
|
|
data: [],
|
|
meta: { requestId: "request-1", traceId: "trace-1" },
|
|
});
|
|
}),
|
|
);
|
|
const delays: number[] = [];
|
|
await expect(
|
|
retryAfterClient(delays).execute("LIST_ENTITIES"),
|
|
).resolves.toMatchObject({ ok: true });
|
|
expect(delays).toEqual([delay]);
|
|
});
|
|
|
|
it("classifies malformed JSON and invalid payloads at the boundary", async () => {
|
|
server.use(
|
|
http.get(
|
|
"https://api.test/api/entities",
|
|
() =>
|
|
new HttpResponse("{", {
|
|
headers: { "Content-Type": "application/json" },
|
|
}),
|
|
),
|
|
);
|
|
const client = testClient({ baseUrl: "https://api.test", clock });
|
|
await expect(client.execute("LIST_ENTITIES")).resolves.toMatchObject({
|
|
ok: false,
|
|
error: { kind: "MALFORMED_JSON" },
|
|
});
|
|
|
|
server.use(
|
|
http.get("https://api.test/api/entities", () =>
|
|
HttpResponse.json({
|
|
success: true,
|
|
data: [{ id: "resource-1", name: 42 }],
|
|
meta: { requestId: "request-1", traceId: "trace-1" },
|
|
}),
|
|
),
|
|
);
|
|
await expect(client.execute("LIST_ENTITIES")).resolves.toMatchObject({
|
|
ok: false,
|
|
error: { kind: "SCHEMA_MISMATCH" },
|
|
});
|
|
});
|
|
|
|
it("projects only approved 422 issue path and code metadata", async () => {
|
|
server.use(
|
|
http.post("https://api.test/api/entities", () =>
|
|
HttpResponse.json(
|
|
{
|
|
success: false,
|
|
error: {
|
|
code: "INVALID_INPUT",
|
|
message: "raw backend secret",
|
|
details: {
|
|
issues: [
|
|
{ path: "name", code: "REQUIRED", message: "raw field copy" },
|
|
{ path: 42, code: "INVALID" },
|
|
],
|
|
},
|
|
},
|
|
meta: { requestId: "request-422", traceId: "trace-422" },
|
|
},
|
|
{ status: 422 },
|
|
),
|
|
),
|
|
);
|
|
const client = testClient({ baseUrl: "https://api.test", clock });
|
|
const result = await client.execute("CREATE_ENTITY", {
|
|
routeId: "TEST_FORM",
|
|
body: { name: "Valid" },
|
|
});
|
|
|
|
expect(result).toMatchObject({
|
|
ok: false,
|
|
error: {
|
|
kind: "VALIDATION_REJECTED",
|
|
validationIssues: [{ path: "name", code: "REQUIRED" }],
|
|
},
|
|
});
|
|
expect(JSON.stringify(result)).not.toContain("raw backend secret");
|
|
expect(JSON.stringify(result)).not.toContain("raw field copy");
|
|
});
|
|
|
|
it("guards mapper exceptions as a mapping contract violation", async () => {
|
|
server.use(
|
|
http.get("https://api.test/api/entities", () =>
|
|
HttpResponse.json({
|
|
success: true,
|
|
data: [{ id: "resource-1", name: "Example" }],
|
|
meta: { requestId: "request-1", traceId: "trace-1" },
|
|
}),
|
|
),
|
|
);
|
|
const client = testClient({
|
|
baseUrl: "https://api.test",
|
|
clock,
|
|
mapPayload: () => {
|
|
throw new Error("raw mapper detail");
|
|
},
|
|
});
|
|
|
|
const result = await client.execute("LIST_ENTITIES");
|
|
expect(result).toMatchObject({
|
|
ok: false,
|
|
error: { kind: "MAPPING_CONTRACT_VIOLATION" },
|
|
});
|
|
expect(JSON.stringify(result)).not.toContain("raw mapper detail");
|
|
});
|
|
});
|
|
|
|
// 백엔드 1101/02-02. The paired backend drops a null field together with its
|
|
// key (its docs/web/http-contract.md §1). A missing key must read as the null
|
|
// it stands for.
|
|
describe("envelope keys the paired backend omits", () => {
|
|
const meta = { requestId: "request-1", traceId: "trace-1" };
|
|
|
|
it.each([
|
|
{ shape: "data: null", body: { success: true, data: null, meta } },
|
|
{ shape: "no data key", body: { success: true, meta } },
|
|
])("reads a success with $shape as null data", async ({ body }) => {
|
|
server.use(
|
|
http.get("https://api.test/api/entities", () => HttpResponse.json(body)),
|
|
);
|
|
const validated: unknown[] = [];
|
|
const client = testClient({
|
|
baseUrl: "https://api.test",
|
|
clock,
|
|
validatePayload: (_schemaId, value) => {
|
|
validated.push(value);
|
|
return { success: true, data: value };
|
|
},
|
|
mapPayload: (_operationId, value) => mappingSuccess(value),
|
|
});
|
|
|
|
await expect(client.execute("LIST_ENTITIES")).resolves.toMatchObject({
|
|
ok: true,
|
|
value: null,
|
|
});
|
|
expect(validated).toEqual([null]);
|
|
});
|
|
|
|
it.each([
|
|
{ shape: "with ids and details", meta, details: { reason: "X" } },
|
|
{ shape: "without details", meta, details: undefined },
|
|
// Answered before the request id filter: the id keys are absent.
|
|
{ shape: "without ids", meta: {}, details: undefined },
|
|
])("keeps the backend code of a failure $shape", async ({ meta, details }) => {
|
|
server.use(
|
|
http.get("https://api.test/api/entities", () =>
|
|
HttpResponse.json(
|
|
{
|
|
success: false,
|
|
error: {
|
|
code: "ACCESS_DENIED",
|
|
category: "FORBIDDEN",
|
|
message: "권한이 없습니다.",
|
|
retryable: false,
|
|
...(details === undefined ? {} : { details }),
|
|
},
|
|
meta,
|
|
},
|
|
{ status: 403 },
|
|
),
|
|
),
|
|
);
|
|
const client = testClient({ baseUrl: "https://api.test", clock });
|
|
|
|
await expect(client.execute("LIST_ENTITIES")).resolves.toMatchObject({
|
|
ok: false,
|
|
error: { kind: "FORBIDDEN", code: "ACCESS_DENIED", httpStatus: 403 },
|
|
});
|
|
});
|
|
});
|