Files
clean-architecture-frontend…/tests/unit/backend-contract-pin.test.ts
T
DongHyeonka 45c9c4dc48 chore(review): 1105 계약·앱 코어 조치 브랜치를 합친다
합치며 고친 것: 두 브랜치가 따로는 맞고 합치면 어긋나는 곳 하나.
- 1105/03-02(HTTP 판정 브랜치)가 §4의 503 `RATE_LIMIT_UNAVAILABLE`·
  `RATE_LIMIT_INCOMPATIBLE`을 답 표(`backend-idempotency-answers.json`)에
  옮겼다. 1105/07-01(이 브랜치)은 같은 두 code를 pin의 `notCopied`에
  두었다. 합친 트리에서 `backend-contract-pin.test.ts`의 "copies the
  answers from the backend table rows at the pin"이 "is both copied and
  listed in notCopied"로 실패한다.
- pin의 `notCopied`를 비우고, 계약 문서 4.1절의 "지금은 §4의 `RATE_LIMIT_*`
  둘"과 "§4 행은 `REQUEST_TIMEOUT` 하나"를 답 표에 맞게 고친다.
- `docs/manual/01-add-a-feature.md` 충돌은 앞 통합(1a4a220c)과 같게
  푼다: "5xx 여섯" 줄과 pin·사본·drift 명령 세 줄을 함께 둔다.

검증: desktop batch에서 확인.
node scripts/run-vitest.ts run tests/unit/backend-contract-pin.test.ts tests/unit/backend-contract-drift.test.ts

Refs: 1105/03-02, 1105/07-01
2026-11-06 02:59:02 +09:00

260 lines
9.1 KiB
TypeScript

