From ba2b4f4c6db52839d22e2b26b6791ad8d0e51742 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 21:03:40 +0900 Subject: [PATCH] =?UTF-8?q?feat(contracts):=20=EC=A7=9D=20=EB=B0=B1?= =?UTF-8?q?=EC=97=94=EB=93=9C=20=EA=B3=84=EC=95=BD=20=EA=B8=B0=EC=A4=80?= =?UTF-8?q?=EC=A0=90=EC=9D=84=20=EA=B8=B0=EA=B3=84=EA=B0=80=20=EC=9D=BD?= =?UTF-8?q?=EB=8A=94=20pin=EA=B3=BC=20=EB=8B=B5=20=ED=91=9C=EB=A1=9C=20?= =?UTF-8?q?=EB=91=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 짝 백엔드 계약의 기준 커밋은 계약 문서의 문장(백엔드 5786126c)뿐이고, 이 SHA를 읽는 코드·설정·테스트가 없다. 쓰기 전 거절 표 REFUSED_BEFORE_WRITE와 5xx 판정은 백엔드 http-contract.md §2를 손으로 옮긴 것이다. 리뷰 중 백엔드에 bbe944bd가 들어와 503 IDEMPOTENCY_COMPLETION_UNKNOWN이 새로 생겼는데 프론트의 어떤 검사도 알리지 않았다(README 10.6). 고른 방법 (결정 D6 (1)+(2)) - config/contracts/backend-contract-pin.json: repo, 전체 SHA(bbe944bd), 대조한 문서와 절(§1·§2·§4), 프론트 쪽 계약 절·판정 파일, 담당. - config/contracts/backend-idempotency-answers.json: 백엔드 §2 표 여섯 행과 §4 REQUEST_TIMEOUT을 code·status·쓰기 전 거절·같은 키 재전송 열로 옮겼다. 백엔드가 문서에 적은 사실만 담는다. - tests/unit/backend-contract-pin.test.ts: 두 JSON의 모양과 같은 SHA를 확인하고, 답마다 프론트 판정이 그 두 열에서 나오는 값인지(쓰기 전 거절이면서 같은 키 재전송이 아니면 NOT_APPLIED, 아니면 MAYBE_APPLIED, 자동 재전송은 둘 다 참일 때만) 본다. 반대로 프론트 표의 행이 모두 이 답 표나 6.1절 읽기(VALIDATION_FAILED)로 뒷받침되는지 본다. 그래서 백엔드 표에 행이 늘거나 status가 바뀐 JSON을 넣으면 실패한다. - scripts/check-backend-contract-drift.ts(check:backend-contract-drift): 형제 디렉터리(또는 --backend)의 백엔드 checkout이 pin 뒤에 http-contract.md를 바꿨는지 알리고 바뀐 표 행을 보인다. CI에는 백엔드가 없어 게이트 밖이다. ungated-scripts.json에 이유를 적었다. - 계약 문서 4.1·6절의 기준 커밋을 bbe944bd와 pin 파일로 옮겼다. 6.1절 표는 5786126c..bbe944bd 사이 바뀐 백엔드 파일 다섯을 다시 읽었다. 판정은 같고 줄 번호만 옮겼다(IdempotencyExecutor, GlobalExceptionHandler → HttpStatusErrorCodes, FailureCategory, PersistenceExceptionTranslator). 버린 대안 - 백엔드 error-codes.yaml과 문서 다이제스트를 기록: 다이제스트는 바뀐 것만 알리고 무엇을 고칠지 말하지 않는다. - 백엔드가 계약 패키지를 발행: 백엔드 빌드에 JS 발행이 생긴다. 지금 규모에는 pin과 표가 작다. 위험·한계 - 답 표 JSON은 사람이 백엔드 문서에서 옮긴다. 옮기는 실수는 drift 스크립트와 리뷰가 잡는다. 백엔드 쪽이 같은 JSON을 자기 레지스트리와 대조하는 일은 백엔드 저장소 몫이다. - 백엔드 HEAD는 이미 pin 뒤로 갔다(지금 c508b1ba). http-contract.md §2의 500 IDEMPOTENCY_RECOVERY_REQUIRED 행이 "같은 키 재전송은 안전하다"로 바뀌었다. 프론트 판정(MAYBE_APPLIED, 자동 재전송 없음, 사용자 재전송은 같은 키)은 그 문장과도 맞는다. pin은 지시대로 bbe944bd에 두었다. 검증 - 새 테스트 10건 통과. 변이 4종 검출: 답 표에 503 새 code 행 추가, 프론트 표에서 COMPLETION_UNKNOWN 제거, 프론트 표에 근거 없는 400 BAD_PARAMETER 추가, 답 표의 RECOVERY_REQUIRED status 변경. - check:backend-contract-drift: worktree에서 skipped(exit 0), 실제 백엔드 checkout으로 exit 1과 바뀐 RECOVERY_REQUIRED 행 출력. - test:unit 178파일 2,645건, check:ci, check:types, eslint, verify:documentation 통과. Refs: docs/reviews/2026-11-03-maturity-review/12-guardrails-ci.md 12-06 Refs: docs/reviews/2026-11-03-maturity-review/README.md 10.6 --- config/ci/ungated-scripts.json | 4 + config/contracts/backend-contract-pin.json | 19 +++ .../backend-idempotency-answers.json | 59 ++++++++ .../backend-api-and-server-state-contract.md | 32 ++-- package.json | 1 + scripts/check-backend-contract-drift.ts | 83 ++++++++++ src/adapters/http/backend-envelope.ts | 41 ++++- tests/unit/backend-contract-pin.test.ts | 143 ++++++++++++++++++ 8 files changed, 366 insertions(+), 16 deletions(-) create mode 100644 config/contracts/backend-contract-pin.json create mode 100644 config/contracts/backend-idempotency-answers.json create mode 100644 scripts/check-backend-contract-drift.ts create mode 100644 tests/unit/backend-contract-pin.test.ts diff --git a/config/ci/ungated-scripts.json b/config/ci/ungated-scripts.json index 5abf98f9..42d1fd1b 100644 --- a/config/ci/ungated-scripts.json +++ b/config/ci/ungated-scripts.json @@ -1,6 +1,10 @@ { "schemaVersion": 1, "entries": [ + { + "script": "check:backend-contract-drift", + "reason": "1103/12-06. Compares the paired backend checkout next to this repository with the commit config/contracts/backend-contract-pin.json pins. CI checks out this repository alone, so a gate has no backend to read; with no checkout the script reports skipped. The gated half of the pin is tests/unit/backend-contract-pin.test.ts (test:unit), which holds the Envelope table to the copied backend answer table. Run this before moving the pin." + }, { "script": "check:feature-index", "reason": "Local check that the generated indexes (src/.generated/, not committed) are current, and the first step of verify:extreme-scale (scripts/verify-extreme-scale.ts), itself a local run. A gate gains nothing from it: every gate script regenerates the indexes first (generate-product-feature-index.ts)." diff --git a/config/contracts/backend-contract-pin.json b/config/contracts/backend-contract-pin.json new file mode 100644 index 00000000..c76b6120 --- /dev/null +++ b/config/contracts/backend-contract-pin.json @@ -0,0 +1,19 @@ +{ + "schemaVersion": 1, + "backend": { + "repository": "clean-architecture-backend-template", + "commit": "bbe944bd3c332c04be8d7af5eeef8f48bee1f2f8", + "document": "docs/web/http-contract.md", + "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" + }, + "owner": "frontend-platform", + "comparedOn": "2026-11-04" +} diff --git a/config/contracts/backend-idempotency-answers.json b/config/contracts/backend-idempotency-answers.json new file mode 100644 index 00000000..af9a0aab --- /dev/null +++ b/config/contracts/backend-idempotency-answers.json @@ -0,0 +1,59 @@ +{ + "schemaVersion": 1, + "source": { + "repository": "clean-architecture-backend-template", + "commit": "bbe944bd3c332c04be8d7af5eeef8f48bee1f2f8", + "document": "docs/web/http-contract.md" + }, + "answers": [ + { + "section": "2", + "code": "IDEMPOTENT_IN_FLIGHT", + "status": 409, + "refusedBeforeWrite": false, + "sameKeyResend": true + }, + { + "section": "2", + "code": "IDEMPOTENT_REQUEST_MISMATCH", + "status": 422, + "refusedBeforeWrite": true, + "sameKeyResend": false + }, + { + "section": "2", + "code": "IDEMPOTENCY_KEY_INVALID", + "status": 400, + "refusedBeforeWrite": true, + "sameKeyResend": false + }, + { + "section": "2", + "code": "IDEMPOTENCY_UNAVAILABLE", + "status": 503, + "refusedBeforeWrite": true, + "sameKeyResend": true + }, + { + "section": "2", + "code": "IDEMPOTENCY_COMPLETION_UNKNOWN", + "status": 503, + "refusedBeforeWrite": false, + "sameKeyResend": true + }, + { + "section": "2", + "code": "IDEMPOTENCY_RECOVERY_REQUIRED", + "status": 500, + "refusedBeforeWrite": false, + "sameKeyResend": false + }, + { + "section": "4", + "code": "REQUEST_TIMEOUT", + "status": 503, + "refusedBeforeWrite": false, + "sameKeyResend": false + } + ] +} diff --git a/docs/architecture/backend-api-and-server-state-contract.md b/docs/architecture/backend-api-and-server-state-contract.md index 00ba8467..38d2df52 100644 --- a/docs/architecture/backend-api-and-server-state-contract.md +++ b/docs/architecture/backend-api-and-server-state-contract.md @@ -165,9 +165,16 @@ Envelope의 모양과 키 존재 규칙은 짝 백엔드 템플릿 문서가 정 - 정본: [`clean-architecture-backend-template/docs/web/http-contract.md`](../../../clean-architecture-backend-template/docs/web/http-contract.md) 1절 "Envelope 키 존재 규칙" -- 기준 커밋: 백엔드 `5786126c`. `http-contract.md`는 `34565130`에서 들어왔고 - `1400dc15`에서 마지막으로 바뀌었다. 값이 null인 필드는 키째 생략한다. 백엔드 - 기준 커밋을 올리면 6.1절 표를 같은 변경에서 다시 확인한다. +- 기준 커밋: 백엔드 `bbe944bd`. 기계가 읽는 정본은 + `config/contracts/backend-contract-pin.json`(repo, 전체 SHA, 대조한 절 §1·§2·§4, + 담당)이다. 백엔드 §2 표와 §4 `REQUEST_TIMEOUT`은 + `config/contracts/backend-idempotency-answers.json`에 code·status·쓰기 전 거절·같은 키 + 재전송 열로 옮겨 두었다. `tests/unit/backend-contract-pin.test.ts`가 그 표와 + `backend-envelope.ts`의 판정을 양방향으로 대조한다. 값이 null인 필드는 키째 + 생략한다. 백엔드 기준 커밋을 올리면 pin, 답 표 JSON, 6.1절 표를 같은 변경에서 + 다시 확인한다. 형제 디렉터리에 백엔드 checkout이 있으면 + `corepack pnpm check:backend-contract-drift`가 pin 뒤 `http-contract.md`가 + 바뀌었는지 알려 준다(게이트 밖). - 프론트에서 Envelope를 읽는 곳: `src/adapters/http/backend-envelope.ts`(스키마와 해석). V3 실행기는 descriptor가 `responseEnvelope: "ENVELOPE_V1"`일 때 쓴다. `create:feature`가 만든 기능은 이 값을 선언한다. 참조 기능은 선언하지 않고 @@ -252,7 +259,7 @@ backend idempotency를 대체하지 않는다. - 정본: [`clean-architecture-backend-template/docs/web/http-contract.md`](../../../clean-architecture-backend-template/docs/web/http-contract.md) 2절 "멱등성 응답", 4절 "web 전용 오류 코드" -- 기준 커밋: 4.1절과 같다(백엔드 `5786126c`). +- 기준 커밋: 4.1절과 같다(백엔드 `bbe944bd`, `config/contracts/backend-contract-pin.json`). - 프론트가 그 응답을 읽는 곳: - 키 생성·검사: `src/contracts/mutation-intent.ts` `isValidIdempotencyKey` - 결과 불명 재전송이 같은 키를 쓰고 `Retry-After`까지 기다리는 곳: @@ -272,7 +279,10 @@ mutation이 400·409·422로 실패하면 프론트는 그 요청이 적용됐 결과 불명으로 보인다. effect가 없는 실패도 이 값이다. 백엔드 `http-contract.md`는 code가 어느 단계에서 나오는지 적지 않는다. 아래 표는 -프론트가 백엔드 `5786126c`의 코드를 읽고 정한 판정이다. 같은 code가 쓰기 전과 +프론트가 백엔드 코드를 읽고 정한 판정이다. `5786126c`에서 읽었고, `bbe944bd`에서 +바뀐 파일(`GlobalExceptionHandler`, `IdempotencyExecutor`, `PersistenceExceptionTranslator`, +`FailureCategory`, `DomainExceptionHandler`)을 다시 읽었다. 판정은 바뀌지 않았고 줄 +번호만 옮겼다. 같은 code가 쓰기 전과 뒤에서 모두 나오면 "쓰기 뒤 가능"으로 둔다. 프론트는 code만 보고 둘을 가를 수 없다. @@ -283,11 +293,11 @@ mutation이 400·409·422로 실패하면 프론트는 그 요청이 적용됐 | `VALIDATION_FAILED` (400), details = `{cause}` 또는 없음 | 본문을 읽지 못함(`HttpMessageNotReadableException`) | 쓰기 전 | `NOT_APPLIED` | `GlobalExceptionHandler.java:233-251` | | `VALIDATION_FAILED` (400), details = `{field, code}` | 페이지·정렬 파라미터. 목록 GET 컨트롤러가 use case 전에 검사한다 | 쓰기 전 | `NOT_APPLIED` | `GlobalExceptionHandler.java:149-153`, `PageParams.java:27-33`, `SortParam.java:16-43` | | `IDEMPOTENCY_KEY_INVALID` (400) | KEYED 컨트롤러 첫 줄의 키 파싱 | 쓰기 전 | `NOT_APPLIED` | `IdempotencyKeyHeader.java:32-38`, `PosterImagePublicationController.java:64` | -| `IDEMPOTENT_REQUEST_MISMATCH` (422) | 멱등성 executor가 action 전에 판정 | 쓰기 전 | `NOT_APPLIED` | `IdempotencyExecutor.java:102-103`, `:134-135` | -| `IDEMPOTENT_IN_FLIGHT` (409) | 멱등성 executor가 action 전에 판정. 같은 키의 앞선 요청이 실행 중이다 | 이번 요청은 쓰기 전. 앞선 요청은 적용될 수 있다 | `MAYBE_APPLIED` | `IdempotencyExecutor.java:104-105`, `:136-137` | -| `BAD_PARAMETER` (400) | 타입 변환 실패, 필수 파라미터·헤더 없음(쓰기 전). **어느 층이든 `IllegalArgumentException`**(use case·domain 포함) | 쓰기 뒤 가능 | `MAYBE_APPLIED` | `GlobalExceptionHandler.java:92-99`, `:108-116`, `:397-438` | -| `MAPPING_FAILED` (400) | web 매퍼(쓰기 전), outbound ACL 매퍼(use case 안), 멱등성 응답 직렬화(action이 끝난 뒤) | 쓰기 뒤 가능 | `MAYBE_APPLIED` | `WorkLogWebMapper.java:36`, `RepoStatsAclMapper.java:14`, `JsonIdempotentResponseCodec.java:32`, `IdempotencyExecutor.java:229` | -| `DB_SERIALIZATION_FAILURE`, `DB_DEADLOCK`, `DB_LOCK_TIMEOUT`, `DB_NULL_VIOLATION`, `DB_FK_VIOLATION`, `DB_UNIQUE_VIOLATION`, `DB_CHECK_VIOLATION`, `DB_OPTIMISTIC_CONFLICT` (409) | persistence 어댑터가 SQL·JPA 실패를 바꾼 것. 트랜잭션 안이나 commit에서 | 쓰기 뒤 가능 | `MAYBE_APPLIED` | `FailureCategory.java:79-95`, `StandardSqlStateErrorMapping.java:46-52`, `PersistenceExceptionTranslator.java:131` | +| `IDEMPOTENT_REQUEST_MISMATCH` (422) | 멱등성 executor가 action 전에 판정 | 쓰기 전 | `NOT_APPLIED` | `IdempotencyExecutor.java:119-120`, `:151-152` | +| `IDEMPOTENT_IN_FLIGHT` (409) | 멱등성 executor가 action 전에 판정. 같은 키의 앞선 요청이 실행 중이다 | 이번 요청은 쓰기 전. 앞선 요청은 적용될 수 있다 | `MAYBE_APPLIED` | `IdempotencyExecutor.java:121-122`, `:153-154` | +| `BAD_PARAMETER` (400) | 타입 변환 실패, 필수 파라미터·헤더 없음(쓰기 전). **어느 층이든 `IllegalArgumentException`**(use case·domain 포함) | 쓰기 뒤 가능 | `MAYBE_APPLIED` | `GlobalExceptionHandler.java:92-99`, `:108-116`, `:397-417`, `HttpStatusErrorCodes.java:33-34` | +| `MAPPING_FAILED` (400) | web 매퍼(쓰기 전), outbound ACL 매퍼(use case 안), 멱등성 응답 직렬화(action이 끝난 뒤) | 쓰기 뒤 가능 | `MAYBE_APPLIED` | `WorkLogWebMapper.java:36`, `RepoStatsAclMapper.java:14`, `JsonIdempotentResponseCodec.java:32`, `IdempotencyExecutor.java:246` | +| `DB_SERIALIZATION_FAILURE`, `DB_DEADLOCK`, `DB_LOCK_TIMEOUT`, `DB_NULL_VIOLATION`, `DB_FK_VIOLATION`, `DB_UNIQUE_VIOLATION`, `DB_CHECK_VIOLATION`, `DB_OPTIMISTIC_CONFLICT` (409) | persistence 어댑터가 SQL·JPA 실패를 바꾼 것. 트랜잭션 안이나 commit에서 | 쓰기 뒤 가능 | `MAYBE_APPLIED` | `FailureCategory.java:86-102`, `StandardSqlStateErrorMapping.java:46-52`, `PersistenceExceptionTranslator.java:133` | | `LOCK_ACQUISITION_TIMEOUT` (409) | 분산 락 대기 초과. use case 안 | 쓰기 뒤 가능 | `MAYBE_APPLIED` | `LockRegistryDistributedLock.java:50`, `:53` | | 참조 도메인 `WORKLOG_INVALID`, `POSTER_INVALID_STATE`, `POSTER_IMAGE_REQUIRED` (400), `WORKLOG_CONFLICT`, `POSTER_ALREADY_EXISTS`, `POSTER_IMAGE_ALREADY_PUBLISHED` (409) | application·domain 예외 | 쓰기 뒤 가능 | `MAYBE_APPLIED` | `DomainExceptionHandler.java:52-90` | | 선택 모듈 web-advanced `PATCH_REJECTED` (400), `PATCH_TEST_FAILED` (409) | patch 라이브러리. 부르는 코드가 단계를 정한다 | 쓰기 뒤 가능 | `MAYBE_APPLIED` | `src/adapter/inbound/web-advanced/README.md` 「오류 응답」 | @@ -304,7 +314,7 @@ mutation이 400·409·422로 실패하면 프론트는 그 요청이 적용됐 자동으로 다시 보내는 것은 KEYED 명령의 503 `IDEMPOTENCY_UNAVAILABLE`뿐이다. 나머지는 결과 불명 화면에서 사용자가 같은 키로 다시 보낸다. - 파일 위치(백엔드 repo 기준): - - `GlobalExceptionHandler.java`: `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/` + - `GlobalExceptionHandler.java`, `HttpStatusErrorCodes.java`: `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/` - `PageParams.java`, `SortParam.java`: 같은 모듈 `.../web/pagination/` - `IdempotencyKeyHeader.java`: 같은 모듈 `.../web/http/` - `IdempotencyExecutor.java`: `src/application-core/src/main/java/dev/caskeleton/application/idempotency/` diff --git a/package.json b/package.json index f0cf9a37..147ef6c4 100644 --- a/package.json +++ b/package.json @@ -20,6 +20,7 @@ "check:i18n": "node scripts/generate-product-feature-index.ts && node scripts/check-i18n.ts", "check:i18n:fixture": "node scripts/generate-product-feature-index.ts && node scripts/check-i18n.ts --fixture", "check:adapter-inventory": "node scripts/check-adapter-inventory.ts", + "check:backend-contract-drift": "node scripts/check-backend-contract-drift.ts", "check:remediation-ledger": "node scripts/check-remediation-ledger.ts", "check:release-admission": "node scripts/generate-product-feature-index.ts && node scripts/check-release-admission.ts", "check:diagnostics": "node scripts/generate-product-feature-index.ts && node scripts/check-diagnostics.ts", diff --git a/scripts/check-backend-contract-drift.ts b/scripts/check-backend-contract-drift.ts new file mode 100644 index 00000000..d7dfe35e --- /dev/null +++ b/scripts/check-backend-contract-drift.ts @@ -0,0 +1,83 @@ +import { spawnSync } from "node:child_process"; +import { existsSync, readFileSync } from "node:fs"; +import path from "node:path"; + +/** + * 1103/12-06. Local only, outside every gate: CI checks this repository out + * alone. Tells whether the paired backend checkout next to this one has moved + * past the commit `config/contracts/backend-contract-pin.json` pins, and + * whether the contract document changed since. + * + * corepack pnpm check:backend-contract-drift [--backend ] + * + * Exit 0: no checkout to compare, the pinned commit itself, or a later commit + * whose contract document is unchanged. Exit 1: the document changed after + * the pin. Recheck the frontend contract 6.1 table, the copied answer table + * and the pin in one change. Exit 2: the checkout cannot be compared. + */ + +type Pin = Readonly<{ + backend: Readonly<{ repository: string; commit: string; document: string }>; +}>; + +const PIN_PATH = "config/contracts/backend-contract-pin.json"; + +function backendDirectory(pin: Pin): string { + const flag = process.argv.indexOf("--backend"); + const given = flag >= 0 ? process.argv[flag + 1] : undefined; + return given + ? path.resolve(given) + : path.resolve("..", pin.backend.repository); +} + +function git(directory: string, ...args: string[]) { + return spawnSync("git", ["-C", directory, ...args], { encoding: "utf8" }); +} + +function main(): void { + const pin = JSON.parse(readFileSync(PIN_PATH, "utf8")) as Pin; + const directory = backendDirectory(pin); + const { commit, document } = pin.backend; + if (!existsSync(path.join(directory, ".git"))) { + console.log( + `Backend contract drift: skipped, no ${pin.backend.repository} checkout at ${directory} (pass --backend )`, + ); + return; + } + const head = git(directory, "rev-parse", "HEAD"); + if (head.status !== 0 || git(directory, "cat-file", "-e", `${commit}^{commit}`).status !== 0) { + console.error( + `Backend contract drift: cannot compare ${directory} with the pinned ${commit.slice(0, 12)}; fetch the backend history first`, + ); + process.exitCode = 2; + return; + } + const headCommit = head.stdout.trim(); + if (headCommit === commit) { + console.log(`Backend contract drift: ${directory} is at the pinned ${commit.slice(0, 12)}`); + return; + } + const changed = git(directory, "diff", "--unified=0", `${commit}..HEAD`, "--", document); + const tableLines = changed.stdout + .split("\n") + .filter((line) => /^[+-]\|/u.test(line)); + if (changed.stdout.trim() === "") { + console.log( + `Backend contract drift: HEAD ${headCommit.slice(0, 12)} is past the pin ${commit.slice(0, 12)}, ${document} unchanged`, + ); + return; + } + console.error( + `Backend contract drift: ${document} changed between the pin ${commit.slice(0, 12)} and HEAD ${headCommit.slice(0, 12)}.`, + ); + console.error( + `Recheck docs/architecture/backend-api-and-server-state-contract.md 6.1, config/contracts/backend-idempotency-answers.json and ${PIN_PATH} together.`, + ); + for (const line of tableLines) console.error(` ${line}`); + if (tableLines.length === 0) { + console.error(" (no table rows changed; read the prose changes with git diff)"); + } + process.exitCode = 1; +} + +main(); diff --git a/src/adapters/http/backend-envelope.ts b/src/adapters/http/backend-envelope.ts index 186cc004..b959cb40 100644 --- a/src/adapters/http/backend-envelope.ts +++ b/src/adapters/http/backend-envelope.ts @@ -136,11 +136,14 @@ export function readFailureEnvelope( /** * 1101/14.4. The 400, 409 and 422 codes the paired backend raises only before - * it writes. Backend 5786126c, read code by code into the frontend contract - * (docs/architecture/backend-api-and-server-state-contract.md 6.1); recheck - * this table with that section when the backend SHA there moves. Only the - * status and code together count. `reason` is the diagnostics name of an - * idempotency refusal, named for what is wrong on this side. + * it writes, read code by code into the frontend contract + * (docs/architecture/backend-api-and-server-state-contract.md 6.1) at the + * backend commit config/contracts/backend-contract-pin.json names. When that + * commit moves, recheck this table with that section; + * tests/unit/backend-contract-pin.test.ts holds it to the copied backend + * answer table. Only the status and code together count. `reason` is the + * diagnostics name of an idempotency refusal, named for what is wrong on + * this side. */ export type IdempotencyRefusalReason = | "IDEMPOTENT_REQUEST_MISMATCH" @@ -168,6 +171,22 @@ const REFUSED_BEFORE_WRITE: Readonly< }), }); +/** + * 1103/12-06. The table's rows, for the test that holds them to the backend's + * own answer table copied at the pinned commit + * (config/contracts/backend-contract-pin.json). + */ +export function refusedBeforeWriteRows(): readonly Readonly<{ + code: string; + status: number; +}>[] { + return Object.freeze( + Object.entries(REFUSED_BEFORE_WRITE).map(([code, refusal]) => + Object.freeze({ code, status: refusal.status }), + ), + ); +} + function refusedBeforeWrite(code: string, status: number | undefined) { const refusal = Object.hasOwn(REFUSED_BEFORE_WRITE, code) ? REFUSED_BEFORE_WRITE[code] @@ -260,6 +279,18 @@ function mayHaveApplied(code: string, status: number): boolean { return maybeAppliedAnswer(code, status) !== undefined; } +/** 1103/12-06. The rows above, for the same comparison as the refusal table. */ +export function maybeAppliedAnswerRows(): readonly Readonly<{ + code: string; + status: number; +}>[] { + return Object.freeze( + Object.entries(MAYBE_APPLIED_ANSWERS).map(([code, answer]) => + Object.freeze({ code, status: answer.status }), + ), + ); +} + /** * 1103/03-05. The cause behind a `MAYBE_APPLIED` the table gave, or * `undefined` when the answer did not leave the result unknown. diff --git a/tests/unit/backend-contract-pin.test.ts b/tests/unit/backend-contract-pin.test.ts new file mode 100644 index 00000000..7bd9051b --- /dev/null +++ b/tests/unit/backend-contract-pin.test.ts @@ -0,0 +1,143 @@ +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"; + +/** + * 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); + } + }); +});