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)", () => {