import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { z } from "zod";
import {
answerTableProblems,
excerptAnswerRows,
} from "../../scripts/lib/backend-contract-excerpt.ts";
import {
envelopeFailureEffect,
invitesKeyedResend,
maybeAppliedAnswerRows,
refusedBeforeWriteRows,
} from "../../src/adapters/http/backend-envelope.ts";
import { PLATFORM_CODES_POSSIBLY_AFTER_WRITE } from "../../src/contracts/external-contract-runtime.ts";
/**
* 1103/12-06. The paired backend's contract is pinned in a file a machine
* reads, and its answer table (http-contract.md §2, with §4's async timeout)
* is copied next to the pin. This test holds the frontend's Envelope table to
* that copy, in both directions. When the backend adds or changes an answer,
* the copy changes with the pin and this test says which frontend verdict has
* to follow.
*
* 1105/07-01. The answer table is also held to the backend's own table rows,
* copied word for word at the pin (`tables.backendExcerpt`), so a mistyped
* status or a row left out fails here without a backend checkout.
* `check:backend-contract-drift` holds that copy to the backend document.
*/
const COMMIT = /^[0-9a-f]{40}$/u;
const pinSchema = z
.object({
schemaVersion: z.literal(1),
backend: z
.object({
repository: z.string().min(1),
commit: z.string().regex(COMMIT),
document: z.string().min(1),
sectionsCompared: z.array(z.string().min(1)).min(1),
})
.strict(),
frontend: z
.object({
contractDocument: z.string().min(1),
contractSections: z.array(z.string().min(1)).min(1),
readers: z.array(z.string().min(1)).min(1),
})
.strict(),
tables: z
.object({
idempotencyAnswers: z.string().min(1),
backendExcerpt: z.string().min(1),
})
.strict(),
// Rows of the compared sections the answer table leaves out, each with why.
notCopied: z.array(
z
.object({
section: z.string().min(1),
code: z.string().regex(/^[A-Z0-9_]{1,64}$/u),
reason: z.string().min(1),
})
.strict(),
),
owner: z.string().min(1),
comparedOn: z.string().regex(/^\d{4}-\d{2}-\d{2}$/u),
})
.strict();
const answersSchema = z
.object({
schemaVersion: z.literal(1),
source: z
.object({
repository: z.string().min(1),
commit: z.string().regex(COMMIT),
document: z.string().min(1),
})
.strict(),
answers: z
.array(
z
.object({
section: z.string().min(1),
code: z.string().regex(/^[A-Z0-9_]{1,64}$/u),
status: z.number().int().min(400).max(599),
// The backend says the command did not run and will not.
refusedBeforeWrite: z.boolean(),
// The backend asks for the same request with the same key.
sameKeyResend: z.boolean(),
})
.strict(),
)
.min(1),
})
.strict();
const pin = pinSchema.parse(
JSON.parse(readFileSync("config/contracts/backend-contract-pin.json", "utf8")),
);
const table = answersSchema.parse(
JSON.parse(readFileSync(pin.tables.idempotencyAnswers, "utf8")),
);
const excerptSchema = z
.object({
schemaVersion: z.literal(1),
source: z
.object({
repository: z.string().min(1),
commit: z.string().regex(COMMIT),
document: z.string().min(1),
})
.strict(),
// Section number → its tables, each the `|` lines as the backend wrote them.
sections: z.record(
z.string().regex(/^\d+$/u),
z.array(z.array(z.string().startsWith("|")).min(2)).min(1),
),
})
.strict();
const excerpt = excerptSchema.parse(
JSON.parse(readFileSync(pin.tables.backendExcerpt, "utf8")),
);
/**
* The refusal-table codes that come from the frontend's own reading of the
* backend code (contract 6.1), not from the backend's answer table.
*/
const FRONTEND_CODE_READINGS: readonly Readonly<{ code: string; status: number }>[] = [
{ code: "VALIDATION_FAILED", status: 400 },
];
describe("paired backend contract pin", () => {
it("names one backend commit for the pin and the copied table", () => {
expect(table.source).toEqual({
repository: pin.backend.repository,
commit: pin.backend.commit,
document: pin.backend.document,
});
expect(excerpt.source).toEqual(table.source);
expect(pin.frontend.readers).toContain("src/adapters/http/backend-envelope.ts");
});
// 1105/07-01. Each answer is a row of the backend table it names, with the
// same code and status, and each backend row is either copied or listed in
// `notCopied` with a reason. The excerpt covers the sections the answers
// come from, and the parser finds rows in each.
it("copies the answers from the backend table rows at the pin", () => {
const sections = [...new Set(table.answers.map((answer) => answer.section))].sort();
expect(Object.keys(excerpt.sections).sort()).toEqual(sections);
expect(sections.every((section) => pin.backend.sectionsCompared.includes(section))).toBe(
true,
);
const rows = excerptAnswerRows(excerpt.sections);
for (const section of sections) {
expect(
rows.some((row) => row.section === section),
`no answer row read from §${section}`,
).toBe(true);
}
expect(answerTableProblems(table.answers, pin.notCopied, rows)).toEqual([]);
});
it("copies each backend answer once", () => {
const keys = table.answers.map((answer) => `${answer.status} ${answer.code}`);
expect(new Set(keys).size).toBe(keys.length);
});
// What the frontend does with each backend answer, from the two facts the
// backend states. A refusal the backend asks to resend with the same key
// stays unknown, because only an unknown result keeps the key.
it.each(table.answers.map((answer) => [`${answer.status} ${answer.code}`, answer] as const))(
"reads the backend's %s as its table says",
(_label, answer) => {
const error = { code: answer.code };
const expected =
answer.refusedBeforeWrite && !answer.sameKeyResend
? "NOT_APPLIED"
: "MAYBE_APPLIED";
expect(envelopeFailureEffect(answer.status, error)).toBe(expected);
expect(invitesKeyedResend(answer.status, error)).toBe(
answer.refusedBeforeWrite && answer.sameKeyResend,
);
},
);
it("backs every frontend table row with the backend table or the 6.1 reading", () => {
const backed = (row: Readonly<{ code: string; status: number }>) =>
table.answers.some(
(answer) => answer.code === row.code && answer.status === row.status,
);
for (const row of refusedBeforeWriteRows()) {
const reading = FRONTEND_CODE_READINGS.some(
(candidate) => candidate.code === row.code && candidate.status === row.status,
);
expect(reading || backed(row), `${row.status} ${row.code}`).toBe(true);
if (!reading) {
expect(
table.answers.find((answer) => answer.code === row.code)?.refusedBeforeWrite,
).toBe(true);
}
}
for (const row of maybeAppliedAnswerRows()) {
expect(backed(row), `${row.status} ${row.code}`).toBe(true);
}
});
});
/**
* 1105/03-01. The codes of the contract 6.1 table rows whose stage is "쓰기 뒤
* 가능" (possibly after the write), read from the document the pin names
* (docs/architecture/backend-api-and-server-state-contract.md). Because this
* file reads that document, the removal drills that copy no documents leave
* it out (REMOVAL_FIXTURE_DOCUMENT_TESTS in scripts/lib/removal-fixture.ts).
*/
function codesPossiblyAfterWrite(): ReadonlySet<string> {
const text = readFileSync(pin.frontend.contractDocument, "utf8");
const section = text.split("### 6.1 ")[1]?.split(/\n#{2,3} /u)[0] ?? "";
const codes = new Set<string>();
for (const line of section.split("\n")) {
const cells = line.split("|").map((cell) => cell.trim());
if (!line.startsWith("|") || cells[3] !== "쓰기 뒤 가능") continue;
for (const [, code = ""] of (cells[1] ?? "").matchAll(/`([A-Z0-9_]+)`/gu)) {
codes.add(code);
}
}
return codes;
}
/**
* Rows of that table whose stage the endpoint decides: the reference domain's
* codes and web-advanced's patch codes ("부르는 코드가 단계를 정한다"). A
* feature author who checked the endpoint may declare them.
*/
const FEATURE_DECIDED_CODES: readonly string[] = [
"WORKLOG_INVALID",
"POSTER_INVALID_STATE",
"POSTER_IMAGE_REQUIRED",
"WORKLOG_CONFLICT",
"POSTER_ALREADY_EXISTS",
"POSTER_IMAGE_ALREADY_PUBLISHED",
"PATCH_REJECTED",
"PATCH_TEST_FAILED",
];
describe("platform codes no operation may declare as refused before its write", () => {
it("are the 6.1 table's possibly-after-write codes outside the feature-decided rows", () => {
const table61 = codesPossiblyAfterWrite();
for (const code of FEATURE_DECIDED_CODES) {
expect(table61.has(code), code).toBe(true);
}
expect([...PLATFORM_CODES_POSSIBLY_AFTER_WRITE].sort()).toEqual(
[...table61].filter((code) => !FEATURE_DECIDED_CODES.includes(code)).sort(),
);
});
});