From 3f7e10c91a964841d725352e75fd52193f4baf6e Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 22:56:52 +0900 Subject: [PATCH] =?UTF-8?q?fix(contracts):=20=ED=95=9C=20=EA=B3=84?= =?UTF-8?q?=EC=95=BD=20=EA=B8=B0=EC=97=AC=20=EC=95=88=EC=97=90=EC=84=9C=20?= =?UTF-8?q?=EC=9D=91=EB=8B=B5=20=EB=AA=A8=EC=96=91=EC=9D=B4=20=EB=8B=A4?= =?UTF-8?q?=EB=A5=B8=20operation=EC=9D=84=20=EA=B1=B0=EC=A0=88=ED=95=9C?= =?UTF-8?q?=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 responseEnvelope는 operation마다 적는 선택 칸이다. 생성 뼈대에 operation을 손으로 더하면서 이 줄을 빠뜨려도 check:types, check:registries, 라우터를 거치는 페이지 테스트가 모두 통과한다. MSW 시나리오 핸들러가 descriptor의 선언대로 답하기 때문이다. 짝 백엔드에 붙이면 그 화면만 SCHEMA_MISMATCH로 깨진다(리뷰 E-1). 고른 방법 계약 조립이 기여 하나 안의 operation이 같은 응답 모양을 읽는지 본다. 값이 없는 것과 "NONE"은 같은 모양이다. 기여 하나는 백엔드 하나의 패키지라서 그 안의 operation은 한 모양이다. 두 백엔드를 쓰는 기능은 기여를 나눈다. 거절 reason은 두 operation과 고칠 방법을 말한다. 앱을 조립하는 모든 테스트와 check:registries가 실패한다. 버린 대안 - responseEnvelope를 필수 칸으로: tsc가 잡는 가장 강한 통제지만 descriptor 약 25곳(참조, tests, 다운스트림 손 descriptor, 계약 패키지)을 깨는 공개 타입 변경이다. 같은 실수(일부만 빠뜨림)를 이 규칙이 잡으므로 작은 쪽을 골랐다. - 기여 단위 기본값: "기본값이 어디서 오나"라는 규칙이 하나 는다. 위험·한계 - 기여 안의 operation 모두에서 줄을 빼면 잡지 못한다. 생성된 gateway 테스트 (백엔드 본문을 손으로 적음)만 잡는다. 매뉴얼에 적었다. - 한 기여에 두 모양을 섞던 다운스트림 기여는 조립이 거부한다. 레포 안에서는 테스트 fixture 하나(api-operation-rows)가 그랬고 고쳤다. 검증 - RED: 새 테스트 3건 중 섞인 기여 거절 1건 실패. GREEN 뒤 통과. - tests/unit·integration·contract·component·features·runtime-schema·platform· architecture 297파일 3,718건: 섞인 fixture 1건만 실패 → 고친 뒤 통과. - check:types, lint 통과. Refs: docs/reviews/2026-11-03-maturity-review/16-structure-patterns.md 16-01 --- docs/manual/01-add-a-feature.md | 19 +++--- docs/manual/reference/errors.md | 1 + src/contracts/external-contract-runtime.ts | 23 ++++++++ tests/unit/api-operation-rows.test.ts | 2 + tests/unit/external-contract-runtime.test.ts | 61 ++++++++++++++++++++ 5 files changed, 99 insertions(+), 7 deletions(-) diff --git a/docs/manual/01-add-a-feature.md b/docs/manual/01-add-a-feature.md index 481909bf..ff81c9dd 100644 --- a/docs/manual/01-add-a-feature.md +++ b/docs/manual/01-add-a-feature.md @@ -193,7 +193,10 @@ FE-REG-API 행은 descriptor에서 자동으로 만든다(`src/contracts/api-ope - Envelope: 성공·실패 본문을 한 번 더 감싸는 공통 바깥 객체다(`http-contract.md` §1). - 성공: `{ "success": true, "data": ..., "meta": ... }` - 실패: `{ "success": false, "error": { "code", ... }, "meta": ... }` -- 이 모양을 읽게 하는 것은 V3 descriptor(`-contract-contribution.ts`)의 한 줄 `responseEnvelope: "ENVELOPE_V1"`이다. 뼈대에 들어 있다. +- 이 모양을 읽게 하는 것은 V3 descriptor(`-contract-contribution.ts`)의 한 줄 `responseEnvelope: "ENVELOPE_V1"`이다. 생성된 operation에는 모두 들어 있다. + - operation을 손으로 더할 때마다 이 줄을 적는다. 이 값은 operation마다 따로다. + - 한 계약 기여 안에서 이 값이 다른 operation이 있으면 계약 조립이 거부한다(`/: responseEnvelope NONE, but in the same contribution reads ENVELOPE_V1; ...`). 기여 하나는 백엔드 하나의 패키지라서다. 그래서 줄을 빠뜨리면 앱을 조립하는 테스트와 `check:registries`가 실패한다. + - **못 잡음**: 기여 안의 operation 모두에서 이 줄을 빼는 것. 그때는 아래 MSW 줄의 손글씨 gateway 테스트만 잡는다. ```text 성공 status → Envelope 확인 → data를 outputValidator로 검증 → mapSuccess @@ -206,7 +209,7 @@ FE-REG-API 행은 descriptor에서 자동으로 만든다(`src/contracts/api-ope - 업무 규칙 거절(`_INVALID`, `*_ALREADY_EXISTS` 등)은 표에 없어 결과 불명이 된다. 그 엔드포인트가 쓰기 전에만 내는 code면 `commandEffect.refusedBeforeWrite`에 적는다. 적어야 사용자가 값을 고쳐 다시 저장할 수 있다(02 결정표 4절). - `mapProblem`이 없거나 `undefined`를 돌려주면 백엔드 code·필드 오류·status별 kind로 읽는다(`src/adapters/http/backend-envelope.ts`). - 바이트 상한(`responseByteLimit`)과 구조 예산은 Envelope 전체에 걸린다. -- MSW: `createHttpScenarioHandler`는 descriptor의 `responseEnvelope`를 보고 Envelope로 답한다(`tests/mocks/handlers/http-scenarios.ts`). 생성된 `tests/features//-http-gateway.test.ts`는 백엔드 본문을 그대로 적어 검사한다. +- MSW: `createHttpScenarioHandler`는 descriptor의 `responseEnvelope`를 보고 Envelope로 답한다(`tests/mocks/handlers/http-scenarios.ts`). 그래서 시나리오 테스트는 선언이 틀려도 통과한다. 생성된 `tests/features//-http-gateway.test.ts`는 백엔드 본문을 그대로 적어 검사한다. operation을 더하면 이 파일에도 그 operation의 백엔드 본문 테스트를 더한다. - `http-contract.md`는 status·`code`의 **뜻**(예: 409 `IDEMPOTENT_IN_FLIGHT`)의 정본이다. 기능 코드에서 그 code는 problem의 `code`로 읽는다. **짝 백엔드가 아닌 백엔드** @@ -239,21 +242,23 @@ DTO와 problem details(`type`·`title`·`status`)를 감싸지 않고 보내는 - `api-request`: 요청 입력. - `api-response`: 응답 DTO. -예: 공지 기능의 검색값 GET과 경로 파라미터 GET. 입력에 관한 칸만 적었다. +예: 공지 기능의 검색값 GET과 경로 파라미터 GET. 입력에 관한 칸과 응답 모양 줄만 적었다. ```ts -// GET /api/notices?q=... inputValidator 스키마 NoticeListQuery (boundary: "route-search-api-request") -pathTemplate: "/api/notices", +// GET /notices?q=... inputValidator 스키마 NoticeListQuery (boundary: "route-search-api-request") +pathTemplate: "/notices", inputValidator: zodValidator("NoticeListQuery", noticeListQuerySchema), +responseEnvelope: "ENVELOPE_V1" as const, projectRequest: (input) => Object.freeze({ pathValues: Object.freeze({}), queryEntries: Object.freeze(input.q === undefined ? [] : [Object.freeze(["q", input.q] as const)]), body: null, }), -// GET /api/notices/{noticeId} inputValidator 스키마 NoticeParams (boundary: "route-params") -pathTemplate: "/api/notices/{noticeId}", +// GET /notices/{noticeId} inputValidator 스키마 NoticeParams (boundary: "route-params") +pathTemplate: "/notices/{noticeId}", inputValidator: zodValidator("NoticeParams", noticeParamsSchema), +responseEnvelope: "ENVELOPE_V1" as const, projectRequest: (input) => Object.freeze({ pathValues: Object.freeze({ noticeId: input.noticeId }), queryEntries: Object.freeze([]), diff --git a/docs/manual/reference/errors.md b/docs/manual/reference/errors.md index c484901d..1d987ccd 100644 --- a/docs/manual/reference/errors.md +++ b/docs/manual/reference/errors.md @@ -101,6 +101,7 @@ lint / check:architecture / check:i18n → FE-GATE-002, FE-GATE-010 | `/: is a read; its retrySemantics is SAFE or IDEMPOTENT, not <값>` | 읽기에 `KEYED`나 `NEVER`를 적었다 | V3 `retrySemantics`. 재시도를 막으려면 `frontend.retryBudget: 0` | | `/: command operations require a command effect descriptor` | 쓰기에 `commandEffect`가 없다 | V3 `commandEffect` | | `/: read operations carry no command descriptors` | GET에 `commandEffect`·`commandRecovery`를 적었다 | 둘 다 `null` | +| `/: responseEnvelope NONE, but in the same contribution reads ENVELOPE_V1; ...` | 한 계약 기여 안에서 operation 하나만 응답 모양이 다르다. 손으로 더한 operation에 `responseEnvelope` 줄을 빠뜨린 경우다 | 그 operation에 `responseEnvelope: "ENVELOPE_V1" as const`를 적는다. 정말 다른 백엔드면 기여를 나눈다 | | `: package version must be exact SemVer` | 버전 범위(`^1.2.0`)나 형식 오류 | `_CONTRACT_PACKAGE.version` | ### 라우트·context diff --git a/src/contracts/external-contract-runtime.ts b/src/contracts/external-contract-runtime.ts index 12b81f83..f89f2e18 100644 --- a/src/contracts/external-contract-runtime.ts +++ b/src/contracts/external-contract-runtime.ts @@ -644,6 +644,28 @@ function assertRefusedBeforeWrite( } } +/** + * 1103/16-01. `responseEnvelope` is per operation so one app can read two + * backends, but one contribution is one backend's package: its operations + * share one frame. A hand-added operation without the line used to pass every + * gate and the MSW scenarios (they answer whatever the descriptor declares) + * and read the real backend's Envelope as a DTO. Missing and `"NONE"` are the + * same frame. Two backends take two contributions. + */ +function assertSameWireFrame( + installed: InstalledHttpContract, + first: InstalledHttpContract | undefined, + featureId: string, +): void { + if (first === undefined) return; + const frame = installed.contract.responseEnvelope ?? "NONE"; + const firstFrame = first.contract.responseEnvelope ?? "NONE"; + if (frame === firstFrame) return; + fail( + `${featureId}/${installed.contract.operationId}: responseEnvelope ${frame}, but ${first.contract.operationId} in the same contribution reads ${firstFrame}; a contribution is one backend's package, so declare the same responseEnvelope on every operation or split the contribution per backend`, + ); +} + function assertEventContract( event: InstalledEventContract, featureId: string, @@ -1006,6 +1028,7 @@ export function composeContractContributions( featureId, ); assertHttpContract(snapshot, featureId, authProfiles); + assertSameWireFrame(snapshot, installedHttp[0], featureId); const operationId = snapshot.contract.operationId; const previous = httpByOperationId.get(operationId); if (previous) fail(`duplicate operation: ${operationId}`); diff --git a/tests/unit/api-operation-rows.test.ts b/tests/unit/api-operation-rows.test.ts index 29c72e8c..59a103e7 100644 --- a/tests/unit/api-operation-rows.test.ts +++ b/tests/unit/api-operation-rows.test.ts @@ -93,6 +93,8 @@ describe("FE-REG-API rows projected from HTTP descriptors", () => { ...TEST_LIST_HTTP_CONTRACT, contract: { ...TEST_LIST_HTTP_CONTRACT.contract, + // 1103/16-01. One contribution reads one frame. + responseEnvelope: "ENVELOPE_V1" as const, outputValidator: unvalidatedPayload( "TestEntityListPayload", "typed by the package", diff --git a/tests/unit/external-contract-runtime.test.ts b/tests/unit/external-contract-runtime.test.ts index 44611d18..564be7e6 100644 --- a/tests/unit/external-contract-runtime.test.ts +++ b/tests/unit/external-contract-runtime.test.ts @@ -311,6 +311,67 @@ describe("declared pre-write refusals", () => { }); }); +// 1103/16-01. A contribution is one backend's package, so its operations read +// one wire frame. An operation added by hand without the `responseEnvelope` +// line used to pass every gate and the MSW scenarios, and failed only on the +// real backend. +describe("one wire frame per contribution (1103/16-01)", () => { + const [listRow, getRow, createRow] = TEST_CONTRACT_CONTRIBUTION.http as readonly [ + InstalledContractContribution["http"][number], + InstalledContractContribution["http"][number], + InstalledContractContribution["http"][number], + ]; + + function framed( + row: InstalledContractContribution["http"][number], + responseEnvelope: "NONE" | "ENVELOPE_V1" | undefined, + ): InstalledContractContribution["http"][number] { + const { responseEnvelope: _dropped, ...contract } = row.contract; + return { + ...row, + contract: + responseEnvelope === undefined ? contract : { ...contract, responseEnvelope }, + } as InstalledContractContribution["http"][number]; + } + + it("refuses an operation that forgot the Envelope its siblings read", () => { + const error = captureContributionError(() => + composeContractContributions([ + contribution("mixed-frames", [ + framed(listRow, "ENVELOPE_V1"), + framed(getRow, undefined), + framed(createRow, "ENVELOPE_V1"), + ]), + ]), + ); + + expect(error.reason).toBe( + "test-feature/TEST_GET_ENTITY: responseEnvelope NONE, but TEST_LIST_ENTITIES in the same contribution reads ENVELOPE_V1; a contribution is one backend's package, so declare the same responseEnvelope on every operation or split the contribution per backend", + ); + }); + + it("reads a missing value and NONE as the same frame", () => { + const composed = composeContractContributions([ + contribution("bare-frames", [ + framed(listRow, "NONE"), + framed(getRow, undefined), + framed(createRow, undefined), + ]), + ]); + + expect(composed.httpByOperationId.size).toBe(3); + }); + + it("lets one feature read two backends through two contributions", () => { + const composed = composeContractContributions([ + contribution("envelope-backend", [framed(listRow, "ENVELOPE_V1")]), + contribution("bare-backend", [framed(getRow, "NONE"), framed(createRow, undefined)]), + ]); + + expect(composed.contributions.map(({ http }) => http.length)).toEqual([1, 2]); + }); +}); + // The sample feature's own cases (its fixture composes, a second one does not) // live in tests/features so they leave with the sample. describe("template fixture provenance (07-04, §4.8)", () => {