Merge lane C: HTTP, server state, auth and telemetry fixes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+3
@@ -635,6 +635,7 @@ export interface CommandEffectDescriptor<Problem> {
|
||||
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<Problem> {
|
||||
- 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
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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 도입 조건
|
||||
|
||||
|
||||
@@ -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로
|
||||
|
||||
@@ -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를 방해하지 않음
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -106,6 +106,11 @@ export type HttpClientDependencies = Readonly<{
|
||||
payload: unknown,
|
||||
) => MappingResult<unknown>;
|
||||
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;
|
||||
|
||||
@@ -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<WireOutput, Problem, Value>(
|
||||
operationId: string,
|
||||
mapSuccess: (value: WireOutput) => MappingResult<Value>,
|
||||
@@ -294,6 +304,30 @@ function projectExecutionOutcome<WireOutput, Problem, Value>(
|
||||
) => FeatureHttpProblemMapping | undefined)
|
||||
| undefined,
|
||||
outcome: HttpExecutionOutcome<WireOutput, Problem>,
|
||||
): Result<Value, ApiFailure> {
|
||||
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<WireOutput, Problem, Value>(
|
||||
operationId: string,
|
||||
mapSuccess: (value: WireOutput) => MappingResult<Value>,
|
||||
mapProblem:
|
||||
| ((
|
||||
problem: Problem,
|
||||
metadata: SafeResponseMetadata,
|
||||
) => FeatureHttpProblemMapping | undefined)
|
||||
| undefined,
|
||||
outcome: HttpExecutionOutcome<WireOutput, Problem>,
|
||||
): Result<Value, ApiFailure> {
|
||||
// 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<WireOutput, Problem, Value>(
|
||||
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<never, ApiFailure> {
|
||||
return Object.freeze({
|
||||
|
||||
@@ -128,6 +128,28 @@ export function classifyProblemEffect<Problem>(
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<Problem>(
|
||||
descriptor: CommandEffectDescriptor<Problem> | 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,
|
||||
|
||||
@@ -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<Value, Problem> =
|
||||
}>
|
||||
| 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<unknown, unknown>,
|
||||
): 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<void>;
|
||||
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<WireOutput, Problem>,
|
||||
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<Input, WireOutput, Problem>(
|
||||
}
|
||||
|
||||
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<Input, WireOutput, Problem>(
|
||||
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<Value, Problem>(
|
||||
function forbidden<Value, Problem>(
|
||||
effect: string,
|
||||
isCommand: boolean,
|
||||
metadata: SafeResponseMetadata,
|
||||
): HttpExecutionOutcome<Value, Problem> {
|
||||
return Object.freeze({
|
||||
kind: "FORBIDDEN" as const,
|
||||
metadata,
|
||||
effect: normalizeOptionalEffect(effect, isCommand),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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<void>;
|
||||
/** 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<EventTarget, "addEventListener" | "removeEventListener">;
|
||||
/**
|
||||
* 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<void> {
|
||||
let inflightKeepaliveBytes = 0;
|
||||
|
||||
async function send(body: string, signal?: AbortSignal): Promise<void> {
|
||||
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<void> {
|
||||
// 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,
|
||||
|
||||
@@ -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({
|
||||
|
||||
+10
-2
@@ -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 }
|
||||
: {}),
|
||||
|
||||
@@ -123,6 +123,12 @@ export interface CommandEffectDescriptor<Problem> {
|
||||
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`);
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -44,6 +44,11 @@ const CREATE_EFFECT: CommandEffectDescriptor<ReferenceProblem> = 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({
|
||||
|
||||
@@ -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();
|
||||
|
||||
|
||||
@@ -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<typeof toCreateReferenceCommand>) =>
|
||||
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() {
|
||||
</FormActions>
|
||||
}
|
||||
feedback={
|
||||
mutationEffectUnknown ? (
|
||||
<AsyncSurface
|
||||
state={mutation.state}
|
||||
onReconcileUnknownEffect={(resolution) => {
|
||||
void mutation.reconcileUnknownEffect(resolution).then(() => {
|
||||
if (resolution === "APPLIED") {
|
||||
form.settleApplied();
|
||||
} else {
|
||||
form.settleNotApplied();
|
||||
}
|
||||
});
|
||||
}}
|
||||
form.failure ? (
|
||||
<FormFailureStatus
|
||||
failure={form.failure}
|
||||
onAction={
|
||||
form.result === "retry-later"
|
||||
? () => void form.submitForm()
|
||||
: failureAction
|
||||
}
|
||||
/>
|
||||
) : mutationEffectUnknown ? (
|
||||
<>
|
||||
<AsyncSurface
|
||||
state={mutation.state}
|
||||
onReconcileUnknownEffect={(resolution) => {
|
||||
void mutation
|
||||
.reconcileUnknownEffect(resolution)
|
||||
.then(form.settleApplied);
|
||||
}}
|
||||
onResendUnknownEffect={() => {
|
||||
void form.resendUnknown(mutation.resendUnknownEffect);
|
||||
}}
|
||||
/>
|
||||
<p>
|
||||
<Link
|
||||
to="/examples/reference-resources"
|
||||
onClick={() => {
|
||||
void invalidation
|
||||
?.invalidate([REFERENCE_RESOURCE_INVALIDATION_TOPIC])
|
||||
.catch(() => {});
|
||||
}}
|
||||
>
|
||||
목록을 새로 불러와 확인
|
||||
</Link>
|
||||
</p>
|
||||
</>
|
||||
) : form.result === "success" ? (
|
||||
<p role="status">저장했습니다.</p>
|
||||
) : form.result === "conflict" ? (
|
||||
|
||||
@@ -219,9 +219,19 @@ type ApplicationMutationController<Input, Value> = Readonly<{
|
||||
state: AsyncState;
|
||||
submit(input: Input): Promise<ApplicationResult<Value>>;
|
||||
resolveConflict(): Promise<void>;
|
||||
/**
|
||||
* 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<void>;
|
||||
/**
|
||||
* 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<ApplicationResult<Value> | null>;
|
||||
}>;
|
||||
|
||||
type MutationExecution<Input> =
|
||||
@@ -231,7 +241,10 @@ type MutationExecution<Input> =
|
||||
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<Input, Value>(
|
||||
),
|
||||
});
|
||||
}
|
||||
// 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<Input, Value>(
|
||||
};
|
||||
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<Input, Value>(
|
||||
const pending = (async (): Promise<ApplicationResult<Value>> => {
|
||||
let execution: MutationExecution<Input>;
|
||||
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<Input, Value>(
|
||||
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<Input, Value>(
|
||||
[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<Input, Value>(
|
||||
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,
|
||||
|
||||
@@ -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}
|
||||
>
|
||||
<h2 id={messageId}>{errorMessage(userMessageKey, locale)}</h2>
|
||||
{description ? <p>{description}</p> : null}
|
||||
{action !== "none" && onAction && (
|
||||
<Button onClick={onAction}>{actionLabels[action]}</Button>
|
||||
)}
|
||||
@@ -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 ? (
|
||||
<>
|
||||
<Button
|
||||
onClick={() => onReconcileUnknownEffect("APPLIED")}
|
||||
>
|
||||
{message("action.confirmMutationApplied")}
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => onReconcileUnknownEffect("NOT_APPLIED")}
|
||||
>
|
||||
{message("action.confirmMutationNotApplied")}
|
||||
</Button>
|
||||
</>
|
||||
<Button onClick={() => onReconcileUnknownEffect("APPLIED")}>
|
||||
{message("action.confirmMutationApplied")}
|
||||
</Button>
|
||||
) : null}
|
||||
{state.indicator === "mutation-effect-unknown" &&
|
||||
onResendUnknownEffect ? (
|
||||
<Button onClick={onResendUnknownEffect}>
|
||||
{message("action.resendMutation")}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
@@ -136,6 +136,7 @@ export {
|
||||
ErrorSummary,
|
||||
Form,
|
||||
FormActions,
|
||||
FormFailureStatus,
|
||||
FormField,
|
||||
useAppForm,
|
||||
useDirtyNavigationGuard,
|
||||
|
||||
@@ -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<Values extends FormValues>(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 (
|
||||
<TerminalErrorSurface
|
||||
userMessageKey={failure.userMessageKey}
|
||||
action={failure.action}
|
||||
onAction={onAction}
|
||||
// Signing in remounts the scope, so the entered values do not survive.
|
||||
description={
|
||||
failure.action === "reauth"
|
||||
? message("form.reauthLosesInput")
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function FormActions(props: Readonly<{
|
||||
children: ReactNode;
|
||||
sticky?: boolean;
|
||||
|
||||
@@ -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<Values extends FormValues> = Readonly<{
|
||||
|
||||
@@ -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<readonly string[]>([]);
|
||||
const [pending, setPending] = useState(false);
|
||||
const [result, setResult] = useState<FormResultState>("idle");
|
||||
const [statusFailure, setStatusFailure] = useState<AppFailure | null>(null);
|
||||
const pendingRef = useRef<Promise<FormResult<Output> | null> | null>(null);
|
||||
const unknownSubmissionRef = useRef<Values | null>(null);
|
||||
|
||||
@@ -175,6 +177,60 @@ export function useAppForm<
|
||||
setResult("idle");
|
||||
}, []);
|
||||
|
||||
const applyOutcome = useCallback(
|
||||
(outcome: FormResult<Output>, submittedValues: Values) => {
|
||||
if (outcome.ok) {
|
||||
settleSuccessfulValues(submittedValues);
|
||||
return;
|
||||
}
|
||||
if (outcome.error.kind === "VALIDATION_REJECTED") {
|
||||
unknownSubmissionRef.current = null;
|
||||
const mapped = mapValidationFailureToFields<Values>(
|
||||
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<FormResult<Output> | null> => {
|
||||
setFieldErrors({} as FieldErrors<Values>);
|
||||
@@ -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<Values>(
|
||||
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<FormResult<Output> | null>,
|
||||
): Promise<FormResult<Output> | 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<FormResultState> = new Set([
|
||||
"reauth-required",
|
||||
"forbidden",
|
||||
"retry-later",
|
||||
]);
|
||||
|
||||
function issuesToFieldErrors<Values extends FormValues>(
|
||||
issues: readonly ZodIssue[],
|
||||
allowedFields: readonly FieldName<Values>[],
|
||||
|
||||
@@ -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.",
|
||||
|
||||
@@ -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<string>[],
|
||||
) {
|
||||
const client = queryClient();
|
||||
const intents: MutationIntent[] = [];
|
||||
const execute = vi.fn(
|
||||
async (
|
||||
input: string,
|
||||
context: Readonly<{ signal: AbortSignal; intent: MutationIntent }>,
|
||||
): Promise<ApplicationResult<string>> => {
|
||||
intents.push(context.intent);
|
||||
return outcomes.shift() ?? { ok: true, value: input };
|
||||
},
|
||||
);
|
||||
const scope = replayScope();
|
||||
const hook = renderHook(
|
||||
() =>
|
||||
useApplicationMutation<string, string>({
|
||||
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<string> = {
|
||||
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<string> | 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);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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
|
||||
</AsyncSurface>,
|
||||
@@ -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();
|
||||
});
|
||||
|
||||
|
||||
@@ -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<typeof createFailure> }>
|
||||
>;
|
||||
resetOnSuccess?: boolean;
|
||||
onFailureAction?(): void;
|
||||
}>) {
|
||||
const form = useAppForm({
|
||||
schema,
|
||||
@@ -57,6 +59,14 @@ function FormHarness(props: Readonly<{
|
||||
fieldId={form.fieldId}
|
||||
onFocusField={form.focusField}
|
||||
/>
|
||||
<FormFailureStatus
|
||||
failure={form.failure}
|
||||
onAction={
|
||||
form.result === "retry-later"
|
||||
? () => void form.submitForm()
|
||||
: props.onFailureAction
|
||||
}
|
||||
/>
|
||||
<FormField {...form.field("name")} label="Name" required />
|
||||
<FormField {...form.field("note")} label="Note" />
|
||||
<Button type="submit" disabled={form.pending}>
|
||||
@@ -137,6 +147,61 @@ describe("local form facade", () => {
|
||||
expect(document.body).not.toHaveTextContent("raw-secret-message");
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
"AUTH_REQUIRED",
|
||||
"reauth-required",
|
||||
"계속하려면 로그인이 필요합니다.",
|
||||
"로그인",
|
||||
],
|
||||
[
|
||||
"FORBIDDEN",
|
||||
"forbidden",
|
||||
"이 작업을 수행할 권한이 없습니다.",
|
||||
"안전한 화면으로 이동",
|
||||
],
|
||||
[
|
||||
"RATE_LIMITED",
|
||||
"retry-later",
|
||||
"요청이 많습니다. 잠시 후 다시 시도해 주세요.",
|
||||
"다시 시도",
|
||||
],
|
||||
] as const)(
|
||||
"shows %s as its own save state, not an input error",
|
||||
async (kind, result, copy, action) => {
|
||||
const user = userEvent.setup();
|
||||
const onFailureAction = vi.fn();
|
||||
const submit = vi.fn(async () => ({
|
||||
ok: false as const,
|
||||
error: createFailure(kind, "CREATE_ENTITY", 0, {
|
||||
effect: "NOT_APPLIED",
|
||||
}),
|
||||
}));
|
||||
render(
|
||||
<FormHarness submit={submit} onFailureAction={onFailureAction} />,
|
||||
);
|
||||
await user.type(screen.getByRole("textbox", { name: /Name/ }), "Valid");
|
||||
await user.click(screen.getByRole("button", { name: "Submit" }));
|
||||
|
||||
expect(await screen.findByTestId("result")).toHaveTextContent(result);
|
||||
expect(screen.getByRole("alert")).toHaveTextContent(copy);
|
||||
expect(document.body).not.toHaveTextContent("입력 내용을 확인해 주세요.");
|
||||
expect(document.body).not.toHaveTextContent("저장하지 못했습니다.");
|
||||
expect(
|
||||
document.body.textContent?.includes("입력한 내용은 사라집니다"),
|
||||
).toBe(kind === "AUTH_REQUIRED");
|
||||
expect(screen.getByRole("textbox", { name: /Name/ })).toHaveValue("Valid");
|
||||
|
||||
await user.click(screen.getByRole("button", { name: action }));
|
||||
if (kind === "RATE_LIMITED") {
|
||||
expect(submit).toHaveBeenCalledTimes(2);
|
||||
expect(onFailureAction).not.toHaveBeenCalled();
|
||||
} else {
|
||||
expect(onFailureAction).toHaveBeenCalledOnce();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps conflict input out of URL and storage", async () => {
|
||||
const user = userEvent.setup();
|
||||
localStorage.clear();
|
||||
|
||||
@@ -337,25 +337,29 @@ describe("reference feature page states", () => {
|
||||
expect(screen.getByLabelText("설명")).toHaveValue("Keep this input");
|
||||
});
|
||||
|
||||
it("blocks resubmit and exposes only reconciliation for an unknown create effect", async () => {
|
||||
it("blocks a new save and resends an unknown create with the same key", async () => {
|
||||
const user = userEvent.setup();
|
||||
const createResource = vi.fn(async () => ({
|
||||
ok: false as const,
|
||||
error: createFailure(
|
||||
"SERVER_FAILURE",
|
||||
"CREATE_REFERENCE_RESOURCE",
|
||||
0,
|
||||
{ effect: "MAYBE_APPLIED" },
|
||||
),
|
||||
}));
|
||||
const createResource = vi
|
||||
.fn<ReferenceFeatureInput["createResource"]>()
|
||||
.mockResolvedValueOnce({
|
||||
ok: false,
|
||||
error: createFailure(
|
||||
"SERVER_FAILURE",
|
||||
"CREATE_REFERENCE_RESOURCE",
|
||||
0,
|
||||
{ effect: "MAYBE_APPLIED" },
|
||||
),
|
||||
})
|
||||
.mockResolvedValue({
|
||||
ok: true,
|
||||
value: { resourceId: "created", title: "Unknown result", createdAt: null },
|
||||
});
|
||||
renderReference(
|
||||
inputWith({ createResource }),
|
||||
"/examples/reference-resources/new",
|
||||
);
|
||||
await user.type(
|
||||
await screen.findByRole("textbox", { name: /새 항목 이름/ }),
|
||||
"Unknown result",
|
||||
);
|
||||
const name = await screen.findByRole("textbox", { name: /새 항목 이름/ });
|
||||
await user.type(name, "Unknown result");
|
||||
await user.click(screen.getByRole("button", { name: "저장" }));
|
||||
|
||||
expect(
|
||||
@@ -365,24 +369,85 @@ describe("reference feature page states", () => {
|
||||
expect(
|
||||
screen.queryByText("저장하지 못했습니다. 잠시 후 다시 시도해 주세요."),
|
||||
).not.toBeInTheDocument();
|
||||
// No path lets the user declare "not applied" without evidence.
|
||||
expect(
|
||||
screen.queryByRole("button", { name: "변경되지 않음으로 확인" }),
|
||||
).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByRole("link", { name: "목록을 새로 불러와 확인" }),
|
||||
).toHaveAttribute("href", "/examples/reference-resources");
|
||||
await user.click(screen.getByRole("button", { name: "저장" }));
|
||||
expect(createResource).toHaveBeenCalledOnce();
|
||||
expect(
|
||||
screen.getByRole("textbox", { name: /새 항목 이름/ }),
|
||||
).toHaveValue("Unknown result");
|
||||
expect(name).toHaveValue("Unknown result");
|
||||
|
||||
await user.click(
|
||||
screen.getByRole("button", { name: "변경되지 않음으로 확인" }),
|
||||
screen.getByRole("button", { name: "같은 요청으로 다시 보내기" }),
|
||||
);
|
||||
await waitFor(() =>
|
||||
expect(screen.getByRole("button", { name: "저장" })).toBeEnabled(),
|
||||
);
|
||||
expect(createResource).toHaveBeenCalledOnce();
|
||||
expect(
|
||||
screen.getByRole("textbox", { name: /새 항목 이름/ }),
|
||||
).toHaveValue("Unknown result");
|
||||
|
||||
expect(await screen.findByRole("status")).toHaveTextContent("저장했습니다.");
|
||||
expect(createResource).toHaveBeenCalledTimes(2);
|
||||
const [first, second] = createResource.mock.calls;
|
||||
expect(second?.[0]).toEqual(first?.[0]);
|
||||
expect(first?.[1]?.intent?.idempotencyKey).toBe("reference-page-key-1");
|
||||
expect(second?.[1]?.intent?.idempotencyKey).toBe("reference-page-key-1");
|
||||
expect(name).toHaveValue("");
|
||||
});
|
||||
|
||||
it.each([
|
||||
["AUTH_REQUIRED", "계속하려면 로그인이 필요합니다.", "로그인"],
|
||||
["FORBIDDEN", "이 작업을 수행할 권한이 없습니다.", "안전한 화면으로 이동"],
|
||||
["RATE_LIMITED", "요청이 많습니다. 잠시 후 다시 시도해 주세요.", "다시 시도"],
|
||||
] as const)(
|
||||
"gives a %s create failure its own copy and action",
|
||||
async (kind, copy, action) => {
|
||||
const user = userEvent.setup();
|
||||
const demoSession = createDemoSessionAdapter("authenticated");
|
||||
const beginSignIn = vi.fn(async () => {});
|
||||
const createResource = vi.fn(async () => ({
|
||||
ok: false as const,
|
||||
error: createFailure(kind, "CREATE_REFERENCE_RESOURCE", 0, {
|
||||
effect: "NOT_APPLIED",
|
||||
}),
|
||||
}));
|
||||
renderReference(
|
||||
inputWith({ createResource }),
|
||||
"/examples/reference-resources/new",
|
||||
{ ...demoSession, beginSignIn },
|
||||
);
|
||||
await user.type(
|
||||
await screen.findByRole("textbox", { name: /새 항목 이름/ }),
|
||||
"Rejected",
|
||||
);
|
||||
await user.click(screen.getByRole("button", { name: "저장" }));
|
||||
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent(copy);
|
||||
expect(document.body).not.toHaveTextContent("입력 내용을 확인해 주세요.");
|
||||
expect(
|
||||
screen.queryByText("변경 결과를 확인할 수 없습니다."),
|
||||
).not.toBeInTheDocument();
|
||||
await user.click(screen.getByRole("button", { name: action }));
|
||||
|
||||
if (kind === "AUTH_REQUIRED") {
|
||||
expect(beginSignIn).toHaveBeenCalledWith(
|
||||
"/examples/reference-resources/new",
|
||||
);
|
||||
} else if (kind === "FORBIDDEN") {
|
||||
// Leaving still passes the dirty-input guard.
|
||||
await user.click(
|
||||
await screen.findByRole("button", { name: "변경 버리고 이동" }),
|
||||
);
|
||||
expect(
|
||||
await screen.findByRole("heading", {
|
||||
level: 1,
|
||||
name: "Clean Architecture Frontend",
|
||||
}),
|
||||
).toBeVisible();
|
||||
} else {
|
||||
await waitFor(() => expect(createResource).toHaveBeenCalledTimes(2));
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("settles the form after confirming an unknown create was applied", async () => {
|
||||
const user = userEvent.setup();
|
||||
const createResource = vi.fn(async () => ({
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { http, HttpResponse } from "msw";
|
||||
import {
|
||||
afterAll,
|
||||
afterEach,
|
||||
@@ -118,4 +119,133 @@ describe("reference feature production vertical path", () => {
|
||||
expect(createRequests).toHaveBeenCalledWith({ name: "Created" });
|
||||
expect(listRequests.mock.calls.length).toBeGreaterThanOrEqual(2);
|
||||
});
|
||||
|
||||
it("resends a create whose 504 lost the response with the same Idempotency-Key", async () => {
|
||||
const user = userEvent.setup();
|
||||
const idempotencyKeys: (string | null)[] = [];
|
||||
mockApi.server.use(
|
||||
http.post("https://api.test/api/reference-resources", async ({ request }) => {
|
||||
idempotencyKeys.push(request.headers.get("idempotency-key"));
|
||||
// The first request reaches the server; only its response is lost.
|
||||
if (idempotencyKeys.length === 1) {
|
||||
return new HttpResponse(null, { status: 504 });
|
||||
}
|
||||
const body = (await request.json()) as { name: string };
|
||||
return HttpResponse.json(
|
||||
{
|
||||
id: "reference-created",
|
||||
name: body.name,
|
||||
createdAt: "2026-07-26T00:00:00.000Z",
|
||||
},
|
||||
{ status: 201 },
|
||||
);
|
||||
}),
|
||||
);
|
||||
const composition = await createRuntimeComposition({
|
||||
fetcher: absoluteFetch,
|
||||
host: {},
|
||||
});
|
||||
window.history.pushState({}, "", "/examples/reference-resources/new");
|
||||
render(<RuntimeApplication composition={composition} />);
|
||||
|
||||
await user.click(
|
||||
await screen.findByRole("button", { name: "로그인 시작" }),
|
||||
);
|
||||
await user.type(
|
||||
await screen.findByRole("textbox", { name: /새 항목 이름/ }),
|
||||
"Lost response",
|
||||
);
|
||||
await user.click(screen.getByRole("button", { name: "저장" }));
|
||||
await user.click(
|
||||
await screen.findByRole("button", { name: "같은 요청으로 다시 보내기" }),
|
||||
);
|
||||
|
||||
expect(await screen.findByText("저장했습니다.")).toBeVisible();
|
||||
expect(idempotencyKeys).toHaveLength(2);
|
||||
expect(idempotencyKeys[0]).toMatch(/^[\x21-\x7e]+$/u);
|
||||
expect(idempotencyKeys[1]).toBe(idempotencyKeys[0]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
// The demo session treats a server 401 as signed out; the route guard
|
||||
// then asks for sign-in and the form is gone.
|
||||
[401, "세션이 필요합니다."],
|
||||
[403, "이 작업을 수행할 권한이 없습니다."],
|
||||
[429, "요청이 많습니다. 잠시 후 다시 시도해 주세요."],
|
||||
])(
|
||||
"treats a create rejected with %i as not applied, not unknown",
|
||||
async (status, guidance) => {
|
||||
const user = userEvent.setup();
|
||||
mockApi.server.use(
|
||||
http.post(
|
||||
"https://api.test/api/reference-resources",
|
||||
() => new HttpResponse(null, { status }),
|
||||
),
|
||||
);
|
||||
const composition = await createRuntimeComposition({
|
||||
fetcher: absoluteFetch,
|
||||
host: {},
|
||||
});
|
||||
window.history.pushState({}, "", "/examples/reference-resources/new");
|
||||
render(<RuntimeApplication composition={composition} />);
|
||||
|
||||
await user.click(
|
||||
await screen.findByRole("button", { name: "로그인 시작" }),
|
||||
);
|
||||
await user.type(
|
||||
await screen.findByRole("textbox", { name: /새 항목 이름/ }),
|
||||
"Rejected",
|
||||
);
|
||||
await user.click(screen.getByRole("button", { name: "저장" }));
|
||||
|
||||
expect(await screen.findByText(guidance)).toBeVisible();
|
||||
expect(
|
||||
screen.queryByText("변경 결과를 확인할 수 없습니다."),
|
||||
).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByRole("button", { name: "같은 요청으로 다시 보내기" }),
|
||||
).not.toBeInTheDocument();
|
||||
expect(document.body).not.toHaveTextContent("입력 내용을 확인해 주세요.");
|
||||
},
|
||||
);
|
||||
|
||||
it("shows a server 422 field error on its field (03-04)", async () => {
|
||||
const user = userEvent.setup();
|
||||
mockApi.server.use(
|
||||
http.post("https://api.test/api/reference-resources", () =>
|
||||
HttpResponse.json(
|
||||
{
|
||||
type: "https://api.test/problems/validation_rejected",
|
||||
title: "VALIDATION_REJECTED",
|
||||
status: 422,
|
||||
code: "VALIDATION_REJECTED",
|
||||
issues: [
|
||||
{ path: "name", code: "too_big", message: "backend copy" },
|
||||
{ path: "serverOnly", code: "REQUIRED" },
|
||||
],
|
||||
},
|
||||
{ status: 422 },
|
||||
),
|
||||
),
|
||||
);
|
||||
const composition = await createRuntimeComposition({
|
||||
fetcher: absoluteFetch,
|
||||
host: {},
|
||||
});
|
||||
window.history.pushState({}, "", "/examples/reference-resources/new");
|
||||
render(<RuntimeApplication composition={composition} />);
|
||||
|
||||
await user.click(
|
||||
await screen.findByRole("button", { name: "로그인 시작" }),
|
||||
);
|
||||
const name = await screen.findByRole("textbox", { name: /새 항목 이름/ });
|
||||
await user.type(name, "Too long for the server");
|
||||
await user.click(screen.getByRole("button", { name: "저장" }));
|
||||
|
||||
const summary = await screen.findByRole("alert");
|
||||
expect(summary).toHaveTextContent("새 항목 이름: 입력값이 너무 깁니다.");
|
||||
expect(summary).toHaveTextContent("서버가 확인하지 못한 입력 항목이 있습니다.");
|
||||
expect(name).toHaveAttribute("aria-invalid", "true");
|
||||
expect(document.body).not.toHaveTextContent("backend copy");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -182,6 +182,72 @@ describe("V3 HTTP observability projection", () => {
|
||||
expect(sinks.diagnostics).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("records the correlation id in diagnostics only (03-03)", async () => {
|
||||
const sinks = recordingSinks();
|
||||
const executor = createContractHttpExecutor({
|
||||
baseUrl: "https://api.example/",
|
||||
maxRetryAttempts: 0,
|
||||
attachCredentials: () => ({ kind: "READY" as const, headers: {} }),
|
||||
fetcher: (async () =>
|
||||
new Response(null, {
|
||||
status: 503,
|
||||
headers: { "x-correlation-id": "server-ref-7" },
|
||||
})) as unknown as typeof fetch,
|
||||
observe: sinks.projector,
|
||||
});
|
||||
|
||||
await executor.execute(
|
||||
TEST_LIST_HTTP_CONTRACT,
|
||||
{ limit: 5 },
|
||||
{ routeId: ROUTE_ID, scope: scopeSnapshot() },
|
||||
);
|
||||
|
||||
expect(sinks.diagnostics[0]?.context).toMatchObject({
|
||||
correlation_id: "server-ref-7",
|
||||
});
|
||||
expect(projectDiagnosticRecord(sinks.diagnostics[0]!).success).toBe(true);
|
||||
expect(sinks.telemetry).toHaveLength(1);
|
||||
expect(JSON.stringify(sinks.telemetry)).not.toContain("server-ref-7");
|
||||
});
|
||||
|
||||
it("keeps a never-sent unauthenticated request out of telemetry (03-07)", async () => {
|
||||
const sinks = recordingSinks();
|
||||
const fetcher = vi.fn();
|
||||
const executor = createContractHttpExecutor({
|
||||
baseUrl: "https://api.example/",
|
||||
maxRetryAttempts: 0,
|
||||
attachCredentials: () => ({ kind: "UNAUTHENTICATED" as const }),
|
||||
fetcher: fetcher as unknown as typeof fetch,
|
||||
observe: sinks.projector,
|
||||
});
|
||||
|
||||
const outcome = await executor.execute(
|
||||
TEST_LIST_HTTP_CONTRACT,
|
||||
{ limit: 5 },
|
||||
{ routeId: ROUTE_ID, scope: scopeSnapshot() },
|
||||
);
|
||||
|
||||
expect(outcome.kind).toBe("UNAUTHENTICATED");
|
||||
expect(fetcher).not.toHaveBeenCalled();
|
||||
expect(sinks.diagnostics).toHaveLength(1);
|
||||
expect(sinks.telemetry).toHaveLength(0);
|
||||
|
||||
// A server 401 is still an API failure.
|
||||
const answered = recordingSinks();
|
||||
await createContractHttpExecutor({
|
||||
baseUrl: "https://api.example/",
|
||||
maxRetryAttempts: 0,
|
||||
attachCredentials: () => ({ kind: "READY" as const, headers: {} }),
|
||||
fetcher: (async () => new Response(null, { status: 401 })) as unknown as typeof fetch,
|
||||
observe: answered.projector,
|
||||
}).execute(
|
||||
TEST_LIST_HTTP_CONTRACT,
|
||||
{ limit: 5 },
|
||||
{ routeId: ROUTE_ID, scope: scopeSnapshot() },
|
||||
);
|
||||
expect(answered.telemetry).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("does not emit failure telemetry for caller cancellation or scope fencing", async () => {
|
||||
const cancelled = recordingSinks();
|
||||
const callerController = new AbortController();
|
||||
|
||||
@@ -232,14 +232,14 @@ function expectationFor(
|
||||
case "unauthenticated-401":
|
||||
statuses = [401];
|
||||
kind = "UNAUTHENTICATED";
|
||||
outcomeEffect = command ? "MAYBE_APPLIED" : "NOT_APPLICABLE";
|
||||
outcomeEffect = command ? "NOT_APPLIED" : "NOT_APPLICABLE";
|
||||
observer = "UNAUTHENTICATED";
|
||||
bodies = [attemptBody("CANCELLED_WITHOUT_READ", 0, 0)];
|
||||
break;
|
||||
case "forbidden-403":
|
||||
statuses = [403];
|
||||
kind = "FORBIDDEN";
|
||||
outcomeEffect = command ? "MAYBE_APPLIED" : "NOT_APPLICABLE";
|
||||
outcomeEffect = command ? "NOT_APPLIED" : "NOT_APPLICABLE";
|
||||
observer = "FORBIDDEN";
|
||||
bodies = [attemptBody("CANCELLED_WITHOUT_READ", 0, 0)];
|
||||
break;
|
||||
@@ -289,7 +289,7 @@ function expectationFor(
|
||||
const attemptCount = command ? 1 : 3;
|
||||
statuses = Array.from({ length: attemptCount }, () => 429);
|
||||
kind = "RATE_LIMITED";
|
||||
outcomeEffect = command ? "MAYBE_APPLIED" : "NOT_APPLICABLE";
|
||||
outcomeEffect = command ? "NOT_APPLIED" : "NOT_APPLICABLE";
|
||||
observer = "RATE_LIMITED";
|
||||
retryReasons = command ? [] : ["HTTP_429", "HTTP_429"];
|
||||
media = Array.from({ length: attemptCount }, () => "application/json");
|
||||
|
||||
@@ -71,7 +71,7 @@ describe("trace and correlation propagation", () => {
|
||||
expect(seen.every((headers) => headers.get("x-correlation-id") === "i-9")).toBe(true);
|
||||
});
|
||||
|
||||
it("adds no trace headers to an interaction that did not opt in", async () => {
|
||||
it("adds no trace to an interaction that did not opt in, only its own request id", async () => {
|
||||
const seen: Array<Headers> = [];
|
||||
const transport = vi.fn<Transport>(async (_input, init) => {
|
||||
seen.push(new Headers(init?.headers));
|
||||
@@ -83,7 +83,8 @@ describe("trace and correlation propagation", () => {
|
||||
{ routeId: "TEST_ROUTE", scope: scopeSnapshot() },
|
||||
);
|
||||
expect(seen[0]?.get("traceparent")).toBeNull();
|
||||
expect(seen[0]?.get("x-correlation-id")).toBeNull();
|
||||
// 03-03. Every execution still sends a request id for the server log.
|
||||
expect(seen[0]?.get("x-correlation-id")).toMatch(/^[A-Za-z0-9._:-]{1,128}$/u);
|
||||
});
|
||||
|
||||
it("does not let a credential collaborator forge the trace headers", async () => {
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
createFailure,
|
||||
kindForStatus,
|
||||
normalizeUnknownFailure,
|
||||
withFailureEffect,
|
||||
} from "../../src/contracts/errors.ts";
|
||||
import { DIAGNOSTIC_EVENT_REGISTRY } from "../../src/contracts/diagnostics.ts";
|
||||
import { TELEMETRY_REGISTRY } from "../../src/contracts/telemetry.ts";
|
||||
@@ -51,6 +52,19 @@ describe("frontend failure classification", () => {
|
||||
expect(kindForStatus(status)).toBe(kind);
|
||||
});
|
||||
|
||||
it("keeps re-login first for an auth failure whose effect is unknown (D-2)", () => {
|
||||
expect(
|
||||
createFailure("AUTH_REQUIRED", "CREATE", 0, { effect: "MAYBE_APPLIED" }),
|
||||
).toMatchObject({ action: "reauth", retryable: false });
|
||||
expect(
|
||||
withFailureEffect(createFailure("AUTH_REQUIRED", "CREATE", 0), "MAYBE_APPLIED"),
|
||||
).toMatchObject({ action: "reauth", retryable: false });
|
||||
// Every other kind still sends an unknown effect to support.
|
||||
expect(
|
||||
createFailure("FORBIDDEN", "CREATE", 0, { effect: "MAYBE_APPLIED" }),
|
||||
).toMatchObject({ action: "contact-support" });
|
||||
});
|
||||
|
||||
it("projects only allowlisted safe fields", () => {
|
||||
const untrustedDetails = {
|
||||
code: "TEMPORARY",
|
||||
|
||||
@@ -992,6 +992,249 @@ describe("terminal owner classification at every wait", () => {
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* 10-03. The executor, not only the pure rule, must read the contract's retry
|
||||
* semantics: a KEYED command with budget left retries a send that never left,
|
||||
* and never replays one that was dispatched.
|
||||
*/
|
||||
describe("KEYED retry budget through the executor", () => {
|
||||
const keyedWithBudget: InstalledHttpContract<unknown, unknown, unknown> = {
|
||||
...createInstalled,
|
||||
frontend: { ...createInstalled.frontend, retryBudget: 2 as const },
|
||||
};
|
||||
|
||||
function keyedExecutor(fetcher: typeof fetch) {
|
||||
return createContractHttpExecutor({
|
||||
baseUrl: "https://api.example/",
|
||||
maxRetryAttempts: 2,
|
||||
attachCredentials: () => ({ kind: "READY", headers: {} }),
|
||||
fetcher,
|
||||
sleep: async () => {},
|
||||
random: () => 0,
|
||||
});
|
||||
}
|
||||
|
||||
it("retries a KEYED send that failed before dispatch, with the same key", async () => {
|
||||
const keys: (string | null)[] = [];
|
||||
const fetcher = vi.fn<typeof fetch>((_input, init) => {
|
||||
keys.push(new Headers(init?.headers).get("idempotency-key"));
|
||||
if (keys.length === 1) throw new TypeError("fetch refused to start");
|
||||
return Promise.resolve(
|
||||
Response.json({ id: "created", name: "created" }, { status: 201 }),
|
||||
);
|
||||
});
|
||||
|
||||
const outcome = await keyedExecutor(fetcher).execute(
|
||||
keyedWithBudget,
|
||||
{ name: "created" },
|
||||
{ routeId: ROUTE_ID, scope, intent: mutationIntent() },
|
||||
);
|
||||
|
||||
expect(fetcher).toHaveBeenCalledTimes(2);
|
||||
expect(keys).toEqual(["key-1", "key-1"]);
|
||||
expect(outcome).toMatchObject({
|
||||
kind: "SUCCESS",
|
||||
effect: "APPLIED_CONFIRMED",
|
||||
});
|
||||
});
|
||||
|
||||
it("does not replay a dispatched KEYED send even with budget left", async () => {
|
||||
const fetcher = vi.fn<typeof fetch>(async () => {
|
||||
throw new TypeError("connection reset");
|
||||
});
|
||||
|
||||
const outcome = await keyedExecutor(fetcher).execute(
|
||||
keyedWithBudget,
|
||||
{ name: "created" },
|
||||
{ routeId: ROUTE_ID, scope, intent: mutationIntent() },
|
||||
);
|
||||
|
||||
expect(fetcher).toHaveBeenCalledOnce();
|
||||
expect(outcome).toMatchObject({
|
||||
kind: "TRANSPORT_FAILURE",
|
||||
effect: "MAYBE_APPLIED",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* 03-03. A support reference must reach the server log: every logical
|
||||
* execution sends one request id, and a failure carries the server's echoed
|
||||
* `x-correlation-id` as `requestId`.
|
||||
*/
|
||||
describe("request correlation", () => {
|
||||
it("sends one request id per logical execution, shared by its retries", async () => {
|
||||
const sent: (string | null)[] = [];
|
||||
const fetcher = vi.fn<typeof fetch>(async (_input, init) => {
|
||||
sent.push(new Headers(init?.headers).get("x-correlation-id"));
|
||||
return sent.length === 1
|
||||
? new Response(null, { status: 503 })
|
||||
: Response.json([{ id: "a", name: "A" }]);
|
||||
});
|
||||
const executor = createContractHttpExecutor({
|
||||
baseUrl: "https://api.example/",
|
||||
maxRetryAttempts: 2,
|
||||
attachCredentials: () => ({ kind: "READY", headers: {} }),
|
||||
fetcher,
|
||||
sleep: async () => {},
|
||||
random: () => 0,
|
||||
});
|
||||
const retried = {
|
||||
...installed,
|
||||
frontend: { ...installed.frontend, retryBudget: 1 as const },
|
||||
};
|
||||
|
||||
await executor.execute(retried, { limit: 20 }, { routeId: ROUTE_ID, scope });
|
||||
await executor.execute(retried, { limit: 20 }, { routeId: ROUTE_ID, scope });
|
||||
|
||||
expect(sent).toHaveLength(3);
|
||||
expect(sent[0]).toMatch(/^[A-Za-z0-9._:-]{1,128}$/u);
|
||||
expect(sent[1]).toBe(sent[0]);
|
||||
expect(sent[2]).not.toBe(sent[0]);
|
||||
});
|
||||
|
||||
it("still sends the request when no request id can be made", async () => {
|
||||
const fetcher = vi.fn<typeof fetch>(async () =>
|
||||
Response.json([{ id: "a", name: "A" }]),
|
||||
);
|
||||
const executor = createContractHttpExecutor({
|
||||
baseUrl: "https://api.example/",
|
||||
maxRetryAttempts: 0,
|
||||
attachCredentials: () => ({ kind: "READY", headers: {} }),
|
||||
fetcher,
|
||||
createRequestId: () => {
|
||||
throw new TypeError("randomUUID needs a secure context");
|
||||
},
|
||||
});
|
||||
|
||||
const outcome = await executor.execute(installed, { limit: 20 }, {
|
||||
routeId: ROUTE_ID,
|
||||
scope,
|
||||
});
|
||||
|
||||
expect(outcome.kind).toBe("SUCCESS");
|
||||
expect(
|
||||
new Headers(fetcher.mock.calls[0]?.[1]?.headers).get("x-correlation-id"),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it.each([
|
||||
["a problem", 400, { type: "about:blank", title: "rejected", status: 400 }],
|
||||
["an unauthenticated answer", 401, null],
|
||||
["a forbidden answer", 403, null],
|
||||
["a rate limit", 429, null],
|
||||
["a gateway outage", 504, null],
|
||||
] as const)("carries the server correlation id on %s", async (_label, status, body) => {
|
||||
const observations: HttpExecutionObservation[] = [];
|
||||
const executor = createContractHttpExecutor({
|
||||
baseUrl: "https://api.example/",
|
||||
maxRetryAttempts: 0,
|
||||
attachCredentials: () => ({ kind: "READY", headers: {} }),
|
||||
fetcher: vi.fn(async () =>
|
||||
body === null
|
||||
? new Response(null, {
|
||||
status,
|
||||
headers: { "x-correlation-id": "server-ref-42" },
|
||||
})
|
||||
: Response.json(body, {
|
||||
status,
|
||||
headers: { "x-correlation-id": "server-ref-42" },
|
||||
}),
|
||||
),
|
||||
observe: (observation) => observations.push(observation),
|
||||
});
|
||||
const list = defineFeatureHttpOperation({
|
||||
contract: TEST_LIST_HTTP_CONTRACT,
|
||||
routeId: ROUTE_ID,
|
||||
mapSuccess: (value) => mappingSuccess(value),
|
||||
});
|
||||
const binding = createFeatureHttpBinding(
|
||||
{
|
||||
execute: (contract, input, context) =>
|
||||
executor.execute(contract, input, { ...context, scope }),
|
||||
},
|
||||
{ [list.operationId]: list },
|
||||
);
|
||||
|
||||
const result = await binding.execute(list.operationId, { limit: 20 });
|
||||
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: { requestId: "server-ref-42" },
|
||||
});
|
||||
expect(observations.at(-1)?.correlationId).toBe("server-ref-42");
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* D-2 (03-02). 401, 403 and 429 are admitted before any problem body is read.
|
||||
* The package may classify them by status; without a classifier, or when it
|
||||
* misbehaves, a dispatched command stays MAYBE_APPLIED.
|
||||
*/
|
||||
describe("command status classification", () => {
|
||||
function withStatusClassifier(
|
||||
classifyStatus: ((status: 401 | 403 | 429) => unknown) | undefined,
|
||||
): InstalledHttpContract<unknown, unknown, unknown> {
|
||||
return {
|
||||
...createInstalled,
|
||||
contract: {
|
||||
...createInstalled.contract,
|
||||
commandEffect: {
|
||||
...createInstalled.contract.commandEffect!,
|
||||
...(classifyStatus === undefined ? {} : { classifyStatus }),
|
||||
} as NonNullable<typeof createInstalled.contract.commandEffect>,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function effectFor(
|
||||
status: number,
|
||||
contract: InstalledHttpContract<unknown, unknown, unknown>,
|
||||
) {
|
||||
const executor = createContractHttpExecutor({
|
||||
baseUrl: "https://api.example/",
|
||||
maxRetryAttempts: 0,
|
||||
attachCredentials: () => ({ kind: "READY", headers: {} }),
|
||||
fetcher: vi.fn(async () => new Response(null, { status })),
|
||||
});
|
||||
const outcome = await executor.execute(
|
||||
contract,
|
||||
{ name: "created" },
|
||||
{ routeId: ROUTE_ID, scope, intent: mutationIntent() },
|
||||
);
|
||||
return { kind: outcome.kind, effect: outcome.effect };
|
||||
}
|
||||
|
||||
it.each([
|
||||
[401, "UNAUTHENTICATED"],
|
||||
[403, "FORBIDDEN"],
|
||||
[429, "RATE_LIMITED"],
|
||||
] as const)("uses the package classifier for %i", async (status, kind) => {
|
||||
const classifyStatus = vi.fn(() => "NOT_APPLIED");
|
||||
await expect(
|
||||
effectFor(status, withStatusClassifier(classifyStatus)),
|
||||
).resolves.toEqual({ kind, effect: "NOT_APPLIED" });
|
||||
expect(classifyStatus).toHaveBeenCalledWith(status);
|
||||
});
|
||||
|
||||
const throwingClassifier = (): unknown => {
|
||||
throw new Error("package defect");
|
||||
};
|
||||
const unknownAnswer = (): unknown => "APPLIED_CONFIRMED";
|
||||
|
||||
it.each([
|
||||
["no classifier", undefined],
|
||||
["a throwing classifier", throwingClassifier],
|
||||
["an unknown answer", unknownAnswer],
|
||||
] as const)("keeps MAYBE_APPLIED for %s", async (_label, classifyStatus) => {
|
||||
for (const status of [401, 403, 429]) {
|
||||
await expect(
|
||||
effectFor(status, withStatusClassifier(classifyStatus)),
|
||||
).resolves.toMatchObject({ effect: "MAYBE_APPLIED" });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Q-6.3-7. A retried command's final effect joins what earlier attempts already
|
||||
* established, and an answer that says the command may already be applied is
|
||||
|
||||
@@ -174,6 +174,44 @@ describe("runtime adapter composition", () => {
|
||||
expect(fetcher).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("sends telemetry stamped with the release identity (13-11)", async () => {
|
||||
const bodies: { events: Record<string, unknown>[] }[] = [];
|
||||
const fetcher = vi.fn(async (_url: RequestInfo | URL, init?: RequestInit) => {
|
||||
if (String(_url) === "https://telemetry.test/events") {
|
||||
bodies.push(JSON.parse(String(init?.body)));
|
||||
}
|
||||
return new Response(null, { status: 204 });
|
||||
});
|
||||
const adapters = await createRuntimeAdapters({
|
||||
runtime: {
|
||||
...runtime,
|
||||
config: {
|
||||
...runtime.config,
|
||||
TELEMETRY_ENABLED: true,
|
||||
TELEMETRY_ENDPOINT: "https://telemetry.test/events",
|
||||
},
|
||||
} as Runtime,
|
||||
release,
|
||||
host: {},
|
||||
fetcher: fetcher as unknown as typeof fetch,
|
||||
});
|
||||
|
||||
adapters.outputPorts.telemetry.emit("api.request.failed", {
|
||||
error_kind: "SERVER_FAILURE",
|
||||
http_status_group: "5xx",
|
||||
attempt_count_bucket: "1",
|
||||
route_id: "TEST_ROUTE",
|
||||
});
|
||||
await adapters.outputPorts.telemetry.flush();
|
||||
|
||||
expect(bodies[0]?.events[0]).toMatchObject({
|
||||
eventName: "api.request.failed",
|
||||
build_id: "build-a",
|
||||
release_id: "release-a",
|
||||
});
|
||||
adapters.infrastructure.dispose();
|
||||
});
|
||||
|
||||
it("replaces the QueryClient and coordinator for each session generation", async () => {
|
||||
const adapters = await createRuntimeAdapters({ runtime, release, host: {} });
|
||||
const previousClient = adapters.infrastructure.queryClient;
|
||||
|
||||
@@ -594,6 +594,140 @@ describe("one collector transport for both telemetry ports (Q-6.9-4)", () => {
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* 13-11. Failures must be attributable to a release while old and new tabs
|
||||
* coexist, so every event the collector sends carries both identities.
|
||||
*/
|
||||
describe("collector release identity (13-11)", () => {
|
||||
it("stamps build_id and release_id on every event of both ports", async () => {
|
||||
const bodies: { events: Record<string, unknown>[] }[] = [];
|
||||
const fetcher = vi.fn(async (_url: RequestInfo | URL, init?: RequestInit) => {
|
||||
bodies.push(JSON.parse(String(init?.body)));
|
||||
return new Response(null, { status: 204 });
|
||||
});
|
||||
const collector = createTelemetryCollector({
|
||||
endpoint: "https://telemetry.test/events",
|
||||
fetcher: fetcher as unknown as typeof fetch,
|
||||
release: { buildId: "build-a", releaseId: "release-a" },
|
||||
});
|
||||
const adapter = createTelemetryAdapter({
|
||||
enabled: true,
|
||||
endpoint: "https://telemetry.test/events",
|
||||
schedule: () => {},
|
||||
collector,
|
||||
});
|
||||
adapter.emit("api.request.failed", validAttributes);
|
||||
await adapter.flush();
|
||||
await createFetchTelemetryTransport({
|
||||
endpoint: "https://telemetry.test/events",
|
||||
collector,
|
||||
}).send([
|
||||
{
|
||||
event: { kind: "catalog.load.failed", severity: "error", featureId: "catalog" },
|
||||
fingerprint: "fp-1",
|
||||
occurrences: 1,
|
||||
},
|
||||
]);
|
||||
// A split batch keeps the identity on every part.
|
||||
await collector.post(
|
||||
Array.from({ length: 70 }, (_, index) => ({ index, padding: "x".repeat(1_000) })),
|
||||
);
|
||||
|
||||
const events = bodies.flatMap((body) => body.events);
|
||||
expect(bodies.length).toBeGreaterThan(3);
|
||||
expect(events).toHaveLength(72);
|
||||
for (const sent of events) {
|
||||
expect(sent).toMatchObject({ build_id: "build-a", release_id: "release-a" });
|
||||
}
|
||||
adapter.dispose();
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* 03-05. Fetch fails every keepalive request once the in-flight keepalive
|
||||
* bodies exceed 64KiB, so a large queue must be split and the collector must
|
||||
* never have more than that in flight with keepalive.
|
||||
*/
|
||||
describe("collector keepalive budget (03-05)", () => {
|
||||
const KEEPALIVE_QUOTA = 64 * 1024;
|
||||
const utf8 = new TextEncoder();
|
||||
|
||||
function recordingFetcher() {
|
||||
const sent: { bytes: number; keepalive: boolean; events: number }[] = [];
|
||||
let inflightKeepalive = 0;
|
||||
let peakKeepalive = 0;
|
||||
const releases: Array<() => void> = [];
|
||||
const fetcher = vi.fn((_url: RequestInfo | URL, init?: RequestInit) => {
|
||||
const body = String(init?.body);
|
||||
const bytes = utf8.encode(body).byteLength;
|
||||
const keepalive = init?.keepalive === true;
|
||||
sent.push({
|
||||
bytes,
|
||||
keepalive,
|
||||
events: (JSON.parse(body) as { events: unknown[] }).events.length,
|
||||
});
|
||||
if (keepalive) inflightKeepalive += bytes;
|
||||
peakKeepalive = Math.max(peakKeepalive, inflightKeepalive);
|
||||
return new Promise<Response>((resolve) => {
|
||||
releases.push(() => {
|
||||
if (keepalive) inflightKeepalive -= bytes;
|
||||
resolve(new Response(null, { status: 204 }));
|
||||
});
|
||||
});
|
||||
});
|
||||
return {
|
||||
sent,
|
||||
peak: () => peakKeepalive,
|
||||
releaseAll: () => releases.splice(0).forEach((release) => release()),
|
||||
fetcher: fetcher as unknown as typeof fetch,
|
||||
};
|
||||
}
|
||||
|
||||
const bigEvents = (count: number) =>
|
||||
Array.from({ length: count }, (_, index) => ({
|
||||
index,
|
||||
padding: "x".repeat(1_000),
|
||||
}));
|
||||
|
||||
it("splits a queue over the keepalive limit into posts that all arrive", async () => {
|
||||
const recording = recordingFetcher();
|
||||
const collector = createTelemetryCollector({
|
||||
endpoint: "https://telemetry.test/events",
|
||||
fetcher: recording.fetcher,
|
||||
});
|
||||
|
||||
const delivered = collector.post(bigEvents(70));
|
||||
await vi.waitFor(() => expect(recording.sent.length).toBeGreaterThan(1));
|
||||
recording.releaseAll();
|
||||
await delivered;
|
||||
|
||||
expect(recording.sent.every((post) => post.bytes <= KEEPALIVE_QUOTA)).toBe(
|
||||
true,
|
||||
);
|
||||
expect(recording.sent.reduce((sum, post) => sum + post.events, 0)).toBe(70);
|
||||
expect(recording.peak()).toBeLessThanOrEqual(KEEPALIVE_QUOTA);
|
||||
});
|
||||
|
||||
it("keeps concurrent posts under one keepalive quota", async () => {
|
||||
const recording = recordingFetcher();
|
||||
const collector = createTelemetryCollector({
|
||||
endpoint: "https://telemetry.test/events",
|
||||
fetcher: recording.fetcher,
|
||||
});
|
||||
|
||||
// Two queues flushing together, as on pagehide.
|
||||
const first = collector.post(bigEvents(40));
|
||||
const second = collector.post(bigEvents(40));
|
||||
await vi.waitFor(() => expect(recording.sent.length).toBeGreaterThan(1));
|
||||
recording.releaseAll();
|
||||
await Promise.all([first, second]);
|
||||
|
||||
expect(recording.peak()).toBeLessThanOrEqual(KEEPALIVE_QUOTA);
|
||||
expect(recording.sent.some((post) => post.keepalive)).toBe(true);
|
||||
expect(recording.sent.reduce((sum, post) => sum + post.events, 0)).toBe(80);
|
||||
});
|
||||
});
|
||||
|
||||
describe("telemetry adapter send-rate limit (spec §27)", () => {
|
||||
function harness(maxSendsPerMinute = 3) {
|
||||
let now = 0;
|
||||
|
||||
Reference in New Issue
Block a user