fix(http): V3 실행기가 짝 백엔드 Envelope를 operation 단위로 읽는다

문제
create:feature가 만든 기능과 참조 기능이 쓰는 V3 실행기
(http-execution-v3.ts, feature-http-binding.ts)는 성공 본문을 DTO로,
실패 본문을 problem details(최상위 code)로 바로 검증한다. 짝 백엔드는
모든 JSON 응답을 Envelope {success, data|error, meta}로 보내고 null 필드는
키째 뺀다(백엔드 docs/web/http-contract.md 1절). 그래서 생성한 기능은 짝
백엔드의 성공을 SCHEMA_MISMATCH로, 실패를 PROBLEM_SCHEMA_INVALID(쓰기는
결과 불명)로 읽는다. 백엔드 맞추기(969979d~64e98ee)는 V2 클라이언트에만
들어갔다.

고른 방법: (가) V3 실행기에 operation 단위 Envelope 읽기
- V3 descriptor에 선택 필드 responseEnvelope("NONE" | "ENVELOPE_V1")를
  둔다. 조립은 이 키를 허용하고 모르는 값을 거부한다. 값이 없으면 지금과
  같다.
- ENVELOPE_V1이면 실행기가 바이트 상한·구조 예산을 Envelope 전체에 건 뒤
  프레임을 확인한다. outputValidator는 data(키가 없으면 null),
  problemValidator는 error를 받는다. 성공 status에 Envelope가 아닌 본문은
  새 위반 ENVELOPE_MISMATCH다. 실패 Envelope의 바이트 상한은
  min(64 KiB, responseByteLimit)이다.
- V2 client.ts의 멱등성 거절 표·필드 검증 판정·gateway status 규칙을
  backend-envelope.ts로 옮기고 V2, V3 실행기, feature binding이 함께
  읽는다. 실행기는 그 표의 판정(422·400 거절, 필드 목록 400은 적용 안 됨,
  409 IDEMPOTENT_IN_FLIGHT·503 IDEMPOTENCY_UNAVAILABLE은 결과 불명)을
  classifyProblem보다 먼저 쓴다. binding은 mapProblem이 답하지 않으면 V2와
  같은 kind·code·validationIssues로 읽는다. V2 출력은 바뀌지 않았다.
- create:feature 뼈대: contribution이 ENVELOPE_V1을 선언하고 problem
  스키마가 Envelope error(code 필수)다. 백엔드 본문을 그대로 적은
  <base>-http-gateway.test.ts를 생성한다.
- MSW createHttpScenarioHandler는 descriptor가 ENVELOPE_V1이면 Envelope로
  답한다.

버린 대안
- provider 단위(실행기 전체): V3 실행기는 baseUrl 하나라 앱 전체가 바뀐다.
  참조 기능·테스트 계약의 problem details fixture가 모두 깨지고 한 앱이 두
  모양의 API를 쓸 수 없다.
- (나) 백엔드 problem+json·DTO 모드: 백엔드 소유자 결정 2(JSON은 모두
  Envelope)와 반대이고 백엔드가 두 모양을 계속 유지해야 한다.
- (다) 기능 스키마가 Envelope를 감쌈: 기능마다 null 생략·success 판별·
  멱등성 판정을 다시 쓰고, V2 행(data 스키마)과 V3 스키마 ID가 갈라진다.

위험·한계
- HttpContractViolationKind에 ENVELOPE_MISMATCH가 더해졌다. default 없는
  exhaustive switch는 분기를 더해야 한다.
- 실행기가 ENVELOPE_V1 operation의 위 판정을 classifyProblem보다 먼저
  정한다. 패키지가 409 IDEMPOTENT_IN_FLIGHT를 적용 안 됨이라 해도 결과
  불명이다.
- V2와 남은 차이: 64 KiB를 넘는 실패 Envelope는 V3만 읽지 않는다. 보낸
  KEYED 요청의 503은 V2만 같은 키로 자동 재시도한다(판정은 같다). 구조
  예산은 V3에만 있다.
- 참조 기능은 그대로 DTO·problem details다. tests/e2e/accessibility.spec.ts는
  모든 API에 []로 답하므로 생성한 기능 라우트는 오류 화면이 검사된다(e2e는
  돌리지 않았다).
- 초기 JS 202,770 → 203,321 B(+551 B, 예산 204,800 B).

검증
- RED: tests/integration/http-execution-v3-envelope.test.ts 19건 중 17건
  실패(성공 → SCHEMA_MISMATCH, 실패 → PROBLEM_SCHEMA_INVALID·MAYBE_APPLIED,
  조립 → unexpected key: responseEnvelope). 크기 2건은 처음부터 통과(동작
  고정).
- GREEN: 같은 파일 25건 통과. 같은 응답을 V2와 V3에 보내 kind·code·
  httpStatus·effect·retryAfterMs·validationIssues가 같음을 7가지 응답으로
  비교한다.
- check:types, lint, check:architecture, check:adapter-inventory,
  check:registries, check:diagnostics, check:i18n, check:ci 통과.
  test:unit 2,604, test:component 244, test:integration 200 통과.
  tests/features·tests/contract 124건 통과.
  test:feature-scaffold 16개 검사 통과(생성한 gateway 테스트 5건,
  Envelope로 답하는 목록 화면 테스트 3건 포함).
  test:sample-removal 23개 검사 통과.
  check:bundle 통과(203,321 / 204,800 B).

