From 5c0b37e39e1368be4d3451fbb5592dcb265f64c5 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 5 Nov 2026 22:15:20 +0900 Subject: [PATCH 1/8] =?UTF-8?q?fix(contracts)!:=20=EC=93=B0=EA=B8=B0=20?= =?UTF-8?q?=EB=92=A4=EC=97=90=EB=8F=84=20=EB=82=98=EC=98=A4=EB=8A=94=20?= =?UTF-8?q?=ED=94=8C=EB=9E=AB=ED=8F=BC=20code=EB=A5=BC=20=EC=93=B0?= =?UTF-8?q?=EA=B8=B0=20=EC=A0=84=20=EA=B1=B0=EC=A0=88=EB=A1=9C=20=EC=A0=81?= =?UTF-8?q?=EC=A7=80=20=EB=AA=BB=ED=95=98=EA=B2=8C=20=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 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 접두사 규칙(_로 시작하는 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 --- .../backend-api-and-server-state-contract.md | 7 +++ docs/manual/02-decision-tables.md | 1 + docs/manual/reference/errors.md | 1 + scripts/lib/removal-fixture.ts | 2 + src/adapters/http/backend-envelope.ts | 5 +- src/contracts/external-contract-runtime.ts | 48 +++++++++++++++++- tests/unit/backend-contract-pin.test.ts | 50 +++++++++++++++++++ tests/unit/backend-envelope.test.ts | 13 +++++ tests/unit/external-contract-runtime.test.ts | 12 +++++ 9 files changed, 137 insertions(+), 2 deletions(-) diff --git a/docs/architecture/backend-api-and-server-state-contract.md b/docs/architecture/backend-api-and-server-state-contract.md index 2e2fe977..b3a57096 100644 --- a/docs/architecture/backend-api-and-server-state-contract.md +++ b/docs/architecture/backend-api-and-server-state-contract.md @@ -343,6 +343,13 @@ mutation이 400·409·422로 실패하면 프론트는 그 요청이 적용됐 - 위 표의 code(`VALIDATION_FAILED` 등)는 적어도 표의 status 규칙을 따른다. `IDEMPOTENT_*`·`IDEMPOTENCY_*`는 적을 수 없다. 계약 조립이 거절하고, 실행기도 무시한다. 409 `IDEMPOTENT_IN_FLIGHT`의 앞선 요청은 적용될 수 있기 때문이다. +- 위 표에서 "쓰기 뒤 가능"인 플랫폼 code(`BAD_PARAMETER`, `MAPPING_FAILED`, `DB_*` 8개, + `LOCK_ACQUISITION_TIMEOUT`, fileserver code)도 적을 수 없다(1105/03-01). 계약 조립이 + 거절하고 실행기도 무시한다. 목록은 `src/contracts/external-contract-runtime.ts`의 + `PLATFORM_CODES_POSSIBLY_AFTER_WRITE`이고, `tests/unit/backend-contract-pin.test.ts`가 + 이 표의 "쓰기 뒤 가능" 행과 대조한다. 참조 도메인 code와 web-advanced patch code는 + 엔드포인트가 단계를 정하므로 그 엔드포인트를 확인한 기능 작성자가 적을 수 있다. 이 표에 + "쓰기 뒤 가능" 플랫폼 code를 더하면 그 목록도 같은 변경에서 고친다. - `responseEnvelope: "ENVELOPE_V1"`가 아닌 operation에는 적을 수 없다. 실행기가 백엔드 code를 읽지 않는다. - 판정은 `src/adapters/http/backend-envelope.ts` `envelopeFailureEffect`, 조립 검사는 diff --git a/docs/manual/02-decision-tables.md b/docs/manual/02-decision-tables.md index e36381f1..55c30c46 100644 --- a/docs/manual/02-decision-tables.md +++ b/docs/manual/02-decision-tables.md @@ -182,6 +182,7 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기 - 짝 백엔드 `new-feature.sh`가 만든 create는 이름을 트랜잭션 전에 검사하고 400 `_INVALID`를 준다(백엔드 `Create__Feature__UseCase.java.tmpl`). 이 code는 적는다. 예: 기능 `worklog`이면 `refusedBeforeWrite: ["WORKLOG_INVALID"]`. - 고르는 기준: 백엔드 코드에서 그 code를 던지는 곳이 모두 쓰기(트랜잭션, 외부 호출) 전인지 확인했을 때만 적는다. 확인하지 못했으면 적지 않는다. 쓰기 뒤에도 나오는 code를 적으면 결과 불명 요청을 새 키로 다시 보내 중복이 생길 수 있다. - 적을 수 없는 code: `IDEMPOTENT_*`, `IDEMPOTENCY_*`. 멱등성 응답은 백엔드 표가 정한다. 적으면 계약 조립이 `refusedBeforeWrite cannot declare ...`로 거부한다. `responseEnvelope: "ENVELOPE_V1"`가 아닌 operation에 적어도 거부한다(`refusedBeforeWrite needs responseEnvelope ENVELOPE_V1 ...`). + - 계약 문서 6.1절이 "쓰기 뒤 가능"으로 둔 플랫폼 code(`BAD_PARAMETER`, `MAPPING_FAILED`, `DB_UNIQUE_VIOLATION` 등 `DB_*`, `LOCK_ACQUISITION_TIMEOUT`, fileserver code)도 적을 수 없다. 폼을 막는 400 `BAD_PARAMETER`나 409 `DB_UNIQUE_VIOLATION`은 어느 층에서든, 트랜잭션 안에서도 나온다. 적으면 계약 조립이 `refusedBeforeWrite cannot declare ...; contract 6.1 reads this platform code as possibly raised after the write`로 거부한다. - 거절 이유를 필드 옆에 보이려면 `mapProblem`이 그 code를 `VALIDATION_REJECTED`와 필드 목록으로 돌려준다. 선언 없이 `mapProblem`만 두면 필드 오류는 보이지만 저장 버튼은 꺼진 채다. **503 `IDEMPOTENCY_UNAVAILABLE`는 `NOT_APPLIED`로 분류하지 않는다.** diff --git a/docs/manual/reference/errors.md b/docs/manual/reference/errors.md index 5ba0d59e..39d28c98 100644 --- a/docs/manual/reference/errors.md +++ b/docs/manual/reference/errors.md @@ -103,6 +103,7 @@ lint / check:architecture / check:i18n → FE-GATE-002, FE-GATE-010 | `/: KEYED commands require a recovery descriptor` | `KEYED`인데 `commandRecovery`가 없다 | V3 `commandRecovery` | | `/: 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` | +| `/: refusedBeforeWrite cannot declare ; contract 6.1 reads this platform code as possibly raised after the write` | `commandEffect.refusedBeforeWrite`에 계약 문서 6.1절이 "쓰기 뒤 가능"으로 둔 플랫폼 code(`BAD_PARAMETER`, `DB_*` 등)를 적었다 | 그 code를 목록에서 지운다. 그 실패는 결과 불명으로 남는다([02 결정표 4절](../02-decision-tables.md#4-결과-불명)) | | `/: 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` | diff --git a/scripts/lib/removal-fixture.ts b/scripts/lib/removal-fixture.ts index efbbf9b3..9aa9bc80 100644 --- a/scripts/lib/removal-fixture.ts +++ b/scripts/lib/removal-fixture.ts @@ -70,6 +70,8 @@ export const REMOVAL_FIXTURE_DOCUMENT_TARGETS = Object.freeze([ export const REMOVAL_FIXTURE_DOCUMENT_TESTS = Object.freeze([ "tests/unit/changelog-review-ids.test.ts", "tests/unit/documentation-readiness.test.ts", + // 1105/03-01. Reads the 6.1 table of the frontend contract document. + "tests/unit/backend-contract-pin.test.ts", ] as const); /** The tests a fixture copied from `copyTargets` cannot run. */ diff --git a/src/adapters/http/backend-envelope.ts b/src/adapters/http/backend-envelope.ts index b959cb40..7d9d28f8 100644 --- a/src/adapters/http/backend-envelope.ts +++ b/src/adapters/http/backend-envelope.ts @@ -4,6 +4,7 @@ import { type FailureKind, type ValidationIssue, } from "../../contracts/errors.ts"; +import { PLATFORM_CODES_POSSIBLY_AFTER_WRITE } from "../../contracts/external-contract-runtime.ts"; import { z } from "../../contracts/zod.ts"; /** @@ -312,7 +313,8 @@ export function unknownEffectReason( * (`commandEffect.refusedBeforeWrite`). Composition already refuses an * idempotency code in that list; this is the runtime's own fail-close for an * executor called without composition. The table's own codes keep its status - * rule. + * rule. 1105/03-01. So do the platform codes contract 6.1 reads as possibly + * raised after the write. */ function declaredBeforeWrite( code: string, @@ -322,6 +324,7 @@ function declaredBeforeWrite( declared !== undefined && !Object.hasOwn(REFUSED_BEFORE_WRITE, code) && !/^IDEMPOTEN(?:T|CY)_/.test(code) && + !PLATFORM_CODES_POSSIBLY_AFTER_WRITE.includes(code) && declared.includes(code) ); } diff --git a/src/contracts/external-contract-runtime.ts b/src/contracts/external-contract-runtime.ts index f89f2e18..77327a9a 100644 --- a/src/contracts/external-contract-runtime.ts +++ b/src/contracts/external-contract-runtime.ts @@ -166,7 +166,10 @@ export interface CommandEffectDescriptor { * carries one of these codes is `NOT_APPLIED`, so the next save takes a new * key. Every code not listed stays `MAYBE_APPLIED`. Idempotency codes * (`IDEMPOTENT_*`, `IDEMPOTENCY_*`) are the backend table's to decide, and - * composition refuses them here. Composition installs a copy of the list. + * composition refuses them here, as it refuses the platform codes contract + * 6.1 reads as possibly after the write (1105/03-01, + * `PLATFORM_CODES_POSSIBLY_AFTER_WRITE`). Composition installs a copy of + * the list. */ readonly refusedBeforeWrite?: readonly string[]; } @@ -613,6 +616,44 @@ const BACKEND_ERROR_CODE = /^[A-Z0-9_]{1,64}$/; */ const IDEMPOTENCY_CODE = /^IDEMPOTEN(?:T|CY)_/; +/** + * 1105/03-01. The paired backend's platform codes that contract 6.1 + * (docs/architecture/backend-api-and-server-state-contract.md) reads as + * possibly raised after the write: `IllegalArgumentException` from any layer, + * the mappers (the idempotency response codec runs after the action), the + * persistence adapter's SQL and JPA failures, the distributed lock and the + * fileserver module. Their stage is the template's knowledge, not the + * feature's, so no operation may declare them as refused before its write. + * Business codes stay the feature author's to declare. + * tests/unit/backend-contract-pin.test.ts holds this list to the 6.1 table. + */ +export const PLATFORM_CODES_POSSIBLY_AFTER_WRITE: readonly string[] = + Object.freeze([ + "BAD_PARAMETER", + "MAPPING_FAILED", + "DB_SERIALIZATION_FAILURE", + "DB_DEADLOCK", + "DB_LOCK_TIMEOUT", + "DB_NULL_VIOLATION", + "DB_FK_VIOLATION", + "DB_UNIQUE_VIOLATION", + "DB_CHECK_VIOLATION", + "DB_OPTIMISTIC_CONFLICT", + "LOCK_ACQUISITION_TIMEOUT", + "BAD_REQUEST", + "FILE_ALREADY_EXISTS", + "FILE_NOT_READY", + "UPLOAD_OFFSET_MISMATCH", + "CONCURRENT_MODIFICATION", + "INTEGRITY_MISMATCH", + "MALWARE_DETECTED", + "INVALID_PATH", + "PATH_OUTSIDE_NAMESPACE", + ]); +const PLATFORM_CODE_AFTER_WRITE: ReadonlySet = new Set( + PLATFORM_CODES_POSSIBLY_AFTER_WRITE, +); + function assertRefusedBeforeWrite( contract: InstalledHttpContract["contract"], label: string, @@ -639,6 +680,11 @@ function assertRefusedBeforeWrite( `${label}: refusedBeforeWrite cannot declare ${code}; the backend's idempotency answers are decided by its own table`, ); } + if (PLATFORM_CODE_AFTER_WRITE.has(code)) { + fail( + `${label}: refusedBeforeWrite cannot declare ${code}; contract 6.1 reads this platform code as possibly raised after the write`, + ); + } if (seen.has(code)) fail(`${label}: refusedBeforeWrite repeats ${code}`); seen.add(code); } diff --git a/tests/unit/backend-contract-pin.test.ts b/tests/unit/backend-contract-pin.test.ts index 7bd9051b..df4f0983 100644 --- a/tests/unit/backend-contract-pin.test.ts +++ b/tests/unit/backend-contract-pin.test.ts @@ -9,6 +9,7 @@ import { 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 @@ -141,3 +142,52 @@ describe("paired backend contract pin", () => { } }); }); + +/** + * 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 { + const text = readFileSync(pin.frontend.contractDocument, "utf8"); + const section = text.split("### 6.1 ")[1]?.split(/\n#{2,3} /u)[0] ?? ""; + const codes = new Set(); + 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(), + ); + }); +}); diff --git a/tests/unit/backend-envelope.test.ts b/tests/unit/backend-envelope.test.ts index 36695dbc..6e2f6344 100644 --- a/tests/unit/backend-envelope.test.ts +++ b/tests/unit/backend-envelope.test.ts @@ -101,6 +101,19 @@ describe("backend Envelope failure table", () => { ); }); + // 1105/03-01. The runtime's own fail-close for an executor called without + // composition: a platform code 6.1 reads as possibly after the write + // stays maybe applied, declared or not. + it.each([ + [400, "BAD_PARAMETER"], + [400, "MAPPING_FAILED"], + [409, "DB_UNIQUE_VIOLATION"], + [409, "LOCK_ACQUISITION_TIMEOUT"], + [422, "INTEGRITY_MISMATCH"], + ] as const)("keeps a declared platform code %i %s maybe applied", (status, code) => { + expect(envelopeFailureEffect(status, { code }, [code])).toBe("MAYBE_APPLIED"); + }); + it("does not reach statuses outside 400, 409 and 422", () => { expect(envelopeFailureEffect(500, { code: "WORKLOG_INVALID" }, declared)).toBeUndefined(); expect(envelopeFailureEffect(503, { code: "REQUEST_TIMEOUT" }, ["REQUEST_TIMEOUT"])).toBe( diff --git a/tests/unit/external-contract-runtime.test.ts b/tests/unit/external-contract-runtime.test.ts index 564be7e6..cfcaf99d 100644 --- a/tests/unit/external-contract-runtime.test.ts +++ b/tests/unit/external-contract-runtime.test.ts @@ -283,6 +283,18 @@ describe("declared pre-write refusals", () => { ); }); + // 1105/03-01. Contract 6.1 reads these platform codes as possibly raised + // after the write. Declared, a 400 or 409 that came after a write would read + // as not applied and the next save would be a new request. + it.each(["BAD_PARAMETER", "MAPPING_FAILED", "DB_UNIQUE_VIOLATION", "LOCK_ACQUISITION_TIMEOUT"])( + "refuses to declare the platform code %s, which 6.1 reads as possibly after the write", + (code) => { + expect(reasonFor(["TEST_ENTITY_INVALID", code])).toBe( + `test-feature/TEST_CREATE_ENTITY: refusedBeforeWrite cannot declare ${code}; contract 6.1 reads this platform code as possibly raised after the write`, + ); + }, + ); + it("refuses a list on an operation that does not read the Envelope", () => { expect(reasonFor(["TEST_ENTITY_INVALID"], "NONE")).toBe( "test-feature/TEST_CREATE_ENTITY: refusedBeforeWrite needs responseEnvelope ENVELOPE_V1; without it classifyProblem decides", From c6c37f395b6b2c05240b44caa73181f0bdfc0b65 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 5 Nov 2026 22:18:20 +0900 Subject: [PATCH 2/8] =?UTF-8?q?fix(http):=20=EB=B0=B1=EC=97=94=EB=93=9C=20?= =?UTF-8?q?rate-limit=20503=20=EB=91=90=20code=EB=A5=BC=20=EC=93=B0?= =?UTF-8?q?=EA=B8=B0=20=EC=A0=84=20=EA=B1=B0=EC=A0=88=EB=A1=9C=20=EC=9D=BD?= =?UTF-8?q?=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 짝 백엔드 http-contract.md §4는 web 전용 code 넷을 적는다. 그중 503 RATE_LIMIT_UNAVAILABLE(저장소 응답 없음, retryable, Retry-After 있음)과 503 RATE_LIMIT_INCOMPATIBLE(제공자 불일치)이 답 표 사본에도 프론트 판정 표에도 없다. 그래서 이 503은 기능 분류기가 정하고, create:feature가 만든 쓰기의 분류기는 늘 MAYBE_APPLIED다. 아무 일도 일어나지 않은 저장이 결과 불명이 되고, NEVER 쓰기는 사실과 다른 "변경됨으로 확인"을 눌러야 폼이 풀린다(리뷰 실험 X4: 429는 NOT_APPLIED, 503 둘은 SERVER_FAILURE/MAYBE_APPLIED). pin은 §4를 대조했다고 적었지만 사본에는 REQUEST_TIMEOUT 한 행만 있었다. 고른 방법 백엔드 45d2a478을 읽기만 해서 code마다 판정했다. 두 code는 RateLimitInterceptor.preHandle이 false를 돌려주며 쓰고(Unavailable· Indeterminate → RATE_LIMIT_UNAVAILABLE, Incompatible → RATE_LIMIT_INCOMPATIBLE), main 소스에서 두 code를 내는 곳은 그 두 줄뿐이다. preHandle이 false면 handler를 부르지 않으므로 둘 다 쓰기 전이다. 백엔드는 같은 키 재전송을 요구하지 않는다(멱등성 executor 전). 그래서 답 표 사본에 refusedBeforeWrite: true, sameKeyResend: false로 두 행을 더하고, 프론트 거절 표 REFUSED_BEFORE_WRITE에 status 503과 함께 더했다. pin 테스트의 "답 표대로 읽는다" 규칙이 그대로 NOT_APPLIED를 요구하고 양방향 대조가 두 표를 함께 지킨다. kind는 지금처럼 SERVER_FAILURE(action retry)이고, KEYED도 자동 재전송은 없다(같은 키를 요구하는 답은 503 IDEMPOTENCY_UNAVAILABLE 하나다). pin의 comparedOn을 §4를 다시 대조한 날짜로 올렸다. 계약 문서 4.1·6.1절과 매뉴얼 01·02의 5xx 행 수를 고쳤다. 버린 대안 생성기 분류기가 503을 code별로 보게 한다: 생성 기능에만 고쳐지고 손으로 쓴 Envelope operation은 그대로 남는다. 판정은 백엔드 답 표 한 곳이 정한다는 지금 규칙을 따랐다. 위험·한계 - 추론(실행 확인 안 함): Spring MVC는 비동기 처리(Callable·DeferredResult) 뒤 ASYNC 재디스패치에서도 interceptor의 preHandle을 다시 부르고, 이 interceptor는 dispatcher 종류를 보지 않는다. 비동기 쓰기 컨트롤러라면 이 503(그리고 429)이 쓰기 뒤에도 나올 수 있다. 45d2a478에는 Envelope을 돌려주는 비동기 쓰기 컨트롤러가 없다(web-advanced 스트리밍과 fileserver 전송뿐). 계약 6.1절에 적었다. 백엔드에 넘길 요청: RateLimitInterceptor가 DispatcherType.REQUEST에서만 평가하게 한다. - fileserver-upload.ts는 같은 백엔드 답을 자기 표로 따로 판정한다(01 영역). 여기서는 바꾸지 않았다. - NOT_APPLIED가 되면서 IDEMPOTENT 쓰기는 이 503에 retryBudget 안에서 자동으로 다시 보낼 수 있게 됐다(503은 재시도 status다). 쓰기 전 거절이라 중복은 없다. RATE_LIMIT_INCOMPATIBLE은 백엔드가 retryable false로 보내지만 실행기는 status로 판단하므로 같은 답을 한 번 더 받을 수 있다. KEYED·NEVER는 자동 재전송이 없다. 검증 desktop batch에서 확인: node scripts/run-vitest.ts run tests/unit/backend-envelope.test.ts tests/unit/backend-contract-pin.test.ts tests/integration/http-execution-v3-envelope.test.ts Refs: 1105/03-02 --- config/contracts/backend-contract-pin.json | 2 +- .../backend-idempotency-answers.json | 14 +++++++ .../backend-api-and-server-state-contract.md | 13 ++++++- docs/manual/01-add-a-feature.md | 2 +- docs/manual/02-decision-tables.md | 4 +- src/adapters/http/backend-envelope.ts | 9 +++++ .../http-execution-v3-envelope.test.ts | 37 +++++++++++++++++++ tests/unit/backend-envelope.test.ts | 13 +++++++ 8 files changed, 89 insertions(+), 5 deletions(-) diff --git a/config/contracts/backend-contract-pin.json b/config/contracts/backend-contract-pin.json index e7a57933..0ae2d8bc 100644 --- a/config/contracts/backend-contract-pin.json +++ b/config/contracts/backend-contract-pin.json @@ -15,5 +15,5 @@ "idempotencyAnswers": "config/contracts/backend-idempotency-answers.json" }, "owner": "frontend-platform", - "comparedOn": "2026-11-04" + "comparedOn": "2026-11-05" } diff --git a/config/contracts/backend-idempotency-answers.json b/config/contracts/backend-idempotency-answers.json index 23c7c23e..57130d0e 100644 --- a/config/contracts/backend-idempotency-answers.json +++ b/config/contracts/backend-idempotency-answers.json @@ -54,6 +54,20 @@ "status": 503, "refusedBeforeWrite": false, "sameKeyResend": false + }, + { + "section": "4", + "code": "RATE_LIMIT_UNAVAILABLE", + "status": 503, + "refusedBeforeWrite": true, + "sameKeyResend": false + }, + { + "section": "4", + "code": "RATE_LIMIT_INCOMPATIBLE", + "status": 503, + "refusedBeforeWrite": true, + "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 b3a57096..13411fa9 100644 --- a/docs/architecture/backend-api-and-server-state-contract.md +++ b/docs/architecture/backend-api-and-server-state-contract.md @@ -167,7 +167,8 @@ Envelope의 모양과 키 존재 규칙은 짝 백엔드 템플릿 문서가 정 1절 "Envelope 키 존재 규칙" - 기준 커밋: 백엔드 `45d2a478`. 기계가 읽는 정본은 `config/contracts/backend-contract-pin.json`(repo, 전체 SHA, 대조한 절 §1·§2·§4, - 담당)이다. 백엔드 §2 표와 §4 `REQUEST_TIMEOUT`은 + 담당)이다. 백엔드 §2 표와 §4의 503 셋(`REQUEST_TIMEOUT`, `RATE_LIMIT_UNAVAILABLE`, + `RATE_LIMIT_INCOMPATIBLE`)은 `config/contracts/backend-idempotency-answers.json`에 code·status·쓰기 전 거절·같은 키 재전송 열로 옮겨 두었다. `tests/unit/backend-contract-pin.test.ts`가 그 표와 `backend-envelope.ts`의 판정을 양방향으로 대조한다. 값이 null인 필드는 키째 @@ -317,6 +318,16 @@ mutation이 400·409·422로 실패하면 프론트는 그 요청이 적용됐 `IDEMPOTENCY_RECOVERY_REQUIRED`, §4의 503 `REQUEST_TIMEOUT`이다. 실행기가 자동으로 다시 보내는 것은 KEYED 명령의 503 `IDEMPOTENCY_UNAVAILABLE`뿐이다. 나머지는 결과 불명 화면에서 사용자가 같은 키로 다시 보낸다. +- §4의 503 `RATE_LIMIT_UNAVAILABLE`(rate-limit 저장소 응답 없음, `Retry-After` 있음)과 + 503 `RATE_LIMIT_INCOMPATIBLE`(rate-limit 제공자가 계약과 맞지 않음)은 status와 code가 + 함께 맞으면 기능 분류기와 상관없이 `NOT_APPLIED`다(1105/03-02, `backend-envelope.ts` + `REFUSED_BEFORE_WRITE`). 백엔드 `RateLimitInterceptor.java`의 `preHandle`이 컨트롤러 전에 + `false`를 돌려주며 낸다. `45d2a478`의 main 소스에서 이 두 code를 내는 곳은 그 두 + 줄뿐이다. 자동 재전송은 없다(KEYED도 같다). 남은 위험(추론, 실행 확인 안 함): Spring MVC는 + 비동기 처리(`Callable`·`DeferredResult`)가 끝난 뒤의 ASYNC 재디스패치에서도 interceptor의 + `preHandle`을 다시 부른다. 그 interceptor는 dispatcher 종류를 보지 않으므로 비동기 쓰기 + 컨트롤러라면 이 503(그리고 429)이 쓰기 뒤에도 나올 수 있다. `45d2a478`에는 Envelope을 + 돌려주는 비동기 쓰기 컨트롤러가 없다(web-advanced 스트리밍과 fileserver 전송뿐). - 파일 위치(백엔드 repo `clean-architecture-backend-template` 기준): - `GlobalExceptionHandler.java`, `HttpStatusErrorCodes.java`: `clean-architecture-backend-template/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/` - `PageParams.java`, `SortParam.java`: 같은 모듈 `.../web/pagination/` diff --git a/docs/manual/01-add-a-feature.md b/docs/manual/01-add-a-feature.md index 6128b020..f9285207 100644 --- a/docs/manual/01-add-a-feature.md +++ b/docs/manual/01-add-a-feature.md @@ -219,7 +219,7 @@ FE-REG-API 행은 descriptor에서 자동으로 만든다(`src/contracts/api-ope - 백엔드는 값이 null인 필드를 키째 뺀다. `data` 키가 없으면 `null`로 읽는다. DTO 안에서 null일 수 있는 필드는 스키마에서 `.optional()`로 받는다. - problem 스키마(`-schemas.ts`의 `ProblemSchema`)는 Envelope의 `error` 객체다. 분기는 `code`로 한다. `message`는 버린다. -- 400·409·422와 백엔드가 정한 5xx 넷이 적용됐는지는 실행기가 백엔드 기준 표로 정한다. 목록은 [02 결정표 4절](02-decision-tables.md#4-결과-불명)이다. +- 400·409·422와 백엔드가 정한 5xx 여섯이 적용됐는지는 실행기가 백엔드 기준 표로 정한다. 목록은 [02 결정표 4절](02-decision-tables.md#4-결과-불명)이다. - 업무 규칙 거절(`_INVALID`, `*_ALREADY_EXISTS` 등)은 표에 없어 결과 불명이 된다. 그 엔드포인트가 쓰기 전에만 내는 code면 `commandEffect.refusedBeforeWrite`에 적는다. 적어야 사용자가 값을 고쳐 다시 저장할 수 있다(02 결정표 4절). - `mapProblem`이 없거나 `undefined`를 돌려주면 백엔드 code·필드 오류·status별 kind로 읽는다(`src/adapters/http/backend-envelope.ts`). - 바이트 상한(`responseByteLimit`)과 구조 예산은 Envelope 전체에 걸린다. diff --git a/docs/manual/02-decision-tables.md b/docs/manual/02-decision-tables.md index 55c30c46..058309cc 100644 --- a/docs/manual/02-decision-tables.md +++ b/docs/manual/02-decision-tables.md @@ -172,8 +172,8 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기 - 같은 status라도 code로 나뉠 수 있다. 예: 409 중 "처리 중"은 `MAYBE_APPLIED`여야 한다. `NOT_APPLIED`로 보면 다음 저장이 새 키를 만들어 같은 작업이 두 번 적용된다. - 401·403·429는 문제 응답 본문을 읽기 전에 status로 나뉜다. 서버가 상태를 안 바꾼다고 보장하면 `classifyStatus`로 `NOT_APPLIED`를 돌려준다. 없으면 `MAYBE_APPLIED`다. - 문제 응답 본문이 기능의 problem 스키마를 통과하지 못하면 `classifyProblem`을 부르지 않는다. 쓰기는 `MAYBE_APPLIED`가 된다(`src/adapters/http/http-execution-v3.ts`). -- `responseEnvelope: "ENVELOPE_V1"`인 operation은 400·409·422와 백엔드가 직접 정한 5xx 네 가지의 판정을 실행기가 백엔드 기준 표로 정한다(`src/adapters/http/backend-envelope.ts`의 `REFUSED_BEFORE_WRITE`, `MAYBE_APPLIED_ANSWERS`). 표의 근거는 [계약 문서](../architecture/backend-api-and-server-state-contract.md) 6.1절이다(백엔드 코드에서 code마다 쓰기 전·후를 읽은 결과). `classifyProblem`은 그 밖의 status만 받고, 다르게 답해도 표의 판정은 바뀌지 않는다. - - `NOT_APPLIED`(쓰기 전 거절): 400 `VALIDATION_FAILED`(details 모양과 상관없음), 400 `IDEMPOTENCY_KEY_INVALID`, 422 `IDEMPOTENT_REQUEST_MISMATCH` +- `responseEnvelope: "ENVELOPE_V1"`인 operation은 400·409·422와 백엔드가 직접 정한 5xx 여섯 가지의 판정을 실행기가 백엔드 기준 표로 정한다(`src/adapters/http/backend-envelope.ts`의 `REFUSED_BEFORE_WRITE`, `MAYBE_APPLIED_ANSWERS`). 표의 근거는 [계약 문서](../architecture/backend-api-and-server-state-contract.md) 6.1절이다(백엔드 코드에서 code마다 쓰기 전·후를 읽은 결과). `classifyProblem`은 그 밖의 status만 받고, 다르게 답해도 표의 판정은 바뀌지 않는다. + - `NOT_APPLIED`(쓰기 전 거절): 400 `VALIDATION_FAILED`(details 모양과 상관없음), 400 `IDEMPOTENCY_KEY_INVALID`, 422 `IDEMPOTENT_REQUEST_MISMATCH`, 503 `RATE_LIMIT_UNAVAILABLE`·`RATE_LIMIT_INCOMPATIBLE`(rate-limit 저장소 장애·제공자 불일치. 컨트롤러 전에 거절한다) - `MAYBE_APPLIED`: 그 밖의 400·409·422. 409 `IDEMPOTENT_IN_FLIGHT`, `BAD_PARAMETER`, 도메인 code, fileserver의 422가 여기 든다. 그리고 status와 code가 함께 맞는 5xx 넷: 503 `IDEMPOTENCY_UNAVAILABLE`, 503 `IDEMPOTENCY_COMPLETION_UNKNOWN`(실행 뒤 결과 기록 실패, 새 키 금지), 500 `IDEMPOTENCY_RECOVERY_REQUIRED`(이전 시도 효과를 증명 못 함), 503 `REQUEST_TIMEOUT`(비동기 요청 시간 초과, 처리가 계속될 수 있음) - 이 넷은 실행기가 자동으로 다시 보내지 않는다. 결과 불명 화면에서 같은 키로 다시 보낸다. 예외는 KEYED 명령의 503 `IDEMPOTENCY_UNAVAILABLE` 하나다(아래) - 짝 백엔드가 모든 엔드포인트에서 쓰기 전에 거절하는 code를 새로 만들면 계약 문서 6.1절과 이 표를 함께 고친다. 표에 없으면 `MAYBE_APPLIED`다 diff --git a/src/adapters/http/backend-envelope.ts b/src/adapters/http/backend-envelope.ts index 7d9d28f8..b9e0c971 100644 --- a/src/adapters/http/backend-envelope.ts +++ b/src/adapters/http/backend-envelope.ts @@ -145,6 +145,10 @@ export function readFailureEnvelope( * 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. + * + * 1105/03-02. And the edge rate limiter's two 503s (§4): its interceptor + * answers in `preHandle`, before the controller runs, so the command did not + * run whatever the operation's own classifier says. */ export type IdempotencyRefusalReason = | "IDEMPOTENT_REQUEST_MISMATCH" @@ -170,6 +174,11 @@ const REFUSED_BEFORE_WRITE: Readonly< status: 422, reason: "IDEMPOTENT_REQUEST_MISMATCH", }), + // §4. The rate-limit store did not answer (retryable, with Retry-After), + // or the rate-limit provider does not match the contract. Both come from + // RateLimitInterceptor.preHandle, before any handler. + RATE_LIMIT_UNAVAILABLE: Object.freeze({ status: 503 }), + RATE_LIMIT_INCOMPATIBLE: Object.freeze({ status: 503 }), }); /** diff --git a/tests/integration/http-execution-v3-envelope.test.ts b/tests/integration/http-execution-v3-envelope.test.ts index a8d35785..e5037d0e 100644 --- a/tests/integration/http-execution-v3-envelope.test.ts +++ b/tests/integration/http-execution-v3-envelope.test.ts @@ -703,6 +703,27 @@ describe("V3 Envelope verdicts follow the backend's refusal table", () => { effect: "NOT_APPLIED", }); }); + + // 1105/03-02. The edge rate limiter answers in its interceptor's preHandle, + // before the controller (http-contract.md §4). The create's own classifier + // reads every problem as maybe applied, as create:feature writes it; the + // table still says the command did not run. + it.each([ + ["RATE_LIMIT_UNAVAILABLE", "TRANSIENT_DEPENDENCY"], + ["RATE_LIMIT_INCOMPATIBLE", "INTERNAL"], + ] as const)("reads the edge's 503 %s as not applied, whatever the package says", async (code, category) => { + answer("post", "/api/envelope-items", failure(code, category, false), { + status: 503, + headers: { "Retry-After": "1" }, + }); + + await expect(v3CreateFailure().then(verdict)).resolves.toMatchObject({ + kind: "SERVER_FAILURE", + code, + httpStatus: 503, + effect: "NOT_APPLIED", + }); + }); }); // 1103/03-01. The paired backend scaffold's create checks the name before @@ -932,6 +953,22 @@ describe("KEYED resend on the backend's pre-execution refusal", () => { expect(keys).toEqual([KEY]); }); + // 1105/03-02. Not applied, but not the one answer that asks for the same + // key again: a KEYED command is not resent on its own. + it("does not resend the edge's 503 RATE_LIMIT_UNAVAILABLE on its own", async () => { + const { outcome, keys } = await run([ + () => + HttpResponse.json(failure("RATE_LIMIT_UNAVAILABLE", "TRANSIENT_DEPENDENCY", true), { + status: 503, + headers: { "Retry-After": "1" }, + }), + created, + ]); + + expect(outcome).toMatchObject({ kind: "PROBLEM", effect: "NOT_APPLIED" }); + expect(keys).toEqual([KEY]); + }); + it("does not resend a 503 the backend did not mark as a pre-execution refusal", async () => { const { outcome, keys } = await run([ () => diff --git a/tests/unit/backend-envelope.test.ts b/tests/unit/backend-envelope.test.ts index 6e2f6344..742c24af 100644 --- a/tests/unit/backend-envelope.test.ts +++ b/tests/unit/backend-envelope.test.ts @@ -48,6 +48,19 @@ describe("backend Envelope failure table", () => { expect(envelopeFailureEffect(status, { code })).toBe("MAYBE_APPLIED"); }); + // 1105/03-02. http-contract.md §4: the edge rate limiter answers before the + // controller runs. Status and code together, like the other rows. + it.each(["RATE_LIMIT_UNAVAILABLE", "RATE_LIMIT_INCOMPATIBLE"])( + "reads the edge's 503 %s as refused before the write", + (code) => { + expect(envelopeFailureEffect(503, { code })).toBe("NOT_APPLIED"); + expect(invitesKeyedResend(503, { code })).toBe(false); + expect(idempotencyRefusalReason(code, 503)).toBeUndefined(); + expect(envelopeFailureReading(503, { code }).kind).toBe("SERVER_FAILURE"); + expect(envelopeFailureEffect(500, { code })).toBeUndefined(); + }, + ); + // 1103/03-04. http-contract.md §2 and §4: the command may have run. it.each([ [503, "IDEMPOTENCY_UNAVAILABLE", true], From 683ccfb56bf209ab2d37445d247cba27de7c4439 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 5 Nov 2026 22:19:53 +0900 Subject: [PATCH 3/8] =?UTF-8?q?fix(query):=20=ED=82=A4=20=EC=97=86?= =?UTF-8?q?=EB=8A=94=20=EA=B2=B0=EA=B3=BC=20=EB=B6=88=EB=AA=85=20=EC=9A=94?= =?UTF-8?q?=EC=B2=AD=EC=9D=98=20=EA=B0=99=EC=9D=80=20=EC=9E=85=EB=A0=A5=20?= =?UTF-8?q?=EC=9E=AC=EC=A0=9C=EC=B6=9C=EC=9D=84=20=ED=9B=85=EC=9D=B4=20?= =?UTF-8?q?=EB=A7=89=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 0929/03-03은 화면 버튼 쪽만 고쳐졌다. 남은 길이 둘이다. - useApplicationMutation의 submit은 같은 canonical input의 결과 불명 admission을 찾아 그 intent를 그대로 다시 보낸다. 키 없는 intent(NEVER)면 서버가 가려낼 수 없는 두 번째 요청이다. 막는 곳은 폼(unknownSubmissionRef)과 두 페이지의 버튼·onSubmit 검사뿐이라, 폼 밖에서 submit을 부르는 화면은 같은 항목을 둘 만들 수 있다(리뷰 실험 X1: 재전송은 null인데 같은 입력 submit이 두 번째 POST를 보냈고 keys=[null,null]). - AsyncSurface는 state.unknownEffectResendable !== false일 때 재전송 버튼을 그린다. 코디네이터 없이 손으로 만든 AsyncState(플래그 없음)는 지금도 버튼을 그린다(실험 X3). 고른 방법 - submit이 같은 입력의 결과 불명 admission을 찾았는데 그 intent에 키가 없으면 보내지 않고 NOT_STARTED DUPLICATE_IN_FLIGHT(code UNKNOWN_EFFECT_PENDING)를 돌려준다. admission을 만들기 전이라 결과 불명 상태와 identity lease는 그대로다. KEYED의 같은 키 재전송, 입력이 바뀐 새 요청은 바뀌지 않는다. LEGACY(테스트 하네스) 경로는 intent가 없어 replay 자체가 없으므로 영향이 없다. - AsyncSurface는 unknownEffectResendable === true일 때만 재전송 버튼을 그린다. 코디네이터의 state는 늘 이 값을 싣는다(canResendUnknownEffect). - 기존 async-surface 테스트 "renders unknown mutation effects with confirm-applied and resend only"는 플래그 없는 상태로 버튼을 기대했다. 이 수정의 의도대로 isUnknownEffectResendable: true를 입력에 적었다. 단언은 그대로다. - 런북 6.3-4와 매뉴얼 01에 키 없는 재제출과 손으로 만든 상태를 적었다. 버린 대안 FailureKind에 새 kind를 더한다: 닫힌 레지스트리를 넓히는 계약 변경이다. "같은 논리 요청이 아직 끝나지 않았다"는 DUPLICATE_IN_FLIGHT(action none)로 충분하다. 위험·한계 - 다운스트림이 AsyncSurface에 손으로 만든 결과 불명 상태와 onResendUnknownEffect를 넘기던 화면은 재전송 버튼이 사라진다. 코디네이터의 state를 넘기면 그대로다. - 결과 불명 admission은 메모리에만 있다. 새로고침 뒤 같은 입력은 막지 못한다 (런북 6.3-7의 한계 그대로). 검증 desktop batch에서 확인: node scripts/run-vitest.ts run tests/component/application-mutation-admission.test.tsx tests/component/async-surface.test.tsx tests/component/application-query.test.tsx Refs: 0929/03-03 --- docs/manual/01-add-a-feature.md | 2 +- .../api-contract-and-server-state-recovery.md | 6 ++- src/application/view-models/async-state.ts | 4 +- .../adapters/query/application-query.ts | 22 +++++++++++ src/presentation/components/async-surface.tsx | 8 ++-- .../application-mutation-admission.test.tsx | 37 +++++++++++++++++++ tests/component/async-surface.test.tsx | 19 ++++++++++ 7 files changed, 92 insertions(+), 6 deletions(-) diff --git a/docs/manual/01-add-a-feature.md b/docs/manual/01-add-a-feature.md index f9285207..2d258ddc 100644 --- a/docs/manual/01-add-a-feature.md +++ b/docs/manual/01-add-a-feature.md @@ -504,7 +504,7 @@ projectRequest: (input) => Object.freeze({ ① **정할 것** - 페이지 템플릿. [02 결정표 6절](02-decision-tables.md#6-페이지-템플릿) -- 쓰기가 있으면 결과 불명 화면. `AsyncSurface`의 `onReconcileUnknownEffect`(확인), `onResendUnknownEffect`(같은 키로 다시 보내기). 다시 보내기 버튼은 키가 있는 요청(`KEYED`)에만 그려진다. `NEVER` 쓰기는 확인만 남는다. +- 쓰기가 있으면 결과 불명 화면. `AsyncSurface`의 `onReconcileUnknownEffect`(확인), `onResendUnknownEffect`(같은 키로 다시 보내기). 다시 보내기 버튼은 키가 있는 요청(`KEYED`)에만 그려진다. `NEVER` 쓰기는 확인만 남는다. 폼 밖에서 `mutation.submit`을 부르는 화면도 `NEVER` 쓰기의 같은 입력을 다시 보낼 수 없다. 훅이 `DUPLICATE_IN_FLIGHT`(code `UNKNOWN_EFFECT_PENDING`)로 거절한다. `AsyncSurface`에 손으로 만든 상태를 넘기면 재전송 버튼은 그려지지 않는다(코디네이터의 `state`를 넘긴다). - 폼이면 서버 필드 오류를 받을 필드(`useAppForm`의 `allowedServerFields`). 짝 백엔드는 필드 검증 거절을 400 `VALIDATION_FAILED`와 `details[{field, code}]`로 보낸다(422가 아니다). 공유 MSW 시나리오에는 짝 백엔드가 보내지 않는 `validation-422`만 있고, Envelope operation에서 그 답은 결과 불명이다. 짝 백엔드 모양의 필드 오류 테스트는 생성된 작성 폼 테스트(`-create-page.test.tsx`)처럼 400 본문을 손으로 적는다. ② **기준** diff --git a/docs/operations/api-contract-and-server-state-recovery.md b/docs/operations/api-contract-and-server-state-recovery.md index c4576711..ba60984a 100644 --- a/docs/operations/api-contract-and-server-state-recovery.md +++ b/docs/operations/api-contract-and-server-state-recovery.md @@ -257,7 +257,11 @@ diagnostics에만 남고 `api.request.failed`에는 세지 않는다(03-07). 그 key다. 자동 재전송은 없다(`src/presentation/adapters/query/application-query.ts` `submit`·`resendUnknownEffect`, 화면 `src/presentation/components/async-surface.tsx`). 키가 없는 command(`NEVER`)는 서버가 두 번째 요청을 가려내지 못하므로 재전송 버튼을 - 그리지 않는다(`canResendUnknownEffect`, 0929/03-03). + 그리지 않는다(`canResendUnknownEffect`, 0929/03-03). 같은 canonical input의 재저장도 + 보내지 않는다. 훅의 `submit`이 `NOT_STARTED` `DUPLICATE_IN_FLIGHT`(code + `UNKNOWN_EFFECT_PENDING`)를 돌려주고, 결과 불명 요청이 확인될 때까지 그대로다. 폼 + 밖에서 `submit`을 부르는 화면도 같다. 화면은 상태에 `unknownEffectResendable: true`가 + 있을 때만 재전송 버튼을 그린다. 5. backend status/receipt로 `COMMITTED`면 cache reconcile/invalidate한다. 화면의 "변경됨으로 확인"이 이 경로다. 6. `NOT_APPLIED`가 증명된 경우만 정책에 따라 retry한다. 화면은 근거 없는 diff --git a/src/application/view-models/async-state.ts b/src/application/view-models/async-state.ts index ecf72aa8..02f2a4f5 100644 --- a/src/application/view-models/async-state.ts +++ b/src/application/view-models/async-state.ts @@ -86,7 +86,9 @@ export type AsyncState = Readonly<{ /** * 0929/03-03. Only with `indicator: "mutation-effect-unknown"`, when the * coordinator said: `false` means the request has no idempotency key, so - * sending it again is a second, unprotected request and no resend is drawn. + * sending it again is a second, unprotected request. A resend is drawn + * only for `true`; absent (a state built without the coordinator) draws + * none. */ unknownEffectResendable?: boolean; }>; diff --git a/src/presentation/adapters/query/application-query.ts b/src/presentation/adapters/query/application-query.ts index 2f6daace..49750c6c 100644 --- a/src/presentation/adapters/query/application-query.ts +++ b/src/presentation/adapters/query/application-query.ts @@ -243,6 +243,13 @@ export type LegacyMutationOptions = LegacyMutationBase = Readonly<{ state: AsyncState; + /** + * D-1. The same canonical input as an unknown-effect request is the same + * logical request: a keyed command sends it again with that request's + * key. 0929/03-03. Without a key it is not sent: the result is a + * `NOT_STARTED` `DUPLICATE_IN_FLIGHT` failure with code + * `UNKNOWN_EFFECT_PENDING` until the unknown request is reconciled. + */ submit(input: Input): Promise>; resolveConflict(): Promise; /** @@ -559,6 +566,21 @@ export function useApplicationMutation( candidate.state === "UNKNOWN" && candidate.intent?.canonicalInputIdentity === identity, ); + // 0929/03-03. Without an idempotency key the server cannot tell that + // request from this one, so saving the same input again could apply it + // twice. The unknown request is settled first (reconcileUnknownEffect), + // never repeated; a page that calls submit outside the form meets this + // too. + if (replayed && replayed.intent?.idempotencyKey === undefined) { + identityLease?.release(); + return Promise.resolve({ + ok: false, + error: createFailure("DUPLICATE_IN_FLIGHT", definitionId, 0, { + code: "UNKNOWN_EFFECT_PENDING", + effect: "NOT_STARTED", + }), + }); + } const admission: MutationAdmission = { sequence: unknownEffectChannel.nextSequence++, state: "ACTIVE", diff --git a/src/presentation/components/async-surface.tsx b/src/presentation/components/async-surface.tsx index b6028b5f..041d3072 100644 --- a/src/presentation/components/async-surface.tsx +++ b/src/presentation/components/async-surface.tsx @@ -128,8 +128,10 @@ export type AsyncSurfaceProps = Readonly<{ onReconcileUnknownEffect?: (resolution: "APPLIED") => void; /** * D-1. Resends the unknown request with its original intent and key. - * 0929/03-03. Not drawn when `state.unknownEffectResendable` is `false`: - * a request without a key would go out as a second, unprotected one. + * 0929/03-03. Drawn only when `state.unknownEffectResendable` is `true` + * (the coordinator's `canResendUnknownEffect`): a request without a key + * would go out as a second, unprotected one, and a state built by hand + * without that answer draws no resend either. */ onResendUnknownEffect?: () => void; /** 08-05. Title level of the empty and failure surfaces it renders. */ @@ -224,7 +226,7 @@ export function AsyncSurface({ ) : null} {state.indicator === "mutation-effect-unknown" && onResendUnknownEffect && - state.unknownEffectResendable !== false ? ( + state.unknownEffectResendable === true ? ( diff --git a/tests/component/application-mutation-admission.test.tsx b/tests/component/application-mutation-admission.test.tsx index f52334af..b62cff0c 100644 --- a/tests/component/application-mutation-admission.test.tsx +++ b/tests/component/application-mutation-admission.test.tsx @@ -555,6 +555,43 @@ describe("application mutation intent admission", () => { expect(hook.result.current.state.indicator).toBe("mutation-effect-unknown"); }); + // 0929/03-03. Saving the same input again reuses the unknown request's + // intent. Without a key that is a second request the server cannot tell + // from the first, so the hook refuses it before sending, whatever page + // calls it (review experiment X1: keys [null, null]). + it("refuses to send a keyless unknown request again for the same input", async () => { + const { hook, execute } = renderKeyedCreate([unknown], { keyed: false }); + await act(() => hook.result.current.submit("keyless-input")); + expect(hook.result.current.state.indicator).toBe("mutation-effect-unknown"); + + let again: ApplicationResult | undefined; + await act(async () => { + again = await hook.result.current.submit("keyless-input"); + }); + + expect(again).toMatchObject({ + ok: false, + error: { + kind: "DUPLICATE_IN_FLIGHT", + code: "UNKNOWN_EFFECT_PENDING", + effect: "NOT_STARTED", + }, + }); + expect(execute).toHaveBeenCalledOnce(); + expect(hook.result.current.state.indicator).toBe("mutation-effect-unknown"); + }); + + it("still sends another input while a keyless request is unknown", async () => { + const { hook, execute } = renderKeyedCreate([unknown], { keyed: false }); + await act(() => hook.result.current.submit("first-input")); + await act(() => hook.result.current.submit("changed-input")); + + expect(execute.mock.calls.map(([input]) => input)).toEqual([ + "first-input", + "changed-input", + ]); + }); + it("offers the same-key resend for an unknown keyed request", async () => { const { hook } = renderKeyedCreate([unknown]); expect(hook.result.current.canResendUnknownEffect).toBe(false); diff --git a/tests/component/async-surface.test.tsx b/tests/component/async-surface.test.tsx index 6b3ab630..3eceb061 100644 --- a/tests/component/async-surface.test.tsx +++ b/tests/component/async-surface.test.tsx @@ -65,9 +65,11 @@ describe("async UI state matrix", () => { const retry = vi.fn(); const reconcile = vi.fn(); const resend = vi.fn(); + // 0929/03-03. The coordinator says the request carries a key. const state = deriveAsyncState({ data: ["value"], hasMutationEffectUnknown: true, + isUnknownEffectResendable: true, }); render( @@ -123,6 +125,23 @@ describe("async UI state matrix", () => { expect(screen.getByRole("button", { name: "변경됨으로 확인" })).toBeInTheDocument(); }); + // 0929/03-03. A state built by hand without the coordinator's answer does + // not know the request has a key, so it draws no resend (review X3). + it("draws no resend for an unknown state that does not say it can be resent", () => { + render( + , + ); + + expect( + screen.queryByRole("button", { name: "같은 요청으로 다시 보내기" }), + ).not.toBeInTheDocument(); + expect(screen.getByRole("button", { name: "변경됨으로 확인" })).toBeInTheDocument(); + }); + it("keeps the resend state to an unknown mutation only", () => { expect( deriveAsyncState({ data: ["value"], isUnknownEffectResendable: false }), From 12d97d746948bed733e3b1f666b125e99fe4bcb8 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 5 Nov 2026 22:22:50 +0900 Subject: [PATCH 4/8] =?UTF-8?q?feat(forms):=20=EA=B8=B0=EB=8A=A5=EC=9D=B4?= =?UTF-8?q?=20=EB=B0=B1=EC=97=94=EB=93=9C=20=EA=B1=B0=EC=A0=88=20code?= =?UTF-8?q?=EC=97=90=20=EC=9E=90=EA=B8=B0=20=EB=AC=B8=EA=B5=AC=EB=A5=BC=20?= =?UTF-8?q?=EB=B6=99=EC=9D=B8=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 refusedBeforeWrite로 선언한 업무 거절은 이제 결과 불명이 아니고 다시 저장된다. 그런데 거절 이유가 사용자 말로 보이지 않는다. 선언한 400은 kind UNKNOWN_CLIENT_FAILURE라 "요청을 처리할 수 없습니다." + "지원 정보 확인"이고, 409는 kind CONFLICT라 "다른 변경과 충돌했습니다."다. 고칠 수 있는 입력인데 지원 문의로 보낸다. mapProblem으로 필드 오류를 만들어도 문구는 플랫폼 표에서 issue code로만 고르므로(표에 없는 DUPLICATE는 "입력값을 확인해 주세요.") 기능이 *_ALREADY_EXISTS 같은 거절에 자기 문구를 붙일 자리가 없다(리뷰 08-R1 A1~A3). conflict 결과에서는 form.failure가 null이라 페이지가 code를 읽어 따로 그릴 수도 없다. 고른 방법 useAppForm에 refusalMessages 옵션을 더한다. 실패 code별로 기능 catalog의 메시지 키와(선택) 필드를 적는다. 적용 안 됨(effect NOT_APPLIED)으로 끝난 실패의 code가 있으면 그 문구를 필드 오류로(필드가 없거나 allowedServerFields 밖이면 오류 요약으로) 보이고 결과를 validation-error로 둔다. 필드면 그 필드로 포커스를 옮긴다. 키는 렌더 때 번역한다(다른 폼 오류와 같다). Object.hasOwn으로 자기 키만 읽는다(1103/08-03). 재로그인(action reauth)이 먼저다. 결과 불명은 code와 상관없이 결과 불명이다. 매뉴얼 02 4절에 적었다. 버린 대안 - 플랫폼 문구 표(form-contracts.ts)에 code를 더한다: 기능 code를 템플릿 파일에 적게 된다. - mapProblem이 문구까지 돌려주게 한다: 어댑터가 presentation 메시지 키를 알게 된다. - 지난 리뷰 5.3절 (B)(useAppForm이 코디네이터 상태를 받아 결과를 하나로 낸다): 더 넓은 구조 변경이라 이 커밋에서 하지 않았다. 위험·한계 - 1103/03-01 남은 부분 중 이 커밋은 "이유 문구와 기능 문구 자리"만 고친다. KEYED 결과 불명의 같은 키 재전송이 500 IDEMPOTENCY_RECOVERY_REQUIRED를 받아도 재전송 버튼이 남는 것(08-R1 A5)은 결정 대기로 남긴다. 백엔드 §2는 이 답에 "같은 키 재전송은 안전하다, 첫 시도가 늦게 끝났으면 그 결과를 재생한다"고 적고 답 표 사본도 sameKeyResend: true다. 버튼을 거두면 그 회복 길도 닫힌다. 고르는 사람: 프론트 템플릿 담당(frontend-platform). 선택지: (a) RECOVERY_REQUIRED 뒤 재전송을 거두고 "목록에서 확인" 안내를 둔다(AppFailure에 답의 원인을 싣는 계약 추가 필요), (b) 백엔드가 KEYED 작업 안의 업무 예외(트랜잭션 롤백)를 "효과 없음" 으로 기록해 같은 키 재전송이 다시 실행되게 한다(백엔드 변경), (c) 지금대로 둔다 (재전송은 안전하고, 참조 폼은 목록 새로 보기 링크가 있다). - 선언하지 않은 code는 지금처럼 결과 불명이고 "변경됨으로 확인"이 남는다(완료 기준의 설계). 참조 기능과 생성기는 이 옵션을 쓰지 않는다. 생성기는 이미 _INVALID를 필드 오류로 보인다. 검증 desktop batch에서 확인: node scripts/run-vitest.ts run tests/component/form-foundation.test.tsx Refs: 1103/03-01 --- docs/manual/02-decision-tables.md | 1 + src/presentation/forms/use-app-form.ts | 67 ++++++++++++- tests/component/form-foundation.test.tsx | 117 ++++++++++++++++++++++- 3 files changed, 182 insertions(+), 3 deletions(-) diff --git a/docs/manual/02-decision-tables.md b/docs/manual/02-decision-tables.md index 058309cc..7a8ae6b3 100644 --- a/docs/manual/02-decision-tables.md +++ b/docs/manual/02-decision-tables.md @@ -184,6 +184,7 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기 - 적을 수 없는 code: `IDEMPOTENT_*`, `IDEMPOTENCY_*`. 멱등성 응답은 백엔드 표가 정한다. 적으면 계약 조립이 `refusedBeforeWrite cannot declare ...`로 거부한다. `responseEnvelope: "ENVELOPE_V1"`가 아닌 operation에 적어도 거부한다(`refusedBeforeWrite needs responseEnvelope ENVELOPE_V1 ...`). - 계약 문서 6.1절이 "쓰기 뒤 가능"으로 둔 플랫폼 code(`BAD_PARAMETER`, `MAPPING_FAILED`, `DB_UNIQUE_VIOLATION` 등 `DB_*`, `LOCK_ACQUISITION_TIMEOUT`, fileserver code)도 적을 수 없다. 폼을 막는 400 `BAD_PARAMETER`나 409 `DB_UNIQUE_VIOLATION`은 어느 층에서든, 트랜잭션 안에서도 나온다. 적으면 계약 조립이 `refusedBeforeWrite cannot declare ...; contract 6.1 reads this platform code as possibly raised after the write`로 거부한다. - 거절 이유를 필드 옆에 보이려면 `mapProblem`이 그 code를 `VALIDATION_REJECTED`와 필드 목록으로 돌려준다. 선언 없이 `mapProblem`만 두면 필드 오류는 보이지만 저장 버튼은 꺼진 채다. + - 거절 이유를 기능의 말로 보이려면 `useAppForm`의 `refusalMessages`에 code별로 기능 catalog의 메시지 키와 필드를 적는다(예: `{ POSTER_ALREADY_EXISTS: { field: "name", message: "poster.form.nameTaken" } }`). 적용 안 됨(`NOT_APPLIED`)으로 끝난 실패만 읽는다. 그 code는 필드 오류(필드가 없으면 오류 요약)가 되고, 결과는 `validation-error`다. 적지 않으면 선언한 400은 "요청을 처리할 수 없습니다" + 지원 안내, 409는 충돌 문구가 보인다. 결과 불명은 code와 상관없이 결과 불명으로 남는다. **503 `IDEMPOTENCY_UNAVAILABLE`는 `NOT_APPLIED`로 분류하지 않는다.** diff --git a/src/presentation/forms/use-app-form.ts b/src/presentation/forms/use-app-form.ts index 652d08b5..8a1c0188 100644 --- a/src/presentation/forms/use-app-form.ts +++ b/src/presentation/forms/use-app-form.ts @@ -26,6 +26,16 @@ import { type FormValues, } from "./form-contracts.ts"; +/** + * 1103/03-01. A feature's own words for one backend refusal: a message key + * from its catalog, shown on `field` when that is one of + * `allowedServerFields`, otherwise in the error summary. + */ +export type FormRefusalMessage = Readonly<{ + message: ParameterlessMessageKey; + field?: FieldName; +}>; + type AppFormOptions< Values extends FormValues, Command, @@ -37,6 +47,16 @@ type AppFormOptions< mapToCommand(values: Values): Command; submit(command: Command): Promise>; resetOnSuccess?: boolean; + /** + * 1103/03-01. By failure `code`: what the form says for a backend refusal + * that did not apply (`effect: "NOT_APPLIED"`), such as a code the + * operation lists in `commandEffect.refusedBeforeWrite`. It replaces the + * copy the failure kind would get (a 400 reads as unavailable with a + * support action, a 409 as a conflict) with an input error the user can + * correct, and the form takes the next save. An unknown result stays + * unknown whatever its code. + */ + refusalMessages?: Readonly>>; }>; export function useAppForm< @@ -52,6 +72,7 @@ export function useAppForm< mapToCommand, submit, resetOnSuccess = true, + refusalMessages, } = options; const generatedId = useId().replaceAll(":", ""); const formId = `app-form-${generatedId}`; @@ -214,6 +235,27 @@ export function useAppForm< settleSuccessfulValues(submittedValues); return; } + const refusal = refusalFor(refusalMessages, outcome.error); + if (refusal) { + // 1103/03-01. The feature's words for its own refusal, as an input + // error: the save is not held and the corrected value goes out as a + // new request. + unknownSubmissionRef.current = null; + const onField = + refusal.field !== undefined && + allowedServerFields.includes(refusal.field) + ? refusal.field + : undefined; + setFieldErrors( + (onField === undefined + ? {} + : { [onField]: refusal.message }) as FieldErrors, + ); + setFormErrors(onField === undefined ? [refusal.message] : []); + setResult("validation-error"); + if (onField !== undefined) focusField(onField); + return; + } if (outcome.error.kind === "VALIDATION_REJECTED") { unknownSubmissionRef.current = null; const mapped = mapValidationFailureToFields( @@ -266,7 +308,13 @@ export function useAppForm< setResult("unavailable"); } }, - [allowedServerFields, focusFirstError, settleSuccessfulValues], + [ + allowedServerFields, + focusField, + focusFirstError, + refusalMessages, + settleSuccessfulValues, + ], ); const validateAndSubmit = useCallback( @@ -408,6 +456,23 @@ export function useAppForm< /** Keeps the key: the form translates at render time. */ const messageKey = (key: ParameterlessMessageKey): string => key; +/** + * 1103/03-01. The feature's message for a refusal that did not apply. Own + * keys only (1103/08-03): a backend code such as `constructor` must not + * reach a name the record inherits. Signing in again still comes first. + */ +function refusalFor( + messages: Readonly>> | undefined, + failure: AppFailure, +): FormRefusalMessage | undefined { + return messages !== undefined && + failure.effect === "NOT_APPLIED" && + failure.action !== "reauth" && + Object.hasOwn(messages, failure.code) + ? messages[failure.code] + : undefined; +} + const STATUS_RESULTS: ReadonlySet = new Set([ "reauth-required", "forbidden", diff --git a/tests/component/form-foundation.test.tsx b/tests/component/form-foundation.test.tsx index e99d1fff..5b342189 100644 --- a/tests/component/form-foundation.test.tsx +++ b/tests/component/form-foundation.test.tsx @@ -102,7 +102,8 @@ const FORM_OPERATIONS = Object.freeze({ /** * 1103/03-01. The same create, declaring the paired backend scaffold's - * `_INVALID` as refused before the write. + * `_INVALID` (and a 409 business code checked before the write) as + * refused before the write. */ const FORM_DECLARING_OPERATIONS = Object.freeze({ FORM_CREATE_ENTITY: defineFeatureHttpOperation({ @@ -112,7 +113,7 @@ const FORM_DECLARING_OPERATIONS = Object.freeze({ ...FORM_CREATE_CONTRACT.contract, commandEffect: Object.freeze({ ...FORM_CREATE_CONTRACT.contract.commandEffect, - refusedBeforeWrite: Object.freeze(["WORKLOG_INVALID"]), + refusedBeforeWrite: Object.freeze(["WORKLOG_INVALID", "POSTER_ALREADY_EXISTS"]), }), }), }), @@ -837,6 +838,12 @@ describe("correcting a field after a server validation refusal", () => { props: Readonly<{ fetcher: typeof fetch; operations?: typeof FORM_DECLARING_OPERATIONS; + refusalMessages?: Readonly< + Record< + string, + Readonly<{ message: ParameterlessMessageKey; field?: "name" | "note" }> + > + >; }>, ) { const [http] = useState(() => formBinding(props.fetcher, props.operations)); @@ -861,12 +868,22 @@ describe("correcting a field after a server validation refusal", () => { allowedServerFields: ["name", "note"], mapToCommand: (values) => ({ name: values.name }), submit: mutation.submit, + refusalMessages: props.refusalMessages, }); const blocked = mutation.state.indicator === "mutation-effect-unknown" || mutation.state.indicator === "mutation-pending"; return (
void form.submitForm(event)}> + {props.refusalMessages ? ( + + ) : null} @@ -718,6 +722,8 @@ export default function ${pascal}CreatePage() { void form.resendUnknown(async () => openSaved(await mutation.resendUnknownEffect())); }} /> + ) : otherSaveRunning && form.result !== "effect-unknown" ? ( + ) : null } guard={} diff --git a/src/features/reference-feature/presentation/reference-resource-form-page.tsx b/src/features/reference-feature/presentation/reference-resource-form-page.tsx index 3a5e4760..f6047e45 100644 --- a/src/features/reference-feature/presentation/reference-resource-form-page.tsx +++ b/src/features/reference-feature/presentation/reference-resource-form-page.tsx @@ -53,6 +53,12 @@ export default function ReferenceResourceFormPage() { mutation.state.indicator === "mutation-effect-unknown"; const mutationBlocked = mutationEffectUnknown || mutation.state.indicator === "mutation-pending"; + // 1105/08-04. A save this form did not start holds the coordinator: one + // left running when the user came back to the form, or the check behind + // "confirm applied". The save button is off and, for the first, the + // feedback says a save is running, instead of a click that does nothing. + const otherSaveRunning = + mutation.state.indicator === "mutation-pending" && !form.pending; const guard = useDirtyNavigationGuard(form.dirty && !form.pending); return ( @@ -125,7 +131,7 @@ export default function ReferenceResourceFormPage() { type="submit" pending={form.pending} pendingLabel={message("reference.form.saving")} - disabled={mutationEffectUnknown} + disabled={mutationEffectUnknown || otherSaveRunning} > {message("reference.form.save")} @@ -179,6 +185,10 @@ export default function ReferenceResourceFormPage() {

{message("reference.form.saved")}

) : form.result === "conflict" ? (

{message("reference.form.conflict")}

+ ) : otherSaveRunning && form.result !== "effect-unknown" ? ( + // 1105/08-04. While this form's own unknown result is being + // checked, the result that follows is shown instead. + ) : null } aside={ diff --git a/tests/features/reference-feature/reference-page.test.tsx b/tests/features/reference-feature/reference-page.test.tsx index a5017ce7..744e5ce6 100644 --- a/tests/features/reference-feature/reference-page.test.tsx +++ b/tests/features/reference-feature/reference-page.test.tsx @@ -586,6 +586,64 @@ describe("reference feature page states", () => { ); }); + // 1105/08-04. A save left running when the user leaves and comes back + // still holds the coordinator. The remounted form says a save is running + // and keeps its save off, instead of a save button that does nothing. + it("says a save is running and keeps the save off after coming back during a save", async () => { + const user = userEvent.setup(); + let release: + | ((result: ReferenceResult) => void) + | undefined; + const createResource = vi + .fn() + .mockImplementationOnce( + () => + new Promise>((resolve) => { + release = resolve; + }), + ) + .mockResolvedValue({ + ok: true, + value: { resourceId: "created-2", title: "Second item", createdAt: null }, + }); + renderReference( + inputWith({ createResource }), + "/examples/reference-resources/new", + ); + await user.type( + await screen.findByRole("textbox", { name: /새 항목 이름/ }), + "First item", + ); + await user.click(screen.getByRole("button", { name: "저장" })); + await waitFor(() => expect(createResource).toHaveBeenCalledOnce()); + await user.click(screen.getByRole("button", { name: "목록으로 돌아가기" })); + await waitFor(() => + expect(window.location.pathname).toBe("/examples/reference-resources"), + ); + window.history.pushState({}, "", "/examples/reference-resources/new"); + window.dispatchEvent(new PopStateEvent("popstate")); + await user.type( + await screen.findByRole("textbox", { name: /새 항목 이름/ }), + "Second item", + ); + + expect(await screen.findByText("변경 사항을 저장하고 있습니다.")).toBeVisible(); + expect(screen.getByRole("button", { name: "저장" })).toBeDisabled(); + + release?.({ + ok: true, + value: { resourceId: "created-1", title: "First item", createdAt: null }, + }); + await waitFor(() => + expect(screen.getByRole("button", { name: "저장" })).toBeEnabled(), + ); + expect(screen.queryByText("변경 사항을 저장하고 있습니다.")).not.toBeInTheDocument(); + await user.click(screen.getByRole("button", { name: "저장" })); + + expect(await screen.findByText("저장했습니다.")).toBeVisible(); + expect(createResource).toHaveBeenCalledTimes(2); + }); + // 0929/08-04. The ids a user quotes to support reach the screens that // need them, and the sample status page shows no made-up reference. it("shows the request id of an unknown create next to its result", async () => { diff --git a/tests/unit/create-feature.test.ts b/tests/unit/create-feature.test.ts index d28042fe..51e50a56 100644 --- a/tests/unit/create-feature.test.ts +++ b/tests/unit/create-feature.test.ts @@ -265,6 +265,23 @@ describe("create:feature --with-create", () => { expect(contribution).toContain('refusedBeforeWrite: Object.freeze(["INVOICE_INVALID"]),'); }); + // 1105/08-04. Like the reference form: while a save this page did not + // start holds the coordinator, the save is off and the feedback says a + // save is running, instead of a save button that does nothing. + it("keeps the create's save off and says so while another save of it runs", () => { + const page = + plan({ id: "invoice-feature", write: "NEVER" }).files.get( + "src/features/invoice-feature/presentation/invoice-create-page.tsx", + ) ?? ""; + + expect(page).toContain( + 'const otherSaveRunning = mutation.state.indicator === "mutation-pending" && !form.pending;', + ); + expect(page).toContain("disabled={effectUnknown || otherSaveRunning}"); + expect(page).toContain('otherSaveRunning && form.result !== "effect-unknown" ? ('); + expect(page).toContain(""); + }); + // 1103/16-07. A backend create made KEYED (IdempotencyExecutor) takes these. it("writes the KEYED values for a backend create made KEYED", () => { const { files } = plan({ id: "invoice-feature", write: "KEYED" }); From 90c489c31a80ad207c233aa44b71d3285b1acbc7 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 5 Nov 2026 22:29:11 +0900 Subject: [PATCH 7/8] =?UTF-8?q?fix(scaffold):=20=EC=83=9D=EC=84=B1=20?= =?UTF-8?q?=ED=8F=BC=EC=9D=B4=20"=EB=B3=80=EA=B2=BD=EB=90=A8=EC=9C=BC?= =?UTF-8?q?=EB=A1=9C=20=ED=99=95=EC=9D=B8"=20=EB=92=A4=20=EB=AA=A9?= =?UTF-8?q?=EB=A1=9D=EC=9D=84=20=EC=97=B0=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 create:feature --with-create가 만드는 작성 폼의 feedback은 form.failure와 결과 불명 두 가지뿐이다. 저장 성공은 상세로 이동해서 알리는데, "변경됨으로 확인"은 reconcileUnknownEffect(...).then(form.settleApplied)이고 이동하지 않는다. settleApplied가 결과를 success로 바꾸고 기본값 resetOnSuccess로 입력을 비우므로, 결과 불명 화면이 사라진 뒤 빈 폼만 남는다. 짝 백엔드 기본(NEVER)에서는 이것이 화면 안의 유일한 행동이다. 사용자는 확인이 받아들여졌는지 모르고, 다시 입력해 저장하면 키 없는 생성이 한 번 더 나간다(실제로 저장됐던 경우 중복). 참조 폼은 같은 경우 "저장했습니다."를 보인다. 고른 방법 확인 뒤 폼을 정리하고(settleApplied, flushSync라 이동 전에 dirty 가드가 풀린다) 목록으로 이동한다. 목록은 항목이 실제로 저장됐는지를 보여 주는 화면이고, reconcileUnknownEffect가 이미 목록 topic을 무효화한다. 라우터가 목록 제목으로 포커스를 옮기므로 08-01의 포커스 문제도 이 폼에서는 생기지 않는다. 생성 기능 테스트에 "응답을 잃은 생성 → 변경됨으로 확인 → 목록 제목과 항목"을 한 행 더했다 (NEVER·KEYED 공통). 매뉴얼 02의 생성 테스트 행에 적었다. 버린 대안 참조 폼처럼 success 가지에 확인 문구를 둔다: 생성 catalog에 키가 하나 늘고, 항목이 실제로 있는지는 여전히 보이지 않는다. 위험·한계 - 짝 백엔드 생성기에는 목록 GET이 아직 없다(1103/03-07 결정 대기). 실제 짝 백엔드에서는 이동한 목록이 405를 받는다(생성 목록 페이지가 지금 그렇다). 생성 테스트는 MSW로 목록을 답한다. - 생성 결과 파일은 단위 테스트가 문자열로만 보고, 동작은 test:feature-scaffold (KEYED, FE-GATE-020)와 test:sample-removal(NEVER)에서 생성한 테스트가 본다. 검증 desktop batch에서 확인: node scripts/run-vitest.ts run tests/unit/create-feature.test.ts corepack pnpm test:feature-scaffold corepack pnpm test:sample-removal Refs: 1105/08-02 --- docs/manual/02-decision-tables.md | 2 +- scripts/create-feature-write-slice.ts | 39 +++++++++++++++++++++++++-- tests/unit/create-feature.test.ts | 17 ++++++++++++ 3 files changed, 55 insertions(+), 3 deletions(-) diff --git a/docs/manual/02-decision-tables.md b/docs/manual/02-decision-tables.md index 7a8ae6b3..6f764c45 100644 --- a/docs/manual/02-decision-tables.md +++ b/docs/manual/02-decision-tables.md @@ -122,7 +122,7 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기 | `commandEffect.refusedBeforeWrite` | `["_INVALID"]` | 같다 | 이름 규칙을 트랜잭션 전에 검사한다(4절) | | `acceptedStatuses` | `[201]` | `[201]` | `ResponseEntity.created`. 같은 키 재생도 첫 요청과 같은 201이다 | | 결과 불명 화면 | 확인만. 다시 보내기 버튼 없음 | "같은 요청으로 다시 보내기"가 같은 키로 보낸다 | 키 없는 재전송은 서버가 새 요청으로 본다 | -| 생성 테스트 | 응답 유실 → 결과 불명, 다시 보내기 없음, 키 헤더 없음 | 응답 유실 → 같은 키로 다시 보내기. 503 `IDEMPOTENCY_UNAVAILABLE` → 같은 키로 1회 자동 재전송 | `tests/features//-create-page.test.tsx`, `-http-gateway.test.ts` | +| 생성 테스트 | 응답 유실 → 결과 불명, 다시 보내기 없음, 키 헤더 없음. "변경됨으로 확인" → 목록 화면 | 응답 유실 → 같은 키로 다시 보내기. 503 `IDEMPOTENCY_UNAVAILABLE` → 같은 키로 1회 자동 재전송. "변경됨으로 확인" → 목록 화면 | `tests/features//-create-page.test.tsx`, `-http-gateway.test.ts` | - 테스트 하네스의 재시도 상한: 생성된 gateway 테스트는 앱 기본값(`maxRetryAttempts: 2`)으로 돈다. 그래야 `retryBudget: 1`의 재전송이 보인다. 페이지 테스트(`-test-app.tsx`)는 실패를 바로 보이려고 `MAX_RETRY_ATTEMPTS: 0`이다. diff --git a/scripts/create-feature-write-slice.ts b/scripts/create-feature-write-slice.ts index 83e147eb..45f20b1d 100644 --- a/scripts/create-feature-write-slice.ts +++ b/scripts/create-feature-write-slice.ts @@ -617,7 +617,8 @@ import { use${pascal}Create } from "./use-${base}-create.ts"; * of the name (400 ${write.invalidCode}, refused before the write) shows on * the field and the form saves again. A save whose result is unknown (the * response was lost) keeps the form: the user checks, or, for a KEYED - * command, resends the same request with the same key. + * command, resends the same request with the same key. Confirming it was + * applied opens the list, which shows whether the item is there. */ export default function ${pascal}CreatePage() { const navigate = useNavigate(); @@ -714,8 +715,13 @@ export default function ${pascal}CreatePage() { { - void mutation.reconcileUnknownEffect(resolution).then(form.settleApplied); + void mutation.reconcileUnknownEffect(resolution).then(() => { + form.settleApplied(); + void navigate(${camel}RouteUrl("${routeId}")); + }); }} // Drawn only for a request with a key (a KEYED command). onResendUnknownEffect={() => { @@ -842,6 +848,14 @@ function answerItem(body: JsonBodyType = { id: ITEM_ID, name: "First item" }) { ); } +function answerList() { + api.use( + http.get(\`\${API}${apiPath}\`, () => + HttpResponse.json({ success: true, data: [{ id: ITEM_ID, name: "First item" }], meta: META }), + ), + ); +} + async function openForm() { const user = await openSignedIn(${camel}RouteUrl("${write.create.routeId}")); expect( @@ -890,6 +904,27 @@ describe("${names.id} create form on the paired backend", () => { }); ${unknownTest} + + // 1105/08-02. Confirming an unknown create opens the list, which shows + // whether the item was saved; the form alone showed nothing. + it("opens the list after the user confirms a create whose response was lost", async () => { + const posts = answerCreate(() => HttpResponse.error()); + answerList(); + const user = await openForm(); + await user.type(await nameField(), "First item"); + await user.click(saveButton()); + expect(await screen.findByText(KO_MESSAGES["async.mutationEffectUnknown"])).toBeVisible(); + + await user.click( + screen.getByRole("button", { name: KO_MESSAGES["action.confirmMutationApplied"] }), + ); + + expect( + await screen.findByRole("heading", { level: 1, name: MESSAGES["${camel}.list.title"] }), + ).toBeVisible(); + expect(await screen.findByText("First item")).toBeVisible(); + expect(posts).toHaveLength(1); + }); }); `; } diff --git a/tests/unit/create-feature.test.ts b/tests/unit/create-feature.test.ts index 51e50a56..2e291100 100644 --- a/tests/unit/create-feature.test.ts +++ b/tests/unit/create-feature.test.ts @@ -282,6 +282,23 @@ describe("create:feature --with-create", () => { expect(page).toContain(""); }); + // 1105/08-02. Confirming an unknown create used to leave an emptied form + // that said nothing. It opens the list, which shows whether the item is + // there, and the generated page test walks that path. + it.each(["NEVER", "KEYED"] as const)( + "opens the list after the user confirms an unknown %s create", + (write) => { + const { files } = plan({ id: "invoice-feature", write }); + + expect( + files.get("src/features/invoice-feature/presentation/invoice-create-page.tsx"), + ).toContain('void navigate(invoiceRouteUrl("INVOICE_LIST"));'); + expect( + files.get("tests/features/invoice-feature/invoice-create-page.test.tsx"), + ).toContain('it("opens the list after the user confirms a create whose response was lost"'); + }, + ); + // 1103/16-07. A backend create made KEYED (IdempotencyExecutor) takes these. it("writes the KEYED values for a backend create made KEYED", () => { const { files } = plan({ id: "invoice-feature", write: "KEYED" }); From f849d781d141859d9187842be2aeb8f3397491f5 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 5 Nov 2026 22:31:39 +0900 Subject: [PATCH 8/8] =?UTF-8?q?fix(home):=20=ED=99=88=20=EC=8B=9C=EC=9E=91?= =?UTF-8?q?=20=EB=A7=81=ED=81=AC=EA=B0=80=20=EB=9F=B0=ED=83=80=EC=9E=84?= =?UTF-8?q?=EC=97=90=20=EA=BA=BC=EC=A7=84=20=EA=B8=B0=EB=8A=A5=EC=9D=84=20?= =?UTF-8?q?=EA=B3=A0=EB=A5=B4=EC=A7=80=20=EC=95=8A=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 home-page.tsx의 STARTER_ROUTES는 모듈을 불러올 때 NAVIGATION_ROUTES에서 APP_HOME을 빼고 앞 3개를 고른다. 기능이 켜져 있는지는 보지 않는다. 셸 탐색은 같은 목록을 runtime.isFeatureActive(owner)로 거르고, 라우터는 꺼진 기능의 라우트에 사용 중지 화면을 그린다. 그래서 운영자가 런타임 설정으로 platform-examples-feature를 끄면 홈의 주요 버튼 셋 중 둘(/examples/ui, /examples/states)이 사용 중지 화면으로 간다(리뷰 08-R1 C, 1103/09-04 수정 b96d61d8이 만듦). 고른 방법 셸과 홈이 같은 함수를 쓴다. navigation-policy.ts에 activeNavigationRoutes (isFeatureActive)를 두고(설치된 레지스트리를 읽어도 되는 기존 예외 파일이다), 셸 탐색과 홈 시작 링크가 렌더 때 그 목록을 읽는다. 홈은 그 뒤에 APP_HOME을 빼고 앞 3개를 고른다. 홈은 여전히 기능 라우트를 이름으로 부르지 않는다(1103/09-04의 보존 조건). 테스트는 platform-examples-feature 테스트 폴더에 두어 기능을 지울 때 함께 지워진다. 버린 대안 홈에서만 같은 filter를 한 번 더 쓴다: 셸과 홈의 조건이 다시 갈라질 수 있다. 위험·한계 빌드에서 뺀 기능은 처음부터 목록에 없으므로 해당 없다. 시작 링크가 셋보다 적을 수 있다(템플릿에서 예제를 끄면 둘). 검증 desktop batch에서 확인: node scripts/run-vitest.ts run tests/features/platform-examples-feature/example-pages.test.tsx tests/component/product-feature-switch.test.tsx tests/component/starter-pages.test.tsx tests/unit/navigation-policy.test.ts Refs: 1105/08-03 --- src/presentation/layouts/app-shell.tsx | 14 +++---- src/presentation/pages/home-page.tsx | 28 ++++++------- src/presentation/routes/navigation-policy.ts | 21 +++++++++- .../example-pages.test.tsx | 39 ++++++++++++++++++- 4 files changed, 78 insertions(+), 24 deletions(-) diff --git a/src/presentation/layouts/app-shell.tsx b/src/presentation/layouts/app-shell.tsx index 1c698e2e..bf59bebe 100644 --- a/src/presentation/layouts/app-shell.tsx +++ b/src/presentation/layouts/app-shell.tsx @@ -3,11 +3,7 @@ import { NavLink, Outlet, useLocation } from "react-router-dom"; import type { SessionState } from "../../application/ports/in/application-api.ts"; import { normalizeColorSchemePreference } from "../../application/policies/color-scheme.ts"; -import { - NAVIGATION_ROUTES, - ROUTE_FEATURE_OWNER, - routePath, -} from "../../features/installed-feature-contracts.ts"; +import { routePath } from "../../features/installed-feature-contracts.ts"; import { Button, Drawer, @@ -26,6 +22,7 @@ import { useSessionAction, } from "../providers/session-provider.tsx"; import { useTheme } from "../providers/theme-provider.tsx"; +import { activeNavigationRoutes } from "../routes/navigation-policy.ts"; const SESSION_MESSAGE_KEYS = Object.freeze({ authenticated: "shell.session.authenticated", @@ -196,10 +193,9 @@ function PrimaryNavigation({ const runtime = useApplicationRuntime(); // §3.5. A feature the runtime document disabled does not advertise itself. // The router refuses its routes too, so this is presentation, not the switch. - const routes = NAVIGATION_ROUTES.filter((definition) => { - const owner = ROUTE_FEATURE_OWNER[definition.routeId]; - return owner === undefined || runtime.isFeatureActive(owner); - }); + const routes = activeNavigationRoutes((featureId) => + runtime.isFeatureActive(featureId), + ); return (