diff --git a/.dependency-cruiser.json b/.dependency-cruiser.json index ea20ba8..f3ffd9d 100644 --- a/.dependency-cruiser.json +++ b/.dependency-cruiser.json @@ -191,6 +191,19 @@ "pathNot": "^src/adapters/($1/|platform/|browser-file-storage/result\\.ts$|cross-context-invalidation/index\\.ts$)" } }, + { + "name": "adapter-groups-are-reached-through-their-barrel", + "comment": "어댑터 그룹의 공개 표면은 그 그룹의 index.ts다. 그룹 바깥(bootstrap, features, presentation)은 배럴만 import한다. 배럴이 없던 시절 bootstrap은 어댑터 내부 파일 15곳을 직접 겨눴고, 그래서 어떤 파일이 공개이고 어떤 파일이 내부 헬퍼인지 아무 데도 적혀 있지 않았다. 출발점에서 src/adapters를 뺀 이유는 어댑터끼리의 간선은 바로 위 adapters-do-not-know-other-concrete-adapters가 이미 담당하고, 커널(platform/**)은 파일 단위로 공유되기 때문이다 — scripts/check-adapter-inventory.ts가 네 소비자에게 platform/abortable-operation.ts로 해석되는 specifier를 직접 요구한다. 도착점에서 1단계 중첩 index.ts를 허용한 이유는 storage/indexeddb와 storage/opfs가 각자 독립적으로 제거 가능한 런타임이고(scripts/test-browser-file-storage-runtime-removal.ts), 그래서 각자의 배럴이 곧 경계이기 때문이다.", + "severity": "error", + "from": { + "path": "^src/", + "pathNot": "^src/adapters/" + }, + "to": { + "path": "^src/adapters/[^/]+/", + "pathNot": "^src/adapters/[^/]+/index\\.ts$|^src/adapters/[^/]+/[^/]+/index\\.ts$" + } + }, { "name": "no-circular-dependencies", "severity": "error", diff --git a/.storybook/preview.tsx b/.storybook/preview.tsx index 3dca769..2d0e868 100644 --- a/.storybook/preview.tsx +++ b/.storybook/preview.tsx @@ -2,8 +2,8 @@ import type { Preview } from "@storybook/react-vite"; import { QueryClientProvider } from "@tanstack/react-query"; import { MemoryRouter } from "react-router-dom"; -import { createAnonymousSessionAdapter } from "../src/adapters/auth/external-session-adapter.ts"; -import { createQueryClient } from "../src/adapters/query-cache/tanstack-query-cache.ts"; +import { createAnonymousSessionAdapter } from "../src/adapters/auth/index.ts"; +import { createQueryClient } from "../src/adapters/query-cache/index.ts"; import { createApplication } from "../src/application/create-application.ts"; import { LocaleProvider } from "../src/presentation/i18n/index.ts"; import { ApplicationProvider } from "../src/presentation/providers/application-provider.tsx"; diff --git a/README.md b/README.md index ff96f28..af69d01 100644 --- a/README.md +++ b/README.md @@ -132,16 +132,22 @@ hand-written: ## Architecture +This repository is a **Frontend Application Foundation**: a starter/composition +skeleton plus a reusable capability platform. Platform capabilities stay +horizontal while product business features use vertical slices. + Dependencies point inward: ```text presentation -> application -> domain adapters -----^ bootstrap composes concrete adapters -contracts own cross-cutting registries +feature use case -> feature port <- feature-owned capability binding ``` -See `docs/architecture/overview.md`, `docs/architecture/layers.md`, and +See +`docs/architecture/frontend-application-foundation.md`, +`docs/architecture/overview.md`, `docs/architecture/layers.md`, and `docs/architecture/starter-experience.md`. TechLog is one feature boundary under `src/features/tech-log`. Its immutable Public catalog and session-scoped Studio mock gateway are injected through the application feature input; @@ -190,6 +196,7 @@ corepack pnpm check:types:node corepack pnpm check:types:test corepack pnpm check:architecture corepack pnpm test:all +corepack pnpm test:contract corepack pnpm test:e2e corepack pnpm test:a11y corepack pnpm build @@ -205,6 +212,11 @@ corepack pnpm exec playwright test tests/e2e/tech-log-public-discovery.spec.ts t corepack pnpm test:visual ``` +`test:all` is the ordinary product-development loop and intentionally excludes +host-level CI-runner assurance. Run `corepack pnpm test:system` only on the +compatible Linux assurance host described in +[`docs/testing/taxonomy.md`](docs/testing/taxonomy.md). + `check:types`는 source, Node scripts/config와 tests를 분리된 TypeScript project로 모두 검사한다. type/architecture/security/registry의 invalid fixture는 `config/ci/gates.json`에서 “실패해야 통과”하는 negative gate로 @@ -251,7 +263,7 @@ Live release verification additionally requires `HOSTING_BASE_URL`. ## CI and evidence -The 26-gate registry is `config/ci/gates.json`; the Gitea workflow is +The 27-gate registry is `config/ci/gates.json`; the Gitea workflow is `.gitea/workflows/quality-gates.yml`. It follows: ```text diff --git a/config/ci/gates.json b/config/ci/gates.json index 814bf30..934f074 100644 --- a/config/ci/gates.json +++ b/config/ci/gates.json @@ -81,6 +81,55 @@ "script": "check:types:fixture:reference-operation", "expect": "fail", "expectedExitCode": 1, + "expectedDiagnosticId": "error TS2741:" + }, + { + "id": "check-types-fixture-http-operation-input", + "script": "check:types:fixture:http-operation-input", + "expect": "fail", + "expectedExitCode": 1, + "expectedDiagnosticId": "error TS2353:" + }, + { + "id": "check-types-fixture-http-wire-mapper", + "script": "check:types:fixture:http-wire-mapper", + "expect": "fail", + "expectedExitCode": 1, + "expectedDiagnosticId": "error TS2322:" + }, + { + "id": "check-types-fixture-http-operation-id", + "script": "check:types:fixture:http-operation-id", + "expect": "fail", + "expectedExitCode": 1, + "expectedDiagnosticId": "error TS2345:" + }, + { + "id": "check-types-fixture-http-route-id", + "script": "check:types:fixture:http-route-id", + "expect": "fail", + "expectedExitCode": 1, + "expectedDiagnosticId": "error TS2322:" + }, + { + "id": "check-types-fixture-feature-contribution-input", + "script": "check:types:fixture:feature-contribution-input", + "expect": "fail", + "expectedExitCode": 1, + "expectedDiagnosticId": "error TS2322:" + }, + { + "id": "check-types-fixture-feature-capability-selection", + "script": "check:types:fixture:feature-capability-selection", + "expect": "fail", + "expectedExitCode": 1, + "expectedDiagnosticId": "error TS2339:" + }, + { + "id": "check-types-fixture-direct-feature-composition", + "script": "check:types:fixture:direct-feature-composition", + "expect": "fail", + "expectedExitCode": 1, "expectedDiagnosticId": "error TS2345:" }, { @@ -95,7 +144,7 @@ "script": "check:types:fixture:route-runtime", "expect": "fail", "expectedExitCode": 1, - "expectedDiagnosticId": "error TS2353:" + "expectedDiagnosticId": "error TS2740:" }, { "id": "check-types-fixture-page-action", @@ -142,6 +191,11 @@ "script": "test:unit", "expect": "pass" }, + { + "id": "test-contract", + "script": "test:contract", + "expect": "pass" + }, { "id": "test-coverage", "script": "test:coverage", @@ -164,6 +218,11 @@ "script": "test:integration", "expect": "pass" }, + { + "id": "test-system", + "script": "test:system", + "expect": "pass" + }, { "id": "test-http-scenario-evidence", "script": "test:http-scenario-evidence", @@ -809,6 +868,15 @@ "test-unit" ] }, + { + "id": "artifact-artifacts-tests-contract-xml", + "path": "artifacts/tests/contract.xml", + "schemaId": "junit", + "production": "command-generated", + "producerCommandIds": [ + "test-contract" + ] + }, { "id": "artifact-artifacts-tests-coverage-xml", "path": "artifacts/tests/coverage.xml", @@ -875,6 +943,15 @@ "test-integration" ] }, + { + "id": "artifact-artifacts-tests-system-xml", + "path": "artifacts/tests/system.xml", + "schemaId": "junit", + "production": "command-generated", + "producerCommandIds": [ + "test-system" + ] + }, { "id": "artifact-artifacts-tests-http-scenario-executions-json", "path": "artifacts/tests/http-scenario-executions.json", @@ -1862,6 +1939,13 @@ "check-types-fixture-feature-input", "check-types-fixture-failure-kind", "check-types-fixture-reference-operation", + "check-types-fixture-http-operation-input", + "check-types-fixture-http-wire-mapper", + "check-types-fixture-http-operation-id", + "check-types-fixture-http-route-id", + "check-types-fixture-feature-contribution-input", + "check-types-fixture-feature-capability-selection", + "check-types-fixture-direct-feature-composition", "check-types-fixture-async-overlay", "check-types-fixture-route-runtime", "check-types-fixture-page-action", @@ -1893,12 +1977,14 @@ "name": "unit", "commandIds": [ "test-unit", + "test-contract", "test-coverage", "check-coverage-fixture" ], "logArtifactId": "artifact-artifacts-quality-gates-FE-GATE-005-txt", "evidenceArtifactIds": [ "artifact-artifacts-tests-unit-xml", + "artifact-artifacts-tests-contract-xml", "artifact-artifacts-tests-coverage-xml", "artifact-artifacts-tests-coverage-coverage-summary-json", "artifact-artifacts-quality-risk-coverage-json", @@ -2098,6 +2184,7 @@ "id": "FE-GATE-013", "name": "security", "commandIds": [ + "test-system", "verify-reproducible-build", "build-release-candidate", "verify-local-evidence", @@ -2108,6 +2195,7 @@ ], "logArtifactId": "artifact-artifacts-quality-gates-FE-GATE-013-txt", "evidenceArtifactIds": [ + "artifact-artifacts-tests-system-xml", "artifact-artifacts-security-scan-sarif", "artifact-artifacts-release-dependency-inventory-json", "artifact-artifacts-release-sbom-cdx-json", diff --git a/config/testing/risk-coverage.json b/config/testing/risk-coverage.json index e2ef978..11cbb03 100644 --- a/config/testing/risk-coverage.json +++ b/config/testing/risk-coverage.json @@ -12,97 +12,192 @@ { "path": "src/adapters/http/bounded-body-reader.ts", "owner": "http-runtime", - "minimum": { "lines": 95, "statements": 95, "functions": 95, "branches": 90 } + "minimum": { + "lines": 95, + "statements": 95, + "functions": 95, + "branches": 90 + } }, { "path": "src/adapters/http/bounded-json.ts", "owner": "http-runtime", - "minimum": { "lines": 85, "statements": 84, "functions": 95, "branches": 78 } + "minimum": { + "lines": 85, + "statements": 84, + "functions": 95, + "branches": 78 + } }, { "path": "src/adapters/http/http-execution-v3.ts", "owner": "http-runtime", - "minimum": { "lines": 75, "statements": 73, "functions": 70, "branches": 52 } + "minimum": { + "lines": 75, + "statements": 73, + "functions": 70, + "branches": 52 + } }, { "path": "src/adapters/http/request-builder.ts", "owner": "http-runtime", - "minimum": { "lines": 85, "statements": 85, "functions": 95, "branches": 82 } + "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 } + "minimum": { + "lines": 80, + "statements": 78, + "functions": 95, + "branches": 78 + } }, { "path": "src/adapters/query-cache/server-state-scope-runtime.ts", "owner": "server-state-runtime", - "minimum": { "lines": 85, "statements": 85, "functions": 85, "branches": 75 } + "minimum": { + "lines": 85, + "statements": 85, + "functions": 85, + "branches": 75 + } }, { "path": "src/adapters/service-worker/service-worker-lifecycle.ts", "owner": "service-worker-runtime", - "minimum": { "lines": 64, "statements": 60, "functions": 65, "branches": 43 } + "minimum": { + "lines": 64, + "statements": 60, + "functions": 65, + "branches": 43 + } }, { "path": "src/adapters/storage/browser-storage-adapter.ts", "owner": "storage-runtime", - "minimum": { "lines": 60, "statements": 60, "functions": 70, "branches": 60 } + "minimum": { + "lines": 60, + "statements": 60, + "functions": 70, + "branches": 60 + } }, { "path": "src/adapters/telemetry/best-effort-telemetry.ts", "owner": "telemetry-runtime", - "minimum": { "lines": 85, "statements": 85, "functions": 70, "branches": 75 } + "minimum": { + "lines": 85, + "statements": 85, + "functions": 70, + "branches": 75 + } }, { "path": "src/application/create-application.ts", "owner": "application-runtime", - "minimum": { "lines": 90, "statements": 90, "functions": 80, "branches": 68 } + "minimum": { + "lines": 90, + "statements": 90, + "functions": 80, + "branches": 68 + } }, { - "path": "src/application/policies/compatibility.ts", - "owner": "application-policy", - "minimum": { "lines": 95, "statements": 95, "functions": 95, "branches": 75 } + "path": "src/contracts/compatibility.ts", + "owner": "compatibility-contracts", + "minimum": { + "lines": 95, + "statements": 95, + "functions": 95, + "branches": 75 + } }, { "path": "src/application/policies/performance-budgets.ts", "owner": "application-policy", - "minimum": { "lines": 80, "statements": 80, "functions": 80, "branches": 40 } + "minimum": { + "lines": 80, + "statements": 80, + "functions": 80, + "branches": 40 + } }, { "path": "src/application/policies/promotion-readiness.ts", "owner": "release-runtime", - "minimum": { "lines": 95, "statements": 95, "functions": 95, "branches": 95 } + "minimum": { + "lines": 95, + "statements": 95, + "functions": 95, + "branches": 95 + } }, { "path": "src/application/use-cases/decide-chunk-recovery.ts", "owner": "application-runtime", - "minimum": { "lines": 90, "statements": 90, "functions": 95, "branches": 85 } + "minimum": { + "lines": 90, + "statements": 90, + "functions": 95, + "branches": 85 + } }, { "path": "src/bootstrap/load-release-manifest.ts", "owner": "release-runtime", - "minimum": { "lines": 90, "statements": 90, "functions": 90, "branches": 80 } + "minimum": { + "lines": 90, + "statements": 90, + "functions": 90, + "branches": 80 + } }, { "path": "src/bootstrap/read-bounded-boot-json.ts", "owner": "bootstrap-runtime", - "minimum": { "lines": 71, "statements": 66, "functions": 48, "branches": 57 } + "minimum": { + "lines": 71, + "statements": 66, + "functions": 48, + "branches": 57 + } }, { "path": "src/contracts/diagnostics.ts", "owner": "diagnostics-contracts", - "minimum": { "lines": 68, "statements": 68, "functions": 95, "branches": 58 } + "minimum": { + "lines": 68, + "statements": 68, + "functions": 95, + "branches": 58 + } }, { "path": "src/features/reference-feature/adapters/reference-http-gateway.ts", "owner": "reference-feature", - "minimum": { "lines": 90, "statements": 90, "functions": 90, "branches": 90 } + "minimum": { + "lines": 90, + "statements": 90, + "functions": 90, + "branches": 90 + } }, { "path": "src/presentation/adapters/query/application-query.ts", "owner": "presentation-runtime", - "minimum": { "lines": 90, "statements": 90, "functions": 90, "branches": 80 } + "minimum": { + "lines": 90, + "statements": 90, + "functions": 90, + "branches": 80 + } } ], "highRiskPaths": [ @@ -116,7 +211,7 @@ "src/adapters/storage/browser-storage-adapter.ts", "src/adapters/telemetry/best-effort-telemetry.ts", "src/application/create-application.ts", - "src/application/policies/compatibility.ts", + "src/contracts/compatibility.ts", "src/application/policies/performance-budgets.ts", "src/application/policies/promotion-readiness.ts", "src/application/use-cases/decide-chunk-recovery.ts", diff --git a/docs/architecture/browser-file-and-origin-storage.md b/docs/architecture/browser-file-and-origin-storage.md index 14f7677..e3e787b 100644 --- a/docs/architecture/browser-file-and-origin-storage.md +++ b/docs/architecture/browser-file-and-origin-storage.md @@ -247,6 +247,8 @@ domain, application state, query cache, global store, diagnostics에 넣지 않 ### 3.2 picker baseline과 enhancement - 접근 가능한 ``가 모든 browser의 canonical baseline이다. + baseline adapter는 `input.click()`으로 이 경로를 활성화한다. `showPicker()` + 존재 여부는 portable baseline capability의 판정 기준으로 사용하지 않는다. - `showOpenFilePicker()`와 `showSaveFilePicker()`는 runtime method별 feature detection을 거친 progressive enhancement다. UA sniffing을 사용하지 않는다. - picker 호출은 click/keyboard handler의 첫 browser action이어야 한다. 그 전에 @@ -987,7 +989,7 @@ recipe의 공통 code는 UI/telemetry에 raw DOMException을 노출하지 않기 | `PERMISSION_DENIED` | picker/save permission | baseline/manual fallback | | `LIMIT_EXCEEDED` | count/bytes/page/buffer budget | 입력 축소 | | `POLICY_REJECTED` | type/cache/data policy | 저장·전송 금지 | -| `BLOCKED` | IndexedDB older context | 다른 탭 close/retry UI | +| `BLOCKED` | IndexedDB older context가 live open/upgrade를 막는 중 | 다른 탭 close/retry UI | | `CONFLICT` | revision/generation/idempotency conflict | authoritative re-read | | `MIGRATION_FAILED` | schema/data migration | read-only/online-only | | `QUOTA_EXCEEDED` | actual write failure | rollback, reconstructable GC, bounded retry | @@ -999,6 +1001,12 @@ recipe의 공통 code는 UI/telemetry에 raw DOMException을 노출하지 않기 | `UNAVAILABLE` | browser/worker/storage temporarily unavailable | documented fallback | | `UNSUPPORTED` | capability absence | baseline/online-only | +`IndexedDbConnectionStatus.BLOCKED`는 대기 중인 live attempt의 observable +상태다. blocked deadline이 끝나 `open()`이 `BLOCKED` failure로 settle되면 +그 attempt는 더 이상 열리는 중이 아니므로 status는 +`CLOSED / NOT_OPENED`로 전이한다. 늦게 성공한 native connection은 즉시 닫고 +settled status를 되살리지 않는다. + user dismissal은 failure가 아니라 outcome이다. browser DOMException name은 adapter에서 이 vocabulary로 mapping하고 raw message/stack은 local bounded diagnostic에도 기본 저장하지 않는다. @@ -1085,18 +1093,17 @@ Playwright Chromium, Firefox, WebKit에서 실제 secure-origin API를 검사한 `test:browser-capabilities`의 JUnit을 `verify:browser-capability-evidence`가 읽어 세 engine의 testcase 집합 동일성, 양수 실행 수, zero failure/error/skipped와 skipped/failure node 부재를 강제한다. -현재 checkout의 source suite는 engine마다 정확히 같은 14개 case(File 2, -IndexedDB 4, OPFS/Cache/StorageManager 각 1, cross-context invalidation 2, -presigned streaming download/multipart upload/Image CDN 각 1)를 정의한다. -promotion artifact는 Chromium/Firefox/WebKit의 14개씩, 총 42개가 모두 -실행되어야 한다. 이 host의 -WebKit은 필수 native libraries(예: -`libbacktrace.so.0`, `libevent-2.1.so.7`, `libjxl.so.0.8`, -`libavif.so.16`과 WPE 계열) 부재로 실행되지 않았고 현재 보존 artifact도 -Chromium/Firefox 14개씩 총 28개만 통과한 상태다. 따라서 promotion evidence를 -충족하지 않으며 verifier가 실패하는 것이 정상이다. `INSTALLED` 전에는 필요한 -system dependency가 있는 CI/device에서 세 engine 전체 evidence를 새로 생성해야 -한다. +browser capability promotion은 source suite에서 관찰된 동일 testcase set을 +Chromium/Firefox/WebKit에서 모두 실행하는 규칙으로 관리한다. case 수를 문서 +상수로 복제하지 않고 `verify:browser-capability-evidence`가 Chromium 결과를 +baseline set으로 계산해 Firefox/WebKit의 set 동일성, 양수 실행 수, +failure/error/skipped 0과 failure/skipped node 부재를 검증한다. + +capability absence도 skip 사유가 아니다. 예를 들어 어떤 engine에서 +`navigator.storage`가 없다면 동일 testcase 안에서 adapter의 +`UNSUPPORTED / STORAGE_ESTIMATE / ONLINE_ONLY` 결과를 browser truth로 +검증한다. 세 engine을 실행할 수 없는 host의 artifact는 promotion evidence로 +사용하지 않는다. - native input keyboard/focus/same-file reselection/multiple/dismissal - Chromium conditional picker/save enhancement와 다른 engine fallback diff --git a/docs/architecture/capability-consumer-experience.md b/docs/architecture/capability-consumer-experience.md new file mode 100644 index 0000000..f9f2e82 --- /dev/null +++ b/docs/architecture/capability-consumer-experience.md @@ -0,0 +1,156 @@ +# Capability consumer experience baseline + +Correctness inside a reusable capability is not sufficient. The platform is +also evaluated by how much of that correctness a normal feature developer must +understand. + +These measurements are baselines, not score targets. A lower line count is not +automatically better if it hides business semantics or creates a universal +repository abstraction. + +## Scenario A — reference REST feature + +The existing reference feature is the executable REST consumer. + +It covers list/detail/create behavior, mapping, typed operation inputs, +application ports and an optimistic mutation path. + +Current source size: + +| Feature-owned area | LOC | +| --- | ---: | +| `application/reference-feature-api.ts` | 91 | +| `contracts/reference-mapper.ts` | 109 | +| `adapters/reference-http-gateway.ts` | 65 | +| `adapters/create-reference-feature-input.ts` | 41 | +| Total measured boundary/application source | 306 | + +The important boundary metric is not the raw total. It is what those files need +to know about the platform. + +Current result: + +- HTTP platform imports in the feature adapter layer: 2 files, +- canonical import path used by both: + `src/adapters/http/index.ts`, +- direct imports of `http-execution-v3.ts`, retry scheduler, response reader, + auth admission or effect-certainty internals: 0, +- feature gateway owns transport failure projection: 0, +- feature gateway chooses operation ID, route ID, exact input/value type and + mapper: yes, +- central installed files own feature-specific adapter/runtime wiring: no; + feature-owned contributions are aggregated centrally. + +The reusable HTTP capability now owns execution-outcome normalization through +`createFeatureHttpBinding`. A feature may still implement a custom outbound +adapter behind its application port when the reusable contract does not match +its business requirement. + +## Scenario B — IndexedDB local draft + +The original executable consumer probe remains at: + +`tests/contract/consumer-experience/indexeddb-local-draft.test.ts` + +with its isolated fixture: + +`tests/contract/consumer-experience/fixtures/local-draft-feature.ts` + +The architecture is now also exercised by a real vertical slice under: + +`src/features/local-draft-feature` + +It owns the Local Draft domain/application API and binds an +`IndexedDbRepositoryPort` in its feature adapter. The +cross-capability composition contract lives at: + +`tests/contract/reusable-capability/feature-adapter-composition.test.ts` + +That test composes one HTTP-only contribution and the IndexedDB-only Local Draft +contribution through the same generic catalog path. + +The browser-level composition proof lives at: + +`tests/browser-capabilities/local-draft-composition.spec.ts` + +It runs against native browser IndexedDB. The test creates the platform +`createIndexedDbRuntime`, exposes that runtime through the typed +`createIndexedDbRepositoryProvider`, composes +`LOCAL_DRAFT_FEATURE_ADAPTER_CONTRIBUTION`, then executes Local Draft +save/find/remove through the feature API. The Local Draft feature still does +not import the IndexedDB runtime or native browser API. + +Measured probe result: + +| Metric | Result | +| --- | ---: | +| feature-owned fixture LOC | 97 | +| platform import statements | 1 | +| native IndexedDB API references | 0 | +| `src/adapters/storage/indexeddb/**` imports | 0 | +| runtime-internal IndexedDB types imported by feature | 0 | + +The feature depends only on the public application boundary: + +`src/application/ports/browser-file-storage/index.ts` + +and specifically `IndexedDbRepositoryPort`. + +The contract test rejects feature source that reaches for +`globalThis.indexedDB`, `IDBFactory`, `IDBDatabase`, `IDBTransaction`, +`IDBObjectStore` or the concrete IndexedDB adapter directory. + +## What this does and does not prove + +The contract probe confirms that **feature business code does not need native +IndexedDB knowledge** once an `IndexedDbRepositoryPort` has been composed. +The browser-capability proof additionally confirms that the same feature +contribution works when that port is backed by the repository's real +`createIndexedDbRuntime` and native IndexedDB implementation. + +It does not prove that composition of `createIndexedDbRuntime` is cheap. +That constructor still owns substantial infrastructure policy: + +- dataset scope and storage policy, +- physical store governance, +- retention/idempotency stores, +- schema migrations, +- codec and query policy, +- lifecycle authority, +- durability, scheduling and observation. + +That complexity belongs at the composition/platform boundary, not in the +feature. The Local Draft vertical slice is now the second concrete consumer, and +it confirms that the stable seam is the typed repository provider plus a +feature-owned repository identity. It does **not** show that dataset scope, +retention, migration, codec or lifecycle-authority configuration can be safely +collapsed into one universal `create...Repository` factory. + +A convenience profile should therefore be introduced only after another +IndexedDB-backed product feature repeats the same infrastructure policy, not +merely because two features consume the same repository port. + +## Consumer-quality review checklist + +For each new product feature, record: + +- feature-owned adapter LOC, +- platform glue LOC, +- files changed, +- central catalog edits, +- direct imports from capability-internal modules, +- native browser/network API references, +- duplicated failure/retry/lifecycle policy. + +A healthy feature path should look like: + +1. domain type and invariant, +2. use case, +3. business port, +4. feature-owned mapper/codec and policy, +5. capability-specific binding, +6. presentation controller/page. + +The feature should not need the retry scheduler, abort ownership, +effect-certainty machinery, IndexedDB transaction lifecycle, OPFS journal, +reconnect coordinator or provider process model. diff --git a/docs/architecture/contract-ownership.md b/docs/architecture/contract-ownership.md new file mode 100644 index 0000000..fec11de --- /dev/null +++ b/docs/architecture/contract-ownership.md @@ -0,0 +1,110 @@ +# Contract ownership + +`src/contracts` is not a default destination for every shared-looking type. +A contract belongs there only when the change authority is genuinely shared +across layers, capabilities, build tooling, or runtime composition. + +## Decision rule + +For every proposed contract, ask: + +1. Which requirement can cause this type or policy to change? +2. Is there one clear capability or feature owner? +3. Does another runtime/tooling boundary consume the same semantic contract? +4. Is the contract a wire/artifact authority shared by browser runtime and + build/release tooling? + +The placement rule is: + +- one feature owner -> keep it under that feature, +- one reusable capability owner -> keep it under that adapter/capability and + export it through the capability public entry point, +- multiple independent capability/layer owners -> `src/contracts`, +- browser/build/release wire or artifact authority -> `src/contracts` even + when the browser source graph alone looks small. + +Consumer count alone is not sufficient. Scripts, generated artifacts and +release gates are semantic consumers too. + +## Audit result + +The September 2026 architecture review triggered an import-graph audit of all +39 contract files. + +### Capability-owned contract moved + +`cursor-pagination.ts` had one production owner: +`src/adapters/query-cache/cursor-pagination-runtime.ts`. + +It moved to: + +`src/adapters/query-cache/cursor-pagination-contract.ts` + +and is exported through: + +`src/adapters/query-cache/index.ts` + +Tests use that public capability entry point. Pagination vocabulary no longer +occupies the global contract bucket merely because it is reusable inside one +adapter. + +### Contracts intentionally kept global + +The following examples have multiple semantic owners and remain global: + +- `errors.ts` — application, presentation and several adapters, +- `result.ts` — common success/failure carrier below application, +- `boundary-mapper.ts` — HTTP, browser RPC, realtime and feature registries, +- `mutation-intent.ts` — application, presentation, HTTP, platform and + bootstrap, +- `exact-snapshot.ts` — HTTP, query-cache and browser-transfer, +- `rest-profiles.ts` — auth, HTTP, bootstrap and feature contract validation, +- `query-invalidation.ts` / `query-keys.ts` — query-cache, presentation, + bootstrap and features, +- `cache-invalidation.ts` — cross-context wire protocol plus query + invalidation policy, +- `storage-keys.ts` — browser storage and cross-context invalidation, +- `telemetry.ts` / `diagnostics.ts` — runtime adapters, application and + bootstrap. + +Some contracts appear to have few browser-source consumers but are still shared +authorities: + +- `env.ts` is consumed by bootstrap, runtime-schema/security tests and + registry governance, +- `deployment-admission.ts` is shared by runtime-config generation and release + admission, +- `release-tokens.ts` is shared by runtime coherence tooling and tests, +- `service-worker-static-manifest.ts` is a runtime-neutral canonical format + shared by build generation, validation and service-worker evidence. + +Moving those based only on `src/**` import counts would split one semantic +authority across processes. + +## Feature contracts + +Feature-specific contracts stay inside the vertical slice: + +`features//contracts` + +The reference feature owns routes, schemas, mapper definitions, message +catalogs and contribution identities. Central installed files aggregate those +contributions; they do not own their semantics. + +The message catalog is a deliberate special case: the compiled catalog remains +total even when a feature is build-time disabled so the typed message lookup +does not become partial. The central message file therefore aggregates compiled +message keys rather than treating runtime installation as message ownership. + +## Review rule for future additions + +A new file under `src/contracts` should be rejected during review when all of +the following are true: + +- one feature or one capability is the only semantic owner, +- no build/release/runtime wire authority needs the same definition, +- moving the definition to that owner does not create an inward dependency + violation. + +Do not move a contract merely to reduce the number 39. The goal is explicit +ownership, not a smaller directory. diff --git a/docs/architecture/decisions/VD-11-browser-file-and-origin-storage.md b/docs/architecture/decisions/VD-11-browser-file-and-origin-storage.md index 6c5e8dc..91e2c6f 100644 --- a/docs/architecture/decisions/VD-11-browser-file-and-origin-storage.md +++ b/docs/architecture/decisions/VD-11-browser-file-and-origin-storage.md @@ -189,17 +189,18 @@ chunk별 `CapabilityResult`를 반환한다. backend upload example 실제 upload feature는 이 예시를 그대로 import하지 않고 purpose와 backend protocol에 맞게 contract를 더 좁힌다. -현재 checkout의 browser source suite는 engine마다 같은 14개 case(File 2, -IndexedDB 4, OPFS/Cache/StorageManager 각 1, cross-context invalidation 2, -presigned streaming download/multipart upload/Image CDN 각 1)를 정의한다. -promotion artifact는 Chromium/Firefox/WebKit 각각 14개, 총 42개를 모두 -실행해야 한다. WebKit은 현재 -host의 필수 native libraries(예: -`libbacktrace.so.0`, `libevent-2.1.so.7`, `libjxl.so.0.8`, -`libavif.so.16`과 WPE 계열) 부재로 실행되지 않았다. 보존 artifact는 -Chromium/Firefox 14개씩 총 28개만 통과했으므로 -`verify:browser-capability-evidence`가 실패하는 것이 정상이다. 세 engine -evidence가 완성되기 전에는 product 상태를 `INSTALLED`로 올리지 않는다. +browser capability promotion은 source suite가 정의한 동일 testcase set을 +Chromium/Firefox/WebKit에서 모두 실행해야 한다. 구체적인 case 개수는 이 결정 +문서에 고정하지 않는다. `verify:browser-capability-evidence`가 Chromium +artifact에서 baseline set을 계산하고 Firefox/WebKit과의 set 동일성 및 +failure/error/skipped 0을 기계적으로 검증한다. + +engine별 native capability 차이는 testcase를 skip하는 이유가 아니다. capability가 +없으면 adapter의 명시적 unsupported/degraded result를 같은 testcase에서 +검증한다. baseline `` activation은 portable한 +`input.click()` 경로를 사용하고, `showOpenFilePicker()` 같은 API는 별도 +progressive enhancement로 유지한다. 세 engine evidence가 완성되기 전에는 +product 상태를 `INSTALLED`로 올리지 않는다. ## 선택 이후 필요한 구현 diff --git a/docs/architecture/frontend-application-foundation.md b/docs/architecture/frontend-application-foundation.md new file mode 100644 index 0000000..6cb3ca2 --- /dev/null +++ b/docs/architecture/frontend-application-foundation.md @@ -0,0 +1,252 @@ +# Frontend Application Foundation + +This repository is not treated as a minimal React project template and it is not +an independent general-purpose SDK. Its architectural role is: + +> Frontend Application Foundation = Starter / Composition Skeleton + Reusable Capability Platform + +The starter side owns bootstrap, routing, providers, project conventions and a +removable reference feature. The capability side owns reusable technical +problems such as HTTP execution, Server State, authentication boundaries, +IndexedDB/OPFS, Cache Storage, realtime, browser RPC, transfer and diagnostics. + +The cost of a sophisticated capability is acceptable only when product features +do not have to understand that internal sophistication. + +## Hybrid architecture + +Platform code is horizontal: + +- `application`: generic application inputs/policies/ports +- `contracts`: genuinely cross-capability shared vocabulary and registries +- `adapters`: reusable capability runtimes +- `presentation`: generic UI/routing/query integration +- `bootstrap`: concrete composition + +Product business code is vertical: + +- `features//domain` +- `features//application` +- `features//contracts` +- `features//adapters` +- `features//presentation` + +The dependency model is: + + Domain / Use case + | + | owns + v + Business port + ^ + | implements / binds + | + Feature-owned adapter binding + | + | generic type + mapper/codec + policy + v + Reusable capability runtime + | + v + Browser / network / native API + +A use case never imports a platform adapter. Generic binding happens in the +feature adapter/composition seam. + +## Capability-specific typed bindings + +Do not introduce one universal `Repository` abstraction for HTTP, +storage, realtime and transfer. Their lifecycle and failure semantics differ. + +A reusable capability boundary is composed from: + +- generic input/output types, +- feature-owned mapper or codec, +- feature-selected policy, +- one capability-specific runtime. + +The HTTP reference path is the first concrete example. +`src/adapters/http/feature-http-binding.ts` owns transport/outcome +normalization. The reference feature contributes only: + +- operation ID, +- route ID, +- exact request input type, +- exact success value type, +- wire-to-domain mapper. + +The feature gateway therefore does not reimplement timeout, cancellation, +transport failure, authentication failure or contract-violation projection. + +Storage, realtime and transfer may gain their own typed binders only after +actual feature repetition demonstrates the need. They must not be forced +through the HTTP abstraction. + +## Custom adapter escape hatch + +A product feature uses a reusable capability when the capability preserves the +business requirement. + +If a platform contract would require changing or weakening the business model, +the feature implements a custom outbound adapter behind the same application +port. The architecture boundary remains stable; platform reuse is optional. + +## Feature installation + +A feature owns its contract, runtime and adapter contributions. + +Central installed catalogs are aggregation points only: + +- `installed-product-manifest.ts`: which product features are compiled/selected +- `installed-feature-contracts.ts`: contract aggregation +- `installed-feature-runtimes.tsx`: runtime contribution aggregation +- `installed-feature-adapters.ts`: application-input contribution aggregation + +Feature-specific composition belongs under the feature itself. Central +catalogs must not grow feature-specific branching logic. + +Adapter contributions declare the platform capabilities they consume through +`needs`. The generic contribution seam in +`src/features/feature-adapter-contribution.ts` derives the context from that +list, so an HTTP-only feature cannot reach IndexedDB and an IndexedDB-only +feature does not receive the HTTP executor. It also binds +`featureId -> ApplicationFeatureInputs[featureId]` at the contribution +definition site instead of recovering that relationship with a final catalog +cast. + +A contribution becomes composable only through +`defineFeatureAdapterContribution()`. That factory adds the private +contribution brand required by `composeFeatureAdapterInputs()`; a raw object +with the same visible fields is rejected by TypeScript and checked again at +runtime. The negative type fixture +`invalid-direct-feature-composition.ts` is part of FE-GATE-003 so this +authority cannot be bypassed by calling the composer directly. + +For IndexedDB-backed features, `createIndexedDbRepositoryProvider()` is the +composition helper that maps feature-owned repository identities to typed +`IndexedDbRepositoryPort` instances. It does not create a universal storage +repository or move dataset/migration/lifecycle policy into the feature. + +The repository now has two executable contribution shapes: + +- Reference feature: `needs: ["http"]` +- Local Draft feature: `needs: ["indexedDb"]` + +Local Draft is a compiled architecture consumer used to prove the second +capability shape; it is not added to the default product manifest. Its +browser-capability test composes the feature over the real +`createIndexedDbRuntime` and native IndexedDB, proving that this seam is not +limited to an in-memory contract fixture. + +## Presentation consumer surface + +`ApplicationProvider` remains the composition root for presentation, but new +consumers should not navigate a root `ApplicationApi` service locator. + +Use the narrow hooks in +`src/presentation/providers/application-provider.tsx`: + +- `useApplicationSession` +- `useApplicationPreferences` +- `useApplicationDiagnostics` +- `useApplicationRuntime` +- `useApplicationRecovery` +- `useApplicationFeature` + +`useApplication` exists only as a deprecated compatibility escape hatch. + +## Canonical imports + +New feature code should use capability public entry points rather than deep +runtime modules. For HTTP the canonical path is +`src/adapters/http/index.ts`. + +Compatibility re-exports may exist during a migration window, but they must be +marked as compatibility/deprecated paths and should not expand into an +unbounded public barrel. + +## Policy ownership + +Duplication is judged by ownership, not by syntax percentage. + +Small local validators can remain duplicated when locality improves auditing. +Business or concurrency policy must have one owner. For example the reference +create mutation keeps definition ID, idempotency requirement, duplicate policy +and invalidation policy in one feature-owned definition and binds only +`scope` and `execute` per usage site. + +## Runtime decomposition rule + +Large runtime files are not split by line count. + +Extract a boundary when it has its own state machine, lifecycle owner, failure +model or compensation/recovery responsibility. Candidate seams include: + +- connection/open/upgrade lifecycle, +- transaction ownership, +- migration state machine, +- reconnect/backoff and heartbeat, +- subscription ownership, +- retry/deadline/cancellation ownership, +- settlement/reconciliation/cleanup. + +A cohesive 2,000-line state machine can remain together. A 300-line file with +multiple lifecycle owners is a better extraction candidate. + +### Current runtime boundary audit + +The current large-runtime inventory was reviewed using that rule. + +- IndexedDB remains large, but connection, transaction, migration, maintenance + and failure translation already have separate owners/modules. +- resumable upload already separates runtime policy, checkpoint persistence, + HTTP control-plane transport, part execution, cancellation and mutation + locking. +- realtime already separates reconnect policy/coordinator, event codec/consumer + and stream coordination. +- OPFS is separated into browser runtime, journal, byte-store, policy and worker + protocol/runtime responsibilities. +- HTTP V3 still owned retry eligibility/backoff inside the execution state + machine, so that responsibility moved to + `src/adapters/http/http-retry-lifecycle.ts`. + +No other runtime is split merely because of its line count. + +## Consumer quality metrics + +Before adding another abstraction, implement or model multiple real feature +uses and measure: + +- feature-owned adapter LOC, +- repeated platform glue, +- number of platform-internal types exposed to the feature, +- central catalog edits, +- files changed for one normal query/command, +- whether native browser/network APIs leak into the feature. + +The target feature-development path is: + +1. domain type and invariant, +2. use case, +3. port, +4. transport/storage schema plus mapper/codec, +5. capability binding, +6. presentation controller/page. + +A product feature should not need to know the retry scheduler, abort ownership, +effect-certainty machinery, transaction leases, reconnect coordinator, OPFS +journal or provider lifecycle. + +The executable REST and IndexedDB consumer baselines are recorded in +[`capability-consumer-experience.md`](./capability-consumer-experience.md). +Contract placement and the global-vs-owner-local audit are recorded in +[`contract-ownership.md`](./contract-ownership.md). + +## Verification paths + +Product-development verification, capability verification and release assurance +are intentionally separate. See +[`docs/testing/taxonomy.md`](../testing/taxonomy.md). + +Host-level CI-runner tests belong to `tests/system`, not `tests/unit`. +Reusable capability consumer contracts belong to `tests/contract`. diff --git a/docs/architecture/layers.md b/docs/architecture/layers.md index 56a2c3f..2734d97 100644 --- a/docs/architecture/layers.md +++ b/docs/architecture/layers.md @@ -44,6 +44,36 @@ registries today, and the two collaborator types `query-cache` reads from `cross-context-invalidation`. Both lists are frozen — a new edge of either kind fails the gate. +## 어댑터 그룹의 공개 경계 + +각 어댑터 그룹의 공개 표면은 그 그룹의 `index.ts`다. 그룹 바깥 +(`bootstrap`, `features`, `presentation`)은 배럴만 import한다. +`adapter-groups-are-reached-through-their-barrel` 규칙이 이를 강제하고, +`tests/fixtures/architecture/dependency-graph/barrel`이 거부와 허용을 +각각 고정한다 — 규칙을 지우면 그 회귀 검사가 먼저 깨진다. + +두 가지 예외가 있고 둘 다 의도된 것이다. + +- **그룹 내부 파일끼리**는 파일 경로로 직접 import한다. 배럴은 바깥을 위한 + 문이지 내부 규율이 아니다. +- **어댑터 → 커널(`platform/**`)** 간선도 파일 경로를 유지한다. 커널은 + 런타임 합성물이 아니라 프리미티브이고, `check:adapter-inventory`가 네 + 소비자에게 `platform/abortable-operation.ts`로 해석되는 specifier를 + 직접 요구한다. 커널 배럴(`platform/index.ts`)은 bootstrap과 테스트를 + 위한 것이다. + +`storage`는 최상위 배럴이 `indexeddb/`·`opfs/` 서브배럴을 재수출하지 +않는다. 두 런타임이 각자 독립적으로 제거 가능하고 +(`test:browser-file-storage-removal`), 그래서 각 서브배럴이 곧 경계다. +규칙의 도착점 정규식이 1단계 중첩 `index.ts`를 배럴로 인정하는 이유가 +이것이다. + +`service-worker/index.ts`는 `tsconfig.service-worker.json`의 `exclude`에 +들어 있다. 그 설정이 그룹 폴더를 통째로 WebWorker lib로 컴파일하면서 페이지 +realm 파일만 빼는 구조라, 배럴이 그 파일을 다시 끌어들이면 워커 타입체크가 +`document`를 찾지 못한다. 배럴의 타입 커버리지는 `tsconfig.app.json`이 +담당하고, 워커 진입점은 배럴을 쓰지 않는다. + `bootstrap` contains composition only. Business rules and page-specific orchestration belong to domain/application. diff --git a/docs/operations/adapter-remediation-dispositions.json b/docs/operations/adapter-remediation-dispositions.json index d0e9edc..3c8140f 100644 --- a/docs/operations/adapter-remediation-dispositions.json +++ b/docs/operations/adapter-remediation-dispositions.json @@ -113,7 +113,7 @@ "previous": "PARTIAL", "disposition": "FIXED", "summary": "A source lease that arrives after the delivery ended is closed exactly once by a compensator.", - "evidence": ["tests/unit/presigned-transfer.test.ts"] + "evidence": ["tests/unit/presigned-transfer-delivery.test.ts"] }, { "id": "TR-03", @@ -123,7 +123,7 @@ "markers": ["X-AUDIT-01", "X-AUDIT-02"], "evidence": [ "tests/unit/abortable-operation.test.ts", - "tests/unit/image-cdn-runtime.test.ts", + "tests/unit/image-cdn-browser-probe.test.ts", "tests/unit/resumable-upload-fetch-transport.test.ts" ] }, @@ -132,7 +132,7 @@ "previous": "PARTIAL", "disposition": "FIXED", "summary": "Teardown proves quiescence of the raw provider registry, not only of the wrappers that bound it.", - "evidence": ["tests/unit/resumable-upload-runtime.test.ts"] + "evidence": ["tests/unit/resumable-upload-runtime-teardown.test.ts"] }, { "id": "TR-05", diff --git a/docs/operations/adapter-remediation-ledger.md b/docs/operations/adapter-remediation-ledger.md index 862c5e3..94e784c 100644 --- a/docs/operations/adapter-remediation-ledger.md +++ b/docs/operations/adapter-remediation-ledger.md @@ -337,7 +337,14 @@ Run on the landed tree. Only what actually passed is claimed as passing. | --- | --- | --- | | `tests/unit/ci-workflow-generation.test.ts` | 82 failed / 325 passed | Identical on the pre-change baseline (`git stash` comparison). The subprocess gates it spawns cannot run in this sandbox. | | `tests/unit/ci-artifact-contract.test.ts` | fails | Unchanged pre-existing sandbox, cgroup and `/tmp` permission behaviour. | -| `tests/unit/security-followup.test.ts`, `tests/unit/provider-guardian-transaction.test.ts`, `tests/unit/risk-coverage.test.ts` | flaky under full-suite load | All three pass in a fresh process (78 passed together). They spawn and reap process groups, so their timing assertions are load sensitive. | +| `tests/unit/security-followup.test.ts`, `tests/unit/provider-guardian-transaction.test.ts`, `tests/unit/risk-coverage.test.ts` | flaky under full-suite load | Historical baseline result. All three passed in a fresh process (78 passed together). | + +> Current classification update (2026-09-18): the provider guardian transaction +> suite moved to `tests/integration/provider-guardian-transaction.test.ts`. +> It spawns child processes and exercises filesystem/IPC/process lifecycle, so it +> is not part of the pure unit pool. Its READY/PUBLISHED wait uses a dedicated +> test watchdog rather than treating a 1-second scheduler delay as a production +> protocol deadline. ### Destructive fixture hazard — fixed @@ -375,7 +382,7 @@ files above plus the two flaky-under-load ones: | `tests/unit/ci-workflow-generation.test.ts` | 82 | Identical on the pre-change baseline (`git stash` comparison). Its subprocess gates cannot run in this sandbox. | | `tests/unit/ci-artifact-contract.test.ts` | 19 | Unchanged pre-existing sandbox, cgroup and `/tmp` permission behaviour. | | `tests/unit/security-followup.test.ts` | 2 | Passes in isolation. | -| `tests/unit/provider-guardian-transaction.test.ts` | 1 | Passes in isolation. | +| `tests/unit/provider-guardian-transaction.test.ts` (historical path; now `tests/integration/provider-guardian-transaction.test.ts`) | 1 | Historical baseline: passed in isolation; current suite is classified as process integration. | 1619 passed / 1723 total, and `tests/unit/removal-fixture.test.ts`, `tests/unit/supply-chain.test.ts` and diff --git a/docs/operations/browser-file-storage-recovery.md b/docs/operations/browser-file-storage-recovery.md index 56b6623..6a58321 100644 --- a/docs/operations/browser-file-storage-recovery.md +++ b/docs/operations/browser-file-storage-recovery.md @@ -148,6 +148,9 @@ read-only나 online-only가 사용자 작성 내용을 잃게 한다면 먼저 e ### 신호 - `BLOCKED`, `UPGRADE_BLOCKED` 또는 blocked duration bucket 증가 + - live attempt가 기다리는 동안 status는 `BLOCKED` + - blocked deadline settle 뒤에는 open result가 `BLOCKED` failure여도 + runtime status는 `CLOSED / NOT_OPENED` - `versionchange` 뒤 connection이 남음 - repeated reload/update loop - open/maintenance의 `POLICY_REJECTED`: immutable dataset binding missing/mismatch @@ -500,16 +503,13 @@ browser engine/version, fixture ID, fault phase, bounded counts/buckets와 PASS/ promotion 직전에는 다음 repository evidence도 함께 보존한다. -- `test:browser-capabilities`가 만든 JUnit에서 Chromium, Firefox, WebKit이 동일 - 14개 testcase set(File 2, IndexedDB 4, OPFS/Cache/StorageManager 각 1, - cross-context invalidation 2, presigned streaming download/multipart - upload/Image CDN 각 1)을 실제 실행해 총 42개이며 failure/error/skipped가 모두 - 0이어야 한다. - `verify:browser-capability-evidence`가 engine 집합과 testcase 동일성을 - 기계적으로 검증한다. 현재 artifact는 Chromium/Firefox 14개씩 총 28개가 - 통과했지만 WebKit 실행에 필요한 native libraries(예: - `libbacktrace.so.0`, `libevent-2.1.so.7`, `libjxl.so.0.8`, - `libavif.so.16`과 WPE 계열)가 이 host에 없으므로 아직 promotion 가능 상태가 +- `test:browser-capabilities`가 만든 JUnit에서 Chromium, Firefox, WebKit이 + source suite의 동일 testcase set을 실제 실행하고 failure/error/skipped가 모두 + 0이어야 한다. 구체적인 case 수는 이 runbook에 복제하지 않는다. + `verify:browser-capability-evidence`가 Chromium을 baseline으로 testcase set과 + engine 집합을 동적으로 검증한다. native capability가 없는 engine도 testcase를 + skip하지 않고 adapter의 명시적 `UNSUPPORTED`/degraded 결과를 검증해야 한다. + 세 engine 중 하나라도 실행되지 않은 artifact는 promotion 가능 상태가 아니다. - `artifacts/quality/vite-module-inventory.json`에서 optional runtime source root가 production chunk에 없음을 `check:optional-recipes`로 검증한다. diff --git a/docs/operations/template-sync-2026-09-21.md b/docs/operations/template-sync-2026-09-21.md new file mode 100644 index 0000000..902d3fd --- /dev/null +++ b/docs/operations/template-sync-2026-09-21.md @@ -0,0 +1,315 @@ +# Template sync — `5434760` → `ebea300` + +Record of how the frontend template's 21 pending commits were transplanted into +this product, and of every decision taken where the two trees disagreed. + +## Starting state + +| | | +| --- | --- | +| template pin before | `5434760` (`template.lock.json`) | +| template pin after | `ebea300` | +| template commits carried | 21 | +| template delta | 205 files, +22,729 / −9,969 | +| this product's divergence since the last sync | 618 files (`bdee07a..b297d65`) | +| files touched by both | 27 | +| applied to this product | 195 files, +21,527 / −9,980 | + +Rollback ref created before touching anything: + +``` +backup/main-before-template-ebea300 → b297d65 +``` + +The two histories share no commit — `git merge-base main template/main` is +empty — so this is a patch transplant, not a merge, the same way every previous +sync was. `template.lock.json` calls it `tracked-snapshot`; there is no sync +script. + +### Pre-transplant baseline + +Captured in a clean worktree at `b297d65` so a pre-existing failure could not be +mistaken for a transplant regression. + +| Gate | Result | +| --- | --- | +| `check:types` | pass | +| `lint` | pass | +| `test:unit` | 1825 passed / 4 failed / 16 skipped | +| `test:component` | 152 passed | +| `test:tech-log` | 415 passed | + +The four failures were `ci-artifact-contract` (2), `provider-guardian-transaction` +(1) and `removal-fixture` (1) — sandbox- and artifact-dependent checks that do +not run on this machine. + +## What the template brought + +| Group | Commits | Substance | +| --- | --- | --- | +| Frontend refactor | `ec7f20e` | Feature adapter contribution model, the `local-draft-feature` demonstration slice, a large set of typecheck fixtures, and several oversized test files split apart | +| Template refactor | `5cc4146` | `feature-http-binding`, reference feature restructured, `run-vitest.ts`, three new architecture documents | +| IndexedDB kernel | `cb62bfb` + 6 | A shared connection/transaction kernel; the OPFS journal, upload checkpoint store, maintenance and runtime moved onto it | +| Adapter barrel boundary | `b29a471` + 5 | A public `index.ts` per adapter group, enforced by the architecture gate | +| Other | `d777fb8`, `ebea300` | Abort-wiring ratchet; release identity derived from the package name | + +## What was deliberately not carried + +| Path | Why | +| --- | --- | +| `artifacts/tests/coverage-gateway/**` (10 files) | A coverage run the template committed by accident. Nothing outside `artifacts/` references it. | +| `docs/superpowers/specs/2026-09-20-memento-frontend-template-bootstrap-design.md` | A design for deriving a different product from the template. | +| `src/presentation/pages/home-page.tsx`, `src/presentation/examples/platform-overview-page.tsx`, `src/features/reference-feature/presentation/**` | Deleted by this product's UI migration. The template modified them; the deletions stand. | + +## Conflicts and how each was decided + +19 conflicts. The rule applied throughout is the one the previous sync wrote +down: **keep the template's mechanism, keep the product's content, and never +invent a third state that neither branch would accept.** + +### The platform HTTP executor — `src/bootstrap/runtime-adapters.ts` + +The substantive change of this sync. The template turned `contractOperations` +from a string-id executor into `InstalledHttpOperationExecutor`, which takes the +installed contract itself so a feature's Input/WireOutput/Problem types flow +through `createFeatureHttpBinding`. + +TechLog's four HTTP gateways address operations by id through their own +`StudioOperationExecutor` — six call sites across +`http-studio-gateway.ts`, `http-studio-asset-gateway.ts`, +`http-management-gateway.ts` and `http-public-content-gateway.ts`. Porting them +onto the typed binding is a rewrite of TechLog's HTTP layer, and nothing about +that is decided here. + +So the platform executor is the template's, verbatim, and the composition root +adapts it for TechLog: `techLogOperations` resolves the id against +`COMPOSED_CONTRACT_CONTRIBUTIONS.httpByOperationId` and delegates. The +resolution happens at the one place that already owns the registry rather than +inside the executor for every caller, and an unregistered id returns the same +`FINAL_REQUEST_INVARIANT_FAILED` violation on both paths. + +The product's `let` + throwing-stub forward reference — which exists to break +the CSRF construction cycle, and which the file documents at length — moved to +`techLogOperations`, where the cycle actually is. `contractOperations` is now a +plain `const`. + +The template's barrel imports were adopted; TechLog's imports were kept. + +### `src/features/installed-feature-adapters.ts` + +The template composes contributions through `composeFeatureAdapterInputs`, +selecting by `featureId` against the manifest. That mechanism is adopted. + +TechLog is composed directly on top of it, and its input stays total, because +TechLog is this product's own domain rather than a `SelectableProductFeature` — +the same split the previous sync recorded, now expressed through the template's +mechanism instead of a hand-written ternary. + +`InstalledFeatureInputs` became `Partial` upstream, so +the return type is that intersected with a total `Pick` of TechLog's entry. + +### `src/features/installed-contract-contributions.ts` + +Same shape. The manifest-governed contributions are filtered by their own +`featureId` — the template's improvement over this file naming the reference +feature — and TechLog's three contributions are appended unconditionally, where +the filter cannot drop them. + +### `src/features/installed-feature-runtimes.tsx` + +The template compiles the reference feature's runtime contribution here and +filters it through the manifest. This product deleted that feature's +presentation layer, so there is no contribution to compile and the import would +not resolve. Carrying an empty list plus the filter would be dead code neither +repository runs, so the previous sync's decision stands: the aggregation comes +back the day those screens do. + +A second reason not to adopt it as written: the template's +`Object.assign(..., ...contributions.map(...))` widens both catalogs to `any`, +and this product's router resolves codecs and components by route id off them. +The object spread keeps them typed. + +### `src/presentation/routes/app-router.tsx`, `src/presentation/layouts/app-shell.tsx` + +The template split `useApplication()` into `useApplicationRuntime()`, +`useApplicationDiagnostics()` and `useApplicationRecovery()`. Adopted. + +The template also added an `AppShell` import to the router; this product's +router never mounts it (the public site has its own header and the studio its +own shell), so the import was not carried — it would be dead. + +### Release identity — `ebea300` + +Three files hard-coded `tech-log-frontend/…` verifier ids because a previous +sync replaced the template's own hard-coded name. The template now derives them +from the package name. Taking the template's side produces the identical value +and removes the hard-coding: `scripts/generate-supply-chain.ts`, +`scripts/lib/local-release-evidence.ts`, `scripts/lib/provider-evidence.ts`. + +### `package.json` + +The template's mechanisms are kept — `node scripts/run-vitest.ts` in place of +bare `vitest`, the new `tests/contract` and `tests/system` suites, and the +typecheck fixtures moved onto per-fixture `tsconfig` files. This product's +entries are kept: `test:tech-log`, `check:tech-log-contract` in `test:all`, and +`tests/features/tech-log` in `test:coverage`. + +### `tests/unit/security-followup.test.ts` + +The template split this file into `security-followup-fixture.ts`, +`security-promotion-staging.test.ts` and `security-provider-evidence.test.ts`. +The product's only additions to it were the two hard-coded verifier ids (now +derived upstream) and `PROCESS_HEAVY_TIMEOUT_MS`, which the template's fixture +already carries. The file is byte-identical to the template's. + +### `tests/component/router.test.tsx` + +The template's hunk asserts `/examples/ui`, a screen this product deleted. The +product's Studio-layout assertions are kept. + +### Derived baselines — recomputed, not chosen + +`scripts/contracts/ci-gates.ts`, `tests/unit/ci-workflow-generation.test.ts` and +`tests/unit/task3-selective-integration.test.ts` pin counts and a digest +describing `config/ci/gates.json`. **Neither side's numbers describe the merged +file.** They were recomputed from it, and the method was checked by first +reproducing this product's pre-merge values from the pre-merge `gates.json`. + +| Value | This product | The template | Merged | +| --- | --- | --- | --- | +| gates | 27 | 27 | 27 | +| command definitions | 85 | 91 | **94** | +| command references | 97 | 103 | **106** | +| commands expecting failure | 23 | 30 | **30** | +| evidence artifact references | 118 | 88 | **120** | +| artifacts | 139 | 109 | **141** | +| canonical gate shape SHA-256 | `8a1a5479…` | `43dc4ed1…` | **`629e5898f6a38d5056fc6a4bee834c47f363669ce9925a2c0dabeddd64d11879`** | + +## Fixes the transplant required + +### The adapter barrel boundary caught three TechLog files + +`27ab17d` makes the architecture gate refuse an import that reaches past an +adapter group's barrel. Three TechLog files did: +`http-studio-gateway.ts` and `studio-error-mapping.ts` imported +`HttpExecutionOutcome` from `adapters/http/http-execution-v3.ts`, and +`studio-session-credentials.ts` imported `CredentialPatchOutcome` from +`adapters/http/http-contract-bridge.ts`. The barrel exports all three types; +the imports now go through it. + +### A relative import went stale when a test moved + +`tests/unit/ci-artifact-contract.test.ts` moved to +`tests/system/ci-runner/`. Its product-only import of +`scripts/lib/provider-sandbox-probe.ts` — a file the template does not have — +kept the old `../../` depth and had to become `../../../`. + +### The remediation ledger pointed at files that had been split + +`ec7f20e` split `presigned-transfer.test.ts`, `image-cdn-runtime.test.ts` and +`resumable-upload-runtime.test.ts`, moving the TR-02, TR-03 and TR-04 markers +into the new files, **but did not update +`docs/operations/adapter-remediation-dispositions.json`** — so +`check:remediation-ledger` is broken upstream as well. The three evidence paths +now name the files that actually carry the markers. + +### `tests/features/tech-log/runtime-composition.test.ts` + +Two changes. The composition call passes `http`, the platform capability the +manifest-governed contributions declare in `needs`. + +And its type assertion no longer uses `keyof`. The composed map became +`Partial` and the template's new local-draft feature +declares a third key, so every declared feature is a key whether installed or +not. What the product needs held is the split itself, so the assertion is now +that the *required* keys are exactly `"tech-log"` and that `"reference-feature"` +is not among them. + +## Gates on the transplanted tree + +| Gate | Result | +| --- | --- | +| `check:types` | pass (6 projects) | +| `lint` | pass, `--max-warnings=0` | +| `check:architecture` | 490 modules, 1630 dependencies, 14 fixtures pass | +| `check:adapter-inventory` | 133 files, 9 importers of the shared abort primitive, 21/21 abort ratchet | +| `check:ci` | 27 gates, artifact schemas and generated workflow pass | +| `check:design-system` | 48 tokens | +| `check:diagnostics` | 8 diagnostics, 5 telemetry producers | +| `check:remediation-ledger` | 25 dispositions, 0 open | +| `check:browser-security` | pass | +| `build` | pass | +| `test:unit` | 1789 passed in the working checkout; 1788 passed / 1 failed in the fresh worktree, where `removal-fixture` has no evidence tree to read | +| `test:component` | 152 passed | +| `test:tech-log` | 415 passed | +| `test:contract` | 7 passed (new suite) | +| `test:integration` | 102 passed | +| `test:reference-feature` | 19 passed | +| `test:recipes` | 17 passed | +| `test:runtime-schema` | 44 passed / 1 failed | + +Two of the pre-transplant failures disappeared because the template moved those +files out of `tests/unit`: `provider-guardian-transaction` now passes inside +`test:integration`, and `ci-artifact-contract` moved to `tests/system`, which +`test:all` does not run. + +## Failures this sync did not cause, and did not fix + +Each was reproduced at `b297d65` in a separate worktree before being classified. + +| Gate | State | +| --- | --- | +| `check:i18n` | Fails at `b297d65` identically. Its rule is `/[가-힣]/` over whole files in `src/presentation/**`, so the Korean comment block in `app-shell.tsx:181` trips it. The gate matches comments, not just user-facing literals. | +| `check:registries` | Fails at `b297d65` with byte-identical output: `TechLogTopicVariantParams`, `TechLogStudioDocumentsSearch` and `TechLogStudioPublicationsSearch` are referenced by routes but absent from the schema registry, plus six breaking changes without evidence. | +| `test:runtime-schema` | Fails at `b297d65`: the vendored TechLog Studio contract is at `3.1.0` and `release-manifest.test.ts:117` still expects `3.0.0`. | +| `tests/unit/removal-fixture.test.ts` | Only fails in a fresh worktree, which has no release evidence artifacts. In the working checkout `test:unit` is 1789/1789. | +| `verify:documentation` | `FAIL_UNVERIFIED` at `b297d65` and after, in both a fresh worktree and the working checkout. `reportDigestValid` is true and both ledger results pass; the single cause is `routeScopeDocumented: false`. Ten TechLog routes — `TECH_LOG_CONCEPT`, `TECH_LOG_SETUP`, `TECH_LOG_STUDIO_ASSETS`, `TECH_LOG_STUDIO_PROJECT_EDIT`, `TECH_LOG_STUDIO_RELEASES`, `TECH_LOG_STUDIO_RELEASE_EDIT`, `TECH_LOG_STUDIO_TAXONOMY`, `TECH_LOG_STUDIO_TOPIC_EDIT`, `TECH_LOG_TOPICS`, `TECH_LOG_TOPIC_VARIANT` — shipped without being added to `README.md` or `docs/accessibility/manual-checklist.md`, and the gate requires both to name every installed route id. Adding them to the checklist means writing a manual accessibility check per route, which is product work, not a transcription. | + +### `test:sample-removal` (FE-GATE-020) + +Broken before this sync — at `b297d65` the fixture's `vite build` fails outright, +so the gate never reaches its checks. After the transplant the fixture builds and +reports four named failures: + +| Check | Cause | +| --- | --- | +| `registry-structure` | The pre-existing registry defect above. `check:registries:structure` fails on the ordinary tree too, so this can never pass until that is fixed. | +| `typecheck` | `tests/features/tech-log/http-studio-gateway.test.ts` imports `tests/mocks/handlers/tech-log-studio.ts`, and `tests/mocks` is deleted whole as feature-owned. Pre-existing coupling in files this sync did not touch. | +| `unit-integration`, `coverage` | Downstream of that typecheck failure. | + +Three of its checks were repaired along the way, because the transplant is what +made them visible: + +- `common-test-evidence` — `tests/integration/http-execution-v3-observability.test.ts` + was in both `commonTestPaths` (must survive) and `featureOwnedPaths` (gets + deleted), so the check could never pass. The file names nothing of the + reference feature, so the `featureOwnedPaths` entry was stale and was removed. +- `fixture-id-residue` — `tests/features/tech-log/studio-csrf-composition.test.ts` + imports the reference feature's contract contribution on purpose: it proves a + 403 on *another* feature's operation does not discard TechLog's CSRF token, + which needs a second feature to exist. With the feature gone the premise is + gone, so it is now feature-owned. The last residue was one comment in + `studio-session-credentials.ts` naming the feature by id; it now says "other + features'". +- The exclusion list still named `tests/unit/ci-artifact-contract.test.ts` at its + old path. + +## Follow-ups this sync deliberately did not decide + +1. **TechLog's HTTP gateways still address operations by id.** The typed + `createFeatureHttpBinding` path is what the template now expects of a feature; + TechLog reaches it through a shim at the composition root. Porting the four + gateways is its own change. +2. **The schema registry defect keeps two gates red.** `check:registries` and, + through it, `test:sample-removal` cannot pass until the three TechLog schema + ids are registered and the six breaking changes carry evidence. +3. **`tests/mocks` is feature-owned but TechLog imports it.** Either the TechLog + handlers move out of `tests/mocks`, or the directory stops being deleted + wholesale. +4. **`check:i18n` cannot distinguish a comment from a user-facing literal.** + Either the rule scans string literals and JSX text, or product comments stop + being written in Korean. Today the gate is simply red. +5. **The template's `local-draft-feature` is carried but not installed.** It is a + demonstration slice with its own IndexedDB store; nothing in this product + composes it. It declares a third `ApplicationFeatureInputs` key, which is why + the composition test's `keyof` assertion had to change. diff --git a/docs/reviews/2026-09-17-senior-frontend-architecture-review.md b/docs/reviews/2026-09-17-senior-frontend-architecture-review.md new file mode 100644 index 0000000..15380c6 --- /dev/null +++ b/docs/reviews/2026-09-17-senior-frontend-architecture-review.md @@ -0,0 +1,1050 @@ +# Clean Architecture Frontend Template — Senior Architecture Review + +> 검토일: 2026-09-17 +> +> 검토 기준: `develop` / `c10a709f2cdea9d58d2f4816b48b4c41d0b5268b` +> +> 검토 관점: 장기 유지보수, Clean Architecture 경계, reusable adapter/capability 설계, TypeScript 타입 안전성, 테스트 품질과 실행 신뢰성, 개발자 경험 + +## 1. 결론 + +이 저장소를 단순한 **React 프로젝트 템플릿**으로 평가하면 현재 구조는 지나치게 크고 복잡하다. 그러나 실제 목적을 반영하면 평가는 달라진다. + +이 저장소의 목표는 다음에 더 가깝다. + +> **비즈니스 use case와 domain을 기술 세부사항에서 보호하면서, HTTP·Server State·IndexedDB·OPFS·WebSocket·Upload/Download 같은 클라이언트 capability를 미리 구현해 두고, 새 제품 기능에서는 비즈니스 타입과 mapper/codec/policy를 결합해 최대한 재사용할 수 있는 Frontend Application Foundation.** + +즉 `Starter Template + Reusable Capability Platform`의 혼합형이다. + +따라서 IndexedDB runtime이 크다거나 WebSocket 구현이 복잡하다는 이유만으로 제거하거나 단순화해서는 안 된다. 이런 복잡성은 여러 feature에서 한 번 구현한 기술 문제를 재사용하기 위한 비용일 수 있다. + +진짜 판정 기준은 다음이다. + +1. feature/use case 개발자가 adapter 내부 구현을 알아야 하는가. +2. use case가 요구하는 비즈니스 타입을 TypeScript generic으로 안전하게 adapter binding에 적용할 수 있는가. +3. 기능별 차이를 mapper/codec/policy만 주입해 표현할 수 있는가. +4. 공통 capability가 요구사항에 맞지 않을 때 custom adapter를 자연스럽게 구현할 수 있는가. +5. 플랫폼 내부의 registry, lifecycle, retry, storage, browser API 복잡도가 application/domain으로 새지 않는가. +6. 플랫폼을 사용하는 비용이 플랫폼을 직접 새로 구현하는 비용보다 충분히 낮은가. + +이 기준으로 보면 현재 저장소는 **방향은 맞고 기술적 기반도 강하지만, consumer surface와 검증 구조가 플랫폼 내부 복잡도를 충분히 숨기지 못하고 있다.** + +현재 가장 중요한 문제는 “플랫폼 기능이 너무 많다”가 아니라 다음 세 가지다. + +- **공통 capability를 사용하는 feature 작성 경로가 아직 충분히 작지 않다.** +- **테스트 taxonomy와 실행 환경이 self-contained하지 않아 테스트 결과를 신뢰하기 어렵게 만든다.** +- **플랫폼 내부 구현과 CI assurance가 매우 커졌는데, 이 복잡성이 명확한 모듈 경계로 격리되지 않았다.** + +--- + +## 2. 검토 기준선 + +현재 저장소 규모는 다음과 같다. + +| 영역 | 파일 수 | LOC | +| --- | ---: | ---: | +| `src/**` | 311 | 83,947 | +| `src/adapters/**` | 129 | 59,120 | +| `src/application/**` | 41 | 3,525 | +| `src/bootstrap/**` | 13 | 1,880 | +| `src/contracts/**` | 39 | 8,144 | +| `src/features/**` | 24 | 2,096 | +| `src/presentation/**` | 65 | 9,182 | +| `tests/**` TypeScript | 308 | 72,120 | +| `scripts/**` TypeScript | 123 | 28,397 | +| `package.json` scripts | 114 | - | + +제품 dependency는 6개, dev dependency는 29개다. 외부 라이브러리 숫자를 무작정 늘린 구조는 아니다. 복잡성의 상당 부분을 저장소가 직접 소유하고 있다는 의미다. + +가장 큰 production source는 다음과 같다. + +| 파일 | LOC | +| --- | ---: | +| `src/adapters/storage/indexeddb/indexeddb-runtime.ts` | 2,744 | +| `src/adapters/browser-transfer/resumable-upload/resumable-upload-runtime.ts` | 2,298 | +| `src/adapters/realtime/websocket/websocket-connection.ts` | 2,003 | +| `src/adapters/storage/opfs/opfs-worker-runtime.ts` | 1,971 | +| `src/adapters/cache-storage/public-response-cache-adapter.ts` | 1,949 | +| `src/adapters/storage/opfs/indexeddb-opfs-journal.ts` | 1,881 | +| `src/adapters/realtime/reconnect-coordinator.ts` | 1,796 | +| `src/adapters/browser-rpc/browser-rpc-runtime.ts` | 1,696 | +| `src/adapters/storage/opfs/opfs-byte-store-adapter.ts` | 1,649 | +| `src/adapters/http/http-execution-v3.ts` | 1,602 | + +큰 파일 자체를 결함으로 판정하지 않는다. 다만 이 규모에서는 내부 책임 분리가 명확하지 않으면 수정 시 regression 위험이 빠르게 증가한다. + +--- + +## 3. 현재 구조에서 잘된 부분 + +### 3.1 Clean Architecture 경계가 실제로 집행된다 + +이 저장소의 가장 강한 부분이다. + +`presentation`, `application`, feature code가 `fetch`, `IndexedDB`, `WebSocket`, browser storage 같은 native I/O를 임의로 직접 호출하는 구조가 아니며, 정적 architecture gate가 dependency 방향을 검사한다. + +검토 시점 `check:architecture`는 다음 기준선을 통과했다. + +```text +307 modules +929 dependencies +PASS +``` + +금지 dependency fixture도 실제로 거절된다. + +즉 폴더 이름만 `domain/application/adapter`로 만든 구조가 아니라 **의존 방향을 executable rule로 만든 구조**다. + +### 3.2 TypeScript generic을 이미 핵심 계약에 사용하고 있다 + +사용자가 원하는 “use case에서 결정되는 비즈니스 타입을 공통 adapter capability에 적용”할 기반은 이미 존재한다. + +예를 들어 V3 HTTP executor는 다음 형태다. + +```ts +interface ContractHttpExecutor { + execute( + operation: InstalledHttpContract, + input: Input, + context: HttpExecutionContext, + ): Promise>; +} +``` + +즉 HTTP runtime은 특정 `User`, `Order`, `ReferenceResource`를 알지 않는다. `Input`, `WireOutput`, `Problem` 타입 파라미터만 안다. + +Server State도 `BoundMutation`와 같이 feature의 command/result 타입을 generic으로 받는다. + +또 `ApplicationFeatureInputs`는 module augmentation을 이용해 concrete feature를 generic application에 직접 import하지 않고도 typed feature API를 등록한다. + +이 방향은 유지할 가치가 높다. + +### 3.3 reference feature가 vertical slice의 실제 증거 역할을 한다 + +`reference-feature`는 단순 데모 화면이 아니다. + +- domain은 외부 DTO/React를 모른다. +- application은 input/gateway 계약을 가진다. +- outbound adapter가 HTTP executor를 feature gateway로 투영한다. +- mapper가 transport payload와 domain/application value 사이를 분리한다. +- presentation은 application input을 호출하며 HTTP나 storage를 직접 알지 않는다. +- sample removal test로 feature를 제거했을 때 generic platform이 유지되는지 확인한다. + +즉 목표 아키텍처를 실제 실행 가능한 vertical slice로 증명하고 있다는 점은 좋다. + +### 3.4 테스트의 사고방식은 깊다 + +테스트는 단순 mock 호출 횟수 검증에 머무르지 않는다. + +예를 들어 query/mutation test는 cancellation, scope fence, stale data, optimistic mutation, effect certainty, reconciliation, duplicate submission을 실제 lifecycle 관점에서 검증한다. + +HTTP/storage/realtime도 정상 경로뿐 아니라 timeout, late settlement, retry, mutation effect, lifecycle cleanup 등을 검증한다. + +따라서 테스트의 핵심 문제는 **검증 깊이가 부족한 것**이 아니다. 오히려 검증 범위가 커지면서 **분류와 실행 경계가 무너진 것**이 문제다. + +--- + +## 4. 이 저장소의 정체성을 명확히 해야 한다 + +현재 문서와 코드에는 `template`, `platform`, `reference feature`, `optional capability`라는 표현이 모두 존재한다. 각각 틀린 표현은 아니지만, 최상위 모델이 명확하지 않으면 이후 리팩터링에서 서로 반대 방향의 결론을 낼 수 있다. + +이 저장소는 다음 두 축을 동시에 가진다고 정의하는 것이 가장 정확하다. + +```text +Frontend Application Foundation +│ +├── Starter / Composition Skeleton +│ ├── bootstrap +│ ├── routing +│ ├── application provider +│ ├── reference feature +│ └── project conventions +│ +└── Reusable Capability Platform + ├── HTTP + ├── Server State + ├── Auth boundary + ├── IndexedDB / OPFS + ├── Cache Storage + ├── Realtime / WebSocket + ├── Browser RPC + ├── Upload / Download + ├── Diagnostics / Telemetry + └── optional browser capabilities +``` + +중요한 점은 **둘을 물리적으로 반드시 별도 repository/package로 분리해야 한다는 의미가 아니다.** + +먼저 코드와 문서에서 책임을 명확히 해야 한다. + +- Starter는 “어떻게 조립하는가”를 보여준다. +- Feature는 “비즈니스 요구를 어떻게 표현하는가”를 보여준다. +- Capability Platform은 “기술 문제를 어떻게 재사용하는가”를 책임진다. +- CI/Assurance는 “이 계약이 깨지지 않았음을 어떻게 증명하는가”를 책임진다. + +이 네 영역이 같은 repository 안에 있어도 된다. 문제는 한 영역을 사용하기 위해 다른 세 영역의 내부 구현을 알아야 하는 경우다. + +--- + +## 5. 목표 Adapter 모델 + +### 5.1 use case가 adapter에 의존하면 안 된다 + +사용자의 표현인 “use case에서 나오는 비즈니스 타입을 adapter에 바로 적용한다”는 의도는 맞다. 다만 dependency 방향은 정확히 구분해야 한다. + +원하는 구조는 다음이다. + +```text +Domain / UseCase + │ + │ owns + ▼ +Business Port + ▲ + │ implements / binds + │ +Feature Adapter Binding + │ + │ supplies generic types + mapper + policy + ▼ +Reusable Capability Runtime +``` + +use case가 `HttpAdapter`를 직접 생성하거나 import하는 구조가 아니다. + +use case는 자신의 port만 안다. + +```ts +interface UserRepository { + findById(id: UserId): Promise>; +} +``` + +그리고 feature-owned outbound adapter/composition이 reusable HTTP capability를 구체화한다. + +```ts +createHttpBinding({ + contract, + decode: decodeUserWireDto, + map: mapUser, + mapFailure, +}); +``` + +이때 `User`는 generic type argument로 capability에 들어갈 수 있지만 capability source가 `User` domain module을 import하지는 않는다. + +### 5.2 제네릭만으로 해결하지 않는다 + +재사용 adapter의 목표를 `Repository` 하나로 모든 기술을 추상화하는 것으로 잡으면 실패한다. + +HTTP, IndexedDB, WebSocket, Upload는 failure semantics와 lifecycle 자체가 다르다. + +공통화 단위는 다음 조합이 적절하다. + +```text +Generic Type ++ Codec / Mapper ++ Policy ++ Capability Runtime +``` + +예를 들어 HTTP는 다음을 공통 runtime이 책임질 수 있다. + +- timeout/deadline +- cancellation +- retry +- auth attachment +- bounded response read +- effect certainty +- diagnostics/telemetry +- transport failure normalization + +Feature는 다음만 책임져야 한다. + +- operation identity +- request input +- wire schema +- wire → domain mapper +- feature-specific failure mapping +- 필요한 retry/idempotency policy 선택 + +IndexedDB는 HTTP와 다른 capability factory를 가져야 한다. + +- key extraction +- encode/decode +- schema/migration policy +- domain-specific repository operation + +WebSocket/realtime은 다시 다른 API가 맞다. + +- event decoder +- event authority/revision policy +- subscription ownership +- reconnect/resume policy + +즉 **“하나의 generic repository”가 아니라 “capability-specific typed factory”**를 목표로 하는 것이 맞다. + +### 5.3 custom adapter escape hatch는 반드시 남긴다 + +Reusable capability가 80~90%의 일반 요구를 해결하더라도 제품 요구가 capability contract와 맞지 않을 수 있다. + +따라서 platform API는 다음을 강제해서는 안 된다. + +> 모든 HTTP/storage/realtime 구현은 반드시 platform factory를 사용해야 한다. + +정확한 규칙은 다음이 좋다. + +> 공통 capability contract가 요구사항을 보존할 수 있으면 재사용한다. 요구사항을 왜곡해야 사용할 수 있다면 feature-owned custom adapter를 구현한다. 단 application port와 architecture boundary는 동일하게 유지한다. + +이 원칙이 있어야 platform abstraction이 business model을 끌어당기지 않는다. + +--- + +## 6. 현재 구현이 목표 모델에 근접한 부분과 남은 간극 + +### 6.1 이미 근접한 부분 + +현재 `ContractHttpExecutor`은 좋은 기반이다. + +feature에서는 `ReferenceOperationMap`을 통해 operation마다 request/value type을 묶고, raw executor 결과를 domain type으로 투영한다. + +`ApplicationFeatureInputs`도 concrete feature를 generic application에서 분리한다. + +즉 **타입을 parameterize하는 방향 자체는 이미 맞다.** + +### 6.2 아직 feature adapter boilerplate가 크다 + +`reference-http-gateway.ts`를 보면 feature가 다음을 모두 직접 작성한다. + +- operation map +- request type projection +- result type projection +- `execute` 호출 +- result guard +- mapping contract failure 생성 + +이 중 일부는 feature-owned이어야 한다. 그러나 동일한 형태가 feature마다 반복된다면 재사용 platform의 consumer API가 충분히 올라오지 않은 것이다. + +향후 실제 feature 2~3개를 추가해 다음을 측정해야 한다. + +- HTTP feature 하나 추가 시 작성해야 하는 adapter glue LOC +- 동일 패턴 반복 비율 +- platform 내부 type 이름을 feature 개발자가 알아야 하는 개수 +- 등록해야 하는 중앙 registry 수 +- 정상 query 하나를 연결하기 위해 건드리는 파일 수 + +이 지표가 platform usability를 판단하는 핵심이다. + +### 6.3 설치 지점이 여러 곳으로 나뉜다 + +현재 reference feature README가 명시하는 설치 지점은 세 곳이다. + +- `installed-feature-contracts.ts` +- `installed-feature-runtimes.tsx` +- `installed-feature-adapters.ts` + +현재 총 181 LOC라 파일 크기 자체는 크지 않다. 문제는 feature가 늘었을 때 **한 기능 설치가 여러 중앙 catalog 수정으로 확산되는 구조**라는 점이다. + +이 구조는 계약/runtime/composition을 분리한다는 장점이 있으므로 무작정 한 객체로 합치면 안 된다. + +대신 다음 목표가 필요하다. + +> feature-owned contribution을 각 boundary가 소비하되, 새 feature 개발자가 중앙 설치 파일의 내부 구조를 반복해서 편집하지 않게 한다. + +예를 들어 feature가 contract/runtime/adapter contribution을 각각 export하고, installed catalog는 단순 aggregation만 담당하는 구조가 적절하다. + +### 6.4 `ApplicationApi`는 지금은 관리 가능하지만 Service Locator로 성장할 수 있다 + +현재 `ApplicationApi`는 다음 플랫폼 기능을 직접 노출한다. + +- session +- preferences +- diagnostics +- runtime +- recovery +- features + +구조 자체는 잘못이 아니다. presentation에서 concrete adapter를 숨기는 역할을 한다. + +그러나 기능이 계속 추가되며 모든 application capability가 하나의 root object 아래 들어가면 다음과 같은 사용 패턴이 일반화될 수 있다. + +```ts +const application = useApplication(); +``` + +이후 모든 presentation 코드가 거대한 application service locator를 바라보게 된다. + +권장 방향은 root provider를 유지하더라도 consumer API를 좁히는 것이다. + +```text +useSession() +useRuntimeCapabilities() +useReferenceFeature() +``` + +즉 composition은 하나여도 presentation dependency surface는 필요한 capability만 노출한다. + +--- + +## 7. P0 — 테스트 실행 환경이 self-contained하지 않다 + +이 문제는 다른 리팩터링보다 먼저 고치는 것이 좋다. 테스트가 신뢰되지 않으면 이후 구조 변경의 안전망도 신뢰할 수 없다. + +### 7.1 Component test가 host `NODE_ENV`에 영향을 받는다 + +검토 환경의 host에는 다음이 설정되어 있었다. + +```text +NODE_ENV=production +``` + +현재 `package.json`의 `test:component`는 다음과 같이 Vitest를 바로 실행하며 test environment를 고정하지 않는다. + +```text +vitest run tests/component ... +``` + +그 결과: + +```text +pnpm test:component +→ React.act is not a function +→ 119 tests failed +``` + +반면 같은 checkout에서: + +```text +NODE_ENV=test pnpm test:component +→ 20 test files passed +→ 130 tests passed +``` + +했다. + +이것은 119개 component가 각각 잘못된 것이 아니라 **test runner가 외부 shell environment를 그대로 받아 React production test path를 로드한 것**이다. + +템플릿/플랫폼 저장소의 테스트는 개발자 머신의 우연한 환경 값에 따라 의미가 바뀌면 안 된다. + +### 권장 + +- component/unit/integration runner가 필요한 environment를 명시적으로 소유한다. +- test bootstrap 단계에서 잘못된 `NODE_ENV`를 fail-fast하거나 고정한다. +- CI에서만 성립하는 environment assumption을 일반 test script와 분리한다. + +--- + +## 8. P0 — `unit` test taxonomy가 실제 실행 특성과 맞지 않는다 + +현재 `docs/testing/taxonomy.md`는 `test:unit`을 별도 test level로 정의하지만 `tests/unit` 안에는 실제로 host-level system assurance가 포함된다. + +검토 환경에서: + +```text +pnpm test:unit +→ 99 failures +``` + +가 발생했다. + +하지만 주요 실패는 business/application logic regression이 아니었다. + +대표 원인은 다음과 같다. + +```text +provider sandbox unavailable: /usr/bin/bwrap is required +systemctl list-units failed: Failed to connect to bus +npm_config_userconfig / npm_config_prefix / npm_config_globalconfig host environment +``` + +`ci-artifact-contract.test.ts`는 다음을 검증한다. + +- bubblewrap sandbox +- systemd unit +- cgroup/resource limit +- process guardian/supervisor +- background process kill/collection +- archive/provider isolation +- host path protection + +이 테스트들은 가치가 있다. 제거할 대상이 아니다. + +그러나 **unit test가 아니다.** + +권장 taxonomy는 다음과 같다. + +```text +tests/ +├── unit/ +│ ├── domain +│ ├── application +│ └── pure-policy +│ +├── contract/ +│ └── reusable-capability contracts +│ +├── component/ +│ └── React / hook / UI behavior +│ +├── integration/ +│ ├── HTTP/MSW +│ ├── IndexedDB +│ └── browser runtime boundaries +│ +├── system/ +│ └── ci-runner/ +│ ├── sandbox +│ ├── cgroup +│ ├── process-supervision +│ └── supply-chain +│ +└── e2e/ +``` + +특히 `pnpm test:unit`은 **지원 Node 환경만 있으면 일반 개발 머신에서 deterministic하게 실행**되어야 한다. + +systemd/bwrap/cgroup이 필요하면 `test:ci-runner` 또는 `test:system`처럼 요구사항이 이름에 드러나야 한다. + +--- + +## 9. P1 — Adapter runtime은 “크기”가 아니라 내부 경계를 기준으로 재검토해야 한다 + +기존에 2,000~2,700 LOC 파일을 단순히 작게 나누는 것은 권장하지 않는다. + +이미 adapter review의 D-07이 적절한 원칙을 가지고 있다. + +> state machine과 Saga 경계로만 큰 runtime을 나누고, public capability identity/failure taxonomy/persisted schema/wire semantics를 유지한다. + +이 원칙을 그대로 적용하는 것이 맞다. + +예를 들어 `indexeddb-runtime.ts`를 다음 이유만으로 분리해서는 안 된다. + +> 2,744줄이니까 500줄씩 다섯 파일로 나누자. + +대신 다음 책임이 독립적으로 설명되고 테스트 가능한지 본다. + +- connection/open/upgrade lifecycle +- transaction ownership +- schema/migration state machine +- quota/budget policy +- serialization/codec +- mutation settlement +- cleanup/compensation +- recovery/reconciliation + +WebSocket도 같은 기준이다. + +- connection state machine +- reconnect/backoff policy +- heartbeat +- subscription ownership +- writer/lease lifecycle +- resume/gap policy +- message codec + +**하나의 변경 이유와 하나의 failure model을 공유한다면 같은 모듈에 있어도 된다.** + +반대로 독립 lifecycle을 가진 책임이 같은 2,000줄 파일에서 mutable state를 공유한다면 추출 우선순위가 높다. + +--- + +## 10. P1 — 테스트 파일도 behavior contract 단위로 분리해야 한다 + +현재 가장 큰 테스트 파일은 다음과 같다. + +| 파일 | LOC | +| --- | ---: | +| `ci-artifact-contract.test.ts` | 2,538 | +| `presigned-transfer.test.ts` | 2,518 | +| `image-cdn-runtime.test.ts` | 2,430 | +| `application-query.test.tsx` | 2,196 | +| `security-followup.test.ts` | 1,859 | +| `public-response-cache.test.ts` | 1,711 | +| `ci-workflow-generation.test.ts` | 1,635 | + +테스트 파일이 production 파일보다 커지는 것 자체는 문제가 아니다. 복잡한 state machine은 많은 테스트를 필요로 한다. + +문제는 서로 다른 behavior가 하나의 파일 안에 섞이면 실패 메시지가 ownership을 알려주지 못한다는 점이다. + +예를 들어 `application-query.test.tsx`는 사실상 다음 여러 계약을 검증한다. + +```text +query initial/background state +query scope fence +result budget +mutation scope fence +optimistic mutation +unknown effect reconciliation +concurrency / duplicate submission +cache invalidation +``` + +따라서 다음처럼 behavior 단위로 분리하는 것이 더 낫다. + +```text +application-query/ +├── query-state.test.tsx +├── query-scope-fence.test.tsx +├── query-budget.test.tsx +├── mutation-scope-fence.test.tsx +├── optimistic-mutation.test.tsx +├── mutation-reconciliation.test.tsx +├── duplicate-submission.test.tsx +└── fixtures.ts +``` + +테스트 분리의 목표도 LOC가 아니다. + +> 하나의 실패 파일명이 “어떤 계약이 깨졌는지”를 설명해야 한다. + +--- + +## 11. P1 — Capability consumer API를 실제 feature 개발 비용으로 평가해야 한다 + +현재 플랫폼은 내부 correctness에 대한 검증은 매우 강하다. 반면 앞으로는 **새 feature를 만드는 개발자의 비용**을 별도 품질 지표로 봐야 한다. + +추천하는 평가 시나리오는 실제 sample feature 2개를 추가해보는 것이다. + +### 시나리오 A — 일반 REST CRUD + +필요 조건: + +- list/detail/create/update +- pagination +- error mapping +- optimistic mutation 하나 + +측정: + +- feature-owned LOC +- platform glue LOC +- 수정 파일 수 +- 중앙 registry 수정 수 +- transport/runtime type을 직접 알아야 하는 횟수 + +### 시나리오 B — IndexedDB local draft + +필요 조건: + +- domain draft type +- save/find/remove +- codec +- migration 없는 단순 store + +측정: + +- IndexedDB native API를 feature가 알아야 하는가 +- runtime internal type을 import해야 하는가 +- `create...Repository` 계열 binding만으로 해결되는가 + +이 실험 결과가 다음 platform API 리팩터링의 근거가 되어야 한다. + +--- + +## 12. P1 — `contracts`는 계속 커지면 제2의 `shared/common`이 된다 + +현재 `src/contracts`는 39개 파일, 약 8,144 LOC다. + +`contracts`라는 이름은 편리하지만 ownership을 잃기 쉽다. + +특히 다음이 모두 한 bucket으로 들어가면 문제가 된다. + +- error vocabulary +- server-state contracts +- capability registry +- boundary mapper +- mutation intent +- runtime descriptor +- compatibility metadata + +공통 계약이 실제로 여러 capability가 공유하는 SSOT라면 `contracts`에 있어도 된다. + +그러나 **특정 feature/adapter만 소비하는 contract는 owner 쪽에 두는 것이 더 낫다.** + +판정 질문은 단순하다. + +> 이 타입을 바꾸는 이유가 어떤 모듈의 요구사항 변화 때문인가? + +답이 항상 특정 feature/storage/http라면 global contracts가 아닐 가능성이 높다. + +--- + +## 13. P1 — CI/Assurance는 가치가 있지만 product development path와 격리해야 한다 + +현재 package script는 114개, `scripts/**/*.ts`는 123개 / 약 28K LOC다. + +이는 단순 frontend build script 수준을 넘어선다. + +현재 저장소는 다음을 자체적으로 검증한다. + +- architecture graph +- registry compatibility +- artifact semantic validation +- supply-chain evidence +- reproducible build +- provider sandbox +- promotion/finalization +- archive traversal/symlink/hardlink +- release admission +- security fixtures + +이 기능을 단순화한다는 이유로 제거할 필요는 없다. 플랫폼 품질과 supply-chain assurance를 강하게 가져가겠다면 정당한 투자다. + +다만 개발자가 일반 feature를 수정할 때 이 전체 영역을 알아야 해서는 안 된다. + +권장 구조적 목표는 다음이다. + +```text +Product development path + feature → focused test → type/lint/architecture + +Platform capability path + adapter → capability contract/integration tests + +Assurance path + CI runner → supply-chain/system/promotion tests +``` + +세 경로의 명령과 실패 메시지가 명확히 분리되어야 한다. + +--- + +## 14. P2 — 실제 중복은 정책 중복부터 제거한다 + +중복 제거의 목표를 “같은 코드 한 줄도 두 번 쓰지 않는다”로 잡으면 이 프로젝트에서는 오히려 abstraction이 과해진다. + +특히 security/protocol boundary의 작은 validator는 local duplication이 가독성과 auditability에 도움이 될 수 있다. + +반대로 **정책 중복은 제거해야 한다.** + +현재 `use-reference-feature.ts`에는 `CREATE_REFERENCE_RESOURCE` mutation definition이 두 경로에 반복된다. + +반복되는 핵심 값은 다음과 같다. + +```text +definitionId +operationId +requiresIdempotencyKey +owner +duplicatePolicy +invalidate +``` + +이것은 단순 syntax 중복이 아니라 하나의 mutation policy다. + +한쪽만 수정되면 같은 feature 안에서 서로 다른 concurrency/idempotency 동작을 할 수 있다. + +따라서 feature-owned mutation definition 또는 factory로 단일화하는 것이 맞다. + +반대로 `isPlainRecord` 같은 3~5줄 helper는 모든 adapter에서 무조건 한 global utility로 합칠 필요가 없다. + +--- + +## 15. P2 — compatibility re-export는 canonical import path를 흐릴 수 있다 + +현재 일부 UI와 Result 계층에는 canonical 정의와 compatibility re-export가 동시에 존재한다. + +이런 구조가 migration window를 위해 필요하다면 괜찮다. + +하지만 템플릿 출발점에서 두 경로가 모두 정식 API처럼 보이면 새 개발자가 어떤 import를 사용해야 하는지 판단해야 한다. + +원칙은 다음이 적절하다. + +- public import path는 capability마다 하나를 canonical로 둔다. +- compatibility export는 deprecated/migration purpose임을 명시한다. +- migration 종료 조건이 충족되면 제거한다. +- 테스트 편의를 위해 barrel export를 무한히 확장하지 않는다. + +--- + +## 16. Hybrid Architecture를 공식 모델로 문서화할 필요가 있다 + +현재 저장소는 순수 horizontal Clean Architecture가 아니다. + +실제 구조는 다음 hybrid에 가깝다. + +```text +Platform horizontal layers +├── application +├── contracts +├── adapters +├── presentation +└── bootstrap + +Feature vertical slices +└── features/ + ├── domain + ├── application + ├── adapters + ├── contracts + └── presentation +``` + +이 구조는 프론트엔드에서 합리적이다. + +공통 HTTP/storage/query runtime을 모든 feature 안에 복사할 이유는 없고, feature domain/application은 vertical slice로 격리할 수 있기 때문이다. + +따라서 전역 `src/domain`이 없다는 이유로 억지로 생성할 필요도 없다. + +대신 문서에서 다음을 명시해야 한다. + +> platform은 horizontal capability layer를 사용하고, product business feature는 vertical slice를 사용한다. feature는 platform capability를 port 뒤에서 소비하며 platform은 concrete feature를 알지 않는다. + +이 문장이 공식 architecture model이 되면 “왜 여기에는 domain이 없고 feature 안에는 domain이 있는가” 같은 혼란이 줄어든다. + +--- + +## 17. 권장 리팩터링 순서 + +### Phase 0 — 테스트 신뢰성 정상화 + +먼저 구조를 바꾸지 않고 검증 기반을 고친다. + +1. test runner의 `NODE_ENV` 등 필수 environment를 deterministic하게 만든다. +2. `tests/unit`에서 systemd/bwrap/cgroup 의존 테스트를 분리한다. +3. `test:unit`, `test:component`, `test:integration`, `test:system`, `test:e2e`의 의미를 다시 고정한다. +4. Node version requirement와 local runner requirement를 명확하게 fail-fast한다. + +이 단계가 끝나야 이후 refactoring failure를 실제 regression으로 믿을 수 있다. + +### Phase 1 — reference feature를 platform consumer UX 기준으로 리팩터링 + +새 abstraction을 먼저 만들지 않는다. + +현재 reference feature를 기준으로 다음을 측정하고 줄인다. + +- HTTP gateway boilerplate +- mapper/result guard 중복 +- query/mutation definition duplication +- installed contribution 수정 지점 +- platform internal type exposure + +이 단계에서 capability API의 이상적인 최소 사용 형태를 결정한다. + +### Phase 2 — capability-specific typed factory 정리 + +반복이 확인된 경우에만 factory를 만든다. + +후보: + +```text +HTTP operation/gateway binder +IndexedDB typed repository/storage binder +Realtime event source binder +Transfer command/session binder +``` + +하나의 범용 repository/framework로 합치지 않는다. + +### Phase 3 — Application/Feature installation surface 축소 + +- root ApplicationProvider는 유지 가능 +- feature consumer hook은 narrow API 제공 +- installed catalog는 aggregation 역할로 제한 +- feature-owned contribution 정의를 강화 +- concrete feature를 generic platform에서 import하지 않는 규칙 유지 + +### Phase 4 — 거대 runtime 내부 경계 추출 + +characterization test를 먼저 고정한다. + +우선순위 후보: + +1. IndexedDB runtime +2. resumable upload +3. WebSocket connection/reconnect +4. HTTP execution V3 +5. OPFS runtime/journal + +파일 크기가 아니라 state machine/Saga/lifecycle ownership을 기준으로 추출한다. + +### Phase 5 — 거대 테스트 분해 + +production runtime extraction과 같은 behavior boundary에 맞춰 test suite도 분리한다. + +### Phase 6 — CI/Assurance 경로 분리 + +product feature 개발 loop와 release/supply-chain system assurance loop를 명령, 테스트 디렉터리, prerequisite 측면에서 명확히 구분한다. + +--- + +## 18. 명시적으로 하지 말아야 할 리팩터링 + +### 18.1 모든 adapter를 하나의 generic repository로 통합하지 않는다 + +HTTP, IndexedDB, Realtime, Upload는 lifecycle과 failure semantics가 다르다. + +타입 파라미터가 비슷하다는 이유로 하나의 abstraction으로 합치면 business 요구를 기술 abstraction에 맞추게 된다. + +### 18.2 use case가 platform adapter를 직접 import하지 않는다 + +`UseCase → HttpAdapter` 구조가 되면 Clean Architecture의 핵심 목적을 잃는다. + +Generic type binding은 feature adapter/composition에서 일어나야 한다. + +### 18.3 단순화를 이유로 hardening을 제거하지 않는다 + +현재 retry/effect certainty/bounded read/recovery/sandbox 같은 계약은 대부분 실제 failure mode를 막기 위해 존재한다. + +필요한 것은 삭제가 아니라 **internal complexity encapsulation**이다. + +### 18.4 파일 길이만 보고 나누지 않는다 + +2,000줄이어도 하나의 cohesive state machine이면 함부로 분리하지 않는다. + +반대로 300줄이어도 서로 다른 lifecycle owner가 섞여 있으면 분리 대상이다. + +### 18.5 중복률 0%를 목표로 하지 않는다 + +local protocol validator의 작은 중복보다 policy가 여러 곳에 존재하는 중복이 더 위험하다. + +--- + +## 19. 최종 목표 개발 경험 + +이 Foundation이 잘 리팩터링됐을 때 새 feature 개발자는 대략 다음만 작성하면 되어야 한다. + +```text +1. Domain type / invariant +2. UseCase +3. Port +4. Transport/storage schema와 mapper +5. Capability binding 설정 +6. Presentation controller/page +``` + +그리고 HTTP/IndexedDB/WebSocket 내부의 다음 내용을 몰라도 되어야 한다. + +```text +retry scheduler +abort ownership +effect certainty +transaction lease +reconnect coordinator +OPFS journal +provider lifecycle +telemetry delivery +``` + +개념적으로 다음 형태가 목표다. + +```text +Business Domain + ↓ +UseCase + ↓ +Port + ↓ +Feature-owned Binding + + + mapper/codec + + policy + ↓ +Reusable Capability Runtime + ↓ +Browser / Network / Native API +``` + +이 구조가 성립하면 내부 runtime이 복잡하다는 사실은 문제가 아니다. + +오히려 복잡한 기술 문제를 한 곳에서 해결했기 때문에 각 제품 feature는 더 단순해진다. + +--- + +## 20. 우선순위 요약 + +| 우선순위 | Finding | 조치 방향 | +| --- | --- | --- | +| P0 | 테스트가 host `NODE_ENV` 영향을 받음 | test environment deterministic하게 고정 | +| P0 | unit suite에 systemd/bwrap/cgroup 테스트 혼재 | system/CI-runner suite로 분리 | +| P1 | capability consumer API의 실제 개발 비용이 불명확 | reference + 추가 feature로 사용성 측정 | +| P1 | feature 설치가 여러 중앙 catalog로 확산 | feature-owned contribution + 단순 aggregation | +| P1 | 거대 runtime 내부 책임 추적 비용 | state machine/Saga/lifecycle 기준 extraction | +| P1 | 2K+ LOC test file 다수 | behavior contract별 suite 분리 | +| P1 | `contracts`가 generic bucket으로 성장 가능 | ownership 기준 재배치 | +| P1 | product dev path와 CI assurance path가 뒤섞임 | command/test prerequisite 격리 | +| P2 | `ApplicationApi`의 Service Locator 성장 위험 | narrow consumer hooks/API | +| P2 | feature mutation policy 중복 | feature-owned definition SSOT | +| P2 | compatibility/re-export 경로 | canonical public API 지정 | +| P2 | hybrid architecture 설명 부족 | platform horizontal + feature vertical 공식화 | + +--- + +## 21. 이번 검토에서 확인한 검증 결과 + +코드 변경 전 기준선에서 확인한 결과다. + +```text +check:architecture +→ PASS +→ 307 modules / 929 dependencies +``` + +앞선 검토에서 다음도 통과했다. + +```text +check:types +→ PASS + +lint +→ PASS +``` + +Component test는 host environment를 그대로 사용하면 실패했다. + +```text +pnpm test:component +→ FAIL +→ React.act is not a function +→ host NODE_ENV=production +``` + +동일 checkout에서 test environment를 명시하면 통과했다. + +```text +NODE_ENV=test pnpm test:component +→ 20 files PASS +→ 130 tests PASS +``` + +Unit 전체는 현재 Coka host에서 green이 아니다. + +```text +pnpm test:unit +→ FAIL +→ 99 failures +``` + +대표 원인은 다음이다. + +- `/usr/bin/bwrap` 미설치 +- systemd bus 사용 불가 +- host `npm_config_*` 환경 오염 + +따라서 이 결과를 application/domain regression 99건으로 해석하면 안 된다. + +또한 저장소가 요구하는 Node 범위는 `>=24.11.0 <25.0.0`인데, 현재 Coka host는 Node `22.23.2`다. 정식 full verification은 지원 Node 환경에서 다시 수행해야 한다. + +--- + +## 22. 최종 평가 + +현재 저장소는 설계가 부족해서 문제가 생긴 코드베이스가 아니다. + +오히려 반대다. + +**실제 브라우저와 네트워크에서 발생할 수 있는 많은 실패를 플랫폼이 직접 책임지려 하면서 내부 correctness와 assurance가 매우 강해졌고, 그 결과 플랫폼 사용성과 유지보수 비용이 다음 병목이 된 상태**다. + +따라서 앞으로의 리팩터링 목표는 abstraction을 더 추가하는 것이 아니다. + +다음 세 가지가 핵심이다. + +1. **비즈니스 개발자가 보는 API를 더 작게 만든다.** +2. **플랫폼 내부의 복잡성은 capability boundary 안에서 더 명확하게 격리한다.** +3. **테스트와 CI를 실제 실행 성격에 맞게 분리해 검증 결과를 신뢰할 수 있게 만든다.** + +특히 이 프로젝트의 성공 여부는 “몇 개의 capability를 구현했는가”보다 다음 질문으로 판단해야 한다. + +> 새로운 비즈니스 기능을 구현할 때, 개발자가 domain과 use case에 집중한 채 이미 구현된 capability를 타입 안전하게 조립할 수 있는가? + +그 답이 지속적으로 `예`가 되도록 만드는 것이 이후 리팩터링의 기준이 되어야 한다. diff --git a/docs/reviews/adapters/INVENTORY.md b/docs/reviews/adapters/INVENTORY.md index ccfa8bf..48a0c0f 100644 --- a/docs/reviews/adapters/INVENTORY.md +++ b/docs/reviews/adapters/INVENTORY.md @@ -9,127 +9,140 @@ | # | full path | 상세 리뷰 | | ---: | --- | --- | | 1 | `src/adapters/auth/external-session-adapter.ts` | [Network/state](./01-network-and-state.md) | -| 2 | `src/adapters/browser-file-storage/index.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 3 | `src/adapters/browser-file-storage/result.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 4 | `src/adapters/browser-file-storage/storage-manager-adapter.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 5 | `src/adapters/browser-files/browser-file-picker.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 6 | `src/adapters/browser-files/browser-file-policy-registry.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 7 | `src/adapters/browser-files/browser-file-vault.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 8 | `src/adapters/browser-files/create-browser-file-runtime.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 9 | `src/adapters/browser-files/download-delivery-adapter.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 10 | `src/adapters/browser-files/file-observer.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 11 | `src/adapters/browser-files/file-policy.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 12 | `src/adapters/browser-files/index.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 13 | `src/adapters/browser-files/object-url-lease.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 14 | `src/adapters/browser-rpc/browser-rpc-runtime.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | -| 15 | `src/adapters/browser-rpc/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | -| 16 | `src/adapters/browser-rpc/transport.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | -| 17 | `src/adapters/browser-rpc/unavailable-browser-rpc-transport.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | -| 18 | `src/adapters/browser-transfer/image-cdn/README.md` | [Browser transfer](./04-browser-transfer.md) | -| 19 | `src/adapters/browser-transfer/image-cdn/browser-image-probe.ts` | [Browser transfer](./04-browser-transfer.md) | -| 20 | `src/adapters/browser-transfer/image-cdn/image-cdn-policy.ts` | [Browser transfer](./04-browser-transfer.md) | -| 21 | `src/adapters/browser-transfer/image-cdn/image-cdn-runtime.ts` | [Browser transfer](./04-browser-transfer.md) | -| 22 | `src/adapters/browser-transfer/image-cdn/image-header-metadata.ts` | [Browser transfer](./04-browser-transfer.md) | -| 23 | `src/adapters/browser-transfer/image-cdn/index.ts` | [Browser transfer](./04-browser-transfer.md) | -| 24 | `src/adapters/browser-transfer/image-cdn/p256-image-capability-verifier.ts` | [Browser transfer](./04-browser-transfer.md) | -| 25 | `src/adapters/browser-transfer/index.ts` | [Browser transfer](./04-browser-transfer.md) | -| 26 | `src/adapters/browser-transfer/presigned/incremental-sha256.ts` | [Browser transfer](./04-browser-transfer.md) | -| 27 | `src/adapters/browser-transfer/presigned/index.ts` | [Browser transfer](./04-browser-transfer.md) | -| 28 | `src/adapters/browser-transfer/presigned/presigned-capability-http-provider.ts` | [Browser transfer](./04-browser-transfer.md) | -| 29 | `src/adapters/browser-transfer/presigned/presigned-capability-vault.ts` | [Browser transfer](./04-browser-transfer.md) | -| 30 | `src/adapters/browser-transfer/presigned/presigned-transfer-executor.ts` | [Browser transfer](./04-browser-transfer.md) | -| 31 | `src/adapters/browser-transfer/resumable-upload/checkpoint-schema.ts` | [Browser transfer](./04-browser-transfer.md) | -| 32 | `src/adapters/browser-transfer/resumable-upload/fetch-json-transport.ts` | [Browser transfer](./04-browser-transfer.md) | -| 33 | `src/adapters/browser-transfer/resumable-upload/http-control-plane-adapter.ts` | [Browser transfer](./04-browser-transfer.md) | -| 34 | `src/adapters/browser-transfer/resumable-upload/index.ts` | [Browser transfer](./04-browser-transfer.md) | -| 35 | `src/adapters/browser-transfer/resumable-upload/indexeddb-checkpoint-store.ts` | [Browser transfer](./04-browser-transfer.md) | -| 36 | `src/adapters/browser-transfer/resumable-upload/presigned-upload-part-executor.ts` | [Browser transfer](./04-browser-transfer.md) | -| 37 | `src/adapters/browser-transfer/resumable-upload/resumable-upload-runtime.ts` | [Browser transfer](./04-browser-transfer.md) | -| 38 | `src/adapters/browser-transfer/resumable-upload/runtime-policy.ts` | [Browser transfer](./04-browser-transfer.md) | -| 39 | `src/adapters/browser-transfer/resumable-upload/upload-byte-source.ts` | [Browser transfer](./04-browser-transfer.md) | -| 40 | `src/adapters/browser-transfer/resumable-upload/upload-cancellation-channel.ts` | [Browser transfer](./04-browser-transfer.md) | -| 41 | `src/adapters/browser-transfer/resumable-upload/upload-mutation-lock.ts` | [Browser transfer](./04-browser-transfer.md) | -| 42 | `src/adapters/cache-storage/index.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 43 | `src/adapters/cache-storage/public-cache-policy.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 44 | `src/adapters/cache-storage/public-response-cache-adapter.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 45 | `src/adapters/cross-context-invalidation/browser-cross-context-host.ts` | [Network/state](./01-network-and-state.md) | -| 46 | `src/adapters/cross-context-invalidation/browser-cross-context-invalidation.ts` | [Network/state](./01-network-and-state.md) | -| 47 | `src/adapters/cross-context-invalidation/index.ts` | [Network/state](./01-network-and-state.md) | -| 48 | `src/adapters/diagnostics/bounded-diagnostics.ts` | [Network/state](./01-network-and-state.md) | -| 49 | `src/adapters/http/bounded-body-reader.ts` | [Network/state](./01-network-and-state.md) | -| 50 | `src/adapters/http/bounded-json.ts` | [Network/state](./01-network-and-state.md) | -| 51 | `src/adapters/http/client.ts` | [Network/state](./01-network-and-state.md) | -| 52 | `src/adapters/http/http-contract-bridge.ts` | [Network/state](./01-network-and-state.md) | -| 53 | `src/adapters/http/http-effect-certainty.ts` | [Network/state](./01-network-and-state.md) | -| 54 | `src/adapters/http/http-execution-v3.ts` | [Network/state](./01-network-and-state.md) | -| 55 | `src/adapters/http/request-builder.ts` | [Network/state](./01-network-and-state.md) | -| 56 | `src/adapters/http/resource-mapper.ts` | [Network/state](./01-network-and-state.md) | -| 57 | `src/adapters/http/retry-policy.ts` | [Network/state](./01-network-and-state.md) | -| 58 | `src/adapters/http/schema-registry.ts` | [Network/state](./01-network-and-state.md) | -| 59 | `src/adapters/platform/abortable-operation.ts` | [Network/state](./01-network-and-state.md) | -| 60 | `src/adapters/platform/browser-lifecycle.ts` | [Network/state](./01-network-and-state.md) | -| 61 | `src/adapters/platform/browser-mutation-intent-factory.ts` | [Network/state](./01-network-and-state.md) | -| 62 | `src/adapters/platform/bounded-capacity.ts` | [Network/state](./01-network-and-state.md) | -| 63 | `src/adapters/platform/system-clock.ts` | [Network/state](./01-network-and-state.md) | -| 64 | `src/adapters/query-cache/conditional-validator-store.ts` | [Network/state](./01-network-and-state.md) | -| 65 | `src/adapters/query-cache/cursor-pagination-runtime.ts` | [Network/state](./01-network-and-state.md) | -| 66 | `src/adapters/query-cache/server-state-scope-runtime.ts` | [Network/state](./01-network-and-state.md) | -| 67 | `src/adapters/query-cache/tanstack-cache-coordinator.ts` | [Network/state](./01-network-and-state.md) | -| 68 | `src/adapters/query-cache/tanstack-query-cache.ts` | [Network/state](./01-network-and-state.md) | -| 69 | `src/adapters/realtime/event-codec.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | -| 70 | `src/adapters/realtime/event-consumer.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | -| 71 | `src/adapters/realtime/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | -| 72 | `src/adapters/realtime/json-member-scanner.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | -| 73 | `src/adapters/realtime/live-poll-handoff-coordinator.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | -| 74 | `src/adapters/realtime/polling/bounded-poll-coordinator.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | -| 75 | `src/adapters/realtime/polling/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | -| 76 | `src/adapters/realtime/reconnect-coordinator.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | -| 77 | `src/adapters/realtime/reconnect-policy.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | -| 78 | `src/adapters/realtime/result.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | -| 79 | `src/adapters/realtime/sse/fetch-sse-connection.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | -| 80 | `src/adapters/realtime/sse/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | -| 81 | `src/adapters/realtime/sse/sse-parser.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | -| 82 | `src/adapters/realtime/stream-coordinator.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | -| 83 | `src/adapters/realtime/websocket/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | -| 84 | `src/adapters/realtime/websocket/websocket-connection.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | -| 85 | `src/adapters/realtime/websocket/websocket-protocol.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | -| 86 | `src/adapters/service-worker/service-worker-entry.ts` | [Worker/push](./05-service-worker-and-web-push.md) | -| 87 | `src/adapters/service-worker/service-worker-lifecycle.ts` | [Worker/push](./05-service-worker-and-web-push.md) | -| 88 | `src/adapters/service-worker/service-worker-page-controller.ts` | [Worker/push](./05-service-worker-and-web-push.md) | -| 89 | `src/adapters/service-worker/service-worker-protocol.ts` | [Worker/push](./05-service-worker-and-web-push.md) | -| 90 | `src/adapters/service-worker/service-worker-removal.ts` | [Worker/push](./05-service-worker-and-web-push.md) | -| 91 | `src/adapters/service-worker/service-worker-static-assets.ts` | [Worker/push](./05-service-worker-and-web-push.md) | -| 92 | `src/adapters/storage/browser-storage-adapter.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 93 | `src/adapters/storage/browser-storage-codec.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 94 | `src/adapters/storage/indexeddb/index.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 95 | `src/adapters/storage/indexeddb/indexeddb-failure.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 96 | `src/adapters/storage/indexeddb/indexeddb-governance.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 97 | `src/adapters/storage/indexeddb/indexeddb-maintenance.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 98 | `src/adapters/storage/indexeddb/indexeddb-migrations.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 99 | `src/adapters/storage/indexeddb/indexeddb-runtime.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 100 | `src/adapters/storage/indexeddb/indexeddb-types.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 101 | `src/adapters/storage/opfs/browser-opfs-runtime.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 102 | `src/adapters/storage/opfs/index.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 103 | `src/adapters/storage/opfs/indexeddb-opfs-journal.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 104 | `src/adapters/storage/opfs/opfs-byte-store-adapter.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 105 | `src/adapters/storage/opfs/opfs-policy.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 106 | `src/adapters/storage/opfs/opfs-worker-client.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 107 | `src/adapters/storage/opfs/opfs-worker-protocol.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 108 | `src/adapters/storage/opfs/opfs-worker-runtime.ts` | [Storage/files](./03-storage-and-browser-files.md) | -| 109 | `src/adapters/telemetry/best-effort-telemetry.ts` | [Network/state](./01-network-and-state.md) | -| 110 | `src/adapters/web-push/inbound/notification-click-adapter.ts` | [Worker/push](./05-service-worker-and-web-push.md) | -| 111 | `src/adapters/web-push/inbound/push-event-adapter.ts` | [Worker/push](./05-service-worker-and-web-push.md) | -| 112 | `src/adapters/web-push/index.ts` | [Worker/push](./05-service-worker-and-web-push.md) | -| 113 | `src/adapters/web-push/notification-registry.ts` | [Worker/push](./05-service-worker-and-web-push.md) | -| 114 | `src/adapters/web-push/push-association-fence-store.ts` | [Worker/push](./05-service-worker-and-web-push.md) | -| 115 | `src/adapters/web-push/push-codec.ts` | [Worker/push](./05-service-worker-and-web-push.md) | -| 116 | `src/adapters/web-push/push-registration-gateway.ts` | [Worker/push](./05-service-worker-and-web-push.md) | -| 117 | `src/adapters/web-push/push-subscription-adapter.ts` | [Worker/push](./05-service-worker-and-web-push.md) | -| 118 | `src/adapters/web-push/runtime-support.ts` | [Worker/push](./05-service-worker-and-web-push.md) | -| 119 | `src/adapters/web-push/service-worker-runtime.ts` | [Worker/push](./05-service-worker-and-web-push.md) | -| 120 | `src/adapters/web-push/service-worker-scope-host.ts` | [Worker/push](./05-service-worker-and-web-push.md) | +| 2 | `src/adapters/auth/index.ts` | [Network/state](./01-network-and-state.md) | +| 3 | `src/adapters/browser-file-storage/index.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 4 | `src/adapters/browser-file-storage/result.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 5 | `src/adapters/browser-file-storage/storage-manager-adapter.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 6 | `src/adapters/browser-files/browser-file-picker.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 7 | `src/adapters/browser-files/browser-file-policy-registry.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 8 | `src/adapters/browser-files/browser-file-vault.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 9 | `src/adapters/browser-files/create-browser-file-runtime.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 10 | `src/adapters/browser-files/download-delivery-adapter.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 11 | `src/adapters/browser-files/file-observer.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 12 | `src/adapters/browser-files/file-policy.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 13 | `src/adapters/browser-files/index.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 14 | `src/adapters/browser-files/object-url-lease.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 15 | `src/adapters/browser-rpc/browser-rpc-runtime.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | +| 16 | `src/adapters/browser-rpc/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | +| 17 | `src/adapters/browser-rpc/transport.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | +| 18 | `src/adapters/browser-rpc/unavailable-browser-rpc-transport.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | +| 19 | `src/adapters/browser-transfer/image-cdn/README.md` | [Browser transfer](./04-browser-transfer.md) | +| 20 | `src/adapters/browser-transfer/image-cdn/browser-image-probe.ts` | [Browser transfer](./04-browser-transfer.md) | +| 21 | `src/adapters/browser-transfer/image-cdn/image-cdn-policy.ts` | [Browser transfer](./04-browser-transfer.md) | +| 22 | `src/adapters/browser-transfer/image-cdn/image-cdn-runtime.ts` | [Browser transfer](./04-browser-transfer.md) | +| 23 | `src/adapters/browser-transfer/image-cdn/image-header-metadata.ts` | [Browser transfer](./04-browser-transfer.md) | +| 24 | `src/adapters/browser-transfer/image-cdn/index.ts` | [Browser transfer](./04-browser-transfer.md) | +| 25 | `src/adapters/browser-transfer/image-cdn/p256-image-capability-verifier.ts` | [Browser transfer](./04-browser-transfer.md) | +| 26 | `src/adapters/browser-transfer/index.ts` | [Browser transfer](./04-browser-transfer.md) | +| 27 | `src/adapters/browser-transfer/presigned/incremental-sha256.ts` | [Browser transfer](./04-browser-transfer.md) | +| 28 | `src/adapters/browser-transfer/presigned/index.ts` | [Browser transfer](./04-browser-transfer.md) | +| 29 | `src/adapters/browser-transfer/presigned/presigned-capability-http-provider.ts` | [Browser transfer](./04-browser-transfer.md) | +| 30 | `src/adapters/browser-transfer/presigned/presigned-capability-vault.ts` | [Browser transfer](./04-browser-transfer.md) | +| 31 | `src/adapters/browser-transfer/presigned/presigned-transfer-executor.ts` | [Browser transfer](./04-browser-transfer.md) | +| 32 | `src/adapters/browser-transfer/resumable-upload/checkpoint-schema.ts` | [Browser transfer](./04-browser-transfer.md) | +| 33 | `src/adapters/browser-transfer/resumable-upload/fetch-json-transport.ts` | [Browser transfer](./04-browser-transfer.md) | +| 34 | `src/adapters/browser-transfer/resumable-upload/http-control-plane-adapter.ts` | [Browser transfer](./04-browser-transfer.md) | +| 35 | `src/adapters/browser-transfer/resumable-upload/index.ts` | [Browser transfer](./04-browser-transfer.md) | +| 36 | `src/adapters/browser-transfer/resumable-upload/indexeddb-checkpoint-store.ts` | [Browser transfer](./04-browser-transfer.md) | +| 37 | `src/adapters/browser-transfer/resumable-upload/presigned-upload-part-executor.ts` | [Browser transfer](./04-browser-transfer.md) | +| 38 | `src/adapters/browser-transfer/resumable-upload/resumable-upload-runtime.ts` | [Browser transfer](./04-browser-transfer.md) | +| 39 | `src/adapters/browser-transfer/resumable-upload/runtime-policy.ts` | [Browser transfer](./04-browser-transfer.md) | +| 40 | `src/adapters/browser-transfer/resumable-upload/upload-byte-source.ts` | [Browser transfer](./04-browser-transfer.md) | +| 41 | `src/adapters/browser-transfer/resumable-upload/upload-cancellation-channel.ts` | [Browser transfer](./04-browser-transfer.md) | +| 42 | `src/adapters/browser-transfer/resumable-upload/upload-mutation-lock.ts` | [Browser transfer](./04-browser-transfer.md) | +| 43 | `src/adapters/cache-storage/index.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 44 | `src/adapters/cache-storage/public-cache-policy.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 45 | `src/adapters/cache-storage/public-response-cache-adapter.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 46 | `src/adapters/cross-context-invalidation/browser-cross-context-host.ts` | [Network/state](./01-network-and-state.md) | +| 47 | `src/adapters/cross-context-invalidation/browser-cross-context-invalidation.ts` | [Network/state](./01-network-and-state.md) | +| 48 | `src/adapters/cross-context-invalidation/index.ts` | [Network/state](./01-network-and-state.md) | +| 49 | `src/adapters/diagnostics/bounded-diagnostics.ts` | [Network/state](./01-network-and-state.md) | +| 50 | `src/adapters/diagnostics/index.ts` | [Network/state](./01-network-and-state.md) | +| 51 | `src/adapters/http/bounded-body-reader.ts` | [Network/state](./01-network-and-state.md) | +| 52 | `src/adapters/http/bounded-json.ts` | [Network/state](./01-network-and-state.md) | +| 53 | `src/adapters/http/client.ts` | [Network/state](./01-network-and-state.md) | +| 54 | `src/adapters/http/feature-http-binding.ts` | [Network/state](./01-network-and-state.md) | +| 55 | `src/adapters/http/http-contract-bridge.ts` | [Network/state](./01-network-and-state.md) | +| 56 | `src/adapters/http/http-effect-certainty.ts` | [Network/state](./01-network-and-state.md) | +| 57 | `src/adapters/http/http-execution-v3.ts` | [Network/state](./01-network-and-state.md) | +| 58 | `src/adapters/http/http-retry-lifecycle.ts` | [Network/state](./01-network-and-state.md) | +| 59 | `src/adapters/http/index.ts` | [Network/state](./01-network-and-state.md) | +| 60 | `src/adapters/http/request-builder.ts` | [Network/state](./01-network-and-state.md) | +| 61 | `src/adapters/http/resource-mapper.ts` | [Network/state](./01-network-and-state.md) | +| 62 | `src/adapters/http/retry-policy.ts` | [Network/state](./01-network-and-state.md) | +| 63 | `src/adapters/http/schema-registry.ts` | [Network/state](./01-network-and-state.md) | +| 64 | `src/adapters/platform/abortable-operation.ts` | [Network/state](./01-network-and-state.md) | +| 65 | `src/adapters/platform/bounded-capacity.ts` | [Network/state](./01-network-and-state.md) | +| 66 | `src/adapters/platform/browser-lifecycle.ts` | [Network/state](./01-network-and-state.md) | +| 67 | `src/adapters/platform/browser-mutation-intent-factory.ts` | [Network/state](./01-network-and-state.md) | +| 68 | `src/adapters/platform/index.ts` | [Network/state](./01-network-and-state.md) | +| 69 | `src/adapters/platform/indexeddb-connection.ts` | [Network/state](./01-network-and-state.md) | +| 70 | `src/adapters/platform/indexeddb-transaction.ts` | [Network/state](./01-network-and-state.md) | +| 71 | `src/adapters/platform/system-clock.ts` | [Network/state](./01-network-and-state.md) | +| 72 | `src/adapters/query-cache/conditional-validator-store.ts` | [Network/state](./01-network-and-state.md) | +| 73 | `src/adapters/query-cache/cursor-pagination-contract.ts` | [Network/state](./01-network-and-state.md) | +| 74 | `src/adapters/query-cache/cursor-pagination-runtime.ts` | [Network/state](./01-network-and-state.md) | +| 75 | `src/adapters/query-cache/index.ts` | [Network/state](./01-network-and-state.md) | +| 76 | `src/adapters/query-cache/server-state-scope-runtime.ts` | [Network/state](./01-network-and-state.md) | +| 77 | `src/adapters/query-cache/tanstack-cache-coordinator.ts` | [Network/state](./01-network-and-state.md) | +| 78 | `src/adapters/query-cache/tanstack-query-cache.ts` | [Network/state](./01-network-and-state.md) | +| 79 | `src/adapters/realtime/event-codec.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | +| 80 | `src/adapters/realtime/event-consumer.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | +| 81 | `src/adapters/realtime/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | +| 82 | `src/adapters/realtime/json-member-scanner.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | +| 83 | `src/adapters/realtime/live-poll-handoff-coordinator.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | +| 84 | `src/adapters/realtime/polling/bounded-poll-coordinator.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | +| 85 | `src/adapters/realtime/polling/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | +| 86 | `src/adapters/realtime/reconnect-coordinator.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | +| 87 | `src/adapters/realtime/reconnect-policy.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | +| 88 | `src/adapters/realtime/result.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | +| 89 | `src/adapters/realtime/sse/fetch-sse-connection.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | +| 90 | `src/adapters/realtime/sse/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | +| 91 | `src/adapters/realtime/sse/sse-parser.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | +| 92 | `src/adapters/realtime/stream-coordinator.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | +| 93 | `src/adapters/realtime/websocket/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | +| 94 | `src/adapters/realtime/websocket/websocket-connection.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | +| 95 | `src/adapters/realtime/websocket/websocket-protocol.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) | +| 96 | `src/adapters/service-worker/index.ts` | [Worker/push](./05-service-worker-and-web-push.md) | +| 97 | `src/adapters/service-worker/service-worker-entry.ts` | [Worker/push](./05-service-worker-and-web-push.md) | +| 98 | `src/adapters/service-worker/service-worker-lifecycle.ts` | [Worker/push](./05-service-worker-and-web-push.md) | +| 99 | `src/adapters/service-worker/service-worker-page-controller.ts` | [Worker/push](./05-service-worker-and-web-push.md) | +| 100 | `src/adapters/service-worker/service-worker-protocol.ts` | [Worker/push](./05-service-worker-and-web-push.md) | +| 101 | `src/adapters/service-worker/service-worker-removal.ts` | [Worker/push](./05-service-worker-and-web-push.md) | +| 102 | `src/adapters/service-worker/service-worker-static-assets.ts` | [Worker/push](./05-service-worker-and-web-push.md) | +| 103 | `src/adapters/storage/browser-storage-adapter.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 104 | `src/adapters/storage/browser-storage-codec.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 105 | `src/adapters/storage/index.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 106 | `src/adapters/storage/indexeddb/index.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 107 | `src/adapters/storage/indexeddb/indexeddb-failure.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 108 | `src/adapters/storage/indexeddb/indexeddb-governance.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 109 | `src/adapters/storage/indexeddb/indexeddb-maintenance.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 110 | `src/adapters/storage/indexeddb/indexeddb-migrations.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 111 | `src/adapters/storage/indexeddb/indexeddb-runtime.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 112 | `src/adapters/storage/indexeddb/indexeddb-types.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 113 | `src/adapters/storage/opfs/browser-opfs-runtime.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 114 | `src/adapters/storage/opfs/index.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 115 | `src/adapters/storage/opfs/indexeddb-opfs-journal.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 116 | `src/adapters/storage/opfs/opfs-byte-store-adapter.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 117 | `src/adapters/storage/opfs/opfs-policy.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 118 | `src/adapters/storage/opfs/opfs-worker-client.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 119 | `src/adapters/storage/opfs/opfs-worker-protocol.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 120 | `src/adapters/storage/opfs/opfs-worker-runtime.ts` | [Storage/files](./03-storage-and-browser-files.md) | +| 121 | `src/adapters/telemetry/best-effort-telemetry.ts` | [Network/state](./01-network-and-state.md) | +| 122 | `src/adapters/telemetry/index.ts` | [Network/state](./01-network-and-state.md) | +| 123 | `src/adapters/web-push/inbound/notification-click-adapter.ts` | [Worker/push](./05-service-worker-and-web-push.md) | +| 124 | `src/adapters/web-push/inbound/push-event-adapter.ts` | [Worker/push](./05-service-worker-and-web-push.md) | +| 125 | `src/adapters/web-push/index.ts` | [Worker/push](./05-service-worker-and-web-push.md) | +| 126 | `src/adapters/web-push/notification-registry.ts` | [Worker/push](./05-service-worker-and-web-push.md) | +| 127 | `src/adapters/web-push/push-association-fence-store.ts` | [Worker/push](./05-service-worker-and-web-push.md) | +| 128 | `src/adapters/web-push/push-codec.ts` | [Worker/push](./05-service-worker-and-web-push.md) | +| 129 | `src/adapters/web-push/push-registration-gateway.ts` | [Worker/push](./05-service-worker-and-web-push.md) | +| 130 | `src/adapters/web-push/push-subscription-adapter.ts` | [Worker/push](./05-service-worker-and-web-push.md) | +| 131 | `src/adapters/web-push/runtime-support.ts` | [Worker/push](./05-service-worker-and-web-push.md) | +| 132 | `src/adapters/web-push/service-worker-runtime.ts` | [Worker/push](./05-service-worker-and-web-push.md) | +| 133 | `src/adapters/web-push/service-worker-scope-host.ts` | [Worker/push](./05-service-worker-and-web-push.md) | -합계: **120/120**. 새 adapter 파일이 추가되면 이 ledger와 해당 상세 리뷰 inventory를 같은 변경에서 갱신한다. +합계: **133/133**. 새 adapter 파일이 추가되면 이 ledger와 해당 상세 리뷰 inventory를 같은 변경에서 갱신한다. ## Feature-scoped adapter 리뷰 (`src/adapters/**` 밖) diff --git a/docs/reviews/adapters/README.md b/docs/reviews/adapters/README.md index 3a35e1a..1c70e9b 100644 --- a/docs/reviews/adapters/README.md +++ b/docs/reviews/adapters/README.md @@ -133,3 +133,15 @@ listener/timer 정리, first-terminal-owner, late rejection 관찰, late native - cleanup 실패를 observation만 남기고 success로 바꾸지 않는다. - schema/database version을 downgrade하거나 broad prefix/root/database 전체 삭제를 rollback으로 사용하지 않는다. - SSE↔WebSocket, Connect↔gRPC-Web↔REST를 장애 중 자동 전환하지 않는다. + +## 테스트의 어댑터 import + +`tests/` 아래 어댑터 import는 배럴로 일괄 이관하지 않는다. `check:architecture`는 +`src`만 스캔하므로 강제되지 않고, 단위 테스트의 상당수가 배럴에 없는 내부 +심볼을 의도적으로 겨눈다. + +어떤 테스트 파일을 **다른 이유로** 수정하거나 분할할 때, 그 파일이 쓰는 +심볼이 해당 그룹 배럴에 있으면 그 파일 안에서만 배럴 경로로 바꾼다. +배럴에 없는 심볼이면 깊은 경로를 유지한다. 배럴에 추가하고 싶으면 그 심볼이 +공개 표면임을 먼저 논증한다 — 테스트 편의로 배럴을 키우면 배럴이 경계가 +아니라 재수출 덤프가 된다. diff --git a/docs/superpowers/plans/2026-09-16-adapter-barrel-boundary.md b/docs/superpowers/plans/2026-09-16-adapter-barrel-boundary.md new file mode 100644 index 0000000..b9968a9 --- /dev/null +++ b/docs/superpowers/plans/2026-09-16-adapter-barrel-boundary.md @@ -0,0 +1,712 @@ +# 어댑터 배럴 공개 경계 확립 Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** 어댑터 16개 그룹 전부에 `index.ts` 공개 경계를 세우고, 그룹 바깥은 배럴만 import하도록 게이트로 강제한다. + +**Architecture:** 각 어댑터 그룹의 `index.ts`가 그 그룹의 공개 표면이 된다. 그룹 내부 파일끼리, 그리고 어댑터→커널(`platform/**`) 간선은 지금처럼 파일 직접 import를 유지한다 — 커널의 정체성은 파일이고 `check:adapter-inventory`가 그것을 파일 경로로 검증하기 때문이다. `.dependency-cruiser.json`에 규칙 하나를 추가하고 회귀 fixture로 그 거부를 고정한다. + +**Tech Stack:** TypeScript (NodeNext/Bundler), dependency-cruiser, 자체 TypeScript 인지 import 그래프(`scripts/check-architecture.ts`), Vite, Vitest + +**Spec:** [`docs/superpowers/specs/2026-09-16-adapter-barrel-boundary-design.md`](../specs/2026-09-16-adapter-barrel-boundary-design.md) + +## Global Constraints + +- 기준선(2026-09-16, `develop` `5434760`): `check:architecture` PASS(297 모듈 / 897 의존 / 미해결 0), `check:types:app` PASS, `check:adapter-inventory` PASS(120 파일). **이 셋을 깨면 안 된다.** +- `docs/reviews/adapters/INVENTORY.md`는 `git ls-files src/adapters`와 **집합이 정확히 일치**해야 한다. 소스 파일을 추가/이동하면 같은 커밋에서 이 표와 하단 합계를 고친다. +- 어댑터→커널 import는 **파일 직접 경로를 유지**한다. `scripts/check-adapter-inventory.ts:63-83`이 4개 소비자에게 `platform/abortable-operation.ts`로 해석되는 specifier를 정규식으로 요구한다. +- `src/adapters/storage/index.ts`는 `indexeddb/`·`opfs/` 서브배럴을 **재수출하지 않는다.** `scripts/test-browser-file-storage-runtime-removal.ts:23-34`가 그 두 폴더만 삭제한 뒤 잔존 import를 예외로 잡는다. +- `src/adapters/service-worker/index.ts`는 `service-worker-entry.ts`를 참조하지 않는다. `tsconfig.app.json:18`이 제외한 파일이다. +- 번들 예산: `config/performance/budgets.json`의 `bundle.initialJsGzipBytes = 204800`. +- 프로젝트 소스는 TypeScript/TSX만. `allowJs` 비활성. 로컬 import는 명시적 `.ts`/`.tsx` 확장자 필수. +- 커밋 메시지 끝에 붙일 것: + `Co-Authored-By: Claude Opus 5 (1M context) ` + +--- + +### Task 1: 배럴 8개 생성 + INVENTORY 등록 + +없는 8개 그룹에 `index.ts`를 만든다. 이 태스크는 **파일 추가만** 한다 — 기존 import는 건드리지 않으므로 런타임 동작이 바뀌지 않는다. + +**Files:** +- Create: `src/adapters/auth/index.ts` +- Create: `src/adapters/diagnostics/index.ts` +- Create: `src/adapters/telemetry/index.ts` +- Create: `src/adapters/platform/index.ts` +- Create: `src/adapters/query-cache/index.ts` +- Create: `src/adapters/service-worker/index.ts` +- Create: `src/adapters/storage/index.ts` +- Create: `src/adapters/http/index.ts` +- Modify: `docs/reviews/adapters/INVENTORY.md` (행 8개 추가 + 합계) + +**Interfaces:** +- Produces: 위 8개 배럴이 내보내는 심볼 82개. Task 2가 이 경로들로 import를 바꾼다. 심볼 존재는 spec §7에서 82/82 기계 대조 완료(누락 0, 오타 0). +- Consumes: 없음 (첫 태스크) + +- [x] **Step 1: 배럴 5개 생성 (단일 파일 그룹 + query-cache)** + +`src/adapters/auth/index.ts`: +```ts +export { + createAnonymousSessionAdapter, + createDemoSessionAdapter, + createExternalAuthSessionAdapter, + createUnavailableSessionAdapter, + DEMO_AUTHORIZATION_MARKER, + type DemoSessionAdapter, + type ExternalSessionOwner, +} from "./external-session-adapter.ts"; +``` + +`src/adapters/diagnostics/index.ts`: +```ts +export { + createDiagnosticsAdapter, + getLastBootEvidence, + MAX_DIAGNOSTIC_ENTRIES, + noOpDiagnostics, + recordBootFailure, +} from "./bounded-diagnostics.ts"; +``` + +`src/adapters/telemetry/index.ts`: +```ts +export { + createTelemetryAdapter, + MAX_TELEMETRY_QUEUE, + noOpTelemetry, + type TelemetryAdapter, + type TelemetryAdapterOptions, +} from "./best-effort-telemetry.ts"; +``` + +`src/adapters/storage/index.ts`: +```ts +/** + * 최상위 storage 배럴은 Web Storage 어댑터만 내보낸다. + * + * `./indexeddb/index.ts`와 `./opfs/index.ts`를 여기서 재수출하지 말 것. + * `scripts/test-browser-file-storage-runtime-removal.ts:23-34`가 그 두 폴더만 + * 삭제한 뒤 잔존 import를 예외로 잡는다 — 재수출하면 제거 드릴이 죽는다. + * 두 서브배럴이 각자 제거 가능한 런타임의 경계다. + */ +export { + createBrowserStorageAdapter, + type BrowserStorageDependencies, +} from "./browser-storage-adapter.ts"; +``` + +`src/adapters/query-cache/index.ts`: +```ts +export { + createConditionalValidatorStore, + type ConditionalValidatorBinding, + type ConditionalValidatorStore, +} from "./conditional-validator-store.ts"; +export { createCursorPaginationRuntime } from "./cursor-pagination-runtime.ts"; +export { + createServerStateScopeRuntime, + type ScopeResetParticipant, + type ServerStateScopeDependencies, +} from "./server-state-scope-runtime.ts"; +export { + createTanStackCacheCoordinator, + type TanStackCacheCoordinatorDependencies, +} from "./tanstack-cache-coordinator.ts"; +export { + createQueryCacheAdapter, + createQueryClient, + QUERY_CACHE_DEFAULTS, + type QueryCacheDependencies, +} from "./tanstack-query-cache.ts"; +``` + +- [x] **Step 2: 배럴 3개 생성 (주석이 계약인 것들)** + +`src/adapters/platform/index.ts`: +```ts +/** + * 어댑터 커널의 공개 경계. + * + * `src/adapters/**` 안에서는 이 배럴을 쓰지 않는다. 커널 프리미티브는 파일 + * 경로로 직접 import한다 — `scripts/check-adapter-inventory.ts:63-83`이 + * `platform/abortable-operation.ts`로 해석되는 specifier를 네 소비자에게 + * 요구하고, `.dependency-cruiser.json`의 kernel carve-out도 폴더 단위다. + * 이 배럴은 bootstrap·features·tests 같은 그룹 바깥 소비자를 위한 문이다. + */ +export { + compensateLateHandle, + createAbortableOperation, + snapshotAbortTimers, + type AbortableOperation, + type AbortableOperationInput, + type AbortRace, + type AbortTerminalReason, + type AbortTimerSnapshot, +} from "./abortable-operation.ts"; +export { assertBoundedCapacity } from "./bounded-capacity.ts"; +export { + createBrowserLifecycleRuntime, + type BrowserLifecycleEvent, + type BrowserLifecycleRuntime, + type BrowserLifecycleSnapshot, +} from "./browser-lifecycle.ts"; +export { + createBrowserMutationIntentFactory, + type BrowserMutationIntentFactoryDependencies, +} from "./browser-mutation-intent-factory.ts"; +export { systemClock } from "./system-clock.ts"; +``` + +`src/adapters/service-worker/index.ts`: +```ts +/** + * `service-worker-entry.ts`는 여기서 참조하지 않는다. `tsconfig.app.json:18`이 + * 제외한 파일이라 참조하면 app 타입체크가 제외 대상을 끌어들인다. 그 파일은 + * export가 0개이므로 넣을 것도 없다. + */ +export { + createServiceWorkerRuntime, + type WorkerClientLike, + type WorkerRuntimeConfig, + type WorkerScopeLike, +} from "./service-worker-lifecycle.ts"; +export { + createServiceWorkerPageController, + type ActivationBlocker, + type PageControllerDependencies, +} from "./service-worker-page-controller.ts"; +export { + createNonceRegistry, + createServiceWorkerMessage, + parseServiceWorkerMessage, + type ParsedMessage, +} from "./service-worker-protocol.ts"; +``` + +`src/adapters/http/index.ts`: +```ts +/** + * §7–§8. 권장 경로는 V3 계약 실행기(`createContractHttpExecutor`)다. 설치된 + * 계약과 타입 입력을 받아 상한·전체 데드라인·재시도 권한·효과 확실성 판정을 + * 런타임이 소유한다. + */ +export { + createContractHttpExecutor, + type AuthIntegrationFailureReason, + type AuthOperationContext, + type CancellationOwner, + type ContractHttpExecutor, + type ContractHttpExecutorDependencies, + type HttpContractViolation, + type HttpContractViolationKind, + type HttpEffectCertainty, + type HttpExecutionContext, + type HttpExecutionObservation, + type HttpExecutionOutcome, + type HttpTransportFailure, + type SafeResponseMetadata, +} from "./http-execution-v3.ts"; +/** V3 `attachCredentials` 콜백이 반환해야 하는 결과 타입. */ +export type { CredentialPatchOutcome } from "./http-contract-bridge.ts"; +/** + * V2 legacy. operationId + `LegacyHttpInput`으로 호출하는 범용 클라이언트다. + * 새 코드는 위의 V3 실행기를 쓴다. 남아 있는 이유는 계약이 아직 없는 + * 오퍼레이션을 위한 이행 경로이기 때문이다. + */ +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"; +``` + +- [x] **Step 3: 타입체크로 심볼 존재를 검증한다** + +Run: `corepack pnpm check:types:app` +Expected: PASS. 실패하면 존재하지 않는 심볼을 재수출한 것이다 — 에러가 지목한 이름을 해당 소스 파일에서 확인하고 배럴에서 빼라. spec §7의 대조표와 대조할 것. + +- [x] **Step 4: 게이트가 새 파일 8개를 거부하는 것을 확인한다 (의도된 실패)** + +Run: `git add -A && corepack pnpm check:adapter-inventory` +Expected: **FAIL.** `git ls-files src/adapters`가 128개를 보고하는데 INVENTORY.md는 120행이므로 불일치를 보고한다. 이 실패를 본 뒤 Step 5로 간다. (실패하지 않으면 `git add`가 안 된 것이다.) + +- [x] **Step 5: INVENTORY.md에 행 8개 추가** + +`docs/reviews/adapters/INVENTORY.md`의 표에 경로 알파벳 순서 위치로 끼워 넣고 번호를 다시 매긴다. 상세 리뷰 링크는 같은 그룹의 기존 행과 동일하게 쓴다. + +| 추가할 경로 | 상세 리뷰 링크 | +|---|---| +| `src/adapters/auth/index.ts` | `[Network/state](./01-network-and-state.md)` | +| `src/adapters/diagnostics/index.ts` | `[Network/state](./01-network-and-state.md)` | +| `src/adapters/http/index.ts` | `[Network/state](./01-network-and-state.md)` | +| `src/adapters/platform/index.ts` | `[Network/state](./01-network-and-state.md)` | +| `src/adapters/query-cache/index.ts` | `[Network/state](./01-network-and-state.md)` | +| `src/adapters/service-worker/index.ts` | `[Worker/push](./05-service-worker-and-web-push.md)` | +| `src/adapters/storage/index.ts` | `[Storage/files](./03-storage-and-browser-files.md)` | +| `src/adapters/telemetry/index.ts` | `[Network/state](./01-network-and-state.md)` | + +그리고 `docs/reviews/adapters/INVENTORY.md:132`의 `합계: **120/120**` → `합계: **128/128**`. + +- [x] **Step 6: 게이트 3종 통과 확인** + +Run: `corepack pnpm check:adapter-inventory && corepack pnpm check:types:app && corepack pnpm check:architecture` +Expected: 셋 다 PASS. `check:adapter-inventory`가 `128 files PASS`를 출력한다. + +- [x] **Step 7: 워커 realm 타입체크 — 실행 중 발견한 필수 단계** + +> 2026-09-16 실행 중 발견. 계획 초안에는 없었다. +> `tsconfig.service-worker.json`은 `src/adapters/service-worker` 폴더를 통째로 +> WebWorker lib로 컴파일하면서 페이지 realm 파일 2개만 `exclude`로 뺀다. +> 새 `index.ts`가 그 폴더 안에서 `service-worker-page-controller.ts`를 +> import하므로, 제외하지 않으면 페이지 realm 파일이 WebWorker lib 컴파일에 +> 끌려 들어와 `Cannot find name 'document'`로 실패한다. +> (M6 리뷰의 "realm 경계가 폴더가 아니라 tsconfig exclude 2줄로만 표현된다"가 +> 그대로 발현된 것이다.) + +`tsconfig.service-worker.json`의 `exclude` 배열 맨 앞에 추가한다: + +```json + "src/adapters/service-worker/index.ts", +``` + +타입 커버리지는 `tsconfig.app.json`이 이 배럴을 포함하므로 유지된다. 워커 진입점 +`service-worker-entry.ts`는 배럴을 쓰지 않고 파일을 직접 import하므로 워커 번들에 +영향이 없다. + +Run: `corepack pnpm check:types:service-worker` +Expected: PASS + +- [x] **Step 8: 제거 드릴이 살아 있는지 확인한다** + +`storage/index.ts`를 새로 만들었으므로 제거 드릴을 돌려 서브폴더 삭제가 여전히 성립하는지 본다. + +Run: `corepack pnpm test:browser-file-storage-removal` +Expected: 드릴 출력에 `error TS`가 0건이어야 한다. `storage/index.ts`가 `indexeddb/`나 `opfs/`를 참조하면 `still imported`로 죽는다 — Step 1의 주석대로 재수출을 제거하라. + +> **이 환경의 알려진 제약.** `tests/unit/ci-artifact-contract.test.ts`의 16건은 +> `bwrap: loopback: Failed RTM_NEWADDR: Operation not permitted`로 실패한다. +> 샌드박스가 네트워크 네임스페이스를 못 만들기 때문이며 `develop` `5434760` +> 기준선에서도 동일하게 16건 실패한다(2026-09-16 확인). 이 드릴은 내부적으로 +> `test:unit`을 돌리므로 그 16건 때문에 항상 exit 1이 된다. +> **판정 기준은 드릴의 exit code가 아니라 `error TS` 0건과 `still imported` 부재다.** +> CI 환경에서는 전체 PASS를 확인할 것. + +- [x] **Step 9: 커밋** + +```bash +git add src/adapters/*/index.ts docs/reviews/adapters/INVENTORY.md tsconfig.service-worker.json +git commit -m "$(cat <<'EOF' +feat: give every adapter group a public barrel + +각 어댑터 그룹의 공개 표면을 index.ts로 선언한다. 소비자는 아직 바꾸지 +않았으므로 런타임 동작은 그대로다. storage 배럴은 서브배럴을 재수출하지 +않는다 — 제거 드릴이 indexeddb/와 opfs/만 삭제하기 때문이다. + +Co-Authored-By: Claude Opus 5 (1M context) +EOF +)" +``` + +--- + +### Task 2: 그룹 바깥 소비자 15줄을 배럴 경로로 치환 + +**Files:** +- Modify: `src/bootstrap/runtime-adapters.ts:6-29` (12줄, 블록 병합 포함) +- Modify: `src/bootstrap/main.tsx:3` +- Modify: `src/bootstrap/optional-runtime-host.ts:4` +- Modify: `src/bootstrap/register-service-worker.ts:5` +- Modify: `src/features/reference-feature/adapters/create-reference-feature-input.ts:9` +- Modify: `.storybook/preview.tsx:5-6` (게이트 범위 밖, 일관성 목적) + +**Interfaces:** +- Consumes: Task 1이 만든 8개 배럴의 심볼 82개 +- Produces: `src/` 안에 어댑터 내부 파일을 직접 겨누는 import 0건. Task 3의 게이트 규칙이 이 상태를 전제로 통과한다. + +- [x] **Step 1: 치환 전 위반 건수를 기록한다** + +Run: +```bash +grep -rn 'from "[^"]*adapters/[^"]*"' src/ | grep -v '^src/adapters/' | grep -v 'index\.ts"' | wc -l +``` +Expected: `15`. 이 숫자가 Step 4에서 `0`이 되어야 한다. + +- [x] **Step 2: `runtime-adapters.ts`의 import 블록을 다시 쓴다** + +`src/bootstrap/runtime-adapters.ts`의 `:6`~`:29` 구간이 한 덩어리다. 아래에서 위로 편집하거나 블록 전체를 한 번에 교체한다 — 위에서부터 고치면 줄 번호가 밀린다. + +치환 내용: + +| 현재 specifier | 바뀔 specifier | +|---|---| +| `../adapters/auth/external-session-adapter.ts` | `../adapters/auth/index.ts` | +| `../adapters/diagnostics/bounded-diagnostics.ts` | `../adapters/diagnostics/index.ts` | +| `../adapters/http/client.ts` | `../adapters/http/index.ts` | +| `../adapters/http/http-execution-v3.ts` | `../adapters/http/index.ts` (위와 **한 블록으로 병합**) | +| `../adapters/query-cache/tanstack-cache-coordinator.ts` | `../adapters/query-cache/index.ts` | +| `../adapters/query-cache/tanstack-query-cache.ts` | `../adapters/query-cache/index.ts` | +| `../adapters/query-cache/server-state-scope-runtime.ts` | `../adapters/query-cache/index.ts` | +| `../adapters/query-cache/conditional-validator-store.ts` | `../adapters/query-cache/index.ts` (위 넷을 **한 블록으로 병합**) | +| `../adapters/storage/browser-storage-adapter.ts` | `../adapters/storage/index.ts` | +| `../adapters/platform/browser-mutation-intent-factory.ts` | `../adapters/platform/index.ts` | +| `../adapters/telemetry/best-effort-telemetry.ts` | `../adapters/telemetry/index.ts` | + +`../adapters/cross-context-invalidation/index.ts` 2줄은 이미 배럴이므로 **건드리지 않는다.** + +- [x] **Step 3: 나머지 4개 파일을 치환한다** + +| 파일:줄 | 현재 | 바뀔 것 | +|---|---|---| +| `src/bootstrap/main.tsx:3` | `../adapters/diagnostics/bounded-diagnostics.ts` | `../adapters/diagnostics/index.ts` | +| `src/bootstrap/optional-runtime-host.ts:4` | `../adapters/platform/browser-lifecycle.ts` | `../adapters/platform/index.ts` | +| `src/bootstrap/register-service-worker.ts:5` | `../adapters/service-worker/service-worker-page-controller.ts` | `../adapters/service-worker/index.ts` | +| `src/features/reference-feature/adapters/create-reference-feature-input.ts:9` | `../../../adapters/http/http-execution-v3.ts` | `../../../adapters/http/index.ts` | +| `.storybook/preview.tsx:5` | `../src/adapters/auth/external-session-adapter.ts` | `../src/adapters/auth/index.ts` | +| `.storybook/preview.tsx:6` | `../src/adapters/query-cache/tanstack-query-cache.ts` | `../src/adapters/query-cache/index.ts` | + +- [x] **Step 4: 위반이 0이 된 것을 확인한다** + +Run: +```bash +grep -rn 'from "[^"]*adapters/[^"]*"' src/ | grep -v '^src/adapters/' | grep -v 'index\.ts"' | wc -l +``` +Expected: `0` + +- [x] **Step 5: 타입·린트·아키텍처 게이트** + +Run: `corepack pnpm check:types:app && corepack pnpm lint && corepack pnpm check:architecture` +Expected: 셋 다 PASS. + +- [x] **Step 6: 번들 예산을 확인한다 — 이 태스크의 최대 위험** + +배럴 재수출이 트리셰이킹을 무력화하면 초기 청크가 커진다. `package.json`에 `sideEffects` 선언이 없어 번들러가 모든 모듈을 부작용 있는 것으로 본다. + +Run: `corepack pnpm check:bundle` +Expected: PASS (`bundle.initialJsGzipBytes` 상한 204800). + +**FAIL한 경우 순서대로 시도한다:** +1. `package.json`에 `"sideEffects": false`를 추가한다. 추가 전에 `src/adapters` 아래 최상위 부작용이 있는지 확인하고, CSS import가 있으면 `"sideEffects": ["*.css"]` 형태로 보존한다. +2. 그래도 넘치면 `src/adapters/service-worker/index.ts`에서 `service-worker-lifecycle.ts` 블록을 빼고, 워커 realm은 파일 직접 import를 유지한다. 그리고 Task 3의 게이트 규칙 `from.pathNot`에 워커 진입점을 추가한다. (근거: realm이 다르면 문도 다르다 — `platform`과 같은 논리.) +3. 1·2로 안 되면 이 태스크를 중단하고 보고한다. 예산 초과를 안고 진행하지 않는다. + +- [x] **Step 7: 단위·통합 테스트** + +Run: `corepack pnpm test:unit && corepack pnpm test:integration` +Expected: PASS. 이 태스크는 import 경로만 바꿨으므로 테스트 결과가 달라질 이유가 없다. 깨지면 배럴이 내보내는 심볼이 원본과 다른 것이다. + +- [x] **Step 8: 커밋** + +```bash +git add src/bootstrap src/features .storybook +git commit -m "$(cat <<'EOF' +refactor: reach adapter groups through their barrel + +bootstrap과 feature 어댑터가 어댑터 내부 파일을 직접 겨누던 15곳을 그룹 +배럴로 바꾼다. 커널(platform/**) 간선과 그룹 내부 import는 파일 경로를 +유지한다 — check:adapter-inventory가 그 경로를 직접 검증한다. + +Co-Authored-By: Claude Opus 5 (1M context) +EOF +)" +``` + +--- + +### Task 3: 게이트 규칙 + 회귀 fixture + +규칙만 추가하면 다음 사람이 규칙을 지워도 아무도 모른다. 이 레포는 거부 규칙마다 회귀 fixture를 두는 방식(`docs/architecture/layers.md`)이므로 fixture까지 같이 넣는다. + +**Files:** +- Modify: `.dependency-cruiser.json` (`:193`과 `:194` 사이에 규칙 1개) +- Create: `tests/fixtures/architecture/dependency-graph/barrel/bootstrap/compose-deep.ts` +- Create: `tests/fixtures/architecture/dependency-graph/barrel/bootstrap/compose-barrel.ts` +- Create: `tests/fixtures/architecture/dependency-graph/barrel/adapters/http/client.ts` +- Create: `tests/fixtures/architecture/dependency-graph/barrel/adapters/http/index.ts` +- Modify: `scripts/check-architecture.ts` (`runGraphFixtureChecks`에 그래프 1개 + assertion 2개) + +**Interfaces:** +- Consumes: Task 2가 만든 "위반 0건" 상태. 위반이 남아 있으면 이 규칙 추가가 곧바로 게이트를 깬다. +- Produces: `adapter-groups-are-reached-through-their-barrel` 규칙과 그 회귀 fixture 2종 + +- [x] **Step 1: fixture 트리를 만든다 (규칙보다 먼저 — 실패를 먼저 본다)** + +`tests/fixtures/architecture/dependency-graph/barrel/adapters/http/client.ts`: +```ts +export function createFixtureHttpClient(): string { + return "fixture"; +} +``` + +`tests/fixtures/architecture/dependency-graph/barrel/adapters/http/index.ts`: +```ts +export { createFixtureHttpClient } from "./client.ts"; +``` + +`tests/fixtures/architecture/dependency-graph/barrel/bootstrap/compose-deep.ts` — 규칙이 **잡아야 할** 형태: +```ts +import { createFixtureHttpClient } from "../adapters/http/client.ts"; + +export const deepComposition = createFixtureHttpClient; +``` + +`tests/fixtures/architecture/dependency-graph/barrel/bootstrap/compose-barrel.ts` — 규칙이 **통과시켜야 할** 형태: +```ts +import { createFixtureHttpClient } from "../adapters/http/index.ts"; + +export const barrelComposition = createFixtureHttpClient; +``` + +> fixture는 `analyzeSourceGraph(dir, "src")`로 분석되어 경로가 `src/...`로 보고된다(`scripts/check-architecture.ts:821-833`). 그래서 `^src/`로 시작하는 규칙이 fixture 트리에 그대로 적용된다. + +- [x] **Step 2: `.dependency-cruiser.json`에 규칙을 추가한다** + +`forbidden` 배열의 `adapters-do-not-know-other-concrete-adapters` **바로 다음**, `no-circular-dependencies` **앞**에 넣는다. + +```json + { + "name": "adapter-groups-are-reached-through-their-barrel", + "comment": "어댑터 그룹의 공개 표면은 그 그룹의 index.ts다. 그룹 바깥(bootstrap, features, presentation)은 배럴만 import한다. 배럴이 없던 시절 bootstrap은 어댑터 내부 파일 15곳을 직접 겨눴고, 그래서 어떤 파일이 공개이고 어떤 파일이 내부 헬퍼인지 아무 데도 적혀 있지 않았다. 출발점에서 src/adapters를 뺀 이유는 어댑터끼리의 간선은 바로 위 adapters-do-not-know-other-concrete-adapters가 이미 담당하고, 커널(platform/**)은 파일 단위로 공유되기 때문이다 — scripts/check-adapter-inventory.ts가 네 소비자에게 platform/abortable-operation.ts로 해석되는 specifier를 직접 요구한다. 도착점에서 1단계 중첩 index.ts를 허용한 이유는 storage/indexeddb와 storage/opfs가 각자 독립적으로 제거 가능한 런타임이고(scripts/test-browser-file-storage-runtime-removal.ts), 그래서 각자의 배럴이 곧 경계이기 때문이다.", + "severity": "error", + "from": { + "path": "^src/", + "pathNot": "^src/adapters/" + }, + "to": { + "path": "^src/adapters/[^/]+/", + "pathNot": "^src/adapters/[^/]+/(?:[^/]+/)?index\\.ts$" + } + }, +``` + +> 규칙 형태 적합성: `scripts/check-architecture.ts:799-815`의 `validateArchitectureRules`는 `from`에 `path`/`pathNot`, `to`에 `path`/`pathNot`/`circular`만 허용한다. 정규식은 `new RegExp(pattern, "u")`로 평가되므로 비캡처 그룹 `(?:...)`이 허용된다. `$1` 역참조는 쓰지 않았다. + +- [x] **Step 3: 규칙이 실제 소스에서 위반 0인지 확인한다** + +Run: `corepack pnpm check:architecture` +Expected: PASS. FAIL하면 Task 2에서 놓친 import가 있다는 뜻이다 — 출력이 지목한 파일을 배럴 경로로 고쳐라. + +- [x] **Step 4: fixture 검사를 `check-architecture.ts`에 배선한다** + +`runGraphFixtureChecks()`의 `Promise.all` 블록(`scripts/check-architecture.ts:826-833`)에 `barrelGraph`를 추가한다: + +```ts + const [allowedGraph, unresolvedGraph, layerGraph, cycleGraph, barrelGraph] = + await Promise.all([ + analyzeSourceGraph(allowedRoot, "src"), + analyzeSourceGraph(resolve(fixtureRoot, "unresolved"), "src"), + analyzeSourceGraph(resolve(fixtureRoot, "layer"), "src"), + analyzeSourceGraph(resolve(fixtureRoot, "cycle"), "src"), + analyzeSourceGraph(resolve(fixtureRoot, "barrel"), "src"), + ]); +``` + +그리고 `assertions` 배열에 두 항목을 추가한다: + +```ts + { + name: "deep adapter import from outside the group is rejected", + passed: blockingViolations(barrelGraph).some( + ({ rule, source, target }) => + rule === "adapter-groups-are-reached-through-their-barrel" && + source === "src/bootstrap/compose-deep.ts" && + target === "src/adapters/http/client.ts", + ), + }, + { + name: "barrel import from outside the group is accepted", + passed: !blockingViolations(barrelGraph).some( + ({ source }) => source === "src/bootstrap/compose-barrel.ts", + ), + }, +``` + +> 필드명 근거: `ArchitectureViolation`은 `rule` / `severity` / `source` / `target`을 갖는다 (`scripts/check-architecture.ts:35`, 생성부 `:734-739`). `from`/`to`가 아니다. + +- [x] **Step 5: fixture 회귀 검사가 통과하는지 확인한다** + +Run: `corepack pnpm check:architecture` +Expected: `Architecture graph fixtures: 14 regression checks PASS` (기존 12 + 신규 2). 그리고 전체 PASS. + +- [x] **Step 6: fixture가 실제로 무언가를 잡는지 역검증한다** + +규칙을 잠시 무력화해서 fixture가 FAIL하는지 본다. fixture가 항상 통과하면 회귀 검사가 아니다. + +```bash +# 규칙 이름을 일시적으로 바꿔 매칭되지 않게 한다 +sed -i 's/"adapter-groups-are-reached-through-their-barrel"/"temporarily-disabled-barrel-rule"/' .dependency-cruiser.json +corepack pnpm check:architecture; echo "EXIT=$?" +# 되돌린다 +sed -i 's/"temporarily-disabled-barrel-rule"/"adapter-groups-are-reached-through-their-barrel"/' .dependency-cruiser.json +corepack pnpm check:architecture; echo "EXIT=$?" +``` +Expected: 첫 번째 EXIT는 0이 아니어야 하고(assertion 실패), 되돌린 뒤 EXIT는 0이어야 한다. + +- [x] **Step 7: 커밋** + +```bash +git add .dependency-cruiser.json scripts/check-architecture.ts tests/fixtures/architecture/dependency-graph/barrel +git commit -m "$(cat <<'EOF' +feat: enforce the adapter barrel boundary in the architecture gate + +그룹 바깥에서 어댑터 내부 파일을 직접 import하면 check:architecture가 +거부한다. 회귀 fixture 2개가 거부와 허용을 각각 고정한다 — 규칙을 지우면 +fixture 검사가 먼저 깨진다. + +Co-Authored-By: Claude Opus 5 (1M context) +EOF +)" +``` + +--- + +### Task 4: 규칙을 문서에 명문화 + +코드로 강제되는 규칙이 문서에 없으면 다음 사람은 게이트 에러를 보고서야 규칙을 알게 된다. + +**Files:** +- Modify: `docs/architecture/layers.md` (배럴 경계 절 추가) +- Modify: `docs/reviews/adapters/README.md` (테스트 이관 규칙) + +**Interfaces:** +- Consumes: Task 3의 규칙 이름 `adapter-groups-are-reached-through-their-barrel` +- Produces: 없음 (문서만) + +- [x] **Step 1: `layers.md`에 배럴 경계 절을 추가한다** + +"The adapter kernel" 절 **다음에** 아래를 넣는다: + +```markdown +## 어댑터 그룹의 공개 경계 + +각 어댑터 그룹의 공개 표면은 그 그룹의 `index.ts`다. 그룹 바깥 +(`bootstrap`, `features`, `presentation`)은 배럴만 import한다. +`adapter-groups-are-reached-through-their-barrel` 규칙이 이를 강제하고, +`tests/fixtures/architecture/dependency-graph/barrel`이 거부와 허용을 +각각 고정한다. + +두 가지 예외가 있고 둘 다 의도된 것이다. + +- **그룹 내부 파일끼리**는 파일 경로로 직접 import한다. 배럴은 바깥을 위한 + 문이지 내부 규율이 아니다. +- **어댑터 → 커널(`platform/**`)** 간선도 파일 경로를 유지한다. 커널은 + 런타임 합성물이 아니라 프리미티브이고, `check:adapter-inventory`가 네 + 소비자에게 `platform/abortable-operation.ts`로 해석되는 specifier를 + 직접 요구한다. 커널 배럴(`platform/index.ts`)은 bootstrap과 테스트를 + 위한 것이다. + +`storage`는 최상위 배럴이 `indexeddb/`·`opfs/` 서브배럴을 재수출하지 +않는다. 두 런타임이 각자 독립적으로 제거 가능하고 +(`test:browser-file-storage-removal`), 그래서 각 서브배럴이 곧 경계다. +규칙의 도착점 정규식이 1단계 중첩 `index.ts`를 배럴로 인정하는 이유가 +이것이다. +``` + +- [x] **Step 2: 테스트 이관 규칙을 적는다** + +`docs/reviews/adapters/README.md` 끝에 추가: + +```markdown +## 테스트의 어댑터 import + +`tests/` 아래 어댑터 import는 배럴로 일괄 이관하지 않는다. `check:architecture`는 +`src`만 스캔하므로 강제되지 않고, 단위 테스트의 상당수가 배럴에 없는 내부 +심볼을 의도적으로 겨눈다. + +어떤 테스트 파일을 **다른 이유로** 수정하거나 분할할 때, 그 파일이 쓰는 +심볼이 해당 그룹 배럴에 있으면 그 파일 안에서만 배럴 경로로 바꾼다. +배럴에 없는 심볼이면 깊은 경로를 유지한다. 배럴에 추가하고 싶으면 그 심볼이 +공개 표면임을 먼저 논증한다 — 테스트 편의로 배럴을 키우면 배럴이 경계가 +아니라 재수출 덤프가 된다. +``` + +- [x] **Step 3: 문서 게이트 확인** + +Run: `corepack pnpm lint && corepack pnpm check:architecture` +Expected: PASS. (문서 링크 검증이 있으면 `corepack pnpm verify:documentation`도 돌린다.) + +- [x] **Step 4: 커밋** + +```bash +git add docs/architecture/layers.md docs/reviews/adapters/README.md +git commit -m "$(cat <<'EOF' +docs: write down the adapter barrel boundary and its two exceptions + +Co-Authored-By: Claude Opus 5 (1M context) +EOF +)" +``` + +--- + +## 완료 판정 + +네 태스크가 끝나면 아래가 전부 PASS여야 한다. + +```bash +corepack pnpm check:types +corepack pnpm lint +corepack pnpm check:architecture +corepack pnpm check:adapter-inventory +corepack pnpm check:bundle +corepack pnpm test:unit +corepack pnpm test:integration +corepack pnpm test:browser-file-storage-removal +corepack pnpm test:realtime-removal +``` + +그리고 아래가 `0`이어야 한다. +```bash +grep -rn 'from "[^"]*adapters/[^"]*"' src/ | grep -v '^src/adapters/' | grep -v 'index\.ts"' | wc -l +``` + +## 이 계획이 하지 않는 것 + +- `tests/` 166줄의 배럴 이관 — Task 4 Step 2의 규칙대로 파일을 손댈 때만 한다. +- 대형 파일 분할 — 별도 계획. 이 계획이 그 선행조건이다. +- spec §6이 남긴 부수 발견 4건(`telemetry:49`의 잉여 재수출, `browser-files/index.ts`의 포트 재수출, `opfs/index.ts` 누락 심볼 3개, `.dependency-cruiser.json:141`의 존재하지 않는 `web-worker` 경로) — 각각 별도 티켓. + +--- + +## 실행 기록 (2026-09-16 완료) + +네 태스크 전부 실행했다. 커밋 5개: `a42d961` (spec·plan), `b29a471` (배럴 8개), +`1606d9b` (소비자 15줄), `27ab17d` (게이트 규칙 + fixture), `eb40bc9` (문서). + +**계획과 달랐던 것 2건.** + +1. **워커 realm 타입체크 실패** — 계획 초안에 없던 Task 1 Step 7이 여기서 나왔다. + `service-worker/index.ts`가 `tsconfig.service-worker.json`의 WebWorker lib + 컴파일에 페이지 realm 파일을 끌어들여 `Cannot find name 'document'`로 실패했다. + 배럴을 그 tsconfig의 `exclude`에 추가해 해결. +2. **spec의 정규식이 게이트에 거부당함** — spec §5.1이 제시한 + `^src/adapters/[^/]+/(?:[^/]+/)?index\.ts$`를 dependency-cruiser가 + "unsafe regular expression"으로 거부했다(`(?:[^/]+/)?` 안의 `+`가 star height 2). + 중첩 없는 교대로 바꿔 통과시켰다: + `^src/adapters/[^/]+/index\.ts$|^src/adapters/[^/]+/[^/]+/index\.ts$` + spec은 이 규칙을 실제로 실행해 본 적이 없었다. + +**측정 결과.** + +- 번들 영향 **0바이트**: 배럴 도입 전후 모두 초기 JS 181114 / 204800 gzip bytes. + `sideEffects` 선언이 없는데도 Rollup이 재수출을 트리셰이킹했다. 계획이 지목한 + 최대 위험은 현실화되지 않았고 대응 3단계는 쓰지 않았다. +- import 그래프: 297 모듈 / 897 의존 → 305 모듈 / 914 의존 (배럴 8개 + fixture 4개). +- 회귀 검사: 12 → 14. 규칙 이름을 바꿔 fixture가 실제로 깨지는 것을 확인했다. +- 배럴 미경유 import: `src/` 15건 → **0건**. + +**PASS:** `check:types` `lint` `check:architecture` `check:adapter-inventory` +`check:bundle` `test:integration`(81) `test:component`(130) `verify:documentation` + +**이 환경에서 판정 불가:** `test:unit`, `test:browser-file-storage-removal`, +`test:realtime-removal`. 셋 다 `tests/unit/ci-artifact-contract.test.ts`의 16건이 +`bwrap: loopback: Failed RTM_NEWADDR: Operation not permitted`로 실패해 exit 1이 +된다. `develop` `5434760` 기준선에서도 동일하게 16건 실패함을 stash 후 실행해 +확인했다. 어댑터 관련 테스트는 전부 통과했고(`test:unit` 1796 passed), 제거 드릴의 +`error TS`는 0건이다. **CI 환경에서 이 셋의 전체 PASS를 확인해야 한다.** diff --git a/docs/superpowers/plans/2026-09-16-indexeddb-kernel-promotion.md b/docs/superpowers/plans/2026-09-16-indexeddb-kernel-promotion.md new file mode 100644 index 0000000..dbdd736 --- /dev/null +++ b/docs/superpowers/plans/2026-09-16-indexeddb-kernel-promotion.md @@ -0,0 +1,464 @@ +# IndexedDB 커널 승격 Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** 어댑터 4곳이 각자 구현한 IndexedDB 연결·트랜잭션 메커니즘을 `src/adapters/platform/`의 커널 2파일로 모으고, 4벌이 서로 다른 답을 내던 지점을 하나로 만든다. + +**Architecture:** 커널은 **메커니즘만** 갖는다 — open 요청을 Promise로 바꾸기, blocked 데드라인, upgrade/error/success 라우팅, 늦게 도착한 연결 닫기, 트랜잭션 상태기계, 커서 펌프. 데이터베이스 이름·스키마·마이그레이션·governance·**실패 분류(taxonomy)**는 각 서브시스템에 남는다. 실패 매핑은 `translate` 콜백으로 주입하므로 `mapIndexedDbException`과 `mapBrowserDataException`이 서로 다른 답을 내는 현 상태가 보존된다. + +**Tech Stack:** TypeScript, IndexedDB, Vitest, `tests/helpers/memory-indexeddb.ts`(가짜 IDB) + +**Spec:** [`docs/superpowers/specs/2026-09-16-indexeddb-kernel-promotion-design.md`](../specs/2026-09-16-indexeddb-kernel-promotion-design.md) + +## Global Constraints + +- **`src/adapters/platform/`은 이미 dependency-cruiser의 kernel carve-out이다.** 커널에 파일을 추가하는 데 규칙 변경이 필요 없다(spec §5.3). +- **`IDBFactory`는 필수 주입 파라미터다.** `globalThis.indexedDB`를 읽으면 안 된다 — `eslint.config.ts:40-63`이 모든 브라우저 루트에서 그 속성을 막고, 예외는 `platform/browser-lifecycle.ts` **한 파일**에만 부여돼 있다. 주입받으면 `eslint.config.ts`를 건드릴 필요가 없다(spec §5.1). +- **소스 파일을 추가하면 `docs/reviews/adapters/INVENTORY.md`에 행을 추가하고 하단 합계를 고친다.** `check:adapter-inventory`가 `git ls-files src/adapters`와 집합을 정확히 대조한다. +- **`check:adapter-inventory`에 abort 래칫이 있다.** `addEventListener("abort")`를 쓰는 어댑터 파일이 24개를 넘으면 실패한다. `platform/`은 세지 않는다. +- **실패 매핑 4벌을 통일하지 마라.** `mapIndexedDbException`(RT/MT/OP)과 `mapBrowserDataException`(CP)은 같은 에러에 다른 답을 낸다 — `ConstraintError` recovery가 NONE vs REOPEN, `QuotaExceeded` retryable이 false vs true, `NotFound`가 MIGRATION_FAILED vs NOT_FOUND. 통일은 별건이고 이 계획의 범위가 아니다. +- **`deleteDatabase`를 나머지 3벌에 추가하지 마라.** CP에만 있는 것이 의도다(spec §2.3). +- **이 환경의 알려진 제약:** `tests/unit/ci-artifact-contract.test.ts` 16건이 `bwrap: loopback: Failed RTM_NEWADDR: Operation not permitted`로 실패한다. `develop` `5434760` 기준선에서도 동일하다. **판정 기준은 그 파일 외의 실패가 0인지**다. +- 커밋 메시지 끝에 붙일 것: `Co-Authored-By: Claude Opus 5 (1M context) ` + +## 왜 이 작업을 하는가 — LOC로 정당화하지 않는다 + +> **2026-09-16 갱신 — 사양의 추정이 빗나갔다.** 커널을 실제로 구현하니 +> 2파일 **1,132줄**(코드 751줄)이다. 사양 추정 470줄의 2.4배다. 사양 §3.1이 +> "470 LOC라 2분할한다"고 쓴 논거도 사실이 아니었다(2분할 자체는 테스트 셋업이 +> 갈린다는 별도 근거로 유지). 그래서 아래 표의 순증감이 뒤집힌다. + +| | 사양 추정 | 실제 | +|---|---:|---:| +| 4벌에서 삭제 | ~974 | (미측정, 이행 후 확정) | +| 4벌에 추가 (커널 호출부·콜백) | ~281 | (미측정) | +| 4벌 순감 | −693 | (미측정) | +| 커널 신규 2파일 | +470 | **+1,132** | +| 신규 커널 테스트 2파일 | (미기재) | **+1,602** | +| **레포 순증감 (소스만)** | **−223** | **약 +439** | + +**이 리팩토링은 줄 수를 줄이지 않는다. 늘린다.** 소스 약 +439줄, 테스트까지 하면 +약 +2,041줄이다. 사양은 "절감이 작다"고 썼지만 실제로는 절감이 아니라 증가다. + +**그래서 이 작업의 근거는 오로지 하나다: 트랜잭션 상태기계가 4개에서 1개가 되는 것.** +줄 수로 정당화하려는 시도는 이제 불가능하다. 근거가 성립하는 이유는 오늘 그 4개가 +이미 서로 다른 답을 내고 있기 때문이다: + +| 상황 | RT | MT | OP | CP | +|---|---|---|---|---| +| 트랜잭션 안 개별 요청 실패 | 본다 | 기록만 | **안 본다** | 즉시 abort | +| 값 없이 완료 | UNAVAILABLE | UNAVAILABLE | UNAVAILABLE | **CORRUPT_DATA** | +| `deleteDatabase` | 없음 | 없음 | 없음 | **있음** | + +리뷰가 "이미 갈라졌다"고 판정한 근거가 이 표다. + +**그리고 이행을 멈추면 최악이다.** 커널만 넣고 사본을 안 옮기면 +1,132줄의 +쓰이지 않는 코드가 남는다. 이 레포가 이미 `abortable-operation.ts`로 겪고 있는 +병(커널은 있는데 24개 파일이 안 씀)을 하나 더 만드는 것이다. 되돌리려면 지금이 +가장 싸다 — 커널 커밋 하나를 revert하면 끝이고 사본은 아직 안 건드렸다. + +--- + +### Task 1: 커널 2파일 + 단위 테스트 + +사본은 **손대지 않는다.** 코드 추가만 하므로 런타임 동작이 바뀌지 않는다. + +**Files:** +- Create: `src/adapters/platform/indexeddb-connection.ts` (~240 LOC) +- Create: `src/adapters/platform/indexeddb-transaction.ts` (~230 LOC) +- Create: `tests/unit/indexeddb-connection.test.ts` +- Create: `tests/unit/indexeddb-transaction.test.ts` +- Modify: `docs/reviews/adapters/INVENTORY.md` (행 2개 + 합계 `128/128` → `130/130`) + +**Interfaces:** +- Produces: spec §3.2·§3.3의 전체 export 시그니처. Task 2~5가 이것만 쓴다. +- Consumes: 기존 커널 `snapshotAbortTimers`(`platform/abortable-operation.ts`), `contracts/result.ts`의 `Result` + +- [x] **Step 1: 기존 커널 관례를 읽는다** + +`src/adapters/platform/`의 5파일을 읽고 주석 스타일(왜 이 규칙이 있는지를 근거와 함께 적는 방식), 에러 처리, 의존성 주입 방식을 파악한다. 새 파일은 그 관례를 따른다. + +- [x] **Step 2: 가짜 IDB의 오류 배선을 확인한다** + +`tests/helpers/memory-indexeddb.ts`를 읽는다. 커널은 요청 레벨 `onerror`를 새로 보게 되므로 가짜가 `request.error`를 채우는지가 전제다. + +확인됨(2026-09-16): 채운다. `:167-170`이 `request.error = asException(error)` 후 `queueMicrotask`로 `onerror` 발화, `:309-311`이 같은 일을 **동기로** 한다. **두 경로의 타이밍이 다르므로** 테스트에서 주의한다. + +- [x] **Step 3: 실패하는 테스트를 먼저 쓴다** + +최소한 아래를 고정한다. 각각 먼저 실패하는 것을 확인한 뒤 구현한다. + +연결(`tests/unit/indexeddb-connection.test.ts`): +- open 성공 / `onerror` / native throw +- `onblocked` — deadline 미설정 시 `BLOCKED`, deadline 경과 시 `BLOCKED_DEADLINE` +- upgrade `APPLIED` +- upgrade `REJECTED` — **versionchange 트랜잭션이 abort되어 스키마가 커밋되지 않는 것까지** 확인 +- upgrade가 throw → `REJECTED` + `detail`에 thrown value +- `newVersion`이 null → `upgrade` 실행 **전에** `UPGRADE_REJECTED` +- admission `ADMIT` / `REJECT` / `FAIL` — 거부 시 연결이 **닫히는지** +- 호출자가 포기한 뒤 늦게 도착한 연결이 닫히는지 +- `CALLER_ABORT` +- `translate`가 각 cause에 대해 호출되는지 + +트랜잭션(`tests/unit/indexeddb-transaction.test.ts`): +- 커밋 / abort +- `succeed()` 없이 완료 → `NO_VALUE_PRODUCED` +- 첫 결과가 이긴다(`succeed` 이후 `fail` 무시) +- 커서 순회와 `SUSPEND` 스텝(중첩 요청 체인) +- 예산 콜백이 "삭제 행 기준"과 "스캔 행 기준" 양쪽을 표현할 수 있는지 +- **CP-4 필수 요건:** `abort()`가 throw하면 caller-abort 표시를 세우지 않고 transaction 이벤트가 결과를 정한다 + +- [x] **Step 4: 구현한다 — 좁은 커널 함정을 피한다** + +기존 커널 `abortable-operation.ts:11`은 `AbortTerminalReason` 3멤버를 **반환 타입**에 박아서 5종이 필요한 `http-execution-v3`가 아예 못 썼다. 같은 실수를 반복하면 이 작업은 실패다. + +구현 후 아래를 확인한다: +- `IndexedDbFailureCause`가 어떤 공개 **반환 타입**에도 나타나지 않는가 (`translate`의 입력으로만 쓰이는가) +- spec §3.4의 4개 사본 예시(RT/MT/OP/CP)가 **전부** 수용되는가 + +하나라도 수용되지 않으면 **구현을 멈추고 보고한다.** spec에 억지로 맞추지 않는다. + +- [x] **Step 5: INVENTORY 갱신** + +`docs/reviews/adapters/INVENTORY.md`에 두 행을 알파벳 위치에 넣고 번호를 다시 매긴다. 링크는 같은 그룹(`platform/`) 기존 행과 동일하게 `[Network/state](./01-network-and-state.md)`. 하단 합계를 `130/130`으로. + +- [x] **Step 6: 게이트** + +```bash +corepack pnpm check:types:app && corepack pnpm check:types:test \ + && corepack pnpm lint && corepack pnpm check:architecture \ + && corepack pnpm check:adapter-inventory +corepack pnpm test:unit +``` +Expected: 앞 묶음 전부 PASS. `test:unit`은 `ci-artifact-contract.test.ts` 외 실패 0. + +- [x] **Step 7: 커밋** + +```bash +git add src/adapters/platform tests/unit/indexeddb-*.test.ts docs/reviews/adapters/INVENTORY.md +git commit -m "$(cat <<'EOF' +feat: add the shared IndexedDB connection and transaction kernel + +네 어댑터가 각자 구현한 open/blocked/upgrade/트랜잭션 메커니즘을 커널로 +모은다. 사본은 아직 이행하지 않았으므로 런타임 동작은 그대로다. + +실패 분류는 커널에 넣지 않고 translate 콜백으로 주입한다. RT/MT/OP의 +mapIndexedDbException과 CP의 mapBrowserDataException이 같은 에러에 다른 +답을 내며, 그 차이를 통일하는 것은 별건이기 때문이다. + +Co-Authored-By: Claude Opus 5 (1M context) +EOF +)" +``` + +--- + +### Task 2: CP 이행 — `indexeddb-checkpoint-store.ts` (712 → 약 570) + +**CP를 먼저 하는 이유:** 가장 작고, 동작 변화 지점이 가장 명확하며, 커널의 CP-4 요건(abort가 throw하면 caller-abort를 세우지 않는다)을 조기에 검증한다. + +**Files:** +- Modify: `src/adapters/browser-transfer/resumable-upload/indexeddb-checkpoint-store.ts` +- Modify: `tests/unit/resumable-upload-checkpoint.test.ts` (동작 변화 지점 고정) + +**Interfaces:** +- Consumes: Task 1의 `openIndexedDbDatabase`, `runIndexedDbTransaction`, `deleteIndexedDbDatabase` +- Produces: 없음 (공개 포트 형태 불변) + +- [x] **Step 1: 동작 변화 지점을 테스트로 먼저 고정한다** + +구현 전에 아래 5개가 현재 동작대로 통과하는지 확인한다. 이행 후에도 같아야 한다. + +| # | 지점 | 현재 동작 | 깨지면 | +|---|---|---|---| +| CP-1 | 값 없는 완료 | `CORRUPT_DATA/RECONCILE` (L541-547) | 번역기가 `NO_VALUE_PRODUCED → CORRUPT_DATA`를 명시 매핑 안 하면 UNAVAILABLE로 바뀜 | +| CP-2 | `durability` | 옵션 bag 없음 (L512) | 커널 기본이나 `"strict"`를 넣으면 체크포인트 쓰기가 조용히 느려짐 (성능 회귀) | +| CP-3 | `nativeFailure` | 기록 후 **즉시 abort** (L577-588) | `requestFailed`(abort 안 함)로 바꾸면 요청 실패 후에도 뒤 요청이 커밋됨. `compareAndSwap`의 `get→put` 체인(L321-343)에서 특히 위험 | +| CP-4 | `abort()`가 throw | `failure`를 **되돌린다** (L528, L536) | 커밋된 체크포인트를 ABORTED로 보고 | +| CP-5 | `deletePartition` blocked 타이머 | 네이티브 `setTimeout` (L450) | 주입형 `timers`로 바뀜. `tests/unit/resumable-upload-checkpoint.test.ts:194`가 이 경로를 봄 | + +기존 단언 위치: `:142` CONFLICT/RECONCILE, `:190` UNAVAILABLE/RESUME, `:194` blocked PENDING, `:238` false-abort 금지. + +- [x] **Step 2: 삭제 대상 블록을 커널 호출로 바꾼다** + +| 블록 | 줄 | 대체 | +|---|---|---| +| `TransactionContext` 타입 | L491-495 | 커널 타입 | +| `openAndBind`의 open 요청 Promise 배선 | L163-175, L198-217 | `openIndexedDbDatabase` (upgrade 본문 L176-197은 `upgrade` 콜백으로, `bindScope` 호출은 `admit`으로) | +| `runCheckpointTransaction` | L497-596 | `runIndexedDbTransaction` | +| `bindScope`의 트랜잭션 배선 | L602-623 | `runIndexedDbTransaction` (검증 로직 L624-652는 `queue`로 그대로) | +| `deletePartition`의 blocked/settle 배선 | L431-462, L472-483 | `deleteIndexedDbDatabase` | + +**남길 것:** `PENDING_DELETIONS` 레지스트리(L31-41) + 생성 시 검사(L116-122), `uploadCheckpointDatabaseName`(L73-83), `sameScopeBinding`(L656-672), `snapshotScope`(L674-691), `snapshotCheckpoint`(L693-711). + +- [x] **Step 3: 게이트 + 표적 테스트** + +```bash +corepack pnpm check:types:app && corepack pnpm lint && corepack pnpm check:architecture +npx vitest run tests/unit/resumable-upload-checkpoint.test.ts --reporter=default +``` +Expected: 전부 PASS. CP-1~CP-5가 이행 전과 같은 답을 내야 한다. + +- [x] **Step 4: 커밋** + +```bash +git add src/adapters/browser-transfer tests/unit/resumable-upload-checkpoint.test.ts +git commit -m "refactor: move the upload checkpoint store onto the IndexedDB kernel + +Co-Authored-By: Claude Opus 5 (1M context) " +``` + +--- + +### Task 3: MT 이행 — `indexeddb-maintenance.ts` (1558 → 약 1370) + +**MT를 두 번째로 하는 이유:** 커널 사용자 중 연결 핸들을 안 쓰는 유일한 사본이라 `openIndexedDbDatabase` 단독 사용 경로를 검증한다. + +**Files:** +- Modify: `src/adapters/storage/indexeddb/indexeddb-maintenance.ts` +- Modify: `tests/unit/indexeddb-maintenance.test.ts` + +**Interfaces:** +- Consumes: Task 1의 `openIndexedDbDatabase`, `openIndexedDbTransaction`, `runIndexedDbTransaction`, `walkIndexedDbCursor` + +- [x] **Step 1: 두 개의 함정을 먼저 이해한다** + +**MT-1 (가장 위험).** `blockedTimeoutMs`를 **넘기지 마라.** 안 넘겨야 오늘 동작(blocked 이벤트 즉시 `BLOCKED`, L485-492)이 유지된다. 넘기면 배치가 최대 그 시간만큼 매달린다. `tests/unit/indexeddb-maintenance.test.ts:289-290`이 `BLOCKED/retryable:true/RELOAD_OTHER_CONTEXTS`를 **즉시** 받길 기대하므로 값을 넣으면 타임아웃으로 실패한다. + +**MT-2.** `upgrade` 콜백을 **생략하라.** 생략해야 오늘의 "upgrade는 곧 실패"(L477-484)가 유지된다. 커널은 생략을 `UPGRADE_REJECTED`로 해석한다. 실수로 `upgrade: () => ({kind:"APPLIED"})`를 넣으면 **잘못된 스키마로 열린다.** + +- [x] **Step 2: 삭제 대상 블록을 커널 호출로 바꾼다** + +| 블록 | 줄 | 대체 | +|---|---|---| +| `TransactionContext` 타입 | L97-101 | 커널 타입 | +| `openExactVersion`의 배선분 | L434-508, L551-585 | `openIndexedDbDatabase` (L509-550을 `admit`으로 이식) | +| `createTransaction` | L587-604 | `openIndexedDbTransaction` | +| `runTransaction` | L606-705 | `runIndexedDbTransaction` | +| 커서 2곳의 deadline/maxRows/abort 보일러플레이트 | L799-833, L1451-1479 | `walkIndexedDbCursor` | + +**MT-3.** `database.onversionchange = () => database.close()`(L543)를 `admit` 안으로 옮긴다. `admit`은 성공 경로에서만 실행되므로 등록 시점이 오늘과 같다. + +**남길 것:** 체크포인트 상태기계(`readCheckpoint` L707-756, `commitPrepared` L969-1251), `prepareRecords`(L863-967), `clock`/`epochClock`(L401-421), `countBucket`(L239-245), 저장 술어(L118-223). + +- [x] **Step 3: 게이트 + 표적 테스트** + +```bash +corepack pnpm check:types:app && corepack pnpm lint && corepack pnpm check:architecture +npx vitest run tests/unit/indexeddb-maintenance.test.ts --reporter=default +``` +Expected: 전부 PASS. 특히 `:289-290`이 **즉시** BLOCKED를 받아야 한다(타임아웃이 아니라). + +- [x] **Step 4: 커밋** + +```bash +git add src/adapters/storage tests/unit/indexeddb-maintenance.test.ts +git commit -m "refactor: move IndexedDB maintenance onto the kernel + +Co-Authored-By: Claude Opus 5 (1M context) " +``` + +--- + +### Task 4: OP 이행 — `indexeddb-opfs-journal.ts` (1817 → 약 1690) + +**이 계획에서 동작 변화가 가장 큰 태스크다.** + +**Files:** +- Modify: `src/adapters/storage/opfs/indexeddb-opfs-journal.ts` +- Modify: `tests/unit/indexeddb-opfs-journal.test.ts` +- 가능성: `tests/helpers/memory-indexeddb.ts` 보강 + +**Interfaces:** +- Consumes: Task 1의 `openIndexedDbDatabase`, `createIndexedDbConnection`, `runIndexedDbTransaction`, `openIndexedDbTransaction`, `walkIndexedDbCursor` + +- [x] **Step 1: OP-1을 테스트로 먼저 드러낸다 — 이 태스크의 핵심** + +오늘 OP는 트랜잭션 안의 개별 요청에 `.onerror`를 **하나도** 안 단다(파일 전체에서 request `.onerror`는 L1042의 open 요청 하나뿐). 요청 실패는 `transaction.onabort`로만 흘러 `mapIndexedDbException(transaction.error)`(L1158)가 된다. + +커널을 쓰면 **요청 자신의 오류가 보고된다.** 구체적으로 `LOGICAL_KEY_INDEX`가 `unique: true`(L1000-1004)이므로 **중복 put은 요청 레벨 `ConstraintError` → `CONFLICT`**가 되고, 오늘은 `transaction.error`가 무엇이냐에 따라 달라진다. + +이행 **전에** 중복 put 테스트를 `tests/unit/indexeddb-opfs-journal.test.ts`에 추가해 현재 답을 기록하고, 이행 후 달라진 답을 의도된 변경으로 승인한다. 가짜 IDB가 이 경로를 표현하지 못하면 `tests/helpers/memory-indexeddb.ts`를 먼저 보강한다. + +- [x] **Step 2: OP-2를 확인한다** + +오늘 OP의 `runTransaction`은 `succeed` 이후 `fail`이 와도 `explicitFailure`가 이기지만(L1133-1141, `hasValue`는 true 유지) `oncomplete`는 값을 반환한다(L1143-1153). 커널의 "첫 결과가 이긴다" 규칙을 따르면 **`succeed` 후의 `fail`이 무시된다.** + +현재 OP 코드에 그 순서가 실제로 발생하는 경로가 있는지 **확인하라**(spec은 미확인으로 남겼다). 없으면 변화 없음으로 기록하고 넘어간다. + +- [x] **Step 3: 삭제 대상 블록을 커널 호출로 바꾼다** + +| 블록 | 줄 | 대체 | +|---|---|---| +| `TransactionContext` 타입 | L48-51 | 커널 타입 | +| scheduler 기본값 인라인 | L144-153 | `snapshotAbortTimers` | +| `openDatabase`의 배선분 | L961-996, L1031-1072 | `openIndexedDbDatabase` + `createIndexedDbConnection` (upgrade 본문 L997-1029는 `upgrade` 콜백으로 그대로 이동) | +| `runTransaction` | L1098-1174 | `runIndexedDbTransaction` | +| `strictReadwriteTransaction` | L1176-1190 | `openIndexedDbTransaction(…, "strict")` | +| 커서 2곳의 limit 루프 | L604-633, L677-712 | `walkIndexedDbCursor` | + +**OP-4.** `signal`은 **넣지 않는다.** 오늘 없는 취소를 새로 만들지 않는다. + +- [x] **Step 4: 게이트 + 표적 테스트** + +```bash +corepack pnpm check:types:app && corepack pnpm lint && corepack pnpm check:architecture +npx vitest run tests/unit/indexeddb-opfs-journal.test.ts tests/unit/opfs-byte-store.test.ts --reporter=default +``` +Expected: PASS. OP-1로 인한 답 변화는 Step 1에서 승인한 것만 있어야 한다. + +- [x] **Step 5: 커밋** + +```bash +git add src/adapters/storage tests +git commit -m "refactor: move the OPFS journal onto the IndexedDB kernel + +요청 레벨 오류를 처음으로 보게 된다. unique 인덱스 위반이 트랜잭션 abort +사유가 아니라 요청 자신의 ConstraintError로 보고된다. + +Co-Authored-By: Claude Opus 5 (1M context) " +``` + +--- + +### Task 5: RT 이행 — `indexeddb-runtime.ts` (2902 → 약 2665) + +**가장 크고 마지막이다.** 다른 셋이 커널을 전부 검증한 뒤에 옮긴다. + +**Files:** +- Modify: `src/adapters/storage/indexeddb/indexeddb-runtime.ts` +- Modify: `tests/unit/indexeddb-runtime.test.ts` + +- [x] **Step 1: RT-1을 번역기에 명시한다** + +`close()`가 진행 중 open을 끝내는 원인이 `unavailable(operation)`(L743)에서 `translate({kind:"CLOSED"})`로 바뀐다. 번역기가 **`CLOSED → unavailable`을 명시 매핑**해야 오늘 동작이 유지된다. 빠뜨리면 `close()` 중 open이 ABORTED로 보고된다. + +기존 실패 코드 단언 위치: `tests/unit/indexeddb-runtime.test.ts:339-340, :371-372, :454, :534, :549-550, :734-735`. + +- [x] **Step 2: 삭제 대상 블록을 커널 호출로 바꾼다** + +| 블록 | 줄 | 대체 | +|---|---|---| +| `defaultScheduler` | L108-117 | `snapshotAbortTimers(scheduler)` | +| `TransactionContext` 타입 | L85-89 | `IndexedDbTransactionContext` | +| `waitForOpeningAttempt` | L659-682 | `connection.acquire(signal)` | +| `startOpeningAttempt`의 배선분 | L684-745, L776-843, L872-921 중 배선분 | `openIndexedDbDatabase` (upgrade/admit 콜백 본문은 그대로) | +| `createTransaction` | L957-974 | `openIndexedDbTransaction` | +| `runTransaction` | L976-1074 | `runIndexedDbTransaction` | +| 커서 5곳의 보일러플레이트 | L1374-1382, L1454-1471, L2364-2389, L2531-2548, L2573-2590, L2644-2661, L2718-2735 | `walkIndexedDbCursor` + `budget.admit` | + +**RT-2.** `settleNativeRequest`/`activeOpeningGeneration`(L595, L691-697)이 사라진다. 커널의 settle-once와 단일 비행이 같은 역할을 한다. **의미는 같지만 경합 순서가 달라질 수 있다** — 동시 open 테스트를 주의해서 본다. + +**RT-3.** `openingRequest` 필드(L593)는 오늘도 L712·L2878의 대입 외에 읽는 곳이 없다. 삭제한다. + +**남길 것:** 코덱/영수증/보존/예산(bytes)/governance/migration 목록/상태 브로드캐스트/`monotonicClock`/`countBucket`/저장 레코드 술어/`purgePartitionRecords`의 스토어 순서 로직 — 전부 정책이다. + +- [x] **Step 3: 게이트 + 전체 테스트** + +```bash +corepack pnpm check:types && corepack pnpm lint && corepack pnpm check:architecture \ + && corepack pnpm check:adapter-inventory +corepack pnpm test:unit +corepack pnpm test:integration +``` +Expected: `ci-artifact-contract.test.ts` 외 실패 0. + +- [x] **Step 4: 커밋** + +```bash +git add src/adapters/storage tests/unit/indexeddb-runtime.test.ts +git commit -m "refactor: move the IndexedDB runtime onto the kernel + +Co-Authored-By: Claude Opus 5 (1M context) " +``` + +--- + +## 완료 판정 + +```bash +corepack pnpm check:types +corepack pnpm lint +corepack pnpm check:architecture +corepack pnpm check:adapter-inventory +corepack pnpm check:bundle +corepack pnpm test:unit # ci-artifact-contract.test.ts 외 실패 0 +corepack pnpm test:integration +corepack pnpm test:component +corepack pnpm test:browser-file-storage-removal # error TS 0건 +corepack pnpm test:realtime-removal # error TS 0건 +``` + +그리고 아래가 **0**이어야 한다 — 커널 밖에 남은 open 요청 배선: +```bash +grep -rn "createObjectStore\|onupgradeneeded" src/adapters --include='*.ts' \ + | grep -v "src/adapters/platform/" | grep -v "upgrade" | wc -l +``` + +**실브라우저 확인이 필요하다.** 이 계획은 가짜 IDB 위에서만 검증된다. `tests/browser-capabilities/indexeddb-runtime.spec.ts`(1033 LOC), `opfs-runtime.spec.ts`(221), `resumable-upload.spec.ts`(526)를 실브라우저에서 돌려야 blocked/versionchange 실동작 회귀를 잡는다. + +## 이 계획이 하지 않는 것 + +- **실패 매핑 4벌 통일** — `mapIndexedDbException`과 `mapBrowserDataException`이 같은 에러에 다른 답을 내는 것은 별건이다. 이 계획은 그 차이를 `translate` 주입으로 **보존**한다. +- **`deleteDatabase`를 3벌에 추가** — CP에만 있는 것이 의도다(spec §2.3). +- 대형 파일 분할 — 커널 이행으로 RT가 2902 → 2665가 되지만 여전히 크다. 분할은 별도 계획이다. + + +--- + +## 실행 기록 (2026-09-16 — 5개 태스크 전부 완료) + +커밋 5개: `cb62bfb`(커널) · `bb6080b`(CP) · `3366a81`(MT) · `217c1dd`(OP) · `a91e78f`(RT). + +### 실측 LOC — 사양 추정은 전부 빗나갔다 + +| 사본 | 사양 추정 | 실제(전체 줄) | 실제(코드 줄) | +|---|---:|---:|---:| +| CP `indexeddb-checkpoint-store.ts` | −142 | 712 → 612 = **−100** | | +| MT `indexeddb-maintenance.ts` | −188 | 1558 → 1430 = **−128** | | +| OP `indexeddb-opfs-journal.ts` | −127 | 1817 → 1881 = **+64** | 1744 → 1724 = −20 | +| RT `indexeddb-runtime.ts` | −235 | 2902 → 2744 = **−158** | 2807 → 2563 = −244 | +| 4벌 합 | **−693** | **−322** | | +| 커널 2파일 | +470 | **+1,132** | +751 | +| **소스 순증감** | **−223** | **+810** | | +| 커널 테스트 2파일 | (미기재) | +1,602 | | + +**공통 원인:** 사양이 `translate`/실패 헬퍼 어댑터 함수 비용을 세지 않았다. CP는 4개(~37줄), MT는 6개가 필요했다. 그리고 이행된 파일들의 주석이 크게 늘었다(OP 6→90줄, RT 12→111줄) — 이 레포 관례상 부풀림이 아니라 개선이지만, 줄 수 예측은 무너뜨린다. + +**결론은 바뀌지 않는다.** 이 작업의 근거는 처음부터 줄 수가 아니라 상태기계 통합이었고, 그건 달성됐다. 다만 **줄 수가 준다는 기대는 완전히 틀렸다**는 것을 기록해 둔다. + +### 부수 성과 + +- **abort 래칫이 24 → 21로 세 칸 조여졌다.** CP·MT·RT가 각각 자기 abort 리스너를 지웠다. 래칫이 설계대로 작동했다. +- **가짜 IndexedDB가 unique 인덱스를 전혀 강제하지 않는 것을 찾아 고쳤다**(`tests/helpers/memory-indexeddb.ts`). 보강 전에는 중복 `begin`이 `ok:true`로 성공했다 — 브라우저가 거부할 상태를 테스트가 조용히 허용하고 있었다. 이 발견이 커널 이행 자체보다 가치가 클 수 있다. +- 사양이 빠뜨린 함정 하나를 CP에서 막았다: `bindScope`는 `succeed()`에 해당하는 것이 없어 그대로 옮기면 정상 바인딩이 `CORRUPT_DATA`로 보고된다. 이후 MT·OP·RT는 성공 출구를 전수 대조했다. + +### 사양이 틀린 것으로 판명된 항목 3건 + +1. **OP-1** — 사양은 "이 리팩토링에서 가장 큰 동작 변화"로 지목하며 중복 put의 답이 달라진다고 봤다. **틀렸다.** 이행 전후 모두 `CONFLICT / retryable:false / recovery:NONE`이다. 요청 오류를 아무도 처리하지 않으면 스토어가 바로 그 에러로 abort해서 `transaction.error === request.error`이기 때문이다. 바뀐 것은 답이 아니라 출처다. +2. **RT-2** — 사양은 "의미 동일"이라고 썼다. **틀렸다.** 아래 참조. +3. **§3.1의 파일 분할 논거** — "470 LOC라 1파일은 폴더 관례를 깬다"고 썼으나 실제 구현은 1,132줄이다. 2분할 자체는 유지할 값이 있지만(테스트 셋업이 갈린다) 그 논거는 사실이 아니었다. + +### 보존하지 못한 동작 1건 — RT-2 (의도적으로 남김) + +blocked 데드라인 이후 재시도가 새 `factory.open()`을 띄운다. 이행 전에는 안 띄웠다. 커널에 "settle 이후에도 살아 있는 요청"을 알려줄 훅이 없기 때문이다. + +**복원하지 않기로 했다.** 근거: +- 이행 전후 모두 10초 blocked 데드라인이 있고, 차이는 두 번째 네이티브 open을 띄우는지뿐이다. +- 늦게 도착한 연결은 커널이 `closeQuietly`로 닫으므로 **연결 누수도 데이터 위험도 없다.** +- 재시도가 10초 데드라인에 게이트되므로 쌓이는 속도가 제한적이다. +- 반면 지금 커널을 고치면 **이미 검증이 끝난 4개 사본을 전부 재검증**해야 한다. 이익 대비 위험이 맞지 않는다. + +복원하려면 `openIndexedDbDatabase`에 `onSettled`를 추가하면 된다(`deleteIndexedDbDatabase`에는 이미 있다). 다만 그러면 "blocked 데드라인 실패가 버려진 요청이 끝날 때까지 다음 acquire를 막는가"라는 설계 질문이 따라온다 — 막는다면 다른 탭이 영영 안 닫힐 때 재시도가 영구 차단되어 **지금보다 나쁘다.** 착수 전 그 답부터 정해야 한다. + +### 테스트로 덮지 못한 경로 1건 + +RT의 `POLICY_REJECTED` upgrade 거절 경로. `queueIndexedDbUpgradeBinding`의 `onRejected`가 비동기라 `.then` 후처리로 보존했으나, **가짜 IDB의 upgrade 트랜잭션이 동기라 단위 테스트로 검증할 수 없다.** 레포 전체에 이 경로를 덮는 테스트가 없다. **실브라우저 확인이 필요하다.** + +### 검증 결과 + +**PASS:** `check:types` `lint` `check:architecture` `check:adapter-inventory`(21/21 래칫) `check:bundle`(181114/204800, 이행 전과 동일) `test:integration`(81) `test:component`(130) + +**`test:unit`:** 실패 파일은 `tests/unit/ci-artifact-contract.test.ts` 하나뿐(16~18건, 실행마다 흔들림 — `bwrap: loopback: Failed RTM_NEWADDR`). `develop` `5434760` 기준선에서도 동일함을 stash 후 실행해 확인했다. **그 파일 밖 실패 0.** + +**실브라우저 미검증:** `tests/browser-capabilities/indexeddb-runtime.spec.ts`(1033) · `opfs-runtime.spec.ts`(221) · `resumable-upload.spec.ts`(526). 전부 가짜 IDB 위에서만 검증됐다. blocked/versionchange 실동작과 위 upgrade 경로는 여기서만 잡힌다. **CI 또는 로컬 브라우저 실행이 남은 과제다.** diff --git a/docs/superpowers/specs/2026-09-16-adapter-barrel-boundary-design.md b/docs/superpowers/specs/2026-09-16-adapter-barrel-boundary-design.md new file mode 100644 index 0000000..92ac715 --- /dev/null +++ b/docs/superpowers/specs/2026-09-16-adapter-barrel-boundary-design.md @@ -0,0 +1,751 @@ +# 어댑터 배럴(`index.ts`)을 공개 경계로 승격 — 설계서 + +- 대상 레포: `/home/donghyeon/workspace/desktop-server-git/clean-architecture-frontend-template` +- 브랜치: `develop` (기준 커밋 `5434760`) +- 전제(이미 확정): 배럴 폐지안은 기각. `src/adapters//index.ts`를 **진짜 공개 경계**로 만든다. +- 게이트 기준선: `check:architecture` PASS, `check:types:app` PASS 유지. +- 이 문서는 설계만 한다. 소스 수정·빌드·테스트 실행 없음. + +--- + +## 0. 요약 (먼저 읽을 것) + +| 항목 | 판정 | +|---|---| +| 배럴 표기 표준 | **명명 재수출(named re-export)**. `export *`는 "이미 명시적인 서브배럴을 합칠 때"만 허용 | +| 새로 만들 배럴 | 8개, 합계 114줄 (auth 9 / diagnostics 7 / telemetry 7 / storage 4 / service-worker 17 / query-cache 21 / platform 22 / http 27) | +| `platform/` | 배럴은 만든다. 단 **어댑터→커널 간선은 파일 직접 import를 유지**한다 (게이트가 그걸 요구함) | +| `storage/` | 최상위 배럴은 **서브폴더를 재수출하지 않는다**. `indexeddb/index.ts`·`opfs/index.ts`가 곧 경계다 | +| `http/` | V3(`createContractHttpExecutor`)가 권장 경로, V2(`createHttpClient`)는 legacy 보존. 둘 다 배럴에 넣고 주석으로 표시 | +| 치환할 import | `src/` 15줄 (배럴 경유 2줄은 이미 합격) + `.storybook/` 2줄(선택) | +| 게이트 | `.dependency-cruiser.json`에 규칙 1개 추가. `tests/`는 대상 아님(스캔 범위가 `src`뿐) | +| 최대 위험 | 번들 예산. `package.json`에 `sideEffects` 선언이 없어 배럴이 초기 청크를 키울 수 있다 | + +--- + +## 1. 기존 배럴 8개의 지배적 관례 + +읽은 파일: `src/adapters/{browser-files,browser-file-storage,browser-rpc,browser-transfer,cache-storage,cross-context-invalidation,realtime,web-push}/index.ts` +추가로 서브배럴 8개: `browser-transfer/{image-cdn,presigned,resumable-upload}/index.ts`, `realtime/{polling,sse,websocket}/index.ts`, `storage/{indexeddb,opfs}/index.ts` + +### 1.1 관례 (문장으로) + +1. **소스 파일 단위로 블록을 만들고, 블록마다 `export { ... } from "./파일.ts";` 로 이름을 전부 적는다.** + 블록이 전부 타입이면 `export type { ... } from "...";` 형태를 쓴다 (`browser-files/index.ts:1`, `:28`, `:52`, `:53`). +2. **블록 안 순서는 「값 먼저, 타입 나중」이고 각각 대소문자 무시 알파벳순이다.** + 근거: `web-push/index.ts:42-51` — `createLinkedAbortController, failureCode, nativeFailure, observeWebPush, systemTimeoutScheduler, withAbortableDeadline, type LinkedAbortController, type TimeoutScheduler`. + 상수도 값이므로 같은 줄에 섞인다: `realtime/index.ts:13-22` — `parseRetryAfterDelay, REALTIME_RECONNECT_CEILINGS, reconnectBudgetRemaining` (대소문자 무시로 `parse < realtime_ < reconnect`). + 타입은 인라인 `type X` 접두어로 쓴다 (`browser-rpc/index.ts:9-18`). +3. **블록(파일) 순서는 대체로 알파벳순이되 엄격하지 않다.** 하위 폴더 블록은 뒤로 몰아둔다 (`web-push/index.ts:59`, `:66`의 `./inbound/*`). + 엄격하지 않은 실례: `cross-context-invalidation/index.ts`는 `browser-cross-context-invalidation.ts`(:1) 다음에 `browser-cross-context-host.ts`(:20) — 역순. +4. **배럴은 그룹의 전체 export 목록이 아니다.** 그룹 안에 배럴에 없는 파일이 실제로 존재한다. + 근거: `src/adapters/realtime/result.ts`는 export를 가지지만 `realtime/index.ts` 어디에도 없다. `browser-files/browser-file-vault.ts`도 `browser-files/index.ts`에 없다. + → 즉 이 레포는 이미 "배럴 = 선별된 공개 표면"을 실천하고 있다. 새 배럴도 같은 기준으로 고르면 된다. +5. (참고, 따라하지 말 것) `browser-files/index.ts:1-16`은 어댑터가 아니라 **application 포트 타입**을 재수출한다. 배럴이 하위 레이어의 통로가 되는 형태라 새 배럴에서는 재현하지 않는다. 필요하면 소비자가 포트에서 직접 가져오면 된다. + +### 1.2 `export *`는 표준인가 — 판정 + +**표준은 명명 재수출이다. `export *`는 예외가 아니라 "서브배럴 합성" 전용 관용구다.** + +근거: + +- `export *`가 쓰인 곳은 단 두 파일, 여섯 줄이다. + - `src/adapters/browser-transfer/index.ts:1-3` — `./image-cdn/index.ts`, `./presigned/index.ts`, `./resumable-upload/index.ts` + - `src/adapters/realtime/index.ts:56-58` — `./polling/index.ts`, `./sse/index.ts`, `./websocket/index.ts` +- **여섯 줄 전부 대상이 `index.ts`(서브배럴)다.** 구현 파일(`.ts`)을 `export *`로 푼 사례는 0건이다. +- 그리고 그 서브배럴들은 자기 자신이 전부 명명 재수출이다 (`browser-transfer/image-cdn/index.ts:1-6`, `realtime/sse/index.ts:1-9` 등). +- `realtime/index.ts`는 한 파일 안에서 두 형태를 동시에 쓴다: 1-55줄은 구현 파일에 대한 명명 재수출, 56-58줄은 서브배럴에 대한 `export *`. 즉 `browser-transfer`만 특이한 게 아니라, **대상이 서브배럴이냐 구현 파일이냐**가 형태를 가른다. + +왜 이 구분이 옳은가: 지시대로 `export *`는 "무엇이 공개되는지 파일을 열어야 안다"는 문제가 있다. 그런데 대상이 서브배럴이면 그 파일 자체가 이미 명시적 목록이므로, `export *` 한 줄을 따라가면 곧바로 명시적 목록에 도달한다. 목록이 사라지는 게 아니라 한 단계 아래에 있는 것뿐이다. 반대로 구현 파일을 `export *`하면 목록이 어디에도 없어진다. + +**채택 규칙** + +> 배럴은 구현 파일(`*.ts`)에 대해서는 반드시 이름을 하나씩 적는다. +> `export *`는 대상이 같은 그룹의 서브배럴(`*/index.ts`)일 때만 쓴다. + +새로 만드는 8개 중 `export *`를 쓸 자리는 **없다** (아래 §3.7에서 `storage`가 서브배럴을 재수출하지 않기로 판정하므로). + +--- + +## 2. 공개/내부 판정 기준 + +판정 근거는 실제 사용처다. 측정 명령: + +``` +grep -rnE 'from "[^"]*adapters/(auth|browser-files|browser-file-storage|browser-rpc|browser-transfer|cache-storage|cross-context-invalidation|diagnostics|http|platform|query-cache|realtime|service-worker|storage|telemetry|web-push)/' src/ --include='*.ts' --include='*.tsx' | grep -v '^src/adapters/' +``` + +- **공개**: `src/bootstrap/**`, `src/features/**`, `src/presentation/**`이 import하는 심볼 + 그 심볼의 시그니처에 이름으로 등장하는 타입(의존성/옵션/반환 파사드). +- **내부**: 그룹 안에서만 쓰이는 헬퍼. +- **내부(테스트 전용)**: `tests/`만 import하는 심볼. 배럴에 넣지 않고, 테스트는 깊은 경로를 유지한다. 각 그룹에서 별도로 표시했다. + +예외 처리 하나: 같은 파일의 동급 팩토리 형제는 오늘 테스트만 쓰더라도 공개로 올린다(예 `createAnonymousSessionAdapter`). 근거는 §3.1. + +--- + +## 3. 새로 만들 배럴 8개 (전문) + +아래 내용은 전부 **그대로 파일로 저장 가능**하다. 모든 심볼은 기계 대조로 존재를 확인했다(82개 전수, §7). + +### 3.1 `src/adapters/auth/index.ts` + +그룹 파일: `external-session-adapter.ts` 1개. + +| 심볼 | 위치 | 판정 | 근거 | +|---|---|---|---| +| `createExternalAuthSessionAdapter` | `external-session-adapter.ts:51` | 공개 | `src/bootstrap/runtime-adapters.ts:3` | +| `createDemoSessionAdapter` | `:104` | 공개 | `src/bootstrap/runtime-adapters.ts:2`, `:279` | +| `createUnavailableSessionAdapter` | `:140` | 공개 | `src/bootstrap/runtime-adapters.ts:4` | +| `createAnonymousSessionAdapter` | `:77` | 공개(승격) | 위 셋과 같은 파일·같은 반환형(`AuthSessionPort`)의 형제 팩토리. 오늘 `src` 소비자는 `.storybook/preview.tsx:5`뿐이라 배럴이 없으면 깊은 경로가 남는다 | +| `DEMO_AUTHORIZATION_MARKER` | `:98` | 공개 | 계약 문서가 이름으로 참조: `docs/architecture/decisions/VD-23-api-transport-selection-and-rest-execution.md:305` | +| `ExternalSessionOwner` | `:10` | 공개 | `src/bootstrap/runtime-adapters.ts:5` | +| `DemoSessionAdapter` | `:89` | 공개 | `createDemoSessionAdapter`의 반환 타입 | +| `validateCredentialPatch` | `:26` | **내부** | `src/`·`tests/` 어디서도 import하지 않음 | + +```ts +export { + createAnonymousSessionAdapter, + createDemoSessionAdapter, + createExternalAuthSessionAdapter, + createUnavailableSessionAdapter, + DEMO_AUTHORIZATION_MARKER, + type DemoSessionAdapter, + type ExternalSessionOwner, +} from "./external-session-adapter.ts"; +``` + +--- + +### 3.2 `src/adapters/diagnostics/index.ts` + +그룹 파일: `bounded-diagnostics.ts` 1개. export 5개 전부 공개. + +| 심볼 | 위치 | 판정 | 근거 | +|---|---|---|---| +| `createDiagnosticsAdapter` | `bounded-diagnostics.ts:18` | 공개 | `src/bootstrap/runtime-adapters.ts:7` | +| `recordBootFailure` | `:80` | 공개 | `src/bootstrap/main.tsx:3` | +| `getLastBootEvidence` | `:108` | 공개 | `recordBootFailure`의 짝(부팅 증거 읽기). 오늘 사용처는 `tests/`만 | +| `noOpDiagnostics` | `:11` | 공개 | `DiagnosticsPort`의 null object. 다른 그룹이 기본값으로 기대하는 형태 | +| `MAX_DIAGNOSTIC_ENTRIES` | `:16` | 공개 | 선언된 상한값(계약 수치) | + +```ts +export { + createDiagnosticsAdapter, + getLastBootEvidence, + MAX_DIAGNOSTIC_ENTRIES, + noOpDiagnostics, + recordBootFailure, +} from "./bounded-diagnostics.ts"; +``` + +--- + +### 3.3 `src/adapters/telemetry/index.ts` + +그룹 파일: `best-effort-telemetry.ts` 1개. + +| 심볼 | 위치 | 판정 | 근거 | +|---|---|---|---| +| `createTelemetryAdapter` | `best-effort-telemetry.ts:52` | 공개 | `src/bootstrap/runtime-adapters.ts:29` | +| `noOpTelemetry` | `:31` | 공개 | null object | +| `MAX_TELEMETRY_QUEUE` | `:47` | 공개 | 선언된 상한값 | +| `TelemetryAdapter` | `:10` | 공개 | 팩토리 반환 타입 | +| `TelemetryAdapterOptions` | `:20` | 공개 | 팩토리 인자 타입 | +| `safeTraceparent` | `:229` | **내부(테스트 전용)** | `tests/`만 import. traceparent 정규화는 어댑터 내부 동작 | +| `assertBoundedCapacity` 재수출 | `:49` | **배럴에 넣지 않음** | 이건 telemetry의 export가 아니라 **커널(`../platform/bounded-capacity.ts`) 심볼의 재수출**이다. 배럴에 올리면 커널로 가는 두 번째 문이 생긴다 | + +> **부수 발견 / 별도 처리 권고** +> `src/adapters/telemetry/best-effort-telemetry.ts:49` +> ```ts +> export { assertBoundedCapacity } from "../platform/bounded-capacity.ts"; +> ``` +> 이 줄은 이 배럴 작업과 무관하게 지우는 게 맞다. 같은 파일 `:8`에서 이미 같은 심볼을 import해서 `:61`에서 쓰고 있으므로 재수출은 순수 잉여이고, 실제 소비자도 없다(`grep -rn 'assertBoundedCapacity' src/ tests/` → `platform/bounded-capacity.ts` 정의부, `telemetry:8,49,61`, `diagnostics:9,25`가 전부). 이 문서 범위에서는 **건드리지 않고** 배럴에서 제외만 한다. + +```ts +export { + createTelemetryAdapter, + MAX_TELEMETRY_QUEUE, + noOpTelemetry, + type TelemetryAdapter, + type TelemetryAdapterOptions, +} from "./best-effort-telemetry.ts"; +``` + +--- + +### 3.4 `src/adapters/platform/index.ts` — 커널 + +#### 판정: 배럴은 만들되, **어댑터→커널 간선은 파일 직접 import를 유지한다.** + +질문은 "`browser-transfer/presigned/presigned-transfer-executor.ts:15`의 `../../platform/abortable-operation.ts`가 `../../platform/index.ts`로 바뀌어야 하는가"였다. **아니다. 바꾸면 게이트가 깨진다.** + +**근거 1 (결정적) — `check:adapter-inventory`가 파일 경로를 직접 검증한다.** +`scripts/check-adapter-inventory.ts:63-83`: + +```ts +const PRIMITIVE_PATH = path.resolve("src/adapters/platform/abortable-operation.ts"); +for (const consumer of REQUIRED_ABORT_CONSUMERS) { + ... + const specifiers = [...source.matchAll(/from\s+"([^"]*platform\/abortable-operation\.ts)"/gu)]...; + const resolved = specifiers.some( + (specifier) => path.resolve(path.dirname(consumer), specifier) === PRIMITIVE_PATH, + ); + if (!resolved) { problems.push(`abortable-operation: ${consumer} does not resolve...`); } +} +``` + +`REQUIRED_ABORT_CONSUMERS`(`scripts/check-adapter-inventory.ts:134-137`)는 정확히 네 파일이다: +`browser-transfer/presigned/presigned-capability-http-provider.ts`, `.../presigned-transfer-executor.ts`, `browser-transfer/image-cdn/browser-image-probe.ts`, `browser-transfer/resumable-upload/fetch-json-transport.ts`. +이들이 `../../platform/index.ts`로 바뀌면 정규식이 매칭되지 않아 `check:adapter-inventory`가 실패한다. + +**근거 2 — 규칙상으로는 둘 다 가능하지만, 커널의 정체성은 "파일"이다.** +`.dependency-cruiser.json:191`의 carve-out은 `^src/adapters/($1/|platform/|browser-file-storage/result\.ts$|cross-context-invalidation/index\.ts$)` 로 `platform/` 폴더 전체를 허용한다. 즉 규칙은 중립이다. +그런데 `docs/architecture/layers.md:34`는 커널을 "the system clock, the shared abort primitive and the bounded-capacity guard" — **세 개의 프리미티브**로 정의한다. 런타임 합성물이 아니라 원시 도구다. 원시 도구는 "어느 파일에서 왔는지"가 곧 정체성이고, 실제로 위 게이트가 그 정체성을 파일 경로로 확인한다. + +**근거 3 — 그래서 새 게이트 규칙은 `src/adapters/**`를 출발점에서 제외한다.** +어댑터끼리의 간선은 이미 `adapters-do-not-know-other-concrete-adapters`(`.dependency-cruiser.json:183-193`)가 담당한다. 새 규칙이 그 위에 겹칠 이유가 없다. §5의 `from.pathNot: "^src/adapters/"`가 이 판정의 실행형이다. + +#### 그러면 배럴에는 뭘 넣나 + +커널 프리미티브도 **전부** 넣는다. 이유: 배럴을 쓰는 쪽은 `src/bootstrap`과 `tests`인데, 이들은 `systemClock`(tests), `createAbortableOperation`(tests), `createBrowserLifecycleRuntime`(`src/bootstrap/optional-runtime-host.ts:2`), `createBrowserMutationIntentFactory`(`src/bootstrap/runtime-adapters.ts:28`)를 쓴다. 일부만 넣으면 "바깥은 배럴만"이라는 규칙에 예외가 생긴다. 두 개의 문이 생기는 게 아니라 **문이 소비자별로 하나씩**이다: 어댑터는 파일, 그 외는 배럴. + +| 파일 | 공개 심볼 | 소비자 근거 | +|---|---|---| +| `abortable-operation.ts` | `createAbortableOperation:90`, `compensateLateHandle:261`, `snapshotAbortTimers:70`, `AbortableOperation:24`, `AbortableOperationInput:51`, `AbortRace:19`, `AbortTerminalReason:11`, `AbortTimerSnapshot:59` | 어댑터 4곳(직접 경로 유지) + `tests/` | +| `bounded-capacity.ts` | `assertBoundedCapacity:10` | `diagnostics:9`, `telemetry:8` (직접 경로 유지) | +| `browser-lifecycle.ts` | `createBrowserLifecycleRuntime:57`, `BrowserLifecycleEvent:20`, `BrowserLifecycleRuntime:36`, `BrowserLifecycleSnapshot:13` | `src/bootstrap/optional-runtime-host.ts:1-4` | +| `browser-mutation-intent-factory.ts` | `createBrowserMutationIntentFactory:9`, `BrowserMutationIntentFactoryDependencies:4` | `src/bootstrap/runtime-adapters.ts:28` | +| `system-clock.ts` | `systemClock:3` | 어댑터 6곳(직접 경로 유지) + `tests/` | + +내부: 없음. 이 그룹은 모든 export가 커널 표면이다. + +```ts +/** + * 어댑터 커널의 공개 경계. + * + * `src/adapters/**` 안에서는 이 배럴을 쓰지 않는다. 커널 프리미티브는 파일 + * 경로로 직접 import한다 — `scripts/check-adapter-inventory.ts`가 + * `platform/abortable-operation.ts`로 해석되는 specifier를 네 소비자에게 + * 요구하고, `.dependency-cruiser.json`의 kernel carve-out도 폴더 단위다. + * 이 배럴은 bootstrap·features·tests 같은 그룹 바깥 소비자를 위한 문이다. + */ +export { + compensateLateHandle, + createAbortableOperation, + snapshotAbortTimers, + type AbortableOperation, + type AbortableOperationInput, + type AbortRace, + type AbortTerminalReason, + type AbortTimerSnapshot, +} from "./abortable-operation.ts"; +export { assertBoundedCapacity } from "./bounded-capacity.ts"; +export { + createBrowserLifecycleRuntime, + type BrowserLifecycleEvent, + type BrowserLifecycleRuntime, + type BrowserLifecycleSnapshot, +} from "./browser-lifecycle.ts"; +export { + createBrowserMutationIntentFactory, + type BrowserMutationIntentFactoryDependencies, +} from "./browser-mutation-intent-factory.ts"; +export { systemClock } from "./system-clock.ts"; +``` + +--- + +### 3.5 `src/adapters/query-cache/index.ts` + +파일 5개, 파일마다 팩토리 1~3개. 전부 공개(4개는 bootstrap이 직접, `createCursorPaginationRuntime`·`createQueryCacheAdapter`는 동급 팩토리). + +| 심볼 | 위치 | 근거 | +|---|---|---| +| `createConditionalValidatorStore` | `conditional-validator-store.ts:55` | `src/bootstrap/runtime-adapters.ts:26` | +| `ConditionalValidatorBinding` / `ConditionalValidatorStore` | `:3` / `:10` | 위 팩토리의 반환·요소 타입 | +| `createCursorPaginationRuntime` | `cursor-pagination-runtime.ts:49` | 동급 런타임 팩토리(오늘 소비자는 `tests/`만) | +| `createServerStateScopeRuntime` | `server-state-scope-runtime.ts:34` | `src/bootstrap/runtime-adapters.ts:25` | +| `ScopeResetParticipant` / `ServerStateScopeDependencies` | `:19` / `:26` | 위 팩토리의 인자 타입 | +| `createTanStackCacheCoordinator` | `tanstack-cache-coordinator.ts:33` | `src/bootstrap/runtime-adapters.ts:22` | +| `TanStackCacheCoordinatorDependencies` | `:21` | 인자 타입 | +| `createQueryClient` | `tanstack-query-cache.ts:21` | `src/bootstrap/runtime-adapters.ts:24`, `.storybook/preview.tsx:6` | +| `createQueryCacheAdapter` | `:59` | 동급 팩토리(`QueryCachePort` 구현) | +| `QUERY_CACHE_DEFAULTS` | `:12` | 선언된 기본값 | +| `QueryCacheDependencies` | `:8` | 인자 타입 | + +내부: 없음. + +> 주의: 이 그룹은 `.dependency-cruiser.json:184`가 명시적으로 이름 붙인 미해결 간선의 출발점이다 — `tanstack-cache-coordinator.ts:19`가 `../cross-context-invalidation/index.ts`에서 협력자 타입 2개를 읽는다. 배럴 작업은 이 간선을 건드리지 않는다(어댑터→어댑터 간선이므로 새 규칙 범위 밖). + +```ts +export { + createConditionalValidatorStore, + type ConditionalValidatorBinding, + type ConditionalValidatorStore, +} from "./conditional-validator-store.ts"; +export { createCursorPaginationRuntime } from "./cursor-pagination-runtime.ts"; +export { + createServerStateScopeRuntime, + type ScopeResetParticipant, + type ServerStateScopeDependencies, +} from "./server-state-scope-runtime.ts"; +export { + createTanStackCacheCoordinator, + type TanStackCacheCoordinatorDependencies, +} from "./tanstack-cache-coordinator.ts"; +export { + createQueryCacheAdapter, + createQueryClient, + QUERY_CACHE_DEFAULTS, + type QueryCacheDependencies, +} from "./tanstack-query-cache.ts"; +``` + +--- + +### 3.6 `src/adapters/service-worker/index.ts` + +#### 제약 하나 먼저 + +`tsconfig.app.json:14-19`의 `exclude`에 `src/adapters/service-worker/service-worker-entry.ts`가 들어 있다. **배럴은 이 파일을 절대 참조하면 안 된다** — 참조하면 app 타입체크가 제외된 파일을 끌어들인다. 다행히 `service-worker-entry.ts`는 export가 0개라(`grep -n '^export ' → 없음`) 넣을 것도 없다. + +| 파일 | 판정 | 근거 | +|---|---|---| +| `service-worker-page-controller.ts` | 공개 | `src/bootstrap/register-service-worker.ts:5`가 `createServiceWorkerPageController`를 씀 | +| `service-worker-lifecycle.ts` | 공개 | 워커 realm 진입점(`service-worker-entry.ts:11`)이 합성하는 런타임. 그룹 바깥(워커 번들·tests)이 실제 소비자 | +| `service-worker-protocol.ts` | 공개 | 페이지↔워커 메시지 코덱. 양쪽 realm이 공유하는 어휘 | +| `service-worker-removal.ts` | **내부** | 소비자는 `service-worker-page-controller.ts:20`(그룹 내) + `tests/`뿐 | +| `service-worker-static-assets.ts` | **내부** | 소비자는 `service-worker-lifecycle.ts:17`(그룹 내) + `tests/`뿐 | +| `service-worker-entry.ts` | 대상 아님 | export 0개 + `tsconfig.app.json` 제외 | + +내부(테스트 전용)로 남아 깊은 경로를 유지할 심볼: `removeOwnedRegistration`, `purgeOwnedResources`, `isOwnedRegistration`, `expectedServiceWorkerUrls`(`service-worker-removal.ts:33,65,89,138`), `installStaticAssets`, `classifyFetch`, `validateStaticAssetManifest`, `selectCachesToDelete`(`service-worker-static-assets.ts:35,85,119,377`). + +```ts +export { + createServiceWorkerRuntime, + type WorkerClientLike, + type WorkerRuntimeConfig, + type WorkerScopeLike, +} from "./service-worker-lifecycle.ts"; +export { + createServiceWorkerPageController, + type ActivationBlocker, + type PageControllerDependencies, +} from "./service-worker-page-controller.ts"; +export { + createNonceRegistry, + createServiceWorkerMessage, + parseServiceWorkerMessage, + type ParsedMessage, +} from "./service-worker-protocol.ts"; +``` + +--- + +### 3.7 `src/adapters/storage/index.ts` + +#### 판정: 최상위 배럴은 서브폴더를 재수출하지 **않는다**. 서브폴더 배럴이 곧 경계다. + +`browser-transfer/index.ts:1-3`과 `realtime/index.ts:56-58`의 선례를 따라 `export * from "./indexeddb/index.ts"`를 넣고 싶어지지만, **storage에서는 그게 게이트를 깬다.** + +**근거 (결정적) — 제거 드릴이 서브폴더만 삭제한다.** +`scripts/test-browser-file-storage-runtime-removal.ts:23-34`: + +```ts +const runtimePaths = [ + ... + "src/adapters/storage/indexeddb", + "src/adapters/storage/opfs", + ... +] as const; +``` + +이 스크립트는 fixture 트리에서 위 경로를 `rm -rf`한 뒤(`:56-61`) `assertNoRuntimeImports(fixtureRoot, runtimeSourceRoots, ...)`를 호출한다(`:129-133`). 그 함수는 `scripts/lib/removal-fixture.ts:251-260`: + +```ts +const graph = await runtimeImportGraph(root, runtimeSourceRoots); +if (graph.importingFiles.length > 0) { + throw new Error(`Removed ${capability} runtime is still imported by: ...`); +} +``` + +즉 `src/adapters/storage/index.ts`가 `./indexeddb/index.ts`를 재수출하면, 삭제 후에도 그 파일이 살아남아 삭제된 런타임을 import하는 상태가 되어 드릴이 **즉시 예외로 실패**한다. 그 뒤에 이어지는 `check:types` / `lint` / `check:architecture` / `build`(`:135-143`)까지 전부 못 간다. + +**대조 — realtime·browser-transfer는 왜 괜찮은가.** +`scripts/test-realtime-runtime-removal.ts:21-31`은 `src/adapters/realtime` **폴더 전체**를 지운다. `browser-file-storage` 드릴도 `src/adapters/browser-transfer` 전체를 지운다(`test-browser-file-storage-runtime-removal.ts:28`). 배럴이 폴더와 함께 사라지므로 문제가 없다. **storage만 부분 삭제 대상**이다 — 최상위 `browser-storage-adapter.ts`(localStorage/sessionStorage KV)는 남고 IndexedDB·OPFS 런타임만 빠진다. + +**따라서:** +- `src/adapters/storage/index.ts` = 최상위 파일들만. +- `src/adapters/storage/indexeddb/index.ts`, `src/adapters/storage/opfs/index.ts` = 각 제거 가능 런타임의 공개 경계. **이미 존재하고 이미 명명 재수출이다.** 새로 만들 필요 없다. +- §5의 게이트 정규식은 그래서 1단계 중첩 `index.ts`까지 배럴로 인정해야 한다. + +| 심볼 | 위치 | 판정 | 근거 | +|---|---|---|---| +| `createBrowserStorageAdapter` | `browser-storage-adapter.ts:35` | 공개 | `src/bootstrap/runtime-adapters.ts:27` | +| `BrowserStorageDependencies` | `:20` | 공개 | 팩토리 인자 타입. 필드가 전부 원시형/포트라 codec 타입을 노출하지 않는다(`:20-27` 확인) | +| `browser-storage-codec.ts` 전체 (`DEFAULT_BROWSER_STORAGE_MAX_SERIALIZED_BYTES:1`, `encodeBrowserStorageEnvelope:31`, `decodeBrowserStorageEnvelope:57`, `assertValidBrowserStorageByteLimit:88`, `BrowserStorageEnvelope:11`, `BrowserStorageCodecFailure:17`, `BrowserStorageCodecResult:22`) | — | **내부** | 유일한 소비자가 `browser-storage-adapter.ts:14-18`(그룹 내). `src/`·`tests/` 어디서도 직접 import 없음 | + +```ts +export { + createBrowserStorageAdapter, + type BrowserStorageDependencies, +} from "./browser-storage-adapter.ts"; +``` + +> **서브배럴 보완 권고 (별건, 이 문서 범위 밖)** +> `tests/unit/opfs-byte-store.test.ts:25,28`가 `OPFS_WORKER_PROTOCOL_VERSION`(`opfs/opfs-worker-protocol.ts:23`), `PreparePhysicalObjectRequest`(`:179`), `writeWithSyncAccessHandle`(`opfs/opfs-worker-runtime.ts:1363`)를 쓰는데 이 셋은 `opfs/index.ts`에 없다. 테스트를 배럴로 옮길 때(§4.2) 함께 결정해야 한다 — 올리거나, 내부로 확정하고 테스트가 깊은 경로를 유지하거나. + +--- + +### 3.8 `src/adapters/http/index.ts` + +#### V2 / V3 판정 + +**V3(`createContractHttpExecutor`, `http-execution-v3.ts:377`)가 권장 경로.** V2(`createHttpClient`, `client.ts:138`)는 legacy 보존. + +근거: +1. `src/adapters/http/client.ts:121`에 `LegacyHttpInput`이라는 타입이 있고, 공개 시그니처 `HttpClient.execute`(`:131-137`)가 그걸 두 번째 인자로 받는다. 파일이 스스로 legacy라고 말한다. +2. `src/adapters/http/http-execution-v3.ts:45-51` 헤더 주석: "§7–§8. Descriptor-driven HTTP execution. ... the runtime owns bounds, the total deadline, the single retry authority and the effect-certainty verdict." — 계약 기반 실행이 V3에 있다. +3. 라이브 경로가 V3다. `src/bootstrap/runtime-adapters.ts:423`이 `createContractHttpExecutor`를 조립해 실제 런타임에 넣는다. 반면 V2 래퍼 `createRuntimeHttpClient`(`src/bootstrap/runtime-adapters.ts:163`)의 유일한 호출자는 `tests/unit/runtime-adapters.test.ts:371`이다 (`grep -rn 'createRuntimeHttpClient' src/ tests/` 결과 3줄: 정의 1 + 테스트 2). +4. V3 타입은 이미 feature 경계를 넘는다: `src/features/reference-feature/adapters/create-reference-feature-input.ts:9`가 `HttpExecutionOutcome`를 import한다. + +둘 다 배럴에 넣되 **블록 순서로 V3를 먼저 두고 주석으로 표시**한다. + +#### 공개 표면 + +| 파일 | 판정 | 근거 | +|---|---|---| +| `http-execution-v3.ts` | 공개 | `src/bootstrap/runtime-adapters.ts:10,11`, `src/features/reference-feature/adapters/create-reference-feature-input.ts:9` | +| `client.ts` | 공개(legacy) | `src/bootstrap/runtime-adapters.ts:8` | +| `http-contract-bridge.ts` | `CredentialPatchOutcome`만 공개 | `http-execution-v3.ts:292`의 공개 시그니처 `attachCredentials(...): Promise \| CredentialPatchOutcome`에 이름으로 등장 → bootstrap이 그 콜백을 구현한다(`src/bootstrap/runtime-adapters.ts:434` 부근) | +| `request-builder.ts` | `OperationRequestInput`만 공개 | `client.ts:133`의 공개 시그니처 `execute(request: string \| OperationRequestInput, ...)`에 이름으로 등장 | +| `bounded-body-reader.ts` | **내부** | 소비자는 `bounded-json.ts:1`, `http-execution-v3.ts:18-20`(그룹 내) + `tests/` | +| `bounded-json.ts` | **내부** | 소비자는 `client.ts:45`(그룹 내) + `tests/` | +| `http-effect-certainty.ts` | **내부** | 소비자는 `http-execution-v3.ts:38-42`(그룹 내) + `tests/` | +| `retry-policy.ts` | **내부** | 소비자는 `client.ts:9`, `http-execution-v3.ts:43`(그룹 내) + `tests/` | +| `schema-registry.ts` | **내부** | 소비자는 `client.ts:14`(그룹 내) + `tests/` | +| `resource-mapper.ts` | **내부** | 소비자는 `client.ts:8`(그룹 내) + `tests/` | +| `http-contract-bridge.ts` 나머지 11개 | **내부** | 그룹 내 + `tests/` | +| `request-builder.ts` 나머지 2개 (`buildRequestTarget:28`, `RequestTargetResult:14`) | **내부(테스트 전용)** | `tests/`만 | + +```ts +/** + * §7–§8. 권장 경로는 V3 계약 실행기(`createContractHttpExecutor`)다. 설치된 + * 계약과 타입 입력을 받아 상한·전체 데드라인·재시도 권한·효과 확실성 판정을 + * 런타임이 소유한다. + */ +export { + createContractHttpExecutor, + type AuthIntegrationFailureReason, + type AuthOperationContext, + type CancellationOwner, + type ContractHttpExecutor, + type ContractHttpExecutorDependencies, + type HttpContractViolation, + type HttpContractViolationKind, + type HttpEffectCertainty, + type HttpExecutionContext, + type HttpExecutionObservation, + type HttpExecutionOutcome, + type HttpTransportFailure, + type SafeResponseMetadata, +} from "./http-execution-v3.ts"; +/** V3 `attachCredentials` 콜백이 반환해야 하는 결과 타입. */ +export type { CredentialPatchOutcome } from "./http-contract-bridge.ts"; +/** + * V2 legacy. operationId + `LegacyHttpInput`으로 호출하는 범용 클라이언트다. + * 새 코드는 위의 V3 실행기를 쓴다. 남아 있는 이유는 계약이 아직 없는 + * 오퍼레이션을 위한 이행 경로이기 때문이다. + */ +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"; +``` + +--- + +## 4. 호출처 치환 목록 + +### 4.1 `src/` — 전수 (17줄) + +측정: §2의 grep. 17줄 중 2줄은 이미 배럴 경유라 변경 없음. 실제 치환 대상 **15줄**. + +| # | 파일:줄 | 현재 specifier | 바뀔 specifier | 비고 | +|---:|---|---|---|---| +| 1 | `src/bootstrap/main.tsx:3` | `../adapters/diagnostics/bounded-diagnostics.ts` | `../adapters/diagnostics/index.ts` | `recordBootFailure` | +| 2 | `src/bootstrap/optional-runtime-host.ts:4` | `../adapters/platform/browser-lifecycle.ts` | `../adapters/platform/index.ts` | 블록 시작은 `:1` | +| 3 | `src/bootstrap/register-service-worker.ts:5` | `../adapters/service-worker/service-worker-page-controller.ts` | `../adapters/service-worker/index.ts` | `createServiceWorkerPageController` | +| 4 | `src/bootstrap/runtime-adapters.ts:6` | `../adapters/auth/external-session-adapter.ts` | `../adapters/auth/index.ts` | 블록 시작 `:1` | +| 5 | `src/bootstrap/runtime-adapters.ts:7` | `../adapters/diagnostics/bounded-diagnostics.ts` | `../adapters/diagnostics/index.ts` | `createDiagnosticsAdapter` | +| 6 | `src/bootstrap/runtime-adapters.ts:8` | `../adapters/http/client.ts` | `../adapters/http/index.ts` | **7번과 한 블록으로 합칠 것** | +| 7 | `src/bootstrap/runtime-adapters.ts:12` | `../adapters/http/http-execution-v3.ts` | `../adapters/http/index.ts` | 블록 시작 `:9` | +| 8 | `src/bootstrap/runtime-adapters.ts:20` | `../adapters/cross-context-invalidation/index.ts` | (변경 없음) | 이미 배럴 | +| 9 | `src/bootstrap/runtime-adapters.ts:23` | `../adapters/query-cache/tanstack-cache-coordinator.ts` | `../adapters/query-cache/index.ts` | 블록 시작 `:21`. **9~12를 한 블록으로 합칠 것** | +| 10 | `src/bootstrap/runtime-adapters.ts:24` | `../adapters/query-cache/tanstack-query-cache.ts` | `../adapters/query-cache/index.ts` | `createQueryClient` | +| 11 | `src/bootstrap/runtime-adapters.ts:25` | `../adapters/query-cache/server-state-scope-runtime.ts` | `../adapters/query-cache/index.ts` | `createServerStateScopeRuntime` | +| 12 | `src/bootstrap/runtime-adapters.ts:26` | `../adapters/query-cache/conditional-validator-store.ts` | `../adapters/query-cache/index.ts` | `createConditionalValidatorStore` | +| 13 | `src/bootstrap/runtime-adapters.ts:27` | `../adapters/storage/browser-storage-adapter.ts` | `../adapters/storage/index.ts` | `createBrowserStorageAdapter` | +| 14 | `src/bootstrap/runtime-adapters.ts:28` | `../adapters/platform/browser-mutation-intent-factory.ts` | `../adapters/platform/index.ts` | `createBrowserMutationIntentFactory` | +| 15 | `src/bootstrap/runtime-adapters.ts:29` | `../adapters/telemetry/best-effort-telemetry.ts` | `../adapters/telemetry/index.ts` | `createTelemetryAdapter` | +| 16 | `src/bootstrap/server-state-generation-store.ts:3` | `../adapters/cross-context-invalidation/index.ts` | (변경 없음) | 이미 배럴 | +| 17 | `src/features/reference-feature/adapters/create-reference-feature-input.ts:9` | `../../../adapters/http/http-execution-v3.ts` | `../../../adapters/http/index.ts` | `type HttpExecutionOutcome` | + +**작업 순서 주의.** `runtime-adapters.ts`는 12줄이 한 덩어리(`:6`~`:29`)다. 6·7을 합치고 9~12를 합치면 그 아래 줄 번호가 전부 밀린다. **아래에서 위로 편집**하거나 `:1`~`:29` 블록을 한 번에 다시 쓴다. + +**선택 사항 (게이트 범위 밖, 일관성 목적).** `check:architecture`는 `src`만 스캔하므로(`scripts/check-architecture.ts:69`, `:116-123`) 아래 두 줄은 강제되지 않는다. 같은 커밋에서 정리하는 걸 권한다. + +| 파일:줄 | 현재 | 바뀔 것 | +|---|---|---| +| `.storybook/preview.tsx:5` | `../src/adapters/auth/external-session-adapter.ts` | `../src/adapters/auth/index.ts` | +| `.storybook/preview.tsx:6` | `../src/adapters/query-cache/tanstack-query-cache.ts` | `../src/adapters/query-cache/index.ts` | + +**곁다리 정리 기회 하나.** `src/bootstrap/runtime-adapters.ts:65`가 `type HttpClientDependencies = Parameters[0];`로 타입을 역추출한다. 배럴이 `HttpClientDependencies`를 직접 내보내므로 이 줄은 지우고 import로 대체할 수 있다. 필수는 아니다. + +### 4.2 `tests/` — 그룹별 집계와 권고 + +측정(2026-09-16, `develop` `5434760`): + +``` +grep -rnE 'from "[^"]*adapters/<16개 그룹>/' tests/ --include='*.ts' --include='*.tsx' | grep -v '^tests/fixtures/' +``` + +**166줄 / 83개 파일.** (`tests/fixtures` 포함 시 169줄. 지시문의 184와 다른데, `tests/fixtures`는 `.dependency-cruiser.json:208`에서 제외 대상이고 그 안의 `indexeddb-repository.ts` 같은 경로는 존재하지 않는 금지 recipe fixture다.) + +| 그룹 | 줄 수 | 배럴 존재 | 배럴 경유 | +|---|---:|---|---:| +| browser-transfer | 26 | 기존 | 0 | +| realtime | 24 | 기존 | 1 | +| http | 22 | **신규** | 0 | +| storage | 20 | **신규**(+서브배럴 2) | 0 | +| web-push | 17 | 기존 | 0 | +| browser-files | 17 | 기존 | 1 | +| query-cache | 9 | **신규** | 0 | +| auth | 9 | **신규** | 0 | +| browser-file-storage | 5 | 기존 | 0 | +| service-worker | 4 | **신규** | 0 | +| platform | 3 | **신규** | 0 | +| browser-rpc | 3 | 기존 | 2 | +| diagnostics | 2 | **신규** | 0 | +| cross-context-invalidation | 2 | 기존 | 2 | +| cache-storage | 2 | 기존 | 0 | +| telemetry | 1 | **신규** | 0 | +| **합계** | **166** | | **6** | + +배럴 경유 6줄의 정확한 위치: +`tests/unit/browser-file-runtime.test.ts:13`, `tests/unit/browser-rpc/browser-rpc-remediation.test.ts:9`, `tests/unit/browser-rpc/browser-rpc-runtime.test.ts:11`, `tests/unit/cross-tab-invalidation.test.ts:21`, `tests/unit/realtime/realtime-reconnect-coordinator.test.ts:20`, `tests/unit/tanstack-cache-coordinator.test.ts:7`. + +#### 권고: 한꺼번에 옮기지 않는다. 파일을 건드릴 때 그 파일 것만 옮긴다. + +이유 셋: + +1. **게이트가 강제하지 않는다.** `check:architecture`는 `src`만 본다(`scripts/check-architecture.ts:69`, `:116-123`). 테스트를 지금 옮겨도 검증되는 게 없고, 안 옮겨도 깨지는 게 없다. 강제되지 않는 대량 변경은 리뷰 비용만 남는다. +2. **테스트의 절반 이상이 내부 심볼을 쓴다.** 예: `tests/unit/opfs-byte-store.test.ts:25,28`의 `PreparePhysicalObjectRequest`·`writeWithSyncAccessHandle`은 `opfs/index.ts`에 없다. http의 `retry-policy`·`schema-registry`·`bounded-body-reader` 테스트도 마찬가지로 §3.8에서 내부로 판정한 심볼을 직접 겨눈다. 일괄 치환은 곧 "배럴에 내부 심볼을 밀어넣자"는 압력이 되고, 그러면 배럴이 경계가 아니라 재수출 덤프가 된다. +3. **내부 심볼을 직접 겨누는 단위 테스트는 그래도 된다.** 배럴 규칙은 "그룹 바깥 **프로덕션 코드**는 배럴만"이지 "아무도 내부를 못 본다"가 아니다. 테스트는 구현 계약을 검증하는 게 일이다. + +**실행 규칙 (문서에 남길 문장)** + +> `tests/` 아래 어댑터 import는 배럴로 일괄 이관하지 않는다. +> 어떤 테스트 파일을 **다른 이유로** 수정하거나 분할할 때, 그 파일이 쓰는 심볼이 해당 그룹 배럴에 있으면 그 파일 안에서만 배럴 경로로 바꾼다. +> 배럴에 없는 심볼이면 깊은 경로를 유지한다. 배럴에 추가하고 싶으면 §2 기준으로 "공개"임을 논증하는 게 먼저다. + +우선순위를 굳이 매긴다면: `auth`(9줄, 전부 공개 심볼), `diagnostics`(2줄), `telemetry`(1줄), `query-cache`(9줄) — 이 넷은 배럴이 그룹 표면을 100% 덮으므로 기계적 치환이 가능하다. 21줄. `http`·`storage`·`service-worker`는 내부 심볼 비중이 커서 파일 단위로만 접근한다. + +--- + +## 5. 게이트로 강제하기 + +### 5.1 추가할 규칙 (그대로 붙여넣기) + +`.dependency-cruiser.json`의 `forbidden` 배열에서 **`adapters-do-not-know-other-concrete-adapters` 바로 다음, `no-circular-dependencies` 앞**에 넣는다 (현재 `:193`과 `:194` 사이). + +```json + { + "name": "adapter-groups-are-reached-through-their-barrel", + "comment": "docs/architecture/layers.md §4: 어댑터 그룹의 공개 표면은 그 그룹의 `index.ts`다. 그룹 바깥(bootstrap, features, presentation)은 배럴만 import한다. 배럴이 없던 시절 bootstrap은 어댑터 내부 파일 15곳을 직접 겨눴고, 그래서 어떤 파일이 공개이고 어떤 파일이 내부 헬퍼인지 아무 데도 적혀 있지 않았다. 출발점에서 `src/adapters`를 뺀 이유는 어댑터끼리의 간선은 바로 위 `adapters-do-not-know-other-concrete-adapters`가 이미 담당하고, 커널(`platform/**`)은 파일 단위로 공유되기 때문이다 — `scripts/check-adapter-inventory.ts`가 네 소비자에게 `platform/abortable-operation.ts`로 해석되는 specifier를 직접 요구한다. 도착점에서 1단계 중첩 `index.ts`를 허용한 이유는 `storage/indexeddb`와 `storage/opfs`가 각자 독립적으로 제거 가능한 런타임이고(scripts/test-browser-file-storage-runtime-removal.ts), 그래서 각자의 배럴이 곧 경계이기 때문이다.", + "severity": "error", + "from": { + "path": "^src/", + "pathNot": "^src/adapters/" + }, + "to": { + "path": "^src/adapters/[^/]+/", + "pathNot": "^src/adapters/[^/]+/(?:[^/]+/)?index\\.ts$" + } + }, +``` + +규칙 형태 적합성: `scripts/check-architecture.ts:799-815`의 `validateArchitectureRules`는 `from`에 `path`/`pathNot`, `to`에 `path`/`pathNot`/`circular`만 허용한다. 이 규칙은 그 안에 있다. 정규식은 `new RegExp(pattern, "u")`로 평가되므로(`:739`, `:747`) 비캡처 그룹 `(?:...)`도 문제없다. `$1` 역참조는 쓰지 않았다. + +### 5.2 이 규칙이 무엇을 잡고 무엇을 안 잡는가 — 실측 + +레포의 실제 import 그래프(`src` 전체, 상대 specifier 해석)에 규칙을 그대로 돌려본 결과: + +**잡는 것 — 오늘 기준 위반 15건** (= §4.1의 치환 대상 15줄과 정확히 일치) + +``` +src/bootstrap/main.tsx:3 -> src/adapters/diagnostics/bounded-diagnostics.ts +src/bootstrap/optional-runtime-host.ts:4 -> src/adapters/platform/browser-lifecycle.ts +src/bootstrap/register-service-worker.ts:5 -> src/adapters/service-worker/service-worker-page-controller.ts +src/bootstrap/runtime-adapters.ts:6 -> src/adapters/auth/external-session-adapter.ts +src/bootstrap/runtime-adapters.ts:7 -> src/adapters/diagnostics/bounded-diagnostics.ts +src/bootstrap/runtime-adapters.ts:8 -> src/adapters/http/client.ts +src/bootstrap/runtime-adapters.ts:12 -> src/adapters/http/http-execution-v3.ts +src/bootstrap/runtime-adapters.ts:23 -> src/adapters/query-cache/tanstack-cache-coordinator.ts +src/bootstrap/runtime-adapters.ts:24 -> src/adapters/query-cache/tanstack-query-cache.ts +src/bootstrap/runtime-adapters.ts:25 -> src/adapters/query-cache/server-state-scope-runtime.ts +src/bootstrap/runtime-adapters.ts:26 -> src/adapters/query-cache/conditional-validator-store.ts +src/bootstrap/runtime-adapters.ts:27 -> src/adapters/storage/browser-storage-adapter.ts +src/bootstrap/runtime-adapters.ts:28 -> src/adapters/platform/browser-mutation-intent-factory.ts +src/bootstrap/runtime-adapters.ts:29 -> src/adapters/telemetry/best-effort-telemetry.ts +src/features/reference-feature/adapters/create-reference-feature-input.ts:9 -> src/adapters/http/http-execution-v3.ts +``` + +§4.1을 적용하면 이 15건이 0이 된다. **즉 배럴 8개 생성 + import 15줄 치환 + 규칙 추가를 한 커밋에 넣어야 `check:architecture`가 계속 PASS한다.** 순서를 나누면 중간 커밋이 빨간불이 된다. + +**안 잡는 것 (의도대로)** + +| 경우 | 건수 | 왜 안 잡히나 | +|---|---:|---| +| 같은 그룹 내부 파일끼리 | 229건 중 189건 | `from.pathNot: "^src/adapters/"`가 출발점을 제외 | +| 어댑터 → 커널 (`platform/**`, `browser-file-storage/result.ts`, `cross-context-invalidation/index.ts`) | 40건 | 같은 이유. 이 간선들은 `adapters-do-not-know-other-concrete-adapters`(`:183-193`)의 `pathNot` carve-out이 계속 담당 | +| 바깥 → 배럴 (이미 합격) | 2건 | `to.pathNot`이 `index.ts`를 면제. `src/bootstrap/runtime-adapters.ts:20`, `src/bootstrap/server-state-generation-store.ts:3` | +| `tests/**` | 166줄 전부 | 스캔 범위 밖 (아래 §5.3) | +| `src/presentation/adapters/query/**` | — | 경로가 `src/presentation/...`이라 `to.path` `^src/adapters/`에 매칭 자체가 안 됨 | + +세 가지 질문에 대한 명시적 답: + +1. **같은 그룹 내부 import — 허용된다.** 출발점이 `^src/adapters/`이면 규칙이 아예 평가되지 않는다. +2. **커널 접근 — 허용된다.** `platform/`은 위와 같은 이유로 통과. `browser-file-storage/result.ts`와 `cross-context-invalidation/index.ts`도 출발점이 어댑터이므로 통과. (참고: `cross-context-invalidation/index.ts`는 마침 `index.ts`라 도착점 면제에도 걸린다 — 이중으로 안전.) +3. **`tests/`는 대상이 아니다.** `scripts/check-architecture.ts:69`가 `sourceRoot = resolve(projectRoot, "src")`이고 `:116-123`이 `depcruise src --config ...`를 돌린다. 두 그래프 모두 `src`만 본다. + +### 5.3 기존 규칙과의 충돌 검토 + +`.dependency-cruiser.json` 전체(18개 규칙)를 읽고 대조했다. + +| 기존 규칙 | 줄 | 충돌 | +|---|---:|---| +| `domain-is-framework-neutral` | 4 | 없음. domain→adapters는 어차피 전면 금지 | +| `application-does-not-know-concrete-runtime` | 13 | 없음. 동일 | +| `presentation-does-not-know-adapters` | 24 | 없음. presentation→adapters 전면 금지가 상위 | +| `page-templates-own-layout-only` | 34 | 없음 | +| `icon-vendor-is-facade-only` | 44 | 없음 (외부 패키지 대상) | +| `adapters-do-not-know-presentation` | 54 | 없음 (방향 반대) | +| `feature-*` 4개 | 64–103 | 없음. feature adapters→`src/adapters`는 이 규칙들이 막지 않으므로 새 규칙이 유효하게 작동 (실측 15번째 위반이 그 경우) | +| `concrete-adapters-compose-only-in-bootstrap` | 104 | 없음. `src/(domain\|application\|presentation\|contracts)` → `^src/adapters` 전면 금지. 새 규칙은 그 나머지(`bootstrap`, `features`)에서만 실효 | +| `external-contract-package-single-import-path` | 114 | 없음 | +| `presentation-does-not-fetch-directly` | 126 | 없음. `^src/adapters/(http\|realtime\|service-worker\|web-worker\|storage)` 를 겨누는데 presentation은 이미 전면 금지 | +| `generic-worker-has-no-network-or-credentials` | 137 | 없음. `^src/adapters/web-worker` 출발이라 새 규칙 출발점 제외와 겹칠 뿐. (`src/adapters/web-worker`는 현재 존재하지 않는 예방 규칙) | +| `service-worker-entry-is-not-page-code` | 148 | 없음 | +| `contracts-do-not-know-application` | 159 | 없음 | +| `generic-presentation-does-not-compose-the-product` | 170 | 없음 | +| **`adapters-do-not-know-other-concrete-adapters`** | **183** | **없음 — 상보적.** 저쪽은 `from: ^src/adapters/([^/]+)/`, 이쪽은 `from.pathNot: ^src/adapters/`. 정확히 반대 집합이라 이중 판정이 생기지 않는다 | +| `no-circular-dependencies` | 194 | 주의 필요 → 아래 | + +**순환 검토.** `no-circular-dependencies`(`:194-201`)가 error다. 배럴 도입이 순환을 만들려면 그룹 안 파일이 자기 그룹 `index.ts`를 import해야 한다. + +``` +grep -rn 'from "\./index\.ts"\|from "\.\./index\.ts"' src/adapters/ --include='*.ts' → 0건 +``` + +또 `src/bootstrap/**`는 어댑터에서 import되지 않는다(`adapters-do-not-know-presentation`이 `^src/(presentation|bootstrap)`을 막음, `:54-62`). 따라서 **새 순환 없음.** 단 §3.7의 판정을 뒤집어 `storage/index.ts`가 서브배럴을 재수출하면, 순환은 아니지만 제거 드릴이 깨진다(§6 위험 2). + +### 5.4 ESLint 쪽은 손대지 않는다 + +`eslint.config.ts:9-34`의 `layerPatterns`는 레이어 단위(`**/adapters/**`)만 다루고 그룹 내부 경로를 구분하지 않는다. 배럴 규칙을 여기에도 복제하면 두 곳에서 같은 사실을 관리하게 된다. dependency-cruiser 쪽 한 곳만 유지한다. + +--- + +## 6. 위험과 부수 작업 + +### 위험 1 (최대) — 번들 예산 + +`package.json`에 `"sideEffects"` 필드가 없다. 번들러는 모든 모듈을 부작용 있을 수 있는 것으로 보고, 배럴 재수출을 통해 들어온 모듈을 트리셰이킹에서 살려둘 수 있다. + +구체적으로 위험한 세 곳: +- `src/bootstrap/register-service-worker.ts`가 `service-worker/index.ts`를 import하면 `service-worker-lifecycle.ts`(666줄) → `service-worker-static-assets.ts`(394줄)가 **페이지 번들 그래프**에 들어온다. 지금은 `service-worker-page-controller.ts`(494줄) → `service-worker-protocol.ts` + `service-worker-removal.ts`만 들어온다. +- `src/bootstrap/runtime-adapters.ts`가 `http/index.ts`를 import하면 V2·V3가 항상 함께 들어온다 (`client.ts` 1107줄 + `http-execution-v3.ts` 1602줄). 지금도 둘 다 import하긴 한다. +- `query-cache/index.ts`는 `cursor-pagination-runtime.ts`(234줄)를 추가로 끌어온다. + +예산: `config/performance/budgets.json`의 `bundle.initialJsGzipBytes = 204800`. `check:bundle`(`scripts/check-bundle.ts:47`)이 초과 시 실패한다. + +**대응 (권장 순서)** +1. 배럴 커밋에서 `corepack pnpm check:bundle`을 반드시 돌린다. 이 문서에서는 실행하지 않았다. +2. 넘치면 `package.json`에 `"sideEffects": false`를 추가한다. `src/adapters` 아래에 최상위 부작용이 있는지 먼저 확인해야 한다(`presentation/styles/theme.css` 같은 CSS import는 `"sideEffects": ["*.css"]` 형태로 보존). +3. 그래도 넘치면 `service-worker/index.ts`에서 `service-worker-lifecycle.ts` 블록을 빼고, 워커 realm은 파일 직접 import를 유지한다(`platform`과 같은 논리 — realm이 다르면 문도 다르다). + +### 위험 2 — `storage/index.ts`에 서브배럴을 넣고 싶은 충동 + +`browser-transfer`/`realtime` 선례만 보고 `export * from "./indexeddb/index.ts"`를 넣으면 `test:browser-file-storage-removal`이 `assertNoRuntimeImports` 단계에서 예외로 죽는다(§3.7). 배럴 파일에 그 이유를 주석으로 못 박아 두는 걸 권한다. + +### 위험 3 — `check:adapter-inventory`가 새 파일 8개를 거부한다 + +`scripts/check-adapter-inventory.ts:58-74`가 `git ls-files src/adapters` 결과와 `docs/reviews/adapters/INVENTORY.md`의 행 목록을 **정확히 일치**시키고, `합계: **N/N**` 숫자도 파일 수와 같아야 한다. + +**같은 커밋에서 해야 할 일:** +1. 새 `index.ts` 8개를 `git add` 한다 (추적되지 않으면 `git ls-files`에 안 잡혀서 오히려 통과하지만, 커밋하는 순간 깨진다). +2. `docs/reviews/adapters/INVENTORY.md`에 행 8개 추가: + +| 추가할 경로 | 상세 리뷰 링크 (같은 그룹 기존 행과 동일하게) | +|---|---| +| `src/adapters/auth/index.ts` | `[Network/state](./01-network-and-state.md)` — 기존 행 `:11` | +| `src/adapters/diagnostics/index.ts` | `[Network/state](./01-network-and-state.md)` — `:58` | +| `src/adapters/http/index.ts` | `[Network/state](./01-network-and-state.md)` — `:59-68` | +| `src/adapters/platform/index.ts` | `[Network/state](./01-network-and-state.md)` — `:69-73` | +| `src/adapters/query-cache/index.ts` | `[Network/state](./01-network-and-state.md)` — `:74-78` | +| `src/adapters/telemetry/index.ts` | `[Network/state](./01-network-and-state.md)` — `:119` | +| `src/adapters/service-worker/index.ts` | `[Worker/push](./05-service-worker-and-web-push.md)` — `:96-101` | +| `src/adapters/storage/index.ts` | `[Storage/files](./03-storage-and-browser-files.md)` — `:102-103` | + +3. `docs/reviews/adapters/INVENTORY.md:132`의 `합계: **120/120**` → `합계: **128/128**`. + +행 번호(`| N |`)는 `inventoryRows`(`scripts/check-adapter-inventory.ts:33-40`)가 아래 정규식으로 **경로만** 뽑고 순서·연속성은 검사하지 않는다. + +``` +^\|\s*\d+\s*\|\s*`([^`]+)`\s*\| +``` + +그래도 읽는 사람을 위해 정렬 위치에 끼워 넣고 번호를 다시 매기는 걸 권한다. + +### 위험 4 — `tsconfig.app.json` 제외 파일 + +`tsconfig.app.json:18`이 `src/adapters/service-worker/service-worker-entry.ts`를 제외한다. `service-worker/index.ts`가 이 파일을 참조하면 app 타입체크가 제외 대상을 끌어들인다. §3.6의 배럴은 참조하지 않는다(그 파일은 export가 0개다). 나중에 누가 "완전성"을 이유로 추가하지 않도록 배럴에 주석을 남기는 것도 방법이다. + +### 부수 발견 (이 문서 범위 밖, 별도 티켓) + +1. `src/adapters/telemetry/best-effort-telemetry.ts:49` — 커널 심볼 재수출. 소비자 0, 같은 파일 `:8`에 import가 이미 있음. 삭제 후보. +2. `src/adapters/browser-files/index.ts:1-16` — 배럴이 application 포트 타입을 재수출. 어댑터 배럴이 하위 레이어의 통로가 되는 형태. +3. `src/adapters/storage/opfs/index.ts` — `tests/unit/opfs-byte-store.test.ts:25,28`이 쓰는 `OPFS_WORKER_PROTOCOL_VERSION`·`PreparePhysicalObjectRequest`·`writeWithSyncAccessHandle` 3개가 빠져 있다. +4. `.dependency-cruiser.json:141` — `^src/adapters/web-worker` 를 겨누는 규칙이 있으나 해당 디렉터리는 존재하지 않는다(어댑터 그룹은 16개). 예방 규칙인지 잔재인지 확인 필요. + +--- + +## 7. 심볼 존재 검증 (기계 대조) + +제시한 8개 배럴의 **모든 재수출 심볼 82개**를, 각 대상 파일의 실제 `export` 선언과 이름 단위로 대조했다. + +- 대조 방법: 각 `export { ... } from "./X.ts"` 블록의 이름을 뽑아, `src/adapters//X.ts`에서 `^export (declare )?(async function|function|const|let|var|class|type|interface|enum) ` 으로 선언된 이름 집합에 들어 있는지 확인. +- 결과: **82/82 존재. 누락 0, 오타 0.** +- 대상 파일 존재 여부도 함께 확인(8개 배럴이 참조하는 소스 파일 16개 전부 존재). + +그룹별 심볼 수: auth 7, diagnostics 5, telemetry 5, platform 16, query-cache 13, storage 2, service-worker 11, http 23. + +--- + +## 8. 실행 체크리스트 (한 커밋) + +1. `src/adapters/{auth,diagnostics,http,platform,query-cache,service-worker,storage,telemetry}/index.ts` 8개 생성 (§3 내용 그대로). +2. §4.1 표의 15줄 치환. `src/bootstrap/runtime-adapters.ts`는 아래에서 위로 편집하거나 `:1-29` 블록 전체를 다시 쓴다. +3. (선택) `.storybook/preview.tsx:5,6` 2줄 치환. +4. `.dependency-cruiser.json`에 §5.1 규칙 추가 (현재 `:193`과 `:194` 사이). +5. `docs/reviews/adapters/INVENTORY.md`에 행 8개 추가 + `:132`의 합계를 `128/128`로. +6. `docs/architecture/layers.md`에 "어댑터 그룹의 공개 표면은 그 그룹의 `index.ts`다. 커널은 예외로 파일 단위로 공유된다"를 한 문단 추가 (`:29-45`의 adapter kernel 절 뒤). 이 문서 규칙들은 실행 규칙과 짝을 이루게 되어 있다(`layers.md:39-45`). +7. 게이트 실행: `check:architecture` → `check:types:app` → `check:adapter-inventory` → `lint` → `check:bundle` → `test:browser-file-storage-removal`. + 마지막 두 개가 이번 변경의 실제 리스크 지점이다(§6 위험 1, 2). diff --git a/docs/superpowers/specs/2026-09-16-indexeddb-kernel-promotion-design.md b/docs/superpowers/specs/2026-09-16-indexeddb-kernel-promotion-design.md new file mode 100644 index 0000000..ffde878 --- /dev/null +++ b/docs/superpowers/specs/2026-09-16-indexeddb-kernel-promotion-design.md @@ -0,0 +1,1154 @@ +# IndexedDB 커널 승격 — 구체 설계 + +> 대상 브랜치: `develop` (5434760) +> 이 문서는 설계만 담는다. 소스는 수정하지 않았고 빌드/테스트도 돌리지 않았다. +> 모든 주장에 `파일:줄번호` 근거를 달았다. 근거를 못 단 항목은 **미확인**이라고 표시했다. + +--- + +## 0. 사본 개수 확정: 5벌이 아니라 **4벌** + +`src/adapters/web-push/push-association-fence-store.ts`는 IndexedDB 사본이 **아니다.** + +``` +$ grep -n "indexedDB|IDBDatabase|IDBTransaction|IDBRequest|IDBObjectStore|IDBKeyRange|IDBFactory|deleteDatabase|onupgradeneeded|objectStore" \ + src/adapters/web-push/push-association-fence-store.ts +→ 매치 없음 +``` + +이 파일은 IndexedDB API를 한 줄도 쓰지 않는다. 대신 `PushControlRepository`라는 **구조적 포트**를 자기가 선언하고 +(`push-association-fence-store.ts:59-87`) 합성 루트에서 주입받는다. 파일 자신의 주석이 그 의도를 명시한다: + +> `push-association-fence-store.ts:49-58` +> "It is declared here, structurally, rather than imported from the browser file/storage port so the two capabilities stay +> independently removable. The generic IndexedDB repository satisfies it as-is; the composition root is where the two are +> joined, and it owns connection, migration, transaction, timeout, codec and version-change policy." + +즉 이 파일은 **이번 리팩토링이 지향하는 모범 사례의 예시**이지 중복 사본이 아니다. 커널 이행 대상에서 제외한다. +(다만 `tests/helpers/fake-push-control-repository.ts`, `tests/unit/web-push-store-port-compatibility.test.ts`는 +runtime의 공개 형태에 구조적으로 의존하므로 §5의 위험 목록에는 남긴다.) + +한편 **실제 IndexedDB 코드를 가진 5번째 파일은 따로 있다**: `src/adapters/storage/indexeddb/indexeddb-governance.ts` +(`queueIndexedDbUpgradeBinding` L160-215, `verifyIndexedDbDatasetBinding` L220-338). 이건 `indexeddb/` 폴더 내부 +헬퍼라 runtime과 maintenance가 **이미 공유**하고 있다. 중복이 아니므로 대조표에는 참고 열로만 넣는다. + +--- + +## 1. 4벌 대조표 + +열 약어: +- **RT** = `src/adapters/storage/indexeddb/indexeddb-runtime.ts` (2902 LOC) +- **MT** = `src/adapters/storage/indexeddb/indexeddb-maintenance.ts` (1558 LOC) +- **OP** = `src/adapters/storage/opfs/indexeddb-opfs-journal.ts` (1817 LOC) +- **CP** = `src/adapters/browser-transfer/resumable-upload/indexeddb-checkpoint-store.ts` (712 LOC) + +### 1.1 연결 수립 + +| 기능 | RT | MT | OP | CP | +|---|---|---|---|---| +| `factory.open()` → Promise | 있음 `L684-921` | 있음 `L434-585` | 있음 `L961-1072` | 있음 `L156-239` | +| `factory` 기본값을 전역에서 해석 | 있음 `L565-569` | 있음 `L359-363` | 있음 `L130-134` | 있음 `L95-97` | +| `IDBKeyRange` 기본값을 전역에서 해석 | 있음 `L570-574` | 있음 `L364-368` | 있음 `L135-139` | **없음** (범위 질의 없음) | +| 단일 비행(single-flight) 오픈 캐시 | 있음 `L594` `L942-951` | **없음 — 의도적**. 배치마다 열고 `finally`에서 닫음 `L1364-1366` `L1549-1551` | 있음 `L166` `L1067-1071` | 있음 `L129` `L144-148` | +| 진행 중 open 취소 훅 | 있음 `cancelPendingOpen L596,L741-744`, `close()`에서 호출 `L2876` | 있음 `signal`→`request.transaction?.abort()` `L467-474` | **없음** | **없음** | +| open generation 토큰(늦게 온 요청 무시) | 있음 `L595,L691-697` | **없음** | **없음** | **없음** | +| 늦게 도착한 connection 강제 close | 있음 `L835-841,L896-902` | 있음 `L505-508,L577-580` | 있음 `L1050-1053` | 있음 `L168-171,L219-224` | + +### 1.2 blocked 처리 + +| 기능 | RT | MT | OP | CP | +|---|---|---|---|---| +| `onblocked` 핸들러 | 있음 `L776-799` | 있음 `L485-492` | 있음 `L1031-1041` | 있음 `L198-207` | +| blocked 후 **대기 타이머** | 있음, 주입형 scheduler `L789-798`, 기본 10_000ms `L576` | **다르게 구현 — 타이머 없이 blocked 이벤트 즉시 실패** `L485-492` | 있음, 주입형 scheduler `L1032-1040`, 기본 10_000ms `L143` | **다르게 구현 — 네이티브 `setTimeout` 하드코딩(주입 불가)** `L199-206`, 기본 5_000ms `L23,L98-99` | +| blocked를 관측 이벤트로 발행 | 있음 `L782-788` | **없음** (결과 매핑에서만 `observeResult` `L391-392`) | **없음** | **없음** | +| blocked 시 연결 상태 전이 | 있음 `{kind:"BLOCKED"}` `L777-781` | **없음** | **없음** | **없음** | + +### 1.3 버전 마이그레이션 / 스키마 + +| 기능 | RT | MT | OP | CP | +|---|---|---|---|---| +| `onupgradeneeded` 훅 | 있음 `L746-774` | 있음 `L477-484` | 있음 `L991-1030` | 있음 `L176-197` | +| upgrade 내부 동작 | **선언적 migration 목록 적용** `applyIndexedDbMigrations L754-760` + governance binding queue `L761-769` | **upgrade 자체를 실패로 취급** — `unexpectedUpgrade=true` 후 abort `L477-484`, 결과 `MIGRATION_FAILED` `L495-496` | **인라인 하드코딩된 createObjectStore 6개 + index 3개** `L997-1029`, `oldVersion!==0`이면 abort `L993-996` | **인라인 `contains` 체크 후 createObjectStore 2개** `L179-188` | +| upgrade 실패 플래그 → 결과 코드 | 있음 `migrationFailed` `L714,L811-819` | 있음 `unexpectedUpgrade` `L460,L495-496` | **없음** (abort가 onerror로 흐름) | **없음** (catch 후 `finish` `L189-196`) | +| open 후 스토어 존재 검증 | 있음 `assertIndexedDbRuntimeStores L844-853` (구현은 `indexeddb-migrations.ts:162-207`) | **다르게 구현 — 인라인 `objectStoreNames.contains` 5개 + index 접근 `L509-542`** | **없음** | **없음** | +| governance/scope binding 검증 | 있음 `verifyIndexedDbDatasetBinding L866-871` | 있음 동일 함수 `L545-550` | **없음** (open 경로에서는 안 함; scope 바인딩은 트랜잭션 내부 로직 `L1310-1347`) | **다르게 구현 — 자체 `bindScope` 별도 트랜잭션 `L598-654`** | +| 마이그레이션 개수를 결과로 반환 | 있음 `appliedMigrations L716,L910-916` | 해당 없음 | 해당 없음 | 해당 없음 | + +### 1.4 versionchange / 연결 무효화 + +| 기능 | RT | MT | OP | CP | +|---|---|---|---|---| +| `onversionchange` | 있음 `L904` → `handleVersionChange L637-651` (상태 브로드캐스트 + 콜백) | 있음 `L543` — `() => database.close()` 한 줄 | 있음 `L1055-1059` — 캐시 무효화(`database=null; opening=null`) | 있음 `L230-233` — 캐시 무효화 | +| `onclose` (강제 종료) | 있음 `L905` → `handleForcedClose L653-657` | **없음** | 있음 `L1060-1063` | 있음 `L234-236` | +| 연결 상태 구독 API | 있음 `getStatus/subscribeStatus L2893-2899` | **없음** | **없음** | **없음** | +| `close()`/dispose | 있음 `L2873-2884` (pending open 취소 + DISPOSED 브로드캐스트) | **없음** (배치마다 자동 close) | 있음 `L757-761` | 있음 `L395-399` + `deletePartition`에서도 `L411-413` | + +### 1.5 트랜잭션 실행 + +| 기능 | RT | MT | OP | CP | +|---|---|---|---|---| +| `createTransaction` + durability 폴백 | 있음 `L957-974` | **RT와 문자 단위로 동일** `L587-604` | **다르게 구현 — readwrite만 `durability:"strict"` 하드코딩, readonly는 옵션 없음** `L1176-1190` | **다르게 구현 — durability 옵션 자체가 없음** `L512` | +| durability를 의존성으로 주입 | 있음 `dependencies.durability?.read/.write` `L962-965` | 있음 동일 `L592-595` | **없음** (하드코딩) | **없음** | +| `runTransaction` (트랜잭션→Promise) | 있음 `L976-1074` | 있음 `L606-705` — RT와 구조 동일, `operation`이 `"INDEXEDDB_MIGRATE"` 고정이고 `database`를 인자로 받음 | 있음 `L1098-1174` — **모듈 최상위 자유함수** | 있음 `runCheckpointTransaction L497-596` — **단일 스토어 `CHECKPOINT_STORE` 고정** `L512,L591` | +| `TransactionContext` 타입 | `L85-89` (`succeed`/`fail`/`requestFailed`) | `L97-101` (동일 3종) | `L48-51` (**`succeed`/`fail` 2종 — `requestFailed` 없음**) | `L491-495` (`succeed`/`fail`/`nativeFailure`) | +| caller `AbortSignal` → transaction.abort | 있음 `L1010-1017,L1041` | 있음 `L640-650,L676` | **없음 — signal 인자 자체가 없음** | 있음 `L527-539` | +| `oncomplete`인데 값이 없을 때 | `UNAVAILABLE/retryable:true/REOPEN` `L1020` (`unavailable` `L397-404`) | `UNAVAILABLE/retryable:true/REOPEN` `L653` (`unavailable` `L257-262`) | `UNAVAILABLE/retryable:true/REOPEN` `L1144-1151` | **다르게 구현 — `CORRUPT_DATA/RECONCILE`** `L541-547` | +| 요청 오류 기록 후 abort 여부 | **abort 안 함** — `requestFailed`는 기록만 `L1055-1060` | **abort 안 함** `L686-694` | 해당 없음 (요청 오류를 안 봄) | **abort 함** — `nativeFailure`가 즉시 abort `L577-588` | +| `queue` 콜백이 throw할 때 | 있음 `L1063-1072` | 있음 `L697-703` | 있음 `L1163-1172` | 있음 `L590-594` | + +### 1.6 요청 → 콜백 변환 + +| 기능 | RT | MT | OP | CP | +|---|---|---|---|---| +| `request.onsuccess` 인라인 배선 | 있음, 수십 곳 (예 `L1134,L1782,L1878,L1932`) | 있음 (예 `L721,L799,L1033,L1079`) | 있음 (예 `L187,L497,L604,L790`) | 있음 (예 `L265,L323,L372`) | +| `request.onerror` 인라인 배선 | 있음, 거의 모든 요청에 (예 `L1133,L1780,L1876`) | 있음 (예 `L720,L798,L1031`) | **없음 — 파일 전체에서 request `.onerror`는 open 요청 1개뿐** (`L1042`; `L1160`은 transaction.onerror) | 있음 (예 `L264,L322,L341,L371,L387`) | +| 요청→콜백 공통 헬퍼 | **없음** | **없음** | **없음** | **없음** | + +### 1.7 커서 순회 + +| 기능 | RT | MT | OP | CP | +|---|---|---|---|---| +| `openCursor` 순회 루프 | 있음 4곳: `query L1364-1527`, `purgeEligibleRecords L2345-2472`, `purgePartitionRecords` 내부 4개 루프 `L2528-2566,L2570-2638,L2641-2713,L2715-2809` | 있음 2곳: `scanBatch L795-858`, `pruneExpiredReceipts L1429-1542` | 있음 2곳: `listIncomplete L600-633`, `listCommittedObjects L673-712` | **없음** | +| 행 수 예산(maxRows) | 있음 — **삭제 행 기준** `deletedRows >= input.maxRows` `L2384,L2543,L2585,L2656,L2730` | 있음 — **스캔 행 기준** `rows.length >= input.maxRows` `L823`, 삭제 행 기준 `L1471` | **다르게 구현 — `limit`만, 예산 개념 없음** `L622,L699` | 해당 없음 | +| 시간 예산(deadline) | 있음 `monotonicClock() L2260-2269`, 비교 `L2385,L2544` 등 | 있음 `clock() L401-410`, 비교 `L824,L1472` | **없음** | **없음** | +| 스캔 상한(방어적) | 있음 `MAX_QUERY_SCANNED_ROWS=5_000 L105`, 계산 `L1349-1352`, 비교 `L1454` | **없음** | **없음** | 해당 없음 | +| 커서 재개 방식 3종 (`continue`/`continue(key)`/`continuePrimaryKey`) | 있음 `L1430-1445` | **없음** (`continue()`만 `L852`) | **없음** (`continue()`만 `L632,L711`) | 해당 없음 | +| 커서 중간에 중첩 요청 체인 실행 | 있음 (모든 순회가 그렇게 함, 예 `L1487-1526`, `L2406-2471`) | 있음 (`L1490-1541`) | **없음** (`push` 후 즉시 `continue()`) | 해당 없음 | +| 순회 중 `signal.aborted` 체크 | 있음 `L1375-1382,L2365-2372` | 있음 `L800-807,L1452-1459` | **없음** | 해당 없음 | + +### 1.8 실패 매핑 + +| 기능 | RT | MT | OP | CP | +|---|---|---|---|---| +| 예외→실패 매핑 함수 | `mapIndexedDbException` `indexeddb-failure.ts:23-72` | 동일 함수 `L15` | 동일 함수 `L21` | **다르게 구현 — `mapBrowserDataException`** `browser-file-storage/result.ts:43-90` (`L11`에서 import) | +| 매핑 테이블이 실제로 다른 지점 | — | — | — | `ConstraintError`: IDB=`CONFLICT/recovery:NONE`(`indexeddb-failure.ts:30-31`) vs BD=`CONFLICT/recovery:REOPEN`(`result.ts:58-60`) · `QuotaExceededError`: IDB=`retryable:false`(`:56-60`) vs BD=`retryable:true`(`:74-79`) · `NotFoundError`: IDB=`MIGRATION_FAILED`(`:41-45`) vs BD=`NOT_FOUND`(`:67-68`) · BD는 `DOMException`이 아니면 전부 `UNAVAILABLE`(`:47-52`), IDB는 name만 보고 판단(`:7-17`) | +| `operation` 라벨 | 호출처마다 다름: `INDEXEDDB_OPEN/READ/WRITE/MIGRATE` | `INDEXEDDB_MIGRATE` 고정 `L248,L252,L258` 등 | 호출처마다 다름: `INDEXEDDB_OPEN/READ/WRITE` | `UPLOAD_RECONCILE` 고정 | +| abort 단축 헬퍼 | `abortedResult` `L19` | `abortedResult` `L11` | **없음** (`signal` 미사용) | **없음** (인라인 `signal?.aborted` `L140-142,L408-410,L506-508`) | + +### 1.9 deleteDatabase + +| 기능 | RT | MT | OP | CP | +|---|---|---|---|---| +| `factory.deleteDatabase` | **없음** | **없음** | **없음** | **있음** `L110-113`, `deletePartition L403-485` | +| 파티션 전체 삭제를 다른 방식으로 구현 | 있음 — **행 단위 순회 삭제** `purgePartitionRecords L2477-2812` | **없음** | **없음** | 해당 없음 | +| 삭제 blocked 처리 | 해당 없음 | 해당 없음 | 해당 없음 | 있음 — blocked 데드라인 후 `PENDING/UNKNOWN/BLOCKED_DEADLINE` 반환 `L449-462` (open의 `L198-207`과 동일 패턴 재작성) | +| 진행 중 삭제 레지스트리 | 해당 없음 | 해당 없음 | 해당 없음 | 있음 `PENDING_DELETIONS WeakMap L31-41`, 생성 시 검사 `L116-122` | + +### 1.10 관측 / 구성 검증 + +| 기능 | RT | MT | OP | CP | +|---|---|---|---|---| +| observe 래퍼 | 있음 `L599-605` + `observeResult L607-624` | 있음 `L373-379` + `observeResult L381-399` — **RT와 형태 동일** | **다르게 구현 — 이벤트 shape가 다름** (`SUCCEEDED/FAILED`, countBucket 없음) `L1074-1091` | **없음** | +| `countBucket` | 있음 `L119-125` | **RT와 문자 단위로 동일** `L239-245` | **없음** | **없음** | +| 식별자 정규식 | `SAFE_DATABASE_NAME` `L91` `{0,63}` | `SAFE_IDENTIFIER` `L103` `{0,127}` | `SAFE_DATABASE_NAME` `L110` `{0,255}`, `SAFE_BOUNDARY_ID` `L111` | `SAFE_OPAQUE_ID`/`SAFE_UPLOAD_KEY` (`checkpoint-schema.ts`) | +| 구성 불변식 검사 후 `TypeError` | 있음 `L530-563` | 있음 `L331-357` | 있음 `L155-163` | 있음 `L100-106,L116-122` | +| 의존성 메서드 bind 스냅샷 | 있음 `L474-527` | 있음 `L290-326` | **없음** | 있음 (부분) `L108-113` | +| 저장 레코드 검증 술어 | 있음 `L223-301` | **거의 동일하지만 별도 구현** `L118-223` | 있음, 도메인 고유 `L1406-1665` | 있음, 도메인 고유 (`checkpoint-schema.ts`) | + +### 1.11 대조표 결론 + +**4벌 전부가 같은 의미로 필요로 하는 것** (커널 후보): +`factory.open→Promise`, `onupgradeneeded` 훅, `onblocked` 처리, 늦게 온 connection 강제 close, +`onversionchange`/`onclose` 배선, `transaction→Promise` 상태기계(succeed/fail/settle-once/queue throw), +`request→콜백` 배선. + +**3벌** (커널 후보): 단일 비행 오픈 캐시(MT 제외 — 의도적), durability 폴백을 가진 트랜잭션 팩토리(CP 제외), +커서 순회(CP 제외), caller signal → transaction.abort(OP 제외 — 결함). + +**2벌 이하** (커널 아님): open 후 스토어 존재 검증(2), governance binding(2, 이미 `indexeddb-governance.ts`로 공유), +observe/countBucket(2), 시간 예산 클럭(2), 상태 구독 API(1), `deleteDatabase`(1), 저장 레코드 술어(전부 도메인 고유). + +**그리고 가장 중요한 결론: 실패 매핑은 공통이 아니다.** 3벌이 `mapIndexedDbException`, 1벌이 +`mapBrowserDataException`을 쓰고 두 테이블은 §1.8에 적은 대로 실제로 다른 답을 낸다. 커널이 매핑을 고르면 +CP의 동작이 조용히 바뀐다. → **매핑은 주입한다.** + +--- + +## 2. 커널 경계선 + +판단 기준은 「4벌 중 3벌 이상이 **같은 의미로** 필요로 하는가」다. + +### 2.1 커널로 올릴 것 + +| 항목 | 벌 수 | 근거 | +|---|---|---| +| `IDBOpenDBRequest` → Promise (settle-once, blocked 데드라인, upgrade 훅, 늦은 connection close, signal→upgrade abort) | 4/4 | §1.1 §1.2 §1.3 | +| 단일 비행 연결 핸들 (+ versionchange/close 무효화, close()가 진행 중 open 취소) | 3/4 | §1.1 §1.4. MT는 의도적으로 안 씀 → 커널의 open 함수만 쓰고 핸들은 안 쓴다 | +| 트랜잭션 팩토리 + durability 폴백 | 3/4 | §1.5. CP는 `durability: undefined`를 넘겨 오늘 동작 유지 | +| `transaction` → Promise 상태기계 | 4/4 | §1.5 | +| `request` → 콜백 배선(성공/오류) | 4/4 | §1.6 | +| 커서 펌프(순회 + 예산 + 중첩 체인 재개) | 3/4 | §1.7 | + +### 2.2 남길 것 (근거 포함) + +| 항목 | 벌 수 | 남기는 이유 | +|---|---|---| +| 실패 매핑 테이블 | 3 + 1 | 두 테이블이 실제로 다른 값을 낸다(§1.8). 통일은 **별도 결정**이고 별도의 테스트 낙진을 만든다. 커널은 **원인(cause)만 알리고 코드를 고르지 않는다.** | +| `operation` 라벨 | 4/4 다름 | 호출처마다 다르다. 커널이 알 필요가 없다. | +| open 후 스토어/인덱스 존재 검증 | 2/4 | RT는 `indexeddb-migrations.ts:162-207`, MT는 인라인. 검증 대상 스토어 목록이 도메인 스키마다. 커널에는 `admit` 콜백만 둔다. | +| governance / scope binding | 2/4 + 1 자체구현 | `indexeddb-governance.ts`가 이미 RT/MT 공유분이다. CP의 `bindScope`는 스코프 모델 자체가 다르다(`L60-66` vs `IndexedDbDatasetScope`). | +| observe / countBucket | 2/4 | RT·MT는 동일하지만 OP는 shape가 다르고 CP는 없다. 2벌은 올리지 않는다. RT·MT 간 중복은 `indexeddb-types.ts`로 내리는 **별건**이다. | +| 시간 예산 클럭 | 2/4 | 커널의 커서 펌프가 예산 판정을 **콜백으로 받는다**. 클럭·deadline·실패값은 호출처가 소유한다. | +| 연결 상태 구독(`getStatus`/`subscribeStatus`) | 1/4 | RT의 포트 계약(`IndexedDbRepositoryPort`)이다. | +| 저장 레코드 검증 술어, 코덱, 예산(bytes), 보존, 영수증 | 도메인 | 커널은 **정책을 하나도 안 갖는다**(§5.3의 방어선). | + +### 2.3 `deleteDatabase` — 규칙의 명시적 예외 (1/4) + +「≥3벌만 커널」 규칙을 그대로 적용하면 `deleteDatabase`는 탈락이다. **그럼에도 커널에 둔다.** 근거: + +1. 이건 **새 기능 발명이 아니라 이동**이다. 규칙이 막으려는 건 아무도 안 쓰는 추상화인데, 이건 오늘 호출자가 + 실제로 존재한다(`indexeddb-checkpoint-store.ts:403-485`). +2. `deleteDatabase`는 `open`과 **같은 `IDBOpenDBRequest` 상태기계**다. CP는 blocked 데드라인 + settle-once + 로직을 `L198-207`(open)과 `L449-462`(delete)에 **두 번** 적었다. 커널이 open만 가져가면 CP 안에 그 로직의 + 세 번째 사본이 남는다. +3. **드러난 발산 자체의 진짜 원인은 `deleteDatabase`가 아니다.** 리뷰가 "한쪽에만 있다"고 잡은 건 표면 차이다. + RT는 파티션 삭제를 `purgePartitionRecords`(`L2477-2812`)의 행 단위 순회로 **의도적으로** 다르게 한다. + 따라서 **`deleteDatabase`를 나머지 3벌에 새로 넣지 않는다.** 이행 계획(§4)에 그런 항목은 없다. +4. 별도 export라 나중에 떼어내도 나머지 커널이 안 흔들린다. + +`PENDING_DELETIONS` WeakMap 레지스트리(`L31-41`)는 **커널로 올리지 않는다.** 그건 realm 정책이고 CP에만 있는 판단이다. + +--- + +## 3. 실제 TypeScript 시그니처 + +### 3.1 파일 구성: **2개** + +``` +src/adapters/platform/indexeddb-connection.ts (~240 LOC) 연결 수명주기 +src/adapters/platform/indexeddb-transaction.ts (~230 LOC) 연결 안에서 벌어지는 일 +``` + +**기각한 대안 1 — 단일 `indexeddb-kernel.ts`(~470 LOC):** `platform/`의 현재 최대 파일은 +`abortable-operation.ts` 269 LOC다. 470 LOC는 1.7배로 폴더 관례를 깬다. 더 중요한 건 테스트 셋업이 갈린다는 +점이다: 연결 쪽은 가짜 `IDBFactory`가 필요하고 트랜잭션 쪽은 가짜 `IDBDatabase`면 충분하다. + +**기각한 대안 2 — 3분할(`open-request`/`connection`/`transaction`):** open 요청과 연결 핸들은 같은 수명주기 +개념이고, 분리하면 `IndexedDbFailureCause`가 두 파일에 걸치거나 세 번째 타입 파일이 필요해진다. 또 inventory +행이 하나 더 는다(§5.2). + +### 3.2 `src/adapters/platform/indexeddb-connection.ts` + +```ts +/** + * IDB-X-01. Shared IndexedDB connection mechanics. + * + * Four adapters independently reimplemented "turn an open request into a + * promise, hold a blocked deadline, route upgrade/error/success, close a + * connection that arrives after the caller gave up, and drop the cached handle + * when the browser takes it away". Only the mechanics are shared here. Database + * naming, schema, migrations, governance binding and the failure taxonomy stay + * with each subsystem, so this module imports none of them and is not a + * generic storage layer. + * + * The `IDBFactory` is a required parameter rather than a read of + * `globalThis.indexedDB`. `eslint.config.ts:40-63` bans that property on every + * browser root and `eslint.config.ts:519-530` grants the owned-adapter escape + * hatch to `src/adapters/platform/browser-lifecycle.ts` as a single file, not + * to this folder. Requiring the factory is also what all four callers already + * do, so nothing in eslint.config.ts has to change. + */ + +import type { Result } from "../../contracts/result.ts"; +import type { AbortTimerSnapshot } from "./abortable-operation.ts"; + +/** + * Everything that can end an IndexedDB operation without the caller getting a + * value. The kernel reports the cause; the caller's `translate` turns it into + * that subsystem's failure code. + * + * This union is the extension point. `abortable-operation.ts:11` baked a closed + * three-member `AbortTerminalReason` into its return type, so http v3 needed + * five owners and could not use the kernel at all. Here the owner vocabulary is + * never in a return type: adding a member is a compile error in every + * `translate` (they are total functions over the union) rather than a silent + * behavior change, and no consumer has to fork. + */ +export type IndexedDbFailureCause = + /** A native throw or a `request.error` / `transaction.error`. */ + | Readonly<{ kind: "NATIVE_EXCEPTION"; error: unknown }> + /** `onblocked` fired and no deadline was configured. */ + | Readonly<{ kind: "BLOCKED"; oldVersion: number; newVersion: number | null }> + /** `onblocked` fired and the configured deadline then elapsed. */ + | Readonly<{ kind: "BLOCKED_DEADLINE" }> + /** The caller's own `AbortSignal` fired. */ + | Readonly<{ kind: "CALLER_ABORT" }> + /** The connection handle was closed, which is not the caller aborting. */ + | Readonly<{ kind: "CLOSED" }> + /** `upgrade` returned `REJECTED`, or a version change happened unexpectedly. */ + | Readonly<{ kind: "UPGRADE_REJECTED"; oldVersion: number; newVersion: number | null; detail?: unknown }> + /** `admit` returned `REJECT`. `detail` is opaque to the kernel. */ + | Readonly<{ kind: "ADMISSION_REJECTED"; detail?: unknown }> + /** A transaction completed without `succeed()` ever being called. */ + | Readonly<{ kind: "NO_VALUE_PRODUCED" }> + /** No `IDBFactory`, or a required `IDBKeyRange` the caller did not supply. */ + | Readonly<{ kind: "UNSUPPORTED" }>; + +/** + * Turns a cause into this subsystem's failure value. Built per call site so the + * kernel never learns an operation label or a failure code; a caller that needs + * `INDEXEDDB_READ` and one that needs `UPLOAD_RECONCILE` differ only here. + */ +export type IndexedDbTranslate = ( + cause: IndexedDbFailureCause, +) => Failure; + +export type IndexedDbUpgradeContext = Readonly<{ + database: IDBDatabase; + transaction: IDBTransaction; + oldVersion: number; + /** Never `null`: a null `newVersion` is reported as `UPGRADE_REJECTED` before `upgrade` runs. */ + newVersion: number; +}>; + +/** + * `REJECTED` aborts the versionchange transaction, so a schema change can never + * commit under a rejected policy. A throw from `upgrade` is equivalent to + * `REJECTED` with the thrown value as `detail`. + */ +export type IndexedDbUpgradeOutcome = + | Readonly<{ kind: "APPLIED" }> + | Readonly<{ kind: "REJECTED"; detail?: unknown }>; + +/** + * Post-open validation. It runs after `onsuccess` and may be asynchronous, so + * store/index assertions and governance reads both fit. A rejected or failed + * admission closes the connection before the caller ever sees it. + */ +export type IndexedDbAdmission = + | Readonly<{ kind: "ADMIT" }> + | Readonly<{ kind: "REJECT"; detail?: unknown }> + | Readonly<{ kind: "FAIL"; cause: IndexedDbFailureCause }>; + +export type IndexedDbOpenInput = Readonly<{ + /** Required. See the module comment for why this is not read from a global. */ + factory: IDBFactory; + databaseName: string; + /** Omit to open whatever version exists. */ + version?: number; + translate: IndexedDbTranslate; + /** + * Called inside the versionchange transaction. Omitting it means any upgrade + * is unexpected and the open fails with `UPGRADE_REJECTED` — which is what + * `indexeddb-maintenance.ts:477-484` does by hand today. + */ + upgrade?: (context: IndexedDbUpgradeContext) => IndexedDbUpgradeOutcome; + /** Post-open validation. Omitting it admits every successful open. */ + admit?: (database: IDBDatabase) => IndexedDbAdmission | Promise; + /** Aborts a pending upgrade transaction and settles with `CALLER_ABORT`. */ + signal?: AbortSignal; + /** + * `undefined` or `0`: the `onblocked` event itself is terminal and settles + * with `BLOCKED` (maintenance's behavior). A positive value waits that long + * before settling with `BLOCKED_DEADLINE` (runtime/opfs/checkpoint). + */ + blockedTimeoutMs?: number; + /** + * Required when `blockedTimeoutMs` is positive. Build it with + * `snapshotAbortTimers` from `./abortable-operation.ts`, which binds the + * callables once so replacing a method after composition cannot change how an + * open already in flight is bounded. + */ + timers?: AbortTimerSnapshot; + /** Observation only; it cannot change the outcome and its throw is swallowed. */ + onBlocked?: ( + event: Readonly<{ oldVersion: number; newVersion: number | null }>, + ) => void; +}>; + +/** + * Settles exactly once. A connection that arrives after the settle — a late + * `onsuccess`, a rejected admission, an abort — is closed rather than leaked. + */ +export function openIndexedDbDatabase( + input: IndexedDbOpenInput, +): Promise>; + +export type IndexedDbConnection = Readonly<{ + /** + * Single-flight: concurrent callers share one in-flight open, and a cached + * live connection is returned without touching the factory. + */ + acquire(signal?: AbortSignal): Promise>; + /** The cached connection, or `null` while none is live. Live accessor, not a snapshot. */ + current(): IDBDatabase | null; + /** + * Idempotent. Closes the cached connection and settles any in-flight open + * with `CLOSED` — not `CALLER_ABORT`, because the two have different codes in + * `indexeddb-runtime.ts` (`L743` resolves UNAVAILABLE while `L676` resolves + * ABORTED), and collapsing them would change one of them. + */ + close(): void; + isClosed(): boolean; +}>; + +export type IndexedDbConnectionInput = Readonly<{ + /** + * How to produce a connection. Normally a closure over + * `openIndexedDbDatabase`. It is a seam rather than a fixed body so a caller + * can retry, decorate or fake the open without faking an `IDBFactory`. + */ + open: (signal: AbortSignal | undefined) => Promise>; + translate: IndexedDbTranslate; + /** + * Fired after the handle has already dropped its cached connection, so a + * listener cannot keep a connection the browser is taking back. The next + * `acquire()` opens again. + */ + onVersionChange?: (event: IDBVersionChangeEvent) => void; + /** `onclose`: the browser closed the connection without a version change. */ + onForcedClose?: () => void; +}>; + +export function createIndexedDbConnection( + input: IndexedDbConnectionInput, +): IndexedDbConnection; + +export type IndexedDbDeleteOutcome = + | Readonly<{ kind: "DELETED" }> + /** + * The request is still live in the browser. It is not a failure and it is not + * "not applied": `deleteDatabase` cannot be cancelled after dispatch, so the + * effect is unknown. `indexeddb-checkpoint-store.ts:449-462` makes the same + * distinction and its comment explains why. + */ + | Readonly<{ kind: "BLOCKED_DEADLINE" }>; + +export type IndexedDbDeleteInput = Readonly<{ + factory: IDBFactory; + databaseName: string; + translate: IndexedDbTranslate; + blockedTimeoutMs?: number; + timers?: AbortTimerSnapshot; + /** + * Called exactly once when the native request truly settles, success or + * error — never on a blocked deadline. The caller uses it to release a + * pending-deletion registration; the kernel does not own such a registry + * because whether a realm may recreate the database is the caller's policy. + */ + onSettled?: () => void; +}>; + +/** + * In this module because it is the same `IDBOpenDBRequest` state machine as + * `openIndexedDbDatabase`, not because three subsystems need it — only + * `indexeddb-checkpoint-store.ts` deletes a database, and nothing here asks the + * other three to start. Leaving it out would leave a third hand-written copy of + * the settle-once blocked-deadline latch eight lines away from the kernel's. + * + * There is deliberately no `signal`: the request cannot be cancelled after + * dispatch, so reporting ABORTED while the deletion may still commit would be a + * lie. Callers check their signal before calling. + */ +export function deleteIndexedDbDatabase( + input: IndexedDbDeleteInput, +): Promise>; +``` + +핵심 구현 로직 (본문은 생략, 분기만): + +```ts +export function openIndexedDbDatabase( + input: IndexedDbOpenInput, +): Promise> { + const { factory, databaseName, translate } = input; + if (input.signal?.aborted) { + return Promise.resolve(fail(translate({ kind: "CALLER_ABORT" }))); + } + return new Promise((resolve) => { + let settled = false; + let blockedTimer: unknown; + let upgradeRejection: IndexedDbFailureCause | null = null; + + const settle = (result: Result) => { + if (settled) { + // A connection that lost the race is closed, never leaked. + if (result.ok) closeQuietly(result.value); + return; + } + settled = true; + if (blockedTimer !== undefined) input.timers?.clearTimer(blockedTimer); + input.signal?.removeEventListener("abort", onCallerAbort); + resolve(result); + }; + + let request: IDBOpenDBRequest; + try { + request = input.version === undefined + ? factory.open(databaseName) + : factory.open(databaseName, input.version); + } catch (error) { + settle(fail(translate({ kind: "NATIVE_EXCEPTION", error }))); + return; + } + + function onCallerAbort(): void { + // An upgrade transaction is the only cancellable part of an open request. + try { request.transaction?.abort(); } catch { /* the error path owns it */ } + settle(fail(translate({ kind: "CALLER_ABORT" }))); + } + input.signal?.addEventListener("abort", onCallerAbort, { once: true }); + + request.onupgradeneeded = (event) => { /* upgrade ?? reject; abort on REJECTED */ }; + request.onblocked = (event) => { /* onBlocked hook; timer or immediate BLOCKED */ }; + request.onerror = () => { /* upgradeRejection ?? NATIVE_EXCEPTION(request.error) */ }; + request.onsuccess = () => { /* settled/closed → close; else await admit → settle */ }; + }); +} +``` + +### 3.3 `src/adapters/platform/indexeddb-transaction.ts` + +```ts +/** + * IDB-X-02. Shared IndexedDB transaction and cursor mechanics. + * + * The same settle-once transaction state machine exists four times + * (`indexeddb-runtime.ts:976-1074`, `indexeddb-maintenance.ts:606-705`, + * `indexeddb-opfs-journal.ts:1098-1174`, + * `indexeddb-checkpoint-store.ts:497-596`) and the four already disagree: one + * of them never routes a request error at all, one aborts on a request error + * while two only record it, and one reports a value-less completion as + * CORRUPT_DATA while three report UNAVAILABLE. This module owns the mechanics + * and keeps every one of those choices at the call site. + */ + +import type { Result } from "../../contracts/result.ts"; +import type { + IndexedDbFailureCause, + IndexedDbTranslate, +} from "./indexeddb-connection.ts"; + +export type IndexedDbDurability = "default" | "strict" | "relaxed"; + +/** + * The failure half of a transaction context. Split out so helpers that only + * need to report failure (`onIndexedDbRequest`, `walkIndexedDbCursor`) do not + * have to be generic over the transaction's success type. + */ +export type IndexedDbRequestSink = Readonly<{ + /** + * Records the failure and aborts the transaction. The first failure wins. + * This is `indexeddb-runtime.ts:1047-1054`'s `fail`. + */ + fail(failure: Failure): void; + /** + * Records a request-level error **without aborting**: the transaction is left + * to complete or abort on its own, and the recorded error becomes the reported + * failure if it aborts. This is `indexeddb-runtime.ts:1055-1060`'s + * `requestFailed`. + * + * `indexeddb-checkpoint-store.ts:577-588` deliberately aborts instead. It + * keeps doing so by calling `fail(translate({kind:"NATIVE_EXCEPTION", error}))`. + * The kernel does not pick. + */ + requestFailed(error: unknown): void; +}>; + +export type IndexedDbTransactionContext = + IndexedDbRequestSink & + Readonly<{ + /** The first `succeed` wins; later ones are ignored. */ + succeed(value: Value): void; + /** For callers that need `objectStore()`/`index()` directly. */ + readonly transaction: IDBTransaction; + }>; + +export type IndexedDbTransactionInput = Readonly<{ + database: IDBDatabase; + stores: readonly string[]; + mode: "readonly" | "readwrite"; + translate: IndexedDbTranslate; + /** Aborts the transaction; the outcome is `CALLER_ABORT` unless completion won. */ + signal?: AbortSignal; + /** + * `undefined` opens with **no options bag at all**, which is + * `indexeddb-checkpoint-store.ts:512`'s current behavior — not the same as + * `"default"`, which passes `{durability:"default"}`. A named value falls back + * to the no-options form when the engine rejects the bag with a `TypeError`. + */ + durability?: IndexedDbDurability; + queue: ( + transaction: IDBTransaction, + context: IndexedDbTransactionContext, + ) => void; +}>; + +/** + * A transaction that completes without `succeed()` is reported through + * `translate({kind:"NO_VALUE_PRODUCED"})`. Three callers map that to + * UNAVAILABLE and `indexeddb-checkpoint-store.ts:541-547` maps it to + * CORRUPT_DATA; the kernel never picks. + */ +export function runIndexedDbTransaction( + input: IndexedDbTransactionInput, +): Promise>; + +/** + * The durability fallback on its own, for a caller that manages its own + * transaction. `undefined` omits the options bag entirely. + */ +export function openIndexedDbTransaction( + database: IDBDatabase, + stores: readonly string[], + mode: "readonly" | "readwrite", + durability?: IndexedDbDurability, +): IDBTransaction; + +/** + * Wires `onsuccess`/`onerror` in one place. The four copies write this pair by + * hand at roughly 70 sites and `indexeddb-opfs-journal.ts` omits `onerror` + * everywhere, which is how a request-level error there becomes whatever + * `transaction.error` happens to hold. + */ +export function onIndexedDbRequest( + request: IDBRequest, + sink: IndexedDbRequestSink, + onSuccess: (value: Value) => void, +): void; + +/** How the visitor wants the cursor advanced. */ +export type IndexedDbCursorStep = + | Readonly<{ kind: "CONTINUE" }> + | Readonly<{ kind: "CONTINUE_FROM"; key: IDBValidKey }> + | Readonly<{ kind: "CONTINUE_PRIMARY"; key: IDBValidKey; primaryKey: IDBValidKey }> + /** End the walk here; `done` gets `reason: "STOPPED"`. */ + | Readonly<{ kind: "STOP" }> + /** + * The visitor started its own request chain and will call `resume(step)` when + * that chain finishes. Without this the pump is unusable by three of the four + * callers: every walk in `indexeddb-runtime.ts` and `indexeddb-maintenance.ts` + * issues nested requests before advancing (e.g. `L1487-1526`, `L2406-2471`, + * `L1490-1541`). A pump that only understood `CONTINUE` would be the + * too-narrow-to-adopt failure again. + */ + | Readonly<{ kind: "SUSPEND" }>; + +export type IndexedDbBudgetVerdict = "CONTINUE" | "ROW_BUDGET" | "TIME_BUDGET"; + +export type IndexedDbBudget = Readonly<{ + /** + * Checked before each row. The kernel counts nothing itself: runtime bounds + * on rows it deleted (`indexeddb-runtime.ts:2384`) while maintenance bounds on + * rows it scanned (`indexeddb-maintenance.ts:823`), so the counter, the clock + * and the deadline all belong to the caller. A clock that cannot be read is a + * failure rather than a `false`, which is what `monotonicClock()` + * (`indexeddb-runtime.ts:2260-2269`) already does. + */ + admit(scannedRows: number): Result; +}>; + +export type IndexedDbCursorVisit = Readonly<{ + cursor: IDBCursorWithValue; + /** Rows handed to `visit` so far, this row included. */ + scannedRows: number; + /** Only meaningful after the visitor returned `SUSPEND`. Idempotent. */ + resume(step: IndexedDbCursorStep): void; +}>; + +export type IndexedDbWalkSummary = Readonly<{ + reason: "EXHAUSTED" | "STOPPED" | "ROW_BUDGET" | "TIME_BUDGET" | "ABORTED"; + scannedRows: number; +}>; + +export type IndexedDbWalkInput = Readonly<{ + request: IDBRequest; + sink: IndexedDbRequestSink; + translate: IndexedDbTranslate; + budget?: IndexedDbBudget; + /** + * Checked at each row. An aborted signal aborts the transaction and ends the + * walk with `reason: "ABORTED"`, which is what `indexeddb-runtime.ts:1375-1382` + * does inline today. + */ + signal?: AbortSignal; + visit: (visit: IndexedDbCursorVisit) => IndexedDbCursorStep; + /** The only success exit. The caller routes it into its own `succeed`. */ + done: (summary: IndexedDbWalkSummary) => void; +}>; + +/** + * Drives an open cursor. It reports a native advance failure through `sink` and + * never decides what a finished walk means — `reason` distinguishes a row budget + * from a time budget so a caller can keep reporting `budgetExhausted` exactly as + * it does now (`indexeddb-runtime.ts:2387`). + */ +export function walkIndexedDbCursor( + input: IndexedDbWalkInput, +): void; +``` + +### 3.4 확장점이 4벌의 요구를 어떻게 다 받는지 — 사본별 예시 + +**(a) RT: `mapIndexedDbException` + 호출처별 operation + 상태 브로드캐스트 + blocked 타이머** + +```ts +// 연산마다 번역기 하나. 커널은 "INDEXEDDB_OPEN"이라는 문자열을 모른다. +const translateFor = (operation: BrowserDataOperation): IndexedDbTranslate => + (cause) => { + switch (cause.kind) { + case "NATIVE_EXCEPTION": + return unwrap(mapIndexedDbException(cause.error, operation)); + case "BLOCKED": + case "BLOCKED_DEADLINE": + return unwrap(browserDataFailure("BLOCKED", operation, { + retryable: true, recovery: "RELOAD_OTHER_CONTEXTS", + })); + case "CALLER_ABORT": + return unwrap(browserDataFailure("ABORTED", operation)); + case "CLOSED": + case "NO_VALUE_PRODUCED": + // runtime L743 / L1020: close와 값 없는 완료는 둘 다 UNAVAILABLE이다. + return unwrap(unavailable(operation)); + case "UPGRADE_REJECTED": + return unwrap(browserDataFailure("MIGRATION_FAILED", "INDEXEDDB_MIGRATE", { recovery: "READ_ONLY" })); + case "ADMISSION_REJECTED": + // detail이 governance 거절인지 store 검증 실패인지는 RT만 안다. + return cause.detail === "POLICY" + ? unwrap(browserDataFailure("POLICY_REJECTED", operation, { + recovery: storagePolicySnapshot.unavailableFallback })) + : unwrap(mapIndexedDbException(cause.detail, "INDEXEDDB_MIGRATE")); + case "UNSUPPORTED": + return unwrap(browserDataFailure("UNSUPPORTED", operation, { recovery: "ONLINE_ONLY" })); + } + }; + +const connection = createIndexedDbConnection({ + open: (signal) => openIndexedDbDatabase({ + factory, databaseName, version: dependencies.schemaVersion, + translate: translateFor("INDEXEDDB_OPEN"), + signal, + blockedTimeoutMs, // L576 + timers: snapshotAbortTimers(scheduler), // L514-527를 대체 + onBlocked: (event) => { // L777-788 그대로 + updateStatus({ kind: "BLOCKED", currentVersion: event.oldVersion, + targetVersion: event.newVersion ?? dependencies.schemaVersion }); + observe({ operation: "INDEXEDDB_OPEN", outcome: "BLOCKED", + schemaVersion: dependencies.schemaVersion, countBucket: "0", failureCode: "BLOCKED" }); + }, + upgrade: ({ database, transaction, oldVersion, newVersion }) => { // L746-774 그대로 + let rejected = false; + try { + appliedMigrations = applyIndexedDbMigrations( + database, transaction, oldVersion, newVersion, dependencies.migrations); + queueIndexedDbUpgradeBinding( + transaction, dependencies.governanceStore, expectedBinding, oldVersion, + () => { rejected = true; }); + } catch (error) { + return { kind: "REJECTED", detail: error }; + } + return rejected ? { kind: "REJECTED", detail: "POLICY" } : { kind: "APPLIED" }; + }, + admit: async (database) => { // L844-895 그대로 + try { + assertIndexedDbRuntimeStores(database, /* … 8개 인자 … */); + } catch (error) { return { kind: "FAIL", cause: { kind: "ADMISSION_REJECTED", detail: error } }; } + const binding = await verifyIndexedDbDatasetBinding( + database, dependencies.governanceStore, expectedBinding, undefined); + if (binding.ok) return { kind: "ADMIT" }; + return binding.reason === "ABORTED" + ? { kind: "FAIL", cause: { kind: "CALLER_ABORT" } } + : binding.reason === "NATIVE_ERROR" + ? { kind: "FAIL", cause: { kind: "NATIVE_EXCEPTION", error: binding.error } } + : { kind: "REJECT", detail: "POLICY" }; + }, + }), + translate: translateFor("INDEXEDDB_OPEN"), + onVersionChange: () => { // L637-651에서 db.close()/connection=null 부분을 뺀 나머지 + const next = Object.freeze({ kind: "CLOSED" as const, reason: "VERSION_CHANGE" as const }); + updateStatus(next); + try { dependencies.onVersionChange?.(next); } catch { /* 알림과 종료는 독립 */ } + }, + onForcedClose: () => updateStatus({ kind: "CLOSED", reason: "FORCED" }), +}); +``` + +RT의 커서 예산(삭제 행 기준 + 모노토닉 deadline)은 `budget.admit`으로: + +```ts +// purgeEligibleRecords L2378-2389 → budget 하나로 +const budget: IndexedDbBudget = { + admit: () => { + const clock = monotonicClock(); // L2260-2269 그대로 남는다 + if (!clock.ok) return clock; + if (clock.value >= deadline) return ok("TIME_BUDGET"); + if (deletedRows >= input.maxRows) return ok("ROW_BUDGET"); // 삭제 행 기준 유지 + return ok("CONTINUE"); + }, +}; +``` + +**(b) MT: blocked 타이머 없음 + upgrade 자체가 실패 + `INDEXEDDB_MIGRATE` 고정 + 연결 캐시 안 씀** + +```ts +// 핸들을 만들지 않는다. openIndexedDbDatabase만 직접 부른다. (L1294-1296, finally L1364-1366 유지) +const opened = await openIndexedDbDatabase({ + factory, databaseName, version: dependencies.schemaVersion, + translate, // operation이 상수라 번역기도 하나 + signal: input.signal, + // blockedTimeoutMs 생략 → BLOCKED 원인이 blocked 이벤트에서 바로 나온다 (L485-492 동작 보존) + // upgrade 생략 → 어떤 upgrade든 UPGRADE_REJECTED (L477-484, L495-496 동작 보존) + admit: async (database) => { // L509-550 그대로 + for (const store of [recordStore, governanceStore, retentionStore, checkpointStore, idempotencyStore]) { + if (!database.objectStoreNames.contains(store)) return { kind: "REJECT", detail: "STORE" }; + } + try { + openIndexedDbTransaction(database, [dependencies.idempotencyStore], "readonly") + .objectStore(dependencies.idempotencyStore).index(dependencies.idempotencyExpiryIndex); + } catch { return { kind: "REJECT", detail: "INDEX" }; } + database.onversionchange = () => database.close(); // L543 그대로 + const binding = await verifyIndexedDbDatasetBinding( + database, dependencies.governanceStore, expectedBinding, input.signal); + return binding.ok ? { kind: "ADMIT" } : { kind: "REJECT", detail: binding }; + }, +}); +``` + +**(c) OP: signal 없음 + readwrite만 strict + 자체 observe shape** + +```ts +// listIncomplete L600-633 → walk. signal도 budget도 안 넘긴다: 지금 없는 걸 새로 만들지 않는다. +runIndexedDbTransaction({ + database: db, stores: [JOURNAL_STORE], mode: "readonly", + translate: translateFor("INDEXEDDB_READ"), + durability: undefined, // readonly는 오늘도 옵션 없음 (L1118) + queue: (transaction, context) => { + const rows: OpfsJournalTransaction[] = []; + walkIndexedDbCursor({ + request: transaction.objectStore(JOURNAL_STORE).index(STARTED_AT_INDEX).openCursor(), + sink: context, translate: translateFor("INDEXEDDB_READ"), + visit: ({ cursor }) => { + if (!isStoredJournalRow(cursor.value) || !isBoundScope(cursor.value.scope)) { + context.fail(unwrap(corrupt("INDEXEDDB_READ"))); + return { kind: "STOP" }; + } + if (rows.length === limit) return { kind: "STOP" }; + rows.push(cursor.value); + return { kind: "CONTINUE" }; + }, + done: (summary) => context.succeed(Object.freeze({ + transactions: Object.freeze(rows), + moreAvailable: summary.reason === "STOPPED" && rows.length === limit, + })), + }); + }, +}); +// readwrite 쪽만 durability: "strict" (L1181-1183 동작 보존) +``` + +**(d) CP: 다른 매핑 테이블 + 값 없는 완료가 CORRUPT_DATA + durability 없음 + 요청 오류에 즉시 abort** + +```ts +const translate: IndexedDbTranslate = (cause) => { + switch (cause.kind) { + case "NATIVE_EXCEPTION": + return unwrap(mapBrowserDataException(cause.error, "UPLOAD_RECONCILE")); // ← 다른 테이블 유지 + case "NO_VALUE_PRODUCED": + return unwrap(browserDataFailure("CORRUPT_DATA", "UPLOAD_RECONCILE", { recovery: "RECONCILE" })); + case "BLOCKED": + case "BLOCKED_DEADLINE": + return unwrap(browserDataFailure("BLOCKED", "UPLOAD_RECONCILE", { retryable: true, recovery: "RESUME" })); + case "CALLER_ABORT": + return unwrap(browserDataFailure("ABORTED", "UPLOAD_RECONCILE")); + case "CLOSED": + return unwrap(browserDataFailure("UNAVAILABLE", "UPLOAD_RECONCILE", { recovery: "RESUME" })); + /* … */ + } +}; + +runIndexedDbTransaction({ + database, stores: [CHECKPOINT_STORE], mode: "readonly", translate, signal, + durability: undefined, // L512: 오늘도 옵션 없음. 커널 기본값을 상속하지 않는다. + queue: (transaction, context) => { + const store = transaction.objectStore(CHECKPOINT_STORE); + const request = store.get(uploadKey); + // nativeFailure(= 기록 후 즉시 abort) 유지: requestFailed가 아니라 fail을 쓴다. + request.onerror = () => context.fail(translate({ kind: "NATIVE_EXCEPTION", error: request.error })); + request.onsuccess = () => { /* L265-283 그대로 */ }; + }, +}); +``` + +이 네 예시가 보여주는 것: **커널은 operation 라벨, 실패 코드, 매핑 테이블, blocked 정책, upgrade 정책, +예산 기준, abort 정책, durability 정책을 하나도 안 정한다.** `abortable-operation.ts:11`이 +`AbortTerminalReason`을 반환 타입에 박아 넣어 http v3가 못 쓴 것과 정확히 반대 구조다. + +--- + +## 4. 사본별 이행 계획 + +LOC 감소는 **추정**이다. 근거로 삭제 대상 블록의 줄 범위를 함께 적었다. + +### 4.1 RT — `indexeddb-runtime.ts` (2902 → 약 2665, **−235**) + +**삭제:** + +| 블록 | 줄 | LOC | 대체 | +|---|---|---:|---| +| `defaultScheduler` | L108-117 | 10 | `snapshotAbortTimers(scheduler)` | +| `TransactionContext` 타입 | L85-89 | 5 | `IndexedDbTransactionContext` | +| `waitForOpeningAttempt` | L659-682 | 24 | `connection.acquire(signal)` | +| `startOpeningAttempt` 중 배선 부분 (settle-once, generation 부기, blocked 타이머, onerror 라우팅, 늦은 close) | L684-745, L776-843, L872-921 중 배선분 | ~110 | `openIndexedDbDatabase` (upgrade/admit 콜백 본문은 그대로 남음) | +| `createTransaction` | L957-974 | 18 | `openIndexedDbTransaction` | +| `runTransaction` | L976-1074 | 99 | `runIndexedDbTransaction` | +| 커서 5곳의 deadline/maxRows/abort 보일러플레이트 | L1374-1382, L1454-1471, L2364-2389, L2531-2548, L2573-2590, L2644-2661, L2718-2735 | ~60 | `walkIndexedDbCursor` + `budget.admit` | +| 소계 삭제 | | **~326** | | +| 커널 호출부·콜백 추가 | | ~90 | | +| **순감** | | **~−235** | | + +**남는 것:** 코덱/영수증/보존/예산(bytes)/governance/migration 목록/상태 브로드캐스트/`monotonicClock`/ +`countBucket`/저장 레코드 술어/`purgePartitionRecords`의 스토어 순서 로직 — 전부 정책이라 그대로. + +**동작 변화 지점:** +- **RT-1.** `close()`가 진행 중 open을 끝내는 원인이 `unavailable(operation)`(L743)에서 + `translate({kind:"CLOSED"})`로 바뀐다. 위 번역기는 `CLOSED → unavailable`로 매핑해 **동일하게 유지**한다. + 이 매핑을 빠뜨리면 `close()` 중 open이 ABORTED로 보고된다. **테스트가 잡아야 할 지점.** +- **RT-2.** `settleNativeRequest`/`activeOpeningGeneration`(L595, L691-697)이 사라진다. 늦게 온 open의 무해화를 + 커널의 settle-once가 대신한다. RT의 generation 토큰은 `openingPromise` 정리 시점 제어용이었고 + `createIndexedDbConnection`의 단일 비행이 같은 역할을 한다. **의미 동일. 단 경합 순서가 달라질 수 있다.** +- **RT-3.** `openingRequest` 필드(L593)가 쓰이지 않게 된다(오늘도 L712와 L2878 대입 외에 읽는 곳 없음). 삭제. + +### 4.2 MT — `indexeddb-maintenance.ts` (1558 → 약 1370, **−188**) + +**삭제:** + +| 블록 | 줄 | LOC | 대체 | +|---|---|---:|---| +| `TransactionContext` 타입 | L97-101 | 5 | 커널 타입 | +| `openExactVersion` 중 배선분 | L434-508, L551-585 | ~95 | `openIndexedDbDatabase` (`admit`에 L509-550 이식) | +| `createTransaction` | L587-604 | 18 | `openIndexedDbTransaction` | +| `runTransaction` | L606-705 | 100 | `runIndexedDbTransaction` | +| 커서 2곳의 deadline/maxRows/abort 보일러플레이트 | L799-833, L1451-1479 | ~30 | `walkIndexedDbCursor` | +| 소계 삭제 | | **~248** | | +| 커널 호출부·콜백 추가 | | ~60 | | +| **순감** | | **~−188** | | + +**남는 것:** 체크포인트 상태기계(`readCheckpoint` L707-756, `commitPrepared` L969-1251), +`prepareRecords` L863-967, `clock`/`epochClock` L401-421, `countBucket` L239-245, 저장 술어 L118-223. + +**동작 변화 지점:** +- **MT-1. (가장 위험)** `blockedTimeoutMs`를 안 넘기면 오늘 동작(blocked 이벤트 즉시 BLOCKED, L485-492)이 + 유지된다. **넘기면 배치가 최대 그 시간만큼 매달린다.** `tests/unit/indexeddb-maintenance.test.ts:289-290`이 + `BLOCKED/retryable:true/RELOAD_OTHER_CONTEXTS`를 즉시 받길 기대하므로 값을 잘못 넣으면 타임아웃 실패한다. +- **MT-2.** `upgrade` 콜백을 **생략**해야 오늘의 "upgrade는 곧 실패"(L477-484)가 유지된다. 커널은 생략을 + `UPGRADE_REJECTED`로 해석하므로 실수로 빈 `upgrade: () => ({kind:"APPLIED"})`를 넣으면 잘못된 스키마로 + 열린다. **테스트가 잡아야 할 지점.** +- **MT-3.** `database.onversionchange = () => database.close()`(L543)를 `admit` 안으로 옮긴다. `admit`은 + 성공 경로에서만 실행되므로 등록 시점이 오늘과 같다. + +### 4.3 OP — `indexeddb-opfs-journal.ts` (1817 → 약 1690, **−127**) + +**삭제:** + +| 블록 | 줄 | LOC | 대체 | +|---|---|---:|---| +| `TransactionContext` 타입 | L48-51 | 4 | 커널 타입 | +| scheduler 기본값 인라인 | L144-153 | 10 | `snapshotAbortTimers` | +| `openDatabase` 중 배선분 | L961-996, L1031-1072 | ~79 | `openIndexedDbDatabase` + `createIndexedDbConnection` (upgrade 본문 L997-1029는 `upgrade` 콜백으로 그대로 이동) | +| `runTransaction` | L1098-1174 | 77 | `runIndexedDbTransaction` | +| `strictReadwriteTransaction` | L1176-1190 | 15 | `openIndexedDbTransaction(…, "strict")` | +| 커서 2곳의 limit 루프 | L604-633, L677-712 | ~20 | `walkIndexedDbCursor` | +| 소계 삭제 | | **~205** | | +| 커널 호출부 + **누락된 요청 오류 배선 추가** | | ~78 | | +| **순감** | | **~−127** | | + +**동작 변화 지점:** +- **OP-1. (이 리팩토링에서 가장 큰 동작 변화)** 오늘 OP는 트랜잭션 안의 개별 요청에 `.onerror`를 **하나도** + 안 단다(파일 전체 request `.onerror`는 L1042 open 요청뿐). 요청 실패는 `transaction.onabort`로만 흘러 + `mapIndexedDbException(transaction.error)`(L1158)가 된다. 커널을 쓰면 **요청 자신의 오류가 보고된다.** + 구체적으로 `LOGICAL_KEY_INDEX`가 `unique:true`(L1000-1004)이므로 중복 put은 요청 레벨 + `ConstraintError` → `CONFLICT`가 되고, 오늘은 `transaction.error`가 무엇이냐에 따라 달라진다. + **`tests/unit/indexeddb-opfs-journal.test.ts`가 잡아야 할 지점.** +- **OP-2.** 오늘 OP의 `runTransaction`은 `succeed` 이후 `fail`이 와도 `explicitFailure`가 이기지만 + (L1133-1141, `hasValue`는 그대로 true) `oncomplete`는 값을 반환한다(L1143-1153). 커널의 + "첫 결과가 이긴다" 규칙(RT L1044-1054와 동일)을 따르면 **`succeed` 후의 `fail`이 무시된다.** + 현재 OP 코드에서 그 순서가 실제로 발생하는 경로가 있는지는 **미확인** — 이행 시 확인 필요. +- **OP-3.** `context.fail` 시 abort가 실패하면 오늘은 즉시 `settle(result)`(L1139)한다. 커널(RT식)은 + `finish(candidate ?? …)`로 같은 결과를 낸다. 의미 동일. +- **OP-4.** `signal`은 **넣지 않는다.** 오늘 없는 취소를 새로 만들지 않는다. + +### 4.4 CP — `indexeddb-checkpoint-store.ts` (712 → 약 570, **−142**) + +**삭제:** + +| 블록 | 줄 | LOC | 대체 | +|---|---|---:|---| +| `TransactionContext` 타입 | L491-495 | 5 | 커널 타입 | +| `openAndBind` 중 open 요청 Promise 배선 | L163-175, L198-217 | ~33 | `openIndexedDbDatabase` (upgrade 본문 L176-197은 콜백으로 이동, `bindScope` 호출은 `admit`으로 이동) | +| `runCheckpointTransaction` | L497-596 | 100 | `runIndexedDbTransaction` | +| `bindScope`의 트랜잭션 배선 | L602-623 | ~22 | `runIndexedDbTransaction` (검증 로직 L624-652는 `queue`로 그대로) | +| `deletePartition`의 blocked/settle 배선 | L431-462, L472-483 | ~35 | `deleteIndexedDbDatabase` | +| 소계 삭제 | | **~195** | | +| 커널 호출부·콜백 추가 | | ~53 | | +| **순감** | | **~−142** | | + +**남는 것:** `PENDING_DELETIONS` 레지스트리 L31-41 + 생성 시 검사 L116-122, `uploadCheckpointDatabaseName` +L73-83, `sameScopeBinding` L656-672, `snapshotScope` L674-691, `snapshotCheckpoint` L693-711. + +**동작 변화 지점:** +- **CP-1.** 값 없는 완료가 `CORRUPT_DATA/RECONCILE`(L541-547)로 유지되려면 번역기가 + `NO_VALUE_PRODUCED → CORRUPT_DATA`를 **명시적으로** 매핑해야 한다. 안 하면 UNAVAILABLE로 바뀐다. + **테스트가 잡아야 할 지점.** +- **CP-2.** `durability: undefined`를 **명시적으로** 넘겨야 오늘 동작(옵션 bag 없음, L512)이 유지된다. + 커널 기본을 상속하거나 `"strict"`를 넣으면 체크포인트 쓰기가 조용히 strict가 되어 느려진다. 정확성은 + 안 깨지지만 성능 회귀다. +- **CP-3.** `nativeFailure`(L577-588, 기록 후 즉시 abort)는 `context.fail(translate(NATIVE_EXCEPTION))`으로 + 표현한다. `requestFailed`(abort 안 함)로 잘못 바꾸면 **요청이 실패했는데도 뒤 요청이 커밋될 수 있다.** + `compareAndSwap`의 `get → put` 체인(L321-343)에서 특히 위험하다. **테스트가 잡아야 할 지점.** +- **CP-4.** `abort()` 호출이 throw했을 때 오늘은 `failure`를 **되돌린다**(L528, L536: "durably committed while + its completion event is still queued" — 커밋된 변경을 ABORTED로 보고하지 않기 위함). 커널의 + RT식 `onAbort`(L1010-1017)에는 이 되돌림이 없다. **커널의 signal abort 처리는 CP의 이 규칙을 채택해야 한다: + abort가 throw하면 caller-abort 표시를 세우지 않고 transaction 이벤트가 결과를 정한다.** 이건 커널 구현의 + 필수 요건이고, 놓치면 CP가 커밋된 체크포인트를 ABORTED로 보고한다. + → `tests/unit/resumable-upload-checkpoint.test.ts:238` "never reports a false abort after irreversible + deleteDatabase dispatch"가 인접 케이스를 이미 지킨다. +- **CP-5.** `deletePartition`의 blocked 타이머가 네이티브 `setTimeout`(L450)에서 주입형 `timers`로 바뀐다. + `tests/unit/resumable-upload-checkpoint.test.ts:194`가 이 경로를 본다. +- **CP-6.** `deleteDatabase`를 나머지 3벌에 **추가하지 않는다.** §2.3 근거. + +### 4.5 전체 합계 + +| | LOC | +|---|---:| +| 4벌에서 삭제 | ~974 | +| 4벌에 추가 (커널 호출부·콜백) | ~281 | +| 4벌 순감 | **~−693** | +| 커널 신규 2파일 | +~470 | +| **레포 순증감** | **~−223** | + +**솔직한 평가:** LOC 절감은 크지 않다. 이 작업의 성과는 줄 수가 아니라 **트랜잭션 상태기계가 4개에서 1개가 +되는 것**이다. 오늘 그 4개는 §1.5에서 본 대로 이미 4가지 다른 답을 낸다(요청 오류를 안 봄 / 기록만 / 즉시 +abort, 값 없는 완료가 UNAVAILABLE / CORRUPT_DATA). LOC로 정당화하면 안 된다. + +--- + +## 5. 위험과 선행조건 + +### 5.1 선행조건 P1 — ESLint (**가장 놓치기 쉬움**) + +`eslint.config.ts:40-63`의 `restrictedBrowserDataProperties`는 `globalThis`/`window`/`self` 세 루트 전부에서 +`indexedDB` **속성 접근**을 금지한다. 추가로 `eslint.config.ts:112-…`의 커스텀 규칙 +`browser-data-boundary/no-capability-alias`가 지역 별칭까지 따라간다 +(`const host = globalThis; host.indexedDB`도 잡힌다 — 규칙 주석 `eslint.config.ts:107-111`). + +두 개의 예외 목록(`eslint.config.ts:519-530`, `eslint.config.ts:677-691`)은 `src/adapters/platform/`을 +**폴더가 아니라 `browser-lifecycle.ts` 한 파일로** 열어 놨다. + +→ **설계 결론: 커널은 `globalThis.indexedDB`를 절대 읽지 않는다.** `IDBFactory`는 필수 주입 파라미터다 +(§3.2). 네 사본은 이미 전역 해석을 자기가 한다(RT L565-569, MT L359-363, OP L130-134, CP L95-97). +**이 설계대로면 `eslint.config.ts`를 한 줄도 안 고쳐도 된다.** + +확인해 둔 것: `IDBFactory`·`IDBDatabase`·`IDBTransaction`·`IDBRequest`·`IDBKeyRange`·`IDBCursorWithValue`는 +어느 금지 목록에도 없다(`eslint.config.ts:40-63`, `:544-561`). 커널이 이 타입들을 이름으로 쓰는 건 문제없다. + +대안(커널이 전역을 읽게 하기)을 택하면 `eslint.config.ts`의 **두 목록 모두**에 신규 파일 2개를 추가해야 한다. +한쪽만 고치면 `no-capability-alias`나 `no-restricted-properties` 중 하나가 남아서 `pnpm lint`가 깨진다. + +### 5.2 선행조건 P2 — `docs/reviews/adapters/INVENTORY.md` **갱신 필요** + +`scripts/check-adapter-inventory.ts:23-31`이 `git ls-files src/adapters`와 inventory 행을 **집합으로** 대조하고 +(`:41-53`), 중복을 거부하며(`:62-64`), `합계: **N/N**`의 두 숫자가 파일 수와 같아야 한다(`:65-72`). + +현재 총계는 `INVENTORY.md:132`의 `합계: **120/120**`이다. 신규 파일 2개 → **`122/122`**. + +확인해 둔 유용한 사실: 행 번호 정규식은 `/^\|\s*\d+\s*\|\s*` + 백틱 경로다(`:35`). 번호는 **위치와 대조되지 +않고** 순서도 무관하다(실제로 현재 `platform/` 행 59-63은 `git ls-files` 정렬과 순서가 다르다 — +`INVENTORY.md:69-73`). → **기존 행을 재번호할 필요 없이 121, 122번 행을 추가하면 된다.** + +추가할 행(기존 `platform/` 행들과 같은 상세 리뷰 링크): + +``` +| 121 | `src/adapters/platform/indexeddb-connection.ts` | [Network/state](./01-network-and-state.md) | +| 122 | `src/adapters/platform/indexeddb-transaction.ts` | [Network/state](./01-network-and-state.md) | +``` + +`INVENTORY.md:132`의 안내문이 "해당 상세 리뷰 inventory를 같은 변경에서 갱신한다"고 요구한다. +→ `docs/reviews/adapters/01-network-and-state.md`에도 두 행이 필요하다. 다만 **그 파일에 구조적 게이트가 +걸려 있는지는 미확인**이다 (`check-adapter-inventory.ts`는 `INVENTORY.md`만 읽는다, `:20`). + +### 5.3 선행조건 P3 — dependency-cruiser **변경 불필요** + +`adapters-do-not-know-other-concrete-adapters`의 `pathNot`이 +`^src/adapters/($1/|platform/|browser-file-storage/result\.ts$|cross-context-invalidation/index\.ts$)`이므로 +`src/adapters/platform/` 전체가 이미 허용 대상이다. 네 사본 전부 커널을 import할 수 있다. + +커널이 `src/contracts/result.ts`를 import하는 것도 허용된다: +- dependency-cruiser에서 contracts를 언급하는 유일한 규칙은 `concrete-adapters-compose-only-in-bootstrap`인데, + 이건 `contracts → adapters`를 막지 `adapters → contracts`를 막지 않는다. +- eslint `layerPatterns.adapters`는 `["**/presentation/**", "**/bootstrap/**"]`뿐이다(`eslint.config.ts:33`). +- 선례: `src/adapters/web-push/push-association-fence-store.ts:12`가 `../../contracts/web-push.ts`를 import한다. + +그리고 `Result`(`src/contracts/result.ts:13-15`)를 쓰면 +`Result`가 정의상 `BrowserDataResult`와 **같은 타입**이다 +(`src/application/ports/browser-file-storage/shared.ts:95`). 변환 코드가 0줄이다. + +### 5.4 깨질 수 있는 기존 테스트 (grep으로 확인한 목록) + +| 파일 | LOC | 위험 | +|---|---:|---| +| `tests/helpers/memory-indexeddb.ts` | 922 | **최고 위험.** 단위 테스트 전부가 도는 가짜 IDB. OP-1(요청 레벨 `onerror`를 새로 달게 됨)이 이 가짜가 `request.error`를 실제로 채우는지에 의존한다. 오늘 OP는 요청 오류를 안 보므로 그 경로가 **한 번도 행사되지 않았을 수 있다.** 채우지 않으면 `NATIVE_EXCEPTION{error: null}` → `UNAVAILABLE`로 뭉개진다. **이행 전에 이 파일을 먼저 읽어야 한다 (이번 조사에서는 미확인).** | +| `tests/unit/indexeddb-runtime.test.ts` | 1140 | RT-1(CLOSED 매핑). 실패 코드 단언은 `:339-340, :371-372, :454, :534, :549-550, :734-735` | +| `tests/unit/indexeddb-maintenance.test.ts` | 842 | MT-1(blocked 즉시 실패). `:289-290`이 `BLOCKED/retryable:true/RELOAD_OTHER_CONTEXTS`를 단언. MT-2(upgrade 거절)도 여기 | +| `tests/unit/indexeddb-opfs-journal.test.ts` | 431 | **OP-1, OP-2.** 요청 오류가 새 코드로 보고되는 건 이 테스트가 잡아야 한다 | +| `tests/unit/resumable-upload-checkpoint.test.ts` | 265 | **CP-1, CP-3, CP-4, CP-5.** `:142` CONFLICT/RECONCILE, `:190` UNAVAILABLE/RESUME, `:194` blocked PENDING, `:238` false-abort 금지 | +| `tests/unit/runtime-adapters.test.ts` | — | `storage/indexeddb` import. 공개 형태가 안 바뀌면 영향 없음 | +| `tests/helpers/fake-push-control-repository.ts`, `tests/unit/web-push-store-port-compatibility.test.ts` | — | RT의 공개 포트 형태에만 의존. §0대로 IDB 코드 없음. 공개 형태 불변이면 영향 없음 | +| `tests/unit/abortable-operation.test.ts`, `tests/unit/system-clock.test.ts` | — | 기존 커널 테스트. `snapshotAbortTimers` 재사용은 계약을 안 바꾸므로 영향 없음 | +| `tests/browser-capabilities/indexeddb-runtime.spec.ts` | 1033 | 실브라우저 Playwright. `deleteDatabase`는 정리용(`:443, :832, :923, :1019`)이라 이번 변경과 무관. 다만 RT의 blocked/versionchange 실동작을 보므로 회귀 감지망 | +| `tests/browser-capabilities/opfs-runtime.spec.ts` | 221 | 동 (`:137`) | +| `tests/browser-capabilities/resumable-upload.spec.ts` | 526 | CP 실동작 | +| `tests/fixtures/optional-recipes/forbidden/runtime-composition/src/bootstrap/bad-runtime.ts` | — | 픽스처. 경로 변경이 없으므로 영향 없음 | + +**신규 테스트:** `tests/unit/indexeddb-connection.test.ts`, `tests/unit/indexeddb-transaction.test.ts`가 +관례상 필요하다(`abortable-operation.test.ts`, `system-clock.test.ts` 선례). `check:test-evidence` / +`check:risk-coverage`가 신규 소스 파일당 테스트를 **강제하는지는 미확인**. + +### 5.5 "커널이 커진다"는 반론과 답 + +**반론:** 오늘 `src/adapters/platform/`은 5파일 550 LOC이고 전부 진짜 원시 요소다 — 시계 24줄, abort 269줄, +용량 가드 21줄, 라이프사이클 186줄, UUID 50줄. 여기에 IndexedDB 전용 470 LOC를 넣으면 "platform"이라는 이름이 +거짓말이 된다. IndexedDB는 플랫폼 원시 요소가 아니라 **하나의 저장 기술**이다. + +**답 1 — 이 레포의 커널 기준은 "보편성"이 아니라 "네이티브 표면의 단일 소유자"다.** 같은 반론이 +`browser-lifecycle.ts`(186 LOC, `visibilitychange`/`online`/`pagehide` 전용)에도 그대로 적용되지만 그 파일은 +이미 커널이고, 자기 주석이 근거를 밝힌다(`browser-lifecycle.ts:4-7`: "No capability adds its own listener… +so the listener count stays constant"). dependency-cruiser 규칙 주석도 같은 말을 한다: +"Only the adapter kernel is shared — `src/adapters/platform` (clock, abort primitive, capacity guard)". + +**답 2 — 다른 위치는 전부 더 나쁘다.** +- `src/adapters/storage/indexeddb/`에 두면 `adapters-do-not-know-other-concrete-adapters`가 + `browser-transfer/`와 `storage/opfs/`의 import를 금지한다. **중복이 존재하는 이유가 바로 이것이다.** +- 새 최상위 `src/adapters/indexeddb-kernel/`은 dependency-cruiser 규칙 변경이 필요한데, 리뷰가 이미 그 비용을 + 이유로 기각했다. + +**답 3 (실제로 위험을 한정하는 답) — 커널은 IndexedDB "정책"을 하나도 갖지 않는다.** +커널이 소유하는 것: 이벤트 배선(request→콜백), 트랜잭션 상태기계, 커서 펌프, settle-once, blocked 래치. +커널이 소유하지 **않는** 것: DB 이름, 스키마, 마이그레이션, governance 바인딩, 코덱, 바이트 예산, 보존 정책, +멱등 영수증, 실패 코드 테이블, operation 라벨, 관측 이벤트 shape, durability 기본값, 예산 기준. +**나중에 이 목록 중 하나를 커널에 넣고 싶어지면, 그게 멈춰야 한다는 신호다.** 이 문장을 커널 파일 최상단 +주석에 넣는다. + +**답 4 — `abortable-operation.ts`의 실패를 반복하지 않는 구체적 차이.** +`abortable-operation.ts:11`의 `AbortTerminalReason`은 3멤버 닫힌 union이고 `AbortRace`(`:19-22`)의 +**반환 타입에 박혀 있다.** 소비자가 5종이 필요하면 커널을 수정하거나 포기하는 두 길뿐이고, http v3는 포기했다. +커널의 `IndexedDbFailureCause`는 **반환 타입에 안 나온다.** 반환 타입은 `Result`이고 `Failure`는 +호출처가 정한다. cause는 `translate` 함수의 **입력**일 뿐이라, 멤버를 추가하면 모든 `translate`에서 +**컴파일 에러**가 나고(전역 함수이므로) 조용한 동작 변화가 안 생긴다. 확장이 커널 수정 없이도 되고, +커널 수정이 필요할 때도 누락이 타입 검사로 잡힌다. + +**남는 솔직한 위험:** 그래도 4개 어댑터가 공통으로 의존하는 470 LOC가 생긴다. 여기 버그가 나면 폭발 반경이 +4배다. 이걸 없앨 방법은 없고, 대가로 얻는 건 §1.5의 4가지 다른 답이 1가지가 되는 것이다. 그 교환이 +받아들일 만한지가 이 리팩토링의 진짜 판단이다. + +--- + +## 6. 이행 순서 권고 + +1. 커널 2파일 + 단위 테스트 추가. 사본은 손대지 않는다. → 게이트 기준선 유지 확인 + (`check:architecture`, `check:types:app`, `lint`, `check:adapter-inventory`). + 이 단계에서 INVENTORY.md(+`01-network-and-state.md`)를 같이 갱신한다. +2. **CP 먼저** 이행. 가장 작고(712), 동작 변화 지점(CP-1~CP-6)이 가장 명확하며, 커널의 CP-4 요건 + (abort가 throw하면 caller-abort를 세우지 않는다)을 조기에 검증한다. +3. **MT.** 커널 사용자 중 연결 핸들을 안 쓰는 유일한 사본이라 `openIndexedDbDatabase` 단독 사용 경로를 검증한다. +4. **OP.** OP-1 때문에 `tests/helpers/memory-indexeddb.ts` 보강이 선행될 가능성이 높다. +5. **RT 마지막.** 가장 크고 다른 셋이 커널을 다 검증한 뒤에 옮긴다. diff --git a/docs/testing/frontend-platform-testing-strategy.md b/docs/testing/frontend-platform-testing-strategy.md index 6003f36..1b33612 100644 --- a/docs/testing/frontend-platform-testing-strategy.md +++ b/docs/testing/frontend-platform-testing-strategy.md @@ -90,13 +90,39 @@ production Playwright profile은 source fixture가 아니라 `build` + `preview` #### TanStack Query의 React integration test 기반 -`tests/component/application-query.test.tsx`는 production query inbound -adapter의 query/mutation lifecycle을 검증한다. cancellation, initial terminal -failure, background stale-failure latch와 retry 복구, duplicate submit, -optimistic commit/rollback, conflict 해제와 namespace invalidation이 실제 -QueryClient 위에서 실행된다. HTTP 자동 retry가 소유자이므로 이 adapter의 +production query inbound adapter의 React integration은 behavior owner별 +component suite로 분리되어 있다. + +- `application-query-bridge.test.tsx`: initial/background state, cancellation +- `application-query-scope-fence.test.tsx`: scope commit fence와 result budget +- `application-mutation-scope-fence.test.tsx`: mutation scope fence +- `application-query.test.tsx`: unknown-effect reconciliation +- `application-mutation-admission.test.tsx`: intent/duplicate admission +- `application-mutation-optimistic-cache.test.tsx`: optimistic cache commit/rollback +- `application-query-fixture.tsx`: 공통 QueryClient/scope fixture + +각 실패 파일명이 깨진 behavior contract를 직접 드러내며, 동일한 52개 계약을 +실제 QueryClient 위에서 검증한다. HTTP 자동 retry가 소유자이므로 이 adapter의 query/mutation vendor retry는 꺼져 있다. +같은 기준을 대형 unit suite에도 적용한다. 줄 수를 기준으로 자르지 않고 실패가 +가리켜야 하는 behavior owner를 기준으로 분리한다. + +- `public-response-cache.test.ts`: 일반 stage/activate/lookup/cache contract +- `public-response-cache-repair.test.ts`: active release repair의 failure atomicity +- `resumable-upload-runtime.test.ts`: upload/reconcile/control-plane 흐름 +- `resumable-upload-runtime-teardown.test.ts`: bounded drain/raw provider teardown +- `security-followup.test.ts`: archived local evidence +- `security-provider-evidence.test.ts`: provider signature/supervision/process lifecycle +- `security-promotion-staging.test.ts`: private staging seal/replay/CLI identity +- `tests/integration/provider-guardian-transaction.test.ts`: child process, + filesystem, IPC frame, READY/PUBLISHED handshake와 process lifecycle. pure unit + pool에 두지 않으며 handshake budget은 protocol timeout이 아닌 test watchdog이다. +- 각 `*-fixture.ts`: 해당 owner들 사이에서만 공유하는 deterministic test fixture + +이 분리는 production owner와 test failure surface를 맞추기 위한 것이며, 단순 +LOC 감축 목적이 아니다. + #### Form과 route 위험 form component/reference feature test가 error summary, 첫 오류 focus, Zod diff --git a/docs/testing/taxonomy.md b/docs/testing/taxonomy.md index 8a4b847..421a3d6 100644 --- a/docs/testing/taxonomy.md +++ b/docs/testing/taxonomy.md @@ -3,14 +3,72 @@ Each gate is blocking in its declared scope. Failures are not downgraded with `continue-on-error` or warning-only scripts. -| Level | Command | Evidence | -| --- | --- | --- | -| runtime schema | `pnpm test:runtime-schema` | `artifacts/tests/runtime-schema.xml` | -| unit | `pnpm test:unit` | `artifacts/tests/unit.xml` | -| component | `pnpm test:component` | `artifacts/tests/component.xml` | -| integration | `pnpm test:integration` | `artifacts/tests/integration.xml` | -| end-to-end | `pnpm test:e2e` | `artifacts/tests/e2e/` | -| accessibility | `pnpm test:a11y` | `artifacts/tests/a11y.json` | +## Executable levels + +| Level | Command | Ownership / prerequisite | Evidence | +| --- | --- | --- | --- | +| runtime schema | `pnpm test:runtime-schema` | pure runtime schema contracts | `artifacts/tests/runtime-schema.xml` | +| unit | `pnpm test:unit` | Node-only domain/application/pure policy/runtime units; no systemd/bwrap/cgroup prerequisite | `artifacts/tests/unit.xml` | +| capability contract | `pnpm test:contract` | reusable capability consumer contracts | `artifacts/tests/contract.xml` | +| component | `pnpm test:component` | React/hook/UI behavior | `artifacts/tests/component.xml` | +| integration | `pnpm test:integration` | HTTP/MSW, IndexedDB, composed browser-runtime boundaries, child-process/filesystem/IPC integration | `artifacts/tests/integration.xml` | +| system / CI runner | `pnpm test:system` | compatible Linux host with systemd, bubblewrap, cgroup v2 and CI-provider process controls | `artifacts/tests/system.xml` | +| end-to-end | `pnpm test:e2e` | pinned browser engines | `artifacts/tests/e2e/` | +| accessibility | `pnpm test:a11y` | pinned browser engines | `artifacts/tests/a11y.json` | + +`test:all` is the normal product-development loop. It intentionally includes +runtime-schema, unit, capability-contract, component, integration, reference +feature and recipe suites, but does not include `test:system`. CI-runner and +supply-chain assurance has different host prerequisites and is invoked +explicitly in the assurance path. + +## Deterministic test process + +All Vitest package scripts launch through `scripts/run-vitest.ts`. + +That runner: + +1. rejects Node versions outside the repository-supported + `>=24.11.0 <25.0.0` range before the suite starts, +2. owns `NODE_ENV=test` rather than trusting the parent shell, +3. removes host-specific `npm_config_userconfig`, `npm_config_prefix` and + `npm_config_globalconfig` values before Vitest starts. + +`vitest.config.ts` also fixes `NODE_ENV=test` so a direct Vitest invocation +cannot accidentally select React's production behavior. + +The system suite additionally runs +`scripts/check-system-test-prerequisites.ts` and fails with one prerequisite +report when the CI-runner host does not provide its required Linux facilities. + +## Development paths + +Product feature: + +- focused feature/unit/component test +- capability contract test when a reusable boundary changes +- type/lint/architecture +- `test:all` + +Reusable capability: + +- focused unit tests +- capability contract tests +- integration tests +- type/lint/architecture + +CI / release assurance: + +- `test:system` +- supply-chain / promotion / release gates + +A host-level process/sandbox test must not be placed in `tests/unit` merely +because it uses Vitest. The classification follows the system boundary and +prerequisites, not the test framework. Process-heavy tests that spawn child +processes but do not require privileged host facilities belong in +`tests/integration`; for example the provider guardian transaction protocol +lives at `tests/integration/provider-guardian-transaction.test.ts`. Its +handshake timeout is a test watchdog, not a production protocol deadline. End-to-end and automated accessibility scenarios run on the pinned Chromium, Firefox, and WebKit engines. The responsive contract explicitly exercises @@ -30,9 +88,6 @@ Promotion is an AND graph: 3. release gates plus rollback/runbook drills 4. production promotion plus eligible field Web Vitals evidence -This file describes the currently registered taxonomy. The -[frontend platform testing strategy](./frontend-platform-testing-strategy.md) -documents the target additions: test TypeScript projects, real bootstrap -composition tests, shared MSW scenarios, query/mutation/form/router coverage, -Storybook interaction and accessibility checks, visual regression, and a -built-output Playwright profile. +The [frontend platform testing strategy](./frontend-platform-testing-strategy.md) +contains the broader testing design. This file is the executable taxonomy for +where a test belongs and which environment is allowed to run it. diff --git a/package.json b/package.json index d3c04e5..b9ef85c 100644 --- a/package.json +++ b/package.json @@ -31,29 +31,31 @@ "check:types:node": "tsc --project tsconfig.node.json", "check:types:test": "tsc --project tsconfig.test.json", "check:types:recipes": "node scripts/check-optional-recipe-types.ts", - "check:types:fixture": "tsc --ignoreConfig --strict --noEmit --target ES2022 --module NodeNext --moduleResolution NodeNext tests/fixtures/typecheck/invalid-port-call.ts", - "check:types:fixture:ts-port": "tsc --ignoreConfig --strict --noEmit --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-port-implementation.ts", - "check:types:fixture:ts-result": "tsc --ignoreConfig --strict --noEmit --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-result-narrowing.ts", - "check:types:fixture:application-output": "tsc --ignoreConfig --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-application-output.ts", - "check:types:fixture:application-input": "tsc --ignoreConfig --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-application-input.ts", - "check:types:fixture:feature-input": "tsc --ignoreConfig --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-feature-input.ts", - "check:types:fixture:failure-kind": "tsc --ignoreConfig --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-failure-kind.ts", - "check:types:fixture:reference-operation": "tsc --ignoreConfig --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-reference-operation.ts", - "check:types:fixture:async-overlay": "tsc --ignoreConfig --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-async-overlay.ts", - "check:types:fixture:route-runtime": "tsc --ignoreConfig --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-route-runtime.ts", - "check:types:fixture:page-action": "tsc --ignoreConfig --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler --jsx react-jsx tests/fixtures/typecheck/invalid-page-action.tsx", - "check:types:fixture:icon-button": "tsc --ignoreConfig --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler --jsx react-jsx tests/fixtures/typecheck/invalid-icon-button.tsx", - "check:types:fixture:i18n-key": "tsc --ignoreConfig --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-message-key.ts", - "check:types:fixture:i18n-params": "tsc --ignoreConfig --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-message-params.ts", - "check:types:fixture:diagnostics": "tsc --ignoreConfig --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-diagnostics-port.ts", - "check:types:fixture:image-resolve-signal": "tsc --ignoreConfig --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-image-cdn-resolve-signal.ts", - "test:runtime-schema": "vitest run tests/runtime-schema --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/runtime-schema.xml --passWithNoTests", - "test:unit": "vitest run tests/unit --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/unit.xml", - "test:component": "vitest run tests/component --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/component.xml", - "test:integration": "vitest run tests/integration --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/integration.xml", - "test:http-scenario-catalog": "vitest run tests/integration/http-scenario-catalog.test.ts --reporter=default --maxWorkers=1", + "check:types:fixture": "tsc -p tests/fixtures/typecheck/tsconfig.port-call.json", + "check:types:fixture:ts-port": "tsc -p tests/fixtures/typecheck/tsconfig.port-implementation.json", + "check:types:fixture:ts-result": "tsc -p tests/fixtures/typecheck/tsconfig.result-narrowing.json", + "check:types:fixture:application-output": "tsc -p tests/fixtures/typecheck/tsconfig.application-output.json", + "check:types:fixture:application-input": "tsc -p tests/fixtures/typecheck/tsconfig.application-input.json", + "check:types:fixture:feature-input": "tsc -p tests/fixtures/typecheck/tsconfig.feature-input.json", + "check:types:fixture:failure-kind": "tsc -p tests/fixtures/typecheck/tsconfig.failure-kind.json", + "check:types:fixture:reference-operation": "tsc -p tests/fixtures/typecheck/tsconfig.reference-operation.json", + "check:types:fixture:async-overlay": "tsc -p tests/fixtures/typecheck/tsconfig.async-overlay.json", + "check:types:fixture:route-runtime": "tsc -p tests/fixtures/typecheck/tsconfig.route-runtime.json", + "check:types:fixture:page-action": "tsc -p tests/fixtures/typecheck/tsconfig.page-action.json", + "check:types:fixture:icon-button": "tsc -p tests/fixtures/typecheck/tsconfig.icon-button.json", + "check:types:fixture:i18n-key": "tsc -p tests/fixtures/typecheck/tsconfig.message-key.json", + "check:types:fixture:i18n-params": "tsc -p tests/fixtures/typecheck/tsconfig.message-params.json", + "check:types:fixture:diagnostics": "tsc -p tests/fixtures/typecheck/tsconfig.diagnostics-port.json", + "check:types:fixture:image-resolve-signal": "tsc -p tests/fixtures/typecheck/tsconfig.image-cdn-resolve-signal.json", + "test:runtime-schema": "node scripts/run-vitest.ts run tests/runtime-schema --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/runtime-schema.xml --passWithNoTests", + "test:unit": "node scripts/run-vitest.ts run tests/unit --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/unit.xml", + "test:contract": "node scripts/run-vitest.ts run tests/contract --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/contract.xml", + "test:system": "node scripts/check-system-test-prerequisites.ts && node scripts/run-vitest.ts run tests/system --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/system.xml", + "test:component": "node scripts/run-vitest.ts run tests/component --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/component.xml", + "test:integration": "node scripts/run-vitest.ts run tests/integration --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/integration.xml", + "test:http-scenario-catalog": "node scripts/run-vitest.ts run tests/integration/http-scenario-catalog.test.ts --reporter=default --maxWorkers=1", "test:http-scenario-evidence": "node scripts/run-http-scenario-evidence.ts", - "test:recipes": "vitest run tests/recipes --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/optional-recipes.xml --passWithNoTests", + "test:recipes": "node scripts/run-vitest.ts run tests/recipes --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/optional-recipes.xml --passWithNoTests", "test:e2e": "playwright test", "test:e2e:dev": "playwright test --config playwright.dev.config.ts", "test:browser-capabilities": "playwright test --config playwright.capabilities.config.ts", @@ -75,12 +77,12 @@ "test:optional-recipe-removal": "node scripts/test-optional-recipe-removal.ts", "test:browser-file-storage-removal": "node scripts/test-browser-file-storage-runtime-removal.ts", "test:realtime-removal": "node scripts/test-realtime-runtime-removal.ts", - "test:reference-feature": "vitest run tests/features/reference-feature --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/reference-feature.xml --passWithNoTests", - "test:tech-log": "vitest run tests/features/tech-log --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/tech-log.xml", + "test:reference-feature": "node scripts/run-vitest.ts run tests/features/reference-feature --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/reference-feature.xml --passWithNoTests", + "test:tech-log": "node scripts/run-vitest.ts run tests/features/tech-log --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/tech-log.xml", "check:v8-coverage-counter-semantics": "node scripts/check-v8-coverage-counter-semantics.ts", - "test:coverage": "corepack pnpm check:v8-coverage-counter-semantics && vitest run tests/runtime-schema tests/unit tests/component tests/integration tests/features/reference-feature tests/features/tech-log --coverage --maxWorkers=4 --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/coverage.xml && node scripts/check-risk-coverage.ts", + "test:coverage": "corepack pnpm check:v8-coverage-counter-semantics && node scripts/run-vitest.ts run tests/runtime-schema tests/unit tests/contract tests/component tests/integration tests/features/reference-feature tests/features/tech-log --coverage --maxWorkers=4 --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/coverage.xml && node scripts/check-risk-coverage.ts", "check:coverage:fixture": "node scripts/check-risk-coverage.ts --summary tests/fixtures/coverage/below-threshold.json --artifact artifacts/quality/risk-coverage-fixture.json", - "test:all": "corepack pnpm test:runtime-schema && corepack pnpm test:unit && corepack pnpm test:component && corepack pnpm test:integration && corepack pnpm test:reference-feature && corepack pnpm check:tech-log-contract && corepack pnpm test:tech-log && corepack pnpm test:recipes", + "test:all": "corepack pnpm test:runtime-schema && corepack pnpm test:unit && corepack pnpm test:contract && corepack pnpm test:component && corepack pnpm test:integration && corepack pnpm test:reference-feature && corepack pnpm check:tech-log-contract && corepack pnpm test:tech-log && corepack pnpm test:recipes", "verify:lockfile": "corepack pnpm install --frozen-lockfile --ignore-scripts", "check:frozen-lockfile:fixture": "node scripts/check-frozen-lockfile-fixture.ts", "generate:artifact-schemas": "node scripts/generate-artifact-schemas.ts", @@ -130,7 +132,14 @@ "build:app-only": "vite build && node scripts/generate-build-manifest.ts", "generate:contract-set": "node scripts/generate-contract-set.ts", "check:types:web-worker": "tsc --project tsconfig.web-worker.json", - "check:types:service-worker": "tsc --project tsconfig.service-worker.json" + "check:types:service-worker": "tsc --project tsconfig.service-worker.json", + "check:types:fixture:http-operation-input": "tsc -p tests/fixtures/typecheck/tsconfig.http-operation-input.json", + "check:types:fixture:http-wire-mapper": "tsc -p tests/fixtures/typecheck/tsconfig.http-wire-mapper.json", + "check:types:fixture:http-operation-id": "tsc -p tests/fixtures/typecheck/tsconfig.http-operation-id.json", + "check:types:fixture:http-route-id": "tsc -p tests/fixtures/typecheck/tsconfig.http-route-id.json", + "check:types:fixture:feature-contribution-input": "tsc -p tests/fixtures/typecheck/tsconfig.feature-contribution-input.json", + "check:types:fixture:feature-capability-selection": "tsc -p tests/fixtures/typecheck/tsconfig.feature-capability-selection.json", + "check:types:fixture:direct-feature-composition": "tsc -p tests/fixtures/typecheck/tsconfig.direct-feature-composition.json" }, "dependencies": { "@fontsource/ibm-plex-mono": "5.3.0", diff --git a/scripts/check-adapter-inventory.ts b/scripts/check-adapter-inventory.ts index 07009a4..c520019 100644 --- a/scripts/check-adapter-inventory.ts +++ b/scripts/check-adapter-inventory.ts @@ -130,6 +130,12 @@ async function main(): Promise { // let an unrelated production import satisfy the gate while Image and // Resumable kept their own diverging copies of the same mechanics — which is // exactly how the four hand-written versions drifted apart in the first place. + // + // 이 목록은 재검토가 이름으로 지목한 네 파일만 덮는다. 같은 두 그룹의 + // `image-cdn-runtime.ts`와 `resumable-upload-runtime.ts`는 여기 없고 지금도 + // 자기 abort 사본을 들고 있다. 어댑터 전체로는 23개 파일이 그렇다. 그 전수 + // 이행은 abort 의미론을 바꾸는 별도 작업이라 이 목록으로 강제하지 않고, + // 아래 래칫이 개수가 늘어나는 것만 막는다. const REQUIRED_ABORT_CONSUMERS: readonly string[] = [ "src/adapters/browser-transfer/presigned/presigned-capability-http-provider.ts", "src/adapters/browser-transfer/presigned/presigned-transfer-executor.ts", @@ -164,6 +170,7 @@ async function main(): Promise { const PRIMITIVE_PATH = path.resolve( "src/adapters/platform/abortable-operation.ts", ); + const PRIMITIVE_SPECIFIER = "platform/abortable-operation.ts"; for (const consumer of REQUIRED_ABORT_CONSUMERS) { if (!importerSet.has(consumer)) continue; const source = readFileSync(consumer, "utf8"); @@ -181,6 +188,43 @@ async function main(): Promise { } } + // 손수 짠 abort 배선은 줄어들기만 해야 한다. + // + // 커널 `platform/abortable-operation.ts`가 있는데도 어댑터 23개 파일이 + // `addEventListener("abort")`로 같은 race/cleanup을 각자 짠다. 그 전수 이행은 + // 동작이 바뀌는 큰 작업이라 한 번에 하지 않는다. 대신 개수를 여기 고정해 + // 되돌아가지 못하게 한다. 이행으로 숫자가 내려가면 이 상수도 같이 내린다. + // `platform/`은 커널 자신이므로 세지 않는다. + // + // 24 → 23: `browser-transfer/resumable-upload/indexeddb-checkpoint-store.ts`가 + // IndexedDB 커널로 옮겨가면서 자기 abort 리스너를 지웠다. + // 23 → 22: `storage/indexeddb/indexeddb-maintenance.ts`가 같은 이유로 지웠다. + // 22 → 21: `storage/indexeddb/indexeddb-runtime.ts`가 같은 이유로 지웠다. + // 이것으로 IndexedDB 어댑터 4벌이 모두 커널을 쓴다. + const HAND_ROLLED_ABORT_CEILING = 21; + const handRolledScan = spawnSync( + "git", + ["grep", "-l", 'addEventListener("abort"', "--", "src/adapters"], + { encoding: "utf8" }, + ); + const handRolledFiles = ( + handRolledScan.status === 0 ? handRolledScan.stdout : "" + ) + .split("\n") + .filter(Boolean) + .filter((file) => !file.startsWith("src/adapters/platform/")) + .filter((file) => !readFileSync(file, "utf8").includes(PRIMITIVE_SPECIFIER)) + .sort(); + if (handRolledFiles.length > HAND_ROLLED_ABORT_CEILING) { + problems.push( + `abortable-operation: hand-rolled abort wiring grew to ` + + `${handRolledFiles.length} files (ceiling ${HAND_ROLLED_ABORT_CEILING}). ` + + `Use platform/abortable-operation.ts instead of a new listener pair. ` + + `Current offenders (the new one is whichever this change added): ` + + `${handRolledFiles.join(", ")}`, + ); + } + if (problems.length > 0) { for (const problem of problems) console.error(problem); process.exitCode = 1; @@ -195,7 +239,9 @@ async function main(): Promise { } shared extensions PASS; ` + `fixture node_modules linking PASS; ` + `shared abort primitive: ${importers.length} importers ` + - `(${importers.join(", ")}) PASS`, + `(${importers.join(", ")}) PASS; ` + + `hand-rolled abort wiring: ${handRolledFiles.length}/` + + `${HAND_ROLLED_ABORT_CEILING} files (ratchet) PASS`, ); } diff --git a/scripts/check-architecture.ts b/scripts/check-architecture.ts index 6b2957a..ee4c14f 100644 --- a/scripts/check-architecture.ts +++ b/scripts/check-architecture.ts @@ -824,12 +824,13 @@ async function runGraphFixtureChecks(): Promise { "tests/fixtures/architecture/dependency-graph", ); const allowedRoot = resolve(fixtureRoot, "allowed"); - const [allowedGraph, unresolvedGraph, layerGraph, cycleGraph] = + const [allowedGraph, unresolvedGraph, layerGraph, cycleGraph, barrelGraph] = await Promise.all([ analyzeSourceGraph(allowedRoot, "src"), analyzeSourceGraph(resolve(fixtureRoot, "unresolved"), "src"), analyzeSourceGraph(resolve(fixtureRoot, "layer"), "src"), analyzeSourceGraph(resolve(fixtureRoot, "cycle"), "src"), + analyzeSourceGraph(resolve(fixtureRoot, "barrel"), "src"), ]); const allowedFiles = new Set(await listFiles(allowedRoot)); const allowedSourceFile = resolve( @@ -850,6 +851,21 @@ async function runGraphFixtureChecks(): Promise { ), ); const assertions = [ + { + name: "deep adapter import from outside the group is rejected", + passed: blockingViolations(barrelGraph).some( + ({ rule, source, target }) => + rule === "adapter-groups-are-reached-through-their-barrel" && + source === "src/bootstrap/compose-deep.ts" && + target === "src/adapters/http/client.ts", + ), + }, + { + name: "barrel import from outside the group is accepted", + passed: !blockingViolations(barrelGraph).some( + ({ source }) => source === "src/bootstrap/compose-barrel.ts", + ), + }, { name: "explicit TS specifier resolves to a TS module", passed: allowedGraph.dependencies.some( diff --git a/scripts/check-compatibility.ts b/scripts/check-compatibility.ts index dc2a79a..32f3a9b 100644 --- a/scripts/check-compatibility.ts +++ b/scripts/check-compatibility.ts @@ -1,6 +1,6 @@ import { mkdir, readFile } from "node:fs/promises"; -import { classifyObjectSchemaChange } from "../src/application/policies/compatibility.ts"; +import { classifyObjectSchemaChange } from "../src/contracts/compatibility.ts"; import { compatibilityFixturesArtifactSchema } from "./contracts/release-artifacts.ts"; import { writeValidatedJsonArtifact } from "./lib/validated-json-artifact.ts"; diff --git a/scripts/check-system-test-prerequisites.ts b/scripts/check-system-test-prerequisites.ts new file mode 100644 index 0000000..c43e32f --- /dev/null +++ b/scripts/check-system-test-prerequisites.ts @@ -0,0 +1,55 @@ +import { constants } from "node:fs"; +import { access, readFile } from "node:fs/promises"; +import { spawnSync } from "node:child_process"; + +const failures: string[] = []; + +async function requireExecutable(path: string, label: string): Promise { + try { + await access(path, constants.X_OK); + } catch { + failures.push(`${label} is required at ${path}`); + } +} + +await Promise.all([ + requireExecutable("/usr/bin/bwrap", "bubblewrap"), + requireExecutable("/usr/bin/systemctl", "systemctl"), + requireExecutable("/usr/bin/tar", "tar"), +]); + +try { + const controllers = await readFile("/sys/fs/cgroup/cgroup.controllers", "utf8"); + if (controllers.trim().length === 0) { + failures.push("cgroup v2 controllers are unavailable"); + } +} catch { + failures.push("cgroup v2 is required at /sys/fs/cgroup/cgroup.controllers"); +} + +if (!failures.some((failure) => failure.includes("systemctl"))) { + const probe = spawnSync("/usr/bin/systemctl", ["show-environment"], { + encoding: "utf8", + timeout: 3_000, + }); + if (probe.error || probe.status !== 0) { + failures.push("a reachable systemd manager bus is required"); + } +} + +if (failures.length > 0) { + process.stderr.write( + [ + "System/CI-runner test prerequisites are unavailable:", + ...failures.map((failure) => ` - ${failure}`), + "", + "Run test:unit/test:contract/test:component/test:integration for the", + "developer loop. test:system is intentionally reserved for a compatible", + "Linux CI-runner host.", + "", + ].join("\n"), + ); + process.exit(1); +} + +process.stdout.write("System test prerequisites: PASS\n"); diff --git a/scripts/contracts/ci-gates.ts b/scripts/contracts/ci-gates.ts index f3fc962..81adcf9 100644 --- a/scripts/contracts/ci-gates.ts +++ b/scripts/contracts/ci-gates.ts @@ -482,7 +482,13 @@ const CANONICAL_GATE_SHAPE_SHA256 = // 주제 화면 셋(`/topics`, `/topics/:slug/:variant`, `/studio/topics/:id`): FE-GATE-009 가 각 // 라우트의 수동 접근성 증거를 얻어 다시 계산했다. 같은 방법이다 — 87a22f68… 을 이전 // gates.json 에서 먼저 재현해 계산이 맞는지 확인한 뒤 새 파일을 해싱했다. - "8a1a5479041cbce479b59d669c97921a5ba83dd7cac309131723acc221903528"; + // Template sync (ebea300). Both sides again carried a digest of their own + // gate set — 8a1a5479… here, 43dc4ed1… upstream — and neither describes the + // merged config/ci/gates.json. Recomputed from the merged file by the same + // method: 8a1a5479… was first reproduced from the pre-merge gates.json, so + // the computation that produced this value is the one the constant is + // pinned under. + "629e5898f6a38d5056fc6a4bee834c47f363669ce9925a2c0dabeddd64d11879"; function canonicalGateShapeSha256(gates: CiGateContract["gates"]): string { const normalized = gates.map( @@ -527,9 +533,11 @@ function canonicalAuthorityBaselineFailures(contract: CiGateContract): string[] // `check-dev-release-manifest`. No gate read `public/*.json` at all, so a // fixture that did not declare the compiled contract set broke `pnpm dev` // outright while every static gate stayed green. - if (contract.commands.length !== 85 || commandReferenceCount !== 97) { + // Template sync (ebea300). The template's own baseline was 91/103; this + // product's was 85/97. Recomputed from the merged config/ci/gates.json. + if (contract.commands.length !== 94 || commandReferenceCount !== 106) { failures.push( - `command authority baseline must contain exactly 85 definitions and 97 references; received ${contract.commands.length} definitions and ${commandReferenceCount} references`, + `command authority baseline must contain exactly 94 definitions and 106 references; received ${contract.commands.length} definitions and ${commandReferenceCount} references`, ); } // Template merge. 126 product artifacts plus the two the template added. @@ -548,8 +556,10 @@ function canonicalAuthorityBaselineFailures(contract: CiGateContract): string[] // 그리고 Studio 의 주제 편집 `/studio/topics/:id`. // 환경 구성(SETUP) 문서 종류가 `/setups/:slug` 를 더했다 — 설치된 라우트마다 수동 접근성 // 증거를 하나씩 갖는 규칙이 그대로 적용된다. - if (contract.artifacts.length !== 139) { - failures.push(`artifact authority baseline must contain exactly 139 artifacts; received ${contract.artifacts.length}`); + // Template sync (ebea300). The template's own baseline was 109 artifacts; + // this product's was 139. Recomputed from the merged config/ci/gates.json. + if (contract.artifacts.length !== 141) { + failures.push(`artifact authority baseline must contain exactly 141 artifacts; received ${contract.artifacts.length}`); } if (contract.stages.length !== 5) { failures.push(`stage authority baseline must contain exactly 5 stages; received ${contract.stages.length}`); diff --git a/scripts/drill-runbook.ts b/scripts/drill-runbook.ts index 4a967ef..1c1a5a6 100644 --- a/scripts/drill-runbook.ts +++ b/scripts/drill-runbook.ts @@ -3,7 +3,7 @@ import { pathToFileURL } from "node:url"; import { shouldRetry } from "../src/adapters/http/retry-policy.ts"; import { createTelemetryAdapter } from "../src/adapters/telemetry/best-effort-telemetry.ts"; -import { verifyCompatibilityTuple } from "../src/application/policies/compatibility.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"; diff --git a/scripts/generate-supply-chain.ts b/scripts/generate-supply-chain.ts index 18a33e5..24682bd 100644 --- a/scripts/generate-supply-chain.ts +++ b/scripts/generate-supply-chain.ts @@ -21,6 +21,7 @@ import { flattenPnpmDependencyTree, isValidSha512Integrity, parsePnpmLockfilePackages, + PROJECT_NAME, supplyChainDigest, verifySupplyChainCoherence, } from "./lib/supply-chain.ts"; @@ -270,7 +271,7 @@ const provenance = { ], }, runDetails: { - builder: { id: "local:tech-log-frontend" }, + builder: { id: `local:${PROJECT_NAME}` }, metadata: { invocationId: "LOCAL_UNSIGNED" }, }, materials: { diff --git a/scripts/lib/local-release-evidence.ts b/scripts/lib/local-release-evidence.ts index 3ab0018..50b1f47 100644 --- a/scripts/lib/local-release-evidence.ts +++ b/scripts/lib/local-release-evidence.ts @@ -66,6 +66,7 @@ import { secretScanRules } from "./secret-scan.ts"; import { isValidSha512Integrity, parsePnpmLockfilePackages, + PROJECT_NAME, supplyChainDigest, verifySupplyChainCoherence, } from "./supply-chain.ts"; @@ -304,8 +305,7 @@ export async function verifyLocalSupplyChainEvidence( }); } -export const LOCAL_EVIDENCE_VERIFIER_ID = - "tech-log-frontend/local-evidence-verifier"; +export const LOCAL_EVIDENCE_VERIFIER_ID = `${PROJECT_NAME}/local-evidence-verifier`; export const LOCAL_EVIDENCE_VERIFIER_VERSION = "1"; export { LOCAL_EVIDENCE_POLICY_INPUT_PATHS, diff --git a/scripts/lib/provider-evidence.ts b/scripts/lib/provider-evidence.ts index 7d63eb6..afb8d1a 100644 --- a/scripts/lib/provider-evidence.ts +++ b/scripts/lib/provider-evidence.ts @@ -4,13 +4,13 @@ import { z } from "zod"; import { canonicalizeSupplyChainValue, + PROJECT_NAME, supplyChainDigest, } from "./supply-chain.ts"; export const PROVIDER_FUTURE_SKEW_MS = 5 * 60 * 1_000; export const PROVIDER_MAX_LIFETIME_MS = 2 * 60 * 60 * 1_000; -export const PROMOTION_VERIFIER_ID = - "tech-log-frontend/promotion-verifier"; +export const PROMOTION_VERIFIER_ID = `${PROJECT_NAME}/promotion-verifier`; export const PROMOTION_VERIFIER_VERSION = "3"; const sha256 = z.string().regex(/^[a-f0-9]{64}$/u); diff --git a/scripts/lib/release-runtime-coherence.ts b/scripts/lib/release-runtime-coherence.ts index 35f103f..857cf53 100644 --- a/scripts/lib/release-runtime-coherence.ts +++ b/scripts/lib/release-runtime-coherence.ts @@ -1,4 +1,4 @@ -import { isVersionCompatible } from "../../src/application/policies/compatibility.ts"; +import { isVersionCompatible } from "../../src/contracts/compatibility.ts"; import { verifyContractSet } from "../../src/contracts/contract-set.ts"; import type { InstalledContractPackageIdentity } from "../../src/contracts/external-contract-runtime.ts"; import type { ReleaseArtifact } from "../../src/contracts/release-artifacts.ts"; diff --git a/scripts/lib/supply-chain.ts b/scripts/lib/supply-chain.ts index 2150ca0..da88f30 100644 --- a/scripts/lib/supply-chain.ts +++ b/scripts/lib/supply-chain.ts @@ -1,6 +1,27 @@ import { createHash } from "node:crypto"; +import { readFileSync } from "node:fs"; import { readFile } from "node:fs/promises"; +function readProjectName(): string { + const manifest: unknown = JSON.parse( + readFileSync(new URL("../../package.json", import.meta.url), "utf8"), + ); + const name = + typeof manifest === "object" && manifest !== null + ? (manifest as { name?: unknown }).name + : undefined; + if (typeof name !== "string" || name.length === 0) { + throw new TypeError("package.json must declare a non-empty \"name\""); + } + return name; +} + +/** + * Identity every release artifact is attributed to. A project derived from this + * template renames itself by editing `name` in package.json and nothing else. + */ +export const PROJECT_NAME = readProjectName(); + export type DependencyScope = "production" | "development"; export type LockfilePackage = Readonly<{ name: string; diff --git a/scripts/run-vitest.ts b/scripts/run-vitest.ts new file mode 100644 index 0000000..09cd3c1 --- /dev/null +++ b/scripts/run-vitest.ts @@ -0,0 +1,67 @@ +import { spawnSync } from "node:child_process"; +import { existsSync } from "node:fs"; +import { fileURLToPath } from "node:url"; + +function assertSupportedNode(): void { + const [majorText = "0", minorText = "0"] = process.versions.node.split("."); + const major = Number(majorText); + const minor = Number(minorText); + + if (major !== 24 || minor < 11) { + process.stderr.write( + [ + `Unsupported Node.js runtime for tests: ${process.versions.node}`, + "Required by package.json: >=24.11.0 <25.0.0", + "Use the repository-supported Node.js runtime before running a test suite.", + "", + ].join("\n"), + ); + process.exit(1); + } +} + +assertSupportedNode(); + +const vitestEntry = fileURLToPath( + new URL("../node_modules/vitest/vitest.mjs", import.meta.url), +); +if (!existsSync(vitestEntry)) { + process.stderr.write( + "Vitest is not installed. Run the repository package installation first.\n", + ); + process.exit(1); +} + +const testEnvironment: NodeJS.ProcessEnv = { + ...process.env, + NODE_ENV: "test", +}; +for (const key of [ + "npm_config_userconfig", + "npm_config_prefix", + "npm_config_globalconfig", + "NPM_CONFIG_USERCONFIG", + "NPM_CONFIG_PREFIX", + "NPM_CONFIG_GLOBALCONFIG", +]) { + delete testEnvironment[key]; +} + +const result = spawnSync( + process.execPath, + [vitestEntry, ...process.argv.slice(2)], + { + stdio: "inherit", + env: testEnvironment, + }, +); + +if (result.error) { + throw result.error; +} +if (result.signal) { + process.stderr.write(`Vitest terminated by signal ${result.signal}.\n`); + process.exit(1); +} + +process.exit(result.status ?? 1); diff --git a/scripts/test-sample-removal.ts b/scripts/test-sample-removal.ts index 6f653e4..70e52e7 100644 --- a/scripts/test-sample-removal.ts +++ b/scripts/test-sample-removal.ts @@ -42,24 +42,53 @@ const featureOwnedPaths = [ featureSource, featureTests, "tests/integration/http-scenario-catalog.test.ts", - "tests/integration/http-execution-v3-observability.test.ts", "tests/features/tech-log/runtime-composition.test.ts", + // Template sync (ebea300). The kill-switch test attributes a real route to a + // real installed feature id; with the sample feature gone there is no + // installed feature left to attribute to, so it goes with it. + "tests/component/product-feature-switch.test.tsx", + // Same sync. This TechLog test imports the sample feature's contract + // contribution on purpose — it proves a 403 on *another* feature's operation + // does not discard TechLog's CSRF token, which needs a second feature to + // exist. With the sample feature gone the premise is gone, so the test goes + // with it rather than being rewritten around a feature that is not there. + "tests/features/tech-log/studio-csrf-composition.test.ts", "tests/e2e/reference-form.spec.ts", "tests/e2e/reference-route.spec.ts", "tests/mocks", "tests/fixtures/typecheck/invalid-feature-input.ts", "tests/fixtures/typecheck/invalid-reference-operation.ts", + "tests/fixtures/typecheck/invalid-http-operation-input.ts", + "tests/fixtures/typecheck/invalid-http-wire-mapper.ts", + "tests/fixtures/typecheck/invalid-http-operation-id.ts", + "tests/fixtures/typecheck/invalid-http-route-id.ts", + "tests/fixtures/typecheck/invalid-feature-contribution-input.ts", + "tests/fixtures/typecheck/invalid-feature-capability-selection.ts", + "tests/fixtures/typecheck/tsconfig.feature-input.json", + "tests/fixtures/typecheck/tsconfig.reference-operation.json", + "tests/fixtures/typecheck/tsconfig.http-operation-input.json", + "tests/fixtures/typecheck/tsconfig.http-wire-mapper.json", + "tests/fixtures/typecheck/tsconfig.http-operation-id.json", + "tests/fixtures/typecheck/tsconfig.http-route-id.json", + "tests/fixtures/typecheck/tsconfig.feature-contribution-input.json", + "tests/fixtures/typecheck/tsconfig.feature-capability-selection.json", ]; +const emptyProductManifest = `export const COMPILED_PRODUCT_FEATURE_IDS: readonly string[] = Object.freeze([]); +export const INSTALLED_PRODUCT_FEATURES: readonly never[] = Object.freeze([]); +export const INSTALLED_PRODUCT_FEATURE_IDS: readonly string[] = Object.freeze([]); +`; + const emptyContracts = `import type { RouteDefinition } from "../contracts/routes.ts"; import { PLATFORM_SCHEMA_REGISTRY } from "../contracts/schema-registry.ts"; +import { INSTALLED_PRODUCT_FEATURES } from "./installed-product-manifest.ts"; import { TECH_LOG_ROUTE_REGISTRY, TECH_LOG_ROUTE_RUNTIME_CONTRACT, TECH_LOG_ROUTE_SCHEMA_REGISTRY, } from "./tech-log/contracts/tech-log-route-contract.ts"; -export const INSTALLED_FEATURE_CONTRACTS: readonly unknown[] = Object.freeze([]); +export const INSTALLED_FEATURE_CONTRACTS = INSTALLED_PRODUCT_FEATURES; export const ROUTE_REGISTRY = TECH_LOG_ROUTE_REGISTRY; export const ROUTE_RUNTIME_CONTRACT = TECH_LOG_ROUTE_RUNTIME_CONTRACT; export const API_OPERATIONS = Object.freeze({}); @@ -73,6 +102,7 @@ export const SCHEMA_REGISTRY = Object.freeze({ ...PLATFORM_SCHEMA_REGISTRY, ...TECH_LOG_ROUTE_SCHEMA_REGISTRY, }); +export const ROUTE_FEATURE_OWNER: Readonly> = Object.freeze({}); export const NAVIGATION_ROUTES = Object.freeze( Object.values(ROUTE_REGISTRY) .filter((definition) => definition.navigationOrder !== null) @@ -103,12 +133,37 @@ export const ROUTE_CODECS = Object.freeze({ export const ROUTE_RUNTIME = TECH_LOG_ROUTE_RUNTIME; `; -const emptyAdapters = `import { createTechLogFeatureInstalledInput } from "./tech-log/adapters/create-tech-log-feature-input.ts"; +const emptyAdapters = `import type { InstalledHttpOperationExecutor } from "../adapters/http/index.ts"; +import type { ApplicationFeatureInputs } from "../application/ports/in/application-api.ts"; +import { + composeFeatureAdapterInputs, + type InstalledFeatureInputs, +} from "./feature-adapter-contribution.ts"; +import { INSTALLED_PRODUCT_FEATURE_IDS } from "./installed-product-manifest.ts"; +import { + createTechLogFeatureInstalledInput, + type TechLogInstallContext, +} from "./tech-log/adapters/create-tech-log-feature-input.ts"; +import { TECH_LOG_FEATURE_ID } from "./tech-log/application/tech-log-feature-input.ts"; -export function createInstalledFeatureInputs(_context: unknown) { - void _context; - const techLog = createTechLogFeatureInstalledInput(); - return Object.freeze({ [techLog.featureId]: techLog.input }); +const COMPILED_FEATURE_ADAPTER_CONTRIBUTIONS = Object.freeze([] as const); + +type ProductFeatureInputs = InstalledFeatureInputs & + Readonly>; + +export function createInstalledFeatureInputs( + context: TechLogInstallContext & + Readonly<{ http: InstalledHttpOperationExecutor }>, +): ProductFeatureInputs { + const techLog = createTechLogFeatureInstalledInput(context); + return Object.freeze({ + ...composeFeatureAdapterInputs( + COMPILED_FEATURE_ADAPTER_CONTRIBUTIONS, + INSTALLED_PRODUCT_FEATURE_IDS, + context, + ), + [techLog.featureId]: techLog.input, + }) as ProductFeatureInputs; } `; @@ -117,9 +172,17 @@ const emptyContractContributions = `import { type InstalledContractContribution, type InstalledContractPackageIdentity, } from "../contracts/external-contract-runtime.ts"; +import { INSTALLED_PRODUCT_FEATURE_IDS } from "./installed-product-manifest.ts"; + +const COMPILED_CONTRACT_CONTRIBUTIONS: readonly InstalledContractContribution[] = + Object.freeze([]); export const INSTALLED_CONTRACT_CONTRIBUTIONS: readonly InstalledContractContribution[] = - Object.freeze([]); + Object.freeze( + COMPILED_CONTRACT_CONTRIBUTIONS.filter((contribution) => + INSTALLED_PRODUCT_FEATURE_IDS.includes(contribution.featureId), + ), + ); export const COMPOSED_CONTRACT_CONTRIBUTIONS = composeContractContributions( INSTALLED_CONTRACT_CONTRIBUTIONS, @@ -168,7 +231,9 @@ try { await prepareRemovalFixture(fixtureRoot); for (const excludedFixtureTest of [ "tests/integration/security-followup-archive.test.ts", - "tests/unit/ci-artifact-contract.test.ts", + // Template sync (ebea300). `ci-artifact-contract` moved to + // `tests/system/ci-runner/`, which `test:all` does not run, so it no longer + // needs excluding — upstream dropped it from this list for the same reason. "tests/unit/ci-workflow-generation.test.ts", "tests/unit/__snapshots__/ci-workflow-generation.test.ts.snap", "tests/unit/removal-fixture.test.ts", @@ -202,6 +267,10 @@ try { force: true, }); } + await writeFile( + path.join(fixtureRoot, "src/features/installed-product-manifest.ts"), + emptyProductManifest, + ); await writeFile( path.join(fixtureRoot, "src/features/installed-feature-contracts.ts"), emptyContracts, @@ -223,6 +292,34 @@ try { emptyContractContributions, ); + // Runtime profiles are product configuration. Once the feature is physically + // removed, its override key must disappear too or the built config still + // advertises a source capability that no longer exists. + for (const profile of [ + "local", + "development", + "staging", + "production", + ] as const) { + const profilePath = path.join( + fixtureRoot, + "config/runtime", + `${profile}.json`, + ); + const runtimeConfig = JSON.parse( + await readFile(profilePath, "utf8"), + ) as { + FEATURE_OVERRIDES?: Record; + }; + if (runtimeConfig.FEATURE_OVERRIDES) { + delete runtimeConfig.FEATURE_OVERRIDES["reference-feature"]; + } + await writeFile( + profilePath, + `${JSON.stringify(runtimeConfig, null, 2)}\n`, + ); + } + const retainedCriticalModules = coveragePolicy.criticalModules.filter( (modulePolicy) => !modulePolicy.path?.startsWith(`${featureSource}/`), ); @@ -317,6 +414,12 @@ try { const removedCiScripts = new Set([ "check:types:fixture:feature-input", "check:types:fixture:reference-operation", + "check:types:fixture:http-operation-input", + "check:types:fixture:http-wire-mapper", + "check:types:fixture:http-operation-id", + "check:types:fixture:http-route-id", + "check:types:fixture:feature-contribution-input", + "check:types:fixture:feature-capability-selection", "test:http-scenario-evidence", "test:reference-feature", ]); @@ -391,13 +494,17 @@ try { ["build", runPnpm("build")], ]; const builtResidue: string[] = []; - for (const file of await filesBelow(path.join(fixtureRoot, "dist"))) { - if (!/\.(?:js|css|html|json)$/.test(file)) continue; - const content = await readFile(file, "utf8"); - if ( - /REFERENCE_RESOURCE|reference-feature|reference-resource/i.test(content) - ) { - builtResidue.push(path.relative(fixtureRoot, file)); + const buildSucceeded = + checks.find(([name]) => name === "build")?.[1] === true; + if (buildSucceeded) { + for (const file of await filesBelow(path.join(fixtureRoot, "dist"))) { + if (!/\.(?:js|css|html|json)$/.test(file)) continue; + const content = await readFile(file, "utf8"); + if ( + /REFERENCE_RESOURCE|reference-feature|reference-resource/i.test(content) + ) { + builtResidue.push(path.relative(fixtureRoot, file)); + } } } const routeCatalog = await import( diff --git a/scripts/verify-release.ts b/scripts/verify-release.ts index ae4eda2..dbc6c5e 100644 --- a/scripts/verify-release.ts +++ b/scripts/verify-release.ts @@ -5,7 +5,7 @@ import { pathToFileURL } from "node:url"; import { verifyCompatibilityTuple, type CompatibilityTuple, -} from "../src/application/policies/compatibility.ts"; +} from "../src/contracts/compatibility.ts"; import type { InstalledContractPackageIdentity } from "../src/contracts/external-contract-runtime.ts"; import { parseBuildManifestArtifact, diff --git a/src/adapters/auth/index.ts b/src/adapters/auth/index.ts new file mode 100644 index 0000000..cb8b996 --- /dev/null +++ b/src/adapters/auth/index.ts @@ -0,0 +1,9 @@ +export { + createAnonymousSessionAdapter, + createDemoSessionAdapter, + createExternalAuthSessionAdapter, + createUnavailableSessionAdapter, + DEMO_AUTHORIZATION_MARKER, + type DemoSessionAdapter, + type ExternalSessionOwner, +} from "./external-session-adapter.ts"; diff --git a/src/adapters/browser-files/browser-file-picker.ts b/src/adapters/browser-files/browser-file-picker.ts index 00ef001..c99270c 100644 --- a/src/adapters/browser-files/browser-file-picker.ts +++ b/src/adapters/browser-files/browser-file-picker.ts @@ -108,14 +108,12 @@ export class NativeInputFilePicker implements DisposableFilePicker { const addInputEvent = options.input.addEventListener; const removeInputEvent = options.input.removeEventListener; const getInputAttribute = options.input.getAttribute; - const showPicker = options.input.showPicker; const click = options.input.click; if ( typeof addInputEvent !== "function" || typeof removeInputEvent !== "function" || typeof getInputAttribute !== "function" || - (typeof showPicker !== "function" && - typeof click !== "function") + typeof click !== "function" ) { throw new TypeError("Native file input API is invalid."); } @@ -123,10 +121,11 @@ export class NativeInputFilePicker implements DisposableFilePicker { add: addInputEvent.bind(options.input), remove: removeInputEvent.bind(options.input), getAttribute: getInputAttribute.bind(options.input), - activate: - typeof showPicker === "function" - ? showPicker.bind(options.input) - : click.bind(options.input), + // The baseline path intentionally uses click(). + // showPicker() exists in multiple engines but is not a portable + // automation/event-interception contract. Enhanced native picking is a + // separate capability owned by EnhancedFilePicker. + activate: click.bind(options.input), }); const windowHost = options.window ?? globalThis.window; if (windowHost) { diff --git a/src/adapters/browser-rpc/browser-rpc-runtime.ts b/src/adapters/browser-rpc/browser-rpc-runtime.ts index 21b6057..1341c1d 100644 --- a/src/adapters/browser-rpc/browser-rpc-runtime.ts +++ b/src/adapters/browser-rpc/browser-rpc-runtime.ts @@ -8,7 +8,7 @@ import type { BrowserRpcUnaryPort, } from "../../application/ports/browser-rpc/index.ts"; import type { ClockPort } from "../../application/ports/clock-port.ts"; -import type { Result } from "../../application/result.ts"; +import type { Result } from "../../contracts/result.ts"; import { installBrowserRpcContractBindings, type InstalledBrowserRpcContractBindings, diff --git a/src/adapters/browser-transfer/resumable-upload/indexeddb-checkpoint-store.ts b/src/adapters/browser-transfer/resumable-upload/indexeddb-checkpoint-store.ts index ee95180..1861697 100644 --- a/src/adapters/browser-transfer/resumable-upload/indexeddb-checkpoint-store.ts +++ b/src/adapters/browser-transfer/resumable-upload/indexeddb-checkpoint-store.ts @@ -4,12 +4,26 @@ import type { ResumableUploadCheckpointStore, PartitionDeleteOutcome, } from "../../../application/ports/browser-transfer/resumable-upload.ts"; -import type { BrowserDataResult } from "../../../application/ports/browser-file-storage/shared.ts"; +import type { + BrowserDataFailure, + BrowserDataFailureCode, + BrowserDataRecovery, + BrowserDataResult, +} from "../../../application/ports/browser-file-storage/shared.ts"; +import { isBrowserDataFailureCode } from "../../../application/ports/browser-file-storage/shared.ts"; import { browserDataFailure, browserDataSuccess, mapBrowserDataException, } from "../../browser-file-storage/result.ts"; +import { snapshotAbortTimers } from "../../platform/abortable-operation.ts"; +import { + createIndexedDbConnection, + deleteIndexedDbDatabase, + openIndexedDbDatabase, + type IndexedDbTranslate, +} from "../../platform/indexeddb-connection.ts"; +import { runIndexedDbTransaction } from "../../platform/indexeddb-transaction.ts"; import { isResumableUploadCheckpoint, SAFE_OPAQUE_ID, @@ -20,6 +34,7 @@ const DATABASE_VERSION = 1; const CHECKPOINT_STORE = "checkpoints"; const GOVERNANCE_STORE = "governance"; const GOVERNANCE_KEY = "scope-binding"; +const OPERATION = "UPLOAD_RECONCILE"; const DEFAULT_BLOCKED_TIMEOUT_MS = 5_000; /** @@ -65,10 +80,94 @@ type ScopeBinding = Readonly<{ partitionToken: string; }>; -type OpenFactory = ( - name: string, - version?: number, -) => IDBOpenDBRequest; +/** + * `browserDataFailure` and `mapBrowserDataException` build a `Result`, while the + * kernel's `translate` contract wants the failure on its own. Both only ever + * build the failure arm, so the branch below is a narrowing, not a claim. + */ +function failureOf(result: BrowserDataResult): BrowserDataFailure { + if (result.ok) { + throw new TypeError("A browser data failure was expected."); + } + return result.error; +} + +function checkpointFailure( + code: BrowserDataFailureCode, + options: Readonly<{ + retryable?: boolean; + recovery?: BrowserDataRecovery; + }> = {}, +): BrowserDataFailure { + return failureOf(browserDataFailure(code, OPERATION, options)); +} + +function mappedFailure(error: unknown): BrowserDataFailure { + return failureOf(mapBrowserDataException(error, OPERATION)); +} + +/** + * The kernel keeps an admission's `detail` opaque, so a rejected scope binding + * carries its own failure through it and the guard hands that failure straight + * back. Any other shape would mean a second taxonomy grew beside this one. + */ +function admissionFailure(detail: unknown): BrowserDataFailure | null { + if (!detail || typeof detail !== "object") return null; + const record = detail as Record; + return isBrowserDataFailureCode(record.code) && record.operation === OPERATION + ? (detail as BrowserDataFailure) + : null; +} + +/** + * BT-UP-03. The checkpoint store keeps its own failure table rather than the + * `mapIndexedDbException` the other three IndexedDB adapters share: the same + * native error is a different answer here (a `ConstraintError` recovers by + * REOPEN, a quota failure is retryable), and unifying the four tables is a + * separate change from moving the mechanics onto the kernel. + */ +const translate: IndexedDbTranslate = (cause) => { + switch (cause.kind) { + case "NATIVE_EXCEPTION": + return mappedFailure(cause.error); + case "NO_VALUE_PRODUCED": + // Three adapters call this UNAVAILABLE. Here a checkpoint transaction + // that committed without producing a value read a row it could not turn + // into a checkpoint, so reconciling is the only way forward; retrying + // would read the same row again. + return checkpointFailure("CORRUPT_DATA", { recovery: "RECONCILE" }); + case "BLOCKED": + case "BLOCKED_DEADLINE": + return checkpointFailure("BLOCKED", { + retryable: true, + recovery: "RESUME", + }); + case "CALLER_ABORT": + return checkpointFailure("ABORTED"); + case "CLOSED": + // A closed handle is not the caller aborting: the upload can resume once + // a new store is built over the partition. + return checkpointFailure("UNAVAILABLE", { recovery: "RESUME" }); + case "UPGRADE_REJECTED": + // The schema body's own throw is what the caller sees. A rejection with + // no detail can only come from a null `newVersion`, which an open request + // never reports. + return cause.detail === undefined + ? checkpointFailure("MIGRATION_FAILED", { recovery: "READ_ONLY" }) + : mappedFailure(cause.detail); + case "ADMISSION_REJECTED": + return ( + admissionFailure(cause.detail) ?? + checkpointFailure("POLICY_REJECTED", { recovery: "READ_ONLY" }) + ); + case "UNSUPPORTED": + return checkpointFailure("UNSUPPORTED", { recovery: "READ_ONLY" }); + default: { + const exhaustive: never = cause; + return exhaustive; + } + } +}; export function uploadCheckpointDatabaseName( scope: IndexedDbUploadCheckpointScope, @@ -104,13 +203,19 @@ export function createIndexedDbResumableUploadCheckpointRuntime( ) { throw new TypeError("Upload checkpoint blocked timeout is invalid."); } - const openFactory: OpenFactory | undefined = factory - ? factory.open.bind(factory) - : undefined; - const deleteFactory = - factory && typeof factory.deleteDatabase === "function" - ? factory.deleteDatabase.bind(factory) - : undefined; + // X-AUDIT-02. The timer callables are captured once, bound to their receiver, + // so replacing a global after composition cannot change how a blocked open or + // a blocked deletion already in flight is bounded. The kernel throws at + // construction if a positive deadline arrives without them. + const timers = snapshotAbortTimers({ + setTimeout: (callback: () => void, milliseconds: number) => + globalThis.setTimeout(callback, milliseconds), + clearTimeout: (handle: ReturnType) => { + globalThis.clearTimeout(handle); + }, + }); + const canDelete = + factory !== undefined && typeof factory.deleteDatabase === "function"; const databaseName = uploadCheckpointDatabaseName(scope); const pendingDeletions = pendingDeletionsFor(factory); if (pendingDeletions.has(databaseName)) { @@ -125,118 +230,60 @@ export function createIndexedDbResumableUploadCheckpointRuntime( schemaVersion: 1, ...scope, }); - let database: IDBDatabase | null = null; - let opening: Promise> | null = null; - let closed = false; - async function open( - signal?: AbortSignal, - ): Promise> { - if (closed || !openFactory) { - return browserDataFailure("UNAVAILABLE", "UPLOAD_RECONCILE", { - recovery: "RESUME", - }); - } - if (signal?.aborted) { - return browserDataFailure("ABORTED", "UPLOAD_RECONCILE"); - } - if (database) return browserDataSuccess(database); - if (!opening) { - opening = openAndBind().finally(() => { - opening = null; - }); - } - const result = await opening; - if (signal?.aborted) { - return browserDataFailure("ABORTED", "UPLOAD_RECONCILE"); - } - return result; - } - - async function openAndBind(): Promise> { - let request: IDBOpenDBRequest; - try { - request = openFactory!(databaseName, DATABASE_VERSION); - } catch (error) { - return mapBrowserDataException(error, "UPLOAD_RECONCILE"); - } - const opened = await new Promise>( - (resolve) => { - let settled = false; - let blockedTimer: ReturnType | undefined; - const finish = (result: BrowserDataResult) => { - if (settled) { - if (result.ok) result.value.close(); - return; - } - settled = true; - if (blockedTimer) clearTimeout(blockedTimer); - resolve(result); - }; - request.onupgradeneeded = () => { - try { - const db = request.result; - if (!db.objectStoreNames.contains(CHECKPOINT_STORE)) { - db.createObjectStore(CHECKPOINT_STORE, { - keyPath: "uploadKey", - }); - } - if (!db.objectStoreNames.contains(GOVERNANCE_STORE)) { - db.createObjectStore(GOVERNANCE_STORE, { - keyPath: "key", - }); - } - } catch (error) { - try { - request.transaction?.abort(); - } catch { - // The open request will surface the original closed failure. - } - finish(mapBrowserDataException(error, "UPLOAD_RECONCILE")); - } - }; - request.onblocked = () => { - blockedTimer = setTimeout(() => { - finish( - browserDataFailure("BLOCKED", "UPLOAD_RECONCILE", { - retryable: true, - recovery: "RESUME", - }), - ); - }, blockedTimeoutMs); - }; - request.onerror = () => - finish( - mapBrowserDataException( - request.error, - "UPLOAD_RECONCILE", - ), - ); - request.onsuccess = () => finish(browserDataSuccess(request.result)); - }, - ); - if (!opened.ok) return opened; - if (closed) { - opened.value.close(); - return browserDataFailure("UNAVAILABLE", "UPLOAD_RECONCILE", { - recovery: "RESUME", - }); - } - const bound = await bindScope(opened.value, expectedBinding); - if (!bound.ok) { - opened.value.close(); - return bound; - } - opened.value.onversionchange = () => { - opened.value.close(); - if (database === opened.value) database = null; - }; - opened.value.onclose = () => { - if (database === opened.value) database = null; - }; - database = opened.value; - return browserDataSuccess(opened.value); - } + /** + * The handle owns the cached connection, the single-flight open and the + * `versionchange`/`close` invalidation this file used to wire by hand. No + * `onVersionChange` callback is passed because closing the connection and + * dropping the cached handle — which the kernel already does — was this + * store's entire listener body; registering one inside `admit` instead would + * be overwritten when the handle adopts the connection. + */ + const connection = createIndexedDbConnection({ + translate, + open: (signal) => + factory === undefined + ? Promise.resolve( + browserDataFailure("UNAVAILABLE", OPERATION, { + recovery: "RESUME", + }), + ) + : openIndexedDbDatabase({ + factory, + databaseName, + version: DATABASE_VERSION, + translate, + signal, + blockedTimeoutMs, + timers, + upgrade: ({ database }) => { + try { + if (!database.objectStoreNames.contains(CHECKPOINT_STORE)) { + database.createObjectStore(CHECKPOINT_STORE, { + keyPath: "uploadKey", + }); + } + if (!database.objectStoreNames.contains(GOVERNANCE_STORE)) { + database.createObjectStore(GOVERNANCE_STORE, { + keyPath: "key", + }); + } + } catch (error) { + return { kind: "REJECTED", detail: error }; + } + return { kind: "APPLIED" }; + }, + // The binding runs before the caller ever sees the connection, so a + // partition bound to another scope can never serve a read. A + // rejected admission closes the connection inside the kernel. + admit: async (database) => { + const bound = await bindScope(database, expectedBinding); + return bound.ok + ? { kind: "ADMIT" } + : { kind: "REJECT", detail: bound.error }; + }, + }), + }); const storeValue: ResumableUploadCheckpointStore = { async read( @@ -246,12 +293,9 @@ export function createIndexedDbResumableUploadCheckpointRuntime( BrowserDataResult > { if (!SAFE_UPLOAD_KEY.test(uploadKey)) { - return browserDataFailure( - "INVALID_INPUT", - "UPLOAD_RECONCILE", - ); + return browserDataFailure("INVALID_INPUT", OPERATION); } - const opened = await open(signal); + const opened = await connection.acquire(signal); if (!opened.ok) return opened; return await runCheckpointTransaction< ResumableUploadCheckpoint | null @@ -261,7 +305,7 @@ export function createIndexedDbResumableUploadCheckpointRuntime( signal, (nativeStore, context) => { const request = nativeStore.get(uploadKey); - request.onerror = () => context.nativeFailure(request.error); + request.onerror = () => context.fail(mappedFailure(request.error)); request.onsuccess = () => { if (request.result === undefined) { context.succeed(null); @@ -269,11 +313,7 @@ export function createIndexedDbResumableUploadCheckpointRuntime( } if (!isResumableUploadCheckpoint(request.result)) { context.fail( - browserDataFailure( - "CORRUPT_DATA", - "UPLOAD_RECONCILE", - { recovery: "RECONCILE" }, - ), + checkpointFailure("CORRUPT_DATA", { recovery: "RECONCILE" }), ); return; } @@ -294,10 +334,7 @@ export function createIndexedDbResumableUploadCheckpointRuntime( try { checkpoint = snapshotCheckpoint(inputValue.checkpoint); } catch { - return browserDataFailure( - "INVALID_INPUT", - "UPLOAD_RECONCILE", - ); + return browserDataFailure("INVALID_INPUT", OPERATION); } const expectedRevision = inputValue.expectedRevision; if ( @@ -306,12 +343,9 @@ export function createIndexedDbResumableUploadCheckpointRuntime( expectedRevision < 1)) || checkpoint.revision !== (expectedRevision ?? 0) + 1 ) { - return browserDataFailure( - "INVALID_INPUT", - "UPLOAD_RECONCILE", - ); + return browserDataFailure("INVALID_INPUT", OPERATION); } - const opened = await open(inputValue.signal); + const opened = await connection.acquire(inputValue.signal); if (!opened.ok) return opened; return await runCheckpointTransaction( opened.value, @@ -319,7 +353,7 @@ export function createIndexedDbResumableUploadCheckpointRuntime( inputValue.signal, (nativeStore, context) => { const request = nativeStore.get(checkpoint.uploadKey); - request.onerror = () => context.nativeFailure(request.error); + request.onerror = () => context.fail(mappedFailure(request.error)); request.onsuccess = () => { const current = request.result; if ( @@ -329,16 +363,12 @@ export function createIndexedDbResumableUploadCheckpointRuntime( current.revision !== expectedRevision)) ) { context.fail( - browserDataFailure( - "CONFLICT", - "UPLOAD_RECONCILE", - { recovery: "RECONCILE" }, - ), + checkpointFailure("CONFLICT", { recovery: "RECONCILE" }), ); return; } const put = nativeStore.put(checkpoint); - put.onerror = () => context.nativeFailure(put.error); + put.onerror = () => context.fail(mappedFailure(put.error)); put.onsuccess = () => context.succeed(checkpoint); }; }, @@ -355,12 +385,9 @@ export function createIndexedDbResumableUploadCheckpointRuntime( !Number.isSafeInteger(inputValue.expectedRevision) || inputValue.expectedRevision < 1 ) { - return browserDataFailure( - "INVALID_INPUT", - "UPLOAD_RECONCILE", - ); + return browserDataFailure("INVALID_INPUT", OPERATION); } - const opened = await open(inputValue.signal); + const opened = await connection.acquire(inputValue.signal); if (!opened.ok) return opened; return await runCheckpointTransaction( opened.value, @@ -368,24 +395,20 @@ export function createIndexedDbResumableUploadCheckpointRuntime( inputValue.signal, (nativeStore, context) => { const request = nativeStore.get(inputValue.uploadKey); - request.onerror = () => context.nativeFailure(request.error); + request.onerror = () => context.fail(mappedFailure(request.error)); request.onsuccess = () => { if ( !isResumableUploadCheckpoint(request.result) || request.result.revision !== inputValue.expectedRevision ) { context.fail( - browserDataFailure( - "CONFLICT", - "UPLOAD_RECONCILE", - { recovery: "RECONCILE" }, - ), + checkpointFailure("CONFLICT", { recovery: "RECONCILE" }), ); return; } const deletion = nativeStore.delete(inputValue.uploadKey); deletion.onerror = () => - context.nativeFailure(deletion.error); + context.fail(mappedFailure(deletion.error)); deletion.onsuccess = () => context.succeed(undefined); }; }, @@ -393,9 +416,7 @@ export function createIndexedDbResumableUploadCheckpointRuntime( }, close() { - closed = true; - database?.close(); - database = null; + connection.close(); }, }; const store = Object.freeze(storeValue); @@ -405,82 +426,50 @@ export function createIndexedDbResumableUploadCheckpointRuntime( ): Promise< BrowserDataResult > { + // IDB deleteDatabase cannot be cancelled after dispatch. AbortSignal is + // intentionally observed only before dispatch so the adapter never + // reports ABORTED while deletion may still commit — which is also why the + // kernel's delete takes no signal. if (signal?.aborted) { - return browserDataFailure("ABORTED", "UPLOAD_RECONCILE"); + return browserDataFailure("ABORTED", OPERATION); } - closed = true; - database?.close(); - database = null; - if (!deleteFactory) { - return browserDataFailure( - "UNSUPPORTED", - "UPLOAD_RECONCILE", - { recovery: "READ_ONLY" }, + connection.close(); + if (factory === undefined || !canDelete) { + return browserDataFailure("UNSUPPORTED", OPERATION, { + recovery: "READ_ONLY", + }); + } + // BT-UP-03. Once dispatched the deletion may still commit after this call + // returns, so the pending registration is installed before the promise + // settles and is only released by the real native completion — which is + // exactly what `onSettled` reports and a blocked deadline never does. + pendingDeletions.add(databaseName); + const deleted = await deleteIndexedDbDatabase({ + factory, + databaseName, + translate, + blockedTimeoutMs, + timers, + onSettled: () => { + pendingDeletions.delete(databaseName); + }, + }); + if (!deleted.ok) return deleted; + if (deleted.value.kind === "DELETED") { + return browserDataSuccess( + Object.freeze({ + state: "DELETED" as const, + effect: "APPLIED" as const, + }), ); } - let request: IDBOpenDBRequest; - try { - request = deleteFactory(databaseName); - } catch (error) { - return mapBrowserDataException(error, "UPLOAD_RECONCILE"); - } - // BT-UP-03. Once dispatched the deletion may still commit after this - // call returns, so the pending registration is installed before the - // promise settles and is only released by the real native completion. - pendingDeletions.add(databaseName); - return await new Promise>( - (resolve) => { - let settled = false; - let blockedTimer: ReturnType | undefined; - const finish = ( - result: BrowserDataResult, - ) => { - if (settled) return; - settled = true; - if (blockedTimer) clearTimeout(blockedTimer); - resolve(result); - }; - const releasePending = () => { - pendingDeletions.delete(databaseName); - }; - // IDB deleteDatabase cannot be cancelled after dispatch. AbortSignal - // is intentionally observed only before dispatch so the adapter never - // reports ABORTED while deletion may still commit. - request.onblocked = () => { - blockedTimer = setTimeout(() => { - // Not NOT_APPLIED: the request is still live in the browser. - finish( - browserDataSuccess( - Object.freeze({ - state: "PENDING" as const, - effect: "UNKNOWN" as const, - reason: "BLOCKED_DEADLINE" as const, - }), - ), - ); - }, blockedTimeoutMs); - }; - request.onerror = () => { - releasePending(); - finish( - mapBrowserDataException( - request.error, - "UPLOAD_RECONCILE", - ), - ); - }; - request.onsuccess = () => { - releasePending(); - finish( - browserDataSuccess( - Object.freeze({ - state: "DELETED" as const, - effect: "APPLIED" as const, - }), - ), - ); - }; - }, + // Not NOT_APPLIED: the request is still live in the browser. + return browserDataSuccess( + Object.freeze({ + state: "PENDING" as const, + effect: "UNKNOWN" as const, + reason: "BLOCKED_DEADLINE" as const, + }), ); }, }; @@ -488,168 +477,79 @@ export function createIndexedDbResumableUploadCheckpointRuntime( return Object.freeze({ store, admin }); } -type TransactionContext = Readonly<{ - succeed(value: Value): void; - fail(result: BrowserDataResult): void; - nativeFailure(error: unknown): void; -}>; - +/** + * `durability` is deliberately `undefined` rather than `"default"`: that opens + * the transaction with no options bag at all, which is what checkpoint writes + * have always done. Passing a named value would quietly move them onto a + * different flush policy and slow every checkpoint write down. + * + * A request error goes through `fail`, which aborts, rather than through the + * kernel's `requestFailed`, which only records. `compareAndSwap` issues its put + * inside the get's success handler, so a transaction left running after a + * failed request is a transaction that can still commit half of a swap. + */ async function runCheckpointTransaction( database: IDBDatabase, - mode: IDBTransactionMode, + mode: "readonly" | "readwrite", signal: AbortSignal | undefined, execute: ( store: IDBObjectStore, - context: TransactionContext, + context: Readonly<{ + succeed(value: Value): void; + fail(failure: BrowserDataFailure): void; + }>, ) => void, ): Promise> { - if (signal?.aborted) { - return browserDataFailure("ABORTED", "UPLOAD_RECONCILE"); - } - return await new Promise>((resolve) => { - let transaction: IDBTransaction; - try { - transaction = database.transaction(CHECKPOINT_STORE, mode); - } catch (error) { - resolve(mapBrowserDataException(error, "UPLOAD_RECONCILE")); - return; - } - let value: Value | undefined; - let hasValue = false; - let failure: BrowserDataResult | null = null; - let settled = false; - const finish = (result: BrowserDataResult) => { - if (settled) return; - settled = true; - signal?.removeEventListener("abort", abort); - resolve(result); - }; - const abort = () => { - const previousFailure = failure; - failure = browserDataFailure("ABORTED", "UPLOAD_RECONCILE"); - try { - transaction.abort(); - } catch { - // The transaction may already be durably committed while its - // completion event is still queued. Wait for oncomplete/onabort so we - // never report ABORTED for a mutation that actually committed. - failure = previousFailure; - } - }; - signal?.addEventListener("abort", abort, { once: true }); - transaction.oncomplete = () => { - if (!hasValue) { - finish( - browserDataFailure("CORRUPT_DATA", "UPLOAD_RECONCILE", { - recovery: "RECONCILE", - }), - ); - return; - } - finish(browserDataSuccess(value as Value)); - }; - transaction.onerror = () => { - // onabort is the terminal transaction signal. - }; - transaction.onabort = () => - finish( - failure ?? - mapBrowserDataException( - transaction.error, - "UPLOAD_RECONCILE", - ), - ); - const context: TransactionContext = Object.freeze({ - succeed(next) { - if (failure) return; - value = next; - hasValue = true; - }, - fail(result) { - if (failure) return; - failure = result; - try { - transaction.abort(); - } catch { - finish(result); - } - }, - nativeFailure(error) { - if (failure) return; - failure = mapBrowserDataException( - error, - "UPLOAD_RECONCILE", - ); - try { - transaction.abort(); - } catch { - finish(failure); - } - }, - }); - try { + return await runIndexedDbTransaction({ + database, + stores: [CHECKPOINT_STORE], + mode, + translate, + signal, + durability: undefined, + queue: (transaction, context) => { execute(transaction.objectStore(CHECKPOINT_STORE), context); - } catch (error) { - context.nativeFailure(error); - } + }, }); } +/** + * No `signal`: the binding is part of opening the connection, and an open the + * caller gave up on is already ended by the kernel's own abort path. + */ async function bindScope( database: IDBDatabase, expected: ScopeBinding, ): Promise> { - return await new Promise>((resolve) => { - let transaction: IDBTransaction; - try { - transaction = database.transaction(GOVERNANCE_STORE, "readwrite"); - } catch (error) { - resolve(mapBrowserDataException(error, "UPLOAD_RECONCILE")); - return; - } - let failure: BrowserDataResult | null = null; - transaction.onerror = () => { - // onabort owns terminal resolution. - }; - transaction.onabort = () => - resolve( - failure ?? - mapBrowserDataException( - transaction.error, - "UPLOAD_RECONCILE", - ), - ); - transaction.oncomplete = () => resolve(browserDataSuccess(undefined)); - const store = transaction.objectStore(GOVERNANCE_STORE); - const request = store.get(GOVERNANCE_KEY); - request.onerror = () => { - failure = mapBrowserDataException( - request.error, - "UPLOAD_RECONCILE", - ); - transaction.abort(); - }; - request.onsuccess = () => { - if (request.result === undefined) { - const add = store.add(expected); - add.onerror = () => { - failure = mapBrowserDataException( - add.error, - "UPLOAD_RECONCILE", + return await runIndexedDbTransaction({ + database, + stores: [GOVERNANCE_STORE], + mode: "readwrite", + translate, + durability: undefined, + queue: (transaction, context) => { + const store = transaction.objectStore(GOVERNANCE_STORE); + const request = store.get(GOVERNANCE_KEY); + request.onerror = () => context.fail(mappedFailure(request.error)); + request.onsuccess = () => { + if (request.result === undefined) { + const add = store.add(expected); + add.onerror = () => context.fail(mappedFailure(add.error)); + // The binding is the value: without this the committed transaction + // would report NO_VALUE_PRODUCED, which this store reads as + // CORRUPT_DATA. + add.onsuccess = () => context.succeed(undefined); + return; + } + if (!sameScopeBinding(request.result, expected)) { + context.fail( + checkpointFailure("POLICY_REJECTED", { recovery: "READ_ONLY" }), ); - transaction.abort(); - }; - return; - } - if (!sameScopeBinding(request.result, expected)) { - failure = browserDataFailure( - "POLICY_REJECTED", - "UPLOAD_RECONCILE", - { recovery: "READ_ONLY" }, - ); - transaction.abort(); - } - }; + return; + } + context.succeed(undefined); + }; + }, }); } diff --git a/src/adapters/diagnostics/index.ts b/src/adapters/diagnostics/index.ts new file mode 100644 index 0000000..57f0af5 --- /dev/null +++ b/src/adapters/diagnostics/index.ts @@ -0,0 +1,7 @@ +export { + createDiagnosticsAdapter, + getLastBootEvidence, + MAX_DIAGNOSTIC_ENTRIES, + noOpDiagnostics, + recordBootFailure, +} from "./bounded-diagnostics.ts"; diff --git a/src/adapters/http/feature-http-binding.ts b/src/adapters/http/feature-http-binding.ts new file mode 100644 index 0000000..838a461 --- /dev/null +++ b/src/adapters/http/feature-http-binding.ts @@ -0,0 +1,400 @@ +import type { + InstalledHttpContract, +} from "../../contracts/external-contract-runtime.ts"; +import type { Result } from "../../contracts/result.ts"; +import type { MappingResult } from "../../contracts/boundary-mapper.ts"; +import { + createFailure, + kindForStatus, + type ApiFailure, + type FailureEffectCertainty, + type FailureKind, +} from "../../contracts/errors.ts"; +import type { MutationIntent } from "../../contracts/mutation-intent.ts"; +import type { + HttpExecutionOutcome, + SafeResponseMetadata, +} from "./http-execution-v3.ts"; + +type ValidatorValue = + Validator extends Readonly<{ + safeParse(value: unknown): infer ParseResult; + }> + ? Extract< + ParseResult, + Readonly<{ success: true; data: unknown }> + > extends Readonly<{ data: infer Value }> + ? Value + : never + : never; + +export type HttpContractInput = + Contract extends Readonly<{ + contract: Readonly<{ inputValidator: infer Validator }>; + }> + ? ValidatorValue + : never; + +export type HttpContractWireOutput = + Contract extends Readonly<{ + contract: Readonly<{ outputValidator: infer Validator }>; + }> + ? ValidatorValue + : never; + +export type HttpContractProblem = + Contract extends Readonly<{ + contract: Readonly<{ problemValidator: infer Validator }>; + }> + ? ValidatorValue + : never; + +export type HttpContractOperationId = + Contract extends Readonly<{ + contract: Readonly<{ operationId: infer OperationId extends string }>; + }> + ? OperationId + : never; + +export type InstalledHttpOperationExecutor = Readonly<{ + execute( + contract: InstalledHttpContract, + input: Input, + context: Readonly<{ + routeId: string; + signal?: AbortSignal; + intent?: MutationIntent; + }>, + ): Promise>; +}>; + +export type FeatureHttpProblemMapping = Readonly<{ + kind: FailureKind; + code: string; +}>; + +type FeatureHttpOperationSpec< + Contract, + Value, + RouteId extends string, +> = Readonly<{ + contract: Contract; + routeId: RouteId; + mapSuccess( + value: HttpContractWireOutput, + ): MappingResult; + mapProblem?( + problem: HttpContractProblem, + metadata: SafeResponseMetadata, + ): FeatureHttpProblemMapping | undefined; +}>; + +export type FeatureHttpOperation< + Contract, + Value, + RouteId extends string = string, +> = FeatureHttpOperationSpec & + Readonly<{ + operationId: HttpContractOperationId; + /** + * Compile-time only carrier. The runtime object has no extra type payload; + * the contract remains the authority for input/wire/problem types. + */ + __types?: Readonly<{ + value: Value; + }>; + }>; + +type ContractValidity = + HttpContractOperationId extends never + ? never + : HttpContractInput extends never + ? never + : HttpContractWireOutput extends never + ? never + : HttpContractProblem extends never + ? never + : unknown; + +function defineFeatureHttpOperationForRoute< + const RouteId extends string, + const Contract, + Value, +>( + spec: FeatureHttpOperationSpec & + ContractValidity, +): FeatureHttpOperation { + return Object.freeze({ + ...spec, + operationId: (spec.contract as Readonly<{ + contract: Readonly<{ operationId: HttpContractOperationId }>; + }>).contract.operationId, + }) as FeatureHttpOperation; +} + +export function defineFeatureHttpOperation< + const Contract, + Value, + const RouteId extends string, +>( + spec: FeatureHttpOperationSpec & + ContractValidity, +): FeatureHttpOperation { + return defineFeatureHttpOperationForRoute(spec); +} + +/** + * Feature-local route typing without introducing a dependency from the HTTP + * capability to the presentation route registry. + */ +export function defineFeatureHttpOperationForRoutes< + const RouteId extends string, +>() { + return function defineRouteBoundFeatureHttpOperation< + const Contract, + Value, + >( + spec: FeatureHttpOperationSpec & + ContractValidity, + ): FeatureHttpOperation { + return defineFeatureHttpOperationForRoute(spec); + }; +} + +type FeatureHttpOperationShape = Readonly<{ + contract: object; + operationId: string; + routeId: string; + mapSuccess: (...args: never[]) => unknown; + mapProblem?: (...args: never[]) => unknown; +}>; + +type OperationContract = + Operation extends Readonly<{ contract: infer Contract }> ? Contract : never; + +type OperationInput = HttpContractInput>; +type OperationWireOutput = + HttpContractWireOutput>; +type OperationProblem = + HttpContractProblem>; + +type OperationValue = + Operation extends FeatureHttpOperation + ? Value + : never; + +type InvalidOperationRegistryKeys< + Operations extends Readonly>, +> = { + [OperationId in keyof Operations & string]: + OperationId extends Operations[OperationId]["operationId"] + ? Operations[OperationId]["operationId"] extends OperationId + ? never + : OperationId + : OperationId; +}[keyof Operations & string]; + +type ValidOperationRegistry< + Operations extends Readonly>, +> = InvalidOperationRegistryKeys extends never + ? unknown + : Readonly<{ + __operationRegistryKeyMismatch: InvalidOperationRegistryKeys; + }>; + +export type FeatureHttpBinding< + Operations extends Readonly>, +> = Readonly<{ + execute( + operationId: OperationId, + input: OperationInput, + context?: Readonly<{ + signal?: AbortSignal; + intent?: MutationIntent; + }>, + ): Promise, ApiFailure>>; +}>; + +/** + * Capability-specific feature binding for the installed HTTP runtime. + * + * The installed contract is the single type authority. A feature contributes + * only a route identity plus wire-to-domain/problem interpretation. Transport, + * retry, validation and effect-certainty stay in the reusable HTTP capability. + */ +export function createFeatureHttpBinding< + const Operations extends Readonly>, +>( + executor: InstalledHttpOperationExecutor, + operations: Operations & ValidOperationRegistry, +): FeatureHttpBinding { + for (const [registryId, operation] of Object.entries(operations)) { + if (registryId !== operation.operationId) { + throw new TypeError( + `Feature HTTP operation key mismatch: ${registryId} !== ${operation.operationId}`, + ); + } + } + + return Object.freeze({ + async execute( + operationId: OperationId, + input: OperationInput, + context: Readonly<{ + signal?: AbortSignal; + intent?: MutationIntent; + }> = {}, + ): Promise, ApiFailure>> { + const operation = operations[operationId]; + type SelectedOperation = Operations[OperationId]; + type Input = OperationInput; + type WireOutput = OperationWireOutput; + type Problem = OperationProblem; + type Value = OperationValue; + + const contract = operation.contract as InstalledHttpContract< + Input, + WireOutput, + Problem + >; + const outcome = await executor.execute(contract, input, { + routeId: operation.routeId, + ...(context.signal === undefined ? {} : { signal: context.signal }), + ...(context.intent === undefined ? {} : { intent: context.intent }), + }); + return projectExecutionOutcome( + operation.operationId, + operation.mapSuccess as (value: WireOutput) => MappingResult, + operation.mapProblem as + | (( + problem: Problem, + metadata: SafeResponseMetadata, + ) => FeatureHttpProblemMapping | undefined) + | undefined, + outcome, + ); + }, + }); +} + +function projectExecutionOutcome( + operationId: string, + mapSuccess: (value: WireOutput) => MappingResult, + mapProblem: + | (( + problem: Problem, + metadata: SafeResponseMetadata, + ) => FeatureHttpProblemMapping | undefined) + | undefined, + outcome: HttpExecutionOutcome, +): Result { + switch (outcome.kind) { + case "SUCCESS": { + const mapped = mapSuccess(outcome.value); + return mapped.ok + ? Object.freeze({ ok: true as const, value: mapped.value }) + : failure( + "MAPPING_CONTRACT_VIOLATION", + operationId, + mapped.code, + { effect: outcome.effect }, + ); + } + case "PROBLEM": { + const mapped = mapProblem?.(outcome.problem, outcome.metadata); + return failure( + mapped?.kind ?? kindForStatus(outcome.metadata.status), + operationId, + mapped?.code ?? "CONTRACT_PROBLEM", + { httpStatus: outcome.metadata.status, effect: outcome.effect }, + ); + } + case "UNAUTHENTICATED": + return failure("AUTH_REQUIRED", operationId, "UNAUTHENTICATED", { + effect: outcome.effect, + }); + case "FORBIDDEN": + return failure("FORBIDDEN", operationId, "FORBIDDEN", { + effect: outcome.effect, + }); + case "RATE_LIMITED": + return failure("RATE_LIMITED", operationId, "RATE_LIMITED", { + ...(outcome.retryAfterMs === undefined + ? {} + : { retryAfterMs: outcome.retryAfterMs }), + effect: outcome.effect, + }); + case "CANCELLED": + return failure("REQUEST_ABORTED", operationId, "REQUEST_ABORTED", { + effect: outcome.effect, + }); + case "AUTH_INTEGRATION_FAILURE": + return failure( + "AUTH_INTEGRATION_FAILURE", + operationId, + outcome.reason, + { effect: outcome.effect }, + ); + case "TRANSPORT_FAILURE": + return failure( + outcome.failure.kind === "TIMEOUT" + ? "REQUEST_TIMEOUT" + : outcome.failure.kind === "ABORTED_BY_SCOPE" + ? "SCOPE_GENERATION_CHANGED" + : "NETWORK_UNREACHABLE", + operationId, + outcome.failure.kind, + { effect: outcome.effect }, + ); + case "CONTRACT_VIOLATION": + return failure( + failureKindForViolation(outcome.violation.kind), + operationId, + outcome.violation.kind, + { effect: outcome.effect }, + ); + } +} + +function failureKindForViolation( + violation: Extract< + HttpExecutionOutcome, + { kind: "CONTRACT_VIOLATION" } + >["violation"]["kind"], +): FailureKind { + switch (violation) { + case "CONTENT_TYPE_MISMATCH": + return "CONTENT_TYPE_MISMATCH"; + case "RESPONSE_TOO_LARGE": + return "RESPONSE_BODY_LIMIT"; + case "UTF8_INVALID": + case "JSON_INVALID": + return "MALFORMED_JSON"; + case "MAPPING_CONTRACT_VIOLATION": + return "MAPPING_CONTRACT_VIOLATION"; + case "SCOPE_FENCED": + return "SCOPE_GENERATION_CHANGED"; + case "SUCCESS_SCHEMA_INVALID": + case "PROBLEM_SCHEMA_INVALID": + case "VALIDATOR_RUNTIME_FAILURE": + return "SCHEMA_MISMATCH"; + default: + return "ENVELOPE_MISMATCH"; + } +} + +function failure( + kind: FailureKind, + operationId: string, + code: string, + details: Readonly<{ + httpStatus?: number; + retryAfterMs?: number; + effect?: FailureEffectCertainty; + }> = {}, +): Result { + return Object.freeze({ + ok: false as const, + error: createFailure(kind, operationId, 0, { code, ...details }), + }); +} diff --git a/src/adapters/http/http-execution-v3.ts b/src/adapters/http/http-execution-v3.ts index 9cb8070..74d6d3e 100644 --- a/src/adapters/http/http-execution-v3.ts +++ b/src/adapters/http/http-execution-v3.ts @@ -41,6 +41,13 @@ import { type PhysicalAttemptState, } from "./http-effect-certainty.ts"; import { parseRetryAfter } from "./retry-policy.ts"; +import { + canRetryTransport, + isRetryableHttpStatus, + isRetryableSemantics, + jitteredDelay, + retryDelayFor, +} from "./http-retry-lifecycle.ts"; /** * §7–§8. Descriptor-driven HTTP execution. @@ -299,14 +306,6 @@ export type ContractHttpExecutorDependencies = Readonly<{ observe?: (observation: HttpExecutionObservation) => void; }>; -const RETRYABLE_STATUSES: ReadonlySet = new Set([ - 408, 425, 429, 502, 503, 504, -]); - -const RETRY_BASE_DELAY_MS = 250; -const RETRY_MAX_LOCAL_DELAY_MS = 2_000; -const RETRY_AFTER_CEILING_MS = 5_000; - type MutationIntentValidation = | Readonly<{ ok: true; intent?: MutationIntent }> | Readonly<{ @@ -1347,7 +1346,7 @@ async function admitProblem( ): Promise> { const contract = operation.contract; const isCommand = contract.commandEffect !== null; - const retryable = RETRYABLE_STATUSES.has(status); + const retryable = isRetryableHttpStatus(status); const bytes = await readResponseBytes( response, @@ -1434,56 +1433,6 @@ async function admitProblem( }); } -/** - * §8.3. `SAFE` and `IDEMPOTENT` may replay the same frozen request. `KEYED` - * must not automatically retry once an attempt was dispatched and its response - * was lost; that path goes to inspect/reconciliation instead. `NEVER` is zero. - */ -function canRetryTransport( - semantics: InstalledHttpContract< - unknown, - unknown, - unknown - >["contract"]["retrySemantics"], - attemptState: PhysicalAttemptState, -): boolean { - if (semantics === "NEVER") return false; - if (semantics === "KEYED") { - return attemptState === "PREPARING" || attemptState === "READY_TO_SEND"; - } - return true; -} - -function isRetryableSemantics( - semantics: InstalledHttpContract< - unknown, - unknown, - unknown - >["contract"]["retrySemantics"], -): boolean { - return semantics === "SAFE" || semantics === "IDEMPOTENT"; -} - -/** §8.2. Full jitter over `min(2000, 250 * 2^index)`. */ -function jitteredDelay(retryIndex: number, random: () => number): number { - const ceiling = Math.min( - RETRY_MAX_LOCAL_DELAY_MS, - RETRY_BASE_DELAY_MS * 2 ** retryIndex, - ); - return Math.floor(random() * ceiling); -} - -function retryDelayFor( - retryAfterMs: number | null, - retryIndex: number, - random: () => number, -): number | null { - const local = jitteredDelay(retryIndex, random); - if (retryAfterMs === null) return local; - if (retryAfterMs > RETRY_AFTER_CEILING_MS) return null; - return Math.max(local, retryAfterMs); -} - /** §7.12. No raw header map, URL, cookie, traceparent or ETag value escapes. */ function safeMetadata( response: Response, diff --git a/src/adapters/http/http-retry-lifecycle.ts b/src/adapters/http/http-retry-lifecycle.ts new file mode 100644 index 0000000..ec7139b --- /dev/null +++ b/src/adapters/http/http-retry-lifecycle.ts @@ -0,0 +1,57 @@ +import type { RetrySemantics } from "../../contracts/external-contract-runtime.ts"; +import type { PhysicalAttemptState } from "./http-effect-certainty.ts"; + +const RETRYABLE_STATUSES: ReadonlySet = new Set([ + 408, 425, 429, 502, 503, 504, +]); +const RETRY_BASE_DELAY_MS = 250; +const RETRY_MAX_LOCAL_DELAY_MS = 2_000; +const RETRY_AFTER_CEILING_MS = 5_000; + +export function isRetryableHttpStatus(status: number): boolean { + return RETRYABLE_STATUSES.has(status); +} + +/** + * Transport replay authority. + * + * KEYED commands may retry only before a physical dispatch. Once dispatched, + * an uncertain result belongs to reconciliation rather than automatic replay. + */ +export function canRetryTransport( + semantics: RetrySemantics, + attemptState: PhysicalAttemptState, +): boolean { + if (semantics === "NEVER") return false; + if (semantics === "KEYED") { + return attemptState === "PREPARING" || attemptState === "READY_TO_SEND"; + } + return true; +} + +export function isRetryableSemantics(semantics: RetrySemantics): boolean { + return semantics === "SAFE" || semantics === "IDEMPOTENT"; +} + +/** Full jitter over min(2000, 250 * 2^retryIndex). */ +export function jitteredDelay( + retryIndex: number, + random: () => number, +): number { + const ceiling = Math.min( + RETRY_MAX_LOCAL_DELAY_MS, + RETRY_BASE_DELAY_MS * 2 ** retryIndex, + ); + return Math.floor(random() * ceiling); +} + +export function retryDelayFor( + retryAfterMs: number | null, + retryIndex: number, + random: () => number, +): number | null { + const local = jitteredDelay(retryIndex, random); + if (retryAfterMs === null) return local; + if (retryAfterMs > RETRY_AFTER_CEILING_MS) return null; + return Math.max(local, retryAfterMs); +} diff --git a/src/adapters/http/index.ts b/src/adapters/http/index.ts new file mode 100644 index 0000000..626f326 --- /dev/null +++ b/src/adapters/http/index.ts @@ -0,0 +1,55 @@ +/** + * §7–§8. 권장 경로는 V3 계약 실행기(`createContractHttpExecutor`)다. 설치된 + * 계약과 타입 입력을 받아 상한·전체 데드라인·재시도 권한·효과 확실성 판정을 + * 런타임이 소유한다. + */ +export { + createContractHttpExecutor, + type AuthIntegrationFailureReason, + type AuthOperationContext, + type CancellationOwner, + type ContractHttpExecutor, + type ContractHttpExecutorDependencies, + type HttpContractViolation, + type HttpContractViolationKind, + type HttpEffectCertainty, + type HttpExecutionContext, + type HttpExecutionObservation, + type HttpExecutionOutcome, + type HttpTransportFailure, + type SafeResponseMetadata, +} from "./http-execution-v3.ts"; +export { + createFeatureHttpBinding, + defineFeatureHttpOperation, + defineFeatureHttpOperationForRoutes, + type FeatureHttpBinding, + type FeatureHttpOperation, + type FeatureHttpProblemMapping, + type HttpContractInput, + type HttpContractOperationId, + type HttpContractProblem, + type HttpContractWireOutput, + type InstalledHttpOperationExecutor, +} 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`)의 네 + * 슬롯을 주입해야 동작한다 — 주입 없이 V3에서 되돌리면 모든 요청이 실패한다. + */ +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/platform/index.ts b/src/adapters/platform/index.ts new file mode 100644 index 0000000..015735f --- /dev/null +++ b/src/adapters/platform/index.ts @@ -0,0 +1,31 @@ +/** + * 어댑터 커널의 공개 경계. + * + * `src/adapters/**` 안에서는 이 배럴을 쓰지 않는다. 커널 프리미티브는 파일 + * 경로로 직접 import한다 — `scripts/check-adapter-inventory.ts:63-83`이 + * `platform/abortable-operation.ts`로 해석되는 specifier를 네 소비자에게 + * 요구하고, `.dependency-cruiser.json`의 kernel carve-out도 폴더 단위다. + * 이 배럴은 bootstrap·features·tests 같은 그룹 바깥 소비자를 위한 문이다. + */ +export { + compensateLateHandle, + createAbortableOperation, + snapshotAbortTimers, + type AbortableOperation, + type AbortableOperationInput, + type AbortRace, + type AbortTerminalReason, + type AbortTimerSnapshot, +} from "./abortable-operation.ts"; +export { assertBoundedCapacity } from "./bounded-capacity.ts"; +export { + createBrowserLifecycleRuntime, + type BrowserLifecycleEvent, + type BrowserLifecycleRuntime, + type BrowserLifecycleSnapshot, +} from "./browser-lifecycle.ts"; +export { + createBrowserMutationIntentFactory, + type BrowserMutationIntentFactoryDependencies, +} from "./browser-mutation-intent-factory.ts"; +export { systemClock } from "./system-clock.ts"; diff --git a/src/adapters/platform/indexeddb-connection.ts b/src/adapters/platform/indexeddb-connection.ts new file mode 100644 index 0000000..c53b3dc --- /dev/null +++ b/src/adapters/platform/indexeddb-connection.ts @@ -0,0 +1,699 @@ +/** + * IDB-X-01. Shared IndexedDB connection mechanics. + * + * Four adapters independently reimplemented "turn an open request into a + * promise, hold a blocked deadline, route upgrade/error/success, close a + * connection that arrives after the caller gave up, and drop the cached handle + * when the browser takes it away". Only the mechanics are shared here. Database + * naming, schema, migrations, governance binding and the failure taxonomy stay + * with each subsystem, so this module imports none of them and is not a + * generic storage layer. + * + * The `IDBFactory` is a required parameter rather than a read of + * `globalThis.indexedDB`. `eslint.config.ts:40-63` bans that property on every + * browser root and `eslint.config.ts:519-530` grants the owned-adapter escape + * hatch to `src/adapters/platform/browser-lifecycle.ts` as a single file, not + * to this folder. Requiring the factory is also what all four callers already + * do, so nothing in eslint.config.ts has to change. + * + * What this module owns: event wiring, the settle-once latch, the blocked + * deadline and the cached-handle lifecycle. What it must never own: database + * names, schemas, migrations, governance bindings, codecs, byte budgets, + * retention, idempotency receipts, failure code tables, operation labels, + * observation event shapes, durability defaults and budget criteria. Wanting to + * move one of those in here is the signal to stop. + */ + +import type { Result } from "../../contracts/result.ts"; +import type { AbortTimerSnapshot } from "./abortable-operation.ts"; + +/** + * Everything that can end an IndexedDB operation without the caller getting a + * value. The kernel reports the cause; the caller's `translate` turns it into + * that subsystem's failure code. + * + * This union is the extension point. `abortable-operation.ts:11` baked a closed + * three-member `AbortTerminalReason` into its return type, so http v3 needed + * five owners and could not use the kernel at all. Here the owner vocabulary is + * never in a return type: adding a member is a compile error in every + * `translate` (they are total functions over the union) rather than a silent + * behavior change, and no consumer has to fork. + */ +export type IndexedDbFailureCause = + /** A native throw or a `request.error` / `transaction.error`. */ + | Readonly<{ kind: "NATIVE_EXCEPTION"; error: unknown }> + /** `onblocked` fired and no deadline was configured. */ + | Readonly<{ kind: "BLOCKED"; oldVersion: number; newVersion: number | null }> + /** `onblocked` fired and the configured deadline then elapsed. */ + | Readonly<{ kind: "BLOCKED_DEADLINE" }> + /** The caller's own `AbortSignal` fired. */ + | Readonly<{ kind: "CALLER_ABORT" }> + /** The connection handle was closed, which is not the caller aborting. */ + | Readonly<{ kind: "CLOSED" }> + /** `upgrade` returned `REJECTED`, or a version change happened unexpectedly. */ + | Readonly<{ + kind: "UPGRADE_REJECTED"; + oldVersion: number; + newVersion: number | null; + detail?: unknown; + }> + /** `admit` returned `REJECT`. `detail` is opaque to the kernel. */ + | Readonly<{ kind: "ADMISSION_REJECTED"; detail?: unknown }> + /** A transaction completed without `succeed()` ever being called. */ + | Readonly<{ kind: "NO_VALUE_PRODUCED" }> + /** + * No `IDBFactory`, or a required `IDBKeyRange` the caller did not supply. + * The kernel never raises this itself — the factory is a required parameter, + * so the condition can only exist before the kernel is called. It is part of + * the vocabulary so a caller that resolves those globals has one place to + * name the failure instead of a second taxonomy beside `translate`. + */ + | Readonly<{ kind: "UNSUPPORTED" }>; + +/** + * Turns a cause into this subsystem's failure value. Built per call site so the + * kernel never learns an operation label or a failure code; a caller that needs + * `INDEXEDDB_READ` and one that needs `UPLOAD_RECONCILE` differ only here. + */ +export type IndexedDbTranslate = ( + cause: IndexedDbFailureCause, +) => Failure; + +export type IndexedDbUpgradeContext = Readonly<{ + database: IDBDatabase; + transaction: IDBTransaction; + oldVersion: number; + /** Never `null`: a null `newVersion` is reported as `UPGRADE_REJECTED` before `upgrade` runs. */ + newVersion: number; +}>; + +/** + * `REJECTED` aborts the versionchange transaction, so a schema change can never + * commit under a rejected policy. A throw from `upgrade` is equivalent to + * `REJECTED` with the thrown value as `detail`. + */ +export type IndexedDbUpgradeOutcome = + | Readonly<{ kind: "APPLIED" }> + | Readonly<{ kind: "REJECTED"; detail?: unknown }>; + +/** + * Post-open validation. It runs after `onsuccess` and may be asynchronous, so + * store/index assertions and governance reads both fit. A rejected or failed + * admission closes the connection before the caller ever sees it. + */ +export type IndexedDbAdmission = + | Readonly<{ kind: "ADMIT" }> + | Readonly<{ kind: "REJECT"; detail?: unknown }> + | Readonly<{ kind: "FAIL"; cause: IndexedDbFailureCause }>; + +export type IndexedDbOpenInput = Readonly<{ + /** Required. See the module comment for why this is not read from a global. */ + factory: IDBFactory; + databaseName: string; + /** Omit to open whatever version exists. */ + version?: number; + translate: IndexedDbTranslate; + /** + * Called inside the versionchange transaction. Omitting it means any upgrade + * is unexpected and the open fails with `UPGRADE_REJECTED` — which is what + * `indexeddb-maintenance.ts:477-484` does by hand today. + */ + upgrade?: (context: IndexedDbUpgradeContext) => IndexedDbUpgradeOutcome; + /** Post-open validation. Omitting it admits every successful open. */ + admit?: ( + database: IDBDatabase, + ) => IndexedDbAdmission | Promise; + /** Aborts a pending upgrade transaction and settles with `CALLER_ABORT`. */ + signal?: AbortSignal; + /** + * `undefined` or `0`: the `onblocked` event itself is terminal and settles + * with `BLOCKED` (maintenance's behavior). A positive value waits that long + * before settling with `BLOCKED_DEADLINE` (runtime/opfs/checkpoint). + */ + blockedTimeoutMs?: number; + /** + * Required when `blockedTimeoutMs` is positive. Build it with + * `snapshotAbortTimers` from `./abortable-operation.ts`, which binds the + * callables once so replacing a method after composition cannot change how an + * open already in flight is bounded. + */ + timers?: AbortTimerSnapshot; + /** Observation only; it cannot change the outcome and its throw is swallowed. */ + onBlocked?: ( + event: Readonly<{ oldVersion: number; newVersion: number | null }>, + ) => void; +}>; + +export type IndexedDbConnection = Readonly<{ + /** + * Single-flight: concurrent callers share one in-flight open, and a cached + * live connection is returned without touching the factory. + */ + acquire(signal?: AbortSignal): Promise>; + /** The cached connection, or `null` while none is live. Live accessor, not a snapshot. */ + current(): IDBDatabase | null; + /** + * Idempotent. Closes the cached connection and settles any in-flight open + * with `CLOSED` — not `CALLER_ABORT`, because the two have different codes in + * `indexeddb-runtime.ts` (`L743` resolves UNAVAILABLE while `L676` resolves + * ABORTED), and collapsing them would change one of them. + */ + close(): void; + isClosed(): boolean; +}>; + +export type IndexedDbConnectionInput = Readonly<{ + /** + * How to produce a connection. Normally a closure over + * `openIndexedDbDatabase`. It is a seam rather than a fixed body so a caller + * can retry, decorate or fake the open without faking an `IDBFactory`. + */ + open: ( + signal: AbortSignal | undefined, + ) => Promise>; + translate: IndexedDbTranslate; + /** + * Fired after the handle has already dropped its cached connection, so a + * listener cannot keep a connection the browser is taking back. The next + * `acquire()` opens again. + */ + onVersionChange?: (event: IDBVersionChangeEvent) => void; + /** `onclose`: the browser closed the connection without a version change. */ + onForcedClose?: () => void; +}>; + +export type IndexedDbDeleteOutcome = + | Readonly<{ kind: "DELETED" }> + /** + * The request is still live in the browser. It is not a failure and it is not + * "not applied": `deleteDatabase` cannot be cancelled after dispatch, so the + * effect is unknown. `indexeddb-checkpoint-store.ts:449-462` makes the same + * distinction and its comment explains why. + */ + | Readonly<{ kind: "BLOCKED_DEADLINE" }>; + +export type IndexedDbDeleteInput = Readonly<{ + factory: IDBFactory; + databaseName: string; + translate: IndexedDbTranslate; + blockedTimeoutMs?: number; + timers?: AbortTimerSnapshot; + /** + * Called exactly once when the native request truly settles, success or + * error — never on a blocked deadline. The caller uses it to release a + * pending-deletion registration; the kernel does not own such a registry + * because whether a realm may recreate the database is the caller's policy. + */ + onSettled?: () => void; +}>; + +function succeeded(value: Value): Result { + return Object.freeze({ ok: true as const, value }); +} + +function failed(error: Failure): Result { + return Object.freeze({ ok: false as const, error }); +} + +/** + * A connection that lost a race is closed, never leaked. The close itself is + * best effort: a handle the browser already tore down cannot be closed again, + * and that must not replace the outcome the caller was given. + */ +function closeQuietly(database: IDBDatabase): void { + try { + database.close(); + } catch { + // A connection that cannot be closed is already gone. + } +} + +/** + * A positive deadline with no scheduler leaves the open unbounded, which is the + * same class of configuration defect `assertBoundedCapacity` and + * `snapshotAbortTimers` reject at construction rather than at runtime. It is a + * throw instead of a `Failure` because no `translate` could describe it without + * the caller first deciding it is acceptable to run unbounded. + */ +function assertBlockedDeadline( + blockedTimeoutMs: number | undefined, + timers: AbortTimerSnapshot | undefined, +): boolean { + const bounded = + blockedTimeoutMs !== undefined && + Number.isFinite(blockedTimeoutMs) && + blockedTimeoutMs > 0; + if (bounded && !timers) { + throw new TypeError( + "A positive blockedTimeoutMs requires a timer snapshot.", + ); + } + return bounded; +} + +/** + * Settles exactly once. A connection that arrives after the settle — a late + * `onsuccess`, a rejected admission, an abort — is closed rather than leaked. + */ +export function openIndexedDbDatabase( + input: IndexedDbOpenInput, +): Promise> { + const { factory, databaseName, translate } = input; + const bounded = assertBlockedDeadline(input.blockedTimeoutMs, input.timers); + if (input.signal?.aborted) { + return Promise.resolve(failed(translate({ kind: "CALLER_ABORT" }))); + } + + return new Promise>((resolve) => { + let settled = false; + let blockedTimer: unknown; + let blockedTimerSet = false; + let upgradeRejection: IndexedDbFailureCause | null = null; + + const settle = (result: Result) => { + if (settled) { + if (result.ok) closeQuietly(result.value); + return; + } + settled = true; + if (blockedTimerSet) { + blockedTimerSet = false; + try { + input.timers?.clearTimer(blockedTimer); + } catch { + // A throwing scheduler cannot keep the open unresolved. + } + } + try { + input.signal?.removeEventListener("abort", onCallerAbort); + } catch { + // A hostile signal facade cannot block cleanup. + } + resolve(result); + }; + const settleFailure = (cause: IndexedDbFailureCause) => { + settle(failed(translate(cause))); + }; + + let request: IDBOpenDBRequest; + try { + request = + input.version === undefined + ? factory.open(databaseName) + : factory.open(databaseName, input.version); + } catch (error) { + settleFailure({ kind: "NATIVE_EXCEPTION", error }); + return; + } + + /** + * An upgrade transaction is the only cancellable part of an open request: + * aborting it makes the request fail through `onerror`, and there is no + * other way to stop a dispatched open. + */ + const abortUpgrade = () => { + try { + request.transaction?.abort(); + } catch { + // The request's own error path owns whatever happens next. + } + }; + + function onCallerAbort(): void { + abortUpgrade(); + settleFailure({ kind: "CALLER_ABORT" }); + } + input.signal?.addEventListener("abort", onCallerAbort, { once: true }); + + request.onupgradeneeded = (event) => { + const transaction = request.transaction; + const oldVersion = event.oldVersion; + const newVersion = event.newVersion; + // A null `newVersion` means a delete is in progress, and no `upgrade` + // policy can be applied to a schema that is going away. It is reported + // before the callback runs so a caller never sees a half-open upgrade. + if (!transaction || newVersion === null || !input.upgrade) { + upgradeRejection = { kind: "UPGRADE_REJECTED", oldVersion, newVersion }; + abortUpgrade(); + return; + } + let outcome: IndexedDbUpgradeOutcome; + try { + outcome = input.upgrade({ + database: request.result, + transaction, + oldVersion, + newVersion, + }); + } catch (error) { + outcome = { kind: "REJECTED", detail: error }; + } + if (outcome.kind === "APPLIED") return; + upgradeRejection = { + kind: "UPGRADE_REJECTED", + oldVersion, + newVersion, + detail: outcome.detail, + }; + abortUpgrade(); + }; + + request.onblocked = (event) => { + const blocked = Object.freeze({ + oldVersion: event.oldVersion, + newVersion: event.newVersion, + }); + if (input.onBlocked) { + try { + input.onBlocked(blocked); + } catch { + // Observation cannot change the outcome. + } + } + if (!bounded) { + settleFailure({ kind: "BLOCKED", ...blocked }); + return; + } + if (blockedTimerSet || settled) return; + try { + blockedTimer = input.timers?.setTimer(() => { + settleFailure({ kind: "BLOCKED_DEADLINE" }); + }, input.blockedTimeoutMs as number); + blockedTimerSet = true; + } catch { + // A scheduler that cannot install the deadline leaves the open + // unbounded, so the deadline is treated as already elapsed. + settleFailure({ kind: "BLOCKED_DEADLINE" }); + } + }; + + request.onerror = () => { + settleFailure( + upgradeRejection ?? { kind: "NATIVE_EXCEPTION", error: request.error }, + ); + }; + + const routeAdmission = ( + database: IDBDatabase, + admission: IndexedDbAdmission, + ) => { + if (settled) { + closeQuietly(database); + return; + } + if (admission.kind === "ADMIT") { + settle(succeeded(database)); + return; + } + // A connection the caller will never see is closed before the failure is + // reported, so a rejected admission cannot leak a live handle. + closeQuietly(database); + settleFailure( + admission.kind === "REJECT" + ? { kind: "ADMISSION_REJECTED", detail: admission.detail } + : admission.cause, + ); + }; + + request.onsuccess = () => { + const database = request.result; + if (settled) { + closeQuietly(database); + return; + } + if (!input.admit) { + settle(succeeded(database)); + return; + } + let admission: IndexedDbAdmission | Promise; + try { + admission = input.admit(database); + } catch (error) { + closeQuietly(database); + settleFailure({ kind: "NATIVE_EXCEPTION", error }); + return; + } + void Promise.resolve(admission).then( + (resolved) => routeAdmission(database, resolved), + (error: unknown) => { + closeQuietly(database); + settleFailure({ kind: "NATIVE_EXCEPTION", error }); + }, + ); + }; + }); +} + +export function createIndexedDbConnection( + input: IndexedDbConnectionInput, +): IndexedDbConnection { + let connection: IDBDatabase | null = null; + let attempt: Promise> | null = null; + let controller: AbortController | null = null; + let closed = false; + const closeWaiters = new Set<() => void>(); + + /** + * The browser is taking the connection back. The cached handle is dropped + * before the subsystem is told, so a notification callback cannot hand out a + * connection that is already gone. The next `acquire()` opens again. + */ + const invalidate = (database: IDBDatabase, notify: () => void) => { + if (connection !== database) return; + connection = null; + try { + notify(); + } catch { + // Losing the connection is independent from announcing it. + } + }; + + const adopt = (database: IDBDatabase): IDBDatabase => { + database.onversionchange = (event) => { + // The connection has to go for the other context's upgrade to proceed, + // so it is closed here rather than left to a listener's discretion. + closeQuietly(database); + invalidate(database, () => input.onVersionChange?.(event)); + }; + database.onclose = () => { + // `onclose` means the browser already tore the connection down, so there + // is nothing left to close — only a cached handle to drop. + invalidate(database, () => input.onForcedClose?.()); + }; + return database; + }; + + const start = (): Promise> => { + const openController = new AbortController(); + controller = openController; + const started = input.open(openController.signal).then( + (result) => { + if (attempt === started) { + attempt = null; + controller = null; + } + if (!result.ok) return result; + if (closed) { + // The handle was closed while the open was in flight; the connection + // that arrived belongs to nobody. + closeQuietly(result.value); + return result; + } + connection = adopt(result.value); + return result; + }, + (error: unknown) => { + if (attempt === started) { + attempt = null; + controller = null; + } + return failed( + input.translate({ kind: "NATIVE_EXCEPTION", error }), + ); + }, + ); + attempt = started; + return started; + }; + + return Object.freeze({ + acquire(signal) { + if (closed) { + return Promise.resolve( + failed(input.translate({ kind: "CLOSED" })), + ); + } + if (signal?.aborted) { + return Promise.resolve( + failed( + input.translate({ kind: "CALLER_ABORT" }), + ), + ); + } + const live = connection; + if (live) return Promise.resolve(succeeded(live)); + + const shared = attempt ?? start(); + // The shared open is not cancelled by one caller giving up: another + // caller may still want the connection, and the request cannot be + // un-dispatched anyway. + return new Promise>((resolve) => { + let callerSettled = false; + const finishCaller = (result: Result) => { + if (callerSettled) return; + callerSettled = true; + try { + signal?.removeEventListener("abort", onAbort); + } catch { + // A hostile signal facade cannot block cleanup. + } + resolve(result); + }; + function onAbort(): void { + finishCaller( + failed(input.translate({ kind: "CALLER_ABORT" })), + ); + } + function onClose(): void { + finishCaller(failed(input.translate({ kind: "CLOSED" }))); + } + signal?.addEventListener("abort", onAbort, { once: true }); + closeWaiters.add(onClose); + void shared.then( + (result) => { + closeWaiters.delete(onClose); + // A handle closed mid-open reports CLOSED even if the open itself + // succeeded: the connection is already gone. + finishCaller( + closed + ? failed(input.translate({ kind: "CLOSED" })) + : result, + ); + }, + () => { + closeWaiters.delete(onClose); + finishCaller(failed(input.translate({ kind: "CLOSED" }))); + }, + ); + }); + }, + current: () => connection, + close() { + if (closed) return; + closed = true; + const live = connection; + connection = null; + if (live) closeQuietly(live); + // Cancelling the in-flight open aborts a pending upgrade transaction, so + // a closed handle does not leave a versionchange transaction running. + try { + controller?.abort(); + } catch { + // A cancelled open still reports CLOSED to its waiters below. + } + controller = null; + for (const waiter of [...closeWaiters]) { + closeWaiters.delete(waiter); + waiter(); + } + }, + isClosed: () => closed, + }); +} + +/** + * In this module because it is the same `IDBOpenDBRequest` state machine as + * `openIndexedDbDatabase`, not because three subsystems need it — only + * `indexeddb-checkpoint-store.ts` deletes a database, and nothing here asks the + * other three to start. Leaving it out would leave a third hand-written copy of + * the settle-once blocked-deadline latch eight lines away from the kernel's. + * + * There is deliberately no `signal`: the request cannot be cancelled after + * dispatch, so reporting ABORTED while the deletion may still commit would be a + * lie. Callers check their signal before calling. + */ +export function deleteIndexedDbDatabase( + input: IndexedDbDeleteInput, +): Promise> { + const { factory, databaseName, translate } = input; + const bounded = assertBlockedDeadline(input.blockedTimeoutMs, input.timers); + + return new Promise>((resolve) => { + let settled = false; + let notified = false; + let blockedTimer: unknown; + let blockedTimerSet = false; + + /** + * Independent of `settle`: a blocked deadline resolves the caller while the + * request is still live, and the registration must be released when the + * request actually lands, not when the caller stopped waiting. + */ + const notifySettled = () => { + if (notified) return; + notified = true; + try { + input.onSettled?.(); + } catch { + // Releasing a registration cannot change the deletion outcome. + } + }; + + const settle = (result: Result) => { + if (settled) return; + settled = true; + if (blockedTimerSet) { + blockedTimerSet = false; + try { + input.timers?.clearTimer(blockedTimer); + } catch { + // A throwing scheduler cannot keep the deletion unresolved. + } + } + resolve(result); + }; + + let request: IDBOpenDBRequest; + try { + request = factory.deleteDatabase(databaseName); + } catch (error) { + notifySettled(); + settle(failed(translate({ kind: "NATIVE_EXCEPTION", error }))); + return; + } + + request.onsuccess = () => { + notifySettled(); + settle(succeeded({ kind: "DELETED" as const })); + }; + request.onerror = () => { + notifySettled(); + settle( + failed(translate({ kind: "NATIVE_EXCEPTION", error: request.error })), + ); + }; + request.onblocked = (event) => { + if (!bounded) { + settle( + failed( + translate({ + kind: "BLOCKED", + oldVersion: event.oldVersion, + newVersion: event.newVersion, + }), + ), + ); + return; + } + if (blockedTimerSet || settled) return; + try { + blockedTimer = input.timers?.setTimer(() => { + settle(succeeded({ kind: "BLOCKED_DEADLINE" as const })); + }, input.blockedTimeoutMs as number); + blockedTimerSet = true; + } catch { + settle(succeeded({ kind: "BLOCKED_DEADLINE" as const })); + } + }; + }); +} diff --git a/src/adapters/platform/indexeddb-transaction.ts b/src/adapters/platform/indexeddb-transaction.ts new file mode 100644 index 0000000..1570e9a --- /dev/null +++ b/src/adapters/platform/indexeddb-transaction.ts @@ -0,0 +1,433 @@ +/** + * IDB-X-02. Shared IndexedDB transaction and cursor mechanics. + * + * The same settle-once transaction state machine exists four times + * (`indexeddb-runtime.ts:976-1074`, `indexeddb-maintenance.ts:606-705`, + * `indexeddb-opfs-journal.ts:1098-1174`, + * `indexeddb-checkpoint-store.ts:497-596`) and the four already disagree: one + * of them never routes a request error at all, one aborts on a request error + * while two only record it, and one reports a value-less completion as + * CORRUPT_DATA while three report UNAVAILABLE. This module owns the mechanics + * and keeps every one of those choices at the call site. + * + * Like `indexeddb-connection.ts`, it owns no policy: not a store name, not a + * durability default, not a budget criterion, not a failure code. + */ + +import type { Result } from "../../contracts/result.ts"; +import type { IndexedDbTranslate } from "./indexeddb-connection.ts"; + +export type IndexedDbDurability = "default" | "strict" | "relaxed"; + +/** + * The failure half of a transaction context. Split out so helpers that only + * need to report failure (`onIndexedDbRequest`, `walkIndexedDbCursor`) do not + * have to be generic over the transaction's success type. + */ +export type IndexedDbRequestSink = Readonly<{ + /** + * Records the failure and aborts the transaction. The first failure wins. + * This is `indexeddb-runtime.ts:1047-1054`'s `fail`. + */ + fail(failure: Failure): void; + /** + * Records a request-level error **without aborting**: the transaction is left + * to complete or abort on its own, and the recorded error becomes the reported + * failure if it aborts. This is `indexeddb-runtime.ts:1055-1060`'s + * `requestFailed`. + * + * `indexeddb-checkpoint-store.ts:577-588` deliberately aborts instead. It + * keeps doing so by calling `fail(translate({kind:"NATIVE_EXCEPTION", error}))`. + * The kernel does not pick. + */ + requestFailed(error: unknown): void; +}>; + +export type IndexedDbTransactionContext = + IndexedDbRequestSink & + Readonly<{ + /** The first `succeed` wins; later ones are ignored. */ + succeed(value: Value): void; + /** For callers that need `objectStore()`/`index()` directly. */ + readonly transaction: IDBTransaction; + }>; + +export type IndexedDbTransactionInput = Readonly<{ + database: IDBDatabase; + stores: readonly string[]; + mode: "readonly" | "readwrite"; + translate: IndexedDbTranslate; + /** Aborts the transaction; the outcome is `CALLER_ABORT` unless completion won. */ + signal?: AbortSignal; + /** + * `undefined` opens with **no options bag at all**, which is + * `indexeddb-checkpoint-store.ts:512`'s current behavior — not the same as + * `"default"`, which passes `{durability:"default"}`. A named value falls back + * to the no-options form when the engine rejects the bag with a `TypeError`. + */ + durability?: IndexedDbDurability; + queue: ( + transaction: IDBTransaction, + context: IndexedDbTransactionContext, + ) => void; +}>; + +/** How the visitor wants the cursor advanced. */ +export type IndexedDbCursorStep = + | Readonly<{ kind: "CONTINUE" }> + | Readonly<{ kind: "CONTINUE_FROM"; key: IDBValidKey }> + | Readonly<{ + kind: "CONTINUE_PRIMARY"; + key: IDBValidKey; + primaryKey: IDBValidKey; + }> + /** End the walk here; `done` gets `reason: "STOPPED"`. */ + | Readonly<{ kind: "STOP" }> + /** + * The visitor started its own request chain and will call `resume(step)` when + * that chain finishes. Without this the pump is unusable by three of the four + * callers: every walk in `indexeddb-runtime.ts` and `indexeddb-maintenance.ts` + * issues nested requests before advancing (e.g. `L1487-1526`, `L2406-2471`, + * `L1490-1541`). A pump that only understood `CONTINUE` would be the + * too-narrow-to-adopt failure again. + */ + | Readonly<{ kind: "SUSPEND" }>; + +export type IndexedDbBudgetVerdict = "CONTINUE" | "ROW_BUDGET" | "TIME_BUDGET"; + +export type IndexedDbBudget = Readonly<{ + /** + * Checked before each row, with the number of rows already handed to `visit`. + * The kernel counts nothing itself: runtime bounds on rows it deleted + * (`indexeddb-runtime.ts:2384`) while maintenance bounds on rows it scanned + * (`indexeddb-maintenance.ts:823`), so the counter, the clock and the deadline + * all belong to the caller. A clock that cannot be read is a failure rather + * than a `false`, which is what `monotonicClock()` + * (`indexeddb-runtime.ts:2260-2269`) already does. + */ + admit(scannedRows: number): Result; +}>; + +export type IndexedDbCursorVisit = Readonly<{ + cursor: IDBCursorWithValue; + /** Rows handed to `visit` so far, this row included. */ + scannedRows: number; + /** Only meaningful after the visitor returned `SUSPEND`. Idempotent. */ + resume(step: IndexedDbCursorStep): void; +}>; + +export type IndexedDbWalkSummary = Readonly<{ + reason: "EXHAUSTED" | "STOPPED" | "ROW_BUDGET" | "TIME_BUDGET" | "ABORTED"; + scannedRows: number; +}>; + +export type IndexedDbWalkInput = Readonly<{ + request: IDBRequest; + sink: IndexedDbRequestSink; + translate: IndexedDbTranslate; + budget?: IndexedDbBudget; + /** + * Checked at each row. An aborted signal aborts the transaction and ends the + * walk with `reason: "ABORTED"`, which is what `indexeddb-runtime.ts:1375-1382` + * does inline today. + */ + signal?: AbortSignal; + visit: (visit: IndexedDbCursorVisit) => IndexedDbCursorStep; + /** The only success exit. The caller routes it into its own `succeed`. */ + done: (summary: IndexedDbWalkSummary) => void; +}>; + +function succeeded(value: Value): Result { + return Object.freeze({ ok: true as const, value }); +} + +function failed(error: Failure): Result { + return Object.freeze({ ok: false as const, error }); +} + +/** + * The durability fallback on its own, for a caller that manages its own + * transaction. `undefined` omits the options bag entirely. + */ +export function openIndexedDbTransaction( + database: IDBDatabase, + stores: readonly string[], + mode: "readonly" | "readwrite", + durability?: IndexedDbDurability, +): IDBTransaction { + const names = [...stores]; + // Not the same as `{durability:"default"}`: an engine that has never seen the + // options bag treats the two differently, and one caller relies on that. + if (durability === undefined) return database.transaction(names, mode); + try { + return database.transaction(names, mode, { durability }); + } catch (error) { + // Only an engine that does not know the option answers with a TypeError. + // Anything else — a closed connection, an unknown store — is a real error + // and must not be retried into a second, differently shaped failure. + if (error instanceof TypeError) return database.transaction(names, mode); + throw error; + } +} + +/** + * A transaction that completes without `succeed()` is reported through + * `translate({kind:"NO_VALUE_PRODUCED"})`. Three callers map that to + * UNAVAILABLE and `indexeddb-checkpoint-store.ts:541-547` maps it to + * CORRUPT_DATA; the kernel never picks. + */ +export function runIndexedDbTransaction( + input: IndexedDbTransactionInput, +): Promise> { + const { translate } = input; + if (input.signal?.aborted) { + return Promise.resolve(failed(translate({ kind: "CALLER_ABORT" }))); + } + + let transaction: IDBTransaction; + try { + transaction = openIndexedDbTransaction( + input.database, + input.stores, + input.mode, + input.durability, + ); + } catch (error) { + return Promise.resolve(failed(translate({ kind: "NATIVE_EXCEPTION", error }))); + } + + return new Promise>((resolve) => { + let candidate: Result | undefined; + let requestError: unknown; + let hasRequestError = false; + let callerAborted = false; + let settled = false; + + const finish = (result: Result) => { + if (settled) return; + settled = true; + try { + input.signal?.removeEventListener("abort", onCallerAbort); + } catch { + // A hostile signal facade cannot block cleanup. + } + resolve(result); + }; + + function onCallerAbort(): void { + const previous = callerAborted; + callerAborted = true; + try { + transaction.abort(); + } catch { + // CP-4. The transaction may already be durably committed while its + // completion event is still queued. Claiming the abort would report a + // committed mutation as ABORTED, so the claim is withdrawn and the + // transaction's own events decide. + callerAborted = previous; + } + } + + transaction.oncomplete = () => { + finish(candidate ?? failed(translate({ kind: "NO_VALUE_PRODUCED" }))); + }; + transaction.onerror = () => { + // `onabort` is the terminal signal; this only captures the error that a + // request left behind before the transaction unwinds. + if (hasRequestError) return; + requestError = transaction.error; + hasRequestError = true; + }; + transaction.onabort = () => { + if (callerAborted) { + finish(failed(translate({ kind: "CALLER_ABORT" }))); + return; + } + if (candidate && !candidate.ok) { + finish(candidate); + return; + } + // An abort never yields the value a `succeed` recorded: the transaction + // did not commit, so the native error is what happened. + finish( + failed( + translate({ + kind: "NATIVE_EXCEPTION", + error: hasRequestError ? requestError : transaction.error, + }), + ), + ); + }; + input.signal?.addEventListener("abort", onCallerAbort, { once: true }); + + const context: IndexedDbTransactionContext = Object.freeze({ + transaction, + succeed(value) { + candidate ??= succeeded(value); + }, + fail(failure) { + candidate ??= failed(failure); + try { + transaction.abort(); + } catch { + // The transaction is already finished, so no abort event is coming. + // The recorded failure is the outcome rather than a hang. + finish(candidate); + } + }, + requestFailed(error) { + if (!hasRequestError) { + requestError = error; + hasRequestError = true; + } + candidate ??= failed(translate({ kind: "NATIVE_EXCEPTION", error })); + }, + }); + + try { + input.queue(transaction, context); + } catch (error) { + context.fail(translate({ kind: "NATIVE_EXCEPTION", error })); + } + }); +} + +/** + * Wires `onsuccess`/`onerror` in one place. The four copies write this pair by + * hand at roughly 70 sites and `indexeddb-opfs-journal.ts` omits `onerror` + * everywhere, which is how a request-level error there becomes whatever + * `transaction.error` happens to hold. + */ +export function onIndexedDbRequest( + request: IDBRequest, + sink: IndexedDbRequestSink, + onSuccess: (value: Value) => void, +): void { + request.onsuccess = () => { + onSuccess(request.result); + }; + request.onerror = () => { + sink.requestFailed(request.error); + }; +} + +/** + * Drives an open cursor. It reports a native advance failure through `sink` and + * never decides what a finished walk means — `reason` distinguishes a row budget + * from a time budget so a caller can keep reporting `budgetExhausted` exactly as + * it does now (`indexeddb-runtime.ts:2387`). + */ +export function walkIndexedDbCursor( + input: IndexedDbWalkInput, +): void { + const { request, sink, translate } = input; + let scannedRows = 0; + let finished = false; + + const end = (reason: IndexedDbWalkSummary["reason"]) => { + if (finished) return; + finished = true; + input.done(Object.freeze({ reason, scannedRows })); + }; + const abandon = (failure: Failure) => { + if (finished) return; + finished = true; + sink.fail(failure); + }; + + const advance = (action: () => void) => { + try { + action(); + } catch (error) { + abandon(translate({ kind: "NATIVE_EXCEPTION", error })); + } + }; + + const applyStep = ( + cursor: IDBCursorWithValue, + step: IndexedDbCursorStep, + ): void => { + switch (step.kind) { + case "CONTINUE": + advance(() => cursor.continue()); + return; + case "CONTINUE_FROM": + advance(() => cursor.continue(step.key)); + return; + case "CONTINUE_PRIMARY": + advance(() => cursor.continuePrimaryKey(step.key, step.primaryKey)); + return; + case "STOP": + end("STOPPED"); + return; + case "SUSPEND": + // The visitor owns the cursor until it calls `resume`. + return; + default: { + const exhaustive: never = step; + return exhaustive; + } + } + }; + + request.onerror = () => { + if (finished) return; + finished = true; + // No `done`: the walk produced no summary, and the transaction's own + // outcome decides what a failed advance means for this call site. + sink.requestFailed(request.error); + }; + + request.onsuccess = () => { + if (finished) return; + const cursor = request.result; + if (!cursor) { + end("EXHAUSTED"); + return; + } + if (input.signal?.aborted) { + // Aborting through the sink keeps one abort path instead of reaching for + // a transaction the pump was never handed. `done` still runs so the + // caller sees why the walk stopped; the recorded failure outranks any + // value it produces there. + finished = true; + sink.fail(translate({ kind: "CALLER_ABORT" })); + input.done(Object.freeze({ reason: "ABORTED" as const, scannedRows })); + return; + } + if (input.budget) { + const verdict = input.budget.admit(scannedRows); + if (!verdict.ok) { + abandon(verdict.error); + return; + } + if (verdict.value === "ROW_BUDGET" || verdict.value === "TIME_BUDGET") { + end(verdict.value); + return; + } + } + + scannedRows += 1; + let suspended = false; + let resumed = false; + const resume = (step: IndexedDbCursorStep) => { + if (!suspended || resumed || finished) return; + resumed = true; + applyStep(cursor, step); + }; + + let step: IndexedDbCursorStep; + try { + step = input.visit( + Object.freeze({ cursor, scannedRows, resume }), + ); + } catch (error) { + // A visitor defect must not let a partially applied write commit, so it + // aborts rather than merely being recorded. + abandon(translate({ kind: "NATIVE_EXCEPTION", error })); + return; + } + if (step.kind === "SUSPEND") suspended = true; + applyStep(cursor, step); + }; +} diff --git a/src/contracts/cursor-pagination.ts b/src/adapters/query-cache/cursor-pagination-contract.ts similarity index 90% rename from src/contracts/cursor-pagination.ts rename to src/adapters/query-cache/cursor-pagination-contract.ts index 6e9dccb..c0aab34 100644 --- a/src/contracts/cursor-pagination.ts +++ b/src/adapters/query-cache/cursor-pagination-contract.ts @@ -1,4 +1,4 @@ -import type { Result } from "./result.ts"; +import type { Result } from "../../contracts/result.ts"; export type CursorPage = Readonly<{ items: readonly Value[]; diff --git a/src/adapters/query-cache/cursor-pagination-runtime.ts b/src/adapters/query-cache/cursor-pagination-runtime.ts index 3ab66a6..4c74b1c 100644 --- a/src/adapters/query-cache/cursor-pagination-runtime.ts +++ b/src/adapters/query-cache/cursor-pagination-runtime.ts @@ -1,9 +1,9 @@ -import type { Result } from "../../application/result.ts"; +import type { Result } from "../../contracts/result.ts"; import type { CursorPage, CursorPaginationProfile, CursorPaginationRuntime, -} from "../../contracts/cursor-pagination.ts"; +} from "./cursor-pagination-contract.ts"; import { createFailure } from "../../contracts/errors.ts"; import { snapshotExactObject } from "../../contracts/exact-snapshot.ts"; diff --git a/src/adapters/query-cache/index.ts b/src/adapters/query-cache/index.ts new file mode 100644 index 0000000..3ea046e --- /dev/null +++ b/src/adapters/query-cache/index.ts @@ -0,0 +1,26 @@ +export { + createConditionalValidatorStore, + type ConditionalValidatorBinding, + type ConditionalValidatorStore, +} from "./conditional-validator-store.ts"; +export { createCursorPaginationRuntime } from "./cursor-pagination-runtime.ts"; +export type { + CursorPage, + CursorPaginationProfile, + CursorPaginationRuntime, +} from "./cursor-pagination-contract.ts"; +export { + createServerStateScopeRuntime, + type ScopeResetParticipant, + type ServerStateScopeDependencies, +} from "./server-state-scope-runtime.ts"; +export { + createTanStackCacheCoordinator, + type TanStackCacheCoordinatorDependencies, +} from "./tanstack-cache-coordinator.ts"; +export { + createQueryCacheAdapter, + createQueryClient, + QUERY_CACHE_DEFAULTS, + type QueryCacheDependencies, +} from "./tanstack-query-cache.ts"; diff --git a/src/adapters/service-worker/index.ts b/src/adapters/service-worker/index.ts new file mode 100644 index 0000000..6a4774c --- /dev/null +++ b/src/adapters/service-worker/index.ts @@ -0,0 +1,31 @@ +/** + * 이 배럴은 그룹 바깥(bootstrap, tests)을 위한 문이다. 워커 realm 진입점 + * `service-worker-entry.ts`는 이 배럴을 쓰지 않고 파일을 직접 import한다. + * + * 그래서 `tsconfig.service-worker.json`의 `exclude`에 이 파일이 들어 있다. + * 그 설정은 `src/adapters/service-worker` 폴더를 통째로 WebWorker lib로 + * 컴파일하면서 페이지 realm 파일(`service-worker-page-controller.ts`, + * `service-worker-removal.ts`)만 빼는 구조다. 배럴이 제외되지 않으면 그 + * 페이지 realm 파일을 다시 끌어들여 `document`를 찾지 못한다. + * 타입 커버리지는 `tsconfig.app.json`이 이 배럴을 포함하므로 유지된다. + * + * `service-worker-entry.ts`도 여기서 참조하지 않는다. `tsconfig.app.json:18`이 + * 제외한 파일이고, export가 0개이므로 넣을 것도 없다. + */ +export { + createServiceWorkerRuntime, + type WorkerClientLike, + type WorkerRuntimeConfig, + type WorkerScopeLike, +} from "./service-worker-lifecycle.ts"; +export { + createServiceWorkerPageController, + type ActivationBlocker, + type PageControllerDependencies, +} from "./service-worker-page-controller.ts"; +export { + createNonceRegistry, + createServiceWorkerMessage, + parseServiceWorkerMessage, + type ParsedMessage, +} from "./service-worker-protocol.ts"; diff --git a/src/adapters/storage/index.ts b/src/adapters/storage/index.ts new file mode 100644 index 0000000..43e058d --- /dev/null +++ b/src/adapters/storage/index.ts @@ -0,0 +1,12 @@ +/** + * 최상위 storage 배럴은 Web Storage 어댑터만 내보낸다. + * + * `./indexeddb/index.ts`와 `./opfs/index.ts`를 여기서 재수출하지 말 것. + * `scripts/test-browser-file-storage-runtime-removal.ts:23-34`가 그 두 폴더만 + * 삭제한 뒤 잔존 import를 예외로 잡는다 — 재수출하면 제거 드릴이 죽는다. + * 두 서브배럴이 각자 제거 가능한 런타임의 경계다. + */ +export { + createBrowserStorageAdapter, + type BrowserStorageDependencies, +} from "./browser-storage-adapter.ts"; diff --git a/src/adapters/storage/indexeddb/indexeddb-maintenance.ts b/src/adapters/storage/indexeddb/indexeddb-maintenance.ts index 2667384..deada7a 100644 --- a/src/adapters/storage/indexeddb/indexeddb-maintenance.ts +++ b/src/adapters/storage/indexeddb/indexeddb-maintenance.ts @@ -5,6 +5,7 @@ import type { IndexedDbReceiptPruneBatchReceipt, } from "../../../application/ports/browser-file-storage/indexeddb-port.ts"; import type { + BrowserDataFailure, BrowserDataResult, } from "../../../application/ports/browser-file-storage/shared.ts"; import { @@ -12,6 +13,17 @@ import { browserDataFailure, browserDataSuccess, } from "../../browser-file-storage/result.ts"; +import { + openIndexedDbDatabase, + type IndexedDbTranslate, +} from "../../platform/indexeddb-connection.ts"; +import { + openIndexedDbTransaction, + runIndexedDbTransaction, + walkIndexedDbCursor, + type IndexedDbBudget, + type IndexedDbTransactionContext, +} from "../../platform/indexeddb-transaction.ts"; import { mapIndexedDbException } from "./indexeddb-failure.ts"; import { createIndexedDbDatasetBinding, @@ -94,12 +106,6 @@ type PreparedRecord = Readonly<{ measuredBytes: number | undefined; }>; -type TransactionContext = Readonly<{ - succeed(value: Value): void; - fail(result: BrowserDataResult): void; - requestFailed(error: unknown): void; -}>; - const SAFE_IDENTIFIER = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u; const OPAQUE_SHA256_FINGERPRINT = /^[a-f0-9]{64}$/u; const MAX_BATCH_ROWS = 500; @@ -261,6 +267,41 @@ function unavailable(): BrowserDataResult { }); } +function unsupported(): BrowserDataResult { + return browserDataFailure("UNSUPPORTED", "INDEXEDDB_MIGRATE", { + recovery: "ONLINE_ONLY", + }); +} + +/** + * `browserDataFailure` and `mapIndexedDbException` build a `Result`, while the + * kernel's `translate` and `context.fail` want the failure on its own. Both + * only ever build the failure arm, so the branch below is a narrowing rather + * than a claim. + */ +function failureOf(result: BrowserDataResult): BrowserDataFailure { + if (result.ok) { + throw new TypeError("A browser data failure was expected."); + } + return result.error; +} + +function invalidInputFailure(): BrowserDataFailure { + return failureOf(invalidInput()); +} + +function migrationFailure(): BrowserDataFailure { + return failureOf(migrationFailed()); +} + +function unsupportedFailure(): BrowserDataFailure { + return failureOf(unsupported()); +} + +function mappedFailure(error: unknown): BrowserDataFailure { + return failureOf(mapIndexedDbException(error, "INDEXEDDB_MIGRATE")); +} + function defaultNow(): number { return typeof globalThis.performance === "undefined" ? Date.now() @@ -420,6 +461,59 @@ export function createIndexedDbMaintenance( } } + /** + * STO-06. Maintenance keeps `mapIndexedDbException`, which the runtime and + * the OPFS journal share, rather than the checkpoint store's own table: the + * same native error is a different answer in the two families, and unifying + * them is a separate change from moving the mechanics onto the kernel. + * + * One translator covers the whole adapter because the operation label is the + * constant `INDEXEDDB_MIGRATE` here — the runtime needs one per operation. + */ + const translate: IndexedDbTranslate = (cause) => { + switch (cause.kind) { + case "NATIVE_EXCEPTION": + return mappedFailure(cause.error); + case "BLOCKED": + case "BLOCKED_DEADLINE": + return failureOf( + browserDataFailure("BLOCKED", "INDEXEDDB_MIGRATE", { + retryable: true, + recovery: "RELOAD_OTHER_CONTEXTS", + }), + ); + case "CALLER_ABORT": + return failureOf( + browserDataFailure("ABORTED", "INDEXEDDB_MIGRATE"), + ); + case "CLOSED": + case "NO_VALUE_PRODUCED": + // A transaction that committed without producing a value is retried, + // not reconciled. `CLOSED` cannot reach here — maintenance opens a + // connection per batch instead of holding a cached handle — and is + // mapped alongside it so the union stays total. + return failureOf(unavailable()); + case "UPGRADE_REJECTED": + // Maintenance owns no schema. Any upgrade means the database is not + // the one this batch was configured against. + return migrationFailure(); + case "ADMISSION_REJECTED": + return cause.detail === "POLICY" + ? failureOf( + browserDataFailure("POLICY_REJECTED", "INDEXEDDB_MIGRATE", { + recovery: storagePolicySnapshot.unavailableFallback, + }), + ) + : migrationFailure(); + case "UNSUPPORTED": + return unsupportedFailure(); + default: { + const exhaustive: never = cause; + return exhaustive; + } + } + }; + function validBatchInput( input: IndexedDbMaintenanceBatchInput, ): boolean { @@ -436,173 +530,76 @@ export function createIndexedDbMaintenance( ): Promise> { const cancelled = abortedResult(signal, "INDEXEDDB_MIGRATE"); if (cancelled) return Promise.resolve(cancelled); - if (!factory) { - return Promise.resolve( - browserDataFailure("UNSUPPORTED", "INDEXEDDB_MIGRATE", { - recovery: "ONLINE_ONLY", - }), - ); - } + if (!factory) return Promise.resolve(unsupported()); - return new Promise>((resolve) => { - let request: IDBOpenDBRequest; - try { - request = factory.open( - databaseName, - dependencies.schemaVersion, - ); - } catch (error) { - resolve(mapIndexedDbException(error, "INDEXEDDB_MIGRATE")); - return; - } - - let settled = false; - let unexpectedUpgrade = false; - const finish = (result: BrowserDataResult) => { - if (settled) return; - settled = true; - signal?.removeEventListener("abort", onAbort); - resolve(result); - }; - function onAbort(): void { - try { - request.transaction?.abort(); - } catch { - // A pending non-upgrade open request cannot be cancelled. - } - finish(browserDataFailure("ABORTED", "INDEXEDDB_MIGRATE")); - } - signal?.addEventListener("abort", onAbort, { once: true }); - - request.onupgradeneeded = () => { - unexpectedUpgrade = true; - try { - request.transaction?.abort(); - } catch { - // The error handler below owns the closed failure result. - } - }; - request.onblocked = () => { - finish( - browserDataFailure("BLOCKED", "INDEXEDDB_MIGRATE", { - retryable: true, - recovery: "RELOAD_OTHER_CONTEXTS", - }), - ); - }; - request.onerror = () => { - finish( - unexpectedUpgrade - ? migrationFailed() - : mapIndexedDbException( - request.error, - "INDEXEDDB_MIGRATE", - ), - ); - }; - request.onsuccess = () => { - const database = request.result; - if (settled) { - database.close(); - return; - } - if ( - !database.objectStoreNames.contains( - dependencies.recordStore, - ) || - !database.objectStoreNames.contains( - dependencies.governanceStore, - ) || - !database.objectStoreNames.contains( - dependencies.retentionStore, - ) || - !database.objectStoreNames.contains( - dependencies.checkpointStore, - ) || - !database.objectStoreNames.contains( - dependencies.idempotencyStore, - ) - ) { - database.close(); - finish(migrationFailed()); - return; + return openIndexedDbDatabase({ + factory, + databaseName, + version: dependencies.schemaVersion, + translate, + signal, + // No `blockedTimeoutMs`, and therefore no `timers`. The blocked event is + // terminal for maintenance: a batch is an opt-in background pass, so + // hanging it for a deadline in the hope another context goes away costs + // more than reporting BLOCKED and letting the caller retry. + // + // No `upgrade` either. The kernel reads an omitted callback as "any + // upgrade is unexpected" and rejects it, which is what maintenance has + // always done: it migrates records under a schema somebody else owns and + // must never create or change one. + admit: async (database) => { + for (const store of [ + dependencies.recordStore, + dependencies.governanceStore, + dependencies.retentionStore, + dependencies.checkpointStore, + dependencies.idempotencyStore, + ]) { + if (!database.objectStoreNames.contains(store)) { + return { kind: "REJECT", detail: "STORE" }; + } } try { - const transaction = database.transaction( - dependencies.idempotencyStore, + openIndexedDbTransaction( + database, + [dependencies.idempotencyStore], "readonly", - ); - transaction + ) .objectStore(dependencies.idempotencyStore) .index(dependencies.idempotencyExpiryIndex); } catch { - database.close(); - finish(migrationFailed()); - return; + return { kind: "REJECT", detail: "INDEX" }; } + // Maintenance never holds the connection past a batch, so the listener + // belongs here rather than on a cached handle: `admit` runs on the + // successful open path only, which is exactly the window the batch + // owns the connection for. database.onversionchange = () => database.close(); - void (async () => { - const binding = await verifyIndexedDbDatasetBinding( - database, - dependencies.governanceStore, - expectedBinding, - signal, - ); - if (!binding.ok) { - database.close(); - if (!settled) { - finish( - binding.reason === "ABORTED" - ? browserDataFailure( - "ABORTED", - "INDEXEDDB_MIGRATE", - ) - : binding.reason === "NATIVE_ERROR" - ? mapIndexedDbException( - binding.error, - "INDEXEDDB_MIGRATE", - ) - : browserDataFailure( - "POLICY_REJECTED", - "INDEXEDDB_MIGRATE", - { - recovery: - storagePolicySnapshot.unavailableFallback, - }, - ), - ); - } - return; - } - if (settled) { - database.close(); - return; - } - finish(browserDataSuccess(database)); - })(); - }; + const binding = await verifyIndexedDbDatasetBinding( + database, + dependencies.governanceStore, + expectedBinding, + signal, + ); + if (binding.ok) return { kind: "ADMIT" }; + return binding.reason === "ABORTED" + ? { kind: "FAIL", cause: { kind: "CALLER_ABORT" } } + : binding.reason === "NATIVE_ERROR" + ? { + kind: "FAIL", + cause: { kind: "NATIVE_EXCEPTION", error: binding.error }, + } + : { kind: "REJECT", detail: "POLICY" }; + }, }); } - function createTransaction( - database: IDBDatabase, - stores: readonly string[], - mode: "readonly" | "readwrite", - ): IDBTransaction { - const durability = - mode === "readonly" - ? dependencies.durability?.read ?? "default" - : dependencies.durability?.write ?? "strict"; - try { - return database.transaction([...stores], mode, { durability }); - } catch (error) { - if (error instanceof TypeError) { - return database.transaction([...stores], mode); - } - throw error; - } - } - + /** + * Durability is named explicitly on both sides because maintenance rewrites + * records: a write that is only queued when the tab goes away would leave a + * checkpoint claiming rows that were never stored. The kernel falls back to + * the no-options form on an engine that rejects the bag. + */ function runTransaction( database: IDBDatabase, stores: readonly string[], @@ -610,97 +607,20 @@ export function createIndexedDbMaintenance( signal: AbortSignal | undefined, queue: ( transaction: IDBTransaction, - context: TransactionContext, + context: IndexedDbTransactionContext, ) => void, ): Promise> { - const cancelled = abortedResult(signal, "INDEXEDDB_MIGRATE"); - if (cancelled) return Promise.resolve(cancelled); - - let transaction: IDBTransaction; - try { - transaction = createTransaction(database, stores, mode); - } catch (error) { - return Promise.resolve( - mapIndexedDbException(error, "INDEXEDDB_MIGRATE"), - ); - } - - return new Promise>((resolve) => { - let candidate: BrowserDataResult | undefined; - let requestError: unknown; - let callerAborted = false; - let settled = false; - - const finish = (result: BrowserDataResult) => { - if (settled) return; - settled = true; - signal?.removeEventListener("abort", onAbort); - resolve(result); - }; - const abortTransaction = () => { - try { - transaction.abort(); - } catch { - // Completion or a prior abort already owns the result. - } - }; - function onAbort(): void { - callerAborted = true; - abortTransaction(); - } - - transaction.oncomplete = () => { - finish(candidate ?? unavailable()); - }; - transaction.onerror = () => { - requestError ??= transaction.error; - }; - transaction.onabort = () => { - if (callerAborted) { - finish( - browserDataFailure("ABORTED", "INDEXEDDB_MIGRATE"), - ); - return; - } - if (candidate && !candidate.ok) { - finish(candidate); - return; - } - finish( - mapIndexedDbException( - requestError ?? transaction.error, - "INDEXEDDB_MIGRATE", - ), - ); - }; - signal?.addEventListener("abort", onAbort, { once: true }); - - const context: TransactionContext = Object.freeze({ - succeed(value) { - if (!candidate) candidate = browserDataSuccess(value); - }, - fail(result) { - if (!candidate) candidate = result; - abortTransaction(); - }, - requestFailed(error) { - requestError ??= error; - if (!candidate) { - candidate = mapIndexedDbException( - error, - "INDEXEDDB_MIGRATE", - ); - } - }, - }); - - try { - queue(transaction, context); - } catch (error) { - context.fail( - mapIndexedDbException(error, "INDEXEDDB_MIGRATE"), - ); - } + return runIndexedDbTransaction({ + database, + stores, + mode, + translate, + signal, + durability: + mode === "readonly" + ? dependencies.durability?.read ?? "default" + : dependencies.durability?.write ?? "strict", + queue, }); } @@ -732,7 +652,7 @@ export function createIndexedDbMaintenance( dependencies.checkpointKey, ) ) { - context.fail(migrationFailed()); + context.fail(migrationFailure()); return; } const persisted = request.result; @@ -777,85 +697,69 @@ export function createIndexedDbMaintenance( true, ); } catch { - context.fail(invalidInput()); + context.fail(invalidInputFailure()); return; } if (checkpoint.effective.lastKey !== null && !query) { - context.fail( - browserDataFailure( - "UNSUPPORTED", - "INDEXEDDB_MIGRATE", - { recovery: "ONLINE_ONLY" }, - ), - ); + context.fail(unsupportedFailure()); return; } const rows: ScannedRecord[] = []; - const request = transaction - .objectStore(dependencies.recordStore) - .openCursor(query); - request.onerror = () => context.requestFailed(request.error); - request.onsuccess = () => { - if (input.signal?.aborted) { - try { - transaction.abort(); - } catch { - // The transaction event decides the abort/complete race. + // The scan bounds on rows it read, so the counter the kernel offers is + // the right one here. The time check comes first so a batch that ran + // out of both answers `budgetExhausted` the way it does today. + const budget: IndexedDbBudget = { + admit: (scannedRows) => { + const currentTime = clock(); + if (!currentTime.ok) return currentTime; + if (currentTime.value >= deadline) { + return browserDataSuccess("TIME_BUDGET" as const); } - return; - } - const cursor = request.result; - if (!cursor) { - context.succeed({ - rows: Object.freeze(rows), - reachedEnd: true, - budgetExhausted: false, - }); - return; - } - const currentTime = clock(); - if (!currentTime.ok) { - context.fail(currentTime); - return; - } - if ( - rows.length >= input.maxRows || - currentTime.value >= deadline - ) { - context.succeed({ - rows: Object.freeze(rows), - reachedEnd: false, - budgetExhausted: - currentTime.value >= deadline, - }); - return; - } - if (!isStoredRecord(cursor.value)) { - context.fail(migrationFailed()); - return; - } - if ( - cursor.value.codecVersion > - dependencies.migrationPolicy.targetCodecVersion - ) { - context.fail(migrationFailed()); - return; - } - rows.push({ - key: cursor.value.key, - codecVersion: cursor.value.codecVersion, - revision: cursor.value.revision, - payload: cursor.value.payload, - }); - try { - cursor.continue(); - } catch (error) { - context.fail( - mapIndexedDbException(error, "INDEXEDDB_MIGRATE"), + return browserDataSuccess( + scannedRows >= input.maxRows + ? ("ROW_BUDGET" as const) + : ("CONTINUE" as const), ); - } + }, }; + walkIndexedDbCursor({ + request: transaction + .objectStore(dependencies.recordStore) + .openCursor(query), + sink: context, + translate, + budget, + signal: input.signal, + visit: ({ cursor }) => { + if ( + !isStoredRecord(cursor.value) || + cursor.value.codecVersion > + dependencies.migrationPolicy.targetCodecVersion + ) { + context.fail(migrationFailure()); + // `fail` aborts, so the walk has nowhere to go. Suspending + // without ever resuming says that without asking the pump for + // another row or claiming a summary the scan never reached. + return { kind: "SUSPEND" }; + } + rows.push({ + key: cursor.value.key, + codecVersion: cursor.value.codecVersion, + revision: cursor.value.revision, + payload: cursor.value.payload, + }); + return { kind: "CONTINUE" }; + }, + done: (summary) => { + if (summary.reason === "ABORTED") return; + context.succeed({ + rows: Object.freeze(rows), + reachedEnd: summary.reason === "EXHAUSTED", + budgetExhausted: summary.reason === "TIME_BUDGET", + }); + }, + }); }, ); } @@ -1023,9 +927,7 @@ export function createIndexedDbMaintenance( try { request = checkpoints.put(stored); } catch (error) { - context.fail( - mapIndexedDbException(error, "INDEXEDDB_MIGRATE"), - ); + context.fail(mappedFailure(error)); return; } request.onerror = () => @@ -1057,7 +959,7 @@ export function createIndexedDbMaintenance( const currentTime = clock(); if (!currentTime.ok) { // A broken clock aborts rather than committing an unbounded batch. - context.fail(currentTime); + context.fail(currentTime.error); return; } if (currentTime.value >= deadline) { @@ -1069,9 +971,7 @@ export function createIndexedDbMaintenance( try { request = records.get(preparedRecord.source.key); } catch (error) { - context.fail( - mapIndexedDbException(error, "INDEXEDDB_MIGRATE"), - ); + context.fail(mappedFailure(error)); return; } request.onerror = () => @@ -1091,7 +991,7 @@ export function createIndexedDbMaintenance( preparedRecord.source.key, ) ) { - context.fail(migrationFailed()); + context.fail(migrationFailure()); return; } if ( @@ -1123,7 +1023,7 @@ export function createIndexedDbMaintenance( !preparedRecord.needsMigration || preparedRecord.measuredBytes === undefined ) { - context.fail(migrationFailed()); + context.fail(migrationFailure()); return; } const measuredBytes = preparedRecord.measuredBytes; @@ -1137,7 +1037,7 @@ export function createIndexedDbMaintenance( live.key, ) ) { - context.fail(migrationFailed()); + context.fail(migrationFailure()); return; } const previousSidecar = sidecarRequest.result; @@ -1152,7 +1052,7 @@ export function createIndexedDbMaintenance( budgetRequest.result.usedBytes < previousSidecar.measuredBytes ) { - context.fail(migrationFailed()); + context.fail(migrationFailure()); return; } const usedBytes = @@ -1165,7 +1065,7 @@ export function createIndexedDbMaintenance( usedBytes > storagePolicySnapshot.hardBudgetBytes ) { - context.fail(migrationFailed()); + context.fail(migrationFailure()); return; } const writeRequest = records.put({ @@ -1221,7 +1121,7 @@ export function createIndexedDbMaintenance( dependencies.checkpointKey, ) ) { - context.fail(migrationFailed()); + context.fail(migrationFailure()); return; } liveCheckpoint = checkpointRequest.result; @@ -1412,134 +1312,106 @@ export function createIndexedDbMaintenance( let range: IDBKeyRange; try { if (!keyRange) { - context.fail( - browserDataFailure( - "UNSUPPORTED", - "INDEXEDDB_MIGRATE", - { recovery: "ONLINE_ONLY" }, - ), - ); + context.fail(unsupportedFailure()); return; } range = keyRange.upperBound(cutoff.value); } catch { - context.fail(invalidInput()); + context.fail(invalidInputFailure()); return; } - const request = store - .index(dependencies.idempotencyExpiryIndex) - .openCursor(range); - let scannedRows = 0; let deletedRows = 0; - - const succeed = ( - state: "MORE" | "COMPLETE", - budgetExhausted: boolean, - ) => { - context.succeed( - Object.freeze({ - state, - scannedRows, - deletedRows, - budgetExhausted, - }), - ); - }; - - request.onerror = () => - context.requestFailed(request.error); - request.onsuccess = () => { - if (input.signal?.aborted) { - try { - transaction.abort(); - } catch { - // The transaction event owns the completion race. + // The prune bounds on rows it deleted, not on rows it read, so the + // counter stays here while the kernel counts scanned rows for the + // receipt. A row past the cutoff is corrupt data, not a stop + // condition, so the walk never reports STOPPED. + const budget: IndexedDbBudget = { + admit: () => { + const currentTime = clock(); + if (!currentTime.ok) return currentTime; + if (currentTime.value >= deadline) { + return browserDataSuccess("TIME_BUDGET" as const); } - return; - } - const cursor = request.result; - if (!cursor) { - succeed("COMPLETE", false); - return; - } - const currentTime = clock(); - if (!currentTime.ok) { - context.fail(currentTime); - return; - } - if ( - deletedRows >= input.maxRows || - currentTime.value >= deadline - ) { - succeed( - "MORE", - currentTime.value >= deadline, + return browserDataSuccess( + deletedRows >= input.maxRows + ? ("ROW_BUDGET" as const) + : ("CONTINUE" as const), ); - return; - } - if ( - !isStoredReceipt(cursor.value) || - cursor.value.idempotencyKey !== - String(cursor.primaryKey) || - cursor.value.expiresAtEpochMs > cutoff.value - ) { - context.fail(migrationFailed()); - return; - } - scannedRows += 1; - let deleteRequest: IDBRequest; - try { - deleteRequest = store.delete( - cursor.primaryKey, - ); - } catch (error) { - context.fail( - mapIndexedDbException( - error, - "INDEXEDDB_MIGRATE", - ), - ); - return; - } - deleteRequest.onerror = () => - context.requestFailed(deleteRequest.error); - deleteRequest.onsuccess = () => { - const budgetRequest = governance.get( - INDEXEDDB_DATASET_BUDGET_KEY, - ); - budgetRequest.onerror = () => - context.requestFailed(budgetRequest.error); - budgetRequest.onsuccess = () => { - if ( - !isStoredDatasetBudget(budgetRequest.result) || - budgetRequest.result.receiptCount < 1 - ) { - context.fail(migrationFailed()); - return; - } - const budgetWrite = governance.put({ - ...budgetRequest.result, - receiptCount: - budgetRequest.result.receiptCount - 1, - } satisfies StoredDatasetBudget); - budgetWrite.onerror = () => - context.requestFailed(budgetWrite.error); - budgetWrite.onsuccess = () => { - deletedRows += 1; - try { - cursor.continue(); - } catch (error) { - context.fail( - mapIndexedDbException( - error, - "INDEXEDDB_MIGRATE", - ), - ); + }, + }; + walkIndexedDbCursor({ + request: store + .index(dependencies.idempotencyExpiryIndex) + .openCursor(range), + sink: context, + translate, + budget, + signal: input.signal, + visit: ({ cursor, resume }) => { + if ( + !isStoredReceipt(cursor.value) || + cursor.value.idempotencyKey !== + String(cursor.primaryKey) || + cursor.value.expiresAtEpochMs > cutoff.value + ) { + context.fail(migrationFailure()); + return { kind: "SUSPEND" }; + } + let deleteRequest: IDBRequest; + try { + deleteRequest = store.delete(cursor.primaryKey); + } catch (error) { + context.fail(mappedFailure(error)); + return { kind: "SUSPEND" }; + } + deleteRequest.onerror = () => + context.requestFailed(deleteRequest.error); + deleteRequest.onsuccess = () => { + const budgetRequest = governance.get( + INDEXEDDB_DATASET_BUDGET_KEY, + ); + budgetRequest.onerror = () => + context.requestFailed(budgetRequest.error); + budgetRequest.onsuccess = () => { + if ( + !isStoredDatasetBudget(budgetRequest.result) || + budgetRequest.result.receiptCount < 1 + ) { + context.fail(migrationFailure()); + return; } + const budgetWrite = governance.put({ + ...budgetRequest.result, + receiptCount: + budgetRequest.result.receiptCount - 1, + } satisfies StoredDatasetBudget); + budgetWrite.onerror = () => + context.requestFailed(budgetWrite.error); + budgetWrite.onsuccess = () => { + deletedRows += 1; + resume({ kind: "CONTINUE" }); + }; }; }; - }; - }; + // The receipt is only counted once its whole delete chain + // commits, so the cursor stays parked until `resume`. + return { kind: "SUSPEND" }; + }, + done: (summary) => { + if (summary.reason === "ABORTED") return; + context.succeed( + Object.freeze({ + state: + summary.reason === "EXHAUSTED" + ? ("COMPLETE" as const) + : ("MORE" as const), + scannedRows: summary.scannedRows, + deletedRows, + budgetExhausted: summary.reason === "TIME_BUDGET", + }), + ); + }, + }); }, ); return observeResult( diff --git a/src/adapters/storage/indexeddb/indexeddb-runtime.ts b/src/adapters/storage/indexeddb/indexeddb-runtime.ts index 3d29f99..1a1e3c0 100644 --- a/src/adapters/storage/indexeddb/indexeddb-runtime.ts +++ b/src/adapters/storage/indexeddb/indexeddb-runtime.ts @@ -12,6 +12,7 @@ import type { IndexedDbWriteReceipt, } from "../../../application/ports/browser-file-storage/indexeddb-port.ts"; import type { + BrowserDataFailure, BrowserDataOperation, BrowserDataResult, } from "../../../application/ports/browser-file-storage/shared.ts"; @@ -20,6 +21,20 @@ import { browserDataFailure, browserDataSuccess, } from "../../browser-file-storage/result.ts"; +import { snapshotAbortTimers } from "../../platform/abortable-operation.ts"; +import { + createIndexedDbConnection, + openIndexedDbDatabase, + type IndexedDbTranslate, +} from "../../platform/indexeddb-connection.ts"; +import { + runIndexedDbTransaction, + walkIndexedDbCursor, + type IndexedDbBudget, + type IndexedDbCursorStep, + type IndexedDbCursorVisit, + type IndexedDbTransactionContext, +} from "../../platform/indexeddb-transaction.ts"; import { mapIndexedDbException } from "./indexeddb-failure.ts"; import { createIndexedDbDatasetBinding, @@ -39,7 +54,6 @@ import type { IndexedDbObservation, IndexedDbQueryPlan, IndexedDbRuntimeDependencies, - IndexedDbScheduler, } from "./indexeddb-types.ts"; type StoredRecord = Readonly<{ @@ -82,11 +96,10 @@ type ReceiptLookup = result: BrowserDataResult; }>; -type TransactionContext = Readonly<{ - succeed(value: Value): void; - fail(result: BrowserDataResult): void; - requestFailed(error: unknown): void; -}>; +type TransactionContext = IndexedDbTransactionContext< + Value, + BrowserDataFailure +>; const SAFE_DATABASE_NAME = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/u; const OPAQUE_SHA256_FINGERPRINT = /^[a-f0-9]{64}$/u; @@ -105,17 +118,6 @@ const MAX_MEASURED_RECORD_BYTES = 2_147_483_647; const MAX_QUERY_SCANNED_ROWS = 5_000; const MAX_IDEMPOTENCY_RECEIPTS = 1_000_000; -function defaultScheduler(): IndexedDbScheduler { - return Object.freeze({ - setTimeout: (callback, milliseconds) => - globalThis.setTimeout(callback, milliseconds), - clearTimeout: (handle) => - globalThis.clearTimeout( - handle as ReturnType, - ), - }); -} - function countBucket(count: number): IndexedDbCountBucket { if (count <= 0) return "0"; if (count === 1) return "1"; @@ -403,6 +405,43 @@ function unavailable( }); } +/** + * The kernel's `translate` and `context.fail` take the failure on its own while + * every helper above builds a whole `Result`. All of them only ever build the + * failure arm, so the branch below is a narrowing rather than a claim. + */ +function failureOf(result: BrowserDataResult): BrowserDataFailure { + if (result.ok) { + throw new TypeError("A browser data failure was expected."); + } + return result.error; +} + +function mappedFailure( + error: unknown, + operation: BrowserDataOperation, +): BrowserDataFailure { + return failureOf(mapIndexedDbException(error, operation)); +} + +function corruptFailure( + operation: BrowserDataOperation, +): BrowserDataFailure { + return failureOf(corruptData(operation)); +} + +function conflictFailure( + operation: BrowserDataOperation, +): BrowserDataFailure { + return failureOf(readwriteConflict(operation)); +} + +function invalidFailure( + operation: BrowserDataOperation, +): BrowserDataFailure { + return failureOf(invalidInput(operation)); +} + export function createIndexedDbRuntime( inputDependencies: IndexedDbRuntimeDependencies, ): IndexedDbRepositoryPort { @@ -572,7 +611,21 @@ export function createIndexedDbRuntime( (typeof globalThis.IDBKeyRange === "undefined" ? undefined : globalThis.IDBKeyRange); - const scheduler = dependencies.scheduler ?? defaultScheduler(); + // X-AUDIT-02. The timer callables are captured once, bound to their receiver, + // so replacing a global after composition cannot change how an open already + // in flight is bounded. The kernel throws at construction if a positive + // deadline arrives without them. + const timers = snapshotAbortTimers( + dependencies.scheduler ?? { + setTimeout: (callback: () => void, milliseconds: number): unknown => + globalThis.setTimeout(callback, milliseconds), + clearTimeout: (handle: unknown): void => { + globalThis.clearTimeout( + handle as ReturnType, + ); + }, + }, + ); const blockedTimeoutMs = dependencies.blockedTimeoutMs ?? 10_000; const nowEpochMilliseconds = dependencies.nowEpochMilliseconds ?? Date.now; @@ -589,11 +642,6 @@ export function createIndexedDbRuntime( kind: "CLOSED", reason: "NOT_OPENED", }); - let connection: IDBDatabase | null = null; - let openingRequest: IDBOpenDBRequest | null = null; - let openingPromise: Promise> | null = null; - let activeOpeningGeneration: object | null = null; - let cancelPendingOpen: (() => void) | null = null; let disposed = false; function observe(event: IndexedDbObservation): void { @@ -634,215 +682,154 @@ export function createIndexedDbRuntime( } } - function handleVersionChange(db: IDBDatabase): void { - if (connection !== db || disposed) return; - connection = null; - db.close(); - const next = Object.freeze({ - kind: "CLOSED" as const, - reason: "VERSION_CHANGE" as const, - }); - updateStatus(next); - try { - dependencies.onVersionChange?.(next); - } catch { - // Connection closure is independent from the notification callback. - } - } - - function handleForcedClose(db: IDBDatabase): void { - if (connection !== db || disposed) return; - connection = null; - updateStatus({ kind: "CLOSED", reason: "FORCED" }); - } - - function waitForOpeningAttempt( - attempt: Promise>, - signal: AbortSignal | undefined, - ): Promise> { - const operation = "INDEXEDDB_OPEN" as const; - const cancelled = abortedResult(signal, operation); - if (cancelled) return Promise.resolve(cancelled); - - return new Promise>((resolve) => { - let callerSettled = false; - const finishCaller = (result: BrowserDataResult) => { - if (callerSettled) return; - callerSettled = true; - signal?.removeEventListener("abort", onAbort); - resolve(result); - }; - function onAbort(): void { - finishCaller(browserDataFailure("ABORTED", operation)); - } - - signal?.addEventListener("abort", onAbort, { once: true }); - void attempt.then(finishCaller, () => finishCaller(unavailable(operation))); - }); - } - - function startOpeningAttempt( - availableFactory: IDBFactory, - generation: object, - ): Promise> { - const operation = "INDEXEDDB_OPEN" as const; - - return new Promise>((resolve) => { - const settleNativeRequest = () => { - if (activeOpeningGeneration !== generation) return; - activeOpeningGeneration = null; - openingRequest = null; - openingPromise = null; - cancelPendingOpen = null; - }; - let request: IDBOpenDBRequest; - try { - request = availableFactory.open( - databaseName, - dependencies.schemaVersion, - ); - } catch (error) { - const result = mapIndexedDbException(error, operation); - updateStatus({ kind: "CLOSED", reason: "NOT_OPENED" }); - resolve(result); - queueMicrotask(settleNativeRequest); - return; - } - - openingRequest = request; - let requestSettled = false; - let migrationFailed = false; - let policyBindingRejected = false; - let appliedMigrations = 0; - let blockedTimer: unknown; - - const clearBlockedTimer = () => { - if (blockedTimer !== undefined) { - scheduler.clearTimeout(blockedTimer); - blockedTimer = undefined; - } - }; - const finishOpeningAttempt = (result: BrowserDataResult) => { - if (requestSettled) return; - requestSettled = true; - clearBlockedTimer(); - resolve(result); - }; - const settleLateRequest = () => { - settleNativeRequest(); - }; - const abortUpgrade = () => { - try { - request.transaction?.abort(); - } catch { - // An open request cannot otherwise be cancelled. - } - }; - cancelPendingOpen = () => { - abortUpgrade(); - finishOpeningAttempt(unavailable(operation)); - }; - - request.onupgradeneeded = (event) => { - const transaction = request.transaction; - if (!transaction || event.newVersion === null) { - migrationFailed = true; - abortUpgrade(); - return; - } - try { - appliedMigrations = applyIndexedDbMigrations( - request.result, - transaction, - event.oldVersion, - event.newVersion, - dependencies.migrations, - ); - queueIndexedDbUpgradeBinding( - transaction, - dependencies.governanceStore, - expectedBinding, - event.oldVersion, - () => { - policyBindingRejected = true; - }, - ); - } catch { - migrationFailed = true; - abortUpgrade(); - } - }; - - request.onblocked = (event) => { - updateStatus({ - kind: "BLOCKED", - currentVersion: event.oldVersion, - targetVersion: event.newVersion ?? dependencies.schemaVersion, - }); - observe({ - operation, - outcome: "BLOCKED", - schemaVersion: dependencies.schemaVersion, - countBucket: "0", - failureCode: "BLOCKED", - }); - if (blockedTimer === undefined) { - blockedTimer = scheduler.setTimeout(() => { - finishOpeningAttempt( - browserDataFailure("BLOCKED", operation, { - retryable: true, - recovery: "RELOAD_OTHER_CONTEXTS", - }), - ); - }, blockedTimeoutMs); - } - }; - - request.onerror = () => { - settleLateRequest(); - try { - request.result.close(); - } catch { - // Failed native open requests do not expose a result. - } - if (!disposed) { - updateStatus({ kind: "CLOSED", reason: "NOT_OPENED" }); - } - if (migrationFailed) { - const result = browserDataFailure( - "MIGRATION_FAILED", - "INDEXEDDB_MIGRATE", - { recovery: "READ_ONLY" }, - ); - observeResult("INDEXEDDB_MIGRATE", result); - finishOpeningAttempt(result); - return; - } - if (policyBindingRejected) { - finishOpeningAttempt( - browserDataFailure("POLICY_REJECTED", operation, { - recovery: storagePolicySnapshot.unavailableFallback, + /** + * STO-06. The runtime keeps `mapIndexedDbException`, which maintenance and + * the OPFS journal share, rather than the checkpoint store's own table: the + * same native error is a different answer in the two families, and unifying + * them is a separate change from moving the mechanics onto the kernel. + * + * A translator per operation, because a read, a write and an open carry + * different labels. `CLOSED` is mapped explicitly: closing the handle while + * an open is in flight has always ended that open with UNAVAILABLE, and + * letting it fall in with the caller's own abort would change the code a + * caller sees when `close()` races its `open()`. + */ + function translateFor( + operation: BrowserDataOperation, + ): IndexedDbTranslate { + return (cause) => { + switch (cause.kind) { + case "NATIVE_EXCEPTION": + return mappedFailure(cause.error, operation); + case "BLOCKED": + case "BLOCKED_DEADLINE": + // The same answer whether the blocked event is itself terminal (a + // `blockedTimeoutMs` of 0) or a deadline ran out: the conflict that + // holds the old version open is the same one. + return failureOf( + browserDataFailure("BLOCKED", operation, { + retryable: true, + recovery: "RELOAD_OTHER_CONTEXTS", }), ); - return; + case "CALLER_ABORT": + return failureOf(browserDataFailure("ABORTED", operation)); + case "CLOSED": + case "NO_VALUE_PRODUCED": + // A closed handle and a transaction that committed without producing + // a value are both UNAVAILABLE here, and both are retried rather + // than reconciled. + return failureOf(unavailable(operation)); + case "UPGRADE_REJECTED": + // Any rejected upgrade is a migration failure, and it is labelled + // against INDEXEDDB_MIGRATE rather than the operation that asked to + // open. + return failureOf( + browserDataFailure("MIGRATION_FAILED", "INDEXEDDB_MIGRATE", { + recovery: "READ_ONLY", + }), + ); + case "ADMISSION_REJECTED": + // Only the runtime knows whether a rejected admission was the + // governance binding or a store the schema never created; the kernel + // keeps `detail` opaque so the two keep their own codes. + return cause.detail === "POLICY" + ? failureOf( + browserDataFailure("POLICY_REJECTED", operation, { + recovery: storagePolicySnapshot.unavailableFallback, + }), + ) + : mappedFailure(cause.detail, "INDEXEDDB_MIGRATE"); + case "UNSUPPORTED": + return failureOf( + browserDataFailure("UNSUPPORTED", operation, { + recovery: "ONLINE_ONLY", + }), + ); + default: { + const exhaustive: never = cause; + return exhaustive; } - finishOpeningAttempt(mapIndexedDbException(request.error, operation)); - }; + } + }; + } - request.onsuccess = () => { - const opened = request.result; - void (async () => { - if (requestSettled || disposed) { - settleLateRequest(); - opened.close(); - if (!disposed) { - updateStatus({ kind: "CLOSED", reason: "NOT_OPENED" }); - } - return; + /** + * The handle owns the cached connection, the single-flight open and the + * `versionchange`/`close` invalidation this file used to wire by hand. The + * status broadcast stays here because it is the runtime's own contract: the + * kernel never learns what OPENING, BLOCKED or READY mean. + */ + const connection = createIndexedDbConnection({ + translate: translateFor("INDEXEDDB_OPEN"), + open: (signal) => { + const operation = "INDEXEDDB_OPEN" as const; + if (factory === undefined) { + return Promise.resolve( + browserDataFailure("UNSUPPORTED", operation, { + recovery: "ONLINE_ONLY", + }), + ); + } + // Per attempt rather than per caller: concurrent callers join one open, + // so the migration count and the binding verdict belong to the attempt. + let appliedMigrations = 0; + let policyBindingRejected = false; + updateStatus({ + kind: "OPENING", + targetVersion: dependencies.schemaVersion, + }); + return openIndexedDbDatabase({ + factory, + databaseName, + version: dependencies.schemaVersion, + translate: translateFor(operation), + signal, + blockedTimeoutMs, + timers, + onBlocked: (event) => { + updateStatus({ + kind: "BLOCKED", + currentVersion: event.oldVersion, + targetVersion: event.newVersion ?? dependencies.schemaVersion, + }); + observe({ + operation, + outcome: "BLOCKED", + schemaVersion: dependencies.schemaVersion, + countBucket: "0", + failureCode: "BLOCKED", + }); + }, + upgrade: ({ database, transaction, oldVersion, newVersion }) => { + try { + appliedMigrations = applyIndexedDbMigrations( + database, + transaction, + oldVersion, + newVersion, + dependencies.migrations, + ); + queueIndexedDbUpgradeBinding( + transaction, + dependencies.governanceStore, + expectedBinding, + oldVersion, + () => { + policyBindingRejected = true; + }, + ); + } catch { + // No detail: a migration that threw and a versionchange this + // runtime never planned are the same MIGRATION_FAILED answer. + return { kind: "REJECTED" }; } + return { kind: "APPLIED" }; + }, + admit: async (database) => { try { assertIndexedDbRuntimeStores( - opened, + database, dependencies.recordStore, dependencies.governanceStore, dependencies.retentionStore, @@ -852,80 +839,90 @@ export function createIndexedDbRuntime( dependencies.idempotencyExpiryIndex, ); } catch (error) { - settleLateRequest(); - opened.close(); - updateStatus({ kind: "CLOSED", reason: "NOT_OPENED" }); - const result = mapIndexedDbException( - error, - "INDEXEDDB_MIGRATE", - ); - observeResult("INDEXEDDB_MIGRATE", result); - finishOpeningAttempt(result); - return; + return { kind: "REJECT", detail: error }; } + // No signal: an open the caller gave up on is already ended by the + // kernel's own abort path. const binding = await verifyIndexedDbDatasetBinding( - opened, + database, dependencies.governanceStore, expectedBinding, undefined, ); - settleLateRequest(); - if (!binding.ok) { - opened.close(); - if (!disposed) { - updateStatus({ kind: "CLOSED", reason: "NOT_OPENED" }); - } - if (!requestSettled) { - finishOpeningAttempt( - binding.reason === "ABORTED" - ? browserDataFailure("ABORTED", operation) - : binding.reason === "NATIVE_ERROR" - ? mapIndexedDbException(binding.error, operation) - : browserDataFailure( - "POLICY_REJECTED", - operation, - { - recovery: - storagePolicySnapshot.unavailableFallback, - }, - ), - ); - } - return; + if (binding.ok) return { kind: "ADMIT" }; + return binding.reason === "ABORTED" + ? { kind: "FAIL", cause: { kind: "CALLER_ABORT" } } + : binding.reason === "NATIVE_ERROR" + ? { + kind: "FAIL", + cause: { kind: "NATIVE_EXCEPTION", error: binding.error }, + } + : { kind: "REJECT", detail: "POLICY" }; + }, + }).then((opened) => { + // `queueIndexedDbUpgradeBinding` reports a mismatch from inside a + // request handler, which runs after `upgrade` has already returned. + // The upgrade transaction aborts and the open then fails as an + // AbortError, so the rejection is applied here instead — and a + // migration failure still outranks it, exactly as the hand-written + // `onerror` ordered the two. + const result: BrowserDataResult = + !opened.ok && + policyBindingRejected && + opened.error.code !== "MIGRATION_FAILED" + ? browserDataFailure("POLICY_REJECTED", operation, { + recovery: storagePolicySnapshot.unavailableFallback, + }) + : opened; + if (disposed) return result; + if (!result.ok) { + updateStatus({ kind: "CLOSED", reason: "NOT_OPENED" }); + // A failed migration is observed against INDEXEDDB_MIGRATE as well + // as against the open the caller asked for. + if (result.error.operation === "INDEXEDDB_MIGRATE") { + observeResult("INDEXEDDB_MIGRATE", result); } - if (requestSettled || disposed) { - opened.close(); - if (!disposed) { - updateStatus({ kind: "CLOSED", reason: "NOT_OPENED" }); - } - return; - } - connection = opened; - opened.onversionchange = () => handleVersionChange(opened); - opened.onclose = () => handleForcedClose(opened); - updateStatus({ - kind: "READY", - schemaVersion: opened.version, - }); - if (appliedMigrations > 0) { - observeResult( - "INDEXEDDB_MIGRATE", - browserDataSuccess(undefined), - appliedMigrations, - ); - } - finishOpeningAttempt(browserDataSuccess(undefined)); - })(); - }; - }); - } + return result; + } + updateStatus({ + kind: "READY", + schemaVersion: result.value.version, + }); + if (appliedMigrations > 0) { + observeResult( + "INDEXEDDB_MIGRATE", + browserDataSuccess(undefined), + appliedMigrations, + ); + } + return result; + }); + }, + onVersionChange: () => { + // The kernel has already closed the connection and dropped the cached + // handle, so only the announcement is left here. + const next = Object.freeze({ + kind: "CLOSED" as const, + reason: "VERSION_CHANGE" as const, + }); + updateStatus(next); + try { + dependencies.onVersionChange?.(next); + } catch { + // Connection closure is independent from the notification callback. + } + }, + onForcedClose: () => { + updateStatus({ kind: "CLOSED", reason: "FORCED" }); + }, + }); async function open( signal?: AbortSignal, ): Promise> { const operation = "INDEXEDDB_OPEN" as const; if (disposed) return observeResult(operation, unavailable(operation)); - if (connection) { + if (connection.current()) { return observeResult(operation, browserDataSuccess(undefined)); } const cancelled = abortedResult(signal, operation); @@ -938,41 +935,24 @@ export function createIndexedDbRuntime( }), ); } - - if (!openingPromise) { - updateStatus({ - kind: "OPENING", - targetVersion: dependencies.schemaVersion, - }); - const generation = {}; - activeOpeningGeneration = generation; - const attempt = startOpeningAttempt(factory, generation); - openingPromise = attempt; - } - - const result = await waitForOpeningAttempt(openingPromise, signal); - return observeResult(operation, result); - } - - function createTransaction( - db: IDBDatabase, - stores: readonly string[], - mode: IDBTransactionMode, - ): IDBTransaction { - const durability = - mode === "readonly" - ? dependencies.durability?.read ?? "default" - : dependencies.durability?.write ?? "strict"; - try { - return db.transaction([...stores], mode, { durability }); - } catch (error) { - if (error instanceof TypeError) { - return db.transaction([...stores], mode); - } - throw error; - } + const acquired = await connection.acquire(signal); + return observeResult( + operation, + acquired.ok ? browserDataSuccess(undefined) : acquired, + ); } + /** + * Durability is named explicitly on both sides, so a read stays on the + * engine default while a write is strict: a record that is only queued when + * the tab goes away would leave a receipt claiming a revision that was never + * stored. The kernel falls back to the no-options form on an engine that + * rejects the bag. + * + * The caller's abort is checked before the connection so a cancelled call + * reports ABORTED rather than UNAVAILABLE, which is the order this file has + * always used. + */ function runTransaction( stores: readonly string[], mode: "readonly" | "readwrite", @@ -985,91 +965,20 @@ export function createIndexedDbRuntime( ): Promise> { const cancelled = abortedResult(signal, operation); if (cancelled) return Promise.resolve(cancelled); - const db = connection; + const db = connection.current(); if (!db || disposed) return Promise.resolve(unavailable(operation)); - let transaction: IDBTransaction; - try { - transaction = createTransaction(db, stores, mode); - } catch (error) { - return Promise.resolve(mapIndexedDbException(error, operation)); - } - - return new Promise>((resolve) => { - let candidate: BrowserDataResult | undefined; - let requestError: unknown; - let callerAborted = false; - let settled = false; - - const finish = (result: BrowserDataResult) => { - if (settled) return; - settled = true; - signal?.removeEventListener("abort", onAbort); - resolve(result); - }; - function onAbort(): void { - callerAborted = true; - try { - transaction.abort(); - } catch { - // If complete won the race, its result remains authoritative. - } - } - - transaction.oncomplete = () => { - finish(candidate ?? unavailable(operation)); - }; - transaction.onerror = () => { - requestError ??= transaction.error; - }; - transaction.onabort = () => { - if (callerAborted) { - finish(browserDataFailure("ABORTED", operation)); - return; - } - if (candidate && !candidate.ok) { - finish(candidate); - return; - } - finish( - mapIndexedDbException( - requestError ?? transaction.error, - operation, - ), - ); - }; - signal?.addEventListener("abort", onAbort, { once: true }); - - const context: TransactionContext = Object.freeze({ - succeed(value) { - if (!candidate) candidate = browserDataSuccess(value); - }, - fail(result) { - if (!candidate) candidate = result; - try { - transaction.abort(); - } catch { - // Completion or a prior abort already owns the result. - } - }, - requestFailed(error) { - requestError ??= error; - if (!candidate) { - candidate = mapIndexedDbException(error, operation); - } - }, - }); - - try { - queue(transaction, context); - } catch (error) { - context.fail(mapIndexedDbException(error, operation)); - try { - transaction.abort(); - } catch { - finish(candidate ?? unavailable(operation)); - } - } + return runIndexedDbTransaction({ + database: db, + stores, + mode, + translate: translateFor(operation), + signal, + durability: + mode === "readonly" + ? dependencies.durability?.read ?? "default" + : dependencies.durability?.write ?? "strict", + queue, }); } @@ -1138,7 +1047,7 @@ export function createIndexedDbRuntime( } const decoded = decodeRecord(request.result, key); if (!decoded.ok) { - context.fail(decoded); + context.fail(failureOf(decoded)); return; } const retentionRequest = transaction @@ -1153,14 +1062,14 @@ export function createIndexedDbRuntime( key, ) ) { - context.fail(corruptData(operation)); + context.fail(corruptFailure(operation)); return; } if ( storagePolicySnapshot.retention.kind === "TTL" && retentionRequest.result.eligibleAtEpochMs === undefined ) { - context.fail(corruptData(operation)); + context.fail(corruptFailure(operation)); return; } if ( @@ -1169,9 +1078,8 @@ export function createIndexedDbRuntime( retentionRequest.result.eligibleAtEpochMs <= readEpochMs ) { context.fail( - browserDataFailure( - "EXPIRED_RESOURCE", - operation, + failureOf( + browserDataFailure("EXPIRED_RESOURCE", operation), ), ); return; @@ -1369,162 +1277,152 @@ export function createIndexedDbRuntime( let lastCursor: IndexedDbCursor | null = null; let lastScannedCursor: IndexedDbCursor | null = null; let scannedRows = 0; + // The two ways a page stops short resume from different places: a scan + // that ran out of budget resumes from the last row it looked at, while + // a full page resumes from the last row it kept. + let stoppedAtScanLimit = false; - request.onerror = () => context.requestFailed(request.error); - request.onsuccess = () => { - if (signal?.aborted) { - try { - transaction.abort(); - } catch { - // Transaction completion decides the race. + walkIndexedDbCursor({ + request, + sink: context, + translate: translateFor(operation), + // No budget: the page is bounded by rows scanned and rows kept, + // both of which are decided against the caller's plan below. + signal, + visit: ({ cursor: nativeCursor, resume }) => { + if ( + !isBoundedCursorKey(nativeCursor.key) || + !isBoundedCursorKey(nativeCursor.primaryKey) + ) { + context.fail(corruptFailure(operation)); + // `fail` aborts, so the pump has nowhere to go. Suspending + // without ever resuming says that without asking for another + // row or claiming a summary the scan never reached. + return { kind: "SUSPEND" }; } - return; - } - const nativeCursor = request.result; - if (!nativeCursor) { - context.succeed( - Object.freeze({ - items: Object.freeze(items), - nextCursor: null, - }), - ); - return; - } - if ( - !isBoundedCursorKey(nativeCursor.key) || - !isBoundedCursorKey(nativeCursor.primaryKey) - ) { - context.fail(corruptData(operation)); - return; - } - const currentCursor: IndexedDbCursor = Object.freeze({ - indexKey: normalizeCursorKey(nativeCursor.key), - primaryKey: normalizeCursorKey(nativeCursor.primaryKey), - }); - if ( - validated.value.cursor && - factory && - !cursorAfter( - factory, - currentCursor, - validated.value.cursor, - direction, - ) - ) { - try { + const currentCursor: IndexedDbCursor = Object.freeze({ + indexKey: normalizeCursorKey(nativeCursor.key), + primaryKey: normalizeCursorKey(nativeCursor.primaryKey), + }); + if ( + validated.value.cursor && + factory && + !cursorAfter( + factory, + currentCursor, + validated.value.cursor, + direction, + ) + ) { + // Rows at or before the caller's cursor are skipped rather than + // counted, so a resumed page never returns what it already did. + // A throwing `cmp` is reported by the pump, which maps it the + // same way the hand-written catch did. const sameIndexKey = factory.cmp( nativeCursorKey(currentCursor.indexKey), - nativeCursorKey( - validated.value.cursor.indexKey, - ), + nativeCursorKey(validated.value.cursor.indexKey), ) === 0; const samePrimaryKey = factory.cmp( nativeCursorKey(currentCursor.primaryKey), - nativeCursorKey( - validated.value.cursor.primaryKey, - ), + nativeCursorKey(validated.value.cursor.primaryKey), ) === 0; if (sameIndexKey && samePrimaryKey) { - nativeCursor.continue(); - } else if (validated.value.plan.index) { - nativeCursor.continuePrimaryKey( - nativeCursorKey( - validated.value.cursor.indexKey, - ), - nativeCursorKey( - validated.value.cursor.primaryKey, - ), - ); - } else { - nativeCursor.continue( - nativeCursorKey( - validated.value.cursor.primaryKey, - ), - ); + return { kind: "CONTINUE" }; } - } catch (error) { - context.fail( - mapIndexedDbException(error, operation), - ); + return validated.value.plan.index + ? { + kind: "CONTINUE_PRIMARY", + key: nativeCursorKey( + validated.value.cursor.indexKey, + ), + primaryKey: nativeCursorKey( + validated.value.cursor.primaryKey, + ), + } + : { + kind: "CONTINUE_FROM", + key: nativeCursorKey( + validated.value.cursor.primaryKey, + ), + }; } - return; - } - if (scannedRows >= scanLimit) { + if (scannedRows >= scanLimit) { + stoppedAtScanLimit = true; + return { kind: "STOP" }; + } + if (items.length >= validated.value.plan.limit) { + return { kind: "STOP" }; + } + if (!isStoredRecord(nativeCursor.value)) { + context.fail(corruptFailure(operation)); + return { kind: "SUSPEND" }; + } + const decoded = decodeRecord( + nativeCursor.value, + nativeCursor.value.key, + ); + if (!decoded.ok) { + context.fail(failureOf(decoded)); + return { kind: "SUSPEND" }; + } + scannedRows += 1; + lastScannedCursor = currentCursor; + const recordKey = nativeCursor.value.key; + const retentionRequest = transaction + .objectStore(dependencies.retentionStore) + .get(recordKey); + retentionRequest.onerror = () => + context.requestFailed(retentionRequest.error); + retentionRequest.onsuccess = () => { + if ( + !isStoredRetentionRecord( + retentionRequest.result, + recordKey, + ) + ) { + context.fail(corruptFailure(operation)); + return; + } + const expired = + storagePolicySnapshot.retention.kind === "TTL" && + retentionRequest.result.eligibleAtEpochMs !== + undefined && + retentionRequest.result.eligibleAtEpochMs <= + queryEpochMs; + if ( + storagePolicySnapshot.retention.kind === "TTL" && + retentionRequest.result.eligibleAtEpochMs === undefined + ) { + context.fail(corruptFailure(operation)); + return; + } + if (!expired) { + items.push(decoded.value.value); + lastCursor = currentCursor; + } + resume({ kind: "CONTINUE" }); + }; + // A row only counts once its retention sidecar has been read, so + // the cursor stays parked until `resume`. + return { kind: "SUSPEND" }; + }, + done: (summary) => { + if (summary.reason === "ABORTED") return; context.succeed( Object.freeze({ items: Object.freeze(items), - nextCursor: lastScannedCursor, + nextCursor: + summary.reason === "EXHAUSTED" + ? null + : stoppedAtScanLimit + ? lastScannedCursor + : lastCursor, }), ); - return; - } - if (items.length >= validated.value.plan.limit) { - context.succeed( - Object.freeze({ - items: Object.freeze(items), - nextCursor: lastCursor, - }), - ); - return; - } - if (!isStoredRecord(nativeCursor.value)) { - context.fail(corruptData(operation)); - return; - } - const decoded = decodeRecord( - nativeCursor.value, - nativeCursor.value.key, - ); - if (!decoded.ok) { - context.fail(decoded); - return; - } - scannedRows += 1; - lastScannedCursor = currentCursor; - const recordKey = nativeCursor.value.key; - const retentionRequest = transaction - .objectStore(dependencies.retentionStore) - .get(recordKey); - retentionRequest.onerror = () => - context.requestFailed(retentionRequest.error); - retentionRequest.onsuccess = () => { - if ( - !isStoredRetentionRecord( - retentionRequest.result, - recordKey, - ) - ) { - context.fail(corruptData(operation)); - return; - } - const expired = - storagePolicySnapshot.retention.kind === "TTL" && - retentionRequest.result.eligibleAtEpochMs !== - undefined && - retentionRequest.result.eligibleAtEpochMs <= - queryEpochMs; - if ( - storagePolicySnapshot.retention.kind === "TTL" && - retentionRequest.result.eligibleAtEpochMs === undefined - ) { - context.fail(corruptData(operation)); - return; - } - if (!expired) { - items.push(decoded.value.value); - lastCursor = currentCursor; - } - try { - nativeCursor.continue(); - } catch (error) { - context.fail( - mapIndexedDbException(error, operation), - ); - } - }; - }; + }, + }); }, ); return observeResult(operation, result, result.ok ? result.value.items.length : 0); @@ -1772,9 +1670,7 @@ export function createIndexedDbRuntime( try { recordRequest = records.get(input.key); } catch (error) { - context.fail( - mapIndexedDbException(error, operation), - ); + context.fail(mappedFailure(error, operation)); return; } recordRequest.onerror = () => @@ -1782,7 +1678,7 @@ export function createIndexedDbRuntime( recordRequest.onsuccess = () => { const raw = recordRequest.result; if (raw !== undefined && !isStoredRecord(raw, input.key)) { - context.fail(corruptData(operation)); + context.fail(corruptFailure(operation)); return; } if ( @@ -1791,12 +1687,12 @@ export function createIndexedDbRuntime( (raw === undefined || raw.revision !== input.expectedRevision)) ) { - context.fail(readwriteConflict(operation)); + context.fail(conflictFailure(operation)); return; } const revision = raw === undefined ? 1 : raw.revision + 1; if (!Number.isSafeInteger(revision)) { - context.fail(corruptData(operation)); + context.fail(corruptFailure(operation)); return; } const sidecarRequest = retention.get(input.key); @@ -1813,7 +1709,7 @@ export function createIndexedDbRuntime( input.key, )) ) { - context.fail(corruptData(operation)); + context.fail(corruptFailure(operation)); return; } const budgetRequest = governance.get( @@ -1823,7 +1719,7 @@ export function createIndexedDbRuntime( context.requestFailed(budgetRequest.error); budgetRequest.onsuccess = () => { if (!isStoredDatasetBudget(budgetRequest.result)) { - context.fail(corruptData(operation)); + context.fail(corruptFailure(operation)); return; } const previousBytes = @@ -1850,11 +1746,13 @@ export function createIndexedDbRuntime( storagePolicySnapshot.hardBudgetBytes || receiptCount > dependencies.maxIdempotencyReceipts - ? browserDataFailure( - "LIMIT_EXCEEDED", - operation, + ? failureOf( + browserDataFailure( + "LIMIT_EXCEEDED", + operation, + ), ) - : corruptData(operation), + : corruptFailure(operation), ); return; } @@ -1868,9 +1766,7 @@ export function createIndexedDbRuntime( try { writeRequest = records.put(stored); } catch (error) { - context.fail( - mapIndexedDbException(error, operation), - ); + context.fail(mappedFailure(error, operation)); return; } writeRequest.onerror = () => @@ -1957,7 +1853,7 @@ export function createIndexedDbRuntime( if (replay.result.ok) { context.succeed(replay.result.value); } else { - context.fail(replay.result); + context.fail(failureOf(replay.result)); } return; } @@ -1968,9 +1864,7 @@ export function createIndexedDbRuntime( input.idempotencyKey, ); } catch (error) { - context.fail( - mapIndexedDbException(error, operation), - ); + context.fail(mappedFailure(error, operation)); return; } deleteRequest.onerror = () => @@ -2045,9 +1939,7 @@ export function createIndexedDbRuntime( try { recordRequest = records.get(input.key); } catch (error) { - context.fail( - mapIndexedDbException(error, operation), - ); + context.fail(mappedFailure(error, operation)); return; } recordRequest.onerror = () => @@ -2057,7 +1949,7 @@ export function createIndexedDbRuntime( !isStoredRecord(recordRequest.result, input.key) || recordRequest.result.revision !== input.expectedRevision ) { - context.fail(readwriteConflict(operation)); + context.fail(conflictFailure(operation)); return; } const revision = input.expectedRevision + 1; @@ -2071,7 +1963,7 @@ export function createIndexedDbRuntime( input.key, ) ) { - context.fail(corruptData(operation)); + context.fail(corruptFailure(operation)); return; } const previousBytes = @@ -2086,7 +1978,7 @@ export function createIndexedDbRuntime( !isStoredDatasetBudget(budgetRequest.result) || budgetRequest.result.usedBytes < previousBytes ) { - context.fail(corruptData(operation)); + context.fail(corruptFailure(operation)); return; } const usedBytes = @@ -2099,9 +1991,11 @@ export function createIndexedDbRuntime( dependencies.maxIdempotencyReceipts ) { context.fail( - browserDataFailure( - "LIMIT_EXCEEDED", - operation, + failureOf( + browserDataFailure( + "LIMIT_EXCEEDED", + operation, + ), ), ); return; @@ -2171,7 +2065,7 @@ export function createIndexedDbRuntime( if (replay.result.ok) { context.succeed(replay.result.value); } else { - context.fail(replay.result); + context.fail(failureOf(replay.result)); } return; } @@ -2182,9 +2076,7 @@ export function createIndexedDbRuntime( input.idempotencyKey, ); } catch (error) { - context.fail( - mapIndexedDbException(error, operation), - ); + context.fail(mappedFailure(error, operation)); return; } deleteRequest.onerror = () => @@ -2318,10 +2210,12 @@ export function createIndexedDbRuntime( (transaction, context) => { if (!keyRange) { context.fail( - browserDataFailure( - "UNSUPPORTED", - "INDEXEDDB_WRITE", - { recovery: "ONLINE_ONLY" }, + failureOf( + browserDataFailure( + "UNSUPPORTED", + "INDEXEDDB_WRITE", + { recovery: "ONLINE_ONLY" }, + ), ), ); return; @@ -2339,7 +2233,7 @@ export function createIndexedDbRuntime( try { range = keyRange.upperBound(cutoffEpochMs); } catch { - context.fail(invalidInput("INDEXEDDB_WRITE")); + context.fail(invalidFailure("INDEXEDDB_WRITE")); return; } const request = retention @@ -2359,117 +2253,115 @@ export function createIndexedDbRuntime( budgetExhausted, }), ); - request.onerror = () => - context.requestFailed(request.error); - request.onsuccess = () => { - if (input.signal?.aborted) { - try { - transaction.abort(); - } catch { - // The transaction completion event decides the race. + // The sweep bounds on rows it deleted, not on rows it read, so the + // counters stay here while the kernel drives the cursor. The time + // check comes first so a batch that ran out of both still reports + // `budgetExhausted`, exactly as the hand-written check did. + const budget: IndexedDbBudget = { + admit: () => { + const clock = monotonicClock(); + if (!clock.ok) return clock; + if (clock.value >= deadline) { + return browserDataSuccess("TIME_BUDGET" as const); } - return; - } - const cursor = request.result; - if (!cursor) { - succeed("COMPLETE", false); - return; - } - const clock = monotonicClock(); - if (!clock.ok) { - context.fail(clock); - return; - } - if ( - deletedRows >= input.maxRows || - clock.value >= deadline - ) { - succeed("MORE", clock.value >= deadline); - return; - } - if ( - !isStoredRetentionRecord( - cursor.value, - String(cursor.primaryKey), - ) || - cursor.value.eligibleAtEpochMs === undefined || - cursor.value.eligibleAtEpochMs > cutoffEpochMs || - (storagePolicySnapshot.retention.kind === - "UNTIL_SYNCED" && - cursor.value.synchronization !== "CONFIRMED") - ) { - context.fail(corruptData("INDEXEDDB_WRITE")); - return; - } - scannedRows += 1; - const measuredBytes = cursor.value.measuredBytes; - let recordDelete: IDBRequest; - try { - recordDelete = records.delete(cursor.value.recordKey); - } catch (error) { - context.fail( - mapIndexedDbException(error, "INDEXEDDB_WRITE"), + return browserDataSuccess( + deletedRows >= input.maxRows + ? ("ROW_BUDGET" as const) + : ("CONTINUE" as const), ); - return; - } - recordDelete.onerror = () => - context.requestFailed(recordDelete.error); - recordDelete.onsuccess = () => { - let sidecarDelete: IDBRequest; - try { - sidecarDelete = retention.delete( - cursor.value.recordKey, - ); - } catch (error) { - context.fail( - mapIndexedDbException(error, "INDEXEDDB_WRITE"), - ); - return; + }, + }; + walkIndexedDbCursor({ + request, + sink: context, + translate: translateFor("INDEXEDDB_WRITE"), + budget, + signal: input.signal, + visit: ({ cursor, resume }) => { + if ( + !isStoredRetentionRecord( + cursor.value, + String(cursor.primaryKey), + ) || + cursor.value.eligibleAtEpochMs === undefined || + cursor.value.eligibleAtEpochMs > cutoffEpochMs || + (storagePolicySnapshot.retention.kind === + "UNTIL_SYNCED" && + cursor.value.synchronization !== "CONFIRMED") + ) { + context.fail(corruptFailure("INDEXEDDB_WRITE")); + // `fail` aborts, so the pump has nowhere to go. Suspending + // without ever resuming says that without claiming a summary + // the sweep never reached. + return { kind: "SUSPEND" }; } - sidecarDelete.onerror = () => - context.requestFailed(sidecarDelete.error); - sidecarDelete.onsuccess = () => { - const budgetRequest = governance.get( - INDEXEDDB_DATASET_BUDGET_KEY, - ); - budgetRequest.onerror = () => - context.requestFailed(budgetRequest.error); - budgetRequest.onsuccess = () => { - if ( - !isStoredDatasetBudget(budgetRequest.result) || - budgetRequest.result.usedBytes < measuredBytes - ) { - context.fail(corruptData("INDEXEDDB_WRITE")); - return; - } - const storedBudgetRequest = governance.put({ - bindingKey: INDEXEDDB_DATASET_BUDGET_KEY, - budgetVersion: 1, - usedBytes: - budgetRequest.result.usedBytes - measuredBytes, - receiptCount: budgetRequest.result.receiptCount, - } satisfies StoredDatasetBudget); - storedBudgetRequest.onerror = () => - context.requestFailed( - storedBudgetRequest.error, - ); - storedBudgetRequest.onsuccess = () => { - deletedRows += 1; - try { - cursor.continue(); - } catch (error) { - context.fail( - mapIndexedDbException( - error, - "INDEXEDDB_WRITE", - ), - ); + scannedRows += 1; + const measuredBytes = cursor.value.measuredBytes; + let recordDelete: IDBRequest; + try { + recordDelete = records.delete(cursor.value.recordKey); + } catch (error) { + context.fail(mappedFailure(error, "INDEXEDDB_WRITE")); + return { kind: "SUSPEND" }; + } + recordDelete.onerror = () => + context.requestFailed(recordDelete.error); + recordDelete.onsuccess = () => { + let sidecarDelete: IDBRequest; + try { + sidecarDelete = retention.delete( + cursor.value.recordKey, + ); + } catch (error) { + context.fail(mappedFailure(error, "INDEXEDDB_WRITE")); + return; + } + sidecarDelete.onerror = () => + context.requestFailed(sidecarDelete.error); + sidecarDelete.onsuccess = () => { + const budgetRequest = governance.get( + INDEXEDDB_DATASET_BUDGET_KEY, + ); + budgetRequest.onerror = () => + context.requestFailed(budgetRequest.error); + budgetRequest.onsuccess = () => { + if ( + !isStoredDatasetBudget(budgetRequest.result) || + budgetRequest.result.usedBytes < measuredBytes + ) { + context.fail(corruptFailure("INDEXEDDB_WRITE")); + return; } + const storedBudgetRequest = governance.put({ + bindingKey: INDEXEDDB_DATASET_BUDGET_KEY, + budgetVersion: 1, + usedBytes: + budgetRequest.result.usedBytes - measuredBytes, + receiptCount: budgetRequest.result.receiptCount, + } satisfies StoredDatasetBudget); + storedBudgetRequest.onerror = () => + context.requestFailed( + storedBudgetRequest.error, + ); + storedBudgetRequest.onsuccess = () => { + deletedRows += 1; + resume({ kind: "CONTINUE" }); + }; }; }; }; - }; - }; + // A row is only counted once its whole delete chain has been + // queued, so the cursor stays parked until `resume`. + return { kind: "SUSPEND" }; + }, + done: (summary) => { + if (summary.reason === "ABORTED") return; + succeed( + summary.reason === "EXHAUSTED" ? "COMPLETE" : "MORE", + summary.reason === "TIME_BUDGET", + ); + }, + }); }, ); } @@ -2517,6 +2409,52 @@ export function createIndexedDbRuntime( }), ); + // The purge bounds on rows it deleted, not on rows it read, so the + // counters stay here. The time check comes first so a pass that ran + // out of both still reports `budgetExhausted`. + const budget: IndexedDbBudget = { + admit: () => { + const clock = monotonicClock(); + if (!clock.ok) return clock; + if (clock.value >= deadline) { + return browserDataSuccess("TIME_BUDGET" as const); + } + return browserDataSuccess( + deletedRows >= input.maxRows + ? ("ROW_BUDGET" as const) + : ("CONTINUE" as const), + ); + }, + }; + + /** + * The four passes differ only in which rows they delete and in what + * runs once a store is empty, so the budget and the "this pass ran + * out" receipt are shared. No signal is passed: the partition purge + * has never checked one per row, and the transaction's own abort + * listener already ends a cancelled batch. + */ + const walkPurge = ( + request: IDBRequest, + visit: (visit: IndexedDbCursorVisit) => IndexedDbCursorStep, + exhausted: () => void, + ) => { + walkIndexedDbCursor({ + request, + sink: context, + translate: translateFor("INDEXEDDB_WRITE"), + budget, + visit, + done: (summary) => { + if (summary.reason === "EXHAUSTED") { + exhausted(); + return; + } + succeed("MORE", summary.reason === "TIME_BUDGET"); + }, + }); + }; + const processMetadataStore = (storeIndex: number) => { const storeName = dependencies.lifecycleMetadataStores[storeIndex]; @@ -2525,78 +2463,88 @@ export function createIndexedDbRuntime( return; } const store = transaction.objectStore(storeName); - const request = store.openCursor(); - request.onerror = () => - context.requestFailed(request.error); - request.onsuccess = () => { - const cursor = request.result; - if (!cursor) { - processMetadataStore(storeIndex + 1); - return; - } - const clock = monotonicClock(); - if (!clock.ok) { - context.fail(clock); - return; - } - if ( - deletedRows >= input.maxRows || - clock.value >= deadline - ) { - succeed("MORE", clock.value >= deadline); - return; - } - scannedRows += 1; - const deletion = store.delete(cursor.primaryKey); - deletion.onerror = () => - context.requestFailed(deletion.error); - deletion.onsuccess = () => { - deletedRows += 1; - try { - cursor.continue(); - } catch (error) { - context.fail( - mapIndexedDbException( - error, - "INDEXEDDB_WRITE", - ), - ); - } - }; - }; + walkPurge( + store.openCursor(), + ({ cursor, resume }) => { + scannedRows += 1; + const deletion = store.delete(cursor.primaryKey); + deletion.onerror = () => + context.requestFailed(deletion.error); + deletion.onsuccess = () => { + deletedRows += 1; + resume({ kind: "CONTINUE" }); + }; + // The row only counts once its deletion is queued, so the + // cursor stays parked until `resume`. + return { kind: "SUSPEND" }; + }, + () => processMetadataStore(storeIndex + 1), + ); }; const processReceipts = () => { - const request = receipts.openCursor(); - request.onerror = () => - context.requestFailed(request.error); - request.onsuccess = () => { - const cursor = request.result; - if (!cursor) { - succeed("COMPLETE", false); - return; - } - const clock = monotonicClock(); - if (!clock.ok) { - context.fail(clock); - return; - } - if ( - deletedRows >= input.maxRows || - clock.value >= deadline - ) { - succeed("MORE", clock.value >= deadline); - return; - } - if (!isStoredReceipt(cursor.value)) { - context.fail(corruptData("INDEXEDDB_WRITE")); - return; - } - scannedRows += 1; - const deletion = receipts.delete(cursor.primaryKey); - deletion.onerror = () => - context.requestFailed(deletion.error); - deletion.onsuccess = () => { + walkPurge( + receipts.openCursor(), + ({ cursor, resume }) => { + if (!isStoredReceipt(cursor.value)) { + context.fail(corruptFailure("INDEXEDDB_WRITE")); + // `fail` aborts, so the pump has nowhere to go. + return { kind: "SUSPEND" }; + } + scannedRows += 1; + const deletion = receipts.delete(cursor.primaryKey); + deletion.onerror = () => + context.requestFailed(deletion.error); + deletion.onsuccess = () => { + const budgetRequest = governance.get( + INDEXEDDB_DATASET_BUDGET_KEY, + ); + budgetRequest.onerror = () => + context.requestFailed(budgetRequest.error); + budgetRequest.onsuccess = () => { + if ( + !isStoredDatasetBudget(budgetRequest.result) || + budgetRequest.result.receiptCount < 1 + ) { + context.fail(corruptFailure("INDEXEDDB_WRITE")); + return; + } + const storedBudgetRequest = governance.put({ + ...budgetRequest.result, + receiptCount: + budgetRequest.result.receiptCount - 1, + } satisfies StoredDatasetBudget); + storedBudgetRequest.onerror = () => + context.requestFailed( + storedBudgetRequest.error, + ); + storedBudgetRequest.onsuccess = () => { + deletedRows += 1; + resume({ kind: "CONTINUE" }); + }; + }; + }; + return { kind: "SUSPEND" }; + }, + () => succeed("COMPLETE", false), + ); + }; + + const processOrphanedRetention = () => { + walkPurge( + retention.openCursor(), + ({ cursor, resume }) => { + if ( + !isStoredRetentionRecord( + cursor.value, + String(cursor.primaryKey), + ) + ) { + context.fail(corruptFailure("INDEXEDDB_WRITE")); + return { kind: "SUSPEND" }; + } + scannedRows += 1; + const measuredBytes = cursor.value.measuredBytes; const budgetRequest = governance.get( INDEXEDDB_DATASET_BUDGET_KEY, ); @@ -2605,208 +2553,104 @@ export function createIndexedDbRuntime( budgetRequest.onsuccess = () => { if ( !isStoredDatasetBudget(budgetRequest.result) || - budgetRequest.result.receiptCount < 1 + budgetRequest.result.usedBytes < measuredBytes ) { - context.fail(corruptData("INDEXEDDB_WRITE")); + context.fail(corruptFailure("INDEXEDDB_WRITE")); return; } - const storedBudgetRequest = governance.put({ - ...budgetRequest.result, - receiptCount: - budgetRequest.result.receiptCount - 1, - } satisfies StoredDatasetBudget); - storedBudgetRequest.onerror = () => - context.requestFailed( - storedBudgetRequest.error, - ); - storedBudgetRequest.onsuccess = () => { - deletedRows += 1; - try { - cursor.continue(); - } catch (error) { - context.fail( - mapIndexedDbException( - error, - "INDEXEDDB_WRITE", - ), - ); - } + const deletion = retention.delete(cursor.primaryKey); + deletion.onerror = () => + context.requestFailed(deletion.error); + deletion.onsuccess = () => { + const budgetWrite = governance.put({ + ...budgetRequest.result, + usedBytes: + budgetRequest.result.usedBytes - measuredBytes, + } satisfies StoredDatasetBudget); + budgetWrite.onerror = () => + context.requestFailed(budgetWrite.error); + budgetWrite.onsuccess = () => { + deletedRows += 1; + resume({ kind: "CONTINUE" }); + }; }; }; - }; - }; + return { kind: "SUSPEND" }; + }, + () => processMetadataStore(0), + ); }; - const processOrphanedRetention = () => { - const request = retention.openCursor(); - request.onerror = () => - context.requestFailed(request.error); - request.onsuccess = () => { - const cursor = request.result; - if (!cursor) { - processMetadataStore(0); - return; - } - const clock = monotonicClock(); - if (!clock.ok) { - context.fail(clock); - return; - } - if ( - deletedRows >= input.maxRows || - clock.value >= deadline - ) { - succeed("MORE", clock.value >= deadline); - return; - } - if ( - !isStoredRetentionRecord( - cursor.value, - String(cursor.primaryKey), - ) - ) { - context.fail(corruptData("INDEXEDDB_WRITE")); - return; + walkPurge( + records.openCursor(), + ({ cursor, resume }) => { + if (!isStoredRecord(cursor.value)) { + context.fail(corruptFailure("INDEXEDDB_WRITE")); + return { kind: "SUSPEND" }; } scannedRows += 1; - const measuredBytes = cursor.value.measuredBytes; - const budgetRequest = governance.get( - INDEXEDDB_DATASET_BUDGET_KEY, - ); - budgetRequest.onerror = () => - context.requestFailed(budgetRequest.error); - budgetRequest.onsuccess = () => { + const key = cursor.value.key; + const sidecarRequest = retention.get(key); + sidecarRequest.onerror = () => + context.requestFailed(sidecarRequest.error); + sidecarRequest.onsuccess = () => { if ( - !isStoredDatasetBudget(budgetRequest.result) || - budgetRequest.result.usedBytes < measuredBytes + !isStoredRetentionRecord( + sidecarRequest.result, + key, + ) ) { - context.fail(corruptData("INDEXEDDB_WRITE")); + context.fail(corruptFailure("INDEXEDDB_WRITE")); return; } - const deletion = retention.delete(cursor.primaryKey); - deletion.onerror = () => - context.requestFailed(deletion.error); - deletion.onsuccess = () => { - const budgetWrite = governance.put({ - ...budgetRequest.result, - usedBytes: - budgetRequest.result.usedBytes - measuredBytes, - } satisfies StoredDatasetBudget); - budgetWrite.onerror = () => - context.requestFailed(budgetWrite.error); - budgetWrite.onsuccess = () => { - deletedRows += 1; - try { - cursor.continue(); - } catch (error) { - context.fail( - mapIndexedDbException( - error, - "INDEXEDDB_WRITE", - ), - ); - } - }; - }; - }; - }; - }; - - const request = records.openCursor(); - request.onerror = () => - context.requestFailed(request.error); - request.onsuccess = () => { - const cursor = request.result; - if (!cursor) { - processOrphanedRetention(); - return; - } - const clock = monotonicClock(); - if (!clock.ok) { - context.fail(clock); - return; - } - if ( - deletedRows >= input.maxRows || - clock.value >= deadline - ) { - succeed("MORE", clock.value >= deadline); - return; - } - if (!isStoredRecord(cursor.value)) { - context.fail(corruptData("INDEXEDDB_WRITE")); - return; - } - scannedRows += 1; - const key = cursor.value.key; - const sidecarRequest = retention.get(key); - sidecarRequest.onerror = () => - context.requestFailed(sidecarRequest.error); - sidecarRequest.onsuccess = () => { - if ( - !isStoredRetentionRecord( - sidecarRequest.result, - key, - ) - ) { - context.fail(corruptData("INDEXEDDB_WRITE")); - return; - } - const measuredBytes = - sidecarRequest.result.measuredBytes; - const budgetRequest = governance.get( - INDEXEDDB_DATASET_BUDGET_KEY, - ); - budgetRequest.onerror = () => - context.requestFailed(budgetRequest.error); - budgetRequest.onsuccess = () => { - if ( - !isStoredDatasetBudget(budgetRequest.result) || - budgetRequest.result.usedBytes < measuredBytes - ) { - context.fail(corruptData("INDEXEDDB_WRITE")); - return; - } - const recordDelete = records.delete(key); - recordDelete.onerror = () => - context.requestFailed(recordDelete.error); - recordDelete.onsuccess = () => { - const sidecarDelete = retention.delete(key); - sidecarDelete.onerror = () => - context.requestFailed(sidecarDelete.error); - sidecarDelete.onsuccess = () => { - const storedBudgetRequest = governance.put({ - bindingKey: - INDEXEDDB_DATASET_BUDGET_KEY, - budgetVersion: 1, - usedBytes: - budgetRequest.result.usedBytes - - measuredBytes, - receiptCount: - budgetRequest.result.receiptCount, - } satisfies StoredDatasetBudget); - storedBudgetRequest.onerror = () => - context.requestFailed( - storedBudgetRequest.error, - ); - storedBudgetRequest.onsuccess = () => { - deletedRows += 1; - try { - cursor.continue(); - } catch (error) { - context.fail( - mapIndexedDbException( - error, - "INDEXEDDB_WRITE", - ), + const measuredBytes = + sidecarRequest.result.measuredBytes; + const budgetRequest = governance.get( + INDEXEDDB_DATASET_BUDGET_KEY, + ); + budgetRequest.onerror = () => + context.requestFailed(budgetRequest.error); + budgetRequest.onsuccess = () => { + if ( + !isStoredDatasetBudget(budgetRequest.result) || + budgetRequest.result.usedBytes < measuredBytes + ) { + context.fail(corruptFailure("INDEXEDDB_WRITE")); + return; + } + const recordDelete = records.delete(key); + recordDelete.onerror = () => + context.requestFailed(recordDelete.error); + recordDelete.onsuccess = () => { + const sidecarDelete = retention.delete(key); + sidecarDelete.onerror = () => + context.requestFailed(sidecarDelete.error); + sidecarDelete.onsuccess = () => { + const storedBudgetRequest = governance.put({ + bindingKey: INDEXEDDB_DATASET_BUDGET_KEY, + budgetVersion: 1, + usedBytes: + budgetRequest.result.usedBytes - + measuredBytes, + receiptCount: + budgetRequest.result.receiptCount, + } satisfies StoredDatasetBudget); + storedBudgetRequest.onerror = () => + context.requestFailed( + storedBudgetRequest.error, ); - } + storedBudgetRequest.onsuccess = () => { + deletedRows += 1; + resume({ kind: "CONTINUE" }); + }; }; }; }; }; - }; - }; + return { kind: "SUSPEND" }; + }, + () => processOrphanedRetention(), + ); }, ); } @@ -2873,12 +2717,10 @@ export function createIndexedDbRuntime( function close(): void { if (disposed) return; disposed = true; - cancelPendingOpen?.(); - cancelPendingOpen = null; - openingRequest = null; - const current = connection; - connection = null; - current?.close(); + // Idempotent in the kernel: it closes the cached connection, cancels an + // open still in flight and settles that open's waiters with CLOSED, which + // `translateFor` maps to UNAVAILABLE rather than ABORTED. + connection.close(); updateStatus({ kind: "DISPOSED" }); subscribers.clear(); } diff --git a/src/adapters/storage/opfs/indexeddb-opfs-journal.ts b/src/adapters/storage/opfs/indexeddb-opfs-journal.ts index 3b4996a..a578f53 100644 --- a/src/adapters/storage/opfs/indexeddb-opfs-journal.ts +++ b/src/adapters/storage/opfs/indexeddb-opfs-journal.ts @@ -18,6 +18,19 @@ import { browserDataFailure, browserDataSuccess, } from "../../browser-file-storage/result.ts"; +import { snapshotAbortTimers } from "../../platform/abortable-operation.ts"; +import { + createIndexedDbConnection, + openIndexedDbDatabase, + type IndexedDbTranslate, +} from "../../platform/indexeddb-connection.ts"; +import { + onIndexedDbRequest, + runIndexedDbTransaction, + walkIndexedDbCursor, + type IndexedDbRequestSink, + type IndexedDbTransactionContext, +} from "../../platform/indexeddb-transaction.ts"; import { mapIndexedDbException } from "../indexeddb/indexeddb-failure.ts"; import { isValidOpfsStorageScope } from "./opfs-policy.ts"; @@ -45,10 +58,10 @@ export interface IndexedDbOpfsJournal extends OpfsJournalPort { close(): void; } -type TransactionContext = Readonly<{ - succeed(value: Value): void; - fail(result: BrowserDataResult): void; -}>; +type TransactionContext = IndexedDbTransactionContext< + Value, + BrowserDataFailure +>; type StoredJournalRow = OpfsJournalTransaction & Readonly<{ logicalKey: string }>; @@ -141,17 +154,6 @@ export function createIndexedDbOpfsJournal( dependencies.createFencingToken ?? (() => globalThis.crypto.randomUUID()); const blockedTimeoutMs = dependencies.blockedTimeoutMs ?? 10_000; - const scheduler = - dependencies.scheduler ?? - Object.freeze({ - setTimeout: (callback: () => void, milliseconds: number) => - globalThis.setTimeout(callback, milliseconds), - clearTimeout: (handle: unknown) => - globalThis.clearTimeout( - handle as ReturnType, - ), - }); - if ( !SAFE_BOUNDARY_ID.test(dependencies.authorityToken) || !SAFE_DATABASE_NAME.test(databaseName) || @@ -162,9 +164,88 @@ export function createIndexedDbOpfsJournal( throw new TypeError("IndexedDB OPFS journal configuration is invalid."); } - let database: IDBDatabase | null = null; - let opening: Promise> | null = null; - let closed = false; + // X-AUDIT-02. The timer callables are captured once, bound to their + // receiver, so replacing a global after composition cannot change how an + // open already in flight is bounded. + const timers = snapshotAbortTimers( + dependencies.scheduler ?? { + setTimeout: (callback: () => void, milliseconds: number): unknown => + globalThis.setTimeout(callback, milliseconds), + clearTimeout: (handle: unknown): void => { + globalThis.clearTimeout( + handle as ReturnType, + ); + }, + }, + ); + + /** + * The handle owns the cached connection, the single-flight open and the + * `versionchange`/`close` invalidation this file used to wire by hand. No + * `onVersionChange` callback is passed because dropping the cached + * connection so the next call reopens — which the kernel already does — was + * this journal's entire listener body. + */ + const connection = createIndexedDbConnection({ + translate: translateFor("INDEXEDDB_OPEN"), + open: (signal) => + factory === undefined + ? Promise.resolve( + browserDataFailure("UNSUPPORTED", "INDEXEDDB_OPEN", { + recovery: "ONLINE_ONLY", + }), + ) + : openIndexedDbDatabase({ + factory, + databaseName, + version: DATABASE_VERSION, + translate: translateFor("INDEXEDDB_OPEN"), + signal, + blockedTimeoutMs, + timers, + upgrade: ({ database, oldVersion }) => { + // Version 1 is the only schema this journal has ever had, so any + // other starting point belongs to a database it does not own. + // Rejecting aborts the versionchange transaction, which is what + // the hand-written `onupgradeneeded` did. + if (oldVersion !== 0) return { kind: "REJECTED" }; + const journalStore = database.createObjectStore(JOURNAL_STORE, { + keyPath: "transactionId", + }); + journalStore.createIndex( + LOGICAL_KEY_INDEX, + "logicalKey", + { unique: true }, + ); + journalStore.createIndex( + STARTED_AT_INDEX, + "startedAtEpochMs", + { unique: false }, + ); + const objectStore = database.createObjectStore(OBJECT_STORE, { + keyPath: "logicalKey", + }); + objectStore.createIndex( + SCOPE_OBJECT_INDEX, + "scopeObjectKey", + { unique: true }, + ); + database.createObjectStore(BUDGET_STORE, { + keyPath: "budgetKey", + }); + database.createObjectStore(SCOPE_BINDING_STORE, { + keyPath: "scopeKey", + }); + database.createObjectStore(LOGICAL_SCOPE_BINDING_STORE, { + keyPath: "logicalScopeKey", + }); + database.createObjectStore(CHUNK_REFERENCE_STORE, { + keyPath: "referenceKey", + }); + return { kind: "APPLIED" }; + }, + }), + }); const journal: IndexedDbOpfsJournal = { async getCommittedObject(scope, objectId) { @@ -181,23 +262,26 @@ export function createIndexedDbOpfsJournal( "readonly", "INDEXEDDB_READ", (transaction, context) => { - const request = transaction - .objectStore(OBJECT_STORE) - .get(logicalObjectKey(scope, objectId)); - request.onsuccess = () => { - if (request.result === undefined) { - context.succeed(null); - return; - } - if ( - !isStoredObjectRow(request.result) || - !sameScope(request.result.preparedObject.descriptor.scope, scope) - ) { - context.fail(corrupt("INDEXEDDB_READ")); - return; - } - context.succeed(request.result.preparedObject); - }; + onIndexedDbRequest( + transaction + .objectStore(OBJECT_STORE) + .get(logicalObjectKey(scope, objectId)), + context, + (stored) => { + if (stored === undefined) { + context.succeed(null); + return; + } + if ( + !isStoredObjectRow(stored) || + !sameScope(stored.preparedObject.descriptor.scope, scope) + ) { + context.fail(corrupt("INDEXEDDB_READ")); + return; + } + context.succeed(stored.preparedObject); + }, + ); }, ), ); @@ -232,176 +316,189 @@ export function createIndexedDbOpfsJournal( const bindingStore = nativeTransaction.objectStore(SCOPE_BINDING_STORE); const scopeKey = storageScopeKey(input.scope); - const bindingRequest = bindingStore.get(scopeKey); - bindingRequest.onsuccess = () => { - const storedBinding = bindingRequest.result; - if ( - storedBinding !== undefined && - !isScopeBinding(storedBinding) - ) { - context.fail(corrupt("INDEXEDDB_WRITE")); - return; - } - const expectedBinding = scopeBinding( - input.scope, - input.targetStoragePolicy, - ); - const logicalBindingStore = nativeTransaction.objectStore( - LOGICAL_SCOPE_BINDING_STORE, - ); - const expectedLogicalBinding = logicalScopeBinding( - input.scope, - ); - const logicalRequest = logicalBindingStore.get( - expectedLogicalBinding.logicalScopeKey, - ); - logicalRequest.onsuccess = () => { - const storedLogicalBinding = logicalRequest.result; + onIndexedDbRequest( + bindingStore.get(scopeKey), + context, + (storedBinding) => { if ( - storedLogicalBinding !== undefined && - !isLogicalScopeBinding(storedLogicalBinding) + storedBinding !== undefined && + !isScopeBinding(storedBinding) ) { context.fail(corrupt("INDEXEDDB_WRITE")); return; } - if ( - (storedBinding && - stableJson(storedBinding) !== - stableJson(expectedBinding)) || - (storedLogicalBinding && - stableJson(storedLogicalBinding) !== - stableJson(expectedLogicalBinding)) - ) { - context.fail(policyRejected("INDEXEDDB_WRITE")); - return; - } - if ( - (storedBinding === undefined) !== - (storedLogicalBinding === undefined) - ) { - context.fail(corrupt("INDEXEDDB_WRITE")); - return; - } - if (!storedBinding) { - bindingStore.add(expectedBinding); - logicalBindingStore.add(expectedLogicalBinding); - } - }; - }; + const expectedBinding = scopeBinding( + input.scope, + input.targetStoragePolicy, + ); + const logicalBindingStore = nativeTransaction.objectStore( + LOGICAL_SCOPE_BINDING_STORE, + ); + const expectedLogicalBinding = logicalScopeBinding( + input.scope, + ); + onIndexedDbRequest( + logicalBindingStore.get( + expectedLogicalBinding.logicalScopeKey, + ), + context, + (storedLogicalBinding) => { + if ( + storedLogicalBinding !== undefined && + !isLogicalScopeBinding(storedLogicalBinding) + ) { + context.fail(corrupt("INDEXEDDB_WRITE")); + return; + } + if ( + (storedBinding && + stableJson(storedBinding) !== + stableJson(expectedBinding)) || + (storedLogicalBinding && + stableJson(storedLogicalBinding) !== + stableJson(expectedLogicalBinding)) + ) { + context.fail(policyRejected("INDEXEDDB_WRITE")); + return; + } + if ( + (storedBinding === undefined) !== + (storedLogicalBinding === undefined) + ) { + context.fail(corrupt("INDEXEDDB_WRITE")); + return; + } + if (!storedBinding) { + watchWrite(bindingStore.add(expectedBinding), context); + watchWrite( + logicalBindingStore.add(expectedLogicalBinding), + context, + ); + } + }, + ); + }, + ); const logicalKey = logicalObjectKey( input.scope, input.objectId, ); - const objectRequest = nativeTransaction - .objectStore(OBJECT_STORE) - .get(logicalKey); - objectRequest.onsuccess = () => { - const storedCurrent = objectRequest.result; - if ( - storedCurrent !== undefined && - !isStoredObjectRow(storedCurrent) - ) { - context.fail(corrupt("INDEXEDDB_WRITE")); - return; - } - const current: OpfsPreparedObject | undefined = - storedCurrent?.preparedObject; - if ( - !generationMatches( - current, - input.expectedGeneration, - ) || - input.targetGeneration !== - (current?.descriptor.generation ?? 0) + 1 - ) { - context.fail(conflict("INDEXEDDB_WRITE")); - return; - } - const currentBytes = - current?.descriptor.byteLength ?? 0; - const reservedBytes = - input.mutation === "PUT" - ? Math.max(0, input.targetByteLength - currentBytes) - : 0; - const budgetKey = storageBudgetKey(input.scope); - const budgetRequest = nativeTransaction - .objectStore(BUDGET_STORE) - .get(budgetKey); - budgetRequest.onsuccess = () => { - const budgetResult = budgetRequest.result; + onIndexedDbRequest( + nativeTransaction.objectStore(OBJECT_STORE).get(logicalKey), + context, + (storedCurrent) => { if ( - budgetResult !== undefined && - !isBudgetRow(budgetResult) + storedCurrent !== undefined && + !isStoredObjectRow(storedCurrent) ) { context.fail(corrupt("INDEXEDDB_WRITE")); return; } + const current: OpfsPreparedObject | undefined = + storedCurrent?.preparedObject; if ( - budgetResult && - (budgetResult.hardBudgetBytes !== - input.targetStoragePolicy.hardBudgetBytes || - budgetResult.namespace !== input.scope.namespace || - budgetResult.authorityToken !== - input.scope.authorityToken || - budgetResult.namespaceToken !== - input.scope.namespaceToken || - budgetResult.partitionToken !== - input.scope.partitionToken) + !generationMatches( + current, + input.expectedGeneration, + ) || + input.targetGeneration !== + (current?.descriptor.generation ?? 0) + 1 ) { - context.fail(policyRejected("INDEXEDDB_WRITE")); + context.fail(conflict("INDEXEDDB_WRITE")); return; } - if (!budgetResult && current) { - context.fail(corrupt("INDEXEDDB_WRITE")); - return; - } - const budget: StoredBudgetRow = - budgetResult ?? { - budgetKey, - namespace: input.scope.namespace, - authorityToken: input.scope.authorityToken, - namespaceToken: input.scope.namespaceToken, - partitionToken: input.scope.partitionToken, - hardBudgetBytes: - input.targetStoragePolicy.hardBudgetBytes, - committedBytes: 0, - reservedBytes: 0, - }; - if ( - budget.committedBytes + - budget.reservedBytes + - reservedBytes > - budget.hardBudgetBytes - ) { - context.fail(limitExceeded("INDEXEDDB_WRITE")); - return; - } - const nextBudget: StoredBudgetRow = Object.freeze({ - ...budget, - reservedBytes: - budget.reservedBytes + reservedBytes, - }); - nativeTransaction - .objectStore(BUDGET_STORE) - .put(nextBudget); - const row: StoredJournalRow = Object.freeze({ - ...input, - logicalKey, - fencingToken, - phase: "PREPARING", - budgetReservation: Object.freeze({ - namespace: input.scope.namespace, - reservedBytes, - hardBudgetBytes: - input.targetStoragePolicy.hardBudgetBytes, - }), - }); - nativeTransaction - .objectStore(JOURNAL_STORE) - .add(row); - context.succeed(row); - }; - }; + const currentBytes = + current?.descriptor.byteLength ?? 0; + const reservedBytes = + input.mutation === "PUT" + ? Math.max(0, input.targetByteLength - currentBytes) + : 0; + const budgetKey = storageBudgetKey(input.scope); + onIndexedDbRequest( + nativeTransaction.objectStore(BUDGET_STORE).get(budgetKey), + context, + (budgetResult) => { + if ( + budgetResult !== undefined && + !isBudgetRow(budgetResult) + ) { + context.fail(corrupt("INDEXEDDB_WRITE")); + return; + } + if ( + budgetResult && + (budgetResult.hardBudgetBytes !== + input.targetStoragePolicy.hardBudgetBytes || + budgetResult.namespace !== input.scope.namespace || + budgetResult.authorityToken !== + input.scope.authorityToken || + budgetResult.namespaceToken !== + input.scope.namespaceToken || + budgetResult.partitionToken !== + input.scope.partitionToken) + ) { + context.fail(policyRejected("INDEXEDDB_WRITE")); + return; + } + if (!budgetResult && current) { + context.fail(corrupt("INDEXEDDB_WRITE")); + return; + } + const budget: StoredBudgetRow = + budgetResult ?? { + budgetKey, + namespace: input.scope.namespace, + authorityToken: input.scope.authorityToken, + namespaceToken: input.scope.namespaceToken, + partitionToken: input.scope.partitionToken, + hardBudgetBytes: + input.targetStoragePolicy.hardBudgetBytes, + committedBytes: 0, + reservedBytes: 0, + }; + if ( + budget.committedBytes + + budget.reservedBytes + + reservedBytes > + budget.hardBudgetBytes + ) { + context.fail(limitExceeded("INDEXEDDB_WRITE")); + return; + } + const nextBudget: StoredBudgetRow = Object.freeze({ + ...budget, + reservedBytes: + budget.reservedBytes + reservedBytes, + }); + watchWrite( + nativeTransaction.objectStore(BUDGET_STORE).put(nextBudget), + context, + ); + const row: StoredJournalRow = Object.freeze({ + ...input, + logicalKey, + fencingToken, + phase: "PREPARING", + budgetReservation: Object.freeze({ + namespace: input.scope.namespace, + reservedBytes, + hardBudgetBytes: + input.targetStoragePolicy.hardBudgetBytes, + }), + }); + // OP-1. The `by-logical-key` index is unique, so a second open + // row for the same object is rejected here rather than by any + // predicate the journal evaluated: the ConstraintError belongs + // to this request, and it is now reported as such. + watchWrite( + nativeTransaction.objectStore(JOURNAL_STORE).add(row), + context, + ); + context.succeed(row); + }, + ); + }, + ); }, ), ); @@ -459,7 +556,7 @@ export function createIndexedDbOpfsJournal( phase: "FILES_READY", preparedObject, }); - store.put(updated); + watchWrite(store.put(updated), context); context.succeed(updated); }, ); @@ -493,24 +590,27 @@ export function createIndexedDbOpfsJournal( "INDEXEDDB_WRITE", (transaction, context) => { const store = transaction.objectStore(JOURNAL_STORE); - const request = store.get(transactionId); - request.onsuccess = () => { - if (request.result === undefined) { - context.succeed(undefined); - return; - } - if ( - !isStoredJournalRow(request.result) || - !isBoundScope(request.result.scope) || - request.result.fencingToken !== fencingToken || - request.result.phase !== "COMMITTED" - ) { - context.fail(conflict("INDEXEDDB_WRITE")); - return; - } - store.delete(transactionId); - context.succeed(undefined); - }; + onIndexedDbRequest( + store.get(transactionId), + context, + (stored) => { + if (stored === undefined) { + context.succeed(undefined); + return; + } + if ( + !isStoredJournalRow(stored) || + !isBoundScope(stored.scope) || + stored.fencingToken !== fencingToken || + stored.phase !== "COMMITTED" + ) { + context.fail(conflict("INDEXEDDB_WRITE")); + return; + } + watchWrite(store.delete(transactionId), context); + context.succeed(undefined); + }, + ); }, ), ); @@ -529,53 +629,56 @@ export function createIndexedDbOpfsJournal( (transaction, context) => { const journalStore = transaction.objectStore(JOURNAL_STORE); - const request = journalStore.get(transactionId); - request.onsuccess = () => { - if (request.result === undefined) { - context.succeed(undefined); - return; - } - const row = request.result; - if ( - !isStoredJournalRow(row) || - !isBoundScope(row.scope) || - row.fencingToken !== fencingToken || - row.phase === "COMMITTED" - ) { - context.fail(conflict("INDEXEDDB_WRITE")); - return; - } - const budgetStore = - transaction.objectStore(BUDGET_STORE); - const budgetRequest = budgetStore.get( - storageBudgetKey(row.scope), - ); - budgetRequest.onsuccess = () => { - if (!isBudgetRow(budgetRequest.result)) { - context.fail(corrupt("INDEXEDDB_WRITE")); + onIndexedDbRequest( + journalStore.get(transactionId), + context, + (row) => { + if (row === undefined) { + context.succeed(undefined); return; } - const budget = budgetRequest.result; if ( - budget.reservedBytes < - row.budgetReservation.reservedBytes + !isStoredJournalRow(row) || + !isBoundScope(row.scope) || + row.fencingToken !== fencingToken || + row.phase === "COMMITTED" ) { - context.fail(corrupt("INDEXEDDB_WRITE")); + context.fail(conflict("INDEXEDDB_WRITE")); return; } - putOrDeleteBudget( - budgetStore, - Object.freeze({ - ...budget, - reservedBytes: - budget.reservedBytes - - row.budgetReservation.reservedBytes, - }), + const budgetStore = + transaction.objectStore(BUDGET_STORE); + onIndexedDbRequest( + budgetStore.get(storageBudgetKey(row.scope)), + context, + (budget) => { + if (!isBudgetRow(budget)) { + context.fail(corrupt("INDEXEDDB_WRITE")); + return; + } + if ( + budget.reservedBytes < + row.budgetReservation.reservedBytes + ) { + context.fail(corrupt("INDEXEDDB_WRITE")); + return; + } + putOrDeleteBudget( + budgetStore, + Object.freeze({ + ...budget, + reservedBytes: + budget.reservedBytes - + row.budgetReservation.reservedBytes, + }), + context, + ); + watchWrite(journalStore.delete(transactionId), context); + context.succeed(undefined); + }, ); - journalStore.delete(transactionId); - context.succeed(undefined); - }; - }; + }, + ); }, ), ); @@ -597,40 +700,43 @@ export function createIndexedDbOpfsJournal( "INDEXEDDB_READ", (transaction, context) => { const rows: OpfsJournalTransaction[] = []; - const request = transaction - .objectStore(JOURNAL_STORE) - .index(STARTED_AT_INDEX) - .openCursor(); - request.onsuccess = () => { - const cursor = request.result; - if (!cursor) { + walkIndexedDbCursor({ + request: transaction + .objectStore(JOURNAL_STORE) + .index(STARTED_AT_INDEX) + .openCursor(), + sink: context, + translate: translateFor("INDEXEDDB_READ"), + // OP-4. Neither a signal nor a budget is passed: the journal + // offers no cancellation and bounds the page on `limit` alone. + visit: ({ cursor }) => { + // The row is validated before the page limit is checked, so a + // corrupt row one past the page still fails the read rather + // than being hidden behind `moreAvailable`. + if ( + !isStoredJournalRow(cursor.value) || + !isBoundScope(cursor.value.scope) + ) { + context.fail(corrupt("INDEXEDDB_READ")); + // `fail` aborts, so the pump has nowhere to go. Suspending + // without ever resuming says that without claiming a summary + // the scan never reached. + return { kind: "SUSPEND" }; + } + if (rows.length === limit) return { kind: "STOP" }; + rows.push(cursor.value); + return { kind: "CONTINUE" }; + }, + done: (summary) => { context.succeed( Object.freeze({ transactions: Object.freeze(rows), - moreAvailable: false, + moreAvailable: + summary.reason === "STOPPED" && rows.length === limit, }), ); - return; - } - if ( - !isStoredJournalRow(cursor.value) || - !isBoundScope(cursor.value.scope) - ) { - context.fail(corrupt("INDEXEDDB_READ")); - return; - } - if (rows.length === limit) { - context.succeed( - Object.freeze({ - transactions: Object.freeze(rows), - moreAvailable: true, - }), - ); - return; - } - rows.push(cursor.value); - cursor.continue(); - }; + }, + }); }, ), ); @@ -670,46 +776,47 @@ export function createIndexedDbOpfsJournal( false, ); const objects: OpfsPreparedObject[] = []; - const cursorRequest = transaction - .objectStore(OBJECT_STORE) - .index(SCOPE_OBJECT_INDEX) - .openCursor(range); - cursorRequest.onsuccess = () => { - const cursor = cursorRequest.result; - if (!cursor) { + walkIndexedDbCursor({ + request: transaction + .objectStore(OBJECT_STORE) + .index(SCOPE_OBJECT_INDEX) + .openCursor(range), + sink: context, + translate: translateFor("INDEXEDDB_READ"), + visit: ({ cursor }) => { + if ( + !isStoredObjectRow(cursor.value) || + !sameScope( + cursor.value.preparedObject.descriptor.scope, + request.scope, + ) + ) { + context.fail(corrupt("INDEXEDDB_READ")); + return { kind: "SUSPEND" }; + } + if (objects.length === request.limit) { + return { kind: "STOP" }; + } + objects.push(cursor.value.preparedObject); + return { kind: "CONTINUE" }; + }, + done: (summary) => { + // A page cut short by the limit hands back the cursor the + // caller resumes from; an exhausted scan has nothing to resume. + const more = + summary.reason === "STOPPED" && + objects.length === request.limit; context.succeed( Object.freeze({ objects: Object.freeze(objects), - nextObjectId: null, - moreAvailable: false, + nextObjectId: more + ? objects.at(-1)?.descriptor.objectId ?? null + : null, + moreAvailable: more, }), ); - return; - } - if ( - !isStoredObjectRow(cursor.value) || - !sameScope( - cursor.value.preparedObject.descriptor.scope, - request.scope, - ) - ) { - context.fail(corrupt("INDEXEDDB_READ")); - return; - } - if (objects.length === request.limit) { - context.succeed( - Object.freeze({ - objects: Object.freeze(objects), - nextObjectId: - objects.at(-1)?.descriptor.objectId ?? null, - moreAvailable: true, - }), - ); - return; - } - objects.push(cursor.value.preparedObject); - cursor.continue(); - }; + }, + }); }, ), ); @@ -731,34 +838,34 @@ export function createIndexedDbOpfsJournal( "readonly", "INDEXEDDB_READ", (transaction, context) => { - const request = transaction - .objectStore(CHUNK_REFERENCE_STORE) - .get(referenceKey); - request.onsuccess = () => { - if (request.result === undefined) { - context.succeed(false); - return; - } - if ( - !isChunkReference(request.result) || - request.result.referenceKey !== referenceKey || - request.result.scopeKey !== storageScopeKey(scope) - ) { - context.fail(corrupt("INDEXEDDB_READ")); - return; - } - context.succeed(request.result.referenceCount > 0); - }; + onIndexedDbRequest( + transaction + .objectStore(CHUNK_REFERENCE_STORE) + .get(referenceKey), + context, + (stored) => { + if (stored === undefined) { + context.succeed(false); + return; + } + if ( + !isChunkReference(stored) || + stored.referenceKey !== referenceKey || + stored.scopeKey !== storageScopeKey(scope) + ) { + context.fail(corrupt("INDEXEDDB_READ")); + return; + } + context.succeed(stored.referenceCount > 0); + }, + ); }, ), ); }, close() { - closed = true; - database?.close(); - database = null; - opening = null; + connection.close(); }, }; @@ -786,122 +893,133 @@ export function createIndexedDbOpfsJournal( (nativeTransaction, context) => { const journalStore = nativeTransaction.objectStore(JOURNAL_STORE); - const journalRequest = journalStore.get(transactionId); - journalRequest.onsuccess = () => { - const row = journalRequest.result; - if ( - !isStoredJournalRow(row) || - !isBoundScope(row.scope) || - row.fencingToken !== fencingToken || - row.mutation !== mutation - ) { - context.fail(conflict("INDEXEDDB_WRITE")); - return; - } - if (row.phase === "COMMITTED") { - context.succeed(row); - return; - } - if ( - mutation === "PUT" && - (row.phase !== "FILES_READY" || !row.preparedObject) - ) { - context.fail(conflict("INDEXEDDB_WRITE")); - return; - } - if (mutation === "DELETE" && row.phase !== "PREPARING") { - context.fail(conflict("INDEXEDDB_WRITE")); - return; - } - - const objectStore = - nativeTransaction.objectStore(OBJECT_STORE); - const objectRequest = objectStore.get(row.logicalKey); - objectRequest.onsuccess = () => { - const storedCurrent = objectRequest.result; + onIndexedDbRequest( + journalStore.get(transactionId), + context, + (row) => { if ( - storedCurrent !== undefined && - !isStoredObjectRow(storedCurrent) - ) { - context.fail(corrupt("INDEXEDDB_WRITE")); - return; - } - const current: OpfsPreparedObject | undefined = - storedCurrent?.preparedObject; - if ( - !generationMatches(current, row.expectedGeneration) + !isStoredJournalRow(row) || + !isBoundScope(row.scope) || + row.fencingToken !== fencingToken || + row.mutation !== mutation ) { context.fail(conflict("INDEXEDDB_WRITE")); return; } - const budgetStore = - nativeTransaction.objectStore(BUDGET_STORE); - const budgetRequest = budgetStore.get( - storageBudgetKey(row.scope), - ); - budgetRequest.onsuccess = () => { - if (!isBudgetRow(budgetRequest.result)) { - context.fail(corrupt("INDEXEDDB_WRITE")); - return; - } - const budget = budgetRequest.result; - const currentBytes = - current?.descriptor.byteLength ?? 0; - const nextBytes = - mutation === "PUT" ? row.targetByteLength : 0; - const nextCommitted = - budget.committedBytes - currentBytes + nextBytes; - const nextReserved = - budget.reservedBytes - - row.budgetReservation.reservedBytes; - if ( - nextCommitted < 0 || - nextReserved < 0 || - nextCommitted + nextReserved > - budget.hardBudgetBytes - ) { - context.fail(corrupt("INDEXEDDB_WRITE")); - return; - } + if (row.phase === "COMMITTED") { + context.succeed(row); + return; + } + if ( + mutation === "PUT" && + (row.phase !== "FILES_READY" || !row.preparedObject) + ) { + context.fail(conflict("INDEXEDDB_WRITE")); + return; + } + if (mutation === "DELETE" && row.phase !== "PREPARING") { + context.fail(conflict("INDEXEDDB_WRITE")); + return; + } - const referenceDeltas = chunkReferenceDeltas( - current, - mutation === "PUT" ? row.preparedObject : undefined, - ); - applyChunkReferenceDeltas( - nativeTransaction.objectStore( - CHUNK_REFERENCE_STORE, - ), - row.scope, - referenceDeltas, - context, - () => { - putOrDeleteBudget( - budgetStore, - Object.freeze({ - ...budget, - committedBytes: nextCommitted, - reservedBytes: nextReserved, - }), - ); - if (mutation === "PUT") { - objectStore.put( - storedObjectRow(row.preparedObject!), + const objectStore = + nativeTransaction.objectStore(OBJECT_STORE); + onIndexedDbRequest( + objectStore.get(row.logicalKey), + context, + (storedCurrent) => { + if ( + storedCurrent !== undefined && + !isStoredObjectRow(storedCurrent) + ) { + context.fail(corrupt("INDEXEDDB_WRITE")); + return; + } + const current: OpfsPreparedObject | undefined = + storedCurrent?.preparedObject; + if ( + !generationMatches(current, row.expectedGeneration) + ) { + context.fail(conflict("INDEXEDDB_WRITE")); + return; + } + const budgetStore = + nativeTransaction.objectStore(BUDGET_STORE); + onIndexedDbRequest( + budgetStore.get(storageBudgetKey(row.scope)), + context, + (budget) => { + if (!isBudgetRow(budget)) { + context.fail(corrupt("INDEXEDDB_WRITE")); + return; + } + const currentBytes = + current?.descriptor.byteLength ?? 0; + const nextBytes = + mutation === "PUT" ? row.targetByteLength : 0; + const nextCommitted = + budget.committedBytes - currentBytes + nextBytes; + const nextReserved = + budget.reservedBytes - + row.budgetReservation.reservedBytes; + if ( + nextCommitted < 0 || + nextReserved < 0 || + nextCommitted + nextReserved > + budget.hardBudgetBytes + ) { + context.fail(corrupt("INDEXEDDB_WRITE")); + return; + } + + const referenceDeltas = chunkReferenceDeltas( + current, + mutation === "PUT" ? row.preparedObject : undefined, ); - } else { - objectStore.delete(row.logicalKey); - } - const committed: StoredJournalRow = Object.freeze({ - ...row, - phase: "COMMITTED", - }); - journalStore.put(committed); - context.succeed(committed); - }, - ); - }; - }; - }; + applyChunkReferenceDeltas( + nativeTransaction.objectStore( + CHUNK_REFERENCE_STORE, + ), + row.scope, + referenceDeltas, + context, + () => { + putOrDeleteBudget( + budgetStore, + Object.freeze({ + ...budget, + committedBytes: nextCommitted, + reservedBytes: nextReserved, + }), + context, + ); + if (mutation === "PUT") { + watchWrite( + objectStore.put( + storedObjectRow(row.preparedObject!), + ), + context, + ); + } else { + watchWrite( + objectStore.delete(row.logicalKey), + context, + ); + } + const committed: StoredJournalRow = Object.freeze({ + ...row, + phase: "COMMITTED", + }); + watchWrite(journalStore.put(committed), context); + context.succeed(committed); + }, + ); + }, + ); + }, + ); + }, + ); }, ), ); @@ -924,18 +1042,21 @@ export function createIndexedDbOpfsJournal( "INDEXEDDB_WRITE", (transaction, context) => { const store = transaction.objectStore(JOURNAL_STORE); - const request = store.get(transactionId); - request.onsuccess = () => { - if ( - !isStoredJournalRow(request.result) || - !isBoundScope(request.result.scope) || - request.result.fencingToken !== fencingToken - ) { - context.fail(conflict("INDEXEDDB_WRITE")); - return; - } - update(request.result, context, store); - }; + onIndexedDbRequest( + store.get(transactionId), + context, + (stored) => { + if ( + !isStoredJournalRow(stored) || + !isBoundScope(stored.scope) || + stored.fencingToken !== fencingToken + ) { + context.fail(conflict("INDEXEDDB_WRITE")); + return; + } + update(stored, context, store); + }, + ); }, ), ); @@ -945,7 +1066,7 @@ export function createIndexedDbOpfsJournal( operation: BrowserDataOperation, task: (db: IDBDatabase) => Promise>, ): Promise> { - const opened = await openDatabase(); + const opened = await connection.acquire(); if (!opened.ok) return opened; try { const result = await task(opened.value); @@ -958,119 +1079,6 @@ export function createIndexedDbOpfsJournal( } } - async function openDatabase(): Promise> { - if (closed || !factory) { - return browserDataFailure("UNSUPPORTED", "INDEXEDDB_OPEN", { - recovery: "ONLINE_ONLY", - }); - } - if (database) return browserDataSuccess(database); - if (opening) return await opening; - - const currentOpening = new Promise>( - (resolve) => { - let settled = false; - let blockedTimer: unknown; - const settle = ( - result: BrowserDataResult, - ): void => { - if (settled) return; - settled = true; - if (blockedTimer !== undefined) { - scheduler.clearTimeout(blockedTimer); - } - resolve(result); - }; - let request: IDBOpenDBRequest; - try { - request = factory.open(databaseName, DATABASE_VERSION); - } catch (error) { - settle(mapIndexedDbException(error, "INDEXEDDB_OPEN")); - return; - } - request.onupgradeneeded = (event) => { - const db = request.result; - if (event.oldVersion !== 0) { - request.transaction?.abort(); - return; - } - const journalStore = db.createObjectStore(JOURNAL_STORE, { - keyPath: "transactionId", - }); - journalStore.createIndex( - LOGICAL_KEY_INDEX, - "logicalKey", - { unique: true }, - ); - journalStore.createIndex( - STARTED_AT_INDEX, - "startedAtEpochMs", - { unique: false }, - ); - const objectStore = db.createObjectStore(OBJECT_STORE, { - keyPath: "logicalKey", - }); - objectStore.createIndex( - SCOPE_OBJECT_INDEX, - "scopeObjectKey", - { unique: true }, - ); - db.createObjectStore(BUDGET_STORE, { - keyPath: "budgetKey", - }); - db.createObjectStore(SCOPE_BINDING_STORE, { - keyPath: "scopeKey", - }); - db.createObjectStore(LOGICAL_SCOPE_BINDING_STORE, { - keyPath: "logicalScopeKey", - }); - db.createObjectStore(CHUNK_REFERENCE_STORE, { - keyPath: "referenceKey", - }); - }; - request.onblocked = () => { - if (blockedTimer !== undefined) return; - blockedTimer = scheduler.setTimeout(() => { - settle( - browserDataFailure("BLOCKED", "INDEXEDDB_OPEN", { - retryable: true, - recovery: "RELOAD_OTHER_CONTEXTS", - }), - ); - }, blockedTimeoutMs); - }; - request.onerror = () => - settle( - mapIndexedDbException( - request.error, - "INDEXEDDB_OPEN", - ), - ); - request.onsuccess = () => { - if (settled || closed) { - request.result.close(); - return; - } - database = request.result; - database.onversionchange = () => { - database?.close(); - database = null; - opening = null; - }; - database.onclose = () => { - database = null; - opening = null; - }; - settle(browserDataSuccess(request.result)); - }; - }, - ).finally(() => { - if (opening === currentOpening) opening = null; - }); - opening = currentOpening; - return await currentOpening; - } - function observe( result: BrowserDataResult, operation: BrowserDataOperation, @@ -1095,6 +1103,13 @@ export function createIndexedDbOpfsJournal( } } +/** + * Every readwrite transaction is strict because the journal is the durable + * record of a two-phase OPFS mutation: a write that is only queued when the + * tab goes away would leave files on disk that no journal row claims. Reads + * pass `undefined`, which opens with no options bag at all rather than with + * `{durability:"default"}` — the form this file has always used. + */ function runTransaction( database: IDBDatabase, storeNames: readonly string[], @@ -1105,88 +1120,21 @@ function runTransaction( context: TransactionContext, ) => void, ): Promise> { - return new Promise((resolve) => { - let value: Value | undefined; - let hasValue = false; - let explicitFailure: BrowserDataResult | null = null; - let settled = false; - let transaction: IDBTransaction; - try { - transaction = - mode === "readwrite" - ? strictReadwriteTransaction(database, storeNames) - : database.transaction([...storeNames], mode); - } catch (error) { - resolve(mapIndexedDbException(error, operation)); - return; - } - const settle = (result: BrowserDataResult): void => { - if (settled) return; - settled = true; - resolve(result); - }; - const context: TransactionContext = { - succeed(nextValue) { - value = nextValue; - hasValue = true; - }, - fail(result) { - if (explicitFailure) return; - explicitFailure = result; - try { - transaction.abort(); - } catch { - settle(result); - } - }, - }; - transaction.oncomplete = () => { - if (!hasValue) { - settle( - browserDataFailure("UNAVAILABLE", operation, { - retryable: true, - recovery: "REOPEN", - }), - ); - return; - } - settle(browserDataSuccess(value as Value)); - }; - transaction.onabort = () => - settle( - explicitFailure ?? - mapIndexedDbException(transaction.error, operation), - ); - transaction.onerror = () => { - // onabort owns the single failure result. - }; - try { - run(transaction, context); - } catch (error) { - explicitFailure = mapIndexedDbException(error, operation); - try { - transaction.abort(); - } catch { - settle(explicitFailure); - } - } - }); -} - -function strictReadwriteTransaction( - database: IDBDatabase, - storeNames: readonly string[], -): IDBTransaction { - try { - return database.transaction([...storeNames], "readwrite", { - durability: "strict", - }); - } catch (error) { - if (error instanceof TypeError) { - return database.transaction([...storeNames], "readwrite"); - } - throw error; + if (mode === "versionchange") { + // The journal only ever opens readonly or readwrite transactions; a + // versionchange transaction belongs to the open request, not here. + return Promise.resolve( + browserDataFailure("INVALID_INPUT", operation), + ); } + return runIndexedDbTransaction({ + database, + stores: storeNames, + mode, + translate: translateFor(operation), + durability: mode === "readwrite" ? "strict" : undefined, + queue: run, + }); } function applyChunkReferenceDeltas( @@ -1204,40 +1152,45 @@ function applyChunkReferenceDeltas( let remaining = entries.length; for (const [digestHex, delta] of entries) { const referenceKey = chunkReferenceKey(scope, digestHex); - const request = store.get(referenceKey); - request.onsuccess = () => { - if ( - request.result !== undefined && - (!isChunkReference(request.result) || - request.result.referenceKey !== referenceKey || - request.result.scopeKey !== storageScopeKey(scope)) - ) { - context.fail(corrupt("INDEXEDDB_WRITE")); - return; - } - const current = - (request.result as StoredChunkReference | undefined) - ?.referenceCount ?? 0; - const next = current + delta; - if (!Number.isSafeInteger(next) || next < 0) { - context.fail(corrupt("INDEXEDDB_WRITE")); - return; - } - if (next === 0) { - store.delete(referenceKey); - } else { - store.put( - Object.freeze({ - referenceKey, - scopeKey: storageScopeKey(scope), - digestHex, - referenceCount: next, - }), - ); - } - remaining -= 1; - if (remaining === 0) completed(); - }; + onIndexedDbRequest( + store.get(referenceKey), + context, + (stored) => { + if ( + stored !== undefined && + (!isChunkReference(stored) || + stored.referenceKey !== referenceKey || + stored.scopeKey !== storageScopeKey(scope)) + ) { + context.fail(corrupt("INDEXEDDB_WRITE")); + return; + } + const current = + (stored as StoredChunkReference | undefined)?.referenceCount ?? 0; + const next = current + delta; + if (!Number.isSafeInteger(next) || next < 0) { + context.fail(corrupt("INDEXEDDB_WRITE")); + return; + } + if (next === 0) { + watchWrite(store.delete(referenceKey), context); + } else { + watchWrite( + store.put( + Object.freeze({ + referenceKey, + scopeKey: storageScopeKey(scope), + digestHex, + referenceCount: next, + }), + ), + context, + ); + } + remaining -= 1; + if (remaining === 0) completed(); + }, + ); } } @@ -1258,12 +1211,16 @@ function chunkReferenceDeltas( function putOrDeleteBudget( store: IDBObjectStore, budget: StoredBudgetRow, + sink: IndexedDbRequestSink, ): void { + // Separate calls rather than one over a ternary: `IDBRequest` is invariant + // in its result through the `this` type of its handlers, so the two request + // types have no useful union. if (budget.committedBytes === 0 && budget.reservedBytes === 0) { - store.delete(budget.budgetKey); - } else { - store.put(budget); + watchWrite(store.delete(budget.budgetKey), sink); + return; } + watchWrite(store.put(budget), sink); } function storedObjectRow( @@ -1784,34 +1741,141 @@ function stableJson(value: unknown): string { throw new TypeError("Journal value is not JSON-safe."); } -function conflict( - operation: BrowserDataOperation, -): BrowserDataResult { - return browserDataFailure("CONFLICT", operation, { - recovery: "REOPEN", +/** + * `browserDataFailure` and `mapIndexedDbException` build a `Result`, while the + * kernel's `translate` and `context.fail` want the failure on its own. Both + * only ever build the failure arm, so the branch below narrows rather than + * claims. + */ +function failureOf(result: BrowserDataResult): BrowserDataFailure { + if (result.ok) { + throw new TypeError("A browser data failure was expected."); + } + return result.error; +} + +/** + * A write nobody waits on still has to report its own failure. This file wired + * no request `onerror` at all before the kernel, so a unique-index + * `ConstraintError` reached the caller only as whatever `transaction.error` + * happened to hold once the store unwound — a provenance the journal never + * chose and cannot rely on. + * + * `requestFailed` records without aborting, which is deliberate: the store + * already aborts a transaction whose request error goes unhandled, and calling + * `fail` here would report the journal as the party that rejected a write the + * index rejected. + */ +function watchWrite( + request: IDBRequest, + sink: IndexedDbRequestSink, +): void { + onIndexedDbRequest(request, sink, () => { + // A write's own success publishes nothing; the transaction's completion + // does. }); } -function corrupt( - operation: BrowserDataOperation, -): BrowserDataResult { - return browserDataFailure("CORRUPT_DATA", operation, { - recovery: "READ_ONLY", - }); +function conflict(operation: BrowserDataOperation): BrowserDataFailure { + return failureOf( + browserDataFailure("CONFLICT", operation, { recovery: "REOPEN" }), + ); +} + +function corrupt(operation: BrowserDataOperation): BrowserDataFailure { + return failureOf( + browserDataFailure("CORRUPT_DATA", operation, { recovery: "READ_ONLY" }), + ); } function policyRejected( operation: BrowserDataOperation, -): BrowserDataResult { - return browserDataFailure("POLICY_REJECTED", operation, { - recovery: "READ_ONLY", - }); +): BrowserDataFailure { + return failureOf( + browserDataFailure("POLICY_REJECTED", operation, { + recovery: "READ_ONLY", + }), + ); } function limitExceeded( operation: BrowserDataOperation, -): BrowserDataResult { - return browserDataFailure("LIMIT_EXCEEDED", operation, { - recovery: "EXPORT_REQUIRED", - }); +): BrowserDataFailure { + return failureOf( + browserDataFailure("LIMIT_EXCEEDED", operation, { + recovery: "EXPORT_REQUIRED", + }), + ); +} + +/** + * STO-01. The journal keeps `mapIndexedDbException`, which the IndexedDB + * runtime and maintenance share, rather than the checkpoint store's own table: + * the same native error is a different answer in the two families and unifying + * them is a separate change from moving the mechanics onto the kernel. + * + * A translator per operation, because the journal labels a read and a write + * differently. The connection always translates as `INDEXEDDB_OPEN`: an open + * failure names the operation it belongs to, not the call that happened to ask + * for the connection, and that is why `withDatabase` returns it unobserved. + */ +function translateFor( + operation: BrowserDataOperation, +): IndexedDbTranslate { + return (cause) => { + switch (cause.kind) { + case "NATIVE_EXCEPTION": + return failureOf(mapIndexedDbException(cause.error, operation)); + case "BLOCKED": + case "BLOCKED_DEADLINE": + // The journal reports the same answer whether the blocked event is + // itself terminal or a deadline ran out: a `blockedTimeoutMs` of 0 is + // a valid configuration here, and it must not report a different code + // from the same standing conflict. + return failureOf( + browserDataFailure("BLOCKED", operation, { + retryable: true, + recovery: "RELOAD_OTHER_CONTEXTS", + }), + ); + case "CLOSED": + case "UNSUPPORTED": + // A closed journal and a realm without IndexedDB are the same answer + // to the caller: this store cannot serve the request at all, so work + // online instead of retrying. + return failureOf( + browserDataFailure("UNSUPPORTED", operation, { + recovery: "ONLINE_ONLY", + }), + ); + case "NO_VALUE_PRODUCED": + return failureOf( + browserDataFailure("UNAVAILABLE", operation, { + retryable: true, + recovery: "REOPEN", + }), + ); + case "UPGRADE_REJECTED": + case "CALLER_ABORT": + // Rejecting an upgrade aborts the versionchange transaction, so the + // open request fails with an `AbortError` and the caller has always + // seen ABORTED. `CALLER_ABORT` shares the arm because the journal + // exposes no cancellation — only the connection handle's own close + // cancels an open, and its waiters are told CLOSED instead. + return failureOf(browserDataFailure("ABORTED", operation)); + case "ADMISSION_REJECTED": + // Unreachable: no `admit` callback is installed. The journal validates + // stored rows per transaction rather than at open time. + return failureOf( + browserDataFailure("UNAVAILABLE", operation, { + retryable: true, + recovery: "REOPEN", + }), + ); + default: { + const exhaustive: never = cause; + return exhaustive; + } + } + }; } diff --git a/src/adapters/telemetry/best-effort-telemetry.ts b/src/adapters/telemetry/best-effort-telemetry.ts index 3d69c77..7797b10 100644 --- a/src/adapters/telemetry/best-effort-telemetry.ts +++ b/src/adapters/telemetry/best-effort-telemetry.ts @@ -46,8 +46,6 @@ type TelemetryLifecycle = "ACTIVE" | "DISPOSED"; /** N-11. Documented absolute ceiling for the in-memory best-effort queue. */ export const MAX_TELEMETRY_QUEUE = 10_000; -export { assertBoundedCapacity } from "../platform/bounded-capacity.ts"; - export function createTelemetryAdapter( options: TelemetryAdapterOptions, diff --git a/src/adapters/telemetry/index.ts b/src/adapters/telemetry/index.ts new file mode 100644 index 0000000..f6abed3 --- /dev/null +++ b/src/adapters/telemetry/index.ts @@ -0,0 +1,7 @@ +export { + createTelemetryAdapter, + MAX_TELEMETRY_QUEUE, + noOpTelemetry, + type TelemetryAdapter, + type TelemetryAdapterOptions, +} from "./best-effort-telemetry.ts"; diff --git a/src/application/policies/compatibility.ts b/src/application/policies/compatibility.ts index 4bd1b68..3fa4cea 100644 --- a/src/application/policies/compatibility.ts +++ b/src/application/policies/compatibility.ts @@ -4,8 +4,10 @@ * The implementation lives in `src/contracts/compatibility.ts`: it is a pure * predicate over release tokens with no application state, and * `src/contracts/release-tokens.ts` needs it, which previously made contracts - * import the application layer. This module re-exports it for application-side - * and script-side callers. + * import the application layer. This module is retained only as a migration + * shim; internal callers use src/contracts/compatibility.ts directly. + * + * @deprecated Import compatibility contracts from ../../contracts/compatibility.ts. */ export { COMPATIBILITY_TUPLE_FIELDS, diff --git a/src/application/ports/browser-file-storage/indexeddb-port.ts b/src/application/ports/browser-file-storage/indexeddb-port.ts index ca73f04..98ad6eb 100644 --- a/src/application/ports/browser-file-storage/indexeddb-port.ts +++ b/src/application/ports/browser-file-storage/indexeddb-port.ts @@ -21,9 +21,23 @@ export type IndexedDbSynchronizationState = | "CONFIRMED"; export type IndexedDbConnectionStatus = - | Readonly<{ kind: "CLOSED"; reason: "NOT_OPENED" | "VERSION_CHANGE" | "FORCED" }> + | Readonly<{ + kind: "CLOSED"; + /** + * NOT_OPENED means the current open attempt has settled without a live + * connection. A blocked upgrade may therefore be observed as BLOCKED + * while it is waiting, then transition to CLOSED/NOT_OPENED when its + * blocked deadline fails closed. + */ + reason: "NOT_OPENED" | "VERSION_CHANGE" | "FORCED"; + }> | Readonly<{ kind: "OPENING"; targetVersion: number }> | Readonly<{ + /** + * A live open/upgrade attempt is currently waiting for another + * IndexedDB context. BLOCKED is transient and is not the settled state + * after the blocked deadline has expired. + */ kind: "BLOCKED"; currentVersion: number; targetVersion: number; diff --git a/src/application/result.ts b/src/application/result.ts index 561ef7a..8240037 100644 --- a/src/application/result.ts +++ b/src/application/result.ts @@ -1,13 +1,9 @@ /** - * The single success/failure carrier used across application input boundaries. - * Adapters map technology-specific errors to an application failure before - * constructing this value. + * Compatibility re-export for application-side callers from older revisions. * - * The type itself lives in `src/contracts` because both layers need it and - * neither owns it: `src/contracts/server-state.ts` and - * `src/contracts/cursor-pagination.ts` reached back into the application layer - * for it, which made the ownership of the shared vocabulary ambiguous in both - * directions. Contracts is the lower of the two, so the shared shape sits there - * and this module re-exports it for every existing application-side importer. + * The canonical Result definition is src/contracts/result.ts. New code should + * import it from that module so the shared carrier has one public authority. + * + * @deprecated Import Result from ../contracts/result.ts. */ export type { Result } from "../contracts/result.ts"; diff --git a/src/bootstrap/main.tsx b/src/bootstrap/main.tsx index b8e31ab..8157f1b 100644 --- a/src/bootstrap/main.tsx +++ b/src/bootstrap/main.tsx @@ -1,6 +1,6 @@ import { createRoot } from "react-dom/client"; -import { recordBootFailure } from "../adapters/diagnostics/bounded-diagnostics.ts"; +import { recordBootFailure } from "../adapters/diagnostics/index.ts"; import { BootErrorShell } from "../presentation/boundaries/boot-error-shell.tsx"; import "pretendard/dist/web/variable/pretendardvariable.css"; import "@fontsource/ibm-plex-mono/400.css"; diff --git a/src/bootstrap/optional-runtime-host.ts b/src/bootstrap/optional-runtime-host.ts index d6c465d..2ace893 100644 --- a/src/bootstrap/optional-runtime-host.ts +++ b/src/bootstrap/optional-runtime-host.ts @@ -1,7 +1,7 @@ import { createBrowserLifecycleRuntime, type BrowserLifecycleRuntime, -} from "../adapters/platform/browser-lifecycle.ts"; +} from "../adapters/platform/index.ts"; import type { ResolvedRuntimeCapabilities, RuntimeHealth, diff --git a/src/bootstrap/register-service-worker.ts b/src/bootstrap/register-service-worker.ts index ff87d96..24e567b 100644 --- a/src/bootstrap/register-service-worker.ts +++ b/src/bootstrap/register-service-worker.ts @@ -2,7 +2,7 @@ import type { ResolvedRuntimeCapabilities, } from "../contracts/runtime-capabilities.ts"; import type { ServiceWorkerRuntimeHost } from "../contracts/service-worker.ts"; -import { createServiceWorkerPageController } from "../adapters/service-worker/service-worker-page-controller.ts"; +import { createServiceWorkerPageController } from "../adapters/service-worker/index.ts"; /** * §17.5. Composition-side factory. The host object is created without any diff --git a/src/bootstrap/runtime-adapters.ts b/src/bootstrap/runtime-adapters.ts index 4e1ade5..2eb6377 100644 --- a/src/bootstrap/runtime-adapters.ts +++ b/src/bootstrap/runtime-adapters.ts @@ -3,13 +3,14 @@ import { createExternalAuthSessionAdapter, createUnavailableSessionAdapter, type ExternalSessionOwner, -} from "../adapters/auth/external-session-adapter.ts"; -import { createDiagnosticsAdapter } from "../adapters/diagnostics/bounded-diagnostics.ts"; -import { createHttpClient } from "../adapters/http/client.ts"; +} from "../adapters/auth/index.ts"; +import { createDiagnosticsAdapter } from "../adapters/diagnostics/index.ts"; import { createContractHttpExecutor, + createHttpClient, type HttpExecutionObservation, -} from "../adapters/http/http-execution-v3.ts"; + type InstalledHttpOperationExecutor, +} from "../adapters/http/index.ts"; import { attemptBucket, durationBucket, @@ -19,14 +20,14 @@ import { import type { TelemetryEventName } from "../contracts/telemetry.ts"; import { createBrowserCrossContextInvalidationFromHost } from "../adapters/cross-context-invalidation/index.ts"; import { + createConditionalValidatorStore, + createQueryClient, + createServerStateScopeRuntime, createTanStackCacheCoordinator, -} from "../adapters/query-cache/tanstack-cache-coordinator.ts"; -import { createQueryClient } from "../adapters/query-cache/tanstack-query-cache.ts"; -import { createServerStateScopeRuntime } from "../adapters/query-cache/server-state-scope-runtime.ts"; -import { createConditionalValidatorStore } from "../adapters/query-cache/conditional-validator-store.ts"; -import { createBrowserStorageAdapter } from "../adapters/storage/browser-storage-adapter.ts"; -import { createBrowserMutationIntentFactory } from "../adapters/platform/browser-mutation-intent-factory.ts"; -import { createTelemetryAdapter } from "../adapters/telemetry/best-effort-telemetry.ts"; +} from "../adapters/query-cache/index.ts"; +import { createBrowserStorageAdapter } from "../adapters/storage/index.ts"; +import { createBrowserMutationIntentFactory } from "../adapters/platform/index.ts"; +import { createTelemetryAdapter } from "../adapters/telemetry/index.ts"; import { createCsrfTokenProvider } from "../features/tech-log/adapters/http/studio-session-csrf.ts"; import { attachStudioSessionCredentials, @@ -69,6 +70,21 @@ import { } 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를 rollback/compatibility 경로로 쓰려는 제품은 이 네 슬롯을 주입해야 + * 한다. 주입하지 않은 채 V3에서 되돌리면 모든 요청이 실패한다. + * V3(`createContractHttpExecutor`)는 설치된 feature 계약에서 오퍼레이션을 + * 받으므로 이 슬롯과 무관하게 동작한다. + */ export type RuntimeHttpContract = Pick< HttpClientDependencies, "getOperation" | "validatePayload" | "validateRequest" | "mapPayload" @@ -436,10 +452,10 @@ export async function createRuntimeAdapters( * entirely and must set the header itself. If each built its own provider, * one Studio session would hold two different tokens. * - * `execute` calls `getStudioSession` through `contractOperations`, which is - * declared further below — a real ordering hazard, since `attachCredentials` - * (needed to build `contractHttp`, needed to build `contractOperations`) - * needs this provider first. + * `execute` calls `getStudioSession` through `techLogOperations`, which is + * assigned further below — a real ordering hazard, since `attachCredentials` + * (needed to build `contractHttp`, needed to build `contractOperations`, + * needed to build `techLogOperations`) needs this provider first. * * Fix round 1 (C1). The original comment here claimed "`getStudioSession` * is a SAFE operation and needs no CSRF, so there is no true cycle" — that @@ -462,17 +478,17 @@ export async function createRuntimeAdapters( * `await` between this declaration and the real assignment, where a stub * fails loudly instead. */ - let contractOperations: TechLogStudioOperationExecutor = Object.freeze({ + let techLogOperations: TechLogStudioOperationExecutor = Object.freeze({ async execute() { throw new Error( - "contractOperations used before assignment in createRuntimeAdapters — " + + "techLogOperations used before assignment in createRuntimeAdapters — " + "construction order regressed.", ); }, }); const techLogCsrf = createCsrfTokenProvider({ async execute(options) { - const outcome = await contractOperations.execute( + const outcome = await techLogOperations.execute( "getStudioSession", {}, { @@ -554,19 +570,13 @@ export async function createRuntimeAdapters( }, observe: createHttpObservationProjector({ diagnostics, telemetry }), }); - contractOperations = Object.freeze({ - async execute( - operationId: string, - input: unknown, - executionContext: Readonly<{ - routeId: string; - signal?: AbortSignal; - intent?: MutationIntent; - }>, - ) { - const operation = - COMPOSED_CONTRACT_CONTRIBUTIONS.httpByOperationId.get(operationId); - if (!operation) { + const contractOperations: InstalledHttpOperationExecutor = Object.freeze({ + async execute(operation, input, executionContext) { + const installed = + COMPOSED_CONTRACT_CONTRIBUTIONS.httpByOperationId.get( + operation.contract.operationId, + ); + if (!installed) { return Object.freeze({ kind: "CONTRACT_VIOLATION" as const, effect: "NOT_STARTED" as const, @@ -576,7 +586,11 @@ export async function createRuntimeAdapters( }), }); } - const outcome = await contractHttp.execute(operation, input, { + // composeContractContributions deliberately snapshots every installed + // contract. Runtime authority is therefore the validated registry entry, + // not object identity with the feature-owned source declaration. + const executableContract = installed as typeof operation; + const outcome = await contractHttp.execute(executableContract, input, { routeId: executionContext.routeId, scope: serverStateScope.getSnapshot(), ...(executionContext.signal === undefined @@ -608,8 +622,52 @@ export async function createRuntimeAdapters( return outcome; }, }); + /** + * Template sync (ebea300). The platform executor above now takes the + * installed contract itself, so a feature's Input/WireOutput/Problem types + * flow through `createFeatureHttpBinding`. TechLog's four HTTP gateways + * still address operations by id through its own `StudioOperationExecutor`, + * so the id is resolved to the installed contract here — at the one place + * that already owns the registry — instead of being resolved inside the + * platform executor for every caller. Porting those gateways onto the typed + * binding is its own change; nothing about it is decided here. + * + * `!installed` returns the same `FINAL_REQUEST_INVARIANT_FAILED` violation + * the platform executor returns for an operation that is not installed, so + * an unregistered id fails identically on both paths. + */ + techLogOperations = Object.freeze({ + async execute( + operationId: string, + input: unknown, + executionContext: Readonly<{ + routeId: string; + signal?: AbortSignal; + intent?: MutationIntent; + }>, + ) { + const installed = + COMPOSED_CONTRACT_CONTRIBUTIONS.httpByOperationId.get(operationId); + if (!installed) { + return Object.freeze({ + kind: "CONTRACT_VIOLATION" as const, + effect: "NOT_STARTED" as const, + violation: Object.freeze({ + kind: "FINAL_REQUEST_INVARIANT_FAILED" as const, + operation: "REQUEST" as const, + }), + }); + } + return contractOperations.execute( + installed as Parameters[0], + input, + executionContext, + ); + }, + }); const featureInputs = createInstalledFeatureInputs({ - contractOperations, + http: contractOperations, + contractOperations: techLogOperations, studioSource: config.TECH_LOG_STUDIO_SOURCE, publicSource: config.TECH_LOG_PUBLIC_SOURCE, apiBaseUrl: config.API_BASE_URL, diff --git a/src/features/feature-adapter-contribution.ts b/src/features/feature-adapter-contribution.ts new file mode 100644 index 0000000..46cdafc --- /dev/null +++ b/src/features/feature-adapter-contribution.ts @@ -0,0 +1,176 @@ +import type { + ApplicationFeatureId, + ApplicationFeatureInputs, +} from "../application/ports/in/application-api.ts"; +import type { + InstalledHttpOperationExecutor, +} from "../adapters/http/index.ts"; + +/** + * Features augment this registry with the repository identities they consume. + * The provider is a composition capability; feature use cases never import it. + */ +export interface FeatureIndexedDbRepositories {} + +export type FeatureIndexedDbRepositoryId = Extract< + keyof FeatureIndexedDbRepositories, + string +>; + +export type IndexedDbRepositoryProvider = Readonly<{ + get( + repositoryId: RepositoryId, + ): FeatureIndexedDbRepositories[RepositoryId]; +}>; + +export function createIndexedDbRepositoryProvider( + repositories: Readonly>, +): IndexedDbRepositoryProvider { + const snapshot = Object.freeze({ ...repositories }); + return Object.freeze({ + get( + repositoryId: RepositoryId, + ): FeatureIndexedDbRepositories[RepositoryId] { + const repository = snapshot[repositoryId]; + if (!repository) { + throw new TypeError( + `IndexedDB repository is not installed: ${repositoryId}`, + ); + } + return repository as FeatureIndexedDbRepositories[RepositoryId]; + }, + }); +} + +export type FeaturePlatformCapabilities = Readonly<{ + http: InstalledHttpOperationExecutor; + indexedDb: IndexedDbRepositoryProvider; +}>; + +export type FeaturePlatformCapabilityId = + keyof FeaturePlatformCapabilities; + +export type FeatureCapabilitySelection< + Needs extends readonly FeaturePlatformCapabilityId[], +> = Pick; + +const FEATURE_ADAPTER_CONTRIBUTION = Symbol( + "feature-adapter-contribution", +); + +type FeatureAdapterContributionDefinition< + FeatureId extends ApplicationFeatureId, + Needs extends readonly FeaturePlatformCapabilityId[], +> = Readonly<{ + featureId: FeatureId; + needs: Needs; + createInput( + context: FeatureCapabilitySelection, + ): Readonly<{ + featureId: FeatureId; + input: ApplicationFeatureInputs[FeatureId]; + }>; +}>; + +export type FeatureAdapterContribution< + FeatureId extends ApplicationFeatureId, + Needs extends readonly FeaturePlatformCapabilityId[], +> = FeatureAdapterContributionDefinition & + Readonly<{ + [FEATURE_ADAPTER_CONTRIBUTION]: true; + }>; + +export function defineFeatureAdapterContribution< + const FeatureId extends ApplicationFeatureId, + const Needs extends readonly FeaturePlatformCapabilityId[], +>( + contribution: FeatureAdapterContributionDefinition, +): FeatureAdapterContribution { + return Object.freeze({ + ...contribution, + needs: Object.freeze([...contribution.needs]) as unknown as Needs, + [FEATURE_ADAPTER_CONTRIBUTION]: true as const, + }); +} + +type ContributionShape = Readonly<{ + [FEATURE_ADAPTER_CONTRIBUTION]: true; + featureId: ApplicationFeatureId; + needs: readonly FeaturePlatformCapabilityId[]; + createInput: (...args: never[]) => unknown; +}>; + +type ContributionNeeds = + Contribution extends Readonly<{ + needs: readonly (infer Capability)[]; + }> + ? Extract + : never; + +export type ContributionsCapabilityContext< + Contributions extends readonly ContributionShape[], +> = Pick< + FeaturePlatformCapabilities, + ContributionNeeds +>; + +export type InstalledFeatureInputs = Readonly< + Partial +>; + +function setFeatureInput( + target: Partial, + featureId: FeatureId, + input: ApplicationFeatureInputs[FeatureId], +): void { + const writable = target as Record< + ApplicationFeatureId, + ApplicationFeatureInputs[ApplicationFeatureId] + >; + writable[featureId] = input; +} + +function invokeContribution< + FeatureId extends ApplicationFeatureId, + Needs extends readonly FeaturePlatformCapabilityId[], +>( + contribution: FeatureAdapterContribution, + context: FeaturePlatformCapabilities, +) { + return contribution.createInput(context); +} + +/** + * Dynamic catalog assembly stays centralized here. Type authority lives at each + * feature contribution; the only dynamic write is isolated in setFeatureInput. + */ +export function composeFeatureAdapterInputs< + const Contributions extends readonly ContributionShape[], +>( + contributions: Contributions, + enabledFeatureIds: readonly string[], + context: ContributionsCapabilityContext, +): InstalledFeatureInputs { + const enabled = new Set(enabledFeatureIds); + const result: Partial = {}; + + for (const contribution of contributions) { + if (contribution[FEATURE_ADAPTER_CONTRIBUTION] !== true) { + throw new TypeError( + "Feature adapter contribution must be defined through defineFeatureAdapterContribution()", + ); + } + if (!enabled.has(contribution.featureId)) continue; + + const installed = invokeContribution( + contribution as unknown as FeatureAdapterContribution< + ApplicationFeatureId, + readonly FeaturePlatformCapabilityId[] + >, + context as FeaturePlatformCapabilities, + ); + setFeatureInput(result, installed.featureId, installed.input); + } + + return Object.freeze(result); +} diff --git a/src/features/installed-contract-contributions.ts b/src/features/installed-contract-contributions.ts index 753abd9..976a03f 100644 --- a/src/features/installed-contract-contributions.ts +++ b/src/features/installed-contract-contributions.ts @@ -3,35 +3,39 @@ import { type InstalledContractContribution, type InstalledContractPackageIdentity, } from "../contracts/external-contract-runtime.ts"; -import { REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION } from "./reference-feature/contracts/reference-feature-contract-contribution.ts"; -import { REFERENCE_FEATURE_ID } from "./reference-feature/contracts/reference-feature-contract.ts"; import { INSTALLED_PRODUCT_FEATURE_IDS } from "./installed-product-manifest.ts"; +import { REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION } from "./reference-feature/contracts/reference-feature-contract-contribution.ts"; import { TECH_LOG_MANAGEMENT_CONTRIBUTION } from "./tech-log/contracts/tech-log-management-contract-contribution.ts"; import { TECH_LOG_PUBLIC_CONTRIBUTION } from "./tech-log/contracts/tech-log-public-contract-contribution.ts"; import { TECH_LOG_STUDIO_CONTRIBUTION } from "./tech-log/contracts/tech-log-studio-contract-contribution.ts"; +const COMPILED_CONTRACT_CONTRIBUTIONS = Object.freeze([ + REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION, +] as const); + /** - * §4.8. Static contract selection SSOT. + * Central contract installation is aggregation only. * - * A product feature adds exactly one entry per service package here and imports - * the generated package only from - * `src/features//contracts/-contract-contribution.ts`. + * Each feature owns its concrete service/package contribution. This catalog + * selects contributions whose feature is installed; it does not contain + * feature-specific branching or service wiring. + * + * Template sync (ebea300). The manifest-governed contributions are now selected + * by their own `featureId` rather than by this file naming the reference + * feature, so installing another selectable feature is one entry above and no + * edit here. TechLog's three contributions are appended unconditionally: it is + * this product's own domain, not a `SelectableProductFeature`, so the manifest + * does not govern it and the filter must not be able to drop it. */ export const INSTALLED_CONTRACT_CONTRIBUTIONS: readonly InstalledContractContribution[] = - Object.freeze( - INSTALLED_PRODUCT_FEATURE_IDS.includes(REFERENCE_FEATURE_ID) - ? [ - REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION, - TECH_LOG_STUDIO_CONTRIBUTION, - TECH_LOG_PUBLIC_CONTRIBUTION, - TECH_LOG_MANAGEMENT_CONTRIBUTION, - ] - : [ - TECH_LOG_STUDIO_CONTRIBUTION, - TECH_LOG_PUBLIC_CONTRIBUTION, - TECH_LOG_MANAGEMENT_CONTRIBUTION, - ], - ); + Object.freeze([ + ...COMPILED_CONTRACT_CONTRIBUTIONS.filter((contribution) => + INSTALLED_PRODUCT_FEATURE_IDS.includes(contribution.featureId), + ), + TECH_LOG_STUDIO_CONTRIBUTION, + TECH_LOG_PUBLIC_CONTRIBUTION, + TECH_LOG_MANAGEMENT_CONTRIBUTION, + ]); export const COMPOSED_CONTRACT_CONTRIBUTIONS = composeContractContributions( INSTALLED_CONTRACT_CONTRIBUTIONS, diff --git a/src/features/installed-feature-adapters.ts b/src/features/installed-feature-adapters.ts index 316066b..7612ae2 100644 --- a/src/features/installed-feature-adapters.ts +++ b/src/features/installed-feature-adapters.ts @@ -1,44 +1,52 @@ import type { ApplicationFeatureInputs } from "../application/ports/in/application-api.ts"; -import { createReferenceFeatureInstalledInput } from "./reference-feature/adapters/create-reference-feature-input.ts"; -import { REFERENCE_FEATURE_ID } from "./reference-feature/contracts/reference-feature-contract.ts"; -import { createTechLogFeatureInstalledInput } from "./tech-log/adapters/create-tech-log-feature-input.ts"; -import type { CsrfTokenProvider } from "./tech-log/adapters/http/studio-session-csrf.ts"; +import { + composeFeatureAdapterInputs, + type ContributionsCapabilityContext, + type InstalledFeatureInputs, +} from "./feature-adapter-contribution.ts"; +import { REFERENCE_FEATURE_ADAPTER_CONTRIBUTION } from "./reference-feature/adapters/create-reference-feature-input.ts"; +import { + createTechLogFeatureInstalledInput, + type TechLogInstallContext, +} from "./tech-log/adapters/create-tech-log-feature-input.ts"; import { TECH_LOG_FEATURE_ID } from "./tech-log/application/tech-log-feature-input.ts"; import { INSTALLED_PRODUCT_FEATURE_IDS } from "./installed-product-manifest.ts"; +const COMPILED_FEATURE_ADAPTER_CONTRIBUTIONS = Object.freeze([ + REFERENCE_FEATURE_ADAPTER_CONTRIBUTION, +] as const); + +type InstalledFeatureCapabilityContext = + ContributionsCapabilityContext< + typeof COMPILED_FEATURE_ADAPTER_CONTRIBUTIONS + >; + /** - * §3.5. Partial on purpose: a feature the manifest did not select supplies no - * driving input, so consumers have to narrow before calling one. A total type - * here would let feature code compile against an input that is not there. + * Central adapter composition only selects and aggregates feature-owned + * contributions. The feature owns how its application input is bound to the + * reusable platform capabilities declared by its `needs` list. + * + * Template sync (ebea300). TechLog is this product's own domain rather than a + * `SelectableProductFeature`, so it is composed directly instead of through + * the manifest: `INSTALLED_PRODUCT_FEATURE_IDS` does not govern it and its + * input is therefore total, while every manifest-governed contribution stays + * optional because a build may narrow it out. This is the same split the + * previous sync recorded — see `docs/operations/template-merge-2026-08-17.md` + * — expressed through the template's new contribution mechanism. */ -type InstalledFeatureInputs = Readonly< - // Template merge. The reference feature is optional — the manifest may - // narrow it out — so its input stays `Partial`. TechLog is this product's - // own UI and is always installed, so its input is total. - Partial> & - Pick ->; +type ProductFeatureInputs = InstalledFeatureInputs & + Readonly>; export function createInstalledFeatureInputs( - context: Parameters[0] & - Readonly<{ - studioSource: "MOCK" | "HTTP"; - publicSource: "MOCK" | "HTTP"; - apiBaseUrl: string; - requestTimeoutMs: number; - csrf: CsrfTokenProvider; - }>, -): InstalledFeatureInputs { - const techLogFeature = createTechLogFeatureInstalledInput(context); - if (!INSTALLED_PRODUCT_FEATURE_IDS.includes(REFERENCE_FEATURE_ID)) { - // A build that narrowed the reference feature out still ships TechLog. - return Object.freeze({ - [techLogFeature.featureId]: techLogFeature.input, - }) as InstalledFeatureInputs; - } - const referenceFeature = createReferenceFeatureInstalledInput(context); + context: InstalledFeatureCapabilityContext & TechLogInstallContext, +): ProductFeatureInputs { + const techLog = createTechLogFeatureInstalledInput(context); return Object.freeze({ - [referenceFeature.featureId]: referenceFeature.input, - [techLogFeature.featureId]: techLogFeature.input, - }) as InstalledFeatureInputs; + ...composeFeatureAdapterInputs( + COMPILED_FEATURE_ADAPTER_CONTRIBUTIONS, + INSTALLED_PRODUCT_FEATURE_IDS, + context, + ), + [techLog.featureId]: techLog.input, + }) as ProductFeatureInputs; } diff --git a/src/features/installed-feature-runtimes.tsx b/src/features/installed-feature-runtimes.tsx index 603018e..a56c182 100644 --- a/src/features/installed-feature-runtimes.tsx +++ b/src/features/installed-feature-runtimes.tsx @@ -7,13 +7,23 @@ import { PLATFORM_ROUTE_RUNTIME } from "../presentation/routes/route-runtime.tsx * §3.5. A feature the manifest did not select contributes no codec and no route * component, so the router has nothing to mount for it. * - * Template merge. The template gated the reference feature's codecs and route - * components on the manifest. This product deleted that feature's presentation - * layer during the UI migration, so there is nothing left to gate — the import - * would not resolve. The gating belongs back here the day those screens return. + * Template merge. The template aggregates feature-owned runtime contributions + * here and filters them through the manifest — as of ebea300 through + * `COMPILED_FEATURE_RUNTIME_CONTRIBUTIONS`. This product deleted the reference + * feature's presentation layer during the UI migration, so there is no + * contribution to compile and nothing to gate; the import would not resolve. + * Carrying an empty contribution list plus the filter would be dead code that + * neither repository runs, so the aggregation belongs back here the day those + * screens return, together with the contribution they export. + * * TechLog is spread unconditionally: it is this product's own UI, not a * selectable feature. The platform entries are empty on this branch and are * kept in the spread so a later platform route lands here without another edit. + * + * The object spread is also what keeps both catalogs precisely typed: the + * template's `Object.assign(..., ...contributions.map(...))` widens its result + * to `any`, which this product's router cannot afford — it resolves codecs and + * components by route id off these two objects. */ export const ROUTE_CODECS = Object.freeze({ ...PLATFORM_ROUTE_CODECS, diff --git a/src/features/local-draft-feature/adapters/create-local-draft-feature-input.ts b/src/features/local-draft-feature/adapters/create-local-draft-feature-input.ts new file mode 100644 index 0000000..93b62d1 --- /dev/null +++ b/src/features/local-draft-feature/adapters/create-local-draft-feature-input.ts @@ -0,0 +1,41 @@ +import type { + IndexedDbRepositoryPort, +} from "../../../application/ports/browser-file-storage/index.ts"; +import { + defineFeatureAdapterContribution, +} from "../../feature-adapter-contribution.ts"; +import type {} from "../../feature-adapter-contribution.ts"; +import { + createLocalDraftFeatureInput, +} from "../application/local-draft-api.ts"; +import type { LocalDraft } from "../domain/local-draft.ts"; +import { + LOCAL_DRAFT_FEATURE_ID, + LOCAL_DRAFT_REPOSITORY_ID, +} from "../contracts/local-draft-contract.ts"; +import { createLocalDraftStore } from "./local-draft-indexeddb-store.ts"; + +declare module "../../feature-adapter-contribution.ts" { + interface FeatureIndexedDbRepositories { + "local-draft": IndexedDbRepositoryPort; + } +} + +export function createLocalDraftFeatureInstalledInput(context: Readonly<{ + indexedDb: Readonly<{ + get(repositoryId: "local-draft"): IndexedDbRepositoryPort; + }>; +}>) { + const repository = context.indexedDb.get(LOCAL_DRAFT_REPOSITORY_ID); + return Object.freeze({ + featureId: LOCAL_DRAFT_FEATURE_ID, + input: createLocalDraftFeatureInput(createLocalDraftStore(repository)), + }); +} + +export const LOCAL_DRAFT_FEATURE_ADAPTER_CONTRIBUTION = + defineFeatureAdapterContribution({ + featureId: LOCAL_DRAFT_FEATURE_ID, + needs: ["indexedDb"] as const, + createInput: createLocalDraftFeatureInstalledInput, + }); diff --git a/src/features/local-draft-feature/adapters/local-draft-indexeddb-store.ts b/src/features/local-draft-feature/adapters/local-draft-indexeddb-store.ts new file mode 100644 index 0000000..bc777be --- /dev/null +++ b/src/features/local-draft-feature/adapters/local-draft-indexeddb-store.ts @@ -0,0 +1,105 @@ +import type { + BrowserDataFailure, + IndexedDbRepositoryPort, +} from "../../../application/ports/browser-file-storage/index.ts"; +import { + createFailure, + type AppFailure, + type FailureKind, +} from "../../../contracts/errors.ts"; +import type { Result } from "../../../contracts/result.ts"; +import type { + LocalDraftStore, + LocalDraftRecord, + RemoveLocalDraftCommand, + SaveLocalDraftCommand, +} from "../application/local-draft-api.ts"; +import type { LocalDraft } from "../domain/local-draft.ts"; + +function failureKind(failure: BrowserDataFailure): FailureKind { + if (failure.code === "QUOTA_EXCEEDED") return "STORAGE_QUOTA_EXCEEDED"; + if (failure.code === "CONFLICT") return "CONFLICT"; + if (failure.code === "ABORTED") return "REQUEST_ABORTED"; + return "STORAGE_UNAVAILABLE"; +} + +function mapFailure( + failure: BrowserDataFailure, + operationId: string, +): AppFailure { + return createFailure(failureKind(failure), operationId, 0, { + code: `INDEXEDDB_${failure.code}`, + }); +} + +function failed( + failure: BrowserDataFailure, + operationId: string, +): Result { + return Object.freeze({ + ok: false as const, + error: mapFailure(failure, operationId), + }); +} + +/** + * Feature-owned adapter over the reusable IndexedDB repository capability. + * Native IDB objects, migrations, connection leases and quota internals do not + * cross this file. + */ +export function createLocalDraftStore( + repository: IndexedDbRepositoryPort, +): LocalDraftStore { + return Object.freeze({ + async save(command: SaveLocalDraftCommand, signal?: AbortSignal) { + const result = await repository.compareAndSwap({ + key: command.draft.draftId, + value: command.draft, + expectedRevision: command.expectedRevision, + idempotencyKey: command.idempotencyKey, + signal, + }); + return result.ok + ? Object.freeze({ + ok: true as const, + value: Object.freeze({ revision: result.value.revision }), + }) + : failed>( + result.error, + "LOCAL_DRAFT_SAVE", + ); + }, + + async find(draftId: string, signal?: AbortSignal) { + const result = await repository.read(draftId, signal); + if (!result.ok) { + return failed( + result.error, + "LOCAL_DRAFT_FIND", + ); + } + return Object.freeze({ + ok: true as const, + value: + result.value === null + ? null + : Object.freeze({ + draft: result.value.value, + revision: result.value.revision, + }), + }); + }, + + async remove(command: RemoveLocalDraftCommand, signal?: AbortSignal) { + const result = await repository.remove({ + key: command.draftId, + expectedRevision: command.expectedRevision, + idempotencyKey: command.idempotencyKey, + signal, + }); + return result.ok + ? Object.freeze({ ok: true as const, value: undefined }) + : failed(result.error, "LOCAL_DRAFT_REMOVE"); + }, + }); +} diff --git a/src/features/local-draft-feature/application/local-draft-api.ts b/src/features/local-draft-feature/application/local-draft-api.ts new file mode 100644 index 0000000..bed3224 --- /dev/null +++ b/src/features/local-draft-feature/application/local-draft-api.ts @@ -0,0 +1,72 @@ +import type { Result } from "../../../contracts/result.ts"; +import type {} from "../../../application/ports/in/application-api.ts"; +import type { LocalDraft } from "../domain/local-draft.ts"; + +export type LocalDraftRecord = Readonly<{ + draft: LocalDraft; + revision: number; +}>; + +export type SaveLocalDraftCommand = Readonly<{ + draft: LocalDraft; + expectedRevision: number | null; + idempotencyKey: string; +}>; + +export type RemoveLocalDraftCommand = Readonly<{ + draftId: string; + expectedRevision: number; + idempotencyKey: string; +}>; + +export type LocalDraftStore = Readonly<{ + save( + command: SaveLocalDraftCommand, + signal?: AbortSignal, + ): Promise>>; + find( + draftId: string, + signal?: AbortSignal, + ): Promise>; + remove( + command: RemoveLocalDraftCommand, + signal?: AbortSignal, + ): Promise>; +}>; + +export type LocalDraftFeatureInput = Readonly<{ + saveDraft( + command: SaveLocalDraftCommand, + context?: Readonly<{ signal?: AbortSignal }>, + ): Promise>>; + findDraft( + draftId: string, + context?: Readonly<{ signal?: AbortSignal }>, + ): Promise>; + removeDraft( + command: RemoveLocalDraftCommand, + context?: Readonly<{ signal?: AbortSignal }>, + ): Promise>; +}>; + +declare module "../../../application/ports/in/application-api.ts" { + interface ApplicationFeatureInputs { + "local-draft": LocalDraftFeatureInput; + } +} + +export function createLocalDraftFeatureInput( + store: LocalDraftStore, +): LocalDraftFeatureInput { + return Object.freeze({ + saveDraft(command, context) { + return store.save(command, context?.signal); + }, + findDraft(draftId, context) { + return store.find(draftId, context?.signal); + }, + removeDraft(command, context) { + return store.remove(command, context?.signal); + }, + }); +} diff --git a/src/features/local-draft-feature/contracts/local-draft-contract.ts b/src/features/local-draft-feature/contracts/local-draft-contract.ts new file mode 100644 index 0000000..d2d1983 --- /dev/null +++ b/src/features/local-draft-feature/contracts/local-draft-contract.ts @@ -0,0 +1,2 @@ +export const LOCAL_DRAFT_FEATURE_ID = "local-draft" as const; +export const LOCAL_DRAFT_REPOSITORY_ID = "local-draft" as const; diff --git a/src/features/local-draft-feature/domain/local-draft.ts b/src/features/local-draft-feature/domain/local-draft.ts new file mode 100644 index 0000000..877fe12 --- /dev/null +++ b/src/features/local-draft-feature/domain/local-draft.ts @@ -0,0 +1,21 @@ +export type LocalDraft = Readonly<{ + draftId: string; + title: string; + body: string; +}>; + +export function createLocalDraft(values: LocalDraft): LocalDraft { + const draftId = values.draftId.trim(); + const title = values.title.trim(); + if (!draftId || !title) { + throw new TypeError("Local draft requires draftId and title"); + } + if (title.length > 160 || values.body.length > 100_000) { + throw new TypeError("Local draft exceeds bounded field limits"); + } + return Object.freeze({ + draftId, + title, + body: values.body, + }); +} diff --git a/src/features/reference-feature/README.md b/src/features/reference-feature/README.md index 1062d0c..cc34c8d 100644 --- a/src/features/reference-feature/README.md +++ b/src/features/reference-feature/README.md @@ -19,16 +19,19 @@ augmentation으로 `"reference-feature": ReferenceFeatureInput`을 기여하므 별도 cast나 runtime shape 확인 없이 정확한 input type을 받는다. 다만 동적 호출로 설치되지 않은 ID가 들어오는 경우를 위해 `get`의 runtime guard도 유지한다. -예측 가능한 실패는 `src/application/result.ts`의 공통 -`Result`로 반환한다. `AppFailure.kind`는 +예측 가능한 실패는 canonical shared contract인 +`src/contracts/result.ts`의 `Result`로 반환한다. +`src/application/result.ts`는 기존 호출자를 위한 deprecated migration shim일 +뿐 새 코드의 import 경로가 아니다. `AppFailure.kind`는 `ERROR_REGISTRY` key에서 파생된 닫힌 vocabulary이며, transport 호환 이름인 `ApiFailure`는 같은 type의 alias다. -HTTP adapter의 operation map은 operation ID마다 허용된 route ID, request shape와 -성공 value type을 함께 묶는다. raw HTTP executor의 성공값은 Zod request/response -검증과 feature mapper를 통과한 뒤 operation별 runtime result guard에서 typed -executor로 승격된다. 따라서 gateway 메서드는 개별 응답 cast 없이 정확한 결과를 -반환하고, operation/route/request 조합 오류는 typecheck에서 차단된다. +HTTP adapter는 `src/adapters/http/feature-http-binding.ts`의 capability-specific +typed binding을 사용한다. feature는 operation ID, route ID, request type, 성공 +value type, mapper만 소유한다. timeout/cancellation/auth/transport/contract +violation을 `AppFailure`로 정규화하는 책임은 reusable HTTP capability가 소유한다. +따라서 gateway 메서드는 transport outcome이나 runtime result guard를 반복 구현하지 +않고도 정확한 결과 타입을 반환한다. route codec과 URL builder는 `src/presentation/routes/route-codecs.ts`, route type은 `route-contract.ts`, React context/provider/hook은 `route-input.tsx`가 각각 @@ -39,12 +42,16 @@ route codec과 URL builder는 `src/presentation/routes/route-codecs.ts`, route t ## 설치 지점 -- 직렬화 계약: `src/features/installed-feature-contracts.ts` -- component/codec: `src/features/installed-feature-runtimes.tsx` -- bootstrap input 조립: `src/features/installed-feature-adapters.ts` +feature가 실제 contribution을 소유한다. -새 기능도 이 세 지점에 contribution을 합성하되 feature ID를 generic application, -router나 HTTP client에 하드코딩하지 않는다. +- contract: `reference-feature-contract.ts` +- component/codec: `REFERENCE_FEATURE_RUNTIME_CONTRIBUTION` +- bootstrap input: `REFERENCE_FEATURE_ADAPTER_CONTRIBUTION` + +중앙 파일인 `installed-feature-contracts.ts`, +`installed-feature-runtimes.tsx`, `installed-feature-adapters.ts`는 선택된 +contribution을 합치는 역할만 한다. 새 기능의 내부 조립 규칙을 중앙 catalog에 +추가하지 않는다. ## 검증과 제거 diff --git a/src/features/reference-feature/adapters/create-reference-feature-input.ts b/src/features/reference-feature/adapters/create-reference-feature-input.ts index d6c040a..536d712 100644 --- a/src/features/reference-feature/adapters/create-reference-feature-input.ts +++ b/src/features/reference-feature/adapters/create-reference-feature-input.ts @@ -1,195 +1,45 @@ -import type { Result } from "../../../application/result.ts"; -import type { ApiFailure, FailureKind } from "../../../contracts/errors.ts"; -import type { FailureEffectCertainty } from "../../../contracts/errors.ts"; -import type { MutationIntent } from "../../../contracts/mutation-intent.ts"; import { - createFailure, - kindForStatus, -} from "../../../contracts/errors.ts"; -import type { HttpExecutionOutcome } from "../../../adapters/http/http-execution-v3.ts"; + createFeatureHttpBinding, + type InstalledHttpOperationExecutor, +} from "../../../adapters/http/index.ts"; +import { + defineFeatureAdapterContribution, +} from "../../feature-adapter-contribution.ts"; import { createReferenceFeatureInput } from "../application/reference-feature-api.ts"; import { REFERENCE_FEATURE_ID, } from "../contracts/reference-feature-contract.ts"; -import { mapReferenceOperation } from "../contracts/reference-mapper.ts"; import { createReferenceHttpGateway, - type RawReferenceHttpExecutor, - type ReferenceHttpRequest, - type ReferenceOperationId, + REFERENCE_HTTP_OPERATIONS, } from "./reference-http-gateway.ts"; -export type InstalledContractOperationExecutor = Readonly<{ - execute( - operationId: string, - input: unknown, - context: Readonly<{ - routeId: string; - signal?: AbortSignal; - intent?: MutationIntent; - }>, - ): Promise>; -}>; +export type InstalledContractOperationExecutor = + InstalledHttpOperationExecutor; /** - * The installed feature consumes the composed external-contract operation - * registry through one descriptor-driven executor. Legacy ApiOperation/schema - * registries are intentionally absent from this production composition seam. + * Feature-owned composition seam. + * + * The feature receives only the HTTP capability it declares in `needs`. + * HTTP lifecycle/error normalization stays in the reusable capability binding. */ export function createReferenceFeatureInstalledInput(context: Readonly<{ - contractOperations: InstalledContractOperationExecutor; + http: InstalledHttpOperationExecutor; }>) { - const rawHttp: RawReferenceHttpExecutor = Object.freeze({ - async execute(request) { - const operationId = request.operationId; - const input = inputFor(request); - const signal = "signal" in request ? request.signal : undefined; - const intent = "intent" in request ? request.intent : undefined; - const outcome = await context.contractOperations.execute( - operationId, - input, - { - // §7.4. The gateway owns the low-cardinality route identity; losing - // it here is what made every V3 diagnostic unattributable. - routeId: request.routeId, - ...(signal === undefined ? {} : { signal }), - ...(intent === undefined ? {} : { intent }), - }, - ); - return projectExecutionOutcome(operationId, outcome); - }, - }); + const http = createFeatureHttpBinding( + context.http, + REFERENCE_HTTP_OPERATIONS, + ); return Object.freeze({ featureId: REFERENCE_FEATURE_ID, - input: createReferenceFeatureInput(createReferenceHttpGateway(rawHttp)), + input: createReferenceFeatureInput(createReferenceHttpGateway(http)), }); } -function inputFor( - request: ReferenceHttpRequest, -): unknown { - switch (request.operationId) { - case "LIST_REFERENCE_RESOURCES": - return request.searchParams; - case "CREATE_REFERENCE_RESOURCE": - return request.body; - case "GET_REFERENCE_RESOURCE": - return request.pathParams; - } -} - -function projectExecutionOutcome( - operationId: ReferenceOperationId, - outcome: HttpExecutionOutcome, -): Result { - switch (outcome.kind) { - case "SUCCESS": { - const mapped = mapReferenceOperation(operationId, outcome.value); - return mapped.ok - ? Object.freeze({ ok: true as const, value: mapped.value }) - : failure( - "MAPPING_CONTRACT_VIOLATION", - operationId, - mapped.code, - { effect: outcome.effect }, - ); - } - case "PROBLEM": - return failure( - kindForStatus(outcome.metadata.status), - operationId, - "CONTRACT_PROBLEM", - { httpStatus: outcome.metadata.status, effect: outcome.effect }, - ); - case "UNAUTHENTICATED": - return failure("AUTH_REQUIRED", operationId, "UNAUTHENTICATED", { - effect: outcome.effect, - }); - case "FORBIDDEN": - return failure("FORBIDDEN", operationId, "FORBIDDEN", { - effect: outcome.effect, - }); - case "RATE_LIMITED": - return failure("RATE_LIMITED", operationId, "RATE_LIMITED", { - ...(outcome.retryAfterMs === undefined - ? {} - : { retryAfterMs: outcome.retryAfterMs }), - effect: outcome.effect, - }); - case "CANCELLED": - return failure("REQUEST_ABORTED", operationId, "REQUEST_ABORTED", { - effect: outcome.effect, - }); - case "AUTH_INTEGRATION_FAILURE": - // §7.7. A configuration or collaborator breach, not a session state, so - // it must not drive the re-authentication surface. - return failure( - "AUTH_INTEGRATION_FAILURE", - operationId, - outcome.reason, - { effect: outcome.effect }, - ); - case "TRANSPORT_FAILURE": - return failure( - outcome.failure.kind === "TIMEOUT" - ? "REQUEST_TIMEOUT" - : outcome.failure.kind === "ABORTED_BY_SCOPE" - ? "SCOPE_GENERATION_CHANGED" - : "NETWORK_UNREACHABLE", - operationId, - outcome.failure.kind, - { effect: outcome.effect }, - ); - case "CONTRACT_VIOLATION": - return failure( - failureKindForViolation(outcome.violation.kind), - operationId, - outcome.violation.kind, - { effect: outcome.effect }, - ); - } -} - -function failureKindForViolation( - violation: Extract< - HttpExecutionOutcome, - { kind: "CONTRACT_VIOLATION" } - >["violation"]["kind"], -): FailureKind { - switch (violation) { - case "CONTENT_TYPE_MISMATCH": - return "CONTENT_TYPE_MISMATCH"; - case "RESPONSE_TOO_LARGE": - return "RESPONSE_BODY_LIMIT"; - case "UTF8_INVALID": - case "JSON_INVALID": - return "MALFORMED_JSON"; - case "MAPPING_CONTRACT_VIOLATION": - return "MAPPING_CONTRACT_VIOLATION"; - case "SCOPE_FENCED": - return "SCOPE_GENERATION_CHANGED"; - case "SUCCESS_SCHEMA_INVALID": - case "PROBLEM_SCHEMA_INVALID": - case "VALIDATOR_RUNTIME_FAILURE": - return "SCHEMA_MISMATCH"; - default: - return "ENVELOPE_MISMATCH"; - } -} - -function failure( - kind: FailureKind, - operationId: string, - code: string, - details: Readonly<{ - httpStatus?: number; - retryAfterMs?: number; - effect?: FailureEffectCertainty; - }> = {}, -): Result { - return Object.freeze({ - ok: false as const, - error: createFailure(kind, operationId, 0, { code, ...details }), +export const REFERENCE_FEATURE_ADAPTER_CONTRIBUTION = + defineFeatureAdapterContribution({ + featureId: REFERENCE_FEATURE_ID, + needs: ["http"] as const, + createInput: createReferenceFeatureInstalledInput, }); -} diff --git a/src/features/reference-feature/adapters/reference-http-gateway.ts b/src/features/reference-feature/adapters/reference-http-gateway.ts index 34e2874..37a5c1f 100644 --- a/src/features/reference-feature/adapters/reference-http-gateway.ts +++ b/src/features/reference-feature/adapters/reference-http-gateway.ts @@ -1,160 +1,82 @@ -import type { Result } from "../../../application/result.ts"; import { - createFailure, - type ApiFailure, -} from "../../../contracts/errors.ts"; + defineFeatureHttpOperationForRoutes, + type FeatureHttpBinding, +} from "../../../adapters/http/index.ts"; +import { + CREATE_REFERENCE_RESOURCE_CONTRACT, + GET_REFERENCE_RESOURCE_CONTRACT, + LIST_REFERENCE_RESOURCES_CONTRACT, +} from "../contracts/reference-feature-contract-contribution.ts"; +import { + REFERENCE_FEATURE_CONTRACT, +} from "../contracts/reference-feature-contract.ts"; +import { + mapReferenceResourceListPayload, + mapReferenceResourcePayload, +} from "../contracts/reference-mapper.ts"; import type { - ReferenceCreateCommand, ReferenceGateway, - ReferenceListFilters, } from "../application/reference-feature-api.ts"; -import type { ReferenceResource } from "../domain/reference-resource.ts"; -import type { MutationIntent } from "../../../contracts/mutation-intent.ts"; -type ReferenceOperationMap = Readonly<{ - LIST_REFERENCE_RESOURCES: Readonly<{ - request: Readonly<{ - operationId: "LIST_REFERENCE_RESOURCES"; - routeId: "REFERENCE_RESOURCE_LIST"; - searchParams: ReferenceListFilters; - signal?: AbortSignal; - }>; - value: readonly ReferenceResource[]; - }>; - CREATE_REFERENCE_RESOURCE: Readonly<{ - request: Readonly<{ - operationId: "CREATE_REFERENCE_RESOURCE"; - routeId: "REFERENCE_RESOURCE_LIST"; - body: ReferenceCreateCommand; - signal?: AbortSignal; - intent?: MutationIntent; - }>; - value: ReferenceResource; - }>; - GET_REFERENCE_RESOURCE: Readonly<{ - request: Readonly<{ - operationId: "GET_REFERENCE_RESOURCE"; - routeId: "REFERENCE_RESOURCE_DETAIL"; - pathParams: Readonly<{ resourceId: string }>; - signal?: AbortSignal; - }>; - value: ReferenceResource; - }>; -}>; +export type ReferenceFeatureRouteId = + keyof typeof REFERENCE_FEATURE_CONTRACT.routes; -export type ReferenceOperationId = keyof ReferenceOperationMap; +const defineReferenceHttpOperation = + defineFeatureHttpOperationForRoutes(); -export type ReferenceHttpRequest< - OperationId extends ReferenceOperationId, -> = ReferenceOperationMap[OperationId]["request"]; +export const REFERENCE_HTTP_OPERATIONS = Object.freeze({ + LIST_REFERENCE_RESOURCES: defineReferenceHttpOperation({ + contract: LIST_REFERENCE_RESOURCES_CONTRACT, + routeId: "REFERENCE_RESOURCE_LIST", + mapSuccess: mapReferenceResourceListPayload, + }), + CREATE_REFERENCE_RESOURCE: defineReferenceHttpOperation({ + contract: CREATE_REFERENCE_RESOURCE_CONTRACT, + routeId: "REFERENCE_RESOURCE_LIST", + mapSuccess: mapReferenceResourcePayload, + mapProblem(problem, metadata) { + if (metadata.status === 409) { + return Object.freeze({ + kind: "CONFLICT" as const, + code: problem.code ?? "REFERENCE_RESOURCE_CONFLICT", + }); + } + if (metadata.status === 422) { + return Object.freeze({ + kind: "VALIDATION_REJECTED" as const, + code: problem.code ?? "REFERENCE_RESOURCE_REJECTED", + }); + } + return undefined; + }, + }), + GET_REFERENCE_RESOURCE: defineReferenceHttpOperation({ + contract: GET_REFERENCE_RESOURCE_CONTRACT, + routeId: "REFERENCE_RESOURCE_DETAIL", + mapSuccess: mapReferenceResourcePayload, + }), +} as const); -export type ReferenceHttpResult< - OperationId extends ReferenceOperationId, -> = Result; - -export type RawReferenceHttpExecutor = Readonly<{ - execute( - request: ReferenceHttpRequest, - ): Promise>; -}>; +export type ReferenceHttpBinding = FeatureHttpBinding< + typeof REFERENCE_HTTP_OPERATIONS +>; export function createReferenceHttpGateway( - http: RawReferenceHttpExecutor, + http: ReferenceHttpBinding, ): ReferenceGateway { return Object.freeze({ - async list( - filters: ReferenceListFilters, - context?: Readonly<{ signal?: AbortSignal }>, - ) { - const result = await http.execute({ - operationId: "LIST_REFERENCE_RESOURCES", - routeId: "REFERENCE_RESOURCE_LIST", - searchParams: filters, - signal: context?.signal, - }); - return projectListResult(result); + list(filters, context) { + return http.execute("LIST_REFERENCE_RESOURCES", filters, context); }, - async create( - command: ReferenceCreateCommand, - context?: Readonly<{ - signal?: AbortSignal; - intent?: MutationIntent; - }>, - ) { - const result = await http.execute({ - operationId: "CREATE_REFERENCE_RESOURCE", - routeId: "REFERENCE_RESOURCE_LIST", - body: command, - signal: context?.signal, - intent: context?.intent, - }); - return projectResourceResult("CREATE_REFERENCE_RESOURCE", result); + create(command, context) { + return http.execute("CREATE_REFERENCE_RESOURCE", command, context); }, - async get( - resourceId: string, - context?: Readonly<{ signal?: AbortSignal }>, - ) { - const result = await http.execute({ - operationId: "GET_REFERENCE_RESOURCE", - routeId: "REFERENCE_RESOURCE_DETAIL", - pathParams: { resourceId }, - signal: context?.signal, - }); - return projectResourceResult("GET_REFERENCE_RESOURCE", result); + get(resourceId, context) { + return http.execute( + "GET_REFERENCE_RESOURCE", + Object.freeze({ resourceId }), + context, + ); }, }); } - -function projectListResult( - result: Result, -): ReferenceHttpResult<"LIST_REFERENCE_RESOURCES"> { - if (!result.ok) return result; - if (isReferenceResourceList(result.value)) { - return { ok: true, value: result.value }; - } - return typedResultFailure("LIST_REFERENCE_RESOURCES"); -} - -function projectResourceResult( - operationId: - | "CREATE_REFERENCE_RESOURCE" - | "GET_REFERENCE_RESOURCE", - result: Result, -): Result { - if (!result.ok) return result; - if (isReferenceResource(result.value)) { - return { ok: true, value: result.value }; - } - return typedResultFailure(operationId); -} - -function typedResultFailure(operationId: ReferenceOperationId) { - return { - ok: false as const, - error: createFailure( - "MAPPING_CONTRACT_VIOLATION", - operationId, - 0, - { code: "BOUND_RESULT_TYPE_MISMATCH" }, - ), - }; -} - -function isReferenceResourceList( - value: unknown, -): value is readonly ReferenceResource[] { - return Array.isArray(value) && value.every(isReferenceResource); -} - -function isReferenceResource(value: unknown): value is ReferenceResource { - if (!value || typeof value !== "object") return false; - const candidate = value as Readonly>; - return ( - typeof candidate.id === "string" && - candidate.id.length > 0 && - typeof candidate.displayName === "string" && - candidate.displayName.length > 0 && - (candidate.createdAt === null || - typeof candidate.createdAt === "string") - ); -} diff --git a/src/features/reference-feature/application/reference-feature-api.ts b/src/features/reference-feature/application/reference-feature-api.ts index 4ee895e..9ea8f21 100644 --- a/src/features/reference-feature/application/reference-feature-api.ts +++ b/src/features/reference-feature/application/reference-feature-api.ts @@ -1,4 +1,4 @@ -import type { Result } from "../../../application/result.ts"; +import type { Result } from "../../../contracts/result.ts"; import type {} from "../../../application/ports/in/application-api.ts"; import { toReferenceView, diff --git a/src/features/reference-feature/contracts/reference-feature-contract-contribution.ts b/src/features/reference-feature/contracts/reference-feature-contract-contribution.ts index a16c67b..6688829 100644 --- a/src/features/reference-feature/contracts/reference-feature-contract-contribution.ts +++ b/src/features/reference-feature/contracts/reference-feature-contract-contribution.ts @@ -2,17 +2,22 @@ import { z } from "zod"; import type { CommandEffectDescriptor, - HttpRequestProjection, InstalledContractContribution, InstalledHttpContract, RuntimeValidator, } from "../../../contracts/external-contract-runtime.ts"; import { REFERENCE_FEATURE_ID } from "./reference-feature-contract.ts"; import { + createReferenceResourceCommandSchema, + referenceProblemSchema, + referenceResourceDtoSchema, referenceResourceListQuerySchema, referenceResourceParamsSchema, + type ReferenceProblem, } from "./reference-schemas.ts"; +export type { ReferenceProblem } from "./reference-schemas.ts"; + /** * §4.8. The single `TEMPLATE_FIXTURE` contribution. It keeps the reference * HTTP vertical executable as deterministic template data and is excluded from @@ -53,33 +58,10 @@ function zodValidator( }); } -const referenceResourceDto = z - .object({ - id: z.string().min(1).max(120), - name: z.string().min(1).max(240), - createdAt: z.string().min(1).optional(), - }) - .strip(); - -const 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(), - }) - .strip(); - -export type ReferenceProblem = z.output; - -const PROBLEM_VALIDATOR = zodValidator("ReferenceProblem", problemSchema); - -const createCommandSchema = z - .object({ - name: z.string().trim().min(1).max(120), - note: z.string().trim().max(500).optional(), - }) - .strict(); +const PROBLEM_VALIDATOR = zodValidator( + "ReferenceProblem", + referenceProblemSchema, +); /** * Fixture-side classifier standing in for the package-provided pure bounded @@ -87,17 +69,17 @@ const createCommandSchema = z */ const CREATE_EFFECT: CommandEffectDescriptor = Object.freeze({ successEffect: "APPLIED_CONFIRMED" as const, - classifyProblem({ status }: Readonly<{ status: number; problem: ReferenceProblem }>) { - if (status === 400 || status === 409 || status === 422) return "NOT_APPLIED"; + classifyProblem({ + status, + }: Readonly<{ status: number; problem: ReferenceProblem }>) { + if (status === 400 || status === 409 || status === 422) { + return "NOT_APPLIED"; + } return "MAYBE_APPLIED"; }, }); -const LIST_REFERENCE_RESOURCES: InstalledHttpContract< - z.output, - readonly z.output[], - ReferenceProblem -> = Object.freeze({ +export const LIST_REFERENCE_RESOURCES_CONTRACT = Object.freeze({ contract: Object.freeze({ operationId: "LIST_REFERENCE_RESOURCES", method: "GET" as const, @@ -108,7 +90,7 @@ const LIST_REFERENCE_RESOURCES: InstalledHttpContract< ), outputValidator: zodValidator( "ReferenceResourceListPayload", - z.array(referenceResourceDto).max(100), + z.array(referenceResourceDtoSchema).max(100), ), problemValidator: PROBLEM_VALIDATOR, acceptedStatuses: Object.freeze([200]), @@ -139,13 +121,13 @@ const LIST_REFERENCE_RESOURCES: InstalledHttpContract< authProfileId: "REFERENCE_EXTERNAL_BEARER", diagnosticsOperation: "reference.list", }), -}); - -const GET_REFERENCE_RESOURCE: InstalledHttpContract< - z.output, - z.output, +}) satisfies InstalledHttpContract< + z.output, + readonly z.output[], ReferenceProblem -> = Object.freeze({ +>; + +export const GET_REFERENCE_RESOURCE_CONTRACT = Object.freeze({ contract: Object.freeze({ operationId: "GET_REFERENCE_RESOURCE", method: "GET" as const, @@ -156,7 +138,7 @@ const GET_REFERENCE_RESOURCE: InstalledHttpContract< ), outputValidator: zodValidator( "ReferenceResourcePayload", - referenceResourceDto, + referenceResourceDtoSchema, ), problemValidator: PROBLEM_VALIDATOR, acceptedStatuses: Object.freeze([200]), @@ -183,24 +165,24 @@ const GET_REFERENCE_RESOURCE: InstalledHttpContract< authProfileId: "REFERENCE_EXTERNAL_BEARER", diagnosticsOperation: "reference.detail", }), -}); - -const CREATE_REFERENCE_RESOURCE: InstalledHttpContract< - z.output, - z.output, +}) satisfies InstalledHttpContract< + z.output, + z.output, ReferenceProblem -> = Object.freeze({ +>; + +export const CREATE_REFERENCE_RESOURCE_CONTRACT = Object.freeze({ contract: Object.freeze({ operationId: "CREATE_REFERENCE_RESOURCE", method: "POST" as const, pathTemplate: "/api/reference-resources", inputValidator: zodValidator( "CreateReferenceResourceCommand", - createCommandSchema, + createReferenceResourceCommandSchema, ), outputValidator: zodValidator( "ReferenceResourcePayload", - referenceResourceDto, + referenceResourceDtoSchema, ), problemValidator: PROBLEM_VALIDATOR, acceptedStatuses: Object.freeze([200, 201]), @@ -213,7 +195,7 @@ const CREATE_REFERENCE_RESOURCE: InstalledHttpContract< operationIdentityField: "idempotencyKey", }), commandEffect: CREATE_EFFECT, - projectRequest(input: z.output) { + projectRequest(input: z.output) { return Object.freeze({ pathValues: Object.freeze({}), queryEntries: Object.freeze([]), @@ -235,7 +217,11 @@ const CREATE_REFERENCE_RESOURCE: InstalledHttpContract< authProfileId: "REFERENCE_EXTERNAL_BEARER", diagnosticsOperation: "reference.create", }), -}); +}) satisfies InstalledHttpContract< + z.output, + z.output, + ReferenceProblem +>; export const REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION: InstalledContractContribution = Object.freeze({ @@ -247,9 +233,9 @@ export const REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION: InstalledContractContribut revision: 1 as const, }), http: Object.freeze([ - LIST_REFERENCE_RESOURCES, - GET_REFERENCE_RESOURCE, - CREATE_REFERENCE_RESOURCE, + LIST_REFERENCE_RESOURCES_CONTRACT, + GET_REFERENCE_RESOURCE_CONTRACT, + CREATE_REFERENCE_RESOURCE_CONTRACT, ]) as readonly InstalledHttpContract[], events: Object.freeze([]), }); diff --git a/src/features/reference-feature/contracts/reference-mapper.ts b/src/features/reference-feature/contracts/reference-mapper.ts index 11b226e..8645f7e 100644 --- a/src/features/reference-feature/contracts/reference-mapper.ts +++ b/src/features/reference-feature/contracts/reference-mapper.ts @@ -5,9 +5,10 @@ import { import { mappingFailure, mappingSuccess, - type MappingResult, type InstalledBoundaryMapper, + type MappingResult, } from "../../../contracts/boundary-mapper.ts"; +import type { ReferenceResourceDto } from "./reference-schemas.ts"; export type ReferenceResourceView = Readonly<{ resourceId: string; @@ -16,20 +17,19 @@ export type ReferenceResourceView = Readonly<{ optimistic?: boolean; }>; -function mapReferenceDto(value: unknown): MappingResult { - if (!value || typeof value !== "object") { - return mappingFailure("MAPPING_INVARIANT_REJECTED"); - } - const dto = value as Record; - if (typeof dto.id !== "string" || typeof dto.name !== "string") { - return mappingFailure("MAPPING_INVARIANT_REJECTED"); - } +/** + * Operation-specific mapper. The HTTP contract has already validated the wire + * shape, so this mapper owns only wire -> domain construction. + */ +export function mapReferenceResourcePayload( + dto: ReferenceResourceDto, +): MappingResult { try { return mappingSuccess( createReferenceResource({ id: dto.id, displayName: dto.name, - createdAt: typeof dto.createdAt === "string" ? dto.createdAt : null, + createdAt: dto.createdAt ?? null, }), ); } catch { @@ -37,28 +37,70 @@ function mapReferenceDto(value: unknown): MappingResult { } } +export function mapReferenceResourceListPayload( + payload: readonly ReferenceResourceDto[], +): MappingResult { + const output: ReferenceResource[] = []; + for (const item of payload) { + const mapped = mapReferenceResourcePayload(item); + if (!mapped.ok) return mapped; + output.push(mapped.value); + } + return mappingSuccess(Object.freeze(output)); +} + +function isReferenceResourceDto(value: unknown): value is ReferenceResourceDto { + if (!value || typeof value !== "object" || Array.isArray(value)) return false; + const dto = value as Record; + return ( + typeof dto.id === "string" && + typeof dto.name === "string" && + (dto.createdAt === undefined || typeof dto.createdAt === "string") + ); +} + +function mapUnknownReferenceResourcePayload( + value: unknown, +): MappingResult { + return isReferenceResourceDto(value) + ? mapReferenceResourcePayload(value) + : mappingFailure("MAPPING_INVARIANT_REJECTED"); +} + +function mapUnknownReferenceResourceListPayload( + value: unknown, +): MappingResult { + if ( + !Array.isArray(value) || + value.length > 100 || + !value.every(isReferenceResourceDto) + ) { + return mappingFailure( + Array.isArray(value) && value.length > 100 + ? "OUTPUT_LIMIT_EXCEEDED" + : "MAPPING_INVARIANT_REJECTED", + ); + } + return mapReferenceResourceListPayload(value); +} + +/** + * Registry-facing compatibility projection. The registry is intentionally + * untyped, so its adapter performs the defensive shape check. Feature HTTP + * bindings use the typed operation-specific mappers above. + */ export function mapReferenceOperation( operationId: string, payload: unknown, ): MappingResult { if (operationId === "LIST_REFERENCE_RESOURCES") { - if (!Array.isArray(payload)) { - return mappingFailure("MAPPING_INVARIANT_REJECTED"); - } - if (payload.length > 100) return mappingFailure("OUTPUT_LIMIT_EXCEEDED"); - const output: ReferenceResource[] = []; - for (const item of payload) { - const mapped = mapReferenceDto(item); - if (!mapped.ok) return mapped; - output.push(mapped.value); - } - return mappingSuccess(Object.freeze(output)); + return mapUnknownReferenceResourceListPayload(payload); } if ( operationId === "CREATE_REFERENCE_RESOURCE" || operationId === "GET_REFERENCE_RESOURCE" ) { - return mapReferenceDto(payload); + return mapUnknownReferenceResourcePayload(payload); } return mappingFailure("MAPPING_INVARIANT_REJECTED"); } @@ -71,8 +113,7 @@ export const REFERENCE_BOUNDARY_MAPPERS = Object.freeze({ outputContractId: "ReferenceResourceList", owner: "feature-frontend-reference-feature-vertical-slice", maxOutputItems: 100, - map: (input: unknown) => - mapReferenceOperation("LIST_REFERENCE_RESOURCES", input), + map: mapUnknownReferenceResourceListPayload, }), ReferenceResourceMapper: Object.freeze({ mapperId: "ReferenceResourceMapper", @@ -81,8 +122,7 @@ export const REFERENCE_BOUNDARY_MAPPERS = Object.freeze({ outputContractId: "ReferenceResource", owner: "feature-frontend-reference-feature-vertical-slice", maxOutputItems: 1, - map: (input: unknown) => - mapReferenceOperation("GET_REFERENCE_RESOURCE", input), + map: mapUnknownReferenceResourcePayload, }), } satisfies Readonly>); diff --git a/src/features/reference-feature/contracts/reference-schemas.ts b/src/features/reference-feature/contracts/reference-schemas.ts index 2300a49..dff64aa 100644 --- a/src/features/reference-feature/contracts/reference-schemas.ts +++ b/src/features/reference-feature/contracts/reference-schemas.ts @@ -13,7 +13,7 @@ export const referenceResourceListQuerySchema = z : Array.isArray(value) ? value : [value], - z.array(z.string().trim().min(1)), + z.array(z.string().trim().min(1)).readonly(), ) .optional(), }) @@ -25,7 +25,7 @@ export const referenceResourceParamsSchema = z }) .strict(); -const referenceResourceDtoSchema = z +export const referenceResourceDtoSchema = z .object({ id: z.string().min(1).max(120), name: z.string().min(1).max(240), @@ -33,6 +33,28 @@ const referenceResourceDtoSchema = z }) .strip(); +export type ReferenceResourceDto = z.output< + typeof referenceResourceDtoSchema +>; + +export const referenceProblemSchema = 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(), + }) + .strip(); + +export type ReferenceProblem = z.output; + +export const createReferenceResourceCommandSchema = z + .object({ + name: z.string().trim().min(1).max(120), + note: z.string().trim().max(500).optional(), + }) + .strict(); + const payloadSchemas = { ReferenceResourceListPayload: z.array(referenceResourceDtoSchema).max(100), ReferenceResourcePayload: referenceResourceDtoSchema, @@ -42,12 +64,7 @@ const requestSchemas = { ReferenceResourceParams: referenceResourceParamsSchema, ReferenceResourceListQuery: referenceResourceListQuerySchema, NoRequest: z.object({}).strict(), - CreateReferenceResourceCommand: z - .object({ - name: z.string().trim().min(1).max(120), - note: z.string().trim().max(500).optional(), - }) - .strict(), + CreateReferenceResourceCommand: createReferenceResourceCommandSchema, } satisfies Record; function project(result: z.ZodSafeParseResult) { diff --git a/src/features/tech-log/adapters/http/http-studio-gateway.ts b/src/features/tech-log/adapters/http/http-studio-gateway.ts index 0d0e5dd..225b9ca 100644 --- a/src/features/tech-log/adapters/http/http-studio-gateway.ts +++ b/src/features/tech-log/adapters/http/http-studio-gateway.ts @@ -4,7 +4,7 @@ import { MUTATION_INTENT_BOUNDS, type MutationIntent, } from "../../../../contracts/mutation-intent.ts"; -import type { HttpExecutionOutcome } from "../../../../adapters/http/http-execution-v3.ts"; +import type { HttpExecutionOutcome } from "../../../../adapters/http/index.ts"; import { stableStringify } from "../stable-stringify.ts"; import type { IdempotentOptions, diff --git a/src/features/tech-log/adapters/http/studio-error-mapping.ts b/src/features/tech-log/adapters/http/studio-error-mapping.ts index 75974f1..7967580 100644 --- a/src/features/tech-log/adapters/http/studio-error-mapping.ts +++ b/src/features/tech-log/adapters/http/studio-error-mapping.ts @@ -1,4 +1,4 @@ -import type { HttpExecutionOutcome } from "../../../../adapters/http/http-execution-v3.ts"; +import type { HttpExecutionOutcome } from "../../../../adapters/http/index.ts"; import { StudioGatewayError } from "../../application/ports/studio-gateway-error.ts"; import type { ProblemDetails } from "../../contracts/studio/contract.ts"; diff --git a/src/features/tech-log/adapters/http/studio-session-credentials.ts b/src/features/tech-log/adapters/http/studio-session-credentials.ts index a06157a..65e4c15 100644 --- a/src/features/tech-log/adapters/http/studio-session-credentials.ts +++ b/src/features/tech-log/adapters/http/studio-session-credentials.ts @@ -1,4 +1,4 @@ -import type { CredentialPatchOutcome } from "../../../../adapters/http/http-contract-bridge.ts"; +import type { CredentialPatchOutcome } from "../../../../adapters/http/index.ts"; import { CREDENTIAL_HEADER_NAMES, type CredentialHeaderName, @@ -91,7 +91,7 @@ function isTechLogStudioAuthProfileId(value: string): value is TechLogStudioAuth * the caller's responsibility, not this function's. * * Final fix wave, item 8. `contractOperations.execute` is one executor shared - * by every installed feature, so it was calling this for reference-feature + * by every installed feature, so it was calling this for other features' * operations too: an unrelated 403 discarded a perfectly good Studio token * and forced an avoidable `getStudioSession` round trip — or, when the * session endpoint is itself unhealthy, turned someone else's authorization diff --git a/src/presentation/adapters/query/application-query.ts b/src/presentation/adapters/query/application-query.ts index 98a4432..1d5a149 100644 --- a/src/presentation/adapters/query/application-query.ts +++ b/src/presentation/adapters/query/application-query.ts @@ -17,7 +17,7 @@ import { deriveAsyncState, type AsyncState, } from "../../../application/view-models/async-state.ts"; -import type { Result } from "../../../application/result.ts"; +import type { Result } from "../../../contracts/result.ts"; import { createFailure, normalizeUnknownFailure, diff --git a/src/presentation/forms/form-contracts.ts b/src/presentation/forms/form-contracts.ts index 5fc7670..cdc1581 100644 --- a/src/presentation/forms/form-contracts.ts +++ b/src/presentation/forms/form-contracts.ts @@ -1,4 +1,4 @@ -import type { Result } from "../../application/result.ts"; +import type { Result } from "../../contracts/result.ts"; import type { AppFailure } from "../../contracts/errors.ts"; import { formatMessage, diff --git a/src/presentation/layouts/app-shell.tsx b/src/presentation/layouts/app-shell.tsx index d01b9f8..5215a97 100644 --- a/src/presentation/layouts/app-shell.tsx +++ b/src/presentation/layouts/app-shell.tsx @@ -20,7 +20,7 @@ import { useLocale, type MessageKey, } from "../i18n/index.ts"; -import { useApplication } from "../providers/application-provider.tsx"; +import { useApplicationRuntime } from "../providers/application-provider.tsx"; import { useSession } from "../providers/session-provider.tsx"; import { useTheme } from "../providers/theme-provider.tsx"; @@ -168,7 +168,7 @@ export function AppShell() { function PrimaryNavigation({ id }: Readonly<{ id: string }>) { const { resolve, message } = useLocale(); - const { runtime } = useApplication(); + const runtime = useApplicationRuntime(); const { pathname } = useLocation(); // §3.5. A feature the runtime document disabled does not advertise itself. // The router refuses its routes too, so this is presentation, not the switch. diff --git a/src/presentation/providers/application-provider.tsx b/src/presentation/providers/application-provider.tsx index f70bbfc..9a74ca0 100644 --- a/src/presentation/providers/application-provider.tsx +++ b/src/presentation/providers/application-provider.tsx @@ -4,7 +4,11 @@ import { useContext, } from "react"; -import type { ApplicationApi } from "../../application/create-application.ts"; +import type { + ApplicationApi, + ApplicationFeatureId, + ApplicationFeatureInputs, +} from "../../application/ports/in/application-api.ts"; const ApplicationContext = createContext(null); @@ -22,10 +26,47 @@ export function ApplicationProvider({ ); } -export function useApplication(): ApplicationApi { +function useApplicationContext(): ApplicationApi { const application = useContext(ApplicationContext); if (!application) { throw new Error("ApplicationProvider is required"); } return application; } + +export function useApplicationSession(): ApplicationApi["session"] { + return useApplicationContext().session; +} + +export function useApplicationPreferences(): ApplicationApi["preferences"] { + return useApplicationContext().preferences; +} + +export function useApplicationDiagnostics(): ApplicationApi["diagnostics"] { + return useApplicationContext().diagnostics; +} + +export function useApplicationRuntime(): ApplicationApi["runtime"] { + return useApplicationContext().runtime; +} + +export function useApplicationRecovery(): ApplicationApi["recovery"] { + return useApplicationContext().recovery; +} + +export function useApplicationFeature< + FeatureId extends ApplicationFeatureId, +>(featureId: FeatureId): ApplicationFeatureInputs[FeatureId] { + return useApplicationContext().features.get(featureId); +} + +/** + * Compatibility escape hatch for composition-oriented presentation code. + * New consumers should use the narrow hooks above so dependencies remain + * explicit instead of growing a root-object service locator. + * + * @deprecated Prefer a capability-specific hook. + */ +export function useApplication(): ApplicationApi { + return useApplicationContext(); +} diff --git a/src/presentation/providers/session-provider.tsx b/src/presentation/providers/session-provider.tsx index 75f9ced..b87129e 100644 --- a/src/presentation/providers/session-provider.tsx +++ b/src/presentation/providers/session-provider.tsx @@ -10,7 +10,7 @@ import type { ApplicationApi, SessionState, } from "../../application/ports/in/application-api.ts"; -import { useApplication } from "./application-provider.tsx"; +import { useApplicationSession } from "./application-provider.tsx"; export type SessionContextValue = Readonly<{ sessionState: SessionState; @@ -24,7 +24,7 @@ const SessionContext = createContext(null); export function SessionProvider({ children, }: Readonly<{ children: ReactNode }>) { - const { session } = useApplication(); + const session = useApplicationSession(); const sessionState = useSyncExternalStore( session.subscribe, session.getSnapshot, diff --git a/src/presentation/providers/theme-provider.tsx b/src/presentation/providers/theme-provider.tsx index e48dd3d..1e53532 100644 --- a/src/presentation/providers/theme-provider.tsx +++ b/src/presentation/providers/theme-provider.tsx @@ -13,7 +13,7 @@ import { normalizeColorSchemePreference, resolveColorScheme, } from "../../application/policies/color-scheme.ts"; -import { useApplication } from "./application-provider.tsx"; +import { useApplicationPreferences } from "./application-provider.tsx"; export type ThemeContextValue = Readonly<{ preference: ColorSchemePreference; @@ -33,7 +33,7 @@ function systemPrefersDark(): boolean { export function ThemeProvider({ children, }: Readonly<{ children: ReactNode }>) { - const { preferences } = useApplication(); + const preferences = useApplicationPreferences(); const [preference, updatePreference] = useState( preferences.getColorScheme, ); diff --git a/src/presentation/routes/app-router.tsx b/src/presentation/routes/app-router.tsx index aa8f05a..5f956b0 100644 --- a/src/presentation/routes/app-router.tsx +++ b/src/presentation/routes/app-router.tsx @@ -33,7 +33,11 @@ import { ChunkRecoveryBoundary } from "../boundaries/chunk-recovery-boundary.tsx import { Button, PageHeader } from "../design-system/index.ts"; import { LocaleProvider, useLocale } from "../i18n/index.ts"; import { TECH_LOG_ROUTE_LAYOUTS } from "../../features/tech-log/presentation/tech-log-route-runtime.tsx"; -import { useApplication } from "../providers/application-provider.tsx"; +import { + useApplicationDiagnostics, + useApplicationRecovery, + useApplicationRuntime, +} from "../providers/application-provider.tsx"; import { SessionProvider, useSession } from "../providers/session-provider.tsx"; import { ThemeProvider } from "../providers/theme-provider.tsx"; import { @@ -136,7 +140,7 @@ function RouteLifecycle({ }) { const location = useLocation(); const { message, resolve } = useLocale(); - const { diagnostics } = useApplication(); + const diagnostics = useApplicationDiagnostics(); useEffect(() => { document.title = message("route.documentTitle", { title: resolve(`route.${definition.routeId}.title`), @@ -305,7 +309,9 @@ function RegisteredRoute({ const params = useParams(); const [search] = useSearchParams(); const location = useLocation(); - const { diagnostics, runtime: platformRuntime, recovery } = useApplication(); + const diagnostics = useApplicationDiagnostics(); + const platformRuntime = useApplicationRuntime(); + const recovery = useApplicationRecovery(); // §3.5 (template merge). A feature the runtime document disabled is out of // service, not merely hidden: withdrawing it from navigation alone would // leave a typed deep link that still mounts it. The template looked the diff --git a/template.lock.json b/template.lock.json index 5ca1deb..84c9551 100644 --- a/template.lock.json +++ b/template.lock.json @@ -2,7 +2,7 @@ "schemaVersion": 1, "template": "clean-architecture-frontend-template", "sourceRepository": "https://git.learn.hyeonworks.com/donghyeon.kang/clean-architecture-frontend-template", - "sourceRevision": "5434760ddf88106d78e335c092367512bb34eacd", - "sourceTree": "f90673eab3a0ed949ed7483e99fba7ac0a0e9eaf", + "sourceRevision": "ebea300e4ffd9ef9312d3982b44ccda2fc3fea2c", + "sourceTree": "22fc8f1dd15edc56728658d24c00b65abe1f2bcb", "materialization": "tracked-snapshot" } diff --git a/tests/browser-capabilities/indexeddb-runtime.spec.ts b/tests/browser-capabilities/indexeddb-runtime.spec.ts index 235b493..feeba8c 100644 --- a/tests/browser-capabilities/indexeddb-runtime.spec.ts +++ b/tests/browser-capabilities/indexeddb-runtime.spec.ts @@ -18,13 +18,13 @@ function databaseName(_prefix: string): string { return `ca-idb-v1:a${token.slice(0, 31)}.n${token.slice(1)}.p${token.split("").reverse().join("").slice(0, 31)}`; } -async function installLifecycleRuntime( +async function startLifecycleRuntime( page: Page, name: string, targetVersion: 1 | 2, blockedTimeoutMs = 1_000, -) { - return await page.evaluate( +): Promise { + await page.evaluate( async ({ currentDatabaseName, currentTargetVersion, @@ -173,8 +173,12 @@ async function installLifecycleRuntime( __indexedDbLifecycleRuntime?: unknown; } ).__indexedDbLifecycleRuntime = runtime; - const opened = await runtime.open(); - return { opened, status: runtime.getStatus() }; + const opening = runtime.open(); + ( + globalThis as unknown as { + __indexedDbLifecycleOpening?: Promise; + } + ).__indexedDbLifecycleOpening = opening; }, { currentDatabaseName: name, @@ -184,6 +188,35 @@ async function installLifecycleRuntime( ); } +async function settleLifecycleRuntime(page: Page): Promise { + return await page.evaluate(async () => { + const state = globalThis as unknown as { + __indexedDbLifecycleRuntime?: { + getStatus(): unknown; + }; + __indexedDbLifecycleOpening?: Promise; + }; + if (!state.__indexedDbLifecycleRuntime || !state.__indexedDbLifecycleOpening) { + throw new Error("IndexedDB lifecycle runtime is not installed."); + } + const opened = await state.__indexedDbLifecycleOpening; + return { + opened, + status: state.__indexedDbLifecycleRuntime.getStatus(), + }; + }); +} + +async function installLifecycleRuntime( + page: Page, + name: string, + targetVersion: 1 | 2, + blockedTimeoutMs = 1_000, +): Promise { + await startLifecycleRuntime(page, name, targetVersion, blockedTimeoutMs); + return await settleLifecycleRuntime(page); +} + async function lifecycleStatus(page: Page): Promise { return await page.evaluate(() => { const runtime = ( @@ -977,12 +1010,16 @@ test("fails a blocked v2 upgrade closed, then closes its late connection after t ); expect(blocker).toBe("OPEN"); - const blocked = await installLifecycleRuntime( - page, - name, - 2, - 25, - ); + await startLifecycleRuntime(page, name, 2, 500); + await expect + .poll(async () => await lifecycleStatus(page)) + .toEqual({ + kind: "BLOCKED", + currentVersion: 1, + targetVersion: 2, + }); + + const blocked = await settleLifecycleRuntime(page); expect(blocked).toMatchObject({ opened: { ok: false, @@ -992,9 +1029,8 @@ test("fails a blocked v2 upgrade closed, then closes its late connection after t }, }, status: { - kind: "BLOCKED", - currentVersion: 1, - targetVersion: 2, + kind: "CLOSED", + reason: "NOT_OPENED", }, }); diff --git a/tests/browser-capabilities/local-draft-composition.spec.ts b/tests/browser-capabilities/local-draft-composition.spec.ts new file mode 100644 index 0000000..6319ad6 --- /dev/null +++ b/tests/browser-capabilities/local-draft-composition.spec.ts @@ -0,0 +1,244 @@ +import type { + IndexedDbRuntimeDependencies, +} from "../../src/adapters/storage/indexeddb/indexeddb-types.ts"; +import type { LocalDraft } from "../../src/features/local-draft-feature/domain/local-draft.ts"; +import { + expect, + test, +} from "../support/browser/strict-browser-test.ts"; + +test("composes the local-draft feature over the real browser IndexedDB runtime", async ({ + page, +}) => { + await page.route("**/favicon.ico", (route) => + route.fulfill({ status: 204 }), + ); + await page.goto("/config.json"); + + const result = await page.evaluate(async () => { + const indexedDbModulePath = + "/src/adapters/storage/indexeddb/index.ts"; + const contributionModulePath = + "/src/features/feature-adapter-contribution.ts"; + const localDraftModulePath = + "/src/features/local-draft-feature/adapters/create-local-draft-feature-input.ts"; + + const { + createIndexedDbRuntime, + indexedDbPhysicalDatabaseName, + } = (await import( + /* @vite-ignore */ indexedDbModulePath + )) as typeof import("../../src/adapters/storage/indexeddb/index.ts"); + const { + composeFeatureAdapterInputs, + createIndexedDbRepositoryProvider, + } = (await import( + /* @vite-ignore */ contributionModulePath + )) as typeof import("../../src/features/feature-adapter-contribution.ts"); + const { + LOCAL_DRAFT_FEATURE_ADAPTER_CONTRIBUTION, + } = (await import( + /* @vite-ignore */ localDraftModulePath + )) as typeof import("../../src/features/local-draft-feature/adapters/create-local-draft-feature-input.ts"); + + const suffix = crypto.randomUUID().replaceAll("-", ""); + const scope = Object.freeze({ + authorityToken: `a${suffix.slice(0, 31)}`, + namespaceToken: `n${suffix.slice(1, 32)}`, + partitionToken: `p${[...suffix].reverse().join("").slice(0, 31)}`, + accountScope: "ORIGIN_SHARED" as const, + }); + const storagePolicy = Object.freeze({ + owner: "local-draft-feature", + namespace: "local-draft", + classification: "INTERNAL" as const, + authority: "LOCAL_FIRST" as const, + accountScope: "ORIGIN_SHARED" as const, + retention: Object.freeze({ kind: "EXPLICIT_DELETE" as const }), + softBudgetBytes: 1_000_000, + hardBudgetBytes: 2_000_000, + evictionPriority: "USER_AUTHORED" as const, + logoutAction: "KEEP_ORIGIN_SHARED" as const, + accountDeletionAction: "KEEP_ORIGIN_SHARED" as const, + pressureAction: "RETAIN" as const, + unavailableFallback: "READ_ONLY" as const, + }); + + const config: IndexedDbRuntimeDependencies< + LocalDraft, + LocalDraft, + never + > = { + scope, + storagePolicy, + schemaVersion: 1, + recordStore: "records", + governanceStore: "governance", + retentionStore: "retention", + retentionEligibilityIndex: "by-eligibility", + lifecycleMetadataStores: [], + idempotencyStore: "receipts", + idempotencyExpiryIndex: "by-expiry", + receiptRetentionMs: 60_000, + maxIdempotencyReceipts: 100, + migrations: [ + { + id: "local-draft-schema-v1", + fromVersion: 0, + toVersion: 1, + operations: [ + { + kind: "CREATE_STORE", + name: "governance", + keyPath: "bindingKey", + }, + { + kind: "CREATE_STORE", + name: "retention", + keyPath: "recordKey", + indexes: [ + { + name: "by-eligibility", + keyPath: "eligibleAtEpochMs", + }, + ], + }, + { + kind: "CREATE_STORE", + name: "records", + keyPath: "key", + }, + { + kind: "CREATE_STORE", + name: "receipts", + keyPath: "idempotencyKey", + indexes: [ + { + name: "by-expiry", + keyPath: "expiresAtEpochMs", + }, + ], + }, + ], + }, + ], + codec: { + currentVersion: 1, + encode: (value) => ({ ok: true, value }), + measureStoredBytes: (value) => + new TextEncoder().encode(JSON.stringify(value)).byteLength, + decode: (version, value) => { + if ( + version !== 1 || + value === null || + typeof value !== "object" + ) { + return { ok: false }; + } + const candidate = value as Partial; + return typeof candidate.draftId === "string" && + typeof candidate.title === "string" && + typeof candidate.body === "string" + ? { ok: true, value: candidate as LocalDraft } + : { ok: false }; + }, + fingerprint: async (value) => { + const bytes = new TextEncoder().encode( + JSON.stringify([value.draftId, value.title, value.body]), + ); + const digest = await crypto.subtle.digest("SHA-256", bytes); + return Array.from( + new Uint8Array(digest), + (byte) => byte.toString(16).padStart(2, "0"), + ).join(""); + }, + }, + queryPolicy: { + plan: () => ({ limit: 1 }), + }, + authorizeLifecycle: () => ({ + authorized: true, + proofToken: "localdraftauthorityproof_001", + }), + }; + + const runtime = createIndexedDbRuntime(config); + const databaseName = indexedDbPhysicalDatabaseName(scope); + const opened = await runtime.open(); + + try { + const indexedDb = createIndexedDbRepositoryProvider( + Object.freeze({ "local-draft": runtime }), + ); + const composed = composeFeatureAdapterInputs( + Object.freeze([LOCAL_DRAFT_FEATURE_ADAPTER_CONTRIBUTION] as const), + Object.freeze(["local-draft"]), + Object.freeze({ indexedDb }), + ); + const localDraft = composed["local-draft"]; + if (!localDraft) { + throw new Error("local-draft feature input was not composed"); + } + + const draft = Object.freeze({ + draftId: "draft-1", + title: "Architecture notes", + body: "Stored through the reusable IndexedDB capability.", + }); + + const saved = await localDraft.saveDraft({ + draft, + expectedRevision: null, + idempotencyKey: "local-draft-create-1", + }); + const found = await localDraft.findDraft(draft.draftId); + const removed = await localDraft.removeDraft({ + draftId: draft.draftId, + expectedRevision: saved.ok ? saved.value.revision : 1, + idempotencyKey: "local-draft-remove-1", + }); + const afterRemove = await localDraft.findDraft(draft.draftId); + + return { + opened, + saved, + found, + removed, + afterRemove, + composedFeatureIds: Object.keys(composed), + runtimeStatus: runtime.getStatus(), + }; + } finally { + runtime.close(); + await new Promise((resolve, reject) => { + const request = indexedDB.deleteDatabase(databaseName); + request.onsuccess = () => resolve(); + request.onerror = () => + reject(request.error ?? new Error("IndexedDB cleanup failed")); + request.onblocked = () => + reject(new Error("IndexedDB cleanup was blocked")); + }); + } + }); + + expect(result.opened).toEqual({ ok: true, value: undefined }); + expect(result.composedFeatureIds).toEqual(["local-draft"]); + expect(result.saved).toEqual({ ok: true, value: { revision: 1 } }); + expect(result.found).toMatchObject({ + ok: true, + value: { + draft: { + draftId: "draft-1", + title: "Architecture notes", + body: "Stored through the reusable IndexedDB capability.", + }, + revision: 1, + }, + }); + expect(result.removed).toEqual({ ok: true, value: undefined }); + expect(result.afterRemove).toEqual({ ok: true, value: null }); + expect(result.runtimeStatus).toMatchObject({ + kind: "READY", + schemaVersion: 1, + }); +}); diff --git a/tests/browser-capabilities/storage-manager.spec.ts b/tests/browser-capabilities/storage-manager.spec.ts index f89f155..74a382a 100644 --- a/tests/browser-capabilities/storage-manager.spec.ts +++ b/tests/browser-capabilities/storage-manager.spec.ts @@ -1,29 +1,48 @@ import { expect, test } from "../support/browser/strict-browser-test.ts"; -test("executes the storage durability adapter against the real browser StorageManager", async ({ +test("executes the storage durability adapter against the real browser StorageManager capability", async ({ page, }) => { await page.goto("/"); - const result = await page.evaluate(async () => { + const observation = await page.evaluate(async () => { const modulePath = "/src/adapters/browser-file-storage/storage-manager-adapter.ts"; const { createStorageDurabilityAdapter } = await import( /* @vite-ignore */ modulePath ); + const hasStorageManager = navigator.storage !== undefined; const adapter = createStorageDurabilityAdapter(navigator.storage); - return adapter.inspect(); + return { + hasStorageManager, + result: await adapter.inspect(), + }; }); - expect(result.ok).toBe(true); - if (result.ok) { + if (!observation.hasStorageManager) { + expect(observation.result).toEqual({ + ok: false, + error: { + code: "UNSUPPORTED", + operation: "STORAGE_ESTIMATE", + retryable: false, + recovery: "ONLINE_ONLY", + }, + }); + return; + } + + expect(observation.result.ok).toBe(true); + if (observation.result.ok) { expect(["UNKNOWN", "NORMAL", "PRESSURE", "CRITICAL"]).toContain( - result.value.pressure, + observation.result.value.pressure, ); expect( - result.value.usageBytes === null || result.value.usageBytes >= 0, + observation.result.value.usageBytes === null || + observation.result.value.usageBytes >= 0, ).toBe(true); expect( - result.value.quotaBytes === null || result.value.quotaBytes >= 0, + observation.result.value.quotaBytes === null || + observation.result.value.quotaBytes >= 0, ).toBe(true); } }); diff --git a/tests/component/application-mutation-admission.test.tsx b/tests/component/application-mutation-admission.test.tsx new file mode 100644 index 0000000..afe60de --- /dev/null +++ b/tests/component/application-mutation-admission.test.tsx @@ -0,0 +1,317 @@ +// @vitest-environment jsdom + +import { act, renderHook, waitFor } from "@testing-library/react"; +import { describe, expect, it, vi } from "vitest"; + +import { + type ApplicationResult, + useApplicationMutation, +} from "../../src/presentation/adapters/query/application-query.ts"; +import type { MutationIntentFactory } from "../../src/application/ports/mutation-intent-factory.ts"; +import { + RESOURCE_INVALIDATION_TOPIC, + deterministicMutationIntentFactory, + queryClient, + scopeSnapshot, + wrapper, +} from "./application-query-fixture.tsx"; + +describe("application mutation intent admission", () => { + it("retains optimistic data when execute throws after dispatch begins", async () => { + const client = queryClient(); + const key = ["resource", "thrown-unknown-effect"]; + client.setQueryData(key, ["base"]); + const hook = renderHook( + () => + useApplicationMutation({ + execute: async () => { + throw new Error("private transport defect"); + }, + currentData: client.getQueryData(key), + optimistic: { + queryKey: key, + update: (previous, input) => [ + ...(previous as string[]), + input, + ], + }, + }), + { wrapper: wrapper(client) }, + ); + + let outcome: ApplicationResult | undefined; + await act(async () => { + outcome = await hook.result.current.submit("created"); + }); + + expect(outcome).toMatchObject({ + ok: false, + error: { + effect: "MAYBE_APPLIED", + retryable: false, + action: "contact-support", + }, + }); + expect(JSON.stringify(outcome)).not.toContain("private transport defect"); + expect(client.getQueryData(key)).toEqual(["base", "created"]); + expect(hook.result.current.state.indicator).toBe( + "mutation-effect-unknown", + ); + }); + + it("creates a distinct logical intent for each independently admitted submit", async () => { + const client = queryClient(); + const scope = scopeSnapshot(); + const observedIntents: unknown[] = []; + const execute = vi.fn( + async ( + input: string, + context: Readonly<{ signal: AbortSignal; intent?: unknown }>, + ) => { + observedIntents.push(context.intent); + return { ok: true as const, value: input }; + }, + ); + const hook = renderHook( + () => + useApplicationMutation({ + definitionId: "independent-intent-v1", + definitionVersion: 1, + operationId: "CREATE_WITH_INTENT", + requiresIdempotencyKey: true, + owner: "platform-test", + duplicatePolicy: "ALLOW_PARALLEL", + scope, + execute, + invalidate: [], + }), + { wrapper: wrapper(client) }, + ); + + await act(async () => { + await hook.result.current.submit("same-input"); + await hook.result.current.submit("same-input"); + }); + + expect(observedIntents).toHaveLength(2); + expect(observedIntents[0]).toMatchObject({ + intentId: "intent-1", + operationId: "CREATE_WITH_INTENT", + idempotencyKey: "key-1", + }); + expect(observedIntents[1]).toMatchObject({ + intentId: "intent-2", + operationId: "CREATE_WITH_INTENT", + idempotencyKey: "key-2", + }); + expect(observedIntents[0]).not.toEqual(observedIntents[1]); + }); + + it("creates no second intent when JOIN_IDENTICAL shares an admitted submit", async () => { + const client = queryClient(); + const scope = scopeSnapshot(); + const deterministicFactory = deterministicMutationIntentFactory(); + const createIntent = vi.fn(deterministicFactory.create); + const factory: MutationIntentFactory = Object.freeze({ + create: createIntent, + }); + let complete: (value: ApplicationResult) => void = () => {}; + const execute = vi.fn( + () => + new Promise>((resolve) => { + complete = resolve; + }), + ); + const hook = renderHook( + () => + useApplicationMutation({ + definitionId: "joined-intent-v1", + definitionVersion: 1, + operationId: "CREATE_JOINED", + requiresIdempotencyKey: true, + owner: "platform-test", + duplicatePolicy: "JOIN_IDENTICAL", + scope, + execute, + invalidate: [], + }), + { wrapper: wrapper(client, factory) }, + ); + + let first: Promise> | null = null; + let joined: Promise> | null = null; + act(() => { + first = hook.result.current.submit("same-input"); + joined = hook.result.current.submit("same-input"); + }); + + expect(first).toBe(joined); + await waitFor(() => expect(execute).toHaveBeenCalledOnce()); + expect(createIntent).toHaveBeenCalledOnce(); + expect(createIntent).toHaveBeenCalledWith({ + operationId: "CREATE_JOINED", + canonicalInputIdentity: + "scope-fingerprint-0001:joined-intent-v1:scope-identity-token-0001", + requiresIdempotencyKey: true, + }); + + complete({ ok: true, value: "same-input" }); + if (!first) throw new Error("expected admitted mutation"); + await act(() => first); + }); + + it("keeps the legacy raw mutation path outside the intent factory", async () => { + const client = queryClient(); + const createIntent = vi.fn(); + const factory: MutationIntentFactory = Object.freeze({ + create: createIntent, + }); + const execute = vi.fn(async (input: string) => ({ + ok: true as const, + value: input, + })); + const hook = renderHook( + () => + useApplicationMutation({ + definitionId: "legacy-raw-path-v1", + execute, + }), + { wrapper: wrapper(client, factory) }, + ); + + await act(() => hook.result.current.submit("legacy-input")); + + expect(execute).toHaveBeenCalledOnce(); + expect(createIntent).not.toHaveBeenCalled(); + }); + + it("rejects a duplicate submit by default while one is active", async () => { + const client = queryClient(); + let complete: (value: ApplicationResult) => void = () => {}; + const execute = vi.fn( + () => + new Promise>((resolve) => { + complete = resolve; + }), + ); + const hook = renderHook( + () => + useApplicationMutation({ + definitionId: "legacy-duplicate-rejection-v1", + execute, + }), + { wrapper: wrapper(client) }, + ); + + let first: Promise> | null = null; + let duplicate: Promise> | null = null; + act(() => { + first = hook.result.current.submit("created"); + duplicate = hook.result.current.submit("created"); + }); + + if (!first || !duplicate) throw new Error("expected two submissions"); + await expect(duplicate).resolves.toMatchObject({ + ok: false, + error: { kind: "DUPLICATE_IN_FLIGHT" }, + }); + expect(execute).toHaveBeenCalledOnce(); + + complete({ ok: true, value: "created" }); + await act(() => first as Promise>); + }); + + it("deduplicates submit and commits one optimistic mutation", async () => { + const client = queryClient(); + const key = ["resource", "list"]; + client.setQueryData(key, ["existing"]); + let complete: (value: ApplicationResult) => void = () => {}; + const execute = vi.fn( + () => + new Promise>((resolve) => { + complete = resolve; + }), + ); + const hook = renderHook( + () => + useApplicationMutation({ + // §11.2: joining is opt-in. The default is REJECT_WHILE_ACTIVE. + duplicatePolicy: "JOIN_IDENTICAL", + execute, + invalidate: [RESOURCE_INVALIDATION_TOPIC], + currentData: client.getQueryData(key), + optimistic: { + queryKey: key, + update: (previous, input) => [ + ...(previous as string[]), + input, + ], + }, + }), + { wrapper: wrapper(client) }, + ); + + let first: Promise> | null = null; + let duplicate: Promise> | null = null; + act(() => { + first = hook.result.current.submit("created"); + duplicate = hook.result.current.submit("created"); + }); + expect(first).toBe(duplicate); + await waitFor(() => + expect(client.getQueryData(key)).toEqual(["existing", "created"]), + ); + await waitFor(() => expect(execute).toHaveBeenCalledOnce()); + await waitFor(() => + expect(hook.result.current.state.indicator).toBe("mutation-pending"), + ); + + complete({ ok: true, value: "created" }); + if (!first) throw new Error("expected pending mutation"); + await act(() => first); + expect(client.getQueryState(key)?.isInvalidated).toBe(true); + await waitFor(() => + expect(hook.result.current.state.indicator).toBeNull(), + ); + }); + + it("never joins distinct mutation inputs to the same runtime promise", async () => { + const client = queryClient(); + const resolvers = new Map< + string, + (value: ApplicationResult) => void + >(); + const execute = vi.fn( + (input: string) => + new Promise>((resolve) => { + resolvers.set(input, resolve); + }), + ); + const hook = renderHook( + () => + useApplicationMutation({ + definitionId: "legacy-parallel-distinct-inputs-v1", + execute, + currentData: true, + }), + { wrapper: wrapper(client) }, + ); + + let first: Promise> | undefined; + let second: Promise> | undefined; + act(() => { + first = hook.result.current.submit("first"); + second = hook.result.current.submit("second"); + }); + expect(first).not.toBe(second); + await waitFor(() => expect(execute).toHaveBeenCalledTimes(2)); + + resolvers.get("first")?.({ ok: true, value: "first" }); + resolvers.get("second")?.({ ok: true, value: "second" }); + if (!first || !second) throw new Error("expected pending mutations"); + await act(async () => { + await Promise.all([first, second]); + }); + }); + +}); diff --git a/tests/component/application-mutation-optimistic-cache.test.tsx b/tests/component/application-mutation-optimistic-cache.test.tsx new file mode 100644 index 0000000..eca908b --- /dev/null +++ b/tests/component/application-mutation-optimistic-cache.test.tsx @@ -0,0 +1,213 @@ +// @vitest-environment jsdom + +import { act, renderHook } from "@testing-library/react"; +import { describe, expect, it, vi } from "vitest"; + +import { + type ApplicationResult, + useApplicationMutation, +} from "../../src/presentation/adapters/query/application-query.ts"; +import { createFailure } from "../../src/contracts/errors.ts"; +import { + RESOURCE_INVALIDATION_TOPIC, + queryClient, + wrapper, +} from "./application-query-fixture.tsx"; + +describe("application mutation optimistic cache lifecycle", () => { + it("cancels an in-flight query before taking the optimistic snapshot", async () => { + const client = queryClient(); + const key = ["resource", "ordered-update"]; + client.setQueryData(key, ["existing"]); + let finishCancellation: () => void = () => {}; + const cancellation = new Promise((resolve) => { + finishCancellation = resolve; + }); + const cancelQueries = vi + .spyOn(client, "cancelQueries") + .mockImplementation(async () => cancellation); + const getQueryData = vi.spyOn(client, "getQueryData"); + const update = vi.fn((previous, input) => [ + ...(previous as string[]), + input, + ]); + const execute = vi.fn(async () => ({ + ok: true as const, + value: "created", + })); + const hook = renderHook( + () => + useApplicationMutation({ + execute, + currentData: ["existing"], + optimistic: { queryKey: key, update }, + }), + { wrapper: wrapper(client) }, + ); + + let pending: Promise> | undefined; + act(() => { + pending = hook.result.current.submit("created"); + }); + expect(cancelQueries).toHaveBeenCalledWith({ + queryKey: key, + exact: true, + }); + expect(getQueryData).not.toHaveBeenCalled(); + expect(update).not.toHaveBeenCalled(); + expect(execute).not.toHaveBeenCalled(); + + finishCancellation(); + if (!pending) throw new Error("expected pending mutation"); + await act(() => pending); + + expect(getQueryData).toHaveBeenCalledWith(key); + expect(update).toHaveBeenCalledWith(["existing"], "created"); + expect(execute).toHaveBeenCalledOnce(); + expect(client.getQueryData(key)).toEqual(["existing", "created"]); + }); + + it("keeps a committed optimistic update when invalidation fails", async () => { + const client = queryClient(); + const key = ["resource", "committed-update"]; + client.setQueryData(key, ["existing"]); + vi.spyOn(client, "invalidateQueries").mockRejectedValue( + new Error("cache refresh failed"), + ); + const hook = renderHook( + () => + useApplicationMutation({ + execute: async () => ({ ok: true, value: "created" }), + invalidate: [RESOURCE_INVALIDATION_TOPIC], + currentData: ["existing"], + optimistic: { + queryKey: key, + update: (previous, input) => [ + ...(previous as string[]), + input, + ], + }, + }), + { wrapper: wrapper(client) }, + ); + + let outcome; + await act(async () => { + outcome = await hook.result.current.submit("created"); + }); + + expect(outcome).toEqual({ ok: true, value: "created" }); + expect(client.getQueryData(key)).toEqual(["existing", "created"]); + }); + + it("normalizes an optimistic preparation defect without running the command", async () => { + const client = queryClient(); + const key = ["resource", "invalid-optimistic-update"]; + client.setQueryData(key, ["existing"]); + const execute = vi.fn(async () => ({ + ok: true as const, + value: "created", + })); + const hook = renderHook( + () => + useApplicationMutation({ + execute, + currentData: ["existing"], + optimistic: { + queryKey: key, + update: () => { + throw new Error("private optimistic detail"); + }, + }, + }), + { wrapper: wrapper(client) }, + ); + + let outcome; + await act(async () => { + outcome = await hook.result.current.submit("created"); + }); + + expect(outcome).toMatchObject({ + ok: false, + error: { + kind: "UNKNOWN_FAILURE", + effect: "NOT_STARTED", + operationId: "APPLICATION_MUTATION", + userMessageKey: "error.unknown_failure", + }, + }); + expect(JSON.stringify(outcome)).not.toContain("private optimistic detail"); + expect(execute).not.toHaveBeenCalled(); + expect(client.getQueryData(key)).toEqual(["existing"]); + }); + + it("removes an optimistic cache entry when no prior data existed", async () => { + const client = queryClient(); + const key = ["resource", "new-optimistic-entry"]; + const failure = createFailure("SERVER_FAILURE", "CREATE", 0, { + effect: "NOT_APPLIED", + }); + const hook = renderHook( + () => + useApplicationMutation({ + execute: async () => ({ ok: false, error: failure }), + currentData: true, + optimistic: { + queryKey: key, + update: (_previous, input) => [input], + }, + }), + { wrapper: wrapper(client) }, + ); + + let outcome; + await act(async () => { + outcome = await hook.result.current.submit("temporary"); + }); + + expect(outcome).toEqual({ ok: false, error: failure }); + expect(client.getQueryData(key)).toBeUndefined(); + expect(client.getQueryState(key)).toBeUndefined(); + }); + + it("rolls optimistic data back and exposes a resolvable conflict", async () => { + const client = queryClient(); + const key = ["resource", "list"]; + client.setQueryData(key, ["existing"]); + const conflict = createFailure("CONFLICT", "CREATE", 0, { + effect: "NOT_APPLIED", + }); + const hook = renderHook( + () => + useApplicationMutation({ + execute: async () => ({ ok: false, error: conflict }), + invalidate: [RESOURCE_INVALIDATION_TOPIC], + currentData: client.getQueryData(key), + optimistic: { + queryKey: key, + update: (previous, input) => [ + ...(previous as string[]), + input, + ], + }, + }), + { wrapper: wrapper(client) }, + ); + + let outcome; + await act(async () => { + outcome = await hook.result.current.submit("conflicting"); + }); + expect(outcome).toEqual({ ok: false, error: conflict }); + expect(client.getQueryData(key)).toEqual(["existing"]); + expect(hook.result.current.state.indicator).toBe("mutation-conflict"); + expect(hook.result.current.state.overlay).toMatchObject({ + mutationPending: false, + mutationConflict: true, + }); + + await act(() => hook.result.current.resolveConflict()); + expect(hook.result.current.state.indicator).toBeNull(); + expect(client.getQueryState(key)?.isInvalidated).toBe(true); + });}); diff --git a/tests/component/application-mutation-scope-fence.test.tsx b/tests/component/application-mutation-scope-fence.test.tsx new file mode 100644 index 0000000..7588b8a --- /dev/null +++ b/tests/component/application-mutation-scope-fence.test.tsx @@ -0,0 +1,133 @@ +// @vitest-environment jsdom + +import { renderHook, waitFor } from "@testing-library/react"; +import { describe, expect, it, vi } from "vitest"; + +import { + type ApplicationResult, + useApplicationMutation, +} from "../../src/presentation/adapters/query/application-query.ts"; +import { createFailure } from "../../src/contracts/errors.ts"; +import { + queryClient, + scopeSnapshot, + wrapper, +} from "./application-query-fixture.tsx"; + +describe("scope-bound mutation fence", () => { + it("rejects a submit whose scope is already fenced", async () => { + const client = queryClient(); + const scope = scopeSnapshot(); + const execute = vi.fn(async () => ({ ok: true as const, value: "v" })); + const hook = renderHook( + () => + useApplicationMutation({ + definitionId: "fenced-mutation-v1", + definitionVersion: 1, + operationId: "CREATE_FENCED", + requiresIdempotencyKey: false, + owner: "platform-test", + duplicatePolicy: "REJECT_WHILE_ACTIVE", + scope, + execute, + invalidate: [], + }), + { wrapper: wrapper(client) }, + ); + + scope.fence(); + const outcome = await hook.result.current.submit("value"); + expect(outcome).toMatchObject({ + ok: false, + error: { + kind: "SCOPE_GENERATION_CHANGED", + effect: "NOT_STARTED", + }, + }); + expect(execute).not.toHaveBeenCalled(); + }); + + it("discards a mutation result whose scope was fenced after dispatch", async () => { + const client = queryClient(); + const scope = scopeSnapshot(); + const execute = vi.fn(async () => { + scope.fence(); + return { ok: true as const, value: "committed" }; + }); + const hook = renderHook( + () => + useApplicationMutation({ + definitionId: "late-mutation-v1", + definitionVersion: 1, + operationId: "CREATE_LATE", + requiresIdempotencyKey: false, + owner: "platform-test", + duplicatePolicy: "ALLOW_PARALLEL", + scope, + execute, + invalidate: [], + }), + { wrapper: wrapper(client) }, + ); + + const outcome = await hook.result.current.submit("value"); + expect(outcome).toMatchObject({ + ok: false, + error: { kind: "SCOPE_GENERATION_CHANGED" }, + }); + expect(execute).toHaveBeenCalledOnce(); + }); + + it("aborts a hung mutation when its captured scope is fenced", async () => { + const client = queryClient(); + const scope = scopeSnapshot(); + let observedSignal: AbortSignal | undefined; + const execute = vi.fn( + (_input: string, context: Readonly<{ signal: AbortSignal }>) => + new Promise>((resolve) => { + observedSignal = context.signal; + context.signal.addEventListener( + "abort", + () => + resolve({ + ok: false, + error: createFailure("REQUEST_ABORTED", "CREATE_HUNG", 0), + }), + { once: true }, + ); + }), + ); + const hook = renderHook( + () => + useApplicationMutation({ + definitionId: "hung-mutation-v1", + definitionVersion: 1, + operationId: "CREATE_HUNG", + requiresIdempotencyKey: false, + owner: "platform-test", + duplicatePolicy: "REJECT_WHILE_ACTIVE", + scope, + execute, + invalidate: [], + }), + { wrapper: wrapper(client) }, + ); + + const outcome = hook.result.current.submit("value"); + await waitFor(() => expect(observedSignal).toBe(scope.signal)); + + scope.fence(); + + expect(observedSignal?.aborted).toBe(true); + await expect(outcome).resolves.toMatchObject({ + ok: false, + error: { + kind: "SCOPE_GENERATION_CHANGED", + effect: "MAYBE_APPLIED", + retryable: false, + action: "contact-support", + }, + }); + }); +}); + diff --git a/tests/component/application-query-bridge.test.tsx b/tests/component/application-query-bridge.test.tsx new file mode 100644 index 0000000..e76bed9 --- /dev/null +++ b/tests/component/application-query-bridge.test.tsx @@ -0,0 +1,129 @@ +// @vitest-environment jsdom + +import { act, renderHook, waitFor } from "@testing-library/react"; +import { describe, expect, it, vi } from "vitest"; + +import { + type ApplicationResult, + useApplicationQuery, +} from "../../src/presentation/adapters/query/application-query.ts"; +import { createFailure } from "../../src/contracts/errors.ts"; +import { queryClient, wrapper } from "./application-query-fixture.tsx"; + +describe("application query inbound bridge", () => { + it("latches a background failure over stale data and clears it on retry success", async () => { + const client = queryClient(); + const responses: ApplicationResult[] = [ + { ok: true, value: ["first"] }, + { + ok: false, + error: createFailure("SERVER_FAILURE", "LIST", 0), + }, + { ok: true, value: ["recovered"] }, + ]; + const execute = vi.fn(async () => responses.shift() ?? responses[0]); + const hook = renderHook( + () => + useApplicationQuery({ + queryKey: ["resource", "list"], + execute, + }), + { wrapper: wrapper(client) }, + ); + + await waitFor(() => expect(hook.result.current.data).toEqual(["first"])); + await act(() => hook.result.current.retry()); + await waitFor(() => + expect(hook.result.current.state.indicator).toBe("stale-degraded"), + ); + expect(hook.result.current.state.base).toBe("success"); + expect(hook.result.current.data).toEqual(["first"]); + + await act(() => hook.result.current.retry()); + await waitFor(() => + expect(hook.result.current.data).toEqual(["recovered"]), + ); + expect(hook.result.current.state.indicator).toBeNull(); + expect(execute).toHaveBeenCalledTimes(3); + }); + + it("projects an initial application failure into terminal state", async () => { + const client = queryClient(); + const failure = createFailure("FORBIDDEN", "LIST", 0); + const hook = renderHook( + () => + useApplicationQuery({ + queryKey: ["forbidden"], + execute: async () => ({ ok: false, error: failure }), + }), + { wrapper: wrapper(client) }, + ); + + await waitFor(() => + expect(hook.result.current.state.base).toBe("terminal-error"), + ); + expect(hook.result.current.state.failure).toBe(failure); + }); + + it("normalizes an unexpected execute rejection into a safe terminal failure", async () => { + const client = queryClient(); + const hook = renderHook( + () => + useApplicationQuery({ + queryKey: ["unexpected-rejection"], + execute: async () => { + throw new Error("private upstream detail"); + }, + }), + { wrapper: wrapper(client) }, + ); + + await waitFor(() => + expect(hook.result.current.state.base).toBe("terminal-error"), + ); + expect(hook.result.current.state.failure).toMatchObject({ + kind: "UNKNOWN_FAILURE", + operationId: "APPLICATION_QUERY", + userMessageKey: "error.unknown_failure", + action: "contact-support", + }); + expect(JSON.stringify(hook.result.current.state.failure)).not.toContain( + "private upstream detail", + ); + }); + + it("passes cancellation to the application and does not retain an unmounted error", async () => { + const client = queryClient(); + let aborted = false; + const execute = vi.fn( + ({ signal }: { signal: AbortSignal }) => + new Promise>((resolve) => { + signal.addEventListener( + "abort", + () => { + aborted = true; + resolve({ + ok: false, + error: createFailure("REQUEST_ABORTED", "LIST", 0), + }); + }, + { once: true }, + ); + }), + ); + const hook = renderHook( + () => + useApplicationQuery({ + queryKey: ["cancelled"], + execute, + }), + { wrapper: wrapper(client) }, + ); + + await waitFor(() => expect(execute).toHaveBeenCalledOnce()); + hook.unmount(); + await waitFor(() => expect(aborted).toBe(true)); + expect(client.getQueryState(["cancelled"])?.status).not.toBe("error"); + }); +}); + diff --git a/tests/component/application-query-fixture.tsx b/tests/component/application-query-fixture.tsx new file mode 100644 index 0000000..567236f --- /dev/null +++ b/tests/component/application-query-fixture.tsx @@ -0,0 +1,107 @@ +// @vitest-environment jsdom + +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import type { ReactNode } from "react"; + +import type { MutationIntentFactory } from "../../src/application/ports/mutation-intent-factory.ts"; +import { QueryInvalidationProvider } from "../../src/presentation/adapters/query/query-invalidation-provider.tsx"; +import { MutationIntentProvider } from "../../src/presentation/adapters/query/mutation-intent-provider.tsx"; +import { + defineQueryInvalidationTopic, + type QueryInvalidationCoordinator, +} from "../../src/contracts/query-invalidation.ts"; +import { createRuntimeIdentityRegistry } from "../../src/contracts/query-keys.ts"; +import type { QueryResultMeasure } from "../../src/contracts/server-state.ts"; +import type { CacheScopeSnapshot } from "../../src/contracts/server-state-scope.ts"; + +export const RESOURCE_INVALIDATION_TOPIC = + defineQueryInvalidationTopic("resource"); + +export function scopeSnapshot( + generation = 1, + fingerprint = "scope-fingerprint-0001", +): CacheScopeSnapshot & { fence(): void } { + let current = true; + const lifetime = new AbortController(); + const identities = createRuntimeIdentityRegistry({ + tokenFactory: () => "scope-identity-token-0001", + }); + return { + generation, + fingerprint, + identities, + signal: lifetime.signal, + isCurrent: () => current, + fence() { + current = false; + lifetime.abort(); + }, + }; +} + +export function measureOne(): QueryResultMeasure { + return { itemCount: 1, estimatedBytes: 8 }; +} + +export function queryClient() { + return new QueryClient({ + defaultOptions: { + queries: { retry: false, staleTime: 0, gcTime: Infinity }, + mutations: { retry: false }, + }, + }); +} + +export function deterministicMutationIntentFactory(): MutationIntentFactory { + let sequence = 0; + return Object.freeze({ + create(input) { + sequence += 1; + return Object.freeze({ + intentId: `intent-${sequence}`, + operationId: input.operationId, + canonicalInputIdentity: input.canonicalInputIdentity, + ...(input.requiresIdempotencyKey + ? { idempotencyKey: `key-${sequence}` } + : {}), + createdAtMonotonicMs: sequence, + }); + }, + }); +} + +export function wrapper( + client: QueryClient, + mutationIntentFactory = deterministicMutationIntentFactory(), +) { + const coordinator: QueryInvalidationCoordinator = { + async invalidate(topics) { + for (const topic of topics) { + await client.invalidateQueries({ + queryKey: [topic], + exact: false, + refetchType: "active", + }); + } + }, + beginMutation() { + return { release: async () => {} }; + }, + async resetLocal() { + await client.cancelQueries(); + client.clear(); + }, + dispose() {}, + }; + return function QueryWrapper({ children }: { children: ReactNode }) { + return ( + + + + {children} + + + + ); + }; +} diff --git a/tests/component/application-query-scope-fence.test.tsx b/tests/component/application-query-scope-fence.test.tsx new file mode 100644 index 0000000..6da1a06 --- /dev/null +++ b/tests/component/application-query-scope-fence.test.tsx @@ -0,0 +1,209 @@ +// @vitest-environment jsdom + +import { act, renderHook, waitFor } from "@testing-library/react"; +import { describe, expect, it, vi } from "vitest"; + +import { + type ApplicationResult, + useApplicationQuery, +} from "../../src/presentation/adapters/query/application-query.ts"; +import { + createQueryInvalidationPrefix, + defineQueryNamespaceIdentity, +} from "../../src/contracts/query-keys.ts"; +import { + bindQuery, + type QueryResultMeasure, +} from "../../src/contracts/server-state.ts"; +import { + measureOne, + queryClient, + scopeSnapshot, + wrapper, +} from "./application-query-fixture.tsx"; + +describe("scope-bound query commit fence", () => { + it("binds the namespace-first V2 query key", () => { + const scope = scopeSnapshot(); + const definition = { + definitionId: "resource-detail-v1", + definitionVersion: 1, + owner: "platform-test", + namespace: "resource", + namespaceVersion: 1, + operationId: "GET_RESOURCE", + profileId: "DETAIL_STANDARD" as const, + measureResult: measureOne, + execute: async () => ({ ok: true as const, value: "value" }), + }; + + const bound = bindQuery(definition, "resource-1", scope); + + expect(bound.queryKey).toEqual([ + "query", + 2, + "resource", + 1, + "scope-fingerprint-0001", + 1, + "scope-identity-token-0001", + ]); + expect(bound.queryKey.slice(0, 4)).toEqual( + createQueryInvalidationPrefix( + defineQueryNamespaceIdentity("resource", 1), + ), + ); + }); + + it("discards a successful result whose scope was fenced during execution", async () => { + const client = queryClient(); + const scope = scopeSnapshot(); + let complete: (value: ApplicationResult) => void = () => {}; + const hook = renderHook( + () => + useApplicationQuery( + bindQuery( + { + definitionId: "fenced-detail-v1", + definitionVersion: 1, + owner: "platform-test", + namespace: "fenced", + namespaceVersion: 1, + operationId: "GET_FENCED", + profileId: "DETAIL_STANDARD", + measureResult: measureOne, + execute: () => + new Promise>((resolve) => { + complete = resolve; + }), + }, + "input", + scope, + ), + ), + { wrapper: wrapper(client) }, + ); + + // §10.8: the scope goes stale after dispatch but before commit. + scope.fence(); + await act(async () => { + complete({ ok: true, value: "late" }); + }); + + await waitFor(() => + expect(hook.result.current.state.failure?.kind).toBe( + "SCOPE_GENERATION_CHANGED", + ), + ); + expect(hook.result.current.data).toBeUndefined(); + }); + + it("refuses to start when the captured scope is already stale", async () => { + const client = queryClient(); + const scope = scopeSnapshot(); + const execute = vi.fn(async () => ({ ok: true as const, value: "v" })); + scope.fence(); + + const hook = renderHook( + () => + useApplicationQuery( + bindQuery( + { + definitionId: "stale-detail-v1", + definitionVersion: 1, + owner: "platform-test", + namespace: "stale", + namespaceVersion: 1, + operationId: "GET_STALE", + profileId: "DETAIL_STANDARD", + measureResult: measureOne, + execute, + }, + "input", + scope, + ), + ), + { wrapper: wrapper(client) }, + ); + + await waitFor(() => + expect(hook.result.current.state.failure?.kind).toBe( + "SCOPE_GENERATION_CHANGED", + ), + ); + expect(execute).not.toHaveBeenCalled(); + }); + + it("rejects a result that exceeds the profile budget instead of caching it", async () => { + const client = queryClient(); + const scope = scopeSnapshot(); + const hook = renderHook( + () => + useApplicationQuery( + bindQuery( + { + definitionId: "oversized-list-v1", + definitionVersion: 1, + owner: "platform-test", + namespace: "oversized", + namespaceVersion: 1, + operationId: "LIST_OVERSIZED", + profileId: "VOLATILE_STATUS", + // §10.4: VOLATILE_STATUS admits 1 item and 64KiB. + measureResult: (): QueryResultMeasure => ({ + itemCount: 2, + estimatedBytes: 8, + }), + execute: async () => ({ ok: true as const, value: "value" }), + }, + "input", + scope, + ), + ), + { wrapper: wrapper(client) }, + ); + + await waitFor(() => + expect(hook.result.current.state.failure?.kind).toBe( + "RESULT_LIMIT_EXCEEDED", + ), + ); + expect(hook.result.current.data).toBeUndefined(); + }); + + it("treats a throwing measurement as a measurement failure, not a cache commit", async () => { + const client = queryClient(); + const scope = scopeSnapshot(); + const hook = renderHook( + () => + useApplicationQuery( + bindQuery( + { + definitionId: "unmeasurable-v1", + definitionVersion: 1, + owner: "platform-test", + namespace: "unmeasurable", + namespaceVersion: 1, + operationId: "GET_UNMEASURABLE", + profileId: "DETAIL_STANDARD", + measureResult: (): QueryResultMeasure => { + throw new Error("estimator defect"); + }, + execute: async () => ({ ok: true as const, value: "value" }), + }, + "input", + scope, + ), + ), + { wrapper: wrapper(client) }, + ); + + await waitFor(() => + expect(hook.result.current.state.failure?.kind).toBe( + "RESULT_LIMIT_EXCEEDED", + ), + ); + expect(hook.result.current.data).toBeUndefined(); + }); +}); + diff --git a/tests/component/application-query.test.tsx b/tests/component/application-query.test.tsx index a82911e..e32e8ed 100644 --- a/tests/component/application-query.test.tsx +++ b/tests/component/application-query.test.tsx @@ -1,557 +1,23 @@ // @vitest-environment jsdom -import { - act, - renderHook, - waitFor, -} from "@testing-library/react"; -import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -import type { ReactNode } from "react"; +import { act, renderHook, waitFor } from "@testing-library/react"; import { renderToString } from "react-dom/server"; import { describe, expect, it, vi } from "vitest"; import { type ApplicationResult, useApplicationMutation, - useApplicationQuery, } from "../../src/presentation/adapters/query/application-query.ts"; -import type { MutationIntentFactory } from "../../src/application/ports/mutation-intent-factory.ts"; -import { MutationIntentProvider } from "../../src/presentation/adapters/query/mutation-intent-provider.tsx"; -import { QueryInvalidationProvider } from "../../src/presentation/adapters/query/query-invalidation-provider.tsx"; -import { - defineQueryInvalidationTopic, - type QueryInvalidationCoordinator, -} from "../../src/contracts/query-invalidation.ts"; import { createFailure } from "../../src/contracts/errors.ts"; +import { MUTATION_COORDINATOR_BOUNDS } from "../../src/contracts/server-state.ts"; import { - createQueryInvalidationPrefix, - createRuntimeIdentityRegistry, - defineQueryNamespaceIdentity, -} from "../../src/contracts/query-keys.ts"; -import { - bindQuery, - MUTATION_COORDINATOR_BOUNDS, - type QueryResultMeasure, -} from "../../src/contracts/server-state.ts"; -import type { CacheScopeSnapshot } from "../../src/contracts/server-state-scope.ts"; + RESOURCE_INVALIDATION_TOPIC, + queryClient, + scopeSnapshot, + wrapper, +} from "./application-query-fixture.tsx"; -const RESOURCE_INVALIDATION_TOPIC = - defineQueryInvalidationTopic("resource"); - -/** - * §24.12: the scope-bound commit fence is common runtime, so it is verified - * here with a local scope fixture rather than through the removable sample - * feature. - */ -function scopeSnapshot( - generation = 1, - fingerprint = "scope-fingerprint-0001", -): CacheScopeSnapshot & { fence(): void } { - let current = true; - const lifetime = new AbortController(); - const identities = createRuntimeIdentityRegistry({ - tokenFactory: () => "scope-identity-token-0001", - }); - return { - generation, - fingerprint, - identities, - signal: lifetime.signal, - isCurrent: () => current, - fence() { - current = false; - lifetime.abort(); - }, - }; -} - -function measureOne(): QueryResultMeasure { - return { itemCount: 1, estimatedBytes: 8 }; -} - -function queryClient() { - return new QueryClient({ - defaultOptions: { - queries: { retry: false, staleTime: 0, gcTime: Infinity }, - mutations: { retry: false }, - }, - }); -} - -function deterministicMutationIntentFactory(): MutationIntentFactory { - let sequence = 0; - return Object.freeze({ - create(input) { - sequence += 1; - return Object.freeze({ - intentId: `intent-${sequence}`, - operationId: input.operationId, - canonicalInputIdentity: input.canonicalInputIdentity, - ...(input.requiresIdempotencyKey - ? { idempotencyKey: `key-${sequence}` } - : {}), - createdAtMonotonicMs: sequence, - }); - }, - }); -} - -function wrapper( - client: QueryClient, - mutationIntentFactory = deterministicMutationIntentFactory(), -) { - const coordinator: QueryInvalidationCoordinator = { - async invalidate(topics) { - for (const topic of topics) { - await client.invalidateQueries({ - queryKey: [topic], - exact: false, - refetchType: "active", - }); - } - }, - beginMutation() { - return { release: async () => {} }; - }, - async resetLocal() { - await client.cancelQueries(); - client.clear(); - }, - dispose() {}, - }; - return function QueryWrapper({ children }: { children: ReactNode }) { - return ( - - - - {children} - - - - ); - }; -} - -describe("application query inbound bridge", () => { - it("latches a background failure over stale data and clears it on retry success", async () => { - const client = queryClient(); - const responses: ApplicationResult[] = [ - { ok: true, value: ["first"] }, - { - ok: false, - error: createFailure("SERVER_FAILURE", "LIST", 0), - }, - { ok: true, value: ["recovered"] }, - ]; - const execute = vi.fn(async () => responses.shift() ?? responses[0]); - const hook = renderHook( - () => - useApplicationQuery({ - queryKey: ["resource", "list"], - execute, - }), - { wrapper: wrapper(client) }, - ); - - await waitFor(() => expect(hook.result.current.data).toEqual(["first"])); - await act(() => hook.result.current.retry()); - await waitFor(() => - expect(hook.result.current.state.indicator).toBe("stale-degraded"), - ); - expect(hook.result.current.state.base).toBe("success"); - expect(hook.result.current.data).toEqual(["first"]); - - await act(() => hook.result.current.retry()); - await waitFor(() => - expect(hook.result.current.data).toEqual(["recovered"]), - ); - expect(hook.result.current.state.indicator).toBeNull(); - expect(execute).toHaveBeenCalledTimes(3); - }); - - it("projects an initial application failure into terminal state", async () => { - const client = queryClient(); - const failure = createFailure("FORBIDDEN", "LIST", 0); - const hook = renderHook( - () => - useApplicationQuery({ - queryKey: ["forbidden"], - execute: async () => ({ ok: false, error: failure }), - }), - { wrapper: wrapper(client) }, - ); - - await waitFor(() => - expect(hook.result.current.state.base).toBe("terminal-error"), - ); - expect(hook.result.current.state.failure).toBe(failure); - }); - - it("normalizes an unexpected execute rejection into a safe terminal failure", async () => { - const client = queryClient(); - const hook = renderHook( - () => - useApplicationQuery({ - queryKey: ["unexpected-rejection"], - execute: async () => { - throw new Error("private upstream detail"); - }, - }), - { wrapper: wrapper(client) }, - ); - - await waitFor(() => - expect(hook.result.current.state.base).toBe("terminal-error"), - ); - expect(hook.result.current.state.failure).toMatchObject({ - kind: "UNKNOWN_FAILURE", - operationId: "APPLICATION_QUERY", - userMessageKey: "error.unknown_failure", - action: "contact-support", - }); - expect(JSON.stringify(hook.result.current.state.failure)).not.toContain( - "private upstream detail", - ); - }); - - it("passes cancellation to the application and does not retain an unmounted error", async () => { - const client = queryClient(); - let aborted = false; - const execute = vi.fn( - ({ signal }: { signal: AbortSignal }) => - new Promise>((resolve) => { - signal.addEventListener( - "abort", - () => { - aborted = true; - resolve({ - ok: false, - error: createFailure("REQUEST_ABORTED", "LIST", 0), - }); - }, - { once: true }, - ); - }), - ); - const hook = renderHook( - () => - useApplicationQuery({ - queryKey: ["cancelled"], - execute, - }), - { wrapper: wrapper(client) }, - ); - - await waitFor(() => expect(execute).toHaveBeenCalledOnce()); - hook.unmount(); - await waitFor(() => expect(aborted).toBe(true)); - expect(client.getQueryState(["cancelled"])?.status).not.toBe("error"); - }); -}); - -describe("scope-bound query commit fence", () => { - it("binds the namespace-first V2 query key", () => { - const scope = scopeSnapshot(); - const definition = { - definitionId: "resource-detail-v1", - definitionVersion: 1, - owner: "platform-test", - namespace: "resource", - namespaceVersion: 1, - operationId: "GET_RESOURCE", - profileId: "DETAIL_STANDARD" as const, - measureResult: measureOne, - execute: async () => ({ ok: true as const, value: "value" }), - }; - - const bound = bindQuery(definition, "resource-1", scope); - - expect(bound.queryKey).toEqual([ - "query", - 2, - "resource", - 1, - "scope-fingerprint-0001", - 1, - "scope-identity-token-0001", - ]); - expect(bound.queryKey.slice(0, 4)).toEqual( - createQueryInvalidationPrefix( - defineQueryNamespaceIdentity("resource", 1), - ), - ); - }); - - it("discards a successful result whose scope was fenced during execution", async () => { - const client = queryClient(); - const scope = scopeSnapshot(); - let complete: (value: ApplicationResult) => void = () => {}; - const hook = renderHook( - () => - useApplicationQuery( - bindQuery( - { - definitionId: "fenced-detail-v1", - definitionVersion: 1, - owner: "platform-test", - namespace: "fenced", - namespaceVersion: 1, - operationId: "GET_FENCED", - profileId: "DETAIL_STANDARD", - measureResult: measureOne, - execute: () => - new Promise>((resolve) => { - complete = resolve; - }), - }, - "input", - scope, - ), - ), - { wrapper: wrapper(client) }, - ); - - // §10.8: the scope goes stale after dispatch but before commit. - scope.fence(); - await act(async () => { - complete({ ok: true, value: "late" }); - }); - - await waitFor(() => - expect(hook.result.current.state.failure?.kind).toBe( - "SCOPE_GENERATION_CHANGED", - ), - ); - expect(hook.result.current.data).toBeUndefined(); - }); - - it("refuses to start when the captured scope is already stale", async () => { - const client = queryClient(); - const scope = scopeSnapshot(); - const execute = vi.fn(async () => ({ ok: true as const, value: "v" })); - scope.fence(); - - const hook = renderHook( - () => - useApplicationQuery( - bindQuery( - { - definitionId: "stale-detail-v1", - definitionVersion: 1, - owner: "platform-test", - namespace: "stale", - namespaceVersion: 1, - operationId: "GET_STALE", - profileId: "DETAIL_STANDARD", - measureResult: measureOne, - execute, - }, - "input", - scope, - ), - ), - { wrapper: wrapper(client) }, - ); - - await waitFor(() => - expect(hook.result.current.state.failure?.kind).toBe( - "SCOPE_GENERATION_CHANGED", - ), - ); - expect(execute).not.toHaveBeenCalled(); - }); - - it("rejects a result that exceeds the profile budget instead of caching it", async () => { - const client = queryClient(); - const scope = scopeSnapshot(); - const hook = renderHook( - () => - useApplicationQuery( - bindQuery( - { - definitionId: "oversized-list-v1", - definitionVersion: 1, - owner: "platform-test", - namespace: "oversized", - namespaceVersion: 1, - operationId: "LIST_OVERSIZED", - profileId: "VOLATILE_STATUS", - // §10.4: VOLATILE_STATUS admits 1 item and 64KiB. - measureResult: (): QueryResultMeasure => ({ - itemCount: 2, - estimatedBytes: 8, - }), - execute: async () => ({ ok: true as const, value: "value" }), - }, - "input", - scope, - ), - ), - { wrapper: wrapper(client) }, - ); - - await waitFor(() => - expect(hook.result.current.state.failure?.kind).toBe( - "RESULT_LIMIT_EXCEEDED", - ), - ); - expect(hook.result.current.data).toBeUndefined(); - }); - - it("treats a throwing measurement as a measurement failure, not a cache commit", async () => { - const client = queryClient(); - const scope = scopeSnapshot(); - const hook = renderHook( - () => - useApplicationQuery( - bindQuery( - { - definitionId: "unmeasurable-v1", - definitionVersion: 1, - owner: "platform-test", - namespace: "unmeasurable", - namespaceVersion: 1, - operationId: "GET_UNMEASURABLE", - profileId: "DETAIL_STANDARD", - measureResult: (): QueryResultMeasure => { - throw new Error("estimator defect"); - }, - execute: async () => ({ ok: true as const, value: "value" }), - }, - "input", - scope, - ), - ), - { wrapper: wrapper(client) }, - ); - - await waitFor(() => - expect(hook.result.current.state.failure?.kind).toBe( - "RESULT_LIMIT_EXCEEDED", - ), - ); - expect(hook.result.current.data).toBeUndefined(); - }); -}); - -describe("scope-bound mutation fence", () => { - it("rejects a submit whose scope is already fenced", async () => { - const client = queryClient(); - const scope = scopeSnapshot(); - const execute = vi.fn(async () => ({ ok: true as const, value: "v" })); - const hook = renderHook( - () => - useApplicationMutation({ - definitionId: "fenced-mutation-v1", - definitionVersion: 1, - operationId: "CREATE_FENCED", - requiresIdempotencyKey: false, - owner: "platform-test", - duplicatePolicy: "REJECT_WHILE_ACTIVE", - scope, - execute, - invalidate: [], - }), - { wrapper: wrapper(client) }, - ); - - scope.fence(); - const outcome = await hook.result.current.submit("value"); - expect(outcome).toMatchObject({ - ok: false, - error: { - kind: "SCOPE_GENERATION_CHANGED", - effect: "NOT_STARTED", - }, - }); - expect(execute).not.toHaveBeenCalled(); - }); - - it("discards a mutation result whose scope was fenced after dispatch", async () => { - const client = queryClient(); - const scope = scopeSnapshot(); - const execute = vi.fn(async () => { - scope.fence(); - return { ok: true as const, value: "committed" }; - }); - const hook = renderHook( - () => - useApplicationMutation({ - definitionId: "late-mutation-v1", - definitionVersion: 1, - operationId: "CREATE_LATE", - requiresIdempotencyKey: false, - owner: "platform-test", - duplicatePolicy: "ALLOW_PARALLEL", - scope, - execute, - invalidate: [], - }), - { wrapper: wrapper(client) }, - ); - - const outcome = await hook.result.current.submit("value"); - expect(outcome).toMatchObject({ - ok: false, - error: { kind: "SCOPE_GENERATION_CHANGED" }, - }); - expect(execute).toHaveBeenCalledOnce(); - }); - - it("aborts a hung mutation when its captured scope is fenced", async () => { - const client = queryClient(); - const scope = scopeSnapshot(); - let observedSignal: AbortSignal | undefined; - const execute = vi.fn( - (_input: string, context: Readonly<{ signal: AbortSignal }>) => - new Promise>((resolve) => { - observedSignal = context.signal; - context.signal.addEventListener( - "abort", - () => - resolve({ - ok: false, - error: createFailure("REQUEST_ABORTED", "CREATE_HUNG", 0), - }), - { once: true }, - ); - }), - ); - const hook = renderHook( - () => - useApplicationMutation({ - definitionId: "hung-mutation-v1", - definitionVersion: 1, - operationId: "CREATE_HUNG", - requiresIdempotencyKey: false, - owner: "platform-test", - duplicatePolicy: "REJECT_WHILE_ACTIVE", - scope, - execute, - invalidate: [], - }), - { wrapper: wrapper(client) }, - ); - - const outcome = hook.result.current.submit("value"); - await waitFor(() => expect(observedSignal).toBe(scope.signal)); - - scope.fence(); - - expect(observedSignal?.aborted).toBe(true); - await expect(outcome).resolves.toMatchObject({ - ok: false, - error: { - kind: "SCOPE_GENERATION_CHANGED", - effect: "MAYBE_APPLIED", - retryable: false, - action: "contact-support", - }, - }); - }); -}); - -describe("application mutation inbound bridge", () => { +describe("application mutation reconciliation bridge", () => { it.each([ ["NOT_STARTED", ["existing"], 0, null], ["NOT_APPLIED", ["existing"], 0, null], @@ -1700,497 +1166,4 @@ describe("application mutation inbound bridge", () => { }, ); - it("retains optimistic data when execute throws after dispatch begins", async () => { - const client = queryClient(); - const key = ["resource", "thrown-unknown-effect"]; - client.setQueryData(key, ["base"]); - const hook = renderHook( - () => - useApplicationMutation({ - execute: async () => { - throw new Error("private transport defect"); - }, - currentData: client.getQueryData(key), - optimistic: { - queryKey: key, - update: (previous, input) => [ - ...(previous as string[]), - input, - ], - }, - }), - { wrapper: wrapper(client) }, - ); - - let outcome: ApplicationResult | undefined; - await act(async () => { - outcome = await hook.result.current.submit("created"); - }); - - expect(outcome).toMatchObject({ - ok: false, - error: { - effect: "MAYBE_APPLIED", - retryable: false, - action: "contact-support", - }, - }); - expect(JSON.stringify(outcome)).not.toContain("private transport defect"); - expect(client.getQueryData(key)).toEqual(["base", "created"]); - expect(hook.result.current.state.indicator).toBe( - "mutation-effect-unknown", - ); - }); - - it("creates a distinct logical intent for each independently admitted submit", async () => { - const client = queryClient(); - const scope = scopeSnapshot(); - const observedIntents: unknown[] = []; - const execute = vi.fn( - async ( - input: string, - context: Readonly<{ signal: AbortSignal; intent?: unknown }>, - ) => { - observedIntents.push(context.intent); - return { ok: true as const, value: input }; - }, - ); - const hook = renderHook( - () => - useApplicationMutation({ - definitionId: "independent-intent-v1", - definitionVersion: 1, - operationId: "CREATE_WITH_INTENT", - requiresIdempotencyKey: true, - owner: "platform-test", - duplicatePolicy: "ALLOW_PARALLEL", - scope, - execute, - invalidate: [], - }), - { wrapper: wrapper(client) }, - ); - - await act(async () => { - await hook.result.current.submit("same-input"); - await hook.result.current.submit("same-input"); - }); - - expect(observedIntents).toHaveLength(2); - expect(observedIntents[0]).toMatchObject({ - intentId: "intent-1", - operationId: "CREATE_WITH_INTENT", - idempotencyKey: "key-1", - }); - expect(observedIntents[1]).toMatchObject({ - intentId: "intent-2", - operationId: "CREATE_WITH_INTENT", - idempotencyKey: "key-2", - }); - expect(observedIntents[0]).not.toEqual(observedIntents[1]); - }); - - it("creates no second intent when JOIN_IDENTICAL shares an admitted submit", async () => { - const client = queryClient(); - const scope = scopeSnapshot(); - const deterministicFactory = deterministicMutationIntentFactory(); - const createIntent = vi.fn(deterministicFactory.create); - const factory: MutationIntentFactory = Object.freeze({ - create: createIntent, - }); - let complete: (value: ApplicationResult) => void = () => {}; - const execute = vi.fn( - () => - new Promise>((resolve) => { - complete = resolve; - }), - ); - const hook = renderHook( - () => - useApplicationMutation({ - definitionId: "joined-intent-v1", - definitionVersion: 1, - operationId: "CREATE_JOINED", - requiresIdempotencyKey: true, - owner: "platform-test", - duplicatePolicy: "JOIN_IDENTICAL", - scope, - execute, - invalidate: [], - }), - { wrapper: wrapper(client, factory) }, - ); - - let first: Promise> | null = null; - let joined: Promise> | null = null; - act(() => { - first = hook.result.current.submit("same-input"); - joined = hook.result.current.submit("same-input"); - }); - - expect(first).toBe(joined); - await waitFor(() => expect(execute).toHaveBeenCalledOnce()); - expect(createIntent).toHaveBeenCalledOnce(); - expect(createIntent).toHaveBeenCalledWith({ - operationId: "CREATE_JOINED", - canonicalInputIdentity: - "scope-fingerprint-0001:joined-intent-v1:scope-identity-token-0001", - requiresIdempotencyKey: true, - }); - - complete({ ok: true, value: "same-input" }); - if (!first) throw new Error("expected admitted mutation"); - await act(() => first); - }); - - it("keeps the legacy raw mutation path outside the intent factory", async () => { - const client = queryClient(); - const createIntent = vi.fn(); - const factory: MutationIntentFactory = Object.freeze({ - create: createIntent, - }); - const execute = vi.fn(async (input: string) => ({ - ok: true as const, - value: input, - })); - const hook = renderHook( - () => - useApplicationMutation({ - definitionId: "legacy-raw-path-v1", - execute, - }), - { wrapper: wrapper(client, factory) }, - ); - - await act(() => hook.result.current.submit("legacy-input")); - - expect(execute).toHaveBeenCalledOnce(); - expect(createIntent).not.toHaveBeenCalled(); - }); - - it("rejects a duplicate submit by default while one is active", async () => { - const client = queryClient(); - let complete: (value: ApplicationResult) => void = () => {}; - const execute = vi.fn( - () => - new Promise>((resolve) => { - complete = resolve; - }), - ); - const hook = renderHook( - () => - useApplicationMutation({ - definitionId: "legacy-duplicate-rejection-v1", - execute, - }), - { wrapper: wrapper(client) }, - ); - - let first: Promise> | null = null; - let duplicate: Promise> | null = null; - act(() => { - first = hook.result.current.submit("created"); - duplicate = hook.result.current.submit("created"); - }); - - if (!first || !duplicate) throw new Error("expected two submissions"); - await expect(duplicate).resolves.toMatchObject({ - ok: false, - error: { kind: "DUPLICATE_IN_FLIGHT" }, - }); - expect(execute).toHaveBeenCalledOnce(); - - complete({ ok: true, value: "created" }); - await act(() => first as Promise>); - }); - - it("deduplicates submit and commits one optimistic mutation", async () => { - const client = queryClient(); - const key = ["resource", "list"]; - client.setQueryData(key, ["existing"]); - let complete: (value: ApplicationResult) => void = () => {}; - const execute = vi.fn( - () => - new Promise>((resolve) => { - complete = resolve; - }), - ); - const hook = renderHook( - () => - useApplicationMutation({ - // §11.2: joining is opt-in. The default is REJECT_WHILE_ACTIVE. - duplicatePolicy: "JOIN_IDENTICAL", - execute, - invalidate: [RESOURCE_INVALIDATION_TOPIC], - currentData: client.getQueryData(key), - optimistic: { - queryKey: key, - update: (previous, input) => [ - ...(previous as string[]), - input, - ], - }, - }), - { wrapper: wrapper(client) }, - ); - - let first: Promise> | null = null; - let duplicate: Promise> | null = null; - act(() => { - first = hook.result.current.submit("created"); - duplicate = hook.result.current.submit("created"); - }); - expect(first).toBe(duplicate); - await waitFor(() => - expect(client.getQueryData(key)).toEqual(["existing", "created"]), - ); - await waitFor(() => expect(execute).toHaveBeenCalledOnce()); - await waitFor(() => - expect(hook.result.current.state.indicator).toBe("mutation-pending"), - ); - - complete({ ok: true, value: "created" }); - if (!first) throw new Error("expected pending mutation"); - await act(() => first); - expect(client.getQueryState(key)?.isInvalidated).toBe(true); - await waitFor(() => - expect(hook.result.current.state.indicator).toBeNull(), - ); - }); - - it("never joins distinct mutation inputs to the same runtime promise", async () => { - const client = queryClient(); - const resolvers = new Map< - string, - (value: ApplicationResult) => void - >(); - const execute = vi.fn( - (input: string) => - new Promise>((resolve) => { - resolvers.set(input, resolve); - }), - ); - const hook = renderHook( - () => - useApplicationMutation({ - definitionId: "legacy-parallel-distinct-inputs-v1", - execute, - currentData: true, - }), - { wrapper: wrapper(client) }, - ); - - let first: Promise> | undefined; - let second: Promise> | undefined; - act(() => { - first = hook.result.current.submit("first"); - second = hook.result.current.submit("second"); - }); - expect(first).not.toBe(second); - await waitFor(() => expect(execute).toHaveBeenCalledTimes(2)); - - resolvers.get("first")?.({ ok: true, value: "first" }); - resolvers.get("second")?.({ ok: true, value: "second" }); - if (!first || !second) throw new Error("expected pending mutations"); - await act(async () => { - await Promise.all([first, second]); - }); - }); - - it("cancels an in-flight query before taking the optimistic snapshot", async () => { - const client = queryClient(); - const key = ["resource", "ordered-update"]; - client.setQueryData(key, ["existing"]); - let finishCancellation: () => void = () => {}; - const cancellation = new Promise((resolve) => { - finishCancellation = resolve; - }); - const cancelQueries = vi - .spyOn(client, "cancelQueries") - .mockImplementation(async () => cancellation); - const getQueryData = vi.spyOn(client, "getQueryData"); - const update = vi.fn((previous, input) => [ - ...(previous as string[]), - input, - ]); - const execute = vi.fn(async () => ({ - ok: true as const, - value: "created", - })); - const hook = renderHook( - () => - useApplicationMutation({ - execute, - currentData: ["existing"], - optimistic: { queryKey: key, update }, - }), - { wrapper: wrapper(client) }, - ); - - let pending: Promise> | undefined; - act(() => { - pending = hook.result.current.submit("created"); - }); - expect(cancelQueries).toHaveBeenCalledWith({ - queryKey: key, - exact: true, - }); - expect(getQueryData).not.toHaveBeenCalled(); - expect(update).not.toHaveBeenCalled(); - expect(execute).not.toHaveBeenCalled(); - - finishCancellation(); - if (!pending) throw new Error("expected pending mutation"); - await act(() => pending); - - expect(getQueryData).toHaveBeenCalledWith(key); - expect(update).toHaveBeenCalledWith(["existing"], "created"); - expect(execute).toHaveBeenCalledOnce(); - expect(client.getQueryData(key)).toEqual(["existing", "created"]); - }); - - it("keeps a committed optimistic update when invalidation fails", async () => { - const client = queryClient(); - const key = ["resource", "committed-update"]; - client.setQueryData(key, ["existing"]); - vi.spyOn(client, "invalidateQueries").mockRejectedValue( - new Error("cache refresh failed"), - ); - const hook = renderHook( - () => - useApplicationMutation({ - execute: async () => ({ ok: true, value: "created" }), - invalidate: [RESOURCE_INVALIDATION_TOPIC], - currentData: ["existing"], - optimistic: { - queryKey: key, - update: (previous, input) => [ - ...(previous as string[]), - input, - ], - }, - }), - { wrapper: wrapper(client) }, - ); - - let outcome; - await act(async () => { - outcome = await hook.result.current.submit("created"); - }); - - expect(outcome).toEqual({ ok: true, value: "created" }); - expect(client.getQueryData(key)).toEqual(["existing", "created"]); - }); - - it("normalizes an optimistic preparation defect without running the command", async () => { - const client = queryClient(); - const key = ["resource", "invalid-optimistic-update"]; - client.setQueryData(key, ["existing"]); - const execute = vi.fn(async () => ({ - ok: true as const, - value: "created", - })); - const hook = renderHook( - () => - useApplicationMutation({ - execute, - currentData: ["existing"], - optimistic: { - queryKey: key, - update: () => { - throw new Error("private optimistic detail"); - }, - }, - }), - { wrapper: wrapper(client) }, - ); - - let outcome; - await act(async () => { - outcome = await hook.result.current.submit("created"); - }); - - expect(outcome).toMatchObject({ - ok: false, - error: { - kind: "UNKNOWN_FAILURE", - effect: "NOT_STARTED", - operationId: "APPLICATION_MUTATION", - userMessageKey: "error.unknown_failure", - }, - }); - expect(JSON.stringify(outcome)).not.toContain("private optimistic detail"); - expect(execute).not.toHaveBeenCalled(); - expect(client.getQueryData(key)).toEqual(["existing"]); - }); - - it("removes an optimistic cache entry when no prior data existed", async () => { - const client = queryClient(); - const key = ["resource", "new-optimistic-entry"]; - const failure = createFailure("SERVER_FAILURE", "CREATE", 0, { - effect: "NOT_APPLIED", - }); - const hook = renderHook( - () => - useApplicationMutation({ - execute: async () => ({ ok: false, error: failure }), - currentData: true, - optimistic: { - queryKey: key, - update: (_previous, input) => [input], - }, - }), - { wrapper: wrapper(client) }, - ); - - let outcome; - await act(async () => { - outcome = await hook.result.current.submit("temporary"); - }); - - expect(outcome).toEqual({ ok: false, error: failure }); - expect(client.getQueryData(key)).toBeUndefined(); - expect(client.getQueryState(key)).toBeUndefined(); - }); - - it("rolls optimistic data back and exposes a resolvable conflict", async () => { - const client = queryClient(); - const key = ["resource", "list"]; - client.setQueryData(key, ["existing"]); - const conflict = createFailure("CONFLICT", "CREATE", 0, { - effect: "NOT_APPLIED", - }); - const hook = renderHook( - () => - useApplicationMutation({ - execute: async () => ({ ok: false, error: conflict }), - invalidate: [RESOURCE_INVALIDATION_TOPIC], - currentData: client.getQueryData(key), - optimistic: { - queryKey: key, - update: (previous, input) => [ - ...(previous as string[]), - input, - ], - }, - }), - { wrapper: wrapper(client) }, - ); - - let outcome; - await act(async () => { - outcome = await hook.result.current.submit("conflicting"); - }); - expect(outcome).toEqual({ ok: false, error: conflict }); - expect(client.getQueryData(key)).toEqual(["existing"]); - expect(hook.result.current.state.indicator).toBe("mutation-conflict"); - expect(hook.result.current.state.overlay).toMatchObject({ - mutationPending: false, - mutationConflict: true, - }); - - await act(() => hook.result.current.resolveConflict()); - expect(hook.result.current.state.indicator).toBeNull(); - expect(client.getQueryState(key)?.isInvalidated).toBe(true); - }); }); diff --git a/tests/contract/consumer-experience/fixtures/local-draft-feature.ts b/tests/contract/consumer-experience/fixtures/local-draft-feature.ts new file mode 100644 index 0000000..5a78fed --- /dev/null +++ b/tests/contract/consumer-experience/fixtures/local-draft-feature.ts @@ -0,0 +1,97 @@ +import type { + BrowserDataResult, + IndexedDbRepositoryPort, +} from "../../../../src/application/ports/browser-file-storage/index.ts"; + +export type LocalDraft = Readonly<{ + draftId: string; + title: string; + body: string; +}>; + +export type SaveLocalDraftCommand = Readonly<{ + draft: LocalDraft; + expectedRevision: number | null; + idempotencyKey: string; +}>; + +export type RemoveLocalDraftCommand = Readonly<{ + draftId: string; + expectedRevision: number; + idempotencyKey: string; +}>; + +export type LocalDraftRecord = Readonly<{ + draft: LocalDraft; + revision: number; +}>; + +export interface LocalDraftStore { + save( + command: SaveLocalDraftCommand, + signal?: AbortSignal, + ): Promise>>; + find( + draftId: string, + signal?: AbortSignal, + ): Promise>; + remove( + command: RemoveLocalDraftCommand, + signal?: AbortSignal, + ): Promise>; +} + +/** + * Feature-owned binding over the technology-neutral IndexedDB application port. + * + * The feature knows its domain type and optimistic concurrency inputs. It does + * not know database names, stores, transactions, native IDB objects, codecs, + * migrations, quota handling or connection lifecycle. + */ +export function createLocalDraftStore( + repository: IndexedDbRepositoryPort, +): LocalDraftStore { + const store: LocalDraftStore = { + async save(command, signal) { + const result = await repository.compareAndSwap({ + key: command.draft.draftId, + value: command.draft, + expectedRevision: command.expectedRevision, + idempotencyKey: command.idempotencyKey, + signal, + }); + if (!result.ok) return result; + return Object.freeze({ + ok: true as const, + value: Object.freeze({ revision: result.value.revision }), + }); + }, + + async find(draftId, signal) { + const result = await repository.read(draftId, signal); + if (!result.ok) return result; + return Object.freeze({ + ok: true as const, + value: + result.value === null + ? null + : Object.freeze({ + draft: result.value.value, + revision: result.value.revision, + }), + }); + }, + + async remove(command, signal) { + const result = await repository.remove({ + key: command.draftId, + expectedRevision: command.expectedRevision, + idempotencyKey: command.idempotencyKey, + signal, + }); + if (!result.ok) return result; + return Object.freeze({ ok: true as const, value: undefined }); + }, + }; + return Object.freeze(store); +} diff --git a/tests/contract/consumer-experience/indexeddb-local-draft.test.ts b/tests/contract/consumer-experience/indexeddb-local-draft.test.ts new file mode 100644 index 0000000..f25dfae --- /dev/null +++ b/tests/contract/consumer-experience/indexeddb-local-draft.test.ts @@ -0,0 +1,161 @@ +import { readFile } from "node:fs/promises"; + +import { describe, expect, it } from "vitest"; + +import type { + BrowserDataResult, + IndexedDbRepositoryPort, +} from "../../../src/application/ports/browser-file-storage/index.ts"; +import { + createLocalDraftStore, + type LocalDraft, +} from "./fixtures/local-draft-feature.ts"; + +function success(value: Value): BrowserDataResult { + return Object.freeze({ ok: true as const, value }); +} + +function repositoryFixture(): IndexedDbRepositoryPort { + let stored: Readonly<{ value: LocalDraft; revision: number }> | null = null; + + const repository: IndexedDbRepositoryPort = { + async open() { + return success(undefined); + }, + async read(key) { + if (stored === null || stored.value.draftId !== key) { + return success(null); + } + return success(stored); + }, + async query() { + return success(Object.freeze({ items: [], nextCursor: null })); + }, + async compareAndSwap(input) { + const currentRevision = stored?.revision ?? null; + if (currentRevision !== input.expectedRevision) { + return Object.freeze({ + ok: false as const, + error: Object.freeze({ + code: "CONFLICT" as const, + operation: "INDEXEDDB_WRITE" as const, + retryable: false, + recovery: "RECONCILE" as const, + }), + }); + } + const revision = (currentRevision ?? 0) + 1; + stored = Object.freeze({ value: input.value, revision }); + return success( + Object.freeze({ + key: input.key, + revision, + replayed: false, + }), + ); + }, + async remove(input) { + if (stored === null || stored.revision !== input.expectedRevision) { + return Object.freeze({ + ok: false as const, + error: Object.freeze({ + code: "CONFLICT" as const, + operation: "INDEXEDDB_WRITE" as const, + retryable: false, + recovery: "RECONCILE" as const, + }), + }); + } + stored = null; + return success( + Object.freeze({ + key: input.key, + revision: input.expectedRevision + 1, + replayed: false, + }), + ); + }, + async enforceLifecycleBatch() { + stored = null; + return success( + Object.freeze({ + state: "COMPLETE" as const, + scannedRows: 0, + deletedRows: 0, + budgetExhausted: false, + }), + ); + }, + getStatus() { + return Object.freeze({ kind: "READY" as const, schemaVersion: 1 }); + }, + subscribeStatus() { + return () => {}; + }, + close() {}, + }; + return Object.freeze(repository); +} + +describe("IndexedDB local-draft consumer experience", () => { + it("implements save/find/remove through the public application port", async () => { + const store = createLocalDraftStore(repositoryFixture()); + const draft = Object.freeze({ + draftId: "draft-1", + title: "Architecture notes", + body: "Feature code owns the draft model.", + }); + + await expect( + store.save({ + draft, + expectedRevision: null, + idempotencyKey: "draft-save-0001", + }), + ).resolves.toEqual({ ok: true, value: { revision: 1 } }); + + await expect(store.find("draft-1")).resolves.toEqual({ + ok: true, + value: { draft, revision: 1 }, + }); + + await expect( + store.remove({ + draftId: "draft-1", + expectedRevision: 1, + idempotencyKey: "draft-remove-0001", + }), + ).resolves.toEqual({ ok: true, value: undefined }); + + await expect(store.find("draft-1")).resolves.toEqual({ + ok: true, + value: null, + }); + }); + + it("keeps native IndexedDB and runtime internals out of feature-owned code", async () => { + const source = await readFile( + new URL("./fixtures/local-draft-feature.ts", import.meta.url), + "utf8", + ); + + const importLines = source + .split("\n") + .filter((line) => line.startsWith("import ")); + expect(importLines).toHaveLength(1); + expect(source).toContain( + "src/application/ports/browser-file-storage/index.ts", + ); + + for (const forbidden of [ + "src/adapters/storage/indexeddb", + "globalThis.indexedDB", + "IDBFactory", + "IDBDatabase", + "IDBTransaction", + "IDBObjectStore", + ]) { + expect(source).not.toContain(forbidden); + } + }); +}); diff --git a/tests/contract/reusable-capability/feature-adapter-composition.test.ts b/tests/contract/reusable-capability/feature-adapter-composition.test.ts new file mode 100644 index 0000000..0db7819 --- /dev/null +++ b/tests/contract/reusable-capability/feature-adapter-composition.test.ts @@ -0,0 +1,122 @@ +import { describe, expect, it } from "vitest"; + +import type { + IndexedDbRepositoryPort, +} from "../../../src/application/ports/browser-file-storage/index.ts"; +import type { + InstalledHttpOperationExecutor, +} from "../../../src/adapters/http/index.ts"; +import { + composeFeatureAdapterInputs, + defineFeatureAdapterContribution, + type IndexedDbRepositoryProvider, +} from "../../../src/features/feature-adapter-contribution.ts"; +import { + LOCAL_DRAFT_FEATURE_ADAPTER_CONTRIBUTION, +} from "../../../src/features/local-draft-feature/adapters/create-local-draft-feature-input.ts"; +import type { LocalDraft } from "../../../src/features/local-draft-feature/domain/local-draft.ts"; + +type TestHttpFeatureInput = Readonly<{ + ping(): Promise<"pong">; +}>; + +declare module "../../../src/application/ports/in/application-api.ts" { + interface ApplicationFeatureInputs { + "test-http-feature": TestHttpFeatureInput; + } +} + +const TEST_HTTP_FEATURE_ADAPTER_CONTRIBUTION = + defineFeatureAdapterContribution({ + featureId: "test-http-feature", + needs: ["http"] as const, + createInput() { + return Object.freeze({ + featureId: "test-http-feature" as const, + input: Object.freeze({ + async ping() { + return "pong" as const; + }, + }), + }); + }, + }); + +function localDraftRepository() { + let stored: Readonly<{ value: LocalDraft; revision: number }> | null = null; + const repository = Object.freeze({ + async compareAndSwap(input: Readonly<{ value: LocalDraft }>) { + stored = Object.freeze({ value: input.value, revision: 1 }); + return Object.freeze({ + ok: true as const, + value: Object.freeze({ revision: 1 }), + }); + }, + async read() { + return Object.freeze({ ok: true as const, value: stored }); + }, + async remove() { + stored = null; + return Object.freeze({ + ok: true as const, + value: Object.freeze({ revision: 2 }), + }); + }, + }) as unknown as IndexedDbRepositoryPort; + return repository; +} + +describe("feature adapter composition", () => { + it("composes HTTP-only and IndexedDB-only concrete contributions together", async () => { + const repository = localDraftRepository(); + const get = ((repositoryId: string) => { + expect(repositoryId).toBe("local-draft"); + return repository; + }) as unknown as IndexedDbRepositoryProvider["get"]; + + const indexedDb = Object.freeze({ get }) satisfies IndexedDbRepositoryProvider; + const http = Object.freeze({ + execute: async () => { + throw new Error("HTTP should not execute during composition"); + }, + }) as unknown as InstalledHttpOperationExecutor; + + const inputs = composeFeatureAdapterInputs( + Object.freeze([ + TEST_HTTP_FEATURE_ADAPTER_CONTRIBUTION, + LOCAL_DRAFT_FEATURE_ADAPTER_CONTRIBUTION, + ] as const), + Object.freeze(["test-http-feature", "local-draft"]), + Object.freeze({ http, indexedDb }), + ); + + expect(Object.keys(inputs).sort()).toEqual([ + "local-draft", + "test-http-feature", + ]); + + await expect(inputs["test-http-feature"]?.ping()).resolves.toBe("pong"); + + const localDraft = inputs["local-draft"]; + if (!localDraft) throw new Error("local-draft input was not composed"); + + const draft = Object.freeze({ + draftId: "draft-1", + title: "Local draft", + body: "Body", + }); + + await expect( + localDraft.saveDraft({ + draft, + expectedRevision: null, + idempotencyKey: "save-draft-1", + }), + ).resolves.toEqual({ ok: true, value: { revision: 1 } }); + + await expect(localDraft.findDraft("draft-1")).resolves.toEqual({ + ok: true, + value: { draft, revision: 1 }, + }); + }); +}); diff --git a/tests/contract/reusable-capability/feature-http-binding.test.ts b/tests/contract/reusable-capability/feature-http-binding.test.ts new file mode 100644 index 0000000..271e090 --- /dev/null +++ b/tests/contract/reusable-capability/feature-http-binding.test.ts @@ -0,0 +1,216 @@ +import { describe, expect, it, vi } from "vitest"; + +import { + createFeatureHttpBinding, + defineFeatureHttpOperation, + type HttpExecutionOutcome, + type InstalledHttpOperationExecutor, +} from "../../../src/adapters/http/index.ts"; +import { + mappingFailure, + mappingSuccess, +} from "../../../src/contracts/boundary-mapper.ts"; +import type { + InstalledHttpContract, + RuntimeValidator, +} from "../../../src/contracts/external-contract-runtime.ts"; + +type ResourceInput = Readonly<{ resourceId: string }>; +type ResourceWire = Readonly<{ id: string; title: string }>; +type ResourceProblem = Readonly<{ code?: string }>; +type Resource = Readonly<{ id: string; title: string }>; + +function validator(schemaId: string): RuntimeValidator { + return Object.freeze({ + schemaId, + safeParse(value: unknown) { + return Object.freeze({ + success: true as const, + data: value as T, + }); + }, + }); +} + +const LOAD_RESOURCE_CONTRACT = Object.freeze({ + contract: Object.freeze({ + operationId: "LOAD_RESOURCE", + method: "GET" as const, + pathTemplate: "/resources/{resourceId}", + inputValidator: validator("ResourceInput"), + outputValidator: validator("ResourceWire"), + problemValidator: validator("ResourceProblem"), + acceptedStatuses: Object.freeze([200]), + emptyBodyStatuses: Object.freeze([]), + retrySemantics: "SAFE" as const, + requestBody: "NONE" as const, + responseBody: "REQUIRED_JSON" as const, + commandRecovery: null, + commandEffect: null, + projectRequest(input: ResourceInput) { + return Object.freeze({ + pathValues: Object.freeze({ resourceId: input.resourceId }), + queryEntries: Object.freeze([]), + body: null, + }); + }, + }), + frontend: Object.freeze({ + policyId: "TEST_LOAD_RESOURCE", + requestByteLimit: 0, + responseByteLimit: 8_192, + totalDeadlineMs: 1_000, + retryBudget: 0 as const, + authProfileId: "TEST", + diagnosticsOperation: "test.load-resource", + }), +}) satisfies InstalledHttpContract; + +const OPERATIONS = Object.freeze({ + LOAD_RESOURCE: defineFeatureHttpOperation({ + contract: LOAD_RESOURCE_CONTRACT, + routeId: "RESOURCE_DETAIL", + mapSuccess(value) { + if (value.title.length === 0) { + return mappingFailure("MAPPING_INVARIANT_REJECTED"); + } + return mappingSuccess( + Object.freeze({ id: value.id, title: value.title }), + ); + }, + mapProblem(problem, metadata) { + if (metadata.status !== 409) return undefined; + return Object.freeze({ + kind: "CONFLICT" as const, + code: problem.code ?? "RESOURCE_CONFLICT", + }); + }, + }), +} as const); + +function scriptedExecutor( + outcome: HttpExecutionOutcome, +) { + const calls: Array< + Readonly<{ + contract: unknown; + input: unknown; + context: unknown; + }> + > = []; + const implementation = async ( + contract: unknown, + input: unknown, + context: unknown, + ) => { + calls.push(Object.freeze({ contract, input, context })); + return outcome; + }; + const execute = vi.fn(implementation) as unknown as + InstalledHttpOperationExecutor["execute"]; + return { + executor: Object.freeze({ execute }) satisfies InstalledHttpOperationExecutor, + calls, + execute, + }; +} + +describe("feature HTTP binding", () => { + it("keeps contract-derived input while platform owns route/context execution", async () => { + const scripted = scriptedExecutor( + Object.freeze({ + kind: "SUCCESS" as const, + value: Object.freeze({ id: "resource-1", title: "Reference" }), + metadata: Object.freeze({ status: 200 }), + effect: "NOT_APPLICABLE" as const, + }), + ); + const binding = createFeatureHttpBinding(scripted.executor, OPERATIONS); + + const result = await binding.execute("LOAD_RESOURCE", { + resourceId: "resource-1", + }); + + expect(result).toEqual({ + ok: true, + value: { id: "resource-1", title: "Reference" }, + }); + expect(scripted.calls).toEqual([ + { + contract: LOAD_RESOURCE_CONTRACT, + input: { resourceId: "resource-1" }, + context: { routeId: "RESOURCE_DETAIL" }, + }, + ]); + }); + + it("normalizes transport failure before it crosses the feature gateway", async () => { + const scripted = scriptedExecutor( + Object.freeze({ + kind: "TRANSPORT_FAILURE" as const, + failure: Object.freeze({ + kind: "TIMEOUT" as const, + retryable: true, + }), + effect: "NOT_STARTED" as const, + }), + ); + const binding = createFeatureHttpBinding(scripted.executor, OPERATIONS); + + const result = await binding.execute("LOAD_RESOURCE", { + resourceId: "resource-1", + }); + + expect(result.ok).toBe(false); + if (result.ok) return; + expect(result.error.kind).toBe("REQUEST_TIMEOUT"); + expect(result.error.operationId).toBe("LOAD_RESOURCE"); + expect(result.error.effect).toBe("NOT_STARTED"); + }); + + it("turns a domain mapper rejection into the shared mapping failure", async () => { + const scripted = scriptedExecutor( + Object.freeze({ + kind: "SUCCESS" as const, + value: Object.freeze({ id: "resource-1", title: "" }), + metadata: Object.freeze({ status: 200 }), + effect: "NOT_APPLICABLE" as const, + }), + ); + const binding = createFeatureHttpBinding(scripted.executor, OPERATIONS); + + const result = await binding.execute("LOAD_RESOURCE", { + resourceId: "resource-1", + }); + + expect(result.ok).toBe(false); + if (result.ok) return; + expect(result.error.kind).toBe("MAPPING_CONTRACT_VIOLATION"); + expect(result.error.code).toBe("MAPPING_INVARIANT_REJECTED"); + }); + + it("lets the feature interpret a typed business problem", async () => { + const scripted = scriptedExecutor( + Object.freeze({ + kind: "PROBLEM" as const, + problem: Object.freeze({ code: "RESOURCE_NAME_EXISTS" }), + metadata: Object.freeze({ status: 409 }), + effect: "NOT_APPLIED" as const, + }), + ); + const binding = createFeatureHttpBinding(scripted.executor, OPERATIONS); + + const result = await binding.execute("LOAD_RESOURCE", { + resourceId: "resource-1", + }); + + expect(result).toMatchObject({ + ok: false, + error: { + kind: "CONFLICT", + code: "RESOURCE_NAME_EXISTS", + httpStatus: 409, + }, + }); + }); +}); diff --git a/tests/features/reference-feature/reference-contract.test.ts b/tests/features/reference-feature/reference-contract.test.ts index a8c6373..3b4d388 100644 --- a/tests/features/reference-feature/reference-contract.test.ts +++ b/tests/features/reference-feature/reference-contract.test.ts @@ -28,7 +28,7 @@ describe("reference feature boundary contracts", () => { effect: "MAYBE_APPLIED" as const, })); const installed = createReferenceFeatureInstalledInput({ - contractOperations: { execute }, + http: { execute }, }); await expect( diff --git a/tests/features/reference-feature/reference-diagnostics.test.ts b/tests/features/reference-feature/reference-diagnostics.test.ts index dcbaebb..4307a40 100644 --- a/tests/features/reference-feature/reference-diagnostics.test.ts +++ b/tests/features/reference-feature/reference-diagnostics.test.ts @@ -1,61 +1,59 @@ import { describe, expect, it, vi } from "vitest"; -import { createHttpClient } from "../../../src/adapters/http/client.ts"; -import { createDemoSessionAdapter } from "../../../src/adapters/auth/external-session-adapter.ts"; -import { - createReferenceHttpGateway, -} from "../../../src/features/reference-feature/adapters/reference-http-gateway.ts"; -import { createReferenceFeatureInput } from "../../../src/features/reference-feature/application/reference-feature-api.ts"; -import { REFERENCE_FEATURE_CONTRACT } from "../../../src/features/reference-feature/contracts/reference-feature-contract.ts"; -import { mapReferenceOperation } from "../../../src/features/reference-feature/contracts/reference-mapper.ts"; -import { - validateReferencePayload, - validateReferenceRequest, -} from "../../../src/features/reference-feature/contracts/reference-schemas.ts"; +import { createContractHttpExecutor } from "../../../src/adapters/http/index.ts"; +import { createHttpObservationProjector } from "../../../src/bootstrap/runtime-adapters.ts"; +import { createReferenceFeatureInstalledInput } from "../../../src/features/reference-feature/adapters/create-reference-feature-input.ts"; -describe("reference feature diagnostics correlation", () => { - it("preserves route, operation and request correlation through the vertical path", async () => { +function scopeSnapshot() { + return Object.freeze({ + generation: 1, + fingerprint: "reference-scope", + identities: Object.freeze({}) as never, + signal: new AbortController().signal, + isCurrent: () => true, + }); +} + +describe("reference feature HTTP diagnostics", () => { + it("preserves route and operation identity through the installed V3 path", async () => { const record = vi.fn(); - const operations = - REFERENCE_FEATURE_CONTRACT.apiOperations as Readonly< - Record< - string, - ReturnType< - NonNullable[0]["getOperation"]> - > - > - >; - const client = createHttpClient({ + const contractHttp = createContractHttpExecutor({ baseUrl: "https://api.test", - authSession: createDemoSessionAdapter("authenticated"), - fetcher: async () => - Response.json({ - success: true, - data: [{ id: "reference-1", name: "Reference" }], - meta: { requestId: "safe-request", traceId: "safe-trace" }, - }), - getOperation(operationId) { - const operation = operations[operationId]; - if (!operation) throw new Error("Unregistered reference operation"); - return operation; - }, - validatePayload: validateReferencePayload, - validateRequest: validateReferenceRequest, - mapPayload: mapReferenceOperation, - correlationIdFactory: () => "reference-correlation", - diagnostics: { record }, - scheduler: { - setTimeout: () => 1, - clearTimeout: () => {}, - }, + maxRetryAttempts: 0, + attachCredentials: () => ({ + kind: "READY" as const, + headers: { authorization: "Bearer diagnostics-test-token" }, + }), + fetcher: (async () => + Response.json([ + { id: "reference-1", name: "Reference" }, + ])) as unknown as typeof fetch, + observe: createHttpObservationProjector({ + diagnostics: { record }, + telemetry: { emit: vi.fn() }, + }), + }); + const installed = createReferenceFeatureInstalledInput({ + http: Object.freeze({ + async execute(operation, input, context) { + return contractHttp.execute(operation, input, { + routeId: context.routeId, + scope: scopeSnapshot(), + ...(context.signal === undefined + ? {} + : { signal: context.signal }), + ...(context.intent === undefined + ? {} + : { intent: context.intent }), + }); + }, + }), }); - const application = createReferenceFeatureInput( - createReferenceHttpGateway(client), - ); await expect( - application.listResources({ limit: 20 }), + installed.input.listResources({ limit: 20 }), ).resolves.toMatchObject({ ok: true }); + expect(record).toHaveBeenCalledOnce(); expect(record).toHaveBeenCalledWith({ level: "info", @@ -63,8 +61,7 @@ describe("reference feature diagnostics correlation", () => { context: expect.objectContaining({ route_id: "REFERENCE_RESOURCE_LIST", operation_id: "LIST_REFERENCE_RESOURCES", - correlation_id: "reference-correlation", - outcome: "success", + outcome: "SUCCESS", }), }); }); diff --git a/tests/features/reference-feature/reference-http-gateway.test.ts b/tests/features/reference-feature/reference-http-gateway.test.ts index 2146b22..77b46f8 100644 --- a/tests/features/reference-feature/reference-http-gateway.test.ts +++ b/tests/features/reference-feature/reference-http-gateway.test.ts @@ -1,9 +1,10 @@ -import { describe, expect, it, vi } from "vitest"; +import { describe, expect, it } from "vitest"; -import { createFailure } from "../../../src/contracts/errors.ts"; +import type { Result } from "../../../src/contracts/result.ts"; +import { createFailure, type ApiFailure } from "../../../src/contracts/errors.ts"; import { createReferenceHttpGateway, - type RawReferenceHttpExecutor, + type ReferenceHttpBinding, } from "../../../src/features/reference-feature/adapters/reference-http-gateway.ts"; import type { ReferenceResource } from "../../../src/features/reference-feature/domain/reference-resource.ts"; @@ -20,14 +21,42 @@ const resources = Object.freeze({ }), }) satisfies Readonly>; +type ScriptedResult = Result< + ReferenceResource | readonly ReferenceResource[], + ApiFailure +>; + +function scriptedBinding(results: ScriptedResult[]) { + const calls: Array< + readonly [operationId: string, input: unknown, context: unknown] + > = []; + let index = 0; + const execute = (async ( + operationId: string, + input: unknown, + context?: unknown, + ) => { + calls.push([operationId, input, context]); + const result = results[index]; + index += 1; + if (!result) throw new Error("Missing scripted result"); + return result; + }) as ReferenceHttpBinding["execute"]; + + return { + binding: Object.freeze({ execute }) satisfies ReferenceHttpBinding, + calls, + }; +} + describe("reference HTTP operation gateway", () => { - it("builds the exact registered request for every gateway operation", async () => { - const execute = vi - .fn() - .mockResolvedValueOnce({ ok: true, value: [resources.first] }) - .mockResolvedValueOnce({ ok: true, value: resources.created }) - .mockResolvedValueOnce({ ok: true, value: resources.first }); - const gateway = createReferenceHttpGateway({ execute }); + it("delegates exact typed feature inputs to the capability binding", async () => { + const scripted = scriptedBinding([ + { ok: true, value: [resources.first] }, + { ok: true, value: resources.created }, + { ok: true, value: resources.first }, + ]); + const gateway = createReferenceHttpGateway(scripted.binding); const signal = new AbortController().signal; await expect( @@ -40,67 +69,37 @@ describe("reference HTTP operation gateway", () => { gateway.get("reference-1", { signal }), ).resolves.toEqual({ ok: true, value: resources.first }); - expect(execute.mock.calls).toEqual([ + expect(scripted.calls).toEqual([ [ - { - operationId: "LIST_REFERENCE_RESOURCES", - routeId: "REFERENCE_RESOURCE_LIST", - searchParams: { - cursor: "next", - limit: 20, - tags: ["active"], - }, - signal, - }, + "LIST_REFERENCE_RESOURCES", + { cursor: "next", limit: 20, tags: ["active"] }, + { signal }, ], [ - { - operationId: "CREATE_REFERENCE_RESOURCE", - routeId: "REFERENCE_RESOURCE_LIST", - body: { name: "Created", note: "safe note" }, - }, + "CREATE_REFERENCE_RESOURCE", + { name: "Created", note: "safe note" }, + undefined, ], [ - { - operationId: "GET_REFERENCE_RESOURCE", - routeId: "REFERENCE_RESOURCE_DETAIL", - pathParams: { resourceId: "reference-1" }, - signal, - }, + "GET_REFERENCE_RESOURCE", + { resourceId: "reference-1" }, + { signal }, ], ]); }); - it("preserves a validated raw failure without casting it into success", async () => { + it("preserves a capability-normalized failure across the feature gateway", async () => { const failure = createFailure( "SCHEMA_MISMATCH", "GET_REFERENCE_RESOURCE", 0, ); - const execute = vi - .fn() - .mockResolvedValue({ ok: false, error: failure }); - const gateway = createReferenceHttpGateway({ execute }); + const scripted = scriptedBinding([{ ok: false, error: failure }]); + const gateway = createReferenceHttpGateway(scripted.binding); await expect(gateway.get("invalid")).resolves.toEqual({ ok: false, error: failure, }); }); - - it("fails closed when a raw success does not match its operation result", async () => { - const execute = vi - .fn() - .mockResolvedValue({ ok: true, value: { id: "not-a-list" } }); - const gateway = createReferenceHttpGateway({ execute }); - - await expect(gateway.list({ limit: 20 })).resolves.toMatchObject({ - ok: false, - error: { - kind: "MAPPING_CONTRACT_VIOLATION", - code: "BOUND_RESULT_TYPE_MISMATCH", - operationId: "LIST_REFERENCE_RESOURCES", - }, - }); - }); }); diff --git a/tests/features/reference-feature/reference-http-problem-mapping.test.ts b/tests/features/reference-feature/reference-http-problem-mapping.test.ts new file mode 100644 index 0000000..a42506f --- /dev/null +++ b/tests/features/reference-feature/reference-http-problem-mapping.test.ts @@ -0,0 +1,135 @@ +import { describe, expect, it } from "vitest"; + +import { + createFeatureHttpBinding, + type InstalledHttpOperationExecutor, +} from "../../../src/adapters/http/index.ts"; +import { + createReferenceHttpGateway, + REFERENCE_HTTP_OPERATIONS, +} from "../../../src/features/reference-feature/adapters/reference-http-gateway.ts"; + +function executorReturning( + outcome: Readonly>, +): InstalledHttpOperationExecutor { + const execute = (async () => outcome) as unknown as + InstalledHttpOperationExecutor["execute"]; + return Object.freeze({ execute }); +} + +describe("reference HTTP business problem mapping", () => { + it("maps a typed 409 reference problem to the feature-owned business code", async () => { + const executor = executorReturning( + Object.freeze({ + kind: "PROBLEM", + problem: Object.freeze({ + type: "https://example.test/problems/reference-conflict", + title: "Reference conflict", + status: 409, + code: "REFERENCE_NAME_ALREADY_EXISTS", + }), + metadata: Object.freeze({ status: 409 }), + effect: "NOT_APPLIED", + }), + ); + const gateway = createReferenceHttpGateway( + createFeatureHttpBinding(executor, REFERENCE_HTTP_OPERATIONS), + ); + + await expect( + gateway.create({ name: "duplicate" }), + ).resolves.toMatchObject({ + ok: false, + error: { + kind: "CONFLICT", + code: "REFERENCE_NAME_ALREADY_EXISTS", + httpStatus: 409, + }, + }); + }); + + it.each([ + { + status: 409, + code: undefined, + expectedKind: "CONFLICT", + expectedCode: "REFERENCE_RESOURCE_CONFLICT", + }, + { + status: 422, + code: "REFERENCE_NAME_REJECTED", + expectedKind: "VALIDATION_REJECTED", + expectedCode: "REFERENCE_NAME_REJECTED", + }, + { + status: 422, + code: undefined, + expectedKind: "VALIDATION_REJECTED", + expectedCode: "REFERENCE_RESOURCE_REJECTED", + }, + { + status: 400, + code: "REFERENCE_BAD_REQUEST", + expectedKind: "UNKNOWN_CLIENT_FAILURE", + expectedCode: "CONTRACT_PROBLEM", + }, + ] as const)( + "projects create problem status $status through the feature-owned mapper/fallback", + async ({ status, code, expectedKind, expectedCode }) => { + const executor = executorReturning( + Object.freeze({ + kind: "PROBLEM", + problem: Object.freeze({ + type: "https://example.test/problems/reference-" + status, + title: "Reference request rejected", + status, + ...(code === undefined ? {} : { code }), + }), + metadata: Object.freeze({ status }), + effect: "NOT_APPLIED", + }), + ); + const gateway = createReferenceHttpGateway( + createFeatureHttpBinding(executor, REFERENCE_HTTP_OPERATIONS), + ); + + await expect( + gateway.create({ name: "rejected" }), + ).resolves.toMatchObject({ + ok: false, + error: { + kind: expectedKind, + code: expectedCode, + httpStatus: status, + }, + }); + }, + ); + + it("keeps the platform status fallback when the operation has no problem mapper", async () => { + const executor = executorReturning( + Object.freeze({ + kind: "PROBLEM", + problem: Object.freeze({ + type: "https://example.test/problems/not-found", + title: "Not found", + status: 404, + }), + metadata: Object.freeze({ status: 404 }), + effect: "NOT_APPLIED", + }), + ); + const gateway = createReferenceHttpGateway( + createFeatureHttpBinding(executor, REFERENCE_HTTP_OPERATIONS), + ); + + await expect(gateway.get("missing")).resolves.toMatchObject({ + ok: false, + error: { + kind: "NOT_FOUND", + code: "CONTRACT_PROBLEM", + httpStatus: 404, + }, + }); + }); +}); diff --git a/tests/features/reference-feature/reference-installed-executor.test.ts b/tests/features/reference-feature/reference-installed-executor.test.ts index f93ced8..fc19ee8 100644 --- a/tests/features/reference-feature/reference-installed-executor.test.ts +++ b/tests/features/reference-feature/reference-installed-executor.test.ts @@ -1,5 +1,8 @@ import { describe, expect, it } from "vitest"; +import { + type InstalledHttpOperationExecutor, +} from "../../../src/adapters/http/index.ts"; import { createReferenceFeatureInstalledInput } from "../../../src/features/reference-feature/adapters/create-reference-feature-input.ts"; /** @@ -14,22 +17,31 @@ import { createReferenceFeatureInstalledInput } from "../../../src/features/refe describe("reference feature installed operation executor", () => { it("preserves the feature route id through the installed operation executor", async () => { const seen: Array>> = []; + const implementation = async ( + contract: Readonly<{ contract: Readonly<{ operationId: string }> }>, + _input: unknown, + context: Readonly>, + ) => { + seen.push(Object.freeze({ ...context })); + const value = + contract.contract.operationId === "LIST_REFERENCE_RESOURCES" + ? [] + : { + id: "resource-1", + name: "Resource", + }; + return Object.freeze({ + kind: "SUCCESS" as const, + value, + metadata: Object.freeze({ status: 200 }), + effect: "NOT_APPLICABLE" as const, + }); + }; + const execute = implementation as unknown as + InstalledHttpOperationExecutor["execute"]; + const installed = createReferenceFeatureInstalledInput({ - contractOperations: Object.freeze({ - async execute( - _operationId: string, - _input: unknown, - context?: Readonly>, - ) { - seen.push(Object.freeze({ ...(context ?? {}) })); - return Object.freeze({ - kind: "SUCCESS" as const, - value: [], - metadata: Object.freeze({ status: 200 }), - effect: "NOT_APPLICABLE" as const, - }); - }, - }), + http: Object.freeze({ execute }), }); await installed.input.listResources({ limit: 20 }); diff --git a/tests/features/tech-log/runtime-composition.test.ts b/tests/features/tech-log/runtime-composition.test.ts index 61d1b89..5c853fa 100644 --- a/tests/features/tech-log/runtime-composition.test.ts +++ b/tests/features/tech-log/runtime-composition.test.ts @@ -15,14 +15,37 @@ type Equal = : false; type Expect = Value; +type RequiredKeys = { + [Key in keyof Value]-?: Record extends Pick + ? never + : Key; +}[keyof Value]; + type InstalledInputs = ReturnType; -type _InstalledIdsAreExact = Expect< - Equal + +/** + * Template sync (ebea300). The composed map became + * `Partial` upstream, and the template's new + * local-draft demonstration feature declares a third key, so `keyof` no longer + * says which features a build installs — every declared feature is a key, + * present or not. What this product needs held is the split itself: TechLog is + * its own domain and is always composed, and a manifest-governed feature stays + * optional because a build may narrow it out. + */ +type _TechLogIsAlwaysInstalled = Expect< + Equal, "tech-log"> +>; +type _ReferenceFeatureStaysOptional = Expect< + Equal< + "reference-feature" extends RequiredKeys ? true : false, + false + > >; type _TechLogRegistryValueIsExact = Expect< Equal >; -void (0 as unknown as _InstalledIdsAreExact); +void (0 as unknown as _TechLogIsAlwaysInstalled); +void (0 as unknown as _ReferenceFeatureStaysOptional); void (0 as unknown as _TechLogRegistryValueIsExact); function inputOf(document: WorkingCopy) { @@ -40,6 +63,14 @@ function installedInputs( return createInstalledFeatureInputs({ studioSource, publicSource, + // Template sync (ebea300). The platform capability the manifest-governed + // contributions declare in `needs`. Composition builds the reference + // feature's gateway from it and never calls it here. + http: { + async execute() { + throw new Error("platform executor is not used by composition tests"); + }, + }, contractOperations: { async execute() { throw new Error("reference executor is not used by composition tests"); diff --git a/tests/fixtures/architecture/dependency-graph/barrel/adapters/http/client.ts b/tests/fixtures/architecture/dependency-graph/barrel/adapters/http/client.ts new file mode 100644 index 0000000..3a414bb --- /dev/null +++ b/tests/fixtures/architecture/dependency-graph/barrel/adapters/http/client.ts @@ -0,0 +1,3 @@ +export function createFixtureHttpClient(): string { + return "fixture"; +} diff --git a/tests/fixtures/architecture/dependency-graph/barrel/adapters/http/index.ts b/tests/fixtures/architecture/dependency-graph/barrel/adapters/http/index.ts new file mode 100644 index 0000000..1ca20a3 --- /dev/null +++ b/tests/fixtures/architecture/dependency-graph/barrel/adapters/http/index.ts @@ -0,0 +1 @@ +export { createFixtureHttpClient } from "./client.ts"; diff --git a/tests/fixtures/architecture/dependency-graph/barrel/bootstrap/compose-barrel.ts b/tests/fixtures/architecture/dependency-graph/barrel/bootstrap/compose-barrel.ts new file mode 100644 index 0000000..29f769d --- /dev/null +++ b/tests/fixtures/architecture/dependency-graph/barrel/bootstrap/compose-barrel.ts @@ -0,0 +1,3 @@ +import { createFixtureHttpClient } from "../adapters/http/index.ts"; + +export const barrelComposition = createFixtureHttpClient; diff --git a/tests/fixtures/architecture/dependency-graph/barrel/bootstrap/compose-deep.ts b/tests/fixtures/architecture/dependency-graph/barrel/bootstrap/compose-deep.ts new file mode 100644 index 0000000..590199c --- /dev/null +++ b/tests/fixtures/architecture/dependency-graph/barrel/bootstrap/compose-deep.ts @@ -0,0 +1,3 @@ +import { createFixtureHttpClient } from "../adapters/http/client.ts"; + +export const deepComposition = createFixtureHttpClient; diff --git a/tests/fixtures/coverage/repository-omission.json b/tests/fixtures/coverage/repository-omission.json index dde669d..ba04a72 100644 --- a/tests/fixtures/coverage/repository-omission.json +++ b/tests/fixtures/coverage/repository-omission.json @@ -35,7 +35,7 @@ "src/application/create-application.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/application/policies/compatibility.ts": { + "src/contracts/compatibility.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/application/policies/performance-budgets.ts": { diff --git a/tests/fixtures/typecheck/invalid-direct-feature-composition.ts b/tests/fixtures/typecheck/invalid-direct-feature-composition.ts new file mode 100644 index 0000000..48a5d61 --- /dev/null +++ b/tests/fixtures/typecheck/invalid-direct-feature-composition.ts @@ -0,0 +1,33 @@ +import type { InstalledHttpOperationExecutor } from "../../../src/adapters/http/index.ts"; +import { composeFeatureAdapterInputs } from "../../../src/features/feature-adapter-contribution.ts"; + +declare module "../../../src/application/ports/in/application-api.ts" { + interface ApplicationFeatureInputs { + "direct-compose-probe": Readonly<{ + ping(): "pong"; + }>; + } +} + +const malformedRawContribution = Object.freeze({ + featureId: "direct-compose-probe" as const, + needs: ["http"] as const, + createInput() { + return Object.freeze({ + featureId: "direct-compose-probe" as const, + input: Object.freeze({ + ping() { + return "pong" as const; + }, + }), + }); + }, +}); + +composeFeatureAdapterInputs( + Object.freeze([malformedRawContribution] as const), + Object.freeze(["direct-compose-probe"]), + Object.freeze({ + http: null as unknown as InstalledHttpOperationExecutor, + }), +); diff --git a/tests/fixtures/typecheck/invalid-feature-capability-selection.ts b/tests/fixtures/typecheck/invalid-feature-capability-selection.ts new file mode 100644 index 0000000..eba2be6 --- /dev/null +++ b/tests/fixtures/typecheck/invalid-feature-capability-selection.ts @@ -0,0 +1,13 @@ +import { defineFeatureAdapterContribution } from "../../../src/features/feature-adapter-contribution.ts"; +import { createReferenceFeatureInstalledInput } from "../../../src/features/reference-feature/adapters/create-reference-feature-input.ts"; + +defineFeatureAdapterContribution({ + featureId: "reference-feature", + needs: ["http"] as const, + createInput(context) { + context.indexedDb; + return createReferenceFeatureInstalledInput({ + http: context.http, + }); + }, +}); diff --git a/tests/fixtures/typecheck/invalid-feature-contribution-input.ts b/tests/fixtures/typecheck/invalid-feature-contribution-input.ts new file mode 100644 index 0000000..4046dd1 --- /dev/null +++ b/tests/fixtures/typecheck/invalid-feature-contribution-input.ts @@ -0,0 +1,15 @@ +import { defineFeatureAdapterContribution } from "../../../src/features/feature-adapter-contribution.ts"; +import type {} from "../../../src/features/reference-feature/application/reference-feature-api.ts"; + +defineFeatureAdapterContribution({ + featureId: "reference-feature", + needs: ["http"] as const, + createInput() { + return { + featureId: "reference-feature" as const, + input: { + definitelyNotReferenceFeatureInput: true, + }, + }; + }, +}); diff --git a/tests/fixtures/typecheck/invalid-http-operation-id.ts b/tests/fixtures/typecheck/invalid-http-operation-id.ts new file mode 100644 index 0000000..e41068c --- /dev/null +++ b/tests/fixtures/typecheck/invalid-http-operation-id.ts @@ -0,0 +1,19 @@ +import { + createFeatureHttpBinding, + defineFeatureHttpOperation, + type InstalledHttpOperationExecutor, +} from "../../../src/adapters/http/index.ts"; +import { GET_REFERENCE_RESOURCE_CONTRACT } from "../../../src/features/reference-feature/contracts/reference-feature-contract-contribution.ts"; +import { mapReferenceResourcePayload } from "../../../src/features/reference-feature/contracts/reference-mapper.ts"; + +declare const executor: InstalledHttpOperationExecutor; + +const operations = Object.freeze({ + TOTALLY_WRONG_OPERATION_ID: defineFeatureHttpOperation({ + contract: GET_REFERENCE_RESOURCE_CONTRACT, + routeId: "REFERENCE_RESOURCE_DETAIL", + mapSuccess: mapReferenceResourcePayload, + }), +}); + +createFeatureHttpBinding(executor, operations); diff --git a/tests/fixtures/typecheck/invalid-http-operation-input.ts b/tests/fixtures/typecheck/invalid-http-operation-input.ts new file mode 100644 index 0000000..3d58e6b --- /dev/null +++ b/tests/fixtures/typecheck/invalid-http-operation-input.ts @@ -0,0 +1,7 @@ +import type { ReferenceHttpBinding } from "../../../src/features/reference-feature/adapters/reference-http-gateway.ts"; + +declare const http: ReferenceHttpBinding; + +http.execute("GET_REFERENCE_RESOURCE", { + name: "wrong-command-for-get", +}); diff --git a/tests/fixtures/typecheck/invalid-http-route-id.ts b/tests/fixtures/typecheck/invalid-http-route-id.ts new file mode 100644 index 0000000..20a9c96 --- /dev/null +++ b/tests/fixtures/typecheck/invalid-http-route-id.ts @@ -0,0 +1,15 @@ +import { defineFeatureHttpOperationForRoutes } from "../../../src/adapters/http/index.ts"; +import { + type ReferenceFeatureRouteId, +} from "../../../src/features/reference-feature/adapters/reference-http-gateway.ts"; +import { GET_REFERENCE_RESOURCE_CONTRACT } from "../../../src/features/reference-feature/contracts/reference-feature-contract-contribution.ts"; +import { mapReferenceResourcePayload } from "../../../src/features/reference-feature/contracts/reference-mapper.ts"; + +const defineReferenceOperation = + defineFeatureHttpOperationForRoutes(); + +defineReferenceOperation({ + contract: GET_REFERENCE_RESOURCE_CONTRACT, + routeId: "TOTALLY_WRONG_ROUTE", + mapSuccess: mapReferenceResourcePayload, +}); diff --git a/tests/fixtures/typecheck/invalid-http-wire-mapper.ts b/tests/fixtures/typecheck/invalid-http-wire-mapper.ts new file mode 100644 index 0000000..6e8b845 --- /dev/null +++ b/tests/fixtures/typecheck/invalid-http-wire-mapper.ts @@ -0,0 +1,13 @@ +import { defineFeatureHttpOperation } from "../../../src/adapters/http/index.ts"; +import { GET_REFERENCE_RESOURCE_CONTRACT } from "../../../src/features/reference-feature/contracts/reference-feature-contract-contribution.ts"; + +defineFeatureHttpOperation({ + contract: GET_REFERENCE_RESOURCE_CONTRACT, + routeId: "REFERENCE_RESOURCE_DETAIL", + mapSuccess(value: Readonly<{ unrelatedWireField: number }>) { + return { + ok: true as const, + value, + }; + }, +}); diff --git a/tests/fixtures/typecheck/invalid-reference-operation.ts b/tests/fixtures/typecheck/invalid-reference-operation.ts index 8ad79da..cbc174d 100644 --- a/tests/fixtures/typecheck/invalid-reference-operation.ts +++ b/tests/fixtures/typecheck/invalid-reference-operation.ts @@ -1,9 +1,8 @@ -import type { RawReferenceHttpExecutor } from "../../../src/features/reference-feature/adapters/reference-http-gateway.ts"; +import type { ReferenceHttpBinding } from "../../../src/features/reference-feature/adapters/reference-http-gateway.ts"; -declare const http: RawReferenceHttpExecutor; +declare const http: ReferenceHttpBinding; -http.execute({ - operationId: "GET_REFERENCE_RESOURCE", - routeId: "REFERENCE_RESOURCE_LIST", - pathParams: { resourceId: "resource-1" }, -}); +const listInput = { limit: 20 }; + +// GET is bound to { resourceId: string }; list input must be rejected. +http.execute("GET_REFERENCE_RESOURCE", listInput); diff --git a/tests/fixtures/typecheck/invalid-result-narrowing.ts b/tests/fixtures/typecheck/invalid-result-narrowing.ts index 5e18fa9..5821540 100644 --- a/tests/fixtures/typecheck/invalid-result-narrowing.ts +++ b/tests/fixtures/typecheck/invalid-result-narrowing.ts @@ -1,4 +1,4 @@ -import type { Result } from "../../../src/application/result.ts"; +import type { Result } from "../../../src/contracts/result.ts"; export function invalidUnwrap(result: Result): number { return result.value; diff --git a/tests/fixtures/typecheck/tsconfig.application-input.json b/tests/fixtures/typecheck/tsconfig.application-input.json new file mode 100644 index 0000000..481901f --- /dev/null +++ b/tests/fixtures/typecheck/tsconfig.application-input.json @@ -0,0 +1,6 @@ +{ + "extends": "./tsconfig.base.json", + "files": [ + "./invalid-application-input.ts" + ] +} diff --git a/tests/fixtures/typecheck/tsconfig.application-output.json b/tests/fixtures/typecheck/tsconfig.application-output.json new file mode 100644 index 0000000..14ed9ff --- /dev/null +++ b/tests/fixtures/typecheck/tsconfig.application-output.json @@ -0,0 +1,6 @@ +{ + "extends": "./tsconfig.base.json", + "files": [ + "./invalid-application-output.ts" + ] +} diff --git a/tests/fixtures/typecheck/tsconfig.async-overlay.json b/tests/fixtures/typecheck/tsconfig.async-overlay.json new file mode 100644 index 0000000..ae1dc4a --- /dev/null +++ b/tests/fixtures/typecheck/tsconfig.async-overlay.json @@ -0,0 +1,6 @@ +{ + "extends": "./tsconfig.base.json", + "files": [ + "./invalid-async-overlay.ts" + ] +} diff --git a/tests/fixtures/typecheck/tsconfig.base.json b/tests/fixtures/typecheck/tsconfig.base.json new file mode 100644 index 0000000..377483a --- /dev/null +++ b/tests/fixtures/typecheck/tsconfig.base.json @@ -0,0 +1,15 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "lib": [ + "ES2022", + "DOM", + "DOM.Iterable" + ], + "types": [ + "node", + "vite/client" + ], + "isolatedModules": false + } +} diff --git a/tests/fixtures/typecheck/tsconfig.diagnostics-port.json b/tests/fixtures/typecheck/tsconfig.diagnostics-port.json new file mode 100644 index 0000000..e36df82 --- /dev/null +++ b/tests/fixtures/typecheck/tsconfig.diagnostics-port.json @@ -0,0 +1,6 @@ +{ + "extends": "./tsconfig.base.json", + "files": [ + "./invalid-diagnostics-port.ts" + ] +} diff --git a/tests/fixtures/typecheck/tsconfig.direct-feature-composition.json b/tests/fixtures/typecheck/tsconfig.direct-feature-composition.json new file mode 100644 index 0000000..81e5953 --- /dev/null +++ b/tests/fixtures/typecheck/tsconfig.direct-feature-composition.json @@ -0,0 +1,6 @@ +{ + "extends": "./tsconfig.base.json", + "files": [ + "./invalid-direct-feature-composition.ts" + ] +} diff --git a/tests/fixtures/typecheck/tsconfig.failure-kind.json b/tests/fixtures/typecheck/tsconfig.failure-kind.json new file mode 100644 index 0000000..713e73f --- /dev/null +++ b/tests/fixtures/typecheck/tsconfig.failure-kind.json @@ -0,0 +1,6 @@ +{ + "extends": "./tsconfig.base.json", + "files": [ + "./invalid-failure-kind.ts" + ] +} diff --git a/tests/fixtures/typecheck/tsconfig.feature-capability-selection.json b/tests/fixtures/typecheck/tsconfig.feature-capability-selection.json new file mode 100644 index 0000000..a2fdc2c --- /dev/null +++ b/tests/fixtures/typecheck/tsconfig.feature-capability-selection.json @@ -0,0 +1,6 @@ +{ + "extends": "./tsconfig.base.json", + "files": [ + "./invalid-feature-capability-selection.ts" + ] +} diff --git a/tests/fixtures/typecheck/tsconfig.feature-contribution-input.json b/tests/fixtures/typecheck/tsconfig.feature-contribution-input.json new file mode 100644 index 0000000..287af83 --- /dev/null +++ b/tests/fixtures/typecheck/tsconfig.feature-contribution-input.json @@ -0,0 +1,6 @@ +{ + "extends": "./tsconfig.base.json", + "files": [ + "./invalid-feature-contribution-input.ts" + ] +} diff --git a/tests/fixtures/typecheck/tsconfig.feature-input.json b/tests/fixtures/typecheck/tsconfig.feature-input.json new file mode 100644 index 0000000..ce3ac52 --- /dev/null +++ b/tests/fixtures/typecheck/tsconfig.feature-input.json @@ -0,0 +1,6 @@ +{ + "extends": "./tsconfig.base.json", + "files": [ + "./invalid-feature-input.ts" + ] +} diff --git a/tests/fixtures/typecheck/tsconfig.http-operation-id.json b/tests/fixtures/typecheck/tsconfig.http-operation-id.json new file mode 100644 index 0000000..9808303 --- /dev/null +++ b/tests/fixtures/typecheck/tsconfig.http-operation-id.json @@ -0,0 +1,6 @@ +{ + "extends": "./tsconfig.base.json", + "files": [ + "./invalid-http-operation-id.ts" + ] +} diff --git a/tests/fixtures/typecheck/tsconfig.http-operation-input.json b/tests/fixtures/typecheck/tsconfig.http-operation-input.json new file mode 100644 index 0000000..5c1b229 --- /dev/null +++ b/tests/fixtures/typecheck/tsconfig.http-operation-input.json @@ -0,0 +1,6 @@ +{ + "extends": "./tsconfig.base.json", + "files": [ + "./invalid-http-operation-input.ts" + ] +} diff --git a/tests/fixtures/typecheck/tsconfig.http-route-id.json b/tests/fixtures/typecheck/tsconfig.http-route-id.json new file mode 100644 index 0000000..c37d1f7 --- /dev/null +++ b/tests/fixtures/typecheck/tsconfig.http-route-id.json @@ -0,0 +1,6 @@ +{ + "extends": "./tsconfig.base.json", + "files": [ + "./invalid-http-route-id.ts" + ] +} diff --git a/tests/fixtures/typecheck/tsconfig.http-wire-mapper.json b/tests/fixtures/typecheck/tsconfig.http-wire-mapper.json new file mode 100644 index 0000000..b6bc81c --- /dev/null +++ b/tests/fixtures/typecheck/tsconfig.http-wire-mapper.json @@ -0,0 +1,6 @@ +{ + "extends": "./tsconfig.base.json", + "files": [ + "./invalid-http-wire-mapper.ts" + ] +} diff --git a/tests/fixtures/typecheck/tsconfig.icon-button.json b/tests/fixtures/typecheck/tsconfig.icon-button.json new file mode 100644 index 0000000..3efcca1 --- /dev/null +++ b/tests/fixtures/typecheck/tsconfig.icon-button.json @@ -0,0 +1,6 @@ +{ + "extends": "./tsconfig.base.json", + "files": [ + "./invalid-icon-button.tsx" + ] +} diff --git a/tests/fixtures/typecheck/tsconfig.image-cdn-resolve-signal.json b/tests/fixtures/typecheck/tsconfig.image-cdn-resolve-signal.json new file mode 100644 index 0000000..7fff2d6 --- /dev/null +++ b/tests/fixtures/typecheck/tsconfig.image-cdn-resolve-signal.json @@ -0,0 +1,6 @@ +{ + "extends": "./tsconfig.base.json", + "files": [ + "./invalid-image-cdn-resolve-signal.ts" + ] +} diff --git a/tests/fixtures/typecheck/tsconfig.message-key.json b/tests/fixtures/typecheck/tsconfig.message-key.json new file mode 100644 index 0000000..4e28e22 --- /dev/null +++ b/tests/fixtures/typecheck/tsconfig.message-key.json @@ -0,0 +1,6 @@ +{ + "extends": "./tsconfig.base.json", + "files": [ + "./invalid-message-key.ts" + ] +} diff --git a/tests/fixtures/typecheck/tsconfig.message-params.json b/tests/fixtures/typecheck/tsconfig.message-params.json new file mode 100644 index 0000000..809efc3 --- /dev/null +++ b/tests/fixtures/typecheck/tsconfig.message-params.json @@ -0,0 +1,6 @@ +{ + "extends": "./tsconfig.base.json", + "files": [ + "./invalid-message-params.ts" + ] +} diff --git a/tests/fixtures/typecheck/tsconfig.page-action.json b/tests/fixtures/typecheck/tsconfig.page-action.json new file mode 100644 index 0000000..4a87502 --- /dev/null +++ b/tests/fixtures/typecheck/tsconfig.page-action.json @@ -0,0 +1,6 @@ +{ + "extends": "./tsconfig.base.json", + "files": [ + "./invalid-page-action.tsx" + ] +} diff --git a/tests/fixtures/typecheck/tsconfig.port-call.json b/tests/fixtures/typecheck/tsconfig.port-call.json new file mode 100644 index 0000000..00cd581 --- /dev/null +++ b/tests/fixtures/typecheck/tsconfig.port-call.json @@ -0,0 +1,6 @@ +{ + "extends": "./tsconfig.base.json", + "files": [ + "./invalid-port-call.ts" + ] +} diff --git a/tests/fixtures/typecheck/tsconfig.port-implementation.json b/tests/fixtures/typecheck/tsconfig.port-implementation.json new file mode 100644 index 0000000..5156ee8 --- /dev/null +++ b/tests/fixtures/typecheck/tsconfig.port-implementation.json @@ -0,0 +1,6 @@ +{ + "extends": "./tsconfig.base.json", + "files": [ + "./invalid-port-implementation.ts" + ] +} diff --git a/tests/fixtures/typecheck/tsconfig.reference-operation.json b/tests/fixtures/typecheck/tsconfig.reference-operation.json new file mode 100644 index 0000000..1a26faa --- /dev/null +++ b/tests/fixtures/typecheck/tsconfig.reference-operation.json @@ -0,0 +1,6 @@ +{ + "extends": "./tsconfig.base.json", + "files": [ + "./invalid-reference-operation.ts" + ] +} diff --git a/tests/fixtures/typecheck/tsconfig.result-narrowing.json b/tests/fixtures/typecheck/tsconfig.result-narrowing.json new file mode 100644 index 0000000..2a61c5a --- /dev/null +++ b/tests/fixtures/typecheck/tsconfig.result-narrowing.json @@ -0,0 +1,6 @@ +{ + "extends": "./tsconfig.base.json", + "files": [ + "./invalid-result-narrowing.ts" + ] +} diff --git a/tests/fixtures/typecheck/tsconfig.route-runtime.json b/tests/fixtures/typecheck/tsconfig.route-runtime.json new file mode 100644 index 0000000..0f13ec7 --- /dev/null +++ b/tests/fixtures/typecheck/tsconfig.route-runtime.json @@ -0,0 +1,6 @@ +{ + "extends": "./tsconfig.base.json", + "files": [ + "./invalid-route-runtime.ts" + ] +} diff --git a/tests/helpers/memory-indexeddb.ts b/tests/helpers/memory-indexeddb.ts index b8e6979..50238e7 100644 --- a/tests/helpers/memory-indexeddb.ts +++ b/tests/helpers/memory-indexeddb.ts @@ -146,6 +146,48 @@ function compareKeys(first: IDBValidKey, second: IDBValidKey): number { return String(left) < String(right) ? -1 : 1; } +/** + * A unique index rejects a second row whose index key already belongs to + * another primary key, which is how a browser reports it: a request-level + * `ConstraintError` that then aborts the transaction. + * + * The fake enforced primary keys only, so the one `unique: true` index in the + * repository — `indexeddb-opfs-journal.ts`'s logical-key index, whose store is + * keyed by `transactionId` instead — could never fail here the way it fails in + * a browser. Every other index in `src/adapters` is non-unique, so this check + * is a no-op for them. + */ +function assertUniqueIndexes( + state: StoreState, + key: string, + value: unknown, +): void { + for (const [name, index] of state.indexes) { + if (!index.unique || typeof index.keyPath !== "string") continue; + const indexKey = readPath(value, index.keyPath); + // An absent index key keeps the row out of the index entirely, so it + // cannot collide with anything. + if (indexKey === undefined) continue; + for (const [otherKey, otherValue] of state.data) { + // Replacing a row never collides with the row it replaces. + if (otherKey === key) continue; + const otherIndexKey = readPath(otherValue, index.keyPath); + if (otherIndexKey === undefined) continue; + if ( + compareKeys( + indexKey as IDBValidKey, + otherIndexKey as IDBValidKey, + ) === 0 + ) { + throw new DOMException( + `Unique index ${name} already holds this key.`, + "ConstraintError", + ); + } + } + } +} + class FakeUpgradeTransaction { aborted = false; @@ -483,6 +525,7 @@ class FakeObjectStore { this.assertWritable(); return this.request(() => { const key = primaryKey(this.state, value); + assertUniqueIndexes(this.state, key, value); this.state.data.set(key, structuredClone(value)); return key as IDBValidKey; }); @@ -495,6 +538,7 @@ class FakeObjectStore { if (this.state.data.has(key)) { throw new DOMException("Key already exists.", "ConstraintError"); } + assertUniqueIndexes(this.state, key, value); this.state.data.set(key, structuredClone(value)); return key as IDBValidKey; }); diff --git a/tests/unit/provider-guardian-transaction.test.ts b/tests/integration/provider-guardian-transaction.test.ts similarity index 95% rename from tests/unit/provider-guardian-transaction.test.ts rename to tests/integration/provider-guardian-transaction.test.ts index 427360f..50543de 100644 --- a/tests/unit/provider-guardian-transaction.test.ts +++ b/tests/integration/provider-guardian-transaction.test.ts @@ -25,6 +25,13 @@ import { afterEach, describe, expect, it } from "vitest"; * longer. Raising the global default instead would hide a genuinely hung test. */ const PROCESS_HEAVY_TIMEOUT_MS = 30_000; +/** + * Test watchdog only. This is not a provider protocol deadline. Child-process + * scheduling can be delayed when the repository suite is under load, so the + * watchdog must not encode a one-second protocol requirement that does not + * exist in production. + */ +const PROCESS_HANDSHAKE_WATCHDOG_MS = 5_000; const roots: string[] = []; @@ -216,7 +223,7 @@ describe("provider guardian transaction protocol", () => { })); const ready = decodeProviderGuardianReady( - await within(readyPayload, 1_000, "guardian READY"), + await within(readyPayload, PROCESS_HANDSHAKE_WATCHDOG_MS, "guardian READY"), nonce, ); const raw = await lstat(rawPath); @@ -231,7 +238,7 @@ describe("provider guardian transaction protocol", () => { .toEqual({ dev: ready.sealedDev, ino: ready.sealedIno, mode: 0o600 }); child.stdin!.end(); - await expect(within(completion, 1_000, "guardian abort")).resolves.toEqual({ + await expect(within(completion, PROCESS_HANDSHAKE_WATCHDOG_MS, "guardian abort")).resolves.toEqual({ code: 125, signal: null, }); @@ -254,7 +261,7 @@ describe("provider guardian transaction protocol", () => { if (input) child.stdin!.end(input); else child.stdin!.end(); - await expect(within(completion, 1_000, `${label} guardian EOF`)).resolves.toEqual({ + await expect(within(completion, PROCESS_HANDSHAKE_WATCHDOG_MS, `${label} guardian EOF`)).resolves.toEqual({ code: expectedCode, signal: null, }); @@ -289,7 +296,7 @@ describe("provider guardian transaction protocol", () => { await expect(within( waitForChild(fixture.child), - 1_000, + PROCESS_HANDSHAKE_WATCHDOG_MS, `${boundKind} partial bootstrap exit`, )).resolves.toEqual({ code: 126, signal: null }); const boundPath = boundKind === "raw" ? fixture.rawStagingPath : fixture.sealedTempPath; @@ -320,7 +327,7 @@ describe("provider guardian transaction protocol", () => { deadlineEpochMs: Date.now() + 2_000, })); - await expect(within(completion, 1_000, "guardian parent startup death")) + await expect(within(completion, PROCESS_HANDSHAKE_WATCHDOG_MS, "guardian parent startup death")) .resolves.toEqual({ code: 125, signal: null }); await expect(readdir(path.join(workspace, "provider-evidence/untrusted"))).resolves.toEqual([]); await expect(readdir(path.join(workspace, "provider-evidence"))).resolves.toEqual(["untrusted"]); @@ -348,7 +355,7 @@ describe("provider guardian transaction protocol", () => { deadlineEpochMs: Date.now() + 3_000, })); const ready = decodeProviderGuardianReady( - await within(readyPayload, 1_000, "guardian READY"), + await within(readyPayload, PROCESS_HANDSHAKE_WATCHDOG_MS, "guardian READY"), nonce, ); const sealedTempPath = path.join(evidenceRoot, ready.sealedTempLeaf); @@ -379,7 +386,7 @@ describe("provider guardian transaction protocol", () => { sha256: createHash("sha256").update(bytes).digest("hex"), })); decodeProviderGuardianPublished( - await within(publishedPayload, 1_000, "guardian PUBLISHED"), + await within(publishedPayload, PROCESS_HANDSHAKE_WATCHDOG_MS, "guardian PUBLISHED"), nonce, { dev: ready.sealedDev, ino: ready.sealedIno }, ); @@ -393,7 +400,7 @@ describe("provider guardian transaction protocol", () => { await new Promise((resolve) => setTimeout(resolve, 50)); expect(child.exitCode).toBeNull(); child.stdin!.end(); - await expect(within(completion, 1_000, "guardian commit EOF")).resolves.toEqual({ + await expect(within(completion, PROCESS_HANDSHAKE_WATCHDOG_MS, "guardian commit EOF")).resolves.toEqual({ code: 0, signal: null, }); @@ -456,7 +463,7 @@ describe("provider guardian transaction protocol", () => { const transaction = await establishPublishedGuardian(workspace, Buffer.alloc(32, 0x31)); transaction.child.stdin!.end(); - await expect(within(transaction.completion, 1_000, "published guardian EOF")) + await expect(within(transaction.completion, PROCESS_HANDSHAKE_WATCHDOG_MS, "published guardian EOF")) .resolves.toEqual({ code: 125, signal: null }); await assertTransactionAbsent(transaction); @@ -487,7 +494,7 @@ describe("provider guardian transaction protocol", () => { transaction.child.stdin!.write(Buffer.from([0, 0, 0, 1, 0x7b])); transaction.child.stdin!.end(); - await expect(within(transaction.completion, 1_000, "guardian trailing frame")) + await expect(within(transaction.completion, PROCESS_HANDSHAKE_WATCHDOG_MS, "guardian trailing frame")) .resolves.toEqual({ code: 126, signal: null }); await assertTransactionAbsent(transaction); }); @@ -505,7 +512,7 @@ describe("provider guardian transaction protocol", () => { }); process.kill(lease.pid, "SIGKILL"); - await expect(within(lease.prematureExit, 1_000, "guardian hard death")) + await expect(within(lease.prematureExit, PROCESS_HANDSHAKE_WATCHDOG_MS, "guardian hard death")) .resolves.toEqual(expect.objectContaining({ message: expect.stringMatching(/SIGKILL/u) })); await lease.abort(); await expect(lstat(lease.rawPath)).rejects.toMatchObject({ code: "ENOENT" }); @@ -536,8 +543,8 @@ describe("provider guardian transaction protocol", () => { }); process.kill(guardianPid, "SIGCONT"); - await within(rawLink, 1_000, "pre-READY canonical raw link"); - await expect(within(starting, 2_000, "pre-READY guardian rejection")) + await within(rawLink, PROCESS_HANDSHAKE_WATCHDOG_MS, "pre-READY canonical raw link"); + await expect(within(starting, PROCESS_HANDSHAKE_WATCHDOG_MS, "pre-READY guardian rejection")) .rejects.toThrow(/provider guardian/u); const possibleTempLeaves = (await readdir(evidenceRoot)).filter((leaf) => leaf.startsWith(".vulnerability-report.json.guardian-") @@ -587,7 +594,7 @@ describe("provider guardian transaction protocol", () => { await canaryHandle.close(); process.kill(guardianPid, "SIGKILL"); - await expect(within(starting, 2_000, "external-canary guardian rejection")) + await expect(within(starting, PROCESS_HANDSHAKE_WATCHDOG_MS, "external-canary guardian rejection")) .rejects.toThrow(/provider guardian/u); expect(await readFile(rawPath)).toEqual(canaryBytes); expect(await lstat(rawPath)).toMatchObject({ @@ -664,14 +671,14 @@ describe("provider guardian transaction protocol", () => { deadlineEpochMs: Date.now() + 3_000, })); const ready = decodeProviderGuardianReady( - await within(readyPayload, 1_000, "closed-stderr guardian READY"), + await within(readyPayload, PROCESS_HANDSHAKE_WATCHDOG_MS, "closed-stderr guardian READY"), nonce, ); child.stderr!.destroy(); await new Promise((resolve) => child.stderr!.once("close", resolve)); child.stdin!.end(); - await expect(within(completion, 1_000, "closed-stderr guardian exit")) + await expect(within(completion, PROCESS_HANDSHAKE_WATCHDOG_MS, "closed-stderr guardian exit")) .resolves.toEqual({ code: 125, signal: null }); await expect(lstat(path.join(rawDirectory, "vulnerability-report.json"))) .rejects.toMatchObject({ code: "ENOENT" }); @@ -697,12 +704,12 @@ describe("provider guardian transaction protocol", () => { deadlineEpochMs: Date.now() + 350, })); const ready = decodeProviderGuardianReady( - await within(readyPayload, 1_000, "deadline guardian READY"), + await within(readyPayload, PROCESS_HANDSHAKE_WATCHDOG_MS, "deadline guardian READY"), nonce, ); const sealedTempPath = path.join(evidenceRoot, ready.sealedTempLeaf); - await expect(within(completion, 1_000, "guardian deadline")) + await expect(within(completion, PROCESS_HANDSHAKE_WATCHDOG_MS, "guardian deadline")) .resolves.toEqual({ code: null, signal: "SIGKILL" }); await expect(lstat(rawPath)).rejects.toMatchObject({ code: "ENOENT" }); await expect(lstat(sealedTempPath)).rejects.toMatchObject({ code: "ENOENT" }); @@ -874,7 +881,7 @@ async function establishPublishedGuardian( deadlineEpochMs: Date.now() + 3_000, })); const ready = decodeProviderGuardianReady( - await within(readyPayload, 1_000, "guardian READY"), + await within(readyPayload, PROCESS_HANDSHAKE_WATCHDOG_MS, "guardian READY"), nonce, ); const sealedTempPath = path.join(evidenceRoot, ready.sealedTempLeaf); @@ -896,7 +903,7 @@ async function establishPublishedGuardian( sha256: createHash("sha256").update(bytes).digest("hex"), })); decodeProviderGuardianPublished( - await within(publishedPayload, 1_000, "guardian PUBLISHED"), + await within(publishedPayload, PROCESS_HANDSHAKE_WATCHDOG_MS, "guardian PUBLISHED"), nonce, { dev: ready.sealedDev, ino: ready.sealedIno }, ); diff --git a/tests/unit/ci-artifact-contract.test.ts b/tests/system/ci-runner/ci-artifact-contract.test.ts similarity index 98% rename from tests/unit/ci-artifact-contract.test.ts rename to tests/system/ci-runner/ci-artifact-contract.test.ts index afd7d81..9fab86d 100644 --- a/tests/unit/ci-artifact-contract.test.ts +++ b/tests/system/ci-runner/ci-artifact-contract.test.ts @@ -11,46 +11,46 @@ import { afterAll, afterEach, describe, expect, it, type TestContext } from "vit import type { CiGateArtifact, CiGateArtifactSchema, -} from "../../scripts/contracts/ci-gates.ts"; -import { parseCiGateContract } from "../../scripts/contracts/ci-gates.ts"; +} from "../../../scripts/contracts/ci-gates.ts"; +import { parseCiGateContract } from "../../../scripts/contracts/ci-gates.ts"; import { hasCiArtifactSemanticValidator, readBoundedRegularFile, validateCiArtifact, -} from "../../scripts/lib/ci-artifact-validator.ts"; -import { writeCiGateLogAtomic } from "../../scripts/lib/ci-gate-log.ts"; -import { linkFixtureNodeModules } from "../../scripts/lib/fixture-node-modules.ts"; -import { copyReleaseEvidenceTree } from "../../scripts/lib/removal-fixture.ts"; -import { captureCiCandidateArchive, verifyCiCandidateArchive } from "../../scripts/lib/ci-candidate-archive.ts"; +} from "../../../scripts/lib/ci-artifact-validator.ts"; +import { writeCiGateLogAtomic } from "../../../scripts/lib/ci-gate-log.ts"; +import { linkFixtureNodeModules } from "../../../scripts/lib/fixture-node-modules.ts"; +import { copyReleaseEvidenceTree } from "../../../scripts/lib/removal-fixture.ts"; +import { captureCiCandidateArchive, verifyCiCandidateArchive } from "../../../scripts/lib/ci-candidate-archive.ts"; import { CANDIDATE_ARCHIVE_USAGE, parseCandidateArchiveArguments, -} from "../../scripts/lib/ci-candidate-archive-cli.ts"; -import { validateProviderUpload } from "../../scripts/lib/provider-upload-validator.ts"; -import { verifyExactPromotionBundle } from "../../scripts/lib/exact-promotion-bundle.ts"; +} from "../../../scripts/lib/ci-candidate-archive-cli.ts"; +import { validateProviderUpload } from "../../../scripts/lib/provider-upload-validator.ts"; +import { verifyExactPromotionBundle } from "../../../scripts/lib/exact-promotion-bundle.ts"; import { cleanupFinalizedPromotion, stageVerifiedPromotion, -} from "../../scripts/lib/promotion-stager.ts"; -import { PROMOTED_FILE_NAMES } from "../../scripts/contracts/promotion-artifacts.ts"; +} from "../../../scripts/lib/promotion-stager.ts"; +import { PROMOTED_FILE_NAMES } from "../../../scripts/contracts/promotion-artifacts.ts"; import { providerEvidenceSignaturePayload, providerPublicKeyFingerprint, providerVerificationArtifactSchema, -} from "../../scripts/lib/provider-evidence.ts"; -import { localEvidenceAssessmentArtifactSchema } from "../../scripts/contracts/release-artifacts.ts"; -import { readProviderTrust } from "../../scripts/lib/provider-trust.ts"; +} from "../../../scripts/lib/provider-evidence.ts"; +import { localEvidenceAssessmentArtifactSchema } from "../../../scripts/contracts/release-artifacts.ts"; +import { readProviderTrust } from "../../../scripts/lib/provider-trust.ts"; import { assertProviderSandboxUsable, probeProviderSandbox, providerSandboxDecision, -} from "../../scripts/lib/provider-sandbox-probe.ts"; +} from "../../../scripts/lib/provider-sandbox-probe.ts"; import { createReleaseCandidateManifest, LOCAL_EVIDENCE_ASSESSMENT_PATH, RELEASE_CANDIDATE_EVIDENCE_PATHS, RELEASE_CANDIDATE_MANIFEST_PATH, -} from "../../scripts/lib/release-candidate.ts"; +} from "../../../scripts/lib/release-candidate.ts"; /** * Budget for the provider suites specifically. They spawn a systemd scope, a diff --git a/tests/system/ci-runner/ci-evidence-freshness.test.ts b/tests/system/ci-runner/ci-evidence-freshness.test.ts new file mode 100644 index 0000000..8eb1877 --- /dev/null +++ b/tests/system/ci-runner/ci-evidence-freshness.test.ts @@ -0,0 +1,168 @@ +import { spawnSync } from "node:child_process"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +import { afterEach, describe, expect, it } from "vitest"; + +import { loadCiGateContract } from "../../../scripts/contracts/ci-gates.ts"; + +const temporaryRoots: string[] = []; + +afterEach(async () => { + await Promise.all( + temporaryRoots.splice(0).map((root) => + rm(root, { recursive: true, force: true }), + ), + ); +}); + +describe("CI-runner command-generated evidence freshness", () => { + it("rejects stale command-generated evidence from a successful no-op producer", async () => { + const root = await mkdtemp(path.join(tmpdir(), "ci-gate-stale-evidence-")); + temporaryRoots.push(root); + await mkdir(path.join(root, "config/ci"), { recursive: true }); + await mkdir(path.join(root, "artifacts/tests"), { recursive: true }); + const contract = JSON.parse( + JSON.stringify(await loadCiGateContract(process.cwd())), + ) as Record; + const command = contract.commands.find( + (entry: Record) => entry.id === "test-runtime-schema", + ); + command.script = "test:stale-evidence-noop"; + const evidence = contract.artifacts.find( + (entry: Record) => + entry.path === "artifacts/tests/runtime-schema.xml", + ); + const packageDocument = JSON.parse( + await readFile("package.json", "utf8"), + ) as { scripts: Record }; + packageDocument.scripts[command.script] = "true"; + await writeFile( + path.join(root, "config/ci/gates.json"), + `${JSON.stringify(contract)}\n`, + ); + await writeFile( + path.join(root, "package.json"), + `${JSON.stringify(packageDocument)}\n`, + ); + await writeFile( + path.join(root, evidence.path), + '\n', + ); + + const result = spawnSync( + process.execPath, + [path.resolve("scripts/run-ci-gate.ts"), "FE-GATE-004"], + { cwd: root, encoding: "utf8", env: { ...process.env, CI: "false" } }, + ); + + expect(result.status).toBe(1); + expect( + await readFile( + path.join(root, "artifacts/quality/gates/FE-GATE-004.txt"), + "utf8", + ), + ).toMatch(/not freshly produced/i); + }); + + it("accepts a fresh deterministic rewrite with identical evidence bytes", async () => { + const root = await mkdtemp( + path.join(tmpdir(), "ci-gate-identical-rewrite-"), + ); + temporaryRoots.push(root); + await mkdir(path.join(root, "config/ci"), { recursive: true }); + await mkdir(path.join(root, "artifacts/tests"), { recursive: true }); + const contract = JSON.parse( + JSON.stringify(await loadCiGateContract(process.cwd())), + ) as Record; + const command = contract.commands.find( + (entry: Record) => entry.id === "test-runtime-schema", + ); + command.script = "test:identical-evidence-rewrite"; + const evidence = contract.artifacts.find( + (entry: Record) => + entry.path === "artifacts/tests/runtime-schema.xml", + ); + const evidenceBytes = + '\n'; + const packageDocument = JSON.parse( + await readFile("package.json", "utf8"), + ) as { scripts: Record }; + packageDocument.scripts[command.script] = + `node -e 'require("node:fs").writeFileSync("${evidence.path}", Buffer.from("${Buffer.from(evidenceBytes).toString("base64")}", "base64"))'`; + await writeFile( + path.join(root, "config/ci/gates.json"), + `${JSON.stringify(contract)}\n`, + ); + await writeFile( + path.join(root, "package.json"), + `${JSON.stringify(packageDocument)}\n`, + ); + await writeFile(path.join(root, evidence.path), evidenceBytes); + + const result = spawnSync( + process.execPath, + [path.resolve("scripts/run-ci-gate.ts"), "FE-GATE-004"], + { cwd: root, encoding: "utf8", env: { ...process.env, CI: "false" } }, + ); + + expect(result.status).toBe(0); + expect(result.stdout).toMatch(/FE-GATE-004 runtime-schema: PASS/); + }); +}); + +describe("CI-runner gate output budget", () => { + it("caps aggregate gate output at the log schema before later commands can accumulate", async () => { + const root = await mkdtemp(path.join(tmpdir(), "ci-gate-output-budget-")); + temporaryRoots.push(root); + await mkdir(path.join(root, "config/ci"), { recursive: true }); + const contract = JSON.parse( + JSON.stringify(await loadCiGateContract(process.cwd())), + ) as Record; + const gate = contract.gates.find( + (entry: Record) => entry.id === "FE-GATE-001", + ); + const command = contract.commands.find( + (entry: Record) => entry.id === gate.commandIds[0], + ); + command.script = "test:huge-output"; + const logArtifact = contract.artifacts.find( + (entry: Record) => entry.id === gate.logArtifactId, + ); + const logSchema = contract.artifactSchemas.find( + (entry: Record) => entry.id === logArtifact.schemaId, + ); + logSchema.maxBytes = 8_192; + const packageDocument = JSON.parse( + await readFile("package.json", "utf8"), + ) as { scripts: Record }; + packageDocument.scripts["test:huge-output"] = + "node -e \"process.stdout.write('x'.repeat(20000))\""; + await writeFile( + path.join(root, "config/ci/gates.json"), + `${JSON.stringify(contract)}\n`, + ); + await writeFile( + path.join(root, "package.json"), + `${JSON.stringify(packageDocument)}\n`, + ); + const result = spawnSync( + process.execPath, + [path.resolve("scripts/run-ci-gate.ts"), "FE-GATE-001"], + { + cwd: root, + encoding: "utf8", + env: { ...process.env, CI: "false" }, + timeout: 15_000, + }, + ); + + expect(result.status).toBe(1); + const log = await readFile(path.join(root, logArtifact.path)); + expect(log.byteLength).toBeLessThanOrEqual(8_192); + expect(log.toString("utf8")).toMatch( + /aggregate output|INFRASTRUCTURE_FAILURE/i, + ); + }, 20_000); +}); diff --git a/tests/system/ci-runner/provider-process-group.test.ts b/tests/system/ci-runner/provider-process-group.test.ts new file mode 100644 index 0000000..a6db0ac --- /dev/null +++ b/tests/system/ci-runner/provider-process-group.test.ts @@ -0,0 +1,41 @@ +import { mkdtemp, readFile, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +import { describe, expect, it } from "vitest"; + +import { runProviderProcess } from "../../../scripts/lib/provider-process-runner.ts"; + +describe("CI-runner provider process-group lifecycle", () => { + it("kills and reaps a stubborn provider process group including its descendant", async () => { + const root = await mkdtemp(path.join(tmpdir(), "provider-process-group-")); + const descendantPidPath = path.join(root, "descendant.pid"); + try { + const source = [ + "const { spawn } = require('node:child_process');", + "const { writeFileSync } = require('node:fs');", + "const child = spawn(process.execPath, ['-e', `process.on('SIGTERM', () => {}); setInterval(() => {}, 1000)`], { stdio: 'ignore' });", + "writeFileSync(process.env.DESCENDANT_PID_PATH, String(child.pid));", + "process.on('SIGTERM', () => {});", + "setInterval(() => {}, 1000);", + ].join("\n"); + + const running = runProviderProcess({ + executable: process.execPath, + arguments: ["-e", source], + environment: { + PATH: process.env.PATH, + DESCENDANT_PID_PATH: descendantPidPath, + }, + timeoutMs: 250, + }); + + await expect(running).rejects.toThrow(/timed out.*process close/u); + const descendantPid = Number(await readFile(descendantPidPath, "utf8")); + expect(Number.isSafeInteger(descendantPid) && descendantPid > 0).toBe(true); + expect(() => process.kill(descendantPid, 0)).toThrow(/ESRCH|no such process/u); + } finally { + await rm(root, { recursive: true, force: true }); + } + }); +}); diff --git a/tests/unit/bounded-body-reader.test.ts b/tests/unit/bounded-body-reader.test.ts index f7603f9..220e4a3 100644 --- a/tests/unit/bounded-body-reader.test.ts +++ b/tests/unit/bounded-body-reader.test.ts @@ -223,11 +223,12 @@ describe("bounded body reader", () => { }); }); - it("abandons and cancels a forbidden-body probe when its lifetime aborts", async () => { + + it("abandons a pending bounded read when the operation is aborted", async () => { const controller = new AbortController(); const reader = { read: vi.fn(() => new Promise(() => {})), - cancel: vi.fn().mockRejectedValue(new Error("abandoned cancel failed")), + cancel: vi.fn().mockRejectedValue(new Error("cancel ignored")), releaseLock: vi.fn(), }; const response = { @@ -235,10 +236,33 @@ describe("bounded body reader", () => { body: { getReader: () => reader }, } as unknown as Response; - const outcome = probeForbiddenBody(response, controller.signal); + const pending = readBoundedBytes(response, 8, controller.signal); controller.abort(); - await expect(outcome).resolves.toEqual({ + await expect(pending).resolves.toEqual({ + ok: false, + code: "RESPONSE_STREAM_FAILURE", + }); + expect(reader.cancel).toHaveBeenCalledOnce(); + expect(reader.releaseLock).toHaveBeenCalledOnce(); + }); + + it("abandons a pending forbidden-body probe when the operation is aborted", async () => { + const controller = new AbortController(); + const reader = { + read: vi.fn(() => new Promise(() => {})), + cancel: vi.fn().mockRejectedValue(new Error("cancel ignored")), + releaseLock: vi.fn(), + }; + const response = { + headers: new Headers(), + body: { getReader: () => reader }, + } as unknown as Response; + + const pending = probeForbiddenBody(response, controller.signal); + controller.abort(); + + await expect(pending).resolves.toEqual({ ok: false, code: "RESPONSE_STREAM_FAILURE", }); diff --git a/tests/unit/browser-file-picker.test.ts b/tests/unit/browser-file-picker.test.ts index 0f7129d..8f20399 100644 --- a/tests/unit/browser-file-picker.test.ts +++ b/tests/unit/browser-file-picker.test.ts @@ -73,12 +73,17 @@ function labelledFileInput(): HTMLInputElement { describe("browser file pickers", () => { it("treats native input cancellation as a normal dismissed outcome", async () => { const input = labelledFileInput(); - Object.defineProperty(input, "showPicker", { + Object.defineProperty(input, "click", { configurable: true, value: vi.fn(() => { queueMicrotask(() => input.dispatchEvent(new Event("cancel"))); }), }); + const baselineShowPicker = vi.fn(); + Object.defineProperty(input, "showPicker", { + configurable: true, + value: baselineShowPicker, + }); const harness = createHarness(); const picker = new NativeInputFilePicker({ input, @@ -90,6 +95,7 @@ describe("browser file pickers", () => { ok: true, value: { kind: "DISMISSED" }, }); + expect(baselineShowPicker).not.toHaveBeenCalled(); }); it("resets the native input and supports same-file reselection", async () => { @@ -102,12 +108,12 @@ describe("browser file pickers", () => { configurable: true, value: [selected], }); - const showPicker = vi.fn(() => { + const click = vi.fn(() => { queueMicrotask(() => input.dispatchEvent(new Event("change"))); }); - Object.defineProperty(input, "showPicker", { + Object.defineProperty(input, "click", { configurable: true, - value: showPicker, + value: click, }); let sequence = 0; const { policies, vault } = createHarness(policyDefinition, { @@ -130,14 +136,14 @@ describe("browser file pickers", () => { ok: true, value: { kind: "SELECTED" }, }); - expect(showPicker).toHaveBeenCalledTimes(2); + expect(click).toHaveBeenCalledTimes(2); expect(input.value).toBe(""); expect(vault.activeReferenceCount).toBe(2); }); it("snapshots selection policy before awaiting picker events", async () => { const input = labelledFileInput(); - Object.defineProperty(input, "showPicker", { + Object.defineProperty(input, "click", { configurable: true, value: vi.fn(), }); @@ -186,7 +192,7 @@ describe("browser file pickers", () => { it("honors AbortSignal while a native dialog is pending", async () => { const input = labelledFileInput(); - Object.defineProperty(input, "showPicker", { + Object.defineProperty(input, "click", { configurable: true, value: vi.fn(), }); @@ -215,7 +221,7 @@ describe("browser file pickers", () => { let fallback: (() => void) | undefined; let delay: number | undefined; const clearTimeout = vi.fn(); - Object.defineProperty(input, "showPicker", { + Object.defineProperty(input, "click", { configurable: true, value: vi.fn(() => { window.dispatchEvent(new Event("focus")); @@ -261,7 +267,7 @@ describe("browser file pickers", () => { const input = labelledFileInput(); let fallback: (() => void) | undefined; const clearTimeout = vi.fn(); - Object.defineProperty(input, "showPicker", { + Object.defineProperty(input, "click", { configurable: true, value: vi.fn(() => { window.dispatchEvent(new Event("focus")); @@ -316,14 +322,14 @@ describe("browser file pickers", () => { setTimeout: originalSetTimeout, clearTimeout: originalClearTimeout, }; - const originalShowPicker = vi.fn(() => { + const originalClick = vi.fn(() => { focus?.(new Event("focus")); }); - const replacedShowPicker = vi.fn(); - Object.defineProperty(input, "showPicker", { + const replacedClick = vi.fn(); + Object.defineProperty(input, "click", { configurable: true, writable: true, - value: originalShowPicker, + value: originalClick, }); const harness = createHarness(); const picker = new NativeInputFilePicker({ @@ -338,7 +344,7 @@ describe("browser file pickers", () => { focusFallbackGraceMs: 0, }); - input.showPicker = replacedShowPicker; + input.click = replacedClick; windowHost.addEventListener = vi.fn(); windowHost.removeEventListener = vi.fn(); scheduler.setTimeout = vi.fn(); @@ -348,8 +354,8 @@ describe("browser file pickers", () => { ok: true, value: { kind: "DISMISSED" }, }); - expect(originalShowPicker).toHaveBeenCalledOnce(); - expect(replacedShowPicker).not.toHaveBeenCalled(); + expect(originalClick).toHaveBeenCalledOnce(); + expect(replacedClick).not.toHaveBeenCalled(); expect(originalWindowAdd).toHaveBeenCalledOnce(); expect(originalWindowRemove).toHaveBeenCalledOnce(); expect(originalSetTimeout).toHaveBeenCalledOnce(); diff --git a/tests/unit/browser-file-runtime.test.ts b/tests/unit/browser-file-runtime.test.ts index 8d7c878..62b71ab 100644 --- a/tests/unit/browser-file-runtime.test.ts +++ b/tests/unit/browser-file-runtime.test.ts @@ -178,7 +178,7 @@ describe("browser file runtime hard limits and disposal", () => { it("aborts a pending native picker and prevents event resurrection", async () => { const input = fileInput(); - Object.defineProperty(input, "showPicker", { + Object.defineProperty(input, "click", { configurable: true, value: vi.fn(), }); diff --git a/tests/unit/browser-rpc/browser-rpc-runtime.test.ts b/tests/unit/browser-rpc/browser-rpc-runtime.test.ts index 0027308..1e68ef5 100644 --- a/tests/unit/browser-rpc/browser-rpc-runtime.test.ts +++ b/tests/unit/browser-rpc/browser-rpc-runtime.test.ts @@ -9,7 +9,7 @@ import { type BrowserRpcStreamFrame, type BrowserRpcTransport, } from "../../../src/adapters/browser-rpc/index.ts"; -import type { Result } from "../../../src/application/result.ts"; +import type { Result } from "../../../src/contracts/result.ts"; import type { AppFailure } from "../../../src/contracts/errors.ts"; import { MAPPERS, diff --git a/tests/unit/ci-workflow-generation.test.ts b/tests/unit/ci-workflow-generation.test.ts index e5e991f..da53fbb 100644 --- a/tests/unit/ci-workflow-generation.test.ts +++ b/tests/unit/ci-workflow-generation.test.ts @@ -193,18 +193,21 @@ describe("CI gate contract", () => { // Alignment follow-up item 2: FE-GATE-007 gained `test-tech-log`. // Dev release manifest drift fix item 2: FE-GATE-010 gained // `check-dev-release-manifest`. - expect(contract.commands).toHaveLength(85); - expect(contract.gates.reduce((total, gate) => total + gate.commandIds.length, 0)).toBe(97); - expect(contract.commands.filter(({ expect }) => expect === "fail")).toHaveLength(23); - // Template merge. Recounted from the merged config/ci/gates.json rather - // than taking either side's number. // Task 11 added TECH_LOG_STUDIO_ASSETS's manual accessibility evidence. // Alignment follow-up item 2 added the TechLog junit report. // 주제 화면 셋(`/topics`, `/topics/:slug/:variant`, `/studio/topics/:id`)이 라우트마다 // 하나씩인 수동 접근성 증거를 셋 더했다. // 환경 구성(SETUP)이 `/setups/:slug` 로 하나를 더 더했다. - expect(contract.gates.reduce((total, gate) => total + gate.evidenceArtifactIds.length, 0)).toBe(118); - expect(contract.artifacts).toHaveLength(139); + // Template sync (ebea300). Every count below is recounted from the merged + // config/ci/gates.json rather than taken from either side: this product + // pinned 85/97/23/118/139 and the template pinned 91/103/30/88/109, and + // neither set describes the merged file. The method was checked by first + // reproducing this product's numbers from the pre-merge gates.json. + expect(contract.commands).toHaveLength(94); + expect(contract.gates.reduce((total, gate) => total + gate.commandIds.length, 0)).toBe(106); + expect(contract.commands.filter(({ expect }) => expect === "fail")).toHaveLength(30); + expect(contract.gates.reduce((total, gate) => total + gate.evidenceArtifactIds.length, 0)).toBe(120); + expect(contract.artifacts).toHaveLength(141); expect(contract.stages).toHaveLength(5); expect(contract.retention.classes).toHaveLength(5); expect(index.gates.get("FE-GATE-015")?.commandIds).toHaveLength(2); @@ -1367,106 +1370,6 @@ describe("CI gate contract", () => { ); }); - it("caps aggregate gate output at the log schema before later commands can accumulate", async () => { - const root = await mkdtemp(path.join(tmpdir(), "ci-gate-output-budget-")); - temporaryRoots.push(root); - await mkdir(path.join(root, "config/ci"), { recursive: true }); - const contract = JSON.parse(JSON.stringify(await loadCiGateContract(process.cwd()))) as Record; - const gate = contract.gates.find((entry: any) => entry.id === "FE-GATE-001"); - const command = contract.commands.find((entry: any) => entry.id === gate.commandIds[0]); - command.script = "test:huge-output"; - const logArtifact = contract.artifacts.find((entry: any) => entry.id === gate.logArtifactId); - const logSchema = contract.artifactSchemas.find((entry: any) => entry.id === logArtifact.schemaId); - logSchema.maxBytes = 8_192; - const packageDocument = JSON.parse(await readFile("package.json", "utf8")) as { scripts: Record }; - packageDocument.scripts["test:huge-output"] = "node -e \"process.stdout.write('x'.repeat(20000))\""; - await writeFile(path.join(root, "config/ci/gates.json"), `${JSON.stringify(contract)}\n`); - await writeFile(path.join(root, "package.json"), `${JSON.stringify(packageDocument)}\n`); - const environment = { ...process.env, CI: "false" }; - const result = spawnSync(process.execPath, [path.resolve("scripts/run-ci-gate.ts"), "FE-GATE-001"], { - cwd: root, - encoding: "utf8", - env: environment, - timeout: 15_000, - }); - expect(result.status).toBe(1); - const log = await readFile(path.join(root, logArtifact.path)); - expect(log.byteLength).toBeLessThanOrEqual(8_192); - expect(log.toString("utf8")).toMatch(/aggregate output|INFRASTRUCTURE_FAILURE/i); - }, 20_000); - - it("rejects stale command-generated evidence from a successful no-op producer", async () => { - const root = await mkdtemp(path.join(tmpdir(), "ci-gate-stale-evidence-")); - temporaryRoots.push(root); - await mkdir(path.join(root, "config/ci"), { recursive: true }); - await mkdir(path.join(root, "artifacts/tests"), { recursive: true }); - const contract = JSON.parse( - JSON.stringify(await loadCiGateContract(process.cwd())), - ) as Record; - const command = contract.commands.find( - (entry: Record) => entry.id === "test-runtime-schema", - ); - command.script = "test:stale-evidence-noop"; - const evidence = contract.artifacts.find( - (entry: Record) => entry.path === "artifacts/tests/runtime-schema.xml", - ); - const packageDocument = JSON.parse(await readFile("package.json", "utf8")) as { - scripts: Record; - }; - packageDocument.scripts[command.script] = "true"; - await writeFile(path.join(root, "config/ci/gates.json"), `${JSON.stringify(contract)}\n`); - await writeFile(path.join(root, "package.json"), `${JSON.stringify(packageDocument)}\n`); - await writeFile( - path.join(root, evidence.path), - '\n', - ); - - const result = spawnSync( - process.execPath, - [path.resolve("scripts/run-ci-gate.ts"), "FE-GATE-004"], - { cwd: root, encoding: "utf8", env: { ...process.env, CI: "false" } }, - ); - - expect(result.status).toBe(1); - expect( - await readFile(path.join(root, "artifacts/quality/gates/FE-GATE-004.txt"), "utf8"), - ).toMatch(/not freshly produced/i); - }); - - it("accepts a fresh deterministic rewrite with identical evidence bytes", async () => { - const root = await mkdtemp(path.join(tmpdir(), "ci-gate-identical-rewrite-")); - temporaryRoots.push(root); - await mkdir(path.join(root, "config/ci"), { recursive: true }); - await mkdir(path.join(root, "artifacts/tests"), { recursive: true }); - const contract = JSON.parse( - JSON.stringify(await loadCiGateContract(process.cwd())), - ) as Record; - const command = contract.commands.find( - (entry: Record) => entry.id === "test-runtime-schema", - ); - command.script = "test:identical-evidence-rewrite"; - const evidence = contract.artifacts.find( - (entry: Record) => entry.path === "artifacts/tests/runtime-schema.xml", - ); - const evidenceBytes = '\n'; - const packageDocument = JSON.parse(await readFile("package.json", "utf8")) as { - scripts: Record; - }; - packageDocument.scripts[command.script] = - `node -e 'require("node:fs").writeFileSync("${evidence.path}", Buffer.from("${Buffer.from(evidenceBytes).toString("base64")}", "base64"))'`; - await writeFile(path.join(root, "config/ci/gates.json"), `${JSON.stringify(contract)}\n`); - await writeFile(path.join(root, "package.json"), `${JSON.stringify(packageDocument)}\n`); - await writeFile(path.join(root, evidence.path), evidenceBytes); - - const result = spawnSync( - process.execPath, - [path.resolve("scripts/run-ci-gate.ts"), "FE-GATE-004"], - { cwd: root, encoding: "utf8", env: { ...process.env, CI: "false" } }, - ); - - expect(result.status).toBe(0); - expect(result.stdout).toMatch(/FE-GATE-004 runtime-schema: PASS/); - }); }); describe("CI workflow generation", () => { diff --git a/tests/unit/compatibility.test.ts b/tests/unit/compatibility.test.ts index 660fce0..bc0654e 100644 --- a/tests/unit/compatibility.test.ts +++ b/tests/unit/compatibility.test.ts @@ -5,7 +5,7 @@ import { isVersionCompatible, parseNumericVersion, verifyCompatibilityTuple, -} from "../../src/application/policies/compatibility.ts"; +} from "../../src/contracts/compatibility.ts"; describe("contract compatibility", () => { it("uses numeric version parsing rather than lexical comparison", () => { diff --git a/tests/unit/cursor-pagination-runtime.test.ts b/tests/unit/cursor-pagination-runtime.test.ts index 9b119c5..eeb6fce 100644 --- a/tests/unit/cursor-pagination-runtime.test.ts +++ b/tests/unit/cursor-pagination-runtime.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from "vitest"; -import { createCursorPaginationRuntime } from "../../src/adapters/query-cache/cursor-pagination-runtime.ts"; +import { createCursorPaginationRuntime } from "../../src/adapters/query-cache/index.ts"; const profile = { profileId: "bounded-cursor-v1", diff --git a/tests/unit/http-retry-lifecycle.test.ts b/tests/unit/http-retry-lifecycle.test.ts new file mode 100644 index 0000000..3e27f63 --- /dev/null +++ b/tests/unit/http-retry-lifecycle.test.ts @@ -0,0 +1,48 @@ +import { describe, expect, it } from "vitest"; + +import { + canRetryTransport, + isRetryableHttpStatus, + isRetryableSemantics, + jitteredDelay, + retryDelayFor, +} from "../../src/adapters/http/http-retry-lifecycle.ts"; + +describe("HTTP retry lifecycle policy", () => { + it("allows KEYED replay only before a physical dispatch", () => { + expect(canRetryTransport("KEYED", "PREPARING")).toBe(true); + expect(canRetryTransport("KEYED", "READY_TO_SEND")).toBe(true); + expect(canRetryTransport("KEYED", "DISPATCHED")).toBe(false); + expect(canRetryTransport("KEYED", "RESPONSE_HEADERS")).toBe(false); + }); + + it("keeps SAFE and IDEMPOTENT retryable while NEVER is terminal", () => { + expect(isRetryableSemantics("SAFE")).toBe(true); + expect(isRetryableSemantics("IDEMPOTENT")).toBe(true); + expect(isRetryableSemantics("KEYED")).toBe(false); + expect(isRetryableSemantics("NEVER")).toBe(false); + + expect(canRetryTransport("SAFE", "DISPATCHED")).toBe(true); + expect(canRetryTransport("IDEMPOTENT", "READING_BODY")).toBe(true); + expect(canRetryTransport("NEVER", "PREPARING")).toBe(false); + }); + + it("owns the closed retryable status vocabulary", () => { + for (const status of [408, 425, 429, 502, 503, 504]) { + expect(isRetryableHttpStatus(status)).toBe(true); + } + for (const status of [400, 401, 403, 404, 409, 500, 501]) { + expect(isRetryableHttpStatus(status)).toBe(false); + } + }); + + it("uses bounded full jitter and rejects excessive Retry-After", () => { + expect(jitteredDelay(0, () => 0)).toBe(0); + expect(jitteredDelay(0, () => 0.5)).toBe(125); + expect(jitteredDelay(8, () => 0.5)).toBe(1_000); + + expect(retryDelayFor(null, 0, () => 0.5)).toBe(125); + expect(retryDelayFor(400, 0, () => 0.5)).toBe(400); + expect(retryDelayFor(5_001, 0, () => 0.5)).toBeNull(); + }); +}); diff --git a/tests/unit/image-cdn-browser-probe.test.ts b/tests/unit/image-cdn-browser-probe.test.ts new file mode 100644 index 0000000..183c8de --- /dev/null +++ b/tests/unit/image-cdn-browser-probe.test.ts @@ -0,0 +1,652 @@ +import { describe, expect, it, vi } from "vitest"; + +import type { + ImageProbeRequest, +} from "../../src/application/ports/browser-transfer/image-cdn.ts"; +import { createBrowserImageProbe } from "../../src/adapters/browser-transfer/image-cdn/browser-image-probe.ts"; +import { + avifBytes, + jpegBytes, + manualImageProbeScheduler, + pngBytes, + publicImageHeaders, + responseAt, + webpBytes, +} from "./image-cdn-test-fixture.ts"; + +describe("browser image probe", () => { + const imageUrl = + "https://images.example.test/v1/assets/a/rev?format=png"; + const request = ( + overrides: Partial = {}, + ): ImageProbeRequest => ({ + absoluteUrl: imageUrl, + expectedMediaType: "image/png", + expectedWidth: 640, + expectedHeight: 360, + maxEncodedBytes: 1_024, + maxDecodedPixels: 230_400, + maxDecodedBytes: 921_600, + delivery: "PUBLIC_IMMUTABLE", + minimumPublicMaxAgeSeconds: 31_536_000, + referrerPolicy: "no-referrer", + signal: new AbortController().signal, + ...overrides, + }); + + it("parses all supported static headers before decode and closes each bitmap", async () => { + const samples = [ + { + mediaType: "image/png" as const, + bytes: pngBytes(640, 360), + }, + { + mediaType: "image/jpeg" as const, + bytes: jpegBytes(640, 360), + }, + { + mediaType: "image/webp" as const, + bytes: webpBytes(640, 360), + }, + { + mediaType: "image/avif" as const, + bytes: avifBytes(640, 360), + }, + ]; + const close = vi.fn(); + for (const sample of samples) { + const exactUrl = imageUrl.replace( + "format=png", + `format=${sample.mediaType.slice("image/".length)}`, + ); + const fetcher = vi.fn(async () => + responseAt(exactUrl, sample.bytes, { + status: 200, + headers: publicImageHeaders( + sample.mediaType, + sample.bytes.byteLength, + ), + }), + ); + const probe = createBrowserImageProbe({ + fetcher: fetcher as typeof fetch, + createBitmap: vi.fn(async () => ({ + width: 640, + height: 360, + close, + })), + }); + + await expect( + probe.probe( + request({ + absoluteUrl: exactUrl, + expectedMediaType: sample.mediaType, + }), + ), + ).resolves.toMatchObject({ + ok: true, + value: { + absoluteUrl: exactUrl, + mediaType: sample.mediaType, + encodedBytes: sample.bytes.byteLength, + decodedWidth: 640, + decodedHeight: 360, + }, + }); + expect(fetcher).toHaveBeenCalledWith( + exactUrl, + expect.objectContaining({ + credentials: "omit", + redirect: "error", + mode: "cors", + cache: "no-store", + referrerPolicy: "no-referrer", + }), + ); + } + expect(close).toHaveBeenCalledTimes(samples.length); + }); + + it("fails closed on duplicate/conflicting cache directives and oversized bodies", async () => { + const png = pngBytes(640, 360); + const createBitmap = vi.fn(async () => ({ + width: 640, + height: 360, + close: vi.fn(), + })); + for (const cacheControl of [ + // BT-IMG-02. Unmatched quotes must not be unwrapped into a bare number. + 'public, max-age="31536000, immutable', + 'public, max-age=31536000", immutable', + 'public, max-age="31536000\\", immutable', + "public, public, max-age=31536000, immutable", + "public, max-age=31536000, s-maxage=60, immutable", + "public, max-age=31536000, immutable, must-revalidate", + "public=1, max-age=31536000, immutable", + "public, max-age=31536000, immutable=true", + ]) { + const probe = createBrowserImageProbe({ + fetcher: (async () => + responseAt(imageUrl, png, { + status: 200, + headers: { + "cache-control": cacheControl, + "content-type": "image/png", + }, + })) as typeof fetch, + createBitmap, + }); + await expect(probe.probe(request())).resolves.toMatchObject({ + ok: false, + error: { code: "POLICY_REJECTED" }, + }); + } + + const probe = createBrowserImageProbe({ + fetcher: (async () => + responseAt(imageUrl, new Uint8Array(2_048), { + status: 200, + headers: { + "cache-control": + "public, max-age=31536000, immutable", + "content-type": "image/png", + }, + })) as typeof fetch, + createBitmap, + }); + await expect(probe.probe(request())).resolves.toMatchObject({ + ok: false, + error: { code: "LIMIT_EXCEEDED" }, + }); + expect(createBitmap).not.toHaveBeenCalled(); + }); + + it("rejects non-identity content encoding and mismatched declared lengths", async () => { + const png = pngBytes(640, 360); + const createBitmap = vi.fn(); + const cases = [ + { + headers: { + "content-encoding": "gzip", + "content-length": String(png.byteLength), + }, + code: "POLICY_REJECTED", + }, + { + headers: { + "content-length": String(png.byteLength + 1), + }, + code: "INTEGRITY_FAILED", + }, + ]; + for (const invalid of cases) { + const headers = publicImageHeaders("image/png"); + for (const [name, value] of Object.entries(invalid.headers)) { + headers.set(name, value); + } + const probe = createBrowserImageProbe({ + fetcher: (async () => + responseAt(imageUrl, png, { + status: 200, + headers, + })) as typeof fetch, + createBitmap, + }); + await expect(probe.probe(request())).resolves.toMatchObject({ + ok: false, + error: { code: invalid.code }, + }); + } + expect(createBitmap).not.toHaveBeenCalled(); + }); + + it("rejects malicious dimensions and animated PNG/WebP before native decode", async () => { + const createBitmap = vi.fn(async () => ({ + width: 640, + height: 360, + close: vi.fn(), + })); + const cases = [ + { + bytes: pngBytes(20_000, 20_000), + mediaType: "image/png" as const, + code: "LIMIT_EXCEEDED", + }, + { + bytes: pngBytes(320, 180), + mediaType: "image/png" as const, + code: "INTEGRITY_FAILED", + }, + { + bytes: jpegBytes(320, 180), + mediaType: "image/jpeg" as const, + code: "INTEGRITY_FAILED", + }, + { + bytes: webpBytes(10_000, 10_000), + mediaType: "image/webp" as const, + code: "LIMIT_EXCEEDED", + }, + { + bytes: avifBytes(20_000, 20_000), + mediaType: "image/avif" as const, + code: "LIMIT_EXCEEDED", + }, + { + bytes: pngBytes(640, 360, true), + mediaType: "image/png" as const, + code: "INTEGRITY_FAILED", + }, + { + bytes: webpBytes(640, 360, true), + mediaType: "image/webp" as const, + code: "INTEGRITY_FAILED", + }, + { + bytes: avifBytes(640, 360, "avis"), + mediaType: "image/avif" as const, + code: "INTEGRITY_FAILED", + }, + ]; + for (const malicious of cases) { + const url = imageUrl.replace( + "format=png", + `format=${malicious.mediaType.slice("image/".length)}`, + ); + const probe = createBrowserImageProbe({ + fetcher: (async () => + responseAt(url, malicious.bytes, { + status: 200, + headers: publicImageHeaders( + malicious.mediaType, + malicious.bytes.byteLength, + ), + })) as typeof fetch, + createBitmap, + }); + await expect( + probe.probe( + request({ + absoluteUrl: url, + expectedMediaType: malicious.mediaType, + }), + ), + ).resolves.toMatchObject({ + ok: false, + error: { code: malicious.code }, + }); + } + expect(createBitmap).not.toHaveBeenCalled(); + }); + + it("enforces private no-store, omitted credentials and the exact final URL", async () => { + const png = pngBytes(640, 360); + const fetcher = vi.fn(async () => + responseAt(imageUrl, png, { + status: 200, + headers: { + // TR-RR-09. A private response carries `no-store` and nothing else + // that describes cacheability. + "cache-control": "no-store", + "content-type": "image/png", + }, + }), + ); + const probe = createBrowserImageProbe({ + fetcher: fetcher as typeof fetch, + createBitmap: async () => ({ + width: 640, + height: 360, + close: vi.fn(), + }), + }); + await expect( + probe.probe( + request({ + delivery: "PRIVATE_SIGNED", + minimumPublicMaxAgeSeconds: 0, + }), + ), + ).resolves.toMatchObject({ ok: true }); + expect(fetcher).toHaveBeenCalledWith( + imageUrl, + expect.objectContaining({ + cache: "no-store", + credentials: "omit", + redirect: "error", + }), + ); + + for (const response of [ + responseAt(imageUrl, png, { + status: 200, + headers: { + "cache-control": "private, no-store=value", + "content-type": "image/png", + }, + }), + responseAt(imageUrl, png, { + status: 200, + headers: { + "cache-control": "public, no-store", + "content-type": "image/png", + }, + }), + responseAt( + "https://images.example.test/v1/assets/other", + png, + { + status: 200, + headers: { + "cache-control": "private, no-store", + "content-type": "image/png", + }, + }, + ), + ]) { + const rejectingProbe = createBrowserImageProbe({ + fetcher: (async () => response) as typeof fetch, + createBitmap: async () => ({ + width: 640, + height: 360, + close: vi.fn(), + }), + }); + await expect( + rejectingProbe.probe( + request({ + delivery: "PRIVATE_SIGNED", + minimumPublicMaxAgeSeconds: 0, + }), + ), + ).resolves.toMatchObject({ + ok: false, + error: { code: "POLICY_REJECTED" }, + }); + } + + await expect( + probe.probe( + request({ + expectedMediaType: "image/svg+xml", + } as unknown as Partial), + ), + ).resolves.toMatchObject({ + ok: false, + error: { code: "POLICY_REJECTED" }, + }); + }); + + /** + * TR-RR-09. The recorded BT-IMG-02 contract for a private response is a + * fail-closed matrix. Accepting `no-store` next to a directive that describes + * cacheability lets a self-contradictory policy read as acceptable. + */ + it("applies the full private Cache-Control matrix", async () => { + const png = pngBytes(640, 360); + const probeWith = async (cacheControl: string) => { + const probe = createBrowserImageProbe({ + fetcher: (async () => + responseAt(imageUrl, png, { + status: 200, + headers: { + "cache-control": cacheControl, + "content-type": "image/png", + }, + })) as typeof fetch, + createBitmap: async () => ({ + width: 640, + height: 360, + close: vi.fn(), + }), + }); + return await probe.probe( + request({ + delivery: "PRIVATE_SIGNED", + minimumPublicMaxAgeSeconds: 0, + }), + ); + }; + + // Only `no-store`, plus a syntactically valid unknown extension. + expect(await probeWith("no-store")).toMatchObject({ ok: true }); + expect(await probeWith('no-store, x-vendor="a,b"')).toMatchObject({ + ok: true, + }); + + for (const companion of [ + "public", + "private", + "immutable", + "max-age=60", + "s-maxage=60", + "no-cache", + "must-revalidate", + "proxy-revalidate", + ]) { + expect(await probeWith(`no-store, ${companion}`)).toMatchObject({ + ok: false, + error: { code: "POLICY_REJECTED" }, + }); + } + + for (const withoutNoStore of ["private", "no-cache", "max-age=0"]) { + expect(await probeWith(withoutNoStore)).toMatchObject({ + ok: false, + error: { code: "POLICY_REJECTED" }, + }); + } + }); + + it("times out a stalled body, aborts the composed signal and cancels its reader", async () => { + const manual = manualImageProbeScheduler(); + const cancel = vi.fn(async () => undefined); + const releaseLock = vi.fn(); + const read = vi.fn( + () => + new Promise>( + () => undefined, + ), + ); + const response = { + body: { + getReader: () => ({ cancel, read, releaseLock }), + }, + headers: publicImageHeaders("image/png"), + ok: true, + redirected: false, + status: 200, + type: "cors", + url: imageUrl, + } as unknown as Response; + const fetcher = vi.fn( + async (_input: RequestInfo | URL, _init?: RequestInit) => + response, + ); + const probe = createBrowserImageProbe({ + fetcher: fetcher as typeof fetch, + createBitmap: vi.fn(), + timeoutMs: 1_000, + scheduler: manual.scheduler, + }); + const probeRequest = request(); + const pending = probe.probe(probeRequest); + await vi.waitFor(() => { + expect(read).toHaveBeenCalledOnce(); + }); + const composedSignal = fetcher.mock.calls[0]?.[1]?.signal as + | AbortSignal + | null + | undefined; + expect(composedSignal).not.toBe(probeRequest.signal); + manual.fire(); + + await expect(pending).resolves.toMatchObject({ + ok: false, + error: { + code: "UNAVAILABLE", + retryable: true, + recovery: "RETRY", + }, + }); + expect(cancel).toHaveBeenCalledOnce(); + expect(releaseLock).toHaveBeenCalledOnce(); + expect(composedSignal?.aborted).toBe(true); + }); + + it("times out stalled decode and closes a bitmap that resolves late", async () => { + const manual = manualImageProbeScheduler(); + const close = vi.fn(); + let finishDecode: + ((bitmap: { + width: number; + height: number; + close(): void; + }) => void) | undefined; + const createBitmap = vi.fn( + () => + new Promise<{ + width: number; + height: number; + close(): void; + }>((resolve) => { + finishDecode = resolve; + }), + ); + const png = pngBytes(640, 360); + const probe = createBrowserImageProbe({ + fetcher: (async () => + responseAt(imageUrl, png, { + status: 200, + headers: publicImageHeaders("image/png", png.byteLength), + })) as typeof fetch, + createBitmap, + timeoutMs: 1_000, + scheduler: manual.scheduler, + }); + const pending = probe.probe(request()); + await vi.waitFor(() => { + expect(createBitmap).toHaveBeenCalledOnce(); + }); + manual.fire(); + await expect(pending).resolves.toMatchObject({ + ok: false, + error: { code: "UNAVAILABLE" }, + }); + + finishDecode?.({ width: 640, height: 360, close }); + await vi.waitFor(() => { + expect(close).toHaveBeenCalledOnce(); + }); + }); + + /** + * X-AUDIT-02. `probe()` promises a `BrowserDataResult`. A scheduler that + * cannot install the probe deadline must close the probe inside that contract + * rather than rejecting it, and must not leave the caller's listener behind. + */ + describe("scheduler boundary", () => { + const trackedSignal = () => { + const controller = new AbortController(); + const added: string[] = []; + const removed: string[] = []; + const add = controller.signal.addEventListener.bind(controller.signal); + const remove = controller.signal.removeEventListener.bind( + controller.signal, + ); + Object.defineProperty(controller.signal, "addEventListener", { + configurable: true, + value: (type: string, ...rest: readonly unknown[]) => { + added.push(type); + return (add as (...args: readonly unknown[]) => unknown)( + type, + ...rest, + ); + }, + }); + Object.defineProperty(controller.signal, "removeEventListener", { + configurable: true, + value: (type: string, ...rest: readonly unknown[]) => { + removed.push(type); + return (remove as (...args: readonly unknown[]) => unknown)( + type, + ...rest, + ); + }, + }); + return { controller, added, removed }; + }; + + it("closes the probe when the scheduler cannot install the deadline", async () => { + const fetcher = vi.fn(async () => new Response(null, { status: 200 })); + const { controller, added, removed } = trackedSignal(); + const probe = createBrowserImageProbe({ + fetcher: fetcher as unknown as typeof fetch, + createBitmap: vi.fn(), + timeoutMs: 1_000, + scheduler: { + setTimeout: () => { + throw new TypeError("image scheduler install exploded"); + }, + clearTimeout: vi.fn(), + }, + }); + + await expect( + probe.probe({ ...request(), signal: controller.signal }), + ).resolves.toMatchObject({ + ok: false, + error: { code: "UNAVAILABLE", retryable: true, recovery: "RETRY" }, + }); + expect(fetcher).not.toHaveBeenCalled(); + expect(added.filter((type) => type === "abort")).toHaveLength(1); + expect(removed.filter((type) => type === "abort")).toHaveLength(1); + }); + + it("starts no timer and no fetch for an already aborted caller", async () => { + const fetcher = vi.fn(async () => new Response(null, { status: 200 })); + const setTimeout_ = vi.fn(() => 1); + const controller = new AbortController(); + controller.abort(); + const probe = createBrowserImageProbe({ + fetcher: fetcher as unknown as typeof fetch, + createBitmap: vi.fn(), + timeoutMs: 1_000, + scheduler: { setTimeout: setTimeout_, clearTimeout: vi.fn() }, + }); + + await expect( + probe.probe({ ...request(), signal: controller.signal }), + ).resolves.toMatchObject({ ok: false, error: { code: "ABORTED" } }); + expect(fetcher).not.toHaveBeenCalled(); + expect(setTimeout_).not.toHaveBeenCalled(); + }); + + it("keeps the classified outcome when clearing the deadline throws", async () => { + const png = pngBytes(640, 360); + const probe = createBrowserImageProbe({ + fetcher: (async () => + responseAt(imageUrl, png, { + status: 200, + headers: publicImageHeaders("image/png", png.byteLength), + })) as typeof fetch, + createBitmap: vi.fn(async () => ({ + width: 640, + height: 360, + close: vi.fn(), + })), + timeoutMs: 1_000, + scheduler: { + setTimeout: (callback: () => void, milliseconds: number) => + setTimeout(callback, milliseconds), + clearTimeout: () => { + throw new TypeError("image scheduler clear exploded"); + }, + }, + }); + + await expect(probe.probe(request())).resolves.toMatchObject({ ok: true }); + }); + }); +}); diff --git a/tests/unit/image-cdn-capability-verifier.test.ts b/tests/unit/image-cdn-capability-verifier.test.ts new file mode 100644 index 0000000..81b36cc --- /dev/null +++ b/tests/unit/image-cdn-capability-verifier.test.ts @@ -0,0 +1,85 @@ +import { describe, expect, it } from "vitest"; + +import { createP256ImageCapabilityVerifier } from "../../src/adapters/browser-transfer/image-cdn/p256-image-capability-verifier.ts"; +import { base64Url } from "./image-cdn-test-fixture.ts"; + +describe("P-256 image capability verifier", () => { + it("rejects an ECDSA public key on any curve other than P-256", async () => { + const generated = await globalThis.crypto.subtle.generateKey( + { name: "ECDSA", namedCurve: "P-384" }, + false, + ["sign", "verify"], + ); + if (!("publicKey" in generated)) { + throw new TypeError("Expected an ECDSA key pair."); + } + expect(() => + createP256ImageCapabilityVerifier({ + subtle: globalThis.crypto.subtle, + publicKeys: [ + { + keyId: "image-signing-wrong-curve", + key: generated.publicKey, + }, + ], + }), + ).toThrow(/public key binding/u); + }); + + it("verifies the exact canonical payload and rejects tampering", async () => { + const generated = await globalThis.crypto.subtle.generateKey( + { name: "ECDSA", namedCurve: "P-256" }, + false, + ["sign", "verify"], + ); + if (!("privateKey" in generated)) { + throw new TypeError("Expected an ECDSA key pair."); + } + const payload = new TextEncoder().encode( + '["image-cdn-capability-v1","bound"]', + ); + const payloadBuffer = new Uint8Array(payload.byteLength); + payloadBuffer.set(payload); + const signature = await globalThis.crypto.subtle.sign( + { name: "ECDSA", hash: "SHA-256" }, + generated.privateKey, + payloadBuffer.buffer, + ); + const verifier = createP256ImageCapabilityVerifier({ + subtle: globalThis.crypto.subtle, + publicKeys: [ + { + keyId: "image-signing-2026-01", + key: generated.publicKey, + }, + ], + }); + expect(verifier.acceptsKey("image-signing-2026-01")).toBe( + true, + ); + expect(verifier.acceptsKey("image-signing-unknown")).toBe( + false, + ); + const signatureBase64Url = base64Url( + new Uint8Array(signature), + ); + await expect( + verifier.verify({ + algorithm: "ECDSA_P256_SHA256", + keyId: "image-signing-2026-01", + canonicalPayload: payload, + signatureBase64Url, + }), + ).resolves.toBe(true); + const tampered = Uint8Array.from(payload); + tampered[0] ^= 1; + await expect( + verifier.verify({ + algorithm: "ECDSA_P256_SHA256", + keyId: "image-signing-2026-01", + canonicalPayload: tampered, + signatureBase64Url, + }), + ).resolves.toBe(false); + }); +}); diff --git a/tests/unit/image-cdn-runtime.test.ts b/tests/unit/image-cdn-runtime.test.ts index e81305f..29590d0 100644 --- a/tests/unit/image-cdn-runtime.test.ts +++ b/tests/unit/image-cdn-runtime.test.ts @@ -7,10 +7,6 @@ import type { ImageProbeRequest, PublicImmutableImageAsset, } from "../../src/application/ports/browser-transfer/image-cdn.ts"; -import { - createBrowserImageProbe, - type ImageProbeScheduler, -} from "../../src/adapters/browser-transfer/image-cdn/browser-image-probe.ts"; import { IMAGE_CDN_IMPLEMENTATION_CEILINGS, ImageCdnPolicyRegistry, @@ -25,7 +21,6 @@ import { MAX_IMAGE_CAPABILITY_VERIFICATION_TIMEOUT_MS, type ImageCapabilityVerificationScheduler, } from "../../src/adapters/browser-transfer/image-cdn/image-cdn-runtime.ts"; -import { createP256ImageCapabilityVerifier } from "../../src/adapters/browser-transfer/image-cdn/p256-image-capability-verifier.ts"; const hardLimits: ImageCdnHardLimits = Object.freeze({ maxIntrinsicWidth: 4_096, @@ -179,6 +174,8 @@ async function privateAsset( }; } +import { manualCapabilityVerificationScheduler } from "./image-cdn-test-fixture.ts"; + describe("production image CDN runtime", () => { it("builds sorted, duplicate-free responsive candidates from a named preset", async () => { const preset = imageCdnPresetReference( @@ -1409,1022 +1406,3 @@ describe("production image CDN runtime", () => { ]); }); }); - -describe("browser image probe", () => { - const imageUrl = - "https://images.example.test/v1/assets/a/rev?format=png"; - const request = ( - overrides: Partial = {}, - ): ImageProbeRequest => ({ - absoluteUrl: imageUrl, - expectedMediaType: "image/png", - expectedWidth: 640, - expectedHeight: 360, - maxEncodedBytes: 1_024, - maxDecodedPixels: 230_400, - maxDecodedBytes: 921_600, - delivery: "PUBLIC_IMMUTABLE", - minimumPublicMaxAgeSeconds: 31_536_000, - referrerPolicy: "no-referrer", - signal: new AbortController().signal, - ...overrides, - }); - - it("parses all supported static headers before decode and closes each bitmap", async () => { - const samples = [ - { - mediaType: "image/png" as const, - bytes: pngBytes(640, 360), - }, - { - mediaType: "image/jpeg" as const, - bytes: jpegBytes(640, 360), - }, - { - mediaType: "image/webp" as const, - bytes: webpBytes(640, 360), - }, - { - mediaType: "image/avif" as const, - bytes: avifBytes(640, 360), - }, - ]; - const close = vi.fn(); - for (const sample of samples) { - const exactUrl = imageUrl.replace( - "format=png", - `format=${sample.mediaType.slice("image/".length)}`, - ); - const fetcher = vi.fn(async () => - responseAt(exactUrl, sample.bytes, { - status: 200, - headers: publicImageHeaders( - sample.mediaType, - sample.bytes.byteLength, - ), - }), - ); - const probe = createBrowserImageProbe({ - fetcher: fetcher as typeof fetch, - createBitmap: vi.fn(async () => ({ - width: 640, - height: 360, - close, - })), - }); - - await expect( - probe.probe( - request({ - absoluteUrl: exactUrl, - expectedMediaType: sample.mediaType, - }), - ), - ).resolves.toMatchObject({ - ok: true, - value: { - absoluteUrl: exactUrl, - mediaType: sample.mediaType, - encodedBytes: sample.bytes.byteLength, - decodedWidth: 640, - decodedHeight: 360, - }, - }); - expect(fetcher).toHaveBeenCalledWith( - exactUrl, - expect.objectContaining({ - credentials: "omit", - redirect: "error", - mode: "cors", - cache: "no-store", - referrerPolicy: "no-referrer", - }), - ); - } - expect(close).toHaveBeenCalledTimes(samples.length); - }); - - it("fails closed on duplicate/conflicting cache directives and oversized bodies", async () => { - const png = pngBytes(640, 360); - const createBitmap = vi.fn(async () => ({ - width: 640, - height: 360, - close: vi.fn(), - })); - for (const cacheControl of [ - // BT-IMG-02. Unmatched quotes must not be unwrapped into a bare number. - 'public, max-age="31536000, immutable', - 'public, max-age=31536000", immutable', - 'public, max-age="31536000\\", immutable', - "public, public, max-age=31536000, immutable", - "public, max-age=31536000, s-maxage=60, immutable", - "public, max-age=31536000, immutable, must-revalidate", - "public=1, max-age=31536000, immutable", - "public, max-age=31536000, immutable=true", - ]) { - const probe = createBrowserImageProbe({ - fetcher: (async () => - responseAt(imageUrl, png, { - status: 200, - headers: { - "cache-control": cacheControl, - "content-type": "image/png", - }, - })) as typeof fetch, - createBitmap, - }); - await expect(probe.probe(request())).resolves.toMatchObject({ - ok: false, - error: { code: "POLICY_REJECTED" }, - }); - } - - const probe = createBrowserImageProbe({ - fetcher: (async () => - responseAt(imageUrl, new Uint8Array(2_048), { - status: 200, - headers: { - "cache-control": - "public, max-age=31536000, immutable", - "content-type": "image/png", - }, - })) as typeof fetch, - createBitmap, - }); - await expect(probe.probe(request())).resolves.toMatchObject({ - ok: false, - error: { code: "LIMIT_EXCEEDED" }, - }); - expect(createBitmap).not.toHaveBeenCalled(); - }); - - it("rejects non-identity content encoding and mismatched declared lengths", async () => { - const png = pngBytes(640, 360); - const createBitmap = vi.fn(); - const cases = [ - { - headers: { - "content-encoding": "gzip", - "content-length": String(png.byteLength), - }, - code: "POLICY_REJECTED", - }, - { - headers: { - "content-length": String(png.byteLength + 1), - }, - code: "INTEGRITY_FAILED", - }, - ]; - for (const invalid of cases) { - const headers = publicImageHeaders("image/png"); - for (const [name, value] of Object.entries(invalid.headers)) { - headers.set(name, value); - } - const probe = createBrowserImageProbe({ - fetcher: (async () => - responseAt(imageUrl, png, { - status: 200, - headers, - })) as typeof fetch, - createBitmap, - }); - await expect(probe.probe(request())).resolves.toMatchObject({ - ok: false, - error: { code: invalid.code }, - }); - } - expect(createBitmap).not.toHaveBeenCalled(); - }); - - it("rejects malicious dimensions and animated PNG/WebP before native decode", async () => { - const createBitmap = vi.fn(async () => ({ - width: 640, - height: 360, - close: vi.fn(), - })); - const cases = [ - { - bytes: pngBytes(20_000, 20_000), - mediaType: "image/png" as const, - code: "LIMIT_EXCEEDED", - }, - { - bytes: pngBytes(320, 180), - mediaType: "image/png" as const, - code: "INTEGRITY_FAILED", - }, - { - bytes: jpegBytes(320, 180), - mediaType: "image/jpeg" as const, - code: "INTEGRITY_FAILED", - }, - { - bytes: webpBytes(10_000, 10_000), - mediaType: "image/webp" as const, - code: "LIMIT_EXCEEDED", - }, - { - bytes: avifBytes(20_000, 20_000), - mediaType: "image/avif" as const, - code: "LIMIT_EXCEEDED", - }, - { - bytes: pngBytes(640, 360, true), - mediaType: "image/png" as const, - code: "INTEGRITY_FAILED", - }, - { - bytes: webpBytes(640, 360, true), - mediaType: "image/webp" as const, - code: "INTEGRITY_FAILED", - }, - { - bytes: avifBytes(640, 360, "avis"), - mediaType: "image/avif" as const, - code: "INTEGRITY_FAILED", - }, - ]; - for (const malicious of cases) { - const url = imageUrl.replace( - "format=png", - `format=${malicious.mediaType.slice("image/".length)}`, - ); - const probe = createBrowserImageProbe({ - fetcher: (async () => - responseAt(url, malicious.bytes, { - status: 200, - headers: publicImageHeaders( - malicious.mediaType, - malicious.bytes.byteLength, - ), - })) as typeof fetch, - createBitmap, - }); - await expect( - probe.probe( - request({ - absoluteUrl: url, - expectedMediaType: malicious.mediaType, - }), - ), - ).resolves.toMatchObject({ - ok: false, - error: { code: malicious.code }, - }); - } - expect(createBitmap).not.toHaveBeenCalled(); - }); - - it("enforces private no-store, omitted credentials and the exact final URL", async () => { - const png = pngBytes(640, 360); - const fetcher = vi.fn(async () => - responseAt(imageUrl, png, { - status: 200, - headers: { - // TR-RR-09. A private response carries `no-store` and nothing else - // that describes cacheability. - "cache-control": "no-store", - "content-type": "image/png", - }, - }), - ); - const probe = createBrowserImageProbe({ - fetcher: fetcher as typeof fetch, - createBitmap: async () => ({ - width: 640, - height: 360, - close: vi.fn(), - }), - }); - await expect( - probe.probe( - request({ - delivery: "PRIVATE_SIGNED", - minimumPublicMaxAgeSeconds: 0, - }), - ), - ).resolves.toMatchObject({ ok: true }); - expect(fetcher).toHaveBeenCalledWith( - imageUrl, - expect.objectContaining({ - cache: "no-store", - credentials: "omit", - redirect: "error", - }), - ); - - for (const response of [ - responseAt(imageUrl, png, { - status: 200, - headers: { - "cache-control": "private, no-store=value", - "content-type": "image/png", - }, - }), - responseAt(imageUrl, png, { - status: 200, - headers: { - "cache-control": "public, no-store", - "content-type": "image/png", - }, - }), - responseAt( - "https://images.example.test/v1/assets/other", - png, - { - status: 200, - headers: { - "cache-control": "private, no-store", - "content-type": "image/png", - }, - }, - ), - ]) { - const rejectingProbe = createBrowserImageProbe({ - fetcher: (async () => response) as typeof fetch, - createBitmap: async () => ({ - width: 640, - height: 360, - close: vi.fn(), - }), - }); - await expect( - rejectingProbe.probe( - request({ - delivery: "PRIVATE_SIGNED", - minimumPublicMaxAgeSeconds: 0, - }), - ), - ).resolves.toMatchObject({ - ok: false, - error: { code: "POLICY_REJECTED" }, - }); - } - - await expect( - probe.probe( - request({ - expectedMediaType: "image/svg+xml", - } as unknown as Partial), - ), - ).resolves.toMatchObject({ - ok: false, - error: { code: "POLICY_REJECTED" }, - }); - }); - - /** - * TR-RR-09. The recorded BT-IMG-02 contract for a private response is a - * fail-closed matrix. Accepting `no-store` next to a directive that describes - * cacheability lets a self-contradictory policy read as acceptable. - */ - it("applies the full private Cache-Control matrix", async () => { - const png = pngBytes(640, 360); - const probeWith = async (cacheControl: string) => { - const probe = createBrowserImageProbe({ - fetcher: (async () => - responseAt(imageUrl, png, { - status: 200, - headers: { - "cache-control": cacheControl, - "content-type": "image/png", - }, - })) as typeof fetch, - createBitmap: async () => ({ - width: 640, - height: 360, - close: vi.fn(), - }), - }); - return await probe.probe( - request({ - delivery: "PRIVATE_SIGNED", - minimumPublicMaxAgeSeconds: 0, - }), - ); - }; - - // Only `no-store`, plus a syntactically valid unknown extension. - expect(await probeWith("no-store")).toMatchObject({ ok: true }); - expect(await probeWith('no-store, x-vendor="a,b"')).toMatchObject({ - ok: true, - }); - - for (const companion of [ - "public", - "private", - "immutable", - "max-age=60", - "s-maxage=60", - "no-cache", - "must-revalidate", - "proxy-revalidate", - ]) { - expect(await probeWith(`no-store, ${companion}`)).toMatchObject({ - ok: false, - error: { code: "POLICY_REJECTED" }, - }); - } - - for (const withoutNoStore of ["private", "no-cache", "max-age=0"]) { - expect(await probeWith(withoutNoStore)).toMatchObject({ - ok: false, - error: { code: "POLICY_REJECTED" }, - }); - } - }); - - it("times out a stalled body, aborts the composed signal and cancels its reader", async () => { - const manual = manualImageProbeScheduler(); - const cancel = vi.fn(async () => undefined); - const releaseLock = vi.fn(); - const read = vi.fn( - () => - new Promise>( - () => undefined, - ), - ); - const response = { - body: { - getReader: () => ({ cancel, read, releaseLock }), - }, - headers: publicImageHeaders("image/png"), - ok: true, - redirected: false, - status: 200, - type: "cors", - url: imageUrl, - } as unknown as Response; - const fetcher = vi.fn( - async (_input: RequestInfo | URL, _init?: RequestInit) => - response, - ); - const probe = createBrowserImageProbe({ - fetcher: fetcher as typeof fetch, - createBitmap: vi.fn(), - timeoutMs: 1_000, - scheduler: manual.scheduler, - }); - const probeRequest = request(); - const pending = probe.probe(probeRequest); - await vi.waitFor(() => { - expect(read).toHaveBeenCalledOnce(); - }); - const composedSignal = fetcher.mock.calls[0]?.[1]?.signal as - | AbortSignal - | null - | undefined; - expect(composedSignal).not.toBe(probeRequest.signal); - manual.fire(); - - await expect(pending).resolves.toMatchObject({ - ok: false, - error: { - code: "UNAVAILABLE", - retryable: true, - recovery: "RETRY", - }, - }); - expect(cancel).toHaveBeenCalledOnce(); - expect(releaseLock).toHaveBeenCalledOnce(); - expect(composedSignal?.aborted).toBe(true); - }); - - it("times out stalled decode and closes a bitmap that resolves late", async () => { - const manual = manualImageProbeScheduler(); - const close = vi.fn(); - let finishDecode: - ((bitmap: { - width: number; - height: number; - close(): void; - }) => void) | undefined; - const createBitmap = vi.fn( - () => - new Promise<{ - width: number; - height: number; - close(): void; - }>((resolve) => { - finishDecode = resolve; - }), - ); - const png = pngBytes(640, 360); - const probe = createBrowserImageProbe({ - fetcher: (async () => - responseAt(imageUrl, png, { - status: 200, - headers: publicImageHeaders("image/png", png.byteLength), - })) as typeof fetch, - createBitmap, - timeoutMs: 1_000, - scheduler: manual.scheduler, - }); - const pending = probe.probe(request()); - await vi.waitFor(() => { - expect(createBitmap).toHaveBeenCalledOnce(); - }); - manual.fire(); - await expect(pending).resolves.toMatchObject({ - ok: false, - error: { code: "UNAVAILABLE" }, - }); - - finishDecode?.({ width: 640, height: 360, close }); - await vi.waitFor(() => { - expect(close).toHaveBeenCalledOnce(); - }); - }); - - /** - * X-AUDIT-02. `probe()` promises a `BrowserDataResult`. A scheduler that - * cannot install the probe deadline must close the probe inside that contract - * rather than rejecting it, and must not leave the caller's listener behind. - */ - describe("scheduler boundary", () => { - const trackedSignal = () => { - const controller = new AbortController(); - const added: string[] = []; - const removed: string[] = []; - const add = controller.signal.addEventListener.bind(controller.signal); - const remove = controller.signal.removeEventListener.bind( - controller.signal, - ); - Object.defineProperty(controller.signal, "addEventListener", { - configurable: true, - value: (type: string, ...rest: readonly unknown[]) => { - added.push(type); - return (add as (...args: readonly unknown[]) => unknown)( - type, - ...rest, - ); - }, - }); - Object.defineProperty(controller.signal, "removeEventListener", { - configurable: true, - value: (type: string, ...rest: readonly unknown[]) => { - removed.push(type); - return (remove as (...args: readonly unknown[]) => unknown)( - type, - ...rest, - ); - }, - }); - return { controller, added, removed }; - }; - - it("closes the probe when the scheduler cannot install the deadline", async () => { - const fetcher = vi.fn(async () => new Response(null, { status: 200 })); - const { controller, added, removed } = trackedSignal(); - const probe = createBrowserImageProbe({ - fetcher: fetcher as unknown as typeof fetch, - createBitmap: vi.fn(), - timeoutMs: 1_000, - scheduler: { - setTimeout: () => { - throw new TypeError("image scheduler install exploded"); - }, - clearTimeout: vi.fn(), - }, - }); - - await expect( - probe.probe({ ...request(), signal: controller.signal }), - ).resolves.toMatchObject({ - ok: false, - error: { code: "UNAVAILABLE", retryable: true, recovery: "RETRY" }, - }); - expect(fetcher).not.toHaveBeenCalled(); - expect(added.filter((type) => type === "abort")).toHaveLength(1); - expect(removed.filter((type) => type === "abort")).toHaveLength(1); - }); - - it("starts no timer and no fetch for an already aborted caller", async () => { - const fetcher = vi.fn(async () => new Response(null, { status: 200 })); - const setTimeout_ = vi.fn(() => 1); - const controller = new AbortController(); - controller.abort(); - const probe = createBrowserImageProbe({ - fetcher: fetcher as unknown as typeof fetch, - createBitmap: vi.fn(), - timeoutMs: 1_000, - scheduler: { setTimeout: setTimeout_, clearTimeout: vi.fn() }, - }); - - await expect( - probe.probe({ ...request(), signal: controller.signal }), - ).resolves.toMatchObject({ ok: false, error: { code: "ABORTED" } }); - expect(fetcher).not.toHaveBeenCalled(); - expect(setTimeout_).not.toHaveBeenCalled(); - }); - - it("keeps the classified outcome when clearing the deadline throws", async () => { - const png = pngBytes(640, 360); - const probe = createBrowserImageProbe({ - fetcher: (async () => - responseAt(imageUrl, png, { - status: 200, - headers: publicImageHeaders("image/png", png.byteLength), - })) as typeof fetch, - createBitmap: vi.fn(async () => ({ - width: 640, - height: 360, - close: vi.fn(), - })), - timeoutMs: 1_000, - scheduler: { - setTimeout: (callback: () => void, milliseconds: number) => - setTimeout(callback, milliseconds), - clearTimeout: () => { - throw new TypeError("image scheduler clear exploded"); - }, - }, - }); - - await expect(probe.probe(request())).resolves.toMatchObject({ ok: true }); - }); - }); -}); - -describe("P-256 image capability verifier", () => { - it("rejects an ECDSA public key on any curve other than P-256", async () => { - const generated = await globalThis.crypto.subtle.generateKey( - { name: "ECDSA", namedCurve: "P-384" }, - false, - ["sign", "verify"], - ); - if (!("publicKey" in generated)) { - throw new TypeError("Expected an ECDSA key pair."); - } - expect(() => - createP256ImageCapabilityVerifier({ - subtle: globalThis.crypto.subtle, - publicKeys: [ - { - keyId: "image-signing-wrong-curve", - key: generated.publicKey, - }, - ], - }), - ).toThrow(/public key binding/u); - }); - - it("verifies the exact canonical payload and rejects tampering", async () => { - const generated = await globalThis.crypto.subtle.generateKey( - { name: "ECDSA", namedCurve: "P-256" }, - false, - ["sign", "verify"], - ); - if (!("privateKey" in generated)) { - throw new TypeError("Expected an ECDSA key pair."); - } - const payload = new TextEncoder().encode( - '["image-cdn-capability-v1","bound"]', - ); - const payloadBuffer = new Uint8Array(payload.byteLength); - payloadBuffer.set(payload); - const signature = await globalThis.crypto.subtle.sign( - { name: "ECDSA", hash: "SHA-256" }, - generated.privateKey, - payloadBuffer.buffer, - ); - const verifier = createP256ImageCapabilityVerifier({ - subtle: globalThis.crypto.subtle, - publicKeys: [ - { - keyId: "image-signing-2026-01", - key: generated.publicKey, - }, - ], - }); - expect(verifier.acceptsKey("image-signing-2026-01")).toBe( - true, - ); - expect(verifier.acceptsKey("image-signing-unknown")).toBe( - false, - ); - const signatureBase64Url = base64Url( - new Uint8Array(signature), - ); - await expect( - verifier.verify({ - algorithm: "ECDSA_P256_SHA256", - keyId: "image-signing-2026-01", - canonicalPayload: payload, - signatureBase64Url, - }), - ).resolves.toBe(true); - const tampered = Uint8Array.from(payload); - tampered[0] ^= 1; - await expect( - verifier.verify({ - algorithm: "ECDSA_P256_SHA256", - keyId: "image-signing-2026-01", - canonicalPayload: tampered, - signatureBase64Url, - }), - ).resolves.toBe(false); - }); -}); - -function responseAt( - url: string, - body: Uint8Array, - init: ResponseInit, -): Response { - const responseBytes = new Uint8Array(body.byteLength); - responseBytes.set(body); - const response = new Response(responseBytes.buffer, init); - Object.defineProperty(response, "url", { - configurable: false, - enumerable: true, - value: url, - }); - return response; -} - -function publicImageHeaders( - mediaType: string, - contentLength?: number, -): Headers { - const headers = new Headers({ - "cache-control": - "public, max-age=31536000, s-maxage=31536000, immutable", - "content-type": mediaType, - vary: "Accept-Encoding", - }); - if (contentLength !== undefined) { - headers.set("content-length", String(contentLength)); - } - return headers; -} - -function pngBytes( - width: number, - height: number, - animated = false, -): Uint8Array { - const header = new Uint8Array(13); - const headerView = new DataView(header.buffer); - headerView.setUint32(0, width); - headerView.setUint32(4, height); - header[8] = 8; - header[9] = 6; - return concatenateBytes([ - Uint8Array.from([ - 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, - ]), - pngChunk("IHDR", header), - ...(animated - ? [pngChunk("acTL", new Uint8Array(8))] - : []), - pngChunk("IDAT", new Uint8Array()), - pngChunk("IEND", new Uint8Array()), - ]); -} - -function pngChunk(type: string, payload: Uint8Array): Uint8Array { - const chunk = new Uint8Array(12 + payload.byteLength); - const view = new DataView(chunk.buffer); - view.setUint32(0, payload.byteLength); - writeAscii(chunk, 4, type); - chunk.set(payload, 8); - return chunk; -} - -function jpegBytes(width: number, height: number): Uint8Array { - return Uint8Array.from([ - 0xff, - 0xd8, - 0xff, - 0xc0, - 0x00, - 0x11, - 0x08, - (height >>> 8) & 0xff, - height & 0xff, - (width >>> 8) & 0xff, - width & 0xff, - 0x03, - 0x01, - 0x11, - 0x00, - 0x02, - 0x11, - 0x00, - 0x03, - 0x11, - 0x00, - 0xff, - 0xda, - ]); -} - -function webpBytes( - width: number, - height: number, - animated = false, -): Uint8Array { - const chunkType = animated ? "VP8X" : "VP8 "; - const payload = new Uint8Array(10); - if (animated) { - payload[0] = 0x02; - writeUint24LittleEndian(payload, 4, width - 1); - writeUint24LittleEndian(payload, 7, height - 1); - } else { - payload.set([0x9d, 0x01, 0x2a], 3); - const view = new DataView(payload.buffer); - view.setUint16(6, width, true); - view.setUint16(8, height, true); - } - const chunk = concatenateBytes([ - asciiBytes(chunkType), - littleEndianUint32(payload.byteLength), - payload, - ]); - return concatenateBytes([ - asciiBytes("RIFF"), - littleEndianUint32(4 + chunk.byteLength), - asciiBytes("WEBP"), - chunk, - ]); -} - -function avifBytes( - width: number, - height: number, - brand = "avif", -): Uint8Array { - const fileType = isoBox( - "ftyp", - concatenateBytes([ - asciiBytes(brand), - new Uint8Array(4), - asciiBytes(brand), - ]), - ); - const spatialExtent = new Uint8Array(12); - const extentView = new DataView(spatialExtent.buffer); - extentView.setUint32(4, width); - extentView.setUint32(8, height); - const primaryItem = new Uint8Array(6); - new DataView(primaryItem.buffer).setUint16(4, 1); - const itemInfoEntry = new Uint8Array(13); - itemInfoEntry[0] = 2; - const itemInfoView = new DataView(itemInfoEntry.buffer); - itemInfoView.setUint16(4, 1); - writeAscii(itemInfoEntry, 8, "av01"); - const itemInfo = new Uint8Array(6); - new DataView(itemInfo.buffer).setUint16(4, 1); - const propertyAssociation = new Uint8Array(12); - const associationView = new DataView( - propertyAssociation.buffer, - ); - associationView.setUint32(4, 1); - associationView.setUint16(8, 1); - propertyAssociation[10] = 1; - propertyAssociation[11] = 0x81; - const properties = isoBox( - "iprp", - concatenateBytes([ - isoBox("ipco", isoBox("ispe", spatialExtent)), - isoBox("ipma", propertyAssociation), - ]), - ); - const metadata = isoBox( - "meta", - concatenateBytes([ - new Uint8Array(4), - isoBox("pitm", primaryItem), - isoBox( - "iinf", - concatenateBytes([ - itemInfo, - isoBox("infe", itemInfoEntry), - ]), - ), - properties, - ]), - ); - return concatenateBytes([ - fileType, - metadata, - isoBox("mdat", Uint8Array.of(0)), - ]); -} - -function isoBox(type: string, payload: Uint8Array): Uint8Array { - const box = new Uint8Array(8 + payload.byteLength); - const view = new DataView(box.buffer); - view.setUint32(0, box.byteLength); - writeAscii(box, 4, type); - box.set(payload, 8); - return box; -} - -function littleEndianUint32(value: number): Uint8Array { - const bytes = new Uint8Array(4); - new DataView(bytes.buffer).setUint32(0, value, true); - return bytes; -} - -function writeUint24LittleEndian( - bytes: Uint8Array, - offset: number, - value: number, -): void { - bytes[offset] = value & 0xff; - bytes[offset + 1] = (value >>> 8) & 0xff; - bytes[offset + 2] = (value >>> 16) & 0xff; -} - -function asciiBytes(value: string): Uint8Array { - return Uint8Array.from( - [...value].map((character) => character.charCodeAt(0)), - ); -} - -function writeAscii( - target: Uint8Array, - offset: number, - value: string, -): void { - target.set(asciiBytes(value), offset); -} - -function concatenateBytes( - chunks: readonly Uint8Array[], -): Uint8Array { - const combined = new Uint8Array( - chunks.reduce((total, chunk) => total + chunk.byteLength, 0), - ); - let offset = 0; - for (const chunk of chunks) { - combined.set(chunk, offset); - offset += chunk.byteLength; - } - return combined; -} - -function manualImageProbeScheduler(): Readonly<{ - scheduler: ImageProbeScheduler; - fire(): void; -}> { - let callback: (() => void) | undefined; - return { - scheduler: { - setTimeout(nextCallback) { - callback = nextCallback; - return 1; - }, - clearTimeout: vi.fn(), - }, - fire() { - if (!callback) { - throw new TypeError("No image probe timeout is scheduled."); - } - callback(); - }, - }; -} - -function manualCapabilityVerificationScheduler(): Readonly<{ - scheduler: ImageCapabilityVerificationScheduler; - delays: readonly number[]; - clearTimeout: ReturnType; - fire(): void; -}> { - let callback: (() => void) | undefined; - const delays: number[] = []; - const clearTimeout = vi.fn(); - return { - scheduler: { - setTimeout(nextCallback, milliseconds) { - callback = nextCallback; - delays.push(milliseconds); - return 1; - }, - clearTimeout, - }, - delays, - clearTimeout, - fire() { - if (!callback) { - throw new TypeError( - "No capability verification timeout is scheduled.", - ); - } - callback(); - }, - }; -} - -function base64Url(bytes: Uint8Array): string { - let binary = ""; - for (const byte of bytes) binary += String.fromCharCode(byte); - return btoa(binary) - .replace(/\+/gu, "-") - .replace(/\//gu, "_") - .replace(/=+$/gu, ""); -} diff --git a/tests/unit/image-cdn-test-fixture.ts b/tests/unit/image-cdn-test-fixture.ts new file mode 100644 index 0000000..7999c26 --- /dev/null +++ b/tests/unit/image-cdn-test-fixture.ts @@ -0,0 +1,309 @@ +import { vi } from "vitest"; + +import type { + ImageProbeScheduler, +} from "../../src/adapters/browser-transfer/image-cdn/browser-image-probe.ts"; +import type { + ImageCapabilityVerificationScheduler, +} from "../../src/adapters/browser-transfer/image-cdn/image-cdn-runtime.ts"; + +export function responseAt( + url: string, + body: Uint8Array, + init: ResponseInit, +): Response { + const responseBytes = new Uint8Array(body.byteLength); + responseBytes.set(body); + const response = new Response(responseBytes.buffer, init); + Object.defineProperty(response, "url", { + configurable: false, + enumerable: true, + value: url, + }); + return response; +} + +export function publicImageHeaders( + mediaType: string, + contentLength?: number, +): Headers { + const headers = new Headers({ + "cache-control": + "public, max-age=31536000, s-maxage=31536000, immutable", + "content-type": mediaType, + vary: "Accept-Encoding", + }); + if (contentLength !== undefined) { + headers.set("content-length", String(contentLength)); + } + return headers; +} + +export function pngBytes( + width: number, + height: number, + animated = false, +): Uint8Array { + const header = new Uint8Array(13); + const headerView = new DataView(header.buffer); + headerView.setUint32(0, width); + headerView.setUint32(4, height); + header[8] = 8; + header[9] = 6; + return concatenateBytes([ + Uint8Array.from([ + 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, + ]), + pngChunk("IHDR", header), + ...(animated + ? [pngChunk("acTL", new Uint8Array(8))] + : []), + pngChunk("IDAT", new Uint8Array()), + pngChunk("IEND", new Uint8Array()), + ]); +} + +function pngChunk(type: string, payload: Uint8Array): Uint8Array { + const chunk = new Uint8Array(12 + payload.byteLength); + const view = new DataView(chunk.buffer); + view.setUint32(0, payload.byteLength); + writeAscii(chunk, 4, type); + chunk.set(payload, 8); + return chunk; +} + +export function jpegBytes(width: number, height: number): Uint8Array { + return Uint8Array.from([ + 0xff, + 0xd8, + 0xff, + 0xc0, + 0x00, + 0x11, + 0x08, + (height >>> 8) & 0xff, + height & 0xff, + (width >>> 8) & 0xff, + width & 0xff, + 0x03, + 0x01, + 0x11, + 0x00, + 0x02, + 0x11, + 0x00, + 0x03, + 0x11, + 0x00, + 0xff, + 0xda, + ]); +} + +export function webpBytes( + width: number, + height: number, + animated = false, +): Uint8Array { + const chunkType = animated ? "VP8X" : "VP8 "; + const payload = new Uint8Array(10); + if (animated) { + payload[0] = 0x02; + writeUint24LittleEndian(payload, 4, width - 1); + writeUint24LittleEndian(payload, 7, height - 1); + } else { + payload.set([0x9d, 0x01, 0x2a], 3); + const view = new DataView(payload.buffer); + view.setUint16(6, width, true); + view.setUint16(8, height, true); + } + const chunk = concatenateBytes([ + asciiBytes(chunkType), + littleEndianUint32(payload.byteLength), + payload, + ]); + return concatenateBytes([ + asciiBytes("RIFF"), + littleEndianUint32(4 + chunk.byteLength), + asciiBytes("WEBP"), + chunk, + ]); +} + +export function avifBytes( + width: number, + height: number, + brand = "avif", +): Uint8Array { + const fileType = isoBox( + "ftyp", + concatenateBytes([ + asciiBytes(brand), + new Uint8Array(4), + asciiBytes(brand), + ]), + ); + const spatialExtent = new Uint8Array(12); + const extentView = new DataView(spatialExtent.buffer); + extentView.setUint32(4, width); + extentView.setUint32(8, height); + const primaryItem = new Uint8Array(6); + new DataView(primaryItem.buffer).setUint16(4, 1); + const itemInfoEntry = new Uint8Array(13); + itemInfoEntry[0] = 2; + const itemInfoView = new DataView(itemInfoEntry.buffer); + itemInfoView.setUint16(4, 1); + writeAscii(itemInfoEntry, 8, "av01"); + const itemInfo = new Uint8Array(6); + new DataView(itemInfo.buffer).setUint16(4, 1); + const propertyAssociation = new Uint8Array(12); + const associationView = new DataView( + propertyAssociation.buffer, + ); + associationView.setUint32(4, 1); + associationView.setUint16(8, 1); + propertyAssociation[10] = 1; + propertyAssociation[11] = 0x81; + const properties = isoBox( + "iprp", + concatenateBytes([ + isoBox("ipco", isoBox("ispe", spatialExtent)), + isoBox("ipma", propertyAssociation), + ]), + ); + const metadata = isoBox( + "meta", + concatenateBytes([ + new Uint8Array(4), + isoBox("pitm", primaryItem), + isoBox( + "iinf", + concatenateBytes([ + itemInfo, + isoBox("infe", itemInfoEntry), + ]), + ), + properties, + ]), + ); + return concatenateBytes([ + fileType, + metadata, + isoBox("mdat", Uint8Array.of(0)), + ]); +} + +export function isoBox(type: string, payload: Uint8Array): Uint8Array { + const box = new Uint8Array(8 + payload.byteLength); + const view = new DataView(box.buffer); + view.setUint32(0, box.byteLength); + writeAscii(box, 4, type); + box.set(payload, 8); + return box; +} + +export function littleEndianUint32(value: number): Uint8Array { + const bytes = new Uint8Array(4); + new DataView(bytes.buffer).setUint32(0, value, true); + return bytes; +} + +export function writeUint24LittleEndian( + bytes: Uint8Array, + offset: number, + value: number, +): void { + bytes[offset] = value & 0xff; + bytes[offset + 1] = (value >>> 8) & 0xff; + bytes[offset + 2] = (value >>> 16) & 0xff; +} + +export function asciiBytes(value: string): Uint8Array { + return Uint8Array.from( + [...value].map((character) => character.charCodeAt(0)), + ); +} + +export function writeAscii( + target: Uint8Array, + offset: number, + value: string, +): void { + target.set(asciiBytes(value), offset); +} + +export function concatenateBytes( + chunks: readonly Uint8Array[], +): Uint8Array { + const combined = new Uint8Array( + chunks.reduce((total, chunk) => total + chunk.byteLength, 0), + ); + let offset = 0; + for (const chunk of chunks) { + combined.set(chunk, offset); + offset += chunk.byteLength; + } + return combined; +} + +export function manualImageProbeScheduler(): Readonly<{ + scheduler: ImageProbeScheduler; + fire(): void; +}> { + let callback: (() => void) | undefined; + return { + scheduler: { + setTimeout(nextCallback) { + callback = nextCallback; + return 1; + }, + clearTimeout: vi.fn(), + }, + fire() { + if (!callback) { + throw new TypeError("No image probe timeout is scheduled."); + } + callback(); + }, + }; +} + +export function manualCapabilityVerificationScheduler(): Readonly<{ + scheduler: ImageCapabilityVerificationScheduler; + delays: readonly number[]; + clearTimeout: ReturnType; + fire(): void; +}> { + let callback: (() => void) | undefined; + const delays: number[] = []; + const clearTimeout = vi.fn(); + return { + scheduler: { + setTimeout(nextCallback, milliseconds) { + callback = nextCallback; + delays.push(milliseconds); + return 1; + }, + clearTimeout, + }, + delays, + clearTimeout, + fire() { + if (!callback) { + throw new TypeError( + "No capability verification timeout is scheduled.", + ); + } + callback(); + }, + }; +} + +export function base64Url(bytes: Uint8Array): string { + let binary = ""; + for (const byte of bytes) binary += String.fromCharCode(byte); + return btoa(binary) + .replace(/\+/gu, "-") + .replace(/\//gu, "_") + .replace(/=+$/gu, ""); +} diff --git a/tests/unit/indexeddb-connection.test.ts b/tests/unit/indexeddb-connection.test.ts new file mode 100644 index 0000000..068c59c --- /dev/null +++ b/tests/unit/indexeddb-connection.test.ts @@ -0,0 +1,886 @@ +import { describe, expect, it, vi } from "vitest"; + +import { + createIndexedDbConnection, + deleteIndexedDbDatabase, + openIndexedDbDatabase, + type IndexedDbFailureCause, + type IndexedDbTranslate, +} from "../../src/adapters/platform/indexeddb-connection.ts"; +import { MemoryIndexedDbFactory } from "../helpers/memory-indexeddb.ts"; + +/** + * IDB-X-01 golden tests. The kernel owns connection mechanics only: it must + * never name an operation label, a failure code or a schema. Every assertion + * below reads the cause the kernel reported, not a taxonomy it chose. + */ + +type TestFailure = Readonly<{ cause: IndexedDbFailureCause["kind"]; detail?: unknown }>; + +/** + * A `translate` written as a total switch over the union. This is the extension + * point `abortable-operation.ts:11` lacked: adding a cause member breaks every + * translate at compile time instead of silently changing behavior, and the + * union never appears in a return type. + */ +function recordingTranslate( + seen: IndexedDbFailureCause["kind"][], +): IndexedDbTranslate { + return (cause) => { + seen.push(cause.kind); + switch (cause.kind) { + case "NATIVE_EXCEPTION": + return { cause: cause.kind, detail: cause.error }; + case "BLOCKED": + return { + cause: cause.kind, + detail: { oldVersion: cause.oldVersion, newVersion: cause.newVersion }, + }; + case "BLOCKED_DEADLINE": + case "CALLER_ABORT": + case "CLOSED": + case "NO_VALUE_PRODUCED": + case "UNSUPPORTED": + return { cause: cause.kind }; + case "UPGRADE_REJECTED": + return { cause: cause.kind, detail: cause.detail }; + case "ADMISSION_REJECTED": + return { cause: cause.kind, detail: cause.detail }; + default: { + const exhaustive: never = cause; + return exhaustive; + } + } + }; +} + +function manualTimers(): Readonly<{ + snapshot: Readonly<{ + setTimer: (callback: () => void, delayMs: number) => unknown; + clearTimer: (handle: unknown) => void; + }>; + pending: Array void; delayMs: number }>>; + cleared: unknown[]; +}> { + const pending: Array void; delayMs: number }>> = []; + const cleared: unknown[] = []; + return { + pending, + cleared, + snapshot: { + setTimer: (callback, delayMs) => { + pending.push({ callback, delayMs }); + return pending.length; + }, + clearTimer: (handle) => { + cleared.push(handle); + }, + }, + }; +} + +async function flush(): Promise { + for (let attempt = 0; attempt < 30; attempt += 1) { + await new Promise((resolve) => { + globalThis.setTimeout(resolve, 0); + }); + } +} + +type StubOpenRequest = { + result: IDBDatabase; + error: DOMException | null; + transaction: IDBTransaction | null; + onsuccess: ((event: Event) => unknown) | null; + onerror: ((event: Event) => unknown) | null; + onblocked: ((event: IDBVersionChangeEvent) => unknown) | null; + onupgradeneeded: ((event: IDBVersionChangeEvent) => unknown) | null; +}; + +type StubFactory = Readonly<{ + factory: IDBFactory; + opened: StubOpenRequest[]; + deleted: StubOpenRequest[]; +}>; + +/** + * The memory fake models a real database. These stubs model only the request + * object, so paths the fake cannot reach — a null `newVersion`, a cancellable + * upgrade transaction, `deleteDatabase` — are still exercised. + */ +function stubFactory(): StubFactory { + const opened: StubOpenRequest[] = []; + const deleted: StubOpenRequest[] = []; + const request = (): StubOpenRequest => ({ + result: { close: vi.fn() } as unknown as IDBDatabase, + error: null, + transaction: null, + onsuccess: null, + onerror: null, + onblocked: null, + onupgradeneeded: null, + }); + return { + opened, + deleted, + factory: { + open: () => { + const next = request(); + opened.push(next); + return next as unknown as IDBOpenDBRequest; + }, + deleteDatabase: () => { + const next = request(); + deleted.push(next); + return next as unknown as IDBOpenDBRequest; + }, + } as unknown as IDBFactory, + }; +} + +function versionChangeEvent( + oldVersion: number, + newVersion: number | null, +): IDBVersionChangeEvent { + return { oldVersion, newVersion } as IDBVersionChangeEvent; +} + +describe("shared IndexedDB connection mechanics", () => { + it("opens a database and hands the caller the live connection", async () => { + const memory = new MemoryIndexedDbFactory(); + const seen: IndexedDbFailureCause["kind"][] = []; + + const result = await openIndexedDbDatabase({ + factory: memory.factory, + databaseName: "kernel", + version: 1, + translate: recordingTranslate(seen), + upgrade: ({ database }) => { + database.createObjectStore("rows", { keyPath: "id" }); + return { kind: "APPLIED" }; + }, + }); + + expect(result.ok).toBe(true); + if (!result.ok) return; + expect(result.value.version).toBe(1); + expect(memory.hasStore("rows")).toBe(true); + expect(seen).toEqual([]); + }); + + it("reports a native throw from the factory as NATIVE_EXCEPTION", async () => { + const boom = new Error("no factory"); + const result = await openIndexedDbDatabase({ + factory: { + open: () => { + throw boom; + }, + } as unknown as IDBFactory, + databaseName: "kernel", + translate: recordingTranslate([]), + }); + + expect(result).toEqual({ + ok: false, + error: { cause: "NATIVE_EXCEPTION", detail: boom }, + }); + }); + + it("routes a request-level error through translate", async () => { + const memory = new MemoryIndexedDbFactory(); + await openIndexedDbDatabase({ + factory: memory.factory, + databaseName: "kernel", + version: 2, + translate: recordingTranslate([]), + upgrade: () => ({ kind: "APPLIED" }), + }); + + // Opening an older version makes the fake fill `request.error` and fire + // `onerror`; the kernel must report that error rather than a generic cause. + const result = await openIndexedDbDatabase({ + factory: memory.factory, + databaseName: "kernel", + version: 1, + translate: recordingTranslate([]), + upgrade: () => ({ kind: "APPLIED" }), + }); + + expect(result.ok).toBe(false); + if (result.ok) return; + expect(result.error.cause).toBe("NATIVE_EXCEPTION"); + expect((result.error.detail as DOMException).name).toBe("VersionError"); + }); + + it("settles with BLOCKED when onblocked fires and no deadline is configured", async () => { + const memory = new MemoryIndexedDbFactory(); + const observed: Array> = []; + memory.blockNextOpen(); + + const result = await openIndexedDbDatabase({ + factory: memory.factory, + databaseName: "kernel", + version: 3, + translate: recordingTranslate([]), + onBlocked: (event) => { + observed.push(event); + throw new Error("an observer cannot change the outcome"); + }, + }); + + expect(observed).toEqual([{ oldVersion: 0, newVersion: 3 }]); + expect(result).toEqual({ + ok: false, + error: { + cause: "BLOCKED", + detail: { oldVersion: 0, newVersion: 3 }, + }, + }); + }); + + it("waits the configured deadline before settling with BLOCKED_DEADLINE", async () => { + const memory = new MemoryIndexedDbFactory(); + const timers = manualTimers(); + memory.blockNextOpen(); + + let settled = false; + const pending = openIndexedDbDatabase({ + factory: memory.factory, + databaseName: "kernel", + version: 3, + translate: recordingTranslate([]), + blockedTimeoutMs: 10_000, + timers: timers.snapshot, + }); + void pending.then(() => { + settled = true; + }); + + await flush(); + expect(settled).toBe(false); + expect(timers.pending).toHaveLength(1); + expect(timers.pending[0]?.delayMs).toBe(10_000); + + timers.pending[0]?.callback(); + await expect(pending).resolves.toEqual({ + ok: false, + error: { cause: "BLOCKED_DEADLINE" }, + }); + }); + + it("rejects a positive blocked deadline that has no timer snapshot", () => { + const memory = new MemoryIndexedDbFactory(); + expect(() => + openIndexedDbDatabase({ + factory: memory.factory, + databaseName: "kernel", + translate: recordingTranslate([]), + blockedTimeoutMs: 10_000, + }), + ).toThrow(TypeError); + }); + + it("aborts the versionchange transaction when upgrade rejects, so no schema commits", async () => { + const memory = new MemoryIndexedDbFactory(); + + const result = await openIndexedDbDatabase({ + factory: memory.factory, + databaseName: "kernel", + version: 1, + translate: recordingTranslate([]), + upgrade: ({ database }) => { + database.createObjectStore("rows", { keyPath: "id" }); + return { kind: "REJECTED", detail: "POLICY" }; + }, + }); + + expect(result).toEqual({ + ok: false, + error: { cause: "UPGRADE_REJECTED", detail: "POLICY" }, + }); + // The store the rejected upgrade created must not be visible afterwards. + expect(memory.hasStore("rows")).toBe(false); + + const oldVersions: number[] = []; + await openIndexedDbDatabase({ + factory: memory.factory, + databaseName: "kernel", + version: 1, + translate: recordingTranslate([]), + upgrade: ({ oldVersion }) => { + oldVersions.push(oldVersion); + return { kind: "APPLIED" }; + }, + }); + expect(oldVersions).toEqual([0]); + }); + + it("treats a throw from upgrade as a rejection and carries the thrown value", async () => { + const memory = new MemoryIndexedDbFactory(); + const boom = new Error("migration defect"); + + const result = await openIndexedDbDatabase({ + factory: memory.factory, + databaseName: "kernel", + version: 1, + translate: recordingTranslate([]), + upgrade: () => { + throw boom; + }, + }); + + expect(result).toEqual({ + ok: false, + error: { cause: "UPGRADE_REJECTED", detail: boom }, + }); + expect(memory.hasStore("rows")).toBe(false); + }); + + it("treats any upgrade as unexpected when no upgrade callback is given", async () => { + const memory = new MemoryIndexedDbFactory(); + + const result = await openIndexedDbDatabase({ + factory: memory.factory, + databaseName: "kernel", + version: 1, + translate: recordingTranslate([]), + }); + + expect(result.ok).toBe(false); + if (result.ok) return; + expect(result.error.cause).toBe("UPGRADE_REJECTED"); + }); + + it("reports UPGRADE_REJECTED before running upgrade when newVersion is null", async () => { + const stub = stubFactory(); + const upgrade = vi.fn(() => ({ kind: "APPLIED" as const })); + const pending = openIndexedDbDatabase({ + factory: stub.factory, + databaseName: "kernel", + translate: recordingTranslate([]), + upgrade, + }); + + const request = stub.opened[0]; + expect(request).toBeDefined(); + if (!request) return; + const abort = vi.fn(); + request.transaction = { abort } as unknown as IDBTransaction; + request.onupgradeneeded?.(versionChangeEvent(4, null)); + request.error = new DOMException("aborted", "AbortError"); + request.onerror?.(new Event("error")); + + expect(upgrade).not.toHaveBeenCalled(); + expect(abort).toHaveBeenCalledTimes(1); + await expect(pending).resolves.toEqual({ + ok: false, + error: { cause: "UPGRADE_REJECTED", detail: undefined }, + }); + }); + + it("admits a successful open and lets an async admission run", async () => { + const memory = new MemoryIndexedDbFactory(); + const result = await openIndexedDbDatabase({ + factory: memory.factory, + databaseName: "kernel", + version: 1, + translate: recordingTranslate([]), + upgrade: () => ({ kind: "APPLIED" }), + admit: async (database) => { + await Promise.resolve(); + return database.objectStoreNames.contains("rows") + ? { kind: "ADMIT" } + : { kind: "REJECT", detail: "STORE" }; + }, + }); + + expect(result.ok).toBe(false); + if (result.ok) return; + expect(result.error).toEqual({ cause: "ADMISSION_REJECTED", detail: "STORE" }); + // A rejected admission must close the connection the caller never saw. + expect(memory.isConnectionClosed()).toBe(true); + }); + + it("closes the connection when admission fails with an explicit cause", async () => { + const memory = new MemoryIndexedDbFactory(); + const result = await openIndexedDbDatabase({ + factory: memory.factory, + databaseName: "kernel", + version: 1, + translate: recordingTranslate([]), + upgrade: () => ({ kind: "APPLIED" }), + admit: () => ({ kind: "FAIL", cause: { kind: "CALLER_ABORT" } }), + }); + + expect(result).toEqual({ ok: false, error: { cause: "CALLER_ABORT" } }); + expect(memory.isConnectionClosed()).toBe(true); + }); + + it("admits every successful open when no admit callback is given", async () => { + const memory = new MemoryIndexedDbFactory(); + const result = await openIndexedDbDatabase({ + factory: memory.factory, + databaseName: "kernel", + version: 1, + translate: recordingTranslate([]), + upgrade: () => ({ kind: "APPLIED" }), + }); + expect(result.ok).toBe(true); + expect(memory.isConnectionClosed()).toBe(false); + }); + + it("returns CALLER_ABORT without touching the factory for an already aborted signal", async () => { + const stub = stubFactory(); + const controller = new AbortController(); + controller.abort(); + + const result = await openIndexedDbDatabase({ + factory: stub.factory, + databaseName: "kernel", + translate: recordingTranslate([]), + signal: controller.signal, + }); + + expect(result).toEqual({ ok: false, error: { cause: "CALLER_ABORT" } }); + expect(stub.opened).toHaveLength(0); + }); + + it("aborts a pending upgrade transaction when the caller signal fires", async () => { + const stub = stubFactory(); + const controller = new AbortController(); + const pending = openIndexedDbDatabase({ + factory: stub.factory, + databaseName: "kernel", + translate: recordingTranslate([]), + signal: controller.signal, + }); + + const request = stub.opened[0]; + expect(request).toBeDefined(); + if (!request) return; + const abort = vi.fn(); + request.transaction = { abort } as unknown as IDBTransaction; + controller.abort(); + + expect(abort).toHaveBeenCalledTimes(1); + await expect(pending).resolves.toEqual({ + ok: false, + error: { cause: "CALLER_ABORT" }, + }); + }); + + it("closes a connection that arrives after the caller gave up", async () => { + const memory = new MemoryIndexedDbFactory(); + const controller = new AbortController(); + let release: ((admission: { kind: "ADMIT" }) => void) | undefined; + + const pending = openIndexedDbDatabase({ + factory: memory.factory, + databaseName: "kernel", + version: 1, + translate: recordingTranslate([]), + signal: controller.signal, + upgrade: () => ({ kind: "APPLIED" }), + admit: () => + new Promise<{ kind: "ADMIT" }>((resolve) => { + release = resolve; + }), + }); + + await flush(); + controller.abort(); + await expect(pending).resolves.toEqual({ + ok: false, + error: { cause: "CALLER_ABORT" }, + }); + + release?.({ kind: "ADMIT" }); + await flush(); + expect(memory.isConnectionClosed()).toBe(true); + }); + + it("calls translate for every cause the kernel can report", async () => { + const seen: IndexedDbFailureCause["kind"][] = []; + const translate = recordingTranslate(seen); + + // NATIVE_EXCEPTION + await openIndexedDbDatabase({ + factory: { + open: () => { + throw new Error("boom"); + }, + } as unknown as IDBFactory, + databaseName: "kernel", + translate, + }); + + // UPGRADE_REJECTED + const rejecting = new MemoryIndexedDbFactory(); + await openIndexedDbDatabase({ + factory: rejecting.factory, + databaseName: "kernel", + version: 1, + translate, + }); + + // BLOCKED + const blocking = new MemoryIndexedDbFactory(); + blocking.blockNextOpen(); + await openIndexedDbDatabase({ + factory: blocking.factory, + databaseName: "kernel", + version: 1, + translate, + }); + + // BLOCKED_DEADLINE + const deadline = new MemoryIndexedDbFactory(); + const timers = manualTimers(); + deadline.blockNextOpen(); + const deadlinePending = openIndexedDbDatabase({ + factory: deadline.factory, + databaseName: "kernel", + version: 1, + translate, + blockedTimeoutMs: 5, + timers: timers.snapshot, + }); + await flush(); + timers.pending[0]?.callback(); + await deadlinePending; + + // ADMISSION_REJECTED + const admitting = new MemoryIndexedDbFactory(); + await openIndexedDbDatabase({ + factory: admitting.factory, + databaseName: "kernel", + version: 1, + translate, + upgrade: () => ({ kind: "APPLIED" }), + admit: () => ({ kind: "REJECT", detail: "POLICY" }), + }); + + // CALLER_ABORT + const aborted = new AbortController(); + aborted.abort(); + await openIndexedDbDatabase({ + factory: new MemoryIndexedDbFactory().factory, + databaseName: "kernel", + translate, + signal: aborted.signal, + }); + + // CLOSED + const handle = createIndexedDbConnection({ + open: () => new Promise(() => undefined), + translate, + }); + const closing = handle.acquire(); + handle.close(); + await closing; + + expect(new Set(seen)).toEqual( + new Set([ + "NATIVE_EXCEPTION", + "UPGRADE_REJECTED", + "BLOCKED", + "BLOCKED_DEADLINE", + "ADMISSION_REJECTED", + "CALLER_ABORT", + "CLOSED", + ]), + ); + }); +}); + +describe("single-flight IndexedDB connection handle", () => { + function handleFor( + memory: MemoryIndexedDbFactory, + overrides: Partial>[0]> = {}, + ) { + const opens = vi.fn((signal: AbortSignal | undefined) => + openIndexedDbDatabase({ + factory: memory.factory, + databaseName: "kernel", + version: 1, + translate: recordingTranslate([]), + signal, + upgrade: ({ database }) => { + if (!database.objectStoreNames.contains("rows")) { + database.createObjectStore("rows", { keyPath: "id" }); + } + return { kind: "APPLIED" }; + }, + }), + ); + return { + opens, + handle: createIndexedDbConnection({ + open: opens, + translate: recordingTranslate([]), + ...overrides, + }), + }; + } + + it("shares one in-flight open and then reuses the cached connection", async () => { + const memory = new MemoryIndexedDbFactory(); + const { handle, opens } = handleFor(memory); + + const [first, second] = await Promise.all([ + handle.acquire(), + handle.acquire(), + ]); + const third = await handle.acquire(); + + expect(opens).toHaveBeenCalledTimes(1); + expect(first.ok && second.ok && third.ok).toBe(true); + expect(handle.current()).not.toBeNull(); + }); + + it("drops and closes the cached connection on versionchange, then reopens", async () => { + const memory = new MemoryIndexedDbFactory(); + const events: string[] = []; + const { handle, opens } = handleFor(memory, { + onVersionChange: () => { + events.push("VERSION_CHANGE"); + throw new Error("a notification defect cannot keep the connection"); + }, + }); + + await handle.acquire(); + memory.triggerVersionChange(2); + + expect(events).toEqual(["VERSION_CHANGE"]); + expect(handle.current()).toBeNull(); + expect(memory.isConnectionClosed()).toBe(true); + + await handle.acquire(); + expect(opens).toHaveBeenCalledTimes(2); + }); + + it("drops the cached connection when the browser forces it closed", async () => { + const memory = new MemoryIndexedDbFactory(); + const events: string[] = []; + const { handle } = handleFor(memory, { + onForcedClose: () => events.push("FORCED"), + }); + + await handle.acquire(); + memory.triggerForcedClose(); + + expect(events).toEqual(["FORCED"]); + expect(handle.current()).toBeNull(); + expect(handle.isClosed()).toBe(false); + }); + + it("settles an in-flight open with CLOSED rather than CALLER_ABORT", async () => { + const seen: IndexedDbFailureCause["kind"][] = []; + let openSignal: AbortSignal | undefined; + const handle = createIndexedDbConnection({ + open: (signal) => { + openSignal = signal; + return new Promise(() => undefined); + }, + translate: recordingTranslate(seen), + }); + + const pending = handle.acquire(); + handle.close(); + handle.close(); + + await expect(pending).resolves.toEqual({ + ok: false, + error: { cause: "CLOSED" }, + }); + expect(seen).toEqual(["CLOSED"]); + expect(handle.isClosed()).toBe(true); + // The in-flight native request is still cancelled, so a pending upgrade + // transaction does not outlive the handle. + expect(openSignal?.aborted).toBe(true); + await expect(handle.acquire()).resolves.toEqual({ + ok: false, + error: { cause: "CLOSED" }, + }); + }); + + it("closes a connection that arrives after the handle was closed", async () => { + const memory = new MemoryIndexedDbFactory(); + let release: ((result: { ok: true; value: IDBDatabase }) => void) | undefined; + const handle = createIndexedDbConnection({ + open: () => + new Promise((resolve) => { + release = resolve as typeof release; + }), + translate: recordingTranslate([]), + }); + + const pending = handle.acquire(); + handle.close(); + await pending; + + const opened = await openIndexedDbDatabase({ + factory: memory.factory, + databaseName: "kernel", + version: 1, + translate: recordingTranslate([]), + upgrade: () => ({ kind: "APPLIED" }), + }); + expect(opened.ok).toBe(true); + if (!opened.ok) return; + release?.({ ok: true, value: opened.value }); + await flush(); + expect(memory.isConnectionClosed()).toBe(true); + expect(handle.current()).toBeNull(); + }); + + it("aborts one caller without cancelling the shared open", async () => { + const memory = new MemoryIndexedDbFactory(); + const { handle, opens } = handleFor(memory); + const controller = new AbortController(); + + const abandoned = handle.acquire(controller.signal); + const kept = handle.acquire(); + controller.abort(); + + await expect(abandoned).resolves.toEqual({ + ok: false, + error: { cause: "CALLER_ABORT" }, + }); + const survivor = await kept; + expect(survivor.ok).toBe(true); + expect(opens).toHaveBeenCalledTimes(1); + expect(handle.current()).not.toBeNull(); + }); + + it("reports CALLER_ABORT for an already aborted acquire without opening", async () => { + const memory = new MemoryIndexedDbFactory(); + const { handle, opens } = handleFor(memory); + const controller = new AbortController(); + controller.abort(); + + await expect(handle.acquire(controller.signal)).resolves.toEqual({ + ok: false, + error: { cause: "CALLER_ABORT" }, + }); + expect(opens).not.toHaveBeenCalled(); + }); + + it("closes the cached connection and reports it through current()", async () => { + const memory = new MemoryIndexedDbFactory(); + const { handle } = handleFor(memory); + + await handle.acquire(); + expect(handle.current()).not.toBeNull(); + handle.close(); + expect(handle.current()).toBeNull(); + expect(memory.isConnectionClosed()).toBe(true); + }); + + it("retries after a failed open instead of caching the failure", async () => { + const attempts: number[] = []; + const handle = createIndexedDbConnection({ + open: () => { + attempts.push(attempts.length); + return Promise.resolve({ + ok: false as const, + error: { cause: "NATIVE_EXCEPTION" as const }, + }); + }, + translate: recordingTranslate([]), + }); + + await handle.acquire(); + await handle.acquire(); + expect(attempts).toHaveLength(2); + }); +}); + +describe("IndexedDB database deletion", () => { + it("reports DELETED and settles the caller's registration exactly once", async () => { + const stub = stubFactory(); + const settled = vi.fn(); + const pending = deleteIndexedDbDatabase({ + factory: stub.factory, + databaseName: "kernel", + translate: recordingTranslate([]), + onSettled: settled, + }); + + const request = stub.deleted[0]; + expect(request).toBeDefined(); + request?.onsuccess?.(new Event("success")); + request?.onsuccess?.(new Event("success")); + + await expect(pending).resolves.toEqual({ ok: true, value: { kind: "DELETED" } }); + expect(settled).toHaveBeenCalledTimes(1); + }); + + it("routes a delete error through translate and still settles the registration", async () => { + const stub = stubFactory(); + const settled = vi.fn(); + const pending = deleteIndexedDbDatabase({ + factory: stub.factory, + databaseName: "kernel", + translate: recordingTranslate([]), + onSettled: settled, + }); + + const request = stub.deleted[0]; + if (!request) throw new Error("no delete request"); + request.error = new DOMException("nope", "UnknownError"); + request.onerror?.(new Event("error")); + + const result = await pending; + expect(result.ok).toBe(false); + if (result.ok) return; + expect(result.error.cause).toBe("NATIVE_EXCEPTION"); + expect(settled).toHaveBeenCalledTimes(1); + }); + + it("reports BLOCKED_DEADLINE without settling, then settles when the request lands", async () => { + const stub = stubFactory(); + const timers = manualTimers(); + const settled = vi.fn(); + const pending = deleteIndexedDbDatabase({ + factory: stub.factory, + databaseName: "kernel", + translate: recordingTranslate([]), + blockedTimeoutMs: 5_000, + timers: timers.snapshot, + onSettled: settled, + }); + + const request = stub.deleted[0]; + if (!request) throw new Error("no delete request"); + request.onblocked?.(versionChangeEvent(1, null)); + expect(timers.pending).toHaveLength(1); + timers.pending[0]?.callback(); + + await expect(pending).resolves.toEqual({ + ok: true, + value: { kind: "BLOCKED_DEADLINE" }, + }); + // A dispatched deleteDatabase cannot be cancelled, so the deadline is not + // the end of the request: the registration is released only when it lands. + expect(settled).not.toHaveBeenCalled(); + + request.onsuccess?.(new Event("success")); + expect(settled).toHaveBeenCalledTimes(1); + }); + + it("settles with BLOCKED when no deadline is configured", async () => { + const stub = stubFactory(); + const pending = deleteIndexedDbDatabase({ + factory: stub.factory, + databaseName: "kernel", + translate: recordingTranslate([]), + }); + + stub.deleted[0]?.onblocked?.(versionChangeEvent(2, null)); + await expect(pending).resolves.toEqual({ + ok: false, + error: { cause: "BLOCKED", detail: { oldVersion: 2, newVersion: null } }, + }); + }); +}); diff --git a/tests/unit/indexeddb-maintenance.test.ts b/tests/unit/indexeddb-maintenance.test.ts index 248efd1..3fe8ea2 100644 --- a/tests/unit/indexeddb-maintenance.test.ts +++ b/tests/unit/indexeddb-maintenance.test.ts @@ -205,6 +205,7 @@ function createMaintenance( now?: () => number; nowEpochMilliseconds?: () => number; observe?: (event: IndexedDbObservation) => void; + factory?: IDBFactory; }> = {}, ) { return createIndexedDbMaintenance({ @@ -225,6 +226,63 @@ function createMaintenance( }); } +/** + * Records every `transaction.abort()` the adapter itself calls, with the mode + * of the transaction it aborted. + * + * A failure code alone cannot tell `fail` (record and abort) from + * `requestFailed` (record only): the fake aborts a transaction on a request + * error by itself, so both end at the same code while only one of them stops + * the writes queued behind it. Swapping the two is exactly the mistake this + * counter makes visible. + */ +function trackAborts(memory: MemoryIndexedDbFactory): Readonly<{ + factory: IDBFactory; + aborts: readonly string[]; +}> { + const aborts: string[] = []; + const wrapped = new WeakSet(); + const wrapDatabase = (database: IDBDatabase): IDBDatabase => { + if (wrapped.has(database)) return database; + wrapped.add(database); + const openTransaction = database.transaction.bind(database); + Object.defineProperty(database, "transaction", { + configurable: true, + value: (...args: Parameters) => { + const transaction = openTransaction(...args); + const abort = transaction.abort.bind(transaction); + Object.defineProperty(transaction, "abort", { + configurable: true, + value: () => { + aborts.push(transaction.mode); + abort(); + }, + }); + return transaction; + }, + }); + return database; + }; + const factory = { + cmp: (first: IDBValidKey, second: IDBValidKey) => + memory.factory.cmp(first, second), + open: (name: string, version?: number) => { + const request = memory.factory.open(name, version); + let stored: IDBDatabase | undefined = request.result; + if (stored) wrapDatabase(stored); + Object.defineProperty(request, "result", { + configurable: true, + get: () => stored, + set: (value: IDBDatabase | undefined) => { + stored = value ? wrapDatabase(value) : value; + }, + }); + return request; + }, + } as unknown as IDBFactory; + return Object.freeze({ factory, aborts }); +} + function seedReceipt( memory: MemoryIndexedDbFactory, idempotencyKey: string, @@ -299,6 +357,101 @@ describe("IndexedDB bounded codec maintenance", () => { }); }); + it("reports a blocked open immediately instead of waiting out a deadline", async () => { + const memory = new MemoryIndexedDbFactory(); + await prepareSchema(memory); + seedLegacy(memory, "blocked", "waiting"); + const maintenance = createMaintenance(memory, defaultPolicy()); + memory.blockNextOpen(); + + // MT-1. The blocked open is never released here. A blocked deadline could + // only settle from a timer, and no amount of microtask draining reaches a + // timer, so a batch that has already landed proves the blocked event + // itself is terminal. Give maintenance a blocked timeout and this test + // stops finishing instead of failing on a code. + let landed = false; + const pending = maintenance + .migrateCodecBatch({ maxRows: 10, maxDurationMs: 10_000 }) + .then((result) => { + landed = true; + return result; + }); + for (let tick = 0; tick < 50; tick += 1) await Promise.resolve(); + expect(landed).toBe(true); + + expect(await pending).toEqual({ + ok: false, + error: { + code: "BLOCKED", + operation: "INDEXEDDB_MIGRATE", + retryable: true, + recovery: "RELOAD_OTHER_CONTEXTS", + }, + }); + // The connection the caller already gave up on is closed, not leaked. + memory.releaseBlockedOpen(); + expect(memory.isConnectionClosed()).toBe(true); + expect(memory.readRaw("records", "blocked")).toMatchObject({ + codecVersion: 1, + }); + }); + + it("rejects an unexpected schema upgrade without creating the schema", async () => { + const memory = new MemoryIndexedDbFactory(); + // No prepareSchema: the database does not exist yet, so opening at the + // exact schema version is an upgrade. + const maintenance = createMaintenance(memory, defaultPolicy()); + + expect( + await maintenance.migrateCodecBatch({ + maxRows: 10, + maxDurationMs: 10_000, + }), + ).toEqual({ + ok: false, + error: { + code: "MIGRATION_FAILED", + operation: "INDEXEDDB_MIGRATE", + retryable: false, + recovery: "READ_ONLY", + }, + }); + // MT-2. Maintenance owns no schema, so a rejected upgrade must leave the + // database untouched rather than open it at the right version with the + // wrong contents. Applying the upgrade instead would fail with the same + // code here and only surface later, as a database nobody can use. + expect(memory.hasStore("records")).toBe(false); + expect(memory.hasStore("governance")).toBe(false); + await prepareSchema(memory); + expect(memory.hasStore("records")).toBe(true); + }); + + it("closes the maintenance connection when another context needs a version change", async () => { + const memory = new MemoryIndexedDbFactory(); + await prepareSchema(memory); + seedReceipt(memory, "versionchange-receipt", 100); + const maintenance = createMaintenance(memory, defaultPolicy(), { + nowEpochMilliseconds: () => 200, + }); + memory.clearLastTransaction(); + memory.pauseTransactions(); + + const pending = maintenance.pruneExpiredReceipts({ + maxRows: 10, + maxDurationMs: 10_000, + }); + await waitForWriteTransaction(memory); + expect(memory.isConnectionClosed()).toBe(false); + + // MT-3. The listener is registered on the successful open path only, so it + // covers exactly the window in which a batch holds the connection. + memory.triggerVersionChange(2); + expect(memory.isConnectionClosed()).toBe(true); + + memory.resumeTransactions(); + await pending; + }); + it("resumes from a durable checkpoint and completes in bounded row batches", async () => { const memory = new MemoryIndexedDbFactory(); await prepareSchema(memory); @@ -667,7 +820,10 @@ describe("IndexedDB bounded codec maintenance", () => { ...defaultPolicy(), measureStoredBytes: () => 2_000_000, }; - const maintenance = createMaintenance(memory, policy); + const tracker = trackAborts(memory); + const maintenance = createMaintenance(memory, policy, { + factory: tracker.factory, + }); expect( await maintenance.migrateCodecBatch({ @@ -681,6 +837,10 @@ describe("IndexedDB bounded codec maintenance", () => { recovery: "READ_ONLY", }, }); + // The budget verdict aborts the commit transaction rather than only + // recording a failure, so the writes already queued behind it cannot + // commit. Recording without aborting would end at the same failure code. + expect(tracker.aborts).toEqual(["readwrite"]); expect(memory.readRaw("records", "oversized")).toMatchObject({ codecVersion: 1, }); @@ -749,10 +909,11 @@ describe("IndexedDB bounded codec maintenance", () => { const memory = new MemoryIndexedDbFactory(); await prepareSchema(memory); seedReceipt(memory, "quota-receipt", 100); + const tracker = trackAborts(memory); const maintenance = createMaintenance( memory, defaultPolicy(), - { nowEpochMilliseconds: () => 200 }, + { nowEpochMilliseconds: () => 200, factory: tracker.factory }, ); memory.failNextWriteCommit( new DOMException("private receipt", "QuotaExceededError"), @@ -767,6 +928,9 @@ describe("IndexedDB bounded codec maintenance", () => { ok: false, error: { code: "QUOTA_EXCEEDED" }, }); + // The commit is what failed, so the adapter never aborts anything itself; + // the quota code has to come from the transaction's own error. + expect(tracker.aborts).toEqual([]); expect( memory.readRaw("receipts", "quota-receipt"), ).toBeDefined(); @@ -776,10 +940,11 @@ describe("IndexedDB bounded codec maintenance", () => { const memory = new MemoryIndexedDbFactory(); await prepareSchema(memory); seedReceipt(memory, "abort-receipt", 100); + const tracker = trackAborts(memory); const maintenance = createMaintenance( memory, defaultPolicy(), - { nowEpochMilliseconds: () => 200 }, + { nowEpochMilliseconds: () => 200, factory: tracker.factory }, ); memory.clearLastTransaction(); memory.pauseTransactions(); @@ -796,6 +961,9 @@ describe("IndexedDB bounded codec maintenance", () => { ok: false, error: { code: "ABORTED" }, }); + // Exactly one abort: the caller's signal. A second one would mean the + // cursor pump and the transaction both claim the abort. + expect(tracker.aborts).toEqual(["readwrite"]); memory.resumeTransactions(); await Promise.resolve(); expect( diff --git a/tests/unit/indexeddb-opfs-journal.test.ts b/tests/unit/indexeddb-opfs-journal.test.ts index 6977bdc..14217ca 100644 --- a/tests/unit/indexeddb-opfs-journal.test.ts +++ b/tests/unit/indexeddb-opfs-journal.test.ts @@ -95,17 +95,98 @@ function prepared( }; } +/** + * Records every `transaction.abort()` the journal itself calls, with the mode + * of the transaction it aborted. + * + * A failure code alone cannot tell `fail` (record and abort) from + * `requestFailed` (record only): the fake aborts a transaction on a request + * error by itself, so both land on the same code while only one of them stops + * the writes queued behind it. + */ +function trackAborts(memory: MemoryIndexedDbFactory): Readonly<{ + factory: IDBFactory; + aborts: readonly string[]; +}> { + const aborts: string[] = []; + const wrapped = new WeakSet(); + const wrapDatabase = (database: IDBDatabase): IDBDatabase => { + if (wrapped.has(database)) return database; + wrapped.add(database); + const openTransaction = database.transaction.bind(database); + Object.defineProperty(database, "transaction", { + configurable: true, + value: (...args: Parameters) => { + const transaction = openTransaction(...args); + const abort = transaction.abort.bind(transaction); + Object.defineProperty(transaction, "abort", { + configurable: true, + value: () => { + aborts.push(transaction.mode); + abort(); + }, + }); + return transaction; + }, + }); + return database; + }; + const factory = { + cmp: (first: IDBValidKey, second: IDBValidKey) => + memory.factory.cmp(first, second), + open: (name: string, version?: number) => { + const request = memory.factory.open(name, version); + let stored: IDBDatabase | undefined = request.result; + if (stored) wrapDatabase(stored); + Object.defineProperty(request, "result", { + configurable: true, + get: () => stored, + set: (value: IDBDatabase | undefined) => { + stored = value ? wrapDatabase(value) : value; + }, + }); + return request; + }, + } as unknown as IDBFactory; + return Object.freeze({ factory, aborts }); +} + function createHarness(factory = new MemoryIndexedDbFactory()) { let tokenSequence = 0; const journal = createIndexedDbOpfsJournal({ authorityToken, factory: factory.factory, + // `listCommittedObjects` is the only caller that needs a key range, and + // this environment has no global one. + keyRange: factory.keyRange, createFencingToken: () => `fencing_${String(++tokenSequence).padStart(8, "0")}`, }); return { factory, journal }; } +async function commitObject( + journal: ReturnType["journal"], + transactionId: string, + objectId: string, + byteLength: number, +): Promise { + const input = beginInput(transactionId, objectId, byteLength); + const begun = await journal.begin(input); + if (!begun.ok) throw new Error(`begin failed for ${objectId}`); + const token = begun.value.fencingToken; + const ready = await journal.markFilesReady( + transactionId, + token, + prepared(input), + ); + if (!ready.ok) throw new Error(`markFilesReady failed for ${objectId}`); + const committed = await journal.commitPut(transactionId, token); + if (!committed.ok) throw new Error(`commitPut failed for ${objectId}`); + const completed = await journal.complete(transactionId, token); + if (!completed.ok) throw new Error(`complete failed for ${objectId}`); +} + describe("IndexedDB OPFS journal", () => { it("fences stale writers and atomically publishes object, budget and chunk refs", async () => { const { factory, journal } = createHarness(); @@ -428,4 +509,234 @@ describe("IndexedDB OPFS journal", () => { error: { code: "CORRUPT_DATA" }, }); }); + + it("reports a unique logical-key violation as the request's own ConstraintError", async () => { + // OP-1. Two open journal rows for one object collide on the `by-logical-key` + // index, which is the only `unique: true` index in `src/adapters`. The + // violation belongs to the `add` request, not to the transaction: the + // journal never asks for the row's uniqueness, it asks the index to enforce + // it, so the answer has to be the request's `ConstraintError` rather than + // whatever the transaction happened to abort with. + const memory = new MemoryIndexedDbFactory(); + const tracker = trackAborts(memory); + let tokenSequence = 0; + const journal = createIndexedDbOpfsJournal({ + authorityToken, + factory: tracker.factory, + createFencingToken: () => + `fencing_${String(++tokenSequence).padStart(8, "0")}`, + }); + + const first = await journal.begin( + beginInput("transaction_dupe0001", "object_dupe_1234", 1), + ); + expect(first).toMatchObject({ ok: true }); + + expect( + await journal.begin( + beginInput("transaction_dupe0002", "object_dupe_1234", 1), + ), + ).toEqual({ + ok: false, + error: { + code: "CONFLICT", + operation: "INDEXEDDB_WRITE", + retryable: false, + recovery: "NONE", + }, + }); + // `mapIndexedDbException`'s ConstraintError arm carries no recovery, while + // the journal's own `conflict()` helper carries REOPEN. The NONE above is + // what proves the answer came from the native error rather than from a + // predicate the journal evaluated itself. + expect(tracker.aborts).toEqual([]); + // The losing transaction rolled back whole: no budget reservation from the + // second `begin` survives, so the partition still admits its full budget. + expect(memory.readRaw("opfs-budgets", `${scope.authorityToken}|${scope.namespaceToken}|${scope.partitionToken}`)).toMatchObject({ + reservedBytes: 1, + }); + expect( + (await journal.listIncomplete(10)) as unknown, + ).toMatchObject({ + ok: true, + value: { transactions: [{ transactionId: "transaction_dupe0001" }] }, + }); + }); + + it("lets the first explicit failure win over a later success in the same transaction", async () => { + // OP-2. `begin` runs two independent request chains: the scope-binding + // chain can fail while the object/budget chain is still queued to succeed. + // The binding chain's `get` is issued first, so its verdict always lands + // first and the later `succeed` never reaches the caller. The abort count + // is what separates "the journal rejected this" from "the store did". + const memory = new MemoryIndexedDbFactory(); + const tracker = trackAborts(memory); + let tokenSequence = 0; + const journal = createIndexedDbOpfsJournal({ + authorityToken, + factory: tracker.factory, + createFencingToken: () => + `fencing_${String(++tokenSequence).padStart(8, "0")}`, + }); + + const bound = await journal.begin( + beginInput("transaction_order001", "object_order_1234", 1), + ); + if (!bound.ok) throw new Error("binding begin failed"); + await journal.rollback( + "transaction_order001", + bound.value.fencingToken, + ); + const abortsBefore = tracker.aborts.length; + + expect( + await journal.begin({ + ...beginInput("transaction_order002", "object_order_5678", 1), + targetStoragePolicy: { ...policy, owner: "rebound-owner" }, + }), + ).toEqual({ + ok: false, + error: { + code: "POLICY_REJECTED", + operation: "INDEXEDDB_WRITE", + retryable: false, + recovery: "READ_ONLY", + }, + }); + // Exactly one abort, from the binding chain's `fail`. A second would mean + // the budget chain also reached a verdict. + expect(tracker.aborts.length - abortsBefore).toBe(1); + expect(memory.readRaw("opfs-journal", "transaction_order002")).toBeUndefined(); + }); + + it("keeps a commit failure attributable to the transaction rather than a request", async () => { + // The commit itself fails, so no request ever errors. The journal must not + // claim an abort it did not perform, and the quota code has to come from + // the transaction's own error. + const memory = new MemoryIndexedDbFactory(); + const tracker = trackAborts(memory); + let tokenSequence = 0; + const journal = createIndexedDbOpfsJournal({ + authorityToken, + factory: tracker.factory, + createFencingToken: () => + `fencing_${String(++tokenSequence).padStart(8, "0")}`, + }); + + memory.failNextWriteCommit( + new DOMException("quota", "QuotaExceededError"), + ); + expect( + await journal.begin( + beginInput("transaction_quota001", "object_quota_1234", 1), + ), + ).toEqual({ + ok: false, + error: { + code: "QUOTA_EXCEEDED", + operation: "INDEXEDDB_WRITE", + retryable: false, + recovery: "READ_ONLY", + }, + }); + expect(tracker.aborts).toEqual([]); + }); + + it("pages incomplete transactions and validates a row before the page limit", async () => { + const { factory, journal } = createHarness(); + for (const index of [1, 2, 3]) { + const id = `transaction_page000${index}`; + expect( + await journal.begin( + beginInput(id, `object_page_000${index}`, 1), + ), + ).toMatchObject({ ok: true }); + } + + expect(await journal.listIncomplete(2)).toMatchObject({ + ok: true, + value: { moreAvailable: true }, + }); + const page = await journal.listIncomplete(2); + if (!page.ok) throw new Error("listIncomplete failed"); + expect(page.value.transactions).toHaveLength(2); + + const whole = await journal.listIncomplete(10); + if (!whole.ok) throw new Error("listIncomplete failed"); + expect(whole.value.transactions).toHaveLength(3); + expect(whole.value.moreAvailable).toBe(false); + + // A corrupt row one past the requested page still fails the read. The + // journal validates a row before it checks the limit, so a page that is + // already full does not hide the next row's damage behind `moreAvailable`. + factory.seed("opfs-journal", { + transactionId: "transaction_page9999", + startedAtEpochMs: 9_000, + corrupt: true, + }); + expect(await journal.listIncomplete(3)).toMatchObject({ + ok: false, + error: { code: "CORRUPT_DATA", recovery: "READ_ONLY" }, + }); + }); + + it("pages committed objects and reports where the next page resumes", async () => { + const { journal } = createHarness(); + await commitObject(journal, "transaction_obj00001", "object_aaaa0001", 1); + await commitObject(journal, "transaction_obj00002", "object_bbbb0002", 1); + await commitObject(journal, "transaction_obj00003", "object_cccc0003", 1); + + const first = await journal.listCommittedObjects({ scope, limit: 2 }); + if (!first.ok) throw new Error("listCommittedObjects failed"); + expect(first.value.objects.map((o) => o.descriptor.objectId)).toEqual([ + "object_aaaa0001", + "object_bbbb0002", + ]); + // A page cut short by the limit names the cursor the caller resumes from. + expect(first.value.moreAvailable).toBe(true); + expect(first.value.nextObjectId).toBe("object_bbbb0002"); + + const second = await journal.listCommittedObjects({ + scope, + limit: 2, + afterObjectId: first.value.nextObjectId ?? undefined, + }); + if (!second.ok) throw new Error("listCommittedObjects failed"); + expect(second.value.objects.map((o) => o.descriptor.objectId)).toEqual([ + "object_cccc0003", + ]); + // An exhausted scan has nothing to resume from, so it reports neither. + expect(second.value.moreAvailable).toBe(false); + expect(second.value.nextObjectId).toBeNull(); + }); + + it("answers UNSUPPORTED once the journal is closed", async () => { + const { factory, journal } = createHarness(); + expect( + await journal.getCommittedObject(scope, "object_12345678"), + ).toEqual({ ok: true, value: null }); + + journal.close(); + expect(factory.isConnectionClosed()).toBe(true); + // A closed journal is not a retryable outage and not an abort: the store + // is gone for this realm, so the caller is told to work online. The + // failure names INDEXEDDB_OPEN rather than the operation that asked, + // because it belongs to the open that never happened. + expect( + await journal.getCommittedObject(scope, "object_12345678"), + ).toEqual({ + ok: false, + error: { + code: "UNSUPPORTED", + operation: "INDEXEDDB_OPEN", + retryable: false, + recovery: "ONLINE_ONLY", + }, + }); + expect( + await journal.begin( + beginInput("transaction_closed001", "object_closed_001", 1), + ), + ).toMatchObject({ ok: false, error: { code: "UNSUPPORTED" } }); + }); }); diff --git a/tests/unit/indexeddb-runtime.test.ts b/tests/unit/indexeddb-runtime.test.ts index af3b02a..792316f 100644 --- a/tests/unit/indexeddb-runtime.test.ts +++ b/tests/unit/indexeddb-runtime.test.ts @@ -152,6 +152,33 @@ function dependencies( }; } +/** + * Counts the aborts the adapter asks for. A failure code on its own cannot + * tell `fail`, which aborts, from `requestFailed`, which only records: both + * report the same code once the transaction unwinds, and only the abort + * decides whether the writes already queued can still commit. + */ +function trackAborts( + memory: MemoryIndexedDbFactory, +): Readonly<{ count: number }> { + const tracker = { count: 0 }; + let current = memory.lastTransaction; + Object.defineProperty(memory, "lastTransaction", { + configurable: true, + get: () => current, + set: (transaction: MemoryIndexedDbFactory["lastTransaction"]) => { + current = transaction; + if (!transaction) return; + const abort = transaction.abort.bind(transaction); + transaction.abort = () => { + tracker.count += 1; + abort(); + }; + }, + }); + return tracker; +} + async function waitForTransaction( memory: MemoryIndexedDbFactory, ): Promise { @@ -464,7 +491,7 @@ describe("IndexedDB runtime", () => { }); }); - it("retains native open ownership after a blocked timeout until late success", async () => { + it("reopens after a blocked deadline and ignores the abandoned request", async () => { const memory = new MemoryIndexedDbFactory(); memory.blockNextOpen(); const nativeOpen = vi.spyOn(memory.factory, "open"); @@ -489,23 +516,59 @@ describe("IndexedDB runtime", () => { ok: false, error: { code: "BLOCKED" }, }); - - const second = runtime.open(); - await Promise.resolve(); - const nativeOpenCountBeforeLateSuccess = nativeOpen.mock.calls.length; - memory.releaseBlockedOpen(); - - await expect(second).resolves.toMatchObject({ - ok: false, - error: { code: "BLOCKED" }, - }); - await Promise.resolve(); - expect(nativeOpenCountBeforeLateSuccess).toBe(1); - expect(memory.isConnectionClosed()).toBe(true); expect(runtime.getStatus()).toEqual({ kind: "CLOSED", reason: "NOT_OPENED", }); + + // The deadline ends the caller's wait, not the native request. A retry + // therefore dispatches a second open instead of answering from the + // abandoned one, which is the one behavior the connection kernel does not + // preserve: it cannot report when an open it already settled lands. + expect(await runtime.open()).toEqual({ ok: true, value: undefined }); + expect(nativeOpen).toHaveBeenCalledTimes(2); + expect(runtime.getStatus()).toEqual({ + kind: "READY", + schemaVersion: 1, + }); + + // The abandoned request lands late. Its connection is closed inside the + // kernel and must not disturb the one the retry established. + memory.releaseBlockedOpen(); + await Promise.resolve(); + expect(runtime.getStatus()).toEqual({ + kind: "READY", + schemaVersion: 1, + }); + expect(await runtime.read("late-arrival")).toEqual({ + ok: true, + value: null, + }); + }); + + it("ends an open in flight with UNAVAILABLE when the runtime closes", async () => { + const memory = new MemoryIndexedDbFactory(); + memory.blockNextOpen(); + const runtime = createIndexedDbRuntime(dependencies(memory)); + + const pending = runtime.open(); + await Promise.resolve(); + expect(runtime.getStatus()).toMatchObject({ kind: "BLOCKED" }); + runtime.close(); + + // Closing the runtime is not the caller aborting. The open is reported as + // UNAVAILABLE/REOPEN so a caller builds a new runtime rather than reading + // its own cancellation into someone else's shutdown. + expect(await pending).toEqual({ + ok: false, + error: { + code: "UNAVAILABLE", + operation: "INDEXEDDB_OPEN", + retryable: true, + recovery: "REOPEN", + }, + }); + expect(runtime.getStatus()).toEqual({ kind: "DISPOSED" }); }); it("closes immediately on versionchange and isolates listener failures", async () => { @@ -735,7 +798,24 @@ describe("IndexedDB runtime", () => { recovery: "READ_ONLY", }, }); - expect(memory.isConnectionClosed()).toBe(true); + // Rejecting the upgrade aborts the versionchange transaction, so the + // half-created schema is rolled back instead of being committed at + // version 1. Only this assertion separates a rejected upgrade from an + // upgrade that was allowed to commit and then refused at admission — + // `NotFoundError` maps to MIGRATION_FAILED either way. + expect([...memory.storeNames()]).toEqual([]); + // A failed open request never exposes a connection, so fail-closed is + // asserted through the runtime rather than through the fake's last + // database handle: no status claiming a live schema, and no read that can + // reach one. + expect(runtime.getStatus()).toEqual({ + kind: "CLOSED", + reason: "NOT_OPENED", + }); + expect(await runtime.read("any-key")).toMatchObject({ + ok: false, + error: { code: "UNAVAILABLE", recovery: "REOPEN" }, + }); }); it("derives physical identity only from opaque scope and rejects an override", () => { @@ -902,6 +982,117 @@ describe("IndexedDB runtime", () => { ).not.toContain("ttl_authority_proof_001"); }); + it("reports a batch that ran out of both budgets as time-exhausted", async () => { + const memory = new MemoryIndexedDbFactory(); + const base = dependencies(memory); + // The start of the batch and the first row are inside the deadline; the + // second row is not, and by then the row budget is spent as well. + let monotonicCalls = 0; + const runtime = createIndexedDbRuntime({ + ...base, + storagePolicy: { + ...TEST_STORAGE_POLICY, + retention: { kind: "SESSION" }, + }, + authorizeLifecycle: () => ({ + authorized: true as const, + proofToken: "budget_authority_proof_001", + }), + nowMonotonicMilliseconds: () => (monotonicCalls++ < 2 ? 0 : 5_000), + }); + expect(await runtime.open()).toMatchObject({ ok: true }); + for (const key of ["budget-one", "budget-two"]) { + expect( + await runtime.compareAndSwap({ + key, + value: { label: key, rank: 1 }, + expectedRevision: null, + idempotencyKey: `${key}-create`, + }), + ).toMatchObject({ ok: true }); + } + + // Both budgets are spent at the same row. The receipt says the deadline + // did it, because a caller that reads `budgetExhausted` as "the clock ran + // out" would otherwise schedule the next batch as if it had room. + expect( + await runtime.enforceLifecycleBatch({ + action: "SESSION_END", + maxRows: 1, + maxDurationMs: 1_000, + }), + ).toEqual({ + ok: true, + value: { + state: "MORE", + scannedRows: 1, + deletedRows: 1, + budgetExhausted: true, + }, + }); + }); + + it("aborts a sweep whose budget row cannot account for the deleted bytes", async () => { + const memory = new MemoryIndexedDbFactory(); + let epochMs = 1_000; + const runtime = createIndexedDbRuntime( + dependencies(memory, { + storagePolicy: { + ...TEST_STORAGE_POLICY, + retention: { kind: "TTL", maxAgeMs: 10 }, + }, + keyRange: + memory.keyRange as NonNullable< + IndexedDbRuntimeDependencies["keyRange"] + >, + nowEpochMilliseconds: () => epochMs, + nowMonotonicMilliseconds: () => 0, + authorizeLifecycle: () => ({ + authorized: true, + proofToken: "sweep_authority_proof_001", + }), + }), + ); + expect(await runtime.open()).toMatchObject({ ok: true }); + expect( + await runtime.compareAndSwap({ + key: "sweep-record", + value: { label: "expires", rank: 1 }, + expectedRevision: null, + idempotencyKey: "sweep-create", + }), + ).toMatchObject({ ok: true }); + + // A budget that cannot account for the record's bytes is corrupt, and the + // sweep only discovers it after both deletions have already succeeded + // inside the transaction. + memory.seed("governance", { + bindingKey: "dataset-budget", + budgetVersion: 1, + usedBytes: 0, + receiptCount: 1, + }); + const aborts = trackAborts(memory); + epochMs = 1_011; + + expect( + await runtime.enforceLifecycleBatch({ + action: "RETENTION_SWEEP", + maxRows: 10, + maxDurationMs: 1_000, + }), + ).toMatchObject({ + ok: false, + error: { code: "CORRUPT_DATA" }, + }); + // `fail` aborts. Recording the failure without aborting would report the + // same code while letting the two deletions commit against a budget that + // never moved. + expect(aborts.count).toBe(1); + expect(memory.readRaw("records", "sweep-record")).toBeDefined(); + expect(memory.readRaw("retention", "sweep-record")).toBeDefined(); + }); + it("requires lifecycle authority and only deletes sync-confirmed rows", async () => { const memory = new MemoryIndexedDbFactory(); const authorizeLifecycle = vi diff --git a/tests/unit/indexeddb-transaction.test.ts b/tests/unit/indexeddb-transaction.test.ts new file mode 100644 index 0000000..f36deb7 --- /dev/null +++ b/tests/unit/indexeddb-transaction.test.ts @@ -0,0 +1,716 @@ +import { describe, expect, it, vi } from "vitest"; + +import type { + IndexedDbFailureCause, + IndexedDbTranslate, +} from "../../src/adapters/platform/indexeddb-connection.ts"; +import { openIndexedDbDatabase } from "../../src/adapters/platform/indexeddb-connection.ts"; +import { + onIndexedDbRequest, + openIndexedDbTransaction, + runIndexedDbTransaction, + walkIndexedDbCursor, + type IndexedDbCursorStep, + type IndexedDbRequestSink, + type IndexedDbWalkSummary, +} from "../../src/adapters/platform/indexeddb-transaction.ts"; +import { MemoryIndexedDbFactory } from "../helpers/memory-indexeddb.ts"; + +/** + * IDB-X-02 golden tests. Four hand-written copies of this state machine already + * disagree about request errors, value-less completions and durability. Every + * one of those choices has to remain expressible at the call site, so the tests + * assert the mechanics and never a taxonomy. + */ + +type TestFailure = Readonly<{ cause: IndexedDbFailureCause["kind"]; detail?: unknown }>; + +function recordingTranslate( + seen: IndexedDbFailureCause["kind"][] = [], +): IndexedDbTranslate { + return (cause) => { + seen.push(cause.kind); + switch (cause.kind) { + case "NATIVE_EXCEPTION": + return { cause: cause.kind, detail: cause.error }; + case "BLOCKED": + return { cause: cause.kind }; + case "BLOCKED_DEADLINE": + case "CALLER_ABORT": + case "CLOSED": + case "NO_VALUE_PRODUCED": + case "UNSUPPORTED": + return { cause: cause.kind }; + case "UPGRADE_REJECTED": + case "ADMISSION_REJECTED": + return { cause: cause.kind, detail: cause.detail }; + default: { + const exhaustive: never = cause; + return exhaustive; + } + } + }; +} + +type Row = Readonly<{ id: string; rank: number }>; + +const ROWS: readonly Row[] = Object.freeze([ + Object.freeze({ id: "a", rank: 1 }), + Object.freeze({ id: "b", rank: 2 }), + Object.freeze({ id: "c", rank: 3 }), + Object.freeze({ id: "d", rank: 4 }), +]); + +async function seededDatabase( + rows: readonly Row[] = ROWS, +): Promise> { + const memory = new MemoryIndexedDbFactory(); + const opened = await openIndexedDbDatabase({ + factory: memory.factory, + databaseName: "kernel", + version: 1, + translate: recordingTranslate(), + upgrade: ({ database }) => { + database.createObjectStore("rows", { keyPath: "id" }); + return { kind: "APPLIED" }; + }, + }); + if (!opened.ok) throw new Error("fixture database did not open"); + for (const row of rows) memory.seed("rows", row); + return { memory, database: opened.value }; +} + +type StubTransaction = { + error: DOMException | null; + abort: () => void; + oncomplete: ((event: Event) => unknown) | null; + onerror: ((event: Event) => unknown) | null; + onabort: ((event: Event) => unknown) | null; + objectStore: (name: string) => IDBObjectStore; +}; + +/** + * A transaction the test drives by hand. The memory fake aborts on every + * request error, so "recorded but not aborted" and "abort() itself throws" — + * the two behaviors the four copies disagree about — are only observable here. + */ +function stubDatabase( + options: Readonly<{ abortThrows?: boolean; rejectOptionsBag?: boolean }> = {}, +): Readonly<{ + database: IDBDatabase; + transactions: StubTransaction[]; + calls: unknown[][]; +}> { + const transactions: StubTransaction[] = []; + const calls: unknown[][] = []; + const database = { + transaction: (...args: unknown[]) => { + calls.push(args); + if (options.rejectOptionsBag === true && args.length > 2) { + throw new TypeError("This engine has no durability option."); + } + const transaction: StubTransaction = { + error: null, + abort: vi.fn(() => { + if (options.abortThrows === true) { + throw new DOMException("already finished", "InvalidStateError"); + } + }), + oncomplete: null, + onerror: null, + onabort: null, + objectStore: () => ({}) as IDBObjectStore, + }; + transactions.push(transaction); + return transaction as unknown as IDBTransaction; + }, + } as unknown as IDBDatabase; + return { database, transactions, calls }; +} + +function stubSink(): Readonly<{ + sink: IndexedDbRequestSink; + failures: TestFailure[]; + requestErrors: unknown[]; +}> { + const failures: TestFailure[] = []; + const requestErrors: unknown[] = []; + return { + failures, + requestErrors, + sink: { + fail: (failure) => failures.push(failure), + requestFailed: (error) => requestErrors.push(error), + }, + }; +} + +describe("shared IndexedDB transaction mechanics", () => { + it("returns the value the queue produced once the transaction commits", async () => { + const { database, memory } = await seededDatabase(); + + const result = await runIndexedDbTransaction({ + database, + stores: ["rows"], + mode: "readwrite", + translate: recordingTranslate(), + queue: (transaction, context) => { + const store = transaction.objectStore("rows"); + onIndexedDbRequest(store.put({ id: "e", rank: 5 }), context, () => { + context.succeed("written"); + }); + }, + }); + + expect(result).toEqual({ ok: true, value: "written" }); + expect(memory.readRaw("rows", "e")).toEqual({ id: "e", rank: 5 }); + }); + + it("reports NO_VALUE_PRODUCED when a transaction completes without succeed", async () => { + const { database } = await seededDatabase(); + const seen: IndexedDbFailureCause["kind"][] = []; + + const result = await runIndexedDbTransaction({ + database, + stores: ["rows"], + mode: "readonly", + translate: recordingTranslate(seen), + queue: (transaction, context) => { + onIndexedDbRequest( + transaction.objectStore("rows").get("a"), + context, + () => undefined, + ); + }, + }); + + expect(result).toEqual({ + ok: false, + error: { cause: "NO_VALUE_PRODUCED" }, + }); + expect(seen).toEqual(["NO_VALUE_PRODUCED"]); + }); + + it("aborts on fail() and reports the recorded failure", async () => { + const { database, memory } = await seededDatabase(); + + const result = await runIndexedDbTransaction({ + database, + stores: ["rows"], + mode: "readwrite", + translate: recordingTranslate(), + queue: (transaction, context) => { + const store = transaction.objectStore("rows"); + onIndexedDbRequest(store.put({ id: "e", rank: 5 }), context, () => { + context.fail({ cause: "ADMISSION_REJECTED", detail: "policy" }); + }); + }, + }); + + expect(result).toEqual({ + ok: false, + error: { cause: "ADMISSION_REJECTED", detail: "policy" }, + }); + // The aborted transaction must not have committed the write. + expect(memory.readRaw("rows", "e")).toBeUndefined(); + }); + + it("routes a request-level error into the sink", async () => { + const { database } = await seededDatabase(); + + const result = await runIndexedDbTransaction({ + database, + stores: ["rows"], + mode: "readwrite", + translate: recordingTranslate(), + queue: (transaction, context) => { + const store = transaction.objectStore("rows"); + // `add` on an existing key is a request-level ConstraintError, the + // exact case `indexeddb-opfs-journal.ts` never wires today. + onIndexedDbRequest(store.add({ id: "a", rank: 9 }), context, () => { + context.succeed("unreachable"); + }); + }, + }); + + expect(result.ok).toBe(false); + if (result.ok) return; + expect(result.error.cause).toBe("NATIVE_EXCEPTION"); + expect((result.error.detail as DOMException).name).toBe("ConstraintError"); + }); + + it("records a request error without aborting, while fail() aborts", () => { + const stub = stubDatabase(); + void runIndexedDbTransaction({ + database: stub.database, + stores: ["rows"], + mode: "readwrite", + translate: recordingTranslate(), + queue: (_transaction, context) => { + context.requestFailed(new Error("recorded only")); + }, + }); + + const transaction = stub.transactions[0]; + expect(transaction).toBeDefined(); + expect(transaction?.abort).not.toHaveBeenCalled(); + }); + + it("never claims a caller abort when transaction.abort() throws", async () => { + // CP-4. A transaction can be durably committed while its completion event + // is still queued. Reporting ABORTED for it would call a committed write a + // failure, so the transaction's own events decide the outcome. + const stub = stubDatabase({ abortThrows: true }); + const controller = new AbortController(); + + const pending = runIndexedDbTransaction({ + database: stub.database, + stores: ["rows"], + mode: "readwrite", + translate: recordingTranslate(), + signal: controller.signal, + queue: (_transaction, context) => { + context.succeed("committed"); + }, + }); + + controller.abort(); + stub.transactions[0]?.oncomplete?.(new Event("complete")); + + await expect(pending).resolves.toEqual({ ok: true, value: "committed" }); + }); + + it("reports CALLER_ABORT when the signal aborts the transaction", async () => { + const stub = stubDatabase(); + const controller = new AbortController(); + + const pending = runIndexedDbTransaction({ + database: stub.database, + stores: ["rows"], + mode: "readwrite", + translate: recordingTranslate(), + signal: controller.signal, + queue: () => undefined, + }); + + controller.abort(); + expect(stub.transactions[0]?.abort).toHaveBeenCalledTimes(1); + stub.transactions[0]?.onabort?.(new Event("abort")); + + await expect(pending).resolves.toEqual({ + ok: false, + error: { cause: "CALLER_ABORT" }, + }); + }); + + it("returns CALLER_ABORT without opening a transaction for an aborted signal", async () => { + const stub = stubDatabase(); + const controller = new AbortController(); + controller.abort(); + + await expect( + runIndexedDbTransaction({ + database: stub.database, + stores: ["rows"], + mode: "readonly", + translate: recordingTranslate(), + signal: controller.signal, + queue: () => undefined, + }), + ).resolves.toEqual({ ok: false, error: { cause: "CALLER_ABORT" } }); + expect(stub.calls).toHaveLength(0); + }); + + it("maps a throw from transaction creation", async () => { + const boom = new DOMException("closed", "InvalidStateError"); + const database = { + transaction: () => { + throw boom; + }, + } as unknown as IDBDatabase; + + await expect( + runIndexedDbTransaction({ + database, + stores: ["rows"], + mode: "readonly", + translate: recordingTranslate(), + queue: () => undefined, + }), + ).resolves.toEqual({ + ok: false, + error: { cause: "NATIVE_EXCEPTION", detail: boom }, + }); + }); + + it("maps a throw from the queue callback and aborts", async () => { + const { database, memory } = await seededDatabase(); + const boom = new Error("queue defect"); + + const result = await runIndexedDbTransaction({ + database, + stores: ["rows"], + mode: "readwrite", + translate: recordingTranslate(), + queue: (transaction) => { + transaction.objectStore("rows").put({ id: "e", rank: 5 }); + throw boom; + }, + }); + + expect(result).toEqual({ + ok: false, + error: { cause: "NATIVE_EXCEPTION", detail: boom }, + }); + expect(memory.readRaw("rows", "e")).toBeUndefined(); + }); + + it("an abort after succeed reports a failure rather than the value", async () => { + const stub = stubDatabase(); + const pending = runIndexedDbTransaction({ + database: stub.database, + stores: ["rows"], + mode: "readwrite", + translate: recordingTranslate(), + queue: (_transaction, context) => { + context.succeed("value"); + context.fail({ cause: "CLOSED" }); + }, + }); + + const transaction = stub.transactions[0]; + if (!transaction) throw new Error("no transaction"); + transaction.error = new DOMException("aborted", "AbortError"); + transaction.onabort?.(new Event("abort")); + + const result = await pending; + expect(result.ok).toBe(false); + if (result.ok) return; + // The first candidate wins, so the later `fail` never becomes the value; + // an aborted transaction still cannot report the success it never kept. + expect(result.error.cause).toBe("NATIVE_EXCEPTION"); + }); +}); + +describe("IndexedDB transaction factory", () => { + it("omits the options bag entirely for an undefined durability", () => { + const stub = stubDatabase(); + openIndexedDbTransaction(stub.database, ["rows"], "readonly"); + expect(stub.calls).toEqual([[["rows"], "readonly"]]); + }); + + it("passes a named durability as an options bag", () => { + const stub = stubDatabase(); + openIndexedDbTransaction(stub.database, ["rows"], "readwrite", "strict"); + expect(stub.calls).toEqual([ + [["rows"], "readwrite", { durability: "strict" }], + ]); + }); + + it("falls back to the no-options form when the engine rejects the bag", () => { + const stub = stubDatabase({ rejectOptionsBag: true }); + openIndexedDbTransaction(stub.database, ["rows"], "readwrite", "relaxed"); + expect(stub.calls).toEqual([ + [["rows"], "readwrite", { durability: "relaxed" }], + [["rows"], "readwrite"], + ]); + }); + + it("rethrows a non-TypeError from transaction creation", () => { + const boom = new DOMException("closed", "InvalidStateError"); + const database = { + transaction: () => { + throw boom; + }, + } as unknown as IDBDatabase; + expect(() => + openIndexedDbTransaction(database, ["rows"], "readonly", "strict"), + ).toThrow(boom); + }); +}); + +describe("IndexedDB cursor pump", () => { + async function walk( + input: Readonly<{ + visit: ( + visit: Readonly<{ + cursor: IDBCursorWithValue; + scannedRows: number; + resume: (step: IndexedDbCursorStep) => void; + }>, + ) => IndexedDbCursorStep; + budget?: Parameters>[0]["budget"]; + signal?: AbortSignal; + store?: IDBObjectStore | undefined; + }>, + ): Promise< + Readonly<{ + result: Awaited>>; + }> + > { + const { database } = await seededDatabase(); + const result = await runIndexedDbTransaction< + IndexedDbWalkSummary, + TestFailure + >({ + database, + stores: ["rows"], + mode: "readwrite", + translate: recordingTranslate(), + queue: (transaction, context) => { + const store = transaction.objectStore("rows"); + walkIndexedDbCursor({ + request: store.openCursor(), + sink: context, + translate: recordingTranslate(), + ...(input.budget ? { budget: input.budget } : {}), + ...(input.signal ? { signal: input.signal } : {}), + visit: input.visit, + done: (summary) => context.succeed(summary), + }); + }, + }); + return { result }; + } + + it("visits every row and reports EXHAUSTED", async () => { + const visited: string[] = []; + const { result } = await walk({ + visit: ({ cursor }) => { + visited.push((cursor.value as Row).id); + return { kind: "CONTINUE" }; + }, + }); + + expect(visited).toEqual(["a", "b", "c", "d"]); + expect(result).toEqual({ + ok: true, + value: { reason: "EXHAUSTED", scannedRows: 4 }, + }); + }); + + it("ends the walk where the visitor stops it", async () => { + const { result } = await walk({ + visit: ({ scannedRows }) => + scannedRows === 2 ? { kind: "STOP" } : { kind: "CONTINUE" }, + }); + + expect(result).toEqual({ + ok: true, + value: { reason: "STOPPED", scannedRows: 2 }, + }); + }); + + it("resumes a row after the visitor's own nested request chain", async () => { + // Without SUSPEND the pump is unusable by runtime and maintenance: every + // walk there issues nested requests before advancing. + const order: string[] = []; + const { database } = await seededDatabase(); + const result = await runIndexedDbTransaction< + IndexedDbWalkSummary, + TestFailure + >({ + database, + stores: ["rows"], + mode: "readwrite", + translate: recordingTranslate(), + queue: (transaction, context) => { + const store = transaction.objectStore("rows"); + walkIndexedDbCursor({ + request: store.openCursor(), + sink: context, + translate: recordingTranslate(), + visit: ({ cursor, resume }) => { + const id = (cursor.value as Row).id; + order.push(`visit:${id}`); + onIndexedDbRequest(store.get(id), context, (value) => { + order.push(`nested:${(value as Row).id}`); + resume({ kind: "CONTINUE" }); + // Idempotent: a second resume cannot advance the cursor twice. + resume({ kind: "CONTINUE" }); + }); + return { kind: "SUSPEND" }; + }, + done: (summary) => context.succeed(summary), + }); + }, + }); + + expect(result).toEqual({ + ok: true, + value: { reason: "EXHAUSTED", scannedRows: 4 }, + }); + expect(order).toEqual([ + "visit:a", + "nested:a", + "visit:b", + "nested:b", + "visit:c", + "nested:c", + "visit:d", + "nested:d", + ]); + }); + + it("supports both keyed resume forms", async () => { + const skipped: string[] = []; + const { result } = await walk({ + visit: ({ cursor, scannedRows }) => { + skipped.push((cursor.value as Row).id); + if (scannedRows === 1) return { kind: "CONTINUE_FROM", key: "c" }; + if (scannedRows === 2) { + return { kind: "CONTINUE_PRIMARY", key: "d", primaryKey: "d" }; + } + return { kind: "CONTINUE" }; + }, + }); + + expect(skipped).toEqual(["a", "c", "d"]); + expect(result).toEqual({ + ok: true, + value: { reason: "EXHAUSTED", scannedRows: 3 }, + }); + }); + + it("stops on a row budget and on a time budget with distinct reasons", async () => { + const rowBudget = await walk({ + budget: { + admit: (scannedRows) => + scannedRows >= 2 + ? { ok: true, value: "ROW_BUDGET" } + : { ok: true, value: "CONTINUE" }, + }, + visit: () => ({ kind: "CONTINUE" }), + }); + expect(rowBudget.result).toEqual({ + ok: true, + value: { reason: "ROW_BUDGET", scannedRows: 2 }, + }); + + const timeBudget = await walk({ + budget: { + admit: (scannedRows) => + scannedRows >= 1 + ? { ok: true, value: "TIME_BUDGET" } + : { ok: true, value: "CONTINUE" }, + }, + visit: () => ({ kind: "CONTINUE" }), + }); + expect(timeBudget.result).toEqual({ + ok: true, + value: { reason: "TIME_BUDGET", scannedRows: 1 }, + }); + }); + + it("routes an unreadable budget clock into the sink instead of continuing", async () => { + const { result } = await walk({ + budget: { + admit: () => ({ ok: false, error: { cause: "UNSUPPORTED" } }), + }, + visit: () => ({ kind: "CONTINUE" }), + }); + + expect(result).toEqual({ ok: false, error: { cause: "UNSUPPORTED" } }); + }); + + it("aborts the transaction and ends the walk when the caller signal fired", async () => { + const controller = new AbortController(); + const { result } = await walk({ + signal: controller.signal, + visit: ({ cursor }) => { + if ((cursor.value as Row).id === "a") controller.abort(); + return { kind: "CONTINUE" }; + }, + }); + + expect(result).toEqual({ ok: false, error: { cause: "CALLER_ABORT" } }); + }); + + it("routes a native advance failure through the sink", async () => { + const { result } = await walk({ + visit: ({ cursor }) => { + // Advancing twice is an InvalidStateError in the engine; the pump must + // report it rather than let it escape the event handler. + cursor.continue(); + return { kind: "CONTINUE" }; + }, + }); + + expect(result.ok).toBe(false); + if (result.ok) return; + expect(result.error.cause).toBe("NATIVE_EXCEPTION"); + }); + + it("reports a cursor request error through requestFailed and stops", () => { + const stub = stubSink(); + const request = { + result: null, + error: new DOMException("gone", "UnknownError"), + onsuccess: null as ((event: Event) => unknown) | null, + onerror: null as ((event: Event) => unknown) | null, + }; + const done = vi.fn(); + walkIndexedDbCursor({ + request: request as unknown as IDBRequest, + sink: stub.sink, + translate: recordingTranslate(), + visit: () => ({ kind: "CONTINUE" }), + done, + }); + + request.onerror?.(new Event("error")); + expect(stub.requestErrors).toEqual([request.error]); + // The transaction's own outcome decides the result; the walk has no value. + expect(done).not.toHaveBeenCalled(); + }); + + it("routes a throw from the visitor into the sink", () => { + const stub = stubSink(); + const boom = new Error("visitor defect"); + const request = { + result: { value: { id: "a" }, continue: vi.fn() }, + error: null, + onsuccess: null as ((event: Event) => unknown) | null, + onerror: null as ((event: Event) => unknown) | null, + }; + walkIndexedDbCursor({ + request: request as unknown as IDBRequest, + sink: stub.sink, + translate: recordingTranslate(), + visit: () => { + throw boom; + }, + done: vi.fn(), + }); + + request.onsuccess?.(new Event("success")); + // A defective visitor must abort rather than let a partial write commit. + expect(stub.failures).toEqual([ + { cause: "NATIVE_EXCEPTION", detail: boom }, + ]); + }); + + it("ignores resume when the visitor did not suspend", () => { + const stub = stubSink(); + const advance = vi.fn(); + const request = { + result: { value: { id: "a" }, continue: advance }, + error: null, + onsuccess: null as ((event: Event) => unknown) | null, + onerror: null as ((event: Event) => unknown) | null, + }; + walkIndexedDbCursor({ + request: request as unknown as IDBRequest, + sink: stub.sink, + translate: recordingTranslate(), + visit: ({ resume }) => { + resume({ kind: "CONTINUE" }); + return { kind: "STOP" }; + }, + done: vi.fn(), + }); + + request.onsuccess?.(new Event("success")); + expect(advance).not.toHaveBeenCalled(); + }); +}); diff --git a/tests/unit/legacy-and-optional-network-remediation.test.ts b/tests/unit/legacy-and-optional-network-remediation.test.ts index a66b870..5c24f2e 100644 --- a/tests/unit/legacy-and-optional-network-remediation.test.ts +++ b/tests/unit/legacy-and-optional-network-remediation.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from "vitest"; -import { createCursorPaginationRuntime } from "../../src/adapters/query-cache/cursor-pagination-runtime.ts"; +import { createCursorPaginationRuntime } from "../../src/adapters/query-cache/index.ts"; import { defineMutationIntent, isValidIdempotencyKey, @@ -8,8 +8,8 @@ import { import type { CursorPage, CursorPaginationProfile, -} from "../../src/contracts/cursor-pagination.ts"; -import type { Result } from "../../src/application/result.ts"; +} from "../../src/adapters/query-cache/index.ts"; +import type { Result } from "../../src/contracts/result.ts"; const PROFILE: CursorPaginationProfile = Object.freeze({ profileId: "TEST_PAGINATION_V1", diff --git a/tests/unit/presigned-transfer-delivery.test.ts b/tests/unit/presigned-transfer-delivery.test.ts new file mode 100644 index 0000000..65d7f0d --- /dev/null +++ b/tests/unit/presigned-transfer-delivery.test.ts @@ -0,0 +1,420 @@ +import { describe, expect, it, vi } from "vitest"; + +import { + BrowserFilePolicyRegistry, + browserFilePolicyReference, +} from "../../src/adapters/browser-files/browser-file-policy-registry.ts"; +import { + createDownloadDeliveryAdapter, + type SaveFileHandle, +} from "../../src/adapters/browser-files/download-delivery-adapter.ts"; +import { + CHECKSUM_HEADER, + CONTROL_ENDPOINT, + DATA_ORIGIN, + DIGEST_HEADER, + DOWNLOAD_HREF, + DOWNLOAD_PATH, + NOW, + POLICY_HEADER, + REQUEST_BINDING_SHA256, + UPLOAD_SESSION_ID, + collect, + createHarness, + downloadCapabilityPayload, + downloadResponse, + jsonResponse, + responseWithUrl, + uploadCapabilityPayload, +} from "./presigned-transfer-fixture.ts"; + +describe("presigned DownloadDelivery integration", () => { + it("connects an issued capability to DownloadDeliveryPort without caller digest input", async () => { + const bytes = new TextEncoder().encode("verified"); + const payload = downloadCapabilityPayload(bytes); + const fetcher = vi.fn(async (input: RequestInfo | URL) => + String(input) === CONTROL_ENDPOINT + ? jsonResponse(payload) + : downloadResponse(bytes.slice().buffer, payload), + ) as unknown as typeof fetch; + const { provider, executor } = createHarness({ fetcher }); + const issued = await provider.issueDownload({ + resourceId: "resource-1", + signal: new AbortController().signal, + }); + expect(issued.ok).toBe(true); + if (!issued.ok) return; + + const policy = browserFilePolicyReference( + "download", + "presigned-stream", + ); + const policies = new BrowserFilePolicyRegistry({ + profiles: [ + { + reference: policy, + download: { + strategy: "PROMPT_AND_STREAM", + mediaType: "application/octet-stream", + safeExtension: ".bin", + maxTransferBytes: 64, + maxBufferedBytes: 8, + integrity: "REQUIRED", + }, + }, + ], + hardLimits: { + maxInspectionBytes: 64, + maxRetainedFileBytes: 64, + maxPreviewBytes: 64, + maxObjectUrlBytes: 64, + maxTransferBytes: 64, + }, + }); + const written: number[] = []; + const handle: SaveFileHandle = { + async createWritable() { + return new WritableStream({ + write(chunk) { + written.push(...chunk); + }, + }); + }, + }; + const downloads = createDownloadDeliveryAdapter({ + host: { handoff() {} }, + policies, + hardMaxObjectUrlBytes: 64, + hardMaxTransferBytes: 64, + browserManagedCapabilities: { + resolve() { + throw new TypeError("not used"); + }, + }, + openAuthorizedSource: + executor.downloadSources.open.bind(executor.downloadSources), + showSaveFilePicker: async () => handle, + userActivation: { isActive: true }, + now: () => NOW, + }); + const result = await downloads.deliver({ + policy, + source: { + kind: "AUTHORIZED_STREAM_RESOURCE", + resourceId: "resource-1", + capability: issued.value, + }, + suggestedFileName: "artifact.bin", + signal: new AbortController().signal, + onProgress() {}, + }); + expect(result).toMatchObject({ + ok: true, + value: { + kind: "SAVED", + integrity: "VERIFIED", + bytesWritten: bytes.byteLength, + }, + }); + expect(written).toEqual([...bytes]); + }); + + /** + * TR-RR-04. A presigned byte source owns a fetch reader and a capability + * lease, and its port requires `close()`. The delivery consumer never called + * it, so every outcome — success, validation failure, writer failure and + * abort — leaked both. + */ + it.each([ + { label: "success", mode: "SUCCESS" as const }, + { label: "writer failure", mode: "WRITER_FAILURE" as const }, + { label: "abort", mode: "ABORT" as const }, + ])("closes the presigned source exactly once on $label", async ({ mode }) => { + const bytes = new Uint8Array([1, 2, 3]); + let closes = 0; + const controller = new AbortController(); + const source = { + byteLength: bytes.byteLength, + integrity: "VERIFIED_ON_SUCCESSFUL_EXHAUSTION" as const, + capability: undefined as never, + close() { + closes += 1; + }, + async *stream() { + if (mode === "ABORT") controller.abort(); + yield { ok: true as const, value: bytes }; + }, + }; + const capability = Object.freeze({ + capabilityReceipt: "capability-close-1", + method: "GET" as const, + binding: { kind: "DOWNLOAD" as const, resourceId: "resource-1" }, + mediaType: "application/octet-stream", + byteLength: bytes.byteLength, + maxBytes: bytes.byteLength, + expectedSha256: "a".repeat(64), + expiresAtEpochMs: NOW + 60_000, + }); + source.capability = capability as never; + + const closePolicy = browserFilePolicyReference( + "download", + "presigned-close", + ); + const policies = new BrowserFilePolicyRegistry({ + profiles: [ + { + reference: closePolicy, + download: { + strategy: "PROMPT_AND_STREAM", + mediaType: "application/octet-stream", + safeExtension: ".bin", + maxTransferBytes: 64, + maxBufferedBytes: 8, + integrity: "REQUIRED", + }, + }, + ], + hardLimits: { + maxInspectionBytes: 64, + maxRetainedFileBytes: 64, + maxPreviewBytes: 64, + maxObjectUrlBytes: 64, + maxTransferBytes: 64, + }, + }); + const handle: SaveFileHandle = { + async createWritable() { + return new WritableStream({ + write() { + if (mode === "WRITER_FAILURE") { + throw new TypeError("writer exploded"); + } + }, + }); + }, + }; + const downloads = createDownloadDeliveryAdapter({ + host: { handoff() {} }, + policies, + hardMaxObjectUrlBytes: 64, + hardMaxTransferBytes: 64, + browserManagedCapabilities: { + resolve() { + throw new TypeError("not used"); + }, + }, + openAuthorizedSource: async () => + ({ ok: true, value: source }) as never, + showSaveFilePicker: async () => handle, + userActivation: { isActive: true }, + now: () => NOW, + }); + + const deliveryResult = await downloads.deliver({ + policy: closePolicy, + source: { + kind: "AUTHORIZED_STREAM_RESOURCE", + resourceId: "resource-1", + capability: capability as never, + }, + suggestedFileName: "artifact.bin", + signal: controller.signal, + onProgress() {}, + }); + + void deliveryResult; + expect(closes).toBe(1); + }); + + /** + * TR-02. A lease that resolved after the abort already ended the delivery + * never reached the holder, so nothing closed it: the fetch reader and the + * capability lease outlived the terminal result. + */ + it("closes a source lease that arrives after the delivery was aborted", async () => { + const bytes = new Uint8Array([1, 2, 3]); + let closes = 0; + const controller = new AbortController(); + let releaseOpen: + | ((value: { ok: true; value: unknown }) => void) + | undefined; + const source = { + byteLength: bytes.byteLength, + integrity: "VERIFIED_ON_SUCCESSFUL_EXHAUSTION" as const, + capability: undefined as never, + close() { + closes += 1; + }, + async *stream() { + yield { ok: true as const, value: bytes }; + }, + }; + const capability = Object.freeze({ + capabilityReceipt: "capability-late-1", + method: "GET" as const, + binding: { kind: "DOWNLOAD" as const, resourceId: "resource-1" }, + mediaType: "application/octet-stream", + byteLength: bytes.byteLength, + maxBytes: bytes.byteLength, + expectedSha256: "a".repeat(64), + expiresAtEpochMs: NOW + 60_000, + }); + source.capability = capability as never; + + const latePolicy = browserFilePolicyReference("download", "presigned-late"); + const policies = new BrowserFilePolicyRegistry({ + profiles: [ + { + reference: latePolicy, + download: { + strategy: "PROMPT_AND_STREAM", + mediaType: "application/octet-stream", + safeExtension: ".bin", + maxTransferBytes: 64, + maxBufferedBytes: 8, + integrity: "REQUIRED", + }, + }, + ], + hardLimits: { + maxInspectionBytes: 64, + maxRetainedFileBytes: 64, + maxPreviewBytes: 64, + maxObjectUrlBytes: 64, + maxTransferBytes: 64, + }, + }); + const downloads = createDownloadDeliveryAdapter({ + host: { handoff() {} }, + policies, + hardMaxObjectUrlBytes: 64, + hardMaxTransferBytes: 64, + browserManagedCapabilities: { + resolve() { + throw new TypeError("not used"); + }, + }, + // Ignores the signal entirely and resolves only when the test says so. + openAuthorizedSource: () => + new Promise((resolve) => { + releaseOpen = resolve as never; + }) as never, + showSaveFilePicker: async () => ({ + async createWritable() { + return new WritableStream({ write() {} }); + }, + }), + userActivation: { isActive: true }, + now: () => NOW, + }); + + const delivering = downloads.deliver({ + policy: latePolicy, + source: { + kind: "AUTHORIZED_STREAM_RESOURCE", + resourceId: "resource-1", + capability: capability as never, + }, + suggestedFileName: "artifact.bin", + signal: controller.signal, + onProgress() {}, + }); + await new Promise((resolve) => setTimeout(resolve, 0)); + controller.abort(); + const delivered = await delivering; + expect(delivered.ok).toBe(false); + + // The lease arrives only now, long after the terminal result. + releaseOpen?.({ ok: true, value: source }); + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(closes).toBe(1); + }); + + it("does not leave a late rejection unhandled after an abort", async () => { + const unhandled: unknown[] = []; + const onUnhandled = (reason: unknown) => unhandled.push(reason); + process.on("unhandledRejection", onUnhandled); + try { + const controller = new AbortController(); + let rejectOpen: ((reason: unknown) => void) | undefined; + const rejectPolicy = browserFilePolicyReference( + "download", + "presigned-late-reject", + ); + const policies = new BrowserFilePolicyRegistry({ + profiles: [ + { + reference: rejectPolicy, + download: { + strategy: "PROMPT_AND_STREAM", + mediaType: "application/octet-stream", + safeExtension: ".bin", + maxTransferBytes: 64, + maxBufferedBytes: 8, + integrity: "REQUIRED", + }, + }, + ], + hardLimits: { + maxInspectionBytes: 64, + maxRetainedFileBytes: 64, + maxPreviewBytes: 64, + maxObjectUrlBytes: 64, + maxTransferBytes: 64, + }, + }); + const downloads = createDownloadDeliveryAdapter({ + host: { handoff() {} }, + policies, + hardMaxObjectUrlBytes: 64, + hardMaxTransferBytes: 64, + browserManagedCapabilities: { + resolve() { + throw new TypeError("not used"); + }, + }, + openAuthorizedSource: () => + new Promise((_resolve, reject) => { + rejectOpen = reject; + }) as never, + showSaveFilePicker: async () => ({ + async createWritable() { + return new WritableStream({ write() {} }); + }, + }), + userActivation: { isActive: true }, + now: () => NOW, + }); + + const delivering = downloads.deliver({ + policy: rejectPolicy, + source: { + kind: "AUTHORIZED_STREAM_RESOURCE", + resourceId: "resource-1", + capability: Object.freeze({ + capabilityReceipt: "capability-late-2", + method: "GET" as const, + binding: { kind: "DOWNLOAD" as const, resourceId: "resource-1" }, + mediaType: "application/octet-stream", + byteLength: 3, + maxBytes: 3, + expectedSha256: "a".repeat(64), + expiresAtEpochMs: NOW + 60_000, + }) as never, + }, + suggestedFileName: "artifact.bin", + signal: controller.signal, + onProgress() {}, + }); + await new Promise((resolve) => setTimeout(resolve, 0)); + controller.abort(); + await delivering; + + rejectOpen?.(new Error("late open failure")); + await new Promise((resolve) => setTimeout(resolve, 10)); + expect(unhandled).toEqual([]); + } finally { + process.off("unhandledRejection", onUnhandled); + } + });}); diff --git a/tests/unit/presigned-transfer-download.test.ts b/tests/unit/presigned-transfer-download.test.ts new file mode 100644 index 0000000..998897d --- /dev/null +++ b/tests/unit/presigned-transfer-download.test.ts @@ -0,0 +1,650 @@ +import { describe, expect, it, vi } from "vitest"; + +import { PRESIGNED_TRANSFER_PROTOCOL } from "../../src/application/ports/browser-transfer/presigned-transfer.ts"; +import { createPresignedCapabilityVault } from "../../src/adapters/browser-transfer/presigned/presigned-capability-vault.ts"; +import { sha256Hex } from "../../src/adapters/browser-transfer/presigned/incremental-sha256.ts"; +import { + CHECKSUM_HEADER, + CONTROL_ENDPOINT, + DATA_ORIGIN, + DIGEST_HEADER, + DOWNLOAD_HREF, + DOWNLOAD_PATH, + NOW, + POLICY_HEADER, + REQUEST_BINDING_SHA256, + UPLOAD_SESSION_ID, + collect, + createHarness, + downloadCapabilityPayload, + downloadResponse, + jsonResponse, + responseWithUrl, + uploadCapabilityPayload, +} from "./presigned-transfer-fixture.ts"; + +describe("presigned download stream lifecycle", () => { + describe("TR-01 the stored capability is the one that was validated", () => { + const baseRegistration = () => ({ + protocol: PRESIGNED_TRANSFER_PROTOCOL, + capabilityReceipt: "capability-snapshot-1", + method: "GET" as const, + binding: { kind: "DOWNLOAD" as const, resourceId: "resource-1" }, + href: `${DATA_ORIGIN}${DOWNLOAD_PATH}`, + origin: DATA_ORIGIN, + path: DOWNLOAD_PATH, + allowedQueryParameters: [], + requestHeaders: [{ name: "x-safe", value: "1" }], + requiredResponseHeaders: [], + digestRequestHeader: null, + digestResponseHeader: null, + receiptResponseHeader: null, + expectedStatus: 200, + expectedResponseByteLength: 3, + mediaType: "application/octet-stream", + byteLength: 3, + maxBytes: 3, + expectedSha256: "a".repeat(64), + expiresAtEpochMs: NOW + 60_000, + }); + + const freshVault = () => + createPresignedCapabilityVault({ + now: () => NOW, + maxActiveCapabilities: 4, + }); + + it("refuses a header row that answers differently on a second read", () => { + const vault = freshVault(); + let nameReads = 0; + const header = new Proxy( + { name: "x-safe", value: "1" }, + { + getOwnPropertyDescriptor(target, key) { + if (key === "name") { + nameReads += 1; + return { + configurable: true, + enumerable: true, + value: nameReads > 1 ? "authorization" : "x-safe", + }; + } + return Reflect.getOwnPropertyDescriptor(target, key); + }, + }, + ); + + const registered = vault.register({ + ...baseRegistration(), + requestHeaders: [header], + } as never); + + if (registered.ok) { + // A single read means the value that was checked is the value stored. + const resolved = vault.resolve(registered.value); + expect(resolved.ok).toBe(true); + if (resolved.ok) { + expect(resolved.value.requestHeaders.map((row) => row.name)).toEqual([ + "x-safe", + ]); + } + } + vault.dispose(); + }); + + const hostileRegistrations: readonly (readonly [string, () => unknown])[] = [ + [ + "an accessor field", + () => + Object.defineProperty(baseRegistration(), "href", { + enumerable: true, + get: () => `${DATA_ORIGIN}${DOWNLOAD_PATH}`, + }), + ], + [ + "an inherited field", + () => Object.assign(Object.create({ injected: true }), baseRegistration()), + ], + [ + "a symbol field", + () => ({ ...baseRegistration(), [Symbol.for("injected")]: true }), + ], + [ + "a non-enumerable own field", + () => + Object.defineProperty(baseRegistration(), "injected", { + enumerable: false, + value: true, + }), + ], + [ + "a throwing ownKeys trap", + () => + new Proxy(baseRegistration(), { + ownKeys() { + throw new TypeError("hostile ownKeys trap"); + }, + }), + ], + [ + "a null header array", + () => ({ ...baseRegistration(), requestHeaders: null }), + ], + [ + "a non-iterable header array", + () => ({ ...baseRegistration(), requestHeaders: { length: 1 } }), + ], + [ + "a header row with an extra field", + () => ({ + ...baseRegistration(), + requestHeaders: [{ name: "x-safe", value: "1", injected: true }], + }), + ], + [ + "an accessor header name", + () => ({ + ...baseRegistration(), + requestHeaders: [ + Object.defineProperty({ value: "1" }, "name", { + enumerable: true, + get: () => "x-safe", + }), + ], + }), + ], + [ + "a binding with an extra field", + () => ({ + ...baseRegistration(), + binding: { kind: "DOWNLOAD", resourceId: "r", injected: true }, + }), + ], + [ + "a null binding", + () => ({ ...baseRegistration(), binding: null }), + ], + ]; + + for (const [label, build] of hostileRegistrations) { + it(`rejects ${label} as POLICY_REJECTED`, () => { + const vault = freshVault(); + expect(vault.register(build() as never)).toMatchObject({ + ok: false, + error: { code: "POLICY_REJECTED" }, + }); + vault.dispose(); + }); + } + + it("does not observe a mutation of the issuer's object after registration", () => { + const vault = freshVault(); + const registration = baseRegistration(); + const registered = vault.register(registration as never); + expect(registered.ok).toBe(true); + if (!registered.ok) return; + + registration.requestHeaders[0]!.name = "authorization"; + registration.expiresAtEpochMs = NOW + 999_999; + + const resolved = vault.resolve(registered.value); + expect(resolved.ok).toBe(true); + if (!resolved.ok) return; + expect(resolved.value.requestHeaders.map((row) => row.name)).toEqual([ + "x-safe", + ]); + expect(resolved.value.expiresAtEpochMs).toBe(NOW + 60_000); + vault.dispose(); + }); + }); + + it("does not fetch a presigned download until stream consumption", async () => { + const bytes = new Uint8Array([1, 2, 3]); + const responsePayload = downloadCapabilityPayload(bytes); + let downloadFetches = 0; + const fetcher = vi.fn(async (input: RequestInfo | URL) => { + if (String(input) === CONTROL_ENDPOINT) { + return jsonResponse(responsePayload); + } + downloadFetches += 1; + return downloadResponse(bytes.slice().buffer, responsePayload); + }) as unknown as typeof fetch; + const { provider, executor } = createHarness({ fetcher }); + const signal = new AbortController().signal; + const issued = await provider.issueDownload({ + resourceId: "resource-1", + signal, + }); + expect(issued.ok).toBe(true); + if (!issued.ok) return; + + const opened = await executor.downloadSources.open({ + resourceId: "resource-1", + capability: issued.value, + signal, + }); + expect(opened.ok).toBe(true); + if (!opened.ok) return; + // BT-PRE-01. open() performs no network I/O. + expect(downloadFetches).toBe(0); + + for await (const chunk of opened.value.stream(signal)) { + expect(chunk.ok).toBe(true); + } + expect(downloadFetches).toBe(1); + opened.value.close(); + }); + + it("closes an unused download source without network I/O", async () => { + const bytes = new Uint8Array([1, 2, 3]); + const responsePayload = downloadCapabilityPayload(bytes); + let downloadFetches = 0; + const fetcher = vi.fn(async (input: RequestInfo | URL) => { + if (String(input) === CONTROL_ENDPOINT) { + return jsonResponse(responsePayload); + } + downloadFetches += 1; + return downloadResponse(bytes.slice().buffer, responsePayload); + }) as unknown as typeof fetch; + const { provider, executor } = createHarness({ fetcher }); + const signal = new AbortController().signal; + const issued = await provider.issueDownload({ + resourceId: "resource-1", + signal, + }); + expect(issued.ok).toBe(true); + if (!issued.ok) return; + + const opened = await executor.downloadSources.open({ + resourceId: "resource-1", + capability: issued.value, + signal, + }); + expect(opened.ok).toBe(true); + if (!opened.ok) return; + + opened.value.close(); + // close() is idempotent and never starts the transfer. + opened.value.close(); + expect(downloadFetches).toBe(0); + + // A stream after close is one terminal conflict, still without fetching. + const results = []; + for await (const chunk of opened.value.stream(signal)) { + results.push(chunk); + } + expect(results).toMatchObject([ + { ok: false, error: { code: "CONFLICT" } }, + ]); + expect(downloadFetches).toBe(0); + }); + + it.each([ + { + name: "truncation", + body: new Uint8Array([1, 2]), + expectedCode: "INTEGRITY_FAILED", + }, + { + name: "overrun", + body: new Uint8Array([1, 2, 3, 4]), + expectedCode: "INTEGRITY_FAILED", + }, + ])("closes $name as a terminal stream failure", async ({ body, expectedCode }) => { + const declared = new Uint8Array([1, 2, 3]); + const payload = downloadCapabilityPayload(declared); + const fetcher = vi.fn(async (input: RequestInfo | URL) => + String(input) === CONTROL_ENDPOINT + ? jsonResponse(payload) + : downloadResponse(body.slice().buffer, payload), + ) as unknown as typeof fetch; + const { provider, executor } = createHarness({ fetcher }); + const issued = await provider.issueDownload({ + resourceId: "resource-1", + signal: new AbortController().signal, + }); + expect(issued.ok).toBe(true); + if (!issued.ok) return; + const opened = await executor.downloadSources.open({ + resourceId: "resource-1", + capability: issued.value, + signal: new AbortController().signal, + }); + expect(opened.ok).toBe(true); + if (!opened.ok) return; + const results = await collect(opened.value); + expect(results.at(-1)).toMatchObject({ + ok: false, + error: { code: expectedCode }, + }); + const firstFailure = results.findIndex((result) => !result.ok); + expect(results.slice(firstFailure + 1)).toEqual([]); + }); + + it("closes native body errors without throwing across the port", async () => { + const bytes = new Uint8Array([1, 2, 3]); + const payload = downloadCapabilityPayload(bytes); + const failingBody = new ReadableStream({ + pull(controller) { + controller.error(new DOMException("secret native detail", "NetworkError")); + }, + }); + const fetcher = vi.fn(async (input: RequestInfo | URL) => + String(input) === CONTROL_ENDPOINT + ? jsonResponse(payload) + : downloadResponse(failingBody, payload), + ) as unknown as typeof fetch; + const { provider, executor } = createHarness({ fetcher }); + const issued = await provider.issueDownload({ + resourceId: "resource-1", + signal: new AbortController().signal, + }); + expect(issued.ok).toBe(true); + if (!issued.ok) return; + const opened = await executor.downloadSources.open({ + resourceId: "resource-1", + capability: issued.value, + signal: new AbortController().signal, + }); + expect(opened.ok).toBe(true); + if (!opened.ok) return; + await expect(collect(opened.value)).resolves.toMatchObject([ + { + ok: false, + error: { + code: "NOT_READABLE", + recovery: "REISSUE_CAPABILITY", + }, + }, + ]); + }); + + it("closes active abort and timeout without leaking native rejection", async () => { + const bytes = new Uint8Array([1]); + const payload = downloadCapabilityPayload(bytes); + const neverBody = () => + new ReadableStream({ pull() {} }); + const fetcher = vi.fn(async (input: RequestInfo | URL) => + String(input) === CONTROL_ENDPOINT + ? jsonResponse(payload) + : downloadResponse(neverBody(), payload), + ) as unknown as typeof fetch; + const controller = new AbortController(); + let harness = createHarness({ fetcher }); + let issued = await harness.provider.issueDownload({ + resourceId: "resource-1", + signal: controller.signal, + }); + expect(issued.ok).toBe(true); + if (!issued.ok) return; + let opened = await harness.executor.downloadSources.open({ + resourceId: "resource-1", + capability: issued.value, + signal: controller.signal, + }); + expect(opened.ok).toBe(true); + if (!opened.ok) return; + const aborted = collect(opened.value, controller.signal); + controller.abort("user"); + expect(await aborted).toMatchObject([ + { ok: false, error: { code: "ABORTED" } }, + ]); + + let timeoutCallback: (() => void) | undefined; + const scheduler = { + setTimeout(callback: () => void) { + timeoutCallback = callback; + return 1; + }, + clearTimeout() {}, + }; + harness = createHarness({ fetcher, scheduler }); + issued = await harness.provider.issueDownload({ + resourceId: "resource-1", + signal: new AbortController().signal, + }); + expect(issued.ok).toBe(true); + if (!issued.ok) return; + opened = await harness.executor.downloadSources.open({ + resourceId: "resource-1", + capability: issued.value, + signal: new AbortController().signal, + }); + expect(opened.ok).toBe(true); + if (!opened.ok) return; + const timedOut = collect(opened.value); + timeoutCallback?.(); + expect(await timedOut).toMatchObject([ + { + ok: false, + error: { + code: "UNAVAILABLE", + recovery: "REISSUE_CAPABILITY", + }, + }, + ]); + }); + + it("rejects an expired capability before data-plane fetch", async () => { + const bytes = new Uint8Array([1]); + const payload = downloadCapabilityPayload(bytes); + let current = NOW; + const fetcher = vi.fn(async (input: RequestInfo | URL) => + String(input) === CONTROL_ENDPOINT + ? jsonResponse(payload) + : downloadResponse(bytes.slice().buffer, payload), + ) as unknown as typeof fetch; + const { provider, executor } = createHarness({ + fetcher, + now: () => current, + }); + const issued = await provider.issueDownload({ + resourceId: "resource-1", + signal: new AbortController().signal, + }); + expect(issued.ok).toBe(true); + if (!issued.ok) return; + current = Number(payload.expiresAtEpochMs) + 1; + expect( + await executor.downloadSources.open({ + resourceId: "resource-1", + capability: issued.value, + signal: new AbortController().signal, + }), + ).toMatchObject({ + ok: false, + error: { + code: "EXPIRED_RESOURCE", + recovery: "REISSUE_CAPABILITY", + }, + }); + expect(fetcher).toHaveBeenCalledTimes(1); + }); + + it("rejects capabilities below the configured minimum remaining lifetime", async () => { + const bytes = new Uint8Array([1]); + const nearExpiryPayload = downloadCapabilityPayload(bytes, { + expiresAtEpochMs: NOW + 999, + }); + let fetcher = vi.fn(async () => + jsonResponse(nearExpiryPayload), + ) as unknown as typeof fetch; + let harness = createHarness({ fetcher }); + expect( + await harness.provider.issueDownload({ + resourceId: "resource-1", + signal: new AbortController().signal, + }), + ).toMatchObject({ + ok: false, + error: { + code: "EXPIRED_RESOURCE", + recovery: "REISSUE_CAPABILITY", + }, + }); + + const acceptedPayload = downloadCapabilityPayload(bytes, { + expiresAtEpochMs: NOW + 2_000, + }); + let current = NOW; + fetcher = vi.fn(async (input: RequestInfo | URL) => + String(input) === CONTROL_ENDPOINT + ? jsonResponse(acceptedPayload) + : downloadResponse(bytes.slice().buffer, acceptedPayload), + ) as unknown as typeof fetch; + harness = createHarness({ + fetcher, + now: () => current, + }); + const issued = await harness.provider.issueDownload({ + resourceId: "resource-1", + signal: new AbortController().signal, + }); + expect(issued.ok).toBe(true); + if (!issued.ok) return; + current = NOW + 1_001; + expect( + await harness.executor.downloadSources.open({ + resourceId: "resource-1", + capability: issued.value, + signal: new AbortController().signal, + }), + ).toMatchObject({ + ok: false, + error: { + code: "EXPIRED_RESOURCE", + recovery: "REISSUE_CAPABILITY", + }, + }); + expect(fetcher).toHaveBeenCalledTimes(1); + }); + + it("closes malformed AbortSignal inputs at every public boundary", async () => { + const bytes = new Uint8Array([1, 2]); + const payload = downloadCapabilityPayload(bytes); + const uploadChecksum = sha256Hex(bytes); + const uploadPayload = uploadCapabilityPayload({ + bytes, + checksum: uploadChecksum, + }); + const fetcher = vi.fn( + async (input: RequestInfo | URL, init?: RequestInit) => { + if (String(input) === CONTROL_ENDPOINT) { + const request = JSON.parse(String(init?.body)) as { + method: string; + }; + return jsonResponse( + request.method === "GET" ? payload : uploadPayload, + ); + } + if (String(input) === DOWNLOAD_HREF) { + return downloadResponse(bytes.slice().buffer, payload); + } + return responseWithUrl( + new Response(null, { + status: 200, + headers: { + [POLICY_HEADER]: "v1", + "Content-Length": "0", + ETag: "\"part-etag-1\"", + }, + }), + String(uploadPayload.href), + ); + }, + ) as unknown as typeof fetch; + const { provider, executor } = createHarness({ fetcher }); + const malformed = {} as AbortSignal; + + expect( + await provider.issueDownload({ + resourceId: "resource-1", + signal: malformed, + }), + ).toMatchObject({ + ok: false, + error: { code: "INVALID_INPUT" }, + }); + expect( + await provider.issueUploadPart({ + sessionId: UPLOAD_SESSION_ID, + requestBindingSha256: REQUEST_BINDING_SHA256, + uploadBindingSha256: "b".repeat(64), + partNumber: 1, + offset: 0, + byteLength: bytes.byteLength, + checksumSha256: uploadChecksum, + mediaType: "application/octet-stream", + idempotencyKey: "part-attempt-1", + signal: malformed, + }), + ).toMatchObject({ + ok: false, + error: { code: "INVALID_INPUT" }, + }); + + const issuedDownload = await provider.issueDownload({ + resourceId: "resource-1", + signal: new AbortController().signal, + }); + expect(issuedDownload.ok).toBe(true); + if (!issuedDownload.ok) return; + expect( + await executor.downloadSources.open({ + resourceId: "resource-1", + capability: issuedDownload.value, + signal: malformed, + }), + ).toMatchObject({ + ok: false, + error: { code: "INVALID_INPUT" }, + }); + const opened = await executor.downloadSources.open({ + resourceId: "resource-1", + capability: issuedDownload.value, + signal: new AbortController().signal, + }); + expect(opened.ok).toBe(true); + if (!opened.ok) return; + expect(await collect(opened.value, malformed)).toMatchObject([ + { ok: false, error: { code: "INVALID_INPUT" } }, + ]); + expect(await collect(opened.value)).toMatchObject([ + { ok: false, error: { code: "CONFLICT" } }, + ]); + + const issuedUpload = await provider.issueUploadPart({ + sessionId: UPLOAD_SESSION_ID, + requestBindingSha256: REQUEST_BINDING_SHA256, + uploadBindingSha256: "b".repeat(64), + partNumber: 1, + offset: 0, + byteLength: bytes.byteLength, + checksumSha256: uploadChecksum, + mediaType: "application/octet-stream", + idempotencyKey: "part-attempt-1", + signal: new AbortController().signal, + }); + expect(issuedUpload.ok).toBe(true); + if (!issuedUpload.ok) return; + expect( + await executor.uploadParts.put({ + capability: issuedUpload.value, + sessionId: UPLOAD_SESSION_ID, + requestBindingSha256: REQUEST_BINDING_SHA256, + uploadBindingSha256: "b".repeat(64), + partNumber: 1, + offset: 0, + byteLength: bytes.byteLength, + checksumSha256: uploadChecksum, + idempotencyKey: "part-attempt-1", + bytes, + signal: malformed, + }), + ).toMatchObject({ + ok: false, + error: { code: "INVALID_INPUT" }, + }); + }); + +}); diff --git a/tests/unit/presigned-transfer-fixture.ts b/tests/unit/presigned-transfer-fixture.ts new file mode 100644 index 0000000..1fd63a8 --- /dev/null +++ b/tests/unit/presigned-transfer-fixture.ts @@ -0,0 +1,247 @@ +import { PRESIGNED_TRANSFER_PROTOCOL } from "../../src/application/ports/browser-transfer/presigned-transfer.ts"; +import type { + PresignedDownloadByteSource, +} from "../../src/application/ports/browser-transfer/presigned-transfer.ts"; +import { RESUMABLE_UPLOAD_PROTOCOL } from "../../src/application/ports/browser-transfer/resumable-upload.ts"; +import type { BrowserDataObservation } from "../../src/application/ports/browser-file-storage/shared.ts"; +import { + createPresignedCapabilityVault, + createSingleUsePresignedReplayGuard, +} from "../../src/adapters/browser-transfer/presigned/presigned-capability-vault.ts"; +import { createPresignedCapabilityHttpProvider } from "../../src/adapters/browser-transfer/presigned/presigned-capability-http-provider.ts"; +import { + createPresignedTransferExecutor, + type PresignedTransferExecutorOptions, +} from "../../src/adapters/browser-transfer/presigned/presigned-transfer-executor.ts"; +import { sha256Hex } from "../../src/adapters/browser-transfer/presigned/incremental-sha256.ts"; + +export const NOW = 1_000_000; +export const CONTROL_ENDPOINT = "https://api.example/capabilities"; +export const DATA_ORIGIN = "https://objects.example"; +export const DOWNLOAD_PATH = "/files/resource-1"; +export const DOWNLOAD_HREF = + `${DATA_ORIGIN}${DOWNLOAD_PATH}?sig=do-not-log-this`; +export const POLICY_HEADER = "x-policy-version"; +export const DIGEST_HEADER = "x-content-sha256"; +export const CHECKSUM_HEADER = "x-checksum-sha256"; +export const UPLOAD_SESSION_ID = "upload-session-1"; +export const REQUEST_BINDING_SHA256 = "c".repeat(64); + +export function downloadCapabilityPayload( + bytes: Uint8Array, + overrides: Readonly> = {}, +) { + const digest = sha256Hex(bytes); + return { + protocol: PRESIGNED_TRANSFER_PROTOCOL, + capabilityReceipt: "capability-download-1", + method: "GET", + binding: { + kind: "DOWNLOAD", + resourceId: "resource-1", + }, + href: DOWNLOAD_HREF, + origin: DATA_ORIGIN, + path: DOWNLOAD_PATH, + allowedQueryParameters: ["sig"], + requestHeaders: [ + { name: "accept", value: "application/octet-stream" }, + ], + requiredResponseHeaders: [ + { name: POLICY_HEADER, value: "v1" }, + ], + digestRequestHeader: null, + digestResponseHeader: DIGEST_HEADER, + receiptResponseHeader: null, + expectedStatus: 200, + expectedResponseByteLength: null, + mediaType: "application/octet-stream", + byteLength: bytes.byteLength, + maxBytes: 64, + expectedSha256: digest, + expiresAtEpochMs: NOW + 30_000, + singleUse: true, + ...overrides, + }; +} + +export type CapabilityPayload = ReturnType; + +export function uploadCapabilityPayload(input: Readonly<{ + bytes: Uint8Array; + checksum: string; +}>, overrides: Readonly> = {}) { + return { + protocol: PRESIGNED_TRANSFER_PROTOCOL, + capabilityReceipt: "capability-upload-1", + method: "PUT", + binding: { + kind: "UPLOAD_PART", + protocol: RESUMABLE_UPLOAD_PROTOCOL, + sessionId: UPLOAD_SESSION_ID, + requestBindingSha256: REQUEST_BINDING_SHA256, + uploadBindingSha256: "b".repeat(64), + partNumber: 1, + offset: 0, + idempotencyKey: "part-attempt-1", + }, + href: `${DATA_ORIGIN}/uploads/session-1/part-1?sig=secret`, + origin: DATA_ORIGIN, + path: "/uploads/session-1/part-1", + allowedQueryParameters: ["sig"], + requestHeaders: [ + { name: "content-type", value: "application/octet-stream" }, + { name: CHECKSUM_HEADER, value: input.checksum }, + ], + requiredResponseHeaders: [ + { name: POLICY_HEADER, value: "v1" }, + ], + digestRequestHeader: CHECKSUM_HEADER, + digestResponseHeader: null, + receiptResponseHeader: "etag", + expectedStatus: 200, + expectedResponseByteLength: 0, + mediaType: "application/octet-stream", + byteLength: input.bytes.byteLength, + maxBytes: 64, + expectedSha256: input.checksum, + expiresAtEpochMs: NOW + 30_000, + singleUse: true, + ...overrides, + }; +} + +export function jsonResponse( + value: unknown, + url = CONTROL_ENDPOINT, +): Response { + return responseWithUrl( + new Response(JSON.stringify(value), { + status: 200, + headers: { "Content-Type": "application/json" }, + }), + url, + ); +} + +export function downloadResponse( + body: BodyInit | null, + payload: CapabilityPayload, + headers: Record = {}, +): Response { + return responseWithUrl( + new Response(body, { + status: payload.expectedStatus as number, + headers: { + "Content-Type": String(payload.mediaType), + "Content-Length": String(payload.byteLength), + [DIGEST_HEADER]: String(payload.expectedSha256), + [POLICY_HEADER]: "v1", + ...headers, + }, + }), + String(payload.href), + ); +} + +export function responseWithUrl(response: Response, href: string): Response { + Object.defineProperty(response, "url", { + configurable: true, + value: href, + }); + return response; +} + +export function createHarness(input: Readonly<{ + fetcher: typeof fetch; + maxActiveCapabilities?: number; + now?: () => number; + digestBytes?: PresignedTransferExecutorOptions["digestBytes"]; + scheduler?: PresignedTransferExecutorOptions["scheduler"]; + observer?: Readonly<{ + record(observation: BrowserDataObservation): void; + }>; +}>) { + const now = input.now ?? (() => NOW); + const vault = createPresignedCapabilityVault({ + maxActiveCapabilities: input.maxActiveCapabilities ?? 16, + now, + }); + const replayGuard = createSingleUsePresignedReplayGuard(); + const provider = createPresignedCapabilityHttpProvider({ + endpoint: CONTROL_ENDPOINT, + vault, + allowedDataOrigins: [DATA_ORIGIN], + allowedDataPathPrefixes: ["/files/", "/uploads/"], + allowedQueryParameters: ["sig"], + allowedRequestHeaders: [ + "accept", + "content-type", + CHECKSUM_HEADER, + ], + allowedResponseHeaders: [ + POLICY_HEADER, + DIGEST_HEADER, + "etag", + ], + hardMaxTransferBytes: 64, + hardMaxUploadResponseBytes: 16, + maxCapabilityTtlMs: 60_000, + minimumRemainingLifetimeMs: 1_000, + timeoutMs: 5_000, + fetcher: input.fetcher, + now, + scheduler: input.scheduler, + observer: input.observer, + }); + const executor = createPresignedTransferExecutor({ + vault, + replayGuard, + hardMaxTransferBytes: 64, + hardMaxChunkBytes: 2, + hardMaxUploadResponseBytes: 16, + minimumRemainingLifetimeMs: 1_000, + timeoutMs: 5_000, + fetcher: input.fetcher, + now, + scheduler: input.scheduler, + digestBytes: input.digestBytes, + observer: input.observer, + }); + return { provider, executor, vault }; +} + +export async function collect( + source: PresignedDownloadByteSource, + signal = new AbortController().signal, +) { + const results = []; + for await (const result of source.stream(signal)) { + results.push(result); + } + return results; +} + +/** + * BT-PRE-01. The download lease is lazy, so a response-shape rejection is + * observed on first consumption rather than at open(). + */ +export async function firstStreamResult( + opened: Awaited< + ReturnType< + ReturnType["executor"]["downloadSources"]["open"] + > + >, +): Promise { + if (!opened.ok) return opened; + try { + for await (const chunk of opened.value.stream( + new AbortController().signal, + )) { + if (!chunk.ok) return chunk; + } + return { ok: true }; + } finally { + opened.value.close(); + } +} diff --git a/tests/unit/presigned-transfer-upload.test.ts b/tests/unit/presigned-transfer-upload.test.ts new file mode 100644 index 0000000..58797c3 --- /dev/null +++ b/tests/unit/presigned-transfer-upload.test.ts @@ -0,0 +1,549 @@ +import { describe, expect, it, vi } from "vitest"; + +import type { BrowserDataObservation } from "../../src/application/ports/browser-file-storage/shared.ts"; +import { sha256Hex } from "../../src/adapters/browser-transfer/presigned/incremental-sha256.ts"; +import { + CHECKSUM_HEADER, + CONTROL_ENDPOINT, + DATA_ORIGIN, + DIGEST_HEADER, + DOWNLOAD_HREF, + DOWNLOAD_PATH, + NOW, + POLICY_HEADER, + REQUEST_BINDING_SHA256, + UPLOAD_SESSION_ID, + collect, + createHarness, + downloadCapabilityPayload, + downloadResponse, + jsonResponse, + responseWithUrl, + uploadCapabilityPayload, +} from "./presigned-transfer-fixture.ts"; + +describe("presigned upload part execution", () => { + it("snapshots, verifies and uploads a PUT part with a separate response receipt", async () => { + const original = new Uint8Array([9, 8, 7]); + const checksum = sha256Hex(original); + const payload = uploadCapabilityPayload({ + bytes: original, + checksum, + }); + let releaseDigest: (() => void) | undefined; + const digestGate = new Promise((resolve) => { + releaseDigest = resolve; + }); + const sentBodies: number[][] = []; + const dataCalls: RequestInit[] = []; + const fetcher = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { + if (String(input) === CONTROL_ENDPOINT) return jsonResponse(payload); + dataCalls.push(init ?? {}); + sentBodies.push([ + ...new Uint8Array(init?.body as ArrayBuffer), + ]); + return responseWithUrl( + new Response(null, { + status: 200, + headers: { + [POLICY_HEADER]: "v1", + "Content-Length": "0", + ETag: "\"part-etag-1\"", + }, + }), + String(payload.href), + ); + }) as unknown as typeof fetch; + const { provider, executor } = createHarness({ + fetcher, + digestBytes: async (bytes) => { + await digestGate; + return sha256Hex(bytes); + }, + }); + const issued = await provider.issueUploadPart({ + sessionId: UPLOAD_SESSION_ID, + requestBindingSha256: REQUEST_BINDING_SHA256, + uploadBindingSha256: "b".repeat(64), + partNumber: 1, + offset: 0, + byteLength: original.byteLength, + checksumSha256: checksum, + mediaType: "application/octet-stream", + idempotencyKey: "part-attempt-1", + signal: new AbortController().signal, + }); + expect(issued.ok).toBe(true); + if (!issued.ok) return; + const request = { + capability: issued.value, + sessionId: UPLOAD_SESSION_ID, + requestBindingSha256: REQUEST_BINDING_SHA256, + uploadBindingSha256: "b".repeat(64), + partNumber: 1, + offset: 0, + byteLength: original.byteLength, + checksumSha256: checksum, + idempotencyKey: "part-attempt-1", + bytes: original, + signal: new AbortController().signal, + }; + const pending = executor.uploadParts.put(request); + original.fill(0); + request.sessionId = "mutated-session"; + request.requestBindingSha256 = "d".repeat(64); + request.checksumSha256 = "f".repeat(64); + releaseDigest?.(); + + expect(await pending).toEqual({ + ok: true, + value: { + bytesWritten: 3, + checksumSha256: checksum, + receiptToken: "part-etag-1", + }, + }); + expect(sentBodies).toEqual([[9, 8, 7]]); + expect(dataCalls[0]).toMatchObject({ + method: "PUT", + credentials: "omit", + redirect: "error", + referrerPolicy: "no-referrer", + }); + expect( + (dataCalls[0]?.headers as Headers).get(CHECKSUM_HEADER), + ).toBe(checksum); + }); + + it.each(["sessionId", "requestBindingSha256"] as const)( + "rejects an actual PUT whose %s differs from the capability", + async (field) => { + const bytes = new Uint8Array([3, 2, 1]); + const checksum = sha256Hex(bytes); + const payload = uploadCapabilityPayload({ bytes, checksum }); + const fetcher = vi.fn(async () => + jsonResponse(payload), + ) as unknown as typeof fetch; + const { provider, executor } = createHarness({ fetcher }); + const issued = await provider.issueUploadPart({ + sessionId: UPLOAD_SESSION_ID, + requestBindingSha256: REQUEST_BINDING_SHA256, + uploadBindingSha256: "b".repeat(64), + partNumber: 1, + offset: 0, + byteLength: bytes.byteLength, + checksumSha256: checksum, + mediaType: "application/octet-stream", + idempotencyKey: "part-attempt-1", + signal: new AbortController().signal, + }); + expect(issued.ok).toBe(true); + if (!issued.ok) return; + expect( + await executor.uploadParts.put({ + capability: issued.value, + sessionId: + field === "sessionId" + ? "different-session" + : UPLOAD_SESSION_ID, + requestBindingSha256: + field === "requestBindingSha256" + ? "d".repeat(64) + : REQUEST_BINDING_SHA256, + uploadBindingSha256: "b".repeat(64), + partNumber: 1, + offset: 0, + byteLength: bytes.byteLength, + checksumSha256: checksum, + idempotencyKey: "part-attempt-1", + bytes, + signal: new AbortController().signal, + }), + ).toMatchObject({ + ok: false, + error: { code: "POLICY_REJECTED" }, + }); + expect(fetcher).toHaveBeenCalledTimes(1); + }, + ); + + it("rejects URL-shaped upload receipts", async () => { + const bytes = new Uint8Array([4, 5, 6]); + const checksum = sha256Hex(bytes); + const payload = uploadCapabilityPayload({ bytes, checksum }); + const fetcher = vi.fn(async (input: RequestInfo | URL) => { + if (String(input) === CONTROL_ENDPOINT) { + return jsonResponse(payload); + } + return responseWithUrl( + new Response(null, { + status: 200, + headers: { + [POLICY_HEADER]: "v1", + "Content-Length": "0", + ETag: "\"https://objects.example/authorizing-token\"", + }, + }), + String(payload.href), + ); + }) as unknown as typeof fetch; + const { provider, executor } = createHarness({ fetcher }); + const issued = await provider.issueUploadPart({ + sessionId: UPLOAD_SESSION_ID, + requestBindingSha256: REQUEST_BINDING_SHA256, + uploadBindingSha256: "b".repeat(64), + partNumber: 1, + offset: 0, + byteLength: bytes.byteLength, + checksumSha256: checksum, + mediaType: "application/octet-stream", + idempotencyKey: "part-attempt-1", + signal: new AbortController().signal, + }); + expect(issued.ok).toBe(true); + if (!issued.ok) return; + expect( + await executor.uploadParts.put({ + capability: issued.value, + sessionId: UPLOAD_SESSION_ID, + requestBindingSha256: REQUEST_BINDING_SHA256, + uploadBindingSha256: "b".repeat(64), + partNumber: 1, + offset: 0, + byteLength: bytes.byteLength, + checksumSha256: checksum, + idempotencyKey: "part-attempt-1", + bytes, + signal: new AbortController().signal, + }), + ).toMatchObject({ + ok: false, + error: { code: "INTEGRITY_FAILED" }, + }); + }); + + it("drains a bounded successful PUT acknowledgement without cancelling it", async () => { + const bytes = new Uint8Array([4, 5, 6]); + const checksum = sha256Hex(bytes); + const payload = uploadCapabilityPayload( + { bytes, checksum }, + { expectedResponseByteLength: 2 }, + ); + let cancelled = false; + const fetcher = vi.fn(async (input: RequestInfo | URL) => { + if (String(input) === CONTROL_ENDPOINT) { + return jsonResponse(payload); + } + const body = new ReadableStream({ + start(controller) { + controller.enqueue(new Uint8Array([8, 9])); + controller.close(); + }, + cancel() { + cancelled = true; + }, + }); + return responseWithUrl( + new Response(body, { + status: 200, + headers: { + [POLICY_HEADER]: "v1", + "Content-Length": "2", + ETag: "\"part-etag-1\"", + }, + }), + String(payload.href), + ); + }) as unknown as typeof fetch; + const { provider, executor } = createHarness({ fetcher }); + const issued = await provider.issueUploadPart({ + sessionId: UPLOAD_SESSION_ID, + requestBindingSha256: REQUEST_BINDING_SHA256, + uploadBindingSha256: "b".repeat(64), + partNumber: 1, + offset: 0, + byteLength: bytes.byteLength, + checksumSha256: checksum, + mediaType: "application/octet-stream", + idempotencyKey: "part-attempt-1", + signal: new AbortController().signal, + }); + expect(issued.ok).toBe(true); + if (!issued.ok) return; + expect( + await executor.uploadParts.put({ + capability: issued.value, + sessionId: UPLOAD_SESSION_ID, + requestBindingSha256: REQUEST_BINDING_SHA256, + uploadBindingSha256: "b".repeat(64), + partNumber: 1, + offset: 0, + byteLength: bytes.byteLength, + checksumSha256: checksum, + idempotencyKey: "part-attempt-1", + bytes, + signal: new AbortController().signal, + }), + ).toMatchObject({ + ok: true, + value: { receiptToken: "part-etag-1" }, + }); + expect(cancelled).toBe(false); + }); + + it("accepts an empty 204 PUT acknowledgement", async () => { + const bytes = new Uint8Array([4, 5, 6]); + const checksum = sha256Hex(bytes); + const payload = uploadCapabilityPayload( + { bytes, checksum }, + { + expectedStatus: 204, + expectedResponseByteLength: 0, + }, + ); + const fetcher = vi.fn(async (input: RequestInfo | URL) => + String(input) === CONTROL_ENDPOINT + ? jsonResponse(payload) + : responseWithUrl( + new Response(null, { + status: 204, + headers: { + [POLICY_HEADER]: "v1", + ETag: "\"part-etag-204\"", + }, + }), + String(payload.href), + ), + ) as unknown as typeof fetch; + const { provider, executor } = createHarness({ fetcher }); + const issued = await provider.issueUploadPart({ + sessionId: UPLOAD_SESSION_ID, + requestBindingSha256: REQUEST_BINDING_SHA256, + uploadBindingSha256: "b".repeat(64), + partNumber: 1, + offset: 0, + byteLength: bytes.byteLength, + checksumSha256: checksum, + mediaType: "application/octet-stream", + idempotencyKey: "part-attempt-1", + signal: new AbortController().signal, + }); + expect(issued.ok).toBe(true); + if (!issued.ok) return; + expect( + await executor.uploadParts.put({ + capability: issued.value, + sessionId: UPLOAD_SESSION_ID, + requestBindingSha256: REQUEST_BINDING_SHA256, + uploadBindingSha256: "b".repeat(64), + partNumber: 1, + offset: 0, + byteLength: bytes.byteLength, + checksumSha256: checksum, + idempotencyKey: "part-attempt-1", + bytes, + signal: new AbortController().signal, + }), + ).toMatchObject({ + ok: true, + value: { receiptToken: "part-etag-204" }, + }); + }); + + it("cancels a PUT acknowledgement whose declared length violates its binding", async () => { + const bytes = new Uint8Array([4, 5, 6]); + const checksum = sha256Hex(bytes); + const payload = uploadCapabilityPayload({ bytes, checksum }); + let cancelled = false; + const fetcher = vi.fn(async (input: RequestInfo | URL) => { + if (String(input) === CONTROL_ENDPOINT) { + return jsonResponse(payload); + } + const body = new ReadableStream({ + pull() {}, + cancel() { + cancelled = true; + }, + }); + return responseWithUrl( + new Response(body, { + status: 200, + headers: { + [POLICY_HEADER]: "v1", + "Content-Length": "1", + ETag: "\"part-etag-1\"", + }, + }), + String(payload.href), + ); + }) as unknown as typeof fetch; + const { provider, executor } = createHarness({ fetcher }); + const issued = await provider.issueUploadPart({ + sessionId: UPLOAD_SESSION_ID, + requestBindingSha256: REQUEST_BINDING_SHA256, + uploadBindingSha256: "b".repeat(64), + partNumber: 1, + offset: 0, + byteLength: bytes.byteLength, + checksumSha256: checksum, + mediaType: "application/octet-stream", + idempotencyKey: "part-attempt-1", + signal: new AbortController().signal, + }); + expect(issued.ok).toBe(true); + if (!issued.ok) return; + expect( + await executor.uploadParts.put({ + capability: issued.value, + sessionId: UPLOAD_SESSION_ID, + requestBindingSha256: REQUEST_BINDING_SHA256, + uploadBindingSha256: "b".repeat(64), + partNumber: 1, + offset: 0, + byteLength: bytes.byteLength, + checksumSha256: checksum, + idempotencyKey: "part-attempt-1", + bytes, + signal: new AbortController().signal, + }), + ).toMatchObject({ + ok: false, + error: { code: "POLICY_REJECTED" }, + }); + expect(cancelled).toBe(true); + }); + + it("observes only safe operation, outcome, failure and byte buckets", async () => { + const bytes = new Uint8Array([7, 8, 9]); + const downloadPayload = downloadCapabilityPayload(bytes); + const checksum = sha256Hex(bytes); + const uploadPayload = uploadCapabilityPayload({ bytes, checksum }); + const observations: BrowserDataObservation[] = []; + const fetcher = vi.fn( + async (input: RequestInfo | URL, init?: RequestInit) => { + if (String(input) === CONTROL_ENDPOINT) { + const request = JSON.parse(String(init?.body)) as { + method: string; + }; + return jsonResponse( + request.method === "GET" + ? downloadPayload + : uploadPayload, + ); + } + if (String(input) === DOWNLOAD_HREF) { + return downloadResponse( + bytes.slice().buffer, + downloadPayload, + ); + } + return responseWithUrl( + new Response(null, { + status: 200, + headers: { + [POLICY_HEADER]: "v1", + "Content-Length": "0", + ETag: "\"part-etag-secret\"", + }, + }), + String(uploadPayload.href), + ); + }, + ) as unknown as typeof fetch; + const { provider, executor } = createHarness({ + fetcher, + observer: { + record(observation) { + observations.push(observation); + }, + }, + }); + const issuedDownload = await provider.issueDownload({ + resourceId: "resource-1", + signal: new AbortController().signal, + }); + expect(issuedDownload.ok).toBe(true); + if (!issuedDownload.ok) return; + const opened = await executor.downloadSources.open({ + resourceId: "resource-1", + capability: issuedDownload.value, + signal: new AbortController().signal, + }); + expect(opened.ok).toBe(true); + if (!opened.ok) return; + expect((await collect(opened.value)).every((result) => result.ok)).toBe( + true, + ); + + const issuedUpload = await provider.issueUploadPart({ + sessionId: UPLOAD_SESSION_ID, + requestBindingSha256: REQUEST_BINDING_SHA256, + uploadBindingSha256: "b".repeat(64), + partNumber: 1, + offset: 0, + byteLength: bytes.byteLength, + checksumSha256: checksum, + mediaType: "application/octet-stream", + idempotencyKey: "part-attempt-1", + signal: new AbortController().signal, + }); + expect(issuedUpload.ok).toBe(true); + if (!issuedUpload.ok) return; + expect( + await executor.uploadParts.put({ + capability: issuedUpload.value, + sessionId: UPLOAD_SESSION_ID, + requestBindingSha256: REQUEST_BINDING_SHA256, + uploadBindingSha256: "b".repeat(64), + partNumber: 1, + offset: 0, + byteLength: bytes.byteLength, + checksumSha256: checksum, + idempotencyKey: "part-attempt-1", + bytes, + signal: new AbortController().signal, + }), + ).toMatchObject({ ok: true }); + + expect(observations).toEqual([ + { + operation: "PRESIGNED_TRANSFER", + outcome: "SUCCEEDED", + byteBucket: "LT1MIB", + }, + { + operation: "PRESIGNED_TRANSFER", + outcome: "SUCCEEDED", + byteBucket: "LT1MIB", + }, + { + operation: "DOWNLOAD", + outcome: "SUCCEEDED", + byteBucket: "LT1MIB", + }, + { + operation: "PRESIGNED_TRANSFER", + outcome: "SUCCEEDED", + byteBucket: "LT1MIB", + }, + { + operation: "UPLOAD_PART", + outcome: "SUCCEEDED", + byteBucket: "LT1MIB", + }, + ]); + const serialized = JSON.stringify(observations); + for (const secret of [ + DOWNLOAD_HREF, + "do-not-log-this", + checksum, + "capability-download-1", + "capability-upload-1", + "part-etag-secret", + "resource-1", + ]) { + expect(serialized).not.toContain(secret); + } + }); + +}); diff --git a/tests/unit/presigned-transfer.test.ts b/tests/unit/presigned-transfer.test.ts index 982dd75..ab260fc 100644 --- a/tests/unit/presigned-transfer.test.ts +++ b/tests/unit/presigned-transfer.test.ts @@ -1,241 +1,33 @@ import { describe, expect, it, vi } from "vitest"; -import { PRESIGNED_TRANSFER_PROTOCOL } from "../../src/application/ports/browser-transfer/presigned-transfer.ts"; - -import type { - PresignedDownloadCapability, - PresignedDownloadByteSource, +import { + PRESIGNED_TRANSFER_PROTOCOL, + type PresignedDownloadCapability, } from "../../src/application/ports/browser-transfer/presigned-transfer.ts"; -import { RESUMABLE_UPLOAD_PROTOCOL } from "../../src/application/ports/browser-transfer/resumable-upload.ts"; -import type { BrowserDataObservation } from "../../src/application/ports/browser-file-storage/shared.ts"; -import { - createPresignedCapabilityVault, - createSingleUsePresignedReplayGuard, -} from "../../src/adapters/browser-transfer/presigned/presigned-capability-vault.ts"; -import { createPresignedCapabilityHttpProvider } from "../../src/adapters/browser-transfer/presigned/presigned-capability-http-provider.ts"; -import { - createPresignedTransferExecutor, - type PresignedTransferExecutorOptions, -} from "../../src/adapters/browser-transfer/presigned/presigned-transfer-executor.ts"; +import { createPresignedCapabilityVault } from "../../src/adapters/browser-transfer/presigned/presigned-capability-vault.ts"; import { sha256Hex } from "../../src/adapters/browser-transfer/presigned/incremental-sha256.ts"; import { - BrowserFilePolicyRegistry, - browserFilePolicyReference, -} from "../../src/adapters/browser-files/browser-file-policy-registry.ts"; -import { - createDownloadDeliveryAdapter, - type SaveFileHandle, -} from "../../src/adapters/browser-files/download-delivery-adapter.ts"; + CHECKSUM_HEADER, + CONTROL_ENDPOINT, + DATA_ORIGIN, + DIGEST_HEADER, + DOWNLOAD_HREF, + DOWNLOAD_PATH, + NOW, + POLICY_HEADER, + REQUEST_BINDING_SHA256, + UPLOAD_SESSION_ID, + collect, + createHarness, + downloadCapabilityPayload, + downloadResponse, + firstStreamResult, + jsonResponse, + responseWithUrl, + uploadCapabilityPayload, +} from "./presigned-transfer-fixture.ts"; -const NOW = 1_000_000; -const CONTROL_ENDPOINT = "https://api.example/capabilities"; -const DATA_ORIGIN = "https://objects.example"; -const DOWNLOAD_PATH = "/files/resource-1"; -const DOWNLOAD_HREF = - `${DATA_ORIGIN}${DOWNLOAD_PATH}?sig=do-not-log-this`; -const POLICY_HEADER = "x-policy-version"; -const DIGEST_HEADER = "x-content-sha256"; -const CHECKSUM_HEADER = "x-checksum-sha256"; -const UPLOAD_SESSION_ID = "upload-session-1"; -const REQUEST_BINDING_SHA256 = "c".repeat(64); - -function downloadCapabilityPayload( - bytes: Uint8Array, - overrides: Readonly> = {}, -) { - const digest = sha256Hex(bytes); - return { - // BT-PRE-02. Every capability envelope carries the top-level protocol. - protocol: PRESIGNED_TRANSFER_PROTOCOL, - capabilityReceipt: "capability-download-1", - method: "GET", - binding: { - kind: "DOWNLOAD", - resourceId: "resource-1", - }, - href: DOWNLOAD_HREF, - origin: DATA_ORIGIN, - path: DOWNLOAD_PATH, - allowedQueryParameters: ["sig"], - requestHeaders: [ - { name: "accept", value: "application/octet-stream" }, - ], - requiredResponseHeaders: [ - { name: POLICY_HEADER, value: "v1" }, - ], - digestRequestHeader: null, - digestResponseHeader: DIGEST_HEADER, - receiptResponseHeader: null, - expectedStatus: 200, - expectedResponseByteLength: null, - mediaType: "application/octet-stream", - byteLength: bytes.byteLength, - maxBytes: 64, - expectedSha256: digest, - expiresAtEpochMs: NOW + 30_000, - singleUse: true, - ...overrides, - }; -} - -type CapabilityPayload = ReturnType; - -function uploadCapabilityPayload(input: Readonly<{ - bytes: Uint8Array; - checksum: string; -}>, overrides: Readonly> = {}) { - return { - protocol: PRESIGNED_TRANSFER_PROTOCOL, - capabilityReceipt: "capability-upload-1", - method: "PUT", - binding: { - kind: "UPLOAD_PART", - protocol: RESUMABLE_UPLOAD_PROTOCOL, - sessionId: UPLOAD_SESSION_ID, - requestBindingSha256: REQUEST_BINDING_SHA256, - uploadBindingSha256: "b".repeat(64), - partNumber: 1, - offset: 0, - idempotencyKey: "part-attempt-1", - }, - href: `${DATA_ORIGIN}/uploads/session-1/part-1?sig=secret`, - origin: DATA_ORIGIN, - path: "/uploads/session-1/part-1", - allowedQueryParameters: ["sig"], - requestHeaders: [ - { name: "content-type", value: "application/octet-stream" }, - { name: CHECKSUM_HEADER, value: input.checksum }, - ], - requiredResponseHeaders: [ - { name: POLICY_HEADER, value: "v1" }, - ], - digestRequestHeader: CHECKSUM_HEADER, - digestResponseHeader: null, - receiptResponseHeader: "etag", - expectedStatus: 200, - expectedResponseByteLength: 0, - mediaType: "application/octet-stream", - byteLength: input.bytes.byteLength, - maxBytes: 64, - expectedSha256: input.checksum, - expiresAtEpochMs: NOW + 30_000, - singleUse: true, - ...overrides, - }; -} - -function jsonResponse( - value: unknown, - url = CONTROL_ENDPOINT, -): Response { - return responseWithUrl( - new Response(JSON.stringify(value), { - status: 200, - headers: { "Content-Type": "application/json" }, - }), - url, - ); -} - -function downloadResponse( - body: BodyInit | null, - payload: CapabilityPayload, - headers: Record = {}, -): Response { - return responseWithUrl( - new Response(body, { - status: payload.expectedStatus as number, - headers: { - "Content-Type": String(payload.mediaType), - "Content-Length": String(payload.byteLength), - [DIGEST_HEADER]: String(payload.expectedSha256), - [POLICY_HEADER]: "v1", - ...headers, - }, - }), - String(payload.href), - ); -} - -function responseWithUrl(response: Response, href: string): Response { - Object.defineProperty(response, "url", { - configurable: true, - value: href, - }); - return response; -} - -function createHarness(input: Readonly<{ - fetcher: typeof fetch; - maxActiveCapabilities?: number; - now?: () => number; - digestBytes?: PresignedTransferExecutorOptions["digestBytes"]; - scheduler?: PresignedTransferExecutorOptions["scheduler"]; - observer?: Readonly<{ - record(observation: BrowserDataObservation): void; - }>; -}>) { - const now = input.now ?? (() => NOW); - const vault = createPresignedCapabilityVault({ - maxActiveCapabilities: input.maxActiveCapabilities ?? 16, - now, - }); - const replayGuard = createSingleUsePresignedReplayGuard(); - const provider = createPresignedCapabilityHttpProvider({ - endpoint: CONTROL_ENDPOINT, - vault, - allowedDataOrigins: [DATA_ORIGIN], - allowedDataPathPrefixes: ["/files/", "/uploads/"], - allowedQueryParameters: ["sig"], - allowedRequestHeaders: [ - "accept", - "content-type", - CHECKSUM_HEADER, - ], - allowedResponseHeaders: [ - POLICY_HEADER, - DIGEST_HEADER, - "etag", - ], - hardMaxTransferBytes: 64, - hardMaxUploadResponseBytes: 16, - maxCapabilityTtlMs: 60_000, - minimumRemainingLifetimeMs: 1_000, - timeoutMs: 5_000, - fetcher: input.fetcher, - now, - scheduler: input.scheduler, - observer: input.observer, - }); - const executor = createPresignedTransferExecutor({ - vault, - replayGuard, - hardMaxTransferBytes: 64, - hardMaxChunkBytes: 2, - hardMaxUploadResponseBytes: 16, - minimumRemainingLifetimeMs: 1_000, - timeoutMs: 5_000, - fetcher: input.fetcher, - now, - scheduler: input.scheduler, - digestBytes: input.digestBytes, - observer: input.observer, - }); - return { provider, executor, vault }; -} - -async function collect( - source: PresignedDownloadByteSource, - signal = new AbortController().signal, -) { - const results = []; - for await (const result of source.stream(signal)) { - results.push(result); - } - return results; -} - -describe("presigned transfer", () => { +describe("presigned transfer capability issuance and admission", () => { it("matches the standard SHA-256 vector", () => { expect(sha256Hex(new TextEncoder().encode("abc"))).toBe( "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", @@ -956,1563 +748,4 @@ describe("presigned transfer", () => { * header set to the forbidden-header check and hand `Authorization` to the * stored binding, so the executor sent a credential no rule had approved. */ - describe("TR-01 the stored capability is the one that was validated", () => { - const baseRegistration = () => ({ - protocol: PRESIGNED_TRANSFER_PROTOCOL, - capabilityReceipt: "capability-snapshot-1", - method: "GET" as const, - binding: { kind: "DOWNLOAD" as const, resourceId: "resource-1" }, - href: `${DATA_ORIGIN}${DOWNLOAD_PATH}`, - origin: DATA_ORIGIN, - path: DOWNLOAD_PATH, - allowedQueryParameters: [], - requestHeaders: [{ name: "x-safe", value: "1" }], - requiredResponseHeaders: [], - digestRequestHeader: null, - digestResponseHeader: null, - receiptResponseHeader: null, - expectedStatus: 200, - expectedResponseByteLength: 3, - mediaType: "application/octet-stream", - byteLength: 3, - maxBytes: 3, - expectedSha256: "a".repeat(64), - expiresAtEpochMs: NOW + 60_000, - }); - - const freshVault = () => - createPresignedCapabilityVault({ - now: () => NOW, - maxActiveCapabilities: 4, - }); - - it("refuses a header row that answers differently on a second read", () => { - const vault = freshVault(); - let nameReads = 0; - const header = new Proxy( - { name: "x-safe", value: "1" }, - { - getOwnPropertyDescriptor(target, key) { - if (key === "name") { - nameReads += 1; - return { - configurable: true, - enumerable: true, - value: nameReads > 1 ? "authorization" : "x-safe", - }; - } - return Reflect.getOwnPropertyDescriptor(target, key); - }, - }, - ); - - const registered = vault.register({ - ...baseRegistration(), - requestHeaders: [header], - } as never); - - if (registered.ok) { - // A single read means the value that was checked is the value stored. - const resolved = vault.resolve(registered.value); - expect(resolved.ok).toBe(true); - if (resolved.ok) { - expect(resolved.value.requestHeaders.map((row) => row.name)).toEqual([ - "x-safe", - ]); - } - } - vault.dispose(); - }); - - const hostileRegistrations: readonly (readonly [string, () => unknown])[] = [ - [ - "an accessor field", - () => - Object.defineProperty(baseRegistration(), "href", { - enumerable: true, - get: () => `${DATA_ORIGIN}${DOWNLOAD_PATH}`, - }), - ], - [ - "an inherited field", - () => Object.assign(Object.create({ injected: true }), baseRegistration()), - ], - [ - "a symbol field", - () => ({ ...baseRegistration(), [Symbol.for("injected")]: true }), - ], - [ - "a non-enumerable own field", - () => - Object.defineProperty(baseRegistration(), "injected", { - enumerable: false, - value: true, - }), - ], - [ - "a throwing ownKeys trap", - () => - new Proxy(baseRegistration(), { - ownKeys() { - throw new TypeError("hostile ownKeys trap"); - }, - }), - ], - [ - "a null header array", - () => ({ ...baseRegistration(), requestHeaders: null }), - ], - [ - "a non-iterable header array", - () => ({ ...baseRegistration(), requestHeaders: { length: 1 } }), - ], - [ - "a header row with an extra field", - () => ({ - ...baseRegistration(), - requestHeaders: [{ name: "x-safe", value: "1", injected: true }], - }), - ], - [ - "an accessor header name", - () => ({ - ...baseRegistration(), - requestHeaders: [ - Object.defineProperty({ value: "1" }, "name", { - enumerable: true, - get: () => "x-safe", - }), - ], - }), - ], - [ - "a binding with an extra field", - () => ({ - ...baseRegistration(), - binding: { kind: "DOWNLOAD", resourceId: "r", injected: true }, - }), - ], - [ - "a null binding", - () => ({ ...baseRegistration(), binding: null }), - ], - ]; - - for (const [label, build] of hostileRegistrations) { - it(`rejects ${label} as POLICY_REJECTED`, () => { - const vault = freshVault(); - expect(vault.register(build() as never)).toMatchObject({ - ok: false, - error: { code: "POLICY_REJECTED" }, - }); - vault.dispose(); - }); - } - - it("does not observe a mutation of the issuer's object after registration", () => { - const vault = freshVault(); - const registration = baseRegistration(); - const registered = vault.register(registration as never); - expect(registered.ok).toBe(true); - if (!registered.ok) return; - - registration.requestHeaders[0]!.name = "authorization"; - registration.expiresAtEpochMs = NOW + 999_999; - - const resolved = vault.resolve(registered.value); - expect(resolved.ok).toBe(true); - if (!resolved.ok) return; - expect(resolved.value.requestHeaders.map((row) => row.name)).toEqual([ - "x-safe", - ]); - expect(resolved.value.expiresAtEpochMs).toBe(NOW + 60_000); - vault.dispose(); - }); - }); - - it("does not fetch a presigned download until stream consumption", async () => { - const bytes = new Uint8Array([1, 2, 3]); - const responsePayload = downloadCapabilityPayload(bytes); - let downloadFetches = 0; - const fetcher = vi.fn(async (input: RequestInfo | URL) => { - if (String(input) === CONTROL_ENDPOINT) { - return jsonResponse(responsePayload); - } - downloadFetches += 1; - return downloadResponse(bytes.slice().buffer, responsePayload); - }) as unknown as typeof fetch; - const { provider, executor } = createHarness({ fetcher }); - const signal = new AbortController().signal; - const issued = await provider.issueDownload({ - resourceId: "resource-1", - signal, - }); - expect(issued.ok).toBe(true); - if (!issued.ok) return; - - const opened = await executor.downloadSources.open({ - resourceId: "resource-1", - capability: issued.value, - signal, - }); - expect(opened.ok).toBe(true); - if (!opened.ok) return; - // BT-PRE-01. open() performs no network I/O. - expect(downloadFetches).toBe(0); - - for await (const chunk of opened.value.stream(signal)) { - expect(chunk.ok).toBe(true); - } - expect(downloadFetches).toBe(1); - opened.value.close(); - }); - - it("closes an unused download source without network I/O", async () => { - const bytes = new Uint8Array([1, 2, 3]); - const responsePayload = downloadCapabilityPayload(bytes); - let downloadFetches = 0; - const fetcher = vi.fn(async (input: RequestInfo | URL) => { - if (String(input) === CONTROL_ENDPOINT) { - return jsonResponse(responsePayload); - } - downloadFetches += 1; - return downloadResponse(bytes.slice().buffer, responsePayload); - }) as unknown as typeof fetch; - const { provider, executor } = createHarness({ fetcher }); - const signal = new AbortController().signal; - const issued = await provider.issueDownload({ - resourceId: "resource-1", - signal, - }); - expect(issued.ok).toBe(true); - if (!issued.ok) return; - - const opened = await executor.downloadSources.open({ - resourceId: "resource-1", - capability: issued.value, - signal, - }); - expect(opened.ok).toBe(true); - if (!opened.ok) return; - - opened.value.close(); - // close() is idempotent and never starts the transfer. - opened.value.close(); - expect(downloadFetches).toBe(0); - - // A stream after close is one terminal conflict, still without fetching. - const results = []; - for await (const chunk of opened.value.stream(signal)) { - results.push(chunk); - } - expect(results).toMatchObject([ - { ok: false, error: { code: "CONFLICT" } }, - ]); - expect(downloadFetches).toBe(0); - }); - - it.each([ - { - name: "truncation", - body: new Uint8Array([1, 2]), - expectedCode: "INTEGRITY_FAILED", - }, - { - name: "overrun", - body: new Uint8Array([1, 2, 3, 4]), - expectedCode: "INTEGRITY_FAILED", - }, - ])("closes $name as a terminal stream failure", async ({ body, expectedCode }) => { - const declared = new Uint8Array([1, 2, 3]); - const payload = downloadCapabilityPayload(declared); - const fetcher = vi.fn(async (input: RequestInfo | URL) => - String(input) === CONTROL_ENDPOINT - ? jsonResponse(payload) - : downloadResponse(body.slice().buffer, payload), - ) as unknown as typeof fetch; - const { provider, executor } = createHarness({ fetcher }); - const issued = await provider.issueDownload({ - resourceId: "resource-1", - signal: new AbortController().signal, - }); - expect(issued.ok).toBe(true); - if (!issued.ok) return; - const opened = await executor.downloadSources.open({ - resourceId: "resource-1", - capability: issued.value, - signal: new AbortController().signal, - }); - expect(opened.ok).toBe(true); - if (!opened.ok) return; - const results = await collect(opened.value); - expect(results.at(-1)).toMatchObject({ - ok: false, - error: { code: expectedCode }, - }); - const firstFailure = results.findIndex((result) => !result.ok); - expect(results.slice(firstFailure + 1)).toEqual([]); - }); - - it("closes native body errors without throwing across the port", async () => { - const bytes = new Uint8Array([1, 2, 3]); - const payload = downloadCapabilityPayload(bytes); - const failingBody = new ReadableStream({ - pull(controller) { - controller.error(new DOMException("secret native detail", "NetworkError")); - }, - }); - const fetcher = vi.fn(async (input: RequestInfo | URL) => - String(input) === CONTROL_ENDPOINT - ? jsonResponse(payload) - : downloadResponse(failingBody, payload), - ) as unknown as typeof fetch; - const { provider, executor } = createHarness({ fetcher }); - const issued = await provider.issueDownload({ - resourceId: "resource-1", - signal: new AbortController().signal, - }); - expect(issued.ok).toBe(true); - if (!issued.ok) return; - const opened = await executor.downloadSources.open({ - resourceId: "resource-1", - capability: issued.value, - signal: new AbortController().signal, - }); - expect(opened.ok).toBe(true); - if (!opened.ok) return; - await expect(collect(opened.value)).resolves.toMatchObject([ - { - ok: false, - error: { - code: "NOT_READABLE", - recovery: "REISSUE_CAPABILITY", - }, - }, - ]); - }); - - it("closes active abort and timeout without leaking native rejection", async () => { - const bytes = new Uint8Array([1]); - const payload = downloadCapabilityPayload(bytes); - const neverBody = () => - new ReadableStream({ pull() {} }); - const fetcher = vi.fn(async (input: RequestInfo | URL) => - String(input) === CONTROL_ENDPOINT - ? jsonResponse(payload) - : downloadResponse(neverBody(), payload), - ) as unknown as typeof fetch; - const controller = new AbortController(); - let harness = createHarness({ fetcher }); - let issued = await harness.provider.issueDownload({ - resourceId: "resource-1", - signal: controller.signal, - }); - expect(issued.ok).toBe(true); - if (!issued.ok) return; - let opened = await harness.executor.downloadSources.open({ - resourceId: "resource-1", - capability: issued.value, - signal: controller.signal, - }); - expect(opened.ok).toBe(true); - if (!opened.ok) return; - const aborted = collect(opened.value, controller.signal); - controller.abort("user"); - expect(await aborted).toMatchObject([ - { ok: false, error: { code: "ABORTED" } }, - ]); - - let timeoutCallback: (() => void) | undefined; - const scheduler = { - setTimeout(callback: () => void) { - timeoutCallback = callback; - return 1; - }, - clearTimeout() {}, - }; - harness = createHarness({ fetcher, scheduler }); - issued = await harness.provider.issueDownload({ - resourceId: "resource-1", - signal: new AbortController().signal, - }); - expect(issued.ok).toBe(true); - if (!issued.ok) return; - opened = await harness.executor.downloadSources.open({ - resourceId: "resource-1", - capability: issued.value, - signal: new AbortController().signal, - }); - expect(opened.ok).toBe(true); - if (!opened.ok) return; - const timedOut = collect(opened.value); - timeoutCallback?.(); - expect(await timedOut).toMatchObject([ - { - ok: false, - error: { - code: "UNAVAILABLE", - recovery: "REISSUE_CAPABILITY", - }, - }, - ]); - }); - - it("rejects an expired capability before data-plane fetch", async () => { - const bytes = new Uint8Array([1]); - const payload = downloadCapabilityPayload(bytes); - let current = NOW; - const fetcher = vi.fn(async (input: RequestInfo | URL) => - String(input) === CONTROL_ENDPOINT - ? jsonResponse(payload) - : downloadResponse(bytes.slice().buffer, payload), - ) as unknown as typeof fetch; - const { provider, executor } = createHarness({ - fetcher, - now: () => current, - }); - const issued = await provider.issueDownload({ - resourceId: "resource-1", - signal: new AbortController().signal, - }); - expect(issued.ok).toBe(true); - if (!issued.ok) return; - current = Number(payload.expiresAtEpochMs) + 1; - expect( - await executor.downloadSources.open({ - resourceId: "resource-1", - capability: issued.value, - signal: new AbortController().signal, - }), - ).toMatchObject({ - ok: false, - error: { - code: "EXPIRED_RESOURCE", - recovery: "REISSUE_CAPABILITY", - }, - }); - expect(fetcher).toHaveBeenCalledTimes(1); - }); - - it("rejects capabilities below the configured minimum remaining lifetime", async () => { - const bytes = new Uint8Array([1]); - const nearExpiryPayload = downloadCapabilityPayload(bytes, { - expiresAtEpochMs: NOW + 999, - }); - let fetcher = vi.fn(async () => - jsonResponse(nearExpiryPayload), - ) as unknown as typeof fetch; - let harness = createHarness({ fetcher }); - expect( - await harness.provider.issueDownload({ - resourceId: "resource-1", - signal: new AbortController().signal, - }), - ).toMatchObject({ - ok: false, - error: { - code: "EXPIRED_RESOURCE", - recovery: "REISSUE_CAPABILITY", - }, - }); - - const acceptedPayload = downloadCapabilityPayload(bytes, { - expiresAtEpochMs: NOW + 2_000, - }); - let current = NOW; - fetcher = vi.fn(async (input: RequestInfo | URL) => - String(input) === CONTROL_ENDPOINT - ? jsonResponse(acceptedPayload) - : downloadResponse(bytes.slice().buffer, acceptedPayload), - ) as unknown as typeof fetch; - harness = createHarness({ - fetcher, - now: () => current, - }); - const issued = await harness.provider.issueDownload({ - resourceId: "resource-1", - signal: new AbortController().signal, - }); - expect(issued.ok).toBe(true); - if (!issued.ok) return; - current = NOW + 1_001; - expect( - await harness.executor.downloadSources.open({ - resourceId: "resource-1", - capability: issued.value, - signal: new AbortController().signal, - }), - ).toMatchObject({ - ok: false, - error: { - code: "EXPIRED_RESOURCE", - recovery: "REISSUE_CAPABILITY", - }, - }); - expect(fetcher).toHaveBeenCalledTimes(1); - }); - - it("closes malformed AbortSignal inputs at every public boundary", async () => { - const bytes = new Uint8Array([1, 2]); - const payload = downloadCapabilityPayload(bytes); - const uploadChecksum = sha256Hex(bytes); - const uploadPayload = uploadCapabilityPayload({ - bytes, - checksum: uploadChecksum, - }); - const fetcher = vi.fn( - async (input: RequestInfo | URL, init?: RequestInit) => { - if (String(input) === CONTROL_ENDPOINT) { - const request = JSON.parse(String(init?.body)) as { - method: string; - }; - return jsonResponse( - request.method === "GET" ? payload : uploadPayload, - ); - } - if (String(input) === DOWNLOAD_HREF) { - return downloadResponse(bytes.slice().buffer, payload); - } - return responseWithUrl( - new Response(null, { - status: 200, - headers: { - [POLICY_HEADER]: "v1", - "Content-Length": "0", - ETag: "\"part-etag-1\"", - }, - }), - String(uploadPayload.href), - ); - }, - ) as unknown as typeof fetch; - const { provider, executor } = createHarness({ fetcher }); - const malformed = {} as AbortSignal; - - expect( - await provider.issueDownload({ - resourceId: "resource-1", - signal: malformed, - }), - ).toMatchObject({ - ok: false, - error: { code: "INVALID_INPUT" }, - }); - expect( - await provider.issueUploadPart({ - sessionId: UPLOAD_SESSION_ID, - requestBindingSha256: REQUEST_BINDING_SHA256, - uploadBindingSha256: "b".repeat(64), - partNumber: 1, - offset: 0, - byteLength: bytes.byteLength, - checksumSha256: uploadChecksum, - mediaType: "application/octet-stream", - idempotencyKey: "part-attempt-1", - signal: malformed, - }), - ).toMatchObject({ - ok: false, - error: { code: "INVALID_INPUT" }, - }); - - const issuedDownload = await provider.issueDownload({ - resourceId: "resource-1", - signal: new AbortController().signal, - }); - expect(issuedDownload.ok).toBe(true); - if (!issuedDownload.ok) return; - expect( - await executor.downloadSources.open({ - resourceId: "resource-1", - capability: issuedDownload.value, - signal: malformed, - }), - ).toMatchObject({ - ok: false, - error: { code: "INVALID_INPUT" }, - }); - const opened = await executor.downloadSources.open({ - resourceId: "resource-1", - capability: issuedDownload.value, - signal: new AbortController().signal, - }); - expect(opened.ok).toBe(true); - if (!opened.ok) return; - expect(await collect(opened.value, malformed)).toMatchObject([ - { ok: false, error: { code: "INVALID_INPUT" } }, - ]); - expect(await collect(opened.value)).toMatchObject([ - { ok: false, error: { code: "CONFLICT" } }, - ]); - - const issuedUpload = await provider.issueUploadPart({ - sessionId: UPLOAD_SESSION_ID, - requestBindingSha256: REQUEST_BINDING_SHA256, - uploadBindingSha256: "b".repeat(64), - partNumber: 1, - offset: 0, - byteLength: bytes.byteLength, - checksumSha256: uploadChecksum, - mediaType: "application/octet-stream", - idempotencyKey: "part-attempt-1", - signal: new AbortController().signal, - }); - expect(issuedUpload.ok).toBe(true); - if (!issuedUpload.ok) return; - expect( - await executor.uploadParts.put({ - capability: issuedUpload.value, - sessionId: UPLOAD_SESSION_ID, - requestBindingSha256: REQUEST_BINDING_SHA256, - uploadBindingSha256: "b".repeat(64), - partNumber: 1, - offset: 0, - byteLength: bytes.byteLength, - checksumSha256: uploadChecksum, - idempotencyKey: "part-attempt-1", - bytes, - signal: malformed, - }), - ).toMatchObject({ - ok: false, - error: { code: "INVALID_INPUT" }, - }); - }); - - it("snapshots, verifies and uploads a PUT part with a separate response receipt", async () => { - const original = new Uint8Array([9, 8, 7]); - const checksum = sha256Hex(original); - const payload = uploadCapabilityPayload({ - bytes: original, - checksum, - }); - let releaseDigest: (() => void) | undefined; - const digestGate = new Promise((resolve) => { - releaseDigest = resolve; - }); - const sentBodies: number[][] = []; - const dataCalls: RequestInit[] = []; - const fetcher = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { - if (String(input) === CONTROL_ENDPOINT) return jsonResponse(payload); - dataCalls.push(init ?? {}); - sentBodies.push([ - ...new Uint8Array(init?.body as ArrayBuffer), - ]); - return responseWithUrl( - new Response(null, { - status: 200, - headers: { - [POLICY_HEADER]: "v1", - "Content-Length": "0", - ETag: "\"part-etag-1\"", - }, - }), - String(payload.href), - ); - }) as unknown as typeof fetch; - const { provider, executor } = createHarness({ - fetcher, - digestBytes: async (bytes) => { - await digestGate; - return sha256Hex(bytes); - }, - }); - const issued = await provider.issueUploadPart({ - sessionId: UPLOAD_SESSION_ID, - requestBindingSha256: REQUEST_BINDING_SHA256, - uploadBindingSha256: "b".repeat(64), - partNumber: 1, - offset: 0, - byteLength: original.byteLength, - checksumSha256: checksum, - mediaType: "application/octet-stream", - idempotencyKey: "part-attempt-1", - signal: new AbortController().signal, - }); - expect(issued.ok).toBe(true); - if (!issued.ok) return; - const request = { - capability: issued.value, - sessionId: UPLOAD_SESSION_ID, - requestBindingSha256: REQUEST_BINDING_SHA256, - uploadBindingSha256: "b".repeat(64), - partNumber: 1, - offset: 0, - byteLength: original.byteLength, - checksumSha256: checksum, - idempotencyKey: "part-attempt-1", - bytes: original, - signal: new AbortController().signal, - }; - const pending = executor.uploadParts.put(request); - original.fill(0); - request.sessionId = "mutated-session"; - request.requestBindingSha256 = "d".repeat(64); - request.checksumSha256 = "f".repeat(64); - releaseDigest?.(); - - expect(await pending).toEqual({ - ok: true, - value: { - bytesWritten: 3, - checksumSha256: checksum, - receiptToken: "part-etag-1", - }, - }); - expect(sentBodies).toEqual([[9, 8, 7]]); - expect(dataCalls[0]).toMatchObject({ - method: "PUT", - credentials: "omit", - redirect: "error", - referrerPolicy: "no-referrer", - }); - expect( - (dataCalls[0]?.headers as Headers).get(CHECKSUM_HEADER), - ).toBe(checksum); - }); - - it.each(["sessionId", "requestBindingSha256"] as const)( - "rejects an actual PUT whose %s differs from the capability", - async (field) => { - const bytes = new Uint8Array([3, 2, 1]); - const checksum = sha256Hex(bytes); - const payload = uploadCapabilityPayload({ bytes, checksum }); - const fetcher = vi.fn(async () => - jsonResponse(payload), - ) as unknown as typeof fetch; - const { provider, executor } = createHarness({ fetcher }); - const issued = await provider.issueUploadPart({ - sessionId: UPLOAD_SESSION_ID, - requestBindingSha256: REQUEST_BINDING_SHA256, - uploadBindingSha256: "b".repeat(64), - partNumber: 1, - offset: 0, - byteLength: bytes.byteLength, - checksumSha256: checksum, - mediaType: "application/octet-stream", - idempotencyKey: "part-attempt-1", - signal: new AbortController().signal, - }); - expect(issued.ok).toBe(true); - if (!issued.ok) return; - expect( - await executor.uploadParts.put({ - capability: issued.value, - sessionId: - field === "sessionId" - ? "different-session" - : UPLOAD_SESSION_ID, - requestBindingSha256: - field === "requestBindingSha256" - ? "d".repeat(64) - : REQUEST_BINDING_SHA256, - uploadBindingSha256: "b".repeat(64), - partNumber: 1, - offset: 0, - byteLength: bytes.byteLength, - checksumSha256: checksum, - idempotencyKey: "part-attempt-1", - bytes, - signal: new AbortController().signal, - }), - ).toMatchObject({ - ok: false, - error: { code: "POLICY_REJECTED" }, - }); - expect(fetcher).toHaveBeenCalledTimes(1); - }, - ); - - it("rejects URL-shaped upload receipts", async () => { - const bytes = new Uint8Array([4, 5, 6]); - const checksum = sha256Hex(bytes); - const payload = uploadCapabilityPayload({ bytes, checksum }); - const fetcher = vi.fn(async (input: RequestInfo | URL) => { - if (String(input) === CONTROL_ENDPOINT) { - return jsonResponse(payload); - } - return responseWithUrl( - new Response(null, { - status: 200, - headers: { - [POLICY_HEADER]: "v1", - "Content-Length": "0", - ETag: "\"https://objects.example/authorizing-token\"", - }, - }), - String(payload.href), - ); - }) as unknown as typeof fetch; - const { provider, executor } = createHarness({ fetcher }); - const issued = await provider.issueUploadPart({ - sessionId: UPLOAD_SESSION_ID, - requestBindingSha256: REQUEST_BINDING_SHA256, - uploadBindingSha256: "b".repeat(64), - partNumber: 1, - offset: 0, - byteLength: bytes.byteLength, - checksumSha256: checksum, - mediaType: "application/octet-stream", - idempotencyKey: "part-attempt-1", - signal: new AbortController().signal, - }); - expect(issued.ok).toBe(true); - if (!issued.ok) return; - expect( - await executor.uploadParts.put({ - capability: issued.value, - sessionId: UPLOAD_SESSION_ID, - requestBindingSha256: REQUEST_BINDING_SHA256, - uploadBindingSha256: "b".repeat(64), - partNumber: 1, - offset: 0, - byteLength: bytes.byteLength, - checksumSha256: checksum, - idempotencyKey: "part-attempt-1", - bytes, - signal: new AbortController().signal, - }), - ).toMatchObject({ - ok: false, - error: { code: "INTEGRITY_FAILED" }, - }); - }); - - it("drains a bounded successful PUT acknowledgement without cancelling it", async () => { - const bytes = new Uint8Array([4, 5, 6]); - const checksum = sha256Hex(bytes); - const payload = uploadCapabilityPayload( - { bytes, checksum }, - { expectedResponseByteLength: 2 }, - ); - let cancelled = false; - const fetcher = vi.fn(async (input: RequestInfo | URL) => { - if (String(input) === CONTROL_ENDPOINT) { - return jsonResponse(payload); - } - const body = new ReadableStream({ - start(controller) { - controller.enqueue(new Uint8Array([8, 9])); - controller.close(); - }, - cancel() { - cancelled = true; - }, - }); - return responseWithUrl( - new Response(body, { - status: 200, - headers: { - [POLICY_HEADER]: "v1", - "Content-Length": "2", - ETag: "\"part-etag-1\"", - }, - }), - String(payload.href), - ); - }) as unknown as typeof fetch; - const { provider, executor } = createHarness({ fetcher }); - const issued = await provider.issueUploadPart({ - sessionId: UPLOAD_SESSION_ID, - requestBindingSha256: REQUEST_BINDING_SHA256, - uploadBindingSha256: "b".repeat(64), - partNumber: 1, - offset: 0, - byteLength: bytes.byteLength, - checksumSha256: checksum, - mediaType: "application/octet-stream", - idempotencyKey: "part-attempt-1", - signal: new AbortController().signal, - }); - expect(issued.ok).toBe(true); - if (!issued.ok) return; - expect( - await executor.uploadParts.put({ - capability: issued.value, - sessionId: UPLOAD_SESSION_ID, - requestBindingSha256: REQUEST_BINDING_SHA256, - uploadBindingSha256: "b".repeat(64), - partNumber: 1, - offset: 0, - byteLength: bytes.byteLength, - checksumSha256: checksum, - idempotencyKey: "part-attempt-1", - bytes, - signal: new AbortController().signal, - }), - ).toMatchObject({ - ok: true, - value: { receiptToken: "part-etag-1" }, - }); - expect(cancelled).toBe(false); - }); - - it("accepts an empty 204 PUT acknowledgement", async () => { - const bytes = new Uint8Array([4, 5, 6]); - const checksum = sha256Hex(bytes); - const payload = uploadCapabilityPayload( - { bytes, checksum }, - { - expectedStatus: 204, - expectedResponseByteLength: 0, - }, - ); - const fetcher = vi.fn(async (input: RequestInfo | URL) => - String(input) === CONTROL_ENDPOINT - ? jsonResponse(payload) - : responseWithUrl( - new Response(null, { - status: 204, - headers: { - [POLICY_HEADER]: "v1", - ETag: "\"part-etag-204\"", - }, - }), - String(payload.href), - ), - ) as unknown as typeof fetch; - const { provider, executor } = createHarness({ fetcher }); - const issued = await provider.issueUploadPart({ - sessionId: UPLOAD_SESSION_ID, - requestBindingSha256: REQUEST_BINDING_SHA256, - uploadBindingSha256: "b".repeat(64), - partNumber: 1, - offset: 0, - byteLength: bytes.byteLength, - checksumSha256: checksum, - mediaType: "application/octet-stream", - idempotencyKey: "part-attempt-1", - signal: new AbortController().signal, - }); - expect(issued.ok).toBe(true); - if (!issued.ok) return; - expect( - await executor.uploadParts.put({ - capability: issued.value, - sessionId: UPLOAD_SESSION_ID, - requestBindingSha256: REQUEST_BINDING_SHA256, - uploadBindingSha256: "b".repeat(64), - partNumber: 1, - offset: 0, - byteLength: bytes.byteLength, - checksumSha256: checksum, - idempotencyKey: "part-attempt-1", - bytes, - signal: new AbortController().signal, - }), - ).toMatchObject({ - ok: true, - value: { receiptToken: "part-etag-204" }, - }); - }); - - it("cancels a PUT acknowledgement whose declared length violates its binding", async () => { - const bytes = new Uint8Array([4, 5, 6]); - const checksum = sha256Hex(bytes); - const payload = uploadCapabilityPayload({ bytes, checksum }); - let cancelled = false; - const fetcher = vi.fn(async (input: RequestInfo | URL) => { - if (String(input) === CONTROL_ENDPOINT) { - return jsonResponse(payload); - } - const body = new ReadableStream({ - pull() {}, - cancel() { - cancelled = true; - }, - }); - return responseWithUrl( - new Response(body, { - status: 200, - headers: { - [POLICY_HEADER]: "v1", - "Content-Length": "1", - ETag: "\"part-etag-1\"", - }, - }), - String(payload.href), - ); - }) as unknown as typeof fetch; - const { provider, executor } = createHarness({ fetcher }); - const issued = await provider.issueUploadPart({ - sessionId: UPLOAD_SESSION_ID, - requestBindingSha256: REQUEST_BINDING_SHA256, - uploadBindingSha256: "b".repeat(64), - partNumber: 1, - offset: 0, - byteLength: bytes.byteLength, - checksumSha256: checksum, - mediaType: "application/octet-stream", - idempotencyKey: "part-attempt-1", - signal: new AbortController().signal, - }); - expect(issued.ok).toBe(true); - if (!issued.ok) return; - expect( - await executor.uploadParts.put({ - capability: issued.value, - sessionId: UPLOAD_SESSION_ID, - requestBindingSha256: REQUEST_BINDING_SHA256, - uploadBindingSha256: "b".repeat(64), - partNumber: 1, - offset: 0, - byteLength: bytes.byteLength, - checksumSha256: checksum, - idempotencyKey: "part-attempt-1", - bytes, - signal: new AbortController().signal, - }), - ).toMatchObject({ - ok: false, - error: { code: "POLICY_REJECTED" }, - }); - expect(cancelled).toBe(true); - }); - - it("observes only safe operation, outcome, failure and byte buckets", async () => { - const bytes = new Uint8Array([7, 8, 9]); - const downloadPayload = downloadCapabilityPayload(bytes); - const checksum = sha256Hex(bytes); - const uploadPayload = uploadCapabilityPayload({ bytes, checksum }); - const observations: BrowserDataObservation[] = []; - const fetcher = vi.fn( - async (input: RequestInfo | URL, init?: RequestInit) => { - if (String(input) === CONTROL_ENDPOINT) { - const request = JSON.parse(String(init?.body)) as { - method: string; - }; - return jsonResponse( - request.method === "GET" - ? downloadPayload - : uploadPayload, - ); - } - if (String(input) === DOWNLOAD_HREF) { - return downloadResponse( - bytes.slice().buffer, - downloadPayload, - ); - } - return responseWithUrl( - new Response(null, { - status: 200, - headers: { - [POLICY_HEADER]: "v1", - "Content-Length": "0", - ETag: "\"part-etag-secret\"", - }, - }), - String(uploadPayload.href), - ); - }, - ) as unknown as typeof fetch; - const { provider, executor } = createHarness({ - fetcher, - observer: { - record(observation) { - observations.push(observation); - }, - }, - }); - const issuedDownload = await provider.issueDownload({ - resourceId: "resource-1", - signal: new AbortController().signal, - }); - expect(issuedDownload.ok).toBe(true); - if (!issuedDownload.ok) return; - const opened = await executor.downloadSources.open({ - resourceId: "resource-1", - capability: issuedDownload.value, - signal: new AbortController().signal, - }); - expect(opened.ok).toBe(true); - if (!opened.ok) return; - expect((await collect(opened.value)).every((result) => result.ok)).toBe( - true, - ); - - const issuedUpload = await provider.issueUploadPart({ - sessionId: UPLOAD_SESSION_ID, - requestBindingSha256: REQUEST_BINDING_SHA256, - uploadBindingSha256: "b".repeat(64), - partNumber: 1, - offset: 0, - byteLength: bytes.byteLength, - checksumSha256: checksum, - mediaType: "application/octet-stream", - idempotencyKey: "part-attempt-1", - signal: new AbortController().signal, - }); - expect(issuedUpload.ok).toBe(true); - if (!issuedUpload.ok) return; - expect( - await executor.uploadParts.put({ - capability: issuedUpload.value, - sessionId: UPLOAD_SESSION_ID, - requestBindingSha256: REQUEST_BINDING_SHA256, - uploadBindingSha256: "b".repeat(64), - partNumber: 1, - offset: 0, - byteLength: bytes.byteLength, - checksumSha256: checksum, - idempotencyKey: "part-attempt-1", - bytes, - signal: new AbortController().signal, - }), - ).toMatchObject({ ok: true }); - - expect(observations).toEqual([ - { - operation: "PRESIGNED_TRANSFER", - outcome: "SUCCEEDED", - byteBucket: "LT1MIB", - }, - { - operation: "PRESIGNED_TRANSFER", - outcome: "SUCCEEDED", - byteBucket: "LT1MIB", - }, - { - operation: "DOWNLOAD", - outcome: "SUCCEEDED", - byteBucket: "LT1MIB", - }, - { - operation: "PRESIGNED_TRANSFER", - outcome: "SUCCEEDED", - byteBucket: "LT1MIB", - }, - { - operation: "UPLOAD_PART", - outcome: "SUCCEEDED", - byteBucket: "LT1MIB", - }, - ]); - const serialized = JSON.stringify(observations); - for (const secret of [ - DOWNLOAD_HREF, - "do-not-log-this", - checksum, - "capability-download-1", - "capability-upload-1", - "part-etag-secret", - "resource-1", - ]) { - expect(serialized).not.toContain(secret); - } - }); - - it("connects an issued capability to DownloadDeliveryPort without caller digest input", async () => { - const bytes = new TextEncoder().encode("verified"); - const payload = downloadCapabilityPayload(bytes); - const fetcher = vi.fn(async (input: RequestInfo | URL) => - String(input) === CONTROL_ENDPOINT - ? jsonResponse(payload) - : downloadResponse(bytes.slice().buffer, payload), - ) as unknown as typeof fetch; - const { provider, executor } = createHarness({ fetcher }); - const issued = await provider.issueDownload({ - resourceId: "resource-1", - signal: new AbortController().signal, - }); - expect(issued.ok).toBe(true); - if (!issued.ok) return; - - const policy = browserFilePolicyReference( - "download", - "presigned-stream", - ); - const policies = new BrowserFilePolicyRegistry({ - profiles: [ - { - reference: policy, - download: { - strategy: "PROMPT_AND_STREAM", - mediaType: "application/octet-stream", - safeExtension: ".bin", - maxTransferBytes: 64, - maxBufferedBytes: 8, - integrity: "REQUIRED", - }, - }, - ], - hardLimits: { - maxInspectionBytes: 64, - maxRetainedFileBytes: 64, - maxPreviewBytes: 64, - maxObjectUrlBytes: 64, - maxTransferBytes: 64, - }, - }); - const written: number[] = []; - const handle: SaveFileHandle = { - async createWritable() { - return new WritableStream({ - write(chunk) { - written.push(...chunk); - }, - }); - }, - }; - const downloads = createDownloadDeliveryAdapter({ - host: { handoff() {} }, - policies, - hardMaxObjectUrlBytes: 64, - hardMaxTransferBytes: 64, - browserManagedCapabilities: { - resolve() { - throw new TypeError("not used"); - }, - }, - openAuthorizedSource: - executor.downloadSources.open.bind(executor.downloadSources), - showSaveFilePicker: async () => handle, - userActivation: { isActive: true }, - now: () => NOW, - }); - const result = await downloads.deliver({ - policy, - source: { - kind: "AUTHORIZED_STREAM_RESOURCE", - resourceId: "resource-1", - capability: issued.value, - }, - suggestedFileName: "artifact.bin", - signal: new AbortController().signal, - onProgress() {}, - }); - expect(result).toMatchObject({ - ok: true, - value: { - kind: "SAVED", - integrity: "VERIFIED", - bytesWritten: bytes.byteLength, - }, - }); - expect(written).toEqual([...bytes]); - }); - - /** - * TR-RR-04. A presigned byte source owns a fetch reader and a capability - * lease, and its port requires `close()`. The delivery consumer never called - * it, so every outcome — success, validation failure, writer failure and - * abort — leaked both. - */ - it.each([ - { label: "success", mode: "SUCCESS" as const }, - { label: "writer failure", mode: "WRITER_FAILURE" as const }, - { label: "abort", mode: "ABORT" as const }, - ])("closes the presigned source exactly once on $label", async ({ mode }) => { - const bytes = new Uint8Array([1, 2, 3]); - let closes = 0; - const controller = new AbortController(); - const source = { - byteLength: bytes.byteLength, - integrity: "VERIFIED_ON_SUCCESSFUL_EXHAUSTION" as const, - capability: undefined as never, - close() { - closes += 1; - }, - async *stream() { - if (mode === "ABORT") controller.abort(); - yield { ok: true as const, value: bytes }; - }, - }; - const capability = Object.freeze({ - capabilityReceipt: "capability-close-1", - method: "GET" as const, - binding: { kind: "DOWNLOAD" as const, resourceId: "resource-1" }, - mediaType: "application/octet-stream", - byteLength: bytes.byteLength, - maxBytes: bytes.byteLength, - expectedSha256: "a".repeat(64), - expiresAtEpochMs: NOW + 60_000, - }); - source.capability = capability as never; - - const closePolicy = browserFilePolicyReference( - "download", - "presigned-close", - ); - const policies = new BrowserFilePolicyRegistry({ - profiles: [ - { - reference: closePolicy, - download: { - strategy: "PROMPT_AND_STREAM", - mediaType: "application/octet-stream", - safeExtension: ".bin", - maxTransferBytes: 64, - maxBufferedBytes: 8, - integrity: "REQUIRED", - }, - }, - ], - hardLimits: { - maxInspectionBytes: 64, - maxRetainedFileBytes: 64, - maxPreviewBytes: 64, - maxObjectUrlBytes: 64, - maxTransferBytes: 64, - }, - }); - const handle: SaveFileHandle = { - async createWritable() { - return new WritableStream({ - write() { - if (mode === "WRITER_FAILURE") { - throw new TypeError("writer exploded"); - } - }, - }); - }, - }; - const downloads = createDownloadDeliveryAdapter({ - host: { handoff() {} }, - policies, - hardMaxObjectUrlBytes: 64, - hardMaxTransferBytes: 64, - browserManagedCapabilities: { - resolve() { - throw new TypeError("not used"); - }, - }, - openAuthorizedSource: async () => - ({ ok: true, value: source }) as never, - showSaveFilePicker: async () => handle, - userActivation: { isActive: true }, - now: () => NOW, - }); - - const deliveryResult = await downloads.deliver({ - policy: closePolicy, - source: { - kind: "AUTHORIZED_STREAM_RESOURCE", - resourceId: "resource-1", - capability: capability as never, - }, - suggestedFileName: "artifact.bin", - signal: controller.signal, - onProgress() {}, - }); - - void deliveryResult; - expect(closes).toBe(1); - }); - - /** - * TR-02. A lease that resolved after the abort already ended the delivery - * never reached the holder, so nothing closed it: the fetch reader and the - * capability lease outlived the terminal result. - */ - it("closes a source lease that arrives after the delivery was aborted", async () => { - const bytes = new Uint8Array([1, 2, 3]); - let closes = 0; - const controller = new AbortController(); - let releaseOpen: - | ((value: { ok: true; value: unknown }) => void) - | undefined; - const source = { - byteLength: bytes.byteLength, - integrity: "VERIFIED_ON_SUCCESSFUL_EXHAUSTION" as const, - capability: undefined as never, - close() { - closes += 1; - }, - async *stream() { - yield { ok: true as const, value: bytes }; - }, - }; - const capability = Object.freeze({ - capabilityReceipt: "capability-late-1", - method: "GET" as const, - binding: { kind: "DOWNLOAD" as const, resourceId: "resource-1" }, - mediaType: "application/octet-stream", - byteLength: bytes.byteLength, - maxBytes: bytes.byteLength, - expectedSha256: "a".repeat(64), - expiresAtEpochMs: NOW + 60_000, - }); - source.capability = capability as never; - - const latePolicy = browserFilePolicyReference("download", "presigned-late"); - const policies = new BrowserFilePolicyRegistry({ - profiles: [ - { - reference: latePolicy, - download: { - strategy: "PROMPT_AND_STREAM", - mediaType: "application/octet-stream", - safeExtension: ".bin", - maxTransferBytes: 64, - maxBufferedBytes: 8, - integrity: "REQUIRED", - }, - }, - ], - hardLimits: { - maxInspectionBytes: 64, - maxRetainedFileBytes: 64, - maxPreviewBytes: 64, - maxObjectUrlBytes: 64, - maxTransferBytes: 64, - }, - }); - const downloads = createDownloadDeliveryAdapter({ - host: { handoff() {} }, - policies, - hardMaxObjectUrlBytes: 64, - hardMaxTransferBytes: 64, - browserManagedCapabilities: { - resolve() { - throw new TypeError("not used"); - }, - }, - // Ignores the signal entirely and resolves only when the test says so. - openAuthorizedSource: () => - new Promise((resolve) => { - releaseOpen = resolve as never; - }) as never, - showSaveFilePicker: async () => ({ - async createWritable() { - return new WritableStream({ write() {} }); - }, - }), - userActivation: { isActive: true }, - now: () => NOW, - }); - - const delivering = downloads.deliver({ - policy: latePolicy, - source: { - kind: "AUTHORIZED_STREAM_RESOURCE", - resourceId: "resource-1", - capability: capability as never, - }, - suggestedFileName: "artifact.bin", - signal: controller.signal, - onProgress() {}, - }); - await new Promise((resolve) => setTimeout(resolve, 0)); - controller.abort(); - const delivered = await delivering; - expect(delivered.ok).toBe(false); - - // The lease arrives only now, long after the terminal result. - releaseOpen?.({ ok: true, value: source }); - await new Promise((resolve) => setTimeout(resolve, 0)); - expect(closes).toBe(1); - }); - - it("does not leave a late rejection unhandled after an abort", async () => { - const unhandled: unknown[] = []; - const onUnhandled = (reason: unknown) => unhandled.push(reason); - process.on("unhandledRejection", onUnhandled); - try { - const controller = new AbortController(); - let rejectOpen: ((reason: unknown) => void) | undefined; - const rejectPolicy = browserFilePolicyReference( - "download", - "presigned-late-reject", - ); - const policies = new BrowserFilePolicyRegistry({ - profiles: [ - { - reference: rejectPolicy, - download: { - strategy: "PROMPT_AND_STREAM", - mediaType: "application/octet-stream", - safeExtension: ".bin", - maxTransferBytes: 64, - maxBufferedBytes: 8, - integrity: "REQUIRED", - }, - }, - ], - hardLimits: { - maxInspectionBytes: 64, - maxRetainedFileBytes: 64, - maxPreviewBytes: 64, - maxObjectUrlBytes: 64, - maxTransferBytes: 64, - }, - }); - const downloads = createDownloadDeliveryAdapter({ - host: { handoff() {} }, - policies, - hardMaxObjectUrlBytes: 64, - hardMaxTransferBytes: 64, - browserManagedCapabilities: { - resolve() { - throw new TypeError("not used"); - }, - }, - openAuthorizedSource: () => - new Promise((_resolve, reject) => { - rejectOpen = reject; - }) as never, - showSaveFilePicker: async () => ({ - async createWritable() { - return new WritableStream({ write() {} }); - }, - }), - userActivation: { isActive: true }, - now: () => NOW, - }); - - const delivering = downloads.deliver({ - policy: rejectPolicy, - source: { - kind: "AUTHORIZED_STREAM_RESOURCE", - resourceId: "resource-1", - capability: Object.freeze({ - capabilityReceipt: "capability-late-2", - method: "GET" as const, - binding: { kind: "DOWNLOAD" as const, resourceId: "resource-1" }, - mediaType: "application/octet-stream", - byteLength: 3, - maxBytes: 3, - expectedSha256: "a".repeat(64), - expiresAtEpochMs: NOW + 60_000, - }) as never, - }, - suggestedFileName: "artifact.bin", - signal: controller.signal, - onProgress() {}, - }); - await new Promise((resolve) => setTimeout(resolve, 0)); - controller.abort(); - await delivering; - - rejectOpen?.(new Error("late open failure")); - await new Promise((resolve) => setTimeout(resolve, 10)); - expect(unhandled).toEqual([]); - } finally { - process.off("unhandledRejection", onUnhandled); - } - }); }); - -/** - * BT-PRE-01. The download lease is lazy, so a response-shape rejection is - * observed on first consumption rather than at `open()`. - */ -async function firstStreamResult( - opened: Awaited< - ReturnType< - ReturnType["executor"]["downloadSources"]["open"] - > - >, -): Promise { - if (!opened.ok) return opened; - try { - for await (const chunk of opened.value.stream( - new AbortController().signal, - )) { - if (!chunk.ok) return chunk; - } - return { ok: true }; - } finally { - opened.value.close(); - } -} diff --git a/tests/unit/product-features.test.ts b/tests/unit/product-features.test.ts index a771db6..9bf9dc5 100644 --- a/tests/unit/product-features.test.ts +++ b/tests/unit/product-features.test.ts @@ -17,7 +17,7 @@ import { } from "../../src/features/installed-feature-contracts.ts"; const COMPILED = Object.freeze([ - Object.freeze({ featureId: "reference-feature" }), + Object.freeze({ featureId: "alpha-feature" }), Object.freeze({ featureId: "billing" }), ]); @@ -27,7 +27,7 @@ describe("build-time product selection", () => { expect( selectCompiledProductFeatures(COMPILED, declared).map((f) => f.featureId), String(declared), - ).toEqual(["reference-feature", "billing"]); + ).toEqual(["alpha-feature", "billing"]); } }); @@ -36,10 +36,10 @@ describe("build-time product selection", () => { selectCompiledProductFeatures(COMPILED, "billing").map((f) => f.featureId), ).toEqual(["billing"]); expect( - selectCompiledProductFeatures(COMPILED, " billing , reference-feature ").map( + selectCompiledProductFeatures(COMPILED, " billing , alpha-feature ").map( (f) => f.featureId, ), - ).toEqual(["reference-feature", "billing"]); + ).toEqual(["alpha-feature", "billing"]); }); it("selects nothing only when asked explicitly", () => { @@ -80,13 +80,13 @@ describe("build-time product selection", () => { describe("runtime product feature resolution", () => { it("reports active, disabled and not-installed distinctly", () => { const statuses = resolveProductFeatures( - ["reference-feature", "billing"], - ["reference-feature"], - { "reference-feature": "DISABLED" }, + ["alpha-feature", "billing"], + ["alpha-feature"], + { "alpha-feature": "DISABLED" }, ); expect(statuses).toEqual([ + { featureId: "alpha-feature", state: "DISABLED_BY_CONFIG" }, { featureId: "billing", state: "NOT_INSTALLED" }, - { featureId: "reference-feature", state: "DISABLED_BY_CONFIG" }, ]); expect(activeProductFeatureIds(statuses)).toEqual([]); }); @@ -104,11 +104,11 @@ describe("runtime product feature resolution", () => { // A shared runtime document may cover several builds, so a stale key is // inert rather than fatal. const statuses = resolveProductFeatures( - ["reference-feature"], - ["reference-feature"], + ["alpha-feature"], + ["alpha-feature"], { analytics: "DISABLED" }, ); - expect(activeProductFeatureIds(statuses)).toEqual(["reference-feature"]); + expect(activeProductFeatureIds(statuses)).toEqual(["alpha-feature"]); }); it("leaves an installed feature active without an override", () => { @@ -141,15 +141,15 @@ describe("runtime config carries the switch", () => { expect( runtimeConfigV2ArtifactSchema.parse({ ...base, - FEATURE_OVERRIDES: { "reference-feature": "DISABLED" }, + FEATURE_OVERRIDES: { "alpha-feature": "DISABLED" }, }).FEATURE_OVERRIDES, - ).toEqual({ "reference-feature": "DISABLED" }); + ).toEqual({ "alpha-feature": "DISABLED" }); // There is no "ENABLED": the vocabulary itself is what makes the rule // unbreakable, not a check somewhere downstream. expect( runtimeConfigV2ArtifactSchema.safeParse({ ...base, - FEATURE_OVERRIDES: { "reference-feature": "ENABLED" }, + FEATURE_OVERRIDES: { "alpha-feature": "ENABLED" }, }).success, ).toBe(false); }); @@ -233,12 +233,16 @@ describe("route ownership", () => { expect(ROUTE_FEATURE_OWNER["NOT_FOUND"]).toBeUndefined(); }); - it("owns exactly the routes the registry received from features", () => { + it("owns exactly routes that exist in the composed registry", () => { // Template merge. `owned` is empty in this product: the only installed // feature's screens were removed by the UI migration. The invariant still // holds and starts asserting again the moment a feature route returns. - for (const routeId of Object.keys(ROUTE_FEATURE_OWNER)) { + const owned = Object.keys(ROUTE_FEATURE_OWNER); + for (const routeId of owned) { expect(Object.keys(ROUTE_REGISTRY), routeId).toContain(routeId); } + expect( + owned.every((routeId) => ROUTE_FEATURE_OWNER[routeId] !== undefined), + ).toBe(true); }); }); diff --git a/tests/unit/public-response-cache-fixture.ts b/tests/unit/public-response-cache-fixture.ts new file mode 100644 index 0000000..313f025 --- /dev/null +++ b/tests/unit/public-response-cache-fixture.ts @@ -0,0 +1,137 @@ +import type { + PublicCacheAsset, + PublicCacheReleaseManifest, +} from "../../src/application/ports/browser-file-storage/cache-storage-ports.ts"; +import { + createDefaultPublicCachePolicy, + type PublicCacheRuntimePolicy, +} from "../../src/adapters/cache-storage/public-cache-policy.ts"; +import { + computePublicCacheManifestDigestHex, + type PublicCacheMutationLock, +} from "../../src/adapters/cache-storage/public-response-cache-adapter.ts"; + +export class MemoryCache { + readonly responses: Array> = []; + + async match(request: RequestInfo | URL): Promise { + const url = + request instanceof Request ? request.url : new URL(String(request)).href; + const nativeRequest = + request instanceof Request ? request : new Request(url); + return this.responses + .find( + (entry) => + entry.request.url === url && + varyMatches(entry.request, nativeRequest, entry.response), + ) + ?.response.clone(); + } + + async put(request: RequestInfo | URL, response: Response): Promise { + const url = + request instanceof Request ? request.url : new URL(String(request)).href; + const nativeRequest = + request instanceof Request ? request.clone() : new Request(url); + const existing = this.responses.findIndex( + (entry) => + entry.request.url === url && + varyMatches(entry.request, nativeRequest, response), + ); + const entry = { + request: nativeRequest, + response: response.clone(), + }; + if (existing >= 0) this.responses.splice(existing, 1, entry); + else this.responses.push(entry); + } +} + +function varyMatches( + storedRequest: Request, + incomingRequest: Request, + response: Response, +): boolean { + const vary = response.headers.get("vary"); + if (!vary) return true; + return vary + .split(",") + .map((name) => name.trim().toLowerCase()) + .every( + (name) => + storedRequest.headers.get(name) === + incomingRequest.headers.get(name), + ); +} + +export class MemoryCacheStorage { + readonly caches = new Map(); + + async open(name: string): Promise { + let cache = this.caches.get(name); + if (!cache) { + cache = new MemoryCache(); + this.caches.set(name, cache); + } + return cache as unknown as Cache; + } + + async keys(): Promise { + return [...this.caches.keys()]; + } + + async delete(name: string): Promise { + return this.caches.delete(name); + } +} + +export const immediateLock: PublicCacheMutationLock = { + async run(_signal, task) { + return await task(); + }, +}; + +export function deferred() { + let settle: ((value: Value) => void) | undefined; + const promise = new Promise((resolve) => { + settle = resolve; + }); + return Object.freeze({ + promise, + resolve(value: Value): void { + settle?.(value); + }, + }); +} + +export async function digestHex(bytes: Uint8Array): Promise { + const digest = await globalThis.crypto.subtle.digest( + "SHA-256", + Uint8Array.from(bytes), + ); + return [...new Uint8Array(digest)] + .map((byte) => byte.toString(16).padStart(2, "0")) + .join(""); +} + +export async function manifestFor( + releaseRegistryId: string, + assets: readonly PublicCacheAsset[], + policy: PublicCacheRuntimePolicy = createDefaultPublicCachePolicy( + "https://assets.example.test", + ), +): Promise { + return { + releaseRegistryId, + assets, + manifestDigestHex: await computePublicCacheManifestDigestHex( + globalThis.crypto, + releaseRegistryId, + assets, + policy, + ), + }; +} diff --git a/tests/unit/public-response-cache-repair.test.ts b/tests/unit/public-response-cache-repair.test.ts new file mode 100644 index 0000000..1ad2757 --- /dev/null +++ b/tests/unit/public-response-cache-repair.test.ts @@ -0,0 +1,207 @@ +import { describe, expect, it } from "vitest"; + +import type { PublicCacheAsset } from "../../src/application/ports/browser-file-storage/cache-storage-ports.ts"; +import { createDefaultPublicCachePolicy } from "../../src/adapters/cache-storage/public-cache-policy.ts"; +import { createPublicResponseCacheAdapter } from "../../src/adapters/cache-storage/public-response-cache-adapter.ts"; +import { + MemoryCacheStorage, + digestHex, + immediateLock, + manifestFor, +} from "./public-response-cache-fixture.ts"; + +/** + * STO-RR-04 / STO-RR-05. A release cache that is currently serving traffic is + * the last thing a repair may destroy. A transient marker read failure is not + * evidence of damage, and a repair that has not yet fetched anything has not + * yet earned the right to delete what still works. + */ +describe("public response cache repair is failure-atomic", () => { + async function stagedRelease(releaseRegistryId: string) { + const policy = createDefaultPublicCachePolicy( + "https://assets.example.test", + ); + const firstBytes = new Uint8Array([1, 1, 1, 1]); + const secondBytes = new Uint8Array([2, 2, 2, 2]); + const assets: readonly PublicCacheAsset[] = [ + { + absoluteUrl: "https://assets.example.test/first.js", + expectedByteLength: firstBytes.byteLength, + expectedContentType: "application/javascript", + integrity: { + algorithm: "SHA-256", + digestHex: await digestHex(firstBytes), + }, + }, + { + absoluteUrl: "https://assets.example.test/second.js", + expectedByteLength: secondBytes.byteLength, + expectedContentType: "application/javascript", + integrity: { + algorithm: "SHA-256", + digestHex: await digestHex(secondBytes), + }, + }, + ]; + const bodies = new Map([ + [assets[0]!.absoluteUrl, firstBytes], + [assets[1]!.absoluteUrl, secondBytes], + ]); + const cacheStorage = new MemoryCacheStorage(); + const fetchLog: string[] = []; + let failFrom: string | null = null; + const adapter = createPublicResponseCacheAdapter({ + cacheStorage: cacheStorage as unknown as CacheStorage, + crypto: globalThis.crypto, + mutationLock: immediateLock, + policy, + fetcher: async (request: Request) => { + fetchLog.push(request.url); + if (failFrom !== null && request.url === failFrom) { + throw new TypeError("network is down"); + } + const body = bodies.get(request.url); + if (!body) throw new TypeError(`unknown asset ${request.url}`); + return new Response(Uint8Array.from(body), { + headers: { + "cache-control": "public", + "content-type": "application/javascript", + }, + }); + }, + }); + const manifest = await manifestFor(releaseRegistryId, assets, policy); + expect(await adapter.admin.stageRelease(manifest)).toMatchObject({ + ok: true, + }); + expect( + await adapter.admin.activateRelease( + manifest.releaseRegistryId, + manifest.manifestDigestHex, + ), + ).toMatchObject({ ok: true }); + const cacheName = [...cacheStorage.caches.keys()].find((name) => + name.includes(releaseRegistryId), + ); + if (!cacheName) throw new Error("staged cache missing"); + + return { + adapter, + assets, + cacheName, + cacheStorage, + fetchLog, + manifest, + setFailure(url: string | null) { + failFrom = url; + }, + }; + } + + it("does not delete an active candidate when the marker read fails transiently", async () => { + const release = await stagedRelease("transient-marker"); + const cache = release.cacheStorage.caches.get(release.cacheName)!; + const realMatch = cache.match.bind(cache); + let markerReads = 0; + const assetUrls = new Set(release.assets.map((asset) => asset.absoluteUrl)); + cache.match = async (request: RequestInfo | URL) => { + const url = + request instanceof Request ? request.url : String(request); + if (!assetUrls.has(url)) { + markerReads += 1; + throw new DOMException("Storage is busy", "InvalidStateError"); + } + return await realMatch(request); + }; + + const restaged = await release.adapter.admin.stageRelease(release.manifest); + + expect(markerReads).toBeGreaterThan(0); + expect(restaged.ok).toBe(false); + expect(release.cacheStorage.caches.has(release.cacheName)).toBe(true); + cache.match = realMatch; + expect( + await release.adapter.responses.matchActiveExact({ + absoluteUrl: release.assets[0]!.absoluteUrl, + }), + ).toMatchObject({ ok: true }); + }); + + it("keeps every healthy asset when one repair fetch fails", async () => { + const release = await stagedRelease("partial-repair"); + const cache = release.cacheStorage.caches.get(release.cacheName)!; + // Corrupt only the first asset's stored bytes. + const corrupted = cache.responses.findIndex( + (entry) => entry.request.url === release.assets[0]!.absoluteUrl, + ); + expect(corrupted).toBeGreaterThanOrEqual(0); + cache.responses.splice(corrupted, 1); + + release.setFailure(release.assets[0]!.absoluteUrl); + const restaged = await release.adapter.admin.stageRelease(release.manifest); + expect(restaged.ok).toBe(false); + + // The cache still exists and the healthy asset is still served. + expect(release.cacheStorage.caches.has(release.cacheName)).toBe(true); + expect( + await release.adapter.responses.matchActiveExact({ + absoluteUrl: release.assets[1]!.absoluteUrl, + }), + ).toMatchObject({ ok: true }); + }); + + it("still removes a candidate this call created when staging fails", async () => { + const policy = createDefaultPublicCachePolicy( + "https://assets.example.test", + ); + const bytes = new Uint8Array([7, 7, 7, 7]); + const asset: PublicCacheAsset = { + absoluteUrl: "https://assets.example.test/fresh.js", + expectedByteLength: bytes.byteLength, + expectedContentType: "application/javascript", + integrity: { + algorithm: "SHA-256", + digestHex: await digestHex(bytes), + }, + }; + const cacheStorage = new MemoryCacheStorage(); + const adapter = createPublicResponseCacheAdapter({ + cacheStorage: cacheStorage as unknown as CacheStorage, + crypto: globalThis.crypto, + mutationLock: immediateLock, + policy, + fetcher: async () => { + throw new TypeError("network is down"); + }, + }); + const manifest = await manifestFor("fresh-release", [asset], policy); + + expect(await adapter.admin.stageRelease(manifest)).toMatchObject({ + ok: false, + }); + expect(await cacheStorage.keys()).toEqual([]); + }); + + it("repairs an evicted asset in place and keeps the release usable", async () => { + const release = await stagedRelease("in-place-repair"); + const cache = release.cacheStorage.caches.get(release.cacheName)!; + const evicted = cache.responses.findIndex( + (entry) => entry.request.url === release.assets[1]!.absoluteUrl, + ); + cache.responses.splice(evicted, 1); + + expect( + await release.adapter.admin.stageRelease(release.manifest), + ).toMatchObject({ ok: true }); + expect( + await release.adapter.responses.matchActiveExact({ + absoluteUrl: release.assets[1]!.absoluteUrl, + }), + ).toMatchObject({ ok: true }); + expect( + await release.adapter.responses.matchActiveExact({ + absoluteUrl: release.assets[0]!.absoluteUrl, + }), + ).toMatchObject({ ok: true }); + }); +}); diff --git a/tests/unit/public-response-cache.test.ts b/tests/unit/public-response-cache.test.ts index 5f97fd1..d6e9456 100644 --- a/tests/unit/public-response-cache.test.ts +++ b/tests/unit/public-response-cache.test.ts @@ -10,135 +10,17 @@ import { type PublicCacheRuntimePolicy, } from "../../src/adapters/cache-storage/public-cache-policy.ts"; import { - computePublicCacheManifestDigestHex, createPublicResponseCacheAdapter, type PublicCacheMutationLock, } from "../../src/adapters/cache-storage/public-response-cache-adapter.ts"; -class MemoryCache { - readonly responses: Array> = []; - - async match(request: RequestInfo | URL): Promise { - const url = - request instanceof Request ? request.url : new URL(String(request)).href; - const nativeRequest = - request instanceof Request ? request : new Request(url); - return this.responses - .find( - (entry) => - entry.request.url === url && - varyMatches(entry.request, nativeRequest, entry.response), - ) - ?.response.clone(); - } - - async put(request: RequestInfo | URL, response: Response): Promise { - const url = - request instanceof Request ? request.url : new URL(String(request)).href; - const nativeRequest = - request instanceof Request ? request.clone() : new Request(url); - const existing = this.responses.findIndex( - (entry) => - entry.request.url === url && - varyMatches(entry.request, nativeRequest, response), - ); - const entry = { - request: nativeRequest, - response: response.clone(), - }; - if (existing >= 0) this.responses.splice(existing, 1, entry); - else this.responses.push(entry); - } -} - -function varyMatches( - storedRequest: Request, - incomingRequest: Request, - response: Response, -): boolean { - const vary = response.headers.get("vary"); - if (!vary) return true; - return vary - .split(",") - .map((name) => name.trim().toLowerCase()) - .every( - (name) => - storedRequest.headers.get(name) === - incomingRequest.headers.get(name), - ); -} - -class MemoryCacheStorage { - readonly caches = new Map(); - - async open(name: string): Promise { - let cache = this.caches.get(name); - if (!cache) { - cache = new MemoryCache(); - this.caches.set(name, cache); - } - return cache as unknown as Cache; - } - - async keys(): Promise { - return [...this.caches.keys()]; - } - - async delete(name: string): Promise { - return this.caches.delete(name); - } -} - -const immediateLock: PublicCacheMutationLock = { - async run(_signal, task) { - return await task(); - }, -}; - -function deferred() { - let settle: ((value: Value) => void) | undefined; - const promise = new Promise((resolve) => { - settle = resolve; - }); - return Object.freeze({ - promise, - resolve(value: Value): void { - settle?.(value); - }, - }); -} - -async function digestHex(bytes: Uint8Array): Promise { - const digest = await globalThis.crypto.subtle.digest( - "SHA-256", - Uint8Array.from(bytes), - ); - return [...new Uint8Array(digest)] - .map((byte) => byte.toString(16).padStart(2, "0")) - .join(""); -} - -async function manifestFor( - releaseRegistryId: string, - assets: readonly PublicCacheAsset[], - policy: PublicCacheRuntimePolicy = createDefaultPublicCachePolicy( - "https://assets.example.test", - ), -): Promise { - return { - releaseRegistryId, - assets, - manifestDigestHex: await computePublicCacheManifestDigestHex( - globalThis.crypto, - releaseRegistryId, - assets, - policy, - ), - }; -} +import { + MemoryCacheStorage, + deferred, + digestHex, + immediateLock, + manifestFor, +} from "./public-response-cache-fixture.ts"; describe("public response Cache Storage adapter", () => { it("rejects a policy that enables variants but strips Vary", () => { @@ -1513,199 +1395,3 @@ describe("public response Cache Storage adapter", () => { expect(await cacheStorage.keys()).toEqual([]); }); }); - -/** - * STO-RR-04 / STO-RR-05. A release cache that is currently serving traffic is - * the last thing a repair may destroy. A transient marker read failure is not - * evidence of damage, and a repair that has not yet fetched anything has not - * yet earned the right to delete what still works. - */ -describe("public response cache repair is failure-atomic", () => { - async function stagedRelease(releaseRegistryId: string) { - const policy = createDefaultPublicCachePolicy( - "https://assets.example.test", - ); - const firstBytes = new Uint8Array([1, 1, 1, 1]); - const secondBytes = new Uint8Array([2, 2, 2, 2]); - const assets: readonly PublicCacheAsset[] = [ - { - absoluteUrl: "https://assets.example.test/first.js", - expectedByteLength: firstBytes.byteLength, - expectedContentType: "application/javascript", - integrity: { - algorithm: "SHA-256", - digestHex: await digestHex(firstBytes), - }, - }, - { - absoluteUrl: "https://assets.example.test/second.js", - expectedByteLength: secondBytes.byteLength, - expectedContentType: "application/javascript", - integrity: { - algorithm: "SHA-256", - digestHex: await digestHex(secondBytes), - }, - }, - ]; - const bodies = new Map([ - [assets[0]!.absoluteUrl, firstBytes], - [assets[1]!.absoluteUrl, secondBytes], - ]); - const cacheStorage = new MemoryCacheStorage(); - const fetchLog: string[] = []; - let failFrom: string | null = null; - const adapter = createPublicResponseCacheAdapter({ - cacheStorage: cacheStorage as unknown as CacheStorage, - crypto: globalThis.crypto, - mutationLock: immediateLock, - policy, - fetcher: async (request: Request) => { - fetchLog.push(request.url); - if (failFrom !== null && request.url === failFrom) { - throw new TypeError("network is down"); - } - const body = bodies.get(request.url); - if (!body) throw new TypeError(`unknown asset ${request.url}`); - return new Response(Uint8Array.from(body), { - headers: { - "cache-control": "public", - "content-type": "application/javascript", - }, - }); - }, - }); - const manifest = await manifestFor(releaseRegistryId, assets, policy); - expect(await adapter.admin.stageRelease(manifest)).toMatchObject({ - ok: true, - }); - expect( - await adapter.admin.activateRelease( - manifest.releaseRegistryId, - manifest.manifestDigestHex, - ), - ).toMatchObject({ ok: true }); - const cacheName = [...cacheStorage.caches.keys()].find((name) => - name.includes(releaseRegistryId), - ); - if (!cacheName) throw new Error("staged cache missing"); - - return { - adapter, - assets, - cacheName, - cacheStorage, - fetchLog, - manifest, - setFailure(url: string | null) { - failFrom = url; - }, - }; - } - - it("does not delete an active candidate when the marker read fails transiently", async () => { - const release = await stagedRelease("transient-marker"); - const cache = release.cacheStorage.caches.get(release.cacheName)!; - const realMatch = cache.match.bind(cache); - let markerReads = 0; - const assetUrls = new Set(release.assets.map((asset) => asset.absoluteUrl)); - cache.match = async (request: RequestInfo | URL) => { - const url = - request instanceof Request ? request.url : String(request); - if (!assetUrls.has(url)) { - markerReads += 1; - throw new DOMException("Storage is busy", "InvalidStateError"); - } - return await realMatch(request); - }; - - const restaged = await release.adapter.admin.stageRelease(release.manifest); - - expect(markerReads).toBeGreaterThan(0); - expect(restaged.ok).toBe(false); - expect(release.cacheStorage.caches.has(release.cacheName)).toBe(true); - cache.match = realMatch; - expect( - await release.adapter.responses.matchActiveExact({ - absoluteUrl: release.assets[0]!.absoluteUrl, - }), - ).toMatchObject({ ok: true }); - }); - - it("keeps every healthy asset when one repair fetch fails", async () => { - const release = await stagedRelease("partial-repair"); - const cache = release.cacheStorage.caches.get(release.cacheName)!; - // Corrupt only the first asset's stored bytes. - const corrupted = cache.responses.findIndex( - (entry) => entry.request.url === release.assets[0]!.absoluteUrl, - ); - expect(corrupted).toBeGreaterThanOrEqual(0); - cache.responses.splice(corrupted, 1); - - release.setFailure(release.assets[0]!.absoluteUrl); - const restaged = await release.adapter.admin.stageRelease(release.manifest); - expect(restaged.ok).toBe(false); - - // The cache still exists and the healthy asset is still served. - expect(release.cacheStorage.caches.has(release.cacheName)).toBe(true); - expect( - await release.adapter.responses.matchActiveExact({ - absoluteUrl: release.assets[1]!.absoluteUrl, - }), - ).toMatchObject({ ok: true }); - }); - - it("still removes a candidate this call created when staging fails", async () => { - const policy = createDefaultPublicCachePolicy( - "https://assets.example.test", - ); - const bytes = new Uint8Array([7, 7, 7, 7]); - const asset: PublicCacheAsset = { - absoluteUrl: "https://assets.example.test/fresh.js", - expectedByteLength: bytes.byteLength, - expectedContentType: "application/javascript", - integrity: { - algorithm: "SHA-256", - digestHex: await digestHex(bytes), - }, - }; - const cacheStorage = new MemoryCacheStorage(); - const adapter = createPublicResponseCacheAdapter({ - cacheStorage: cacheStorage as unknown as CacheStorage, - crypto: globalThis.crypto, - mutationLock: immediateLock, - policy, - fetcher: async () => { - throw new TypeError("network is down"); - }, - }); - const manifest = await manifestFor("fresh-release", [asset], policy); - - expect(await adapter.admin.stageRelease(manifest)).toMatchObject({ - ok: false, - }); - expect(await cacheStorage.keys()).toEqual([]); - }); - - it("repairs an evicted asset in place and keeps the release usable", async () => { - const release = await stagedRelease("in-place-repair"); - const cache = release.cacheStorage.caches.get(release.cacheName)!; - const evicted = cache.responses.findIndex( - (entry) => entry.request.url === release.assets[1]!.absoluteUrl, - ); - cache.responses.splice(evicted, 1); - - expect( - await release.adapter.admin.stageRelease(release.manifest), - ).toMatchObject({ ok: true }); - expect( - await release.adapter.responses.matchActiveExact({ - absoluteUrl: release.assets[1]!.absoluteUrl, - }), - ).toMatchObject({ ok: true }); - expect( - await release.adapter.responses.matchActiveExact({ - absoluteUrl: release.assets[0]!.absoluteUrl, - }), - ).toMatchObject({ ok: true }); - }); -}); diff --git a/tests/unit/resumable-upload-checkpoint.test.ts b/tests/unit/resumable-upload-checkpoint.test.ts index 1034a49..88aca0b 100644 --- a/tests/unit/resumable-upload-checkpoint.test.ts +++ b/tests/unit/resumable-upload-checkpoint.test.ts @@ -80,6 +80,155 @@ function deletingFactory( } as IDBFactory; } +/** + * A database the test drives by hand. The memory fake commits or aborts on its + * own, so the three places the checkpoint store deliberately disagrees with the + * other IndexedDB adapters — a commit that produced no value, a request error + * that must abort, and an `abort()` that throws — are only observable here. + * + * The scope-binding transaction is driven automatically because no test below + * is about it; only checkpoint transactions are handed to the test. + */ +type ScriptedRequest = { + result: unknown; + error: DOMException | null; + onsuccess: ((event: Event) => unknown) | null; + onerror: ((event: Event) => unknown) | null; +}; + +type ScriptedTransaction = { + abortCalls: number; + error: DOMException | null; + oncomplete: ((event: Event) => unknown) | null; + onerror: ((event: Event) => unknown) | null; + onabort: ((event: Event) => unknown) | null; + readonly requests: ScriptedRequest[]; + objectStore(name: string): IDBObjectStore; + abort(): void; + complete(): void; +}; + +function scriptedFactory( + options: Readonly<{ abortThrows?: boolean }> = {}, +): Readonly<{ + factory: IDBFactory; + /** One entry per `database.transaction(...)` call, holding its argument count. */ + transactionArguments: number[]; + checkpoints: ScriptedTransaction[]; +}> { + const transactionArguments: number[] = []; + const checkpoints: ScriptedTransaction[] = []; + + const scriptedRequest = (): ScriptedRequest => ({ + result: undefined, + error: null, + onsuccess: null, + onerror: null, + }); + + const makeTransaction = (): ScriptedTransaction => { + const requests: ScriptedRequest[] = []; + const transaction: ScriptedTransaction = { + abortCalls: 0, + error: null, + oncomplete: null, + onerror: null, + onabort: null, + requests, + objectStore: () => { + const queue = () => { + const request = scriptedRequest(); + requests.push(request); + return request as unknown as IDBRequest; + }; + return { + get: queue, + add: queue, + put: queue, + delete: queue, + } as unknown as IDBObjectStore; + }, + abort() { + transaction.abortCalls += 1; + if (options.abortThrows === true) { + throw new DOMException("Transaction is finished.", "InvalidStateError"); + } + transaction.error = new DOMException("Transaction aborted.", "AbortError"); + transaction.onerror?.(new Event("error")); + transaction.onabort?.(new Event("abort")); + }, + complete() { + transaction.oncomplete?.(new Event("complete")); + }, + }; + return transaction; + }; + + const database = { + close() {}, + transaction: (...args: unknown[]) => { + transactionArguments.push(args.length); + const requested = args[0]; + const names = + typeof requested === "string" + ? [requested] + : [...(requested as Iterable)]; + const transaction = makeTransaction(); + if (names.includes("governance")) { + queueMicrotask(() => { + transaction.requests[0]?.onsuccess?.(new Event("success")); + queueMicrotask(() => { + transaction.requests[1]?.onsuccess?.(new Event("success")); + queueMicrotask(() => { + transaction.complete(); + }); + }); + }); + } else { + checkpoints.push(transaction); + } + return transaction as unknown as IDBTransaction; + }, + } as unknown as IDBDatabase; + + const factory = { + open: () => { + const request = { + result: database, + error: null, + transaction: null, + onsuccess: null, + onerror: null, + onblocked: null, + onupgradeneeded: null, + } as unknown as IDBOpenDBRequest; + queueMicrotask(() => request.onsuccess?.(new Event("success"))); + return request; + }, + cmp: () => 0, + databases: async () => [], + } as unknown as IDBFactory; + + return { factory, transactionArguments, checkpoints }; +} + +async function flushTasks(): Promise { + for (let tick = 0; tick < 5; tick += 1) { + await new Promise((resolve) => { + setTimeout(resolve, 0); + }); + } +} + +async function openedCheckpointTransaction( + scripted: ReturnType, +): Promise { + await flushTasks(); + const transaction = scripted.checkpoints[0]; + if (!transaction) throw new Error("no checkpoint transaction was opened"); + return transaction; +} + describe("IndexedDB resumable upload checkpoint", () => { it("length-prefixes scope tuples so delimiter placement cannot collide", () => { const first = uploadCheckpointDatabaseName({ @@ -262,4 +411,112 @@ describe("IndexedDB resumable upload checkpoint", () => { error: { code: "ABORTED" }, }); }); + + // CP-1. Three IndexedDB adapters report a value-less commit as UNAVAILABLE; + // this one reports CORRUPT_DATA/RECONCILE because a checkpoint read that + // committed while producing nothing means the stored row could not be turned + // into a checkpoint, and the caller has to reconcile rather than retry. + it("reports a checkpoint commit that produced no value as CORRUPT_DATA", async () => { + const scripted = scriptedFactory(); + const store = createIndexedDbResumableUploadCheckpointStore({ + scope, + factory: scripted.factory, + }); + const pending = store.read("upload_key_01"); + const transaction = await openedCheckpointTransaction(scripted); + + transaction.complete(); + + expect(await pending).toMatchObject({ + ok: false, + error: { + code: "CORRUPT_DATA", + operation: "UPLOAD_RECONCILE", + recovery: "RECONCILE", + }, + }); + }); + + // CP-2. A third argument would be a `{durability}` options bag. An engine + // that has never seen the bag treats it differently from no bag at all, so + // checkpoint writes stay on whatever the engine defaults to. + it("opens checkpoint transactions without a durability options bag", async () => { + const scripted = scriptedFactory(); + const store = createIndexedDbResumableUploadCheckpointStore({ + scope, + factory: scripted.factory, + }); + const pending = store.read("upload_key_01"); + const transaction = await openedCheckpointTransaction(scripted); + transaction.complete(); + await pending; + + expect(scripted.transactionArguments).toEqual([2, 2]); + }); + + // CP-3. Recording the error and letting the transaction run on would let + // `compareAndSwap`'s put commit after its get had already failed. + it("aborts the checkpoint transaction as soon as a request fails", async () => { + const scripted = scriptedFactory(); + const store = createIndexedDbResumableUploadCheckpointStore({ + scope, + factory: scripted.factory, + }); + const pending = store.read("upload_key_01"); + const transaction = await openedCheckpointTransaction(scripted); + const read = transaction.requests[0]; + if (!read) throw new Error("the checkpoint read queued no request"); + + read.error = new DOMException("disk is unreadable", "NotReadableError"); + read.onerror?.(new Event("error")); + + expect(transaction.abortCalls).toBe(1); + expect(await pending).toMatchObject({ + ok: false, + error: { code: "NOT_READABLE", retryable: true, recovery: "REOPEN" }, + }); + }); + + // CP-4. The transaction can already be durably committed while its completion + // event is still queued, which is when `abort()` throws. Claiming the abort + // would report a committed checkpoint as ABORTED. + it("keeps a committed checkpoint when the abort call itself throws", async () => { + const scripted = scriptedFactory({ abortThrows: true }); + const store = createIndexedDbResumableUploadCheckpointStore({ + scope, + factory: scripted.factory, + }); + const controller = new AbortController(); + const stored = checkpoint(1); + const pending = store.read(stored.uploadKey, controller.signal); + const transaction = await openedCheckpointTransaction(scripted); + const read = transaction.requests[0]; + if (!read) throw new Error("the checkpoint read queued no request"); + + read.result = stored; + read.onsuccess?.(new Event("success")); + controller.abort(); + expect(transaction.abortCalls).toBe(1); + transaction.complete(); + + expect(await pending).toEqual({ ok: true, value: stored }); + }); + + // CP-5. The blocked deadline is the only bound on an open that another + // context is holding up, so it has to fire from the scheduler the store was + // built with rather than leave the read pending forever. + it("bounds a blocked open with the configured deadline", async () => { + const memory = new MemoryIndexedDbFactory(); + const store = createIndexedDbResumableUploadCheckpointStore({ + scope, + factory: memory.factory, + blockedTimeoutMs: 1, + }); + memory.blockNextOpen(); + + expect(await store.read("upload_key_01")).toMatchObject({ + ok: false, + error: { code: "BLOCKED", retryable: true, recovery: "RESUME" }, + }); + }); }); diff --git a/tests/unit/resumable-upload-runtime-fixture.ts b/tests/unit/resumable-upload-runtime-fixture.ts new file mode 100644 index 0000000..79e84b7 --- /dev/null +++ b/tests/unit/resumable-upload-runtime-fixture.ts @@ -0,0 +1,341 @@ +import { vi } from "vitest"; + +import type { + ResumableUploadCheckpoint, + ResumableUploadCheckpointStore, + ResumableUploadControlPlane, + ResumableUploadSource, + UploadPartExecutor, + UploadPartReceipt, + UploadProviderResult, + UploadSession, +} from "../../src/application/ports/browser-transfer/resumable-upload.ts"; +import { RESUMABLE_UPLOAD_PROTOCOL } from "../../src/application/ports/browser-transfer/resumable-upload.ts"; +import type { + BrowserDataResult, +} from "../../src/application/ports/browser-file-storage/shared.ts"; +import { + browserDataFailure, + browserDataSuccess, +} from "../../src/adapters/browser-file-storage/result.ts"; +import { resolveResumableUploadRuntimePolicy } from "../../src/adapters/browser-transfer/resumable-upload/runtime-policy.ts"; +import type { + UploadCancellationChannel, + UploadCancellationListener, +} from "../../src/adapters/browser-transfer/resumable-upload/upload-cancellation-channel.ts"; +import type { UploadMutationLock } from "../../src/adapters/browser-transfer/resumable-upload/upload-mutation-lock.ts"; + +export type TestCapability = Readonly<{ id: string }>; + +export const activeSignal = new AbortController().signal; +export const noContentionLock: UploadMutationLock = Object.freeze({ + async run( + _uploadKey: string, + _signal: AbortSignal, + task: () => Promise, + ): Promise { + return await task(); + }, +}); + +export function createSerialMutationLock(): UploadMutationLock { + let tail = Promise.resolve(); + return Object.freeze({ + run( + _uploadKey: string, + signal: AbortSignal, + task: () => Promise, + ): Promise { + const result = tail.then(async () => { + if (signal.aborted) { + throw new DOMException( + "The operation was aborted.", + "AbortError", + ); + } + return await task(); + }); + tail = result.then( + () => undefined, + () => undefined, + ); + return result; + }, + }); +} + +export function createMemoryCancellationPair(): readonly [ + UploadCancellationChannel, + UploadCancellationChannel, +] { + const listeners = [ + new Set(), + new Set(), + ] as const; + const channels = listeners.map((ownListeners, ownIndex) => { + let closed = false; + return Object.freeze({ + publish(uploadKey: string) { + if (closed) return false; + for (const [index, peerListeners] of listeners.entries()) { + if (index === ownIndex) continue; + for (const listener of [...peerListeners]) { + listener(uploadKey); + } + } + return true; + }, + subscribe(listener: UploadCancellationListener) { + if (closed) throw new TypeError("closed"); + ownListeners.add(listener); + return () => ownListeners.delete(listener); + }, + close() { + closed = true; + ownListeners.clear(); + }, + }); + }); + return channels as unknown as readonly [ + UploadCancellationChannel, + UploadCancellationChannel, + ]; +} + +export class MemoryCheckpointStore implements ResumableUploadCheckpointStore { + readonly rows = new Map(); + closed = false; + + async read( + uploadKey: string, + ): Promise> { + return browserDataSuccess( + structuredClone(this.rows.get(uploadKey) ?? null), + ); + } + + async compareAndSwap( + input: Parameters< + ResumableUploadCheckpointStore["compareAndSwap"] + >[0], + ): Promise> { + const current = this.rows.get(input.checkpoint.uploadKey); + if ( + (input.expectedRevision === null && current) || + (input.expectedRevision !== null && + current?.revision !== input.expectedRevision) + ) { + return browserDataFailure("CONFLICT", "UPLOAD_RECONCILE", { + recovery: "RECONCILE", + }); + } + const snapshot = structuredClone(input.checkpoint); + this.rows.set(snapshot.uploadKey, snapshot); + return browserDataSuccess(snapshot); + } + + async remove( + input: Parameters[0], + ): Promise> { + const current = this.rows.get(input.uploadKey); + if (current?.revision !== input.expectedRevision) { + return browserDataFailure("CONFLICT", "UPLOAD_RECONCILE", { + recovery: "RECONCILE", + }); + } + this.rows.delete(input.uploadKey); + return browserDataSuccess(undefined); + } + + close(): void { + this.closed = true; + } +} + +export function rangeSource(bytes: Uint8Array): ResumableUploadSource { + return Object.freeze({ + kind: "RANGE_READER" as const, + reader: Object.freeze({ + byteLength: bytes.byteLength, + async readRange(input: Readonly<{ + offset: number; + length: number; + signal: AbortSignal; + }>) { + if (input.signal.aborted) { + return browserDataFailure("ABORTED", "FILE_READ"); + } + return browserDataSuccess( + bytes.slice(input.offset, input.offset + input.length), + ); + }, + }), + }); +} + +export function byteStreamSource(bytes: Uint8Array): ResumableUploadSource { + return Object.freeze({ + kind: "FILE_BYTE_SOURCE" as const, + bytes: Object.freeze({ + byteLength: bytes.byteLength, + async *stream(signal: AbortSignal) { + if (signal.aborted) { + yield browserDataFailure("ABORTED", "FILE_READ"); + return; + } + yield browserDataSuccess(bytes.slice(0, 3)); + yield browserDataSuccess(bytes.slice(3)); + }, + }), + }); +} + +export function runtimePolicy( + overrides: Partial< + Parameters[0] + > = {}, +) { + return { + partSizeBytes: 4, + maxFileBytes: 100, + maxPartCount: 25, + maxConcurrency: 3, + maxInFlightBytes: 48, + partBufferCopyFactor: 4, + maxSourceChunkBytes: 8, + maxRetries: 2, + retryBaseDelayMs: 1, + retryMaxDelayMs: 10, + maxRetryAfterMs: 100, + capabilityRefreshSkewMs: 5, + maxSessionLifetimeMs: 10_000, + providerAttemptTimeoutMs: 100, + ...overrides, + }; +} + +export type ControlHarness = Readonly<{ + control: ResumableUploadControlPlane; + accepted: Map; + issued: ReturnType; + completedParts: UploadPartReceipt[][]; + getSession(): UploadSession | null; +}>; + +export function createControlHarness(options: Readonly<{ + now?: number; + serverMaxConcurrency?: number; + sessionId?: (createIndex: number) => string; + statusParts?: ( + session: UploadSession, + accepted: Map, + ) => readonly UploadPartReceipt[]; + issueCapability?: ( + input: Parameters< + ResumableUploadControlPlane["issuePartCapability"] + >[0], + callIndex: number, + ) => UploadProviderResult>; +}> = {}): ControlHarness { + const now = options.now ?? 1_000; + const accepted = new Map(); + const completedParts: UploadPartReceipt[][] = []; + let session: UploadSession | null = null; + let createCount = 0; + let issueCount = 0; + const issued = vi.fn(); + const control: ResumableUploadControlPlane = { + async createSession(input) { + createCount += 1; + session = Object.freeze({ + protocol: RESUMABLE_UPLOAD_PROTOCOL, + sessionId: + options.sessionId?.(createCount) ?? "session_01", + requestBindingSha256: input.requestBindingSha256, + fingerprint: input.fingerprint, + partSizeBytes: input.requestedPartSizeBytes, + partCount: input.fingerprint.partCount, + maxConcurrency: options.serverMaxConcurrency ?? 2, + expiresAtEpochMs: now + 5_000, + }); + return browserDataSuccess(session); + }, + async getStatus() { + if (!session) { + return browserDataFailure("NOT_FOUND", "UPLOAD_RECONCILE"); + } + const parts = + options.statusParts?.(session, accepted) ?? + [...accepted.values()].sort( + (left, right) => left.partNumber - right.partNumber, + ); + return browserDataSuccess({ + state: "ACTIVE", + session, + acceptedParts: parts, + }); + }, + async issuePartCapability(input) { + issueCount += 1; + issued(input); + return ( + options.issueCapability?.(input, issueCount) ?? + browserDataSuccess({ + capability: Object.freeze({ id: `cap-${issueCount}` }), + uploadBindingSha256: input.uploadBindingSha256, + expiresAtEpochMs: now + 4_000, + }) + ); + }, + async complete(input) { + completedParts.push([...input.orderedParts]); + return browserDataSuccess({ + state: "QUARANTINED", + protocol: RESUMABLE_UPLOAD_PROTOCOL, + sessionId: input.sessionId, + requestBindingSha256: input.requestBindingSha256, + fingerprint: input.fingerprint, + resourceId: "resource_01", + }); + }, + async abort() { + return browserDataSuccess({ state: "ABORTED" }); + }, + }; + return { + control, + accepted, + issued, + completedParts, + getSession: () => session, + }; +} + +export function executorFor( + harness: ControlHarness, + options: Readonly<{ + delay?: () => Promise; + onActive?: (active: number) => void; + }> = {}, +): UploadPartExecutor { + let active = 0; + return { + async uploadPart(input) { + active += 1; + options.onActive?.(active); + await options.delay?.(); + active -= 1; + const receipt = Object.freeze({ + ...input.part, + receiptToken: `etag-part-${input.part.partNumber}`, + }); + harness.accepted.set(input.part.partNumber, receipt); + return browserDataSuccess(receipt); + }, + }; +} + diff --git a/tests/unit/resumable-upload-runtime-teardown.test.ts b/tests/unit/resumable-upload-runtime-teardown.test.ts new file mode 100644 index 0000000..d15b5c7 --- /dev/null +++ b/tests/unit/resumable-upload-runtime-teardown.test.ts @@ -0,0 +1,188 @@ +import { describe, expect, it, vi } from "vitest"; + +import { browserDataFailure } from "../../src/adapters/browser-file-storage/result.ts"; +import { createResumableUploadRuntime } from "../../src/adapters/browser-transfer/resumable-upload/resumable-upload-runtime.ts"; +import { + activeSignal, + byteStreamSource, + createControlHarness, + executorFor, + MemoryCheckpointStore, + noContentionLock, + runtimePolicy, +} from "./resumable-upload-runtime-fixture.ts"; + +/** + * TR-RR-06. A non-cooperative mutation lock or provider must not make teardown + * unbounded: `dispose()` bounds its drain and reports honestly when the runtime + * is still CLOSING, and an abort is admitted physical work it cannot step over. + */ +describe("TR-RR-06 bounded resumable teardown", () => { + it("reports an unproved drain instead of waiting forever", async () => { + const checkpoints = new MemoryCheckpointStore(); + const harness = createControlHarness(); + const runtime = createResumableUploadRuntime({ + controlPlane: harness.control, + partExecutor: executorFor(harness, { delay: async () => {} }), + checkpoints, + // A lock that never grants: dispose must still be bounded. + mutationLock: Object.freeze({ + async run(): Promise { + return await new Promise(() => {}); + }, + }), + crypto, + policy: runtimePolicy({ cleanupDeadlineMs: 20 }), + now: () => 1_000, + random: () => 0, + sleep: async () => {}, + }); + + void runtime.upload({ + uploadKey: "upload_key_hung", + purpose: "attachment", + mediaType: "application/octet-stream", + source: byteStreamSource(new Uint8Array([1, 2, 3, 4, 5])), + signal: activeSignal, + }); + await Promise.resolve(); + await Promise.resolve(); + + const disposed = await runtime.dispose(); + expect(disposed.ok).toBe(false); + // Still CLOSING: physical work the caller must not treat as finished. + expect(runtime.lifecycle()).toBe("CLOSING"); + expect(checkpoints.closed).toBe(false); + }); + + it("closes once every admitted operation settles", async () => { + const checkpoints = new MemoryCheckpointStore(); + const harness = createControlHarness(); + const runtime = createResumableUploadRuntime({ + controlPlane: harness.control, + partExecutor: executorFor(harness, { delay: async () => {} }), + checkpoints, + mutationLock: noContentionLock, + crypto, + policy: runtimePolicy({ cleanupDeadlineMs: 200 }), + now: () => 1_000, + random: () => 0, + sleep: async () => {}, + }); + const disposed = await runtime.dispose(); + expect(disposed).toMatchObject({ ok: true }); + expect(runtime.lifecycle()).toBe("CLOSED"); + expect(checkpoints.closed).toBe(true); + }); +}); + +/** + * TR-04. `dispose()` proved quiescence from the wrapper registry only. A + * provider that ignored its attempt deadline let the wrapper settle first and + * leave the set empty, so teardown reported a drained runtime — and closed the + * checkpoint store — while the provider was still running. + */ +describe("TR-04 teardown waits for raw provider work, not only its wrapper", () => { + it("refuses to report a drained runtime while a provider is still running", async () => { + const harness = createControlHarness(); + const checkpoints = new MemoryCheckpointStore(); + const closeStore = vi.spyOn(checkpoints, "close"); + let releaseProvider: (() => void) | undefined; + // Ignores the attempt signal entirely and outlives its own deadline. + harness.control.createSession = () => + new Promise((resolve) => { + releaseProvider = () => + resolve( + browserDataFailure("UNAVAILABLE", "UPLOAD_SESSION", { + retryable: true, + recovery: "RESUME", + }), + ); + }); + + const runtime = createResumableUploadRuntime({ + controlPlane: harness.control, + partExecutor: executorFor(harness), + checkpoints, + mutationLock: noContentionLock, + crypto, + policy: runtimePolicy({ + providerAttemptTimeoutMs: 5, + cleanupDeadlineMs: 25, + maxRetries: 0, + }), + now: () => 1_000, + random: () => 0, + sleep: async () => {}, + }); + + const uploading = runtime.upload({ + uploadKey: "upload_key_raw", + purpose: "attachment", + mediaType: "application/octet-stream", + source: byteStreamSource(new Uint8Array([1, 2, 3, 4, 5])), + signal: activeSignal, + }); + await vi.waitFor(() => expect(releaseProvider).toBeDefined()); + // The wrapper has already given up on the attempt. + await uploading; + + const disposed = await runtime.dispose(); + expect(disposed.ok).toBe(false); + if (!disposed.ok) { + expect(disposed.error.code).toBe("UNAVAILABLE"); + expect(disposed.error.recovery).toBe("RESUME"); + } + // The store stays open while something could still write a checkpoint. + expect(closeStore).not.toHaveBeenCalled(); + + releaseProvider?.(); + }); + + it("reports a drained runtime once the raw provider settles", async () => { + const harness = createControlHarness(); + const checkpoints = new MemoryCheckpointStore(); + let releaseProvider: (() => void) | undefined; + harness.control.createSession = () => + new Promise((resolve) => { + releaseProvider = () => + resolve( + browserDataFailure("UNAVAILABLE", "UPLOAD_SESSION", { + retryable: true, + recovery: "RESUME", + }), + ); + }); + + const runtime = createResumableUploadRuntime({ + controlPlane: harness.control, + partExecutor: executorFor(harness), + checkpoints, + mutationLock: noContentionLock, + crypto, + policy: runtimePolicy({ + providerAttemptTimeoutMs: 5, + cleanupDeadlineMs: 1_000, + maxRetries: 0, + }), + now: () => 1_000, + random: () => 0, + sleep: async () => {}, + }); + + const uploading = runtime.upload({ + uploadKey: "upload_key_raw_2", + purpose: "attachment", + mediaType: "application/octet-stream", + source: byteStreamSource(new Uint8Array([1, 2, 3, 4, 5])), + signal: activeSignal, + }); + await vi.waitFor(() => expect(releaseProvider).toBeDefined()); + await uploading; + + const disposing = runtime.dispose(); + releaseProvider?.(); + await expect(disposing).resolves.toMatchObject({ ok: true }); + expect(runtime.lifecycle()).toBe("CLOSED"); + }); +}); diff --git a/tests/unit/resumable-upload-runtime.test.ts b/tests/unit/resumable-upload-runtime.test.ts index bf4e015..9a5f5c4 100644 --- a/tests/unit/resumable-upload-runtime.test.ts +++ b/tests/unit/resumable-upload-runtime.test.ts @@ -32,319 +32,19 @@ import type { } from "../../src/adapters/browser-transfer/resumable-upload/upload-cancellation-channel.ts"; import type { UploadMutationLock } from "../../src/adapters/browser-transfer/resumable-upload/upload-mutation-lock.ts"; -type TestCapability = Readonly<{ id: string }>; - -const activeSignal = new AbortController().signal; -const noContentionLock: UploadMutationLock = Object.freeze({ - async run( - _uploadKey: string, - _signal: AbortSignal, - task: () => Promise, - ): Promise { - return await task(); - }, -}); - -function createSerialMutationLock(): UploadMutationLock { - let tail = Promise.resolve(); - return Object.freeze({ - run( - _uploadKey: string, - signal: AbortSignal, - task: () => Promise, - ): Promise { - const result = tail.then(async () => { - if (signal.aborted) { - throw new DOMException( - "The operation was aborted.", - "AbortError", - ); - } - return await task(); - }); - tail = result.then( - () => undefined, - () => undefined, - ); - return result; - }, - }); -} - -function createMemoryCancellationPair(): readonly [ - UploadCancellationChannel, - UploadCancellationChannel, -] { - const listeners = [ - new Set(), - new Set(), - ] as const; - const channels = listeners.map((ownListeners, ownIndex) => { - let closed = false; - return Object.freeze({ - publish(uploadKey: string) { - if (closed) return false; - for (const [index, peerListeners] of listeners.entries()) { - if (index === ownIndex) continue; - for (const listener of [...peerListeners]) { - listener(uploadKey); - } - } - return true; - }, - subscribe(listener: UploadCancellationListener) { - if (closed) throw new TypeError("closed"); - ownListeners.add(listener); - return () => ownListeners.delete(listener); - }, - close() { - closed = true; - ownListeners.clear(); - }, - }); - }); - return channels as unknown as readonly [ - UploadCancellationChannel, - UploadCancellationChannel, - ]; -} - -class MemoryCheckpointStore implements ResumableUploadCheckpointStore { - readonly rows = new Map(); - closed = false; - - async read( - uploadKey: string, - ): Promise> { - return browserDataSuccess( - structuredClone(this.rows.get(uploadKey) ?? null), - ); - } - - async compareAndSwap( - input: Parameters< - ResumableUploadCheckpointStore["compareAndSwap"] - >[0], - ): Promise> { - const current = this.rows.get(input.checkpoint.uploadKey); - if ( - (input.expectedRevision === null && current) || - (input.expectedRevision !== null && - current?.revision !== input.expectedRevision) - ) { - return browserDataFailure("CONFLICT", "UPLOAD_RECONCILE", { - recovery: "RECONCILE", - }); - } - const snapshot = structuredClone(input.checkpoint); - this.rows.set(snapshot.uploadKey, snapshot); - return browserDataSuccess(snapshot); - } - - async remove( - input: Parameters[0], - ): Promise> { - const current = this.rows.get(input.uploadKey); - if (current?.revision !== input.expectedRevision) { - return browserDataFailure("CONFLICT", "UPLOAD_RECONCILE", { - recovery: "RECONCILE", - }); - } - this.rows.delete(input.uploadKey); - return browserDataSuccess(undefined); - } - - close(): void { - this.closed = true; - } -} - -function rangeSource(bytes: Uint8Array): ResumableUploadSource { - return Object.freeze({ - kind: "RANGE_READER" as const, - reader: Object.freeze({ - byteLength: bytes.byteLength, - async readRange(input: Readonly<{ - offset: number; - length: number; - signal: AbortSignal; - }>) { - if (input.signal.aborted) { - return browserDataFailure("ABORTED", "FILE_READ"); - } - return browserDataSuccess( - bytes.slice(input.offset, input.offset + input.length), - ); - }, - }), - }); -} - -function byteStreamSource(bytes: Uint8Array): ResumableUploadSource { - return Object.freeze({ - kind: "FILE_BYTE_SOURCE" as const, - bytes: Object.freeze({ - byteLength: bytes.byteLength, - async *stream(signal: AbortSignal) { - if (signal.aborted) { - yield browserDataFailure("ABORTED", "FILE_READ"); - return; - } - yield browserDataSuccess(bytes.slice(0, 3)); - yield browserDataSuccess(bytes.slice(3)); - }, - }), - }); -} - -function runtimePolicy( - overrides: Partial< - Parameters[0] - > = {}, -) { - return { - partSizeBytes: 4, - maxFileBytes: 100, - maxPartCount: 25, - maxConcurrency: 3, - maxInFlightBytes: 48, - partBufferCopyFactor: 4, - maxSourceChunkBytes: 8, - maxRetries: 2, - retryBaseDelayMs: 1, - retryMaxDelayMs: 10, - maxRetryAfterMs: 100, - capabilityRefreshSkewMs: 5, - maxSessionLifetimeMs: 10_000, - providerAttemptTimeoutMs: 100, - ...overrides, - }; -} - -type ControlHarness = Readonly<{ - control: ResumableUploadControlPlane; - accepted: Map; - issued: ReturnType; - completedParts: UploadPartReceipt[][]; - getSession(): UploadSession | null; -}>; - -function createControlHarness(options: Readonly<{ - now?: number; - serverMaxConcurrency?: number; - sessionId?: (createIndex: number) => string; - statusParts?: ( - session: UploadSession, - accepted: Map, - ) => readonly UploadPartReceipt[]; - issueCapability?: ( - input: Parameters< - ResumableUploadControlPlane["issuePartCapability"] - >[0], - callIndex: number, - ) => UploadProviderResult>; -}> = {}): ControlHarness { - const now = options.now ?? 1_000; - const accepted = new Map(); - const completedParts: UploadPartReceipt[][] = []; - let session: UploadSession | null = null; - let createCount = 0; - let issueCount = 0; - const issued = vi.fn(); - const control: ResumableUploadControlPlane = { - async createSession(input) { - createCount += 1; - session = Object.freeze({ - protocol: RESUMABLE_UPLOAD_PROTOCOL, - sessionId: - options.sessionId?.(createCount) ?? "session_01", - requestBindingSha256: input.requestBindingSha256, - fingerprint: input.fingerprint, - partSizeBytes: input.requestedPartSizeBytes, - partCount: input.fingerprint.partCount, - maxConcurrency: options.serverMaxConcurrency ?? 2, - expiresAtEpochMs: now + 5_000, - }); - return browserDataSuccess(session); - }, - async getStatus() { - if (!session) { - return browserDataFailure("NOT_FOUND", "UPLOAD_RECONCILE"); - } - const parts = - options.statusParts?.(session, accepted) ?? - [...accepted.values()].sort( - (left, right) => left.partNumber - right.partNumber, - ); - return browserDataSuccess({ - state: "ACTIVE", - session, - acceptedParts: parts, - }); - }, - async issuePartCapability(input) { - issueCount += 1; - issued(input); - return ( - options.issueCapability?.(input, issueCount) ?? - browserDataSuccess({ - capability: Object.freeze({ id: `cap-${issueCount}` }), - uploadBindingSha256: input.uploadBindingSha256, - expiresAtEpochMs: now + 4_000, - }) - ); - }, - async complete(input) { - completedParts.push([...input.orderedParts]); - return browserDataSuccess({ - state: "QUARANTINED", - protocol: RESUMABLE_UPLOAD_PROTOCOL, - sessionId: input.sessionId, - requestBindingSha256: input.requestBindingSha256, - fingerprint: input.fingerprint, - resourceId: "resource_01", - }); - }, - async abort() { - return browserDataSuccess({ state: "ABORTED" }); - }, - }; - return { - control, - accepted, - issued, - completedParts, - getSession: () => session, - }; -} - -function executorFor( - harness: ControlHarness, - options: Readonly<{ - delay?: () => Promise; - onActive?: (active: number) => void; - }> = {}, -): UploadPartExecutor { - let active = 0; - return { - async uploadPart(input) { - active += 1; - options.onActive?.(active); - await options.delay?.(); - active -= 1; - const receipt = Object.freeze({ - ...input.part, - receiptToken: `etag-part-${input.part.partNumber}`, - }); - harness.accepted.set(input.part.partNumber, receipt); - return browserDataSuccess(receipt); - }, - }; -} +import { + activeSignal, + byteStreamSource, + createControlHarness, + createMemoryCancellationPair, + createSerialMutationLock, + executorFor, + MemoryCheckpointStore, + noContentionLock, + rangeSource, + runtimePolicy, + type TestCapability, +} from "./resumable-upload-runtime-fixture.ts"; describe("production resumable upload runtime", () => { it("disposes through one drain that proves quiescence", async () => { @@ -1280,177 +980,3 @@ describe("production resumable upload runtime", () => { } }); }); -/** - * TR-RR-06. A non-cooperative mutation lock or provider must not make teardown - * unbounded: `dispose()` bounds its drain and reports honestly when the runtime - * is still CLOSING, and an abort is admitted physical work it cannot step over. - */ -describe("TR-RR-06 bounded resumable teardown", () => { - it("reports an unproved drain instead of waiting forever", async () => { - const checkpoints = new MemoryCheckpointStore(); - const harness = createControlHarness(); - const runtime = createResumableUploadRuntime({ - controlPlane: harness.control, - partExecutor: executorFor(harness, { delay: async () => {} }), - checkpoints, - // A lock that never grants: dispose must still be bounded. - mutationLock: Object.freeze({ - async run(): Promise { - return await new Promise(() => {}); - }, - }), - crypto, - policy: runtimePolicy({ cleanupDeadlineMs: 20 }), - now: () => 1_000, - random: () => 0, - sleep: async () => {}, - }); - - void runtime.upload({ - uploadKey: "upload_key_hung", - purpose: "attachment", - mediaType: "application/octet-stream", - source: byteStreamSource(new Uint8Array([1, 2, 3, 4, 5])), - signal: activeSignal, - }); - await Promise.resolve(); - await Promise.resolve(); - - const disposed = await runtime.dispose(); - expect(disposed.ok).toBe(false); - // Still CLOSING: physical work the caller must not treat as finished. - expect(runtime.lifecycle()).toBe("CLOSING"); - expect(checkpoints.closed).toBe(false); - }); - - it("closes once every admitted operation settles", async () => { - const checkpoints = new MemoryCheckpointStore(); - const harness = createControlHarness(); - const runtime = createResumableUploadRuntime({ - controlPlane: harness.control, - partExecutor: executorFor(harness, { delay: async () => {} }), - checkpoints, - mutationLock: noContentionLock, - crypto, - policy: runtimePolicy({ cleanupDeadlineMs: 200 }), - now: () => 1_000, - random: () => 0, - sleep: async () => {}, - }); - const disposed = await runtime.dispose(); - expect(disposed).toMatchObject({ ok: true }); - expect(runtime.lifecycle()).toBe("CLOSED"); - expect(checkpoints.closed).toBe(true); - }); -}); - -/** - * TR-04. `dispose()` proved quiescence from the wrapper registry only. A - * provider that ignored its attempt deadline let the wrapper settle first and - * leave the set empty, so teardown reported a drained runtime — and closed the - * checkpoint store — while the provider was still running. - */ -describe("TR-04 teardown waits for raw provider work, not only its wrapper", () => { - it("refuses to report a drained runtime while a provider is still running", async () => { - const harness = createControlHarness(); - const checkpoints = new MemoryCheckpointStore(); - const closeStore = vi.spyOn(checkpoints, "close"); - let releaseProvider: (() => void) | undefined; - // Ignores the attempt signal entirely and outlives its own deadline. - harness.control.createSession = () => - new Promise((resolve) => { - releaseProvider = () => - resolve( - browserDataFailure("UNAVAILABLE", "UPLOAD_SESSION", { - retryable: true, - recovery: "RESUME", - }), - ); - }); - - const runtime = createResumableUploadRuntime({ - controlPlane: harness.control, - partExecutor: executorFor(harness), - checkpoints, - mutationLock: noContentionLock, - crypto, - policy: runtimePolicy({ - providerAttemptTimeoutMs: 5, - cleanupDeadlineMs: 25, - maxRetries: 0, - }), - now: () => 1_000, - random: () => 0, - sleep: async () => {}, - }); - - const uploading = runtime.upload({ - uploadKey: "upload_key_raw", - purpose: "attachment", - mediaType: "application/octet-stream", - source: byteStreamSource(new Uint8Array([1, 2, 3, 4, 5])), - signal: activeSignal, - }); - await vi.waitFor(() => expect(releaseProvider).toBeDefined()); - // The wrapper has already given up on the attempt. - await uploading; - - const disposed = await runtime.dispose(); - expect(disposed.ok).toBe(false); - if (!disposed.ok) { - expect(disposed.error.code).toBe("UNAVAILABLE"); - expect(disposed.error.recovery).toBe("RESUME"); - } - // The store stays open while something could still write a checkpoint. - expect(closeStore).not.toHaveBeenCalled(); - - releaseProvider?.(); - }); - - it("reports a drained runtime once the raw provider settles", async () => { - const harness = createControlHarness(); - const checkpoints = new MemoryCheckpointStore(); - let releaseProvider: (() => void) | undefined; - harness.control.createSession = () => - new Promise((resolve) => { - releaseProvider = () => - resolve( - browserDataFailure("UNAVAILABLE", "UPLOAD_SESSION", { - retryable: true, - recovery: "RESUME", - }), - ); - }); - - const runtime = createResumableUploadRuntime({ - controlPlane: harness.control, - partExecutor: executorFor(harness), - checkpoints, - mutationLock: noContentionLock, - crypto, - policy: runtimePolicy({ - providerAttemptTimeoutMs: 5, - cleanupDeadlineMs: 1_000, - maxRetries: 0, - }), - now: () => 1_000, - random: () => 0, - sleep: async () => {}, - }); - - const uploading = runtime.upload({ - uploadKey: "upload_key_raw_2", - purpose: "attachment", - mediaType: "application/octet-stream", - source: byteStreamSource(new Uint8Array([1, 2, 3, 4, 5])), - signal: activeSignal, - }); - await vi.waitFor(() => expect(releaseProvider).toBeDefined()); - await uploading; - - const disposing = runtime.dispose(); - releaseProvider?.(); - await expect(disposing).resolves.toMatchObject({ ok: true }); - expect(runtime.lifecycle()).toBe("CLOSED"); - }); -}); diff --git a/tests/unit/security-followup-fixture.ts b/tests/unit/security-followup-fixture.ts new file mode 100644 index 0000000..7ec9770 --- /dev/null +++ b/tests/unit/security-followup-fixture.ts @@ -0,0 +1,543 @@ +import { + createHash, + generateKeyPairSync, + sign, + type KeyObject, +} from "node:crypto"; +import { mkdir, mkdtemp, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +import { localEvidenceAssessmentArtifactSchema } from "../../scripts/contracts/release-artifacts.ts"; +import { PROMOTED_FILE_NAMES } from "../../scripts/contracts/promotion-artifacts.ts"; +import { + PROMOTION_VERIFIER_ID, + providerEvidenceSignaturePayload, + trustPolicySha256, +} from "../../scripts/lib/provider-evidence.ts"; +import { LOCAL_EVIDENCE_VERIFIER_ID } from "../../scripts/lib/local-release-evidence.ts"; +import { + LOCAL_EVIDENCE_ASSESSMENT_PATH, + distSha256, + type ReleaseCandidateManifest, +} from "../../scripts/lib/release-candidate.ts"; +import { supplyChainDigest } from "../../scripts/lib/supply-chain.ts"; + +export const PROCESS_HEAVY_TIMEOUT_MS = 30_000; + +export const digest = (value: string): string => + createHash("sha256").update(value).digest("hex"); +export const digestBytes = (value: Buffer): string => + createHash("sha256").update(value).digest("hex"); + +export function passingAssessment(): any { + return { + schemaVersion: 1 as const, + artifactType: "local-evidence-assessment" as const, + generatedAt: "2026-08-02T00:00:00.000Z", + status: "PASS" as const, + verifier: { + id: LOCAL_EVIDENCE_VERIFIER_ID, + version: "1", + sourceSha256: digest("verifier source"), + }, + source: { + revision: "a".repeat(40), + sourceSetSha256: digest("source set"), + }, + candidate: { + distSha256: digest("dist"), + lockfileSha256: digest("lockfile"), + sbomSha256: digest("sbom"), + }, + secretScan: { + policySha256: digest("secret policy"), + sarifSha256: digest("secret sarif"), + scanInputSha256: digest("secret scan input"), + }, + policyInputs: [ + { + path: "config/security/dependency-policy.json", + bytes: 3, + sha256: digest("{}\n"), + }, + ], + evidenceInputs: [ + { path: "pnpm-lock.yaml", bytes: 9, sha256: digest("lockfile\n") }, + ], + checks: { + release: "PASS" as const, + supplyChain: "PASS" as const, + dependencyPolicy: "PASS" as const, + licensePolicy: "PASS" as const, + vulnerabilityPolicy: "PASS" as const, + secretScan: "PASS" as const, + }, + failures: [] as string[], + }; +} + + +export function providerExpectedContext() { + return { + run: { id: "run-42", attempt: 1 }, + source: { revision: "b".repeat(40), sourceSetSha256: digest("provider source") }, + candidate: { + archiveSha256: digest("archive"), + bundleSha256: digest("bundle"), + distSha256: digest("provider dist"), + lockfileSha256: digest("provider lockfile"), + }, + secretScanAttestation: { + status: "PASS" as const, + localEvidenceAssessmentSha256: digest("provider assessment"), + sourceSetSha256: digest("provider source"), + policySha256: digest("provider secret policy"), + sarifSha256: digest("provider secret sarif"), + scanInputSha256: digest("provider secret input"), + }, + } as const; +} + +export function privatePromotionFiles() { + return PROMOTED_FILE_NAMES.map((name) => { + const bytes = Buffer.from(`${name}\n`); + return { name, bytes, sha256: digestBytes(bytes) }; + }); +} + +export function syntheticSignedPromotionBundle() { + const vulnerabilityKeys = generateKeyPairSync("ed25519"); + const provenanceKeys = generateKeyPairSync("ed25519"); + const archiveBytes = Buffer.from("synthetic signed replay archive\n"); + const run = { id: "signed-run", attempt: 1 } as const; + const source = { + revision: "a".repeat(40), + sourceSetSha256: digest("synthetic-source-set"), + } as const; + const candidate = { + archiveSha256: digestBytes(archiveBytes), + bundleSha256: digest("synthetic-bundle"), + distSha256: digest("synthetic-dist"), + lockfileSha256: digest("synthetic-lock"), + } as const; + const vulnerability = signedProviderV2( + { + schemaVersion: 2, + evidenceType: "vulnerability-report", + provider: "synthetic-vulnerability-provider", + issuedAt: "2026-08-02T01:00:00.000Z", + expiresAt: "2026-08-02T02:00:00.000Z", + run: { ...run, invocationNonce: "1".repeat(64) }, + source, + candidate, + secretScanAttestation: { + status: "PASS", + localEvidenceAssessmentSha256: digest("synthetic-assessment"), + sourceSetSha256: source.sourceSetSha256, + policySha256: digest("synthetic-policy"), + sarifSha256: digest("synthetic-sarif"), + scanInputSha256: digest("synthetic-scan-input"), + }, + findings: [], + }, + "synthetic-vulnerability", + vulnerabilityKeys.publicKey, + vulnerabilityKeys.privateKey, + ); + const provenance = signedProviderV2( + { + schemaVersion: 2, + evidenceType: "provenance-attestation", + provider: "synthetic-provenance-provider", + signer: "synthetic-signer", + issuedAt: "2026-08-02T01:00:00.000Z", + expiresAt: "2026-08-02T02:00:00.000Z", + run: { ...run, invocationNonce: "2".repeat(64) }, + source, + candidate, + subject: { name: "dist", digest: { sha256: candidate.distSha256 } }, + }, + "synthetic-provenance", + provenanceKeys.publicKey, + provenanceKeys.privateKey, + ); + const vulnerabilityBytes = Buffer.from(`${JSON.stringify(vulnerability)}\n`); + const provenanceBytes = Buffer.from(`${JSON.stringify(provenance)}\n`); + const vulnerabilityTrust = trust("synthetic-vulnerability", vulnerabilityKeys.publicKey); + const provenanceTrust = trust("synthetic-provenance", provenanceKeys.publicKey); + const providerEvidence = { + vulnerabilityReportSha256: digestBytes(vulnerabilityBytes), + provenanceAttestationSha256: digestBytes(provenanceBytes), + vulnerabilityInvocationNonce: "1".repeat(64), + provenanceInvocationNonce: "2".repeat(64), + vulnerabilityKeyId: vulnerabilityTrust.keyId, + vulnerabilityKeyFingerprint: vulnerabilityTrust.publicKeyFingerprint, + provenanceKeyId: provenanceTrust.keyId, + provenanceKeyFingerprint: provenanceTrust.publicKeyFingerprint, + secretScanAttestation: vulnerability.secretScanAttestation, + }; + const common = { + schemaVersion: 3, + verifiedAt: "2026-08-02T01:00:00.000Z", + status: "PASS", + verifier: { + id: PROMOTION_VERIFIER_ID, + version: "3", + }, + run, + source, + candidate, + providerEvidence, + trustPolicySha256: trustPolicySha256({ vulnerabilityTrust, provenanceTrust }), + failures: [], + }; + const providerBytes = Buffer.from( + `${JSON.stringify({ + ...common, + artifactType: "provider-verification", + vulnerabilityStatus: "PASS", + provenanceAttestationStatus: "PASS", + }, null, 2)}\n`, + ); + const promotionBytes = Buffer.from( + `${JSON.stringify({ + ...common, + artifactType: "promotion-verification", + localEvidenceStatus: "PASS", + localEvidenceAssessmentSha256: digest("synthetic-assessment"), + providerVerificationSha256: digestBytes(providerBytes), + }, null, 2)}\n`, + ); + return { + files: { + "release-candidate.tar.gz": archiveBytes, + "vulnerability-report.json": vulnerabilityBytes, + "provenance-attestation.json": provenanceBytes, + "provider-verification.json": providerBytes, + "promotion-verification.json": promotionBytes, + }, + verification: { + vulnerabilityTrust, + provenanceTrust, + nowEpochMs: () => Date.parse("2026-08-02T01:00:00.000Z"), + expected: { + run, + sourceRevision: source.revision, + sourceSetSha256: source.sourceSetSha256, + archiveSha256: candidate.archiveSha256, + bundleSha256: candidate.bundleSha256, + distSha256: candidate.distSha256, + lockfileSha256: candidate.lockfileSha256, + }, + }, + vulnerabilityPem: vulnerabilityKeys.publicKey.export({ type: "spki", format: "pem" }), + provenancePem: provenanceKeys.publicKey.export({ type: "spki", format: "pem" }), + }; +} + +export function fingerprint(publicKey: KeyObject): string { + return `sha256:${createHash("sha256") + .update(publicKey.export({ type: "spki", format: "der" })) + .digest("hex")}`; +} + +export function trust(keyId: string, publicKey: KeyObject) { + return { keyId, publicKey, publicKeyFingerprint: fingerprint(publicKey) }; +} + +export function signedProviderV2( + unsigned: Record, + keyId: string, + publicKey: KeyObject, + privateKey: KeyObject, + fingerprintOverride?: string, +): Record { + const { signature: existingSignature, ...payload } = unsigned; + const value = { + ...payload, + signature: { + algorithm: "Ed25519" as const, + keyId, + publicKeyFingerprint: + fingerprintOverride ?? + (existingSignature && typeof existingSignature === "object" && + "publicKeyFingerprint" in existingSignature + ? String(existingSignature.publicKeyFingerprint) + : fingerprint(publicKey)), + value: "", + }, + }; + value.signature.value = sign( + null, + providerEvidenceSignaturePayload(value), + privateKey, + ).toString("base64"); + return value; +} + +export function providerUnsigned( + kind: "vulnerability" | "provenance", + expected: ReturnType, +): Record { + const common = { + source: expected.source, + candidate: expected.candidate, + schemaVersion: 2, + evidenceType: + kind === "vulnerability" + ? "vulnerability-report" + : "provenance-attestation", + provider: `fixture-${kind}`, + issuedAt: "2026-08-02T01:00:00.000Z", + expiresAt: "2026-08-02T02:00:00.000Z", + run: { + ...expected.run, + invocationNonce: kind === "vulnerability" ? "1".repeat(64) : "2".repeat(64), + }, + }; + return kind === "vulnerability" + ? { + ...common, + secretScanAttestation: expected.secretScanAttestation, + findings: [], + } + : { + ...common, + signer: "fixture-workload", + subject: { + name: "dist", + digest: { sha256: expected.candidate.distSha256 }, + }, + }; +} + +export async function createArchivedAssessmentFixture(): Promise<{ + root: string; + manifest: ReleaseCandidateManifest; + assessmentSha256: string; +}> { + const root = await mkdtemp(path.join(tmpdir(), "archived-assessment-")); + const sourceRevision = "a".repeat(40); + const sourceSetSha256 = digest("source set"); + const releaseManifestBytes = Buffer.from( + `${JSON.stringify({ + schemaVersion: 1, + appVersion: "1.0.0", + buildId: "build-1", + commitSha: sourceRevision, + configSchemaVersion: "1", + apiContractVersion: "1", + assetManifestHash: digest("vite manifest"), + releaseId: "release-1", + builtAt: "2026-08-02T00:00:00.000Z", + routeChunks: { home: "assets/home.js" }, + })}\n`, + ); + const distInputs = [ + { path: "dist/app.js", bytes: Buffer.byteLength("app\n"), sha256: digest("app\n"), gzipBytes: 0 }, + { + path: "dist/release-manifest.json", + bytes: releaseManifestBytes.byteLength, + sha256: digestBytes(releaseManifestBytes), + gzipBytes: 0, + }, + ]; + const candidateDist = distSha256(distInputs); + const sbomBytes = Buffer.from( + `${JSON.stringify({ + bomFormat: "CycloneDX", + specVersion: "1.6", + serialNumber: "urn:uuid:00000000-0000-4000-8000-000000000001", + version: 1, + metadata: { + component: { type: "application", name: "fixture", version: "1.0.0" }, + properties: [], + }, + components: [], + dependencies: [], + })}\n`, + ); + const sbomSha256 = digestBytes(sbomBytes); + const lockfileBytes = Buffer.from("lockfile\n"); + const lockfileDigest = digestBytes(lockfileBytes); + const buildManifest = { + schemaVersion: 1, + buildId: "build-1", + commitSha: sourceRevision, + releaseId: "release-1", + moduleInventoryHash: digest("module inventory"), + generatedAt: "2026-08-02T00:00:00.000Z", + buildContext: { + nodeVersion: "v24.0.0", + packageManagerVersion: "11.0.0", + runnerImage: "linux-x64", + sourceDateEpoch: "1785638400", + }, + outputs: { + directory: "dist", + viteManifest: "dist/.vite/manifest.json", + moduleInventory: "artifacts/quality/vite-module-inventory.json", + routeChunks: { home: "assets/home.js" }, + runtimeConfigSchema: "dist/runtime-config.schema.json", + }, + }; + const provenance = { + _type: "https://in-toto.io/Statement/v1", + subject: [{ name: "dist", digest: { sha256: candidateDist } }], + predicateType: "https://slsa.dev/provenance/v1", + predicate: { + buildDefinition: { + buildType: "https://vite.dev/build/v1", + externalParameters: {}, + internalParameters: {}, + resolvedDependencies: [ + { uri: "pnpm-lock.yaml", digest: { sha256: lockfileDigest } }, + ], + }, + runDetails: { + builder: { id: "fixture-builder" }, + metadata: { invocationId: "LOCAL_UNSIGNED" }, + }, + materials: { lockfileSha256: lockfileDigest, sourceSetSha256, sbomSha256 }, + }, + }; + const supplyVerification = { + schemaVersion: 1, + localStatus: "PASS", + promotionStatus: "FAIL_UNVERIFIED", + lockfileSha256: lockfileDigest, + sourceSetSha256, + distSha256: candidateDist, + sbomSha256, + dependencyDiff: { added: [], removed: [], changed: [], upgrades: [] }, + highRiskReview: [], + vulnerabilityStatus: "FAIL_UNVERIFIED", + provenanceAttestationStatus: "FAIL_UNVERIFIED", + failures: [], + }; + const members = new Map([ + ["dist/app.js", Buffer.from("app\n")], + ["dist/release-manifest.json", releaseManifestBytes], + ["pnpm-lock.yaml", lockfileBytes], + ["artifacts/release/build-manifest.json", Buffer.from(`${JSON.stringify(buildManifest)}\n`)], + ["artifacts/release/provenance.json", Buffer.from(`${JSON.stringify(provenance)}\n`)], + [ + "artifacts/security/supply-chain-verification.json", + Buffer.from(`${JSON.stringify(supplyVerification)}\n`), + ], + ["artifacts/release/sbom.cdx.json", sbomBytes], + ]); + const evidenceInputs = [...members.entries()] + .map(([memberPath, bytes]) => ({ + path: memberPath, + bytes: bytes.byteLength, + sha256: digestBytes(bytes), + })) + .sort((left, right) => (left.path < right.path ? -1 : left.path > right.path ? 1 : 0)); + const policyPaths = [ + "config/security/dependency-baseline.approval.json", + "config/security/dependency-baseline.json", + "config/security/dependency-change-evidence.json", + "config/security/dependency-policy.json", + "config/security/secret-scan-policy.json", + "config/security/vulnerability-exceptions.json", + "config/security/vulnerability-policy.json", + "schemas/artifacts/build-manifest.schema.json", + "schemas/artifacts/dependency-inventory.schema.json", + "schemas/artifacts/supply-chain-verification.schema.json", + "scripts/contracts/release-artifacts.ts", + "scripts/create-release-candidate.ts", + "scripts/generate-supply-chain.ts", + "scripts/lib/build-manifest-outputs.ts", + "scripts/lib/json-schema.ts", + "scripts/lib/local-policy-evidence.ts", + "scripts/lib/local-release-evidence.ts", + "scripts/lib/release-candidate.ts", + "scripts/lib/release-input-evidence.ts", + "scripts/lib/release-runtime-coherence.ts", + "scripts/lib/repository-file-inventory.ts", + "scripts/lib/secret-scan-evaluator.ts", + "scripts/lib/secret-scan-policy.ts", + "scripts/lib/secret-scan.ts", + "scripts/lib/supply-chain.ts", + "scripts/lib/validated-json-artifact.ts", + "src/contracts/release-artifacts.ts", + "src/features/installed-contract-contributions.ts", + "src/features/installed-feature-contracts.ts", + ]; + const sbomRow = evidenceInputs.find( + ({ path: memberPath }) => memberPath === "artifacts/release/sbom.cdx.json", + )!; + const policyInputs = policyPaths.map((policyPath) => ({ + path: policyPath, + bytes: 2, + sha256: digest(`policy:${policyPath}`), + })); + const verifierPaths = new Set([ + "scripts/contracts/release-artifacts.ts", + "scripts/create-release-candidate.ts", + "scripts/generate-supply-chain.ts", + "scripts/lib/build-manifest-outputs.ts", + "scripts/lib/json-schema.ts", + "scripts/lib/local-policy-evidence.ts", + "scripts/lib/local-release-evidence.ts", + "scripts/lib/release-candidate.ts", + "scripts/lib/release-input-evidence.ts", + "scripts/lib/release-runtime-coherence.ts", + "scripts/lib/repository-file-inventory.ts", + "scripts/lib/secret-scan-evaluator.ts", + "scripts/lib/secret-scan-policy.ts", + "scripts/lib/secret-scan.ts", + "scripts/lib/supply-chain.ts", + "scripts/lib/validated-json-artifact.ts", + "src/contracts/release-artifacts.ts", + "src/features/installed-contract-contributions.ts", + "src/features/installed-feature-contracts.ts", + ]); + const assessment = localEvidenceAssessmentArtifactSchema.parse({ + ...passingAssessment(), + verifier: { + id: LOCAL_EVIDENCE_VERIFIER_ID, + version: "1", + sourceSha256: supplyChainDigest( + policyInputs.filter(({ path: policyPath }) => verifierPaths.has(policyPath)), + ), + }, + source: { revision: sourceRevision, sourceSetSha256 }, + candidate: { + distSha256: candidateDist, + lockfileSha256: evidenceInputs.find(({ path: memberPath }) => memberPath === "pnpm-lock.yaml")! + .sha256, + sbomSha256: sbomRow.sha256, + }, + policyInputs, + evidenceInputs, + }); + const assessmentBytes = Buffer.from(`${JSON.stringify(assessment)}\n`); + members.set(LOCAL_EVIDENCE_ASSESSMENT_PATH, assessmentBytes); + for (const [memberPath, bytes] of members) { + await mkdir(path.dirname(path.join(root, memberPath)), { recursive: true }); + await writeFile(path.join(root, memberPath), bytes); + } + const files = [...members.entries()] + .map(([memberPath, bytes]) => ({ + path: memberPath, + bytes: bytes.byteLength, + sha256: digestBytes(bytes), + })) + .sort((left, right) => (left.path < right.path ? -1 : left.path > right.path ? 1 : 0)); + const manifest: ReleaseCandidateManifest = { + schemaVersion: 1, + distSha256: assessment.candidate.distSha256, + lockfileSha256: assessment.candidate.lockfileSha256, + bundleSha256: supplyChainDigest(files), + files, + }; + await mkdir(path.join(root, "artifacts/release"), { recursive: true }); + await writeFile( + path.join(root, "artifacts/release/release-candidate.json"), + `${JSON.stringify(manifest)}\n`, + ); + return { root, manifest, assessmentSha256: digestBytes(assessmentBytes) }; +} diff --git a/tests/unit/security-followup.test.ts b/tests/unit/security-followup.test.ts index 369cb65..937f75c 100644 --- a/tests/unit/security-followup.test.ts +++ b/tests/unit/security-followup.test.ts @@ -1,113 +1,28 @@ import { - createHash, - generateKeyPairSync, - sign, - type KeyObject, -} from "node:crypto"; -import { spawnSync } from "node:child_process"; -import { - chmod, - lstat, mkdir, - mkdtemp, readFile, - readdir, - rename, rm, writeFile, } from "node:fs/promises"; -import { tmpdir } from "node:os"; import path from "node:path"; -import { pathToFileURL } from "node:url"; -import { EventEmitter } from "node:events"; import { describe, expect, it } from "vitest"; import { localEvidenceAssessmentArtifactSchema } from "../../scripts/contracts/release-artifacts.ts"; -import { PROMOTED_FILE_NAMES } from "../../scripts/contracts/promotion-artifacts.ts"; import { verifyArchivedLocalEvidence } from "../../scripts/lib/local-release-evidence.ts"; -import { - evaluatePromotionEvidence, - providerEvidenceSignaturePayload, - providerPublicKeyFingerprint, - trustPolicySha256, - validateProviderEvidence, -} from "../../scripts/lib/provider-evidence.ts"; -import { readProviderTrust } from "../../scripts/lib/provider-trust.ts"; -import { superviseProviderEvidence } from "../../scripts/lib/provider-supervisor.ts"; -import { runProviderProcess } from "../../scripts/lib/provider-process-runner.ts"; -import { runStageVerifiedPromotionCli } from "../../scripts/lib/stage-verified-promotion-cli.ts"; -import { publishPrivatePromotionStaging } from "../../scripts/lib/promotion-stager.ts"; -import { verifyExactPromotionBundle } from "../../scripts/lib/exact-promotion-bundle.ts"; import { LOCAL_EVIDENCE_ASSESSMENT_PATH, LOCAL_EVIDENCE_VERIFIER_SOURCE_PATHS, - distSha256, - type ReleaseCandidateManifest, } from "../../scripts/lib/release-candidate.ts"; import { supplyChainDigest } from "../../scripts/lib/supply-chain.ts"; +import { + createArchivedAssessmentFixture, + digest, + digestBytes, + passingAssessment, +} from "./security-followup-fixture.ts"; -/** - * This suite's budget, not the file's. The 10s default is sized for pure-JS - * unit tests; these spawn processes, build archives and sign evidence, and on a - * machine running the rest of the suite in parallel they legitimately need - * longer. Raising the global default instead would hide a genuinely hung test. - */ -const PROCESS_HEAVY_TIMEOUT_MS = 30_000; - -const digest = (value: string): string => - createHash("sha256").update(value).digest("hex"); -const digestBytes = (value: Buffer): string => - createHash("sha256").update(value).digest("hex"); - -function passingAssessment(): any { - return { - schemaVersion: 1 as const, - artifactType: "local-evidence-assessment" as const, - generatedAt: "2026-08-02T00:00:00.000Z", - status: "PASS" as const, - verifier: { - id: "tech-log-frontend/local-evidence-verifier", - version: "1", - sourceSha256: digest("verifier source"), - }, - source: { - revision: "a".repeat(40), - sourceSetSha256: digest("source set"), - }, - candidate: { - distSha256: digest("dist"), - lockfileSha256: digest("lockfile"), - sbomSha256: digest("sbom"), - }, - secretScan: { - policySha256: digest("secret policy"), - sarifSha256: digest("secret sarif"), - scanInputSha256: digest("secret scan input"), - }, - policyInputs: [ - { - path: "config/security/dependency-policy.json", - bytes: 3, - sha256: digest("{}\n"), - }, - ], - evidenceInputs: [ - { path: "pnpm-lock.yaml", bytes: 9, sha256: digest("lockfile\n") }, - ], - checks: { - release: "PASS" as const, - supplyChain: "PASS" as const, - dependencyPolicy: "PASS" as const, - licensePolicy: "PASS" as const, - vulnerabilityPolicy: "PASS" as const, - secretScan: "PASS" as const, - }, - failures: [] as string[], - }; -} - -describe("security follow-up contracts", () => { +describe("security local evidence contracts", () => { it("rejects a PASS local assessment with a failed check or failure diagnostic", () => { const failedCheck = passingAssessment(); failedCheck.checks.secretScan = "FAIL"; @@ -342,1520 +257,4 @@ describe("security follow-up contracts", () => { } }); - it("accepts signed provider v2 evidence only for the exact run, source, archive, and nonce", () => { - const now = Date.parse("2026-08-02T01:00:00.000Z"); - const vulnerabilityKeys = generateKeyPairSync("ed25519"); - const provenanceKeys = generateKeyPairSync("ed25519"); - const expected = providerExpectedContext(); - const vulnerability = signedProviderV2( - { - source: expected.source, - candidate: expected.candidate, - schemaVersion: 2, - evidenceType: "vulnerability-report", - provider: "fixture-vulnerability", - issuedAt: "2026-08-02T01:00:00.000Z", - expiresAt: "2026-08-02T02:00:00.000Z", - run: { ...expected.run, invocationNonce: "1".repeat(64) }, - secretScanAttestation: expected.secretScanAttestation, - findings: [], - }, - "vulnerability-key", - vulnerabilityKeys.publicKey, - vulnerabilityKeys.privateKey, - ); - const provenance = signedProviderV2( - { - source: expected.source, - candidate: expected.candidate, - schemaVersion: 2, - evidenceType: "provenance-attestation", - provider: "fixture-provenance", - signer: "fixture-workload", - issuedAt: "2026-08-02T01:00:00.000Z", - expiresAt: "2026-08-02T02:00:00.000Z", - run: { ...expected.run, invocationNonce: "2".repeat(64) }, - subject: { name: "dist", digest: { sha256: expected.candidate.distSha256 } }, - }, - "provenance-key", - provenanceKeys.publicKey, - provenanceKeys.privateKey, - ); - const result = evaluatePromotionEvidence({ - expected: { - ...expected, - vulnerabilityInvocationNonce: "1".repeat(64), - provenanceInvocationNonce: "2".repeat(64), - }, - localStatus: "PASS", - vulnerabilityReport: vulnerability, - provenanceAttestation: provenance, - vulnerabilityTrust: trust("vulnerability-key", vulnerabilityKeys.publicKey), - provenanceTrust: trust("provenance-key", provenanceKeys.publicKey), - nowEpochMs: () => now, - }); - - expect(result).toEqual({ - status: "PASS", - vulnerabilityStatus: "PASS", - provenanceAttestationStatus: "PASS", - failures: [], - }); - const replayed = evaluatePromotionEvidence({ - expected: { - ...expected, - run: { id: expected.run.id, attempt: 2 }, - vulnerabilityInvocationNonce: "1".repeat(64), - provenanceInvocationNonce: "2".repeat(64), - }, - localStatus: "PASS", - vulnerabilityReport: vulnerability, - provenanceAttestation: provenance, - vulnerabilityTrust: trust("vulnerability-key", vulnerabilityKeys.publicKey), - provenanceTrust: trust("provenance-key", provenanceKeys.publicKey), - nowEpochMs: () => now, - }); - expect(replayed.status).toBe("FAIL_UNVERIFIED"); - expect(replayed.failures).toEqual( - expect.arrayContaining([ - "vulnerability report run identity mismatch", - "provenance attestation run identity mismatch", - ]), - ); - }); - - it("rejects a signed vulnerability PASS when the captured SARIF attestation differs", () => { - const keys = generateKeyPairSync("ed25519"); - const expected = providerExpectedContext(); - const secretScanAttestation = { - status: "PASS" as const, - localEvidenceAssessmentSha256: digest("assessment"), - sourceSetSha256: expected.source.sourceSetSha256, - policySha256: digest("secret policy"), - sarifSha256: digest("real sarif"), - scanInputSha256: digest("scan input"), - }; - const report = signedProviderV2( - { - schemaVersion: 2, - evidenceType: "vulnerability-report", - provider: "fixture-vulnerability", - issuedAt: "2026-08-02T01:00:00.000Z", - expiresAt: "2026-08-02T02:00:00.000Z", - run: { ...expected.run, invocationNonce: "1".repeat(64) }, - source: expected.source, - candidate: expected.candidate, - secretScanAttestation, - findings: [], - }, - "vulnerability-key", - keys.publicKey, - keys.privateKey, - ); - const validated = validateProviderEvidence({ - kind: "vulnerability", - value: report, - expected: { - ...expected, - vulnerabilityInvocationNonce: "1".repeat(64), - provenanceInvocationNonce: "2".repeat(64), - secretScanAttestation: { - ...secretScanAttestation, - sarifSha256: digest("forged empty sarif"), - }, - }, - trust: trust("vulnerability-key", keys.publicKey), - nowEpochMs: () => Date.parse("2026-08-02T01:00:00.000Z"), - }); - expect(validated.status).toBe("FAIL_UNVERIFIED"); - expect(validated.failures).toContain( - "vulnerability report secret scan attestation mismatch", - ); - const forged = structuredClone(report); - forged.secretScanAttestation.sarifSha256 = digest("forged empty sarif"); - const forgedValidation = validateProviderEvidence({ - kind: "vulnerability", - value: forged, - expected: { - ...expected, - vulnerabilityInvocationNonce: "1".repeat(64), - provenanceInvocationNonce: "2".repeat(64), - secretScanAttestation: forged.secretScanAttestation, - }, - trust: trust("vulnerability-key", keys.publicKey), - nowEpochMs: () => Date.parse("2026-08-02T01:00:00.000Z"), - }); - expect(forgedValidation.failures).toContain( - "vulnerability report signature verification failed", - ); - - const provenanceKeys = generateKeyPairSync("ed25519"); - const provenance = signedProviderV2( - { - schemaVersion: 2, - evidenceType: "provenance-attestation", - provider: "fixture-provenance", - signer: "fixture-workload", - issuedAt: "2026-08-02T01:00:00.000Z", - expiresAt: "2026-08-02T02:00:00.000Z", - run: { ...expected.run, invocationNonce: "2".repeat(64) }, - source: expected.source, - candidate: expected.candidate, - subject: { name: "dist", digest: { sha256: expected.candidate.distSha256 } }, - }, - "provenance-key", - provenanceKeys.publicKey, - provenanceKeys.privateKey, - ); - const evaluated = evaluatePromotionEvidence({ - expected: { - ...expected, - vulnerabilityInvocationNonce: "1".repeat(64), - provenanceInvocationNonce: "2".repeat(64), - secretScanAttestation: { - ...secretScanAttestation, - sarifSha256: digest("forged empty sarif"), - }, - }, - localStatus: "PASS", - vulnerabilityReport: report, - provenanceAttestation: provenance, - vulnerabilityTrust: trust("vulnerability-key", keys.publicKey), - provenanceTrust: trust("provenance-key", provenanceKeys.publicKey), - nowEpochMs: () => Date.parse("2026-08-02T01:00:00.000Z"), - }); - expect(evaluated.vulnerabilityStatus).toBe("FAIL_UNVERIFIED"); - expect(evaluated.failures).toContain( - "vulnerability report secret scan attestation mismatch", - ); - }); - - it.each(["vulnerability", "provenance"] as const)( - "rejects correctly re-signed %s v2 context/time/replay drift", - (kind) => { - const now = Date.parse("2026-08-02T01:00:00.000Z"); - const vulnerabilityKeys = generateKeyPairSync("ed25519"); - const provenanceKeys = generateKeyPairSync("ed25519"); - const expected = providerExpectedContext(); - const baseVulnerability = providerUnsigned("vulnerability", expected); - const baseProvenance = providerUnsigned("provenance", expected); - const validVulnerability = signedProviderV2( - baseVulnerability, - "vulnerability-key", - vulnerabilityKeys.publicKey, - vulnerabilityKeys.privateKey, - ); - const validProvenance = signedProviderV2( - baseProvenance, - "provenance-key", - provenanceKeys.publicKey, - provenanceKeys.privateKey, - ); - const rawCases: Array) => Record, - RegExp, - ]> = [ - ["schema v1", (value) => ({ ...value, schemaVersion: 1 }), /missing or invalid/u], - [ - "evidence type", - (value) => ({ - ...value, - evidenceType: - kind === "vulnerability" - ? "provenance-attestation" - : "vulnerability-report", - }), - /missing or invalid/u, - ], - ...(["archiveSha256", "bundleSha256", "distSha256", "lockfileSha256"] as const).map( - (field) => [ - `candidate ${field}`, - (value: Record) => ({ - ...value, - candidate: { ...value.candidate, [field]: "f".repeat(64) }, - ...(kind === "provenance" && field === "distSha256" - ? { - subject: { - name: "dist", - digest: { sha256: "f".repeat(64) }, - }, - } - : {}), - }), - /candidate identity|subject dist/u, - ] as const, - ), - [ - "different archive with same dist and lockfile", - (value) => ({ - ...value, - candidate: { ...value.candidate, archiveSha256: "e".repeat(64) }, - }), - /candidate identity/u, - ], - [ - "source revision", - (value) => ({ ...value, source: { ...value.source, revision: "c".repeat(40) } }), - /source identity/u, - ], - [ - "source set", - (value) => ({ ...value, source: { ...value.source, sourceSetSha256: "c".repeat(64) } }), - /source identity/u, - ], - [ - "run id", - (value) => ({ ...value, run: { ...value.run, id: "other-run" } }), - /run identity/u, - ], - [ - "run attempt replay", - (value) => ({ ...value, run: { ...value.run, attempt: 2 } }), - /run identity/u, - ], - [ - "different nonce", - (value) => ({ ...value, run: { ...value.run, invocationNonce: "3".repeat(64) } }), - /invocation nonce/u, - ], - [ - "missing nonce", - (value) => { - const run = { ...value.run }; - delete run.invocationNonce; - return { ...value, run }; - }, - /missing or invalid/u, - ], - [ - "uppercase nonce", - (value) => ({ ...value, run: { ...value.run, invocationNonce: "A".repeat(64) } }), - /missing or invalid/u, - ], - [ - "short nonce", - (value) => ({ ...value, run: { ...value.run, invocationNonce: "1".repeat(62) } }), - /missing or invalid/u, - ], - [ - "issued future boundary", - (value) => ({ ...value, issuedAt: "2026-08-02T01:05:00.001Z" }), - /future skew/u, - ], - [ - "expiry equality", - (value) => ({ ...value, expiresAt: "2026-08-02T01:00:00.000Z" }), - /expired/u, - ], - [ - "expiry past", - (value) => ({ ...value, expiresAt: "2026-08-02T00:59:59.999Z" }), - /expired/u, - ], - [ - "zero lifetime", - (value) => ({ - ...value, - issuedAt: "2026-08-02T01:01:00.000Z", - expiresAt: "2026-08-02T01:01:00.000Z", - }), - /not positive/u, - ], - [ - "negative lifetime", - (value) => ({ - ...value, - issuedAt: "2026-08-02T01:02:00.000Z", - expiresAt: "2026-08-02T01:01:59.999Z", - }), - /not positive/u, - ], - [ - "lifetime above two hours", - (value) => ({ - ...value, - issuedAt: "2026-08-02T01:00:00.000Z", - expiresAt: "2026-08-02T03:00:00.001Z", - }), - /exceeds two hours/u, - ], - [ - "wrong fingerprint", - (value) => ({ - ...value, - signature: { - ...value.signature, - publicKeyFingerprint: `sha256:${"d".repeat(64)}`, - }, - }), - /trust identity/u, - ], - ]; - const cases = rawCases.map(([name, mutate, failure]) => ({ - name, - mutate, - failure, - })); - - for (const testCase of cases) { - const base = kind === "vulnerability" ? baseVulnerability : baseProvenance; - const mutated = testCase.mutate(structuredClone(base)); - const resigned = signedProviderV2( - mutated, - kind === "vulnerability" ? "vulnerability-key" : "provenance-key", - kind === "vulnerability" ? vulnerabilityKeys.publicKey : provenanceKeys.publicKey, - kind === "vulnerability" ? vulnerabilityKeys.privateKey : provenanceKeys.privateKey, - "signature" in mutated && mutated.signature?.publicKeyFingerprint - ? mutated.signature.publicKeyFingerprint - : undefined, - ); - const result = evaluatePromotionEvidence({ - expected: { - ...expected, - vulnerabilityInvocationNonce: "1".repeat(64), - provenanceInvocationNonce: "2".repeat(64), - }, - localStatus: "PASS", - vulnerabilityReport: - kind === "vulnerability" ? resigned : validVulnerability, - provenanceAttestation: - kind === "provenance" ? resigned : validProvenance, - vulnerabilityTrust: trust("vulnerability-key", vulnerabilityKeys.publicKey), - provenanceTrust: trust("provenance-key", provenanceKeys.publicKey), - nowEpochMs: () => now, - }); - expect(result.status, testCase.name).toBe("FAIL_UNVERIFIED"); - expect(result.failures.join("\n"), testCase.name).toMatch(testCase.failure); - } - }, - ); - - it("canonicalizes provider fingerprints from DER SPKI across PEM wrapping and rejects Ed448", async () => { - const root = await mkdtemp(path.join(tmpdir(), "provider-fingerprint-")); - try { - const ed25519 = generateKeyPairSync("ed25519").publicKey; - const pem = ed25519.export({ type: "spki", format: "pem" }).toString(); - const body = pem.replace(/-----[^-]+-----|\s/gu, ""); - const wrapped = (width: number) => - `-----BEGIN PUBLIC KEY-----\n${body.match(new RegExp(`.{1,${width}}`, "gu"))!.join("\n")}\n-----END PUBLIC KEY-----\n`; - await writeFile(path.join(root, "a.pem"), wrapped(64)); - await writeFile(path.join(root, "b.pem"), wrapped(32)); - const first = await readProviderTrust(root, "a.pem", "fixture-key"); - const second = await readProviderTrust(root, "b.pem", "fixture-key"); - expect(first?.publicKeyFingerprint).toBe(providerPublicKeyFingerprint(ed25519)); - expect(second?.publicKeyFingerprint).toBe(first?.publicKeyFingerprint); - - const ed448 = generateKeyPairSync("ed448").publicKey; - await writeFile(root + "/ed448.pem", ed448.export({ type: "spki", format: "pem" })); - await expect(readProviderTrust(root, "ed448.pem", "fixture-key")).resolves.toBeNull(); - expect(() => providerPublicKeyFingerprint(ed448)).toThrow(/must be Ed25519/u); - } finally { - await rm(root, { recursive: true, force: true }); - } - }); - - it("captures the downloaded archive pathname exactly once in the provider supervisor", async () => { - const keys = generateKeyPairSync("ed25519"); - const expected = providerExpectedContext(); - let captureCount = 0; - let receivedEnvironment: Readonly> | undefined; - const manifest: ReleaseCandidateManifest = { - schemaVersion: 1, - distSha256: expected.candidate.distSha256, - lockfileSha256: expected.candidate.lockfileSha256, - bundleSha256: expected.candidate.bundleSha256, - files: [{ path: "pnpm-lock.yaml", bytes: 1, sha256: expected.candidate.lockfileSha256 }], - }; - const result = await superviseProviderEvidence( - { - kind: "vulnerability", - archivePath: "/downloads/candidate.tar.gz", - expectedArchiveSha256: expected.candidate.archiveSha256, - expectedRun: { - id: expected.run.id, - attempt: expected.run.attempt, - sourceRevision: expected.source.revision, - }, - trust: trust("vulnerability-key", keys.publicKey), - executeProvider: async ({ environment }) => { - receivedEnvironment = environment; - }, - captureReport: async () => Buffer.from("{}\n"), - }, - { - captureArchive: async (input) => { - captureCount += 1; - expect(input).toEqual({ - archivePath: "/downloads/candidate.tar.gz", - expectedSha256: expected.candidate.archiveSha256, - }); - return { - bytes: Buffer.from("captured archive"), - archiveSha256: expected.candidate.archiveSha256, - }; - }, - withVerifiedCandidate: (async (input: any) => - input.verify({ extractionRoot: "/captured/extraction", manifest })) as any, - verifyLocalEvidence: async () => ({ - status: "PASS", - identity: { - sourceRevision: expected.source.revision, - sourceSetSha256: expected.source.sourceSetSha256, - assessmentSha256: digest("assessment"), - secretScan: { - policySha256: digest("provider secret policy"), - sarifSha256: digest("provider secret sarif"), - scanInputSha256: digest("provider secret input"), - }, - }, - failures: [], - }), - validateUpload: (async (input: any) => { - expect("archivePath" in input).toBe(false); - return { sealed: true }; - }) as any, - randomBytes: () => Buffer.alloc(32, 0x11), - nowEpochMs: () => Date.parse("2026-08-02T01:00:00.000Z"), - }, - ); - - expect(captureCount).toBe(1); - expect(receivedEnvironment).toEqual( - expect.objectContaining({ - PROVIDER_EVIDENCE_SCHEMA_VERSION: "2", - PROVIDER_INVOCATION_NONCE: "11".repeat(32), - PROVIDER_ISSUED_AT: "2026-08-02T01:00:00.000Z", - PROVIDER_EXPIRES_AT: "2026-08-02T02:00:00.000Z", - CI_RUN_ID: expected.run.id, - CI_RUN_ATTEMPT: "1", - SOURCE_REVISION: expected.source.revision, - CANDIDATE_ARCHIVE_SHA256: expected.candidate.archiveSha256, - }), - ); - expect(result.evidence).toEqual({ sealed: true }); - }); - - it("samples provider freshness after report capture instead of reusing issuance time", async () => { - const keys = generateKeyPairSync("ed25519"); - const expected = providerExpectedContext(); - const manifest: ReleaseCandidateManifest = { - schemaVersion: 1, - distSha256: expected.candidate.distSha256, - lockfileSha256: expected.candidate.lockfileSha256, - bundleSha256: expected.candidate.bundleSha256, - files: [{ path: "pnpm-lock.yaml", bytes: 1, sha256: expected.candidate.lockfileSha256 }], - }; - const issuedSample = Date.parse("2026-08-02T01:00:00.000Z"); - const validationSample = Date.parse("2026-08-02T02:00:00.001Z"); - const samples = [issuedSample, validationSample]; - let issuedAt = ""; - await expect( - superviseProviderEvidence( - { - kind: "vulnerability", - archivePath: "/downloads/candidate.tar.gz", - expectedArchiveSha256: expected.candidate.archiveSha256, - expectedRun: { - id: expected.run.id, - attempt: expected.run.attempt, - sourceRevision: expected.source.revision, - }, - trust: trust("vulnerability-key", keys.publicKey), - executeProvider: async ({ environment }) => { - issuedAt = environment.PROVIDER_ISSUED_AT!; - }, - captureReport: async () => Buffer.from("{}\n"), - }, - { - captureArchive: async () => ({ - bytes: Buffer.from("captured archive"), - archiveSha256: expected.candidate.archiveSha256, - }), - withVerifiedCandidate: (async (input: any) => - input.verify({ extractionRoot: "/captured/extraction", manifest })) as any, - verifyLocalEvidence: async () => ({ - status: "PASS", - identity: { - sourceRevision: expected.source.revision, - sourceSetSha256: expected.source.sourceSetSha256, - assessmentSha256: digest("assessment"), - secretScan: { - policySha256: digest("provider secret policy"), - sarifSha256: digest("provider secret sarif"), - scanInputSha256: digest("provider secret input"), - }, - }, - failures: [], - }), - validateUpload: (async (input: any) => { - expect(input.nowEpochMs()).toBe(validationSample); - throw new Error("provider report expired during execution"); - }) as any, - randomBytes: () => Buffer.alloc(32, 0x33), - nowEpochMs: () => samples.shift()!, - }, - ), - ).rejects.toThrow(/expired during execution/u); - expect(issuedAt).toBe("2026-08-02T01:00:00.000Z"); - }); - - it("kills a timed-out provider but settles only after the child closes", async () => { - const child = new EventEmitter() as EventEmitter & { - kill(signal: NodeJS.Signals): boolean; - }; - let killedWith: NodeJS.Signals | undefined; - child.kill = (signal) => { - killedWith = signal; - return true; - }; - let fireTimeout: (() => void) | undefined; - let settled = false; - const running = runProviderProcess( - { executable: "/usr/bin/bwrap", arguments: [], environment: {}, timeoutMs: 1 }, - { - spawnChild: () => child as any, - setTimer: (callback) => { - fireTimeout = callback; - return 1 as any; - }, - clearTimer: () => undefined, - }, - ).finally(() => { - settled = true; - }); - fireTimeout?.(); - await Promise.resolve(); - expect(killedWith).toBe("SIGKILL"); - expect(settled).toBe(false); - child.emit("close", null, "SIGKILL"); - await expect(running).rejects.toThrow(/timed out/u); - expect(settled).toBe(true); - }); - - it("captures process-group kill errors, attempts child fallback, and settles after close", async () => { - const child = new EventEmitter() as EventEmitter & { - pid: number; - kill(signal: NodeJS.Signals): boolean; - }; - child.pid = 12_346; - let fallbackSignal: NodeJS.Signals | undefined; - child.kill = (signal) => { - fallbackSignal = signal; - return true; - }; - let fireTimeout: (() => void) | undefined; - const running = runProviderProcess( - { executable: "/usr/bin/bwrap", arguments: [], environment: {}, timeoutMs: 1 }, - { - spawnChild: () => child as any, - setTimer: (callback) => { - fireTimeout = callback; - return 1 as any; - }, - clearTimer: () => undefined, - killProcessGroup: () => { - throw Object.assign(new Error("group kill denied"), { code: "EPERM" }); - }, - }, - ); - expect(() => fireTimeout?.()).not.toThrow(); - expect(fallbackSignal).toBe("SIGKILL"); - child.emit("close", null, "SIGKILL"); - await expect(running).rejects.toThrow(/timed out.*kill failed.*close/u); - }); - - it("kills and reaps a stubborn provider process group including its descendant", async () => { - const root = await mkdtemp(path.join(tmpdir(), "provider-process-group-")); - const descendantPidPath = path.join(root, "descendant.pid"); - try { - const source = [ - "const { spawn } = require('node:child_process');", - "const { writeFileSync } = require('node:fs');", - "const child = spawn(process.execPath, ['-e', `process.on('SIGTERM', () => {}); setInterval(() => {}, 1000)`], { stdio: 'ignore' });", - "writeFileSync(process.env.DESCENDANT_PID_PATH, String(child.pid));", - "process.on('SIGTERM', () => {});", - "setInterval(() => {}, 1000);", - ].join("\n"); - const running = runProviderProcess({ - executable: process.execPath, - arguments: ["-e", source], - environment: { - PATH: process.env.PATH, - DESCENDANT_PID_PATH: descendantPidPath, - }, - timeoutMs: 250, - }); - await expect(running).rejects.toThrow(/timed out.*process close/u); - const descendantPid = Number(await readFile(descendantPidPath, "utf8")); - expect(Number.isSafeInteger(descendantPid) && descendantPid > 0).toBe(true); - expect(() => process.kill(descendantPid, 0)).toThrow(/ESRCH|no such process/u); - } finally { - await rm(root, { recursive: true, force: true }); - } - }); - - it.each(["open failure", "partial write failure"])( - "cleans finalized staging from memory when GITHUB_OUTPUT has a %s", - async (failureKind) => { - const finalized = { - stagingRoot: "/runner/promotion-run-1-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - cleanupToken: "promotion-run-1-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - runnerTempIdentity: { dev: 10, ino: 20 }, - stagingIdentity: { dev: 30, ino: 40 }, - files: [], - } as const; - let cleanupInput: unknown; - let appendCalls = 0; - const environment = { - CANDIDATE_ARCHIVE_PATH: "candidate.tar.gz", - CANDIDATE_ARCHIVE_SHA256: "a".repeat(64), - VULNERABILITY_REPORT_PATH: "vulnerability.json", - PROVENANCE_ATTESTATION_PATH: "provenance.json", - VULNERABILITY_PUBLIC_KEY_PATH: "vulnerability.pem", - VULNERABILITY_KEY_ID: "vulnerability-key", - PROVENANCE_PUBLIC_KEY_PATH: "provenance.pem", - PROVENANCE_KEY_ID: "provenance-key", - CI_RUN_ID: "run", - CI_RUN_ATTEMPT: "1", - VITE_COMMIT_SHA: "b".repeat(40), - VULNERABILITY_INVOCATION_NONCE: "c".repeat(64), - PROVENANCE_INVOCATION_NONCE: "d".repeat(64), - RUNNER_TEMP: "/runner", - GITHUB_OUTPUT: "/runner/github-output", - }; - await expect( - runStageVerifiedPromotionCli(environment, { - cwd: () => "/workspace", - finalize: async () => finalized as any, - appendOutput: async () => { - appendCalls += 1; - if (failureKind === "partial write failure") { - // The output sink accepted an unspecified prefix before rejecting. - } - throw new Error(failureKind); - }, - cleanup: async (input) => { - cleanupInput = input; - }, - writeStdout: () => undefined, - }), - ).rejects.toThrow(new RegExp(failureKind, "u")); - expect(appendCalls).toBe(1); - expect(cleanupInput).toEqual({ - runnerTempRoot: "/runner", - stagingRoot: finalized.stagingRoot, - cleanupToken: finalized.cleanupToken, - runnerTempIdentity: finalized.runnerTempIdentity, - stagingIdentity: finalized.stagingIdentity, - }); - }, - ); - - it("forces exact private staging modes in an isolated child with umask 077", async () => { - const root = await mkdtemp(path.join(tmpdir(), "promotion-umask-")); - try { - const stagerUrl = pathToFileURL( - path.join(process.cwd(), "scripts/lib/promotion-stager.ts"), - ).href; - const contractsUrl = pathToFileURL( - path.join(process.cwd(), "scripts/contracts/promotion-artifacts.ts"), - ).href; - const childPath = path.join(root, "umask-child.mjs"); - const resultPath = path.join(root, "result.json"); - await writeFile(resultPath, "{}\n", { mode: 0o600 }); - await writeFile( - childPath, - [ - `import { lstat, writeFile } from "node:fs/promises";`, - `import path from "node:path";`, - `import { createHash } from "node:crypto";`, - `import { cleanupFinalizedPromotion, publishPrivatePromotionStaging } from ${JSON.stringify(stagerUrl)};`, - `import { PROMOTED_FILE_NAMES } from ${JSON.stringify(contractsUrl)};`, - `process.umask(Number.parseInt(process.argv[2], 8));`, - `const runnerTempRoot = process.argv[3];`, - `const files = PROMOTED_FILE_NAMES.map((name) => { const bytes = Buffer.from(name); return { name, bytes, sha256: createHash("sha256").update(bytes).digest("hex") }; });`, - `const finalized = await publishPrivatePromotionStaging(runnerTempRoot, { id: "umask", attempt: 1 }, files, () => Buffer.alloc(16, 1));`, - `const directoryMode = (await lstat(finalized.stagingRoot)).mode & 0o777;`, - `const fileModes = await Promise.all(PROMOTED_FILE_NAMES.map(async (name) => (await lstat(path.join(finalized.stagingRoot, name))).mode & 0o777));`, - `await cleanupFinalizedPromotion({ runnerTempRoot, stagingRoot: finalized.stagingRoot, cleanupToken: finalized.cleanupToken, runnerTempIdentity: finalized.runnerTempIdentity, stagingIdentity: finalized.stagingIdentity });`, - `await writeFile(process.argv[4], JSON.stringify({ directoryMode, fileModes }));`, - ].join("\n"), - ); - const child = spawnSync(process.execPath, [childPath, "077", root, resultPath], { - cwd: root, - encoding: "utf8", - timeout: 30_000, - }); - expect(child.status, `${child.stdout}\n${child.stderr}`).toBe(0); - expect(JSON.parse(await readFile(resultPath, "utf8"))).toEqual({ - directoryMode: 0o700, - fileModes: [0o400, 0o400, 0o400, 0o400, 0o400], - }); - } finally { - await rm(root, { recursive: true, force: true }); - } - }); - - it("rejects a staged file unlinked and recreated after its original write", async () => { - const root = await mkdtemp(path.join(tmpdir(), "promotion-seal-recreate-")); - const files = privatePromotionFiles(); - const token = `promotion-seal-1-${"11".repeat(16)}`; - try { - await expect( - publishPrivatePromotionStaging( - root, - { id: "seal", attempt: 1 }, - files, - () => Buffer.alloc(16, 0x11), - undefined, - async (name) => { - if (name !== PROMOTED_FILE_NAMES.at(-1)) return; - const first = path.join(root, token, PROMOTED_FILE_NAMES[0]); - await rm(first); - await writeFile(first, "replacement bytes\n", { mode: 0o400 }); - }, - ), - ).rejects.toThrow(/staged.*digest|inode|seal/u); - } finally { - await rm(root, { recursive: true, force: true }); - } - }); - - it("rejects staged mode drift before returning the upload root", async () => { - const root = await mkdtemp(path.join(tmpdir(), "promotion-seal-mode-")); - const files = privatePromotionFiles(); - const token = `promotion-seal-1-${"12".repeat(16)}`; - try { - await expect( - publishPrivatePromotionStaging( - root, - { id: "seal", attempt: 1 }, - files, - () => Buffer.alloc(16, 0x12), - undefined, - async (name) => { - if (name === PROMOTED_FILE_NAMES.at(-1)) { - await chmod(path.join(root, token, PROMOTED_FILE_NAMES[0]), 0o600); - } - }, - ), - ).rejects.toThrow(/mode.*0400|staged.*mode|seal/u); - } finally { - await rm(root, { recursive: true, force: true }); - } - }); - - it("rejects staging leaf replacement between mkdir and descriptor open", async () => { - const root = await mkdtemp(path.join(tmpdir(), "promotion-preopen-replace-")); - const files = privatePromotionFiles(); - const token = `promotion-preopen-1-${"13".repeat(16)}`; - const displaced = path.join(root, `${token}-displaced`); - const replacementCanary = path.join(root, token, PROMOTED_FILE_NAMES[0]); - try { - await expect( - publishPrivatePromotionStaging( - root, - { id: "preopen", attempt: 1 }, - files, - () => Buffer.alloc(16, 0x13), - undefined, - undefined, - undefined, - async (stagingRoot) => { - await rename(stagingRoot, displaced); - await mkdir(stagingRoot, { mode: 0o700 }); - await writeFile(replacementCanary, "external replacement canary\n"); - }, - ), - ).rejects.toThrow(/staging leaf.*changed|mkdir.*open|identity/u); - await expect(readFile(replacementCanary, "utf8")).resolves.toBe( - "external replacement canary\n", - ); - await expect(readdir(displaced)).resolves.toEqual([]); - } finally { - await rm(root, { recursive: true, force: true }); - } - }); - - it("does not scan a crowded parent to recover an unverified pre-open leaf", async () => { - const root = await mkdtemp(path.join(tmpdir(), "promotion-preopen-bounded-")); - const files = privatePromotionFiles(); - const token = `promotion-preopen-bound-1-${"14".repeat(16)}`; - const displaced = path.join(root, `${token}-displaced`); - const replacementCanary = path.join(root, token, PROMOTED_FILE_NAMES[0]); - try { - for (let offset = 0; offset < 4_097; offset += 128) { - await Promise.all( - Array.from( - { length: Math.min(128, 4_097 - offset) }, - (_, index) => - mkdir( - path.join( - root, - `noise-${String(offset + index).padStart(4, "0")}`, - ), - ), - ), - ); - } - let failure: unknown; - try { - await publishPrivatePromotionStaging( - root, - { id: "preopen-bound", attempt: 1 }, - files, - () => Buffer.alloc(16, 0x14), - undefined, - undefined, - undefined, - async (stagingRoot) => { - await rename(stagingRoot, displaced); - await mkdir(stagingRoot, { mode: 0o700 }); - await writeFile(replacementCanary, "external replacement canary\n"); - }, - ); - } catch (error) { - failure = error; - } - expect(failure).toBeInstanceOf(Error); - expect(failure).not.toBeInstanceOf(AggregateError); - expect((failure as Error).message).toMatch(/staging leaf.*identity/i); - await expect(readdir(displaced)).resolves.toEqual([]); - await expect(readFile(replacementCanary, "utf8")).resolves.toBe( - "external replacement canary\n", - ); - } finally { - await rm(root, { recursive: true, force: true }); - } - }, 20_000); - - it("leaves a non-empty moved original untouched after pre-open mismatch", async () => { - const root = await mkdtemp(path.join(tmpdir(), "promotion-preopen-nonempty-")); - const files = privatePromotionFiles(); - const token = `promotion-preopen-nonempty-1-${"15".repeat(16)}`; - const displaced = path.join(root, `${token}-displaced`); - const ownedResidual = path.join(displaced, "owned-residual"); - const replacementCanary = path.join(root, token, PROMOTED_FILE_NAMES[0]); - try { - let failure: unknown; - try { - await publishPrivatePromotionStaging( - root, - { id: "preopen-nonempty", attempt: 1 }, - files, - () => Buffer.alloc(16, 0x15), - undefined, - undefined, - undefined, - async (stagingRoot) => { - await rename(stagingRoot, displaced); - await writeFile(ownedResidual, "owned residual\n"); - await mkdir(stagingRoot, { mode: 0o700 }); - await writeFile(replacementCanary, "external replacement canary\n"); - }, - ); - } catch (error) { - failure = error; - } - expect(failure).toBeInstanceOf(Error); - expect(failure).not.toBeInstanceOf(AggregateError); - expect((failure as Error).message).toMatch(/staging leaf.*identity/i); - await expect(readFile(ownedResidual, "utf8")).resolves.toBe( - "owned residual\n", - ); - await expect(readFile(replacementCanary, "utf8")).resolves.toBe( - "external replacement canary\n", - ); - } finally { - await rm(root, { recursive: true, force: true }); - } - }); - - it("does not search outside the parent for a moved unverified original", async () => { - const root = await mkdtemp(path.join(tmpdir(), "promotion-preopen-missing-")); - const outside = await mkdtemp(path.join(tmpdir(), "promotion-preopen-moved-")); - const files = privatePromotionFiles(); - const token = `promotion-preopen-missing-1-${"16".repeat(16)}`; - const displaced = path.join(outside, token); - const replacementCanary = path.join(root, token, PROMOTED_FILE_NAMES[0]); - try { - let failure: unknown; - try { - await publishPrivatePromotionStaging( - root, - { id: "preopen-missing", attempt: 1 }, - files, - () => Buffer.alloc(16, 0x16), - undefined, - undefined, - undefined, - async (stagingRoot) => { - await rename(stagingRoot, displaced); - await mkdir(stagingRoot, { mode: 0o700 }); - await writeFile(replacementCanary, "external replacement canary\n"); - }, - ); - } catch (error) { - failure = error; - } - expect(failure).toBeInstanceOf(Error); - expect(failure).not.toBeInstanceOf(AggregateError); - expect((failure as Error).message).toMatch(/staging leaf.*identity/i); - await expect(lstat(displaced)).resolves.toEqual( - expect.objectContaining({ dev: expect.any(Number), ino: expect.any(Number) }), - ); - await expect(readFile(replacementCanary, "utf8")).resolves.toBe( - "external replacement canary\n", - ); - } finally { - await rm(root, { recursive: true, force: true }); - await rm(outside, { recursive: true, force: true }); - } - }); - - it("rejects a fresh signed exact-five bundle replayed under a different expected run", async () => { - const fixture = syntheticSignedPromotionBundle(); - await expect( - verifyExactPromotionBundle(fixture.files, { - ...fixture.verification, - expected: { - ...fixture.verification.expected, - run: { id: "different-run", attempt: 1 }, - }, - }), - ).rejects.toThrow(/external expected run.*mismatch|expected promotion run/u); - }); - - it("requires every external expected identity variable at the exact promotion CLI", async () => { - const fixture = syntheticSignedPromotionBundle(); - const root = await mkdtemp(path.join(tmpdir(), "promotion-replay-cli-")); - const bundleRoot = path.join(root, "bundle"); - try { - await mkdir(bundleRoot); - for (const [name, bytes] of Object.entries(fixture.files)) { - await writeFile(path.join(bundleRoot, name), bytes); - } - await writeFile(path.join(root, "vulnerability.pem"), fixture.vulnerabilityPem); - await writeFile(path.join(root, "provenance.pem"), fixture.provenancePem); - const cliPath = path.join(process.cwd(), "scripts/verify-exact-promotion-bundle.ts"); - const baseEnvironment: NodeJS.ProcessEnv = { - ...process.env, - PROMOTION_BUNDLE_ROOT: bundleRoot, - VULNERABILITY_PUBLIC_KEY_PATH: "vulnerability.pem", - VULNERABILITY_KEY_ID: "synthetic-vulnerability", - PROVENANCE_PUBLIC_KEY_PATH: "provenance.pem", - PROVENANCE_KEY_ID: "synthetic-provenance", - EXPECTED_PROMOTION_RUN_ID: fixture.verification.expected.run.id, - EXPECTED_PROMOTION_RUN_ATTEMPT: String( - fixture.verification.expected.run.attempt, - ), - EXPECTED_PROMOTION_SOURCE_REVISION: - fixture.verification.expected.sourceRevision, - EXPECTED_PROMOTION_ARCHIVE_SHA256: - fixture.verification.expected.archiveSha256, - }; - const requiredExpected = [ - "EXPECTED_PROMOTION_RUN_ID", - "EXPECTED_PROMOTION_RUN_ATTEMPT", - "EXPECTED_PROMOTION_SOURCE_REVISION", - "EXPECTED_PROMOTION_ARCHIVE_SHA256", - ] as const; - for (const missing of requiredExpected) { - const environment = { ...baseEnvironment }; - delete environment[missing]; - const result = spawnSync(process.execPath, [cliPath], { - cwd: root, - encoding: "utf8", - env: environment, - }); - expect(result.status, missing).not.toBe(0); - expect(result.stderr, missing).toContain( - `exact promotion verification environment is missing ${missing}`, - ); - } - for (const [name, value, diagnostic] of [ - ["EXPECTED_PROMOTION_RUN_ID", "different-run", /external expected run.*mismatch/u], - ["EXPECTED_PROMOTION_RUN_ATTEMPT", "2", /external expected run.*mismatch/u], - ["EXPECTED_PROMOTION_SOURCE_REVISION", "f".repeat(40), /external expected source revision.*mismatch/u], - ["EXPECTED_PROMOTION_ARCHIVE_SHA256", "0".repeat(64), /external expected archive digest.*mismatch/u], - ] as const) { - const result = spawnSync(process.execPath, [cliPath], { - cwd: root, - encoding: "utf8", - env: { ...baseEnvironment, [name]: value }, - }); - expect(result.status, name).not.toBe(0); - expect(result.stderr, name).toMatch(diagnostic); - } - } finally { - await rm(root, { recursive: true, force: true }); - } - }, PROCESS_HEAVY_TIMEOUT_MS); }); - -function providerExpectedContext() { - return { - run: { id: "run-42", attempt: 1 }, - source: { revision: "b".repeat(40), sourceSetSha256: digest("provider source") }, - candidate: { - archiveSha256: digest("archive"), - bundleSha256: digest("bundle"), - distSha256: digest("provider dist"), - lockfileSha256: digest("provider lockfile"), - }, - secretScanAttestation: { - status: "PASS" as const, - localEvidenceAssessmentSha256: digest("provider assessment"), - sourceSetSha256: digest("provider source"), - policySha256: digest("provider secret policy"), - sarifSha256: digest("provider secret sarif"), - scanInputSha256: digest("provider secret input"), - }, - } as const; -} - -function privatePromotionFiles() { - return PROMOTED_FILE_NAMES.map((name) => { - const bytes = Buffer.from(`${name}\n`); - return { name, bytes, sha256: digestBytes(bytes) }; - }); -} - -function syntheticSignedPromotionBundle() { - const vulnerabilityKeys = generateKeyPairSync("ed25519"); - const provenanceKeys = generateKeyPairSync("ed25519"); - const archiveBytes = Buffer.from("synthetic signed replay archive\n"); - const run = { id: "signed-run", attempt: 1 } as const; - const source = { - revision: "a".repeat(40), - sourceSetSha256: digest("synthetic-source-set"), - } as const; - const candidate = { - archiveSha256: digestBytes(archiveBytes), - bundleSha256: digest("synthetic-bundle"), - distSha256: digest("synthetic-dist"), - lockfileSha256: digest("synthetic-lock"), - } as const; - const vulnerability = signedProviderV2( - { - schemaVersion: 2, - evidenceType: "vulnerability-report", - provider: "synthetic-vulnerability-provider", - issuedAt: "2026-08-02T01:00:00.000Z", - expiresAt: "2026-08-02T02:00:00.000Z", - run: { ...run, invocationNonce: "1".repeat(64) }, - source, - candidate, - secretScanAttestation: { - status: "PASS", - localEvidenceAssessmentSha256: digest("synthetic-assessment"), - sourceSetSha256: source.sourceSetSha256, - policySha256: digest("synthetic-policy"), - sarifSha256: digest("synthetic-sarif"), - scanInputSha256: digest("synthetic-scan-input"), - }, - findings: [], - }, - "synthetic-vulnerability", - vulnerabilityKeys.publicKey, - vulnerabilityKeys.privateKey, - ); - const provenance = signedProviderV2( - { - schemaVersion: 2, - evidenceType: "provenance-attestation", - provider: "synthetic-provenance-provider", - signer: "synthetic-signer", - issuedAt: "2026-08-02T01:00:00.000Z", - expiresAt: "2026-08-02T02:00:00.000Z", - run: { ...run, invocationNonce: "2".repeat(64) }, - source, - candidate, - subject: { name: "dist", digest: { sha256: candidate.distSha256 } }, - }, - "synthetic-provenance", - provenanceKeys.publicKey, - provenanceKeys.privateKey, - ); - const vulnerabilityBytes = Buffer.from(`${JSON.stringify(vulnerability)}\n`); - const provenanceBytes = Buffer.from(`${JSON.stringify(provenance)}\n`); - const vulnerabilityTrust = trust("synthetic-vulnerability", vulnerabilityKeys.publicKey); - const provenanceTrust = trust("synthetic-provenance", provenanceKeys.publicKey); - const providerEvidence = { - vulnerabilityReportSha256: digestBytes(vulnerabilityBytes), - provenanceAttestationSha256: digestBytes(provenanceBytes), - vulnerabilityInvocationNonce: "1".repeat(64), - provenanceInvocationNonce: "2".repeat(64), - vulnerabilityKeyId: vulnerabilityTrust.keyId, - vulnerabilityKeyFingerprint: vulnerabilityTrust.publicKeyFingerprint, - provenanceKeyId: provenanceTrust.keyId, - provenanceKeyFingerprint: provenanceTrust.publicKeyFingerprint, - secretScanAttestation: vulnerability.secretScanAttestation, - }; - const common = { - schemaVersion: 3, - verifiedAt: "2026-08-02T01:00:00.000Z", - status: "PASS", - verifier: { - id: "tech-log-frontend/promotion-verifier", - version: "3", - }, - run, - source, - candidate, - providerEvidence, - trustPolicySha256: trustPolicySha256({ vulnerabilityTrust, provenanceTrust }), - failures: [], - }; - const providerBytes = Buffer.from( - `${JSON.stringify({ - ...common, - artifactType: "provider-verification", - vulnerabilityStatus: "PASS", - provenanceAttestationStatus: "PASS", - }, null, 2)}\n`, - ); - const promotionBytes = Buffer.from( - `${JSON.stringify({ - ...common, - artifactType: "promotion-verification", - localEvidenceStatus: "PASS", - localEvidenceAssessmentSha256: digest("synthetic-assessment"), - providerVerificationSha256: digestBytes(providerBytes), - }, null, 2)}\n`, - ); - return { - files: { - "release-candidate.tar.gz": archiveBytes, - "vulnerability-report.json": vulnerabilityBytes, - "provenance-attestation.json": provenanceBytes, - "provider-verification.json": providerBytes, - "promotion-verification.json": promotionBytes, - }, - verification: { - vulnerabilityTrust, - provenanceTrust, - nowEpochMs: () => Date.parse("2026-08-02T01:00:00.000Z"), - expected: { - run, - sourceRevision: source.revision, - sourceSetSha256: source.sourceSetSha256, - archiveSha256: candidate.archiveSha256, - bundleSha256: candidate.bundleSha256, - distSha256: candidate.distSha256, - lockfileSha256: candidate.lockfileSha256, - }, - }, - vulnerabilityPem: vulnerabilityKeys.publicKey.export({ type: "spki", format: "pem" }), - provenancePem: provenanceKeys.publicKey.export({ type: "spki", format: "pem" }), - }; -} - -function fingerprint(publicKey: KeyObject): string { - return `sha256:${createHash("sha256") - .update(publicKey.export({ type: "spki", format: "der" })) - .digest("hex")}`; -} - -function trust(keyId: string, publicKey: KeyObject) { - return { keyId, publicKey, publicKeyFingerprint: fingerprint(publicKey) }; -} - -function signedProviderV2( - unsigned: Record, - keyId: string, - publicKey: KeyObject, - privateKey: KeyObject, - fingerprintOverride?: string, -): Record { - const { signature: existingSignature, ...payload } = unsigned; - const value = { - ...payload, - signature: { - algorithm: "Ed25519" as const, - keyId, - publicKeyFingerprint: - fingerprintOverride ?? - (existingSignature && typeof existingSignature === "object" && - "publicKeyFingerprint" in existingSignature - ? String(existingSignature.publicKeyFingerprint) - : fingerprint(publicKey)), - value: "", - }, - }; - value.signature.value = sign( - null, - providerEvidenceSignaturePayload(value), - privateKey, - ).toString("base64"); - return value; -} - -function providerUnsigned( - kind: "vulnerability" | "provenance", - expected: ReturnType, -): Record { - const common = { - source: expected.source, - candidate: expected.candidate, - schemaVersion: 2, - evidenceType: - kind === "vulnerability" - ? "vulnerability-report" - : "provenance-attestation", - provider: `fixture-${kind}`, - issuedAt: "2026-08-02T01:00:00.000Z", - expiresAt: "2026-08-02T02:00:00.000Z", - run: { - ...expected.run, - invocationNonce: kind === "vulnerability" ? "1".repeat(64) : "2".repeat(64), - }, - }; - return kind === "vulnerability" - ? { - ...common, - secretScanAttestation: expected.secretScanAttestation, - findings: [], - } - : { - ...common, - signer: "fixture-workload", - subject: { - name: "dist", - digest: { sha256: expected.candidate.distSha256 }, - }, - }; -} - -async function createArchivedAssessmentFixture(): Promise<{ - root: string; - manifest: ReleaseCandidateManifest; - assessmentSha256: string; -}> { - const root = await mkdtemp(path.join(tmpdir(), "archived-assessment-")); - const sourceRevision = "a".repeat(40); - const sourceSetSha256 = digest("source set"); - const releaseManifestBytes = Buffer.from( - `${JSON.stringify({ - schemaVersion: 1, - appVersion: "1.0.0", - buildId: "build-1", - commitSha: sourceRevision, - configSchemaVersion: "1", - apiContractVersion: "1", - assetManifestHash: digest("vite manifest"), - releaseId: "release-1", - builtAt: "2026-08-02T00:00:00.000Z", - routeChunks: { home: "assets/home.js" }, - })}\n`, - ); - const distInputs = [ - { path: "dist/app.js", bytes: Buffer.byteLength("app\n"), sha256: digest("app\n"), gzipBytes: 0 }, - { - path: "dist/release-manifest.json", - bytes: releaseManifestBytes.byteLength, - sha256: digestBytes(releaseManifestBytes), - gzipBytes: 0, - }, - ]; - const candidateDist = distSha256(distInputs); - const sbomBytes = Buffer.from( - `${JSON.stringify({ - bomFormat: "CycloneDX", - specVersion: "1.6", - serialNumber: "urn:uuid:00000000-0000-4000-8000-000000000001", - version: 1, - metadata: { - component: { type: "application", name: "fixture", version: "1.0.0" }, - properties: [], - }, - components: [], - dependencies: [], - })}\n`, - ); - const sbomSha256 = digestBytes(sbomBytes); - const lockfileBytes = Buffer.from("lockfile\n"); - const lockfileDigest = digestBytes(lockfileBytes); - const buildManifest = { - schemaVersion: 1, - buildId: "build-1", - commitSha: sourceRevision, - releaseId: "release-1", - moduleInventoryHash: digest("module inventory"), - generatedAt: "2026-08-02T00:00:00.000Z", - buildContext: { - nodeVersion: "v24.0.0", - packageManagerVersion: "11.0.0", - runnerImage: "linux-x64", - sourceDateEpoch: "1785638400", - }, - outputs: { - directory: "dist", - viteManifest: "dist/.vite/manifest.json", - moduleInventory: "artifacts/quality/vite-module-inventory.json", - routeChunks: { home: "assets/home.js" }, - runtimeConfigSchema: "dist/runtime-config.schema.json", - }, - }; - const provenance = { - _type: "https://in-toto.io/Statement/v1", - subject: [{ name: "dist", digest: { sha256: candidateDist } }], - predicateType: "https://slsa.dev/provenance/v1", - predicate: { - buildDefinition: { - buildType: "https://vite.dev/build/v1", - externalParameters: {}, - internalParameters: {}, - resolvedDependencies: [ - { uri: "pnpm-lock.yaml", digest: { sha256: lockfileDigest } }, - ], - }, - runDetails: { - builder: { id: "fixture-builder" }, - metadata: { invocationId: "LOCAL_UNSIGNED" }, - }, - materials: { lockfileSha256: lockfileDigest, sourceSetSha256, sbomSha256 }, - }, - }; - const supplyVerification = { - schemaVersion: 1, - localStatus: "PASS", - promotionStatus: "FAIL_UNVERIFIED", - lockfileSha256: lockfileDigest, - sourceSetSha256, - distSha256: candidateDist, - sbomSha256, - dependencyDiff: { added: [], removed: [], changed: [], upgrades: [] }, - highRiskReview: [], - vulnerabilityStatus: "FAIL_UNVERIFIED", - provenanceAttestationStatus: "FAIL_UNVERIFIED", - failures: [], - }; - const members = new Map([ - ["dist/app.js", Buffer.from("app\n")], - ["dist/release-manifest.json", releaseManifestBytes], - ["pnpm-lock.yaml", lockfileBytes], - ["artifacts/release/build-manifest.json", Buffer.from(`${JSON.stringify(buildManifest)}\n`)], - ["artifacts/release/provenance.json", Buffer.from(`${JSON.stringify(provenance)}\n`)], - [ - "artifacts/security/supply-chain-verification.json", - Buffer.from(`${JSON.stringify(supplyVerification)}\n`), - ], - ["artifacts/release/sbom.cdx.json", sbomBytes], - ]); - const evidenceInputs = [...members.entries()] - .map(([memberPath, bytes]) => ({ - path: memberPath, - bytes: bytes.byteLength, - sha256: digestBytes(bytes), - })) - .sort((left, right) => (left.path < right.path ? -1 : left.path > right.path ? 1 : 0)); - const policyPaths = [ - "config/security/dependency-baseline.approval.json", - "config/security/dependency-baseline.json", - "config/security/dependency-change-evidence.json", - "config/security/dependency-policy.json", - "config/security/secret-scan-policy.json", - "config/security/vulnerability-exceptions.json", - "config/security/vulnerability-policy.json", - "schemas/artifacts/build-manifest.schema.json", - "schemas/artifacts/dependency-inventory.schema.json", - "schemas/artifacts/supply-chain-verification.schema.json", - "scripts/contracts/release-artifacts.ts", - "scripts/create-release-candidate.ts", - "scripts/generate-supply-chain.ts", - "scripts/lib/build-manifest-outputs.ts", - "scripts/lib/json-schema.ts", - "scripts/lib/local-policy-evidence.ts", - "scripts/lib/local-release-evidence.ts", - "scripts/lib/release-candidate.ts", - "scripts/lib/release-input-evidence.ts", - "scripts/lib/release-runtime-coherence.ts", - "scripts/lib/repository-file-inventory.ts", - "scripts/lib/secret-scan-evaluator.ts", - "scripts/lib/secret-scan-policy.ts", - "scripts/lib/secret-scan.ts", - "scripts/lib/supply-chain.ts", - "scripts/lib/validated-json-artifact.ts", - "scripts/lib/vite-route-chunks.ts", - "src/contracts/release-artifacts.ts", - "src/features/installed-contract-contributions.ts", - "src/features/installed-feature-contracts.ts", - ]; - const sbomRow = evidenceInputs.find( - ({ path: memberPath }) => memberPath === "artifacts/release/sbom.cdx.json", - )!; - const policyInputs = policyPaths.map((policyPath) => ({ - path: policyPath, - bytes: 2, - sha256: digest(`policy:${policyPath}`), - })); - const verifierPaths = new Set([ - "scripts/contracts/release-artifacts.ts", - "scripts/create-release-candidate.ts", - "scripts/generate-supply-chain.ts", - "scripts/lib/build-manifest-outputs.ts", - "scripts/lib/json-schema.ts", - "scripts/lib/local-policy-evidence.ts", - "scripts/lib/local-release-evidence.ts", - "scripts/lib/release-candidate.ts", - "scripts/lib/release-input-evidence.ts", - "scripts/lib/release-runtime-coherence.ts", - "scripts/lib/repository-file-inventory.ts", - "scripts/lib/secret-scan-evaluator.ts", - "scripts/lib/secret-scan-policy.ts", - "scripts/lib/secret-scan.ts", - "scripts/lib/supply-chain.ts", - "scripts/lib/validated-json-artifact.ts", - "scripts/lib/vite-route-chunks.ts", - "src/contracts/release-artifacts.ts", - "src/features/installed-contract-contributions.ts", - "src/features/installed-feature-contracts.ts", - ]); - const assessment = localEvidenceAssessmentArtifactSchema.parse({ - ...passingAssessment(), - verifier: { - id: "tech-log-frontend/local-evidence-verifier", - version: "1", - sourceSha256: supplyChainDigest( - policyInputs.filter(({ path: policyPath }) => verifierPaths.has(policyPath)), - ), - }, - source: { revision: sourceRevision, sourceSetSha256 }, - candidate: { - distSha256: candidateDist, - lockfileSha256: evidenceInputs.find(({ path: memberPath }) => memberPath === "pnpm-lock.yaml")! - .sha256, - sbomSha256: sbomRow.sha256, - }, - policyInputs, - evidenceInputs, - }); - const assessmentBytes = Buffer.from(`${JSON.stringify(assessment)}\n`); - members.set(LOCAL_EVIDENCE_ASSESSMENT_PATH, assessmentBytes); - for (const [memberPath, bytes] of members) { - await mkdir(path.dirname(path.join(root, memberPath)), { recursive: true }); - await writeFile(path.join(root, memberPath), bytes); - } - const files = [...members.entries()] - .map(([memberPath, bytes]) => ({ - path: memberPath, - bytes: bytes.byteLength, - sha256: digestBytes(bytes), - })) - .sort((left, right) => (left.path < right.path ? -1 : left.path > right.path ? 1 : 0)); - const manifest: ReleaseCandidateManifest = { - schemaVersion: 1, - distSha256: assessment.candidate.distSha256, - lockfileSha256: assessment.candidate.lockfileSha256, - bundleSha256: supplyChainDigest(files), - files, - }; - await mkdir(path.join(root, "artifacts/release"), { recursive: true }); - await writeFile( - path.join(root, "artifacts/release/release-candidate.json"), - `${JSON.stringify(manifest)}\n`, - ); - return { root, manifest, assessmentSha256: digestBytes(assessmentBytes) }; -} diff --git a/tests/unit/security-promotion-staging.test.ts b/tests/unit/security-promotion-staging.test.ts new file mode 100644 index 0000000..69ee88f --- /dev/null +++ b/tests/unit/security-promotion-staging.test.ts @@ -0,0 +1,370 @@ +import { createHash } from "node:crypto"; +import { spawnSync } from "node:child_process"; +import { + chmod, + lstat, + mkdir, + mkdtemp, + readFile, + readdir, + rename, + rm, + writeFile, +} from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { pathToFileURL } from "node:url"; + +import { describe, expect, it } from "vitest"; + +import { PROMOTED_FILE_NAMES } from "../../scripts/contracts/promotion-artifacts.ts"; +import { publishPrivatePromotionStaging } from "../../scripts/lib/promotion-stager.ts"; +import { verifyExactPromotionBundle } from "../../scripts/lib/exact-promotion-bundle.ts"; +import { + PROCESS_HEAVY_TIMEOUT_MS, + privatePromotionFiles, + syntheticSignedPromotionBundle, +} from "./security-followup-fixture.ts"; + +describe("security private promotion staging contracts", () => { + it("forces exact private staging modes in an isolated child with umask 077", async () => { + const root = await mkdtemp(path.join(tmpdir(), "promotion-umask-")); + try { + const stagerUrl = pathToFileURL( + path.join(process.cwd(), "scripts/lib/promotion-stager.ts"), + ).href; + const contractsUrl = pathToFileURL( + path.join(process.cwd(), "scripts/contracts/promotion-artifacts.ts"), + ).href; + const childPath = path.join(root, "umask-child.mjs"); + const resultPath = path.join(root, "result.json"); + await writeFile(resultPath, "{}\n", { mode: 0o600 }); + await writeFile( + childPath, + [ + `import { lstat, writeFile } from "node:fs/promises";`, + `import path from "node:path";`, + `import { createHash } from "node:crypto";`, + `import { cleanupFinalizedPromotion, publishPrivatePromotionStaging } from ${JSON.stringify(stagerUrl)};`, + `import { PROMOTED_FILE_NAMES } from ${JSON.stringify(contractsUrl)};`, + `process.umask(Number.parseInt(process.argv[2], 8));`, + `const runnerTempRoot = process.argv[3];`, + `const files = PROMOTED_FILE_NAMES.map((name) => { const bytes = Buffer.from(name); return { name, bytes, sha256: createHash("sha256").update(bytes).digest("hex") }; });`, + `const finalized = await publishPrivatePromotionStaging(runnerTempRoot, { id: "umask", attempt: 1 }, files, () => Buffer.alloc(16, 1));`, + `const directoryMode = (await lstat(finalized.stagingRoot)).mode & 0o777;`, + `const fileModes = await Promise.all(PROMOTED_FILE_NAMES.map(async (name) => (await lstat(path.join(finalized.stagingRoot, name))).mode & 0o777));`, + `await cleanupFinalizedPromotion({ runnerTempRoot, stagingRoot: finalized.stagingRoot, cleanupToken: finalized.cleanupToken, runnerTempIdentity: finalized.runnerTempIdentity, stagingIdentity: finalized.stagingIdentity });`, + `await writeFile(process.argv[4], JSON.stringify({ directoryMode, fileModes }));`, + ].join("\n"), + ); + const child = spawnSync(process.execPath, [childPath, "077", root, resultPath], { + cwd: root, + encoding: "utf8", + timeout: 30_000, + }); + expect(child.status, `${child.stdout}\n${child.stderr}`).toBe(0); + expect(JSON.parse(await readFile(resultPath, "utf8"))).toEqual({ + directoryMode: 0o700, + fileModes: [0o400, 0o400, 0o400, 0o400, 0o400], + }); + } finally { + await rm(root, { recursive: true, force: true }); + } + }); + + it("rejects a staged file unlinked and recreated after its original write", async () => { + const root = await mkdtemp(path.join(tmpdir(), "promotion-seal-recreate-")); + const files = privatePromotionFiles(); + const token = `promotion-seal-1-${"11".repeat(16)}`; + try { + await expect( + publishPrivatePromotionStaging( + root, + { id: "seal", attempt: 1 }, + files, + () => Buffer.alloc(16, 0x11), + undefined, + async (name) => { + if (name !== PROMOTED_FILE_NAMES.at(-1)) return; + const first = path.join(root, token, PROMOTED_FILE_NAMES[0]); + await rm(first); + await writeFile(first, "replacement bytes\n", { mode: 0o400 }); + }, + ), + ).rejects.toThrow(/staged.*digest|inode|seal/u); + } finally { + await rm(root, { recursive: true, force: true }); + } + }); + + it("rejects staged mode drift before returning the upload root", async () => { + const root = await mkdtemp(path.join(tmpdir(), "promotion-seal-mode-")); + const files = privatePromotionFiles(); + const token = `promotion-seal-1-${"12".repeat(16)}`; + try { + await expect( + publishPrivatePromotionStaging( + root, + { id: "seal", attempt: 1 }, + files, + () => Buffer.alloc(16, 0x12), + undefined, + async (name) => { + if (name === PROMOTED_FILE_NAMES.at(-1)) { + await chmod(path.join(root, token, PROMOTED_FILE_NAMES[0]), 0o600); + } + }, + ), + ).rejects.toThrow(/mode.*0400|staged.*mode|seal/u); + } finally { + await rm(root, { recursive: true, force: true }); + } + }); + + it("rejects staging leaf replacement between mkdir and descriptor open", async () => { + const root = await mkdtemp(path.join(tmpdir(), "promotion-preopen-replace-")); + const files = privatePromotionFiles(); + const token = `promotion-preopen-1-${"13".repeat(16)}`; + const displaced = path.join(root, `${token}-displaced`); + const replacementCanary = path.join(root, token, PROMOTED_FILE_NAMES[0]); + try { + await expect( + publishPrivatePromotionStaging( + root, + { id: "preopen", attempt: 1 }, + files, + () => Buffer.alloc(16, 0x13), + undefined, + undefined, + undefined, + async (stagingRoot) => { + await rename(stagingRoot, displaced); + await mkdir(stagingRoot, { mode: 0o700 }); + await writeFile(replacementCanary, "external replacement canary\n"); + }, + ), + ).rejects.toThrow(/staging leaf.*changed|mkdir.*open|identity/u); + await expect(readFile(replacementCanary, "utf8")).resolves.toBe( + "external replacement canary\n", + ); + await expect(readdir(displaced)).resolves.toEqual([]); + } finally { + await rm(root, { recursive: true, force: true }); + } + }); + + it("does not scan a crowded parent to recover an unverified pre-open leaf", async () => { + const root = await mkdtemp(path.join(tmpdir(), "promotion-preopen-bounded-")); + const files = privatePromotionFiles(); + const token = `promotion-preopen-bound-1-${"14".repeat(16)}`; + const displaced = path.join(root, `${token}-displaced`); + const replacementCanary = path.join(root, token, PROMOTED_FILE_NAMES[0]); + try { + for (let offset = 0; offset < 4_097; offset += 128) { + await Promise.all( + Array.from( + { length: Math.min(128, 4_097 - offset) }, + (_, index) => + mkdir( + path.join( + root, + `noise-${String(offset + index).padStart(4, "0")}`, + ), + ), + ), + ); + } + let failure: unknown; + try { + await publishPrivatePromotionStaging( + root, + { id: "preopen-bound", attempt: 1 }, + files, + () => Buffer.alloc(16, 0x14), + undefined, + undefined, + undefined, + async (stagingRoot) => { + await rename(stagingRoot, displaced); + await mkdir(stagingRoot, { mode: 0o700 }); + await writeFile(replacementCanary, "external replacement canary\n"); + }, + ); + } catch (error) { + failure = error; + } + expect(failure).toBeInstanceOf(Error); + expect(failure).not.toBeInstanceOf(AggregateError); + expect((failure as Error).message).toMatch(/staging leaf.*identity/i); + await expect(readdir(displaced)).resolves.toEqual([]); + await expect(readFile(replacementCanary, "utf8")).resolves.toBe( + "external replacement canary\n", + ); + } finally { + await rm(root, { recursive: true, force: true }); + } + }, 20_000); + + it("leaves a non-empty moved original untouched after pre-open mismatch", async () => { + const root = await mkdtemp(path.join(tmpdir(), "promotion-preopen-nonempty-")); + const files = privatePromotionFiles(); + const token = `promotion-preopen-nonempty-1-${"15".repeat(16)}`; + const displaced = path.join(root, `${token}-displaced`); + const ownedResidual = path.join(displaced, "owned-residual"); + const replacementCanary = path.join(root, token, PROMOTED_FILE_NAMES[0]); + try { + let failure: unknown; + try { + await publishPrivatePromotionStaging( + root, + { id: "preopen-nonempty", attempt: 1 }, + files, + () => Buffer.alloc(16, 0x15), + undefined, + undefined, + undefined, + async (stagingRoot) => { + await rename(stagingRoot, displaced); + await writeFile(ownedResidual, "owned residual\n"); + await mkdir(stagingRoot, { mode: 0o700 }); + await writeFile(replacementCanary, "external replacement canary\n"); + }, + ); + } catch (error) { + failure = error; + } + expect(failure).toBeInstanceOf(Error); + expect(failure).not.toBeInstanceOf(AggregateError); + expect((failure as Error).message).toMatch(/staging leaf.*identity/i); + await expect(readFile(ownedResidual, "utf8")).resolves.toBe( + "owned residual\n", + ); + await expect(readFile(replacementCanary, "utf8")).resolves.toBe( + "external replacement canary\n", + ); + } finally { + await rm(root, { recursive: true, force: true }); + } + }); + + it("does not search outside the parent for a moved unverified original", async () => { + const root = await mkdtemp(path.join(tmpdir(), "promotion-preopen-missing-")); + const outside = await mkdtemp(path.join(tmpdir(), "promotion-preopen-moved-")); + const files = privatePromotionFiles(); + const token = `promotion-preopen-missing-1-${"16".repeat(16)}`; + const displaced = path.join(outside, token); + const replacementCanary = path.join(root, token, PROMOTED_FILE_NAMES[0]); + try { + let failure: unknown; + try { + await publishPrivatePromotionStaging( + root, + { id: "preopen-missing", attempt: 1 }, + files, + () => Buffer.alloc(16, 0x16), + undefined, + undefined, + undefined, + async (stagingRoot) => { + await rename(stagingRoot, displaced); + await mkdir(stagingRoot, { mode: 0o700 }); + await writeFile(replacementCanary, "external replacement canary\n"); + }, + ); + } catch (error) { + failure = error; + } + expect(failure).toBeInstanceOf(Error); + expect(failure).not.toBeInstanceOf(AggregateError); + expect((failure as Error).message).toMatch(/staging leaf.*identity/i); + await expect(lstat(displaced)).resolves.toEqual( + expect.objectContaining({ dev: expect.any(Number), ino: expect.any(Number) }), + ); + await expect(readFile(replacementCanary, "utf8")).resolves.toBe( + "external replacement canary\n", + ); + } finally { + await rm(root, { recursive: true, force: true }); + await rm(outside, { recursive: true, force: true }); + } + }); + + it("rejects a fresh signed exact-five bundle replayed under a different expected run", async () => { + const fixture = syntheticSignedPromotionBundle(); + await expect( + verifyExactPromotionBundle(fixture.files, { + ...fixture.verification, + expected: { + ...fixture.verification.expected, + run: { id: "different-run", attempt: 1 }, + }, + }), + ).rejects.toThrow(/external expected run.*mismatch|expected promotion run/u); + }); + + it("requires every external expected identity variable at the exact promotion CLI", async () => { + const fixture = syntheticSignedPromotionBundle(); + const root = await mkdtemp(path.join(tmpdir(), "promotion-replay-cli-")); + const bundleRoot = path.join(root, "bundle"); + try { + await mkdir(bundleRoot); + for (const [name, bytes] of Object.entries(fixture.files)) { + await writeFile(path.join(bundleRoot, name), bytes); + } + await writeFile(path.join(root, "vulnerability.pem"), fixture.vulnerabilityPem); + await writeFile(path.join(root, "provenance.pem"), fixture.provenancePem); + const cliPath = path.join(process.cwd(), "scripts/verify-exact-promotion-bundle.ts"); + const baseEnvironment: NodeJS.ProcessEnv = { + ...process.env, + PROMOTION_BUNDLE_ROOT: bundleRoot, + VULNERABILITY_PUBLIC_KEY_PATH: "vulnerability.pem", + VULNERABILITY_KEY_ID: "synthetic-vulnerability", + PROVENANCE_PUBLIC_KEY_PATH: "provenance.pem", + PROVENANCE_KEY_ID: "synthetic-provenance", + EXPECTED_PROMOTION_RUN_ID: fixture.verification.expected.run.id, + EXPECTED_PROMOTION_RUN_ATTEMPT: String( + fixture.verification.expected.run.attempt, + ), + EXPECTED_PROMOTION_SOURCE_REVISION: + fixture.verification.expected.sourceRevision, + EXPECTED_PROMOTION_ARCHIVE_SHA256: + fixture.verification.expected.archiveSha256, + }; + const requiredExpected = [ + "EXPECTED_PROMOTION_RUN_ID", + "EXPECTED_PROMOTION_RUN_ATTEMPT", + "EXPECTED_PROMOTION_SOURCE_REVISION", + "EXPECTED_PROMOTION_ARCHIVE_SHA256", + ] as const; + for (const missing of requiredExpected) { + const environment = { ...baseEnvironment }; + delete environment[missing]; + const result = spawnSync(process.execPath, [cliPath], { + cwd: root, + encoding: "utf8", + env: environment, + }); + expect(result.status, missing).not.toBe(0); + expect(result.stderr, missing).toContain( + `exact promotion verification environment is missing ${missing}`, + ); + } + for (const [name, value, diagnostic] of [ + ["EXPECTED_PROMOTION_RUN_ID", "different-run", /external expected run.*mismatch/u], + ["EXPECTED_PROMOTION_RUN_ATTEMPT", "2", /external expected run.*mismatch/u], + ["EXPECTED_PROMOTION_SOURCE_REVISION", "f".repeat(40), /external expected source revision.*mismatch/u], + ["EXPECTED_PROMOTION_ARCHIVE_SHA256", "0".repeat(64), /external expected archive digest.*mismatch/u], + ] as const) { + const result = spawnSync(process.execPath, [cliPath], { + cwd: root, + encoding: "utf8", + env: { ...baseEnvironment, [name]: value }, + }); + expect(result.status, name).not.toBe(0); + expect(result.stderr, name).toMatch(diagnostic); + } + } finally { + await rm(root, { recursive: true, force: true }); + } + }, PROCESS_HEAVY_TIMEOUT_MS); +}); diff --git a/tests/unit/security-provider-evidence.test.ts b/tests/unit/security-provider-evidence.test.ts new file mode 100644 index 0000000..778498b --- /dev/null +++ b/tests/unit/security-provider-evidence.test.ts @@ -0,0 +1,708 @@ +import { generateKeyPairSync } from "node:crypto"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { EventEmitter } from "node:events"; + +import { describe, expect, it } from "vitest"; + +import { + evaluatePromotionEvidence, + providerPublicKeyFingerprint, + validateProviderEvidence, +} from "../../scripts/lib/provider-evidence.ts"; +import { readProviderTrust } from "../../scripts/lib/provider-trust.ts"; +import { superviseProviderEvidence } from "../../scripts/lib/provider-supervisor.ts"; +import { runProviderProcess } from "../../scripts/lib/provider-process-runner.ts"; +import { runStageVerifiedPromotionCli } from "../../scripts/lib/stage-verified-promotion-cli.ts"; +import type { ReleaseCandidateManifest } from "../../scripts/lib/release-candidate.ts"; +import { + digest, + providerExpectedContext, + providerUnsigned, + signedProviderV2, + trust, +} from "./security-followup-fixture.ts"; + +describe("security provider evidence contracts", () => { + it("accepts signed provider v2 evidence only for the exact run, source, archive, and nonce", () => { + const now = Date.parse("2026-08-02T01:00:00.000Z"); + const vulnerabilityKeys = generateKeyPairSync("ed25519"); + const provenanceKeys = generateKeyPairSync("ed25519"); + const expected = providerExpectedContext(); + const vulnerability = signedProviderV2( + { + source: expected.source, + candidate: expected.candidate, + schemaVersion: 2, + evidenceType: "vulnerability-report", + provider: "fixture-vulnerability", + issuedAt: "2026-08-02T01:00:00.000Z", + expiresAt: "2026-08-02T02:00:00.000Z", + run: { ...expected.run, invocationNonce: "1".repeat(64) }, + secretScanAttestation: expected.secretScanAttestation, + findings: [], + }, + "vulnerability-key", + vulnerabilityKeys.publicKey, + vulnerabilityKeys.privateKey, + ); + const provenance = signedProviderV2( + { + source: expected.source, + candidate: expected.candidate, + schemaVersion: 2, + evidenceType: "provenance-attestation", + provider: "fixture-provenance", + signer: "fixture-workload", + issuedAt: "2026-08-02T01:00:00.000Z", + expiresAt: "2026-08-02T02:00:00.000Z", + run: { ...expected.run, invocationNonce: "2".repeat(64) }, + subject: { name: "dist", digest: { sha256: expected.candidate.distSha256 } }, + }, + "provenance-key", + provenanceKeys.publicKey, + provenanceKeys.privateKey, + ); + const result = evaluatePromotionEvidence({ + expected: { + ...expected, + vulnerabilityInvocationNonce: "1".repeat(64), + provenanceInvocationNonce: "2".repeat(64), + }, + localStatus: "PASS", + vulnerabilityReport: vulnerability, + provenanceAttestation: provenance, + vulnerabilityTrust: trust("vulnerability-key", vulnerabilityKeys.publicKey), + provenanceTrust: trust("provenance-key", provenanceKeys.publicKey), + nowEpochMs: () => now, + }); + + expect(result).toEqual({ + status: "PASS", + vulnerabilityStatus: "PASS", + provenanceAttestationStatus: "PASS", + failures: [], + }); + const replayed = evaluatePromotionEvidence({ + expected: { + ...expected, + run: { id: expected.run.id, attempt: 2 }, + vulnerabilityInvocationNonce: "1".repeat(64), + provenanceInvocationNonce: "2".repeat(64), + }, + localStatus: "PASS", + vulnerabilityReport: vulnerability, + provenanceAttestation: provenance, + vulnerabilityTrust: trust("vulnerability-key", vulnerabilityKeys.publicKey), + provenanceTrust: trust("provenance-key", provenanceKeys.publicKey), + nowEpochMs: () => now, + }); + expect(replayed.status).toBe("FAIL_UNVERIFIED"); + expect(replayed.failures).toEqual( + expect.arrayContaining([ + "vulnerability report run identity mismatch", + "provenance attestation run identity mismatch", + ]), + ); + }); + + it("rejects a signed vulnerability PASS when the captured SARIF attestation differs", () => { + const keys = generateKeyPairSync("ed25519"); + const expected = providerExpectedContext(); + const secretScanAttestation = { + status: "PASS" as const, + localEvidenceAssessmentSha256: digest("assessment"), + sourceSetSha256: expected.source.sourceSetSha256, + policySha256: digest("secret policy"), + sarifSha256: digest("real sarif"), + scanInputSha256: digest("scan input"), + }; + const report = signedProviderV2( + { + schemaVersion: 2, + evidenceType: "vulnerability-report", + provider: "fixture-vulnerability", + issuedAt: "2026-08-02T01:00:00.000Z", + expiresAt: "2026-08-02T02:00:00.000Z", + run: { ...expected.run, invocationNonce: "1".repeat(64) }, + source: expected.source, + candidate: expected.candidate, + secretScanAttestation, + findings: [], + }, + "vulnerability-key", + keys.publicKey, + keys.privateKey, + ); + const validated = validateProviderEvidence({ + kind: "vulnerability", + value: report, + expected: { + ...expected, + vulnerabilityInvocationNonce: "1".repeat(64), + provenanceInvocationNonce: "2".repeat(64), + secretScanAttestation: { + ...secretScanAttestation, + sarifSha256: digest("forged empty sarif"), + }, + }, + trust: trust("vulnerability-key", keys.publicKey), + nowEpochMs: () => Date.parse("2026-08-02T01:00:00.000Z"), + }); + expect(validated.status).toBe("FAIL_UNVERIFIED"); + expect(validated.failures).toContain( + "vulnerability report secret scan attestation mismatch", + ); + const forged = structuredClone(report); + forged.secretScanAttestation.sarifSha256 = digest("forged empty sarif"); + const forgedValidation = validateProviderEvidence({ + kind: "vulnerability", + value: forged, + expected: { + ...expected, + vulnerabilityInvocationNonce: "1".repeat(64), + provenanceInvocationNonce: "2".repeat(64), + secretScanAttestation: forged.secretScanAttestation, + }, + trust: trust("vulnerability-key", keys.publicKey), + nowEpochMs: () => Date.parse("2026-08-02T01:00:00.000Z"), + }); + expect(forgedValidation.failures).toContain( + "vulnerability report signature verification failed", + ); + + const provenanceKeys = generateKeyPairSync("ed25519"); + const provenance = signedProviderV2( + { + schemaVersion: 2, + evidenceType: "provenance-attestation", + provider: "fixture-provenance", + signer: "fixture-workload", + issuedAt: "2026-08-02T01:00:00.000Z", + expiresAt: "2026-08-02T02:00:00.000Z", + run: { ...expected.run, invocationNonce: "2".repeat(64) }, + source: expected.source, + candidate: expected.candidate, + subject: { name: "dist", digest: { sha256: expected.candidate.distSha256 } }, + }, + "provenance-key", + provenanceKeys.publicKey, + provenanceKeys.privateKey, + ); + const evaluated = evaluatePromotionEvidence({ + expected: { + ...expected, + vulnerabilityInvocationNonce: "1".repeat(64), + provenanceInvocationNonce: "2".repeat(64), + secretScanAttestation: { + ...secretScanAttestation, + sarifSha256: digest("forged empty sarif"), + }, + }, + localStatus: "PASS", + vulnerabilityReport: report, + provenanceAttestation: provenance, + vulnerabilityTrust: trust("vulnerability-key", keys.publicKey), + provenanceTrust: trust("provenance-key", provenanceKeys.publicKey), + nowEpochMs: () => Date.parse("2026-08-02T01:00:00.000Z"), + }); + expect(evaluated.vulnerabilityStatus).toBe("FAIL_UNVERIFIED"); + expect(evaluated.failures).toContain( + "vulnerability report secret scan attestation mismatch", + ); + }); + + it.each(["vulnerability", "provenance"] as const)( + "rejects correctly re-signed %s v2 context/time/replay drift", + (kind) => { + const now = Date.parse("2026-08-02T01:00:00.000Z"); + const vulnerabilityKeys = generateKeyPairSync("ed25519"); + const provenanceKeys = generateKeyPairSync("ed25519"); + const expected = providerExpectedContext(); + const baseVulnerability = providerUnsigned("vulnerability", expected); + const baseProvenance = providerUnsigned("provenance", expected); + const validVulnerability = signedProviderV2( + baseVulnerability, + "vulnerability-key", + vulnerabilityKeys.publicKey, + vulnerabilityKeys.privateKey, + ); + const validProvenance = signedProviderV2( + baseProvenance, + "provenance-key", + provenanceKeys.publicKey, + provenanceKeys.privateKey, + ); + const rawCases: Array) => Record, + RegExp, + ]> = [ + ["schema v1", (value) => ({ ...value, schemaVersion: 1 }), /missing or invalid/u], + [ + "evidence type", + (value) => ({ + ...value, + evidenceType: + kind === "vulnerability" + ? "provenance-attestation" + : "vulnerability-report", + }), + /missing or invalid/u, + ], + ...(["archiveSha256", "bundleSha256", "distSha256", "lockfileSha256"] as const).map( + (field) => [ + `candidate ${field}`, + (value: Record) => ({ + ...value, + candidate: { ...value.candidate, [field]: "f".repeat(64) }, + ...(kind === "provenance" && field === "distSha256" + ? { + subject: { + name: "dist", + digest: { sha256: "f".repeat(64) }, + }, + } + : {}), + }), + /candidate identity|subject dist/u, + ] as const, + ), + [ + "different archive with same dist and lockfile", + (value) => ({ + ...value, + candidate: { ...value.candidate, archiveSha256: "e".repeat(64) }, + }), + /candidate identity/u, + ], + [ + "source revision", + (value) => ({ ...value, source: { ...value.source, revision: "c".repeat(40) } }), + /source identity/u, + ], + [ + "source set", + (value) => ({ ...value, source: { ...value.source, sourceSetSha256: "c".repeat(64) } }), + /source identity/u, + ], + [ + "run id", + (value) => ({ ...value, run: { ...value.run, id: "other-run" } }), + /run identity/u, + ], + [ + "run attempt replay", + (value) => ({ ...value, run: { ...value.run, attempt: 2 } }), + /run identity/u, + ], + [ + "different nonce", + (value) => ({ ...value, run: { ...value.run, invocationNonce: "3".repeat(64) } }), + /invocation nonce/u, + ], + [ + "missing nonce", + (value) => { + const run = { ...value.run }; + delete run.invocationNonce; + return { ...value, run }; + }, + /missing or invalid/u, + ], + [ + "uppercase nonce", + (value) => ({ ...value, run: { ...value.run, invocationNonce: "A".repeat(64) } }), + /missing or invalid/u, + ], + [ + "short nonce", + (value) => ({ ...value, run: { ...value.run, invocationNonce: "1".repeat(62) } }), + /missing or invalid/u, + ], + [ + "issued future boundary", + (value) => ({ ...value, issuedAt: "2026-08-02T01:05:00.001Z" }), + /future skew/u, + ], + [ + "expiry equality", + (value) => ({ ...value, expiresAt: "2026-08-02T01:00:00.000Z" }), + /expired/u, + ], + [ + "expiry past", + (value) => ({ ...value, expiresAt: "2026-08-02T00:59:59.999Z" }), + /expired/u, + ], + [ + "zero lifetime", + (value) => ({ + ...value, + issuedAt: "2026-08-02T01:01:00.000Z", + expiresAt: "2026-08-02T01:01:00.000Z", + }), + /not positive/u, + ], + [ + "negative lifetime", + (value) => ({ + ...value, + issuedAt: "2026-08-02T01:02:00.000Z", + expiresAt: "2026-08-02T01:01:59.999Z", + }), + /not positive/u, + ], + [ + "lifetime above two hours", + (value) => ({ + ...value, + issuedAt: "2026-08-02T01:00:00.000Z", + expiresAt: "2026-08-02T03:00:00.001Z", + }), + /exceeds two hours/u, + ], + [ + "wrong fingerprint", + (value) => ({ + ...value, + signature: { + ...value.signature, + publicKeyFingerprint: `sha256:${"d".repeat(64)}`, + }, + }), + /trust identity/u, + ], + ]; + const cases = rawCases.map(([name, mutate, failure]) => ({ + name, + mutate, + failure, + })); + + for (const testCase of cases) { + const base = kind === "vulnerability" ? baseVulnerability : baseProvenance; + const mutated = testCase.mutate(structuredClone(base)); + const resigned = signedProviderV2( + mutated, + kind === "vulnerability" ? "vulnerability-key" : "provenance-key", + kind === "vulnerability" ? vulnerabilityKeys.publicKey : provenanceKeys.publicKey, + kind === "vulnerability" ? vulnerabilityKeys.privateKey : provenanceKeys.privateKey, + "signature" in mutated && mutated.signature?.publicKeyFingerprint + ? mutated.signature.publicKeyFingerprint + : undefined, + ); + const result = evaluatePromotionEvidence({ + expected: { + ...expected, + vulnerabilityInvocationNonce: "1".repeat(64), + provenanceInvocationNonce: "2".repeat(64), + }, + localStatus: "PASS", + vulnerabilityReport: + kind === "vulnerability" ? resigned : validVulnerability, + provenanceAttestation: + kind === "provenance" ? resigned : validProvenance, + vulnerabilityTrust: trust("vulnerability-key", vulnerabilityKeys.publicKey), + provenanceTrust: trust("provenance-key", provenanceKeys.publicKey), + nowEpochMs: () => now, + }); + expect(result.status, testCase.name).toBe("FAIL_UNVERIFIED"); + expect(result.failures.join("\n"), testCase.name).toMatch(testCase.failure); + } + }, + ); + + it("canonicalizes provider fingerprints from DER SPKI across PEM wrapping and rejects Ed448", async () => { + const root = await mkdtemp(path.join(tmpdir(), "provider-fingerprint-")); + try { + const ed25519 = generateKeyPairSync("ed25519").publicKey; + const pem = ed25519.export({ type: "spki", format: "pem" }).toString(); + const body = pem.replace(/-----[^-]+-----|\s/gu, ""); + const wrapped = (width: number) => + `-----BEGIN PUBLIC KEY-----\n${body.match(new RegExp(`.{1,${width}}`, "gu"))!.join("\n")}\n-----END PUBLIC KEY-----\n`; + await writeFile(path.join(root, "a.pem"), wrapped(64)); + await writeFile(path.join(root, "b.pem"), wrapped(32)); + const first = await readProviderTrust(root, "a.pem", "fixture-key"); + const second = await readProviderTrust(root, "b.pem", "fixture-key"); + expect(first?.publicKeyFingerprint).toBe(providerPublicKeyFingerprint(ed25519)); + expect(second?.publicKeyFingerprint).toBe(first?.publicKeyFingerprint); + + const ed448 = generateKeyPairSync("ed448").publicKey; + await writeFile(root + "/ed448.pem", ed448.export({ type: "spki", format: "pem" })); + await expect(readProviderTrust(root, "ed448.pem", "fixture-key")).resolves.toBeNull(); + expect(() => providerPublicKeyFingerprint(ed448)).toThrow(/must be Ed25519/u); + } finally { + await rm(root, { recursive: true, force: true }); + } + }); + + it("captures the downloaded archive pathname exactly once in the provider supervisor", async () => { + const keys = generateKeyPairSync("ed25519"); + const expected = providerExpectedContext(); + let captureCount = 0; + let receivedEnvironment: Readonly> | undefined; + const manifest: ReleaseCandidateManifest = { + schemaVersion: 1, + distSha256: expected.candidate.distSha256, + lockfileSha256: expected.candidate.lockfileSha256, + bundleSha256: expected.candidate.bundleSha256, + files: [{ path: "pnpm-lock.yaml", bytes: 1, sha256: expected.candidate.lockfileSha256 }], + }; + const result = await superviseProviderEvidence( + { + kind: "vulnerability", + archivePath: "/downloads/candidate.tar.gz", + expectedArchiveSha256: expected.candidate.archiveSha256, + expectedRun: { + id: expected.run.id, + attempt: expected.run.attempt, + sourceRevision: expected.source.revision, + }, + trust: trust("vulnerability-key", keys.publicKey), + executeProvider: async ({ environment }) => { + receivedEnvironment = environment; + }, + captureReport: async () => Buffer.from("{}\n"), + }, + { + captureArchive: async (input) => { + captureCount += 1; + expect(input).toEqual({ + archivePath: "/downloads/candidate.tar.gz", + expectedSha256: expected.candidate.archiveSha256, + }); + return { + bytes: Buffer.from("captured archive"), + archiveSha256: expected.candidate.archiveSha256, + }; + }, + withVerifiedCandidate: (async (input: any) => + input.verify({ extractionRoot: "/captured/extraction", manifest })) as any, + verifyLocalEvidence: async () => ({ + status: "PASS", + identity: { + sourceRevision: expected.source.revision, + sourceSetSha256: expected.source.sourceSetSha256, + assessmentSha256: digest("assessment"), + secretScan: { + policySha256: digest("provider secret policy"), + sarifSha256: digest("provider secret sarif"), + scanInputSha256: digest("provider secret input"), + }, + }, + failures: [], + }), + validateUpload: (async (input: any) => { + expect("archivePath" in input).toBe(false); + return { sealed: true }; + }) as any, + randomBytes: () => Buffer.alloc(32, 0x11), + nowEpochMs: () => Date.parse("2026-08-02T01:00:00.000Z"), + }, + ); + + expect(captureCount).toBe(1); + expect(receivedEnvironment).toEqual( + expect.objectContaining({ + PROVIDER_EVIDENCE_SCHEMA_VERSION: "2", + PROVIDER_INVOCATION_NONCE: "11".repeat(32), + PROVIDER_ISSUED_AT: "2026-08-02T01:00:00.000Z", + PROVIDER_EXPIRES_AT: "2026-08-02T02:00:00.000Z", + CI_RUN_ID: expected.run.id, + CI_RUN_ATTEMPT: "1", + SOURCE_REVISION: expected.source.revision, + CANDIDATE_ARCHIVE_SHA256: expected.candidate.archiveSha256, + }), + ); + expect(result.evidence).toEqual({ sealed: true }); + }); + + it("samples provider freshness after report capture instead of reusing issuance time", async () => { + const keys = generateKeyPairSync("ed25519"); + const expected = providerExpectedContext(); + const manifest: ReleaseCandidateManifest = { + schemaVersion: 1, + distSha256: expected.candidate.distSha256, + lockfileSha256: expected.candidate.lockfileSha256, + bundleSha256: expected.candidate.bundleSha256, + files: [{ path: "pnpm-lock.yaml", bytes: 1, sha256: expected.candidate.lockfileSha256 }], + }; + const issuedSample = Date.parse("2026-08-02T01:00:00.000Z"); + const validationSample = Date.parse("2026-08-02T02:00:00.001Z"); + const samples = [issuedSample, validationSample]; + let issuedAt = ""; + await expect( + superviseProviderEvidence( + { + kind: "vulnerability", + archivePath: "/downloads/candidate.tar.gz", + expectedArchiveSha256: expected.candidate.archiveSha256, + expectedRun: { + id: expected.run.id, + attempt: expected.run.attempt, + sourceRevision: expected.source.revision, + }, + trust: trust("vulnerability-key", keys.publicKey), + executeProvider: async ({ environment }) => { + issuedAt = environment.PROVIDER_ISSUED_AT!; + }, + captureReport: async () => Buffer.from("{}\n"), + }, + { + captureArchive: async () => ({ + bytes: Buffer.from("captured archive"), + archiveSha256: expected.candidate.archiveSha256, + }), + withVerifiedCandidate: (async (input: any) => + input.verify({ extractionRoot: "/captured/extraction", manifest })) as any, + verifyLocalEvidence: async () => ({ + status: "PASS", + identity: { + sourceRevision: expected.source.revision, + sourceSetSha256: expected.source.sourceSetSha256, + assessmentSha256: digest("assessment"), + secretScan: { + policySha256: digest("provider secret policy"), + sarifSha256: digest("provider secret sarif"), + scanInputSha256: digest("provider secret input"), + }, + }, + failures: [], + }), + validateUpload: (async (input: any) => { + expect(input.nowEpochMs()).toBe(validationSample); + throw new Error("provider report expired during execution"); + }) as any, + randomBytes: () => Buffer.alloc(32, 0x33), + nowEpochMs: () => samples.shift()!, + }, + ), + ).rejects.toThrow(/expired during execution/u); + expect(issuedAt).toBe("2026-08-02T01:00:00.000Z"); + }); + + it("kills a timed-out provider but settles only after the child closes", async () => { + const child = new EventEmitter() as EventEmitter & { + kill(signal: NodeJS.Signals): boolean; + }; + let killedWith: NodeJS.Signals | undefined; + child.kill = (signal) => { + killedWith = signal; + return true; + }; + let fireTimeout: (() => void) | undefined; + let settled = false; + const running = runProviderProcess( + { executable: "/usr/bin/bwrap", arguments: [], environment: {}, timeoutMs: 1 }, + { + spawnChild: () => child as any, + setTimer: (callback) => { + fireTimeout = callback; + return 1 as any; + }, + clearTimer: () => undefined, + }, + ).finally(() => { + settled = true; + }); + fireTimeout?.(); + await Promise.resolve(); + expect(killedWith).toBe("SIGKILL"); + expect(settled).toBe(false); + child.emit("close", null, "SIGKILL"); + await expect(running).rejects.toThrow(/timed out/u); + expect(settled).toBe(true); + }); + + it("captures process-group kill errors, attempts child fallback, and settles after close", async () => { + const child = new EventEmitter() as EventEmitter & { + pid: number; + kill(signal: NodeJS.Signals): boolean; + }; + child.pid = 12_346; + let fallbackSignal: NodeJS.Signals | undefined; + child.kill = (signal) => { + fallbackSignal = signal; + return true; + }; + let fireTimeout: (() => void) | undefined; + const running = runProviderProcess( + { executable: "/usr/bin/bwrap", arguments: [], environment: {}, timeoutMs: 1 }, + { + spawnChild: () => child as any, + setTimer: (callback) => { + fireTimeout = callback; + return 1 as any; + }, + clearTimer: () => undefined, + killProcessGroup: () => { + throw Object.assign(new Error("group kill denied"), { code: "EPERM" }); + }, + }, + ); + expect(() => fireTimeout?.()).not.toThrow(); + expect(fallbackSignal).toBe("SIGKILL"); + child.emit("close", null, "SIGKILL"); + await expect(running).rejects.toThrow(/timed out.*kill failed.*close/u); + }); + + it.each(["open failure", "partial write failure"])( + "cleans finalized staging from memory when GITHUB_OUTPUT has a %s", + async (failureKind) => { + const finalized = { + stagingRoot: "/runner/promotion-run-1-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + cleanupToken: "promotion-run-1-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + runnerTempIdentity: { dev: 10, ino: 20 }, + stagingIdentity: { dev: 30, ino: 40 }, + files: [], + } as const; + let cleanupInput: unknown; + let appendCalls = 0; + const environment = { + CANDIDATE_ARCHIVE_PATH: "candidate.tar.gz", + CANDIDATE_ARCHIVE_SHA256: "a".repeat(64), + VULNERABILITY_REPORT_PATH: "vulnerability.json", + PROVENANCE_ATTESTATION_PATH: "provenance.json", + VULNERABILITY_PUBLIC_KEY_PATH: "vulnerability.pem", + VULNERABILITY_KEY_ID: "vulnerability-key", + PROVENANCE_PUBLIC_KEY_PATH: "provenance.pem", + PROVENANCE_KEY_ID: "provenance-key", + CI_RUN_ID: "run", + CI_RUN_ATTEMPT: "1", + VITE_COMMIT_SHA: "b".repeat(40), + VULNERABILITY_INVOCATION_NONCE: "c".repeat(64), + PROVENANCE_INVOCATION_NONCE: "d".repeat(64), + RUNNER_TEMP: "/runner", + GITHUB_OUTPUT: "/runner/github-output", + }; + await expect( + runStageVerifiedPromotionCli(environment, { + cwd: () => "/workspace", + finalize: async () => finalized as any, + appendOutput: async () => { + appendCalls += 1; + if (failureKind === "partial write failure") { + // The output sink accepted an unspecified prefix before rejecting. + } + throw new Error(failureKind); + }, + cleanup: async (input) => { + cleanupInput = input; + }, + writeStdout: () => undefined, + }), + ).rejects.toThrow(new RegExp(failureKind, "u")); + expect(appendCalls).toBe(1); + expect(cleanupInput).toEqual({ + runnerTempRoot: "/runner", + stagingRoot: finalized.stagingRoot, + cleanupToken: finalized.cleanupToken, + runnerTempIdentity: finalized.runnerTempIdentity, + stagingIdentity: finalized.stagingIdentity, + }); + }, + ); + +}); diff --git a/tests/unit/task3-selective-integration.test.ts b/tests/unit/task3-selective-integration.test.ts index f70a2ff..f468e77 100644 --- a/tests/unit/task3-selective-integration.test.ts +++ b/tests/unit/task3-selective-integration.test.ts @@ -190,9 +190,11 @@ describe("selective Task 3 contract closure", () => { // FE-GATE-007, bringing the totals to 84/96/130. The dev release manifest // drift fix added `check-dev-release-manifest` to FE-GATE-010: 85/97/130. expect(canonical.gates).toHaveLength(27); - expect(canonical.commands).toHaveLength(85); - expect(canonical.gates.reduce((sum, gate) => sum + gate.commandIds.length, 0)).toBe(97); - expect(canonical.artifacts).toHaveLength(139); + // Template sync (ebea300). Recomputed from the merged config/ci/gates.json: + // neither 85/97/139 (this product) nor 91/103/109 (the template) describes it. + expect(canonical.commands).toHaveLength(94); + expect(canonical.gates.reduce((sum, gate) => sum + gate.commandIds.length, 0)).toBe(106); + expect(canonical.artifacts).toHaveLength(141); expect(canonical.stages).toHaveLength(5); expect(canonical.retention.classes).toHaveLength(5); diff --git a/tsconfig.service-worker.json b/tsconfig.service-worker.json index 9ca8f56..fe6ade3 100644 --- a/tsconfig.service-worker.json +++ b/tsconfig.service-worker.json @@ -11,6 +11,7 @@ "src/contracts/service-worker.ts" ], "exclude": [ + "src/adapters/service-worker/index.ts", "src/adapters/service-worker/service-worker-page-controller.ts", "src/adapters/service-worker/service-worker-removal.ts" ] diff --git a/vitest.config.ts b/vitest.config.ts index b146aa9..6f74f17 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -1,5 +1,11 @@ import { configDefaults, defineConfig } from "vitest/config"; +// Tests must not inherit a caller's production React/runtime selection. +// Package scripts also launch Vitest through scripts/run-vitest.ts, which owns +// NODE_ENV before the Vitest process starts. Keeping the config deterministic +// protects direct `vitest` invocations as well. +process.env.NODE_ENV = "test"; + export default defineConfig({ test: { globals: false,