문제: 짝 백엔드 답 표 JSON(backend-idempotency-answers.json)이 pin한
백엔드 http-contract.md와 같은지 아무 검사도 보지 않는다.
backend-contract-pin.test.ts는 pin과 답 표 두 파일만 읽고, drift
스크립트는 pin과 HEAD 사이에 문서 글자가 바뀌었는지만 본다. 그래서
답 표 status 오타나 옮기지 않은 행(§4 RATE_LIMIT_*)은 어디서도 걸리지
않는다. drift 스크립트는 옆 checkout이 없으면 "skipped"로 rc=0이고
(worktree에서 늘 그렇다), 매뉴얼에는 스크립트가 없다.
고른 방법: 게이트가 백엔드 checkout 없이 볼 수 있게, 백엔드 §2·§4 표의
`|` 줄을 pin 커밋 그대로 config/contracts/backend-http-contract-excerpt.json
에 옮겼다. 읽는 함수는 scripts/lib/backend-contract-excerpt.ts 하나다.
- test:unit(backend-contract-pin.test.ts): 답 표의 행마다 사본의 같은 절에
같은 code·status 행이 있는지, 사본의 행마다 답 표에 있거나 pin의
`notCopied`에 이유와 함께 있는지 본다. `notCopied`에는 RATE_LIMIT_* 둘을
적었다(리뷰가 지적한 sectionsCompared §4의 실제 범위).
- check:backend-contract-drift(게이트 밖): pin 커밋의 문서에서 같은 표를
읽어 사본과 글자 단위로 비교하고, 답 표도 그 표와 비교하고, pin 뒤
HEAD에서 바뀐 사본 표 행을 찍는다. checkout이 없거나 pin 커밋·문서가
없으면 rc=2("not compared")로 끝난다. 기본 경로는 main checkout 옆이라
linked worktree에서도 같은 백엔드를 찾는다. `--write-excerpt`는 pin을
올릴 때 사본을 pin 커밋에서 다시 옮긴다.
- 매뉴얼 01 Envelope 단계와 계약 문서 4.1에 언제 무엇을 돌리는지 적었다.
버린 대안: 백엔드 문서의 digest만 pin에 두는 것. 게이트는 digest로 답
표를 확인할 수 없다. 계약 패키지(리뷰 안 D)는 배포 경로가 아직 없다.
위험·한계: 사본과 백엔드 문서의 일치는 여전히 백엔드 checkout이 있을
때만 drift 스크립트가 본다. 게이트는 답 표와 사본의 일치만 본다. 사본을
손으로 같이 고치면 게이트는 통과한다(drift 스크립트가 잡는다). 답 표의
refusedBeforeWrite·sameKeyResend는 백엔드 문장(클라이언트 행동)을 사람이
읽은 값이라 기계로 대조하지 않는다. 그 문장이 바뀌면 사본 diff와 drift
출력에 보인다. 백엔드 표 형식(머리글 `error.code`·`코드`·`status`)이
바뀌면 파서도 고친다. pin의 comparedOn을 사본을 옮긴 날로 올렸다.
검증: desktop batch에서 확인.
node scripts/run-vitest.ts run tests/unit/backend-contract-pin.test.ts tests/unit/backend-contract-drift.test.ts
drift 테스트는 가짜 백엔드 git repo로 D6g(pin 뒤 status 변경), 답 표
status 오타, 사본 오타, 옮기지도 적지도 않은 행, checkout 없음,
--write-excerpt를 돈다.
Refs: 1105/07-01
268 lines
9.0 KiB
TypeScript
268 lines
9.0 KiB
TypeScript
import { spawnSync } from "node:child_process";
|
|
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
|
import { tmpdir } from "node:os";
|
|
import path from "node:path";
|
|
|
|
import { afterEach, describe, expect, it } from "vitest";
|
|
|
|
/**
|
|
* 1105/07-01. `check:backend-contract-drift` on a fake paired backend: a git
|
|
* repository with a small `docs/web/http-contract.md`, and a frontend root
|
|
* with the pin, the answer table and the table excerpt. The script compared
|
|
* only the document between the pin and HEAD, so an answer table or an
|
|
* excerpt that disagreed with the pinned document passed, and no checkout
|
|
* passed as "skipped".
|
|
*/
|
|
|
|
type Answer = Readonly<{ section: string; code: string; status: number }>;
|
|
type Sections = Readonly<Record<string, readonly (readonly string[])[]>>;
|
|
|
|
const T2A = [
|
|
"| 경우 | status | `error.code` | 클라이언트 행동 |",
|
|
"| --- | --- | --- | --- |",
|
|
"| 재생: 같은 키, 첫 요청 완료 | 첫 요청과 같은 성공 status | — (성공 Envelope) | 받아들인다 |",
|
|
"| 처리 중 | 409 | `IDEMPOTENT_IN_FLIGHT` | 같은 키로 다시 보낸다 |",
|
|
];
|
|
const T2B = [
|
|
"| 경우 | status | `error.code` | 클라이언트 행동 |",
|
|
"| --- | --- | --- | --- |",
|
|
"| 결과 불명 | 503 | `IDEMPOTENCY_COMPLETION_UNKNOWN` | 같은 키로 나중에 |",
|
|
];
|
|
const T4 = [
|
|
"| 코드 | status | 언제 |",
|
|
"| --- | --- | --- |",
|
|
"| `REQUEST_TIMEOUT` | 503 | 시간 안에 끝나지 않았다 |",
|
|
"| `RATE_LIMIT_UNAVAILABLE` | 503 | rate-limit 저장소 응답 없음 |",
|
|
];
|
|
const SECTIONS: Sections = { "2": [T2A, T2B], "4": [T4] };
|
|
const ANSWERS: readonly Answer[] = [
|
|
{ section: "2", code: "IDEMPOTENT_IN_FLIGHT", status: 409 },
|
|
{ section: "2", code: "IDEMPOTENCY_COMPLETION_UNKNOWN", status: 503 },
|
|
{ section: "4", code: "REQUEST_TIMEOUT", status: 503 },
|
|
];
|
|
const NOT_COPIED = [
|
|
{ section: "4", code: "RATE_LIMIT_UNAVAILABLE", reason: "fixture" },
|
|
];
|
|
|
|
function contractDocument(sections: Sections): string {
|
|
return [
|
|
"# HTTP wire 계약",
|
|
"",
|
|
"## 1. Envelope",
|
|
"",
|
|
"| 응답 | 키 |",
|
|
"| --- | --- |",
|
|
"| 성공 | `data` |",
|
|
"",
|
|
"## 2. 멱등성 응답",
|
|
"",
|
|
...(sections["2"]?.[0] ?? []),
|
|
"",
|
|
"### 저장소가 응답하지 않을 때",
|
|
"",
|
|
...(sections["2"]?.[1] ?? []),
|
|
"",
|
|
"## 4. web 전용 오류 코드",
|
|
"",
|
|
...(sections["4"]?.[0] ?? []),
|
|
"",
|
|
"## 5. 바꿀 때",
|
|
"",
|
|
"- 표를 고치면 짝 프론트에 알린다.",
|
|
"",
|
|
].join("\n");
|
|
}
|
|
|
|
const directories: string[] = [];
|
|
afterEach(async () => {
|
|
await Promise.all(
|
|
directories.splice(0).map((directory) => rm(directory, { recursive: true, force: true })),
|
|
);
|
|
});
|
|
|
|
function git(cwd: string, ...args: string[]): string {
|
|
const result = spawnSync("git", args, {
|
|
cwd,
|
|
encoding: "utf8",
|
|
env: {
|
|
...process.env,
|
|
GIT_AUTHOR_NAME: "drift-fixture",
|
|
GIT_AUTHOR_EMAIL: "drift-fixture@localhost",
|
|
GIT_COMMITTER_NAME: "drift-fixture",
|
|
GIT_COMMITTER_EMAIL: "drift-fixture@localhost",
|
|
},
|
|
});
|
|
if (result.error || result.status !== 0) {
|
|
throw new Error(`fixture git ${args[0]} failed: ${result.stderr || result.error?.message}`);
|
|
}
|
|
return result.stdout.trim();
|
|
}
|
|
|
|
async function commitDocument(backend: string, text: string, message: string): Promise<string> {
|
|
await mkdir(path.join(backend, "docs/web"), { recursive: true });
|
|
await writeFile(path.join(backend, "docs/web/http-contract.md"), text);
|
|
git(backend, "add", "--all");
|
|
git(backend, "commit", "--quiet", "--no-gpg-sign", "--no-verify", "-m", message);
|
|
return git(backend, "rev-parse", "HEAD");
|
|
}
|
|
|
|
async function drift(
|
|
options: Readonly<{
|
|
answers?: readonly Answer[];
|
|
excerpt?: Sections;
|
|
notCopied?: typeof NOT_COPIED;
|
|
/** The document of a backend commit after the pin. */
|
|
head?: string;
|
|
/** Where the script looks for the backend instead of the fake one. */
|
|
backend?: string;
|
|
flags?: readonly string[];
|
|
}> = {},
|
|
) {
|
|
const root = await mkdtemp(path.join(tmpdir(), "drift-frontend-"));
|
|
const backend = await mkdtemp(path.join(tmpdir(), "drift-backend-"));
|
|
directories.push(root, backend);
|
|
git(backend, "init", "--quiet", "--initial-branch=fixture");
|
|
const commit = await commitDocument(backend, contractDocument(SECTIONS), "pinned");
|
|
if (options.head !== undefined) await commitDocument(backend, options.head, "after the pin");
|
|
|
|
const source = {
|
|
repository: "clean-architecture-backend-template",
|
|
commit,
|
|
document: "docs/web/http-contract.md",
|
|
};
|
|
const write = async (file: string, value: unknown) => {
|
|
await mkdir(path.dirname(path.join(root, file)), { recursive: true });
|
|
await writeFile(path.join(root, file), `${JSON.stringify(value, null, 2)}\n`);
|
|
};
|
|
await write("config/contracts/backend-contract-pin.json", {
|
|
schemaVersion: 1,
|
|
backend: { ...source, sectionsCompared: ["1", "2", "4"] },
|
|
frontend: {
|
|
contractDocument: "docs/architecture/backend-api-and-server-state-contract.md",
|
|
contractSections: ["4.1", "6", "6.1"],
|
|
readers: ["src/adapters/http/backend-envelope.ts"],
|
|
},
|
|
tables: {
|
|
idempotencyAnswers: "config/contracts/backend-idempotency-answers.json",
|
|
backendExcerpt: "config/contracts/backend-http-contract-excerpt.json",
|
|
},
|
|
notCopied: options.notCopied ?? NOT_COPIED,
|
|
owner: "fixture",
|
|
comparedOn: "2026-11-05",
|
|
});
|
|
await write("config/contracts/backend-idempotency-answers.json", {
|
|
schemaVersion: 1,
|
|
source,
|
|
answers: (options.answers ?? ANSWERS).map((answer) => ({
|
|
...answer,
|
|
refusedBeforeWrite: false,
|
|
sameKeyResend: true,
|
|
})),
|
|
});
|
|
await write("config/contracts/backend-http-contract-excerpt.json", {
|
|
schemaVersion: 1,
|
|
source,
|
|
sections: options.excerpt ?? SECTIONS,
|
|
});
|
|
|
|
const result = spawnSync(
|
|
process.execPath,
|
|
[
|
|
path.resolve("scripts/check-backend-contract-drift.ts"),
|
|
"--backend",
|
|
options.backend ?? backend,
|
|
...(options.flags ?? []),
|
|
],
|
|
{ cwd: root, encoding: "utf8" },
|
|
);
|
|
return {
|
|
status: result.status,
|
|
stdout: result.stdout,
|
|
stderr: result.stderr,
|
|
readExcerpt: async () =>
|
|
JSON.parse(
|
|
await readFile(path.join(root, "config/contracts/backend-http-contract-excerpt.json"), "utf8"),
|
|
) as { sections: Sections },
|
|
};
|
|
}
|
|
|
|
describe("check:backend-contract-drift (1105/07-01)", () => {
|
|
it("passes when the excerpt and the answer table match the pinned document", async () => {
|
|
const result = await drift();
|
|
|
|
expect(result.stderr).toBe("");
|
|
expect(result.status).toBe(0);
|
|
});
|
|
|
|
it("fails when an answer's status is not the pinned document's", async () => {
|
|
const result = await drift({
|
|
answers: ANSWERS.map((answer) =>
|
|
answer.code === "IDEMPOTENCY_COMPLETION_UNKNOWN" ? { ...answer, status: 500 } : answer,
|
|
),
|
|
});
|
|
|
|
expect(result.status).toBe(1);
|
|
expect(result.stderr).toContain(
|
|
"answer 500 IDEMPOTENCY_COMPLETION_UNKNOWN is not a row of the pinned document's §2",
|
|
);
|
|
});
|
|
|
|
it("fails when the excerpt is not the pinned document's, even if the answers follow it", async () => {
|
|
const edited = T2B.map((line) => line.replace("| 503 |", "| 500 |"));
|
|
const result = await drift({
|
|
excerpt: { ...SECTIONS, "2": [T2A, edited] },
|
|
answers: ANSWERS.map((answer) =>
|
|
answer.code === "IDEMPOTENCY_COMPLETION_UNKNOWN" ? { ...answer, status: 500 } : answer,
|
|
),
|
|
});
|
|
|
|
expect(result.status).toBe(1);
|
|
expect(result.stderr).toContain(
|
|
"excerpt differs from the pinned document: §2 -| 결과 불명 | 500 |",
|
|
);
|
|
expect(result.stderr).toContain(
|
|
"excerpt differs from the pinned document: §2 +| 결과 불명 | 503 |",
|
|
);
|
|
});
|
|
|
|
it("fails on a row of the pinned document neither copied nor listed as not copied", async () => {
|
|
const result = await drift({ notCopied: [] });
|
|
|
|
expect(result.status).toBe(1);
|
|
expect(result.stderr).toContain(
|
|
"§4 503 RATE_LIMIT_UNAVAILABLE is neither in the answer table nor in the pin's notCopied",
|
|
);
|
|
});
|
|
|
|
// D6g in the 2026-11-05 review: the backend changes a copied row after the pin.
|
|
it("fails on a copied row the backend changed after the pin", async () => {
|
|
const result = await drift({
|
|
head: contractDocument({
|
|
...SECTIONS,
|
|
"2": [T2A, T2B.map((line) => line.replace("| 503 |", "| 500 |"))],
|
|
}),
|
|
});
|
|
|
|
expect(result.status).toBe(1);
|
|
expect(result.stderr).toContain("| 결과 불명 | 500 |");
|
|
});
|
|
|
|
it("does not pass without a backend checkout", async () => {
|
|
const result = await drift({ backend: path.join(tmpdir(), "no-such-backend-checkout") });
|
|
|
|
expect(result.status).toBe(2);
|
|
expect(result.stderr).toContain("not compared");
|
|
});
|
|
|
|
it("writes the excerpt from the pinned document with --write-excerpt", async () => {
|
|
const result = await drift({
|
|
excerpt: { "2": [T2A], "4": [T4.slice(0, 3)] },
|
|
flags: ["--write-excerpt"],
|
|
});
|
|
|
|
expect(result.stderr).toBe("");
|
|
expect(result.status).toBe(0);
|
|
expect((await result.readExcerpt()).sections).toEqual(SECTIONS);
|
|
});
|
|
});
|