diff --git a/CHANGELOG.md b/CHANGELOG.md index 95a8435b..ce92cbbc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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` | diff --git a/config/contracts/registry-governance.json b/config/contracts/registry-governance.json index 80846b6b..c4a71cf5 100644 --- a/config/contracts/registry-governance.json +++ b/config/contracts/registry-governance.json @@ -359,7 +359,7 @@ }, "consumers": [ { - "path": "src/adapters/http/client.ts", + "path": "src/adapters/http/feature-http-binding.ts", "token": "failure(" } ], diff --git a/config/testing/risk-coverage.json b/config/testing/risk-coverage.json index 3095ac12..0ba7859c 100644 --- a/config/testing/risk-coverage.json +++ b/config/testing/risk-coverage.json @@ -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", diff --git a/docs/architecture/backend-api-and-server-state-contract.md b/docs/architecture/backend-api-and-server-state-contract.md index 3c7b8d47..772be5ca 100644 --- a/docs/architecture/backend-api-and-server-state-contract.md +++ b/docs/architecture/backend-api-and-server-state-contract.md @@ -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) diff --git a/docs/architecture/frontend-platform-capability-review.md b/docs/architecture/frontend-platform-capability-review.md index 965f5b7a..eaf21b76 100644 --- a/docs/architecture/frontend-platform-capability-review.md +++ b/docs/architecture/frontend-platform-capability-review.md @@ -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을 소유 diff --git a/docs/contracts/compatibility.md b/docs/contracts/compatibility.md index 25152bdb..2d172d24 100644 --- a/docs/contracts/compatibility.md +++ b/docs/contracts/compatibility.md @@ -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` | diff --git a/docs/operations/adapter-remediation-ledger.md b/docs/operations/adapter-remediation-ledger.md index 5a958f5f..90ce4f2d 100644 --- a/docs/operations/adapter-remediation-ledger.md +++ b/docs/operations/adapter-remediation-ledger.md @@ -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. | diff --git a/docs/operations/api-contract-and-server-state-recovery.md b/docs/operations/api-contract-and-server-state-recovery.md index 6991a90f..57bc2fc2 100644 --- a/docs/operations/api-contract-and-server-state-recovery.md +++ b/docs/operations/api-contract-and-server-state-recovery.md @@ -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 코드 기준 상태: diff --git a/docs/reviews/adapters/01-network-and-state.md b/docs/reviews/adapters/01-network-and-state.md index 6d29b71b..1859961f 100644 --- a/docs/reviews/adapters/01-network-and-state.md +++ b/docs/reviews/adapters/01-network-and-state.md @@ -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. | diff --git a/docs/reviews/adapters/INVENTORY.md b/docs/reviews/adapters/INVENTORY.md index 99e71065..d86ef817 100644 --- a/docs/reviews/adapters/INVENTORY.md +++ b/docs/reviews/adapters/INVENTORY.md @@ -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를 같은 변경에서 갱신한다. diff --git a/scripts/check-diagnostics.ts b/scripts/check-diagnostics.ts index 8c535246..384972b2 100644 --- a/scripts/check-diagnostics.ts +++ b/scripts/check-diagnostics.ts @@ -30,7 +30,7 @@ async function filesBelow(directory: string): Promise { const telemetryProducerFiles: Readonly> = { "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> = { }; const diagnosticProducerFiles: Readonly> = { "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": diff --git a/scripts/drill-runbook.ts b/scripts/drill-runbook.ts index 020c46fa..c1c8c987 100644 --- a/scripts/drill-runbook.ts +++ b/scripts/drill-runbook.ts @@ -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 { }; } +/** + * 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, + answer: () => Response, +): Promise { + 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 { - 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 { assertion( "schema fixtures", "schema mismatch is not retryable", - verdict(!shouldRetry({ idempotency: "safe" }, { kind: "SCHEMA_MISMATCH" }, 0)), + verdict(!schemaRetry), ), ], negativeFixtureFailedAsExpected: verdict(!unkeyedRetry), diff --git a/scripts/lib/risk-coverage.ts b/scripts/lib/risk-coverage.ts index c0b6bc24..0d951f22 100644 --- a/scripts/lib/risk-coverage.ts +++ b/scripts/lib/risk-coverage.ts @@ -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", diff --git a/src/adapters/http/backend-envelope.ts b/src/adapters/http/backend-envelope.ts index bd9da4fd..8e769232 100644 --- a/src/adapters/http/backend-envelope.ts +++ b/src/adapters/http/backend-envelope.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, diff --git a/src/adapters/http/bounded-json.ts b/src/adapters/http/bounded-json.ts deleted file mode 100644 index 0979c5c7..00000000 --- a/src/adapters/http/bounded-json.ts +++ /dev/null @@ -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 { - 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 }); -} diff --git a/src/adapters/http/client.ts b/src/adapters/http/client.ts deleted file mode 100644 index 12bb532a..00000000 --- a/src/adapters/http/client.ts +++ /dev/null @@ -1,1135 +0,0 @@ -import { systemClock } from "../platform/system-clock.ts"; -import { getApiOperation } from "../../contracts/api-operations.ts"; -import { - createFailure as failure, - kindForStatus as statusKind, -} from "../../contracts/errors.ts"; -import { - envelopeFailureEffect, - envelopeFailureReading, - gatewayFailureOr, - idempotencyRefusalReason, - type EnvelopeError, -} from "./backend-envelope.ts"; -import { mapOperationPayload } from "./resource-mapper.ts"; -import { retryDelay, shouldRetry } from "./retry-policy.ts"; -import { parseRetryAfterDelay } from "../platform/retry-after.ts"; -import { - validateEnvelope, - validateOperationPayload, - validateOperationRequest, -} from "./schema-registry.ts"; -import { buildRequestTarget } from "./request-builder.ts"; -import { - attemptBucket, - durationBucket, - statusGroup, -} from "../../contracts/diagnostics.ts"; -import type { - AuthSessionPort, - CredentialOperationContext, -} from "../../application/ports/auth-session-port.ts"; -import { isValidIdempotencyKey } from "../../contracts/mutation-intent.ts"; - -/** Sentinel for a credential wait ended by the attempt lifetime. */ -const ATTEMPT_ABORTED = Symbol("ATTEMPT_ABORTED"); - -/** - * LEG-02. The pre-V2 operations have no installed auth profile, so this is the - * legacy allowance the shared validator applies to them. It requires nothing, - * which preserves their existing behaviour exactly. - */ -const LEGACY_ALLOWED_CREDENTIAL_HEADERS = Object.freeze([ - "authorization", - "x-csrf-token", -] as const); -import type { ClockPort } from "../../application/ports/clock-port.ts"; -import type { DiagnosticsPort } from "../../application/ports/diagnostics-port.ts"; -import type { TelemetryPort } from "../../application/ports/telemetry-port.ts"; -import type { ApiOperation } from "../../contracts/api-operations.ts"; -import type { AppFailure } from "../../contracts/errors.ts"; -import type { OperationRequestInput } from "./request-builder.ts"; -import { readBoundedJson } from "./bounded-json.ts"; -import { admitCredentialHeaders } from "./http-contract-bridge.ts"; -import type { BoundaryMappingResult } from "../../contracts/boundary-mapper.ts"; -import { - createRestProviderProfile, - resolveRestSecurityProfiles, - INSTALLED_REST_AUTH_PROFILES, - REST_CSRF_PROFILES, - type RestAuthProfile, - type RestCsrfProfile, - type RestProviderProfile, -} from "../../contracts/rest-profiles.ts"; - -type HttpAuthSession = Pick< - AuthSessionPort, - "getState" | "credentialPatch" | "recover" | "onUnauthenticated" ->; - -const noAuthSession: HttpAuthSession = Object.freeze({ - getState: () => "integration-failed", - credentialPatch: async () => { - throw new TypeError("Auth session is not installed"); - }, - recover: async () => "no-session", - onUnauthenticated: () => {}, -} satisfies HttpAuthSession); - -export type HttpFailure = AppFailure; - -export type Scheduler = Readonly<{ - setTimeout(callback: () => void, milliseconds: number): unknown; - clearTimeout(handle: unknown): void; -}>; - -export type HttpResult = - | Readonly<{ - ok: true; - value: unknown; - meta: Readonly>; - }> - | Readonly<{ ok: false; error: HttpFailure }>; - -type SchemaValidator = ( - schemaId: string, - value: unknown, -) => - | Readonly<{ success: true; data: unknown }> - | Readonly<{ success: false }>; - -export type HttpClientDependencies = Readonly<{ - baseUrl: string; - fetcher?: typeof fetch; - authSession?: AuthSessionPort; - clock?: ClockPort; - random?: () => number; - validatePayload?: SchemaValidator; - validateRequest?: SchemaValidator; - validatePath?: SchemaValidator; - mapPayload?: ( - operationId: string, - payload: unknown, - ) => BoundaryMappingResult; - idempotencyKeyFactory?: () => string; - /** - * Default total deadline for an operation without its own `timeoutMs`. Not a - * ceiling: an operation may set a longer one. V3 treats `REQUEST_TIMEOUT_MS` - * as a ceiling instead (03-06). - */ - timeoutMs?: number; - maxRetryAttempts?: number; - scheduler?: Scheduler; - getOperation?: typeof getApiOperation; - diagnostics?: DiagnosticsPort; - telemetry?: TelemetryPort; - correlationIdFactory?: () => string; - providerProfile?: RestProviderProfile; - authProfiles?: Readonly>; - csrfProfiles?: Readonly>; - maxCumulativeSleepMs?: number; -}>; - -export type LegacyHttpInput = Readonly<{ - body?: unknown; - routeId?: string; - pathParams?: Readonly>; - searchParams?: unknown; - signal?: AbortSignal; - idempotencyKey?: string; - correlationId?: string; -}>; - -export type HttpClient = Readonly<{ - execute( - request: string | OperationRequestInput, - legacyInput?: LegacyHttpInput, - ): Promise; -}>; - -export function createHttpClient( - dependencies: HttpClientDependencies, -): HttpClient { - const fetcher = dependencies.fetcher ?? fetch; - const authSession = dependencies.authSession ?? noAuthSession; - const clock = dependencies.clock ?? systemClock; - const random = dependencies.random ?? Math.random; - const validatePayload = - dependencies.validatePayload ?? validateOperationPayload; - const validateRequest = - dependencies.validateRequest ?? validateOperationRequest; - const validatePath = dependencies.validatePath ?? validateRequest; - const mapPayload = dependencies.mapPayload ?? mapOperationPayload; - const idempotencyKeyFactory = - dependencies.idempotencyKeyFactory ?? (() => crypto.randomUUID()); - const defaultTimeoutMs = dependencies.timeoutMs ?? 10_000; - const maxRetryAttempts = dependencies.maxRetryAttempts ?? 2; - const maxCumulativeSleepMs = - dependencies.maxCumulativeSleepMs ?? defaultTimeoutMs; - const selectOperation = dependencies.getOperation ?? getApiOperation; - const diagnostics = dependencies.diagnostics; - const telemetry = dependencies.telemetry; - const correlationIdFactory = - dependencies.correlationIdFactory ?? - (() => `request-${Math.floor(random() * 1_000_000).toString(36)}`); - const scheduler = - dependencies.scheduler ?? - ({ - setTimeout: (callback, milliseconds) => - globalThis.setTimeout(callback, milliseconds), - clearTimeout: (handle) => - globalThis.clearTimeout( - handle as ReturnType, - ), - } satisfies Scheduler); - - async function execute( - request: string | OperationRequestInput, - legacyInput: LegacyHttpInput = {}, - ): Promise { - const input = - typeof request === "string" - ? { - operationId: request, - routeId: legacyInput.routeId ?? "UNSPECIFIED_ROUTE", - pathParams: legacyInput.pathParams, - searchParams: legacyInput.searchParams, - body: legacyInput.body, - signal: legacyInput.signal, - idempotencyKey: legacyInput.idempotencyKey, - correlationId: legacyInput.correlationId, - } - : request; - const startedAt = clock.now(); - let correlationId: string; - try { - correlationId = correlationIdValue( - input.correlationId ?? correlationIdFactory(), - ); - } catch { - correlationId = "client-generated"; - } - let operation: ApiOperation; - try { - operation = selectOperation(input.operationId); - } catch { - return { - ok: false, - error: failure("UNKNOWN_CLIENT_FAILURE", input.operationId, 0, { - code: "OPERATION_NOT_REGISTERED", - }), - }; - } - const totalDeadlineMs = operation.timeoutMs ?? defaultTimeoutMs; - const deadlineAt = startedAt + totalDeadlineMs; - let physicalAttemptCount = 0; - function finalize( - outcome: HttpResult, - outcomeKind: "success" | "recovered" | "failed" | "aborted", - ): HttpResult { - const error = outcome.ok ? undefined : outcome.error; - const reason = - error && idempotencyRefusalReason(error.code, error.httpStatus); - const context = { - route_id: input.routeId, - operation_id: input.operationId, - correlation_id: correlationId, - outcome: outcomeKind, - error_kind: error?.kind ?? "NONE", - http_status_group: statusGroup( - error?.httpStatus ?? - (outcome.ok ? Number(outcome.meta.httpStatus) : undefined), - ), - attempt_count_bucket: attemptBucket( - error?.attemptCount ?? Math.max(1, physicalAttemptCount), - ), - duration_bucket: durationBucket(clock.now() - startedAt), - }; - try { - diagnostics?.record({ - level: error ? "warn" : "info", - eventId: "http.request.completed", - // Diagnostics only: telemetry below keeps its fixed attribute set. - context: reason ? { ...context, reason } : context, - }); - } catch { - // Diagnostics cannot change the HTTP result. - } - if (error && outcomeKind !== "aborted") { - try { - telemetry?.emit("api.request.failed", { - error_kind: context.error_kind, - http_status_group: context.http_status_group, - attempt_count_bucket: context.attempt_count_bucket, - route_id: context.route_id, - operation_id: context.operation_id, - duration_bucket: context.duration_bucket, - }); - } catch { - // Telemetry cannot change the HTTP result. - } - } - return outcome; - } - // N-06. A caller-supplied key is validated before credentials, timers or - // fetch. An invalid value is rejected outright rather than trimmed or - // replaced, so a keyed command can never replay with no key at all. - let logicalIdempotencyKey: string | undefined; - if (operation.idempotency === "keyed") { - if (input.idempotencyKey !== undefined) { - if (!isValidIdempotencyKey(input.idempotencyKey)) { - return finalize( - { - ok: false, - error: failure("VALIDATION_REJECTED", input.operationId, 0, { - code: "IDEMPOTENCY_KEY_INVALID", - }), - }, - "failed", - ); - } - logicalIdempotencyKey = input.idempotencyKey; - } else { - let generated: string; - try { - generated = idempotencyKeyFactory(); - } catch { - return finalize( - { - ok: false, - error: failure("UNKNOWN_CLIENT_FAILURE", input.operationId, 0, { - code: "IDEMPOTENCY_KEY_CREATION_FAILED", - }), - }, - "failed", - ); - } - if (!isValidIdempotencyKey(generated)) { - return finalize( - { - ok: false, - error: failure("UNKNOWN_CLIENT_FAILURE", input.operationId, 0, { - code: "IDEMPOTENCY_KEY_CREATION_FAILED", - }), - }, - "failed", - ); - } - logicalIdempotencyKey = generated; - } - } - let retryCount = 0; - let recoveryUsed = false; - let cumulativeSleepMs = 0; - - while (true) { - const attempt = physicalAttemptCount; - physicalAttemptCount += 1; - let outcome: HttpResult; - try { - outcome = await performAttempt({ - operation, - input, - attempt, - idempotencyKey: logicalIdempotencyKey, - deadlineAt, - correlationId, - }); - } catch { - outcome = { - ok: false, - error: failure("UNKNOWN_CLIENT_FAILURE", input.operationId, attempt, { - code: "HTTP_EXECUTION_CONTRACT_VIOLATION", - }), - }; - } - - if (outcome.ok) { - return finalize( - outcome, - retryCount > 0 || recoveryUsed ? "recovered" : "success", - ); - } - - // Q-6.3-11. Recovery is its own single replay, bounded by - // `recoveryUsed` and the deadline, not by the retry budget: a disabled - // or spent budget must not turn a recoverable 401 into a logout. - if (outcome.error.httpStatus === 401 && !recoveryUsed) { - recoveryUsed = true; - let recovered: SessionRecoveryOutcome; - // LEG-01. The recovery collaborator receives the request lifetime, and - // the transport races the same signal so a non-cooperative owner cannot - // hold the request open. - const recoveryLifetime = new AbortController(); - try { - recovered = await withinLogicalDeadline( - recoverSession( - authSession, - operation, - outcome.error, - Object.freeze({ - signal: recoveryLifetime.signal, - deadlineAtMonotonicMs: deadlineAt, - }), - ), - deadlineAt, - input.signal, - ); - } catch (error) { - // The request is over. Whatever the recovery answers next is observed - // by its own owner, never adopted here. - recoveryLifetime.abort(); - return finalize( - { - ok: false, - error: failure( - error instanceof LogicalDeadlineError - ? "REQUEST_TIMEOUT" - : "REQUEST_ABORTED", - operation.operationId, - attempt, - { - code: - error instanceof LogicalDeadlineError - ? "OPERATION_DEADLINE_EXCEEDED" - : "REQUEST_ABORTED", - }, - ), - }, - error instanceof LogicalDeadlineError ? "failed" : "aborted", - ); - } - if (!recovered.ok) { - // The result is adopted here, so the notification happens here. - if (recovered.notifyUnauthenticated) authSession.onUnauthenticated(); - return finalize( - { ok: false, error: recovered.error }, - "failed", - ); - } - if (operation.idempotency === "none") { - return finalize( - { - ok: false, - error: { - ...outcome.error, - retryable: false, - action: "retry", - }, - }, - "failed", - ); - } - continue; - } - - if (outcome.error.httpStatus === 401 && recoveryUsed) { - authSession.onUnauthenticated(); - return finalize(outcome, "failed"); - } - - if ( - !shouldRetry( - operation, - outcome.error, - retryCount, - maxRetryAttempts, - ) - ) { - return finalize( - outcome, - outcome.error.kind === "REQUEST_ABORTED" ? "aborted" : "failed", - ); - } - - const delay = retryDelay(outcome.error, retryCount, random, clock.now()); - retryCount += 1; - cumulativeSleepMs += delay; - if ( - clock.now() + delay >= deadlineAt || - cumulativeSleepMs > maxCumulativeSleepMs - ) { - return finalize( - { - ok: false, - error: failure("REQUEST_TIMEOUT", input.operationId, attempt, { - code: "OPERATION_DEADLINE_EXCEEDED", - }), - }, - "failed", - ); - } - - try { - await clock.sleep(delay, input.signal); - } catch { - return finalize( - { - ok: false, - error: failure("REQUEST_ABORTED", input.operationId, retryCount, { - code: "REQUEST_ABORTED", - }), - }, - "aborted", - ); - } - } - } - - async function performAttempt( - context: Readonly<{ - operation: ApiOperation; - input: OperationRequestInput; - attempt: number; - idempotencyKey?: string; - deadlineAt: number; - correlationId: string; - }>, - ): Promise { - const { - operation, - input, - attempt, - idempotencyKey, - deadlineAt, - correlationId, - } = context; - if (clock.now() >= deadlineAt) { - return { - ok: false, - error: failure("REQUEST_TIMEOUT", operation.operationId, attempt, { - code: "OPERATION_DEADLINE_EXCEEDED", - }), - }; - } - let parsedSearch: unknown = {}; - let parsedBody: unknown; - let parsedPath: Readonly> = - input.pathParams ?? {}; - if (operation.pathSchema) { - const pathValidation = validatePath( - operation.pathSchema, - input.pathParams ?? {}, - ); - if ( - !pathValidation.success || - !isPathParameterRecord(pathValidation.data) - ) { - return { - ok: false, - error: failure( - "VALIDATION_REJECTED", - operation.operationId, - attempt, - { code: "PATH_SCHEMA_INVALID" }, - ), - }; - } - parsedPath = pathValidation.data; - } - const requestValue = - operation.requestSource === "search" - ? input.searchParams ?? {} - : operation.requestSource === "body" - ? input.body - : {}; - if (operation.requestSource !== "none") { - const requestValidation = validateRequest( - operation.requestSchema, - requestValue, - ); - if (!requestValidation.success) { - return { - ok: false, - error: failure("VALIDATION_REJECTED", operation.operationId, attempt, { - code: "REQUEST_SCHEMA_INVALID", - }), - }; - } - if (operation.requestSource === "search") { - parsedSearch = requestValidation.data; - } else { - parsedBody = requestValidation.data; - } - } - - let target: ReturnType; - let provider: RestProviderProfile | null = null; - let security: - | ReturnType - | undefined; - try { - provider = - dependencies.providerProfile ?? - createRestProviderProfile( - operation.providerId ?? "LEGACY_API", - dependencies.baseUrl, - ["omit", "same-origin"], - ); - if ( - operation.contractVersion === 2 && - operation.providerId !== provider.providerId - ) { - throw new TypeError("REST provider binding mismatch."); - } - if (operation.contractVersion === 2) { - security = resolveRestSecurityProfiles( - operation, - provider, - dependencies.authProfiles ?? INSTALLED_REST_AUTH_PROFILES, - dependencies.csrfProfiles ?? REST_CSRF_PROFILES, - ); - } - target = buildRequestTarget( - provider.baseUrl, - operation, - parsedPath, - parsedSearch, - ); - } catch { - target = { success: false, code: "BASE_URL_INVALID" }; - } - if (!target.success || !provider) { - return { - ok: false, - error: failure("VALIDATION_REJECTED", operation.operationId, attempt, { - code: target.success ? "BASE_URL_INVALID" : target.code, - }), - }; - } - - const controller = new AbortController(); - let timedOut = false; - const remainingMs = Math.max(1, deadlineAt - clock.now()); - const timeout = scheduler.setTimeout(() => { - timedOut = true; - controller.abort("timeout"); - }, remainingMs); - const onExternalAbort = () => controller.abort(input.signal?.reason); - input.signal?.addEventListener("abort", onExternalAbort, { once: true }); - if (input.signal?.aborted) onExternalAbort(); - - try { - const headers = new Headers({ - Accept: operation.responseMediaTypes?.join(", ") ?? "application/json", - "X-Correlation-ID": correlationIdValue(correlationId), - }); - if (parsedBody !== undefined) headers.set("Content-Type", "application/json"); - if (idempotencyKey) headers.set("Idempotency-Key", idempotencyKey); - - if (operation.auth === "external-session") { - let sessionState: ReturnType; - try { - sessionState = authSession.getState(); - } catch { - return { - ok: false, - error: failure( - "AUTH_INTEGRATION_FAILURE", - operation.operationId, - attempt, - { code: "AUTH_STATE_FAILED" }, - ), - }; - } - if (sessionState === "unauthenticated") { - return { - ok: false, - error: failure("AUTH_REQUIRED", operation.operationId, attempt, { - code: "AUTH_REQUIRED", - }), - }; - } - if (sessionState !== "authenticated") { - return { - ok: false, - error: failure( - "AUTH_INTEGRATION_FAILURE", - operation.operationId, - attempt, - { code: "AUTH_SESSION_UNAVAILABLE" }, - ), - }; - } - try { - // N-07. The credential owner is bounded by the attempt lifetime that - // already carries the total deadline and the caller signal, so a - // non-cooperative owner cannot hold the request open and no extra - // timer is introduced. A late completion is observed and discarded. - const raced = await raceAttemptSignal( - Promise.resolve( - authSession.credentialPatch( - { - origin: target.url.origin, - method: operation.method, - operationId: operation.operationId, - }, - Object.freeze({ - signal: controller.signal, - deadlineAtMonotonicMs: deadlineAt, - }), - ), - ), - controller.signal, - ); - if (raced === ATTEMPT_ABORTED) { - return { - ok: false, - error: timedOut - ? failure( - "REQUEST_TIMEOUT", - operation.operationId, - attempt, - { code: "OPERATION_DEADLINE_EXCEEDED" }, - ) - : failure( - "REQUEST_ABORTED", - operation.operationId, - attempt, - { code: "REQUEST_ABORTED" }, - ), - }; - } - const patch = raced; - // LEG-02. The same admission validator V3 uses. Checking only the - // allowed set let a bearer profile dispatch with no Authorization at - // all, which is precisely the anonymous downgrade the required set - // exists to prevent. - const admission = admitCredentialHeaders(patch.headers, { - allowedCredentialHeaders: - security?.auth.allowedCredentialHeaders ?? - LEGACY_ALLOWED_CREDENTIAL_HEADERS, - requiredCredentialHeaders: - security?.auth.requiredCredentialHeaders ?? [], - }); - if (!admission.ok) { - return { - ok: false, - error: failure( - "AUTH_INTEGRATION_FAILURE", - operation.operationId, - attempt, - { code: "AUTH_ATTACH_FAILED" }, - ), - }; - } - for (const [name, value] of Object.entries(admission.headers)) { - headers.set(name, value); - } - } catch { - // An ordinary owner rejection stays an integration failure. - return { - ok: false, - error: failure("AUTH_INTEGRATION_FAILURE", operation.operationId, attempt, { - code: "AUTH_ATTACH_FAILED", - }), - }; - } - } - - const request = new Request(target.url, { - method: operation.method, - headers, - body: parsedBody === undefined ? undefined : JSON.stringify(parsedBody), - signal: controller.signal, - credentials: security?.auth.credentials ?? "same-origin", - cache: "no-store", - redirect: provider.redirect, - referrerPolicy: provider.referrerPolicy, - }); - const response = await fetcher(request); - return await parseResponse( - response, - operation, - attempt, - validatePayload, - mapPayload, - clock.now(), - ); - } catch { - if (timedOut) { - return { - ok: false, - error: failure("REQUEST_TIMEOUT", operation.operationId, attempt, { - code: "REQUEST_TIMEOUT", - }), - }; - } - if (controller.signal.aborted || input.signal?.aborted) { - const externalReason = input.signal?.reason; - if (externalReason === "timeout") { - return { - ok: false, - error: failure("REQUEST_TIMEOUT", operation.operationId, attempt, { - code: "REQUEST_TIMEOUT", - }), - }; - } - if ( - externalReason !== undefined && - !["navigation", "user", "superseded"].includes(String(externalReason)) - ) { - return { - ok: false, - error: failure("UNKNOWN_FAILURE", operation.operationId, attempt, { - code: "EXTERNAL_ABORT_UNRESOLVED", - }), - }; - } - return { - ok: false, - error: failure("REQUEST_ABORTED", operation.operationId, attempt, { - code: "REQUEST_ABORTED", - }), - }; - } - return { - ok: false, - error: failure("NETWORK_UNREACHABLE", operation.operationId, attempt, { - code: "NETWORK_UNREACHABLE", - }), - }; - } finally { - scheduler.clearTimeout(timeout); - input.signal?.removeEventListener("abort", onExternalAbort); - } - } - - return Object.freeze({ execute }); - - function raceAttemptSignal( - operation: Promise, - signal: AbortSignal, - ): Promise { - operation.catch(() => {}); - if (signal.aborted) return Promise.resolve(ATTEMPT_ABORTED); - return new Promise((resolve, reject) => { - const onAbort = () => resolve(ATTEMPT_ABORTED); - signal.addEventListener("abort", onAbort, { once: true }); - operation.then( - (value) => { - signal.removeEventListener("abort", onAbort); - resolve(value); - }, - (error: unknown) => { - signal.removeEventListener("abort", onAbort); - reject(error instanceof Error ? error : new Error("rejected")); - }, - ); - }); - } - - function withinLogicalDeadline( - promise: Promise, - deadlineAt: number, - externalSignal: AbortSignal | undefined, - ): Promise { - const remaining = deadlineAt - clock.now(); - if (remaining <= 0) return Promise.reject(new LogicalDeadlineError()); - return new Promise((resolve, reject) => { - let settled = false; - const timeout = scheduler.setTimeout( - () => settle(() => reject(new LogicalDeadlineError())), - remaining, - ); - const onAbort = () => - settle(() => reject(new DOMException("Aborted", "AbortError"))); - externalSignal?.addEventListener("abort", onAbort, { once: true }); - const settle = (complete: () => void) => { - if (settled) return; - settled = true; - scheduler.clearTimeout(timeout); - externalSignal?.removeEventListener("abort", onAbort); - complete(); - }; - if (externalSignal?.aborted) { - onAbort(); - return; - } - promise.then( - (value) => settle(() => resolve(value)), - (error: unknown) => settle(() => reject(error)), - ); - }); - } -} - -class LogicalDeadlineError extends Error {} - -async function parseResponse( - response: Response, - operation: ApiOperation, - attempt: number, - validatePayload: SchemaValidator, - mapPayload: ( - operationId: string, - payload: unknown, - ) => BoundaryMappingResult, - now: number, -): Promise { - // R3-1. Retry-After is read only where the retry policy honors it; 502/504 - // keep the local backoff. 백엔드 1101/02-01: a 409 is never retried here, - // but a same-key resend after it waits on its Retry-After. - const retryAfterMs = [408, 409, 425, 429, 503].includes(response.status) - ? (parseRetryAfterDelay(response.headers.get("retry-after"), now) ?? - undefined) - : undefined; - const contentType = mediaType(response.headers.get("content-type")); - const acceptedMedia = operation.responseMediaTypes ?? ["application/json"]; - if (!contentType || !acceptedMedia.includes(contentType)) { - // N-08. A rejected response still owns an open body stream. Cancellation is - // best-effort cleanup, so it is started but not awaited: the closed result - // must not depend on stream teardown settling. - void response.body?.cancel().catch(() => {}); - return { - ok: false, - error: failure( - gatewayFailureOr(response.status, "CONTENT_TYPE_MISMATCH"), - operation.operationId, - attempt, - { - code: "CONTENT_TYPE_MISMATCH", - httpStatus: response.status, - retryAfterMs, - }, - ), - }; - } - - const decoded = await readBoundedJson( - response, - operation.maxResponseBytes ?? 1_048_576, - ); - if (!decoded.ok) { - return { - ok: false, - error: failure( - gatewayFailureOr(response.status, decoded.code), - operation.operationId, - attempt, - { code: decoded.code, httpStatus: response.status, retryAfterMs }, - ), - }; - } - const envelope = decoded.value; - - const envelopeValidation = validateEnvelope(envelope); - if (!envelopeValidation.success) { - return { - ok: false, - error: failure( - response.ok - ? "ENVELOPE_MISMATCH" - : gatewayFailureOr(response.status, statusKind(response.status)), - operation.operationId, - attempt, - { - code: response.ok ? "ENVELOPE_MISMATCH" : "HTTP_FAILURE", - httpStatus: response.status, - retryAfterMs, - }, - ), - }; - } - - const envelopeRecord = envelopeValidation.data as Record; - const successStatus = operation.successStatuses - ? operation.successStatuses.includes(response.status) - : response.ok; - if (successStatus && envelopeRecord.success === true && "data" in envelopeRecord) { - const payload = validatePayload(operation.responseSchema, envelopeRecord.data); - if (!payload.success) { - return { - ok: false, - error: failure("SCHEMA_MISMATCH", operation.operationId, attempt, { - code: "SCHEMA_MISMATCH", - httpStatus: response.status, - }), - }; - } - - try { - const mapped = mapPayload(operation.operationId, payload.data); - if (!mapped.ok) { - return { - ok: false, - error: failure( - "MAPPING_CONTRACT_VIOLATION", - operation.operationId, - attempt, - { - code: mapped.code, - httpStatus: response.status, - }, - ), - }; - } - return { - ok: true, - value: mapped.value, - meta: { - ...safeMeta(envelopeRecord.meta), - httpStatus: String(response.status), - }, - }; - } catch { - return { - ok: false, - error: failure( - "MAPPING_CONTRACT_VIOLATION", - operation.operationId, - attempt, - { - code: "MAPPING_CONTRACT_VIOLATION", - httpStatus: response.status, - }, - ), - }; - } - } - if (successStatus !== response.ok || (successStatus && envelopeRecord.success !== true)) { - return { - ok: false, - error: failure("ENVELOPE_MISMATCH", operation.operationId, attempt, { - code: "STATUS_ENVELOPE_MISMATCH", - httpStatus: response.status, - }), - }; - } - - // 1101 README 14.3. The kind, the field issues and the effect come from - // `backend-envelope.ts`, which a V3 Envelope operation reads too. A success - // Envelope on an error status has no error object: its code is HTTP_FAILURE. - const backendError: EnvelopeError = Object.freeze({ - code: safeBackendCode(envelope), - details: - envelopeRecord.error && typeof envelopeRecord.error === "object" - ? (envelopeRecord.error as Record).details - : undefined, - }); - const reading = envelopeFailureReading(response.status, backendError); - // V2 marks only a refusal made before the command ran. An absent effect is - // the coordinator's MAYBE_APPLIED, which an in-flight 409 needs. - const effect = envelopeFailureEffect(response.status, backendError); - return { - ok: false, - error: failure(reading.kind, operation.operationId, attempt, { - code: reading.code, - ...(effect === "NOT_APPLIED" ? { effect } : {}), - httpStatus: response.status, - requestId: safeMeta(envelopeRecord.meta).requestId, - traceId: safeMeta(envelopeRecord.meta).traceId, - retryAfterMs, - validationIssues: reading.validationIssues, - }), - }; -} - -/** - * LEG-01. Recovery returns data only. - * - * The sign-out notification is a user-visible side effect, so it belongs to - * whoever adopts this result — not to the raw recovery call. A recovery that - * loses the race against the deadline or a caller abort still settles, and - * signing the user out then would attribute a request nobody is waiting on to - * an expired session. - */ -type SessionRecoveryOutcome = - | Readonly<{ ok: true }> - | Readonly<{ - ok: false; - error: HttpFailure; - notifyUnauthenticated: boolean; - }>; - -async function recoverSession( - authSession: HttpAuthSession, - operation: ApiOperation, - originalFailure: HttpFailure, - context: CredentialOperationContext, -): Promise { - try { - const result = await authSession.recover(context); - if (result === "restored") return { ok: true }; - if (result === "no-session") { - return { - ok: false, - notifyUnauthenticated: true, - error: failure("AUTH_REQUIRED", operation.operationId, originalFailure.attemptCount - 1, { - code: "AUTH_REQUIRED", - httpStatus: 401, - }), - }; - } - } catch { - // Normalized below. - } - - return { - ok: false, - notifyUnauthenticated: false, - error: failure( - "AUTH_INTEGRATION_FAILURE", - operation.operationId, - originalFailure.attemptCount - 1, - { code: "AUTH_RECOVERY_FAILED" }, - ), - }; -} - -function safeBackendCode(envelope: unknown): string { - if (!envelope || typeof envelope !== "object") return "HTTP_FAILURE"; - const error = (envelope as Record).error; - if (!error || typeof error !== "object") return "HTTP_FAILURE"; - const code = (error as Record).code; - return typeof code === "string" && /^[A-Z0-9_]{1,64}$/.test(code) - ? code - : "HTTP_FAILURE"; -} - -function safeMeta(meta: unknown): Record { - if (!meta || typeof meta !== "object") return {}; - const metaRecord = meta as Record; - return { - ...(typeof metaRecord.requestId === "string" - ? safeIdentifier(metaRecord.requestId, "requestId") - : {}), - ...(typeof metaRecord.traceId === "string" - ? safeIdentifier(metaRecord.traceId, "traceId") - : {}), - }; -} - -function safeIdentifier( - value: string, - property: "requestId" | "traceId", -): Record { - return /^[A-Za-z0-9._:-]{1,128}$/.test(value) ? { [property]: value } : {}; -} - -function mediaType(value: string | null): string | null { - if (!value) return null; - const selected = value.split(";", 1)[0]?.trim().toLowerCase(); - return selected && /^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/.test(selected) - ? selected - : null; -} - -function correlationIdValue(value: string | undefined): string { - return value && /^[A-Za-z0-9._:-]{1,128}$/.test(value) - ? value - : "client-generated"; -} - -function isPathParameterRecord( - value: unknown, -): value is Readonly> { - return ( - value !== null && - typeof value === "object" && - !Array.isArray(value) && - Object.values(value).every( - (item) => typeof item === "string" || typeof item === "number", - ) - ); -} diff --git a/src/adapters/http/feature-http-binding.ts b/src/adapters/http/feature-http-binding.ts index 6d27216a..2643cafb 100644 --- a/src/adapters/http/feature-http-binding.ts +++ b/src/adapters/http/feature-http-binding.ts @@ -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( 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) diff --git a/src/adapters/http/http-contract-bridge.ts b/src/adapters/http/http-contract-bridge.ts index 5c3d1d81..692bb0c0 100644 --- a/src/adapters/http/http-contract-bridge.ts +++ b/src/adapters/http/http-contract-bridge.ts @@ -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. */ diff --git a/src/adapters/http/http-execution-v3.ts b/src/adapters/http/http-execution-v3.ts index f6cc4451..6fa152a4 100644 --- a/src/adapters/http/http-execution-v3.ts +++ b/src/adapters/http/http-execution-v3.ts @@ -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( 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( } // 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( 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( } // 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 }) diff --git a/src/adapters/http/index.ts b/src/adapters/http/index.ts index 025f3e05..c1af125a 100644 --- a/src/adapters/http/index.ts +++ b/src/adapters/http/index.ts @@ -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"; diff --git a/src/adapters/http/request-builder.ts b/src/adapters/http/request-builder.ts deleted file mode 100644 index 6ead1d9f..00000000 --- a/src/adapters/http/request-builder.ts +++ /dev/null @@ -1,137 +0,0 @@ -import type { ApiOperation } from "../../contracts/api-operations.ts"; - -export type OperationRequestInput = Readonly<{ - operationId: string; - routeId: string; - pathParams?: Readonly>; - 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> = {}, - 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(); - 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>; - 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 }; -} diff --git a/src/adapters/http/resource-mapper.ts b/src/adapters/http/resource-mapper.ts deleted file mode 100644 index ea4a71e4..00000000 --- a/src/adapters/http/resource-mapper.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { - mappingFailure, - type BoundaryMappingResult, -} from "../../contracts/boundary-mapper.ts"; - -export function mapOperationPayload( - _operationId: string, - _payload: unknown, -): BoundaryMappingResult { - return mappingFailure("MAPPING_INVARIANT_REJECTED"); -} diff --git a/src/adapters/http/retry-policy.ts b/src/adapters/http/retry-policy.ts deleted file mode 100644 index 5809bc8b..00000000 --- a/src/adapters/http/retry-policy.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { parseRetryAfterDelay } from "../platform/retry-after.ts"; - -const retryKinds: ReadonlySet = 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); -} diff --git a/src/adapters/http/schema-registry.ts b/src/adapters/http/schema-registry.ts deleted file mode 100644 index b22ca36b..00000000 --- a/src/adapters/http/schema-registry.ts +++ /dev/null @@ -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>> = - Object.freeze({}); - -const requestSchemas: Readonly>> = - 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), - }; -} diff --git a/src/bootstrap/runtime-adapters.ts b/src/bootstrap/runtime-adapters.ts index 3563b814..8651f019 100644 --- a/src/bootstrap/runtime-adapters.ts +++ b/src/bootstrap/runtime-adapters.ts @@ -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[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; @@ -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. diff --git a/tests/component/form-foundation.test.tsx b/tests/component/form-foundation.test.tsx index 24294523..9edc44d4 100644 --- a/tests/component/form-foundation.test.tsx +++ b/tests/component/form-foundation.test.tsx @@ -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>; 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( { - 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, diff --git a/tests/fixtures/architecture/forbidden/application-imports-adapter.ts b/tests/fixtures/architecture/forbidden/application-imports-adapter.ts index 3a0bd7cd..6aec6333 100644 --- a/tests/fixtures/architecture/forbidden/application-imports-adapter.ts +++ b/tests/fixtures/architecture/forbidden/application-imports-adapter.ts @@ -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; diff --git a/tests/fixtures/architecture/forbidden/presentation-imports-adapter.ts b/tests/fixtures/architecture/forbidden/presentation-imports-adapter.ts index 7d8db729..a2eb9e4c 100644 --- a/tests/fixtures/architecture/forbidden/presentation-imports-adapter.ts +++ b/tests/fixtures/architecture/forbidden/presentation-imports-adapter.ts @@ -1,3 +1,3 @@ -import "../../../../src/adapters/http/client.ts"; +import "../../../../src/adapters/http/http-execution-v3.ts"; export const invalidEdge = true; diff --git a/tests/fixtures/architecture/forbidden/presentation-imports-adapter.tsx b/tests/fixtures/architecture/forbidden/presentation-imports-adapter.tsx index 9da982f4..c0bbb90a 100644 --- a/tests/fixtures/architecture/forbidden/presentation-imports-adapter.tsx +++ b/tests/fixtures/architecture/forbidden/presentation-imports-adapter.tsx @@ -1,4 +1,4 @@ -import "../../../../src/adapters/http/client.ts"; +import "../../../../src/adapters/http/http-execution-v3.ts"; export function InvalidPresentationFixture() { return

invalid

; diff --git a/tests/fixtures/coverage/repository-omission.json b/tests/fixtures/coverage/repository-omission.json index ae2b8436..1d6940b6 100644 --- a/tests/fixtures/coverage/repository-omission.json +++ b/tests/fixtures/coverage/repository-omission.json @@ -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 } }, diff --git a/tests/helpers/http-contract-fixture.ts b/tests/helpers/http-contract-fixture.ts deleted file mode 100644 index 2e3ab640..00000000 --- a/tests/helpers/http-contract-fixture.ts +++ /dev/null @@ -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> = {}) => - 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[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" ->; diff --git a/tests/integration/auth-recovery.test.ts b/tests/integration/auth-recovery.test.ts deleted file mode 100644 index 28392f86..00000000 --- a/tests/integration/auth-recovery.test.ts +++ /dev/null @@ -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[0]; - -function testClient(options: HttpDependencies) { - return createHttpClient({ ...TEST_HTTP_CONTRACT, ...options }); -} - -type ExternalSessionOwner = Parameters< - typeof createExternalAuthSessionAdapter ->[0]; - -function createOwner( - overrides: Partial = {}, -): 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" }, - }); - }); -}); diff --git a/tests/integration/http-client.test.ts b/tests/integration/http-client.test.ts deleted file mode 100644 index bea16586..00000000 --- a/tests/integration/http-client.test.ts +++ /dev/null @@ -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[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(() => {}); - }, - 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("raw body", { 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: "raw body", 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: "

too early

", 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 = {}, - ) { - 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); - }, - ); -}); diff --git a/tests/integration/http-diagnostics.test.ts b/tests/integration/http-diagnostics.test.ts deleted file mode 100644 index 5c60fd91..00000000 --- a/tests/integration/http-diagnostics.test.ts +++ /dev/null @@ -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>; -}>; - -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() - .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"); - }); -}); diff --git a/tests/integration/http-execution-contract.test.ts b/tests/integration/http-execution-contract.test.ts index e2683b16..89ebd660 100644 --- a/tests/integration/http-execution-contract.test.ts +++ b/tests/integration/http-execution-contract.test.ts @@ -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[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((_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(); - }); }); diff --git a/tests/integration/http-execution-v3-envelope.test.ts b/tests/integration/http-execution-v3-envelope.test.ts index b945c43b..a1c5f6d6 100644 --- a/tests/integration/http-execution-v3-envelope.test.ts +++ b/tests/integration/http-execution-v3-envelope.test.ts @@ -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> = 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 { - 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, "execute"> = v3(), ): Promise { @@ -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 }>, @@ -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>>> = { + "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); }); }); diff --git a/tests/integration/legacy-http-credential-authority.test.ts b/tests/integration/legacy-http-credential-authority.test.ts deleted file mode 100644 index 7f407fb7..00000000 --- a/tests/integration/legacy-http-credential-authority.test.ts +++ /dev/null @@ -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[0]; - -function bearerClient(options: Partial) { - 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 }>; - 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[] = [ - { 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); - }); -}); diff --git a/tests/runtime-schema/http-schema.test.ts b/tests/runtime-schema/http-schema.test.ts index 61a68ad2..b30eeeb0 100644 --- a/tests/runtime-schema/http-schema.test.ts +++ b/tests/runtime-schema/http-schema.test.ts @@ -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); }); }); diff --git a/tests/unit/boundary-mapper.test.ts b/tests/unit/boundary-mapper.test.ts index 8fb4d4be..1580098d 100644 --- a/tests/unit/boundary-mapper.test.ts +++ b/tests/unit/boundary-mapper.test.ts @@ -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", diff --git a/tests/unit/bounded-json-compatibility.test.ts b/tests/unit/bounded-json-compatibility.test.ts deleted file mode 100644 index 7c4b1b80..00000000 --- a/tests/unit/bounded-json-compatibility.test.ts +++ /dev/null @@ -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 | 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({ - 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({ - 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 }, - }); - }); -}); diff --git a/tests/unit/request-builder.test.ts b/tests/unit/request-builder.test.ts deleted file mode 100644 index 9ff8e7c2..00000000 --- a/tests/unit/request-builder.test.ts +++ /dev/null @@ -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" }); - }, - ); -}); diff --git a/tests/unit/retry-policy.test.ts b/tests/unit/retry-policy.test.ts deleted file mode 100644 index 3241bf0e..00000000 --- a/tests/unit/retry-policy.test.ts +++ /dev/null @@ -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); - }); -}); diff --git a/tests/unit/risk-coverage.test.ts b/tests/unit/risk-coverage.test.ts index d58c86fc..0c89a678 100644 --- a/tests/unit/risk-coverage.test.ts +++ b/tests/unit/risk-coverage.test.ts @@ -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, diff --git a/tests/unit/runtime-adapters.test.ts b/tests/unit/runtime-adapters.test.ts index aa9135d7..77bbedb5 100644 --- a/tests/unit/runtime-adapters.test.ts +++ b/tests/unit/runtime-adapters.test.ts @@ -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[0]["runtime"]; type Release = Parameters[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(); - }); });