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 e3a317fc..4bb4d32d 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/` @@ -359,6 +370,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/01-add-a-feature.md b/docs/manual/01-add-a-feature.md index 6128b020..2d258ddc 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 전체에 걸린다. @@ -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/manual/02-decision-tables.md b/docs/manual/02-decision-tables.md index 3571f427..df5efb6c 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`이다. @@ -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`다 @@ -182,7 +182,9 @@ 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`만 두면 필드 오류는 보이지만 저장 버튼은 꺼진 채다. + - 거절 이유를 기능의 말로 보이려면 `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/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/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/scripts/create-feature-write-slice.ts b/scripts/create-feature-write-slice.ts index 558967c5..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(); @@ -656,6 +657,10 @@ export default function ${pascal}CreatePage() { }); const effectUnknown = mutation.state.indicator === "mutation-effect-unknown"; const blocked = effectUnknown || mutation.state.indicator === "mutation-pending"; + // A save this form did not start holds the coordinator (one left running + // when the user came back, or the check behind "confirm applied"): the save + // is off and the feedback says a save is running (1105/08-04). + const otherSaveRunning = mutation.state.indicator === "mutation-pending" && !form.pending; const guard = useDirtyNavigationGuard(form.dirty && !form.pending); return ( @@ -694,7 +699,7 @@ export default function ${pascal}CreatePage() { type="submit" pending={form.pending} pendingLabel={message("${camel}.form.saving")} - disabled={effectUnknown} + disabled={effectUnknown || otherSaveRunning} > {message("${camel}.form.save")} @@ -710,14 +715,21 @@ 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={() => { void form.resendUnknown(async () => openSaved(await mutation.resendUnknownEffect())); }} /> + ) : otherSaveRunning && form.result !== "effect-unknown" ? ( + ) : null } guard={} @@ -836,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( @@ -884,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/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..b9e0c971 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"; /** @@ -144,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" @@ -169,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 }), }); /** @@ -312,7 +322,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 +333,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/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/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/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/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/src/presentation/forms/use-app-form.ts b/src/presentation/forms/use-app-form.ts index 652d08b5..ef67fb2d 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}`; @@ -93,8 +114,21 @@ export function useAppForm< // focus, so the browser drops focus to the body. The status takes focus // once it has rendered (`feedbackId`). const focusFeedbackRef = useRef(false); + // 1105/08-01. The recovery actions (confirm applied, resend, retry) sit in + // that status and go away with it once they have done their work, so the + // browser drops focus to the body again. A success that replaces a status + // or an unknown result takes focus to the feedback area, but only when + // focus was lost: a save that leaves focus on its button or a field keeps + // it there, and a first save that just succeeds moves nothing. + const shownResultRef = useRef(result); useEffect(() => { - if (!focusFeedbackRef.current) return; + const previous = shownResultRef.current; + shownResultRef.current = result; + const recovered = + result === "success" && + (previous === "effect-unknown" || STATUS_RESULTS.has(previous)) && + focusIsLost(); + if (!focusFeedbackRef.current && !recovered) return; focusFeedbackRef.current = false; const feedback = document.getElementById(feedbackId); if (feedback instanceof HTMLElement) feedback.focus(); @@ -214,6 +248,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 +321,13 @@ export function useAppForm< setResult("unavailable"); } }, - [allowedServerFields, focusFirstError, settleSuccessfulValues], + [ + allowedServerFields, + focusField, + focusFirstError, + refusalMessages, + settleSuccessfulValues, + ], ); const validateAndSubmit = useCallback( @@ -408,6 +469,29 @@ 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; +} + +/** 1105/08-01. Nothing has focus: the focused element left the document. */ +function focusIsLost(): boolean { + const active = document.activeElement; + return active === null || active === document.body; +} + const STATUS_RESULTS: ReadonlySet = new Set([ "reauth-required", "forbidden", 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 (