From f59a806429ec35f93f3c428add3360b937d6b1da Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 22:59:48 +0900 Subject: [PATCH] =?UTF-8?q?feat(server-state):=20=EB=AE=A4=ED=85=8C?= =?UTF-8?q?=EC=9D=B4=EC=85=98=20=EC=A0=95=EC=B1=85=EC=9D=B4=20operation=20?= =?UTF-8?q?ID=EC=99=80=20=ED=82=A4=20=EC=97=AC=EB=B6=80=EB=A5=BC=20descrip?= =?UTF-8?q?tor=EC=97=90=EC=84=9C=20=EB=B0=9B=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 BoundMutation의 operationId와 requiresIdempotencyKey는 기능이 손으로 다시 적는 자유 값이다. operationId에 오타가 있어도 check:types와 check:registries가 통과하고, 실행기는 intent의 operation ID가 descriptor와 다르다며 보내기 전에 거부한다(MISSING_IDEMPOTENCY_KEY 위반). 화면은 "요청을 처리할 수 없습니다"로 멈추고 원인을 말하지 않는다(리뷰 E-2). 1101/03-03이 같은 재기술을 적었다. 고른 방법 src/contracts/server-state.ts에 commandMutationIdentity(descriptor)를 둔다. descriptor의 operationId와 retrySemantics === "KEYED"를 돌려주고, 정책은 이것을 펼쳐 쓴다. 상수 이름 오타는 tsc가 잡는다. GET·HEAD descriptor를 넘기면 바인딩 때 throw한다. 참조 기능의 생성 정책이 이것을 쓴다. 버린 대안 - BoundMutation.operationId를 brand 타입으로: 자유 문자열도 막지만 테스트 약 27곳과 다운스트림 정책을 깨는 공개 타입 변경이다. - 실행기 위반 이름을 INTENT_OPERATION_MISMATCH로 나누기: http 어댑터의 닫힌 위반 어휘와 화면 매핑을 바꾼다. 값을 descriptor에서 받으면 그 경로에 닿지 않으므로 미뤘다. - 타입에서 method를 쓰기 method로 좁히기: InstalledHttpContract로 주석한 descriptor(method: HttpMethod)가 모두 타입 오류가 나서 실행 때 검사만 둔다. 위험·한계 - 정책에 operationId 문자열을 직접 적는 길은 남는다. 매뉴얼 7단계 "못 잡음"에 적었다. - 참조 기능 presentation이 계약 기여 파일을 import한다. 두 파일 모두 지연 청크라 초기 JS는 바뀌지 않는다(check:bundle은 다음 커밋들과 함께 잰다). 검증 - RED: tests/unit/command-mutation-identity.test.ts 4건이 함수 없음으로 실패. GREEN 뒤 통과. - tests/features/reference-feature, tests/component/application-query.test.tsx 125건 통과. - check:types, check:architecture, lint, verify:documentation 통과. Refs: docs/reviews/2026-11-03-maturity-review/16-structure-patterns.md 16-05 --- docs/manual/01-add-a-feature.md | 22 ++++++++-- docs/manual/02-decision-tables.md | 2 +- docs/manual/reference/errors.md | 1 + docs/manual/reference/patterns.md | 2 +- src/contracts/server-state.ts | 35 ++++++++++++++++ .../presentation/use-reference-feature.ts | 7 +++- tests/unit/command-mutation-identity.test.ts | 40 +++++++++++++++++++ 7 files changed, 102 insertions(+), 7 deletions(-) create mode 100644 tests/unit/command-mutation-identity.test.ts diff --git a/docs/manual/01-add-a-feature.md b/docs/manual/01-add-a-feature.md index ff81c9dd..e13b7b4e 100644 --- a/docs/manual/01-add-a-feature.md +++ b/docs/manual/01-add-a-feature.md @@ -441,15 +441,29 @@ projectRequest: (input) => Object.freeze({ - profile: `LIST_STANDARD`, `DETAIL_STANDARD`, `LOOKUP_STABLE`, `VOLATILE_STATUS` 중 하나. 캐시 시간 정책이다. 정의는 `src/contracts/server-state.ts`. - `measureResult`: 결과 크기 추정 함수. 캐시 예산에 쓴다. - `definitionId`: 쿼리·뮤테이션 정의 이름. -- 쓰기가 있으면 뮤테이션 정책: `requiresIdempotencyKey`, `duplicatePolicy`, `invalidate`. +- 쓰기가 있으면 뮤테이션 정책: `duplicatePolicy`, `invalidate`. operation ID와 멱등 키 여부는 정하지 않는다. descriptor에서 받는다(아래). ② **기준** - topic은 복사하지 않는다. 새 topic이 더 필요하면 값을 새로 만든다. - 형식: `qinv.` + 소문자·숫자 26자. `scripts/create-feature.ts`의 `randomTopicSuffix`가 쓰는 방식이다. - `measureResult`에서 `JSON.stringify`를 쓰지 않는다. 문자열 바이트와 항목당 고정 크기로 어림한다(생성된 `measureItems` 참고). -- `KEYED` 쓰기는 `requiresIdempotencyKey: true`, `duplicatePolicy: "REJECT_WHILE_ACTIVE"`, `invalidate: [topic]`을 쓴다. - - 예제: `src/features/reference-feature/presentation/use-reference-feature.ts`의 생성 뮤테이션 정책. +- 뮤테이션 정책의 operation ID와 `requiresIdempotencyKey`는 `commandMutationIdentity(_CONTRACT)`(`src/contracts/server-state.ts`)로 descriptor에서 받는다. 손으로 적지 않는다. + - 실행기는 intent의 operation ID가 descriptor와 다르면 보내기 전에 거부한다. 손으로 적은 ID에 오타가 있으면 저장이 항상 실패하고, 화면은 "요청을 처리할 수 없습니다"다. + - `requiresIdempotencyKey`는 `retrySemantics`가 `KEYED`일 때만 참이다. +- 쓰기 정책은 `duplicatePolicy: "REJECT_WHILE_ACTIVE"`, `invalidate: [topic]`을 쓴다. + + ```ts + const INVOICE_CREATE_MUTATION_POLICY = Object.freeze({ + definitionId: "invoice-create-v1", + definitionVersion: 1, + ...commandMutationIdentity(INVOICE_CREATE_CONTRACT), + duplicatePolicy: "REJECT_WHILE_ACTIVE" as const, + invalidate: Object.freeze([INVOICE_ITEM_INVALIDATION_TOPIC]), + }); + ``` + + - 예제: 참조 기능 `src/features/reference-feature/presentation/use-reference-feature.ts`의 생성 뮤테이션 정책. ③ **잡는 검사 / 못 잡는 것** @@ -457,6 +471,8 @@ projectRequest: (input) => Object.freeze({ - topic 형식이 틀리면 `Query invalidation topic is invalid.`로 실패한다. - 등록되지 않은 profile은 실행 때 `Unregistered server-state profile: `로 실패한다. - topic·namespace·edge를 더하기만 하면 레지스트리 기준선은 바뀌지 않는다(additive). 9단계에서 할 일이 없다. +- 뮤테이션 정책의 operation ID를 `commandMutationIdentity`로 받으면 descriptor 상수 이름의 오타는 `check:types`가 막는다. 쓰기 descriptor 대신 GET descriptor를 넘기면 바인딩 때 `commandMutationIdentity: is a GET; a mutation binds a write operation`으로 throw한다. +- **못 잡음**: 뮤테이션 정책에 operation ID를 문자열로 직접 적은 것. 타입이 `string`이라 오타가 통과하고, 저장할 때 실행기가 보내기 전에 거부한다(`MISSING_IDEMPOTENCY_KEY` 위반). `commandMutationIdentity`를 쓴다. - **못 잡음**: `bindQuery`의 `operationId` 오타. 타입이 `string`이라 operation과 묶이지 않는다. - **못 잡음**: `definitionId` 중복. 유일성 검사가 없다. diff --git a/docs/manual/02-decision-tables.md b/docs/manual/02-decision-tables.md index 63f21efb..1fed09ad 100644 --- a/docs/manual/02-decision-tables.md +++ b/docs/manual/02-decision-tables.md @@ -89,7 +89,7 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기 | 서버 보장 | 멱등 키(`Idempotency-Key` 헤더)로 같은 요청의 중복 적용을 막는다 | 같은 요청을 여러 번 적용해도 결과가 같다 (키 없이) | 중복을 막지 못한다 | | 자동 재시도 | 실제로 보내기 전까지만. 보낸 뒤 결과를 모르면 결과 불명(4절)으로 넘긴다. 예외: 짝 백엔드가 503 `IDEMPOTENCY_UNAVAILABLE`(실행 전 거절)로 답하면 `retryBudget` 안에서 같은 키로 다시 보낸다 | 된다 | 하지 않는다 | | descriptor | `commandRecovery: { mode: "IDEMPOTENCY_REPLAY", operationIdentityField }` 필수. 참조 기능은 `retryBudget: 0` | — | `retryBudget: 0` 필수 | -| 뮤테이션 정책 | `requiresIdempotencyKey: true` | — | — | +| 뮤테이션 정책 | `...commandMutationIdentity(_CONTRACT)`가 `requiresIdempotencyKey: true`를 준다 | 같은 함수가 `false`를 준다 | 같은 함수가 `false`를 준다 | - 멱등 키: 서버가 "같은 쓰기 요청"을 알아보게 하는 값이다. - 결과를 모를 때 새 키로 다시 보내면 안 된다. 서버는 새 키를 다른 요청으로 보고 막지 못한다. diff --git a/docs/manual/reference/errors.md b/docs/manual/reference/errors.md index 1d987ccd..aa3c68f1 100644 --- a/docs/manual/reference/errors.md +++ b/docs/manual/reference/errors.md @@ -124,6 +124,7 @@ lint / check:architecture / check:i18n → FE-GATE-002, FE-GATE-010 | `Query invalidation topic is invalid.` | topic 형식이 `qinv.` + 26자가 아니다 | `defineQueryInvalidationTopic` 값 | | `Orphan invalidation topic: ` | edge가 없는 topic | 계약 `invalidation.edges` | | `Unregistered server-state profile: ` | 없는 profile | 쿼리 바인딩의 `profileId` | +| `commandMutationIdentity: is a GET; a mutation binds a write operation` | 뮤테이션 정책에 읽기 descriptor를 넘겼다 | 정책의 `commandMutationIdentity(...)` 인자를 쓰기 descriptor로 | ### 조립 기여 diff --git a/docs/manual/reference/patterns.md b/docs/manual/reference/patterns.md index a584972c..99a34e4c 100644 --- a/docs/manual/reference/patterns.md +++ b/docs/manual/reference/patterns.md @@ -95,7 +95,7 @@ const search = (q: string) => |---|---|---|---| | 쿼리 바인딩 | `src/contracts/server-state.ts`의 `bindQuery`, `src/presentation/adapters/query/application-query.ts` | 생성 뼈대 `presentation/use--items.ts` | profile ID (실행 때). `operationId`는 `string`이라 묶이지 않음 | | 무효화 topic | `src/contracts/query-invalidation.ts` | 생성 뼈대 계약 `invalidation` | 조립(중복, 고아 topic) | -| 멱등 키 쓰기 | V3 `retrySemantics: "KEYED"`, `commandRecovery`, 뮤테이션 정책 | 참조 기능 생성 명령(`use-reference-feature.ts`, `reference-feature-contract-contribution.ts`) | 계약 조립(복구 descriptor 필수), 기능 테스트 | +| 멱등 키 쓰기 | V3 `retrySemantics: "KEYED"`, `commandRecovery`, 뮤테이션 정책(`src/contracts/server-state.ts`의 `commandMutationIdentity`로 operation ID와 키 여부를 descriptor에서 받는다) | 참조 기능 생성 명령(`use-reference-feature.ts`, `reference-feature-contract-contribution.ts`) | 계약 조립(복구 descriptor 필수), 타입(descriptor 상수 이름), 기능 테스트 | | 결과 불명 화면 | `src/presentation/components/async-surface.tsx`의 `onReconcileUnknownEffect`, `onResendUnknownEffect` | 참조 기능 `presentation/reference-resource-form-page.tsx` | 기능 테스트만 | | 수정·삭제 명령 | 같은 V3 계약 (`PUT`, `PATCH`, `DELETE`) | 없음 (참조 기능은 생성 명령만 있다) | — | | 낙관적 갱신 | `useApplicationMutation`의 `optimistic` 옵션 (`application-query.ts`) | 없음 | 런타임 테스트만 | diff --git a/src/contracts/server-state.ts b/src/contracts/server-state.ts index d0da23fd..d5acfcc4 100644 --- a/src/contracts/server-state.ts +++ b/src/contracts/server-state.ts @@ -8,6 +8,7 @@ import { } from "./query-keys.ts"; import type { CacheScopeSnapshot } from "./server-state-scope.ts"; import type { MutationIntent } from "./mutation-intent.ts"; +import type { HttpMethod, RetrySemantics } from "./external-contract-runtime.ts"; /** * §10.2. The four fixed profiles. A feature selects one by ID; it never @@ -258,6 +259,40 @@ export const MUTATION_COORDINATOR_BOUNDS = Object.freeze({ settledRetentionMs: 0, }); +/** + * 1103/16-05, 1101/03-03. The two values a mutation policy shares with its + * command's HTTP descriptor, read from the descriptor rather than written a + * second time: the operation id its intent names (the executor refuses an + * intent whose id is not its descriptor's, before sending, reported as a + * missing idempotency key) and whether the intent carries a key (a KEYED + * command only). Spread it into the policy: + * + * ...commandMutationIdentity(INVOICE_CREATE_CONTRACT), + * + * A misspelt descriptor constant fails the type check; a hand-written id + * string fails only when the form sends. + */ +export function commandMutationIdentity( + command: Readonly<{ + contract: Readonly<{ + operationId: string; + method: HttpMethod; + retrySemantics: RetrySemantics; + }>; + }>, +): Readonly<{ operationId: string; requiresIdempotencyKey: boolean }> { + const { operationId, method, retrySemantics } = command.contract; + if (method === "GET" || method === "HEAD") { + throw new TypeError( + `commandMutationIdentity: ${operationId} is a ${method}; a mutation binds a write operation`, + ); + } + return Object.freeze({ + operationId, + requiresIdempotencyKey: retrySemantics === "KEYED", + }); +} + export type BoundMutation = Readonly<{ definitionId: string; definitionVersion: number; diff --git a/src/features/reference-feature/presentation/use-reference-feature.ts b/src/features/reference-feature/presentation/use-reference-feature.ts index 8ab414a2..3a92f496 100644 --- a/src/features/reference-feature/presentation/use-reference-feature.ts +++ b/src/features/reference-feature/presentation/use-reference-feature.ts @@ -14,8 +14,10 @@ import type { ReferenceListFilters, } from "../application/reference-feature-api.ts"; import type { ReferenceResourceView } from "../contracts/reference-mapper.ts"; +import { CREATE_REFERENCE_RESOURCE_CONTRACT } from "../contracts/reference-feature-contract-contribution.ts"; import { bindQuery, + commandMutationIdentity, type BoundMutation, type QueryResultMeasure, } from "../../../contracts/server-state.ts"; @@ -53,8 +55,9 @@ function measureResourceList( const REFERENCE_CREATE_MUTATION_POLICY = Object.freeze({ definitionId: "reference-resource-create-v1", definitionVersion: 1, - operationId: "CREATE_REFERENCE_RESOURCE", - requiresIdempotencyKey: true, + // 1103/16-05. The operation id and the key requirement are the + // descriptor's, so a misspelt id cannot pass the type check. + ...commandMutationIdentity(CREATE_REFERENCE_RESOURCE_CONTRACT), owner: REFERENCE_FEATURE_ID, duplicatePolicy: "REJECT_WHILE_ACTIVE" as const, invalidate: Object.freeze([REFERENCE_RESOURCE_INVALIDATION_TOPIC]), diff --git a/tests/unit/command-mutation-identity.test.ts b/tests/unit/command-mutation-identity.test.ts new file mode 100644 index 00000000..bfa3d858 --- /dev/null +++ b/tests/unit/command-mutation-identity.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, it } from "vitest"; + +import { commandMutationIdentity } from "../../src/contracts/server-state.ts"; +import { + TEST_CREATE_HTTP_CONTRACT, + TEST_LIST_HTTP_CONTRACT, +} from "../helpers/external-contract-fixture.ts"; + +/** + * 1103/16-05, 1101/03-03. A mutation policy used to restate its command's + * operation id and key requirement as free values. A misspelt id passed the + * type check and the registries, and the executor refused every save before + * sending, as a missing idempotency key. The policy now takes both from the + * HTTP descriptor. + */ +describe("commandMutationIdentity", () => { + it("takes the operation id and the key requirement from a KEYED descriptor", () => { + expect(commandMutationIdentity(TEST_CREATE_HTTP_CONTRACT)).toEqual({ + operationId: "TEST_CREATE_ENTITY", + requiresIdempotencyKey: true, + }); + }); + + it.each(["NEVER", "IDEMPOTENT"] as const)( + "sends no key for a %s command", + (retrySemantics) => { + expect( + commandMutationIdentity({ + contract: { ...TEST_CREATE_HTTP_CONTRACT.contract, retrySemantics }, + }), + ).toEqual({ operationId: "TEST_CREATE_ENTITY", requiresIdempotencyKey: false }); + }, + ); + + it("refuses a read descriptor", () => { + expect(() => commandMutationIdentity(TEST_LIST_HTTP_CONTRACT)).toThrow( + "commandMutationIdentity: TEST_LIST_ENTITIES is a GET; a mutation binds a write operation", + ); + }); +});