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), // 1105/16-02. Backend scaffold files the generator copies facts from. scaffoldSources: z .array( z .object({ path: z.string().min(1), fact: z.string().min(1), copiedTo: z .object({ file: z.string().min(1), symbol: z.string().min(1) }) .strict(), }) .strict(), ) .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([]); }); /** * 1105/16-02. The `--with-create` slice copies the backend scaffold's path * rule, name limit, error codes and check order. Each copy names the * backend file it came from, so check:backend-contract-drift can say which * frontend line to recheck when that file changes. */ it("names the backend scaffold file behind each fact the generator copies", () => { const paths = pin.backend.scaffoldSources.map((source) => source.path); expect(new Set(paths).size).toBe(paths.length); for (const source of pin.backend.scaffoldSources) { expect(readFileSync(source.copiedTo.file, "utf8"), source.path).toContain( source.copiedTo.symbol, ); } const copiedFiles = new Set(pin.backend.scaffoldSources.map((source) => source.copiedTo.file)); expect([...copiedFiles].sort()).toEqual([ "scripts/create-feature-write-slice.ts", "scripts/create-feature.ts", ]); expect(paths).toEqual( expect.arrayContaining([ "scripts/new-feature.sh", expect.stringMatching(/\/__Feature__\.java\.tmpl$/u), expect.stringMatching(/\/__Feature__ErrorCode\.java\.tmpl$/u), expect.stringMatching(/\/__Feature__Controller\.java\.tmpl$/u), expect.stringMatching(/\/Create__Feature__UseCase\.java\.tmpl$/u), ]), ); }); 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 { const text = readFileSync(pin.frontend.contractDocument, "utf8"); const section = text.split("### 6.1 ")[1]?.split(/\n#{2,3} /u)[0] ?? ""; const codes = new Set(); 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(), ); }); });