Refs: docs/reviews/2026-11-01-maturity-review/README.md 14.3, 14.6
This commit is contained in:
DongHyeonka
2026-11-03 20:10:51 +09:00
parent ec7435c3f7
commit 7db32e1343
13 changed files with 1317 additions and 212 deletions
@@ -58,6 +58,7 @@ All 24 files below were read in full.
| src/adapters/cross-context-invalidation/browser-cross-context-invalidation.ts | Versioned invalidate-only wire protocol, BroadcastChannel/storage fallback, TTL, dedupe, per-source sequence/gap detection, bounded tracking, subscription and close | contracts/cache-invalidation.ts; host adapter; TanStack coordinator | Preserve closed envelope, bounded maps, and idempotent close. Modify exact storage-area admission; dual-transport fan-out is a separate product choice. |
| src/adapters/cross-context-invalidation/index.ts | Public barrel for host/runtime types and constructors | bootstrap and query-cache coordinator | Modify exports only if the storage event facade type changes. |
| 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. |
+91 -90
View File
@@ -64,95 +64,96 @@
| 54 | `src/adapters/cross-context-invalidation/index.ts` | [Network/state](./01-network-and-state.md) |
| 55 | `src/adapters/diagnostics/bounded-diagnostics.ts` | [Network/state](./01-network-and-state.md) |
| 56 | `src/adapters/diagnostics/index.ts` | [Network/state](./01-network-and-state.md) |
| 57 | `src/adapters/http/bounded-body-reader.ts` | [Network/state](./01-network-and-state.md) |
| 58 | `src/adapters/http/bounded-json.ts` | [Network/state](./01-network-and-state.md) |
| 59 | `src/adapters/http/client.ts` | [Network/state](./01-network-and-state.md) |
| 60 | `src/adapters/http/feature-http-binding.ts` | [Network/state](./01-network-and-state.md) |
| 61 | `src/adapters/http/http-contract-bridge.ts` | [Network/state](./01-network-and-state.md) |
| 62 | `src/adapters/http/http-effect-certainty.ts` | [Network/state](./01-network-and-state.md) |
| 63 | `src/adapters/http/http-execution-v3.ts` | [Network/state](./01-network-and-state.md) |
| 64 | `src/adapters/http/http-retry-lifecycle.ts` | [Network/state](./01-network-and-state.md) |
| 65 | `src/adapters/http/index.ts` | [Network/state](./01-network-and-state.md) |
| 66 | `src/adapters/http/platform-error-mapping.ts` | [Network/state](./01-network-and-state.md) |
| 67 | `src/adapters/http/request-builder.ts` | [Network/state](./01-network-and-state.md) |
| 68 | `src/adapters/http/resource-mapper.ts` | [Network/state](./01-network-and-state.md) |
| 69 | `src/adapters/http/retry-policy.ts` | [Network/state](./01-network-and-state.md) |
| 70 | `src/adapters/http/schema-registry.ts` | [Network/state](./01-network-and-state.md) |
| 71 | `src/adapters/platform/abortable-operation.ts` | [Network/state](./01-network-and-state.md) |
| 72 | `src/adapters/platform/bounded-capacity.ts` | [Network/state](./01-network-and-state.md) |
| 73 | `src/adapters/platform/browser-lifecycle.ts` | [Network/state](./01-network-and-state.md) |
| 74 | `src/adapters/platform/browser-mutation-intent-factory.ts` | [Network/state](./01-network-and-state.md) |
| 75 | `src/adapters/platform/index.ts` | [Network/state](./01-network-and-state.md) |
| 76 | `src/adapters/platform/indexeddb-connection.ts` | [Network/state](./01-network-and-state.md) |
| 77 | `src/adapters/platform/indexeddb-transaction.ts` | [Network/state](./01-network-and-state.md) |
| 78 | `src/adapters/platform/json-member-scanner.ts` | [Network/state](./01-network-and-state.md) |
| 79 | `src/adapters/platform/retry-after.ts` | [Network/state](./01-network-and-state.md) |
| 80 | `src/adapters/platform/system-clock.ts` | [Network/state](./01-network-and-state.md) |
| 81 | `src/adapters/query-cache/conditional-validator-store.ts` | [Network/state](./01-network-and-state.md) |
| 82 | `src/adapters/query-cache/cursor-pagination-contract.ts` | [Network/state](./01-network-and-state.md) |
| 83 | `src/adapters/query-cache/cursor-pagination-runtime.ts` | [Network/state](./01-network-and-state.md) |
| 84 | `src/adapters/query-cache/index.ts` | [Network/state](./01-network-and-state.md) |
| 85 | `src/adapters/query-cache/server-state-scope-runtime.ts` | [Network/state](./01-network-and-state.md) |
| 86 | `src/adapters/query-cache/tanstack-cache-coordinator.ts` | [Network/state](./01-network-and-state.md) |
| 87 | `src/adapters/query-cache/tanstack-query-cache.ts` | [Network/state](./01-network-and-state.md) |
| 88 | `src/adapters/realtime/event-codec.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
| 89 | `src/adapters/realtime/event-consumer.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
| 90 | `src/adapters/realtime/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
| 91 | `src/adapters/realtime/live-poll-handoff-coordinator.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
| 92 | `src/adapters/realtime/polling/bounded-poll-coordinator.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
| 93 | `src/adapters/realtime/polling/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
| 94 | `src/adapters/realtime/reconnect-coordinator.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
| 95 | `src/adapters/realtime/reconnect-policy.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
| 96 | `src/adapters/realtime/result.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
| 97 | `src/adapters/realtime/sse/fetch-sse-connection.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
| 98 | `src/adapters/realtime/sse/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
| 99 | `src/adapters/realtime/sse/sse-parser.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
| 100 | `src/adapters/realtime/stream-coordinator.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
| 101 | `src/adapters/realtime/websocket/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
| 102 | `src/adapters/realtime/websocket/websocket-connection.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
| 103 | `src/adapters/realtime/websocket/websocket-protocol.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
| 104 | `src/adapters/service-worker/index.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
| 105 | `src/adapters/service-worker/service-worker-entry.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
| 106 | `src/adapters/service-worker/service-worker-lifecycle.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
| 107 | `src/adapters/service-worker/service-worker-page-controller.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
| 108 | `src/adapters/service-worker/service-worker-protocol.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
| 109 | `src/adapters/service-worker/service-worker-removal.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
| 110 | `src/adapters/service-worker/service-worker-static-assets.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
| 111 | `src/adapters/storage/browser-storage-adapter.ts` | [Storage/files](./03-storage-and-browser-files.md) |
| 112 | `src/adapters/storage/browser-storage-codec.ts` | [Storage/files](./03-storage-and-browser-files.md) |
| 113 | `src/adapters/storage/index.ts` | [Storage/files](./03-storage-and-browser-files.md) |
| 114 | `src/adapters/storage/indexeddb/index.ts` | [Storage/files](./03-storage-and-browser-files.md) |
| 115 | `src/adapters/storage/indexeddb/indexeddb-governance.ts` | [Storage/files](./03-storage-and-browser-files.md) |
| 116 | `src/adapters/storage/indexeddb/indexeddb-maintenance.ts` | [Storage/files](./03-storage-and-browser-files.md) |
| 117 | `src/adapters/storage/indexeddb/indexeddb-migrations.ts` | [Storage/files](./03-storage-and-browser-files.md) |
| 118 | `src/adapters/storage/indexeddb/indexeddb-records.ts` | [Storage/files](./03-storage-and-browser-files.md) |
| 119 | `src/adapters/storage/indexeddb/indexeddb-runtime.ts` | [Storage/files](./03-storage-and-browser-files.md) |
| 120 | `src/adapters/storage/indexeddb/indexeddb-types.ts` | [Storage/files](./03-storage-and-browser-files.md) |
| 121 | `src/adapters/storage/opfs/browser-opfs-runtime.ts` | [Storage/files](./03-storage-and-browser-files.md) |
| 122 | `src/adapters/storage/opfs/index.ts` | [Storage/files](./03-storage-and-browser-files.md) |
| 123 | `src/adapters/storage/opfs/indexeddb-opfs-journal.ts` | [Storage/files](./03-storage-and-browser-files.md) |
| 124 | `src/adapters/storage/opfs/opfs-byte-store-adapter.ts` | [Storage/files](./03-storage-and-browser-files.md) |
| 125 | `src/adapters/storage/opfs/opfs-policy.ts` | [Storage/files](./03-storage-and-browser-files.md) |
| 126 | `src/adapters/storage/opfs/opfs-prepared-object.ts` | [Storage/files](./03-storage-and-browser-files.md) |
| 127 | `src/adapters/storage/opfs/opfs-worker-client.ts` | [Storage/files](./03-storage-and-browser-files.md) |
| 128 | `src/adapters/storage/opfs/opfs-worker-protocol.ts` | [Storage/files](./03-storage-and-browser-files.md) |
| 129 | `src/adapters/storage/opfs/opfs-worker-runtime.ts` | [Storage/files](./03-storage-and-browser-files.md) |
| 130 | `src/adapters/telemetry/best-effort-telemetry.ts` | [Network/state](./01-network-and-state.md) |
| 131 | `src/adapters/telemetry/feature-telemetry.ts` | [Network/state](./01-network-and-state.md) |
| 132 | `src/adapters/telemetry/index.ts` | [Network/state](./01-network-and-state.md) |
| 133 | `src/adapters/telemetry/telemetry-collector.ts` | [Network/state](./01-network-and-state.md) |
| 134 | `src/adapters/web-push/codec-primitives.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
| 135 | `src/adapters/web-push/inbound/notification-click-adapter.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
| 136 | `src/adapters/web-push/inbound/push-event-adapter.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
| 137 | `src/adapters/web-push/index.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
| 138 | `src/adapters/web-push/notification-registry.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
| 139 | `src/adapters/web-push/push-association-fence-store.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
| 140 | `src/adapters/web-push/push-codec.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
| 141 | `src/adapters/web-push/push-registration-gateway.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
| 142 | `src/adapters/web-push/push-subscription-adapter.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
| 143 | `src/adapters/web-push/runtime-support.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
| 144 | `src/adapters/web-push/service-worker-runtime.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
| 145 | `src/adapters/web-push/service-worker-scope-host.ts` | [Worker/push](./05-service-worker-and-web-push.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) |
합계: **145/145**. 새 adapter 파일이 추가되면 이 ledger와 해당 상세 리뷰 inventory를 같은 변경에서 갱신한다.
합계: **146/146**. 새 adapter 파일이 추가되면 이 ledger와 해당 상세 리뷰 inventory를 같은 변경에서 갱신한다.
+144 -6
View File
@@ -292,6 +292,7 @@ export function planFeature(
[`${feature}/presentation/${base}-list-page.tsx`, renderListPage(shape)],
[`tests/features/${id}/${base}-feature-input.test.ts`, renderInputTest(shape)],
[`tests/features/${id}/${base}-list-page.test.tsx`, renderPageTest(shape)],
[`tests/features/${id}/${base}-http-gateway.test.ts`, renderGatewayTest(shape)],
[`artifacts/tests/a11y-manual/${routeId}.md`, renderA11yRecord(routeId)],
]);
return Object.freeze({
@@ -539,13 +540,17 @@ export type ${pascal}ItemDto = z.output<typeof ${camel}ItemDtoSchema>;
export const ${camel}ItemListPayloadSchema = z.array(${camel}ItemDtoSchema).max(100);
/** Problem details; a backend message is never kept. */
/**
* The paired backend's Envelope \`error\` (clean-architecture-backend-template
* docs/web/http-contract.md §1). Branch on \`code\`; the backend message is
* never kept.
*/
export const ${camel}ProblemSchema = z
.object({
type: z.string().min(1).max(512),
title: z.string().min(1).max(240),
status: z.int().min(100).max(599),
code: z.string().min(1).max(120).optional(),
code: z.string().regex(/^[A-Z0-9_]{1,64}$/u),
category: z.string().min(1).max(64).optional(),
retryable: z.boolean().optional(),
details: z.unknown().optional(),
})
.strip();
@@ -726,6 +731,9 @@ export const ${operationId}_CONTRACT = Object.freeze({
retrySemantics: "SAFE" as const,
requestBody: "NONE" as const,
responseBody: "REQUIRED_JSON" as const,
// The paired backend wraps every JSON body (http-contract.md §1). Drop
// this line for a backend that sends the DTO and problem details bare.
responseEnvelope: "ENVELOPE_V1" as const,
commandRecovery: null,
commandEffect: null,
projectRequest() {
@@ -1177,7 +1185,7 @@ describe("${names.id} list page through the router", () => {
expect(await screen.findByText("First item")).toBeVisible();
});
// tests/e2e/accessibility.spec.ts answers every API with [].
// The backend answers an empty list as \`data: []\`, never by dropping \`data\`.
it("renders an empty list as the empty state", async () => {
api.use(createHttpScenarioHandler(${operationId}_CONTRACT, { scenario: "empty", payload: [] }));
await openList();
@@ -1207,6 +1215,136 @@ describe("${names.id} list page through the router", () => {
`;
}
function renderGatewayTest({ names, apiPath }: Shape): string {
const { base, pascal, upper } = names;
return `import { http, HttpResponse, type JsonBodyType } from "msw";
import { setupServer } from "msw/node";
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
import {
createContractHttpExecutor,
createFeatureHttpBinding,
type InstalledHttpOperationExecutor,
} from "../../../src/adapters/http/index.ts";
import {
create${pascal}HttpGateway,
${upper}_HTTP_OPERATIONS,
} from "../../../src/features/${names.id}/adapters/${base}-http-gateway.ts";
/**
* The paired backend's wire (clean-architecture-backend-template
* docs/web/http-contract.md §1): every JSON body is an Envelope, and a null
* field is dropped with its key. The bodies are written out here rather than
* taken from the shared scenarios, so this fails if the contract stops
* reading that wire.
*/
const API = "https://api.test";
const META = { requestId: "req-1", traceId: "0af7651916cd43dd8448eb211c80319c" };
const api = setupServer();
beforeAll(() => api.listen({ onUnhandledRequest: "error" }));
afterEach(() => api.resetHandlers());
afterAll(() => api.close());
function answer(status: number, body: JsonBodyType) {
api.use(http.get(\`\${API}${apiPath}\`, () => HttpResponse.json(body, { status })));
}
function failure(code: string, details?: JsonBodyType) {
return {
success: false,
error: {
code,
category: "VALIDATION",
message: "backend message",
retryable: false,
...(details === undefined ? {} : { details }),
},
meta: META,
};
}
function gateway() {
const executor = createContractHttpExecutor({
baseUrl: API,
maxRetryAttempts: 0,
attachCredentials: () => ({
kind: "READY" as const,
headers: { authorization: "Bearer test-token" },
}),
});
const installed: InstalledHttpOperationExecutor = Object.freeze({
execute: (contract, input, context) =>
executor.execute(contract, input, {
routeId: context.routeId,
scope: Object.freeze({
generation: 1,
fingerprint: "${names.id}-test-scope",
identities: Object.freeze({}) as never,
signal: new AbortController().signal,
isCurrent: () => true,
}),
}),
});
return create${pascal}HttpGateway(createFeatureHttpBinding(installed, ${upper}_HTTP_OPERATIONS));
}
describe("${names.id} HTTP gateway on the paired backend's Envelope", () => {
it("reads the success Envelope's data", async () => {
answer(200, { success: true, data: [{ id: "item-1", name: "First item" }], meta: META });
await expect(gateway().list()).resolves.toEqual({
ok: true,
value: [{ itemId: "item-1", name: "First item" }],
});
});
it("reads an Envelope whose null keys the backend dropped", async () => {
// No id keys: the answer was written before the request id filter.
answer(200, { success: true, data: [], meta: {} });
await expect(gateway().list()).resolves.toEqual({ ok: true, value: [] });
});
it("reads the failure Envelope's code and drops its message", async () => {
answer(404, failure("NOT_FOUND"));
const result = await gateway().list();
expect(result).toMatchObject({
ok: false,
error: { kind: "NOT_FOUND", code: "NOT_FOUND", httpStatus: 404 },
});
expect(JSON.stringify(result)).not.toContain("backend message");
});
it("reads a parameter validation failure's field list", async () => {
answer(
400,
failure("VALIDATION_FAILED", [{ field: "size", code: "MAX", message: "too large" }]),
);
await expect(gateway().list()).resolves.toMatchObject({
ok: false,
error: {
kind: "VALIDATION_REJECTED",
code: "VALIDATION_FAILED",
validationIssues: [{ path: "size", code: "MAX" }],
},
});
});
it("refuses a bare DTO", async () => {
answer(200, [{ id: "item-1", name: "First item" }]);
await expect(gateway().list()).resolves.toMatchObject({
ok: false,
error: { kind: "ENVELOPE_MISMATCH" },
});
});
});
`;
}
function renderA11yRecord(routeId: string): string {
return `# ${routeId} accessibility review
+159
View File
@@ -0,0 +1,159 @@
import {
kindForStatus,
safeValidationIssues,
type FailureKind,
type ValidationIssue,
} from "../../contracts/errors.ts";
import {
failureEnvelopeSchema,
successEnvelopeSchema,
} from "./schema-registry.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.
*/
export type EnvelopeError = Readonly<{
code: string;
category?: string;
message?: string;
retryable?: boolean;
details?: unknown;
}>;
export type EnvelopeRead<Value> =
| Readonly<{ ok: true; value: Value }>
| Readonly<{ ok: false }>;
const ENVELOPE_INVALID: EnvelopeRead<never> = Object.freeze({ ok: false });
/** The success `data`. A missing key is the null the backend dropped. */
export function readSuccessEnvelope(value: unknown): EnvelopeRead<unknown> {
const parsed = successEnvelopeSchema.safeParse(value);
return parsed.success
? Object.freeze({ ok: true as const, value: parsed.data.data })
: ENVELOPE_INVALID;
}
/** The failure `error` object, as the backend sent it. */
export function readFailureEnvelope(
value: unknown,
): EnvelopeRead<EnvelopeError> {
const parsed = failureEnvelopeSchema.safeParse(value);
return parsed.success
? Object.freeze({ ok: true as const, value: parsed.data.error })
: ENVELOPE_INVALID;
}
/**
* 백엔드 1101/02-01. Refusals the paired backend answers before it runs the
* command (§2): the request was not applied and sending it again unchanged
* gets the same answer. Only the documented status and code together count.
* The value is the diagnostics `reason`, named for what is wrong on this side.
*/
const IDEMPOTENCY_REFUSALS: Readonly<
Record<string, Readonly<{ status: number; reason: string }>>
> = Object.freeze({
// The same key went out with another body.
IDEMPOTENT_REQUEST_MISMATCH: Object.freeze({
status: 422,
reason: "IDEMPOTENT_REQUEST_MISMATCH",
}),
// `isValidIdempotencyKey` passed the key before sending, so the client and
// server key rules disagree.
IDEMPOTENCY_KEY_INVALID: Object.freeze({
status: 400,
reason: "IDEMPOTENCY_KEY_RULE_MISMATCH",
}),
});
export function idempotencyRefusalReason(
code: string,
status: number | undefined,
): string | undefined {
const refusal = Object.hasOwn(IDEMPOTENCY_REFUSALS, code)
? IDEMPOTENCY_REFUSALS[code]
: undefined;
return refusal !== undefined && refusal.status === status
? refusal.reason
: undefined;
}
/**
* 백엔드 1101/02-01 후속. A field validation failure: a 422, or the paired
* backend's 400 VALIDATION_FAILED whose details is the field list (§4). A 400
* VALIDATION_FAILED whose body did not parse carries `{cause}`, not a list,
* and is not one.
*/
export function isFieldValidationFailure(
status: number,
error: EnvelopeError,
): boolean {
return (
status === 422 ||
(status === 400 &&
error.code === "VALIDATION_FAILED" &&
Array.isArray(error.details))
);
}
/**
* The verdict the backend contract gives whatever the operation is, or
* `undefined` when the operation's own classifier decides.
*
* - Not applied: a field validation failure, checked when the request is
* bound, before the command runs (64e98ee), and an idempotency refusal.
* - Maybe applied: 409 IDEMPOTENT_IN_FLIGHT (the first request still runs)
* and 503 IDEMPOTENCY_UNAVAILABLE. §2 says to resend both with the same
* key, which only an unknown result keeps.
*/
export function envelopeFailureEffect(
status: number,
error: EnvelopeError,
): "NOT_APPLIED" | "MAYBE_APPLIED" | undefined {
if (
(status === 409 && error.code === "IDEMPOTENT_IN_FLIGHT") ||
(status === 503 && error.code === "IDEMPOTENCY_UNAVAILABLE")
) {
return "MAYBE_APPLIED";
}
return isFieldValidationFailure(status, error) ||
idempotencyRefusalReason(error.code, status) !== undefined
? "NOT_APPLIED"
: undefined;
}
/**
* Q-6.3-3b. A gateway 5xx/408/425 is a server outage, not a contract breach:
* it keeps the SERVER_FAILURE retry rule.
*/
export function gatewayFailureOr(status: number, kind: FailureKind): FailureKind {
return status >= 500 || status === 408 || status === 425
? "SERVER_FAILURE"
: kind;
}
/** The failure kind, code and field issues the V2 client reports. */
export function envelopeFailureReading(
status: number,
error: EnvelopeError,
): Readonly<{
kind: FailureKind;
code: string;
validationIssues?: readonly ValidationIssue[];
}> {
const fieldValidation = isFieldValidationFailure(status, error);
return Object.freeze({
kind: fieldValidation
? "VALIDATION_REJECTED"
: gatewayFailureOr(status, kindForStatus(status)),
code: error.code,
...(fieldValidation
? { validationIssues: safeValidationIssues(error.details) }
: {}),
});
}
+26 -83
View File
@@ -3,8 +3,14 @@ import { getApiOperation } from "../../contracts/api-operations.ts";
import {
createFailure as failure,
kindForStatus as statusKind,
safeValidationIssues,
} 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";
@@ -41,7 +47,7 @@ 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, FailureKind } from "../../contracts/errors.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";
@@ -850,17 +856,6 @@ export function createHttpClient(
class LogicalDeadlineError extends Error {}
/**
* 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 normal
* SERVER_FAILURE retry rule instead of a non-retryable body error.
*/
function gatewayFailureOr(status: number, kind: FailureKind): FailureKind {
return status >= 500 || status === 408 || status === 425
? "SERVER_FAILURE"
: kind;
}
async function parseResponse(
response: Response,
operation: ApiOperation,
@@ -1002,47 +997,30 @@ async function parseResponse(
};
}
const backendError =
envelopeRecord.error && typeof envelopeRecord.error === "object"
? (envelopeRecord.error as Record<string, unknown>)
: {};
const code = safeBackendCode(envelope);
// 백엔드 1101/02-01 후속. The paired backend answers a field validation
// failure with 400 VALIDATION_FAILED whose details is the field list
// (clean-architecture-backend-template docs/web/http-contract.md §4). It is
// the same failure as a 422, so it gets the same kind and issues and a form
// maps it with the same allowed fields. A 400 VALIDATION_FAILED whose body
// did not parse carries `{cause}`, not a list, and keeps its reading.
// Field validation is checked when the request is bound, before the
// command runs, so it is NOT_APPLIED: the coordinator must not hold it as an
// unknown effect, or the form cannot save the corrected value.
const fieldValidation =
response.status === 422 ||
(response.status === 400 &&
code === "VALIDATION_FAILED" &&
Array.isArray(backendError.details));
// R3-1. V2 treats a 408/425 error envelope as the same server failure as a
// gateway body; the shared status map in contracts is not changed.
const kind = fieldValidation
? "VALIDATION_REJECTED"
: gatewayFailureOr(response.status, statusKind(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<string, unknown>).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(kind, operation.operationId, attempt, {
code,
// A refusal the server made before running the command: not applied,
// so the mutation coordinator does not hold it as an unknown effect.
...(fieldValidation ||
idempotencyRefusalReason(code, response.status) !== undefined
? { effect: "NOT_APPLIED" as const }
: {}),
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: fieldValidation
? safeValidationIssues(backendError.details)
: undefined,
validationIssues: reading.validationIssues,
}),
};
}
@@ -1099,41 +1077,6 @@ async function recoverSession(
};
}
/**
* 백엔드 1101/02-01. Refusals the paired backend answers before it runs the
* command (clean-architecture-backend-template docs/web/http-contract.md §2):
* the request was not applied and sending it again unchanged gets the same
* answer. Only the documented status and code together count. The value is
* the diagnostics `reason`, named for what is wrong on this side.
*/
const IDEMPOTENCY_REFUSALS: Readonly<
Record<string, Readonly<{ status: number; reason: string }>>
> = Object.freeze({
// The same key went out with another body.
IDEMPOTENT_REQUEST_MISMATCH: Object.freeze({
status: 422,
reason: "IDEMPOTENT_REQUEST_MISMATCH",
}),
// `isValidIdempotencyKey` passed the key before sending, so the client and
// server key rules disagree.
IDEMPOTENCY_KEY_INVALID: Object.freeze({
status: 400,
reason: "IDEMPOTENCY_KEY_RULE_MISMATCH",
}),
});
function idempotencyRefusalReason(
code: string,
status: number | undefined,
): string | undefined {
const refusal = Object.hasOwn(IDEMPOTENCY_REFUSALS, code)
? IDEMPOTENCY_REFUSALS[code]
: undefined;
return refusal !== undefined && refusal.status === status
? refusal.reason
: undefined;
}
function safeBackendCode(envelope: unknown): string {
if (!envelope || typeof envelope !== "object") return "HTTP_FAILURE";
const error = (envelope as Record<string, unknown>).error;
+46 -6
View File
@@ -13,6 +13,7 @@ import {
} from "../../contracts/errors.ts";
import type { MutationIntent } from "../../contracts/mutation-intent.ts";
import type { ExecutionContext } from "../../platform/execution/execution-context.ts";
import { envelopeFailureReading } from "./backend-envelope.ts";
import type {
HttpContractViolation,
HttpExecutionOutcome,
@@ -280,18 +281,57 @@ export function createFeatureHttpBinding<
return projectExecutionOutcome(
operation.operationId,
operation.mapSuccess as (value: WireOutput) => BoundaryMappingResult<Value>,
operation.mapProblem as
| ((
problem: Problem,
metadata: SafeResponseMetadata,
) => FeatureHttpProblemMapping | undefined)
| undefined,
problemMapper(
operation.mapProblem as
| ((
problem: Problem,
metadata: SafeResponseMetadata,
) => FeatureHttpProblemMapping | undefined)
| undefined,
contract.contract.responseEnvelope === "ENVELOPE_V1",
),
outcome,
);
},
});
}
/**
* 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.
*/
function problemMapper<Problem>(
mapProblem:
| ((
problem: Problem,
metadata: SafeResponseMetadata,
) => FeatureHttpProblemMapping | undefined)
| undefined,
enveloped: boolean,
):
| ((
problem: Problem,
metadata: SafeResponseMetadata,
) => FeatureHttpProblemMapping | undefined)
| undefined {
if (!enveloped) return mapProblem;
return (problem, metadata) =>
mapProblem?.(problem, metadata) ??
envelopeProblemMapping(problem, metadata.status);
}
function envelopeProblemMapping(
problem: unknown,
status: number,
): FeatureHttpProblemMapping | undefined {
if (!problem || typeof problem !== "object") return undefined;
const { code, details } = problem as Readonly<Record<string, unknown>>;
return typeof code === "string" && /^[A-Z0-9_]{1,64}$/u.test(code)
? envelopeFailureReading(status, { code, details })
: undefined;
}
/**
* 03-03. A failure carries the server's echoed correlation id as `requestId`,
* so the support reference a user reports points at one server log entry.
+70 -16
View File
@@ -2,6 +2,7 @@ import {
HTTP_EXECUTION_CEILINGS,
invokeValidator,
type InstalledHttpContract,
type ValidatorInvocation,
} from "../../contracts/external-contract-runtime.ts";
import type { CacheScopeSnapshot } from "../../contracts/server-state-scope.ts";
import {
@@ -44,6 +45,11 @@ import {
type PhysicalAttemptState,
} from "./http-effect-certainty.ts";
import { parseRetryAfter } from "./retry-policy.ts";
import {
envelopeFailureEffect,
readFailureEnvelope,
readSuccessEnvelope,
} from "./backend-envelope.ts";
import {
createExecutionContext,
MAX_INTERACTION_DEADLINE_MS,
@@ -93,6 +99,8 @@ export type HttpContractViolationKind =
| "RESPONSE_TOO_LARGE"
| "UTF8_INVALID"
| "JSON_INVALID"
/** 1101 README 14.3. A success status whose body is not a success Envelope. */
| "ENVELOPE_MISMATCH"
| "SUCCESS_SCHEMA_INVALID"
| "PROBLEM_SCHEMA_INVALID"
| "VALIDATOR_RUNTIME_FAILURE"
@@ -1407,7 +1415,25 @@ async function admitResponse<Input, WireOutput, Problem>(
);
}
const validated = invokeValidator(contract.outputValidator, decoded.value);
// 1101 README 14.3. The frame is checked after the byte and structure
// bounds, which count the whole Envelope, as V2 counts maxResponseBytes.
let wireValue = decoded.value;
if (contract.responseEnvelope === "ENVELOPE_V1") {
const framed = readSuccessEnvelope(decoded.value);
if (!framed.ok) {
return settled(
violation(
"ENVELOPE_MISMATCH",
"RESPONSE",
postDispatchEffect(isCommand),
),
"CONTRACT_VIOLATION",
);
}
wireValue = framed.value;
}
const validated = invokeValidator(contract.outputValidator, wireValue);
if (validated.outcome === "THROWN") {
return settled(
violation(
@@ -1550,6 +1576,11 @@ async function awaitWithAbort<Value>(
}
}
const UNFRAMED_PROBLEM: ValidatorInvocation<never> = Object.freeze({
outcome: "INVALID" as const,
issues: Object.freeze([]),
});
async function admitProblem<Input, WireOutput, Problem>(
operation: InstalledHttpContract<Input, WireOutput, Problem>,
response: Response,
@@ -1562,12 +1593,18 @@ async function admitProblem<Input, WireOutput, Problem>(
const contract = operation.contract;
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.
const problemByteLimit = enveloped
? Math.min(
HTTP_EXECUTION_CEILINGS.problemResponseBytes,
operation.frontend.responseByteLimit,
)
: HTTP_EXECUTION_CEILINGS.problemResponseBytes;
const bytes = await readResponseBytes(
response,
HTTP_EXECUTION_CEILINGS.problemResponseBytes,
signal,
);
const bytes = await readResponseBytes(response, problemByteLimit, signal);
if (!bytes.ok || isEffectivelyEmpty(bytes.bytes)) {
// An unclassifiable failure stays uncertain for a command.
return Object.freeze({
@@ -1612,10 +1649,8 @@ async function admitProblem<Input, WireOutput, Problem>(
}
if (
!checkJsonStructure(
decoded.value,
responseValidationBudget(HTTP_EXECUTION_CEILINGS.problemResponseBytes),
).ok
!checkJsonStructure(decoded.value, responseValidationBudget(problemByteLimit))
.ok
) {
return Object.freeze({
result: violation<WireOutput, Problem>(
@@ -1630,7 +1665,21 @@ async function admitProblem<Input, WireOutput, Problem>(
});
}
const validated = invokeValidator(contract.problemValidator, decoded.value);
// 1101 README 14.3. An Envelope operation's problem is the `error` object.
// A body that is not a failure Envelope is an unreadable problem.
let validated: ValidatorInvocation<Problem>;
let backendEffect: "NOT_APPLIED" | "MAYBE_APPLIED" | undefined;
if (enveloped) {
const framed = readFailureEnvelope(decoded.value);
validated = framed.ok
? invokeValidator(contract.problemValidator, framed.value)
: UNFRAMED_PROBLEM;
backendEffect = framed.ok
? envelopeFailureEffect(status, framed.value)
: undefined;
} else {
validated = invokeValidator(contract.problemValidator, decoded.value);
}
if (validated.outcome !== "VALID") {
return Object.freeze({
result: violation<WireOutput, Problem>(
@@ -1647,11 +1696,16 @@ async function admitProblem<Input, WireOutput, Problem>(
});
}
const classification = classifyProblemEffect({
status,
problem: validated.value,
descriptor: contract.commandEffect,
});
// 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.
const classification =
isCommand && backendEffect !== undefined
? Object.freeze({ effect: backendEffect, contractRuntimeFailure: false })
: classifyProblemEffect({
status,
problem: validated.value,
descriptor: contract.commandEffect,
});
const effect = isCommand
? classification.effect
: certaintyForAbandonedAttempt(attemptState, false);
+4 -3
View File
@@ -43,9 +43,10 @@ export type { CredentialPatchOutcome } from "./http-contract-bridge.ts";
*
* 이 템플릿은 V2의 오퍼레이션 레지스트리와 payload 매퍼를 비워서 출하한다.
* 제품이 `RuntimeHttpContract`(`src/bootstrap/runtime-adapters.ts`)의 네
* 슬롯을 주입해야 동작한다. V3의 롤백 경로는 아니다 — V2는
* `{ success, data, meta }` 봉투를, V3는 DTO 자체를 검증하므로 V2로 되돌리려면
* 슬롯 주입과 함께 서버 응답도 V2 봉투여야 한다.
* 슬롯을 주입해야 동작한다. V2는 늘 `{ success, data | error, meta }` 봉투를
* 읽는다. V3는 descriptor가 `responseEnvelope: "ENVELOPE_V1"`일 때만 봉투를
* 읽고, 아니면 DTO 자체를 검증한다. 두 경로는 같은 봉투 해석
* (`backend-envelope.ts`)을 쓴다.
*/
export {
createHttpClient,
+26 -1
View File
@@ -161,6 +161,8 @@ export type HttpMethod =
export type RetrySemantics = "SAFE" | "IDEMPOTENT" | "KEYED" | "NEVER";
export type ResponseEnvelope = "NONE" | "ENVELOPE_V1";
export interface HttpExecutionPolicy {
readonly policyId: string;
readonly requestByteLimit: number;
@@ -191,6 +193,17 @@ export interface InstalledHttpContract<Input, WireOutput, Problem> {
retrySemantics: RetrySemantics;
requestBody: "NONE" | "JSON";
responseBody: "REQUIRED_JSON" | "OPTIONAL_JSON" | "NONE";
/**
* 1101 README 14.3. How the server frames a JSON body. Absent or `"NONE"`:
* the body is the DTO, and a failure body is the problem. `"ENVELOPE_V1"`:
* the paired backend's `{ success, data | error, meta }`
* (clean-architecture-backend-template docs/web/http-contract.md §1).
* `outputValidator` then sees `data` (`null` when the key is absent),
* `problemValidator` sees `error`, and the backend's operation-independent
* verdicts (§2, §4) come before `commandEffect.classifyProblem`. A body
* that is empty by `emptyBodyStatuses` has no Envelope.
*/
responseEnvelope?: ResponseEnvelope;
commandRecovery: CommandRecoveryDescriptor | null;
commandEffect: CommandEffectDescriptor<Problem> | null;
/**
@@ -468,6 +481,13 @@ function assertHttpContract(
) {
fail(`${label}: responseBody`);
}
if (
contract.responseEnvelope !== undefined &&
contract.responseEnvelope !== "NONE" &&
contract.responseEnvelope !== "ENVELOPE_V1"
) {
fail(`${label}: responseEnvelope`);
}
assertStatuses(contract.acceptedStatuses, `${label}.acceptedStatuses`);
if (contract.emptyBodyStatuses.length > 0) {
assertStatuses(contract.emptyBodyStatuses, `${label}.emptyBodyStatuses`);
@@ -593,6 +613,11 @@ const HTTP_CONTRACT_KEYS = [
"projectRequest",
] as const;
const HTTP_CONTRACT_ALLOWED_KEYS = [
...HTTP_CONTRACT_KEYS,
"responseEnvelope",
] as const;
const COMMAND_RECOVERY_KEYS = [
"mode",
"operationIdentityField",
@@ -639,7 +664,7 @@ function snapshotHttpContract(
});
const source = exactOwnDataSnapshot<
InstalledHttpContract<unknown, unknown, unknown>["contract"]
>(row.contract, HTTP_CONTRACT_KEYS, HTTP_CONTRACT_KEYS, reject);
>(row.contract, HTTP_CONTRACT_ALLOWED_KEYS, HTTP_CONTRACT_KEYS, reject);
const contract = Object.freeze({
...source,
acceptedStatuses: statusArray(source.acceptedStatuses, reject),
@@ -0,0 +1,677 @@
import { HttpResponse, http, type JsonBodyType } from "msw";
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,
defineFeatureHttpOperation,
type InstalledHttpOperationExecutor,
} from "../../src/adapters/http/index.ts";
import { mappingSuccess } from "../../src/contracts/boundary-mapper.ts";
import type { AppFailure } from "../../src/contracts/errors.ts";
import {
composeContractContributions,
type CommandEffectDescriptor,
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";
/**
* 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).
*/
const BASE_URL = "https://api.test";
const LIST_LIMIT = 2_048;
const itemSchema = z
.object({
id: z.string().min(1),
name: z.string().min(1),
// The backend drops a null field with its key.
description: z.string().optional(),
})
.strip();
/** What the scaffold generates as the problem: the Envelope's `error`. */
const errorSchema = z
.object({
code: z.string().regex(/^[A-Z0-9_]{1,64}$/u),
category: z.string().min(1).max(64).optional(),
retryable: z.boolean().optional(),
details: z.unknown().optional(),
})
.strip();
type EnvelopeProblem = z.output<typeof errorSchema>;
const problemValidator = zodValidator("EnvelopeTestProblem", errorSchema);
const noInput = zodValidator("EnvelopeTestNoInput", z.object({}).strict());
function readPolicy(policyId: string) {
return Object.freeze({
policyId,
requestByteLimit: 0,
responseByteLimit: LIST_LIMIT,
totalDeadlineMs: 10_000,
retryBudget: 0 as const,
authProfileId: "ANONYMOUS",
diagnosticsOperation: "envelope.read",
});
}
const LIST_CONTRACT = Object.freeze({
contract: Object.freeze({
operationId: "ENVELOPE_LIST_ITEMS",
method: "GET" as const,
pathTemplate: "/api/envelope-items",
inputValidator: noInput,
outputValidator: zodValidator(
"EnvelopeTestItemList",
z.array(itemSchema).max(100),
),
problemValidator,
acceptedStatuses: Object.freeze([200]),
emptyBodyStatuses: Object.freeze([]),
retrySemantics: "SAFE" as const,
requestBody: "NONE" as const,
responseBody: "REQUIRED_JSON" as const,
responseEnvelope: "ENVELOPE_V1" as const,
commandRecovery: null,
commandEffect: null,
projectRequest: () =>
Object.freeze({
pathValues: Object.freeze({}),
queryEntries: Object.freeze([]),
body: null,
}),
}),
frontend: readPolicy("ENVELOPE_LIST_V1"),
}) satisfies InstalledHttpContract<
Readonly<Record<never, never>>,
readonly z.output<typeof itemSchema>[],
EnvelopeProblem
>;
/** A success whose `data` is null: the backend sends no `data` key. */
const ARCHIVE_CONTRACT = Object.freeze({
contract: Object.freeze({
...LIST_CONTRACT.contract,
operationId: "ENVELOPE_ARCHIVE_ITEMS",
method: "POST" as const,
pathTemplate: "/api/envelope-items/archive",
outputValidator: zodValidator("EnvelopeTestNull", z.null()),
retrySemantics: "KEYED" as const,
requestBody: "JSON" 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,
}) satisfies CommandEffectDescriptor<EnvelopeProblem>,
}),
frontend: Object.freeze({
...readPolicy("ENVELOPE_ARCHIVE_V1"),
requestByteLimit: 1_024,
diagnosticsOperation: "envelope.archive",
}),
}) satisfies InstalledHttpContract<
Readonly<Record<never, never>>,
null,
EnvelopeProblem
>;
/**
* The most conservative package classifier: every problem may have applied.
* What the V3 run then says NOT_APPLIED comes from the backend's own
* operation-independent refusals.
*/
const CREATE_CONTRACT = Object.freeze({
contract: Object.freeze({
...ARCHIVE_CONTRACT.contract,
operationId: "ENVELOPE_CREATE_ITEM",
pathTemplate: "/api/envelope-items",
outputValidator: zodValidator("EnvelopeTestItem", itemSchema),
acceptedStatuses: Object.freeze([201]),
}),
frontend: Object.freeze({
...ARCHIVE_CONTRACT.frontend,
policyId: "ENVELOPE_CREATE_V1",
diagnosticsOperation: "envelope.create",
}),
}) satisfies InstalledHttpContract<
Readonly<Record<never, never>>,
z.output<typeof itemSchema>,
EnvelopeProblem
>;
/** A package that reads every 409 as a domain conflict refused untouched. */
const CREATE_CONFLICT_NOT_APPLIED_CONTRACT = Object.freeze({
...CREATE_CONTRACT,
contract: Object.freeze({
...CREATE_CONTRACT.contract,
commandEffect: Object.freeze({
successEffect: "APPLIED_CONFIRMED" as const,
classifyProblem: ({ status }: Readonly<{ status: number }>) =>
status === 409 || status === 503 ? "NOT_APPLIED" : "MAYBE_APPLIED",
}) satisfies CommandEffectDescriptor<EnvelopeProblem>,
}),
});
const OPERATIONS = Object.freeze({
ENVELOPE_LIST_ITEMS: defineFeatureHttpOperation({
contract: LIST_CONTRACT,
routeId: "ENVELOPE_ROUTE",
mapSuccess: (value) => mappingSuccess(value),
}),
ENVELOPE_ARCHIVE_ITEMS: defineFeatureHttpOperation({
contract: ARCHIVE_CONTRACT,
routeId: "ENVELOPE_ROUTE",
mapSuccess: (value) => mappingSuccess(value),
}),
ENVELOPE_CREATE_ITEM: defineFeatureHttpOperation({
contract: CREATE_CONTRACT,
routeId: "ENVELOPE_ROUTE",
mapSuccess: (value) => mappingSuccess(value),
}),
});
const CONFLICT_OPERATIONS = Object.freeze({
ENVELOPE_CREATE_ITEM: defineFeatureHttpOperation({
contract: CREATE_CONFLICT_NOT_APPLIED_CONTRACT,
routeId: "ENVELOPE_ROUTE",
mapSuccess: (value) => mappingSuccess(value),
}),
});
const META = Object.freeze({
requestId: "req-1",
traceId: "0af7651916cd43dd8448eb211c80319c",
correlationId: "corr-1",
});
function success(data: JsonBodyType, meta: JsonBodyType = META) {
return { success: true, ...(data === null ? {} : { data }), meta };
}
function failure(
code: string,
category: string,
retryable: boolean,
details?: JsonBodyType,
) {
return {
success: false,
error: {
code,
category,
message: "서버가 보낸 문구",
retryable,
...(details === undefined ? {} : { details }),
},
meta: META,
};
}
const server = setupServer();
beforeAll(() => server.listen({ onUnhandledRequest: "error" }));
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
function answer(
method: "get" | "post",
path: string,
body: JsonBodyType,
init: Readonly<{ status?: number; headers?: Record<string, string> }> = {},
) {
server.use(
http[method](`${BASE_URL}${path}`, () =>
HttpResponse.json(body, {
status: init.status ?? 200,
...(init.headers === undefined ? {} : { headers: init.headers }),
}),
),
);
}
function scope() {
return Object.freeze({
generation: 1,
fingerprint: "envelope-scope",
identities: Object.freeze({}) as never,
signal: new AbortController().signal,
isCurrent: () => true,
});
}
function v3Executor(fetcher?: typeof fetch): InstalledHttpOperationExecutor {
const executor = createContractHttpExecutor({
baseUrl: BASE_URL,
...(fetcher === undefined ? {} : { fetcher }),
maxRetryAttempts: 0,
attachCredentials: () => ({ kind: "READY" as const, headers: {} }),
random: () => 0,
});
return Object.freeze({
execute(contract, input, context) {
return executor.execute(contract, input, {
routeId: context.routeId,
scope: scope(),
...(context.intent === undefined ? {} : { intent: context.intent }),
});
},
});
}
function v3(fetcher?: typeof fetch) {
return createFeatureHttpBinding(v3Executor(fetcher), OPERATIONS);
}
const KEY = "envelope-key-1";
function intent(operationId: string) {
return Object.freeze({
intentId: `intent-${operationId}`,
operationId,
canonicalInputIdentity: "{}",
idempotencyKey: KEY,
createdAtMonotonicMs: 0,
});
}
/** The same paths as V2 rows; V2 always reads the Envelope. */
const V2_OPERATIONS = Object.freeze({
ENVELOPE_LIST_ITEMS: Object.freeze({
method: "GET",
path: "/api/envelope-items",
operationId: "ENVELOPE_LIST_ITEMS",
auth: "external-session",
timeoutMs: null,
idempotency: "safe",
retry: "runtime",
requestSource: "none",
requestSchema: "EnvelopeTestNoInput",
responseSchema: "EnvelopeTestItemList",
maxResponseBytes: LIST_LIMIT,
owner: "test-fixture",
}),
ENVELOPE_CREATE_ITEM: Object.freeze({
method: "POST",
path: "/api/envelope-items",
operationId: "ENVELOPE_CREATE_ITEM",
auth: "external-session",
timeoutMs: null,
idempotency: "keyed",
retry: "never",
requestSource: "body",
requestSchema: "EnvelopeTestNoInput",
responseSchema: "EnvelopeTestItem",
successStatuses: [201],
maxResponseBytes: LIST_LIMIT,
owner: "test-fixture",
}),
});
const V2_PAYLOADS: Readonly<Record<string, z.ZodType>> = Object.freeze({
EnvelopeTestItemList: z.array(itemSchema).max(100),
EnvelopeTestItem: itemSchema,
});
function v2(fetcher?: typeof fetch) {
return createHttpClient({
baseUrl: BASE_URL,
...(fetcher === undefined ? {} : { fetcher }),
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 {
kind: error.kind,
code: error.code,
httpStatus: error.httpStatus,
effect:
error.effect === undefined || error.effect === "NOT_APPLICABLE"
? "MAYBE_APPLIED"
: error.effect,
retryAfterMs: error.retryAfterMs,
validationIssues: error.validationIssues,
};
}
async function v2CreateFailure(): Promise<AppFailure> {
const result = await v2().execute("ENVELOPE_CREATE_ITEM", {
body: {},
idempotencyKey: KEY,
});
if (result.ok) throw new Error("V2 create unexpectedly succeeded");
return result.error;
}
async function v3CreateFailure(
binding: Pick<ReturnType<typeof v3>, "execute"> = v3(),
): Promise<AppFailure> {
const result = await binding.execute(
"ENVELOPE_CREATE_ITEM",
Object.freeze({}),
{ intent: intent("ENVELOPE_CREATE_ITEM") },
);
if (result.ok) throw new Error("V3 create unexpectedly succeeded");
return result.error;
}
describe("V3 operation that reads the paired backend's Envelope", () => {
it("reads the success data and ignores meta keys it does not know", async () => {
answer(
"get",
"/api/envelope-items",
success([{ id: "item-1", name: "First" }], {
...META,
page: { number: 0, size: 20, total: 1, sort: null },
}),
);
await expect(
v3().execute("ENVELOPE_LIST_ITEMS", Object.freeze({})),
).resolves.toEqual({
ok: true,
value: [{ id: "item-1", name: "First" }],
});
});
it("reads keys the backend dropped as null: a DTO field, the meta ids and the data", async () => {
answer("get", "/api/envelope-items", success([{ id: "item-1", name: "First" }], {}));
await expect(
v3().execute("ENVELOPE_LIST_ITEMS", Object.freeze({})),
).resolves.toEqual({ ok: true, value: [{ id: "item-1", name: "First" }] });
answer("post", "/api/envelope-items/archive", success(null));
await expect(
v3().execute("ENVELOPE_ARCHIVE_ITEMS", Object.freeze({}), {
intent: intent("ENVELOPE_ARCHIVE_ITEMS"),
}),
).resolves.toEqual({ ok: true, value: null });
});
it("reads the failure error's code and keeps the backend message out", async () => {
answer("get", "/api/envelope-items", failure("NOT_FOUND", "NOT_FOUND", false), {
status: 404,
});
const result = await v3().execute(
"ENVELOPE_LIST_ITEMS",
Object.freeze({}),
);
expect(result).toMatchObject({
ok: false,
error: { kind: "NOT_FOUND", code: "NOT_FOUND", httpStatus: 404 },
});
expect(JSON.stringify(result)).not.toContain("서버가 보낸 문구");
});
it.each([
["a bare DTO", [{ id: "item-1", name: "First" }]],
["a failure Envelope", failure("NOT_FOUND", "NOT_FOUND", false)],
["a success Envelope that also carries error", { ...success([]), error: { code: "X" } }],
])("rejects %s on a success status as an Envelope mismatch", async (_label, body) => {
answer("get", "/api/envelope-items", body as JsonBodyType);
await expect(
v3().execute("ENVELOPE_LIST_ITEMS", Object.freeze({})),
).resolves.toMatchObject({
ok: false,
error: { kind: "ENVELOPE_MISMATCH", code: "ENVELOPE_MISMATCH" },
});
});
it("counts the whole Envelope against the byte limit, as V2 counts maxResponseBytes", 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 }];
expect(JSON.stringify(data).length).toBeLessThan(LIST_LIMIT);
expect(JSON.stringify(success(data)).length).toBeGreaterThan(LIST_LIMIT);
// A native Response, as http-execution-contract.test.ts uses: MSW never
// 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" } });
});
it("applies the structure budget to the whole Envelope, not only data", async () => {
let deep: JsonBodyType = "leaf";
for (let depth = 0; depth < 70; depth += 1) deep = { nested: deep };
answer("get", "/api/envelope-items", success([], { ...META, deep }));
await expect(
v3().execute("ENVELOPE_LIST_ITEMS", Object.freeze({})),
).resolves.toMatchObject({
ok: false,
error: { kind: "RESPONSE_BODY_LIMIT", code: "RESPONSE_TOO_LARGE" },
});
});
});
describe("V3 Envelope verdicts equal the V2 client's for the same answer", () => {
const cases: readonly (readonly [
string,
Readonly<{ status: number; body: JsonBodyType; headers?: Record<string, string> }>,
])[] = [
[
"409 IDEMPOTENT_IN_FLIGHT",
{
status: 409,
body: failure("IDEMPOTENT_IN_FLIGHT", "CONFLICT", true),
headers: { "Retry-After": "2" },
},
],
[
"422 IDEMPOTENT_REQUEST_MISMATCH",
{ status: 422, body: failure("IDEMPOTENT_REQUEST_MISMATCH", "VALIDATION", false) },
],
[
"400 IDEMPOTENCY_KEY_INVALID",
{
status: 400,
body: failure("IDEMPOTENCY_KEY_INVALID", "VALIDATION", false, {
reason: "MALFORMED",
}),
},
],
[
"503 IDEMPOTENCY_UNAVAILABLE",
{
status: 503,
body: failure("IDEMPOTENCY_UNAVAILABLE", "TRANSIENT_DEPENDENCY", true),
},
],
[
"400 VALIDATION_FAILED with the field list",
{
status: 400,
body: failure("VALIDATION_FAILED", "VALIDATION", false, [
{ field: "name", code: "NOT_BLANK", message: "비어 있으면 안 됩니다" },
]),
},
],
[
"400 VALIDATION_FAILED without a field list",
{
status: 400,
body: failure("VALIDATION_FAILED", "VALIDATION", false, {
cause: "JsonParseException",
}),
},
],
[
"409 domain conflict",
{ status: 409, body: failure("RESOURCE_CONFLICT", "CONFLICT", false) },
],
];
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({
kind: "CONFLICT",
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({
kind: "VALIDATION_REJECTED",
effect: "NOT_APPLIED",
validationIssues: [{ path: "name", code: "NOT_BLANK" }],
});
});
it("keeps an in-flight 409 and an idempotency 503 uncertain even when the package calls them not applied", async () => {
const conflict = createFeatureHttpBinding(v3Executor(), CONFLICT_OPERATIONS);
answer(
"post",
"/api/envelope-items",
failure("IDEMPOTENT_IN_FLIGHT", "CONFLICT", true),
{ status: 409, headers: { "Retry-After": "2" } },
);
await expect(v3CreateFailure(conflict)).resolves.toMatchObject({
effect: "MAYBE_APPLIED",
});
answer(
"post",
"/api/envelope-items",
failure("IDEMPOTENCY_UNAVAILABLE", "TRANSIENT_DEPENDENCY", true),
{ status: 503 },
);
await expect(v3CreateFailure(conflict)).resolves.toMatchObject({
effect: "MAYBE_APPLIED",
});
// A domain 409 is the package's to classify.
answer("post", "/api/envelope-items", failure("RESOURCE_CONFLICT", "CONFLICT", false), {
status: 409,
});
await expect(v3CreateFailure(conflict)).resolves.toMatchObject({
effect: "NOT_APPLIED",
});
});
});
describe("shared MSW scenarios for an Envelope operation", () => {
it.each([
["success", { ok: true, value: [{ id: "item-1", name: "First" }] }],
["empty", { ok: true, value: [] }],
["not-found-404", { ok: false, error: { kind: "NOT_FOUND", code: "NOT_FOUND" } }],
[
"server-terminal-503",
{ ok: false, error: { kind: "SERVER_FAILURE", code: "SERVER_FAILURE" } },
],
[
"envelope-mismatch",
{ ok: false, error: { kind: "ENVELOPE_MISMATCH", code: "ENVELOPE_MISMATCH" } },
],
[
"schema-mismatch",
{ ok: false, error: { kind: "SCHEMA_MISMATCH", code: "SUCCESS_SCHEMA_INVALID" } },
],
] as const)("answers %s in the backend's frame", async (scenario, expected) => {
server.use(
createHttpScenarioHandler(LIST_CONTRACT, {
scenario,
payload: [{ id: "item-1", name: "First" }],
}),
);
await expect(
v3().execute("ENVELOPE_LIST_ITEMS", Object.freeze({})),
).resolves.toMatchObject(expected);
});
});
describe("Envelope declaration at composition", () => {
function contribution(responseEnvelope: unknown) {
return Object.freeze({
contributionId: "envelope-test-http-v1",
featureId: "envelope-test",
source: TEST_CONTRACT_CONTRIBUTION.source,
http: Object.freeze([
Object.freeze({
...LIST_CONTRACT,
contract: Object.freeze({ ...LIST_CONTRACT.contract, responseEnvelope }),
}),
]) as never,
events: Object.freeze([]),
});
}
it("installs an operation that declares the Envelope and keeps the declaration", () => {
const composed = composeContractContributions([contribution("ENVELOPE_V1")]);
expect(
composed.httpByOperationId.get("ENVELOPE_LIST_ITEMS")?.contract.responseEnvelope,
).toBe("ENVELOPE_V1");
});
it("refuses a framing it does not know", () => {
expect(() => composeContractContributions([contribution("PROBLEM_JSON")])).toThrow(
expect.objectContaining({ reason: "envelope-test/ENVELOPE_LIST_ITEMS: responseEnvelope" }),
);
});
});
+51 -6
View File
@@ -11,7 +11,10 @@ import {
* 16-02. One MSW handler that answers an installed HTTP operation with one
* catalog scenario. The route, the success status and the response ceiling
* come from the operation's own descriptor, so a feature test passes its
* contract and needs no catalog entry:
* contract and needs no catalog entry. An operation that declares
* `responseEnvelope: "ENVELOPE_V1"` is answered the way the paired backend
* answers (clean-architecture-backend-template docs/web/http-contract.md §1):
* every JSON body is an Envelope and a null field is dropped with its key.
*
* server.use(createHttpScenarioHandler(LIST_X_CONTRACT, {
* scenario: "server-terminal-503", payload: [...],
@@ -58,8 +61,15 @@ async function scenarioResponse(
scenario: HttpScenarioId,
payload: JsonBodyType,
attempt: number,
{ ceiling, successStatus }: ReturnType<typeof httpScenarioOperationFacts>,
{
ceiling,
successStatus,
enveloped,
}: ReturnType<typeof httpScenarioOperationFacts>,
) {
const body = (data: JsonBodyType) => (enveloped ? successEnvelope(data) : data);
const problem = (status: number, code: string) =>
enveloped ? failureEnvelope(status, code) : problemDetails(status, code);
if (scenario === "slow") await delay(50);
if (scenario === "timeout" || scenario === "aborted") {
await delay("infinite");
@@ -78,10 +88,15 @@ async function scenarioResponse(
});
}
if (scenario === "envelope-mismatch") {
return HttpResponse.json({ data: payload }, { status: successStatus });
// The frame the operation does not read: a bare DTO for an Envelope one.
return HttpResponse.json(enveloped ? payload : { data: payload }, {
status: successStatus,
});
}
if (scenario === "schema-mismatch") {
return HttpResponse.json({ unexpected: true }, { status: successStatus });
return HttpResponse.json(body({ unexpected: true }), {
status: successStatus,
});
}
if (scenario === "unauthenticated-401") {
return HttpResponse.json(problem(401, "AUTH_REQUIRED"), { status: 401 });
@@ -137,10 +152,10 @@ async function scenarioResponse(
},
);
}
return HttpResponse.json(payload, { status: successStatus });
return HttpResponse.json(body(payload), { status: successStatus });
}
function problem(status: number, code: string) {
function problemDetails(status: number, code: string) {
return Object.freeze({
type: `https://api.test/problems/${code.toLowerCase()}`,
title: code,
@@ -148,3 +163,33 @@ function problem(status: number, code: string) {
code,
});
}
const ENVELOPE_META = Object.freeze({
requestId: "scenario-request",
traceId: "0af7651916cd43dd8448eb211c80319c",
});
function successEnvelope(data: JsonBodyType) {
return Object.freeze({
success: true,
...(data === null ? {} : { data }),
meta: ENVELOPE_META,
});
}
/**
* Every key the backend always sends. The frontend reads only `code` and
* `details`; `category`, `message` and `retryable` are never branched on.
*/
function failureEnvelope(status: number, code: string) {
return Object.freeze({
success: false,
error: Object.freeze({
code,
category: "SCENARIO",
message: "scenario message",
retryable: status >= 500 || code === "IDEMPOTENT_IN_FLIGHT",
}),
meta: ENVELOPE_META,
});
}
+6 -1
View File
@@ -74,7 +74,11 @@ export type HttpScenarioContract = Readonly<{
contract: Readonly<
Pick<
InstalledHttpContract<unknown, unknown, unknown>["contract"],
"operationId" | "method" | "pathTemplate" | "acceptedStatuses"
| "operationId"
| "method"
| "pathTemplate"
| "acceptedStatuses"
| "responseEnvelope"
> & { commandEffect: unknown }
>;
frontend: Readonly<{ responseByteLimit: number }>;
@@ -132,6 +136,7 @@ export function httpScenarioOperationFacts(installed: HttpScenarioContract) {
command: installed.contract.commandEffect !== null,
ceiling: installed.frontend.responseByteLimit,
successStatus: installed.contract.acceptedStatuses[0]!,
enveloped: installed.contract.responseEnvelope === "ENVELOPE_V1",
});
}
+16
View File
@@ -139,6 +139,22 @@ describe("create:feature rendering", () => {
expect(contract).not.toContain("PLACEHOLDER");
expect(digest).not.toBe(PLACEHOLDER_CONTRACT_PACKAGE_DIGEST);
});
// 1101 README 14.3. test:feature-scaffold runs the gateway test this renders.
it("reads the paired backend's Envelope and tests it with the backend's own bodies", () => {
const { files } = plan({ id: "invoice-feature" });
const contracts = "src/features/invoice-feature/contracts";
expect(files.get(`${contracts}/invoice-contract-contribution.ts`)).toContain(
'responseEnvelope: "ENVELOPE_V1" as const,',
);
expect(files.get(`${contracts}/invoice-schemas.ts`)).toMatch(
/invoiceProblemSchema = z\s*\.object\(\{\s*code: z\.string\(\)\.regex/u,
);
expect(
files.get("tests/features/invoice-feature/invoice-http-gateway.test.ts"),
).toContain('success: true, data: [{ id: "item-1", name: "First item" }]');
});
});
describe("create:feature refusals", () => {