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"; /** * 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. * * 1106/12-01. This file reads config and code only, so every removal drill * runs it. The check of the contract 6.1 table reads a document and is in * tests/unit/backend-contract-pin-document.test.ts. */ 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); } }); });