문제 commandEffect.refusedBeforeWrite의 조립 검사는 code 문법, 멱등성 접두사, 중복, Envelope 여부만 본다. 계약 문서 6.1절은 BAD_PARAMETER(어느 층이든 IllegalArgumentException), MAPPING_FAILED(멱등성 응답 직렬화는 action 뒤), DB_* 8개, LOCK_ACQUISITION_TIMEOUT, fileserver code를 "쓰기 뒤 가능"으로 적는다. 이 code를 목록에 적어도 조립이 통과하고, 그 code로 온 400·409·422가 NOT_APPLIED가 된다. 쓰기 뒤에 난 실패를 사용자가 다시 저장하면 새 키나 키 없는 새 요청이 나가 같은 항목이 둘 생길 수 있다(리뷰 실험 X2: 네 code가 조립을 통과하고 모두 NOT_APPLIED). 고른 방법 6.1절의 "쓰기 뒤 가능" 플랫폼 code를 src/contracts/external-contract-runtime.ts에 PLATFORM_CODES_POSSIBLY_AFTER_WRITE로 두고, assertRefusedBeforeWrite가 그 code의 선언을 6.1절을 이유로 거절한다. 실행기의 fail-close(조립 없이 부른 경우)도 같은 목록을 무시한다. 목록을 adapters가 아니라 contracts에 둔 것은 조립 검사가 adapters를 import할 수 없기 때문이다(리뷰 문서의 최소 개선은 backend-envelope.ts에 두라고 했다). backend-contract-pin.test.ts가 계약 문서 6.1절 표의 "쓰기 뒤 가능" 행을 읽어 목록과 양방향으로 대조한다. 참조 도메인 code와 web-advanced patch code는 엔드포인트가 단계를 정하므로 테스트의 예외 목록에 적고 선언할 수 있게 둔다. 버린 대안 - 매뉴얼 문장만 둔다(현상 유지): 폼을 막는 code를 넣고 싶어지는 바로 그 자리에 통제가 없다. - 업무 code 접두사 규칙(<FEATURE>_로 시작하는 code만 허용): 다운스트림 code 이름을 강제해 과하다. 위험·한계 - 이미 이 code를 적은 다운스트림 계약은 부팅에서 조립이 실패한다. 의도한 실패다. - 6.1절 표에 플랫폼 code가 더해지면 목록도 같이 고쳐야 한다. 대조 테스트가 알린다. 백엔드가 code를 더한 것은 pin을 올릴 때 6.1절을 다시 읽어야 안다. - 업무 code를 잘못 선언하는 것은 여전히 막지 못한다(기능 작성자의 판단). - 대조 테스트는 계약 문서를 읽으므로, 문서를 복사하지 않는 기능 제거 드릴(FE-GATE-020의 optional-recipe·browser-file-storage·realtime)에서는 돌지 않는다. `scripts/lib/removal-fixture.ts`의 문서 테스트 목록에 `tests/unit/backend-contract-pin.test.ts`를 더했다. 저장소 자신의 test:unit은 그대로 돌린다. 검증 desktop batch에서 확인: node scripts/run-vitest.ts run tests/unit/external-contract-runtime.test.ts tests/unit/backend-envelope.test.ts tests/unit/backend-contract-pin.test.ts corepack pnpm test:optional-recipe-removal BREAKING CHANGE: refusedBeforeWrite에 계약 문서 6.1절이 "쓰기 뒤 가능"으로 둔 플랫폼 code(PLATFORM_CODES_POSSIBLY_AFTER_WRITE)를 적으면 composeContractContributions가 거절한다. 그 code를 목록에서 지운다. 그 code의 실패는 결과 불명으로 남는다. Refs: 1105/03-01
194 lines
6.8 KiB
TypeScript
194 lines
6.8 KiB
TypeScript
import { readFileSync } from "node:fs";
|
|
|
|
import { describe, expect, it } from "vitest";
|
|
import { z } from "zod";
|
|
|
|
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.
|
|
*/
|
|
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) }).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")),
|
|
);
|
|
|
|
/**
|
|
* 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(pin.frontend.readers).toContain("src/adapters/http/backend-envelope.ts");
|
|
});
|
|
|
|
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(),
|
|
);
|
|
});
|
|
});
|