refactor(http)!: V2 HTTP 클라이언트를 지우고 V3 실행기 하나만 남긴다
문제
HTTP 실행 경로가 둘이다. V3 실행기(createContractHttpExecutor)가 모든 기능을
실행하고, V2 클라이언트(createHttpClient)는 bootstrap의
createRuntimeHttpClient에서만 만들어지는데 그 함수를 앱 안에서 부르는 곳이
없다(테스트만 부른다). tech-log·memento도 같다. 그런데도 V2는 초기 청크에
들어가고, 짝 백엔드 해석(7db32e1~3261208)과 테스트를 두 벌로 유지하게 했다.
사용자 지시: 레거시를 두지 말고 최신 경로 하나만 남긴다.
고른 방법
- src/adapters/http/의 client.ts, bounded-json.ts, request-builder.ts,
resource-mapper.ts, retry-policy.ts, schema-registry.ts를 지웠다. Envelope
스키마는 backend-envelope.ts로 옮겼다. V3가 retry-policy.ts에서 쓰던
parseRetryAfter는 그것이 감싸던 platform/retry-after.ts의
parseRetryAfterDelay를 직접 부른다.
- 배럴의 V2 export와 bootstrap의 createRuntimeHttpClient·RuntimeHttpContract를
지웠다.
- V2 전용 테스트(http-client, http-diagnostics, auth-recovery,
legacy-http-credential-authority, bounded-json-compatibility,
request-builder, retry-policy)와 tests/helpers/http-contract-fixture.ts를
지웠다. 섞인 파일(http-execution-contract, runtime-adapters,
boundary-mapper)은 V2 블록만 지웠다.
- V2로 돌던 폼 테스트(form-foundation)는 Envelope을 읽는 V3 keyed create
계약으로 옮겼다. 400 VALIDATION_FAILED 필드 오류, {cause} 뒤 다시 저장,
422 뒤 저장 꺼짐을 그대로 검사한다. http-execution-v3-envelope 테스트는 V2와
비교하던 행을 기대 판정을 직접 적는 행으로 바꿨다.
- drill:runbook FE-RB-003은 V2 shouldRetry 대신 V3 실행기를 실제로 돌려
보낸 요청 수를 센다(NEVER 503: 1회, SAFE 503: 재시도, SAFE 스키마 불일치:
1회).
- check:diagnostics의 http 이벤트 생산자, registry-governance의 오류 표 소비자,
risk-coverage 고위험 경로, 아키텍처 금지 fixture, adapter INVENTORY, 문서의
경로를 V3 파일로 바꿨다.
버린 대안
- V2를 @deprecated로 한 릴리스 남기기: 템플릿과 두 다운스트림 모두 부르는
곳이 없어 옮겨 갈 사용자가 없다. 남기면 초기 JS와 두 벌 유지 비용만 남는다.
위험·한계
- BREAKING: 배럴과 bootstrap의 V2 이름을 쓰던 제품 코드는 컴파일이 깨진다.
CHANGELOG에 옮기는 방법을 적었다.
- V2에만 있던 동작이 사라졌다: 401 뒤 세션 복구 후 한 번 재전송, KEYED 503
자동 재시도. V3는 401을 UNAUTHENTICATED로 넘기고 KEYED 요청은 보낸 뒤
재시도하지 않는다.
- 기능마다 적는 V2 API 행(*-api-contract.ts, check:registries가 읽음)은 이
커밋에서 지우지 않았다. 다음 커밋이 지운다.
검증
- check:types, lint, check:architecture(금지 fixture 9건 거절),
check:adapter-inventory(140 files), check:diagnostics, check:registries,
check:ci, verify:documentation 통과.
- test:unit 2,585, test:integration 114, test:component 245, test:contract 23,
test:runtime-schema 56, tests/features 101 통과.
- drill:runbook FE-RB-003: no local check failed.
- check:bundle 통과. 초기 JS 203,354 → 201,598 B(−1,756 B).
BREAKING CHANGE: src/adapters/http/index.ts가 createHttpClient, HttpClient,
HttpClientDependencies, HttpFailure, HttpResult, LegacyHttpInput, Scheduler,
OperationRequestInput를, src/bootstrap/runtime-adapters.ts가
createRuntimeHttpClient, RuntimeHttpContract를 내보내지 않는다. 그 operation의
V3 descriptor를 만들어 createFeatureHttpBinding으로 실행한다.
This commit is contained in:
@@ -75,6 +75,7 @@
|
||||
| [계약] | V2: 422 `IDEMPOTENT_REQUEST_MISMATCH`·400 `IDEMPOTENCY_KEY_INVALID`가 `effect: "NOT_APPLIED"`와 진단 reason을 싣는다. 409의 `Retry-After`는 `retryAfterMs`로 실린다(V3 PROBLEM 실패도 같다). 결과 불명 요청을 같은 키로 다시 보낼 때 그 시각까지(최대 5초) 기다린다. 응답 code의 정본은 백엔드 템플릿 `docs/web/http-contract.md` §2다 (백엔드 리뷰 1101/02-01) | `src/adapters/http/client.ts`, `src/adapters/http/feature-http-binding.ts`, `src/presentation/adapters/query/application-query.ts` | `93782b0`, `47fec5c` |
|
||||
| [계약] | V2 클라이언트가 짝 백엔드의 400 `VALIDATION_FAILED`(필드 목록 `details: [{field, code, message}]`)를 422와 같은 `VALIDATION_REJECTED`·`validationIssues`로 읽는다. 필드 검증 거절(422와 이 400)은 `effect: "NOT_APPLIED"`다. 전에는 결과 불명으로 붙들어 폼에서 값을 고쳐도 다시 저장할 수 없었다. 그 밖의 400·409는 그대로 결과 불명이다. 적용 여부는 다음 행이 다시 정했다 (백엔드 리뷰 1101/02-01) | `src/adapters/http/client.ts`, `src/contracts/errors.ts` | `02e35d2`, `64e98ee` |
|
||||
| [계약] | 거절의 적용 여부를 계약 문서 6.1절 표(백엔드 `5786126c` 코드 기준)로 정한다. V2와 V3 Envelope operation이 같은 표(`src/adapters/http/backend-envelope.ts`)를 쓴다. 적용 안 됨은 400 `VALIDATION_FAILED`(details 모양과 상관없음)·400 `IDEMPOTENCY_KEY_INVALID`·422 `IDEMPOTENT_REQUEST_MISMATCH`뿐이고, 그 밖의 400·409·422는 결과 불명이다. V2에서 `IDEMPOTENT_REQUEST_MISMATCH`가 아닌 422는 이제 결과 불명이라 폼에서 값을 고쳐도 다시 저장할 수 없다. 필드 검증을 422로 보내는 백엔드를 쓰는 프로젝트는 영향을 받는다. 필드 목록 없는 400 `VALIDATION_FAILED`는 바로 다시 저장할 수 있다. V3 Envelope operation의 400·409·422는 `classifyProblem` 대신 이 표가 정한다 (1101/14.4) | `src/adapters/http/backend-envelope.ts`, `src/adapters/http/client.ts`, `src/adapters/http/http-execution-v3.ts` | `3261208` |
|
||||
| [계약] **BREAKING** | V2 HTTP 클라이언트를 지웠다. HTTP 경로는 V3 실행기 하나다. 배럴(`src/adapters/http/index.ts`)에서 `createHttpClient`, `HttpClient`, `HttpClientDependencies`, `HttpFailure`, `HttpResult`, `LegacyHttpInput`, `Scheduler`, `OperationRequestInput`가, `src/bootstrap/runtime-adapters.ts`에서 `createRuntimeHttpClient`, `RuntimeHttpContract`가 없어졌다. 지운 파일: `client.ts`, `bounded-json.ts`, `request-builder.ts`, `resource-mapper.ts`, `retry-policy.ts`, `schema-registry.ts`(`src/adapters/http/`). Envelope 스키마는 `backend-envelope.ts`로 옮겼다. 템플릿과 tech-log·memento 모두 앱 안에서 V2 클라이언트를 부르는 곳이 없었다. 부르는 코드가 있으면 그 operation의 V3 descriptor를 만들어 `createFeatureHttpBinding`으로 실행한다. 초기 JS 203,354 → 201,598 B | `src/adapters/http/`, `src/bootstrap/runtime-adapters.ts`, `scripts/drill-runbook.ts` | `@@V2CLIENT@@` |
|
||||
| [계약] | V3 descriptor에 선택 필드 `responseEnvelope`가 생겼다. `"ENVELOPE_V1"`이면 V3 실행기가 짝 백엔드 Envelope(`{success, data\|error, meta}`)를 읽는다. `outputValidator`는 `data`(키가 없으면 `null`), `problemValidator`는 `error`를 받는다. 400·409·422와 503 `IDEMPOTENCY_UNAVAILABLE`의 적용 여부는 실행기가 V2와 같은 표로 정하고(아래 6.1 표 행), `mapProblem`이 답하지 않으면 V2와 같은 kind·code·필드 오류로 읽는다. 성공 status의 Envelope 아닌 본문은 새 위반 `ENVELOPE_MISMATCH`다(`HttpContractViolationKind`에 추가만, exhaustive switch는 분기를 더한다). Envelope operation의 진단은 422 `IDEMPOTENT_REQUEST_MISMATCH`·400 `IDEMPOTENCY_KEY_INVALID`에 V2와 같은 `reason`을 싣는다(`HttpDiagnosticReason`에 두 값 추가). `create:feature`가 만든 기능은 이 값을 선언하고 problem 스키마가 Envelope `error`다. 값이 없는 descriptor(참조 기능 포함)는 그대로다. 이전에 만든 기능을 짝 백엔드에 붙이려면 contribution에 `responseEnvelope: "ENVELOPE_V1" as const`를 더하고 problem 스키마를 `error` 모양(`code` 필수)으로 바꾼다 (1101 README 14.3) | `src/contracts/external-contract-runtime.ts`, `src/adapters/http/`, `scripts/create-feature.ts`, `tests/mocks/handlers/http-scenarios.ts` | `7db32e1`, `bd83b49` |
|
||||
| [계약] | V3 실행 결과에 선택 필드 `sentRequestId`가 생겼다. 서버가 `x-correlation-id`를 돌려주지 않으면 `AppFailure.requestId`는 보낸 값이다. 결과 불명·조회 실패 화면에 "지원 참조" 줄이 보인다 (0929/03-04) | `src/adapters/http/http-execution-v3.ts`, `src/adapters/http/feature-http-binding.ts` | `849d000` |
|
||||
| [계약] | `ResumableUploadPort.upload()`: part 발급(BFF)이 401/403으로 거절하면 recovery가 `RESUME` 대신 `NONE`(`retryable: false`)이다. 세션 만료·권한 회수라 재인증 전에는 다시 불러도 같다. object store PUT 403은 그대로 `RESUME`이다 (0929/01-01) | `src/adapters/browser-transfer/resumable-upload/resumable-upload-runtime.ts` | `c5f87aa` |
|
||||
|
||||
@@ -359,7 +359,7 @@
|
||||
},
|
||||
"consumers": [
|
||||
{
|
||||
"path": "src/adapters/http/client.ts",
|
||||
"path": "src/adapters/http/feature-http-binding.ts",
|
||||
"token": "failure("
|
||||
}
|
||||
],
|
||||
|
||||
@@ -19,16 +19,6 @@
|
||||
"branches": 90
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "src/adapters/http/bounded-json.ts",
|
||||
"owner": "http-runtime",
|
||||
"minimum": {
|
||||
"lines": 85,
|
||||
"statements": 84,
|
||||
"functions": 95,
|
||||
"branches": 78
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "src/adapters/http/http-execution-v3.ts",
|
||||
"owner": "http-runtime",
|
||||
@@ -39,26 +29,6 @@
|
||||
"branches": 52
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "src/adapters/http/request-builder.ts",
|
||||
"owner": "http-runtime",
|
||||
"minimum": {
|
||||
"lines": 85,
|
||||
"statements": 85,
|
||||
"functions": 95,
|
||||
"branches": 82
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "src/adapters/http/retry-policy.ts",
|
||||
"owner": "http-runtime",
|
||||
"minimum": {
|
||||
"lines": 80,
|
||||
"statements": 78,
|
||||
"functions": 95,
|
||||
"branches": 78
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "src/adapters/query-cache/server-state-scope-runtime.ts",
|
||||
"owner": "server-state-runtime",
|
||||
@@ -212,10 +182,7 @@
|
||||
],
|
||||
"highRiskPaths": [
|
||||
"src/adapters/http/bounded-body-reader.ts",
|
||||
"src/adapters/http/bounded-json.ts",
|
||||
"src/adapters/http/http-execution-v3.ts",
|
||||
"src/adapters/http/request-builder.ts",
|
||||
"src/adapters/http/retry-policy.ts",
|
||||
"src/adapters/query-cache/server-state-scope-runtime.ts",
|
||||
"src/adapters/service-worker/service-worker-lifecycle.ts",
|
||||
"src/adapters/storage/browser-storage-adapter.ts",
|
||||
|
||||
@@ -248,8 +248,9 @@ backend idempotency를 대체하지 않는다.
|
||||
- 키 생성·검사: `src/contracts/mutation-intent.ts` `isValidIdempotencyKey`
|
||||
- 결과 불명 재전송이 같은 키를 쓰고 `Retry-After`까지 기다리는 곳:
|
||||
`src/presentation/adapters/query/application-query.ts`
|
||||
- V2 거절 판정: `src/adapters/http/client.ts` `IDEMPOTENCY_REFUSALS`
|
||||
- V3 참조 기능 판정: `src/features/reference-feature/contracts/reference-feature-contract-contribution.ts`
|
||||
- Envelope operation의 거절 판정: `src/adapters/http/backend-envelope.ts`
|
||||
`REFUSED_BEFORE_WRITE`(6.1절 표)
|
||||
- 참조 기능(Envelope 없음) 판정: `src/features/reference-feature/contracts/reference-feature-contract-contribution.ts`
|
||||
(effect), `src/features/reference-feature/adapters/reference-http-gateway.ts`
|
||||
(code)
|
||||
|
||||
|
||||
@@ -434,9 +434,9 @@ bootstrap → React TSX → tests 순서로 이동한다.
|
||||
|
||||
### retry, API client, logger, token manager, error, validation은 어디에 있는가
|
||||
|
||||
- retry: `src/adapters/http/retry-policy.ts`, runtime max-attempt/cleanup 계약까지 구현
|
||||
- API client: `src/adapters/http/client.ts`, path/search/body projection과
|
||||
runtime schema/mapper를 사용하며 feature gateway 뒤에서 실행
|
||||
- retry: `src/adapters/http/http-retry-lifecycle.ts`, runtime max-attempt/cleanup 계약까지 구현
|
||||
- API client: `src/adapters/http/http-execution-v3.ts`, 설치된 계약의 path/search/body
|
||||
projection과 검증기를 쓰며 feature binding(`feature-http-binding.ts`) 뒤에서 실행
|
||||
- logger: `DiagnosticsPort`로 telemetry와 분리해 구현. closed event/level,
|
||||
allowlist와 bounded/no-op adapter 제공
|
||||
- token manager: 의도적으로 없음. opaque external auth owner가 credential을 소유
|
||||
|
||||
@@ -24,7 +24,7 @@ reader that accepts it must ship before any writer sends it.
|
||||
| `CAPABILITY_OVERRIDES` | strict; unknown capability rejected | breaking | `capabilityOverrideArtifactSchema` in `src/contracts/release-artifacts.ts` |
|
||||
| `FEATURE_OVERRIDES` | record; unknown feature id ignored | additive | `featureOverrideArtifactSchema` in `src/contracts/release-artifacts.ts` |
|
||||
| Release manifest V2 | strict object | breaking | `releaseManifestV2ArtifactSchema` in `src/contracts/release-artifacts.ts` |
|
||||
| HTTP success/failure envelope (V2, and V3 with `responseEnvelope: "ENVELOPE_V1"`) | strict object (`meta` strips) | breaking | `successEnvelopeSchema`, `failureEnvelopeSchema` in `src/adapters/http/schema-registry.ts`, read by `src/adapters/http/backend-envelope.ts` |
|
||||
| HTTP success/failure envelope (V3 with `responseEnvelope: "ENVELOPE_V1"`) | strict object (`meta` strips) | breaking | `successEnvelopeSchema`, `failureEnvelopeSchema` in `src/adapters/http/backend-envelope.ts` |
|
||||
| HTTP V3 response DTO (reference feature) | `.strip()` drops unknown fields | additive | `referenceResourceDtoSchema` in `src/features/reference-feature/contracts/reference-schemas.ts` |
|
||||
| Realtime envelope | exact key set; unknown `eventType` is `MALFORMED_EVENT` | breaking | `decodeUnsafe` in `src/adapters/realtime/event-codec.ts` |
|
||||
| Browser RPC transport error code | closed vocabulary; unknown code is a protocol violation | breaking | `decodeTransportFailure` in `src/adapters/browser-rpc/browser-rpc-runtime.ts` |
|
||||
|
||||
@@ -256,7 +256,7 @@ down, and this section is left as written so the two passes stay comparable.
|
||||
| LIVE-03 | High | `FIXED` | `f4bfdf0` | Same suite — the composed HTTP registry was clearable and a post-composition mutation of a source policy changed `totalDeadlineMs` from 10000 to 999999. |
|
||||
| LIVE-04 | Medium | `FIXED` | `f4bfdf0` | Same integration suite — a non-cooperative fetch and reader held the port result open; a body that finished after the deadline was admitted as SUCCESS. |
|
||||
| LIVE-05 | High | `FIXED` | `f4bfdf0` | Same suite — a DEADLINE timeout emitted no `api.request.failed`. |
|
||||
| LEG-01 | High | `FIXED` | `ca210d3` | `tests/integration/legacy-http-credential-authority.test.ts` — a recovery that answered after the deadline called `onUnauthenticated` once; it now calls it zero times, and only an adopted no-session result notifies. |
|
||||
| LEG-01 | High | `FIXED` | `ca210d3` | The V2 client's credential authority test (deleted with the V2 client on 2026-11-03) — a recovery that answered after the deadline called `onUnauthenticated` once; it now calls it zero times, and only an adopted no-session result notifies. |
|
||||
| LEG-02 | High | `FIXED` | `ca210d3` | Same suite — a bearer profile dispatched with no `Authorization` at all. |
|
||||
| OPT-NET-01 | Medium | `FIXED` | `ca210d3` | `tests/unit/legacy-and-optional-network-remediation.test.ts` — a loader rejection with a live signal became `PAGINATION_ABORTED`. |
|
||||
| OPT-NET-02 | Low | `FIXED` | `ca210d3` | Same suite — `defineMutationIntent` accepted control characters the executor rejected. |
|
||||
|
||||
@@ -15,8 +15,8 @@
|
||||
현재 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` 호출처 없음).
|
||||
"current v1"은 V2 client 시절에 쓴 말이다. V2 client는 2026-11-03에 지웠다.
|
||||
HTTP 경로는 V3 하나다.
|
||||
|
||||
2026-09-25 코드 기준 상태:
|
||||
|
||||
|
||||
@@ -60,16 +60,16 @@ All 24 files below were read in full.
|
||||
| src/adapters/diagnostics/bounded-diagnostics.ts | Bounded in-memory diagnostics projection/sink and safe pre-mount boot evidence | DiagnosticsPort; contracts/diagnostics.ts and telemetry.ts; bootstrap | Preserve fail-isolated projection and cloning. Harden non-finite capacity. V3 producer fix belongs primarily in bootstrap. |
|
||||
| src/adapters/http/backend-envelope.ts | Reads the paired backend's Envelope frame and its operation-independent failure verdicts (idempotency refusals, in-flight 409, 503 IDEMPOTENCY_UNAVAILABLE, field validation) | V2 client.ts; V3 executor and feature binding for `responseEnvelope: "ENVELOPE_V1"` | Added 2026-11-03 (1101 README 14.3). Keep as the one place both paths read the backend wire, so their verdicts cannot drift apart. |
|
||||
| src/adapters/http/bounded-body-reader.ts | Declared-length and streamed byte ceilings, stream cancellation/release isolation, forbidden-body probing, strict UTF-8/JSON decode | V3 executor; bounded-body-reader tests | Keep as the single bounded response primitive. It already contains the cleanup behavior missing from bounded-json.ts. |
|
||||
| src/adapters/http/bounded-json.ts | Legacy response stream reader and JSON decoder | legacy client.ts | Replace internals with bounded-body-reader delegation, then remove with V2 retirement. Current cancel/release failures can reject. |
|
||||
| src/adapters/http/client.ts | Legacy/V2 operation lookup, profiles, auth recovery, retries, total deadline, response validation/mapping, diagnostics and telemetry | legacy contracts and ports; runtime-adapters createRuntimeHttpClient | Compatibility-only but exported. Fix empty keyed replay, cooperative auth cancellation, and common body-reader use before relying on it for rollback. Not a drop-in rollback for V3: V2 validates the `{success,data,meta}` envelope and V3 the bare DTO, so a rollback needs the four slots and a V2-envelope server (Q-6.3-11). 401 recovery is a single replay outside the retry budget. Deprecate after callers are migrated. |
|
||||
| src/adapters/http/bounded-json.ts | Legacy response stream reader and JSON decoder | legacy client.ts | Replace internals with bounded-body-reader delegation, then remove with V2 retirement. Current cancel/release failures can reject. Deleted 2026-11-03 with the V2 client (V3 is the only HTTP path). |
|
||||
| src/adapters/http/client.ts | Legacy/V2 operation lookup, profiles, auth recovery, retries, total deadline, response validation/mapping, diagnostics and telemetry | legacy contracts and ports; runtime-adapters createRuntimeHttpClient | Compatibility-only but exported. Fix empty keyed replay, cooperative auth cancellation, and common body-reader use before relying on it for rollback. Not a drop-in rollback for V3: V2 validates the `{success,data,meta}` envelope and V3 the bare DTO, so a rollback needs the four slots and a V2-envelope server (Q-6.3-11). 401 recovery is a single replay outside the retry budget. Deprecate after callers are migrated. Deleted 2026-11-03 with the V2 client (V3 is the only HTTP path). |
|
||||
| src/adapters/http/http-contract-bridge.ts | V3 request projection, URL/body bounds, credential patch type, final request invariant | external-contract-runtime.ts; V3 executor | Preserve descriptor-owned request projection. Change credential authority: patch cannot own credentials or transport headers; final invariant must compare exact resolved profile. |
|
||||
| src/adapters/http/http-effect-certainty.ts | Converts physical-attempt state and problem descriptors into mutation certainty/UI projection | V3 executor; contracts | Preserve explicit certainty vocabulary. Add a monotonic logical-execution certainty join used across retries. |
|
||||
| src/adapters/http/http-execution-v3.ts | Descriptor-driven V3 lifetime: validation, projection, credentials, deadline, retry, fetch, response admission, effect verdict and observation | external contracts, scope, mutation intent, bridge, bounded reader, certainty, retry policy | Main correction site for N-01, N-02, N-03 and cooperative cancellation. Keep one retry authority and closed result union. |
|
||||
| src/adapters/http/request-builder.ts | Legacy path/query construction and origin/base-prefix checks | legacy client; ApiOperation | Keep while V2 remains. Do not reuse it to weaken V3 descriptor projection. |
|
||||
| src/adapters/http/resource-mapper.ts | Thin legacy operation-payload mapper delegation | boundary-mapper; legacy client | No standalone defect. Remove only with V2, not as part of the correctness patch. |
|
||||
| src/adapters/http/retry-policy.ts | Legacy retry decision/backoff plus parseRetryAfter reused by V3; parsing delegates to kernel platform/retry-after.ts (Q-6.4-8) | legacy client and V3 executor; platform/retry-after.ts | Keep deterministic parse/backoff seam. V2 must additionally prove a valid key before keyed replay. |
|
||||
| src/adapters/http/request-builder.ts | Legacy path/query construction and origin/base-prefix checks | legacy client; ApiOperation | Keep while V2 remains. Do not reuse it to weaken V3 descriptor projection. Deleted 2026-11-03 with the V2 client (V3 is the only HTTP path). |
|
||||
| src/adapters/http/resource-mapper.ts | Thin legacy operation-payload mapper delegation | boundary-mapper; legacy client | No standalone defect. Remove only with V2, not as part of the correctness patch. Deleted 2026-11-03 with the V2 client (V3 is the only HTTP path). |
|
||||
| src/adapters/http/retry-policy.ts | Legacy retry decision/backoff plus parseRetryAfter reused by V3; parsing delegates to kernel platform/retry-after.ts (Q-6.4-8) | legacy client and V3 executor; platform/retry-after.ts | Keep deterministic parse/backoff seam. V2 must additionally prove a valid key before keyed replay. Deleted 2026-11-03 with the V2 client (V3 is the only HTTP path). |
|
||||
| src/adapters/http/platform-error-mapping.ts | Maps feature-less V3 transport outcomes (cancel, timeout, network, response-invalid) to the platform AppError envelope; feature-owned outcomes return null | http-execution-v3.ts outcomes; platform/errors; feature HTTP binding | Keep. Registered 2026-09-24 (added in 6f6c48e without a ledger row). |
|
||||
| src/adapters/http/schema-registry.ts | Legacy Zod envelope/request/payload validation and clone | legacy client/tests | No standalone defect. Remains V2-only and should not be merged with installed external validators. |
|
||||
| src/adapters/http/schema-registry.ts | Legacy Zod envelope/request/payload validation and clone | legacy client/tests | No standalone defect. Remains V2-only and should not be merged with installed external validators. Deleted 2026-11-03 with the V2 client (V3 is the only HTTP path). |
|
||||
| src/adapters/platform/browser-lifecycle.ts | Single owner of visibility/network/focus/page/beforeunload listeners and lifecycle snapshots | optional-runtime-host.ts | Preserve centralized listener ownership and idempotent dispose. Clarify or redesign dirty-source attachment semantics; selection item O-02. |
|
||||
| src/adapters/platform/browser-mutation-intent-factory.ts | Secure intent/idempotency UUIDs plus monotonic creation time, normalized by defineMutationIntent | MutationIntentFactory port; bootstrap | Keep. Share one idempotency-key validator so external inputs and generated values have identical bounds. |
|
||||
| src/adapters/platform/json-member-scanner.ts | Non-recursive duplicate-member and structure-budget scan before `JSON.parse`; moved from realtime in 2nd round (Q-6.4-8) | realtime event codec and WS protocol; web-push hint codec | Keep. Single scanner; web-push now checks every depth, not only top-level keys. |
|
||||
|
||||
@@ -66,94 +66,88 @@
|
||||
| 56 | `src/adapters/diagnostics/index.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 57 | `src/adapters/http/backend-envelope.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 58 | `src/adapters/http/bounded-body-reader.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 59 | `src/adapters/http/bounded-json.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 60 | `src/adapters/http/client.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 61 | `src/adapters/http/feature-http-binding.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 62 | `src/adapters/http/http-contract-bridge.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 63 | `src/adapters/http/http-effect-certainty.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 64 | `src/adapters/http/http-execution-v3.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 65 | `src/adapters/http/http-retry-lifecycle.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 66 | `src/adapters/http/index.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 67 | `src/adapters/http/platform-error-mapping.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 68 | `src/adapters/http/request-builder.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 69 | `src/adapters/http/resource-mapper.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 70 | `src/adapters/http/retry-policy.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 71 | `src/adapters/http/schema-registry.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 72 | `src/adapters/platform/abortable-operation.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 73 | `src/adapters/platform/bounded-capacity.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 74 | `src/adapters/platform/browser-lifecycle.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 75 | `src/adapters/platform/browser-mutation-intent-factory.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 76 | `src/adapters/platform/index.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 77 | `src/adapters/platform/indexeddb-connection.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 78 | `src/adapters/platform/indexeddb-transaction.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 79 | `src/adapters/platform/json-member-scanner.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 80 | `src/adapters/platform/retry-after.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 81 | `src/adapters/platform/system-clock.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 82 | `src/adapters/query-cache/conditional-validator-store.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 83 | `src/adapters/query-cache/cursor-pagination-contract.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 84 | `src/adapters/query-cache/cursor-pagination-runtime.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 85 | `src/adapters/query-cache/index.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 86 | `src/adapters/query-cache/server-state-scope-runtime.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 87 | `src/adapters/query-cache/tanstack-cache-coordinator.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 88 | `src/adapters/query-cache/tanstack-query-cache.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 89 | `src/adapters/realtime/event-codec.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 90 | `src/adapters/realtime/event-consumer.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 91 | `src/adapters/realtime/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 92 | `src/adapters/realtime/live-poll-handoff-coordinator.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 93 | `src/adapters/realtime/polling/bounded-poll-coordinator.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 94 | `src/adapters/realtime/polling/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 95 | `src/adapters/realtime/reconnect-coordinator.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 96 | `src/adapters/realtime/reconnect-policy.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 97 | `src/adapters/realtime/result.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 98 | `src/adapters/realtime/sse/fetch-sse-connection.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 99 | `src/adapters/realtime/sse/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 100 | `src/adapters/realtime/sse/sse-parser.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 101 | `src/adapters/realtime/stream-coordinator.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 102 | `src/adapters/realtime/websocket/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 103 | `src/adapters/realtime/websocket/websocket-connection.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 104 | `src/adapters/realtime/websocket/websocket-protocol.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 105 | `src/adapters/service-worker/index.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 106 | `src/adapters/service-worker/service-worker-entry.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 107 | `src/adapters/service-worker/service-worker-lifecycle.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 108 | `src/adapters/service-worker/service-worker-page-controller.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 109 | `src/adapters/service-worker/service-worker-protocol.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 110 | `src/adapters/service-worker/service-worker-removal.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 111 | `src/adapters/service-worker/service-worker-static-assets.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 112 | `src/adapters/storage/browser-storage-adapter.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 113 | `src/adapters/storage/browser-storage-codec.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 114 | `src/adapters/storage/index.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 115 | `src/adapters/storage/indexeddb/index.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 116 | `src/adapters/storage/indexeddb/indexeddb-governance.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 117 | `src/adapters/storage/indexeddb/indexeddb-maintenance.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 118 | `src/adapters/storage/indexeddb/indexeddb-migrations.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 119 | `src/adapters/storage/indexeddb/indexeddb-records.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 120 | `src/adapters/storage/indexeddb/indexeddb-runtime.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 121 | `src/adapters/storage/indexeddb/indexeddb-types.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 122 | `src/adapters/storage/opfs/browser-opfs-runtime.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 123 | `src/adapters/storage/opfs/index.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 124 | `src/adapters/storage/opfs/indexeddb-opfs-journal.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 125 | `src/adapters/storage/opfs/opfs-byte-store-adapter.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 126 | `src/adapters/storage/opfs/opfs-policy.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 127 | `src/adapters/storage/opfs/opfs-prepared-object.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 128 | `src/adapters/storage/opfs/opfs-worker-client.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 129 | `src/adapters/storage/opfs/opfs-worker-protocol.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 130 | `src/adapters/storage/opfs/opfs-worker-runtime.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 131 | `src/adapters/telemetry/best-effort-telemetry.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 132 | `src/adapters/telemetry/feature-telemetry.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 133 | `src/adapters/telemetry/index.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 134 | `src/adapters/telemetry/telemetry-collector.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 135 | `src/adapters/web-push/codec-primitives.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 136 | `src/adapters/web-push/inbound/notification-click-adapter.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 137 | `src/adapters/web-push/inbound/push-event-adapter.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 138 | `src/adapters/web-push/index.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 139 | `src/adapters/web-push/notification-registry.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 140 | `src/adapters/web-push/push-association-fence-store.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 141 | `src/adapters/web-push/push-codec.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 142 | `src/adapters/web-push/push-registration-gateway.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 143 | `src/adapters/web-push/push-subscription-adapter.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 144 | `src/adapters/web-push/runtime-support.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 145 | `src/adapters/web-push/service-worker-runtime.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 146 | `src/adapters/web-push/service-worker-scope-host.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 59 | `src/adapters/http/feature-http-binding.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 60 | `src/adapters/http/http-contract-bridge.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 61 | `src/adapters/http/http-effect-certainty.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 62 | `src/adapters/http/http-execution-v3.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 63 | `src/adapters/http/http-retry-lifecycle.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 64 | `src/adapters/http/index.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 65 | `src/adapters/http/platform-error-mapping.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 66 | `src/adapters/platform/abortable-operation.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 67 | `src/adapters/platform/bounded-capacity.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 68 | `src/adapters/platform/browser-lifecycle.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 69 | `src/adapters/platform/browser-mutation-intent-factory.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 70 | `src/adapters/platform/index.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 71 | `src/adapters/platform/indexeddb-connection.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 72 | `src/adapters/platform/indexeddb-transaction.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 73 | `src/adapters/platform/json-member-scanner.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 74 | `src/adapters/platform/retry-after.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 75 | `src/adapters/platform/system-clock.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 76 | `src/adapters/query-cache/conditional-validator-store.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 77 | `src/adapters/query-cache/cursor-pagination-contract.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 78 | `src/adapters/query-cache/cursor-pagination-runtime.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 79 | `src/adapters/query-cache/index.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 80 | `src/adapters/query-cache/server-state-scope-runtime.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 81 | `src/adapters/query-cache/tanstack-cache-coordinator.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 82 | `src/adapters/query-cache/tanstack-query-cache.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 83 | `src/adapters/realtime/event-codec.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 84 | `src/adapters/realtime/event-consumer.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 85 | `src/adapters/realtime/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 86 | `src/adapters/realtime/live-poll-handoff-coordinator.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 87 | `src/adapters/realtime/polling/bounded-poll-coordinator.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 88 | `src/adapters/realtime/polling/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 89 | `src/adapters/realtime/reconnect-coordinator.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 90 | `src/adapters/realtime/reconnect-policy.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 91 | `src/adapters/realtime/result.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 92 | `src/adapters/realtime/sse/fetch-sse-connection.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 93 | `src/adapters/realtime/sse/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 94 | `src/adapters/realtime/sse/sse-parser.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 95 | `src/adapters/realtime/stream-coordinator.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 96 | `src/adapters/realtime/websocket/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 97 | `src/adapters/realtime/websocket/websocket-connection.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 98 | `src/adapters/realtime/websocket/websocket-protocol.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 99 | `src/adapters/service-worker/index.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 100 | `src/adapters/service-worker/service-worker-entry.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 101 | `src/adapters/service-worker/service-worker-lifecycle.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 102 | `src/adapters/service-worker/service-worker-page-controller.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 103 | `src/adapters/service-worker/service-worker-protocol.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 104 | `src/adapters/service-worker/service-worker-removal.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 105 | `src/adapters/service-worker/service-worker-static-assets.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 106 | `src/adapters/storage/browser-storage-adapter.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 107 | `src/adapters/storage/browser-storage-codec.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 108 | `src/adapters/storage/index.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 109 | `src/adapters/storage/indexeddb/index.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 110 | `src/adapters/storage/indexeddb/indexeddb-governance.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 111 | `src/adapters/storage/indexeddb/indexeddb-maintenance.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 112 | `src/adapters/storage/indexeddb/indexeddb-migrations.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 113 | `src/adapters/storage/indexeddb/indexeddb-records.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 114 | `src/adapters/storage/indexeddb/indexeddb-runtime.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 115 | `src/adapters/storage/indexeddb/indexeddb-types.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 116 | `src/adapters/storage/opfs/browser-opfs-runtime.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 117 | `src/adapters/storage/opfs/index.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 118 | `src/adapters/storage/opfs/indexeddb-opfs-journal.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 119 | `src/adapters/storage/opfs/opfs-byte-store-adapter.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 120 | `src/adapters/storage/opfs/opfs-policy.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 121 | `src/adapters/storage/opfs/opfs-prepared-object.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 122 | `src/adapters/storage/opfs/opfs-worker-client.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 123 | `src/adapters/storage/opfs/opfs-worker-protocol.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 124 | `src/adapters/storage/opfs/opfs-worker-runtime.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 125 | `src/adapters/telemetry/best-effort-telemetry.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 126 | `src/adapters/telemetry/feature-telemetry.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 127 | `src/adapters/telemetry/index.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 128 | `src/adapters/telemetry/telemetry-collector.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 129 | `src/adapters/web-push/codec-primitives.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 130 | `src/adapters/web-push/inbound/notification-click-adapter.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 131 | `src/adapters/web-push/inbound/push-event-adapter.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 132 | `src/adapters/web-push/index.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 133 | `src/adapters/web-push/notification-registry.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 134 | `src/adapters/web-push/push-association-fence-store.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 135 | `src/adapters/web-push/push-codec.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 136 | `src/adapters/web-push/push-registration-gateway.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 137 | `src/adapters/web-push/push-subscription-adapter.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 138 | `src/adapters/web-push/runtime-support.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 139 | `src/adapters/web-push/service-worker-runtime.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 140 | `src/adapters/web-push/service-worker-scope-host.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
|
||||
합계: **146/146**. 새 adapter 파일이 추가되면 이 ledger와 해당 상세 리뷰 inventory를 같은 변경에서 갱신한다.
|
||||
합계: **140/140**. 새 adapter 파일이 추가되면 이 ledger와 해당 상세 리뷰 inventory를 같은 변경에서 갱신한다.
|
||||
|
||||
|
||||
@@ -30,7 +30,7 @@ async function filesBelow(directory: string): Promise<string[]> {
|
||||
|
||||
const telemetryProducerFiles: Readonly<Record<string, string>> = {
|
||||
"app.boot.failed": "src/adapters/diagnostics/bounded-diagnostics.ts",
|
||||
"api.request.failed": "src/adapters/http/client.ts",
|
||||
"api.request.failed": "src/bootstrap/runtime-adapters.ts",
|
||||
"ui.render.failed": "src/application/create-application.ts",
|
||||
"release.mismatch.detected": "src/application/create-application.ts",
|
||||
"service-worker.start.failed": "src/bootstrap/optional-runtime-host.ts",
|
||||
@@ -39,7 +39,7 @@ const telemetryProducerFiles: Readonly<Record<string, string>> = {
|
||||
};
|
||||
const diagnosticProducerFiles: Readonly<Record<string, string>> = {
|
||||
"app.boot.failed": "src/adapters/diagnostics/bounded-diagnostics.ts",
|
||||
"http.request.completed": "src/adapters/http/client.ts",
|
||||
"http.request.completed": "src/bootstrap/runtime-adapters.ts",
|
||||
"cache.operation.failed":
|
||||
"src/adapters/query-cache/tanstack-query-cache.ts",
|
||||
"storage.operation.failed":
|
||||
|
||||
+93
-13
@@ -2,13 +2,18 @@ import { access, mkdir, readFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
|
||||
import { shouldRetry } from "../src/adapters/http/retry-policy.ts";
|
||||
import { createContractHttpExecutor } from "../src/adapters/http/index.ts";
|
||||
import { createTelemetryAdapter } from "../src/adapters/telemetry/best-effort-telemetry.ts";
|
||||
import { verifyCompatibilityTuple } from "../src/contracts/compatibility.ts";
|
||||
import type { StoragePort } from "../src/application/ports/storage-port.ts";
|
||||
import { decideChunkRecovery } from "../src/application/use-cases/decide-chunk-recovery.ts";
|
||||
import { validateRuntimeConfig } from "../src/bootstrap/runtime-config-schema.ts";
|
||||
import type { InstalledContractPackageIdentity } from "../src/contracts/external-contract-runtime.ts";
|
||||
import type {
|
||||
InstalledContractPackageIdentity,
|
||||
RetrySemantics,
|
||||
} from "../src/contracts/external-contract-runtime.ts";
|
||||
import { z } from "../src/contracts/zod.ts";
|
||||
import { zodValidator } from "../src/contracts/zod-validator.ts";
|
||||
import {
|
||||
parseReleaseArtifact,
|
||||
parseRuntimeConfigArtifact,
|
||||
@@ -241,17 +246,92 @@ async function drillChunkMismatch(context: DrillContext): Promise<DrillResult> {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* One operation through the V3 executor against a fixed answer. Returns how
|
||||
* many requests it sent, which is what retry amplification is measured in.
|
||||
*/
|
||||
async function physicalAttempts(
|
||||
retrySemantics: Extract<RetrySemantics, "SAFE" | "NEVER">,
|
||||
answer: () => Response,
|
||||
): Promise<number> {
|
||||
const read = retrySemantics === "SAFE";
|
||||
let sent = 0;
|
||||
const executor = createContractHttpExecutor({
|
||||
baseUrl: "https://api.invalid",
|
||||
maxRetryAttempts: 2,
|
||||
attachCredentials: () => ({ kind: "READY" as const, headers: {} }),
|
||||
fetcher: (async () => {
|
||||
sent += 1;
|
||||
return answer();
|
||||
}) as typeof fetch,
|
||||
sleep: async () => {},
|
||||
random: () => 0,
|
||||
});
|
||||
await executor.execute(
|
||||
Object.freeze({
|
||||
contract: Object.freeze({
|
||||
operationId: "DRILL_API_DEGRADATION",
|
||||
method: read ? ("GET" as const) : ("POST" as const),
|
||||
pathTemplate: "/api/drill",
|
||||
inputValidator: zodValidator("DrillInput", z.object({}).strict()),
|
||||
outputValidator: zodValidator(
|
||||
"DrillOutput",
|
||||
z.object({ id: z.string() }).strict(),
|
||||
),
|
||||
problemValidator: zodValidator(
|
||||
"DrillProblem",
|
||||
z.object({ code: z.string() }).strip(),
|
||||
),
|
||||
acceptedStatuses: Object.freeze([200]),
|
||||
emptyBodyStatuses: Object.freeze([]),
|
||||
retrySemantics,
|
||||
requestBody: read ? ("NONE" as const) : ("JSON" as const),
|
||||
responseBody: "REQUIRED_JSON" as const,
|
||||
commandRecovery: null,
|
||||
commandEffect: read
|
||||
? null
|
||||
: Object.freeze({
|
||||
successEffect: "APPLIED_CONFIRMED" as const,
|
||||
classifyProblem: () => "MAYBE_APPLIED" as const,
|
||||
}),
|
||||
projectRequest: () =>
|
||||
Object.freeze({
|
||||
pathValues: Object.freeze({}),
|
||||
queryEntries: Object.freeze([]),
|
||||
body: read ? null : Object.freeze({}),
|
||||
}),
|
||||
}),
|
||||
frontend: Object.freeze({
|
||||
policyId: "DRILL_API_V1",
|
||||
requestByteLimit: read ? 0 : 1_024,
|
||||
responseByteLimit: 4_096,
|
||||
totalDeadlineMs: 5_000,
|
||||
retryBudget: read ? (2 as const) : (0 as const),
|
||||
authProfileId: "ANONYMOUS",
|
||||
diagnosticsOperation: "drill.api",
|
||||
}),
|
||||
}),
|
||||
Object.freeze({}),
|
||||
{
|
||||
routeId: "DRILL_ROUTE",
|
||||
scope: Object.freeze({
|
||||
generation: 1,
|
||||
fingerprint: "drill-scope",
|
||||
identities: Object.freeze({}) as never,
|
||||
signal: new AbortController().signal,
|
||||
isCurrent: () => true,
|
||||
}),
|
||||
},
|
||||
);
|
||||
return sent;
|
||||
}
|
||||
|
||||
async function drillApiDegradation(): Promise<DrillResult> {
|
||||
const unkeyedRetry = shouldRetry(
|
||||
{ idempotency: "none" },
|
||||
{ kind: "SERVER_FAILURE", httpStatus: 503 },
|
||||
0,
|
||||
);
|
||||
const safeRetry = shouldRetry(
|
||||
{ idempotency: "safe" },
|
||||
{ kind: "SERVER_FAILURE", httpStatus: 503 },
|
||||
0,
|
||||
);
|
||||
const unavailable = () => Response.json({ code: "TEMPORARY" }, { status: 503 });
|
||||
const unkeyedRetry = (await physicalAttempts("NEVER", unavailable)) > 1;
|
||||
const safeRetry = (await physicalAttempts("SAFE", unavailable)) > 1;
|
||||
const schemaRetry =
|
||||
(await physicalAttempts("SAFE", () => Response.json({ unexpected: true }))) > 1;
|
||||
return {
|
||||
// The trigger is a failure rate over live traffic.
|
||||
triggerAsserted: "UNVERIFIED",
|
||||
@@ -263,7 +343,7 @@ async function drillApiDegradation(): Promise<DrillResult> {
|
||||
assertion(
|
||||
"schema fixtures",
|
||||
"schema mismatch is not retryable",
|
||||
verdict(!shouldRetry({ idempotency: "safe" }, { kind: "SCHEMA_MISMATCH" }, 0)),
|
||||
verdict(!schemaRetry),
|
||||
),
|
||||
],
|
||||
negativeFixtureFailedAsExpected: verdict(!unkeyedRetry),
|
||||
|
||||
@@ -21,9 +21,7 @@ const maximumWaiverDurationMs = 90 * 24 * 60 * 60 * 1_000;
|
||||
|
||||
export const REQUIRED_HIGH_RISK_PATHS = Object.freeze([
|
||||
"src/adapters/http/http-execution-v3.ts",
|
||||
"src/adapters/http/request-builder.ts",
|
||||
"src/adapters/http/bounded-body-reader.ts",
|
||||
"src/adapters/http/bounded-json.ts",
|
||||
"src/bootstrap/read-bounded-boot-json.ts",
|
||||
"src/adapters/service-worker/service-worker-lifecycle.ts",
|
||||
"src/adapters/query-cache/server-state-scope-runtime.ts",
|
||||
|
||||
@@ -4,19 +4,52 @@ import {
|
||||
type FailureKind,
|
||||
type ValidationIssue,
|
||||
} from "../../contracts/errors.ts";
|
||||
import {
|
||||
failureEnvelopeSchema,
|
||||
successEnvelopeSchema,
|
||||
} from "./schema-registry.ts";
|
||||
import { z } from "../../contracts/zod.ts";
|
||||
|
||||
/**
|
||||
* 1101 README 14.3. How this client reads the paired backend's Envelope
|
||||
* (clean-architecture-backend-template docs/web/http-contract.md §1, §2, §4).
|
||||
* The V2 client and a V3 operation that declares
|
||||
* `responseEnvelope: "ENVELOPE_V1"` both read it here, so the same answer gets
|
||||
* the same verdict on both paths.
|
||||
* (clean-architecture-backend-template docs/web/http-contract.md §1, §2, §4)
|
||||
* for a V3 operation that declares `responseEnvelope: "ENVELOPE_V1"`.
|
||||
*/
|
||||
|
||||
/**
|
||||
* 백엔드 1101/02-02. The paired backend drops a null field together with its
|
||||
* key (§1). The id keys are absent on an answer written before its request id
|
||||
* filter, so they are optional here too.
|
||||
*/
|
||||
const metaSchema = z
|
||||
.object({
|
||||
requestId: z.string().regex(/^[A-Za-z0-9._:-]{1,128}$/).optional(),
|
||||
traceId: z.string().regex(/^[A-Za-z0-9._:-]{1,128}$/).optional(),
|
||||
correlationId: z.string().regex(/^[A-Za-z0-9._:-]{1,128}$/).optional(),
|
||||
})
|
||||
.strip();
|
||||
|
||||
export const successEnvelopeSchema = z
|
||||
.object({
|
||||
success: z.literal(true),
|
||||
// A missing `data` is the null the backend dropped.
|
||||
data: z.unknown().default(null),
|
||||
meta: metaSchema,
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const failureEnvelopeSchema = z
|
||||
.object({
|
||||
success: z.literal(false),
|
||||
error: z
|
||||
.object({
|
||||
code: z.string().regex(/^[A-Z0-9_]{1,64}$/),
|
||||
category: z.string().min(1).max(64).optional(),
|
||||
message: z.string().max(1_024).optional(),
|
||||
retryable: z.boolean().optional(),
|
||||
details: z.unknown().optional(),
|
||||
})
|
||||
.strict(),
|
||||
meta: metaSchema,
|
||||
})
|
||||
.strict();
|
||||
|
||||
export type EnvelopeError = Readonly<{
|
||||
code: string;
|
||||
category?: string;
|
||||
@@ -150,7 +183,7 @@ export function gatewayFailureOr(status: number, kind: FailureKind): FailureKind
|
||||
: kind;
|
||||
}
|
||||
|
||||
/** The failure kind, code and field issues the V2 client reports. */
|
||||
/** The failure kind, code and field issues an unmapped problem reads as. */
|
||||
export function envelopeFailureReading(
|
||||
status: number,
|
||||
error: EnvelopeError,
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
import { decodeJsonBytes, readBoundedBytes } from "./bounded-body-reader.ts";
|
||||
|
||||
export type BoundedJsonResult =
|
||||
| Readonly<{ ok: true; value: unknown }>
|
||||
| Readonly<{ ok: false; code: "RESPONSE_BODY_LIMIT" | "MALFORMED_JSON" }>;
|
||||
|
||||
/**
|
||||
* N-08. The V2 compatibility reader delegates to the common bounded reader
|
||||
* instead of maintaining a second stream-reading strategy.
|
||||
*
|
||||
* `bounded-body-reader` already isolates `cancel()` and `releaseLock()` throws
|
||||
* so a cleanup failure cannot escape the closed result. Only the legacy failure
|
||||
* codes are preserved here:
|
||||
*
|
||||
* - `RESPONSE_TOO_LARGE` → `RESPONSE_BODY_LIMIT`
|
||||
* - `RESPONSE_STREAM_FAILURE` / `UTF8_INVALID` / `JSON_INVALID` →
|
||||
* `MALFORMED_JSON`
|
||||
*/
|
||||
export async function readBoundedJson(
|
||||
response: Response,
|
||||
maxBytes: number,
|
||||
): Promise<BoundedJsonResult> {
|
||||
const bytes = await readBoundedBytes(response, maxBytes);
|
||||
if (!bytes.ok) {
|
||||
return Object.freeze({
|
||||
ok: false as const,
|
||||
code:
|
||||
bytes.code === "RESPONSE_TOO_LARGE"
|
||||
? ("RESPONSE_BODY_LIMIT" as const)
|
||||
: ("MALFORMED_JSON" as const),
|
||||
});
|
||||
}
|
||||
// An absent body decodes to zero bytes, which is not valid JSON. The legacy
|
||||
// contract reported that as MALFORMED_JSON, and that is preserved.
|
||||
const decoded = decodeJsonBytes(bytes.bytes);
|
||||
return decoded.ok
|
||||
? Object.freeze({ ok: true as const, value: decoded.value })
|
||||
: Object.freeze({ ok: false as const, code: "MALFORMED_JSON" as const });
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -298,8 +298,8 @@ export function createFeatureHttpBinding<
|
||||
|
||||
/**
|
||||
* 1101 README 14.3. An Envelope operation's problem is the backend `error`
|
||||
* object, so what the feature does not map reads as the V2 client reads it:
|
||||
* the backend code, field issues from a validation failure, and the V2 kind.
|
||||
* object, so what the feature does not map still reads as the backend means
|
||||
* it: its code, field issues from a validation failure, and the status kind.
|
||||
*/
|
||||
function problemMapper<Problem>(
|
||||
mapProblem:
|
||||
@@ -524,7 +524,7 @@ function failureKindForViolation(violation: HttpContractViolation): FailureKind
|
||||
// 03-02. Only input the user can change is "input rejected"; a client
|
||||
// wiring defect (contract not installed, path template and projection
|
||||
// disagree, intent policy disagrees with the contract) cannot be fixed by
|
||||
// the user, the same reading as the V2 client's OPERATION_NOT_REGISTERED.
|
||||
// the user.
|
||||
case "FINAL_REQUEST_INVARIANT_FAILED":
|
||||
return violation.reason === undefined ||
|
||||
USER_INPUT_REJECTIONS.has(violation.reason)
|
||||
|
||||
@@ -51,7 +51,7 @@ export type CredentialAdmissionOutcome =
|
||||
const MAX_CREDENTIAL_HEADER_VALUE_BYTES = 8_192;
|
||||
|
||||
/**
|
||||
* R-3.4. The one credential value rule for V2 and V3: a ByteString (every code
|
||||
* R-3.4. The one credential value rule: a ByteString (every code
|
||||
* unit one byte on the wire) with no C0/C1 control characters. Fetch rejects
|
||||
* anything else only after the request counts as dispatched.
|
||||
*/
|
||||
|
||||
@@ -44,7 +44,7 @@ import {
|
||||
type MutationEffectCertainty,
|
||||
type PhysicalAttemptState,
|
||||
} from "./http-effect-certainty.ts";
|
||||
import { parseRetryAfter } from "./retry-policy.ts";
|
||||
import { parseRetryAfterDelay } from "../platform/retry-after.ts";
|
||||
import {
|
||||
envelopeFailureEffect,
|
||||
idempotencyRefusalReason,
|
||||
@@ -339,8 +339,8 @@ export type HttpExecutionObservation = Readonly<{
|
||||
* - an `HttpRequestRejectionReason`: copied from the refused request's
|
||||
* violation (03-02).
|
||||
* - an `IdempotencyRefusalReason`: an Envelope operation's backend refused
|
||||
* the idempotency key, the reason the V2 client records (1101 README 14.4).
|
||||
* No other backend code reaches diagnostics; the failure's code carries it.
|
||||
* the idempotency key (1101 README 14.4). No other backend code reaches
|
||||
* diagnostics; the failure's code carries it.
|
||||
*/
|
||||
export type HttpDiagnosticReason =
|
||||
| "CLASSIFIER_FAILED"
|
||||
@@ -1233,7 +1233,10 @@ async function admitResponse<Input, WireOutput, Problem>(
|
||||
const policy = operation.frontend;
|
||||
const isCommand = contract.commandEffect !== null;
|
||||
const status = response.status;
|
||||
const retryAfterMs = parseRetryAfter(response.headers.get("retry-after"));
|
||||
const retryAfterMs = parseRetryAfterDelay(
|
||||
response.headers.get("retry-after"),
|
||||
Date.now(),
|
||||
);
|
||||
|
||||
if (response.redirected || response.type === "opaqueredirect") {
|
||||
await response.body?.cancel().catch(() => {});
|
||||
@@ -1422,7 +1425,7 @@ async function admitResponse<Input, WireOutput, Problem>(
|
||||
}
|
||||
|
||||
// 1101 README 14.3. The frame is checked after the byte and structure
|
||||
// bounds, which count the whole Envelope, as V2 counts maxResponseBytes.
|
||||
// bounds, which count the whole Envelope.
|
||||
let wireValue = decoded.value;
|
||||
if (contract.responseEnvelope === "ENVELOPE_V1") {
|
||||
const framed = readSuccessEnvelope(decoded.value);
|
||||
@@ -1600,9 +1603,8 @@ async function admitProblem<Input, WireOutput, Problem>(
|
||||
const isCommand = contract.commandEffect !== null;
|
||||
const retryable = isRetryableHttpStatus(status);
|
||||
const enveloped = contract.responseEnvelope === "ENVELOPE_V1";
|
||||
// 1101 README 14.3. V2 bounds a failure Envelope by maxResponseBytes, the
|
||||
// same value as responseByteLimit. The problem ceiling stays the upper
|
||||
// bound, so V2 alone reads a failure Envelope between it and that limit.
|
||||
// 1101 README 14.3. A failure Envelope is bounded by the operation's
|
||||
// response limit too, and never above the problem ceiling.
|
||||
const problemByteLimit = enveloped
|
||||
? Math.min(
|
||||
HTTP_EXECUTION_CEILINGS.problemResponseBytes,
|
||||
@@ -1705,7 +1707,7 @@ async function admitProblem<Input, WireOutput, Problem>(
|
||||
}
|
||||
|
||||
// The backend's own verdict, when it has one, is the same for every
|
||||
// operation and the same one V2 gives. The package classifies the rest.
|
||||
// operation. The package classifies the rest.
|
||||
const classification =
|
||||
isCommand && backendEffect !== undefined
|
||||
? Object.freeze({ effect: backendEffect, contractRuntimeFailure: false })
|
||||
|
||||
@@ -37,25 +37,3 @@ export {
|
||||
} from "./feature-http-binding.ts";
|
||||
/** V3 `attachCredentials` 콜백이 반환해야 하는 결과 타입. */
|
||||
export type { CredentialPatchOutcome } from "./http-contract-bridge.ts";
|
||||
/**
|
||||
* V2 legacy. operationId + `LegacyHttpInput`으로 호출하는 범용 클라이언트다.
|
||||
* 새 코드는 위의 V3 실행기를 쓴다.
|
||||
*
|
||||
* 이 템플릿은 V2의 오퍼레이션 레지스트리와 payload 매퍼를 비워서 출하한다.
|
||||
* 제품이 `RuntimeHttpContract`(`src/bootstrap/runtime-adapters.ts`)의 네
|
||||
* 슬롯을 주입해야 동작한다. V2는 늘 `{ success, data | error, meta }` 봉투를
|
||||
* 읽는다. V3는 descriptor가 `responseEnvelope: "ENVELOPE_V1"`일 때만 봉투를
|
||||
* 읽고, 아니면 DTO 자체를 검증한다. 두 경로는 같은 봉투 해석
|
||||
* (`backend-envelope.ts`)을 쓴다.
|
||||
*/
|
||||
export {
|
||||
createHttpClient,
|
||||
type HttpClient,
|
||||
type HttpClientDependencies,
|
||||
type HttpFailure,
|
||||
type HttpResult,
|
||||
type LegacyHttpInput,
|
||||
type Scheduler,
|
||||
} from "./client.ts";
|
||||
/** V2 `HttpClient.execute`의 첫 인자 타입. */
|
||||
export type { OperationRequestInput } from "./request-builder.ts";
|
||||
|
||||
@@ -1,137 +0,0 @@
|
||||
import type { ApiOperation } from "../../contracts/api-operations.ts";
|
||||
|
||||
export type OperationRequestInput = Readonly<{
|
||||
operationId: string;
|
||||
routeId: string;
|
||||
pathParams?: Readonly<Record<string, string | number>>;
|
||||
searchParams?: unknown;
|
||||
body?: unknown;
|
||||
signal?: AbortSignal;
|
||||
idempotencyKey?: string;
|
||||
correlationId?: string;
|
||||
}>;
|
||||
|
||||
export type RequestTargetResult =
|
||||
| Readonly<{ success: true; url: URL }>
|
||||
| Readonly<{
|
||||
success: false;
|
||||
code:
|
||||
| "BASE_URL_INVALID"
|
||||
| "PATH_PARAMETER_MISSING"
|
||||
| "PATH_PARAMETER_UNEXPECTED"
|
||||
| "PATH_PARAMETER_INVALID"
|
||||
| "SEARCH_PARAMETER_INVALID";
|
||||
}>;
|
||||
|
||||
const pathParameterPattern = /:([A-Za-z][A-Za-z0-9_]*)|\{([A-Za-z][A-Za-z0-9_]*)\}/g;
|
||||
|
||||
export function buildRequestTarget(
|
||||
baseUrl: string,
|
||||
operation: ApiOperation,
|
||||
pathParams: Readonly<Record<string, string | number>> = {},
|
||||
parsedSearch: unknown = {},
|
||||
): RequestTargetResult {
|
||||
let base: URL;
|
||||
try {
|
||||
base = new URL(baseUrl);
|
||||
} catch {
|
||||
return { success: false, code: "BASE_URL_INVALID" };
|
||||
}
|
||||
if (
|
||||
(base.protocol !== "https:" &&
|
||||
!(
|
||||
base.protocol === "http:" &&
|
||||
["localhost", "127.0.0.1", "[::1]"].includes(base.hostname)
|
||||
)) ||
|
||||
base.username ||
|
||||
base.password ||
|
||||
base.search ||
|
||||
base.hash
|
||||
) {
|
||||
return { success: false, code: "BASE_URL_INVALID" };
|
||||
}
|
||||
|
||||
const placeholders = new Set<string>();
|
||||
for (const match of operation.path.matchAll(pathParameterPattern)) {
|
||||
placeholders.add(match[1] ?? match[2] ?? "");
|
||||
}
|
||||
if (Object.keys(pathParams).some((key) => !placeholders.has(key))) {
|
||||
return { success: false, code: "PATH_PARAMETER_UNEXPECTED" };
|
||||
}
|
||||
let missingPathParameter = false;
|
||||
let invalidPathParameter = false;
|
||||
const pathname = operation.path.replace(
|
||||
pathParameterPattern,
|
||||
(_token, colonName: string | undefined, braceName: string | undefined) => {
|
||||
const name = colonName ?? braceName ?? "";
|
||||
const value = pathParams[name];
|
||||
if (value === undefined) {
|
||||
missingPathParameter = true;
|
||||
return "";
|
||||
}
|
||||
const serialized = String(value);
|
||||
if (
|
||||
serialized.length === 0 ||
|
||||
serialized.length > 512 ||
|
||||
// Dot segments are not encoded and pathname assignment normalizes them.
|
||||
serialized === "." ||
|
||||
serialized === ".." ||
|
||||
[...serialized].some((character) => {
|
||||
const code = character.codePointAt(0) ?? 0;
|
||||
return code < 32 || code === 127;
|
||||
})
|
||||
) {
|
||||
invalidPathParameter = true;
|
||||
return "";
|
||||
}
|
||||
return encodeURIComponent(serialized);
|
||||
},
|
||||
);
|
||||
if (missingPathParameter) {
|
||||
return { success: false, code: "PATH_PARAMETER_MISSING" };
|
||||
}
|
||||
if (invalidPathParameter) {
|
||||
return { success: false, code: "PATH_PARAMETER_INVALID" };
|
||||
}
|
||||
|
||||
if (
|
||||
parsedSearch === null ||
|
||||
typeof parsedSearch !== "object" ||
|
||||
Array.isArray(parsedSearch)
|
||||
) {
|
||||
return { success: false, code: "SEARCH_PARAMETER_INVALID" };
|
||||
}
|
||||
|
||||
const basePrefix = base.pathname.endsWith("/")
|
||||
? base.pathname
|
||||
: `${base.pathname}/`;
|
||||
const relativePath = pathname.replace(/^\/+/, "");
|
||||
base.pathname = `${basePrefix}${relativePath}`.replace(/\/{2,}/g, "/");
|
||||
const url = base;
|
||||
const search = parsedSearch as Readonly<Record<string, unknown>>;
|
||||
for (const key of Object.keys(search).sort((left, right) =>
|
||||
left.localeCompare(right),
|
||||
)) {
|
||||
const value = search[key];
|
||||
if (value === undefined || value === null) continue;
|
||||
const values = Array.isArray(value) ? value : [value];
|
||||
for (const item of values) {
|
||||
if (
|
||||
typeof item !== "string" &&
|
||||
typeof item !== "number" &&
|
||||
typeof item !== "boolean"
|
||||
) {
|
||||
return { success: false, code: "SEARCH_PARAMETER_INVALID" };
|
||||
}
|
||||
url.searchParams.append(key, String(item));
|
||||
}
|
||||
}
|
||||
if (
|
||||
operation.maxEncodedSearchBytes !== undefined &&
|
||||
new TextEncoder().encode(url.search).byteLength >
|
||||
operation.maxEncodedSearchBytes
|
||||
) {
|
||||
return { success: false, code: "SEARCH_PARAMETER_INVALID" };
|
||||
}
|
||||
return { success: true, url };
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
import {
|
||||
mappingFailure,
|
||||
type BoundaryMappingResult,
|
||||
} from "../../contracts/boundary-mapper.ts";
|
||||
|
||||
export function mapOperationPayload(
|
||||
_operationId: string,
|
||||
_payload: unknown,
|
||||
): BoundaryMappingResult<never> {
|
||||
return mappingFailure("MAPPING_INVARIANT_REJECTED");
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
import { parseRetryAfterDelay } from "../platform/retry-after.ts";
|
||||
|
||||
const retryKinds: ReadonlySet<string> = new Set([
|
||||
"NETWORK_UNREACHABLE",
|
||||
"REQUEST_TIMEOUT",
|
||||
"RATE_LIMITED",
|
||||
"SERVER_FAILURE",
|
||||
]);
|
||||
|
||||
export function calculateBackoff(
|
||||
retryIndex: number,
|
||||
random = Math.random,
|
||||
baseDelayMs = 250,
|
||||
maxDelayMs = 2_000,
|
||||
): number {
|
||||
return Math.min(maxDelayMs, baseDelayMs * 2 ** retryIndex) * random();
|
||||
}
|
||||
|
||||
export function parseRetryAfter(
|
||||
value: string | null | undefined,
|
||||
now = Date.now(),
|
||||
): number | null {
|
||||
return parseRetryAfterDelay(value, now);
|
||||
}
|
||||
|
||||
export type RetryOperation = Readonly<{
|
||||
idempotency: "safe" | "keyed" | "none";
|
||||
retry?: "runtime" | "never";
|
||||
}>;
|
||||
|
||||
export type RetryFailure = Readonly<{
|
||||
kind: string;
|
||||
retryAfterMs?: number;
|
||||
retryAfter?: string;
|
||||
httpStatus?: number;
|
||||
}>;
|
||||
|
||||
export function shouldRetry(
|
||||
operation: RetryOperation,
|
||||
failure: RetryFailure,
|
||||
retryCount: number,
|
||||
maxRetries = 2,
|
||||
): boolean {
|
||||
if (operation.retry === "never") return false;
|
||||
if (retryCount >= maxRetries) return false;
|
||||
if (!retryKinds.has(failure.kind)) return false;
|
||||
if (
|
||||
failure.kind === "SERVER_FAILURE" &&
|
||||
failure.httpStatus !== undefined &&
|
||||
![408, 425, 502, 503, 504].includes(failure.httpStatus)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
typeof failure.retryAfterMs === "number" &&
|
||||
failure.retryAfterMs > 30_000
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
return operation.idempotency === "safe" || operation.idempotency === "keyed";
|
||||
}
|
||||
|
||||
export function retryDelay(
|
||||
failure: RetryFailure,
|
||||
retryIndex: number,
|
||||
random = Math.random,
|
||||
now = Date.now(),
|
||||
): number {
|
||||
const localBackoff = calculateBackoff(retryIndex, random);
|
||||
const retryAfterMs =
|
||||
typeof failure.retryAfterMs === "number"
|
||||
? failure.retryAfterMs
|
||||
: parseRetryAfter(failure.retryAfter, now);
|
||||
|
||||
return retryAfterMs === null ? localBackoff : Math.max(localBackoff, retryAfterMs);
|
||||
}
|
||||
@@ -1,117 +0,0 @@
|
||||
import { z } from "../../contracts/zod.ts";
|
||||
import { projectValidationIssues } from "../../contracts/validation-issues.ts";
|
||||
|
||||
/**
|
||||
* 백엔드 1101/02-02. The paired backend drops a null field together with its
|
||||
* key (clean-architecture-backend-template docs/web/http-contract.md §1). The
|
||||
* id keys are absent on an answer written before its request id filter, so
|
||||
* they are optional here too.
|
||||
*/
|
||||
const metaSchema = z
|
||||
.object({
|
||||
requestId: z.string().regex(/^[A-Za-z0-9._:-]{1,128}$/).optional(),
|
||||
traceId: z.string().regex(/^[A-Za-z0-9._:-]{1,128}$/).optional(),
|
||||
correlationId: z.string().regex(/^[A-Za-z0-9._:-]{1,128}$/).optional(),
|
||||
})
|
||||
.strip();
|
||||
|
||||
export const successEnvelopeSchema = z
|
||||
.object({
|
||||
success: z.literal(true),
|
||||
// A missing `data` is the null the backend dropped.
|
||||
data: z.unknown().default(null),
|
||||
meta: metaSchema,
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const failureEnvelopeSchema = z
|
||||
.object({
|
||||
success: z.literal(false),
|
||||
error: z
|
||||
.object({
|
||||
code: z.string().regex(/^[A-Z0-9_]{1,64}$/),
|
||||
category: z.string().min(1).max(64).optional(),
|
||||
message: z.string().max(1_024).optional(),
|
||||
retryable: z.boolean().optional(),
|
||||
details: z.unknown().optional(),
|
||||
})
|
||||
.strict(),
|
||||
meta: metaSchema,
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const responseEnvelopeSchema = z.discriminatedUnion("success", [
|
||||
successEnvelopeSchema,
|
||||
failureEnvelopeSchema,
|
||||
]);
|
||||
|
||||
const payloadSchemas: Readonly<Record<string, z.ZodType<unknown>>> =
|
||||
Object.freeze({});
|
||||
|
||||
const requestSchemas: Readonly<Record<string, z.ZodType<unknown>>> =
|
||||
Object.freeze({});
|
||||
|
||||
export type SchemaIssue = Readonly<{
|
||||
path: string;
|
||||
code: string;
|
||||
schemaId?: string;
|
||||
}>;
|
||||
|
||||
export type SchemaValidationResult =
|
||||
| Readonly<{ success: true; data: unknown }>
|
||||
| Readonly<{ success: false; issues: readonly SchemaIssue[] }>;
|
||||
|
||||
export function validateEnvelope(value: unknown): SchemaValidationResult {
|
||||
return projectResult(responseEnvelopeSchema.safeParse(value));
|
||||
}
|
||||
|
||||
export function validateOperationPayload(
|
||||
schemaId: string,
|
||||
value: unknown,
|
||||
): SchemaValidationResult {
|
||||
const schema = payloadSchemas[schemaId];
|
||||
if (!schema) return missingSchema(schemaId);
|
||||
return projectResult(schema.safeParse(value));
|
||||
}
|
||||
|
||||
export function validateOperationRequest(
|
||||
schemaId: string,
|
||||
value: unknown,
|
||||
): SchemaValidationResult {
|
||||
const schema = requestSchemas[schemaId];
|
||||
if (!schema) return missingSchema(schemaId);
|
||||
return projectResult(schema.safeParse(value));
|
||||
}
|
||||
|
||||
function missingSchema(schemaId: string): SchemaValidationResult {
|
||||
return {
|
||||
success: false,
|
||||
issues: [{ path: "", code: "SCHEMA_NOT_REGISTERED", schemaId }],
|
||||
};
|
||||
}
|
||||
|
||||
function projectResult(
|
||||
result:
|
||||
| Readonly<{ success: true; data: unknown }>
|
||||
| Readonly<{
|
||||
success: false;
|
||||
error: Readonly<{
|
||||
issues: readonly Readonly<{
|
||||
path: readonly PropertyKey[];
|
||||
code: string;
|
||||
}>[];
|
||||
}>;
|
||||
}>,
|
||||
): SchemaValidationResult {
|
||||
if (result.success) {
|
||||
return {
|
||||
success: true,
|
||||
data: structuredClone(result.data),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
issues: projectValidationIssues(result.error.issues),
|
||||
};
|
||||
}
|
||||
@@ -7,7 +7,6 @@ import {
|
||||
import { createDiagnosticsAdapter } from "../adapters/diagnostics/index.ts";
|
||||
import {
|
||||
createContractHttpExecutor,
|
||||
createHttpClient,
|
||||
type HttpExecutionObservation,
|
||||
type InstalledHttpOperationExecutor,
|
||||
} from "../adapters/http/index.ts";
|
||||
@@ -35,13 +34,8 @@ import {
|
||||
createTelemetryAdapter,
|
||||
createTelemetryCollector,
|
||||
} from "../adapters/telemetry/index.ts";
|
||||
import type { AuthSessionPort } from "../application/ports/auth-session-port.ts";
|
||||
import type { ReleaseInfo } from "../application/ports/release-info-port.ts";
|
||||
import {
|
||||
createRestProviderProfile,
|
||||
INSTALLED_REST_AUTH_PROFILES,
|
||||
} from "../contracts/rest-profiles.ts";
|
||||
import type { ClockPort } from "../application/ports/clock-port.ts";
|
||||
import { INSTALLED_REST_AUTH_PROFILES } from "../contracts/rest-profiles.ts";
|
||||
import { createInstalledFeatureLoaders } from "../features/installed-feature-adapters.ts";
|
||||
import {
|
||||
INVALIDATION_REGISTRY,
|
||||
@@ -72,41 +66,6 @@ import {
|
||||
indexInvalidationTopicVersions,
|
||||
} from "../contracts/query-invalidation.ts";
|
||||
|
||||
type HttpClientDependencies = Parameters<typeof createHttpClient>[0];
|
||||
/**
|
||||
* 제품이 V2 전송을 쓰려면 채워야 하는 슬롯 네 개.
|
||||
*
|
||||
* 이 템플릿은 넷 다 비워서 출하한다. 기본값인
|
||||
* `contracts/api-operations.ts`의 `API_OPERATIONS`는 빈 객체이고
|
||||
* `adapters/http/resource-mapper.ts`의 `mapOperationPayload`는 항상
|
||||
* `MAPPING_INVARIANT_REJECTED`를 반환한다. 그래서 **이 레포 상태 그대로는
|
||||
* V2로 어떤 오퍼레이션도 실행되지 않는다** — 그건 결함이 아니라 제품이
|
||||
* 채우는 자리다.
|
||||
*
|
||||
* V2는 V3를 그대로 되돌리는 롤백 경로가 아니다. 두 경로는 wire 형식이
|
||||
* 다르다. V2는 `{ success, data, meta }` 봉투를 검증하고
|
||||
* (`adapters/http/schema-registry.ts`), V3는 봉투 없는 DTO 자체를 검증한다.
|
||||
* 그래서 네 슬롯을 모두 주입해도 같은 백엔드로 V2로 되돌리면 모든 응답이
|
||||
* `ENVELOPE_MISMATCH`다. V2로 되돌리려면 슬롯 주입과 함께 서버도 V2 봉투로
|
||||
* 응답해야 한다.
|
||||
* V3(`createContractHttpExecutor`)는 설치된 feature 계약에서 오퍼레이션을
|
||||
* 받으므로 이 슬롯과 무관하게 동작한다.
|
||||
*/
|
||||
export type RuntimeHttpContract = Pick<
|
||||
HttpClientDependencies,
|
||||
"getOperation" | "validatePayload" | "validateRequest" | "mapPayload"
|
||||
>;
|
||||
|
||||
type RuntimeHttpContext = Readonly<{
|
||||
runtime: RuntimeConfigLoadResult;
|
||||
authSession: AuthSessionPort;
|
||||
fetcher?: typeof fetch;
|
||||
clock?: ClockPort;
|
||||
scheduler?: HttpClientDependencies["scheduler"];
|
||||
diagnostics?: HttpClientDependencies["diagnostics"];
|
||||
telemetry?: HttpClientDependencies["telemetry"];
|
||||
}>;
|
||||
|
||||
export type RuntimeAdaptersContext = Readonly<{
|
||||
runtime: RuntimeConfigLoadResult;
|
||||
release: Readonly<ReleaseManifest>;
|
||||
@@ -211,33 +170,6 @@ function storageOrUndefined(value: unknown): Storage | undefined {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Runtime-aware transport factory. Feature gateway composition calls this
|
||||
* factory when a registered API capability is installed.
|
||||
*/
|
||||
export function createRuntimeHttpClient(
|
||||
context: RuntimeHttpContext,
|
||||
contract: RuntimeHttpContract = {},
|
||||
) {
|
||||
return createHttpClient({
|
||||
baseUrl: context.runtime.config.API_BASE_URL,
|
||||
timeoutMs: context.runtime.config.REQUEST_TIMEOUT_MS,
|
||||
maxRetryAttempts: context.runtime.config.MAX_RETRY_ATTEMPTS,
|
||||
authSession: context.authSession,
|
||||
providerProfile: createRestProviderProfile(
|
||||
"PRIMARY_API",
|
||||
context.runtime.config.API_BASE_URL,
|
||||
["omit"],
|
||||
),
|
||||
fetcher: context.fetcher,
|
||||
clock: context.clock,
|
||||
scheduler: context.scheduler,
|
||||
diagnostics: context.diagnostics,
|
||||
telemetry: context.telemetry,
|
||||
...contract,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* VD-07. Exactly one diagnostic per logical V3 execution and exactly one
|
||||
* `api.request.failed` telemetry event per terminal non-abort failure.
|
||||
|
||||
@@ -7,11 +7,16 @@ import { createMemoryRouter, RouterProvider, useNavigate } from "react-router-do
|
||||
import { z } from "zod";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { createHttpClient } from "../../src/adapters/http/client.ts";
|
||||
import {
|
||||
createContractHttpExecutor,
|
||||
createFeatureHttpBinding,
|
||||
defineFeatureHttpOperation,
|
||||
} from "../../src/adapters/http/index.ts";
|
||||
import { mappingSuccess } from "../../src/contracts/boundary-mapper.ts";
|
||||
import { createFailure } from "../../src/contracts/errors.ts";
|
||||
import { createRuntimeIdentityRegistry } from "../../src/contracts/query-keys.ts";
|
||||
import { zodValidator } from "../../src/contracts/zod-validator.ts";
|
||||
import { useApplicationMutation } from "../../src/presentation/adapters/query/application-query.ts";
|
||||
import { TEST_HTTP_CONTRACT } from "../helpers/http-contract-fixture.ts";
|
||||
import { queryClient, scopeSnapshot, wrapper } from "./application-query-fixture.tsx";
|
||||
import { Button } from "../../src/presentation/components/ui/button.ts";
|
||||
import {
|
||||
@@ -24,6 +29,92 @@ import {
|
||||
useDirtyNavigationGuard,
|
||||
} from "../../src/presentation/forms/index.ts";
|
||||
|
||||
/**
|
||||
* A keyed create that reads the paired backend's Envelope, the shape
|
||||
* `create:feature` generates for a command.
|
||||
*/
|
||||
const FORM_CREATE_CONTRACT = Object.freeze({
|
||||
contract: Object.freeze({
|
||||
operationId: "FORM_CREATE_ENTITY",
|
||||
method: "POST" as const,
|
||||
pathTemplate: "/api/form-entities",
|
||||
inputValidator: zodValidator(
|
||||
"FormCreateEntityCommand",
|
||||
z.object({ name: z.string().min(1) }).strict(),
|
||||
),
|
||||
outputValidator: zodValidator(
|
||||
"FormEntity",
|
||||
z.object({ id: z.string(), name: z.string() }).strip(),
|
||||
),
|
||||
problemValidator: zodValidator(
|
||||
"FormProblem",
|
||||
z
|
||||
.object({
|
||||
code: z.string().regex(/^[A-Z0-9_]{1,64}$/u),
|
||||
details: z.unknown().optional(),
|
||||
})
|
||||
.strip(),
|
||||
),
|
||||
acceptedStatuses: Object.freeze([200]),
|
||||
emptyBodyStatuses: Object.freeze([]),
|
||||
retrySemantics: "KEYED" as const,
|
||||
requestBody: "JSON" as const,
|
||||
responseBody: "REQUIRED_JSON" as const,
|
||||
responseEnvelope: "ENVELOPE_V1" as const,
|
||||
commandRecovery: Object.freeze({
|
||||
mode: "IDEMPOTENCY_REPLAY" as const,
|
||||
operationIdentityField: "idempotencyKey",
|
||||
}),
|
||||
commandEffect: Object.freeze({
|
||||
successEffect: "APPLIED_CONFIRMED" as const,
|
||||
classifyProblem: () => "MAYBE_APPLIED" as const,
|
||||
}),
|
||||
projectRequest: (input: Readonly<{ name: string }>) =>
|
||||
Object.freeze({
|
||||
pathValues: Object.freeze({}),
|
||||
queryEntries: Object.freeze([]),
|
||||
body: Object.freeze({ ...input }),
|
||||
}),
|
||||
}),
|
||||
frontend: Object.freeze({
|
||||
policyId: "FORM_CREATE_V1",
|
||||
requestByteLimit: 1_024,
|
||||
responseByteLimit: 4_096,
|
||||
totalDeadlineMs: 5_000,
|
||||
retryBudget: 0 as const,
|
||||
authProfileId: "ANONYMOUS",
|
||||
diagnosticsOperation: "form.create",
|
||||
}),
|
||||
});
|
||||
|
||||
const FORM_OPERATIONS = Object.freeze({
|
||||
FORM_CREATE_ENTITY: defineFeatureHttpOperation({
|
||||
contract: FORM_CREATE_CONTRACT,
|
||||
routeId: "FORM_ROUTE",
|
||||
mapSuccess: (value) => mappingSuccess(value),
|
||||
}),
|
||||
});
|
||||
|
||||
function formBinding(fetcher: typeof fetch) {
|
||||
const executor = createContractHttpExecutor({
|
||||
baseUrl: "https://api.test",
|
||||
maxRetryAttempts: 0,
|
||||
attachCredentials: () => ({ kind: "READY" as const, headers: {} }),
|
||||
fetcher,
|
||||
});
|
||||
return createFeatureHttpBinding(
|
||||
Object.freeze({
|
||||
execute: (contract, input, context) =>
|
||||
executor.execute(contract, input, {
|
||||
routeId: context.routeId,
|
||||
scope: scopeSnapshot(),
|
||||
...(context.intent === undefined ? {} : { intent: context.intent }),
|
||||
}),
|
||||
}),
|
||||
FORM_OPERATIONS,
|
||||
);
|
||||
}
|
||||
|
||||
type Values = Readonly<Record<"name" | "note", string>>;
|
||||
|
||||
const schema = z
|
||||
@@ -155,14 +246,11 @@ describe("local form facade", () => {
|
||||
|
||||
// 백엔드 1101/02-01 후속. The paired backend answers a field validation
|
||||
// failure with 400 VALIDATION_FAILED and details [{field, code, message}]
|
||||
// (its docs/web/http-contract.md §4). It reaches the form through the V2
|
||||
// client and lands on the same allowed fields a 422 does.
|
||||
// (its docs/web/http-contract.md §4). It reaches the form through the HTTP
|
||||
// executor and lands on the same allowed fields a 422 does.
|
||||
it("maps a paired backend 400 VALIDATION_FAILED onto the form fields", async () => {
|
||||
const user = userEvent.setup();
|
||||
const client = createHttpClient({
|
||||
...TEST_HTTP_CONTRACT,
|
||||
baseUrl: "https://api.test",
|
||||
fetcher: async () =>
|
||||
const http = formBinding(async () =>
|
||||
Response.json(
|
||||
{
|
||||
success: false,
|
||||
@@ -180,14 +268,23 @@ describe("local form facade", () => {
|
||||
},
|
||||
{ status: 400 },
|
||||
),
|
||||
});
|
||||
);
|
||||
render(
|
||||
<FormHarness
|
||||
submit={async (command) => {
|
||||
const result = await client.execute("CREATE_ENTITY", {
|
||||
body: { name: command.name },
|
||||
idempotencyKey: "key-1",
|
||||
});
|
||||
const result = await http.execute(
|
||||
"FORM_CREATE_ENTITY",
|
||||
{ name: command.name },
|
||||
{
|
||||
intent: Object.freeze({
|
||||
intentId: "intent-1",
|
||||
operationId: "FORM_CREATE_ENTITY",
|
||||
canonicalInputIdentity: "{}",
|
||||
idempotencyKey: "key-1",
|
||||
createdAtMonotonicMs: 0,
|
||||
}),
|
||||
},
|
||||
);
|
||||
if (result.ok) throw new Error("expected a validation failure");
|
||||
return result;
|
||||
}}
|
||||
@@ -583,11 +680,11 @@ describe("submission timing", () => {
|
||||
});
|
||||
|
||||
/**
|
||||
* A server validation refusal through the V2 client and the mutation
|
||||
* A server validation refusal through the HTTP executor and the mutation
|
||||
* coordinator, with the reference form page's gate: the save button is off
|
||||
* while the coordinator holds an unknown effect.
|
||||
*/
|
||||
describe("correcting a field after a V2 validation refusal", () => {
|
||||
describe("correcting a field after a server validation refusal", () => {
|
||||
let token = 0;
|
||||
const scope = {
|
||||
...scopeSnapshot(),
|
||||
@@ -597,30 +694,21 @@ describe("correcting a field after a V2 validation refusal", () => {
|
||||
};
|
||||
|
||||
function CoordinatedForm(props: Readonly<{ fetcher: typeof fetch }>) {
|
||||
const [client] = useState(() =>
|
||||
createHttpClient({
|
||||
...TEST_HTTP_CONTRACT,
|
||||
baseUrl: "https://api.test",
|
||||
fetcher: props.fetcher,
|
||||
}),
|
||||
);
|
||||
const [http] = useState(() => formBinding(props.fetcher));
|
||||
const mutation = useApplicationMutation<
|
||||
Readonly<{ name: string; note?: string }>,
|
||||
unknown
|
||||
>({
|
||||
definitionId: "v2-create-v1",
|
||||
definitionId: "form-create-v1",
|
||||
definitionVersion: 1,
|
||||
operationId: "CREATE_ENTITY",
|
||||
operationId: "FORM_CREATE_ENTITY",
|
||||
requiresIdempotencyKey: true,
|
||||
owner: "platform-test",
|
||||
duplicatePolicy: "REJECT_WHILE_ACTIVE",
|
||||
scope,
|
||||
invalidate: [],
|
||||
execute: (command, { intent }) =>
|
||||
client.execute("CREATE_ENTITY", {
|
||||
body: { name: command.name },
|
||||
idempotencyKey: intent.idempotencyKey,
|
||||
}),
|
||||
http.execute("FORM_CREATE_ENTITY", { name: command.name }, { intent }),
|
||||
});
|
||||
const form = useAppForm({
|
||||
schema,
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
import { createHttpClient } from "../../../../src/adapters/http/client.ts";
|
||||
import { createContractHttpExecutor } from "../../../../src/adapters/http/http-execution-v3.ts";
|
||||
|
||||
export const leakedHttpFactory = createHttpClient;
|
||||
export const leakedHttpFactory = createContractHttpExecutor;
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
import "../../../../src/adapters/http/client.ts";
|
||||
import "../../../../src/adapters/http/http-execution-v3.ts";
|
||||
|
||||
export const invalidEdge = true;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import "../../../../src/adapters/http/client.ts";
|
||||
import "../../../../src/adapters/http/http-execution-v3.ts";
|
||||
|
||||
export function InvalidPresentationFixture() {
|
||||
return <p>invalid</p>;
|
||||
|
||||
+4
-13
@@ -1,25 +1,16 @@
|
||||
{
|
||||
"total": {
|
||||
"lines": { "total": 14, "covered": 14, "skipped": 0, "pct": 100 },
|
||||
"statements": { "total": 14, "covered": 14, "skipped": 0, "pct": 100 },
|
||||
"functions": { "total": 14, "covered": 14, "skipped": 0, "pct": 100 },
|
||||
"branches": { "total": 14, "covered": 14, "skipped": 0, "pct": 100 }
|
||||
"lines": { "total": 11, "covered": 11, "skipped": 0, "pct": 100 },
|
||||
"statements": { "total": 11, "covered": 11, "skipped": 0, "pct": 100 },
|
||||
"functions": { "total": 11, "covered": 11, "skipped": 0, "pct": 100 },
|
||||
"branches": { "total": 11, "covered": 11, "skipped": 0, "pct": 100 }
|
||||
},
|
||||
"src/adapters/http/bounded-body-reader.ts": {
|
||||
"lines": { "total": 1, "covered": 1, "skipped": 0, "pct": 100 }, "statements": { "total": 1, "covered": 1, "skipped": 0, "pct": 100 }, "functions": { "total": 1, "covered": 1, "skipped": 0, "pct": 100 }, "branches": { "total": 1, "covered": 1, "skipped": 0, "pct": 100 }
|
||||
},
|
||||
"src/adapters/http/bounded-json.ts": {
|
||||
"lines": { "total": 1, "covered": 1, "skipped": 0, "pct": 100 }, "statements": { "total": 1, "covered": 1, "skipped": 0, "pct": 100 }, "functions": { "total": 1, "covered": 1, "skipped": 0, "pct": 100 }, "branches": { "total": 1, "covered": 1, "skipped": 0, "pct": 100 }
|
||||
},
|
||||
"src/adapters/http/http-execution-v3.ts": {
|
||||
"lines": { "total": 1, "covered": 1, "skipped": 0, "pct": 100 }, "statements": { "total": 1, "covered": 1, "skipped": 0, "pct": 100 }, "functions": { "total": 1, "covered": 1, "skipped": 0, "pct": 100 }, "branches": { "total": 1, "covered": 1, "skipped": 0, "pct": 100 }
|
||||
},
|
||||
"src/adapters/http/request-builder.ts": {
|
||||
"lines": { "total": 1, "covered": 1, "skipped": 0, "pct": 100 }, "statements": { "total": 1, "covered": 1, "skipped": 0, "pct": 100 }, "functions": { "total": 1, "covered": 1, "skipped": 0, "pct": 100 }, "branches": { "total": 1, "covered": 1, "skipped": 0, "pct": 100 }
|
||||
},
|
||||
"src/adapters/http/retry-policy.ts": {
|
||||
"lines": { "total": 1, "covered": 1, "skipped": 0, "pct": 100 }, "statements": { "total": 1, "covered": 1, "skipped": 0, "pct": 100 }, "functions": { "total": 1, "covered": 1, "skipped": 0, "pct": 100 }, "branches": { "total": 1, "covered": 1, "skipped": 0, "pct": 100 }
|
||||
},
|
||||
"src/adapters/query-cache/server-state-scope-runtime.ts": {
|
||||
"lines": { "total": 1, "covered": 1, "skipped": 0, "pct": 100 }, "statements": { "total": 1, "covered": 1, "skipped": 0, "pct": 100 }, "functions": { "total": 1, "covered": 1, "skipped": 0, "pct": 100 }, "branches": { "total": 1, "covered": 1, "skipped": 0, "pct": 100 }
|
||||
},
|
||||
|
||||
@@ -1,115 +0,0 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { createHttpClient } from "../../src/adapters/http/client.ts";
|
||||
import { canonicalize } from "../../src/contracts/query-keys.ts";
|
||||
import { mappingSuccess } from "../../src/contracts/boundary-mapper.ts";
|
||||
import { createDemoSessionAdapter } from "../../src/adapters/auth/external-session-adapter.ts";
|
||||
|
||||
const entitySchema = z
|
||||
.object({
|
||||
id: z.string().min(1),
|
||||
name: z.string().min(1),
|
||||
})
|
||||
.passthrough();
|
||||
const payloadSchemas = {
|
||||
EntityListPayload: z.array(entitySchema),
|
||||
EntityPayload: entitySchema,
|
||||
};
|
||||
const requestSchemas = {
|
||||
EntityListQuery: z
|
||||
.object({
|
||||
cursor: z.string().optional(),
|
||||
limit: z.coerce.number().int().min(1).max(100).default(20),
|
||||
tags: z.array(z.string().trim().min(1)).optional(),
|
||||
})
|
||||
.strict(),
|
||||
CreateEntityCommand: z
|
||||
.object({ name: z.string().trim().min(1).max(120) })
|
||||
.strict(),
|
||||
};
|
||||
|
||||
export const TEST_OPERATIONS = Object.freeze({
|
||||
LIST_ENTITIES: Object.freeze({
|
||||
method: "GET",
|
||||
path: "/api/entities",
|
||||
operationId: "LIST_ENTITIES",
|
||||
auth: "external-session",
|
||||
timeoutMs: null,
|
||||
idempotency: "safe",
|
||||
retry: "runtime",
|
||||
requestSource: "search",
|
||||
requestSchema: "EntityListQuery",
|
||||
responseSchema: "EntityListPayload",
|
||||
owner: "test-fixture",
|
||||
}),
|
||||
CREATE_ENTITY: Object.freeze({
|
||||
method: "POST",
|
||||
path: "/api/entities",
|
||||
operationId: "CREATE_ENTITY",
|
||||
auth: "external-session",
|
||||
timeoutMs: null,
|
||||
idempotency: "keyed",
|
||||
retry: "runtime",
|
||||
requestSource: "body",
|
||||
requestSchema: "CreateEntityCommand",
|
||||
responseSchema: "EntityPayload",
|
||||
owner: "test-fixture",
|
||||
}),
|
||||
});
|
||||
|
||||
export const entityQueryKeys = Object.freeze({
|
||||
list: (filters: Readonly<Record<string, unknown>> = {}) =>
|
||||
Object.freeze(["entity", 1, canonicalize(filters)]),
|
||||
});
|
||||
|
||||
type Validation =
|
||||
| Readonly<{ success: true; data: unknown }>
|
||||
| Readonly<{ success: false }>;
|
||||
|
||||
function project(schema: z.ZodType | undefined, value: unknown): Validation {
|
||||
const result = schema?.safeParse(value);
|
||||
if (!result?.success) return { success: false };
|
||||
return { success: true, data: structuredClone(result.data) };
|
||||
}
|
||||
|
||||
type HttpDependencies = Parameters<typeof createHttpClient>[0];
|
||||
|
||||
export const TEST_HTTP_CONTRACT = Object.freeze({
|
||||
authSession: createDemoSessionAdapter("authenticated"),
|
||||
getOperation(operationId: string) {
|
||||
const operation =
|
||||
TEST_OPERATIONS[operationId as keyof typeof TEST_OPERATIONS];
|
||||
if (!operation) throw new Error(`Unknown test operation: ${operationId}`);
|
||||
return operation;
|
||||
},
|
||||
validatePayload(schemaId: string, value: unknown) {
|
||||
return project(
|
||||
payloadSchemas[schemaId as keyof typeof payloadSchemas],
|
||||
value,
|
||||
);
|
||||
},
|
||||
validateRequest(schemaId: string, value: unknown) {
|
||||
return project(
|
||||
requestSchemas[schemaId as keyof typeof requestSchemas],
|
||||
value,
|
||||
);
|
||||
},
|
||||
mapPayload(operationId: string, payload: unknown) {
|
||||
const mapOne = (value: unknown) => {
|
||||
const entity = value as { id: string; name: string };
|
||||
return { id: entity.id, displayName: entity.name };
|
||||
};
|
||||
if (operationId === "LIST_ENTITIES") {
|
||||
return mappingSuccess((payload as readonly unknown[]).map(mapOne));
|
||||
}
|
||||
if (operationId === "CREATE_ENTITY") return mappingSuccess(mapOne(payload));
|
||||
throw new Error(`Unknown test mapper: ${operationId}`);
|
||||
},
|
||||
}) satisfies Pick<
|
||||
HttpDependencies,
|
||||
| "authSession"
|
||||
| "getOperation"
|
||||
| "validatePayload"
|
||||
| "validateRequest"
|
||||
| "mapPayload"
|
||||
>;
|
||||
@@ -1,156 +0,0 @@
|
||||
import { HttpResponse, http } from "msw";
|
||||
import { setupServer } from "msw/node";
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { createExternalAuthSessionAdapter } from "../../src/adapters/auth/external-session-adapter.ts";
|
||||
import { createHttpClient } from "../../src/adapters/http/client.ts";
|
||||
import { TEST_HTTP_CONTRACT } from "../helpers/http-contract-fixture.ts";
|
||||
|
||||
let responseStatuses: number[] = [];
|
||||
const server = setupServer(
|
||||
http.get("https://api.test/api/entities", () => {
|
||||
const status = responseStatuses.shift() ?? 200;
|
||||
if (status !== 200) {
|
||||
return HttpResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: { code: status === 401 ? "UNAUTHENTICATED" : "UNAVAILABLE" },
|
||||
meta: { requestId: "request-1", traceId: "trace-1" },
|
||||
},
|
||||
{ status },
|
||||
);
|
||||
}
|
||||
return HttpResponse.json({
|
||||
success: true,
|
||||
data: [{ id: "resource-1", name: "Example" }],
|
||||
meta: { requestId: "request-2", traceId: "trace-1" },
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
beforeAll(() => server.listen({ onUnhandledRequest: "error" }));
|
||||
afterEach(() => {
|
||||
responseStatuses = [];
|
||||
server.resetHandlers();
|
||||
});
|
||||
afterAll(() => server.close());
|
||||
|
||||
const clock = { now: () => 0, sleep: async () => {} };
|
||||
|
||||
type HttpDependencies = Parameters<typeof createHttpClient>[0];
|
||||
|
||||
function testClient(options: HttpDependencies) {
|
||||
return createHttpClient({ ...TEST_HTTP_CONTRACT, ...options });
|
||||
}
|
||||
|
||||
type ExternalSessionOwner = Parameters<
|
||||
typeof createExternalAuthSessionAdapter
|
||||
>[0];
|
||||
|
||||
function createOwner(
|
||||
overrides: Partial<ExternalSessionOwner> = {},
|
||||
): ExternalSessionOwner {
|
||||
return {
|
||||
readState: () => "authenticated",
|
||||
readSubject: () => "user-a",
|
||||
subscribe: () => () => {},
|
||||
beginSignIn: async () => {},
|
||||
signOut: async () => {},
|
||||
attachCredential: async () => ({ headers: {} }),
|
||||
recoverSession: async () => "restored",
|
||||
notifyUnauthenticated: () => {},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("bounded 401 session recovery", () => {
|
||||
it("calls recovery once and replays a safe request once", async () => {
|
||||
responseStatuses = [401, 200];
|
||||
const recoverSession = vi.fn(async () => "restored" as const);
|
||||
const authSession = createExternalAuthSessionAdapter(createOwner({
|
||||
attachCredential: async () => ({ headers: {} }),
|
||||
recoverSession,
|
||||
notifyUnauthenticated: vi.fn(),
|
||||
}));
|
||||
const client = testClient({
|
||||
baseUrl: "https://api.test",
|
||||
authSession,
|
||||
clock,
|
||||
});
|
||||
|
||||
await expect(client.execute("LIST_ENTITIES")).resolves.toMatchObject({
|
||||
ok: true,
|
||||
});
|
||||
expect(recoverSession).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("stops after a second 401 and notifies unauthenticated once", async () => {
|
||||
responseStatuses = [401, 401];
|
||||
const notifyUnauthenticated = vi.fn();
|
||||
const authSession = createExternalAuthSessionAdapter(createOwner({
|
||||
attachCredential: async () => ({ headers: {} }),
|
||||
recoverSession: async () => "restored",
|
||||
notifyUnauthenticated,
|
||||
}));
|
||||
const client = testClient({
|
||||
baseUrl: "https://api.test",
|
||||
authSession,
|
||||
clock,
|
||||
});
|
||||
|
||||
await expect(client.execute("LIST_ENTITIES")).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: { kind: "AUTH_REQUIRED" },
|
||||
});
|
||||
expect(notifyUnauthenticated).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
// Q-6.3-11. Recovery is its own single replay, not a retry: an exhausted or
|
||||
// disabled retry budget must not turn a recoverable 401 into a logout.
|
||||
it.each([
|
||||
{ label: "retries are disabled", statuses: [401, 200], maxRetryAttempts: 0 },
|
||||
{
|
||||
label: "a 503 already used the retry budget",
|
||||
statuses: [503, 401, 200],
|
||||
maxRetryAttempts: 1,
|
||||
},
|
||||
])("recovers a 401 when $label", async ({ statuses, maxRetryAttempts }) => {
|
||||
responseStatuses = [...statuses];
|
||||
const recoverSession = vi.fn(async () => "restored" as const);
|
||||
const notifyUnauthenticated = vi.fn();
|
||||
const client = testClient({
|
||||
baseUrl: "https://api.test",
|
||||
authSession: createExternalAuthSessionAdapter(
|
||||
createOwner({ recoverSession, notifyUnauthenticated }),
|
||||
),
|
||||
clock,
|
||||
maxRetryAttempts,
|
||||
});
|
||||
|
||||
await expect(client.execute("LIST_ENTITIES")).resolves.toMatchObject({
|
||||
ok: true,
|
||||
});
|
||||
expect(recoverSession).toHaveBeenCalledTimes(1);
|
||||
expect(notifyUnauthenticated).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("normalizes attach and invalid recovery failures", async () => {
|
||||
const attachFailure = createExternalAuthSessionAdapter(createOwner({
|
||||
attachCredential: async () => {
|
||||
throw new Error("credential detail");
|
||||
},
|
||||
recoverSession: async () => "restored",
|
||||
notifyUnauthenticated: vi.fn(),
|
||||
}));
|
||||
const client = testClient({
|
||||
baseUrl: "https://api.test",
|
||||
authSession: attachFailure,
|
||||
clock,
|
||||
});
|
||||
|
||||
await expect(client.execute("LIST_ENTITIES")).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: { kind: "AUTH_INTEGRATION_FAILURE" },
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,701 +0,0 @@
|
||||
import { HttpResponse, http } from "msw";
|
||||
import { setupServer } from "msw/node";
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
|
||||
|
||||
import { createHttpClient } from "../../src/adapters/http/client.ts";
|
||||
import { mappingSuccess } from "../../src/contracts/boundary-mapper.ts";
|
||||
import {
|
||||
TEST_HTTP_CONTRACT,
|
||||
TEST_OPERATIONS,
|
||||
} from "../helpers/http-contract-fixture.ts";
|
||||
|
||||
let attempts = 0;
|
||||
const server = setupServer(
|
||||
http.get("https://api.test/api/entities", () => {
|
||||
attempts += 1;
|
||||
if (attempts < 3) {
|
||||
return HttpResponse.json(
|
||||
{ success: false, error: { code: "TEMPORARY" } },
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
return HttpResponse.json({
|
||||
success: true,
|
||||
data: [{ id: "resource-1", name: "Example" }],
|
||||
meta: { requestId: "request-1", traceId: "trace-1" },
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
beforeAll(() => server.listen({ onUnhandledRequest: "error" }));
|
||||
afterEach(() => {
|
||||
attempts = 0;
|
||||
server.resetHandlers();
|
||||
});
|
||||
afterAll(() => server.close());
|
||||
|
||||
const clock = {
|
||||
now: () => 0,
|
||||
sleep: async () => {},
|
||||
};
|
||||
|
||||
type HttpDependencies = Parameters<typeof createHttpClient>[0];
|
||||
|
||||
function testClient(options: HttpDependencies) {
|
||||
return createHttpClient({ ...TEST_HTTP_CONTRACT, ...options });
|
||||
}
|
||||
|
||||
describe("shared HTTP client", () => {
|
||||
it("retries a safe request at most twice and returns validated data", async () => {
|
||||
const client = testClient({
|
||||
baseUrl: "https://api.test",
|
||||
clock,
|
||||
random: () => 0,
|
||||
});
|
||||
|
||||
await expect(
|
||||
client.execute("LIST_ENTITIES", { routeId: "TEST_ROUTE" }),
|
||||
).resolves.toMatchObject({
|
||||
ok: true,
|
||||
value: [{ id: "resource-1", displayName: "Example" }],
|
||||
meta: { requestId: "request-1" },
|
||||
});
|
||||
expect(attempts).toBe(3);
|
||||
});
|
||||
|
||||
it.each(["", " ", "bad\u0000key", "x".repeat(513)])(
|
||||
"rejects invalid keyed command key %j before credentials and fetch",
|
||||
async (idempotencyKey) => {
|
||||
let fetched = 0;
|
||||
let credentialAttempts = 0;
|
||||
server.use(
|
||||
http.post("https://api.test/api/entities", () => {
|
||||
fetched += 1;
|
||||
return HttpResponse.json({ success: true, data: {} });
|
||||
}),
|
||||
);
|
||||
const client = testClient({
|
||||
baseUrl: "https://api.test",
|
||||
clock,
|
||||
authSession: {
|
||||
getState: () => "authenticated",
|
||||
getSubject: () => "user-a",
|
||||
subscribe: () => () => {},
|
||||
beginSignIn: async () => {},
|
||||
signOut: async () => {},
|
||||
async credentialPatch() {
|
||||
credentialAttempts += 1;
|
||||
return { headers: {} };
|
||||
},
|
||||
recover: async () => "no-session" as const,
|
||||
onUnauthenticated: () => {},
|
||||
},
|
||||
});
|
||||
|
||||
await expect(
|
||||
client.execute("CREATE_ENTITY", {
|
||||
body: { name: "n" },
|
||||
idempotencyKey,
|
||||
}),
|
||||
).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
kind: "VALIDATION_REJECTED",
|
||||
code: "IDEMPOTENCY_KEY_INVALID",
|
||||
// The repository reports attempt counts as 1-based; the invariant
|
||||
// proved below is that no physical attempt happened at all.
|
||||
attemptCount: 1,
|
||||
},
|
||||
});
|
||||
expect(fetched).toBe(0);
|
||||
expect(credentialAttempts).toBe(0);
|
||||
},
|
||||
);
|
||||
|
||||
it("bounds a non-cooperative legacy credential owner by total deadline", async () => {
|
||||
let fetched = 0;
|
||||
let observedSignal: AbortSignal | undefined;
|
||||
server.use(
|
||||
http.get("https://api.test/api/entities", () => {
|
||||
fetched += 1;
|
||||
return HttpResponse.json({ success: true, data: [] });
|
||||
}),
|
||||
);
|
||||
const client = testClient({
|
||||
baseUrl: "https://api.test",
|
||||
timeoutMs: 5,
|
||||
clock: { now: () => 0, sleep: async () => {} },
|
||||
authSession: {
|
||||
getState: () => "authenticated",
|
||||
getSubject: () => "user-a",
|
||||
subscribe: () => () => {},
|
||||
beginSignIn: async () => {},
|
||||
signOut: async () => {},
|
||||
credentialPatch: (_binding, context) => {
|
||||
observedSignal = context?.signal;
|
||||
// Never settles on its own.
|
||||
return new Promise<never>(() => {});
|
||||
},
|
||||
recover: async () => "no-session" as const,
|
||||
onUnauthenticated: () => {},
|
||||
},
|
||||
});
|
||||
|
||||
const result = await client.execute("LIST_ENTITIES");
|
||||
expect(result).toMatchObject({ ok: false });
|
||||
expect(fetched).toBe(0);
|
||||
expect(observedSignal).toBeDefined();
|
||||
});
|
||||
|
||||
it("rejects a non-JSON response without exposing its body", async () => {
|
||||
server.use(
|
||||
http.get(
|
||||
"https://api.test/api/entities",
|
||||
() => new HttpResponse("<secret>raw body</secret>", { status: 200 }),
|
||||
),
|
||||
);
|
||||
const client = testClient({ baseUrl: "https://api.test", clock });
|
||||
const result = await client.execute("LIST_ENTITIES");
|
||||
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: { kind: "CONTENT_TYPE_MISMATCH" },
|
||||
});
|
||||
expect(JSON.stringify(result)).not.toContain("raw body");
|
||||
});
|
||||
|
||||
// Q-6.3-3b. A gateway 5xx/408/425 with an HTML, empty or broken body is a
|
||||
// server outage, not a contract breach: it keeps its status and the V2
|
||||
// SERVER_FAILURE retry rule (408/425/502/503/504, R3-1).
|
||||
it.each([
|
||||
{ status: 502, contentType: "text/html", body: "<secret>raw body</secret>", fetches: 3 },
|
||||
{ status: 503, contentType: "application/json", body: "", fetches: 3 },
|
||||
{ status: 504, contentType: "application/json", body: "{", fetches: 3 },
|
||||
{ status: 408, contentType: "text/plain", body: "timeout", fetches: 3 },
|
||||
{ status: 425, contentType: "text/html", body: "<p>too early</p>", fetches: 3 },
|
||||
])(
|
||||
"keeps a $status gateway body as a server failure with its status",
|
||||
async ({ status, contentType, body, fetches }) => {
|
||||
let fetched = 0;
|
||||
server.use(
|
||||
http.get("https://api.test/api/entities", () => {
|
||||
fetched += 1;
|
||||
return new HttpResponse(body, {
|
||||
status,
|
||||
headers: { "Content-Type": contentType },
|
||||
});
|
||||
}),
|
||||
);
|
||||
const client = testClient({
|
||||
baseUrl: "https://api.test",
|
||||
clock,
|
||||
random: () => 0,
|
||||
});
|
||||
const result = await client.execute("LIST_ENTITIES");
|
||||
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: { kind: "SERVER_FAILURE", httpStatus: status },
|
||||
});
|
||||
expect(fetched).toBe(fetches);
|
||||
expect(JSON.stringify(result)).not.toContain("raw body");
|
||||
},
|
||||
);
|
||||
|
||||
const errorEnvelope = {
|
||||
success: false,
|
||||
error: { code: "UPSTREAM_BUSY" },
|
||||
meta: { requestId: "request-1", traceId: "trace-1" },
|
||||
};
|
||||
|
||||
// A gateway body (not an envelope) or a valid V2 error envelope.
|
||||
function busyResponse(
|
||||
status: number,
|
||||
envelope: boolean,
|
||||
headers: Record<string, string> = {},
|
||||
) {
|
||||
return envelope
|
||||
? HttpResponse.json(errorEnvelope, { status, headers })
|
||||
: new HttpResponse("busy", {
|
||||
status,
|
||||
headers: { "Content-Type": "text/plain", ...headers },
|
||||
});
|
||||
}
|
||||
|
||||
const busyCases = [408, 425, 503].flatMap((status) => [
|
||||
{ status, envelope: false },
|
||||
{ status, envelope: true },
|
||||
]);
|
||||
|
||||
// R3-1. A 408/425 with a valid error envelope is a server failure in V2 and
|
||||
// keeps the backend code the envelope carries.
|
||||
it.each([408, 425, 503])(
|
||||
"retries a safe request on a %i error envelope and keeps its code",
|
||||
async (status) => {
|
||||
let fetched = 0;
|
||||
server.use(
|
||||
http.get("https://api.test/api/entities", () => {
|
||||
fetched += 1;
|
||||
return busyResponse(status, true);
|
||||
}),
|
||||
);
|
||||
const client = testClient({
|
||||
baseUrl: "https://api.test",
|
||||
clock,
|
||||
random: () => 0,
|
||||
});
|
||||
|
||||
await expect(client.execute("LIST_ENTITIES")).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
kind: "SERVER_FAILURE",
|
||||
code: "UPSTREAM_BUSY",
|
||||
httpStatus: status,
|
||||
requestId: "request-1",
|
||||
},
|
||||
});
|
||||
expect(fetched).toBe(3);
|
||||
},
|
||||
);
|
||||
|
||||
// R3-1. 408/425/503 follow the retry rule of the operation: a keyed command
|
||||
// may replay, a non-idempotent command is never replayed.
|
||||
it.each(
|
||||
busyCases.flatMap((busy) => [
|
||||
{ ...busy, idempotency: "none" as const, fetches: 1 },
|
||||
{ ...busy, idempotency: "keyed" as const, fetches: 3 },
|
||||
]),
|
||||
)(
|
||||
"sends a $idempotency command $fetches time(s) on $status (envelope: $envelope)",
|
||||
async ({ status, envelope, idempotency, fetches }) => {
|
||||
let fetched = 0;
|
||||
server.use(
|
||||
http.post("https://api.test/api/entities", () => {
|
||||
fetched += 1;
|
||||
return busyResponse(status, envelope);
|
||||
}),
|
||||
);
|
||||
const client = testClient({
|
||||
baseUrl: "https://api.test",
|
||||
clock,
|
||||
random: () => 0,
|
||||
getOperation: () => ({ ...TEST_OPERATIONS.CREATE_ENTITY, idempotency }),
|
||||
});
|
||||
const result = await client.execute("CREATE_ENTITY", {
|
||||
body: { name: "n" },
|
||||
...(idempotency === "keyed" ? { idempotencyKey: "key-1" } : {}),
|
||||
});
|
||||
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: { kind: "SERVER_FAILURE", httpStatus: status },
|
||||
});
|
||||
expect(fetched).toBe(fetches);
|
||||
},
|
||||
);
|
||||
|
||||
function retryAfterClient(delays: number[]) {
|
||||
return testClient({
|
||||
baseUrl: "https://api.test",
|
||||
clock: {
|
||||
now: () => 0,
|
||||
sleep: async (ms: number) => {
|
||||
delays.push(ms);
|
||||
},
|
||||
},
|
||||
random: () => 0.5, // local backoff for the first retry: 125ms
|
||||
});
|
||||
}
|
||||
|
||||
function listAfter(first: () => Response) {
|
||||
let fetched = 0;
|
||||
server.use(
|
||||
http.get("https://api.test/api/entities", () => {
|
||||
fetched += 1;
|
||||
return fetched === 1
|
||||
? first()
|
||||
: HttpResponse.json({
|
||||
success: true,
|
||||
data: [],
|
||||
meta: { requestId: "request-1", traceId: "trace-1" },
|
||||
});
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
// R3-1. The retry waits at least the Retry-After of a 408/425/503, under
|
||||
// the same 30s ceiling as a 429.
|
||||
it.each(busyCases)(
|
||||
"waits for the Retry-After of a $status (envelope: $envelope)",
|
||||
async ({ status, envelope }) => {
|
||||
listAfter(() => busyResponse(status, envelope, { "Retry-After": "2" }));
|
||||
const delays: number[] = [];
|
||||
await expect(
|
||||
retryAfterClient(delays).execute("LIST_ENTITIES"),
|
||||
).resolves.toMatchObject({ ok: true });
|
||||
expect(delays).toEqual([2_000]);
|
||||
},
|
||||
);
|
||||
|
||||
// R3-1. 502/504 keep the local backoff whatever Retry-After says.
|
||||
it.each([502, 504])(
|
||||
"ignores the Retry-After of a %i",
|
||||
async (status) => {
|
||||
listAfter(() => busyResponse(status, true, { "Retry-After": "2" }));
|
||||
const delays: number[] = [];
|
||||
await expect(
|
||||
retryAfterClient(delays).execute("LIST_ENTITIES"),
|
||||
).resolves.toMatchObject({ ok: true });
|
||||
expect(delays).toEqual([125]);
|
||||
},
|
||||
);
|
||||
|
||||
it.each(busyCases)(
|
||||
"does not retry a $status whose Retry-After exceeds 30 seconds (envelope: $envelope)",
|
||||
async ({ status, envelope }) => {
|
||||
let fetched = 0;
|
||||
server.use(
|
||||
http.get("https://api.test/api/entities", () => {
|
||||
fetched += 1;
|
||||
return busyResponse(status, envelope, { "Retry-After": "31" });
|
||||
}),
|
||||
);
|
||||
const delays: number[] = [];
|
||||
await expect(
|
||||
retryAfterClient(delays).execute("LIST_ENTITIES"),
|
||||
).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: { kind: "SERVER_FAILURE", httpStatus: status, retryAfterMs: 31_000 },
|
||||
});
|
||||
expect(fetched).toBe(1);
|
||||
expect(delays).toEqual([]);
|
||||
},
|
||||
);
|
||||
|
||||
// R3-1. Retry-After goes through the platform kernel parser: delta-seconds
|
||||
// or an IMF-fixdate only. Anything else falls back to the local backoff.
|
||||
it.each([
|
||||
{ value: "2", delay: 2_000 },
|
||||
{ value: " 2 ", delay: 2_000 },
|
||||
{ value: "Thu, 01 Jan 1970 00:00:05 GMT", delay: 5_000 },
|
||||
{ value: "", delay: 125 },
|
||||
{ value: " ", delay: 125 },
|
||||
{ value: "1e3", delay: 125 },
|
||||
{ value: "1.5", delay: 125 },
|
||||
{ value: "0x10", delay: 125 },
|
||||
{ value: "-1", delay: 125 },
|
||||
{ value: "2099-01-01T00:00:00Z", delay: 125 },
|
||||
{ value: "Thursday, 01-Jan-70 00:00:05 GMT", delay: 125 },
|
||||
])("parses a 429 Retry-After of $value as $delay ms", async ({ value, delay }) => {
|
||||
let fetched = 0;
|
||||
server.use(
|
||||
http.get("https://api.test/api/entities", () => {
|
||||
fetched += 1;
|
||||
return fetched === 1
|
||||
? HttpResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: { code: "RATE_LIMITED" },
|
||||
meta: { requestId: "request-1", traceId: "trace-1" },
|
||||
},
|
||||
{ status: 429, headers: { "Retry-After": value } },
|
||||
)
|
||||
: HttpResponse.json({
|
||||
success: true,
|
||||
data: [],
|
||||
meta: { requestId: "request-1", traceId: "trace-1" },
|
||||
});
|
||||
}),
|
||||
);
|
||||
const delays: number[] = [];
|
||||
await expect(
|
||||
retryAfterClient(delays).execute("LIST_ENTITIES"),
|
||||
).resolves.toMatchObject({ ok: true });
|
||||
expect(delays).toEqual([delay]);
|
||||
});
|
||||
|
||||
it("classifies malformed JSON and invalid payloads at the boundary", async () => {
|
||||
server.use(
|
||||
http.get(
|
||||
"https://api.test/api/entities",
|
||||
() =>
|
||||
new HttpResponse("{", {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
}),
|
||||
),
|
||||
);
|
||||
const client = testClient({ baseUrl: "https://api.test", clock });
|
||||
await expect(client.execute("LIST_ENTITIES")).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: { kind: "MALFORMED_JSON" },
|
||||
});
|
||||
|
||||
server.use(
|
||||
http.get("https://api.test/api/entities", () =>
|
||||
HttpResponse.json({
|
||||
success: true,
|
||||
data: [{ id: "resource-1", name: 42 }],
|
||||
meta: { requestId: "request-1", traceId: "trace-1" },
|
||||
}),
|
||||
),
|
||||
);
|
||||
await expect(client.execute("LIST_ENTITIES")).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: { kind: "SCHEMA_MISMATCH" },
|
||||
});
|
||||
});
|
||||
|
||||
it("projects only approved 422 issue path and code metadata", async () => {
|
||||
server.use(
|
||||
http.post("https://api.test/api/entities", () =>
|
||||
HttpResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: {
|
||||
code: "INVALID_INPUT",
|
||||
message: "raw backend secret",
|
||||
details: {
|
||||
issues: [
|
||||
{ path: "name", code: "REQUIRED", message: "raw field copy" },
|
||||
{ path: 42, code: "INVALID" },
|
||||
],
|
||||
},
|
||||
},
|
||||
meta: { requestId: "request-422", traceId: "trace-422" },
|
||||
},
|
||||
{ status: 422 },
|
||||
),
|
||||
),
|
||||
);
|
||||
const client = testClient({ baseUrl: "https://api.test", clock });
|
||||
const result = await client.execute("CREATE_ENTITY", {
|
||||
routeId: "TEST_FORM",
|
||||
body: { name: "Valid" },
|
||||
});
|
||||
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
kind: "VALIDATION_REJECTED",
|
||||
validationIssues: [{ path: "name", code: "REQUIRED" }],
|
||||
},
|
||||
});
|
||||
expect(JSON.stringify(result)).not.toContain("raw backend secret");
|
||||
expect(JSON.stringify(result)).not.toContain("raw field copy");
|
||||
});
|
||||
|
||||
it("guards mapper exceptions as a mapping contract violation", async () => {
|
||||
server.use(
|
||||
http.get("https://api.test/api/entities", () =>
|
||||
HttpResponse.json({
|
||||
success: true,
|
||||
data: [{ id: "resource-1", name: "Example" }],
|
||||
meta: { requestId: "request-1", traceId: "trace-1" },
|
||||
}),
|
||||
),
|
||||
);
|
||||
const client = testClient({
|
||||
baseUrl: "https://api.test",
|
||||
clock,
|
||||
mapPayload: () => {
|
||||
throw new Error("raw mapper detail");
|
||||
},
|
||||
});
|
||||
|
||||
const result = await client.execute("LIST_ENTITIES");
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: { kind: "MAPPING_CONTRACT_VIOLATION" },
|
||||
});
|
||||
expect(JSON.stringify(result)).not.toContain("raw mapper detail");
|
||||
});
|
||||
});
|
||||
|
||||
// 백엔드 1101/02-01. The paired backend answers a same-key request while the
|
||||
// first still runs with 409 IDEMPOTENT_IN_FLIGHT, retryable and Retry-After 2.
|
||||
// The client does not resend it itself (the result is unknown); it hands the
|
||||
// Retry-After to whoever resends with the same key.
|
||||
it("keeps the Retry-After of an in-flight 409 without resending", async () => {
|
||||
let fetched = 0;
|
||||
server.use(
|
||||
http.post("https://api.test/api/entities", () => {
|
||||
fetched += 1;
|
||||
return HttpResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: {
|
||||
code: "IDEMPOTENT_IN_FLIGHT",
|
||||
category: "CONFLICT",
|
||||
message: "같은 요청을 처리하고 있습니다.",
|
||||
retryable: true,
|
||||
},
|
||||
meta: { requestId: "request-1", traceId: "trace-1" },
|
||||
},
|
||||
{ status: 409, headers: { "Retry-After": "2" } },
|
||||
);
|
||||
}),
|
||||
);
|
||||
const client = testClient({ baseUrl: "https://api.test", clock });
|
||||
|
||||
await expect(
|
||||
client.execute("CREATE_ENTITY", {
|
||||
body: { name: "n" },
|
||||
idempotencyKey: "key-1",
|
||||
}),
|
||||
).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
kind: "CONFLICT",
|
||||
code: "IDEMPOTENT_IN_FLIGHT",
|
||||
retryAfterMs: 2_000,
|
||||
},
|
||||
});
|
||||
expect(fetched).toBe(1);
|
||||
});
|
||||
|
||||
// 백엔드 1101/02-02. The paired backend drops a null field together with its
|
||||
// key (its docs/web/http-contract.md §1). A missing key must read as the null
|
||||
// it stands for.
|
||||
describe("envelope keys the paired backend omits", () => {
|
||||
const meta = { requestId: "request-1", traceId: "trace-1" };
|
||||
|
||||
it.each([
|
||||
{ shape: "data: null", body: { success: true, data: null, meta } },
|
||||
{ shape: "no data key", body: { success: true, meta } },
|
||||
])("reads a success with $shape as null data", async ({ body }) => {
|
||||
server.use(
|
||||
http.get("https://api.test/api/entities", () => HttpResponse.json(body)),
|
||||
);
|
||||
const validated: unknown[] = [];
|
||||
const client = testClient({
|
||||
baseUrl: "https://api.test",
|
||||
clock,
|
||||
validatePayload: (_schemaId, value) => {
|
||||
validated.push(value);
|
||||
return { success: true, data: value };
|
||||
},
|
||||
mapPayload: (_operationId, value) => mappingSuccess(value),
|
||||
});
|
||||
|
||||
await expect(client.execute("LIST_ENTITIES")).resolves.toMatchObject({
|
||||
ok: true,
|
||||
value: null,
|
||||
});
|
||||
expect(validated).toEqual([null]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ shape: "with ids and details", meta, details: { reason: "X" } },
|
||||
{ shape: "without details", meta, details: undefined },
|
||||
// Answered before the request id filter: the id keys are absent.
|
||||
{ shape: "without ids", meta: {}, details: undefined },
|
||||
])("keeps the backend code of a failure $shape", async ({ meta, details }) => {
|
||||
server.use(
|
||||
http.get("https://api.test/api/entities", () =>
|
||||
HttpResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: {
|
||||
code: "ACCESS_DENIED",
|
||||
category: "FORBIDDEN",
|
||||
message: "권한이 없습니다.",
|
||||
retryable: false,
|
||||
...(details === undefined ? {} : { details }),
|
||||
},
|
||||
meta,
|
||||
},
|
||||
{ status: 403 },
|
||||
),
|
||||
),
|
||||
);
|
||||
const client = testClient({ baseUrl: "https://api.test", clock });
|
||||
|
||||
await expect(client.execute("LIST_ENTITIES")).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: { kind: "FORBIDDEN", code: "ACCESS_DENIED", httpStatus: 403 },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// 백엔드 1101/02-01 후속. The paired backend answers a field validation
|
||||
// failure with 400 VALIDATION_FAILED, details [{field, code, message}]
|
||||
// (its docs/web/http-contract.md §4): read as the 422 field validation it is.
|
||||
// Every other 400 keeps its reading.
|
||||
describe("paired backend 400 VALIDATION_FAILED", () => {
|
||||
const meta = { requestId: "request-1", traceId: "trace-1" };
|
||||
|
||||
function answer400(code: string, details?: unknown) {
|
||||
server.use(
|
||||
http.post("https://api.test/api/entities", () =>
|
||||
HttpResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: {
|
||||
code,
|
||||
category: "VALIDATION",
|
||||
message: "요청 값이 올바르지 않습니다.",
|
||||
retryable: false,
|
||||
...(details === undefined ? {} : { details }),
|
||||
},
|
||||
meta,
|
||||
},
|
||||
{ status: 400 },
|
||||
),
|
||||
),
|
||||
);
|
||||
return testClient({ baseUrl: "https://api.test", clock }).execute(
|
||||
"CREATE_ENTITY",
|
||||
{ body: { name: "n" }, idempotencyKey: "key-1" },
|
||||
);
|
||||
}
|
||||
|
||||
it("reads the field details as validation issues, without backend copy", async () => {
|
||||
const result = await answer400("VALIDATION_FAILED", [
|
||||
{ field: "name", code: "NOT_BLANK", message: "raw backend copy" },
|
||||
{ field: "items.name", code: "SIZE", message: "raw backend copy" },
|
||||
{ field: "request", code: "INVALID", message: "raw backend copy" },
|
||||
]);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
kind: "VALIDATION_REJECTED",
|
||||
code: "VALIDATION_FAILED",
|
||||
httpStatus: 400,
|
||||
retryable: false,
|
||||
effect: "NOT_APPLIED",
|
||||
validationIssues: [
|
||||
{ path: "name", code: "NOT_BLANK" },
|
||||
{ path: "items.name", code: "SIZE" },
|
||||
{ path: "request", code: "INVALID" },
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(JSON.stringify(result)).not.toContain("raw backend copy");
|
||||
});
|
||||
|
||||
// 1101/14.4. The backend raises every VALIDATION_FAILED while it binds the
|
||||
// request, before it writes (frontend contract 6.1, backend 5786126c), so
|
||||
// it is not applied whatever its details are. BAD_PARAMETER can come from
|
||||
// any layer, after a write too.
|
||||
it.each([
|
||||
// A body that did not parse: details names the cause, not a field.
|
||||
{ code: "VALIDATION_FAILED", details: { cause: "JsonParseException" }, effect: "NOT_APPLIED" },
|
||||
{ code: "VALIDATION_FAILED", details: undefined, effect: "NOT_APPLIED" },
|
||||
// A page or sort parameter: one {field, code}, not a list.
|
||||
{ code: "VALIDATION_FAILED", details: { field: "size", code: "MAX" }, effect: "NOT_APPLIED" },
|
||||
{ code: "BAD_PARAMETER", details: { parameter: "limit" }, effect: undefined },
|
||||
])(
|
||||
"reads a 400 $code with details $details as a client failure, effect $effect",
|
||||
async ({ code, details, effect }) => {
|
||||
const result = await answer400(code, details);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: { kind: "UNKNOWN_CLIENT_FAILURE", code, httpStatus: 400 },
|
||||
});
|
||||
expect(result.ok ? null : result.error.validationIssues).toBeUndefined();
|
||||
expect(result.ok ? null : result.error.effect).toBe(effect);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -1,286 +0,0 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { createHttpClient } from "../../src/adapters/http/client.ts";
|
||||
import type { DiagnosticRecordInput } from "../../src/contracts/diagnostics.ts";
|
||||
import { TEST_HTTP_CONTRACT } from "../helpers/http-contract-fixture.ts";
|
||||
|
||||
function successResponse(data: unknown) {
|
||||
return Response.json({
|
||||
success: true,
|
||||
data,
|
||||
meta: { requestId: "request-1", traceId: "trace-1" },
|
||||
});
|
||||
}
|
||||
|
||||
function failureResponse(status: number) {
|
||||
return Response.json(
|
||||
{
|
||||
success: false,
|
||||
error: { code: "TEMPORARY" },
|
||||
meta: { requestId: "request-1", traceId: "trace-1" },
|
||||
},
|
||||
{ status },
|
||||
);
|
||||
}
|
||||
|
||||
type EmittedEvent = Readonly<{
|
||||
eventName: string;
|
||||
attributes: Readonly<Record<string, unknown>>;
|
||||
}>;
|
||||
|
||||
function harness(fetcher: typeof fetch, maxRetryAttempts = 1) {
|
||||
const records: DiagnosticRecordInput[] = [];
|
||||
const emitted: EmittedEvent[] = [];
|
||||
let currentTime = 0;
|
||||
const client = createHttpClient({
|
||||
...TEST_HTTP_CONTRACT,
|
||||
baseUrl: "https://api.test",
|
||||
fetcher,
|
||||
maxRetryAttempts,
|
||||
clock: {
|
||||
now: () => currentTime,
|
||||
sleep: async () => {
|
||||
currentTime += 150;
|
||||
},
|
||||
},
|
||||
scheduler: {
|
||||
setTimeout: () => 1,
|
||||
clearTimeout: () => {},
|
||||
},
|
||||
correlationIdFactory: () => "correlation-fixed",
|
||||
diagnostics: {
|
||||
record(input) {
|
||||
records.push(structuredClone(input));
|
||||
},
|
||||
},
|
||||
telemetry: {
|
||||
emit(eventName, attributes) {
|
||||
emitted.push({
|
||||
eventName,
|
||||
attributes: structuredClone(attributes),
|
||||
});
|
||||
},
|
||||
},
|
||||
});
|
||||
return { client, records, emitted };
|
||||
}
|
||||
|
||||
describe("HTTP diagnostics and terminal telemetry", () => {
|
||||
it("records one successful reference route outcome and no failure event", async () => {
|
||||
const { client, records, emitted } = harness(
|
||||
vi.fn(async () => successResponse([])),
|
||||
);
|
||||
|
||||
await expect(
|
||||
client.execute({
|
||||
operationId: "LIST_ENTITIES",
|
||||
routeId: "TEST_ROUTE",
|
||||
}),
|
||||
).resolves.toMatchObject({ ok: true });
|
||||
|
||||
expect(records).toEqual([
|
||||
{
|
||||
level: "info",
|
||||
eventId: "http.request.completed",
|
||||
context: {
|
||||
route_id: "TEST_ROUTE",
|
||||
operation_id: "LIST_ENTITIES",
|
||||
correlation_id: "correlation-fixed",
|
||||
outcome: "success",
|
||||
error_kind: "NONE",
|
||||
http_status_group: "2xx",
|
||||
attempt_count_bucket: "1",
|
||||
duration_bucket: "lt100ms",
|
||||
},
|
||||
},
|
||||
]);
|
||||
expect(emitted).toEqual([]);
|
||||
});
|
||||
|
||||
it("summarizes retry recovery once without a terminal failure event", async () => {
|
||||
const fetcher = vi
|
||||
.fn<typeof fetch>()
|
||||
.mockResolvedValueOnce(failureResponse(503))
|
||||
.mockResolvedValueOnce(successResponse([]));
|
||||
const { client, records, emitted } = harness(fetcher);
|
||||
|
||||
await expect(
|
||||
client.execute({
|
||||
operationId: "LIST_ENTITIES",
|
||||
routeId: "TEST_ROUTE",
|
||||
}),
|
||||
).resolves.toMatchObject({ ok: true });
|
||||
|
||||
expect(fetcher).toHaveBeenCalledTimes(2);
|
||||
expect(records).toHaveLength(1);
|
||||
expect(records[0]).toMatchObject({
|
||||
eventId: "http.request.completed",
|
||||
context: {
|
||||
outcome: "recovered",
|
||||
correlation_id: "correlation-fixed",
|
||||
duration_bucket: "100-499ms",
|
||||
},
|
||||
});
|
||||
expect(emitted).toEqual([]);
|
||||
});
|
||||
|
||||
it("emits one bounded terminal failure after all attempts", async () => {
|
||||
const fetcher = vi.fn(async () => failureResponse(503));
|
||||
const { client, records, emitted } = harness(fetcher);
|
||||
|
||||
await expect(
|
||||
client.execute({
|
||||
operationId: "CREATE_ENTITY",
|
||||
routeId: "TEST_ROUTE",
|
||||
body: { name: "private user input" },
|
||||
idempotencyKey: "private-idempotency-key",
|
||||
}),
|
||||
).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: { kind: "SERVER_FAILURE" },
|
||||
});
|
||||
|
||||
expect(fetcher).toHaveBeenCalledTimes(2);
|
||||
expect(records).toHaveLength(1);
|
||||
expect(emitted).toEqual([
|
||||
{
|
||||
eventName: "api.request.failed",
|
||||
attributes: {
|
||||
error_kind: "SERVER_FAILURE",
|
||||
http_status_group: "5xx",
|
||||
attempt_count_bucket: "2",
|
||||
route_id: "TEST_ROUTE",
|
||||
operation_id: "CREATE_ENTITY",
|
||||
duration_bucket: "100-499ms",
|
||||
},
|
||||
},
|
||||
]);
|
||||
expect(JSON.stringify({ records, emitted })).not.toMatch(
|
||||
/private user input|private-idempotency-key/,
|
||||
);
|
||||
});
|
||||
|
||||
it("records navigation abort without failure telemetry", async () => {
|
||||
const caller = new AbortController();
|
||||
caller.abort("navigation");
|
||||
const fetcher = vi.fn(async (request: RequestInfo | URL) => {
|
||||
const signal = (request as Request).signal;
|
||||
if (signal.aborted) throw new DOMException("aborted", "AbortError");
|
||||
return successResponse([]);
|
||||
});
|
||||
const { client, records, emitted } = harness(
|
||||
fetcher as unknown as typeof fetch,
|
||||
);
|
||||
|
||||
await expect(
|
||||
client.execute({
|
||||
operationId: "LIST_ENTITIES",
|
||||
routeId: "TEST_ROUTE",
|
||||
signal: caller.signal,
|
||||
}),
|
||||
).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: { kind: "REQUEST_ABORTED" },
|
||||
});
|
||||
|
||||
expect(records).toHaveLength(1);
|
||||
expect(records[0]).toMatchObject({
|
||||
eventId: "http.request.completed",
|
||||
context: { outcome: "aborted", error_kind: "REQUEST_ABORTED" },
|
||||
});
|
||||
expect(emitted).toEqual([]);
|
||||
});
|
||||
|
||||
// 백엔드 1101/02-01. The paired backend refuses these before it runs the
|
||||
// command (its docs/web/http-contract.md §2): not applied, not resent, and
|
||||
// diagnostics name the cause.
|
||||
it.each([
|
||||
{
|
||||
status: 422,
|
||||
code: "IDEMPOTENT_REQUEST_MISMATCH",
|
||||
kind: "VALIDATION_REJECTED",
|
||||
details: undefined,
|
||||
reason: "IDEMPOTENT_REQUEST_MISMATCH",
|
||||
},
|
||||
{
|
||||
status: 400,
|
||||
code: "IDEMPOTENCY_KEY_INVALID",
|
||||
kind: "UNKNOWN_CLIENT_FAILURE",
|
||||
details: { reason: "MALFORMED" },
|
||||
// This client checked the key before sending, so the two rules disagree.
|
||||
reason: "IDEMPOTENCY_KEY_RULE_MISMATCH",
|
||||
},
|
||||
])(
|
||||
"reports a $status $code as not applied, sent once, with reason $reason",
|
||||
async ({ status, code, kind, details, reason }) => {
|
||||
const fetcher = vi.fn(async () =>
|
||||
Response.json(
|
||||
{
|
||||
success: false,
|
||||
error: {
|
||||
code,
|
||||
category: "VALIDATION",
|
||||
message: "요청을 처리할 수 없습니다.",
|
||||
retryable: false,
|
||||
...(details === undefined ? {} : { details }),
|
||||
},
|
||||
meta: { requestId: "request-1", traceId: "trace-1" },
|
||||
},
|
||||
{ status },
|
||||
),
|
||||
);
|
||||
const { client, records } = harness(fetcher);
|
||||
|
||||
await expect(
|
||||
client.execute({
|
||||
operationId: "CREATE_ENTITY",
|
||||
routeId: "TEST_ROUTE",
|
||||
body: { name: "n" },
|
||||
idempotencyKey: "key-1",
|
||||
}),
|
||||
).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
kind,
|
||||
code,
|
||||
httpStatus: status,
|
||||
retryable: false,
|
||||
effect: "NOT_APPLIED",
|
||||
},
|
||||
});
|
||||
expect(fetcher).toHaveBeenCalledTimes(1);
|
||||
expect(records).toMatchObject([
|
||||
{ context: { outcome: "failed", error_kind: kind, reason } },
|
||||
]);
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
// 1101/14.4. Only IDEMPOTENT_REQUEST_MISMATCH is a 422 refused before a
|
||||
// write (frontend contract 6.1); fileserver's 422s come after one.
|
||||
{ status: 422, code: "INVALID_INPUT", effect: undefined },
|
||||
// Any other refusal keeps no effect: the coordinator holds it as unknown.
|
||||
{ status: 409, code: "SOMETHING_NEW", effect: undefined },
|
||||
])("gives an unrelated $status $code no reason", async ({ status, code, effect }) => {
|
||||
const fetcher = vi.fn(async () =>
|
||||
Response.json(
|
||||
{
|
||||
success: false,
|
||||
error: { code },
|
||||
meta: { requestId: "request-1", traceId: "trace-1" },
|
||||
},
|
||||
{ status },
|
||||
),
|
||||
);
|
||||
const { client, records } = harness(fetcher);
|
||||
|
||||
const result = await client.execute({
|
||||
operationId: "CREATE_ENTITY",
|
||||
routeId: "TEST_ROUTE",
|
||||
body: { name: "n" },
|
||||
});
|
||||
|
||||
expect(result.ok ? undefined : result.error.effect).toBe(effect);
|
||||
expect(records[0]?.context).not.toHaveProperty("reason");
|
||||
});
|
||||
});
|
||||
@@ -1,55 +1,9 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { createHttpClient } from "../../src/adapters/http/client.ts";
|
||||
import { createContractHttpExecutor } from "../../src/adapters/http/http-execution-v3.ts";
|
||||
import { joinMutationEffectCertainty } from "../../src/adapters/http/http-effect-certainty.ts";
|
||||
import {
|
||||
entityQueryKeys,
|
||||
TEST_HTTP_CONTRACT,
|
||||
} from "../helpers/http-contract-fixture.ts";
|
||||
import { TEST_CREATE_HTTP_CONTRACT } from "../helpers/external-contract-fixture.ts";
|
||||
|
||||
function successResponse(data: unknown) {
|
||||
return Response.json({
|
||||
success: true,
|
||||
data,
|
||||
meta: { requestId: "request-1", traceId: "trace-1" },
|
||||
});
|
||||
}
|
||||
|
||||
function failureResponse(status: number) {
|
||||
return Response.json(
|
||||
{
|
||||
success: false,
|
||||
error: { code: "TEMPORARY" },
|
||||
meta: { requestId: "request-1", traceId: "trace-1" },
|
||||
},
|
||||
{ status },
|
||||
);
|
||||
}
|
||||
|
||||
function immediateClock() {
|
||||
return { now: () => 0, sleep: async () => {} };
|
||||
}
|
||||
|
||||
function recordingScheduler() {
|
||||
const callbacks: Array<() => void> = [];
|
||||
return {
|
||||
callbacks,
|
||||
setTimeout: vi.fn((callback: () => void) => {
|
||||
callbacks.push(callback);
|
||||
return callbacks.length - 1;
|
||||
}),
|
||||
clearTimeout: vi.fn(),
|
||||
};
|
||||
}
|
||||
|
||||
type HttpDependencies = Parameters<typeof createHttpClient>[0];
|
||||
|
||||
function testClient(options: HttpDependencies) {
|
||||
return createHttpClient({ ...TEST_HTTP_CONTRACT, ...options });
|
||||
}
|
||||
|
||||
describe("mutation effect certainty lattice", () => {
|
||||
it.each([
|
||||
["NOT_STARTED", "NOT_APPLIED", "NOT_APPLIED"],
|
||||
@@ -138,257 +92,4 @@ describe("HTTP operation execution contract", () => {
|
||||
expect(attachCredentials).not.toHaveBeenCalled();
|
||||
expect(fetcher).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("fails auth-required execution before fetch when the session integration is unavailable", async () => {
|
||||
const fetcher = vi.fn();
|
||||
const client = testClient({
|
||||
baseUrl: "https://api.test",
|
||||
fetcher,
|
||||
authSession: undefined,
|
||||
});
|
||||
|
||||
await expect(
|
||||
client.execute({ operationId: "LIST_ENTITIES", routeId: "TEST_ROUTE" }),
|
||||
).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: { kind: "AUTH_INTEGRATION_FAILURE" },
|
||||
});
|
||||
expect(fetcher).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects an oversized response without materializing its JSON", async () => {
|
||||
const largeOperation = {
|
||||
...TEST_HTTP_CONTRACT.getOperation("LIST_ENTITIES"),
|
||||
maxResponseBytes: 32,
|
||||
responseMediaTypes: ["application/json"],
|
||||
successStatuses: [200],
|
||||
};
|
||||
const client = testClient({
|
||||
baseUrl: "https://api.test",
|
||||
getOperation: () => largeOperation,
|
||||
fetcher: vi.fn(async () =>
|
||||
Response.json({
|
||||
success: true,
|
||||
data: [{ id: "one", name: "a".repeat(100) }],
|
||||
meta: { requestId: "request-1", traceId: "trace-1" },
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
await expect(client.execute("LIST_ENTITIES")).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: { kind: "RESPONSE_BODY_LIMIT" },
|
||||
});
|
||||
});
|
||||
|
||||
it("sends parsed search/body values and aligns canonical query identity", async () => {
|
||||
const requests: Request[] = [];
|
||||
const scheduler = recordingScheduler();
|
||||
const fetcher = vi.fn(async (input: RequestInfo | URL) => {
|
||||
const request = input as Request;
|
||||
requests.push(request);
|
||||
if (request.method === "POST") {
|
||||
return successResponse({ id: "created", name: "Trimmed" });
|
||||
}
|
||||
return successResponse([]);
|
||||
});
|
||||
const client = testClient({
|
||||
baseUrl: "https://api.test",
|
||||
fetcher,
|
||||
clock: immediateClock(),
|
||||
scheduler,
|
||||
});
|
||||
const filters = { tags: ["open", "new"], cursor: "a/b", limit: 5 };
|
||||
|
||||
await client.execute({
|
||||
operationId: "LIST_ENTITIES",
|
||||
routeId: "TEST_ROUTE",
|
||||
searchParams: filters,
|
||||
});
|
||||
await client.execute({
|
||||
operationId: "CREATE_ENTITY",
|
||||
routeId: "TEST_ROUTE",
|
||||
body: { name: " Trimmed " },
|
||||
idempotencyKey: "logical-command",
|
||||
});
|
||||
|
||||
expect(requests[0].url).toBe(
|
||||
"https://api.test/api/entities?cursor=a%2Fb&limit=5&tags=open&tags=new",
|
||||
);
|
||||
expect(requests[0].headers.get("Idempotency-Key")).toBeNull();
|
||||
expect(entityQueryKeys.list(filters).at(-1)).toEqual(filters);
|
||||
await expect(requests[1].json()).resolves.toEqual({ name: "Trimmed" });
|
||||
expect(requests[1].headers.get("Idempotency-Key")).toBe("logical-command");
|
||||
expect(requests[1].url).not.toContain("logical-command");
|
||||
expect(requests[0].headers.get("X-Correlation-ID")).toBeTruthy();
|
||||
expect(requests[0].credentials).toBe("same-origin");
|
||||
expect(requests[0].cache).toBe("no-store");
|
||||
expect(requests[0].redirect).toBe("error");
|
||||
expect(scheduler.setTimeout).toHaveBeenCalledTimes(2);
|
||||
expect(scheduler.clearTimeout).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("performs no fetch or timer work for invalid request input", async () => {
|
||||
const fetcher = vi.fn();
|
||||
const scheduler = recordingScheduler();
|
||||
const client = testClient({
|
||||
baseUrl: "https://api.test",
|
||||
fetcher,
|
||||
scheduler,
|
||||
});
|
||||
|
||||
await expect(
|
||||
client.execute({
|
||||
operationId: "CREATE_ENTITY",
|
||||
routeId: "TEST_ROUTE",
|
||||
body: { name: " " },
|
||||
}),
|
||||
).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: { kind: "VALIDATION_REJECTED" },
|
||||
});
|
||||
expect(fetcher).not.toHaveBeenCalled();
|
||||
expect(scheduler.setTimeout).not.toHaveBeenCalled();
|
||||
expect(scheduler.clearTimeout).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
[0, 1],
|
||||
[1, 2],
|
||||
[2, 3],
|
||||
])(
|
||||
"applies runtime max retry count %i as %i total attempts",
|
||||
async (maxRetryAttempts, totalAttempts) => {
|
||||
const fetcher = vi.fn(async () => failureResponse(503));
|
||||
const scheduler = recordingScheduler();
|
||||
const client = testClient({
|
||||
baseUrl: "https://api.test",
|
||||
fetcher,
|
||||
clock: immediateClock(),
|
||||
scheduler,
|
||||
maxRetryAttempts,
|
||||
});
|
||||
|
||||
await expect(
|
||||
client.execute({
|
||||
operationId: "LIST_ENTITIES",
|
||||
routeId: "TEST_ROUTE",
|
||||
}),
|
||||
).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: { kind: "SERVER_FAILURE" },
|
||||
});
|
||||
expect(fetcher).toHaveBeenCalledTimes(totalAttempts);
|
||||
expect(scheduler.setTimeout).toHaveBeenCalledTimes(totalAttempts);
|
||||
expect(scheduler.clearTimeout).toHaveBeenCalledTimes(totalAttempts);
|
||||
},
|
||||
);
|
||||
|
||||
it("distinguishes a runtime timeout from caller navigation abort and cleans listeners", async () => {
|
||||
const scheduler = recordingScheduler();
|
||||
const fetcher = vi.fn(
|
||||
(input: RequestInfo | URL) =>
|
||||
new Promise<Response>((_resolve, reject) => {
|
||||
(input as Request).signal.addEventListener(
|
||||
"abort",
|
||||
() => reject(new DOMException("aborted", "AbortError")),
|
||||
{ once: true },
|
||||
);
|
||||
}),
|
||||
);
|
||||
const client = testClient({
|
||||
baseUrl: "https://api.test",
|
||||
fetcher,
|
||||
scheduler,
|
||||
maxRetryAttempts: 0,
|
||||
});
|
||||
const timeoutResult = client.execute({
|
||||
operationId: "LIST_ENTITIES",
|
||||
routeId: "TEST_ROUTE",
|
||||
});
|
||||
// The credential wait is bounded by the same attempt controller, so wait
|
||||
// until the request is actually in flight before firing the deadline.
|
||||
await vi.waitFor(() => expect(fetcher).toHaveBeenCalledTimes(1));
|
||||
await vi.waitFor(() => expect(scheduler.callbacks).toHaveLength(1));
|
||||
scheduler.callbacks[0]();
|
||||
await expect(timeoutResult).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: { kind: "REQUEST_TIMEOUT" },
|
||||
});
|
||||
|
||||
const caller = new AbortController();
|
||||
const add = vi.spyOn(caller.signal, "addEventListener");
|
||||
const remove = vi.spyOn(caller.signal, "removeEventListener");
|
||||
const abortResult = client.execute({
|
||||
operationId: "LIST_ENTITIES",
|
||||
routeId: "TEST_ROUTE",
|
||||
signal: caller.signal,
|
||||
});
|
||||
await vi.waitFor(() => expect(fetcher).toHaveBeenCalledTimes(2));
|
||||
caller.abort("navigation");
|
||||
await expect(abortResult).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: { kind: "REQUEST_ABORTED" },
|
||||
});
|
||||
expect(add).toHaveBeenCalledOnce();
|
||||
expect(remove).toHaveBeenCalledOnce();
|
||||
expect(scheduler.clearTimeout).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("never retries unsafe, non-retryable status, or schema failures", async () => {
|
||||
const unsafeOperation = {
|
||||
method: "POST",
|
||||
path: "/api/unsafe",
|
||||
operationId: "UNSAFE",
|
||||
auth: "none",
|
||||
timeoutMs: null,
|
||||
idempotency: "none",
|
||||
retry: "never",
|
||||
requestSource: "none",
|
||||
requestSchema: "unused",
|
||||
responseSchema: "EntityPayload",
|
||||
owner: "test",
|
||||
} as const;
|
||||
const unsafeFetch = vi.fn(async () => failureResponse(503));
|
||||
const unsafeClient = testClient({
|
||||
baseUrl: "https://api.test",
|
||||
fetcher: unsafeFetch,
|
||||
clock: immediateClock(),
|
||||
getOperation: () => unsafeOperation,
|
||||
});
|
||||
await unsafeClient.execute({
|
||||
operationId: "UNSAFE",
|
||||
routeId: "TEST",
|
||||
});
|
||||
expect(unsafeFetch).toHaveBeenCalledOnce();
|
||||
|
||||
const statusFetch = vi.fn(async () => failureResponse(500));
|
||||
const statusClient = testClient({
|
||||
baseUrl: "https://api.test",
|
||||
fetcher: statusFetch,
|
||||
clock: immediateClock(),
|
||||
});
|
||||
await statusClient.execute({
|
||||
operationId: "LIST_ENTITIES",
|
||||
routeId: "TEST_ROUTE",
|
||||
});
|
||||
expect(statusFetch).toHaveBeenCalledOnce();
|
||||
|
||||
const schemaFetch = vi.fn(async () =>
|
||||
successResponse([{ id: "one", name: 42 }]),
|
||||
);
|
||||
const schemaScheduler = recordingScheduler();
|
||||
const schemaClient = testClient({
|
||||
baseUrl: "https://api.test",
|
||||
fetcher: schemaFetch,
|
||||
clock: immediateClock(),
|
||||
scheduler: schemaScheduler,
|
||||
});
|
||||
await schemaClient.execute({
|
||||
operationId: "LIST_ENTITIES",
|
||||
routeId: "TEST_ROUTE",
|
||||
});
|
||||
expect(schemaFetch).toHaveBeenCalledOnce();
|
||||
expect(schemaScheduler.clearTimeout).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,7 +3,6 @@ import { setupServer } from "msw/node";
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { createHttpClient } from "../../src/adapters/http/client.ts";
|
||||
import {
|
||||
createContractHttpExecutor,
|
||||
createFeatureHttpBinding,
|
||||
@@ -21,7 +20,6 @@ import {
|
||||
type InstalledHttpContract,
|
||||
} from "../../src/contracts/external-contract-runtime.ts";
|
||||
import { zodValidator } from "../../src/contracts/zod-validator.ts";
|
||||
import { createDemoSessionAdapter } from "../../src/adapters/auth/external-session-adapter.ts";
|
||||
import { TEST_CONTRACT_CONTRIBUTION } from "../helpers/external-contract-fixture.ts";
|
||||
import { createHttpScenarioHandler } from "../mocks/handlers/http-scenarios.ts";
|
||||
|
||||
@@ -29,8 +27,8 @@ import { createHttpScenarioHandler } from "../mocks/handlers/http-scenarios.ts";
|
||||
* 1101 README 14.3. The paired backend answers every JSON body as an Envelope
|
||||
* (clean-architecture-backend-template docs/web/http-contract.md §1) and drops
|
||||
* a null field together with its key. A V3 operation that declares
|
||||
* `responseEnvelope: "ENVELOPE_V1"` reads it, and reaches the verdict the V2
|
||||
* client reaches for the same answer (§2 idempotency, §4 VALIDATION_FAILED).
|
||||
* `responseEnvelope: "ENVELOPE_V1"` reads it, and judges whether a refusal
|
||||
* applied by the backend's own table (frontend contract 6.1).
|
||||
*/
|
||||
const BASE_URL = "https://api.test";
|
||||
const LIST_LIMIT = 2_048;
|
||||
@@ -294,71 +292,6 @@ function intent(operationId: string) {
|
||||
});
|
||||
}
|
||||
|
||||
/** The same paths as V2 rows; V2 always reads the Envelope. */
|
||||
const V2_OPERATIONS = Object.freeze({
|
||||
ENVELOPE_LIST_ITEMS: Object.freeze({
|
||||
method: "GET",
|
||||
path: "/api/envelope-items",
|
||||
operationId: "ENVELOPE_LIST_ITEMS",
|
||||
auth: "external-session",
|
||||
timeoutMs: null,
|
||||
idempotency: "safe",
|
||||
retry: "runtime",
|
||||
requestSource: "none",
|
||||
requestSchema: "EnvelopeTestNoInput",
|
||||
responseSchema: "EnvelopeTestItemList",
|
||||
maxResponseBytes: LIST_LIMIT,
|
||||
owner: "test-fixture",
|
||||
}),
|
||||
ENVELOPE_CREATE_ITEM: Object.freeze({
|
||||
method: "POST",
|
||||
path: "/api/envelope-items",
|
||||
operationId: "ENVELOPE_CREATE_ITEM",
|
||||
auth: "external-session",
|
||||
timeoutMs: null,
|
||||
idempotency: "keyed",
|
||||
retry: "never",
|
||||
requestSource: "body",
|
||||
requestSchema: "EnvelopeTestNoInput",
|
||||
responseSchema: "EnvelopeTestItem",
|
||||
successStatuses: [201],
|
||||
maxResponseBytes: LIST_LIMIT,
|
||||
owner: "test-fixture",
|
||||
}),
|
||||
});
|
||||
const V2_PAYLOADS: Readonly<Record<string, z.ZodType>> = Object.freeze({
|
||||
EnvelopeTestItemList: z.array(itemSchema).max(100),
|
||||
EnvelopeTestItem: itemSchema,
|
||||
});
|
||||
|
||||
function v2(
|
||||
fetcher?: typeof fetch,
|
||||
diagnostics?: Readonly<{ record(input: DiagnosticRecordInput): void }>,
|
||||
) {
|
||||
return createHttpClient({
|
||||
baseUrl: BASE_URL,
|
||||
...(fetcher === undefined ? {} : { fetcher }),
|
||||
...(diagnostics === undefined ? {} : { diagnostics }),
|
||||
maxRetryAttempts: 0,
|
||||
clock: { now: () => 0, sleep: async () => {} },
|
||||
authSession: createDemoSessionAdapter("authenticated"),
|
||||
getOperation: (operationId: string) =>
|
||||
V2_OPERATIONS[operationId as keyof typeof V2_OPERATIONS],
|
||||
validatePayload(schemaId: string, value: unknown) {
|
||||
const parsed = V2_PAYLOADS[schemaId]?.safeParse(value);
|
||||
return parsed?.success
|
||||
? { success: true as const, data: parsed.data }
|
||||
: { success: false as const, issues: [] };
|
||||
},
|
||||
validateRequest: (_schemaId: string, value: unknown) => ({
|
||||
success: true as const,
|
||||
data: value,
|
||||
}),
|
||||
mapPayload: (_operationId: string, payload: unknown) =>
|
||||
mappingSuccess(payload),
|
||||
});
|
||||
}
|
||||
|
||||
/** What the mutation coordinator reads (`mutationFailureWithEffect`). */
|
||||
function verdict(error: AppFailure) {
|
||||
return {
|
||||
@@ -374,15 +307,6 @@ function verdict(error: AppFailure) {
|
||||
};
|
||||
}
|
||||
|
||||
async function v2CreateFailure(): Promise<AppFailure> {
|
||||
const result = await v2().execute("ENVELOPE_CREATE_ITEM", {
|
||||
body: {},
|
||||
idempotencyKey: KEY,
|
||||
});
|
||||
if (result.ok) throw new Error("V2 create unexpectedly succeeded");
|
||||
return result.error;
|
||||
}
|
||||
|
||||
async function v3CreateFailure(
|
||||
binding: Pick<ReturnType<typeof v3>, "execute"> = v3(),
|
||||
): Promise<AppFailure> {
|
||||
@@ -460,7 +384,7 @@ describe("V3 operation that reads the paired backend's Envelope", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("counts the whole Envelope against the byte limit, as V2 counts maxResponseBytes", async () => {
|
||||
it("counts the whole Envelope against the byte limit", async () => {
|
||||
// The data alone fits the limit; with its frame it does not.
|
||||
const name = "n".repeat(LIST_LIMIT - 120);
|
||||
const data = [{ id: "item-1", name }];
|
||||
@@ -470,14 +394,9 @@ describe("V3 operation that reads the paired backend's Envelope", () => {
|
||||
// settles a cancel() on a body it is still streaming.
|
||||
const fetcher = (async () => Response.json(success(data))) as typeof fetch;
|
||||
|
||||
const v3Result = await v3(fetcher).execute(
|
||||
"ENVELOPE_LIST_ITEMS",
|
||||
Object.freeze({}),
|
||||
);
|
||||
const v2Result = await v2(fetcher).execute("ENVELOPE_LIST_ITEMS", {});
|
||||
|
||||
expect(v3Result).toMatchObject({ ok: false, error: { kind: "RESPONSE_BODY_LIMIT" } });
|
||||
expect(v2Result).toMatchObject({ ok: false, error: { kind: "RESPONSE_BODY_LIMIT" } });
|
||||
await expect(
|
||||
v3(fetcher).execute("ENVELOPE_LIST_ITEMS", Object.freeze({})),
|
||||
).resolves.toMatchObject({ ok: false, error: { kind: "RESPONSE_BODY_LIMIT" } });
|
||||
});
|
||||
|
||||
it("applies the structure budget to the whole Envelope, not only data", async () => {
|
||||
@@ -494,7 +413,7 @@ describe("V3 operation that reads the paired backend's Envelope", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("V3 Envelope verdicts equal the V2 client's for the same answer", () => {
|
||||
describe("V3 Envelope verdicts follow the backend's refusal table", () => {
|
||||
const cases: readonly (readonly [
|
||||
string,
|
||||
Readonly<{ status: number; body: JsonBodyType; headers?: Record<string, string> }>,
|
||||
@@ -573,67 +492,47 @@ describe("V3 Envelope verdicts equal the V2 client's for the same answer", () =>
|
||||
],
|
||||
];
|
||||
|
||||
it.each(cases)("%s", async (_label, response) => {
|
||||
answer("post", "/api/envelope-items", response.body, response);
|
||||
const v2Verdict = verdict(await v2CreateFailure());
|
||||
const v3Verdict = verdict(await v3CreateFailure());
|
||||
|
||||
expect(v3Verdict).toEqual(v2Verdict);
|
||||
});
|
||||
|
||||
it("pins what those verdicts are", async () => {
|
||||
const read = async (response: (typeof cases)[number][1]) => {
|
||||
answer("post", "/api/envelope-items", response.body, response);
|
||||
return verdict(await v3CreateFailure());
|
||||
};
|
||||
const byLabel = new Map(cases);
|
||||
|
||||
await expect(read(byLabel.get("409 IDEMPOTENT_IN_FLIGHT")!)).resolves.toMatchObject({
|
||||
// 1101/14.4. Frontend contract 6.1: only the three codes the backend raises
|
||||
// before it writes are not applied; every other 400, 409 and 422 may be.
|
||||
const expected: Readonly<Record<string, Readonly<Record<string, unknown>>>> = {
|
||||
"409 IDEMPOTENT_IN_FLIGHT": {
|
||||
kind: "CONFLICT",
|
||||
code: "IDEMPOTENT_IN_FLIGHT",
|
||||
effect: "MAYBE_APPLIED",
|
||||
retryAfterMs: 2_000,
|
||||
});
|
||||
await expect(
|
||||
read(byLabel.get("422 IDEMPOTENT_REQUEST_MISMATCH")!),
|
||||
).resolves.toMatchObject({ kind: "VALIDATION_REJECTED", effect: "NOT_APPLIED" });
|
||||
await expect(read(byLabel.get("400 IDEMPOTENCY_KEY_INVALID")!)).resolves.toMatchObject({
|
||||
kind: "UNKNOWN_CLIENT_FAILURE",
|
||||
code: "IDEMPOTENCY_KEY_INVALID",
|
||||
effect: "NOT_APPLIED",
|
||||
});
|
||||
await expect(read(byLabel.get("503 IDEMPOTENCY_UNAVAILABLE")!)).resolves.toMatchObject({
|
||||
kind: "SERVER_FAILURE",
|
||||
effect: "MAYBE_APPLIED",
|
||||
});
|
||||
await expect(
|
||||
read(byLabel.get("400 VALIDATION_FAILED with the field list")!),
|
||||
).resolves.toMatchObject({
|
||||
},
|
||||
"422 IDEMPOTENT_REQUEST_MISMATCH": { kind: "VALIDATION_REJECTED", effect: "NOT_APPLIED" },
|
||||
"400 IDEMPOTENCY_KEY_INVALID": { kind: "UNKNOWN_CLIENT_FAILURE", effect: "NOT_APPLIED" },
|
||||
"503 IDEMPOTENCY_UNAVAILABLE": { kind: "SERVER_FAILURE", effect: "MAYBE_APPLIED" },
|
||||
"400 VALIDATION_FAILED with the field list": {
|
||||
kind: "VALIDATION_REJECTED",
|
||||
effect: "NOT_APPLIED",
|
||||
validationIssues: [{ path: "name", code: "NOT_BLANK" }],
|
||||
},
|
||||
"400 VALIDATION_FAILED for an unreadable body": {
|
||||
kind: "UNKNOWN_CLIENT_FAILURE",
|
||||
effect: "NOT_APPLIED",
|
||||
},
|
||||
"400 VALIDATION_FAILED without details": {
|
||||
kind: "UNKNOWN_CLIENT_FAILURE",
|
||||
effect: "NOT_APPLIED",
|
||||
},
|
||||
"400 VALIDATION_FAILED for a page parameter": {
|
||||
kind: "UNKNOWN_CLIENT_FAILURE",
|
||||
effect: "NOT_APPLIED",
|
||||
},
|
||||
"400 BAD_PARAMETER": { kind: "UNKNOWN_CLIENT_FAILURE", effect: "MAYBE_APPLIED" },
|
||||
"409 domain conflict": { kind: "CONFLICT", effect: "MAYBE_APPLIED" },
|
||||
"422 INTEGRITY_MISMATCH": { kind: "VALIDATION_REJECTED", effect: "MAYBE_APPLIED" },
|
||||
};
|
||||
|
||||
it.each(cases)("%s", async (label, response) => {
|
||||
answer("post", "/api/envelope-items", response.body, response);
|
||||
|
||||
await expect(v3CreateFailure().then(verdict)).resolves.toMatchObject({
|
||||
httpStatus: response.status,
|
||||
...expected[label],
|
||||
});
|
||||
// 1101/14.4. Every VALIDATION_FAILED is raised before a write.
|
||||
for (const label of [
|
||||
"400 VALIDATION_FAILED for an unreadable body",
|
||||
"400 VALIDATION_FAILED without details",
|
||||
"400 VALIDATION_FAILED for a page parameter",
|
||||
]) {
|
||||
await expect(read(byLabel.get(label)!)).resolves.toMatchObject({
|
||||
kind: "UNKNOWN_CLIENT_FAILURE",
|
||||
code: "VALIDATION_FAILED",
|
||||
effect: "NOT_APPLIED",
|
||||
});
|
||||
}
|
||||
// Codes the backend can raise after a write.
|
||||
for (const label of [
|
||||
"400 BAD_PARAMETER",
|
||||
"409 domain conflict",
|
||||
"422 INTEGRITY_MISMATCH",
|
||||
]) {
|
||||
await expect(read(byLabel.get(label)!)).resolves.toMatchObject({
|
||||
effect: "MAYBE_APPLIED",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// 1101/14.4. For an Envelope operation the table decides 400, 409 and 422
|
||||
@@ -685,10 +584,10 @@ describe("V3 Envelope verdicts equal the V2 client's for the same answer", () =>
|
||||
});
|
||||
});
|
||||
|
||||
// 1101 README 14.4. V2 names an idempotency refusal in diagnostics (`reason`,
|
||||
// a closed taxonomy). An Envelope operation's executor now knows the backend
|
||||
// code and names the same ones; any other code stays out of diagnostics.
|
||||
describe("V3 Envelope diagnostics name what V2 names", () => {
|
||||
// 1101 README 14.4. An Envelope operation's executor knows the backend code
|
||||
// and names an idempotency refusal in diagnostics (`reason`, a closed
|
||||
// taxonomy); any other code stays out of diagnostics.
|
||||
describe("V3 Envelope diagnostics name idempotency refusals", () => {
|
||||
it.each([
|
||||
["422 IDEMPOTENT_REQUEST_MISMATCH", 422, "IDEMPOTENT_REQUEST_MISMATCH", "IDEMPOTENT_REQUEST_MISMATCH"],
|
||||
["400 IDEMPOTENCY_KEY_INVALID", 400, "IDEMPOTENCY_KEY_INVALID", "IDEMPOTENCY_KEY_RULE_MISMATCH"],
|
||||
@@ -696,25 +595,18 @@ describe("V3 Envelope diagnostics name what V2 names", () => {
|
||||
["409 domain conflict", 409, "RESOURCE_CONFLICT", undefined],
|
||||
] as const)("%s", async (_label, status, code, reason) => {
|
||||
answer("post", "/api/envelope-items", failure(code, "VALIDATION", false), { status });
|
||||
const v2Records: DiagnosticRecordInput[] = [];
|
||||
const v3Records: DiagnosticRecordInput[] = [];
|
||||
const records: DiagnosticRecordInput[] = [];
|
||||
const project = createHttpObservationProjector({
|
||||
diagnostics: { record: (input) => v3Records.push(input) },
|
||||
diagnostics: { record: (input) => records.push(input) },
|
||||
telemetry: { emit: () => {} },
|
||||
});
|
||||
|
||||
await v2(undefined, { record: (input) => v2Records.push(input) }).execute(
|
||||
"ENVELOPE_CREATE_ITEM",
|
||||
{ body: {}, idempotencyKey: KEY },
|
||||
);
|
||||
await v3CreateFailure(
|
||||
createFeatureHttpBinding(v3Executor(undefined, project), OPERATIONS),
|
||||
);
|
||||
|
||||
expect(v2Records).toHaveLength(1);
|
||||
expect(v3Records).toHaveLength(1);
|
||||
expect(v3Records[0]?.context?.reason).toBe(reason);
|
||||
expect(v3Records[0]?.context?.reason).toBe(v2Records[0]?.context?.reason);
|
||||
expect(records).toHaveLength(1);
|
||||
expect(records[0]?.context?.reason).toBe(reason);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,240 +0,0 @@
|
||||
import { HttpResponse, http } from "msw";
|
||||
import { setupServer } from "msw/node";
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { createHttpClient } from "../../src/adapters/http/client.ts";
|
||||
import { defineRestOperation } from "../../src/contracts/api-operations.ts";
|
||||
import { createRestProviderProfile } from "../../src/contracts/rest-profiles.ts";
|
||||
import { TEST_HTTP_CONTRACT } from "../helpers/http-contract-fixture.ts";
|
||||
|
||||
/**
|
||||
* LEG-01 / LEG-02. The V2 client is not the default path any more, but a
|
||||
* rollback re-activates it, so its credential and recovery authority must match
|
||||
* V3 rather than diverge quietly.
|
||||
*/
|
||||
|
||||
const BEARER_LIST = defineRestOperation({
|
||||
method: "GET",
|
||||
path: "/api/entities",
|
||||
operationId: "LIST_ENTITIES",
|
||||
auth: "external-session",
|
||||
timeoutMs: null,
|
||||
idempotency: "safe",
|
||||
retry: "runtime",
|
||||
requestSource: "search",
|
||||
requestSchema: "EntityListQuery",
|
||||
responseSchema: "EntityListPayload",
|
||||
owner: "test-fixture",
|
||||
contractVersion: 2,
|
||||
protocol: "REST",
|
||||
semantics: "QUERY",
|
||||
replayPolicy: "SAFE",
|
||||
idempotencyKeyPolicy: "NONE",
|
||||
mapperId: "EntityListMapper",
|
||||
successStatuses: [200],
|
||||
responseMediaTypes: ["application/json"],
|
||||
maxResponseBytes: 32_768,
|
||||
providerId: "PRIMARY_API",
|
||||
authProfileId: "EXTERNAL_BEARER",
|
||||
csrfProfileId: "NO_CSRF_BEARER",
|
||||
pathSchema: "NoRequest",
|
||||
pathParameterNames: [],
|
||||
maxEncodedSearchBytes: 1_024,
|
||||
});
|
||||
|
||||
let observedAuthorization: string | null = null;
|
||||
let requestCount = 0;
|
||||
let nextStatus = 200;
|
||||
|
||||
const server = setupServer(
|
||||
http.get("https://api.test/api/entities", ({ request }) => {
|
||||
requestCount += 1;
|
||||
observedAuthorization = request.headers.get("authorization");
|
||||
if (nextStatus === 401) {
|
||||
return HttpResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: { code: "UNAUTHENTICATED" },
|
||||
meta: { requestId: "request-1", traceId: "trace-1" },
|
||||
},
|
||||
{ status: 401 },
|
||||
);
|
||||
}
|
||||
return HttpResponse.json({
|
||||
success: true,
|
||||
data: [{ id: "resource-1", name: "Example" }],
|
||||
meta: { requestId: "request-2", traceId: "trace-1" },
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
beforeAll(() => server.listen({ onUnhandledRequest: "error" }));
|
||||
afterEach(() => {
|
||||
observedAuthorization = null;
|
||||
requestCount = 0;
|
||||
nextStatus = 200;
|
||||
server.resetHandlers();
|
||||
});
|
||||
afterAll(() => server.close());
|
||||
|
||||
const clock = { now: () => 0, sleep: async () => {} };
|
||||
|
||||
type HttpDependencies = Parameters<typeof createHttpClient>[0];
|
||||
|
||||
function bearerClient(options: Partial<HttpDependencies>) {
|
||||
return createHttpClient({
|
||||
...TEST_HTTP_CONTRACT,
|
||||
getOperation: (operationId: string) => {
|
||||
if (operationId !== "LIST_ENTITIES") {
|
||||
throw new Error(`Unknown test operation: ${operationId}`);
|
||||
}
|
||||
return BEARER_LIST;
|
||||
},
|
||||
baseUrl: "https://api.test",
|
||||
providerProfile: createRestProviderProfile("PRIMARY_API", "https://api.test", [
|
||||
"omit",
|
||||
]),
|
||||
// The V2 fixture declares `NoRequest` for its path codec, which the shared
|
||||
// schema registry does not carry.
|
||||
validatePath: () => ({ success: true as const, data: {} }),
|
||||
clock,
|
||||
...options,
|
||||
} as HttpDependencies);
|
||||
}
|
||||
|
||||
function sessionStub(
|
||||
overrides: Partial<{
|
||||
getState: () => "authenticated" | "unauthenticated" | "recovery-pending" | "integration-failed";
|
||||
credentialPatch: (...args: never[]) => Promise<{ headers: Record<string, string> }>;
|
||||
recover: (...args: never[]) => Promise<"restored" | "no-session">;
|
||||
onUnauthenticated: () => void;
|
||||
}> = {},
|
||||
) {
|
||||
return {
|
||||
getState: () => "authenticated" as const,
|
||||
subscribe: () => () => {},
|
||||
beginSignIn: async () => {},
|
||||
signOut: async () => {},
|
||||
credentialPatch: async () => ({ headers: { authorization: "Bearer t" } }),
|
||||
recover: async () => "restored" as const,
|
||||
onUnauthenticated: () => {},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("LEG-02 the bearer profile's required header is enforced", () => {
|
||||
it("refuses to dispatch when a READY patch omits authorization", async () => {
|
||||
const client = bearerClient({
|
||||
authSession: sessionStub({
|
||||
credentialPatch: async () => ({ headers: {} }),
|
||||
}) as never,
|
||||
});
|
||||
|
||||
await expect(client.execute("LIST_ENTITIES")).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: { kind: "AUTH_INTEGRATION_FAILURE" },
|
||||
});
|
||||
expect(requestCount).toBe(0);
|
||||
});
|
||||
|
||||
it("rejects a malformed or duplicated authorization value", async () => {
|
||||
const hostilePatches: readonly Record<string, string>[] = [
|
||||
{ authorization: "" },
|
||||
{ authorization: "Bearer bad\nvalue" },
|
||||
{ Authorization: "Bearer a", authorization: "Bearer b" },
|
||||
];
|
||||
for (const headers of hostilePatches) {
|
||||
const client = bearerClient({
|
||||
authSession: sessionStub({
|
||||
credentialPatch: async () => ({ headers }),
|
||||
}) as never,
|
||||
});
|
||||
await expect(client.execute("LIST_ENTITIES")).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: { kind: "AUTH_INTEGRATION_FAILURE" },
|
||||
});
|
||||
}
|
||||
expect(requestCount).toBe(0);
|
||||
});
|
||||
|
||||
it("dispatches with the admitted authorization header", async () => {
|
||||
const client = bearerClient({
|
||||
authSession: sessionStub() as never,
|
||||
});
|
||||
|
||||
await expect(client.execute("LIST_ENTITIES")).resolves.toMatchObject({
|
||||
ok: true,
|
||||
});
|
||||
expect(observedAuthorization).toBe("Bearer t");
|
||||
});
|
||||
});
|
||||
|
||||
describe("LEG-01 recovery notification follows the adopted result", () => {
|
||||
it("does not sign the user out when recovery answers after the deadline", async () => {
|
||||
nextStatus = 401;
|
||||
const onUnauthenticated = vi.fn();
|
||||
let elapsed = 0;
|
||||
const client = bearerClient({
|
||||
clock: {
|
||||
now: () => elapsed,
|
||||
sleep: async () => {},
|
||||
},
|
||||
timeoutMs: 20,
|
||||
authSession: sessionStub({
|
||||
onUnauthenticated,
|
||||
recover: async () => {
|
||||
// The request's own deadline expires while recovery is still out.
|
||||
elapsed = 10_000;
|
||||
await new Promise((resolve) => setTimeout(resolve, 30));
|
||||
return "no-session" as const;
|
||||
},
|
||||
}) as never,
|
||||
});
|
||||
|
||||
const outcome = await client.execute("LIST_ENTITIES");
|
||||
expect(outcome.ok).toBe(false);
|
||||
await new Promise((resolve) => setTimeout(resolve, 60));
|
||||
expect(onUnauthenticated).toHaveBeenCalledTimes(0);
|
||||
});
|
||||
|
||||
it("signs the user out exactly once for an adopted no-session result", async () => {
|
||||
nextStatus = 401;
|
||||
const onUnauthenticated = vi.fn();
|
||||
const client = bearerClient({
|
||||
authSession: sessionStub({
|
||||
onUnauthenticated,
|
||||
recover: async () => "no-session" as const,
|
||||
}) as never,
|
||||
});
|
||||
|
||||
await expect(client.execute("LIST_ENTITIES")).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: { kind: "AUTH_REQUIRED" },
|
||||
});
|
||||
expect(onUnauthenticated).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("stays bounded when recovery never settles", async () => {
|
||||
nextStatus = 401;
|
||||
const onUnauthenticated = vi.fn();
|
||||
let elapsed = 0;
|
||||
const client = bearerClient({
|
||||
clock: {
|
||||
now: () => {
|
||||
elapsed += 5;
|
||||
return elapsed;
|
||||
},
|
||||
sleep: async () => {},
|
||||
},
|
||||
timeoutMs: 20,
|
||||
authSession: sessionStub({
|
||||
onUnauthenticated,
|
||||
recover: () => new Promise<"restored">(() => {}),
|
||||
}) as never,
|
||||
});
|
||||
|
||||
const outcome = await client.execute("LIST_ENTITIES");
|
||||
expect(outcome.ok).toBe(false);
|
||||
expect(onUnauthenticated).toHaveBeenCalledTimes(0);
|
||||
});
|
||||
});
|
||||
@@ -1,43 +1,50 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
validateEnvelope,
|
||||
validateOperationPayload,
|
||||
validateOperationRequest,
|
||||
} from "../../src/adapters/http/schema-registry.ts";
|
||||
readFailureEnvelope,
|
||||
readSuccessEnvelope,
|
||||
} from "../../src/adapters/http/backend-envelope.ts";
|
||||
import {
|
||||
composeRuntimeSchemaCodecs,
|
||||
validateWithRuntimeSchemaRegistry,
|
||||
} from "../../src/contracts/schema-registry.ts";
|
||||
|
||||
describe("HTTP platform schema boundary", () => {
|
||||
describe("paired backend Envelope boundary", () => {
|
||||
it("rejects an invalid top-level envelope", () => {
|
||||
expect(validateEnvelope({ success: true }).success).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts and clones a generic valid response envelope", () => {
|
||||
const source = {
|
||||
success: true,
|
||||
data: [],
|
||||
meta: { requestId: "request-1", traceId: "trace-1" },
|
||||
};
|
||||
const result = validateEnvelope(source);
|
||||
expect(result).toMatchObject({ success: true, data: source });
|
||||
if (!result.success) throw new Error("expected valid envelope");
|
||||
expect(result.data).not.toBe(source);
|
||||
});
|
||||
|
||||
it("fails closed without leaking input when a feature schema is absent", () => {
|
||||
const result = validateOperationPayload("UnknownPayload", {
|
||||
secret: "not-projected",
|
||||
});
|
||||
expect(result).toMatchObject({
|
||||
success: false,
|
||||
issues: [{ path: "", code: "SCHEMA_NOT_REGISTERED" }],
|
||||
});
|
||||
expect(JSON.stringify(result)).not.toContain("not-projected");
|
||||
expect(readSuccessEnvelope({ success: true }).ok).toBe(false);
|
||||
expect(
|
||||
validateOperationRequest("UnknownCommand", { name: "Example" }).success,
|
||||
readSuccessEnvelope({ success: true, data: [], meta: {}, error: {} }).ok,
|
||||
).toBe(false);
|
||||
expect(readFailureEnvelope({ success: false, meta: {} }).ok).toBe(false);
|
||||
});
|
||||
|
||||
it("reads data, and a dropped data key as null", () => {
|
||||
expect(
|
||||
readSuccessEnvelope({
|
||||
success: true,
|
||||
data: [],
|
||||
meta: { requestId: "request-1", traceId: "trace-1" },
|
||||
}),
|
||||
).toEqual({ ok: true, value: [] });
|
||||
expect(readSuccessEnvelope({ success: true, meta: {} })).toEqual({
|
||||
ok: true,
|
||||
value: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("reads the failure error and refuses a code outside the backend grammar", () => {
|
||||
expect(
|
||||
readFailureEnvelope({
|
||||
success: false,
|
||||
error: { code: "NOT_FOUND", category: "NOT_FOUND", retryable: false },
|
||||
meta: {},
|
||||
}),
|
||||
).toEqual({
|
||||
ok: true,
|
||||
value: { code: "NOT_FOUND", category: "NOT_FOUND", retryable: false },
|
||||
});
|
||||
expect(
|
||||
readFailureEnvelope({ success: false, error: { code: "not-a-code" }, meta: {} }).ok,
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { mapOperationPayload } from "../../src/adapters/http/resource-mapper.ts";
|
||||
import {
|
||||
composeBoundaryMapperRegistry,
|
||||
mappingFailure,
|
||||
@@ -10,13 +9,6 @@ import {
|
||||
import { mappingViolation } from "../../src/contracts/external-contract-runtime.ts";
|
||||
|
||||
describe("platform DTO mapper boundary", () => {
|
||||
it("fails closed when no feature mapper was injected", () => {
|
||||
expect(mapOperationPayload("UNKNOWN", {})).toEqual({
|
||||
ok: false,
|
||||
code: "MAPPING_INVARIANT_REJECTED",
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects duplicate mapper contributions before installation", () => {
|
||||
const mapper = {
|
||||
mapperId: "ResourceMapper",
|
||||
|
||||
@@ -1,91 +0,0 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { readBoundedJson } from "../../src/adapters/http/bounded-json.ts";
|
||||
|
||||
/**
|
||||
* N-08. The legacy V2 reader delegates to the common bounded reader. These
|
||||
* cases pin the preserved failure codes and prove that a throwing cancel or
|
||||
* releaseLock cannot escape the closed result.
|
||||
*/
|
||||
function responseWith(
|
||||
body: ReadableStream<Uint8Array> | string | null,
|
||||
init: ResponseInit = {},
|
||||
): Response {
|
||||
return new Response(body, init);
|
||||
}
|
||||
|
||||
describe("legacy bounded JSON compatibility", () => {
|
||||
it("preserves RESPONSE_BODY_LIMIT for a declared oversize body", async () => {
|
||||
const response = responseWith("{}", {
|
||||
headers: { "content-length": "9999" },
|
||||
});
|
||||
await expect(readBoundedJson(response, 8)).resolves.toEqual({
|
||||
ok: false,
|
||||
code: "RESPONSE_BODY_LIMIT",
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves RESPONSE_BODY_LIMIT for a headerless oversize body", async () => {
|
||||
const response = responseWith("[1,2,3,4,5,6,7,8,9,10]");
|
||||
await expect(readBoundedJson(response, 4)).resolves.toEqual({
|
||||
ok: false,
|
||||
code: "RESPONSE_BODY_LIMIT",
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["invalid UTF-8", new Uint8Array([0xff, 0xfe, 0xfd])],
|
||||
["malformed JSON", new TextEncoder().encode("{")],
|
||||
["an empty body", new Uint8Array(0)],
|
||||
])("maps %s to MALFORMED_JSON", async (_label, bytes) => {
|
||||
const response = responseWith(
|
||||
new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
if (bytes.byteLength > 0) controller.enqueue(bytes);
|
||||
controller.close();
|
||||
},
|
||||
}),
|
||||
);
|
||||
await expect(readBoundedJson(response, 1_024)).resolves.toEqual({
|
||||
ok: false,
|
||||
code: "MALFORMED_JSON",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps a closed result when reader cancel or releaseLock throws", async () => {
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
controller.enqueue(new TextEncoder().encode("[1,2,3,4,5,6,7,8]"));
|
||||
},
|
||||
});
|
||||
const response = responseWith(stream);
|
||||
const body = response.body!;
|
||||
const nativeGetReader = body.getReader.bind(body);
|
||||
vi.spyOn(body, "getReader").mockImplementation((() => {
|
||||
const actual = nativeGetReader();
|
||||
return {
|
||||
...actual,
|
||||
read: actual.read.bind(actual),
|
||||
cancel: async () => {
|
||||
throw new TypeError("cancel exploded");
|
||||
},
|
||||
releaseLock: () => {
|
||||
throw new TypeError("releaseLock exploded");
|
||||
},
|
||||
};
|
||||
}) as never);
|
||||
|
||||
await expect(readBoundedJson(response, 4)).resolves.toEqual({
|
||||
ok: false,
|
||||
code: "RESPONSE_BODY_LIMIT",
|
||||
});
|
||||
});
|
||||
|
||||
it("reads a bounded JSON value successfully", async () => {
|
||||
const response = responseWith('{"a":1}');
|
||||
await expect(readBoundedJson(response, 1_024)).resolves.toEqual({
|
||||
ok: true,
|
||||
value: { a: 1 },
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,74 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { buildRequestTarget } from "../../src/adapters/http/request-builder.ts";
|
||||
import type { ApiOperation } from "../../src/contracts/api-operations.ts";
|
||||
|
||||
const operation: ApiOperation = {
|
||||
method: "GET",
|
||||
path: "/api/resources/{resourceId}",
|
||||
operationId: "GET_RESOURCE",
|
||||
auth: "none",
|
||||
timeoutMs: null,
|
||||
idempotency: "safe",
|
||||
retry: "runtime",
|
||||
requestSource: "search",
|
||||
requestSchema: "ResourceQuery",
|
||||
responseSchema: "ResourcePayload",
|
||||
owner: "test",
|
||||
};
|
||||
|
||||
describe("deterministic HTTP request target", () => {
|
||||
it("escapes path values and serializes optional/array search in key order", () => {
|
||||
const result = buildRequestTarget(
|
||||
"https://api.test/base/",
|
||||
operation,
|
||||
{ resourceId: "folder/item" },
|
||||
{
|
||||
tags: ["beta", "alpha"],
|
||||
omitted: undefined,
|
||||
limit: 20,
|
||||
cursor: "next page",
|
||||
},
|
||||
);
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
if (!result.success) return;
|
||||
expect(result.url.href).toBe(
|
||||
"https://api.test/base/api/resources/folder%2Fitem?cursor=next+page&limit=20&tags=beta&tags=alpha",
|
||||
);
|
||||
});
|
||||
|
||||
it("fails closed when a path value or scalar search value is invalid", () => {
|
||||
expect(
|
||||
buildRequestTarget("https://api.test", operation, {}, {}),
|
||||
).toEqual({ success: false, code: "PATH_PARAMETER_MISSING" });
|
||||
expect(
|
||||
buildRequestTarget(
|
||||
"https://api.test",
|
||||
operation,
|
||||
{ resourceId: "one" },
|
||||
{ nested: { secret: true } },
|
||||
),
|
||||
).toEqual({ success: false, code: "SEARCH_PARAMETER_INVALID" });
|
||||
expect(
|
||||
buildRequestTarget(
|
||||
"https://api.test",
|
||||
operation,
|
||||
{ resourceId: "one", unexpected: "two" },
|
||||
{},
|
||||
),
|
||||
).toEqual({ success: false, code: "PATH_PARAMETER_UNEXPECTED" });
|
||||
expect(
|
||||
buildRequestTarget("http://api.test", operation, { resourceId: "one" }),
|
||||
).toEqual({ success: false, code: "BASE_URL_INVALID" });
|
||||
});
|
||||
|
||||
it.each([".", ".."])(
|
||||
"rejects the dot segment %j instead of letting pathname normalization move the target",
|
||||
(resourceId) => {
|
||||
expect(
|
||||
buildRequestTarget("https://api.test/base/", operation, { resourceId }),
|
||||
).toEqual({ success: false, code: "PATH_PARAMETER_INVALID" });
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -1,81 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
calculateBackoff,
|
||||
parseRetryAfter,
|
||||
retryDelay,
|
||||
shouldRetry,
|
||||
} from "../../src/adapters/http/retry-policy.ts";
|
||||
|
||||
describe("HTTP retry policy", () => {
|
||||
it("uses capped exponential full jitter", () => {
|
||||
expect(calculateBackoff(0, () => 0.5)).toBe(125);
|
||||
expect(calculateBackoff(8, () => 1)).toBe(2_000);
|
||||
});
|
||||
|
||||
it("parses retry-after and chooses the longer bounded delay", () => {
|
||||
expect(parseRetryAfter("2", 0)).toBe(2_000);
|
||||
expect(parseRetryAfter(" 2 ", 0)).toBe(2_000);
|
||||
expect(parseRetryAfter("Thu, 01 Jan 1970 00:00:05 GMT", 1_000)).toBe(
|
||||
4_000,
|
||||
);
|
||||
expect(retryDelay({ kind: "RATE_LIMITED", retryAfterMs: 500 }, 0, () => 0)).toBe(
|
||||
500,
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects Retry-After values that are not delta-seconds or an HTTP date", () => {
|
||||
for (const value of ["", " ", "1e3", "1.5", "-1", "0x10", "2024-01-01"]) {
|
||||
expect(parseRetryAfter(value, 0)).toBeNull();
|
||||
}
|
||||
});
|
||||
|
||||
it("allows at most two retries for safe or keyed requests", () => {
|
||||
const failure = { kind: "SERVER_FAILURE" };
|
||||
expect(shouldRetry({ idempotency: "safe" }, failure, 0)).toBe(true);
|
||||
expect(shouldRetry({ idempotency: "keyed" }, failure, 1)).toBe(true);
|
||||
expect(shouldRetry({ idempotency: "safe" }, failure, 2)).toBe(false);
|
||||
expect(shouldRetry({ idempotency: "none" }, failure, 0)).toBe(false);
|
||||
expect(
|
||||
shouldRetry(
|
||||
{ idempotency: "safe" },
|
||||
{ kind: "SERVER_FAILURE", httpStatus: 500 },
|
||||
0,
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
// R3-1. 408/425 server failures share the 502/503/504 rule and honor
|
||||
// Retry-After with the same 30s ceiling.
|
||||
it("retries 408 and 425 server failures only for safe or keyed requests", () => {
|
||||
for (const httpStatus of [408, 425]) {
|
||||
const failure = { kind: "SERVER_FAILURE", httpStatus };
|
||||
expect(shouldRetry({ idempotency: "safe" }, failure, 0)).toBe(true);
|
||||
expect(shouldRetry({ idempotency: "keyed" }, failure, 0)).toBe(true);
|
||||
expect(shouldRetry({ idempotency: "none" }, failure, 0)).toBe(false);
|
||||
expect(
|
||||
shouldRetry({ idempotency: "safe", retry: "never" }, failure, 0),
|
||||
).toBe(false);
|
||||
expect(
|
||||
retryDelay({ ...failure, retryAfterMs: 1_500 }, 0, () => 0),
|
||||
).toBe(1_500);
|
||||
expect(
|
||||
shouldRetry(
|
||||
{ idempotency: "safe" },
|
||||
{ ...failure, retryAfterMs: 31_000 },
|
||||
0,
|
||||
),
|
||||
).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it("does not automatically wait beyond 30 seconds", () => {
|
||||
expect(
|
||||
shouldRetry(
|
||||
{ idempotency: "safe" },
|
||||
{ kind: "RATE_LIMITED", retryAfterMs: 31_000 },
|
||||
0,
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -143,7 +143,7 @@ describe("repository-aware risk coverage", () => {
|
||||
summary,
|
||||
});
|
||||
|
||||
expect(result.selectedTotal).toBe(14);
|
||||
expect(result.selectedTotal).toBe(11);
|
||||
expect(result.repositoryTotal).toBeGreaterThan(result.selectedTotal);
|
||||
expect(result.uncoveredModules).toHaveLength(
|
||||
result.repositoryTotal - result.selectedTotal,
|
||||
|
||||
@@ -1,14 +1,10 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
createRuntimeAdapters,
|
||||
createRuntimeHttpClient,
|
||||
} from "../../src/bootstrap/runtime-adapters.ts";
|
||||
import { createRuntimeAdapters } from "../../src/bootstrap/runtime-adapters.ts";
|
||||
import { createBrowserMutationIntentFactory } from "../../src/adapters/platform/browser-mutation-intent-factory.ts";
|
||||
import { createApplication } from "../../src/application/create-application.ts";
|
||||
import type { ApplicationFeatureId } from "../../src/application/ports/in/application-api.ts";
|
||||
import { INSTALLED_PRODUCT_FEATURE_IDS } from "../../src/features/installed-product-manifest.ts";
|
||||
import { TEST_HTTP_CONTRACT } from "../helpers/http-contract-fixture.ts";
|
||||
|
||||
type Runtime = Parameters<typeof createRuntimeAdapters>[0]["runtime"];
|
||||
type Release = Parameters<typeof createRuntimeAdapters>[0]["release"];
|
||||
@@ -483,53 +479,4 @@ describe("runtime adapter composition", () => {
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("injects runtime timeout and max-attempt policy into HTTP execution", async () => {
|
||||
const scheduled: Array<{ callback: () => void; milliseconds: number }> = [];
|
||||
const scheduler = {
|
||||
setTimeout: vi.fn((callback: () => void, milliseconds: number) => {
|
||||
scheduled.push({ callback, milliseconds });
|
||||
return scheduled.length;
|
||||
}),
|
||||
clearTimeout: vi.fn(),
|
||||
};
|
||||
const fetcher = vi.fn(async () =>
|
||||
Response.json(
|
||||
{
|
||||
success: false,
|
||||
error: { code: "TEMPORARY" },
|
||||
meta: { requestId: "request-1", traceId: "trace-1" },
|
||||
},
|
||||
{ status: 503 },
|
||||
),
|
||||
);
|
||||
const authSession =
|
||||
(await createRuntimeAdapters({
|
||||
runtime,
|
||||
release,
|
||||
host: {},
|
||||
})).outputPorts.session;
|
||||
const client = createRuntimeHttpClient(
|
||||
{
|
||||
runtime,
|
||||
authSession,
|
||||
fetcher,
|
||||
clock: { now: () => 0, sleep: async () => {} },
|
||||
scheduler,
|
||||
},
|
||||
TEST_HTTP_CONTRACT,
|
||||
);
|
||||
|
||||
await client.execute({
|
||||
operationId: "LIST_ENTITIES",
|
||||
routeId: "TEST_ROUTE",
|
||||
});
|
||||
|
||||
expect(fetcher).toHaveBeenCalledOnce();
|
||||
expect(scheduler.setTimeout).toHaveBeenCalledWith(
|
||||
expect.any(Function),
|
||||
4321,
|
||||
);
|
||||
expect(scheduler.clearTimeout).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user