diff --git a/docs/architecture/2026-07-30-frontend-runtime-capability-repository-aligned-implementation-closed-deep-design.md b/docs/architecture/2026-07-30-frontend-runtime-capability-repository-aligned-implementation-closed-deep-design.md index a7bec984..2112ff41 100644 --- a/docs/architecture/2026-07-30-frontend-runtime-capability-repository-aligned-implementation-closed-deep-design.md +++ b/docs/architecture/2026-07-30-frontend-runtime-capability-repository-aligned-implementation-closed-deep-design.md @@ -635,6 +635,7 @@ export interface CommandEffectDescriptor { status: number; problem: Problem; }>): "NOT_APPLIED" | "APPLIED_CONFIRMED" | "MAYBE_APPLIED"; + classifyStatus?(status: 401 | 403 | 429): "NOT_APPLIED" | "MAYBE_APPLIED"; } ``` @@ -647,6 +648,8 @@ export interface CommandEffectDescriptor { - frontend는 inspect request/response wire shape나 problem effect meaning을 작성하지 않는다; - `classifyProblem`은 package가 제공한 pure bounded classifier다; - classifier가 throw/unknown을 반환하면 effect는 fail-safe `MAYBE_APPLIED`이고 contract runtime failure를 기록한다; +- 401·403·429는 본문을 읽기 전에 판정하므로 `classifyProblem`을 거치지 않는다. package가 `classifyStatus`를 주면 그 판정을 쓰고, 없거나 `NOT_APPLIED` 외 값·throw면 전송 뒤 `MAYBE_APPLIED`다(`src/adapters/http/http-effect-certainty.ts` `classifyStatusEffect`); +- `AUTH_REQUIRED`는 effect가 `MAYBE_APPLIED`여도 action이 `reauth`다(`src/contracts/errors.ts` `unknownEffectAction`); - feature gateway가 package의 inspect operation을 application-safe outcome으로 mapping한다. ### 4.5 event contribution diff --git a/docs/architecture/backend-api-and-server-state-contract.md b/docs/architecture/backend-api-and-server-state-contract.md index 95d45cac..c209ef03 100644 --- a/docs/architecture/backend-api-and-server-state-contract.md +++ b/docs/architecture/backend-api-and-server-state-contract.md @@ -253,7 +253,9 @@ Cross-origin bearer provider 최소 CORS: - exact allow-origin 목록과 bounded preflight cache - `Authorization`, `Content-Type`, `Idempotency-Key`, `X-Correlation-ID`, 향후 `If-None-Match`, `If-Match` 허용 -- 필요한 경우 `ETag`, `Retry-After`, request/trace header만 expose +- 필요한 경우 `ETag`, `Retry-After`, request/trace header만 expose. + `X-Correlation-ID`를 expose하면 V3 실패의 `AppFailure.requestId`가 된다 + (`src/adapters/http/feature-http-binding.ts`) - redirect login page, HTML error body와 wildcard credential 금지 ## 6. Command와 idempotency @@ -593,6 +595,21 @@ query invalidate hint로만 쓸지 operation별 reducer contract가 필요하다 - rate limit key는 principal/tenant/operation과 abuse policy에 binding하며 raw credential/IP를 metric label에 넣지 않는다. +### 16.1 전송별 재시도·타임아웃 규칙 (2026-09-25 코드 기준) + +같은 이름의 정책이라도 전송마다 동작이 다르다. operation을 다른 전송으로 옮기면 +이 표로 동작 변화를 확인한다. + +| 규칙 | V3 contract executor (기본 경로) | V2 client (기본 조합에 없음) | Browser RPC | +|---|---|---|---| +| KEYED 명령 자동 재시도 | 전송 전 실패만 재시도한다. 전송 뒤 실패는 재시도하지 않고 `MAYBE_APPLIED`다. 응답(5xx·429)으로는 재시도하지 않는다 (`src/adapters/http/http-retry-lifecycle.ts` `canRetryTransport`, `isRetryableSemantics`) | 네트워크·타임아웃·429·408/425/502/503/504 뒤 같은 키로 다시 보낸다. 전송 여부를 보지 않는다 (`src/adapters/http/retry-policy.ts` `shouldRetry`) | `KEYED_COMMAND`는 유효한 키가 있고 profile `retryOwner`가 `FRONTEND_ADAPTER`면 `retryableFailures`에서 같은 키로 다시 보낸다 (`src/adapters/browser-rpc/browser-rpc-runtime.ts` `shouldRetry`) | +| 재시도 횟수 상한 | min(계약 `retryBudget`, `MAX_RETRY_ATTEMPTS`, 2) (`http-execution-v3.ts` `retryCeiling`) | `MAX_RETRY_ATTEMPTS`, 기본 2 (`client.ts` `maxRetryAttempts`) | profile `maxAttempts`(시도 횟수), 하드 상한 4 (`src/contracts/browser-rpc.ts` `BROWSER_RPC_HARD_LIMITS`) | +| `Retry-After` | 5초를 넘으면 재시도하지 않는다. 이하면 hint에 jitter를 더해 기다린다 (`http-retry-lifecycle.ts` `retryDelayFor`) | 30초를 넘으면 재시도하지 않는다. 이하면 max(backoff, hint)만큼 기다린다 (`retry-policy.ts`) | profile `maxRetryAfterMs`로 잘라 max(backoff, hint)만큼 기다린다. 하드 상한 60초 (`browser-rpc-runtime.ts` `retryDelay`) | +| `REQUEST_TIMEOUT_MS` | 상한이다. 계약 `totalDeadlineMs`를 줄이기만 한다 (`runtime-adapters.ts` `requestDeadlineCeilingMs`) | 기본값이다. operation `timeoutMs`가 있으면 그 값을 쓰고, 더 길 수도 있다 (`client.ts` `defaultTimeoutMs`) | 쓰지 않는다. operation `totalDeadlineMs`만 쓴다. 하드 상한 30분 | + +결과 불명 뒤 사용자 재전송은 전송과 무관하게 같은 intent·같은 키를 쓴다 +(`src/presentation/adapters/query/application-query.ts` `resendUnknownEffect`). + ## 17. Observability와 privacy 허용되는 공통 dimension: diff --git a/docs/architecture/decisions/VD-04-native-form-facade.md b/docs/architecture/decisions/VD-04-native-form-facade.md index 374fd20b..958581c6 100644 --- a/docs/architecture/decisions/VD-04-native-form-facade.md +++ b/docs/architecture/decisions/VD-04-native-form-facade.md @@ -18,7 +18,8 @@ field orchestration까지 플랫폼 기본값으로 고정하게 된다. 2. Zod presentation schema, application command mapper와 domain invariant는 서로 다른 소유물로 유지한다. 3. page와 feature는 `useAppForm`, `Form`, `FormField`, `ErrorSummary`, - `mapValidationFailureToFields`, `useDirtyNavigationGuard`만 사용한다. + `FormFailureStatus`, `mapValidationFailureToFields`, `useDirtyNavigationGuard`만 + 사용한다. 4. 422 details는 승인된 `path`와 `code`만 HTTP 경계에서 투영한다. backend message와 알 수 없는 field는 field에 전달하지 않고 안전한 form-level error로 이동한다. @@ -27,6 +28,15 @@ field orchestration까지 플랫폼 기본값으로 고정하게 된다. dirty 상태를 해제한다. 7. `StandardPage`, `CollectionPage`, `DetailPage`, `FormPage`, `StatusPage`는 layout과 state slot만 소유하며 application/query/HTTP를 import하지 않는다. +8. (2026-09-25, 08-01) 입력 오류가 아닌 저장 실패는 ErrorSummary에 넣지 않는다. + `useAppForm`은 `action: "reauth"`를 `reauth-required`, `FORBIDDEN`을 `forbidden`, + `action: "retry"`를 `retry-later`로 구분하고 그 실패를 `failure`로 낸다. 화면은 + `FormFailureStatus`로 문구와 행동(로그인·이동·다시 시도)을 보여 준다. 재로그인은 + 입력을 지운다는 안내를 버튼 앞에 둔다(`src/presentation/forms/use-app-form.ts`, + `form-components.tsx`). +9. (2026-09-25, 03-01) 결과 불명 저장은 사용자가 "변경되지 않음"을 판정하지 않는다. + `resendUnknown(mutation.resendUnknownEffect)`로 같은 intent·같은 + `Idempotency-Key`를 다시 보낸다(`src/presentation/adapters/query/application-query.ts`). ## React Hook Form 도입 조건 diff --git a/docs/architecture/decisions/VD-07-diagnostics-and-telemetry-exporter.md b/docs/architecture/decisions/VD-07-diagnostics-and-telemetry-exporter.md index b9c30ac6..524a55bb 100644 --- a/docs/architecture/decisions/VD-07-diagnostics-and-telemetry-exporter.md +++ b/docs/architecture/decisions/VD-07-diagnostics-and-telemetry-exporter.md @@ -43,13 +43,17 @@ vendor 결정 전에는 안전한 기본값이 아니다. `createHttpObservationProjector`가 유일한 projection authority다. observation은 arbitrary context map이 아니며 projector는 `route_id`, `operation_id`, `operation`, `outcome`, `error_kind`, `http_status_group`, - `attempt_count_bucket`, `duration_bucket`만 사용한다. raw attempt count, + `attempt_count_bucket`, `duration_bucket`만 사용한다. diagnostics에만 + `correlation_id`(서버가 돌려준 `x-correlation-id`, 없으면 실행이 보낸 요청 ID)를 + 더한다. telemetry에는 넣지 않는다(03-03, `createHttpObservationProjector`). raw attempt count, duration, status, URL, intent, key, input identity와 내부 `terminalReason`은 sink로 나가지 않는다. effect certainty가 운영상 필요해지면 `effect_certainty` key와 닫힌 value policy를 contract·fixture·이 ADR에 동시에 추가한 뒤에만 전달한다. 5-2. caller cancellation과 scope fence는 API failure가 아니다. diagnostics는 한 - 번 남기고 `api.request.failed`는 발행하지 않는다. + 번 남기고 `api.request.failed`는 발행하지 않는다. 자격증명이 없어 한 번도 + 보내지 않은 `UNAUTHENTICATED`(응답 status 없음)도 같다(03-07, + `src/bootstrap/runtime-adapters.ts` `isTerminalNonAbortFailure`). 5-3. `routeId`는 installed operation-executor 경계의 필수 입력이다. feature gateway가 소유한 low-cardinality route identity를 URL에서 재구성하지 않는다. 6. `app.boot.failed`, `ui.render.failed`, `release.mismatch.detected`, @@ -72,6 +76,11 @@ vendor 결정 전에는 안전한 기본값이 아니다. 아니거나 1 미만이거나 문서화된 ceiling(각각 `MAX_TELEMETRY_QUEUE`, `MAX_DIAGNOSTIC_ENTRIES` = 10,000)을 넘으면 `TypeError`로 거절한다. NaN/Infinity가 조용히 eviction을 비활성화하는 경로를 남기지 않는다. +7-5. (2026-09-25) 두 telemetry port는 collector 하나로 보낸다 + (`src/adapters/telemetry/telemetry-collector.ts`). collector는 본문을 60KiB 아래로 + 나누고, 진행 중인 keepalive 본문 합이 64KiB를 넘으면 그 부분은 keepalive 없이 + 보낸다(03-05). 조합 루트가 release manifest의 `buildId`·`releaseId`를 넘기면 모든 + 이벤트에 `build_id`·`release_id`를 붙인다(13-11, `src/bootstrap/runtime-adapters.ts`). 8. diagnostics와 telemetry failure는 제품 흐름, HTTP 결과, route transition, storage/cache fallback과 React error surface를 바꾸지 않는다. 9. mount 전 bootstrap failure는 안전한 build/config/error kind만 별도 evidence로 diff --git a/docs/architecture/typescript-state-and-data-flow.md b/docs/architecture/typescript-state-and-data-flow.md index 32fa998f..e0bb045a 100644 --- a/docs/architecture/typescript-state-and-data-flow.md +++ b/docs/architecture/typescript-state-and-data-flow.md @@ -597,6 +597,7 @@ Form 또는 TanStack Form adapter를 평가한다. - `Description` - `FieldError` - `ErrorSummary` +- `FormFailureStatus` (재로그인·권한 없음·잠시 후 재시도 저장 실패) - `useAppForm` - `mapValidationFailureToFields` - `useDirtyNavigationGuard` @@ -620,6 +621,7 @@ backend message와 알 수 없는 path는 field copy로 사용하지 않는다. 3. submitting 중 중복 제출 방지 4. 422 응답의 알려진 field만 표시하고 나머지는 form-level failure로 처리 5. 409 conflict는 validation error로 위장하지 않음 +5a. 401·403·429 같은 입력 외 실패는 ErrorSummary가 아니라 `FormFailureStatus`로 표시 6. 취소와 route 이탈 시 dirty policy 적용 7. form value → application command mapper를 별도 함수로 둠 8. browser autofill, IME composition, paste, password manager를 방해하지 않음 diff --git a/docs/operations/api-contract-and-server-state-recovery.md b/docs/operations/api-contract-and-server-state-recovery.md index 18f71224..dfc7fba4 100644 --- a/docs/operations/api-contract-and-server-state-recovery.md +++ b/docs/operations/api-contract-and-server-state-recovery.md @@ -4,7 +4,7 @@ schema/cache 절차 분리 - backend 구조와 handoff: [Backend API와 Server State contract](../architecture/backend-api-and-server-state-contract.md) -- 기준일: 2026-07-28 +- 기준일: 2026-07-28, 1절·5.1·6.0·6.3은 2026-09-25 V3 코드 기준으로 갱신 - 설계: [API contract, Schema, Mapper와 Server State](../architecture/api-contract-schema-mapper-and-server-state.md) - browser Protobuf/gateway 설계: @@ -12,18 +12,28 @@ ## 1. 적용 범위 -현재 reference REST → Schema → Mapper → TanStack Query vertical은 `COMPOSED`다. -하지만 다음 target delta는 아직 `DESIGNED_NOT_IMPLEMENTED`다. +현재 reference REST → Schema → Mapper → TanStack Query vertical은 V3 contract +executor(`src/adapters/http/http-execution-v3.ts`)로 `COMPOSED`다. 조합 위치는 +`src/bootstrap/runtime-adapters.ts`의 `createContractHttpExecutor`다. 이 문서의 +"current v1"은 V2 client(`src/adapters/http/client.ts`) 시절에 쓴 말이다. V2는 +기본 조합에 없다(`createRuntimeHttpClient` 호출처 없음). -- REST v2 auth fail-close/final invariant -- total logical deadline와 bounded response decoder -- complete cursor/conditional request -- typed schema/mapper registry -- strict query/mutation definition과 concurrency coordinator -- GraphQL reference adapter -- Connect-Web reference adapter -- gRPC-Web reference adapter -- Protobuf REST Gateway +2026-09-25 코드 기준 상태: + +| 항목 | 상태 | 코드 위치 | +| --- | --- | --- | +| auth fail-close / final request invariant | 구현됨. 자격증명 없음·owner 장애·scope 불일치면 fetch 0회. 전송 직전 최종 요청을 다시 검사 | `runtime-adapters.ts` `attachCredentials`, `http-execution-v3.ts` credential patch 처리, `src/adapters/http/http-contract-bridge.ts` `checkFinalInvariants` | +| total logical deadline | 구현됨. 자격증명·lease·fetch·본문·backoff가 마감 하나를 공유. `REQUEST_TIMEOUT_MS`는 상한 | `http-execution-v3.ts` `effectiveDeadlineMs`, lifetime signal | +| bounded response decoder | 구현됨. 선언 길이 → 스트림 바이트 → JSON 구조 → 스키마 순 | `src/adapters/http/bounded-body-reader.ts`, `bounded-json.ts`, `http-execution-v3.ts` `admitResponse` | +| typed schema/mapper | 구현됨. 계약별 input/output/problem validator와 feature mapper | `src/contracts/external-contract-runtime.ts`, `src/adapters/http/feature-http-binding.ts` | +| strict query/mutation definition과 concurrency coordinator | 구현됨 | `src/contracts/server-state.ts` `bindQuery`·`BoundMutation`, `src/presentation/adapters/query/application-query.ts` | +| 결과 불명 command의 같은 키 재전송 | 구현됨. 사용자가 누를 때만 보낸다 | `application-query.ts` `resendUnknownEffect` (6.3) | +| cursor pagination | runtime만 있다. 설치된 operation이 쓰지 않는다 | `src/adapters/query-cache/cursor-pagination-runtime.ts` | +| conditional request | validator store만 조합됐다. V3는 `If-None-Match`/`If-Match`를 보내지 않는다 | `src/adapters/query-cache/conditional-validator-store.ts` | +| GraphQL reference adapter | 구현 안 됨 | 없음 | +| Connect-Web / gRPC-Web reference adapter | provider 중립 Browser RPC runtime만 있다. 조합되지 않았다 | `src/adapters/browser-rpc/` | +| Protobuf REST Gateway | 구현 안 됨 | 없음 | +| operation별 `TrafficAdmission` switch | 구현 안 됨 | 없음 | GraphQL/Connect/gRPC-Web/REST Gateway 절차는 해당 runtime과 actual provider가 구현·조합된 뒤에만 운영 gate로 활성화한다. 문서나 fake fixture만으로 capability를 @@ -142,11 +152,14 @@ artifact에서 access-controlled하게 비교한다. ### 5.1 Auth-required request가 무자격으로 전송됨 -현재 v1은 external auth integration이 unavailable이어도 unchanged request가 -전송될 수 있으므로 target v2 전까지 제품 auth-required traffic을 provider -evidence 없이 활성화하지 않는다. +V3는 자격증명이 없거나(`UNAUTHENTICATED`), auth owner가 장애거나 +(`integration-failed` → `CREDENTIAL_OWNER_UNAVAILABLE`), scope가 준비되지 않았으면 +fetch 없이 끝난다(`src/bootstrap/runtime-adapters.ts` `attachCredentials`, +`src/adapters/http/http-execution-v3.ts` credential patch 처리). 전송 0회 미인증은 +diagnostics에만 남고 `api.request.failed`에는 세지 않는다(03-07). 그래도 무자격 +전송이 보이면 V3가 아닌 경로(V2 client 직접 조합, 외부 SDK)를 먼저 의심한다. -target 점검: +점검: 1. session state가 authenticated인지 확인한다. 2. auth owner가 `CredentialPatch`만 반환하는지 또는 final request invariant를 @@ -168,26 +181,37 @@ target 점검: 3. cross-origin allow-origin/credentials/method/header/expose가 exact한지 확인한다. 4. wildcard credential, redirect와 unexpected origin을 복구한다. 5. CSRF token/header 값을 ticket에 기록하지 않는다. +6. V3 요청은 논리 실행마다 `x-correlation-id` 하나를 보낸다(재시도도 같은 값, + `src/adapters/http/http-execution-v3.ts` `createRequestId`). cross-origin API면 + preflight `Access-Control-Allow-Headers`에 `x-correlation-id`가 있어야 요청이 + 나간다. 응답의 `x-correlation-id`를 `AppFailure.requestId`와 diagnostics + `correlation_id`로 쓰려면 `Access-Control-Expose-Headers`에도 넣는다 + (`src/adapters/http/feature-http-binding.ts` `projectExecutionOutcome`, + `src/bootstrap/runtime-adapters.ts` `createHttpObservationProjector`). telemetry에는 + 넣지 않는다. ## 6. REST incident -### 6.0 Current v1 available checks +### 6.0 V3에서 바로 쓸 수 있는 점검 -1. current per-attempt timeout/bounded retry, Query retry off, AbortSignal과 401 - recovery observation을 확인한다. -2. installed request/envelope/payload Zod schema와 mapper failure kind를 확인하되 - current `Response.json()`이 body cap 증거가 아님을 기록한다. +1. 전체 마감 하나와 재시도 상한 min(계약 `retryBudget`, `MAX_RETRY_ATTEMPTS`, 2)을 + 확인한다. TanStack Query 재시도는 꺼져 있다(`http-execution-v3.ts`, + `src/adapters/query-cache/tanstack-query-cache.ts`). 전송별 차이는 + [backend contract 16.1절](../architecture/backend-api-and-server-state-contract.md) + 표를 본다. +2. 본문은 `bounded-body-reader.ts`가 상한을 적용한 뒤 계약 validator와 feature + mapper를 거친다. 실패 kind로 어느 단계인지 좁힌다. 3. QueryClient/coordinator로 affected read를 cancel/invalidate/clear한다. -4. cursor response/page runtime, APP_ETAG와 total deadline은 아직 없으므로 해당 - control을 실행했다고 기록하지 않는다. -5. command effect는 backend와 reconcile한다. basic optimistic snapshot 문제가 - 의심되면 runtime switch를 가정하지 말고 no-optimistic/known-good release로 - rollback한다. +4. cursor runtime과 conditional request는 설치된 operation에 조합되지 않았으므로 + 해당 control을 실행했다고 기록하지 않는다(1절 표). +5. 문의 식별자는 `AppFailure.requestId`와 diagnostics `correlation_id`로 서버 로그와 + 잇는다(5.2절 6항). -아래 6.1~6.5는 target v2 coordinator가 해당 operation에 composed된 뒤에만 -운영 절차로 활성화한다. +6.1·6.2는 V3 operation에 적용한다. 항목 중 V3에 없는 control은 실행했다고 +기록하지 않는다. 6.4·6.5는 해당 runtime이 operation에 조합된 뒤에만 운영 절차로 +활성화한다. -### 6.1 Timeout/retry storm — target v2 +### 6.1 Timeout/retry storm 1. Query retry가 꺼지고 REST transport 하나만 network retry하는지 확인한다. 2. total logical deadline 안에 auth, fetch, body, mapper, recovery와 sleep이 모두 @@ -202,7 +226,7 @@ target 점검: 7. timer/listener/reader leak가 있는 cohort는 traffic을 닫는다. 8. keyed command는 backend dedupe evidence 없이는 retry를 끈다. -### 6.2 Body/media/schema failure — target v2 +### 6.2 Body/media/schema failure 1. final URL/status/content type을 확인한다. 2. present/valid Content-Length advisory preflight와 actual browser-visible decoded @@ -219,15 +243,24 @@ target 점검: 10. backend/frontend artifact가 coherent하지 않으면 operation traffic을 닫고 N/N-1 compatible set으로 rollback한다. -### 6.3 Idempotency/ambiguous command — target v2 +### 6.3 Idempotency/ambiguous command 1. principal/operation/payload digest/key tuple과 backend TTL/status를 access-controlled evidence에서 확인한다. 2. 같은 key + 다른 payload가 거절되는지 확인한다. 3. concurrent same-key request가 duplicate commit을 만들지 않았는지 확인한다. -4. `UNKNOWN` effect에 새 key를 생성해 retry하지 않는다. -5. backend status/receipt로 `COMMITTED`면 cache reconcile/invalidate한다. -6. `NOT_APPLIED`가 증명된 경우만 정책에 따라 retry한다. +4. `UNKNOWN` effect에 새 key를 생성해 retry하지 않는다. 클라이언트는 결과 불명 + admission의 intent를 보관하고, 같은 canonical input의 재저장과 "같은 요청으로 + 다시 보내기"는 그 intent와 같은 `Idempotency-Key`로 보낸다. 입력이 바뀌면 새 + key다. 자동 재전송은 없다(`src/presentation/adapters/query/application-query.ts` + `submit`·`resendUnknownEffect`, 화면 `src/presentation/components/async-surface.tsx`). +5. backend status/receipt로 `COMMITTED`면 cache reconcile/invalidate한다. 화면의 + "변경됨으로 확인"이 이 경로다. +6. `NOT_APPLIED`가 증명된 경우만 정책에 따라 retry한다. 화면은 근거 없는 + "변경되지 않음" 확정을 주지 않고 목록 새로고침 링크를 준다. +7. 한계: 결과 불명 admission은 메모리에만 있다. 새로고침·로그아웃·계정 전환 뒤 + 같은 입력의 저장은 새 key다. 서버 key 보관 기간이 지난 뒤의 재전송도 중복될 + 수 있다. 두 경우는 backend 도메인 유일성 제약이나 status 조회로 막는다. ### 6.4 Cursor loop — target v2 diff --git a/src/adapters/http/client.ts b/src/adapters/http/client.ts index 8f9a9225..f002ca4c 100644 --- a/src/adapters/http/client.ts +++ b/src/adapters/http/client.ts @@ -106,6 +106,11 @@ export type HttpClientDependencies = Readonly<{ payload: unknown, ) => MappingResult; idempotencyKeyFactory?: () => string; + /** + * Default total deadline for an operation without its own `timeoutMs`. Not a + * ceiling: an operation may set a longer one. V3 treats `REQUEST_TIMEOUT_MS` + * as a ceiling instead (03-06). + */ timeoutMs?: number; maxRetryAttempts?: number; scheduler?: Scheduler; diff --git a/src/adapters/http/feature-http-binding.ts b/src/adapters/http/feature-http-binding.ts index 4e083218..856265f8 100644 --- a/src/adapters/http/feature-http-binding.ts +++ b/src/adapters/http/feature-http-binding.ts @@ -9,6 +9,7 @@ import { type ApiFailure, type FailureEffectCertainty, type FailureKind, + type ValidationIssue, } from "../../contracts/errors.ts"; import type { MutationIntent } from "../../contracts/mutation-intent.ts"; import type { ExecutionContext } from "../../platform/execution/execution-context.ts"; @@ -73,6 +74,11 @@ export type InstalledHttpOperationExecutor = Readonly<{ export type FeatureHttpProblemMapping = Readonly<{ kind: FailureKind; code: string; + /** + * 03-04. Field issues read from the problem body. Only `path` and `code` + * survive; `createFailure` bounds them with `projectValidationIssues`. + */ + validationIssues?: readonly ValidationIssue[]; }>; type FeatureHttpOperationSpec< @@ -284,6 +290,10 @@ export function createFeatureHttpBinding< }); } +/** + * 03-03. A failure carries the server's echoed correlation id as `requestId`, + * so the support reference a user reports points at one server log entry. + */ function projectExecutionOutcome( operationId: string, mapSuccess: (value: WireOutput) => MappingResult, @@ -294,6 +304,30 @@ function projectExecutionOutcome( ) => FeatureHttpProblemMapping | undefined) | undefined, outcome: HttpExecutionOutcome, +): Result { + const projected = projectOutcome(operationId, mapSuccess, mapProblem, outcome); + const requestId = + "metadata" in outcome + ? outcome.metadata?.correlationReference + : undefined; + return projected.ok || requestId === undefined + ? projected + : Object.freeze({ + ok: false as const, + error: Object.freeze({ ...projected.error, requestId }), + }); +} + +function projectOutcome( + operationId: string, + mapSuccess: (value: WireOutput) => MappingResult, + mapProblem: + | (( + problem: Problem, + metadata: SafeResponseMetadata, + ) => FeatureHttpProblemMapping | undefined) + | undefined, + outcome: HttpExecutionOutcome, ): Result { // A throwing feature mapper is a mapping defect, not a transport failure: it // must not reject and lose the effect the server already confirmed. @@ -335,7 +369,13 @@ function projectExecutionOutcome( mapped?.kind ?? kindForStatus(outcome.metadata.status), operationId, mapped?.code ?? "CONTRACT_PROBLEM", - { httpStatus: outcome.metadata.status, effect: outcome.effect }, + { + httpStatus: outcome.metadata.status, + effect: outcome.effect, + ...(mapped?.validationIssues === undefined + ? {} + : { validationIssues: mapped.validationIssues }), + }, ); } case "UNAUTHENTICATED": @@ -442,6 +482,7 @@ function failure( httpStatus?: number; retryAfterMs?: number; effect?: FailureEffectCertainty; + validationIssues?: readonly ValidationIssue[]; }> = {}, ): Result { return Object.freeze({ diff --git a/src/adapters/http/http-effect-certainty.ts b/src/adapters/http/http-effect-certainty.ts index d008b707..0ad44c28 100644 --- a/src/adapters/http/http-effect-certainty.ts +++ b/src/adapters/http/http-effect-certainty.ts @@ -128,6 +128,28 @@ export function classifyProblemEffect( }); } +/** + * D-2. A dispatched command answered 401, 403 or 429 is `MAYBE_APPLIED` unless + * the package classifies that status as `NOT_APPLIED`. Any other answer, or a + * throw, fails safe to `MAYBE_APPLIED`. + */ +export function classifyStatusEffect( + descriptor: CommandEffectDescriptor | null, + status: 401 | 403 | 429, + abandoned: MutationEffectCertainty, +): MutationEffectCertainty { + if (abandoned !== "MAYBE_APPLIED" || !descriptor?.classifyStatus) { + return abandoned; + } + try { + return descriptor.classifyStatus(status) === "NOT_APPLIED" + ? "NOT_APPLIED" + : "MAYBE_APPLIED"; + } catch { + return "MAYBE_APPLIED"; + } +} + /** §8.10. Certainty to UI intent. The copy itself is owned by the i18n catalog. */ export function projectCertaintyToUi( certainty: MutationEffectCertainty, diff --git a/src/adapters/http/http-execution-v3.ts b/src/adapters/http/http-execution-v3.ts index 47138898..d5fd0e09 100644 --- a/src/adapters/http/http-execution-v3.ts +++ b/src/adapters/http/http-execution-v3.ts @@ -36,6 +36,7 @@ import { import { certaintyForAbandonedAttempt, classifyProblemEffect, + classifyStatusEffect, joinMutationEffectCertainty, type MutationEffectCertainty, type PhysicalAttemptState, @@ -52,7 +53,10 @@ import { } from "../../platform/traffic/concurrency-budget.ts"; import type { TrafficBudget } from "../../platform/traffic/traffic-budget.ts"; import { checkJsonStructure } from "../../platform/validation/bounded-json.ts"; -import { buildTraceHeaders } from "../../platform/telemetry/trace-context.ts"; +import { + buildTraceHeaders, + CORRELATION_ID_HEADER, +} from "../../platform/telemetry/trace-context.ts"; import { responseValidationBudget } from "../../platform/validation/validation-budget.ts"; import { canRetryTransport, @@ -143,11 +147,13 @@ export type HttpExecutionOutcome = }> | Readonly<{ kind: "FORBIDDEN"; + metadata?: SafeResponseMetadata; effect: "NOT_APPLICABLE" | "NOT_APPLIED" | "MAYBE_APPLIED"; }> | Readonly<{ kind: "RATE_LIMITED"; retryAfterMs?: number; + metadata?: SafeResponseMetadata; effect: "NOT_APPLICABLE" | "NOT_APPLIED" | "MAYBE_APPLIED"; }> | Readonly<{ @@ -266,6 +272,11 @@ export type HttpExecutionObservation = Readonly<{ durationMs: number; effect: HttpEffectCertainty; cancellationOwner?: CancellationOwner; + /** + * 03-03. The server's echoed `x-correlation-id`, else the request id this + * execution sent. Diagnostics only; never telemetry. + */ + correlationId?: string; /** * The internal terminal-reason label recorded by the execution site. It is * evidence for the HTTP scenario catalog only; the composition-root @@ -313,6 +324,14 @@ function observationStatus( return "metadata" in outcome ? outcome.metadata?.status : undefined; } +function responseCorrelation( + outcome: HttpExecutionOutcome, +): string | undefined { + return "metadata" in outcome + ? outcome.metadata?.correlationReference + : undefined; +} + export type ContractHttpExecutorDependencies = Readonly<{ baseUrl: string; /** §8.2. `MAX_RETRY_ATTEMPTS` from Runtime Config; the ceiling is still 2. */ @@ -344,6 +363,8 @@ export type ContractHttpExecutorDependencies = Readonly<{ monotonicNow?: () => number; sleep?: (ms: number, signal: AbortSignal) => Promise; random?: () => number; + /** 03-03. One id per logical execution, sent as `x-correlation-id`. */ + createRequestId?: () => string; observe?: (observation: HttpExecutionObservation) => void; }>; @@ -424,6 +445,8 @@ export function createContractHttpExecutor( dependencies.readBoundedResponseBytes ?? readBoundedBytes; const now = dependencies.monotonicNow ?? (() => performance.now()); const random = dependencies.random ?? Math.random; + const createRequestId = + dependencies.createRequestId ?? (() => globalThis.crypto.randomUUID()); const deadlineCeilingMs = dependencies.requestDeadlineCeilingMs; const effectiveDeadlineMs = (contractDeadlineMs: number): number => typeof deadlineCeilingMs === "number" && @@ -563,6 +586,7 @@ export function createContractHttpExecutor( lifetimeController.abort(); }; + let sentRequestId: string | undefined; const finish = ( outcome: HttpExecutionOutcome, terminalReason: string, @@ -570,6 +594,7 @@ export function createContractHttpExecutor( disposeLifetime(); try { const status = observationStatus(outcome); + const correlationId = responseCorrelation(outcome) ?? sentRequestId; dependencies.observe?.( Object.freeze({ routeId: context.routeId, @@ -585,6 +610,7 @@ export function createContractHttpExecutor( ...(terminalCancellation === null ? {} : { cancellationOwner: terminalCancellation }), + ...(correlationId === undefined ? {} : { correlationId }), }), ); } catch { @@ -788,6 +814,16 @@ export function createContractHttpExecutor( if (context.execution?.trace !== undefined) { Object.assign(headers, buildTraceHeaders(context.execution)); } + // 03-03. Every other logical execution still sends its own request id, + // shared by its retries, so a failure can be found in the server log. + if (headers[CORRELATION_ID_HEADER] === undefined) { + try { + headers[CORRELATION_ID_HEADER] = createRequestId(); + } catch { + // A diagnostic id never blocks the request (e.g. no secure context). + } + } + sentRequestId = headers[CORRELATION_ID_HEADER]; const retryCeiling = Math.min( policy.retryBudget, @@ -1142,23 +1178,25 @@ async function admitResponse( } const metadata = safeMetadata(response, retryAfterMs); + const statusEffect = (classified: 401 | 403 | 429) => + classifyStatusEffect( + contract.commandEffect, + classified, + certaintyForAbandonedAttempt(attemptState, isCommand), + ); if (!contract.acceptedStatuses.includes(status)) { if (status === 401) { await response.body?.cancel().catch(() => {}); return settled( - unauthenticated( - certaintyForAbandonedAttempt(attemptState, isCommand), - isCommand, - metadata, - ), + unauthenticated(statusEffect(401), isCommand, metadata), "UNAUTHENTICATED", ); } if (status === 403) { await response.body?.cancel().catch(() => {}); return settled( - forbidden(certaintyForAbandonedAttempt(attemptState, isCommand), isCommand), + forbidden(statusEffect(403), isCommand, metadata), "FORBIDDEN", ); } @@ -1168,10 +1206,8 @@ async function admitResponse( result: Object.freeze({ kind: "RATE_LIMITED" as const, ...(retryAfterMs === null ? {} : { retryAfterMs }), - effect: normalizeOptionalEffect( - certaintyForAbandonedAttempt(attemptState, isCommand), - isCommand, - ), + metadata, + effect: normalizeOptionalEffect(statusEffect(429), isCommand), }), certainty: "RATE_LIMITED", retryHint: true, @@ -1664,9 +1700,11 @@ function unauthenticated( function forbidden( effect: string, isCommand: boolean, + metadata: SafeResponseMetadata, ): HttpExecutionOutcome { return Object.freeze({ kind: "FORBIDDEN" as const, + metadata, effect: normalizeOptionalEffect(effect, isCommand), }); } diff --git a/src/adapters/telemetry/telemetry-collector.ts b/src/adapters/telemetry/telemetry-collector.ts index db74f0c7..d3bb2300 100644 --- a/src/adapters/telemetry/telemetry-collector.ts +++ b/src/adapters/telemetry/telemetry-collector.ts @@ -18,9 +18,9 @@ export type TelemetryCollector = Readonly<{ /** Spec §27. Shared by every queue posting to this collector. */ sendRate: TelemetrySendRate; /** - * POSTs `{ events }`. Rejects when the collector refuses the batch, the - * deadline passes, or `signal` aborts — a hung collector never stalls the - * caller's next flush. + * POSTs `{ events }`, split into bodies under the keepalive limit. Rejects + * when the collector refuses any part, the deadline passes, or `signal` + * aborts — a hung collector never stalls the caller's next flush. */ post(events: readonly unknown[], signal?: AbortSignal): Promise; /** Runs `flush` on `pagehide`. Returns the unsubscribe. */ @@ -37,6 +37,11 @@ export type TelemetryCollectorOptions = Readonly<{ /** Monotonic clock for the send-rate window (default `performance.now`). */ now?: () => number; lifecycle?: Pick; + /** + * 13-11. Stamped on every event as `build_id` and `release_id`, so a + * failure rate can be split by release while old and new tabs coexist. + */ + release?: Readonly<{ buildId: string; releaseId: string }>; }>; export const DEFAULT_TELEMETRY_SENDS_PER_MINUTE = 20; @@ -44,12 +49,49 @@ export const DEFAULT_TELEMETRY_TIMEOUT_MS = 10_000; /** Also bounds the send-time window the rate keeps in memory. */ const MAX_SENDS_PER_MINUTE = 10_000; const MAX_TIMEOUT_MS = 60_000; +/** + * 03-05. Fetch fails every keepalive request once the keepalive bodies in + * flight pass 64KiB. Bodies are split below that, and a body that would push + * this collector's in-flight keepalive total over the quota is sent without + * keepalive. A split batch still counts as one send against the rate. + */ +const KEEPALIVE_QUOTA_BYTES = 64 * 1024; +const MAX_BODY_BYTES = 60 * 1024; +const utf8 = new TextEncoder(); + +/** Same bytes as `JSON.stringify({ events })`, cut into bounded bodies. */ +function splitBodies(events: readonly unknown[]): string[] { + const envelopeBytes = '{"events":[]}'.length; + const bodies: string[] = []; + let items: string[] = []; + let itemBytes = 0; + const cut = () => { + bodies.push(`{"events":[${items.join(",")}]}`); + items = []; + itemBytes = 0; + }; + for (const event of events) { + const item = JSON.stringify(event) ?? "null"; + const bytes = utf8.encode(item).byteLength + 1; + if (items.length > 0 && envelopeBytes + itemBytes + bytes > MAX_BODY_BYTES) { + cut(); + } + items.push(item); + itemBytes += bytes; + } + if (items.length > 0 || bodies.length === 0) cut(); + return bodies; +} export function createTelemetryCollector( options: TelemetryCollectorOptions, ): TelemetryCollector { - const { endpoint } = options; + const { endpoint, release } = options; const fetcher = options.fetcher ?? fetch; + const stamp = (event: unknown): unknown => + release && event !== null && typeof event === "object" && !Array.isArray(event) + ? { ...event, build_id: release.buildId, release_id: release.releaseId } + : event; const timeoutMs = assertBoundedCapacity( options.timeoutMs ?? DEFAULT_TELEMETRY_TIMEOUT_MS, MAX_TIMEOUT_MS, @@ -74,10 +116,12 @@ export function createTelemetryCollector( for (const flush of [...exitFlushes]) flush(); }; - async function post( - events: readonly unknown[], - signal?: AbortSignal, - ): Promise { + let inflightKeepaliveBytes = 0; + + async function send(body: string, signal?: AbortSignal): Promise { + const bytes = utf8.encode(body).byteLength; + const keepalive = inflightKeepaliveBytes + bytes <= KEEPALIVE_QUOTA_BYTES; + if (keepalive) inflightKeepaliveBytes += bytes; const operation = createAbortableOperation({ ...(signal === undefined ? {} : { signal }), timeoutMs, @@ -88,8 +132,8 @@ export function createTelemetryCollector( fetcher(endpoint, { method: "POST", headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ events }), - keepalive: true, + body, + keepalive, credentials: "omit", cache: "no-store", signal: operation.signal, @@ -101,9 +145,20 @@ export function createTelemetryCollector( } } finally { operation.close(); + if (keepalive) inflightKeepaliveBytes -= bytes; } } + async function post( + events: readonly unknown[], + signal?: AbortSignal, + ): Promise { + // Sent together so a page-exit flush dispatches every part at once. + await Promise.all( + splitBodies(events.map(stamp)).map((body) => send(body, signal)), + ); + } + return Object.freeze({ sendRate, post, diff --git a/src/bootstrap/runtime-adapters.ts b/src/bootstrap/runtime-adapters.ts index 2025e0ed..87bdfbdf 100644 --- a/src/bootstrap/runtime-adapters.ts +++ b/src/bootstrap/runtime-adapters.ts @@ -246,6 +246,10 @@ export function createHttpObservationProjector( ...safeAttributes, operation: observation.diagnosticsOperation, outcome: observation.outcome, + // 03-03. Request-scoped: diagnostics may carry it, telemetry never. + ...(observation.correlationId === undefined + ? {} + : { correlation_id: observation.correlationId }), }, }); } catch { @@ -281,6 +285,13 @@ function isTerminalNonAbortFailure( ): boolean { if (observation.outcome === "SUCCESS") return false; if (observation.outcome === "CANCELLED") return false; + // 03-07. No credential, nothing sent: a client state, not an API failure. + if ( + observation.outcome === "UNAUTHENTICATED" && + observation.status === undefined + ) { + return false; + } if ( observation.cancellationOwner !== undefined && CALLER_OWNED_CANCELLATION.has(observation.cancellationOwner) @@ -315,6 +326,10 @@ export async function createRuntimeAdapters( ? createTelemetryCollector({ endpoint: config.TELEMETRY_ENDPOINT, ...(context.fetcher === undefined ? {} : { fetcher: context.fetcher }), + release: { + buildId: context.release.buildId, + releaseId: context.release.releaseId, + }, }) : undefined; const telemetry = createTelemetryAdapter({ diff --git a/src/contracts/errors.ts b/src/contracts/errors.ts index 3fc3e571..86873b98 100644 --- a/src/contracts/errors.ts +++ b/src/contracts/errors.ts @@ -314,13 +314,21 @@ export function createFailure( userMessageKey: definition.userMessageKey, action: details.effect === "MAYBE_APPLIED" - ? "contact-support" + ? unknownEffectAction(definition.action) : details.effect === "APPLIED_CONFIRMED" ? "none" : definition.action, }); } +/** + * D-2. An unknown effect sends the user to support, except when the session + * itself is the problem: signing in again comes first either way. + */ +function unknownEffectAction(action: ErrorAction): ErrorAction { + return action === "reauth" ? "reauth" : "contact-support"; +} + /** * Adds controller-owned mutation effect knowledge without weakening the * fail-safe handling required for an unknown server-side outcome. @@ -333,7 +341,7 @@ export function withFailureEffect( ...failure, effect, ...(effect === "MAYBE_APPLIED" - ? { retryable: false as const, action: "contact-support" as const } + ? { retryable: false as const, action: unknownEffectAction(failure.action) } : effect === "APPLIED_CONFIRMED" ? { retryable: false as const, action: "none" as const } : {}), diff --git a/src/contracts/external-contract-runtime.ts b/src/contracts/external-contract-runtime.ts index 671eaa7b..ca930d11 100644 --- a/src/contracts/external-contract-runtime.ts +++ b/src/contracts/external-contract-runtime.ts @@ -123,6 +123,12 @@ export interface CommandEffectDescriptor { classifyProblem( input: Readonly<{ status: number; problem: Problem }>, ): CommandEffectClassification; + /** + * D-2. 401, 403 and 429 are admitted by status before any problem body is + * read. Declare `NOT_APPLIED` only when the server contract guarantees the + * command was rejected untouched. Without this, they stay `MAYBE_APPLIED`. + */ + classifyStatus?(status: 401 | 403 | 429): "NOT_APPLIED" | "MAYBE_APPLIED"; } export type HttpMethod = @@ -470,6 +476,12 @@ function assertHttpContract( if (typeof contract.commandEffect.classifyProblem !== "function") { fail(`${label}: command effect classifier is required`); } + if ( + contract.commandEffect.classifyStatus !== undefined && + typeof contract.commandEffect.classifyStatus !== "function" + ) { + fail(`${label}: command status classifier must be a function`); + } if (contract.retrySemantics === "KEYED" && !contract.commandRecovery) { fail(`${label}: KEYED commands require a recovery descriptor`); } diff --git a/src/features/reference-feature/adapters/reference-http-gateway.ts b/src/features/reference-feature/adapters/reference-http-gateway.ts index 37a5c1fb..12ebc8f4 100644 --- a/src/features/reference-feature/adapters/reference-http-gateway.ts +++ b/src/features/reference-feature/adapters/reference-http-gateway.ts @@ -45,6 +45,7 @@ export const REFERENCE_HTTP_OPERATIONS = Object.freeze({ return Object.freeze({ kind: "VALIDATION_REJECTED" as const, code: problem.code ?? "REFERENCE_RESOURCE_REJECTED", + validationIssues: problem.issues ?? [], }); } return undefined; diff --git a/src/features/reference-feature/contracts/reference-feature-contract-contribution.ts b/src/features/reference-feature/contracts/reference-feature-contract-contribution.ts index 48985218..0f38d803 100644 --- a/src/features/reference-feature/contracts/reference-feature-contract-contribution.ts +++ b/src/features/reference-feature/contracts/reference-feature-contract-contribution.ts @@ -44,6 +44,11 @@ const CREATE_EFFECT: CommandEffectDescriptor = Object.freeze({ } return "MAYBE_APPLIED"; }, + /** + * D-2. The reference backend rejects an unauthenticated, forbidden or + * rate-limited create before touching state. + */ + classifyStatus: () => "NOT_APPLIED" as const, }); export const LIST_REFERENCE_RESOURCES_CONTRACT = Object.freeze({ diff --git a/src/features/reference-feature/contracts/reference-schemas.ts b/src/features/reference-feature/contracts/reference-schemas.ts index 62372639..0d24d33d 100644 --- a/src/features/reference-feature/contracts/reference-schemas.ts +++ b/src/features/reference-feature/contracts/reference-schemas.ts @@ -44,6 +44,18 @@ export const referenceProblemSchema = z title: z.string().min(1).max(240), status: z.int().min(100).max(599), code: z.string().min(1).max(120).optional(), + /** 03-04. 422 field issues; backend messages are stripped. */ + issues: z + .array( + z + .object({ + path: z.string().min(1).max(120), + code: z.string().min(1).max(80), + }) + .strip(), + ) + .max(50) + .optional(), }) .strip(); 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 599bdd6e..80bec0f4 100644 --- a/src/features/reference-feature/presentation/reference-resource-form-page.tsx +++ b/src/features/reference-feature/presentation/reference-resource-form-page.tsx @@ -1,5 +1,5 @@ import { useCallback } from "react"; -import { useNavigate } from "react-router-dom"; +import { Link, useNavigate } from "react-router-dom"; import { Button, @@ -8,17 +8,21 @@ import { ErrorSummary, Form, FormActions, + FormFailureStatus, FormPage, FormField, useAppForm, useDirtyNavigationGuard, } from "../../../presentation/design-system/index.ts"; +import { useQueryInvalidationCoordinator } from "../../../presentation/adapters/query/query-invalidation-provider.tsx"; +import { REFERENCE_RESOURCE_INVALIDATION_TOPIC } from "../contracts/reference-feature-contract.ts"; import { REFERENCE_FORM_DEFAULTS, referenceResourceFormSchema, toCreateReferenceCommand, type ReferenceResourceFormValues, } from "./reference-resource-form.ts"; +import { useReferenceFailureAction } from "./use-reference-failure-action.ts"; import { useReferenceCreate } from "./use-reference-feature.ts"; const FIELD_LABELS = Object.freeze({ @@ -29,6 +33,7 @@ const FIELD_LABELS = Object.freeze({ export default function ReferenceResourceFormPage() { const navigate = useNavigate(); const mutation = useReferenceCreate(); + const invalidation = useQueryInvalidationCoordinator(); const submit = useCallback( (command: ReturnType) => mutation.submit(command), @@ -41,6 +46,7 @@ export default function ReferenceResourceFormPage() { mapToCommand: toCreateReferenceCommand, submit, }); + const failureAction = useReferenceFailureAction(form.failure ?? undefined); const mutationEffectUnknown = mutation.state.indicator === "mutation-effect-unknown"; const mutationBlocked = @@ -126,19 +132,41 @@ export default function ReferenceResourceFormPage() { } feedback={ - mutationEffectUnknown ? ( - { - void mutation.reconcileUnknownEffect(resolution).then(() => { - if (resolution === "APPLIED") { - form.settleApplied(); - } else { - form.settleNotApplied(); - } - }); - }} + form.failure ? ( + void form.submitForm() + : failureAction + } /> + ) : mutationEffectUnknown ? ( + <> + { + void mutation + .reconcileUnknownEffect(resolution) + .then(form.settleApplied); + }} + onResendUnknownEffect={() => { + void form.resendUnknown(mutation.resendUnknownEffect); + }} + /> +

+ { + void invalidation + ?.invalidate([REFERENCE_RESOURCE_INVALIDATION_TOPIC]) + .catch(() => {}); + }} + > + 목록을 새로 불러와 확인 + +

+ ) : form.result === "success" ? (

저장했습니다.

) : form.result === "conflict" ? ( diff --git a/src/presentation/adapters/query/application-query.ts b/src/presentation/adapters/query/application-query.ts index 696869f0..c747c916 100644 --- a/src/presentation/adapters/query/application-query.ts +++ b/src/presentation/adapters/query/application-query.ts @@ -219,9 +219,19 @@ type ApplicationMutationController = Readonly<{ state: AsyncState; submit(input: Input): Promise>; resolveConflict(): Promise; + /** + * Settles the oldest unknown effect. `NOT_APPLIED` needs evidence (an + * inspect operation or a server read); without it, resend instead. + */ reconcileUnknownEffect( resolution: "APPLIED" | "NOT_APPLIED", ): Promise; + /** + * D-1. Sends the oldest unknown-effect request again with its original + * intent, so a keyed command carries the same `Idempotency-Key`. Resolves + * to `null` when nothing is waiting to be resent. + */ + resendUnknownEffect(): Promise | null>; }>; type MutationExecution = @@ -231,7 +241,10 @@ type MutationExecution = type MutationAdmission = { sequence: number; state: "ACTIVE" | "UNKNOWN" | "RECONCILING" | "SETTLED"; + readonly input: unknown; intent: MutationIntent | null; + /** Held while UNKNOWN so the same input keeps the same identity token. */ + identityLease: Readonly<{ release(): void }> | null; scope: CacheScopeSnapshot | null; optimisticLayer: OptimisticLayerLease | null; optimisticQueryKey: readonly unknown[] | null; @@ -486,10 +499,19 @@ export function useApplicationMutation( ), }); } + // D-1. Saving the same canonical input again is the same logical + // request: it reuses the unknown admission's intent (and key). + const replayed = unknownEffectChannel.admissions.find( + (candidate) => + candidate.state === "UNKNOWN" && + candidate.intent?.canonicalInputIdentity === identity, + ); const admission: MutationAdmission = { sequence: unknownEffectChannel.nextSequence++, state: "ACTIVE", + input, intent: null, + identityLease: null, scope: scope ?? null, optimisticLayer: null, optimisticQueryKey: optimistic?.queryKey ?? null, @@ -498,6 +520,12 @@ export function useApplicationMutation( }; unknownEffectChannel.admissions.push(admission); unknownEffectChannel.registry.activeAdmissions += 1; + if (replayed) { + // The new attempt re-applies its own optimistic layer and owns the + // outcome from here. + replayed.optimisticLayer?.reconcile("NOT_APPLIED"); + settleMutationAdmission(unknownEffectChannel, replayed); + } notifyUnknownEffectChannel(unknownEffectChannel); setConflict(null); mutation.reset(); @@ -506,11 +534,13 @@ export function useApplicationMutation( const pending = (async (): Promise> => { let execution: MutationExecution; if (scope) { - const intent = mutationIntentFactory.create({ - operationId: mutationOperationId, - canonicalInputIdentity: identity, - requiresIdempotencyKey, - }); + const intent = + replayed?.intent ?? + mutationIntentFactory.create({ + operationId: mutationOperationId, + canonicalInputIdentity: identity, + requiresIdempotencyKey, + }); admission.intent = intent; execution = Object.freeze({ kind: "BOUND", input, intent }); } else { @@ -572,6 +602,10 @@ export function useApplicationMutation( optimisticLayer?.markUncertain(); if (!scope || scope.isCurrent()) { admission.state = "UNKNOWN"; + if (identityLease) { + identityLease.acquire(); + admission.identityLease = identityLease; + } notifyUnknownEffectChannel(unknownEffectChannel); } else { settleMutationAdmission(unknownEffectChannel, admission); @@ -699,6 +733,19 @@ export function useApplicationMutation( [mutation, queryClient, unknownEffectChannel], ); + const resendUnknownEffect = useCallback(async () => { + const head = unknownEffectChannel?.admissions[0]; + if ( + !head || + head.state !== "UNKNOWN" || + !head.intent || + unknownEffectChannel?.reconciliationInFlight + ) { + return null; + } + return submit(head.input as Input); + }, [submit, unknownEffectChannel]); + const unknownEffectHead = unknownEffectChannel?.admissions[0]; return Object.freeze({ @@ -714,6 +761,7 @@ export function useApplicationMutation( submit, resolveConflict, reconcileUnknownEffect, + resendUnknownEffect, }); } @@ -822,6 +870,8 @@ function markMutationAdmissionSettled( ): void { if (admission.state === "SETTLED") return; admission.state = "SETTLED"; + admission.identityLease?.release(); + admission.identityLease = null; channel.registry.activeAdmissions = Math.max( 0, channel.registry.activeAdmissions - 1, diff --git a/src/presentation/components/async-surface.tsx b/src/presentation/components/async-surface.tsx index 08bde41e..e551e43b 100644 --- a/src/presentation/components/async-surface.tsx +++ b/src/presentation/components/async-surface.tsx @@ -55,12 +55,15 @@ export type TerminalErrorSurfaceProps = Readonly<{ userMessageKey: string; action: AppFailure["action"]; onAction?: () => void; + /** Read before the action, inside the same alert. */ + description?: string; }>; export function TerminalErrorSurface({ userMessageKey, action, onAction, + description, }: TerminalErrorSurfaceProps) { const { locale, message } = useLocale(); const messageId = useId(); @@ -81,6 +84,7 @@ export function TerminalErrorSurface({ data-message-key={userMessageKey} >

{errorMessage(userMessageKey, locale)}

+ {description ?

{description}

: null} {action !== "none" && onAction && ( )} @@ -96,9 +100,10 @@ export type AsyncSurfaceProps = Readonly<{ onAction?: () => void; onRetry?: () => void; onResolveConflict?: () => void; - onReconcileUnknownEffect?: ( - resolution: "APPLIED" | "NOT_APPLIED", - ) => void; + /** Only `APPLIED` is offered: "not applied" needs evidence the UI lacks. */ + onReconcileUnknownEffect?: (resolution: "APPLIED") => void; + /** D-1. Resends the unknown request with its original intent and key. */ + onResendUnknownEffect?: () => void; }>; export function AsyncSurface({ @@ -109,6 +114,7 @@ export function AsyncSurface({ onRetry, onResolveConflict, onReconcileUnknownEffect, + onResendUnknownEffect, }: AsyncSurfaceProps) { const { message } = useLocale(); if (state.base === "idle") return idle ?? null; @@ -155,18 +161,15 @@ export function AsyncSurface({ ) : null} {state.indicator === "mutation-effect-unknown" && onReconcileUnknownEffect ? ( - <> - - - + + ) : null} + {state.indicator === "mutation-effect-unknown" && + onResendUnknownEffect ? ( + ) : null} ) : null} diff --git a/src/presentation/design-system/index.ts b/src/presentation/design-system/index.ts index 3467658e..5a519cf4 100644 --- a/src/presentation/design-system/index.ts +++ b/src/presentation/design-system/index.ts @@ -136,6 +136,7 @@ export { ErrorSummary, Form, FormActions, + FormFailureStatus, FormField, useAppForm, useDirtyNavigationGuard, diff --git a/src/presentation/forms/form-components.tsx b/src/presentation/forms/form-components.tsx index 16bc9b8e..f87d771f 100644 --- a/src/presentation/forms/form-components.tsx +++ b/src/presentation/forms/form-components.tsx @@ -1,5 +1,7 @@ import { useId, type FormHTMLAttributes, type ReactNode } from "react"; +import type { AppFailure } from "../../contracts/errors.ts"; +import { TerminalErrorSurface } from "../components/async-surface.tsx"; import { TextField } from "../components/ui/text-field.ts"; import { useLocale } from "../i18n/index.ts"; import type { @@ -78,6 +80,33 @@ export function ErrorSummary(props: Readonly<{ ); } +/** + * 08-01. A save that failed for a reason other than the input (sign-in, + * permission, retry later) is announced here with its own action, not in + * ErrorSummary. Pass `useAppForm().failure`. + */ +export function FormFailureStatus(props: Readonly<{ + failure: AppFailure | null; + onAction?: () => void; +}>) { + const { message } = useLocale(); + const { failure, onAction } = props; + if (!failure) return null; + return ( + + ); +} + export function FormActions(props: Readonly<{ children: ReactNode; sticky?: boolean; diff --git a/src/presentation/forms/form-contracts.ts b/src/presentation/forms/form-contracts.ts index cdc1581d..c432ef1b 100644 --- a/src/presentation/forms/form-contracts.ts +++ b/src/presentation/forms/form-contracts.ts @@ -19,6 +19,10 @@ export type FormResultState = | "validation-error" | "conflict" | "effect-unknown" + /** 08-01. Not input errors: shown by `FormFailureStatus`, never ErrorSummary. */ + | "reauth-required" + | "forbidden" + | "retry-later" | "unavailable"; export type MappedValidationFailure = Readonly<{ diff --git a/src/presentation/forms/use-app-form.ts b/src/presentation/forms/use-app-form.ts index bf389ab3..5a4e00a8 100644 --- a/src/presentation/forms/use-app-form.ts +++ b/src/presentation/forms/use-app-form.ts @@ -9,6 +9,7 @@ import { } from "react"; import { flushSync } from "react-dom"; import type { ZodType, ZodIssue } from "zod"; +import type { AppFailure } from "../../contracts/errors.ts"; import { useLocale, type ParameterlessMessageKey, @@ -64,6 +65,7 @@ export function useAppForm< const [formErrors, setFormErrors] = useState([]); const [pending, setPending] = useState(false); const [result, setResult] = useState("idle"); + const [statusFailure, setStatusFailure] = useState(null); const pendingRef = useRef | null> | null>(null); const unknownSubmissionRef = useRef(null); @@ -175,6 +177,60 @@ export function useAppForm< setResult("idle"); }, []); + const applyOutcome = useCallback( + (outcome: FormResult, submittedValues: Values) => { + if (outcome.ok) { + settleSuccessfulValues(submittedValues); + return; + } + if (outcome.error.kind === "VALIDATION_REJECTED") { + unknownSubmissionRef.current = null; + const mapped = mapValidationFailureToFields( + outcome.error, + allowedServerFields, + message, + ); + setFieldErrors(mapped.fieldErrors); + setFormErrors(mapped.formErrors); + setResult("validation-error"); + focusFirstError(mapped.fieldErrors); + } else if (outcome.error.action === "reauth") { + // D-2. Signing in again comes first, whatever the effect. + unknownSubmissionRef.current = null; + setFormErrors([]); + setStatusFailure(outcome.error); + setResult("reauth-required"); + } else if (outcome.error.effect === "MAYBE_APPLIED") { + unknownSubmissionRef.current = submittedValues; + setFormErrors([]); + setResult("effect-unknown"); + } else if (outcome.error.effect === "APPLIED_CONFIRMED") { + settleSuccessfulValues(submittedValues); + } else if (outcome.error.kind === "CONFLICT") { + unknownSubmissionRef.current = null; + setFormErrors([ + message("form.conflict"), + ]); + setResult("conflict"); + } else if ( + outcome.error.kind === "FORBIDDEN" || + outcome.error.action === "retry" + ) { + unknownSubmissionRef.current = null; + setFormErrors([]); + setStatusFailure(outcome.error); + setResult( + outcome.error.kind === "FORBIDDEN" ? "forbidden" : "retry-later", + ); + } else { + unknownSubmissionRef.current = null; + setFormErrors([message("form.unavailable")]); + setResult("unavailable"); + } + }, + [allowedServerFields, focusFirstError, message, settleSuccessfulValues], + ); + const validateAndSubmit = useCallback( async (): Promise | null> => { setFieldErrors({} as FieldErrors); @@ -205,38 +261,7 @@ export function useAppForm< setPending(true); try { const outcome = await submit(command); - if (outcome.ok) { - settleSuccessfulValues(parsed.data); - return outcome; - } - if (outcome.error.kind === "VALIDATION_REJECTED") { - unknownSubmissionRef.current = null; - const mapped = mapValidationFailureToFields( - outcome.error, - allowedServerFields, - message, - ); - setFieldErrors(mapped.fieldErrors); - setFormErrors(mapped.formErrors); - setResult("validation-error"); - focusFirstError(mapped.fieldErrors); - } else if (outcome.error.effect === "MAYBE_APPLIED") { - unknownSubmissionRef.current = parsed.data; - setFormErrors([]); - setResult("effect-unknown"); - } else if (outcome.error.effect === "APPLIED_CONFIRMED") { - settleSuccessfulValues(parsed.data); - } else if (outcome.error.kind === "CONFLICT") { - unknownSubmissionRef.current = null; - setFormErrors([ - message("form.conflict"), - ]); - setResult("conflict"); - } else { - unknownSubmissionRef.current = null; - setFormErrors([message("form.unavailable")]); - setResult("unavailable"); - } + applyOutcome(outcome, parsed.data); return outcome; } finally { setPending(false); @@ -244,11 +269,11 @@ export function useAppForm< }, [ allowedServerFields, + applyOutcome, focusFirstError, mapToCommand, message, schema, - settleSuccessfulValues, submit, values, ], @@ -270,6 +295,37 @@ export function useAppForm< [validateAndSubmit], ); + /** + * D-1. Runs a resend of the unknown submission (for example + * `mutation.resendUnknownEffect`) through the same outcome handling as a + * submit. The form never builds a new command here: the caller resends the + * original request with its original key. + */ + const resendUnknown = useCallback( + ( + send: () => Promise | null>, + ): Promise | null> => { + if (pendingRef.current) return pendingRef.current; + // After a remount the form no longer holds the submitted values. + const submittedValues = unknownSubmissionRef.current ?? values; + const resend = (async () => { + setPending(true); + try { + const outcome = await send(); + if (outcome) applyOutcome(outcome, submittedValues); + return outcome; + } finally { + setPending(false); + } + })().finally(() => { + pendingRef.current = null; + }); + pendingRef.current = resend; + return resend; + }, + [applyOutcome, values], + ); + return Object.freeze({ formId, values, @@ -279,17 +335,26 @@ export function useAppForm< formErrors, pending, result, + /** The save failure behind `reauth-required`, `forbidden` or `retry-later`. */ + failure: STATUS_RESULTS.has(result) ? statusFailure : null, field, fieldId, focusField, setValue, submitForm, + resendUnknown, reset, settleApplied, settleNotApplied, }); } +const STATUS_RESULTS: ReadonlySet = new Set([ + "reauth-required", + "forbidden", + "retry-later", +]); + function issuesToFieldErrors( issues: readonly ZodIssue[], allowedFields: readonly FieldName[], diff --git a/src/presentation/i18n/catalog.ts b/src/presentation/i18n/catalog.ts index 9bf90c7c..6ec1a18c 100644 --- a/src/presentation/i18n/catalog.ts +++ b/src/presentation/i18n/catalog.ts @@ -12,7 +12,7 @@ const PLATFORM_KO_MESSAGES = { "action.contactSupport": "지원 정보 확인", "action.resolveConflict": "충돌 해결", "action.confirmMutationApplied": "변경됨으로 확인", - "action.confirmMutationNotApplied": "변경되지 않음으로 확인", + "action.resendMutation": "같은 요청으로 다시 보내기", "action.continueEditing": "계속 작성", "action.discardAndLeave": "변경 버리고 이동", "action.signIn": "로그인 시작", @@ -125,6 +125,8 @@ const PLATFORM_KO_MESSAGES = { "form.conflict": "다른 변경과 충돌했습니다. 입력은 유지되었으니 최신 상태를 확인해 주세요.", "form.unavailable": "저장하지 못했습니다. 잠시 후 다시 시도해 주세요.", + "form.reauthLosesInput": + "다시 로그인하면 이 화면에 입력한 내용은 사라집니다. 필요하면 먼저 복사해 두세요.", "form.remaining": "{count}자 남음", "toast.region": "알림", "error.network_unreachable": "네트워크에 연결할 수 없습니다.", @@ -171,7 +173,7 @@ const PLATFORM_EN_MESSAGES = { "action.contactSupport": "View support information", "action.resolveConflict": "Resolve conflict", "action.confirmMutationApplied": "Confirm the change was applied", - "action.confirmMutationNotApplied": "Confirm the change was not applied", + "action.resendMutation": "Send the same request again", "action.continueEditing": "Continue editing", "action.discardAndLeave": "Discard and leave", "action.signIn": "Start sign-in", @@ -283,6 +285,8 @@ const PLATFORM_EN_MESSAGES = { "form.conflict": "Another update conflicts with this change. Your input has been preserved.", "form.unavailable": "The change could not be saved. Try again shortly.", + "form.reauthLosesInput": + "Signing in again clears what you entered on this page. Copy it first if you need it.", "form.remaining": "{count} characters remaining", "toast.region": "Notifications", "error.network_unreachable": "The network is unavailable.", diff --git a/tests/component/application-mutation-admission.test.tsx b/tests/component/application-mutation-admission.test.tsx index 64d7c43e..d569e635 100644 --- a/tests/component/application-mutation-admission.test.tsx +++ b/tests/component/application-mutation-admission.test.tsx @@ -8,6 +8,9 @@ import { useApplicationMutation, } from "../../src/presentation/adapters/query/application-query.ts"; import type { MutationIntentFactory } from "../../src/application/ports/mutation-intent-factory.ts"; +import { createFailure } from "../../src/contracts/errors.ts"; +import type { MutationIntent } from "../../src/contracts/mutation-intent.ts"; +import { createRuntimeIdentityRegistry } from "../../src/contracts/query-keys.ts"; import { MUTATION_COORDINATOR_BOUNDS } from "../../src/contracts/server-state.ts"; import { RESOURCE_INVALIDATION_TOPIC, @@ -371,4 +374,124 @@ describe("application mutation intent admission", () => { }); }); + describe("unknown-effect replay (D-1)", () => { + function replayScope() { + let token = 0; + return { + ...scopeSnapshot(), + identities: createRuntimeIdentityRegistry({ + tokenFactory: () => `replay-identity-token-${String(++token).padStart(4, "0")}`, + }), + }; + } + + function renderKeyedCreate( + outcomes: ApplicationResult[], + ) { + const client = queryClient(); + const intents: MutationIntent[] = []; + const execute = vi.fn( + async ( + input: string, + context: Readonly<{ signal: AbortSignal; intent: MutationIntent }>, + ): Promise> => { + intents.push(context.intent); + return outcomes.shift() ?? { ok: true, value: input }; + }, + ); + const scope = replayScope(); + const hook = renderHook( + () => + useApplicationMutation({ + definitionId: "replay-intent-v1", + definitionVersion: 1, + operationId: "CREATE_REPLAYED", + requiresIdempotencyKey: true, + owner: "platform-test", + duplicatePolicy: "REJECT_WHILE_ACTIVE", + scope, + execute, + invalidate: [], + }), + { wrapper: wrapper(client) }, + ); + return { hook, intents, execute }; + } + + const unknown: ApplicationResult = { + ok: false, + error: createFailure("SERVER_FAILURE", "CREATE_REPLAYED", 0, { + effect: "MAYBE_APPLIED", + }), + }; + + it("sends the same intent when the same input is saved again after an unknown effect", async () => { + const { hook, intents } = renderKeyedCreate([unknown]); + await act(() => hook.result.current.submit("same-input")); + expect(hook.result.current.state.indicator).toBe( + "mutation-effect-unknown", + ); + + await act(() => hook.result.current.submit("same-input")); + + expect(intents).toHaveLength(2); + expect(intents[1]).toBe(intents[0]); + expect(intents[1]?.idempotencyKey).toBe("key-1"); + await waitFor(() => + expect(hook.result.current.state.indicator).toBeNull(), + ); + }); + + it("mints a new key when the input changes after an unknown effect", async () => { + const { hook, intents } = renderKeyedCreate([unknown]); + await act(() => hook.result.current.submit("first-input")); + await act(() => hook.result.current.submit("changed-input")); + + expect(intents.map((intent) => intent.idempotencyKey)).toEqual([ + "key-1", + "key-2", + ]); + // The first request is still unresolved; a different request cannot + // settle it. + expect(hook.result.current.state.indicator).toBe( + "mutation-effect-unknown", + ); + }); + + it("resends the unknown head request with its original key", async () => { + const { hook, intents, execute } = renderKeyedCreate([unknown, unknown]); + await act(() => hook.result.current.submit("resent-input")); + + let resent: ApplicationResult | null | undefined; + await act(async () => { + resent = await hook.result.current.resendUnknownEffect(); + }); + expect(resent).toMatchObject({ + ok: false, + error: { effect: "MAYBE_APPLIED" }, + }); + await act(async () => { + resent = await hook.result.current.resendUnknownEffect(); + }); + + expect(resent).toEqual({ ok: true, value: "resent-input" }); + expect(execute.mock.calls.map(([input]) => input)).toEqual([ + "resent-input", + "resent-input", + "resent-input", + ]); + expect(new Set(intents.map((intent) => intent.idempotencyKey))).toEqual( + new Set(["key-1"]), + ); + await waitFor(() => + expect(hook.result.current.state.indicator).toBeNull(), + ); + // Nothing is left to resend once the effect is settled. + await act(async () => { + resent = await hook.result.current.resendUnknownEffect(); + }); + expect(resent).toBeNull(); + expect(execute).toHaveBeenCalledTimes(3); + }); + }); }); diff --git a/tests/component/async-surface.test.tsx b/tests/component/async-surface.test.tsx index 24d1ddd0..7cb44269 100644 --- a/tests/component/async-surface.test.tsx +++ b/tests/component/async-surface.test.tsx @@ -53,10 +53,11 @@ describe("async UI state matrix", () => { }); }); - it("renders unknown mutation effects with reconciliation-only actions", async () => { + it("renders unknown mutation effects with confirm-applied and resend only", async () => { const user = userEvent.setup(); const retry = vi.fn(); const reconcile = vi.fn(); + const resend = vi.fn(); const state = deriveAsyncState({ data: ["value"], hasMutationEffectUnknown: true, @@ -67,6 +68,7 @@ describe("async UI state matrix", () => { state={state} onRetry={retry} onReconcileUnknownEffect={reconcile} + onResendUnknownEffect={resend} > existing content
, @@ -81,12 +83,15 @@ describe("async UI state matrix", () => { expect( screen.queryByRole("button", { name: "다시 시도" }), ).not.toBeInTheDocument(); + expect( + screen.queryByRole("button", { name: "변경되지 않음으로 확인" }), + ).not.toBeInTheDocument(); await user.click(screen.getByRole("button", { name: "변경됨으로 확인" })); await user.click( - screen.getByRole("button", { name: "변경되지 않음으로 확인" }), + screen.getByRole("button", { name: "같은 요청으로 다시 보내기" }), ); - expect(reconcile).toHaveBeenNthCalledWith(1, "APPLIED"); - expect(reconcile).toHaveBeenNthCalledWith(2, "NOT_APPLIED"); + expect(reconcile).toHaveBeenCalledExactlyOnceWith("APPLIED"); + expect(resend).toHaveBeenCalledOnce(); expect(retry).not.toHaveBeenCalled(); }); diff --git a/tests/component/form-foundation.test.tsx b/tests/component/form-foundation.test.tsx index 1711148d..a91113f8 100644 --- a/tests/component/form-foundation.test.tsx +++ b/tests/component/form-foundation.test.tsx @@ -13,6 +13,7 @@ import { DirtyNavigationDialog, ErrorSummary, Form, + FormFailureStatus, FormField, useAppForm, useDirtyNavigationGuard, @@ -34,6 +35,7 @@ function FormHarness(props: Readonly<{ | Readonly<{ ok: false; error: ReturnType }> >; resetOnSuccess?: boolean; + onFailureAction?(): void; }>) { const form = useAppForm({ schema, @@ -57,6 +59,14 @@ function FormHarness(props: Readonly<{ fieldId={form.fieldId} onFocusField={form.focusField} /> + void form.submitForm() + : props.onFailureAction + } + />