chore(review): 1105 HTTP 판정·폼 조치 브랜치를 합친다

This commit is contained in:
DongHyeonka
2026-11-06 02:59:01 +09:00
30 changed files with 879 additions and 46 deletions
+1 -1
View File
@@ -15,5 +15,5 @@
"idempotencyAnswers": "config/contracts/backend-idempotency-answers.json"
},
"owner": "frontend-platform",
"comparedOn": "2026-11-04"
"comparedOn": "2026-11-05"
}
@@ -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
}
]
}
@@ -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`, 조립 검사는
+2 -2
View File
@@ -219,7 +219,7 @@ FE-REG-API 행은 descriptor에서 자동으로 만든다(`src/contracts/api-ope
- 백엔드는 값이 null인 필드를 키째 뺀다. `data` 키가 없으면 `null`로 읽는다. DTO 안에서 null일 수 있는 필드는 스키마에서 `.optional()`로 받는다.
- problem 스키마(`<base>-schemas.ts`의 `<base>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-결과-불명)이다.
- 업무 규칙 거절(`<FEATURE>_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에서 그 답은 결과 불명이다. 짝 백엔드 모양의 필드 오류 테스트는 생성된 작성 폼 테스트(`<base>-create-page.test.tsx`)처럼 400 본문을 손으로 적는다.
② **기준**
+5 -3
View File
@@ -122,7 +122,7 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기
| `commandEffect.refusedBeforeWrite` | `["<FEATURE>_INVALID"]` | 같다 | 이름 규칙을 트랜잭션 전에 검사한다(4절) |
| `acceptedStatuses` | `[201]` | `[201]` | `ResponseEntity.created`. 같은 키 재생도 첫 요청과 같은 201이다 |
| 결과 불명 화면 | 확인만. 다시 보내기 버튼 없음 | "같은 요청으로 다시 보내기"가 같은 키로 보낸다 | 키 없는 재전송은 서버가 새 요청으로 본다 |
| 생성 테스트 | 응답 유실 → 결과 불명, 다시 보내기 없음, 키 헤더 없음 | 응답 유실 → 같은 키로 다시 보내기. 503 `IDEMPOTENCY_UNAVAILABLE` → 같은 키로 1회 자동 재전송 | `tests/features/<id>/<base>-create-page.test.tsx`, `<base>-http-gateway.test.ts` |
| 생성 테스트 | 응답 유실 → 결과 불명, 다시 보내기 없음, 키 헤더 없음. "변경됨으로 확인" → 목록 화면 | 응답 유실 → 같은 키로 다시 보내기. 503 `IDEMPOTENCY_UNAVAILABLE` → 같은 키로 1회 자동 재전송. "변경됨으로 확인" → 목록 화면 | `tests/features/<id>/<base>-create-page.test.tsx`, `<base>-http-gateway.test.ts` |
- 테스트 하네스의 재시도 상한: 생성된 gateway 테스트는 앱 기본값(`maxRetryAttempts: 2`)으로 돈다. 그래야 `retryBudget: 1`의 재전송이 보인다. 페이지 테스트(`<base>-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 `<FEATURE>_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`로 분류하지 않는다.**
+1
View File
@@ -103,6 +103,7 @@ lint / check:architecture / check:i18n → FE-GATE-002, FE-GATE-010
| `<id>/<operationId>: KEYED commands require a recovery descriptor` | `KEYED`인데 `commandRecovery`가 없다 | V3 `commandRecovery` |
| `<id>/<operationId>: <GET·HEAD> is a read; its retrySemantics is SAFE or IDEMPOTENT, not <값>` | 읽기에 `KEYED`나 `NEVER`를 적었다 | V3 `retrySemantics`. 재시도를 막으려면 `frontend.retryBudget: 0` |
| `<id>/<operationId>: command operations require a command effect descriptor` | 쓰기에 `commandEffect`가 없다 | V3 `commandEffect` |
| `<id>/<operationId>: refusedBeforeWrite cannot declare <code>; 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-결과-불명)) |
| `<id>/<operationId>: read operations carry no command descriptors` | GET에 `commandEffect`·`commandRecovery`를 적었다 | 둘 다 `null` |
| `<id>/<operationId>: responseEnvelope NONE, but <other> in the same contribution reads ENVELOPE_V1; ...` | 한 계약 기여 안에서 operation 하나만 응답 모양이 다르다. 손으로 더한 operation에 `responseEnvelope` 줄을 빠뜨린 경우다 | 그 operation에 `responseEnvelope: "ENVELOPE_V1" as const`를 적는다. 정말 다른 백엔드면 기여를 나눈다 |
| `<id>: package version must be exact SemVer` | 버전 범위(`^1.2.0`)나 형식 오류 | `<BASE>_CONTRACT_PACKAGE.version` |
@@ -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한다. 화면은 근거 없는
+44 -3
View File
@@ -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")}
</Button>
@@ -710,14 +715,21 @@ export default function ${pascal}CreatePage() {
<AsyncSurface
state={mutation.state}
supportReference={form.supportReference}
// The list shows whether the item is there; the form alone
// would show nothing but an emptied input (1105/08-02).
onReconcileUnknownEffect={(resolution) => {
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" ? (
<AsyncSurface state={mutation.state} />
) : null
}
guard={<DirtyNavigationDialog guard={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);
});
});
`;
}
+2
View File
@@ -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. */
+13 -1
View File
@@ -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)
);
}
+3 -1
View File
@@ -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;
}>;
+47 -1
View File
@@ -166,7 +166,10 @@ export interface CommandEffectDescriptor<Problem> {
* 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<string> = new Set(
PLATFORM_CODES_POSSIBLY_AFTER_WRITE,
);
function assertRefusedBeforeWrite(
contract: InstalledHttpContract<unknown, unknown, unknown>["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);
}
@@ -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")}
</Button>
@@ -179,6 +185,10 @@ export default function ReferenceResourceFormPage() {
<p role="status">{message("reference.form.saved")}</p>
) : form.result === "conflict" ? (
<p role="status">{message("reference.form.conflict")}</p>
) : 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.
<AsyncSurface state={mutation.state} />
) : null
}
aside={
@@ -243,6 +243,13 @@ export type LegacyMutationOptions<Input, Value> = LegacyMutationBase<Input, Valu
type ApplicationMutationController<Input, Value> = 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<ApplicationResult<Value>>;
resolveConflict(): Promise<void>;
/**
@@ -559,6 +566,21 @@ export function useApplicationMutation<Input, Value>(
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",
@@ -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 ? (
<Button onClick={onResendUnknownEffect}>
{message("action.resendMutation")}
</Button>
+86 -2
View File
@@ -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<Values extends FormValues> = Readonly<{
message: ParameterlessMessageKey;
field?: FieldName<Values>;
}>;
type AppFormOptions<
Values extends FormValues,
Command,
@@ -37,6 +47,16 @@ type AppFormOptions<
mapToCommand(values: Values): Command;
submit(command: Command): Promise<FormResult<Output>>;
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<Record<string, FormRefusalMessage<Values>>>;
}>;
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<FormResultState>(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<Values>,
);
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<Values>(
@@ -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<Values extends FormValues>(
messages: Readonly<Record<string, FormRefusalMessage<Values>>> | undefined,
failure: AppFailure,
): FormRefusalMessage<Values> | 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<FormResultState> = new Set([
"reauth-required",
"forbidden",
+5 -9
View File
@@ -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 (
<nav id={id} aria-label={message("shell.primaryNavigation")}>
<ul className="app-navigation">
+15 -13
View File
@@ -1,10 +1,10 @@
import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { NAVIGATION_ROUTES } from "../../features/installed-feature-contracts.ts";
import { PageHeader } from "../design-system/index.ts";
import { useLocale } from "../i18n/index.ts";
import { useApplicationRuntime } from "../providers/application-provider.tsx";
import { activeNavigationRoutes } from "../routes/navigation-policy.ts";
const READINESS_ITEMS = Object.freeze([
"contract",
@@ -12,19 +12,21 @@ const READINESS_ITEMS = Object.freeze([
"accessibility",
] as const);
/**
* 1103/09-04. The first screens of the navigation after this page. In the
* template those are its example screens, a removable feature; a
* product that leaves them out gets its own screens here, and the page names
* no feature's route.
*/
const STARTER_ROUTES = Object.freeze(
NAVIGATION_ROUTES.filter((route) => route.routeId !== "APP_HOME").slice(0, 3),
);
export default function HomePage() {
const runtime = useApplicationRuntime();
const { message, resolve } = useLocale();
/**
* 1103/09-04. The first screens of the navigation after this page. In the
* template those are its example screens, a removable feature; a product
* that leaves them out gets its own screens here, and the page names no
* feature's route. 1105/08-03. Read at render, like the shell's
* navigation: a feature the runtime document disabled is not offered.
*/
const starterRoutes = activeNavigationRoutes((featureId) =>
runtime.isFeatureActive(featureId),
)
.filter((route) => route.routeId !== "APP_HOME")
.slice(0, 3);
const [release, setRelease] = useState<
Awaited<ReturnType<typeof runtime.getReleaseSummary>> | "failed" | null
>(null);
@@ -69,14 +71,14 @@ export default function HomePage() {
})
: message("home.runtime.checking")}
</p>
{STARTER_ROUTES.length > 0 ? (
{starterRoutes.length > 0 ? (
<section className="ui-panel starter-actions" aria-labelledby="starter-title">
<div>
<h2 id="starter-title">{message("home.starter.title")}</h2>
<p>{message("home.starter.description")}</p>
</div>
<div className="button-row">
{STARTER_ROUTES.map((route, index) => (
{starterRoutes.map((route, index) => (
<Link
key={route.routeId}
className={
+20 -1
View File
@@ -1,5 +1,24 @@
import type { SessionState } from "../../application/ports/in/application-api.ts";
import { getRoute } from "../../features/installed-feature-contracts.ts";
import {
getRoute,
NAVIGATION_ROUTES,
ROUTE_FEATURE_OWNER,
} from "../../features/installed-feature-contracts.ts";
/**
* §3.5. The navigation routes a screen may advertise: a feature the runtime
* document disabled does not advertise itself. The router refuses its routes
* too, so this is presentation, not the switch. 1105/08-03. The shell's
* navigation and the home page's starter links read this one list.
*/
export function activeNavigationRoutes(
isFeatureActive: (featureId: string) => boolean,
): typeof NAVIGATION_ROUTES {
return NAVIGATION_ROUTES.filter((definition) => {
const owner = ROUTE_FEATURE_OWNER[definition.routeId];
return owner === undefined || isFeatureActive(owner);
});
}
export type RouteAccessDecision =
| Readonly<{ allowed: true; action: "none" }>
@@ -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<string> | 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);
+19
View File
@@ -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(
<AsyncSurface
state={deriveAsyncState({ data: ["value"], hasMutationEffectUnknown: true })}
onReconcileUnknownEffect={vi.fn()}
onResendUnknownEffect={vi.fn()}
/>,
);
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 }),
+115 -2
View File
@@ -102,7 +102,8 @@ const FORM_OPERATIONS = Object.freeze({
/**
* 1103/03-01. The same create, declaring the paired backend scaffold's
* `<FEATURE>_INVALID` as refused before the write.
* `<FEATURE>_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 (
<Form pending={form.pending} onSubmit={(event) => void form.submitForm(event)}>
{props.refusalMessages ? (
<ErrorSummary
fieldErrors={form.fieldErrors}
formErrors={form.formErrors}
fieldLabels={{ name: "Name", note: "Note" }}
fieldId={form.fieldId}
onFocusField={form.focusField}
/>
) : null}
<FormField {...form.field("name")} label="Name" required />
<Button type="submit" disabled={form.pending || blocked}>
Submit
@@ -984,6 +1001,102 @@ describe("correcting a field after a server validation refusal", () => {
expect(sentKeys(fetcher)).toEqual(["key-1", "key-2"]);
});
// 1103/03-01 (remaining part). The declared refusal in the feature's own
// words, on the field it names, instead of the platform's unavailable
// status and its support action. A feature passes a key of its catalog.
it("shows the feature's words for a declared refusal on its field and saves again", async () => {
const user = userEvent.setup();
const fetcher = answerFirst(400, { code: "WORKLOG_INVALID" });
render(
<CoordinatedForm
fetcher={fetcher}
operations={FORM_DECLARING_OPERATIONS}
refusalMessages={{
WORKLOG_INVALID: { field: "name", message: "form.validation.invalidFormat" },
}}
/>,
{ wrapper: wrapper(queryClient()) },
);
const name = screen.getByRole("textbox", { name: /Name/ });
await user.type(name, "Rejected");
await user.click(screen.getByRole("button", { name: "Submit" }));
await waitFor(() =>
expect(screen.getByTestId("result")).toHaveTextContent("validation-error"),
);
expect(name).toHaveAttribute("aria-invalid", "true");
expect(name).toHaveFocus();
expect(screen.getByRole("alert")).toHaveTextContent(
`Name: ${formatMessage("ko-KR", "form.validation.invalidFormat")}`,
);
expect(screen.getByRole("button", { name: "Submit" })).toBeEnabled();
await user.clear(name);
await user.type(name, "Fixed");
await user.click(screen.getByRole("button", { name: "Submit" }));
await waitFor(() =>
expect(screen.getByTestId("result")).toHaveTextContent("success"),
);
expect(sentKeys(fetcher)).toEqual(["key-1", "key-2"]);
});
it("shows a declared refusal without a field in the error summary", async () => {
const user = userEvent.setup();
const fetcher = answerFirst(409, { code: "POSTER_ALREADY_EXISTS" });
render(
<CoordinatedForm
fetcher={fetcher}
operations={FORM_DECLARING_OPERATIONS}
refusalMessages={{
POSTER_ALREADY_EXISTS: { message: "form.validation.invalidValue" },
}}
/>,
{ wrapper: wrapper(queryClient()) },
);
const name = screen.getByRole("textbox", { name: /Name/ });
await user.type(name, "Taken");
await user.click(screen.getByRole("button", { name: "Submit" }));
await waitFor(() =>
expect(screen.getByTestId("result")).toHaveTextContent("validation-error"),
);
expect(screen.getByRole("alert")).toHaveTextContent(
formatMessage("ko-KR", "form.validation.invalidValue"),
);
expect(screen.getByRole("alert")).not.toHaveTextContent(
formatMessage("ko-KR", "form.conflict"),
);
expect(name).not.toHaveAttribute("aria-invalid");
expect(screen.getByRole("button", { name: "Submit" })).toBeEnabled();
});
// An unknown result stays unknown: the words are for a refusal that did
// not apply, never for one that may have.
it("keeps an undeclared refusal unknown even when the form has words for its code", async () => {
const user = userEvent.setup();
const fetcher = answerFirst(400, { code: "WORKLOG_INVALID" });
render(
<CoordinatedForm
fetcher={fetcher}
refusalMessages={{
WORKLOG_INVALID: { field: "name", message: "form.validation.invalidFormat" },
}}
/>,
{ wrapper: wrapper(queryClient()) },
);
await user.type(screen.getByRole("textbox", { name: /Name/ }), "Rejected");
await user.click(screen.getByRole("button", { name: "Submit" }));
await waitFor(() =>
expect(screen.getByTestId("result")).toHaveTextContent("effect-unknown"),
);
expect(screen.getByRole("button", { name: "Submit" })).toBeDisabled();
});
// 1103/03-01. A code the operation did not declare may have been raised
// after a write, so the coordinator keeps holding it.
it("keeps the save off after a business refusal the operation did not declare", async () => {
+63
View File
@@ -130,6 +130,29 @@ test.describe("after a rate-limited save", () => {
await saveFromKeyboard(page, "다시 시도");
});
// 1105/08-01. The retry button goes away with the status once the save
// succeeds; focus stays in the feedback area, not on the body.
test("keeps keyboard focus in the feedback after retrying from the keyboard", async ({
page,
}) => {
await openForm(page);
await routeCreate(page, [
(route) =>
route.fulfill({
status: 429,
headers: { "retry-after": "1" },
json: { title: "Too many requests" },
}),
created,
]);
await saveFromKeyboard(page, "다시 시도");
await page.keyboard.press("Enter");
await expect(page.getByRole("status")).toHaveText("저장했습니다.");
await expect(page.locator(".page-template__feedback")).toBeFocused();
});
});
test.describe("after a save whose result is unknown", () => {
@@ -171,4 +194,44 @@ test.describe("after a save whose result is unknown", () => {
await saveFromKeyboard(page, "변경됨으로 확인");
});
// 1105/08-01. Confirming or resending removes the button that had focus;
// focus stays in the feedback area that shows the result.
test("keeps keyboard focus in the feedback after confirming from the keyboard", async ({
page,
}) => {
await openForm(page);
const calls = await routeCreate(page, [
(route) => route.fulfill({ status: 500, json: { title: "Internal error" } }),
]);
await saveFromKeyboard(page, "변경됨으로 확인");
await page.keyboard.press("Enter");
await expect(page.getByRole("status")).toHaveText("저장했습니다.");
await expect(page.locator(".page-template__feedback")).toBeFocused();
expect(calls).toHaveLength(1);
});
test("keeps keyboard focus in the feedback after resending from the keyboard", async ({
page,
}) => {
await openForm(page);
const calls = await routeCreate(page, [
(route) => route.fulfill({ status: 500, json: { title: "Internal error" } }),
created,
]);
await saveFromKeyboard(page, "변경됨으로 확인");
await page.keyboard.press("Tab");
await expect(
page.getByRole("button", { name: "같은 요청으로 다시 보내기" }),
).toBeFocused();
await page.keyboard.press("Enter");
await expect(page.getByRole("status")).toHaveText("저장했습니다.");
await expect(page.locator(".page-template__feedback")).toBeFocused();
expect(calls).toHaveLength(2);
expect(calls[1]?.idempotencyKey).toBe(calls[0]?.idempotencyKey);
});
});
@@ -1,15 +1,21 @@
// @vitest-environment jsdom
import { render, screen, waitFor } from "@testing-library/react";
import { render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it, vi } from "vitest";
import { createAnonymousSessionAdapter } from "../../../src/adapters/auth/external-session-adapter.ts";
import {
ROUTE_FEATURE_OWNER,
ROUTE_REGISTRY,
} from "../../../src/features/installed-feature-contracts.ts";
import { PLATFORM_EXAMPLES_FEATURE_ID } from "../../../src/features/platform-examples-feature/contracts/platform-examples-contract.ts";
import StateGalleryPage from "../../../src/features/platform-examples-feature/presentation/state-gallery-page.tsx";
import { ApplicationProvider } from "../../../src/presentation/providers/application-provider.tsx";
import { PreferenceProviders } from "../../../src/presentation/providers/preference-providers.tsx";
import { AppRouter } from "../../../src/presentation/routes/app-router.tsx";
import { createTestApplication } from "../../helpers/create-test-application.ts";
import { createProductFeaturesStub } from "../../helpers/runtime-capabilities-stub.ts";
/**
* The example screens (`/examples/ui`, `/examples/states`, `/examples/auth`)
@@ -48,6 +54,37 @@ describe("example pages", () => {
);
});
// 1105/08-03. The home page's starter links read the same switch as the
// shell's navigation: switched off at runtime, this feature's screens are
// not offered there, and the next active screens take their place.
it("leaves this feature's screens out of the home page's starter links when it is switched off", async () => {
renderApp(
"/",
createTestApplication({
productFeatures: createProductFeaturesStub({
[PLATFORM_EXAMPLES_FEATURE_ID]: "DISABLED_BY_CONFIG",
}),
}),
);
const starter = await screen.findByRole("region", { name: "준비된 화면 살펴보기" });
const starterPaths = within(starter)
.getAllByRole("link")
.map((link) => link.getAttribute("href"));
const ownPaths = Object.values(ROUTE_REGISTRY)
.filter((route) => ROUTE_FEATURE_OWNER[route.routeId] === PLATFORM_EXAMPLES_FEATURE_ID)
.map((route) => route.path);
const [navigation] = screen.getAllByRole("navigation", { name: "주요 탐색" });
const advertised = within(navigation!)
.getAllByRole("link")
.map((link) => link.getAttribute("href"))
.filter((path) => path !== "/");
expect(ownPaths.length).toBeGreaterThan(0);
expect(starterPaths.some((path) => ownPaths.includes(path ?? ""))).toBe(false);
expect(starterPaths).toEqual(advertised.slice(0, 3));
});
it("returns to the current URL with its hash from the auth example page", async () => {
const user = userEvent.setup();
const beginSignIn = vi.fn(async () => {});
@@ -516,6 +516,134 @@ describe("reference feature page states", () => {
expect(screen.getByRole("button", { name: firstAction })).toHaveFocus();
});
/**
* 1105/08-01. A recovery action goes away with its status once it has
* done its work, so the browser dropped focus to the body. Focus now stays
* in the feedback area that shows the result.
*/
it.each([
{
action: "변경됨으로 확인",
tabs: 1,
failure: createFailure("SERVER_FAILURE", "CREATE_REFERENCE_RESOURCE", 0, {
effect: "MAYBE_APPLIED",
}),
text: "변경 결과를 확인할 수 없습니다.",
},
{
action: "같은 요청으로 다시 보내기",
tabs: 2,
failure: createFailure("SERVER_FAILURE", "CREATE_REFERENCE_RESOURCE", 0, {
effect: "MAYBE_APPLIED",
}),
text: "변경 결과를 확인할 수 없습니다.",
},
{
action: "다시 시도",
tabs: 1,
failure: createFailure("RATE_LIMITED", "CREATE_REFERENCE_RESOURCE", 0, {
effect: "NOT_APPLIED",
httpStatus: 429,
}),
text: "요청이 많습니다. 잠시 후 다시 시도해 주세요.",
},
])("keeps focus in the feedback after '$action' from the keyboard", async ({
action,
tabs,
failure,
text,
}) => {
const user = userEvent.setup();
const createResource = vi
.fn<ReferenceFeatureInput["createResource"]>()
.mockResolvedValueOnce({ ok: false, error: failure })
.mockResolvedValue({
ok: true,
value: { resourceId: "created", title: "Keyboard save", createdAt: null },
});
renderReference(
inputWith({ createResource }),
"/examples/reference-resources/new",
);
await user.type(
await screen.findByRole("textbox", { name: /새 항목 이름/ }),
"Keyboard save",
);
screen.getByRole("button", { name: "저장" }).focus();
await user.keyboard("{Enter}");
const status = (await screen.findByText(text)).closest(
".page-template__feedback",
);
await waitFor(() => expect(status).toHaveFocus());
for (let tab = 0; tab < tabs; tab += 1) await user.tab();
expect(screen.getByRole("button", { name: action })).toHaveFocus();
await user.keyboard("{Enter}");
const saved = await screen.findByText("저장했습니다.");
await waitFor(() =>
expect(saved.closest(".page-template__feedback")).toHaveFocus(),
);
});
// 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<ReferenceResourceView>) => void)
| undefined;
const createResource = vi
.fn<ReferenceFeatureInput["createResource"]>()
.mockImplementationOnce(
() =>
new Promise<ReferenceResult<ReferenceResourceView>>((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 () => {
@@ -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([
() =>
+50
View File
@@ -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<string> {
const text = readFileSync(pin.frontend.contractDocument, "utf8");
const section = text.split("### 6.1 ")[1]?.split(/\n#{2,3} /u)[0] ?? "";
const codes = new Set<string>();
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(),
);
});
});
+26
View File
@@ -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],
@@ -101,6 +114,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(
+34
View File
@@ -265,6 +265,40 @@ 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("<AsyncSurface state={mutation.state} />");
});
// 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" });
@@ -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",