Merge branch 'fix/src-review-round2' into main
Round 2 of the 2026-09-24 src review fixes: every recommended/minor finding, the SW fetch-scope follow-up and the bundle budget (T51-T115). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -167,6 +167,17 @@
|
||||
"path": "^src/(application|features)"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "contracts-do-not-know-presentation-or-bootstrap",
|
||||
"comment": "Q-6.7-12. `src/contracts` is shared vocabulary read by every layer, including the service worker and web worker builds. Importing presentation or the composition root from it would pull React and the whole app into those builds. There is no such import today; this keeps it that way.",
|
||||
"severity": "error",
|
||||
"from": {
|
||||
"path": "^src/contracts"
|
||||
},
|
||||
"to": {
|
||||
"path": "^src/(presentation|bootstrap)"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "generic-presentation-does-not-compose-the-product",
|
||||
"comment": "§4 / §9. Which features are installed is a product decision that belongs to bootstrap. Generic presentation reads the installed registries directly today; the paths below are the exact set that does so, frozen so the coupling cannot spread while the assembly is lifted into bootstrap.",
|
||||
|
||||
@@ -101,3 +101,113 @@
|
||||
| D-5 (R-8.3) | 로케일 저장은 테마와 같은 `preferences` 경로를 쓴다. Locale/Theme provider는 scope fence 바깥으로 올린다. | 이미 있는 테마 패턴을 재사용한다. |
|
||||
| D-6 (R-9.2) | 누적 count는 dedup 창이 닫힐 때나 다음 flush 때 요약 이벤트의 `occurrences`로 보낸다. | 기존 이벤트 스키마(`occurrences`)를 그대로 쓴다. |
|
||||
| D-7 (R-6.3) | previous 캐시 fallback은 hashed URL에만 적용한다. | hashed URL은 같은 URL이면 같은 내용이라 안전하다. |
|
||||
|
||||
---
|
||||
|
||||
# 2차 라운드: 권장·사소 항목과 1차 후속 결정
|
||||
|
||||
1차 라운드(R-0 ~ R-9.3)는 `9bef702`로 main에 병합했다. 2차 라운드에서는 리뷰의 **권장·사소 항목 전부**와 1차에서 남긴 결정 두 건을 처리한다. 요구사항 ID는 `Q-<리뷰 섹션>` 형식이다(예: Q-6.1-5 = 리뷰 6.1-5).
|
||||
|
||||
## 공통 완료 기준 (2차)
|
||||
|
||||
1차 공통 기준과 같다. 여기에 두 가지를 더한다.
|
||||
- **동작을 바꾸지 않는 정리(파일 분리, 중복 합치기)**: 새 RED 테스트 대신 기존 테스트가 안전망이다. 해당 경로에 테스트가 없으면 현재 동작을 고정하는 테스트(characterization)를 먼저 추가한다.
|
||||
- **번들**: 정리가 끝난 뒤 `check:optional-recipes`가 통과해야 한다. 예산은 올리지 않는다(D-11).
|
||||
|
||||
## 요구사항
|
||||
|
||||
### browser-transfer
|
||||
- Q-6.1-5 worker 하나가 실패하면 transfer 단위 abort로 나머지 worker를 즉시 멈춘다.
|
||||
- Q-6.1-6 해석할 수 없는 checkpoint 행이 있어도 abort는 그 행을 지우고 ORPHANED로 보고한다.
|
||||
- Q-6.1-7 PRIMARY_REQUIRED probe를 쓰는 preset은 fit이 cover/contain/fill일 때만 정책을 통과한다(D-12).
|
||||
- Q-6.1-8 probe의 decode는 EXIF/irot 회전을 적용하지 않는다(`imageOrientation: "none"`).
|
||||
- Q-6.1-9 presigned HTTP helper를 한 모듈로 합친다. statusFailure recovery를 통일하고, 쓰지 않는 `compensateLateResponse`는 삭제한다. download Content-Length를 엄격하게 파싱하고, runtime attempt는 kernel `createAbortableOperation`을 쓴다.
|
||||
- Q-6.1-3b part마다 일어나는 방어적 복사 중 겹치는 것(`Uint8Array.from`과 `slice()`)을 하나로 줄인다.
|
||||
- Q-6.1-10 `resumable-upload-runtime.ts`에서 서버 응답 검증과 의존성 snapshot 래퍼를 별도 모듈로 분리한다. 동작은 바꾸지 않는다.
|
||||
- Q-6.1-11 vault `register`는 snapshot 값만 읽는다.
|
||||
|
||||
### browser-files / cache-storage / cross-context
|
||||
- Q-6.2-6 cache 조회 비용: JSON은 chunk를 모아 읽고, 검증된 marker는 메모리에 캐시하고, asset 탐색은 Map으로 한다.
|
||||
- Q-6.2-7 browser-files의 abort race를 kernel `race`와 compensate로 교체한다. 늦게 도착한 lease와 writable은 닫는다.
|
||||
- Q-6.2-8 native `cancel`을 한 번이라도 관찰했으면 focus fallback을 끈다.
|
||||
- Q-6.2-9 host factory가 비활성으로 끝날 때 observe로 보고한다. epoch는 releaseId를 인코딩해서 만든다.
|
||||
- Q-6.2-10 파일명 자르기를 O(n)으로 바꾸고, 중복 호출을 하나로 줄인다.
|
||||
- Q-6.2-11 `public-response-cache-adapter.ts`와 `download-delivery-adapter.ts`에서 코덱·검증 모듈을 분리한다. 동작은 바꾸지 않는다.
|
||||
- Q-6.2-12 `MEDIA_TYPE`/opaque 정규식과 `positiveSafeInteger` 중복을 합치고, `object-url-lease.ts`의 죽은 분기를 지운다.
|
||||
|
||||
### http / browser-rpc / query-cache / auth
|
||||
- Q-6.3-6 요청 종료 사유 판정을 `terminalOutcomeFor` 하나로 모은다. 백오프 중 scope fence는 scope 종료로 분류된다.
|
||||
- Q-6.3-7 명령의 최종 effect는 누적 certainty와 합친다. `MAYBE_APPLIED`면 재시도하지 않는다.
|
||||
- Q-6.3-8 namespace 무효화를 병렬로 실행한다.
|
||||
- Q-6.3-9 RPC 명령이 전송 뒤 실패하면 `MAYBE_APPLIED`로 보고한다. 재시도 전에 scope를 확인하고, 소비자가 abort한 stream은 정리한다.
|
||||
- Q-6.3-11 V2 401 복구를 재시도 예산과 분리한다. "롤백 가능 seam" 문서의 잘못된 주장을 고친다(V2와 V3는 wire 형식이 다르다).
|
||||
- Q-6.3-12 cursor pagination의 누적 직렬화와 `push(...)` 한도 문제를 고친다. 쓰지 않는 `validTransportFailure`를 삭제하고, 따옴표가 닫히지 않은 `W/"` ETag를 거부한다.
|
||||
- Q-6.3-3b V2도 5xx/408/425의 HTML/빈 바디를 status를 담은 서버 장애로 분류하고 재시도 대상으로 둔다.
|
||||
|
||||
### realtime
|
||||
- Q-6.4-5 chunk당 item 상한을 넘으면 실패하지 않고 다음 처리로 넘긴다. COMMENT는 상수 객체를 쓴다.
|
||||
- Q-6.4-6 dedupe는 FIFO로 제거하고, fingerprint는 해시로 저장하고, prune은 `break`한다. 가득 차도 전체 recovery를 하지 않는다.
|
||||
- Q-6.4-7 재시도 예산은 유효 신호가 있고 `stableOpenMs`가 지났을 때만 초기화한다.
|
||||
- Q-6.4-8 realtime 내부의 DataSnapshot과 abort/timeout race 헬퍼를 한 벌로 합친다. Retry-After 파싱과 JSON 중복 키 스캐너는 kernel(`src/adapters/platform/`)로 올리고, http retry-policy와 web-push codec도 이를 쓴다.
|
||||
- Q-6.4-9 반복되는 attempt 정리를 `endAttempt()`로 뽑고, 무시되던 `_recovery` 파라미터를 없앤다.
|
||||
- Q-6.4-10 probe 버퍼 상한을 현재 버퍼 기준으로 계산한다.
|
||||
- Q-6.4-11 사소 항목: poll execute가 throw하면 retryable OFFLINE으로 둔다. BOM은 한 번만 제거하고, 이중 encode와 이벤트마다 만드는 TextEncoder를 없애고, 잘못 붙은 JSDoc을 옮긴다.
|
||||
|
||||
### storage
|
||||
- Q-6.5-6 openObject는 사전 검증에서 manifest만 대조하고, root digest는 스트림 끝에서 확인한다.
|
||||
- Q-6.5-7 IndexedDB 저장 행 타입·검증기·측정 공식을 `indexeddb-records.ts` 하나로 모은다. 동작은 바꾸지 않는다.
|
||||
- Q-6.5-8 삭제 후 재생성하면 revision/generation이 다시 시작한다는 점을 port 주석과 문서에 명시한다(D-13).
|
||||
- Q-6.5-9 보상이 실패해도 put의 원래 실패 코드를 유지하고, recovery만 RECONCILE로 바꾼다.
|
||||
- Q-6.5-10 kernel: `succeed` 뒤에 온 `fail`이 이기도록 하고, settle된 뒤의 upgrade는 abort한다.
|
||||
|
||||
### service-worker / web-push
|
||||
- Q-6.6-6b fetch 가로채기를 "same-origin GET, navigate 아님, 해시 파일명 또는 manifest URL"로 넓힌다. previous 캐시 fallback이 옛 빌드 chunk에 실제로 동작해야 한다(1차 T29/T32 후속, 사용자 결정).
|
||||
- Q-6.6-8 후보 캐시 이름이 active 캐시와 같으면 설치 실패 시 지우지 않는다.
|
||||
- Q-6.6-9 activate는 오래된 캐시부터 지우고, marker 쓰기 실패가 삭제를 막지 않는다.
|
||||
- Q-6.6-10b 페이지 쪽 활성화 deadline에 워커 drain 시간과 여유분을 더한다.
|
||||
- Q-6.6-11 알림 클릭이 거절되면 handoff 데이터 없이 앱 루트를 연다. 조용한 push drop은 트레이드오프를 문서에 명시한다(D-14).
|
||||
- Q-6.6-12 web-push codec primitive(base64url, OPAQUE_ID, validAuthority, exactRecord)를 한 모듈로 합친다. page controller가 주입받은 document를 쓴다.
|
||||
|
||||
### contracts
|
||||
- Q-6.7-6 exact-key/스냅샷 구현을 `exact-snapshot.ts` 하나로 모으고 배열 스냅샷을 추가한다. iterator·getter 우회를 막는다.
|
||||
- Q-6.7-7 검증된 인덱스·레지스트리는 `createReadOnlyRegistry`를 쓰고 row마다 스냅샷해서 얼린다.
|
||||
- Q-6.7-8 검증기 프로토콜과 `MappingResult`의 기준 모양을 하나로 정하고, 나머지는 호환 alias나 어댑터로 둔다(D-15).
|
||||
- Q-6.7-9 REST 인증 프로필은 설치된 레지스트리 하나를 기준으로 한다. V2 resolve도 검증된 레지스트리를 쓴다.
|
||||
- Q-6.7-10 배포 승인은 IPv6 loopback·ULA·link-local, IPv4-mapped, CGNAT, `0.0.0.0/8`, `.internal`/`.local`을 사설 주소로 본다. 로컬 호스트 목록은 한 곳에 둔다.
|
||||
- Q-6.7-11 레지스트리 조회는 `Object.hasOwn`으로 한다. 목록에 없는 offline 전이는 false를 반환한다.
|
||||
- Q-6.7-12 release-tokens는 비교하지 않은 값을 통과로 보고하지 않는다. contract-set 중복은 실패 코드로 반환한다. query-keys 정렬은 필요할 때만 한다. dependency-cruiser에 contracts → presentation/bootstrap 금지 규칙을 추가한다.
|
||||
|
||||
### presentation
|
||||
- Q-6.8-9 디자인시스템 링크(`PageActionBar`, `Breadcrumbs`, `LinkButton`)는 router `Link`로 렌더한다. Pagination은 다른 검색 파라미터를 보존한다.
|
||||
- Q-6.8-10 로딩·인증필요·404 화면을 하나씩으로 합치고, 세션 액션은 hook 하나로 묶는다. reject 시 멈추던 임시 로딩도 고친다.
|
||||
- Q-6.8-11 Tooltip: `aria-describedby`를 포커스되는 자식에 붙이고, Escape로 닫는다.
|
||||
- Q-6.8-12 Pagination은 현재 페이지 주변과 처음·끝만 보여주고(windowing), landmark 중첩을 없앤다.
|
||||
- Q-6.8-13a 플랫폼 라우트의 `none` 코덱은 모르는 쿼리 파라미터를 거부하지 않고 무시한다(D-16).
|
||||
- Q-6.8-13b 폼 제출은 비동기 검증 중에도 두 번 일어나지 않는다. 저장 직후 이동할 때 dirty guard가 뜨지 않는다.
|
||||
- Q-6.8-13c 기본 fallback 문구는 현재 로케일을 따른다. SearchField를 지우면 입력으로 포커스를 돌려준다.
|
||||
- Q-6.8-13d `theme.css`를 여러 파일로 나눈다. 빌드 결과 CSS 바이트가 달라지지 않아야 한다.
|
||||
|
||||
### application / features / bootstrap / platform (+ telemetry adapter)
|
||||
- Q-6.9-4 텔레메트리 전송 계층을 하나로 합친다(rate limit, credentials `omit`, `pagehide` flush, dispose abort). best-effort fetch에 타임아웃을 둔다(6.3-10 포함).
|
||||
- Q-6.9-5 킬스위치로 끈 feature는 `features.get()`이 API를 돌려주지 않는다.
|
||||
- Q-6.9-6 adapter contribution의 featureId가 중복되거나 소속 module과 다르면 throw한다.
|
||||
- Q-6.9-7 execution context interaction에 완료/정리 API를 두어 부모 signal listener가 남지 않게 한다.
|
||||
- Q-6.9-8 부트 중에 정적 boot shell(로딩 표시, `aria-busy`)을 보여준다.
|
||||
- Q-6.9-9 chunk와 boot의 "한 번만 reload" 가드를 공용 guard 하나로 합친다.
|
||||
- Q-6.9-10 검증을 통과한 config 값만 safe 에러에 싣는다.
|
||||
- Q-6.9-11 텔레메트리 버퍼는 필요한 공간이 확보될 때만 낮은 severity를 지운다. 주석을 코드와 맞춘다.
|
||||
- Q-6.9-12 re-export만 하는 `reference-feature-runtime.tsx`를 삭제한다. CI 전용 정책(`promotion-readiness`, `performance-budgets`)은 src 소비자가 없으면 `scripts/`로 옮긴다. 메시지 로케일은 하드코딩하지 않고 카탈로그에서 도출한다.
|
||||
|
||||
### 통합
|
||||
- Q-B 번들 예산: 모든 레인을 병합한 뒤 `check:optional-recipes`를 통과시킨다. 필요하면 해당 번들 코드를 줄인다(D-11).
|
||||
|
||||
## 결정 (2차)
|
||||
|
||||
| ID | 결정 |
|
||||
|---|---|
|
||||
| D-11 | 번들 예산은 올리지 않는다. 코드를 줄여 맞춘다(사용자 결정). |
|
||||
| D-12 | PRIMARY_REQUIRED는 fit cover/contain/fill만 허용한다. 비율을 유지하는 fit은 probe를 쓰지 않는 preset에서만 허용한다. |
|
||||
| D-13 | 삭제 뒤 revision 재시작(ABA)은 스키마를 바꾸지 않고 문서로 계약을 명시한다. tombstone 도입은 저장 스키마 변경이라 범위 밖이다. |
|
||||
| D-14 | 클릭 실패 시 앱 루트를 연다. push drop은 설계 의도로 두고 문서에 명시한다. |
|
||||
| D-15 | `external-contract-runtime`의 모양을 기준으로 삼는다. 다른 쪽은 호환 alias나 어댑터로 유지한다(공개 타입을 삭제하지 않음). |
|
||||
| D-16 | 플랫폼 라우트의 모르는 쿼리 파라미터는 무시한다(strip). URL은 건드리지 않는다. |
|
||||
|
||||
@@ -119,26 +119,6 @@
|
||||
"branches": 75
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "src/application/policies/performance-budgets.ts",
|
||||
"owner": "application-policy",
|
||||
"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
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "src/application/use-cases/decide-chunk-recovery.ts",
|
||||
"owner": "application-runtime",
|
||||
@@ -212,8 +192,6 @@
|
||||
"src/adapters/telemetry/best-effort-telemetry.ts",
|
||||
"src/application/create-application.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",
|
||||
"src/bootstrap/load-release-manifest.ts",
|
||||
"src/bootstrap/read-bounded-boot-json.ts",
|
||||
|
||||
+1
-1
@@ -2604,7 +2604,7 @@ export const DEFAULT_REALTIME_RECONNECT_POLICY = Object.freeze({
|
||||
- remaining episode budget 초과 hint: reconnect 종료;
|
||||
- attempts/exhausted: `DEGRADED`, explicit recovery action;
|
||||
- automatic new episode cooldown: 300,000ms;
|
||||
- valid event/heartbeat 또는 60s stable open 후 attempt counter reset;
|
||||
- valid event/heartbeat를 받고 60s stable open도 지난 뒤에만 attempt counter reset;
|
||||
- offline state에서는 timer 대신 `online` signal을 기다림.
|
||||
|
||||
### 14.4 error classification
|
||||
|
||||
@@ -525,6 +525,14 @@ recipe의 feature-facing `StoredRecord<T>` view model과 혼동하지 않는다.
|
||||
`writtenAtEpochMs`, synchronization, `measuredBytes`, `eligibleAtEpochMs`는 record
|
||||
envelope에 중복 저장하지 않고 `retentionStore` sidecar에 둔다.
|
||||
|
||||
revision은 살아 있는 record 하나 안에서만 순서를 매긴다(D-13). `remove`는 행을
|
||||
tombstone 없이 지우므로 같은 key를 다시 만들면 revision이 1부터 다시 시작한다.
|
||||
그래서 `(key, revision)`은 key의 전체 수명에서 유일하지 않다. 삭제 전에
|
||||
revision N을 읽은 writer는 재생성된 record가 N에 도달하면 `expectedRevision: N`
|
||||
CAS로 그 record를 덮어쓸 수 있다. 이 구분이 필요한 호출자는 revision과 함께
|
||||
자기가 소유한 값(server version, payload 안의 ID)을 비교한다. tombstone으로
|
||||
번호를 이어 가는 방식은 저장 스키마 변경이라 이 템플릿 범위 밖이다.
|
||||
|
||||
- structured clone 성공을 업무 schema 검증으로 간주하지 않는다.
|
||||
- 모든 read는 `unknown`에서 runtime codec으로 envelope와 payload version을
|
||||
검증한 뒤 domain value로 mapping한다.
|
||||
@@ -752,7 +760,9 @@ CLEANED -> journal 제거
|
||||
- journal row와 budget reservation은 physical cleanup effect가
|
||||
`CLEANED` 또는 `ALREADY_CLEAN`으로 확인된 뒤에만 해제한다. timeout, crash,
|
||||
malformed response, `EFFECT_UNKNOWN`은 성공이 아니며 `PREPARING`/`FILES_READY`를
|
||||
그대로 남기고 `OBJECT_RECONCILE`로 반환한다.
|
||||
그대로 남긴다. 이때 put은 자기 실패 코드(취소면 `ABORTED`, 쿼터 초과면
|
||||
`QUOTA_EXCEEDED` 등)를 그대로 반환하고 recovery만 `RECONCILE`로 바꾼다
|
||||
(Q-6.5-9). journal rollback이 실패해도 같다.
|
||||
- coordinator가 `abortPreparedPut()` 하나만 소유한다. worker client는 prepare 실패
|
||||
시 별도의 fire-and-forget abort를 발행하지 않는다. 중복 보상은 아직 남아 있어야
|
||||
할 journal row를 조기에 지우는 경로였다.
|
||||
@@ -771,6 +781,11 @@ CLEANED -> journal 제거
|
||||
`STORAGE_EVICTED`; reconstructable만 rehydrate한다.
|
||||
- delete는 logical row tombstone을 먼저 commit해 신규 open을 막고 physical bytes를
|
||||
나중에 정리한다.
|
||||
- delete가 끝나면 logical row가 없어지므로 같은 object ID의 다음 put은
|
||||
generation 1부터 다시 시작한다(D-13). 삭제 전에 기억한 generation이나
|
||||
`expectedGeneration`은 다른 객체와 일치할 수 있다. `(objectId, generation)`을
|
||||
객체 수명 전체의 식별자로 쓰지 않고, 필요하면 integrity root digest를 함께
|
||||
비교한다.
|
||||
- operation ID로 replay를 deduplicate한다.
|
||||
|
||||
`Web Locks`를 쓰면 고정된 origin mutation lock과 AbortSignal/timeout을 사용한다.
|
||||
|
||||
@@ -360,7 +360,10 @@ resume through upload()
|
||||
정한 `schemaVersion: 2`가 필요하다. 기존 schema에 필드를 몰래 추가하지 않는다.
|
||||
|
||||
현재 checkpoint store도 single-key `read/CAS/remove`와 account partition 전체
|
||||
삭제만 제공한다. abandoned upload가 같은 `uploadKey`로 다시 열리지 않으면 local
|
||||
삭제만 제공한다. 예외로 읽을 수 없는 행(손상, 또는 이 빌드가 모르는
|
||||
`schemaVersion`)은 명시적 `abort()`가 `removeUnreadable`로 지우고 `ORPHANED`로
|
||||
보고한다. 그 행에서는 session을 알 수 없으므로 server session은 만료에 맡긴다.
|
||||
`upload()`는 같은 행에서 계속 `CORRUPT_DATA`로 fail-closed한다. abandoned upload가 같은 `uploadKey`로 다시 열리지 않으면 local
|
||||
checkpoint를 retention 기준으로 자동 발견·정리하지 못한다. 향후 admin lifecycle은
|
||||
다음을 제공한다.
|
||||
|
||||
@@ -545,6 +548,9 @@ DOM, persisted state, telemetry 또는 query cache에 장기 보관하지 않는
|
||||
private delivery는 `PRIMARY_REQUIRED` browser probe가 필수이며 이를 `NONE`으로
|
||||
낮출 수 없다. probe는 `credentials: omit`, redirect 금지, exact response URL과
|
||||
`Cache-Control: no-store`를 실제 response에서 확인한다.
|
||||
probe는 decode 크기가 primary 후보의 pixel 크기와 정확히 같아야 통과하므로
|
||||
`PRIMARY_REQUIRED` preset의 `fit`은 `cover`/`contain`/`fill`만 허용한다(D-12).
|
||||
원본 비율을 유지하는 `inside`/`outside`는 probe를 쓰지 않는 preset에서만 쓴다.
|
||||
실제 `<img crossorigin="anonymous">`는 same-origin일 때 cookie를 보낼 수
|
||||
있으므로 registry는 CDN origin이 composition의 application origin과 같으면
|
||||
생성 단계에서 거절한다. private CDN 응답은 cookie나 ambient authorization에
|
||||
|
||||
@@ -618,7 +618,8 @@ stream + epoch별 `lastAppliedSequence`를 기준으로 처리한다.
|
||||
| `sequence == lastApplied + 1` | 순차 적용 |
|
||||
| `sequence > lastApplied + 1` | gap; delta 적용 중지, `RESYNC_REQUIRED` |
|
||||
| unknown `streamEpoch` | old/new epoch를 섞지 않고 registered snapshot 또는 session rebuild |
|
||||
| dedupe/queue ceiling 초과 | 임의 eviction 후 계속 적용하지 않고 registered recovery |
|
||||
| dedupe window 가득 참 | 가장 오래된 항목부터 제거(FIFO)하고 계속 적용. 창에서 밀려난 재전송은 `sequence <= lastApplied`로 drop |
|
||||
| queue ceiling 초과 | 임의 eviction 후 계속 적용하지 않고 registered recovery |
|
||||
| captured old runtime generation | late callback safe drop + aggregate diagnostic |
|
||||
| current connection의 `scopeBinding` mismatch | effect/sequence/cursor 0, freshness `UNKNOWN`, close + session revalidation + registered recovery |
|
||||
|
||||
@@ -763,8 +764,9 @@ effectiveDelay = max(localDelay, validServerNotBefore)
|
||||
bound로 취급한다. `effectiveDelay`가 implementation max delay나 남은 elapsed
|
||||
budget을 넘으면 낮춰 clamp하지 않고 reconnect/poll을 종료해
|
||||
`DEGRADED`/`STALE`로 전환한다.
|
||||
- connection이 잠깐 열렸다는 이유로 attempt를 0으로 만들지 않는다. stable-open
|
||||
window 또는 valid heartbeat/event 뒤에만 reset한다.
|
||||
- connection이 잠깐 열렸다는 이유로 attempt를 0으로 만들지 않는다. valid
|
||||
heartbeat/event를 받았고 stable-open window도 지났을 때만 reset한다(둘 중
|
||||
하나만으로는 reset하지 않는다).
|
||||
- stream reconnect는 realtime recovery coordinator, credential recovery는
|
||||
session owner, Poll attempt 사이 cadence는 poll coordinator가 각각 소유한다.
|
||||
Poll-bound REST transport retry와 Query retry는 끈다. 같은 logical recovery의
|
||||
@@ -1411,6 +1413,20 @@ Service Worker는 언제든 종료될 수 있다. in-memory cursor, queue, auth
|
||||
timer를 authority로 사용하지 않는다. `waitUntil`도 무제한 lifetime을 보장하지
|
||||
않으므로 large fetch, retry loop, data migration을 넣지 않는다.
|
||||
|
||||
**조용한 drop은 설계 의도다(D-14).** 검증에 실패한 push(EXPIRED,
|
||||
RELEASE_MISMATCH, association mismatch, fence 읽기 실패, handler deadline 초과,
|
||||
malformed/unknown)는 알림을 띄우지 않고 끝난다. 계정 정보가 없는 generic
|
||||
알림으로 대신 띄우지 않는 이유는 logout·계정 전환 뒤에 도착한 push가 어떤
|
||||
형태로든 사용자에게 보이면 안 되기 때문이다. 대가는 두 가지다.
|
||||
|
||||
- Chrome은 `userVisibleOnly` push가 알림 없이 끝나면 "This site has been updated
|
||||
in the background" 같은 기본 알림을 대신 띄울 수 있다.
|
||||
- Safari(WebKit)는 알림 없는 push가 반복되면 구독을 취소할 수 있다.
|
||||
|
||||
그래서 drop은 드물어야 한다. backend는 ACTIVE association에만 보내고, 짧은
|
||||
server TTL을 쓰고, release를 바꾼 직후에는 이전 release epoch로 보내지 않는다.
|
||||
drop은 `web_push_hint_processed`의 `FAILED` + reason으로 관측한다.
|
||||
|
||||
### 8.5 Notification content와 click
|
||||
|
||||
- title/body/icon/action은 closed notification registry가 만든다.
|
||||
@@ -1438,8 +1454,14 @@ type NotificationClickDataV1 = Readonly<{
|
||||
|
||||
worker가 종료·재시작된 뒤에도 click을 처리할 수 있도록 이 bounded, non-sensitive
|
||||
envelope만 `NotificationOptions.data`에 넣는다. click handler는 codec/size/expiry,
|
||||
current local `ACTIVE` fence와 release epoch를 다시 검증한다. unknown/mismatch는
|
||||
route를 열지 않고 notification을 닫는다. 이미 표시된 notification은 logout 뒤
|
||||
current local `ACTIVE` fence와 release epoch를 다시 검증한다. unknown/mismatch
|
||||
(만료, fence·release 불일치, fence 읽기 실패, 모르는 route)는 notification을 닫고
|
||||
요청한 route 대신 **앱 루트(`<origin>/`)를 handoff 데이터 없이 연다**(D-14).
|
||||
사용자의 탭이 아무 반응 없이 사라지지 않게 하되, 거절된 click의 route와
|
||||
notification 정보는 페이지로 넘기지 않는다. 결과는 여전히 실패로 보고하고
|
||||
(`web_push_click_dispatched` `FAILED` + reason, `nativeEffect`는 루트 창의
|
||||
확실성), 브라우저가 창 열기를 거절한 native 실패나 deadline/abort 뒤에는 루트를
|
||||
다시 시도하지 않는다. 이미 표시된 notification은 logout 뒤
|
||||
OS notification center에 남을 수 있으므로 copy는 항상 account-neutral하고
|
||||
민감하지 않아야 하며, `getNotifications()` cleanup 성공을 privacy 보장으로
|
||||
과장하지 않는다.
|
||||
|
||||
@@ -78,6 +78,8 @@ session/account Query lifecycle, strict query policy와 Web Storage v2 lifecycle
|
||||
- `BROADCAST_PUBLISH_FAILED`
|
||||
- `STORAGE_LISTENER_FAILED`
|
||||
- `STORAGE_PUBLISH_FAILED`
|
||||
- `INVALID_CACHE_EPOCH`, `SECURE_RANDOM_UNAVAILABLE`(OPEN FAILED): runtime을
|
||||
만들지 못해 이 tab은 cross-tab 무효화 없이 `DEGRADED_LOCAL_ONLY`로 동작한다
|
||||
- runtime status `DEGRADED_STORAGE_FALLBACK` 또는 `DEGRADED_LOCAL_ONLY`
|
||||
|
||||
### 확인
|
||||
|
||||
@@ -16,7 +16,7 @@ No Critical issue was found. Five High findings are implementation blockers or n
|
||||
4. N-04: telemetry dispose only removes pagehide; queued callbacks, future emit calls, and in-flight delivery survive runtime teardown.
|
||||
5. N-05: the conditional-validator key codec is delimiter-ambiguous and lets two valid bindings overwrite each other. It is not composed into HTTP yet, so this is a rollout blocker rather than a current request-path incident.
|
||||
|
||||
The current reference feature uses V3. The older createHttpClient path remains exported and is still the documented rollback/compatibility seam, so its replay and cancellation defects cannot be dismissed as dead code.
|
||||
The current reference feature uses V3. The older createHttpClient path remains exported and is still the documented rollback/compatibility seam, so its replay and cancellation defects cannot be dismissed as dead code. (2026-09-24, Q-6.3-11: the comments no longer call it a rollback seam; V2 and V3 use different wire shapes, so a rollback also needs a V2-envelope server.)
|
||||
|
||||
## 2. Method, severity, and confidence
|
||||
|
||||
@@ -60,17 +60,19 @@ All 24 files below were read in full.
|
||||
| src/adapters/diagnostics/bounded-diagnostics.ts | Bounded in-memory diagnostics projection/sink and safe pre-mount boot evidence | DiagnosticsPort; contracts/diagnostics.ts and telemetry.ts; bootstrap | Preserve fail-isolated projection and cloning. Harden non-finite capacity. V3 producer fix belongs primarily in bootstrap. |
|
||||
| src/adapters/http/bounded-body-reader.ts | Declared-length and streamed byte ceilings, stream cancellation/release isolation, forbidden-body probing, strict UTF-8/JSON decode | V3 executor; bounded-body-reader tests | Keep as the single bounded response primitive. It already contains the cleanup behavior missing from bounded-json.ts. |
|
||||
| src/adapters/http/bounded-json.ts | Legacy response stream reader and JSON decoder | legacy client.ts | Replace internals with bounded-body-reader delegation, then remove with V2 retirement. Current cancel/release failures can reject. |
|
||||
| src/adapters/http/client.ts | Legacy/V2 operation lookup, profiles, auth recovery, retries, total deadline, response validation/mapping, diagnostics and telemetry | legacy contracts and ports; runtime-adapters createRuntimeHttpClient | Compatibility-only but exported. Fix empty keyed replay, cooperative auth cancellation, and common body-reader use before relying on it for rollback. Deprecate after callers are migrated. |
|
||||
| src/adapters/http/client.ts | Legacy/V2 operation lookup, profiles, auth recovery, retries, total deadline, response validation/mapping, diagnostics and telemetry | legacy contracts and ports; runtime-adapters createRuntimeHttpClient | Compatibility-only but exported. Fix empty keyed replay, cooperative auth cancellation, and common body-reader use before relying on it for rollback. Not a drop-in rollback for V3: V2 validates the `{success,data,meta}` envelope and V3 the bare DTO, so a rollback needs the four slots and a V2-envelope server (Q-6.3-11). 401 recovery is a single replay outside the retry budget. Deprecate after callers are migrated. |
|
||||
| src/adapters/http/http-contract-bridge.ts | V3 request projection, URL/body bounds, credential patch type, final request invariant | external-contract-runtime.ts; V3 executor | Preserve descriptor-owned request projection. Change credential authority: patch cannot own credentials or transport headers; final invariant must compare exact resolved profile. |
|
||||
| src/adapters/http/http-effect-certainty.ts | Converts physical-attempt state and problem descriptors into mutation certainty/UI projection | V3 executor; contracts | Preserve explicit certainty vocabulary. Add a monotonic logical-execution certainty join used across retries. |
|
||||
| src/adapters/http/http-execution-v3.ts | Descriptor-driven V3 lifetime: validation, projection, credentials, deadline, retry, fetch, response admission, effect verdict and observation | external contracts, scope, mutation intent, bridge, bounded reader, certainty, retry policy | Main correction site for N-01, N-02, N-03 and cooperative cancellation. Keep one retry authority and closed result union. |
|
||||
| src/adapters/http/request-builder.ts | Legacy path/query construction and origin/base-prefix checks | legacy client; ApiOperation | Keep while V2 remains. Do not reuse it to weaken V3 descriptor projection. |
|
||||
| src/adapters/http/resource-mapper.ts | Thin legacy operation-payload mapper delegation | boundary-mapper; legacy client | No standalone defect. Remove only with V2, not as part of the correctness patch. |
|
||||
| src/adapters/http/retry-policy.ts | Legacy retry decision/backoff plus parseRetryAfter reused by V3 | legacy client and V3 executor | Keep deterministic parse/backoff seam. V2 must additionally prove a valid key before keyed replay. |
|
||||
| src/adapters/http/retry-policy.ts | Legacy retry decision/backoff plus parseRetryAfter reused by V3; parsing delegates to kernel platform/retry-after.ts (Q-6.4-8) | legacy client and V3 executor; platform/retry-after.ts | Keep deterministic parse/backoff seam. V2 must additionally prove a valid key before keyed replay. |
|
||||
| src/adapters/http/platform-error-mapping.ts | Maps feature-less V3 transport outcomes (cancel, timeout, network, response-invalid) to the platform AppError envelope; feature-owned outcomes return null | http-execution-v3.ts outcomes; platform/errors; feature HTTP binding | Keep. Registered 2026-09-24 (added in 6f6c48e without a ledger row). |
|
||||
| src/adapters/http/schema-registry.ts | Legacy Zod envelope/request/payload validation and clone | legacy client/tests | No standalone defect. Remains V2-only and should not be merged with installed external validators. |
|
||||
| src/adapters/platform/browser-lifecycle.ts | Single owner of visibility/network/focus/page/beforeunload listeners and lifecycle snapshots | optional-runtime-host.ts | Preserve centralized listener ownership and idempotent dispose. Clarify or redesign dirty-source attachment semantics; selection item O-02. |
|
||||
| src/adapters/platform/browser-mutation-intent-factory.ts | Secure intent/idempotency UUIDs plus monotonic creation time, normalized by defineMutationIntent | MutationIntentFactory port; bootstrap | Keep. Share one idempotency-key validator so external inputs and generated values have identical bounds. |
|
||||
| src/adapters/platform/json-member-scanner.ts | Non-recursive duplicate-member and structure-budget scan before `JSON.parse`; moved from realtime in 2nd round (Q-6.4-8) | realtime event codec and WS protocol; web-push hint codec | Keep. Single scanner; web-push now checks every depth, not only top-level keys. |
|
||||
| src/adapters/platform/retry-after.ts | Strict Retry-After parser: delta-seconds or IMF-fixdate, no guessed delays (Q-6.4-8) | realtime reconnect policy / SSE; http retry-policy.ts | Keep. Rejects blank, decimal and exponent values the old http copy accepted. |
|
||||
| src/adapters/platform/system-clock.ts | Wall clock and abortable sleep with listener/timer cleanup | ClockPort; legacy HTTP | Keep. Existing unit test covers abort cleanup behavior. |
|
||||
| src/adapters/query-cache/conditional-validator-store.ts | In-memory ETag CAS sidecar keyed by scope, definition, identity, representation and cache revision | bootstrap scope reset; future conditional HTTP/query join | Fix tuple codec before composition. Preserve validator grammar, generation/revision checks and bounded capacity. |
|
||||
| src/adapters/query-cache/cursor-pagination-runtime.ts | Bounded cursor chain, page/snapshot/loop/item/byte validation | cursor pagination contract; currently available but not composed | Add post-await abort admission or an abort race. Current pre-await-only check can admit a late page. |
|
||||
@@ -79,6 +81,7 @@ All 24 files below were read in full.
|
||||
| src/adapters/query-cache/tanstack-query-cache.ts | Creates QueryClient defaults and QueryCachePort read/write/invalidate adapter with diagnostics | TanStack Query, QueryCachePort, errors/diagnostics | Keep retry disabled and clone-on-write. Clone-on-read is an optional port-semantics decision, not a confirmed production defect. |
|
||||
| src/adapters/telemetry/best-effort-telemetry.ts | Allowlisted bounded oldest-drop telemetry queue, scheduled/pagehide flush, sink isolation and evidence | TelemetryPort, telemetry/diagnostic contracts, bootstrap | Add terminal lifecycle state, joined flush promise and in-flight abort; ensure runtime composition disposes it. |
|
||||
| src/adapters/telemetry/feature-telemetry.ts | Feature TelemetryPort adapter over the platform telemetry pipeline; fetch transport to the collector endpoint | platform/telemetry pipeline; TelemetryPort; bootstrap | Keep. Registered 2026-09-24 (added in 6f6c48e without a ledger row); shares the collector with best-effort-telemetry (review 6.9-4). |
|
||||
| src/adapters/telemetry/telemetry-collector.ts | The one collector transport behind both telemetry ports: shared send-rate window, `credentials: "omit"`, `cache: "no-store"`, per-request deadline through the kernel abort primitive, one `pagehide` fan-out | platform/telemetry send rate; adapters/platform abort and capacity kernel; bootstrap | Keep. Added 2026-09-24 for review 6.9-4 / 6.3-10: a hung collector no longer stalls later flushes, and the two ports no longer send 20+20 per minute. |
|
||||
|
||||
## 4. Traced boundary inventory
|
||||
|
||||
|
||||
@@ -6,9 +6,9 @@
|
||||
- 방식: 코드 리뷰만 수행했다. 이 문서 외 구현 파일은 수정하지 않았다.
|
||||
- 결론: **Critical 0, High 4, Medium 3**이다. R-01~R-06은 코드상 확정된 lifecycle/immutability/resource 문제이고, R-07은 문서에도 미완료라고 명시된 production promotion blocker다. 두 runtime 모두 현재 `AVAILABLE_NOT_COMPOSED`이므로 production traffic 사고로 과장하지 않는다.
|
||||
|
||||
## 1. 21/21 파일 inventory와 책임
|
||||
## 1. 20/20 파일 inventory와 책임
|
||||
|
||||
아래 경로는 모두 저장소 루트 기준 full path이며, 범위의 구현 파일 21개를 모두 읽었다.
|
||||
아래 경로는 모두 저장소 루트 기준 full path이며, 범위의 구현 파일 21개를 모두 읽었다. 2차 라운드(Q-6.4-8)에서 `json-member-scanner.ts`는 kernel `src/adapters/platform/`로 옮겨 [Network/state](./01-network-and-state.md) 표에서 다룬다.
|
||||
|
||||
| # | full path | 책임 | 주요 의존성 / downstream | 판정 |
|
||||
|---:|---|---|---|---|
|
||||
@@ -16,23 +16,22 @@
|
||||
| 2 | `src/adapters/browser-rpc/index.ts` | Browser RPC public adapter export surface | runtime, transport, unavailable adapter | 새 lease/install type export 필요 |
|
||||
| 3 | `src/adapters/browser-rpc/transport.ts` | provider-neutral unary/stream transport result와 runtime identity 계약 | `src/contracts/browser-rpc.ts` | R-01, R-07 |
|
||||
| 4 | `src/adapters/browser-rpc/unavailable-browser-rpc-transport.ts` | 선택되지 않은 runtime의 명시적 fail-closed Null Object | `transport.ts` | 유지; 새 stream lease shape만 맞춤 |
|
||||
| 5 | `src/adapters/realtime/event-codec.ts` | raw JSON byte/shape/registry/schema 검증, immutable DTO와 semantic fingerprint 생성 | realtime contracts, schema registry, JSON scanner, result codec | 유지 |
|
||||
| 5 | `src/adapters/realtime/event-codec.ts` | raw JSON byte/shape/registry/schema 검증, immutable DTO와 semantic fingerprint 생성 | realtime contracts, schema registry, kernel JSON scanner, result codec | 유지 |
|
||||
| 6 | `src/adapters/realtime/event-consumer.ts` | SSE/WS cursor 규칙을 codec 결과와 결합하고 common stream coordinator outcome으로 투영 | realtime ports/contracts, event codec, stream coordinator | 유지 |
|
||||
| 7 | `src/adapters/realtime/index.ts` | common realtime adapter public export surface | codec, consumer, reconnect, handoff, stream, sub-index | R-02/R-03 lifecycle type export 필요 |
|
||||
| 8 | `src/adapters/realtime/json-member-scanner.ts` | `JSON.parse` 전 duplicate member와 structure budget을 비재귀적으로 검사 | 독립 utility | 유지 |
|
||||
| 9 | `src/adapters/realtime/live-poll-handoff-coordinator.ts` | LIVE/POLL 단일 effect writer, generation fence, quiescence/checkpoint, probe buffer와 전환 | `ClockPort`, realtime result/ports | R-03 |
|
||||
| 10 | `src/adapters/realtime/polling/bounded-poll-coordinator.ts` | visible/online finite lease, single-flight poll, retry hint, response/apply deadline, non-cooperative task drain | bounded polling policy, `ClockPort`, realtime result | 유지 |
|
||||
| 11 | `src/adapters/realtime/polling/index.ts` | polling public exports | bounded poll coordinator | 유지 |
|
||||
| 12 | `src/adapters/realtime/reconnect-coordinator.ts` | 단일 reconnect owner, online gate, retry budget, session close authority, exact recovery proof, post-abort DRAINING | reconnect policy, `ClockPort`, realtime ports/result | 유지 |
|
||||
| 13 | `src/adapters/realtime/reconnect-policy.ts` | immutable reconnect policy, full jitter, elapsed budget, Retry-After 계산/검증 | 독립 policy | 유지 |
|
||||
| 14 | `src/adapters/realtime/result.ts` | hostile/mutable collaborator result를 exact own-data snapshot으로 canonicalize | realtime ports/contracts | 유지; R-04의 기준 패턴 |
|
||||
| 15 | `src/adapters/realtime/sse/fetch-sse-connection.ts` | fixed same-origin fetch-stream SSE, response/media/open gate, read/event deadline, cursor rule, bounded reader cancel | `ClockPort`, event authority/result, parser, reconnect policy | 유지; R-02 common drain과 함께 검증 |
|
||||
| 16 | `src/adapters/realtime/sse/index.ts` | SSE public exports | fetch connection, parser | 유지 |
|
||||
| 17 | `src/adapters/realtime/sse/sse-parser.ts` | strict incremental UTF-8 SSE parser, BOM/line ending/id/retry/event buffer ceiling | realtime contracts/result | 유지 |
|
||||
| 18 | `src/adapters/realtime/stream-coordinator.ts` | per-stream sequential effect, dedupe/order, recovery, checkpoint/barrier, scope generation fence | event authority port, realtime contracts, mapper registry, codec/result | R-02 |
|
||||
| 19 | `src/adapters/realtime/websocket/index.ts` | WebSocket connection/protocol public exports | connection, protocol | 유지 |
|
||||
| 20 | `src/adapters/realtime/websocket/websocket-connection.ts` | 한 physical WS의 handshake/subscription/tombstone/FIFO/heartbeat/apply gate/recovery close | `ClockPort`, realtime contracts/result, WS protocol | 유지; R-02 upstream timeout과 함께 검증 |
|
||||
| 21 | `src/adapters/realtime/websocket/websocket-protocol.ts` | exact closed JSON frame decode/encode, duplicate key/structure/sequence/frame byte 검증 | realtime contracts, JSON scanner | R-05 |
|
||||
| 8 | `src/adapters/realtime/live-poll-handoff-coordinator.ts` | LIVE/POLL 단일 effect writer, generation fence, quiescence/checkpoint, probe buffer와 전환 | `ClockPort`, realtime result/ports | R-03 |
|
||||
| 9 | `src/adapters/realtime/polling/bounded-poll-coordinator.ts` | visible/online finite lease, single-flight poll, retry hint, response/apply deadline, non-cooperative task drain | bounded polling policy, `ClockPort`, realtime result | 유지 |
|
||||
| 10 | `src/adapters/realtime/polling/index.ts` | polling public exports | bounded poll coordinator | 유지 |
|
||||
| 11 | `src/adapters/realtime/reconnect-coordinator.ts` | 단일 reconnect owner, online gate, retry budget, session close authority, exact recovery proof, post-abort DRAINING | reconnect policy, `ClockPort`, realtime ports/result | 유지 |
|
||||
| 12 | `src/adapters/realtime/reconnect-policy.ts` | immutable reconnect policy, full jitter, elapsed budget; Retry-After 파서는 kernel `platform/retry-after.ts`를 re-export | kernel retry-after | 유지 |
|
||||
| 13 | `src/adapters/realtime/result.ts` | hostile/mutable collaborator result를 exact own-data snapshot으로 canonicalize | realtime ports/contracts | 유지; R-04의 기준 패턴 |
|
||||
| 14 | `src/adapters/realtime/sse/fetch-sse-connection.ts` | fixed same-origin fetch-stream SSE, response/media/open gate, read/event deadline, cursor rule, bounded reader cancel | `ClockPort`, event authority/result, parser, reconnect policy | 유지; R-02 common drain과 함께 검증 |
|
||||
| 15 | `src/adapters/realtime/sse/index.ts` | SSE public exports | fetch connection, parser | 유지 |
|
||||
| 16 | `src/adapters/realtime/sse/sse-parser.ts` | strict incremental UTF-8 SSE parser, BOM/line ending/id/retry/event buffer ceiling | realtime contracts/result | 유지 |
|
||||
| 17 | `src/adapters/realtime/stream-coordinator.ts` | per-stream sequential effect, dedupe/order, recovery, checkpoint/barrier, scope generation fence | event authority port, realtime contracts, mapper registry, codec/result | R-02 |
|
||||
| 18 | `src/adapters/realtime/websocket/index.ts` | WebSocket connection/protocol public exports | connection, protocol | 유지 |
|
||||
| 19 | `src/adapters/realtime/websocket/websocket-connection.ts` | 한 physical WS의 handshake/subscription/tombstone/FIFO/heartbeat/apply gate/recovery close | `ClockPort`, realtime contracts/result, WS protocol | 유지; R-02 upstream timeout과 함께 검증 |
|
||||
| 20 | `src/adapters/realtime/websocket/websocket-protocol.ts` | exact closed JSON frame decode/encode, duplicate key/structure/sequence/frame byte 검증 | realtime contracts, kernel JSON scanner | R-05 |
|
||||
|
||||
## 2. 추적한 contracts, ports, bootstrap, tests, docs
|
||||
|
||||
|
||||
@@ -43,6 +43,7 @@
|
||||
| `src/adapters/browser-files/browser-file-vault.ts` | transient native File/handle 보관, opaque ref, inspection receipt, bounded range/source | file port/shared/result/policy registry. File이 application 경계를 넘지 않고 receipt가 exact file/profile에 묶이는 설계가 좋다. |
|
||||
| `src/adapters/browser-files/create-browser-file-runtime.ts` | vault/picker/preview/download를 선택적으로 조립하고 일괄 dispose | 위 adapters 및 application contracts. optional capability를 제품 선택 없이 bootstrap에 암묵 조립하지 않는 점을 유지. preview 조립 전 GAP-01 gate 필요. |
|
||||
| `src/adapters/browser-files/download-delivery-adapter.ts` | browser handoff, foreground save stream, bounded object URL download, integrity/progress/cancellation | file/authorized-download ports, policy registry, object URL lease, Result. STO-02와 STO-08; stream close truth/backpressure는 유지. |
|
||||
| `src/adapters/browser-files/download-input-validation.ts` | download 요청 snapshot, policy/limit/activation 검증, presigned·browser-managed capability 검증, canonical handoff target 해석 | file/authorized-download ports, policy registry, `file-policy.ts`, Result. Q-6.2-11에서 adapter에서 그대로 옮겼다(동작 불변). |
|
||||
| `src/adapters/browser-files/file-observer.ts` | file-safe observation DTO를 공통 browser observation으로 변환 | shared port/result. raw filename/ref 비노출 유지. |
|
||||
| `src/adapters/browser-files/file-policy.ts` | policy input validation, MIME/extension/signature/hard byte caps, immutable resolved policy | file/shared contracts. closed allowlist 및 absolute ceiling을 유지. |
|
||||
| `src/adapters/browser-files/index.ts` | browser-file public exports | 위 모듈. native implementation detail export 확장을 피한다. |
|
||||
@@ -53,7 +54,9 @@
|
||||
| 파일 | 책임 | 주요 의존성 / 리뷰 결과 |
|
||||
| --- | --- | --- |
|
||||
| `src/adapters/cache-storage/index.ts` | public cache policy/adapter barrel | optional public static cache만 export; private/range cache로 일반화하지 않는다. |
|
||||
| `src/adapters/cache-storage/public-cache-codec.ts` | manifest 정규화·canonical digest 입력, marker/active pointer 검증, bounded control JSON 읽기, owned cache 이름, 검증 실패 → Result 매핑 | cache ports/result/policy. Q-6.2-11에서 adapter에서 그대로 옮겼다(동작 불변). |
|
||||
| `src/adapters/cache-storage/public-cache-policy.ts` | same-origin/public-only release 정책, URL/header/query/size/retention hard limits | cache ports/shared. STO-03 policy cross-field invariant 누락. 기본 policy에는 `vary`가 있어 기본-path 테스트는 통과한다. |
|
||||
| `src/adapters/cache-storage/public-cache-response-validation.ts` | network/cached response 수용 검증: status, cache directive, Content-Type, Vary, bounded body, digest | `public-cache-codec.ts`, policy, Result. Q-6.2-11에서 adapter에서 그대로 옮겼다(동작 불변). |
|
||||
| `src/adapters/cache-storage/public-response-cache-adapter.ts` | manifest canonicalization/digest, anonymous fetch, bounded body 검증, candidate marker-last staging, explicit activation, exact lookup/reverify, owned cleanup/inspect | cache ports/result/policy, CacheStorage/fetch/Crypto/Web Lock snapshot. STO-03~05 및 GAP-02. private/auth/opaque/206 거절과 current+previous 보존은 유지. |
|
||||
|
||||
### 1.4 `storage` root / IndexedDB
|
||||
@@ -67,6 +70,7 @@
|
||||
| `src/adapters/storage/indexeddb/indexeddb-governance.ts` | opaque dataset scope/physical DB identity 및 frozen policy binding | indexeddb/shared ports. account/business ID를 physical name에 쓰지 않는 양방향 binding 유지. |
|
||||
| `src/adapters/storage/indexeddb/indexeddb-maintenance.ts` | post-open codec migration 및 idempotency receipt prune, keyset checkpoint, budget/revision fencing | IndexedDB port/types/failure/governance. async transform outside tx, row+sidecar+budget+checkpoint atomic commit은 좋다. STO-06 및 temporal drain lease 개선 후보. |
|
||||
| `src/adapters/storage/indexeddb/indexeddb-migrations.ts` | additive-only contiguous DDL planner/validator | indexeddb types. destructive DDL 거절 유지. |
|
||||
| `src/adapters/storage/indexeddb/indexeddb-records.ts` | runtime·maintenance·dataset binding이 함께 쓰는 저장 행 타입, 검증기, record 바이트 측정, `countBucket`/`failureOf` | IndexedDB port/shared/types. Q-6.5-7: 복사본 3벌을 하나로 합쳤다. 실패 코드는 호출부가 정한다(runtime `INVALID_INPUT`, maintenance `MIGRATION_FAILED`). budget의 `hardBudgetBytes` 상한은 binding 검증에서만 본다. |
|
||||
| `src/adapters/storage/indexeddb/indexeddb-runtime.ts` | generic repository open/read/query/CAS/delete, idempotency, retention, lifecycle purge, connection lifecycle | indexeddb ports/types/governance/failure/migrations. transaction `complete` truth, versionchange close, shared open/abort isolation, exact budgets 유지. lifecycle proof는 현재 문서 계약(형식 검증 후 폐기)과 일치하므로 결함으로 분류하지 않았다. |
|
||||
| `src/adapters/storage/indexeddb/indexeddb-types.ts` | adapter-local codec/query/schema/dependency contracts | application indexeddb/shared ports. `isOldWriterDrainConfirmed()` boolean은 provider가 전체 window를 보장한다는 문서 전제; lease형으로 강화 권고. |
|
||||
|
||||
|
||||
@@ -35,6 +35,7 @@
|
||||
| --- | --- | --- | --- |
|
||||
| `browser-transfer/index.ts` | 하위 capability export | KEEP | public export 증가는 각 capability 계획에서만 수행 |
|
||||
| `presigned/index.ts` | presigned public surface | KEEP | `BT-PRE-04`에서 vault issuer 노출만 축소 검토 |
|
||||
| `presigned/http-common.ts` | executor·provider 공용 HTTP 메커니즘(abort scope, status 표, Content-Length 파싱, body 취소) | KEEP | Q-6.1-9. 두 벌이던 사본을 합쳤다. status 표는 여기 한 벌만 둔다 |
|
||||
| `presigned/incremental-sha256.ts` | streaming SHA-256 | KEEP | WebCrypto `digest()`로 바꾸면 전체 buffering이 되므로 교체 금지 |
|
||||
| `presigned/presigned-capability-http-provider.ts` | BFF capability 발급, strict decode | CONTRACT_GAP | `BT-PRE-02`, `BT-PRE-03`, `BT-X-01` |
|
||||
| `presigned/presigned-capability-vault.ts` | identity capability 보관/폐기 | REFACTOR | `BT-PRE-04` |
|
||||
@@ -45,8 +46,10 @@
|
||||
| `resumable-upload/index.ts` | resumable public surface | KEEP | facade 호환 유지 |
|
||||
| `resumable-upload/indexeddb-checkpoint-store.ts` | scope-bound CAS store/admin | VERIFIED_DEFECT | `BT-UP-03` |
|
||||
| `resumable-upload/presigned-upload-part-executor.ts` | multipart와 presigned bridge | VERIFIED_DEFECT | `BT-UP-04` |
|
||||
| `resumable-upload/resumable-upload-runtime.ts` | session state/retry/part scheduling/commit | REFACTOR | `BT-UP-05`, `BT-UP-06` |
|
||||
| `resumable-upload/resumable-upload-runtime.ts` | session state/retry/part scheduling/commit | REFACTOR | `BT-UP-05`, `BT-UP-06`. Q-6.1-10에서 검증·snapshot 래퍼를 분리 |
|
||||
| `resumable-upload/runtime-dependencies.ts` | runtime 주입 의존성 검증과 메서드 snapshot, clock/random guard | KEEP | Q-6.1-10. runtime 파일에서 분리, 동작 불변 |
|
||||
| `resumable-upload/runtime-policy.ts` | hard bound snapshot | KEEP | 값 변경은 contract migration으로만 수행 |
|
||||
| `resumable-upload/upload-response-validation.ts` | session/status/part capability/receipt strict decoder | KEEP | Q-6.1-10. runtime 파일에서 분리, 동작 불변 |
|
||||
| `resumable-upload/upload-byte-source.ts` | stream/range source snapshot과 hashing | KEEP/REFACTOR | runtime에서 source preparation Strategy로 주입 |
|
||||
| `resumable-upload/upload-cancellation-channel.ts` | best-effort cross-context cancel hint | KEEP | backend/CAS가 authority라는 주석과 동작 유지 |
|
||||
| `resumable-upload/upload-mutation-lock.ts` | Web Lock exclusive mutation | PLANNED_GAP | `BT-UP-07` |
|
||||
|
||||
@@ -30,6 +30,7 @@ Web Push는 현재 `AVAILABLE_NOT_COMPOSED`이고 제품 선택도 `NOT_SELECTED
|
||||
| `service-worker-protocol.ts` | page-worker strict message codec/nonce | CONTRACT_GAP | `SW-06`, `SW-10` |
|
||||
| `service-worker-removal.ts` | exact registration/cache ownership cleanup | VERIFIED_DEFECT | `SW-03` |
|
||||
| `service-worker-static-assets.ts` | static manifest/install/cache policy | KEEP/REFACTOR | `SW-01`, `SW-05`, `SW-09` |
|
||||
| `web-push/codec-primitives.ts` | 공유 검증 primitive(base64url decode, opaque id, authority, exact record) | KEEP | Q-6.6-12에서 4개 파일의 복사본을 합침. 복사본이 다르던 곳은 더 엄격한 쪽을 유지 |
|
||||
| `web-push/index.ts` | public exports | KEEP | product selection 전 surface 확대 금지 |
|
||||
| `web-push/notification-registry.ts` | closed copy/route registry | KEEP | arbitrary copy/URL 허용 금지 |
|
||||
| `web-push/push-association-fence-store.ts` | durable authority state machine | VERIFIED_DEFECT | `WP-01`, `WP-02` |
|
||||
|
||||
+137
-127
@@ -18,132 +18,142 @@
|
||||
| 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/platform-error-mapping.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 61 | `src/adapters/http/request-builder.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 62 | `src/adapters/http/resource-mapper.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 63 | `src/adapters/http/retry-policy.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 64 | `src/adapters/http/schema-registry.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 65 | `src/adapters/platform/abortable-operation.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 66 | `src/adapters/platform/bounded-capacity.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 67 | `src/adapters/platform/browser-lifecycle.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 68 | `src/adapters/platform/browser-mutation-intent-factory.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 69 | `src/adapters/platform/index.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 70 | `src/adapters/platform/indexeddb-connection.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 71 | `src/adapters/platform/indexeddb-transaction.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 72 | `src/adapters/platform/system-clock.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 73 | `src/adapters/query-cache/conditional-validator-store.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 74 | `src/adapters/query-cache/cursor-pagination-contract.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 75 | `src/adapters/query-cache/cursor-pagination-runtime.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 76 | `src/adapters/query-cache/index.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 77 | `src/adapters/query-cache/server-state-scope-runtime.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 78 | `src/adapters/query-cache/tanstack-cache-coordinator.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 79 | `src/adapters/query-cache/tanstack-query-cache.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 80 | `src/adapters/realtime/event-codec.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 81 | `src/adapters/realtime/event-consumer.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 82 | `src/adapters/realtime/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 83 | `src/adapters/realtime/json-member-scanner.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 84 | `src/adapters/realtime/live-poll-handoff-coordinator.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 85 | `src/adapters/realtime/polling/bounded-poll-coordinator.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 86 | `src/adapters/realtime/polling/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 87 | `src/adapters/realtime/reconnect-coordinator.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 88 | `src/adapters/realtime/reconnect-policy.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 89 | `src/adapters/realtime/result.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 90 | `src/adapters/realtime/sse/fetch-sse-connection.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 91 | `src/adapters/realtime/sse/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 92 | `src/adapters/realtime/sse/sse-parser.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 93 | `src/adapters/realtime/stream-coordinator.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 94 | `src/adapters/realtime/websocket/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 95 | `src/adapters/realtime/websocket/websocket-connection.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 96 | `src/adapters/realtime/websocket/websocket-protocol.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 97 | `src/adapters/service-worker/index.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 98 | `src/adapters/service-worker/service-worker-entry.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 99 | `src/adapters/service-worker/service-worker-lifecycle.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 100 | `src/adapters/service-worker/service-worker-page-controller.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 101 | `src/adapters/service-worker/service-worker-protocol.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 102 | `src/adapters/service-worker/service-worker-removal.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 103 | `src/adapters/service-worker/service-worker-static-assets.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 104 | `src/adapters/storage/browser-storage-adapter.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 105 | `src/adapters/storage/browser-storage-codec.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 106 | `src/adapters/storage/index.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 107 | `src/adapters/storage/indexeddb/index.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 108 | `src/adapters/storage/indexeddb/indexeddb-failure.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 109 | `src/adapters/storage/indexeddb/indexeddb-governance.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 110 | `src/adapters/storage/indexeddb/indexeddb-maintenance.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 111 | `src/adapters/storage/indexeddb/indexeddb-migrations.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 112 | `src/adapters/storage/indexeddb/indexeddb-runtime.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 113 | `src/adapters/storage/indexeddb/indexeddb-types.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 114 | `src/adapters/storage/opfs/browser-opfs-runtime.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 115 | `src/adapters/storage/opfs/index.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 116 | `src/adapters/storage/opfs/indexeddb-opfs-journal.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 117 | `src/adapters/storage/opfs/opfs-byte-store-adapter.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 118 | `src/adapters/storage/opfs/opfs-policy.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 119 | `src/adapters/storage/opfs/opfs-prepared-object.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 120 | `src/adapters/storage/opfs/opfs-worker-client.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 121 | `src/adapters/storage/opfs/opfs-worker-protocol.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 122 | `src/adapters/storage/opfs/opfs-worker-runtime.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 123 | `src/adapters/telemetry/best-effort-telemetry.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 124 | `src/adapters/telemetry/feature-telemetry.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 125 | `src/adapters/telemetry/index.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 126 | `src/adapters/web-push/inbound/notification-click-adapter.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 127 | `src/adapters/web-push/inbound/push-event-adapter.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 128 | `src/adapters/web-push/index.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 129 | `src/adapters/web-push/notification-registry.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 130 | `src/adapters/web-push/push-association-fence-store.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 131 | `src/adapters/web-push/push-codec.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 132 | `src/adapters/web-push/push-registration-gateway.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 133 | `src/adapters/web-push/push-subscription-adapter.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 134 | `src/adapters/web-push/runtime-support.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 135 | `src/adapters/web-push/service-worker-runtime.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 136 | `src/adapters/web-push/service-worker-scope-host.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 11 | `src/adapters/browser-files/download-input-validation.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 12 | `src/adapters/browser-files/file-observer.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 13 | `src/adapters/browser-files/file-policy.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 14 | `src/adapters/browser-files/index.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 15 | `src/adapters/browser-files/object-url-lease.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 16 | `src/adapters/browser-rpc/browser-rpc-runtime.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 17 | `src/adapters/browser-rpc/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 18 | `src/adapters/browser-rpc/transport.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 19 | `src/adapters/browser-rpc/unavailable-browser-rpc-transport.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 20 | `src/adapters/browser-transfer/image-cdn/README.md` | [Browser transfer](./04-browser-transfer.md) |
|
||||
| 21 | `src/adapters/browser-transfer/image-cdn/browser-image-probe.ts` | [Browser transfer](./04-browser-transfer.md) |
|
||||
| 22 | `src/adapters/browser-transfer/image-cdn/image-cdn-policy.ts` | [Browser transfer](./04-browser-transfer.md) |
|
||||
| 23 | `src/adapters/browser-transfer/image-cdn/image-cdn-runtime.ts` | [Browser transfer](./04-browser-transfer.md) |
|
||||
| 24 | `src/adapters/browser-transfer/image-cdn/image-header-metadata.ts` | [Browser transfer](./04-browser-transfer.md) |
|
||||
| 25 | `src/adapters/browser-transfer/image-cdn/index.ts` | [Browser transfer](./04-browser-transfer.md) |
|
||||
| 26 | `src/adapters/browser-transfer/image-cdn/p256-image-capability-verifier.ts` | [Browser transfer](./04-browser-transfer.md) |
|
||||
| 27 | `src/adapters/browser-transfer/index.ts` | [Browser transfer](./04-browser-transfer.md) |
|
||||
| 28 | `src/adapters/browser-transfer/presigned/http-common.ts` | [Browser transfer](./04-browser-transfer.md) |
|
||||
| 29 | `src/adapters/browser-transfer/presigned/incremental-sha256.ts` | [Browser transfer](./04-browser-transfer.md) |
|
||||
| 30 | `src/adapters/browser-transfer/presigned/index.ts` | [Browser transfer](./04-browser-transfer.md) |
|
||||
| 31 | `src/adapters/browser-transfer/presigned/presigned-capability-http-provider.ts` | [Browser transfer](./04-browser-transfer.md) |
|
||||
| 32 | `src/adapters/browser-transfer/presigned/presigned-capability-vault.ts` | [Browser transfer](./04-browser-transfer.md) |
|
||||
| 33 | `src/adapters/browser-transfer/presigned/presigned-transfer-executor.ts` | [Browser transfer](./04-browser-transfer.md) |
|
||||
| 34 | `src/adapters/browser-transfer/resumable-upload/checkpoint-schema.ts` | [Browser transfer](./04-browser-transfer.md) |
|
||||
| 35 | `src/adapters/browser-transfer/resumable-upload/fetch-json-transport.ts` | [Browser transfer](./04-browser-transfer.md) |
|
||||
| 36 | `src/adapters/browser-transfer/resumable-upload/http-control-plane-adapter.ts` | [Browser transfer](./04-browser-transfer.md) |
|
||||
| 37 | `src/adapters/browser-transfer/resumable-upload/index.ts` | [Browser transfer](./04-browser-transfer.md) |
|
||||
| 38 | `src/adapters/browser-transfer/resumable-upload/indexeddb-checkpoint-store.ts` | [Browser transfer](./04-browser-transfer.md) |
|
||||
| 39 | `src/adapters/browser-transfer/resumable-upload/presigned-upload-part-executor.ts` | [Browser transfer](./04-browser-transfer.md) |
|
||||
| 40 | `src/adapters/browser-transfer/resumable-upload/resumable-upload-runtime.ts` | [Browser transfer](./04-browser-transfer.md) |
|
||||
| 41 | `src/adapters/browser-transfer/resumable-upload/runtime-dependencies.ts` | [Browser transfer](./04-browser-transfer.md) |
|
||||
| 42 | `src/adapters/browser-transfer/resumable-upload/runtime-policy.ts` | [Browser transfer](./04-browser-transfer.md) |
|
||||
| 43 | `src/adapters/browser-transfer/resumable-upload/upload-byte-source.ts` | [Browser transfer](./04-browser-transfer.md) |
|
||||
| 44 | `src/adapters/browser-transfer/resumable-upload/upload-cancellation-channel.ts` | [Browser transfer](./04-browser-transfer.md) |
|
||||
| 45 | `src/adapters/browser-transfer/resumable-upload/upload-mutation-lock.ts` | [Browser transfer](./04-browser-transfer.md) |
|
||||
| 46 | `src/adapters/browser-transfer/resumable-upload/upload-response-validation.ts` | [Browser transfer](./04-browser-transfer.md) |
|
||||
| 47 | `src/adapters/cache-storage/index.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 48 | `src/adapters/cache-storage/public-cache-codec.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 49 | `src/adapters/cache-storage/public-cache-policy.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 50 | `src/adapters/cache-storage/public-cache-response-validation.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 51 | `src/adapters/cache-storage/public-response-cache-adapter.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 52 | `src/adapters/cross-context-invalidation/browser-cross-context-host.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 53 | `src/adapters/cross-context-invalidation/browser-cross-context-invalidation.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 54 | `src/adapters/cross-context-invalidation/index.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 55 | `src/adapters/diagnostics/bounded-diagnostics.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 56 | `src/adapters/diagnostics/index.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 57 | `src/adapters/http/bounded-body-reader.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 58 | `src/adapters/http/bounded-json.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 59 | `src/adapters/http/client.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 60 | `src/adapters/http/feature-http-binding.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 61 | `src/adapters/http/http-contract-bridge.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 62 | `src/adapters/http/http-effect-certainty.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 63 | `src/adapters/http/http-execution-v3.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 64 | `src/adapters/http/http-retry-lifecycle.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 65 | `src/adapters/http/index.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 66 | `src/adapters/http/platform-error-mapping.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 67 | `src/adapters/http/request-builder.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 68 | `src/adapters/http/resource-mapper.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 69 | `src/adapters/http/retry-policy.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 70 | `src/adapters/http/schema-registry.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 71 | `src/adapters/platform/abortable-operation.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 72 | `src/adapters/platform/bounded-capacity.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 73 | `src/adapters/platform/browser-lifecycle.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 74 | `src/adapters/platform/browser-mutation-intent-factory.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 75 | `src/adapters/platform/index.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 76 | `src/adapters/platform/indexeddb-connection.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 77 | `src/adapters/platform/indexeddb-transaction.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 78 | `src/adapters/platform/json-member-scanner.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 79 | `src/adapters/platform/retry-after.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 80 | `src/adapters/platform/system-clock.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 81 | `src/adapters/query-cache/conditional-validator-store.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 82 | `src/adapters/query-cache/cursor-pagination-contract.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 83 | `src/adapters/query-cache/cursor-pagination-runtime.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 84 | `src/adapters/query-cache/index.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 85 | `src/adapters/query-cache/server-state-scope-runtime.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 86 | `src/adapters/query-cache/tanstack-cache-coordinator.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 87 | `src/adapters/query-cache/tanstack-query-cache.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 88 | `src/adapters/realtime/event-codec.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 89 | `src/adapters/realtime/event-consumer.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 90 | `src/adapters/realtime/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 91 | `src/adapters/realtime/live-poll-handoff-coordinator.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 92 | `src/adapters/realtime/polling/bounded-poll-coordinator.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 93 | `src/adapters/realtime/polling/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 94 | `src/adapters/realtime/reconnect-coordinator.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 95 | `src/adapters/realtime/reconnect-policy.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 96 | `src/adapters/realtime/result.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 97 | `src/adapters/realtime/sse/fetch-sse-connection.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 98 | `src/adapters/realtime/sse/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 99 | `src/adapters/realtime/sse/sse-parser.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 100 | `src/adapters/realtime/stream-coordinator.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 101 | `src/adapters/realtime/websocket/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 102 | `src/adapters/realtime/websocket/websocket-connection.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 103 | `src/adapters/realtime/websocket/websocket-protocol.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 104 | `src/adapters/service-worker/index.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 105 | `src/adapters/service-worker/service-worker-entry.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 106 | `src/adapters/service-worker/service-worker-lifecycle.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 107 | `src/adapters/service-worker/service-worker-page-controller.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 108 | `src/adapters/service-worker/service-worker-protocol.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 109 | `src/adapters/service-worker/service-worker-removal.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 110 | `src/adapters/service-worker/service-worker-static-assets.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 111 | `src/adapters/storage/browser-storage-adapter.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 112 | `src/adapters/storage/browser-storage-codec.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 113 | `src/adapters/storage/index.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 114 | `src/adapters/storage/indexeddb/index.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 115 | `src/adapters/storage/indexeddb/indexeddb-failure.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 116 | `src/adapters/storage/indexeddb/indexeddb-governance.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 117 | `src/adapters/storage/indexeddb/indexeddb-maintenance.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 118 | `src/adapters/storage/indexeddb/indexeddb-migrations.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 119 | `src/adapters/storage/indexeddb/indexeddb-records.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 120 | `src/adapters/storage/indexeddb/indexeddb-runtime.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 121 | `src/adapters/storage/indexeddb/indexeddb-types.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 122 | `src/adapters/storage/opfs/browser-opfs-runtime.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 123 | `src/adapters/storage/opfs/index.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 124 | `src/adapters/storage/opfs/indexeddb-opfs-journal.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 125 | `src/adapters/storage/opfs/opfs-byte-store-adapter.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 126 | `src/adapters/storage/opfs/opfs-policy.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 127 | `src/adapters/storage/opfs/opfs-prepared-object.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 128 | `src/adapters/storage/opfs/opfs-worker-client.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 129 | `src/adapters/storage/opfs/opfs-worker-protocol.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 130 | `src/adapters/storage/opfs/opfs-worker-runtime.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 131 | `src/adapters/telemetry/best-effort-telemetry.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 132 | `src/adapters/telemetry/feature-telemetry.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 133 | `src/adapters/telemetry/index.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 134 | `src/adapters/telemetry/telemetry-collector.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 135 | `src/adapters/web-push/codec-primitives.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 136 | `src/adapters/web-push/inbound/notification-click-adapter.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 137 | `src/adapters/web-push/inbound/push-event-adapter.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 138 | `src/adapters/web-push/index.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 139 | `src/adapters/web-push/notification-registry.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 140 | `src/adapters/web-push/push-association-fence-store.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 141 | `src/adapters/web-push/push-codec.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 142 | `src/adapters/web-push/push-registration-gateway.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 143 | `src/adapters/web-push/push-subscription-adapter.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 144 | `src/adapters/web-push/runtime-support.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 145 | `src/adapters/web-push/service-worker-runtime.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 146 | `src/adapters/web-push/service-worker-scope-host.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
|
||||
합계: **136/136**. 새 adapter 파일이 추가되면 이 ledger와 해당 상세 리뷰 inventory를 같은 변경에서 갱신한다.
|
||||
합계: **146/146**. 새 adapter 파일이 추가되면 이 ledger와 해당 상세 리뷰 inventory를 같은 변경에서 갱신한다.
|
||||
|
||||
|
||||
@@ -57,7 +57,9 @@ RP-07 구현 이후 이 기반은 저장소 내부 디자인 시스템 플랫폼
|
||||
3. 앱 셸, 예제와 reference feature는 public design-system barrel을 소비한다.
|
||||
4. 문자 glyph는 semantic Lucide facade로 교체됐다.
|
||||
5. token은 세 CSS 파일로 분리됐고 `theme.css`는 layout/component styling만
|
||||
소유한다.
|
||||
소유한다. `theme.css`는 import 순서만 정하는 진입점이고, 실제 규칙은
|
||||
`styles/theme/` 아래 파일(base, shell, primitives, templates, pages,
|
||||
responsive)에 같은 순서로 있다.
|
||||
6. runtime gallery는 있지만 격리된 story, interaction story, 시각 회귀 기준선이
|
||||
없다.
|
||||
7. 사용자 문구가 한국어 literal로 고정되어 locale과 RTL 계약이 없다.
|
||||
|
||||
+12
-1
@@ -7,7 +7,18 @@
|
||||
<title>Clean Architecture Frontend</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<div id="root">
|
||||
<!-- Q-6.9-8. Static boot shell: visible while config, manifest and
|
||||
contract checks run; the first React render replaces it. -->
|
||||
<div
|
||||
class="state-surface state-surface--loading"
|
||||
role="status"
|
||||
aria-busy="true"
|
||||
data-boot-shell=""
|
||||
>
|
||||
불러오는 중
|
||||
</div>
|
||||
</div>
|
||||
<script type="module" src="/src/bootstrap/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -201,7 +201,11 @@ async function main(): Promise<void> {
|
||||
// 23 → 22: `storage/indexeddb/indexeddb-maintenance.ts`가 같은 이유로 지웠다.
|
||||
// 22 → 21: `storage/indexeddb/indexeddb-runtime.ts`가 같은 이유로 지웠다.
|
||||
// 이것으로 IndexedDB 어댑터 4벌이 모두 커널을 쓴다.
|
||||
const HAND_ROLLED_ABORT_CEILING = 21;
|
||||
// 21 → 19: `browser-files/download-delivery-adapter.ts`와
|
||||
// `browser-files/browser-file-vault.ts`가 커널 race로 옮겨갔다(Q-6.2-7).
|
||||
// 19 → 18: `browser-file-storage/storage-manager-adapter.ts`의 inspection
|
||||
// 대기가 커널 race로 옮겨갔다(Q-B).
|
||||
const HAND_ROLLED_ABORT_CEILING = 17;
|
||||
const handRolledScan = spawnSync(
|
||||
"git",
|
||||
["grep", "-l", 'addEventListener("abort"', "--", "src/adapters"],
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
|
||||
import { evaluateBundleBudget } from "../src/application/policies/performance-budgets.ts";
|
||||
import { evaluateBundleBudget } from "./lib/performance-budgets.ts";
|
||||
import {
|
||||
bundleOutputInventoryArtifactSchema,
|
||||
bundlePerformanceArtifactSchema,
|
||||
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
evaluatePromotionReadiness,
|
||||
PROMOTION_FORMULA,
|
||||
type GateResult,
|
||||
} from "../src/application/policies/promotion-readiness.ts";
|
||||
} from "./lib/promotion-readiness.ts";
|
||||
import {
|
||||
loadCiGateContract,
|
||||
indexCiGateContract,
|
||||
|
||||
@@ -28,8 +28,14 @@ for (const [layer, file, tokens] of tokenLayers) {
|
||||
}
|
||||
}
|
||||
|
||||
// theme.css only imports the files under styles/theme/, so check them all.
|
||||
const styleFiles = (
|
||||
await readdir("src/presentation/styles", { recursive: true })
|
||||
)
|
||||
.filter((file) => file.endsWith(".css"))
|
||||
.map((file) => path.join("src/presentation/styles", file));
|
||||
const cssSources = await Promise.all(
|
||||
[...Object.values(tokenFiles), "src/presentation/styles/theme.css"].map(
|
||||
[...Object.values(tokenFiles), ...styleFiles].map(
|
||||
async (file) => ({ file, source: await readFile(file, "utf8") }),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -3,7 +3,7 @@ import { mkdir, readFile } from "node:fs/promises";
|
||||
import {
|
||||
evaluateFieldBudget,
|
||||
percentile75,
|
||||
} from "../src/application/policies/performance-budgets.ts";
|
||||
} from "./lib/performance-budgets.ts";
|
||||
import { fieldWebVitalsArtifactSchema } from "./contracts/release-artifacts.ts";
|
||||
import { validateFieldEvidenceInput } from "./lib/field-vitals-evidence.ts";
|
||||
import { writeValidatedJsonArtifact } from "./lib/validated-json-artifact.ts";
|
||||
|
||||
@@ -4,7 +4,7 @@ import path from "node:path";
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
import { PROMOTION_FORMULA } from "../../src/application/policies/promotion-readiness.ts";
|
||||
import { PROMOTION_FORMULA } from "../lib/promotion-readiness.ts";
|
||||
import {
|
||||
RELEASE_CANDIDATE_EVIDENCE_PATHS,
|
||||
RELEASE_CANDIDATE_MANIFEST_PATH,
|
||||
|
||||
@@ -5,7 +5,7 @@ import process from "node:process";
|
||||
|
||||
import { chromium } from "@playwright/test";
|
||||
|
||||
import { evaluateLabBudget } from "../src/application/policies/performance-budgets.ts";
|
||||
import { evaluateLabBudget } from "./lib/performance-budgets.ts";
|
||||
import { ROUTE_REGISTRY } from "../src/features/installed-feature-contracts.ts";
|
||||
import { labPerformanceArtifactSchema } from "./contracts/release-artifacts.ts";
|
||||
import { writeValidatedJsonArtifact } from "./lib/validated-json-artifact.ts";
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
browserDataSuccess,
|
||||
mapBrowserDataException,
|
||||
} from "./result.ts";
|
||||
import { createAbortableOperation } from "../platform/abortable-operation.ts";
|
||||
|
||||
export type StorageManagerFacade = Readonly<{
|
||||
estimate(): Promise<Readonly<{ usage?: number; quota?: number }>>;
|
||||
@@ -155,48 +156,22 @@ function snapshotPressurePolicy(
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
/**
|
||||
* The kernel race: a caller abort ends the wait, and a native call that settles
|
||||
* afterwards — including one that rejects — is consumed rather than leaked.
|
||||
*/
|
||||
async function awaitStorageInspection<Value>(
|
||||
inspection: Promise<Value>,
|
||||
signal: AbortSignal | undefined,
|
||||
): Promise<Value | typeof STORAGE_INSPECTION_ABORTED> {
|
||||
if (!signal) return await inspection;
|
||||
if (signal.aborted) {
|
||||
// The native calls have already been invoked. Consume a later rejection
|
||||
// even though the caller no longer waits for their result.
|
||||
void inspection.catch(() => undefined);
|
||||
return STORAGE_INSPECTION_ABORTED;
|
||||
const operation = createAbortableOperation({ signal });
|
||||
try {
|
||||
const raced = await operation.race(inspection);
|
||||
if (raced.kind === "REJECTED") throw raced.reason;
|
||||
return raced.kind === "VALUE" ? raced.value : STORAGE_INSPECTION_ABORTED;
|
||||
} finally {
|
||||
operation.close();
|
||||
}
|
||||
|
||||
return await new Promise<Value | typeof STORAGE_INSPECTION_ABORTED>(
|
||||
(resolve, reject) => {
|
||||
let settled = false;
|
||||
const finish = (
|
||||
outcome:
|
||||
| Readonly<{ kind: "VALUE"; value: Value }>
|
||||
| Readonly<{ kind: "ABORTED" }>
|
||||
| Readonly<{ kind: "ERROR"; error: unknown }>,
|
||||
): void => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
signal.removeEventListener("abort", onAbort);
|
||||
if (outcome.kind === "VALUE") {
|
||||
resolve(outcome.value);
|
||||
} else if (outcome.kind === "ABORTED") {
|
||||
resolve(STORAGE_INSPECTION_ABORTED);
|
||||
} else {
|
||||
reject(outcome.error);
|
||||
}
|
||||
};
|
||||
const onAbort = (): void => finish({ kind: "ABORTED" });
|
||||
|
||||
signal.addEventListener("abort", onAbort, { once: true });
|
||||
inspection.then(
|
||||
(value) => finish({ kind: "VALUE", value }),
|
||||
(error: unknown) => finish({ kind: "ERROR", error }),
|
||||
);
|
||||
if (signal.aborted) onAbort();
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async function inspectPersistenceState(
|
||||
|
||||
@@ -54,7 +54,8 @@ interface DisposableFilePicker extends FilePickerPort {
|
||||
/**
|
||||
* Focus can return before some engines dispatch the file input change event.
|
||||
* This grace keeps the fallback from misclassifying a real selection as a
|
||||
* dismissal. The native cancel event remains authoritative and immediate.
|
||||
* dismissal. The native cancel event remains authoritative and immediate, and
|
||||
* once a picker has seen it the fallback is no longer installed.
|
||||
*/
|
||||
export const DEFAULT_NATIVE_PICKER_FOCUS_GRACE_MS = 1_000;
|
||||
|
||||
@@ -97,6 +98,12 @@ export class NativeInputFilePicker implements DisposableFilePicker {
|
||||
#pending = false;
|
||||
#disposed = false;
|
||||
#abortPending: (() => void) | undefined;
|
||||
/**
|
||||
* Q-6.2-8. Once this engine has dispatched a native `cancel`, dismissal is
|
||||
* reported natively, so the focus heuristic would only turn a slow `change`
|
||||
* (a cloud provider still fetching the file) into a false dismissal.
|
||||
*/
|
||||
#nativeCancelObserved = false;
|
||||
|
||||
constructor(options: NativeInputFilePickerOptions) {
|
||||
this.#input = options.input;
|
||||
@@ -200,23 +207,25 @@ export class NativeInputFilePicker implements DisposableFilePicker {
|
||||
try {
|
||||
request = snapshotSelectionRequest(input);
|
||||
} catch {
|
||||
return this.#finishObservation(
|
||||
return observeSelection(
|
||||
this.#observer,
|
||||
browserDataFailure("INVALID_INPUT", "FILE_SELECT"),
|
||||
);
|
||||
}
|
||||
if (this.#disposed) {
|
||||
return this.#finishObservation(
|
||||
return observeSelection(
|
||||
this.#observer,
|
||||
browserDataFailure("UNAVAILABLE", "FILE_SELECT"),
|
||||
);
|
||||
}
|
||||
const cancelled = abortedResult(request.signal, "FILE_SELECT");
|
||||
if (cancelled) return this.#finishObservation(cancelled);
|
||||
if (cancelled) return observeSelection(this.#observer, cancelled);
|
||||
const resolvedPolicy = this.#resolveSelection(
|
||||
request.policy,
|
||||
request.limits,
|
||||
);
|
||||
if (!resolvedPolicy.ok) {
|
||||
return this.#finishObservation(resolvedPolicy);
|
||||
return observeSelection(this.#observer, resolvedPolicy);
|
||||
}
|
||||
const policy = resolvedPolicy.value;
|
||||
if (
|
||||
@@ -225,17 +234,20 @@ export class NativeInputFilePicker implements DisposableFilePicker {
|
||||
this.#inputEvents.getAttribute,
|
||||
)
|
||||
) {
|
||||
return this.#finishObservation(
|
||||
return observeSelection(
|
||||
this.#observer,
|
||||
browserDataFailure("INVALID_INPUT", "FILE_SELECT"),
|
||||
);
|
||||
}
|
||||
if (this.#pending) {
|
||||
return this.#finishObservation(
|
||||
return observeSelection(
|
||||
this.#observer,
|
||||
browserDataFailure("BLOCKED", "FILE_SELECT"),
|
||||
);
|
||||
}
|
||||
if (this.#userActivation && !this.#userActivation.isActive) {
|
||||
return this.#finishObservation(
|
||||
return observeSelection(
|
||||
this.#observer,
|
||||
browserDataFailure("PERMISSION_DENIED", "FILE_SELECT"),
|
||||
);
|
||||
}
|
||||
@@ -293,7 +305,10 @@ export class NativeInputFilePicker implements DisposableFilePicker {
|
||||
: captured,
|
||||
);
|
||||
};
|
||||
const onCancel = (): void => dismiss();
|
||||
const onCancel = (): void => {
|
||||
this.#nativeCancelObserved = true;
|
||||
dismiss();
|
||||
};
|
||||
const onAbort = (): void =>
|
||||
finish(browserDataFailure("ABORTED", "FILE_SELECT"));
|
||||
const abortPending = (): void =>
|
||||
@@ -319,7 +334,9 @@ export class NativeInputFilePicker implements DisposableFilePicker {
|
||||
this.#inputEvents.add("change", onChange, { once: true });
|
||||
this.#inputEvents.add("cancel", onCancel, { once: true });
|
||||
signal?.addEventListener("abort", onAbort, { once: true });
|
||||
this.#windowEvents?.add("focus", onWindowFocus);
|
||||
if (!this.#nativeCancelObserved) {
|
||||
this.#windowEvents?.add("focus", onWindowFocus);
|
||||
}
|
||||
this.#abortPending = abortPending;
|
||||
try {
|
||||
this.#input.accept = pickerAcceptValue(policy);
|
||||
@@ -332,9 +349,10 @@ export class NativeInputFilePicker implements DisposableFilePicker {
|
||||
}
|
||||
},
|
||||
);
|
||||
return this.#finishObservation(result);
|
||||
return observeSelection(this.#observer, result);
|
||||
} catch (error) {
|
||||
return this.#finishObservation(
|
||||
return observeSelection(
|
||||
this.#observer,
|
||||
mapBrowserDataException(error, "FILE_SELECT"),
|
||||
);
|
||||
} finally {
|
||||
@@ -356,33 +374,6 @@ export class NativeInputFilePicker implements DisposableFilePicker {
|
||||
// Some test doubles or constrained DOM hosts expose a readonly value.
|
||||
}
|
||||
}
|
||||
|
||||
#finishObservation(
|
||||
result: BrowserDataResult<FileSelectionOutcome>,
|
||||
): BrowserDataResult<FileSelectionOutcome> {
|
||||
if (result.ok) {
|
||||
const dismissed = result.value.kind === "DISMISSED";
|
||||
const bytes =
|
||||
result.value.kind === "SELECTED"
|
||||
? result.value.files.reduce(
|
||||
(total, candidate) => total + candidate.sizeBytes,
|
||||
0,
|
||||
)
|
||||
: null;
|
||||
observeBrowserFile(this.#observer, {
|
||||
operation: "FILE_SELECT",
|
||||
outcome: dismissed ? "DISMISSED" : "SUCCESS",
|
||||
byteBucket: byteBucket(bytes),
|
||||
});
|
||||
} else {
|
||||
observeBrowserFile(this.#observer, {
|
||||
operation: "FILE_SELECT",
|
||||
outcome: "FAILED",
|
||||
failureCode: result.error.code,
|
||||
});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
export type SystemOpenPickerAcceptType = Readonly<{
|
||||
@@ -460,30 +451,36 @@ export class EnhancedFilePicker implements DisposableFilePicker {
|
||||
try {
|
||||
request = snapshotSelectionRequest(input);
|
||||
} catch {
|
||||
return this.#observe(
|
||||
return observeSelection(
|
||||
this.#observer,
|
||||
browserDataFailure("INVALID_INPUT", "FILE_SELECT"),
|
||||
);
|
||||
}
|
||||
if (this.#disposed) {
|
||||
return this.#observe(
|
||||
return observeSelection(
|
||||
this.#observer,
|
||||
browserDataFailure("UNAVAILABLE", "FILE_SELECT"),
|
||||
);
|
||||
}
|
||||
const cancelled = abortedResult(request.signal, "FILE_SELECT");
|
||||
if (cancelled) return this.#observe(cancelled);
|
||||
if (cancelled) return observeSelection(this.#observer, cancelled);
|
||||
const resolvedPolicy = this.#resolveSelection(
|
||||
request.policy,
|
||||
request.limits,
|
||||
);
|
||||
if (!resolvedPolicy.ok) return this.#observe(resolvedPolicy);
|
||||
if (!resolvedPolicy.ok) {
|
||||
return observeSelection(this.#observer, resolvedPolicy);
|
||||
}
|
||||
const policy = resolvedPolicy.value;
|
||||
if (this.#pending) {
|
||||
return this.#observe(
|
||||
return observeSelection(
|
||||
this.#observer,
|
||||
browserDataFailure("BLOCKED", "FILE_SELECT"),
|
||||
);
|
||||
}
|
||||
if (this.#userActivation && !this.#userActivation.isActive) {
|
||||
return this.#observe(
|
||||
return observeSelection(
|
||||
this.#observer,
|
||||
browserDataFailure("PERMISSION_DENIED", "FILE_SELECT"),
|
||||
);
|
||||
}
|
||||
@@ -499,9 +496,10 @@ export class EnhancedFilePicker implements DisposableFilePicker {
|
||||
request.signal,
|
||||
);
|
||||
const aborted = abortedResult(request.signal, "FILE_SELECT");
|
||||
if (aborted) return this.#observe(aborted);
|
||||
if (aborted) return observeSelection(this.#observer, aborted);
|
||||
if (handles.length === 0) {
|
||||
return this.#observe(
|
||||
return observeSelection(
|
||||
this.#observer,
|
||||
browserDataSuccess(
|
||||
Object.freeze({ kind: "DISMISSED" as const }),
|
||||
),
|
||||
@@ -512,7 +510,8 @@ export class EnhancedFilePicker implements DisposableFilePicker {
|
||||
policy,
|
||||
request.signal ?? new AbortController().signal,
|
||||
);
|
||||
return this.#observe(
|
||||
return observeSelection(
|
||||
this.#observer,
|
||||
captured.ok
|
||||
? browserDataSuccess(
|
||||
Object.freeze({
|
||||
@@ -524,20 +523,23 @@ export class EnhancedFilePicker implements DisposableFilePicker {
|
||||
);
|
||||
} catch (error) {
|
||||
if (error instanceof PickerDisposedError) {
|
||||
return this.#observe(
|
||||
return observeSelection(
|
||||
this.#observer,
|
||||
browserDataFailure("ABORTED", "FILE_SELECT"),
|
||||
);
|
||||
}
|
||||
if (error instanceof DOMException && error.name === "AbortError") {
|
||||
const aborted = abortedResult(input.signal, "FILE_SELECT");
|
||||
if (aborted) return this.#observe(aborted);
|
||||
return this.#observe(
|
||||
if (aborted) return observeSelection(this.#observer, aborted);
|
||||
return observeSelection(
|
||||
this.#observer,
|
||||
browserDataSuccess(
|
||||
Object.freeze({ kind: "DISMISSED" as const }),
|
||||
),
|
||||
);
|
||||
}
|
||||
return this.#observe(
|
||||
return observeSelection(
|
||||
this.#observer,
|
||||
mapBrowserDataException(error, "FILE_SELECT"),
|
||||
);
|
||||
} finally {
|
||||
@@ -589,34 +591,36 @@ export class EnhancedFilePicker implements DisposableFilePicker {
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#observe(
|
||||
result: BrowserDataResult<FileSelectionOutcome>,
|
||||
): BrowserDataResult<FileSelectionOutcome> {
|
||||
if (!result.ok) {
|
||||
observeBrowserFile(this.#observer, {
|
||||
operation: "FILE_SELECT",
|
||||
outcome: "FAILED",
|
||||
failureCode: result.error.code,
|
||||
});
|
||||
} else if (result.value.kind === "DISMISSED") {
|
||||
observeBrowserFile(this.#observer, {
|
||||
operation: "FILE_SELECT",
|
||||
outcome: "DISMISSED",
|
||||
});
|
||||
} else {
|
||||
const bytes = result.value.files.reduce(
|
||||
(total, file) => total + file.sizeBytes,
|
||||
0,
|
||||
);
|
||||
observeBrowserFile(this.#observer, {
|
||||
operation: "FILE_SELECT",
|
||||
outcome: "SUCCESS",
|
||||
byteBucket: byteBucket(bytes),
|
||||
});
|
||||
}
|
||||
return result;
|
||||
/** One observation per terminal selection result, shared by both pickers. */
|
||||
function observeSelection(
|
||||
observer: BrowserFileObserver | undefined,
|
||||
result: BrowserDataResult<FileSelectionOutcome>,
|
||||
): BrowserDataResult<FileSelectionOutcome> {
|
||||
if (!result.ok) {
|
||||
observeBrowserFile(observer, {
|
||||
operation: "FILE_SELECT",
|
||||
outcome: "FAILED",
|
||||
failureCode: result.error.code,
|
||||
});
|
||||
} else if (result.value.kind === "DISMISSED") {
|
||||
observeBrowserFile(observer, {
|
||||
operation: "FILE_SELECT",
|
||||
outcome: "DISMISSED",
|
||||
});
|
||||
} else {
|
||||
const bytes = result.value.files.reduce(
|
||||
(total, file) => total + file.sizeBytes,
|
||||
0,
|
||||
);
|
||||
observeBrowserFile(observer, {
|
||||
operation: "FILE_SELECT",
|
||||
outcome: "SUCCESS",
|
||||
byteBucket: byteBucket(bytes),
|
||||
});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function pickerAcceptValue(
|
||||
|
||||
@@ -14,6 +14,8 @@ import {
|
||||
import {
|
||||
assertFileInspectionPolicy,
|
||||
assertFileSelectionPolicy,
|
||||
EXACT_MEDIA_TYPE,
|
||||
isPositiveSafeInteger,
|
||||
sanitizeSuggestedFileName,
|
||||
type RegisteredFileInspectionPolicy,
|
||||
type RegisteredFileSelectionPolicy,
|
||||
@@ -81,8 +83,6 @@ type SnapshotProfile = Readonly<{
|
||||
}>;
|
||||
|
||||
const POLICY_TOKEN = /^[a-z0-9][a-z0-9._:-]{0,127}$/i;
|
||||
const MEDIA_TYPE =
|
||||
/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/i;
|
||||
const ISSUED_POLICY_REFERENCES = new WeakSet<object>();
|
||||
|
||||
/**
|
||||
@@ -417,7 +417,7 @@ function snapshotPreview(
|
||||
hardMaxPreviewBytes: number,
|
||||
): SnapshotProfile["preview"] {
|
||||
if (
|
||||
!positiveSafeInteger(input.maxPreviewBytes) ||
|
||||
!isPositiveSafeInteger(input.maxPreviewBytes) ||
|
||||
input.maxPreviewBytes > hardMaxPreviewBytes ||
|
||||
!Array.isArray(input.allowedMediaTypes) ||
|
||||
input.allowedMediaTypes.length < 1 ||
|
||||
@@ -428,7 +428,7 @@ function snapshotPreview(
|
||||
const allowedMediaTypes = new Set<string>();
|
||||
for (const inputMediaType of input.allowedMediaTypes) {
|
||||
const mediaType = inputMediaType.trim().toLowerCase();
|
||||
if (!MEDIA_TYPE.test(mediaType)) {
|
||||
if (!EXACT_MEDIA_TYPE.test(mediaType)) {
|
||||
throw new TypeError("File preview media type is invalid.");
|
||||
}
|
||||
allowedMediaTypes.add(mediaType);
|
||||
@@ -451,9 +451,9 @@ function snapshotDownload(
|
||||
"PROMPT_AND_STREAM",
|
||||
"BOUNDED_OBJECT_URL",
|
||||
].includes(input.strategy) ||
|
||||
!MEDIA_TYPE.test(mediaType) ||
|
||||
!positiveSafeInteger(input.maxTransferBytes) ||
|
||||
!positiveSafeInteger(input.maxBufferedBytes) ||
|
||||
!EXACT_MEDIA_TYPE.test(mediaType) ||
|
||||
!isPositiveSafeInteger(input.maxTransferBytes) ||
|
||||
!isPositiveSafeInteger(input.maxBufferedBytes) ||
|
||||
input.maxTransferBytes > hardLimits.maxTransferBytes ||
|
||||
input.maxBufferedBytes > input.maxTransferBytes ||
|
||||
(input.strategy === "BOUNDED_OBJECT_URL" &&
|
||||
@@ -478,11 +478,11 @@ function assertHardLimits(
|
||||
input: BrowserFilePolicyRegistryOptions["hardLimits"],
|
||||
): void {
|
||||
if (
|
||||
!positiveSafeInteger(input.maxInspectionBytes) ||
|
||||
!positiveSafeInteger(input.maxRetainedFileBytes) ||
|
||||
!positiveSafeInteger(input.maxPreviewBytes) ||
|
||||
!positiveSafeInteger(input.maxObjectUrlBytes) ||
|
||||
!positiveSafeInteger(input.maxTransferBytes) ||
|
||||
!isPositiveSafeInteger(input.maxInspectionBytes) ||
|
||||
!isPositiveSafeInteger(input.maxRetainedFileBytes) ||
|
||||
!isPositiveSafeInteger(input.maxPreviewBytes) ||
|
||||
!isPositiveSafeInteger(input.maxObjectUrlBytes) ||
|
||||
!isPositiveSafeInteger(input.maxTransferBytes) ||
|
||||
input.maxObjectUrlBytes > input.maxTransferBytes
|
||||
) {
|
||||
throw new TypeError("Browser file policy hard limits are invalid.");
|
||||
@@ -497,7 +497,7 @@ function reducedLimit(
|
||||
if (requested === undefined) {
|
||||
return browserDataSuccess(configured);
|
||||
}
|
||||
if (!positiveSafeInteger(requested)) {
|
||||
if (!isPositiveSafeInteger(requested)) {
|
||||
return browserDataFailure("INVALID_INPUT", operation);
|
||||
}
|
||||
if (requested > configured) {
|
||||
@@ -520,7 +520,3 @@ function referenceKey(reference: FilePolicyReference): string {
|
||||
reference.intention,
|
||||
]);
|
||||
}
|
||||
|
||||
function positiveSafeInteger(value: number): boolean {
|
||||
return Number.isSafeInteger(value) && value > 0;
|
||||
}
|
||||
|
||||
@@ -19,10 +19,16 @@ import {
|
||||
browserDataSuccess,
|
||||
mapBrowserDataException,
|
||||
} from "../browser-file-storage/result.ts";
|
||||
import {
|
||||
createAbortableOperation,
|
||||
type AbortableOperation,
|
||||
} from "../platform/abortable-operation.ts";
|
||||
import {
|
||||
assertFileInspectionPolicy,
|
||||
assertFileSelectionPolicy,
|
||||
findMatchingSignature,
|
||||
isPositiveSafeInteger,
|
||||
isSafeGeneratedToken,
|
||||
matchesSelectionHint,
|
||||
normalizedExtension,
|
||||
signatureMetadataMatches,
|
||||
@@ -119,7 +125,8 @@ export class BrowserFileVault
|
||||
readonly #observer: BrowserFileObserver | undefined;
|
||||
readonly #resolveInspection:
|
||||
BrowserFilePolicyRegistry["resolveInspection"];
|
||||
readonly #lifetime = new AbortController();
|
||||
/** Open streams; dispose() closes each, which ends its pending read. */
|
||||
readonly #streams = new Set<AbortableOperation>();
|
||||
#disposed = false;
|
||||
#retainedBytes = 0;
|
||||
|
||||
@@ -504,15 +511,12 @@ export class BrowserFileVault
|
||||
signal: AbortSignal,
|
||||
): AsyncIterable<BrowserDataResult<Uint8Array>> {
|
||||
let transferred = 0;
|
||||
const combined = combineAbortSignals(
|
||||
signal,
|
||||
vault.#lifetime.signal,
|
||||
);
|
||||
// Q-6.2-7. The kernel owner joins the caller signal and dispose().
|
||||
const owner = createAbortableOperation({ signal });
|
||||
if (vault.#disposed) owner.close();
|
||||
else vault.#streams.add(owner);
|
||||
try {
|
||||
for await (const chunk of streamNativeFile(
|
||||
file,
|
||||
combined.signal,
|
||||
)) {
|
||||
for await (const chunk of streamNativeFile(file, owner)) {
|
||||
transferred += chunk.byteLength;
|
||||
yield browserDataSuccess(chunk);
|
||||
}
|
||||
@@ -533,7 +537,8 @@ export class BrowserFileVault
|
||||
vault.#observeFailureResult(failure);
|
||||
yield failure;
|
||||
} finally {
|
||||
combined.release();
|
||||
vault.#streams.delete(owner);
|
||||
owner.close();
|
||||
}
|
||||
},
|
||||
});
|
||||
@@ -620,7 +625,8 @@ export class BrowserFileVault
|
||||
dispose(): void {
|
||||
if (this.#disposed) return;
|
||||
this.#disposed = true;
|
||||
this.#lifetime.abort();
|
||||
for (const stream of this.#streams) stream.close();
|
||||
this.#streams.clear();
|
||||
this.#verifications.clear();
|
||||
this.#verificationReceiptsByRef.clear();
|
||||
this.#records.clear();
|
||||
@@ -681,7 +687,7 @@ export class BrowserFileVault
|
||||
return browserDataFailure("LIMIT_EXCEEDED", "FILE_SELECT");
|
||||
}
|
||||
const refValue = this.#createReference();
|
||||
if (!safeOpaqueValue(refValue)) {
|
||||
if (!isSafeGeneratedToken(refValue)) {
|
||||
return browserDataFailure("UNAVAILABLE", "FILE_SELECT");
|
||||
}
|
||||
const ref = refValue as LocalFileRef;
|
||||
@@ -716,7 +722,7 @@ export class BrowserFileVault
|
||||
#issueVerification(record: VerificationRecord):
|
||||
BrowserDataResult<FileVerificationReceipt> {
|
||||
const receiptValue = this.#createVerificationReceipt();
|
||||
if (!safeOpaqueValue(receiptValue)) {
|
||||
if (!isSafeGeneratedToken(receiptValue)) {
|
||||
return browserDataFailure("UNAVAILABLE", "FILE_INSPECT");
|
||||
}
|
||||
const receipt = receiptValue as FileVerificationReceipt;
|
||||
@@ -810,21 +816,20 @@ function snapshotSystemFileHandles(
|
||||
|
||||
async function* streamNativeFile(
|
||||
file: File,
|
||||
signal: AbortSignal,
|
||||
owner: AbortableOperation,
|
||||
): AsyncIterable<Uint8Array> {
|
||||
if (signal.aborted) throw abortException();
|
||||
if (owner.signal.aborted) throw abortException();
|
||||
const reader = file.stream().getReader();
|
||||
const abort = () => {
|
||||
void reader.cancel(abortException()).catch(() => {});
|
||||
};
|
||||
signal.addEventListener("abort", abort, { once: true });
|
||||
let transferred = 0;
|
||||
let completed = false;
|
||||
try {
|
||||
while (true) {
|
||||
if (signal.aborted) throw abortException();
|
||||
const result = await reader.read();
|
||||
if (signal.aborted) throw abortException();
|
||||
const raced = await owner.race(reader.read());
|
||||
if (raced.kind === "REJECTED") throw raced.reason;
|
||||
if (raced.kind === "TERMINAL" || owner.signal.aborted) {
|
||||
throw abortException();
|
||||
}
|
||||
const result = raced.value;
|
||||
if (result.done) break;
|
||||
const chunk = result.value;
|
||||
if (!(chunk instanceof Uint8Array)) {
|
||||
@@ -844,12 +849,16 @@ async function* streamNativeFile(
|
||||
}
|
||||
completed = true;
|
||||
} finally {
|
||||
signal.removeEventListener("abort", abort);
|
||||
if (!completed) {
|
||||
try {
|
||||
await reader.cancel();
|
||||
// An aborted read never waits on the source's own cancel algorithm.
|
||||
if (owner.signal.aborted) {
|
||||
void reader.cancel(abortException()).catch(() => {});
|
||||
} else {
|
||||
await reader.cancel();
|
||||
}
|
||||
} catch {
|
||||
// The stream may already be errored or cancelled by AbortSignal.
|
||||
// The stream may already be errored.
|
||||
}
|
||||
}
|
||||
reader.releaseLock();
|
||||
@@ -861,35 +870,6 @@ function normalizedMediaType(value: string): string | null {
|
||||
return normalized.length > 0 ? normalized : null;
|
||||
}
|
||||
|
||||
function isPositiveSafeInteger(value: number): boolean {
|
||||
return Number.isSafeInteger(value) && value > 0;
|
||||
}
|
||||
|
||||
function safeOpaqueValue(value: string): boolean {
|
||||
return /^[a-z0-9][a-z0-9:_-]{0,127}$/i.test(value);
|
||||
}
|
||||
|
||||
function combineAbortSignals(
|
||||
caller: AbortSignal,
|
||||
lifetime: AbortSignal,
|
||||
): Readonly<{ signal: AbortSignal; release(): void }> {
|
||||
const controller = new AbortController();
|
||||
const abort = (): void => controller.abort();
|
||||
if (caller.aborted || lifetime.aborted) {
|
||||
controller.abort();
|
||||
} else {
|
||||
caller.addEventListener("abort", abort, { once: true });
|
||||
lifetime.addEventListener("abort", abort, { once: true });
|
||||
}
|
||||
return Object.freeze({
|
||||
signal: controller.signal,
|
||||
release(): void {
|
||||
caller.removeEventListener("abort", abort);
|
||||
lifetime.removeEventListener("abort", abort);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function abortException(): DOMException {
|
||||
return new DOMException("Operation aborted", "AbortError");
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
type DownloadDeliveryAdapterOptions,
|
||||
} from "./download-delivery-adapter.ts";
|
||||
import type { BrowserFileObserver } from "./file-observer.ts";
|
||||
import { isPositiveSafeInteger } from "./file-policy.ts";
|
||||
import {
|
||||
BrowserTransientPreview,
|
||||
ObjectUrlLeaseRegistry,
|
||||
@@ -239,7 +240,3 @@ function resolveRuntimeLimits(
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
|
||||
function isPositiveSafeInteger(value: number): boolean {
|
||||
return Number.isSafeInteger(value) && value > 0;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import type {
|
||||
BrowserManagedDownloadCapability,
|
||||
BrowserManagedDownloadCapabilityResolver,
|
||||
DownloadDeliveryPort,
|
||||
DownloadOutcome,
|
||||
@@ -12,7 +11,6 @@ import type {
|
||||
TransferProgress,
|
||||
} from "../../application/ports/browser-file-storage/shared.ts";
|
||||
import type {
|
||||
PresignedDownloadCapability,
|
||||
PresignedDownloadByteSource,
|
||||
PresignedDownloadSourcePort,
|
||||
} from "../../application/ports/browser-transfer/presigned-transfer.ts";
|
||||
@@ -22,23 +20,31 @@ import {
|
||||
browserDataSuccess,
|
||||
mapBrowserDataException,
|
||||
} from "../browser-file-storage/result.ts";
|
||||
import {
|
||||
createAbortableOperation,
|
||||
type AbortableOperation,
|
||||
} from "../platform/abortable-operation.ts";
|
||||
import {
|
||||
byteBucket,
|
||||
observeBrowserFile,
|
||||
type BrowserFileObserver,
|
||||
} from "./file-observer.ts";
|
||||
import {
|
||||
sanitizeSuggestedFileName,
|
||||
type SuggestedFileNamePolicy,
|
||||
} from "./file-policy.ts";
|
||||
import {
|
||||
ObjectUrlLeaseRegistry,
|
||||
type ObjectUrlLease,
|
||||
} from "./object-url-lease.ts";
|
||||
import { BrowserFilePolicyRegistry } from "./browser-file-policy-registry.ts";
|
||||
import { isPositiveSafeInteger, isSafeGeneratedToken } from "./file-policy.ts";
|
||||
import {
|
||||
BrowserFilePolicyRegistry,
|
||||
type ResolvedDownloadPolicy,
|
||||
} from "./browser-file-policy-registry.ts";
|
||||
activeDeliveryInput,
|
||||
resolveBrowserManagedTarget,
|
||||
validByteSource,
|
||||
validPresignedByteSource,
|
||||
validateBrowserManagedCapability,
|
||||
validateDownloadInput,
|
||||
type DeliveryInput,
|
||||
type DeliveryRequest,
|
||||
} from "./download-input-validation.ts";
|
||||
|
||||
export type BrowserDownloadHost = Readonly<{
|
||||
handoff(href: string, suggestedFileName: string): void;
|
||||
@@ -134,9 +140,6 @@ export type DownloadDeliveryAdapterOptions = Readonly<{
|
||||
observer?: BrowserFileObserver;
|
||||
}>;
|
||||
|
||||
const MEDIA_TYPE = /^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/i;
|
||||
const SHA256 = /^[a-f0-9]{64}$/i;
|
||||
|
||||
/**
|
||||
* Keeps a one-shot Blob URL alive across browser download scheduling and
|
||||
* process handoff. Runtime dispose() still revokes every active lease
|
||||
@@ -170,7 +173,8 @@ export function createDownloadDeliveryAdapter(
|
||||
options.baseOrigin ?? globalThis.location?.origin ?? "https://localhost";
|
||||
const userActivation =
|
||||
options.userActivation ?? globalThis.navigator?.userActivation;
|
||||
const lifetime = new AbortController();
|
||||
// Every delivery in flight; dispose() closes each, which aborts its signal.
|
||||
const liveOperations = new Set<AbortableOperation>();
|
||||
let disposed = false;
|
||||
|
||||
if (
|
||||
@@ -178,8 +182,8 @@ export function createDownloadDeliveryAdapter(
|
||||
progressMinIntervalMs < 0 ||
|
||||
!Number.isSafeInteger(releaseDelayMs) ||
|
||||
releaseDelayMs < 0 ||
|
||||
!isPositiveByteLimit(options.hardMaxObjectUrlBytes) ||
|
||||
!isPositiveByteLimit(options.hardMaxTransferBytes) ||
|
||||
!isPositiveSafeInteger(options.hardMaxObjectUrlBytes) ||
|
||||
!isPositiveSafeInteger(options.hardMaxTransferBytes) ||
|
||||
options.hardMaxObjectUrlBytes > options.hardMaxTransferBytes ||
|
||||
typeof options.host?.handoff !== "function" ||
|
||||
typeof options.policies?.resolveDownload !== "function" ||
|
||||
@@ -266,19 +270,23 @@ export function createDownloadDeliveryAdapter(
|
||||
dependencies.observer,
|
||||
);
|
||||
}
|
||||
const combined = combineAbortSignals(
|
||||
input.signal,
|
||||
lifetime.signal,
|
||||
);
|
||||
// Q-6.2-7. One owner per delivery: caller abort and dispose() both end
|
||||
// it, and a lease or writable that lands after that is compensated by the
|
||||
// kernel race instead of a hand-written listener pair.
|
||||
const owner = createAbortableOperation({ signal: input.signal });
|
||||
liveOperations.add(owner);
|
||||
try {
|
||||
return await deliverActive({ ...input, signal: combined.signal });
|
||||
return await deliverActive({ ...input, signal: owner.signal }, owner);
|
||||
} finally {
|
||||
combined.release();
|
||||
liveOperations.delete(owner);
|
||||
owner.close();
|
||||
}
|
||||
}
|
||||
|
||||
async function deliverActive(input: DeliveryRequest):
|
||||
Promise<BrowserDataResult<DownloadOutcome>> {
|
||||
async function deliverActive(
|
||||
input: DeliveryRequest,
|
||||
owner: AbortableOperation,
|
||||
): Promise<BrowserDataResult<DownloadOutcome>> {
|
||||
const resolvedPolicy = resolveDownloadPolicy(
|
||||
input.policy,
|
||||
{
|
||||
@@ -315,17 +323,10 @@ export function createDownloadDeliveryAdapter(
|
||||
dependencies.observer,
|
||||
);
|
||||
}
|
||||
let suggestedFileName: string;
|
||||
// Q-6.2-10. Validation already sanitized the name; it is not redone.
|
||||
const suggestedFileName = validation.value;
|
||||
let transferId: string;
|
||||
try {
|
||||
suggestedFileName = sanitizeSuggestedFileName(
|
||||
activeInput.suggestedFileName,
|
||||
{
|
||||
safeExtension: activeInput.safeExtension,
|
||||
maxUtf8Bytes:
|
||||
dependencies.filenameMaxUtf8Bytes,
|
||||
} satisfies SuggestedFileNamePolicy,
|
||||
);
|
||||
transferId = createTransferId();
|
||||
} catch {
|
||||
return observeResult(
|
||||
@@ -333,7 +334,7 @@ export function createDownloadDeliveryAdapter(
|
||||
dependencies.observer,
|
||||
);
|
||||
}
|
||||
if (!safeGeneratedToken(transferId)) {
|
||||
if (!isSafeGeneratedToken(transferId)) {
|
||||
return observeResult(
|
||||
browserDataFailure("UNAVAILABLE", "DOWNLOAD"),
|
||||
dependencies.observer,
|
||||
@@ -358,6 +359,7 @@ export function createDownloadDeliveryAdapter(
|
||||
if (activeInput.strategy === "PROMPT_AND_STREAM") {
|
||||
return promptAndStream({
|
||||
input: activeInput,
|
||||
owner,
|
||||
suggestedFileName,
|
||||
transferId,
|
||||
options: dependencies,
|
||||
@@ -367,6 +369,7 @@ export function createDownloadDeliveryAdapter(
|
||||
|
||||
return boundedObjectUrlHandoff({
|
||||
input: activeInput,
|
||||
owner,
|
||||
suggestedFileName,
|
||||
transferId,
|
||||
options: dependencies,
|
||||
@@ -382,7 +385,8 @@ export function createDownloadDeliveryAdapter(
|
||||
dispose(): void {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
lifetime.abort();
|
||||
for (const operation of liveOperations) operation.close();
|
||||
liveOperations.clear();
|
||||
objectUrls.dispose();
|
||||
},
|
||||
});
|
||||
@@ -482,6 +486,7 @@ function browserManagedHandoff(context: Readonly<{
|
||||
|
||||
async function promptAndStream(context: Readonly<{
|
||||
input: DeliveryInput;
|
||||
owner: AbortableOperation;
|
||||
suggestedFileName: string;
|
||||
transferId: string;
|
||||
options: DownloadDeliveryAdapterOptions;
|
||||
@@ -542,10 +547,7 @@ async function promptAndStream(context: Readonly<{
|
||||
|
||||
let handle: SaveFileHandle;
|
||||
try {
|
||||
handle = await awaitWithSignal(
|
||||
handlePromise,
|
||||
context.input.signal,
|
||||
);
|
||||
handle = await raceOwner(context.owner, handlePromise);
|
||||
} catch (error) {
|
||||
if (
|
||||
error instanceof DOMException &&
|
||||
@@ -576,7 +578,7 @@ async function promptAndStream(context: Readonly<{
|
||||
try {
|
||||
const sourceResult = await resolveByteSource(
|
||||
context.input,
|
||||
context.input.signal,
|
||||
context.owner,
|
||||
context.options,
|
||||
sourceHolder,
|
||||
);
|
||||
@@ -595,9 +597,14 @@ async function promptAndStream(context: Readonly<{
|
||||
);
|
||||
}
|
||||
context.progress.report("PREPARING", 0, source.byteLength, true);
|
||||
const writable = await awaitWithSignal(
|
||||
const writable = await raceOwner(
|
||||
context.owner,
|
||||
handle.createWritable(),
|
||||
context.input.signal,
|
||||
// A writable that opens after the abort keeps a browser swap file
|
||||
// until it is aborted.
|
||||
(late) => {
|
||||
void late.abort().catch(() => undefined);
|
||||
},
|
||||
);
|
||||
const writer = writable.getWriter();
|
||||
let committed = false;
|
||||
@@ -606,7 +613,7 @@ async function promptAndStream(context: Readonly<{
|
||||
try {
|
||||
for await (const chunkResult of abortableFileChunks(
|
||||
source,
|
||||
context.input.signal,
|
||||
context.owner,
|
||||
)) {
|
||||
if (!chunkResult.ok) {
|
||||
throw new ClosedFileStreamError(chunkResult.error);
|
||||
@@ -622,15 +629,12 @@ async function promptAndStream(context: Readonly<{
|
||||
throw limitException();
|
||||
}
|
||||
if (verifier) {
|
||||
await awaitWithSignal(
|
||||
await raceOwner(
|
||||
context.owner,
|
||||
Promise.resolve(verifier.update(chunk)),
|
||||
context.input.signal,
|
||||
);
|
||||
}
|
||||
await awaitWithSignal(
|
||||
writer.write(chunk),
|
||||
context.input.signal,
|
||||
);
|
||||
await raceOwner(context.owner, writer.write(chunk));
|
||||
transferred = next;
|
||||
context.progress.report(
|
||||
"TRANSFERRING",
|
||||
@@ -647,9 +651,9 @@ async function promptAndStream(context: Readonly<{
|
||||
true,
|
||||
);
|
||||
if (verifier) {
|
||||
const verified = await awaitWithSignal(
|
||||
const verified = await raceOwner(
|
||||
context.owner,
|
||||
Promise.resolve(verifier.verify()),
|
||||
context.input.signal,
|
||||
);
|
||||
if (!verified) throw integrityException();
|
||||
}
|
||||
@@ -716,6 +720,7 @@ async function promptAndStream(context: Readonly<{
|
||||
|
||||
async function boundedObjectUrlHandoff(context: Readonly<{
|
||||
input: DeliveryInput;
|
||||
owner: AbortableOperation;
|
||||
suggestedFileName: string;
|
||||
transferId: string;
|
||||
options: DownloadDeliveryAdapterOptions;
|
||||
@@ -739,10 +744,10 @@ async function boundedObjectUrlHandoff(context: Readonly<{
|
||||
let lease: ObjectUrlLease | undefined;
|
||||
try {
|
||||
// Inside the try: an open that throws or is aborted must still resolve to
|
||||
// a Result and reach the finally that latches the holder for late leases.
|
||||
// a Result and reach the finally that closes the held lease.
|
||||
const sourceResult = await resolveByteSource(
|
||||
context.input,
|
||||
context.input.signal,
|
||||
context.owner,
|
||||
context.options,
|
||||
sourceHolder,
|
||||
);
|
||||
@@ -765,7 +770,7 @@ async function boundedObjectUrlHandoff(context: Readonly<{
|
||||
context.progress.report("PREPARING", 0, source.byteLength, true);
|
||||
for await (const chunkResult of abortableFileChunks(
|
||||
source,
|
||||
context.input.signal,
|
||||
context.owner,
|
||||
)) {
|
||||
if (!chunkResult.ok) {
|
||||
throw new ClosedFileStreamError(chunkResult.error);
|
||||
@@ -782,9 +787,9 @@ async function boundedObjectUrlHandoff(context: Readonly<{
|
||||
throw limitException();
|
||||
}
|
||||
if (verifier) {
|
||||
await awaitWithSignal(
|
||||
await raceOwner(
|
||||
context.owner,
|
||||
Promise.resolve(verifier.update(chunk)),
|
||||
context.input.signal,
|
||||
);
|
||||
}
|
||||
const copy = chunk.slice();
|
||||
@@ -804,9 +809,9 @@ async function boundedObjectUrlHandoff(context: Readonly<{
|
||||
true,
|
||||
);
|
||||
if (verifier) {
|
||||
const verified = await awaitWithSignal(
|
||||
const verified = await raceOwner(
|
||||
context.owner,
|
||||
Promise.resolve(verifier.verify()),
|
||||
context.input.signal,
|
||||
);
|
||||
if (!verified) throw integrityException();
|
||||
}
|
||||
@@ -857,168 +862,14 @@ async function boundedObjectUrlHandoff(context: Readonly<{
|
||||
}
|
||||
}
|
||||
|
||||
type DeliveryRequest =
|
||||
Parameters<DownloadDeliveryPort["deliver"]>[0];
|
||||
|
||||
type DeliveryInput = Readonly<
|
||||
Omit<
|
||||
DeliveryRequest,
|
||||
"maxTransferBytes" | "maxBufferedBytes"
|
||||
> &
|
||||
ResolvedDownloadPolicy & {
|
||||
expectedSha256?: string;
|
||||
}
|
||||
>;
|
||||
|
||||
function activeDeliveryInput(
|
||||
input: DeliveryRequest,
|
||||
policy: ResolvedDownloadPolicy,
|
||||
): DeliveryInput {
|
||||
const source = snapshotDownloadSource(input.source);
|
||||
const expectedSha256 =
|
||||
source.kind === "GENERATED"
|
||||
? source.expectedSha256
|
||||
: undefined;
|
||||
return Object.freeze({
|
||||
policy: input.policy,
|
||||
source,
|
||||
suggestedFileName: input.suggestedFileName,
|
||||
signal: input.signal,
|
||||
onProgress: input.onProgress,
|
||||
...policy,
|
||||
...(expectedSha256 !== undefined ? { expectedSha256 } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
function snapshotDownloadSource(
|
||||
source: DownloadSource,
|
||||
): DownloadSource {
|
||||
const kind = source.kind;
|
||||
if (kind === "BROWSER_MANAGED_RESOURCE") {
|
||||
return Object.freeze({
|
||||
kind,
|
||||
resourceId: source.resourceId,
|
||||
capabilityReceipt: source.capabilityReceipt,
|
||||
});
|
||||
}
|
||||
if (kind === "AUTHORIZED_STREAM_RESOURCE") {
|
||||
return Object.freeze({
|
||||
kind,
|
||||
resourceId: source.resourceId,
|
||||
capability: source.capability,
|
||||
});
|
||||
}
|
||||
if (kind !== "GENERATED") {
|
||||
throw new TypeError("Download source kind is invalid.");
|
||||
}
|
||||
const sourceBytes = source.bytes;
|
||||
const stream = sourceBytes.stream;
|
||||
const byteLength = sourceBytes.byteLength;
|
||||
if (typeof stream !== "function") {
|
||||
throw new TypeError("Download byte source is invalid.");
|
||||
}
|
||||
const bytes: FileByteSource = Object.freeze({
|
||||
byteLength,
|
||||
stream: stream.bind(sourceBytes),
|
||||
});
|
||||
const expectedSha256 = source.expectedSha256;
|
||||
return Object.freeze({
|
||||
kind,
|
||||
bytes,
|
||||
...(expectedSha256 !== undefined ? { expectedSha256 } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
function validateDownloadInput(
|
||||
input: DeliveryInput,
|
||||
options: DownloadDeliveryAdapterOptions,
|
||||
userActivation: Readonly<{ isActive: boolean }> | undefined,
|
||||
): BrowserDataResult<true> {
|
||||
if (
|
||||
input.signal.aborted ||
|
||||
input.suggestedFileName.length === 0 ||
|
||||
!MEDIA_TYPE.test(input.mediaType) ||
|
||||
!isValidByteLength(input.maxTransferBytes) ||
|
||||
input.maxTransferBytes === 0 ||
|
||||
!isValidByteLength(input.maxBufferedBytes) ||
|
||||
input.maxBufferedBytes === 0 ||
|
||||
(input.expectedSha256 !== undefined &&
|
||||
!SHA256.test(input.expectedSha256)) ||
|
||||
(input.source.kind === "AUTHORIZED_STREAM_RESOURCE" &&
|
||||
(!safeOpaqueId(input.source.resourceId) ||
|
||||
!validPresignedCapabilityForInput(
|
||||
input.source.capability,
|
||||
input.source.resourceId,
|
||||
input.mediaType,
|
||||
input.maxTransferBytes,
|
||||
options.now?.() ?? Date.now(),
|
||||
) ||
|
||||
options.openAuthorizedSource === undefined)) ||
|
||||
(input.source.kind === "BROWSER_MANAGED_RESOURCE" &&
|
||||
(!safeOpaqueId(input.source.resourceId) ||
|
||||
!safeOpaqueId(input.source.capabilityReceipt))) ||
|
||||
(input.strategy === "PROMPT_AND_STREAM" &&
|
||||
options.showSaveFilePicker === undefined)
|
||||
) {
|
||||
return browserDataFailure(
|
||||
input.signal.aborted ? "ABORTED" : "INVALID_INPUT",
|
||||
"DOWNLOAD",
|
||||
);
|
||||
}
|
||||
if (
|
||||
input.maxTransferBytes > options.hardMaxTransferBytes ||
|
||||
(input.strategy === "BOUNDED_OBJECT_URL" &&
|
||||
(input.maxBufferedBytes > options.hardMaxObjectUrlBytes ||
|
||||
input.maxBufferedBytes > input.maxTransferBytes))
|
||||
) {
|
||||
return browserDataFailure("LIMIT_EXCEEDED", "DOWNLOAD");
|
||||
}
|
||||
if (
|
||||
(input.strategy === "BROWSER_MANAGED" &&
|
||||
input.source.kind !== "BROWSER_MANAGED_RESOURCE") ||
|
||||
(input.strategy !== "BROWSER_MANAGED" &&
|
||||
input.source.kind === "BROWSER_MANAGED_RESOURCE") ||
|
||||
(input.integrity === "REQUIRED" &&
|
||||
input.source.kind === "GENERATED" &&
|
||||
input.expectedSha256 === undefined)
|
||||
) {
|
||||
return browserDataFailure("POLICY_REJECTED", "DOWNLOAD");
|
||||
}
|
||||
if (input.source.kind === "GENERATED") {
|
||||
try {
|
||||
if (!validByteSource(input.source.bytes)) {
|
||||
return browserDataFailure("INTEGRITY_FAILED", "DOWNLOAD");
|
||||
}
|
||||
if (
|
||||
input.source.bytes.byteLength !== null &&
|
||||
input.source.bytes.byteLength > input.maxTransferBytes
|
||||
) {
|
||||
return browserDataFailure("LIMIT_EXCEEDED", "DOWNLOAD");
|
||||
}
|
||||
} catch {
|
||||
return browserDataFailure("INVALID_INPUT", "DOWNLOAD");
|
||||
}
|
||||
}
|
||||
if (userActivation && !userActivation.isActive) {
|
||||
return browserDataFailure("PERMISSION_DENIED", "DOWNLOAD");
|
||||
}
|
||||
try {
|
||||
sanitizeSuggestedFileName(input.suggestedFileName, {
|
||||
safeExtension: input.safeExtension,
|
||||
maxUtf8Bytes: options.filenameMaxUtf8Bytes,
|
||||
});
|
||||
} catch {
|
||||
return browserDataFailure("INVALID_INPUT", "DOWNLOAD");
|
||||
}
|
||||
return browserDataSuccess(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 success, validation failure, writer failure and abort leaked both. The
|
||||
* closeable subtype is lost in the `FileByteSource` projection, so the holder
|
||||
* keeps it and the outermost boundary closes it exactly once.
|
||||
* keeps it and the outermost boundary closes it exactly once. A lease that
|
||||
* lands after the owner ended never reaches the holder; the owner's race
|
||||
* compensates it instead.
|
||||
*/
|
||||
type CloseableSourceHolder = { source: FileByteSource | null; closed: boolean };
|
||||
|
||||
@@ -1026,32 +877,6 @@ function createSourceHolder(): CloseableSourceHolder {
|
||||
return { source: null, closed: false };
|
||||
}
|
||||
|
||||
/**
|
||||
* TR-02. Closes a lease that fulfilled after the delivery already ended. The
|
||||
* holder's own `closed` latch is the single close-once authority, so a lease
|
||||
* the holder did adopt is never closed twice and a lease it never saw is still
|
||||
* closed exactly once. A late rejection is observed and discarded.
|
||||
*/
|
||||
function compensateLateSource(
|
||||
pending: Promise<BrowserDataResult<FileByteSource>>,
|
||||
holder: CloseableSourceHolder | undefined,
|
||||
): void {
|
||||
if (!holder) return;
|
||||
void pending.then(
|
||||
(result) => {
|
||||
if (!result.ok || !holder.closed) return;
|
||||
// The holder was already closed, so this lease was never adopted.
|
||||
if (!isVerifiedPresignedSource(result.value)) return;
|
||||
try {
|
||||
result.value.close();
|
||||
} catch {
|
||||
// Compensation is best effort and never changes the outcome.
|
||||
}
|
||||
},
|
||||
() => undefined,
|
||||
);
|
||||
}
|
||||
|
||||
function closeHeldSource(holder: CloseableSourceHolder): void {
|
||||
if (holder.closed) return;
|
||||
holder.closed = true;
|
||||
@@ -1067,12 +892,12 @@ function closeHeldSource(holder: CloseableSourceHolder): void {
|
||||
|
||||
async function resolveByteSource(
|
||||
input: DeliveryInput,
|
||||
signal: AbortSignal,
|
||||
owner: AbortableOperation,
|
||||
options: DownloadDeliveryAdapterOptions,
|
||||
holder?: CloseableSourceHolder,
|
||||
): Promise<BrowserDataResult<FileByteSource>> {
|
||||
const source = input.source;
|
||||
if (signal.aborted) {
|
||||
if (owner.signal.aborted) {
|
||||
return browserDataFailure("ABORTED", "DOWNLOAD");
|
||||
}
|
||||
if (source.kind === "GENERATED") {
|
||||
@@ -1085,17 +910,22 @@ async function resolveByteSource(
|
||||
}
|
||||
const open = options.openAuthorizedSource;
|
||||
if (!open) return browserDataFailure("UNSUPPORTED", "DOWNLOAD");
|
||||
const pendingOpen = open({
|
||||
resourceId: source.resourceId,
|
||||
capability: source.capability,
|
||||
signal,
|
||||
});
|
||||
// TR-02. A lease that arrives after the abort already ended the delivery
|
||||
// never reaches the holder, so nothing would ever close it: the fetch reader
|
||||
// and the capability lease outlived the terminal result. The compensator and
|
||||
// the holder share one close-once latch, so exactly one of them closes it.
|
||||
compensateLateSource(pendingOpen, holder);
|
||||
const result = await awaitWithSignal(pendingOpen, signal);
|
||||
// TR-02 / Q-6.2-7. A lease that arrives after the owner ended never reaches
|
||||
// the holder, so the race closes it: exactly one of the two ever sees it,
|
||||
// with no gap between the abort and the holder's own cleanup.
|
||||
const result = await raceOwner(
|
||||
owner,
|
||||
open({
|
||||
resourceId: source.resourceId,
|
||||
capability: source.capability,
|
||||
signal: owner.signal,
|
||||
}),
|
||||
(late) => {
|
||||
if (late.ok && isVerifiedPresignedSource(late.value)) {
|
||||
late.value.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
if (!result.ok) {
|
||||
return browserDataFailure(result.error.code, "DOWNLOAD", {
|
||||
retryable: result.error.retryable,
|
||||
@@ -1117,14 +947,6 @@ async function resolveByteSource(
|
||||
: browserDataFailure("INTEGRITY_FAILED", "DOWNLOAD");
|
||||
}
|
||||
|
||||
function validByteSource(source: FileByteSource): boolean {
|
||||
return (
|
||||
typeof source.stream === "function" &&
|
||||
(source.byteLength === null ||
|
||||
isValidByteLength(source.byteLength))
|
||||
);
|
||||
}
|
||||
|
||||
function isVerifiedPresignedSource(
|
||||
source: FileByteSource,
|
||||
): source is PresignedDownloadByteSource {
|
||||
@@ -1134,70 +956,16 @@ function isVerifiedPresignedSource(
|
||||
);
|
||||
}
|
||||
|
||||
function validPresignedByteSource(
|
||||
source: PresignedDownloadByteSource,
|
||||
capability: PresignedDownloadCapability,
|
||||
resourceId: string,
|
||||
mediaType: string,
|
||||
maxTransferBytes: number,
|
||||
nowEpochMs: number,
|
||||
): boolean {
|
||||
return (
|
||||
validByteSource(source) &&
|
||||
source.capability === capability &&
|
||||
source.integrity === "VERIFIED_ON_SUCCESSFUL_EXHAUSTION" &&
|
||||
source.byteLength === capability.byteLength &&
|
||||
capability.method === "GET" &&
|
||||
capability.binding.kind === "DOWNLOAD" &&
|
||||
capability.binding.resourceId === resourceId &&
|
||||
capability.mediaType === mediaType &&
|
||||
capability.byteLength <= capability.maxBytes &&
|
||||
capability.maxBytes <= maxTransferBytes &&
|
||||
SHA256.test(capability.expectedSha256) &&
|
||||
Number.isSafeInteger(nowEpochMs) &&
|
||||
capability.expiresAtEpochMs > nowEpochMs
|
||||
);
|
||||
}
|
||||
|
||||
function validPresignedCapabilityForInput(
|
||||
capability: PresignedDownloadCapability,
|
||||
resourceId: string,
|
||||
mediaType: string,
|
||||
maxTransferBytes: number,
|
||||
nowEpochMs: number,
|
||||
): boolean {
|
||||
try {
|
||||
return (
|
||||
Boolean(capability) &&
|
||||
typeof capability === "object" &&
|
||||
Object.isFrozen(capability) &&
|
||||
capability.method === "GET" &&
|
||||
capability.binding.kind === "DOWNLOAD" &&
|
||||
capability.binding.resourceId === resourceId &&
|
||||
capability.mediaType === mediaType &&
|
||||
isValidByteLength(capability.byteLength) &&
|
||||
isPositiveByteLimit(capability.maxBytes) &&
|
||||
capability.byteLength <= capability.maxBytes &&
|
||||
capability.maxBytes <= maxTransferBytes &&
|
||||
SHA256.test(capability.expectedSha256) &&
|
||||
Number.isSafeInteger(capability.expiresAtEpochMs) &&
|
||||
Number.isSafeInteger(nowEpochMs) &&
|
||||
capability.expiresAtEpochMs > nowEpochMs
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function* abortableFileChunks(
|
||||
source: FileByteSource,
|
||||
signal: AbortSignal,
|
||||
owner: AbortableOperation,
|
||||
): AsyncIterable<BrowserDataResult<Uint8Array>> {
|
||||
const signal = owner.signal;
|
||||
const iterator = source.stream(signal)[Symbol.asyncIterator]();
|
||||
let completed = false;
|
||||
try {
|
||||
while (true) {
|
||||
const next = await awaitWithSignal(iterator.next(), signal);
|
||||
const next = await raceOwner(owner, iterator.next());
|
||||
if (next.done) {
|
||||
completed = true;
|
||||
return;
|
||||
@@ -1270,116 +1038,6 @@ function mapDownloadException(
|
||||
return mapBrowserDataException(error, "DOWNLOAD");
|
||||
}
|
||||
|
||||
function validateBrowserManagedCapability(
|
||||
capability: BrowserManagedDownloadCapability,
|
||||
input: DeliveryInput,
|
||||
nowEpochMs: number,
|
||||
): BrowserDataResult<BrowserManagedDownloadCapability> {
|
||||
if (
|
||||
input.source.kind !== "BROWSER_MANAGED_RESOURCE" ||
|
||||
!capability ||
|
||||
typeof capability !== "object" ||
|
||||
typeof capability.href !== "string" ||
|
||||
capability.href.length === 0 ||
|
||||
capability.capabilityReceipt !==
|
||||
input.source.capabilityReceipt ||
|
||||
capability.resourceId !== input.source.resourceId ||
|
||||
capability.mediaType.trim().toLowerCase() !==
|
||||
input.mediaType ||
|
||||
capability.safeExtension.trim().toLowerCase() !==
|
||||
input.safeExtension ||
|
||||
!isPositiveByteLimit(capability.maxBytes) ||
|
||||
capability.maxBytes > input.maxTransferBytes ||
|
||||
!Number.isSafeInteger(capability.expiresAtEpochMs) ||
|
||||
!Number.isSafeInteger(nowEpochMs) ||
|
||||
(capability.expectedSha256 !== undefined &&
|
||||
!SHA256.test(capability.expectedSha256)) ||
|
||||
(input.integrity === "REQUIRED" &&
|
||||
capability.expectedSha256 === undefined)
|
||||
) {
|
||||
return browserDataFailure("POLICY_REJECTED", "DOWNLOAD");
|
||||
}
|
||||
if (capability.expiresAtEpochMs <= nowEpochMs) {
|
||||
return browserDataFailure("EXPIRED_RESOURCE", "DOWNLOAD", {
|
||||
recovery: "RETRY",
|
||||
});
|
||||
}
|
||||
return browserDataSuccess(
|
||||
Object.freeze({
|
||||
capabilityReceipt: capability.capabilityReceipt,
|
||||
href: capability.href,
|
||||
resourceId: capability.resourceId,
|
||||
mediaType: input.mediaType,
|
||||
safeExtension: input.safeExtension,
|
||||
maxBytes: capability.maxBytes,
|
||||
...(capability.expectedSha256
|
||||
? {
|
||||
expectedSha256:
|
||||
capability.expectedSha256.toLowerCase(),
|
||||
}
|
||||
: {}),
|
||||
expiresAtEpochMs: capability.expiresAtEpochMs,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
type ResolvedBrowserManagedTarget = Readonly<{ absoluteHref: string }>;
|
||||
|
||||
/**
|
||||
* STO-02. Parse once, canonicalize, then execute the canonical value.
|
||||
*
|
||||
* Returning a boolean and handing the raw href to the host let the browser
|
||||
* re-resolve a relative target against `document.baseURI`, so a hostile
|
||||
* `<base>` could send the navigation to a different origin than the one this
|
||||
* policy just approved.
|
||||
*/
|
||||
function resolveBrowserManagedTarget(
|
||||
href: string,
|
||||
baseOrigin: string,
|
||||
policy: Readonly<{
|
||||
allowCrossOrigin: boolean;
|
||||
allowQuery: boolean;
|
||||
}>,
|
||||
): BrowserDataResult<ResolvedBrowserManagedTarget> {
|
||||
let base: URL;
|
||||
let target: URL;
|
||||
try {
|
||||
base = new URL(baseOrigin);
|
||||
target = new URL(href, base);
|
||||
} catch {
|
||||
return browserDataFailure("POLICY_REJECTED", "DOWNLOAD");
|
||||
}
|
||||
if (
|
||||
!["http:", "https:"].includes(target.protocol) ||
|
||||
target.username.length > 0 ||
|
||||
target.password.length > 0 ||
|
||||
(!policy.allowCrossOrigin && target.origin !== base.origin) ||
|
||||
(!policy.allowQuery && target.search.length > 0) ||
|
||||
target.hash.length > 0
|
||||
) {
|
||||
return browserDataFailure("POLICY_REJECTED", "DOWNLOAD");
|
||||
}
|
||||
return browserDataSuccess(
|
||||
Object.freeze({ absoluteHref: target.href }),
|
||||
);
|
||||
}
|
||||
|
||||
function safeOpaqueId(value: unknown): value is string {
|
||||
if (typeof value !== "string") return false;
|
||||
if (value.length === 0 || value.length > 256) return false;
|
||||
for (const character of value) {
|
||||
const code = character.codePointAt(0);
|
||||
if (code === undefined || code <= 0x20 || code === 0x7f) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function safeGeneratedToken(value: string): boolean {
|
||||
return /^[a-z0-9][a-z0-9:_-]{0,127}$/i.test(value);
|
||||
}
|
||||
|
||||
type ProgressReporter = Readonly<{
|
||||
report(
|
||||
phase: TransferProgress["phase"],
|
||||
@@ -1482,50 +1140,17 @@ class ClosedFileStreamError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
function combineAbortSignals(
|
||||
caller: AbortSignal,
|
||||
lifetime: AbortSignal,
|
||||
): Readonly<{ signal: AbortSignal; release(): void }> {
|
||||
const controller = new AbortController();
|
||||
const abort = (): void => controller.abort();
|
||||
if (caller.aborted || lifetime.aborted) {
|
||||
controller.abort();
|
||||
} else {
|
||||
caller.addEventListener("abort", abort, { once: true });
|
||||
lifetime.addEventListener("abort", abort, { once: true });
|
||||
}
|
||||
return Object.freeze({
|
||||
signal: controller.signal,
|
||||
release(): void {
|
||||
caller.removeEventListener("abort", abort);
|
||||
lifetime.removeEventListener("abort", abort);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function awaitWithSignal<Value>(
|
||||
/**
|
||||
* The owner's value, the task's own rejection, or an AbortError once the owner
|
||||
* ended. `compensate` receives a value that lands after that.
|
||||
*/
|
||||
async function raceOwner<Value>(
|
||||
owner: AbortableOperation,
|
||||
pending: Promise<Value>,
|
||||
signal: AbortSignal,
|
||||
compensate?: (value: Value) => void,
|
||||
): Promise<Value> {
|
||||
if (signal.aborted) throw abortException();
|
||||
return new Promise<Value>((resolve, reject) => {
|
||||
let settled = false;
|
||||
const finish = (callback: () => void): void => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
signal.removeEventListener("abort", onAbort);
|
||||
callback();
|
||||
};
|
||||
const onAbort = (): void =>
|
||||
finish(() => reject(abortException()));
|
||||
signal.addEventListener("abort", onAbort, { once: true });
|
||||
pending.then(
|
||||
(value) => finish(() => resolve(value)),
|
||||
(error: unknown) => finish(() => reject(error)),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function isPositiveByteLimit(value: number): boolean {
|
||||
return isValidByteLength(value) && value > 0;
|
||||
const raced = await owner.race(pending, compensate);
|
||||
if (raced.kind === "VALUE") return raced.value;
|
||||
if (raced.kind === "REJECTED") throw raced.reason;
|
||||
throw abortException();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,367 @@
|
||||
import type {
|
||||
BrowserManagedDownloadCapability,
|
||||
DownloadDeliveryPort,
|
||||
DownloadSource,
|
||||
FileByteSource,
|
||||
} from "../../application/ports/browser-file-storage/file.ts";
|
||||
import type { BrowserDataResult } from "../../application/ports/browser-file-storage/shared.ts";
|
||||
import type {
|
||||
PresignedDownloadCapability,
|
||||
PresignedDownloadByteSource,
|
||||
} from "../../application/ports/browser-transfer/presigned-transfer.ts";
|
||||
import { isValidByteLength } from "../../application/ports/browser-file-storage/shared.ts";
|
||||
import {
|
||||
browserDataFailure,
|
||||
browserDataSuccess,
|
||||
} from "../browser-file-storage/result.ts";
|
||||
import {
|
||||
EXACT_MEDIA_TYPE,
|
||||
isPositiveSafeInteger,
|
||||
sanitizeSuggestedFileName,
|
||||
type SuggestedFileNamePolicy,
|
||||
} from "./file-policy.ts";
|
||||
import type { ResolvedDownloadPolicy } from "./browser-file-policy-registry.ts";
|
||||
|
||||
/**
|
||||
* Q-6.2-11. Input admission for download delivery: request snapshot, policy
|
||||
* and limit checks, presigned and browser-managed capability validation, and
|
||||
* canonical handoff target resolution. Moved verbatim out of the adapter.
|
||||
*/
|
||||
|
||||
/** The adapter options that input validation reads. */
|
||||
export type DownloadInputValidationOptions = Readonly<{
|
||||
hardMaxObjectUrlBytes: number;
|
||||
hardMaxTransferBytes: number;
|
||||
openAuthorizedSource?: unknown;
|
||||
showSaveFilePicker?: unknown;
|
||||
filenameMaxUtf8Bytes?: number;
|
||||
now?: () => number;
|
||||
}>;
|
||||
|
||||
const SHA256 = /^[a-f0-9]{64}$/i;
|
||||
|
||||
export type DeliveryRequest =
|
||||
Parameters<DownloadDeliveryPort["deliver"]>[0];
|
||||
|
||||
export type DeliveryInput = Readonly<
|
||||
Omit<
|
||||
DeliveryRequest,
|
||||
"maxTransferBytes" | "maxBufferedBytes"
|
||||
> &
|
||||
ResolvedDownloadPolicy & {
|
||||
expectedSha256?: string;
|
||||
}
|
||||
>;
|
||||
|
||||
export function activeDeliveryInput(
|
||||
input: DeliveryRequest,
|
||||
policy: ResolvedDownloadPolicy,
|
||||
): DeliveryInput {
|
||||
const source = snapshotDownloadSource(input.source);
|
||||
const expectedSha256 =
|
||||
source.kind === "GENERATED"
|
||||
? source.expectedSha256
|
||||
: undefined;
|
||||
return Object.freeze({
|
||||
policy: input.policy,
|
||||
source,
|
||||
suggestedFileName: input.suggestedFileName,
|
||||
signal: input.signal,
|
||||
onProgress: input.onProgress,
|
||||
...policy,
|
||||
...(expectedSha256 !== undefined ? { expectedSha256 } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
function snapshotDownloadSource(
|
||||
source: DownloadSource,
|
||||
): DownloadSource {
|
||||
const kind = source.kind;
|
||||
if (kind === "BROWSER_MANAGED_RESOURCE") {
|
||||
return Object.freeze({
|
||||
kind,
|
||||
resourceId: source.resourceId,
|
||||
capabilityReceipt: source.capabilityReceipt,
|
||||
});
|
||||
}
|
||||
if (kind === "AUTHORIZED_STREAM_RESOURCE") {
|
||||
return Object.freeze({
|
||||
kind,
|
||||
resourceId: source.resourceId,
|
||||
capability: source.capability,
|
||||
});
|
||||
}
|
||||
if (kind !== "GENERATED") {
|
||||
throw new TypeError("Download source kind is invalid.");
|
||||
}
|
||||
const sourceBytes = source.bytes;
|
||||
const stream = sourceBytes.stream;
|
||||
const byteLength = sourceBytes.byteLength;
|
||||
if (typeof stream !== "function") {
|
||||
throw new TypeError("Download byte source is invalid.");
|
||||
}
|
||||
const bytes: FileByteSource = Object.freeze({
|
||||
byteLength,
|
||||
stream: stream.bind(sourceBytes),
|
||||
});
|
||||
const expectedSha256 = source.expectedSha256;
|
||||
return Object.freeze({
|
||||
kind,
|
||||
bytes,
|
||||
...(expectedSha256 !== undefined ? { expectedSha256 } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
export function validateDownloadInput(
|
||||
input: DeliveryInput,
|
||||
options: DownloadInputValidationOptions,
|
||||
userActivation: Readonly<{ isActive: boolean }> | undefined,
|
||||
): BrowserDataResult<string> {
|
||||
if (
|
||||
input.signal.aborted ||
|
||||
input.suggestedFileName.length === 0 ||
|
||||
!EXACT_MEDIA_TYPE.test(input.mediaType) ||
|
||||
!isValidByteLength(input.maxTransferBytes) ||
|
||||
input.maxTransferBytes === 0 ||
|
||||
!isValidByteLength(input.maxBufferedBytes) ||
|
||||
input.maxBufferedBytes === 0 ||
|
||||
(input.expectedSha256 !== undefined &&
|
||||
!SHA256.test(input.expectedSha256)) ||
|
||||
(input.source.kind === "AUTHORIZED_STREAM_RESOURCE" &&
|
||||
(!safeOpaqueId(input.source.resourceId) ||
|
||||
!validPresignedCapabilityForInput(
|
||||
input.source.capability,
|
||||
input.source.resourceId,
|
||||
input.mediaType,
|
||||
input.maxTransferBytes,
|
||||
options.now?.() ?? Date.now(),
|
||||
) ||
|
||||
options.openAuthorizedSource === undefined)) ||
|
||||
(input.source.kind === "BROWSER_MANAGED_RESOURCE" &&
|
||||
(!safeOpaqueId(input.source.resourceId) ||
|
||||
!safeOpaqueId(input.source.capabilityReceipt))) ||
|
||||
(input.strategy === "PROMPT_AND_STREAM" &&
|
||||
options.showSaveFilePicker === undefined)
|
||||
) {
|
||||
return browserDataFailure(
|
||||
input.signal.aborted ? "ABORTED" : "INVALID_INPUT",
|
||||
"DOWNLOAD",
|
||||
);
|
||||
}
|
||||
if (
|
||||
input.maxTransferBytes > options.hardMaxTransferBytes ||
|
||||
(input.strategy === "BOUNDED_OBJECT_URL" &&
|
||||
(input.maxBufferedBytes > options.hardMaxObjectUrlBytes ||
|
||||
input.maxBufferedBytes > input.maxTransferBytes))
|
||||
) {
|
||||
return browserDataFailure("LIMIT_EXCEEDED", "DOWNLOAD");
|
||||
}
|
||||
if (
|
||||
(input.strategy === "BROWSER_MANAGED" &&
|
||||
input.source.kind !== "BROWSER_MANAGED_RESOURCE") ||
|
||||
(input.strategy !== "BROWSER_MANAGED" &&
|
||||
input.source.kind === "BROWSER_MANAGED_RESOURCE") ||
|
||||
(input.integrity === "REQUIRED" &&
|
||||
input.source.kind === "GENERATED" &&
|
||||
input.expectedSha256 === undefined)
|
||||
) {
|
||||
return browserDataFailure("POLICY_REJECTED", "DOWNLOAD");
|
||||
}
|
||||
if (input.source.kind === "GENERATED") {
|
||||
try {
|
||||
if (!validByteSource(input.source.bytes)) {
|
||||
return browserDataFailure("INTEGRITY_FAILED", "DOWNLOAD");
|
||||
}
|
||||
if (
|
||||
input.source.bytes.byteLength !== null &&
|
||||
input.source.bytes.byteLength > input.maxTransferBytes
|
||||
) {
|
||||
return browserDataFailure("LIMIT_EXCEEDED", "DOWNLOAD");
|
||||
}
|
||||
} catch {
|
||||
return browserDataFailure("INVALID_INPUT", "DOWNLOAD");
|
||||
}
|
||||
}
|
||||
if (userActivation && !userActivation.isActive) {
|
||||
return browserDataFailure("PERMISSION_DENIED", "DOWNLOAD");
|
||||
}
|
||||
try {
|
||||
return browserDataSuccess(
|
||||
sanitizeSuggestedFileName(input.suggestedFileName, {
|
||||
safeExtension: input.safeExtension,
|
||||
maxUtf8Bytes: options.filenameMaxUtf8Bytes,
|
||||
} satisfies SuggestedFileNamePolicy),
|
||||
);
|
||||
} catch {
|
||||
return browserDataFailure("INVALID_INPUT", "DOWNLOAD");
|
||||
}
|
||||
}
|
||||
|
||||
export function validByteSource(source: FileByteSource): boolean {
|
||||
return (
|
||||
typeof source.stream === "function" &&
|
||||
(source.byteLength === null ||
|
||||
isValidByteLength(source.byteLength))
|
||||
);
|
||||
}
|
||||
|
||||
export function validPresignedByteSource(
|
||||
source: PresignedDownloadByteSource,
|
||||
capability: PresignedDownloadCapability,
|
||||
resourceId: string,
|
||||
mediaType: string,
|
||||
maxTransferBytes: number,
|
||||
nowEpochMs: number,
|
||||
): boolean {
|
||||
return (
|
||||
validByteSource(source) &&
|
||||
source.capability === capability &&
|
||||
source.integrity === "VERIFIED_ON_SUCCESSFUL_EXHAUSTION" &&
|
||||
source.byteLength === capability.byteLength &&
|
||||
capability.method === "GET" &&
|
||||
capability.binding.kind === "DOWNLOAD" &&
|
||||
capability.binding.resourceId === resourceId &&
|
||||
capability.mediaType === mediaType &&
|
||||
capability.byteLength <= capability.maxBytes &&
|
||||
capability.maxBytes <= maxTransferBytes &&
|
||||
SHA256.test(capability.expectedSha256) &&
|
||||
Number.isSafeInteger(nowEpochMs) &&
|
||||
capability.expiresAtEpochMs > nowEpochMs
|
||||
);
|
||||
}
|
||||
|
||||
function validPresignedCapabilityForInput(
|
||||
capability: PresignedDownloadCapability,
|
||||
resourceId: string,
|
||||
mediaType: string,
|
||||
maxTransferBytes: number,
|
||||
nowEpochMs: number,
|
||||
): boolean {
|
||||
try {
|
||||
return (
|
||||
Boolean(capability) &&
|
||||
typeof capability === "object" &&
|
||||
Object.isFrozen(capability) &&
|
||||
capability.method === "GET" &&
|
||||
capability.binding.kind === "DOWNLOAD" &&
|
||||
capability.binding.resourceId === resourceId &&
|
||||
capability.mediaType === mediaType &&
|
||||
isValidByteLength(capability.byteLength) &&
|
||||
isPositiveSafeInteger(capability.maxBytes) &&
|
||||
capability.byteLength <= capability.maxBytes &&
|
||||
capability.maxBytes <= maxTransferBytes &&
|
||||
SHA256.test(capability.expectedSha256) &&
|
||||
Number.isSafeInteger(capability.expiresAtEpochMs) &&
|
||||
Number.isSafeInteger(nowEpochMs) &&
|
||||
capability.expiresAtEpochMs > nowEpochMs
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function validateBrowserManagedCapability(
|
||||
capability: BrowserManagedDownloadCapability,
|
||||
input: DeliveryInput,
|
||||
nowEpochMs: number,
|
||||
): BrowserDataResult<BrowserManagedDownloadCapability> {
|
||||
if (
|
||||
input.source.kind !== "BROWSER_MANAGED_RESOURCE" ||
|
||||
!capability ||
|
||||
typeof capability !== "object" ||
|
||||
typeof capability.href !== "string" ||
|
||||
capability.href.length === 0 ||
|
||||
capability.capabilityReceipt !==
|
||||
input.source.capabilityReceipt ||
|
||||
capability.resourceId !== input.source.resourceId ||
|
||||
capability.mediaType.trim().toLowerCase() !==
|
||||
input.mediaType ||
|
||||
capability.safeExtension.trim().toLowerCase() !==
|
||||
input.safeExtension ||
|
||||
!isPositiveSafeInteger(capability.maxBytes) ||
|
||||
capability.maxBytes > input.maxTransferBytes ||
|
||||
!Number.isSafeInteger(capability.expiresAtEpochMs) ||
|
||||
!Number.isSafeInteger(nowEpochMs) ||
|
||||
(capability.expectedSha256 !== undefined &&
|
||||
!SHA256.test(capability.expectedSha256)) ||
|
||||
(input.integrity === "REQUIRED" &&
|
||||
capability.expectedSha256 === undefined)
|
||||
) {
|
||||
return browserDataFailure("POLICY_REJECTED", "DOWNLOAD");
|
||||
}
|
||||
if (capability.expiresAtEpochMs <= nowEpochMs) {
|
||||
return browserDataFailure("EXPIRED_RESOURCE", "DOWNLOAD", {
|
||||
recovery: "RETRY",
|
||||
});
|
||||
}
|
||||
return browserDataSuccess(
|
||||
Object.freeze({
|
||||
capabilityReceipt: capability.capabilityReceipt,
|
||||
href: capability.href,
|
||||
resourceId: capability.resourceId,
|
||||
mediaType: input.mediaType,
|
||||
safeExtension: input.safeExtension,
|
||||
maxBytes: capability.maxBytes,
|
||||
...(capability.expectedSha256
|
||||
? {
|
||||
expectedSha256:
|
||||
capability.expectedSha256.toLowerCase(),
|
||||
}
|
||||
: {}),
|
||||
expiresAtEpochMs: capability.expiresAtEpochMs,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export type ResolvedBrowserManagedTarget = Readonly<{ absoluteHref: string }>;
|
||||
|
||||
/**
|
||||
* STO-02. Parse once, canonicalize, then execute the canonical value.
|
||||
*
|
||||
* Returning a boolean and handing the raw href to the host let the browser
|
||||
* re-resolve a relative target against `document.baseURI`, so a hostile
|
||||
* `<base>` could send the navigation to a different origin than the one this
|
||||
* policy just approved.
|
||||
*/
|
||||
export function resolveBrowserManagedTarget(
|
||||
href: string,
|
||||
baseOrigin: string,
|
||||
policy: Readonly<{
|
||||
allowCrossOrigin: boolean;
|
||||
allowQuery: boolean;
|
||||
}>,
|
||||
): BrowserDataResult<ResolvedBrowserManagedTarget> {
|
||||
let base: URL;
|
||||
let target: URL;
|
||||
try {
|
||||
base = new URL(baseOrigin);
|
||||
target = new URL(href, base);
|
||||
} catch {
|
||||
return browserDataFailure("POLICY_REJECTED", "DOWNLOAD");
|
||||
}
|
||||
if (
|
||||
!["http:", "https:"].includes(target.protocol) ||
|
||||
target.username.length > 0 ||
|
||||
target.password.length > 0 ||
|
||||
(!policy.allowCrossOrigin && target.origin !== base.origin) ||
|
||||
(!policy.allowQuery && target.search.length > 0) ||
|
||||
target.hash.length > 0
|
||||
) {
|
||||
return browserDataFailure("POLICY_REJECTED", "DOWNLOAD");
|
||||
}
|
||||
return browserDataSuccess(
|
||||
Object.freeze({ absoluteHref: target.href }),
|
||||
);
|
||||
}
|
||||
|
||||
function safeOpaqueId(value: unknown): value is string {
|
||||
if (typeof value !== "string") return false;
|
||||
if (value.length === 0 || value.length > 256) return false;
|
||||
for (const character of value) {
|
||||
const code = character.codePointAt(0);
|
||||
if (code === undefined || code <= 0x20 || code === 0x7f) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -6,6 +6,8 @@ import type {
|
||||
} from "../../application/ports/browser-file-storage/shared.ts";
|
||||
import { observeBrowserData } from "../browser-file-storage/result.ts";
|
||||
|
||||
export { browserDataByteBucket as byteBucket } from "../../application/ports/browser-file-storage/shared.ts";
|
||||
|
||||
type BrowserFileObservation = Readonly<{
|
||||
operation: BrowserDataOperation;
|
||||
outcome: "SUCCESS" | "DISMISSED" | "FAILED";
|
||||
@@ -19,19 +21,6 @@ type BrowserFileObservation = Readonly<{
|
||||
*/
|
||||
export type BrowserFileObserver = BrowserDataObserver;
|
||||
|
||||
export function byteBucket(
|
||||
byteLength: number | null,
|
||||
): BrowserFileObservation["byteBucket"] | undefined {
|
||||
if (byteLength === null || !Number.isSafeInteger(byteLength) || byteLength < 0) {
|
||||
return undefined;
|
||||
}
|
||||
if (byteLength === 0) return "ZERO";
|
||||
if (byteLength < 1_048_576) return "LT1MIB";
|
||||
if (byteLength < 10_485_760) return "1_TO_9MIB";
|
||||
if (byteLength < 104_857_600) return "10_TO_99MIB";
|
||||
return "GTE100MIB";
|
||||
}
|
||||
|
||||
export function observeBrowserFile(
|
||||
observer: BrowserFileObserver | undefined,
|
||||
observation: BrowserFileObservation,
|
||||
|
||||
@@ -40,6 +40,20 @@ export type RegisteredFileInspectionPolicy = Readonly<{
|
||||
}>;
|
||||
|
||||
const MEDIA_TYPE = /^[a-z0-9!#$&^_.+-]+\/(?:[a-z0-9!#$&^_.+-]+|\*)$/i;
|
||||
/**
|
||||
* Q-6.2-12. The shared browser-file copies of three checks that used to be
|
||||
* redefined per module: an exact `type/subtype` media type (no wildcard), a
|
||||
* generated opaque token (file reference, receipt or transfer ID) and a
|
||||
* positive safe integer limit.
|
||||
*/
|
||||
export const EXACT_MEDIA_TYPE = /^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/i;
|
||||
|
||||
export function isSafeGeneratedToken(value: string): boolean {
|
||||
return /^[a-z0-9][a-z0-9:_-]{0,127}$/i.test(value);
|
||||
}
|
||||
|
||||
export { isPositiveSafeInteger } from "../../application/ports/browser-file-storage/shared.ts";
|
||||
|
||||
const EXTENSION =
|
||||
/^\.[a-z0-9][a-z0-9+_-]{0,15}(?:\.[a-z0-9][a-z0-9+_-]{0,15})?$/i;
|
||||
const POLICY_TOKEN = /^[a-z0-9][a-z0-9._:-]{0,127}$/i;
|
||||
@@ -354,12 +368,7 @@ export function sanitizeSuggestedFileName(
|
||||
base = fallbackBase.length > 0 ? fallbackBase : "download";
|
||||
}
|
||||
|
||||
while (
|
||||
base.length > 0 &&
|
||||
utf8Length(`${base}${safeExtension}`) > maxUtf8Bytes
|
||||
) {
|
||||
base = Array.from(base).slice(0, -1).join("").trimEnd();
|
||||
}
|
||||
base = truncateUtf8(base, maxUtf8Bytes - utf8Length(safeExtension));
|
||||
if (base.length === 0 || WINDOWS_RESERVED.test(base)) {
|
||||
base = fallbackBase;
|
||||
}
|
||||
@@ -401,21 +410,36 @@ function utf8Length(value: string): number {
|
||||
return new TextEncoder().encode(value).byteLength;
|
||||
}
|
||||
|
||||
/**
|
||||
* Q-6.2-10. The longest code-point prefix within `maxBytes` UTF-8 bytes, with
|
||||
* trailing whitespace removed once it was cut; `value` itself when it fits.
|
||||
* One pass: re-encoding the whole name per dropped code point was O(n^2).
|
||||
*/
|
||||
function truncateUtf8(value: string, maxBytes: number): string {
|
||||
let bytes = 0;
|
||||
let end = 0;
|
||||
for (const character of value) {
|
||||
const codePoint = character.codePointAt(0) ?? 0;
|
||||
// A lone surrogate encodes as U+FFFD, three bytes, like any BMP point.
|
||||
bytes +=
|
||||
codePoint <= 0x7f ? 1 : codePoint <= 0x7ff ? 2 : codePoint <= 0xffff ? 3 : 4;
|
||||
if (bytes > maxBytes) return value.slice(0, end).trimEnd();
|
||||
end += character.length;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function fitFallbackBaseName(
|
||||
configured: string,
|
||||
extension: string,
|
||||
maxUtf8Bytes: number,
|
||||
): string {
|
||||
let fallback =
|
||||
const fallback = truncateUtf8(
|
||||
configured.length > 0 && !WINDOWS_RESERVED.test(configured)
|
||||
? configured
|
||||
: "download";
|
||||
while (
|
||||
fallback.length > 0 &&
|
||||
utf8Length(`${fallback}${extension}`) > maxUtf8Bytes
|
||||
) {
|
||||
fallback = Array.from(fallback).slice(0, -1).join("").trimEnd();
|
||||
}
|
||||
: "download",
|
||||
maxUtf8Bytes - utf8Length(extension),
|
||||
);
|
||||
return fallback.length > 0 && !WINDOWS_RESERVED.test(fallback)
|
||||
? fallback
|
||||
: "a";
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
type BrowserFileObserver,
|
||||
} from "./file-observer.ts";
|
||||
import { BrowserFilePolicyRegistry } from "./browser-file-policy-registry.ts";
|
||||
import { EXACT_MEDIA_TYPE, isPositiveSafeInteger } from "./file-policy.ts";
|
||||
|
||||
export type ObjectUrlApi = Readonly<{
|
||||
createObjectURL(blob: Blob): string;
|
||||
@@ -109,13 +110,6 @@ export class ObjectUrlLeaseRegistry {
|
||||
}
|
||||
const url = this.#createObjectURL(blob);
|
||||
if (typeof url !== "string" || url.length === 0) {
|
||||
if (typeof url === "string" && url.length > 0) {
|
||||
try {
|
||||
this.#revokeObjectURL(url);
|
||||
} catch {
|
||||
// The invalid lease is rejected regardless of cleanup support.
|
||||
}
|
||||
}
|
||||
throw new DOMException(
|
||||
"Object URL allocation failed",
|
||||
"InvalidStateError",
|
||||
@@ -184,7 +178,6 @@ const DEFAULT_ACTIVE_CONTENT = new Set([
|
||||
"text/html",
|
||||
"text/xml",
|
||||
]);
|
||||
const MEDIA_TYPE = /^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/i;
|
||||
|
||||
export class BrowserTransientPreview implements TransientPreviewPort {
|
||||
readonly #resolveVerifiedFile:
|
||||
@@ -269,7 +262,7 @@ export class BrowserTransientPreview implements TransientPreviewPort {
|
||||
}
|
||||
const mediaType = resolved.value.mediaType.trim().toLowerCase();
|
||||
if (
|
||||
!MEDIA_TYPE.test(mediaType) ||
|
||||
!EXACT_MEDIA_TYPE.test(mediaType) ||
|
||||
!policy.allowedMediaTypes.has(mediaType) ||
|
||||
this.#hardForbiddenMediaTypes.has(mediaType)
|
||||
) {
|
||||
@@ -333,7 +326,3 @@ export class BrowserTransientPreview implements TransientPreviewPort {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
function isPositiveSafeInteger(value: number): boolean {
|
||||
return Number.isSafeInteger(value) && value > 0;
|
||||
}
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
import type { InstalledBoundaryMapper } from "../../contracts/boundary-mapper.ts";
|
||||
import {
|
||||
createFailure,
|
||||
withFailureEffect,
|
||||
type AppFailure,
|
||||
type FailureKind,
|
||||
} from "../../contracts/errors.ts";
|
||||
@@ -292,6 +293,7 @@ async function executeUnary<Output>(
|
||||
const { operation, profile, encoder, transport } = bound;
|
||||
const linked = linkedAbortController(context.signal);
|
||||
let attemptCount = 0;
|
||||
let sent = false;
|
||||
|
||||
const finish = (
|
||||
result: Result<Output, AppFailure>,
|
||||
@@ -300,7 +302,11 @@ async function executeUnary<Output>(
|
||||
// R-06. Listener and timer cleanup happens exactly once, on every exit.
|
||||
linked.cleanup();
|
||||
observe(dependencies, operation, outcome, attemptCount, result.ok ? 1 : 0);
|
||||
return result;
|
||||
// Q-6.3-9. Once a command reached the transport, no failure proves the
|
||||
// server did not apply it, so it is never offered as a plain retry.
|
||||
return !result.ok && sent && operation.semantics === "COMMAND"
|
||||
? failureResult(withFailureEffect(result.error, "MAYBE_APPLIED"))
|
||||
: result;
|
||||
};
|
||||
|
||||
const generation = safeCapture(generationFence);
|
||||
@@ -350,6 +356,21 @@ async function executeUnary<Output>(
|
||||
}
|
||||
|
||||
for (let attempt = 0; attempt < profile.maxAttempts; attempt += 1) {
|
||||
// Q-6.3-9. A retry never outlives the scope generation that started it,
|
||||
// so a previous user's request is not sent again after a logout.
|
||||
if (attempt > 0 && !safeIsCurrent(generationFence, generation)) {
|
||||
return finish(
|
||||
failureResult(
|
||||
callFailure(
|
||||
operation,
|
||||
attempt - 1,
|
||||
"SCOPE_GENERATION_CHANGED",
|
||||
"RPC_SCOPE_GENERATION_CHANGED",
|
||||
),
|
||||
),
|
||||
"ABORTED",
|
||||
);
|
||||
}
|
||||
attemptCount = attempt + 1;
|
||||
const attemptNow = safeNow(clock);
|
||||
if (attemptNow === CLOCK_FAILURE) {
|
||||
@@ -393,6 +414,7 @@ async function executeUnary<Output>(
|
||||
? { idempotencyKey: context.idempotencyKey }
|
||||
: {}),
|
||||
});
|
||||
sent = true;
|
||||
const timed = await raceWithin(
|
||||
Promise.resolve().then(() => transport.invokeUnary!(call)),
|
||||
remainingMs,
|
||||
@@ -549,10 +571,30 @@ async function* executeServerStream<Event>(
|
||||
const deadlineAt = safeNowOrDeadline(clock, 0) + operation.totalDeadlineMs;
|
||||
const linked = linkedAbortController(context.signal);
|
||||
let iterator: AsyncIterator<BrowserRpcStreamFrame> | null = null;
|
||||
let lease: BrowserRpcServerStreamLease | null = null;
|
||||
let registered: ActiveStreamLease | null = null;
|
||||
let observed = false;
|
||||
let messageCount = 0;
|
||||
|
||||
// R-01 / RPC-RR-01. Runs once, when the stream's own signal aborts. The
|
||||
// lease's `cancel` is what actually stops the physical stream, and the entry
|
||||
// is removed only once the transport confirms the physical stream closed.
|
||||
// Until then the operation stays DRAINING and admits nothing new — a bounded
|
||||
// wait here would re-open the very hole this registry exists to close.
|
||||
const releaseRegistered = () => {
|
||||
const entry = registered;
|
||||
if (!entry) return;
|
||||
try {
|
||||
entry.cancel("stream-closed");
|
||||
} catch {
|
||||
// A transport that refuses to cancel stays DRAINING below.
|
||||
}
|
||||
void entry.closed.then((confirmed) => {
|
||||
if (confirmed && activeStreams.get(operation.operationId) === entry) {
|
||||
activeStreams.delete(operation.operationId);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const finish = (outcome: BrowserRpcObservationOutcome) => {
|
||||
if (observed) return;
|
||||
observed = true;
|
||||
@@ -662,21 +704,28 @@ async function* executeServerStream<Event>(
|
||||
yield failureResult(protocolFailure(operation, 0));
|
||||
return;
|
||||
}
|
||||
lease = decodedLease;
|
||||
const lease = decodedLease;
|
||||
// Registered at the moment the physical stream exists, not after a timeout.
|
||||
activeStreams.set(
|
||||
operation.operationId,
|
||||
Object.freeze({
|
||||
streamId: lease.streamId,
|
||||
cancel: lease.cancel,
|
||||
// RPC-01. Only a fulfilled, contract-shaped receipt is evidence that the
|
||||
// physical stream closed. Absorbing a rejection, a synchronous throw or
|
||||
// a non-promise into `undefined` forged that evidence, and the registry
|
||||
// then admitted a second stream for the same operation while the first
|
||||
// was still running against the server.
|
||||
closed: confirmPhysicalClosure(lease),
|
||||
}),
|
||||
);
|
||||
registered = Object.freeze({
|
||||
streamId: lease.streamId,
|
||||
cancel: lease.cancel,
|
||||
// RPC-01. Only a fulfilled, contract-shaped receipt is evidence that the
|
||||
// physical stream closed. Absorbing a rejection, a synchronous throw or
|
||||
// a non-promise into `undefined` forged that evidence, and the registry
|
||||
// then admitted a second stream for the same operation while the first
|
||||
// was still running against the server.
|
||||
closed: confirmPhysicalClosure(lease),
|
||||
});
|
||||
activeStreams.set(operation.operationId, registered);
|
||||
// Q-6.3-9. A consumer that aborts and walks away without `return()` leaves
|
||||
// this generator suspended at a `yield`, so `finally` never runs. The
|
||||
// abort itself releases the physical stream.
|
||||
if (linked.controller.signal.aborted) releaseRegistered();
|
||||
else {
|
||||
linked.controller.signal.addEventListener("abort", releaseRegistered, {
|
||||
once: true,
|
||||
});
|
||||
}
|
||||
try {
|
||||
iterator = lease.frames[Symbol.asyncIterator]();
|
||||
} catch {
|
||||
@@ -842,38 +891,13 @@ async function* executeServerStream<Event>(
|
||||
}
|
||||
} finally {
|
||||
// R-01 / RPC-RR-01. The commit/admission generation is fenced immediately
|
||||
// and listeners are released without waiting for the transport.
|
||||
// `iterator.return()` is a cleanup request, not a lifecycle authority, so
|
||||
// the lease's own `cancel` is what actually stops the physical stream.
|
||||
// and listeners are released without waiting for the transport. The abort
|
||||
// runs `releaseRegistered` (cancel + positive-close subscription) unless
|
||||
// an earlier abort already did. RPC-02: that happens before any fallible
|
||||
// cleanup, so a throwing `return` accessor cannot strand the entry.
|
||||
// `iterator.return()` is a cleanup request, not a lifecycle authority.
|
||||
linked.controller.abort("stream-closed");
|
||||
linked.cleanup();
|
||||
const registered = lease
|
||||
? activeStreams.get(operation.operationId)
|
||||
: undefined;
|
||||
if (registered && registered.streamId === lease?.streamId) {
|
||||
try {
|
||||
registered.cancel("stream-closed");
|
||||
} catch {
|
||||
// A transport that refuses to cancel stays DRAINING below.
|
||||
}
|
||||
}
|
||||
if (registered && registered.streamId === lease?.streamId) {
|
||||
// RPC-02. The positive-close subscription is installed before any
|
||||
// fallible cleanup. Running cleanup first meant a throwing `return`
|
||||
// accessor could skip it entirely and strand the registry entry.
|
||||
// The entry is removed only once the transport confirms the physical
|
||||
// stream closed. Until then the operation stays DRAINING and admits
|
||||
// nothing new — a bounded wait here would re-open the very hole this
|
||||
// registry exists to close.
|
||||
void registered.closed.then((confirmed) => {
|
||||
if (
|
||||
confirmed &&
|
||||
activeStreams.get(operation.operationId) === registered
|
||||
) {
|
||||
activeStreams.delete(operation.operationId);
|
||||
}
|
||||
});
|
||||
}
|
||||
const returnIterator = safeIteratorReturn(iterator);
|
||||
if (returnIterator) {
|
||||
const cleanup = Promise.resolve()
|
||||
@@ -882,7 +906,7 @@ async function* executeServerStream<Event>(
|
||||
.catch(() => undefined);
|
||||
await boundedStreamCleanup(cleanup, clock, STREAM_CLEANUP_BOUND_MS);
|
||||
}
|
||||
if (registered && registered.streamId === lease?.streamId) {
|
||||
if (registered) {
|
||||
await boundedStreamCleanup(
|
||||
registered.closed.then(() => undefined),
|
||||
clock,
|
||||
@@ -1465,22 +1489,6 @@ function decodeTransportFailure(
|
||||
});
|
||||
}
|
||||
|
||||
function validTransportFailure(
|
||||
failure: unknown,
|
||||
): failure is BrowserRpcTransportFailure {
|
||||
if (!failure || typeof failure !== "object" || !("code" in failure)) {
|
||||
return false;
|
||||
}
|
||||
const candidate = failure as BrowserRpcTransportFailure;
|
||||
return (
|
||||
TRANSPORT_FAILURE_CODES.has(candidate.code) &&
|
||||
(candidate.retryAfterMs === undefined ||
|
||||
(Number.isSafeInteger(candidate.retryAfterMs) &&
|
||||
candidate.retryAfterMs >= 0 &&
|
||||
candidate.retryAfterMs <= BROWSER_RPC_HARD_LIMITS.maxRetryAfterMs))
|
||||
);
|
||||
}
|
||||
|
||||
const TRANSPORT_FAILURE_CODES =
|
||||
new Set<BrowserRpcTransportFailureCode>([
|
||||
"NETWORK_UNREACHABLE",
|
||||
|
||||
@@ -133,7 +133,10 @@ and every CDN origin must differ from it. This is required because an
|
||||
`anonymous` image request omits credentials only when it is cross-origin.
|
||||
Private descriptors must be backend-signed, remain above the configured
|
||||
minimum TTL at every resolve, and use an eager, non-low-priority
|
||||
`PRIMARY_REQUIRED` preset. Digest and signature verification share one
|
||||
`PRIMARY_REQUIRED` preset. A `PRIMARY_REQUIRED` preset must use `fit`
|
||||
`cover`, `contain` or `fill`: the probe expects the exact primary pixel size,
|
||||
and `inside`/`outside` keep the source ratio, so the registry rejects that
|
||||
combination at composition time. Digest and signature verification share one
|
||||
composition-owned deadline and race the caller's abort signal. The probe sends
|
||||
no credentials, rejects any final URL other than the exact signed URL, and
|
||||
requires the private response to declare the flag-only directive
|
||||
|
||||
@@ -7,11 +7,16 @@ import {
|
||||
browserDataSuccess,
|
||||
} from "../../browser-file-storage/result.ts";
|
||||
import {
|
||||
cancelBody,
|
||||
cancelReader,
|
||||
createAbortableOperation,
|
||||
snapshotAbortTimers,
|
||||
type AbortTimerSnapshot,
|
||||
type AbortableOperation,
|
||||
} from "../../platform/abortable-operation.ts";
|
||||
import { parseStaticImageHeaderMetadata } from "./image-header-metadata.ts";
|
||||
import {
|
||||
isPositiveSafeInteger as positiveSafeInteger,
|
||||
} from "../../../application/ports/browser-file-storage/shared.ts";
|
||||
|
||||
export type DecodedImageFacade = Readonly<{
|
||||
width: number;
|
||||
@@ -49,7 +54,10 @@ export function createBrowserImageProbe(
|
||||
const createBitmap =
|
||||
dependencies.createBitmap ??
|
||||
(typeof createImageBitmap === "function"
|
||||
? async (image: Blob) => createImageBitmap(image)
|
||||
? // Q-6.1-8. The header parser reads pre-rotation dimensions, so the
|
||||
// decode must not apply EXIF/irot orientation and swap them.
|
||||
async (image: Blob) =>
|
||||
createImageBitmap(image, { imageOrientation: "none" })
|
||||
: undefined);
|
||||
const timeoutMs = dependencies.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
||||
const timers = snapshotAbortTimers(
|
||||
@@ -100,11 +108,15 @@ export function createBrowserImageProbe(
|
||||
return browserDataFailure("UNSUPPORTED", "IMAGE_RESOLVE");
|
||||
}
|
||||
|
||||
const scope = createProbeAbortScope(
|
||||
request.signal,
|
||||
// X-AUDIT-02 / TR-RR-05. The probe is owned by the shared abort
|
||||
// primitive: the caller listener and the deadline are installed
|
||||
// together, so a throwing scheduler closes the probe instead of
|
||||
// rejecting `probe()`.
|
||||
const scope = createAbortableOperation({
|
||||
signal: request.signal,
|
||||
timeoutMs,
|
||||
timers,
|
||||
);
|
||||
...timers,
|
||||
});
|
||||
let response: Response | undefined;
|
||||
try {
|
||||
if (scope.signal.aborted) {
|
||||
@@ -124,8 +136,8 @@ export function createBrowserImageProbe(
|
||||
signal: scope.signal,
|
||||
}),
|
||||
);
|
||||
response = await scope.await(fetchTask, (lateResponse) => {
|
||||
cancelResponseBody(lateResponse);
|
||||
response = await awaitOwned(scope, fetchTask, (lateResponse) => {
|
||||
cancelBody(lateResponse);
|
||||
});
|
||||
} catch {
|
||||
return signalFailure(request.signal);
|
||||
@@ -140,7 +152,7 @@ export function createBrowserImageProbe(
|
||||
response.url !== url.href ||
|
||||
!validResponseHeaders(response, request)
|
||||
) {
|
||||
cancelResponseBody(response);
|
||||
cancelBody(response);
|
||||
return browserDataFailure(
|
||||
"POLICY_REJECTED",
|
||||
"IMAGE_RESOLVE",
|
||||
@@ -152,10 +164,10 @@ export function createBrowserImageProbe(
|
||||
bytes = await readBoundedBody(
|
||||
response,
|
||||
request.maxEncodedBytes,
|
||||
scope.signal,
|
||||
scope,
|
||||
);
|
||||
} catch (error) {
|
||||
if (request.signal.aborted || scope.timedOut()) {
|
||||
if (request.signal.aborted || unanswered(scope)) {
|
||||
return signalFailure(request.signal);
|
||||
}
|
||||
return error instanceof EncodedBodyLimitError
|
||||
@@ -227,18 +239,12 @@ export function createBrowserImageProbe(
|
||||
type: request.expectedMediaType,
|
||||
}),
|
||||
);
|
||||
bitmap = await scope.await(decodeTask, closeBitmap);
|
||||
bitmap = await awaitOwned(scope, decodeTask, closeBitmap);
|
||||
if (
|
||||
!positiveSafeInteger(bitmap.width) ||
|
||||
!positiveSafeInteger(bitmap.height) ||
|
||||
// The header dimensions are positive and already within the
|
||||
// decode budget, so an exact match is the whole check.
|
||||
bitmap.width !== metadata.width ||
|
||||
bitmap.height !== metadata.height ||
|
||||
!withinDecodeBudget(
|
||||
bitmap.width,
|
||||
bitmap.height,
|
||||
request.maxDecodedPixels,
|
||||
request.maxDecodedBytes,
|
||||
)
|
||||
bitmap.height !== metadata.height
|
||||
) {
|
||||
return browserDataFailure(
|
||||
"INTEGRITY_FAILED",
|
||||
@@ -255,7 +261,7 @@ export function createBrowserImageProbe(
|
||||
}),
|
||||
);
|
||||
} catch {
|
||||
return request.signal.aborted || scope.timedOut()
|
||||
return request.signal.aborted || unanswered(scope)
|
||||
? signalFailure(request.signal)
|
||||
: browserDataFailure(
|
||||
"INTEGRITY_FAILED",
|
||||
@@ -265,7 +271,7 @@ export function createBrowserImageProbe(
|
||||
if (bitmap) closeBitmap(bitmap);
|
||||
}
|
||||
} finally {
|
||||
scope.release();
|
||||
scope.close();
|
||||
}
|
||||
},
|
||||
});
|
||||
@@ -474,7 +480,7 @@ class EncodedBodyLimitError extends Error {}
|
||||
async function readBoundedBody(
|
||||
response: Response,
|
||||
maximumBytes: number,
|
||||
signal: AbortSignal,
|
||||
scope: AbortableOperation,
|
||||
): Promise<Uint8Array> {
|
||||
if (!response.body) {
|
||||
throw new TypeError("Image response body is unavailable.");
|
||||
@@ -484,8 +490,9 @@ async function readBoundedBody(
|
||||
let total = 0;
|
||||
try {
|
||||
while (true) {
|
||||
if (signal.aborted) throw abortException();
|
||||
const next = await readOrAbort(reader.read(), signal);
|
||||
if (scope.signal.aborted) throw abortException();
|
||||
// A late chunk is dropped: the bytes are only accumulated below.
|
||||
const next = await awaitOwned(scope, reader.read(), () => undefined);
|
||||
if (next.done) break;
|
||||
if (!(next.value instanceof Uint8Array)) {
|
||||
throw new TypeError("Image response chunk is invalid.");
|
||||
@@ -515,90 +522,28 @@ async function readBoundedBody(
|
||||
return bytes;
|
||||
}
|
||||
|
||||
type ProbeAbortScope = Readonly<{
|
||||
signal: AbortSignal;
|
||||
/** True once a deadline, or a deadline that could not be installed, ended it. */
|
||||
timedOut(): boolean;
|
||||
/**
|
||||
* Awaits `task` under this scope's ownership. A late value is compensated
|
||||
* exactly once; a terminal owner raises the scope's abort exception.
|
||||
*/
|
||||
await<Value>(
|
||||
task: Promise<Value>,
|
||||
onLateValue: (value: Value) => void,
|
||||
): Promise<Value>;
|
||||
release(): void;
|
||||
}>;
|
||||
|
||||
/**
|
||||
* X-AUDIT-02 / TR-RR-05. The probe scope is the shared abort primitive with
|
||||
* this subsystem's vocabulary on top. Owning a private copy meant the caller
|
||||
* listener was attached before the timer was installed, so a scheduler that
|
||||
* threw rejected the public `probe()` promise and left the listener behind.
|
||||
* `CLOSED` here means the deadline could never be installed, so the probe was
|
||||
* never bounded: operationally the same unanswered host as a deadline.
|
||||
*/
|
||||
function createProbeAbortScope(
|
||||
externalSignal: AbortSignal,
|
||||
timeoutMs: number,
|
||||
timers: AbortTimerSnapshot,
|
||||
): ProbeAbortScope {
|
||||
const operation = createAbortableOperation({
|
||||
signal: externalSignal,
|
||||
timeoutMs,
|
||||
setTimer: timers.setTimer,
|
||||
clearTimer: timers.clearTimer,
|
||||
});
|
||||
return Object.freeze({
|
||||
signal: operation.signal,
|
||||
// `CLOSED` here means the deadline could never be installed, so the probe
|
||||
// was never bounded: operationally the same unanswered host as a deadline.
|
||||
timedOut: () =>
|
||||
operation.terminal() !== "CALLER_ABORT" && operation.terminal() !== null,
|
||||
async await<Value>(
|
||||
task: Promise<Value>,
|
||||
onLateValue: (value: Value) => void,
|
||||
): Promise<Value> {
|
||||
const raced = await operation.race(task, onLateValue);
|
||||
if (raced.kind === "VALUE") return raced.value;
|
||||
if (raced.kind === "REJECTED") throw raced.reason;
|
||||
throw abortException();
|
||||
},
|
||||
release: () => operation.close(),
|
||||
});
|
||||
function unanswered(scope: AbortableOperation): boolean {
|
||||
const terminal = scope.terminal();
|
||||
return terminal !== null && terminal !== "CALLER_ABORT";
|
||||
}
|
||||
|
||||
/**
|
||||
* A single read raced against the probe's ownership. A late chunk is dropped:
|
||||
* the bytes are only ever accumulated by the caller below.
|
||||
* Awaits `task` under the probe's ownership. A late value is compensated
|
||||
* exactly once; a terminal owner raises the probe's abort exception.
|
||||
*/
|
||||
function readOrAbort<Value>(
|
||||
async function awaitOwned<Value>(
|
||||
scope: AbortableOperation,
|
||||
task: Promise<Value>,
|
||||
signal: AbortSignal,
|
||||
onLateValue: (value: Value) => void,
|
||||
): Promise<Value> {
|
||||
return new Promise<Value>((resolve, reject) => {
|
||||
let settled = false;
|
||||
const onAbort = () => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
reject(abortException());
|
||||
};
|
||||
signal.addEventListener("abort", onAbort, { once: true });
|
||||
void task.then(
|
||||
(value) => {
|
||||
signal.removeEventListener("abort", onAbort);
|
||||
if (!settled) {
|
||||
settled = true;
|
||||
resolve(value);
|
||||
}
|
||||
},
|
||||
(error: unknown) => {
|
||||
signal.removeEventListener("abort", onAbort);
|
||||
if (!settled) {
|
||||
settled = true;
|
||||
reject(error);
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
const raced = await scope.race(task, onLateValue);
|
||||
if (raced.kind === "VALUE") return raced.value;
|
||||
if (raced.kind === "REJECTED") throw raced.reason;
|
||||
throw abortException();
|
||||
}
|
||||
|
||||
function signalFailure(externalSignal: AbortSignal) {
|
||||
@@ -612,25 +557,6 @@ function signalFailure(externalSignal: AbortSignal) {
|
||||
});
|
||||
}
|
||||
|
||||
function cancelResponseBody(response: Response): void {
|
||||
try {
|
||||
const cancellation = response.body?.cancel();
|
||||
void cancellation?.catch(() => undefined);
|
||||
} catch {
|
||||
// Best-effort release cannot change the closed probe result.
|
||||
}
|
||||
}
|
||||
|
||||
function cancelReader(
|
||||
reader: ReadableStreamDefaultReader<Uint8Array>,
|
||||
): void {
|
||||
try {
|
||||
void reader.cancel().catch(() => undefined);
|
||||
} catch {
|
||||
// Best-effort release cannot change the closed probe result.
|
||||
}
|
||||
}
|
||||
|
||||
function closeBitmap(bitmap: DecodedImageFacade): void {
|
||||
try {
|
||||
bitmap.close();
|
||||
@@ -682,7 +608,3 @@ function isRasterMediaType(
|
||||
"image/webp",
|
||||
].includes(value);
|
||||
}
|
||||
|
||||
function positiveSafeInteger(value: number): boolean {
|
||||
return Number.isSafeInteger(value) && value > 0;
|
||||
}
|
||||
|
||||
@@ -4,6 +4,11 @@ import type {
|
||||
ImagePresetReference,
|
||||
ImageRasterMediaType,
|
||||
} from "../../../application/ports/browser-transfer/image-cdn.ts";
|
||||
import {
|
||||
isPositiveSafeInteger as positiveSafeInteger,
|
||||
isNonNegativeSafeInteger as nonNegativeSafeInteger,
|
||||
hasControlCharacter,
|
||||
} from "../../../application/ports/browser-file-storage/shared.ts";
|
||||
|
||||
export type ImageCdnOriginPolicy = Readonly<{
|
||||
originKey: string;
|
||||
@@ -476,7 +481,7 @@ function snapshotPreset(
|
||||
!positiveSafeInteger(input.quality) ||
|
||||
input.quality > hardLimits.maxQuality ||
|
||||
!SAFE_SIZES.test(input.sizes) ||
|
||||
hasControlCharacters(input.sizes) ||
|
||||
hasControlCharacter(input.sizes) ||
|
||||
!["eager", "lazy"].includes(input.loading) ||
|
||||
!["async", "sync"].includes(input.decoding) ||
|
||||
!["high", "low", "auto"].includes(input.fetchPriority) ||
|
||||
@@ -485,6 +490,10 @@ function snapshotPreset(
|
||||
"strict-origin-when-cross-origin",
|
||||
].includes(input.referrerPolicy) ||
|
||||
!["NONE", "PRIMARY_REQUIRED"].includes(input.probeMode) ||
|
||||
// Q-6.1-7 / D-12. The probe expects the exact primary pixel size, which
|
||||
// only these fits produce; inside/outside keep the source ratio.
|
||||
(input.probeMode === "PRIMARY_REQUIRED" &&
|
||||
!["cover", "contain", "fill"].includes(input.fit)) ||
|
||||
typeof input.allowUpscale !== "boolean" ||
|
||||
!positiveSafeInteger(input.maxTransformedPixels) ||
|
||||
input.maxTransformedPixels > hardLimits.maxTransformedPixels ||
|
||||
@@ -722,14 +731,6 @@ function positiveDpr(value: number): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
function positiveSafeInteger(value: number): boolean {
|
||||
return Number.isSafeInteger(value) && value > 0;
|
||||
}
|
||||
|
||||
function nonNegativeSafeInteger(value: number): boolean {
|
||||
return Number.isSafeInteger(value) && value >= 0;
|
||||
}
|
||||
|
||||
function hasExactOwnKeys(
|
||||
input: unknown,
|
||||
keys: readonly string[],
|
||||
@@ -744,10 +745,3 @@ function hasExactOwnKeys(
|
||||
actual.every((key, index) => key === expected[index])
|
||||
);
|
||||
}
|
||||
|
||||
function hasControlCharacters(value: string): boolean {
|
||||
return [...value].some((character) => {
|
||||
const codePoint = character.codePointAt(0) ?? 0;
|
||||
return codePoint < 0x20 || codePoint === 0x7f;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -71,6 +71,7 @@ type IssuedDescriptorSnapshot = BackendIssuedImageAsset;
|
||||
const OPAQUE_TOKEN = /^[A-Za-z0-9_-]{8,128}$/u;
|
||||
const SIGNATURE = /^[A-Za-z0-9_-]{16,512}$/u;
|
||||
const SHA256_HEX = /^[a-f0-9]{64}$/u;
|
||||
const REGISTRY_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;
|
||||
const PUBLIC_DESCRIPTOR_KEYS = Object.freeze([
|
||||
"kind",
|
||||
"originKey",
|
||||
@@ -145,19 +146,18 @@ export function createImageCdnRuntime(
|
||||
dependencies.capabilityVerifier,
|
||||
);
|
||||
if (dependencies.capabilityVerifier) {
|
||||
let covered = false;
|
||||
try {
|
||||
if (
|
||||
!verifyCapability ||
|
||||
!acceptsCapabilityKey ||
|
||||
[...capabilityPolicy.acceptedKeyIds].some(
|
||||
(keyId) => acceptsCapabilityKey(keyId) !== true,
|
||||
)
|
||||
) {
|
||||
throw new TypeError(
|
||||
"Image capability verifier registry does not cover policy keys.",
|
||||
covered =
|
||||
!!verifyCapability &&
|
||||
!!acceptsCapabilityKey &&
|
||||
[...capabilityPolicy.acceptedKeyIds].every(
|
||||
(keyId) => acceptsCapabilityKey(keyId) === true,
|
||||
);
|
||||
}
|
||||
} catch {
|
||||
// A throwing registry covers nothing.
|
||||
}
|
||||
if (!covered) {
|
||||
throw new TypeError(
|
||||
"Image capability verifier registry does not cover policy keys.",
|
||||
);
|
||||
@@ -943,17 +943,11 @@ function snapshotIssuedDescriptor(
|
||||
allowedPresetBindingIds.some(
|
||||
(bindingId) =>
|
||||
typeof bindingId !== "string" ||
|
||||
!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test(
|
||||
bindingId,
|
||||
),
|
||||
!REGISTRY_ID.test(bindingId),
|
||||
) ||
|
||||
snapshot.signature.algorithm !== "ECDSA_P256_SHA256" ||
|
||||
!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test(
|
||||
snapshot.issuer,
|
||||
) ||
|
||||
!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test(
|
||||
snapshot.signature.keyId,
|
||||
) ||
|
||||
!REGISTRY_ID.test(snapshot.issuer) ||
|
||||
!REGISTRY_ID.test(snapshot.signature.keyId) ||
|
||||
!SHA256_HEX.test(
|
||||
snapshot.signature.capabilityBindingDigestHex,
|
||||
) ||
|
||||
@@ -1062,34 +1056,25 @@ function createCapabilityVerificationDeadline(
|
||||
timeoutMs: number,
|
||||
scheduler: ImageCapabilityVerificationScheduler,
|
||||
): ImageCapabilityVerificationDeadline {
|
||||
const controller = new AbortController();
|
||||
let released = false;
|
||||
const abortListeners = new Map<AbortSignal, () => void>();
|
||||
const activeSignals = signals.filter(
|
||||
(signal): signal is AbortSignal => signal !== undefined,
|
||||
const scope = combineImageRuntimeAbortSignals(
|
||||
signals.filter(
|
||||
(signal): signal is AbortSignal => signal !== undefined,
|
||||
),
|
||||
);
|
||||
for (const signal of new Set(activeSignals)) {
|
||||
const onAbort = () => controller.abort(signal.reason);
|
||||
abortListeners.set(signal, onAbort);
|
||||
signal.addEventListener("abort", onAbort, { once: true });
|
||||
if (signal.aborted) onAbort();
|
||||
}
|
||||
|
||||
let released = false;
|
||||
let timeoutHandle: unknown;
|
||||
try {
|
||||
timeoutHandle = scheduler.setTimeout(() => {
|
||||
if (released) return;
|
||||
controller.abort(capabilityVerificationAbortException());
|
||||
scope.abort(capabilityVerificationAbortException());
|
||||
}, timeoutMs);
|
||||
} catch (error) {
|
||||
for (const [signal, onAbort] of abortListeners) {
|
||||
signal.removeEventListener("abort", onAbort);
|
||||
}
|
||||
scope.release();
|
||||
throw error;
|
||||
}
|
||||
|
||||
return Object.freeze({
|
||||
signal: controller.signal,
|
||||
signal: scope.signal,
|
||||
release() {
|
||||
if (released) return;
|
||||
released = true;
|
||||
@@ -1098,10 +1083,7 @@ function createCapabilityVerificationDeadline(
|
||||
} catch {
|
||||
// Scheduler cleanup cannot alter an already closed adapter result.
|
||||
}
|
||||
for (const [signal, onAbort] of abortListeners) {
|
||||
signal.removeEventListener("abort", onAbort);
|
||||
}
|
||||
abortListeners.clear();
|
||||
scope.release();
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1139,7 +1121,11 @@ function awaitImageRuntimeAbort<Value>(
|
||||
|
||||
function combineImageRuntimeAbortSignals(
|
||||
signals: readonly AbortSignal[],
|
||||
): Readonly<{ signal: AbortSignal; release(): void }> {
|
||||
): Readonly<{
|
||||
signal: AbortSignal;
|
||||
abort(reason: unknown): void;
|
||||
release(): void;
|
||||
}> {
|
||||
const controller = new AbortController();
|
||||
const abortListeners = new Map<AbortSignal, () => void>();
|
||||
for (const signal of new Set(signals)) {
|
||||
@@ -1151,6 +1137,7 @@ function combineImageRuntimeAbortSignals(
|
||||
let released = false;
|
||||
return Object.freeze({
|
||||
signal: controller.signal,
|
||||
abort: (reason: unknown) => controller.abort(reason),
|
||||
release() {
|
||||
if (released) return;
|
||||
released = true;
|
||||
|
||||
@@ -73,8 +73,6 @@ function parsePng(
|
||||
const interlace = bytes[payloadStart + 12];
|
||||
if (
|
||||
!dimensions ||
|
||||
bitDepth === undefined ||
|
||||
colorType === undefined ||
|
||||
!validPngColorDepth(colorType, bitDepth) ||
|
||||
compression !== 0 ||
|
||||
filter !== 0 ||
|
||||
@@ -144,7 +142,7 @@ function parseJpeg(
|
||||
if (offset >= bytes.byteLength) return null;
|
||||
const marker = bytes[offset];
|
||||
offset += 1;
|
||||
if (marker === undefined || marker === 0x00) return null;
|
||||
if (marker === 0x00) return null;
|
||||
if (marker === 0xd9) return null;
|
||||
if (marker === 0xda) return dimensions;
|
||||
if (
|
||||
@@ -227,7 +225,6 @@ function parseWebp(
|
||||
chunkIndex !== 0 ||
|
||||
extendedHeaderSeen ||
|
||||
length !== 10 ||
|
||||
bytes[payloadStart] === undefined ||
|
||||
(bytes[payloadStart] & 0xc3) !== 0
|
||||
) {
|
||||
return null;
|
||||
@@ -260,15 +257,7 @@ function parseWebp(
|
||||
const byte2 = bytes[payloadStart + 2];
|
||||
const byte3 = bytes[payloadStart + 3];
|
||||
const byte4 = bytes[payloadStart + 4];
|
||||
if (
|
||||
byte1 === undefined ||
|
||||
byte2 === undefined ||
|
||||
byte3 === undefined ||
|
||||
byte4 === undefined ||
|
||||
(byte4 & 0xe0) !== 0
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
if ((byte4 & 0xe0) !== 0) return null;
|
||||
candidate = validDimensions(
|
||||
1 + byte1 + ((byte2 & 0x3f) << 8),
|
||||
1 +
|
||||
@@ -306,14 +295,8 @@ function parseAvif(
|
||||
return null;
|
||||
}
|
||||
const fileType = boxes[0];
|
||||
const fileTypeLength = fileType
|
||||
? fileType.payloadEnd - fileType.payloadStart
|
||||
: 0;
|
||||
if (
|
||||
!fileType ||
|
||||
fileTypeLength < 8 ||
|
||||
(fileTypeLength - 8) % 4 !== 0
|
||||
) {
|
||||
const fileTypeLength = fileType.payloadEnd - fileType.payloadStart;
|
||||
if (fileTypeLength < 8 || (fileTypeLength - 8) % 4 !== 0) {
|
||||
return null;
|
||||
}
|
||||
const brands: string[] = [
|
||||
@@ -343,7 +326,6 @@ function parseAvif(
|
||||
const metadataBox = metadataBoxes[0];
|
||||
if (
|
||||
metadataBoxes.length !== 1 ||
|
||||
!metadataBox ||
|
||||
metadataBox.payloadStart + 4 > metadataBox.payloadEnd ||
|
||||
!zeroFullBoxFlags(bytes, metadataBox.payloadStart)
|
||||
) {
|
||||
@@ -413,9 +395,7 @@ function parseAvif(
|
||||
const dimensions = state.properties.get(propertyIndex);
|
||||
if (dimensions) associatedExtents.push(dimensions);
|
||||
}
|
||||
return associatedExtents.length === 1
|
||||
? (associatedExtents[0] ?? null)
|
||||
: null;
|
||||
return associatedExtents.length === 1 ? associatedExtents[0] : null;
|
||||
}
|
||||
|
||||
type IsoBox = Readonly<{
|
||||
@@ -532,11 +512,7 @@ function parseAvifItemProperties(
|
||||
(child) => child.type === "ipma",
|
||||
);
|
||||
const propertyContainer = propertyContainers[0];
|
||||
if (
|
||||
propertyContainers.length !== 1 ||
|
||||
associationBoxes.length < 1 ||
|
||||
!propertyContainer
|
||||
) {
|
||||
if (propertyContainers.length !== 1 || associationBoxes.length < 1) {
|
||||
return false;
|
||||
}
|
||||
const properties = parseBoxes(
|
||||
@@ -581,9 +557,7 @@ function parseAvifPropertyAssociations(
|
||||
const version = bytes[start];
|
||||
if (version !== 0 && version !== 1) return false;
|
||||
const flags =
|
||||
((bytes[start + 1] ?? 0) << 16) |
|
||||
((bytes[start + 2] ?? 0) << 8) |
|
||||
(bytes[start + 3] ?? 0);
|
||||
(bytes[start + 1] << 16) | (bytes[start + 2] << 8) | bytes[start + 3];
|
||||
if ((flags & ~1) !== 0) return false;
|
||||
const wideAssociation = (flags & 1) === 1;
|
||||
const view = dataView(bytes);
|
||||
@@ -598,7 +572,6 @@ function parseAvifPropertyAssociations(
|
||||
: view.getUint32(offset);
|
||||
offset += itemIdBytes;
|
||||
const associationCount = bytes[offset];
|
||||
if (associationCount === undefined) return false;
|
||||
offset += 1;
|
||||
const propertyIndices: number[] = [];
|
||||
for (
|
||||
@@ -609,9 +582,7 @@ function parseAvifPropertyAssociations(
|
||||
const associationBytes = wideAssociation ? 2 : 1;
|
||||
if (offset + associationBytes > end) return false;
|
||||
const encoded =
|
||||
associationBytes === 2
|
||||
? view.getUint16(offset)
|
||||
: (bytes[offset] ?? 0);
|
||||
associationBytes === 2 ? view.getUint16(offset) : bytes[offset];
|
||||
const propertyIndex =
|
||||
encoded & (wideAssociation ? 0x7fff : 0x7f);
|
||||
offset += associationBytes;
|
||||
@@ -694,35 +665,23 @@ function validDimensions(
|
||||
: null;
|
||||
}
|
||||
|
||||
/** Callers pass an offset whose three bytes lie inside a checked chunk. */
|
||||
function readUint24LittleEndian(
|
||||
bytes: Uint8Array,
|
||||
offset: number,
|
||||
): number {
|
||||
const byte0 = bytes[offset];
|
||||
const byte1 = bytes[offset + 1];
|
||||
const byte2 = bytes[offset + 2];
|
||||
if (
|
||||
byte0 === undefined ||
|
||||
byte1 === undefined ||
|
||||
byte2 === undefined
|
||||
) {
|
||||
return Number.NaN;
|
||||
}
|
||||
return byte0 | (byte1 << 8) | (byte2 << 16);
|
||||
return (
|
||||
bytes[offset] | (bytes[offset + 1] << 8) | (bytes[offset + 2] << 16)
|
||||
);
|
||||
}
|
||||
|
||||
/** Callers pass a range that the surrounding length checks keep in bounds. */
|
||||
function ascii(
|
||||
bytes: Uint8Array,
|
||||
start: number,
|
||||
end: number,
|
||||
): string {
|
||||
let value = "";
|
||||
for (let offset = start; offset < end; offset += 1) {
|
||||
const byte = bytes[offset];
|
||||
if (byte === undefined) return "";
|
||||
value += String.fromCharCode(byte);
|
||||
}
|
||||
return value;
|
||||
return String.fromCharCode(...bytes.subarray(start, end));
|
||||
}
|
||||
|
||||
function dataView(bytes: Uint8Array): DataView {
|
||||
|
||||
@@ -87,8 +87,7 @@ export function createP256ImageCapabilityVerifier(
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
const signatureBytes = new Uint8Array(signature.byteLength);
|
||||
signatureBytes.set(signature);
|
||||
// `decodeBase64Url` already returns an owned, exactly sized buffer.
|
||||
const payloadBytes = new Uint8Array(
|
||||
request.canonicalPayload.byteLength,
|
||||
);
|
||||
@@ -96,7 +95,7 @@ export function createP256ImageCapabilityVerifier(
|
||||
return await verify(
|
||||
{ name: "ECDSA", hash: "SHA-256" },
|
||||
key,
|
||||
signatureBytes.buffer,
|
||||
signature.buffer,
|
||||
payloadBytes.buffer,
|
||||
);
|
||||
} catch {
|
||||
@@ -106,7 +105,7 @@ export function createP256ImageCapabilityVerifier(
|
||||
});
|
||||
}
|
||||
|
||||
function decodeBase64Url(value: string): Uint8Array | null {
|
||||
function decodeBase64Url(value: string): Uint8Array<ArrayBuffer> | null {
|
||||
if (
|
||||
!/^[A-Za-z0-9_-]+$/u.test(value) ||
|
||||
value.length % 4 === 1
|
||||
@@ -119,9 +118,8 @@ function decodeBase64Url(value: string): Uint8Array | null {
|
||||
let accumulator = 0;
|
||||
let bitCount = 0;
|
||||
for (const character of value) {
|
||||
const index = alphabet.indexOf(character);
|
||||
if (index < 0) return null;
|
||||
accumulator = (accumulator << 6) | index;
|
||||
// The pattern above admits only alphabet characters.
|
||||
accumulator = (accumulator << 6) | alphabet.indexOf(character);
|
||||
bitCount += 6;
|
||||
if (bitCount >= 8) {
|
||||
bitCount -= 8;
|
||||
|
||||
@@ -0,0 +1,236 @@
|
||||
import {
|
||||
createAbortableOperation,
|
||||
type AbortTimerSnapshot,
|
||||
} from "../../platform/abortable-operation.ts";
|
||||
import type {
|
||||
BrowserDataFailureCode,
|
||||
BrowserDataObserver,
|
||||
BrowserDataOperation,
|
||||
BrowserDataRecovery,
|
||||
BrowserDataResult,
|
||||
} from "../../../application/ports/browser-file-storage/shared.ts";
|
||||
import { browserDataByteBucket as byteBucket } from "../../../application/ports/browser-file-storage/shared.ts";
|
||||
import type { Result } from "../../../contracts/result.ts";
|
||||
import {
|
||||
browserDataFailure,
|
||||
observeBrowserData,
|
||||
} from "../../browser-file-storage/result.ts";
|
||||
|
||||
/**
|
||||
* Q-6.1-9. HTTP mechanics shared by the presigned executor (object-store
|
||||
* GET/PUT) and the capability provider (BFF issuance). They were two
|
||||
* near-identical copies whose status table had already drifted apart.
|
||||
*/
|
||||
|
||||
export { byteBucket };
|
||||
|
||||
/** BT-PRE-03. The scope ended before the task settled. */
|
||||
export const SCOPE_ENDED = Symbol("presigned-scope-ended");
|
||||
|
||||
export type PresignedAbortScope = ReturnType<typeof createAbortScope>;
|
||||
|
||||
/**
|
||||
* TR-RR-01 / TR-RR-05. A thin projection of the shared
|
||||
* `createAbortableOperation` primitive into this subsystem's vocabulary.
|
||||
*
|
||||
* `abort()` exists, so `close()` on a download can actually stop a pending
|
||||
* fetch instead of only dropping listeners; and additional ownership signals —
|
||||
* a consumer's stream signal — are composed into the same operation *before*
|
||||
* any I/O starts, so an already-aborted consumer never causes a fetch.
|
||||
*/
|
||||
export function createAbortScope(
|
||||
external: AbortSignal,
|
||||
timeoutMs: number,
|
||||
timers: AbortTimerSnapshot,
|
||||
additionalSignals: readonly AbortSignal[] = [],
|
||||
) {
|
||||
const operation = createAbortableOperation({
|
||||
signal: external,
|
||||
timeoutMs,
|
||||
setTimer: timers.setTimer,
|
||||
clearTimer: timers.clearTimer,
|
||||
});
|
||||
const releases: (() => void)[] = [];
|
||||
for (const extra of additionalSignals) {
|
||||
if (!extra) continue;
|
||||
if (extra.aborted) {
|
||||
operation.close();
|
||||
continue;
|
||||
}
|
||||
const onAbort = () => operation.close();
|
||||
try {
|
||||
extra.addEventListener("abort", onAbort, { once: true });
|
||||
releases.push(() => {
|
||||
try {
|
||||
extra.removeEventListener("abort", onAbort);
|
||||
} catch {
|
||||
// A hostile signal facade cannot block the rest of cleanup.
|
||||
}
|
||||
});
|
||||
} catch {
|
||||
// A signal that refuses a listener cannot bound this operation, so the
|
||||
// operation closes rather than running unbounded.
|
||||
operation.close();
|
||||
}
|
||||
}
|
||||
const end = () => {
|
||||
operation.close();
|
||||
for (const release of releases.splice(0)) release();
|
||||
};
|
||||
return Object.freeze({
|
||||
signal: operation.signal,
|
||||
timedOut: () => operation.terminal() === "DEADLINE",
|
||||
/** Bounds a fetch that ignores its signal; a late response is cancelled. */
|
||||
async race<Value>(task: Promise<Value>): Promise<Value | typeof SCOPE_ENDED> {
|
||||
const outcome = await operation.race(task, (value) => {
|
||||
const body = (
|
||||
value as { body?: { cancel(): Promise<void> } | null } | null
|
||||
)?.body;
|
||||
void body?.cancel().catch(() => undefined);
|
||||
});
|
||||
if (outcome.kind === "VALUE") return outcome.value;
|
||||
// A collaborator's own rejection stays a rejection: the caller's existing
|
||||
// catch classifies it, and it is never forged into a cancellation.
|
||||
if (outcome.kind === "REJECTED") throw outcome.reason;
|
||||
return SCOPE_ENDED;
|
||||
},
|
||||
/** TR-RR-01. Ends the physical work, not just the bookkeeping. */
|
||||
abort: end,
|
||||
release: end,
|
||||
});
|
||||
}
|
||||
|
||||
export function readWithSignal(
|
||||
reader: ReadableStreamDefaultReader<Uint8Array>,
|
||||
signal: AbortSignal,
|
||||
): Promise<ReadableStreamReadResult<Uint8Array>> {
|
||||
if (signal.aborted) {
|
||||
return Promise.reject(new DOMException("Aborted", "AbortError"));
|
||||
}
|
||||
return new Promise((resolve, reject) => {
|
||||
const onAbort = () => {
|
||||
reject(new DOMException("Aborted", "AbortError"));
|
||||
};
|
||||
signal.addEventListener("abort", onAbort, { once: true });
|
||||
reader.read().then(
|
||||
(result) => {
|
||||
signal.removeEventListener("abort", onAbort);
|
||||
resolve(result);
|
||||
},
|
||||
(error: unknown) => {
|
||||
signal.removeEventListener("abort", onAbort);
|
||||
reject(error);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* A plain decimal `Content-Length`. `Number()` alone accepted `"5e0"`,
|
||||
* `"0x5"`, `"+5"` and `""`. An absent header is `null` unless the caller's
|
||||
* binding allows an implicit zero.
|
||||
*/
|
||||
export function normalizedContentLength(
|
||||
value: string | null,
|
||||
allowImplicitZero = false,
|
||||
): number | null {
|
||||
if (value === null) return allowImplicitZero ? 0 : null;
|
||||
const trimmed = value.trim();
|
||||
if (!/^(?:0|[1-9][0-9]{0,15})$/.test(trimmed)) return null;
|
||||
const length = Number(trimmed);
|
||||
return Number.isSafeInteger(length) ? length : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* One status table for both HTTP exchanges. Presigned capabilities are
|
||||
* single-use, so every recoverable refusal — an expired or rejected signature
|
||||
* (401/403), a conflict, a gone resource or a transient 429/5xx — is recovered
|
||||
* by issuing a new capability, never by replaying the same one.
|
||||
*/
|
||||
export function statusFailure(
|
||||
status: number,
|
||||
): BrowserDataResult<never> {
|
||||
let code: BrowserDataFailureCode = "UNAVAILABLE";
|
||||
let recovery: BrowserDataRecovery = "REISSUE_CAPABILITY";
|
||||
let retryable = status === 429 || status >= 500;
|
||||
if (status === 401 || status === 403) {
|
||||
code = "PERMISSION_DENIED";
|
||||
retryable = false;
|
||||
} else if (status === 404) {
|
||||
code = "NOT_FOUND";
|
||||
recovery = "NONE";
|
||||
retryable = false;
|
||||
} else if (status === 409) {
|
||||
code = "CONFLICT";
|
||||
retryable = false;
|
||||
} else if (status === 410) {
|
||||
code = "EXPIRED_RESOURCE";
|
||||
retryable = false;
|
||||
} else if (status === 413) {
|
||||
code = "LIMIT_EXCEEDED";
|
||||
recovery = "NONE";
|
||||
retryable = false;
|
||||
} else if (status >= 400 && status < 500 && status !== 429) {
|
||||
code = "POLICY_REJECTED";
|
||||
recovery = "NONE";
|
||||
retryable = false;
|
||||
}
|
||||
return browserDataFailure(code, "PRESIGNED_TRANSFER", {
|
||||
retryable,
|
||||
recovery,
|
||||
});
|
||||
}
|
||||
|
||||
export function transferFailure(
|
||||
externalSignal: AbortSignal,
|
||||
timedOut: boolean,
|
||||
): BrowserDataResult<never> {
|
||||
if (externalSignal.aborted) {
|
||||
return browserDataFailure("ABORTED", "PRESIGNED_TRANSFER");
|
||||
}
|
||||
return browserDataFailure(
|
||||
timedOut ? "UNAVAILABLE" : "NOT_READABLE",
|
||||
"PRESIGNED_TRANSFER",
|
||||
{
|
||||
retryable: true,
|
||||
recovery: "REISSUE_CAPABILITY",
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
export function isAbortSignal(value: unknown): value is AbortSignal {
|
||||
try {
|
||||
if (!value || typeof value !== "object") return false;
|
||||
const abortedGetter = Object.getOwnPropertyDescriptor(
|
||||
AbortSignal.prototype,
|
||||
"aborted",
|
||||
)?.get;
|
||||
return Boolean(
|
||||
abortedGetter &&
|
||||
typeof abortedGetter.call(value) === "boolean" &&
|
||||
typeof (value as AbortSignal).addEventListener === "function" &&
|
||||
typeof (value as AbortSignal).removeEventListener === "function",
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One terminal observation for presigned and resumable transfers. An absent or
|
||||
* invalid byte length leaves `byteBucket` out rather than guessing one.
|
||||
*/
|
||||
export function observeTransferResult(
|
||||
observer: BrowserDataObserver | undefined,
|
||||
operation: BrowserDataOperation,
|
||||
result: Result<unknown, Readonly<{ code: BrowserDataFailureCode }>>,
|
||||
byteLength?: number,
|
||||
): void {
|
||||
const bucket = byteBucket(byteLength);
|
||||
observeBrowserData(observer, {
|
||||
operation,
|
||||
outcome: result.ok ? "SUCCEEDED" : "FAILED",
|
||||
...(!result.ok ? { failureCode: result.error.code } : {}),
|
||||
...(bucket !== undefined ? { byteBucket: bucket } : {}),
|
||||
});
|
||||
}
|
||||
@@ -126,8 +126,8 @@ class Sha256Accumulator {
|
||||
words[index] = view.getUint32(index * 4, false);
|
||||
}
|
||||
for (let index = 16; index < 64; index += 1) {
|
||||
const previous15 = words[index - 15] ?? 0;
|
||||
const previous2 = words[index - 2] ?? 0;
|
||||
const previous15 = words[index - 15];
|
||||
const previous2 = words[index - 2];
|
||||
const sigma0 =
|
||||
rotateRight(previous15, 7) ^
|
||||
rotateRight(previous15, 18) ^
|
||||
@@ -136,22 +136,18 @@ class Sha256Accumulator {
|
||||
rotateRight(previous2, 17) ^
|
||||
rotateRight(previous2, 19) ^
|
||||
(previous2 >>> 10);
|
||||
words[index] =
|
||||
((words[index - 16] ?? 0) +
|
||||
sigma0 +
|
||||
(words[index - 7] ?? 0) +
|
||||
sigma1) >>>
|
||||
0;
|
||||
// A Uint32Array store already reduces modulo 2^32.
|
||||
words[index] = words[index - 16] + sigma0 + words[index - 7] + sigma1;
|
||||
}
|
||||
|
||||
let a = this.#state[0] ?? 0;
|
||||
let b = this.#state[1] ?? 0;
|
||||
let c = this.#state[2] ?? 0;
|
||||
let d = this.#state[3] ?? 0;
|
||||
let e = this.#state[4] ?? 0;
|
||||
let f = this.#state[5] ?? 0;
|
||||
let g = this.#state[6] ?? 0;
|
||||
let h = this.#state[7] ?? 0;
|
||||
let a = this.#state[0];
|
||||
let b = this.#state[1];
|
||||
let c = this.#state[2];
|
||||
let d = this.#state[3];
|
||||
let e = this.#state[4];
|
||||
let f = this.#state[5];
|
||||
let g = this.#state[6];
|
||||
let h = this.#state[7];
|
||||
|
||||
for (let index = 0; index < 64; index += 1) {
|
||||
const sum1 =
|
||||
@@ -161,8 +157,8 @@ class Sha256Accumulator {
|
||||
(h +
|
||||
sum1 +
|
||||
choice +
|
||||
(ROUND_CONSTANTS[index] ?? 0) +
|
||||
(words[index] ?? 0)) >>>
|
||||
ROUND_CONSTANTS[index] +
|
||||
words[index]) >>>
|
||||
0;
|
||||
const sum0 =
|
||||
rotateRight(a, 2) ^ rotateRight(a, 13) ^ rotateRight(a, 22);
|
||||
@@ -178,14 +174,15 @@ class Sha256Accumulator {
|
||||
a = (temporary1 + temporary2) >>> 0;
|
||||
}
|
||||
|
||||
this.#state[0] = ((this.#state[0] ?? 0) + a) >>> 0;
|
||||
this.#state[1] = ((this.#state[1] ?? 0) + b) >>> 0;
|
||||
this.#state[2] = ((this.#state[2] ?? 0) + c) >>> 0;
|
||||
this.#state[3] = ((this.#state[3] ?? 0) + d) >>> 0;
|
||||
this.#state[4] = ((this.#state[4] ?? 0) + e) >>> 0;
|
||||
this.#state[5] = ((this.#state[5] ?? 0) + f) >>> 0;
|
||||
this.#state[6] = ((this.#state[6] ?? 0) + g) >>> 0;
|
||||
this.#state[7] = ((this.#state[7] ?? 0) + h) >>> 0;
|
||||
const state = this.#state;
|
||||
state[0] += a;
|
||||
state[1] += b;
|
||||
state[2] += c;
|
||||
state[3] += d;
|
||||
state[4] += e;
|
||||
state[5] += f;
|
||||
state[6] += g;
|
||||
state[7] += h;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -11,30 +11,39 @@ import type {
|
||||
PresignedUploadPartCapabilityProvider,
|
||||
} from "../../../application/ports/browser-transfer/presigned-transfer.ts";
|
||||
import {
|
||||
createAbortableOperation,
|
||||
cancelBody,
|
||||
cancelReader,
|
||||
snapshotAbortTimers,
|
||||
type AbortTimerSnapshot,
|
||||
} from "../../platform/abortable-operation.ts";
|
||||
import { RESUMABLE_UPLOAD_PROTOCOL } from "../../../application/ports/browser-transfer/resumable-upload.ts";
|
||||
import type {
|
||||
BrowserDataFailureCode,
|
||||
BrowserDataObserver,
|
||||
BrowserDataRecovery,
|
||||
BrowserDataResult,
|
||||
} from "../../../application/ports/browser-file-storage/shared.ts";
|
||||
import {
|
||||
browserDataFailure,
|
||||
browserDataSuccess,
|
||||
observeBrowserData,
|
||||
} from "../../browser-file-storage/result.ts";
|
||||
import type {
|
||||
PresignedCapabilityRegistration,
|
||||
PresignedCapabilityVault,
|
||||
PresignedHeaderBinding,
|
||||
} from "./presigned-capability-vault.ts";
|
||||
import { SAFE_TRANSFER_ID } from "../resumable-upload/checkpoint-schema.ts";
|
||||
import {
|
||||
createAbortScope,
|
||||
isAbortSignal,
|
||||
normalizedContentLength,
|
||||
observeTransferResult,
|
||||
readWithSignal,
|
||||
SCOPE_ENDED,
|
||||
statusFailure,
|
||||
transferFailure,
|
||||
} from "./http-common.ts";
|
||||
import {
|
||||
SAFE_TRANSFER_ID,
|
||||
SHA256_HEX as SHA256,
|
||||
} from "../resumable-upload/checkpoint-schema.ts";
|
||||
|
||||
const SHA256 = /^[a-f0-9]{64}$/;
|
||||
const MEDIA_TYPE = /^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/;
|
||||
const HEADER_NAME = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
|
||||
const QUERY_NAME = /^[A-Za-z0-9_.~-]{1,128}$/;
|
||||
@@ -170,15 +179,12 @@ export function createPresignedCapabilityHttpProvider(
|
||||
result: BrowserDataResult<Capability>,
|
||||
byteLength?: number,
|
||||
): BrowserDataResult<Capability> {
|
||||
const bucket = byteBucket(
|
||||
observeTransferResult(
|
||||
observer,
|
||||
"PRESIGNED_TRANSFER",
|
||||
result,
|
||||
result.ok ? result.value.byteLength : byteLength,
|
||||
);
|
||||
observeBrowserData(observer, {
|
||||
operation: "PRESIGNED_TRANSFER",
|
||||
outcome: result.ok ? "SUCCEEDED" : "FAILED",
|
||||
...(!result.ok ? { failureCode: result.error.code } : {}),
|
||||
...(bucket !== undefined ? { byteBucket: bucket } : {}),
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -237,11 +243,11 @@ export function createPresignedCapabilityHttpProvider(
|
||||
response.type === "opaqueredirect" ||
|
||||
response.url !== endpoint
|
||||
) {
|
||||
cancelResponseBody(response);
|
||||
cancelBody(response);
|
||||
return browserDataFailure("POLICY_REJECTED", "PRESIGNED_TRANSFER");
|
||||
}
|
||||
if (!response.ok || response.status !== 200) {
|
||||
cancelResponseBody(response);
|
||||
cancelBody(response);
|
||||
return statusFailure(response.status);
|
||||
}
|
||||
const contentType = response.headers.get("content-type") ?? "";
|
||||
@@ -249,7 +255,7 @@ export function createPresignedCapabilityHttpProvider(
|
||||
contentType.split(";", 1)[0]?.trim().toLowerCase() !==
|
||||
"application/json"
|
||||
) {
|
||||
cancelResponseBody(response);
|
||||
cancelBody(response);
|
||||
return browserDataFailure("POLICY_REJECTED", "PRESIGNED_TRANSFER");
|
||||
}
|
||||
const payload = await readBoundedJson(
|
||||
@@ -762,11 +768,11 @@ async function readBoundedJson(
|
||||
if (declared !== null) {
|
||||
declaredLength = normalizedContentLength(declared);
|
||||
if (declaredLength === null) {
|
||||
cancelResponseBody(response);
|
||||
cancelBody(response);
|
||||
throw new ResponseIntegrityError();
|
||||
}
|
||||
if (declaredLength > maxBytes) {
|
||||
cancelResponseBody(response);
|
||||
cancelBody(response);
|
||||
throw new ResponseLimitError();
|
||||
}
|
||||
}
|
||||
@@ -797,15 +803,7 @@ async function readBoundedJson(
|
||||
text += decoder.decode();
|
||||
return JSON.parse(text) as unknown;
|
||||
} finally {
|
||||
if (!completed) {
|
||||
try {
|
||||
void reader.cancel().catch(() => {
|
||||
// Response cancellation is best effort after classification.
|
||||
});
|
||||
} catch {
|
||||
// Response cleanup cannot alter the closed result.
|
||||
}
|
||||
}
|
||||
if (!completed) cancelReader(reader);
|
||||
try {
|
||||
reader.releaseLock();
|
||||
} catch {
|
||||
@@ -814,223 +812,6 @@ async function readBoundedJson(
|
||||
}
|
||||
}
|
||||
|
||||
function cancelResponseBody(response: Response): void {
|
||||
try {
|
||||
void response.body?.cancel().catch(() => {
|
||||
// Cancellation is best effort after the response is classified.
|
||||
});
|
||||
} catch {
|
||||
// Response cleanup cannot alter the closed result.
|
||||
}
|
||||
}
|
||||
|
||||
function normalizedContentLength(value: string): number | null {
|
||||
const trimmed = value.trim();
|
||||
if (!/^(?:0|[1-9][0-9]{0,15})$/.test(trimmed)) return null;
|
||||
const length = Number(trimmed);
|
||||
return Number.isSafeInteger(length) ? length : null;
|
||||
}
|
||||
|
||||
function readWithSignal(
|
||||
reader: ReadableStreamDefaultReader<Uint8Array>,
|
||||
signal: AbortSignal,
|
||||
): Promise<ReadableStreamReadResult<Uint8Array>> {
|
||||
if (signal.aborted) {
|
||||
return Promise.reject(new DOMException("Aborted", "AbortError"));
|
||||
}
|
||||
return new Promise((resolve, reject) => {
|
||||
const onAbort = () =>
|
||||
reject(new DOMException("Aborted", "AbortError"));
|
||||
signal.addEventListener("abort", onAbort, { once: true });
|
||||
reader.read().then(
|
||||
(result) => {
|
||||
signal.removeEventListener("abort", onAbort);
|
||||
resolve(result);
|
||||
},
|
||||
(error: unknown) => {
|
||||
signal.removeEventListener("abort", onAbort);
|
||||
reject(error);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function statusFailure(
|
||||
status: number,
|
||||
): BrowserDataResult<never> {
|
||||
let code: BrowserDataFailureCode = "UNAVAILABLE";
|
||||
let recovery: BrowserDataRecovery = "RETRY";
|
||||
let retryable = status === 429 || status >= 500;
|
||||
if (status === 401 || status === 403) {
|
||||
code = "PERMISSION_DENIED";
|
||||
recovery = "NONE";
|
||||
retryable = false;
|
||||
} else if (status === 404) {
|
||||
code = "NOT_FOUND";
|
||||
recovery = "NONE";
|
||||
retryable = false;
|
||||
} else if (status === 409) {
|
||||
code = "CONFLICT";
|
||||
recovery = "REISSUE_CAPABILITY";
|
||||
retryable = false;
|
||||
} else if (status === 410) {
|
||||
code = "EXPIRED_RESOURCE";
|
||||
recovery = "REISSUE_CAPABILITY";
|
||||
retryable = false;
|
||||
} else if (status === 413) {
|
||||
code = "LIMIT_EXCEEDED";
|
||||
recovery = "NONE";
|
||||
retryable = false;
|
||||
} else if (status >= 400 && status < 500 && status !== 429) {
|
||||
code = "POLICY_REJECTED";
|
||||
recovery = "NONE";
|
||||
retryable = false;
|
||||
}
|
||||
return browserDataFailure(code, "PRESIGNED_TRANSFER", {
|
||||
retryable,
|
||||
recovery,
|
||||
});
|
||||
}
|
||||
|
||||
/** BT-PRE-03. The scope ended before the task settled. */
|
||||
const SCOPE_ENDED = Symbol("presigned-capability-scope-ended");
|
||||
|
||||
/**
|
||||
* TR-RR-01 / TR-RR-05. The abort scope is a thin projection of the shared
|
||||
* `createAbortableOperation` primitive into this subsystem's vocabulary.
|
||||
*
|
||||
* Two things changed with the migration. `abort()` exists, so `close()` on a
|
||||
* download can actually stop a pending fetch instead of only dropping
|
||||
* listeners; and additional ownership signals — a consumer's stream signal —
|
||||
* are composed into the same operation *before* any I/O starts, so an
|
||||
* already-aborted consumer never causes a fetch.
|
||||
*/
|
||||
function createAbortScope(
|
||||
external: AbortSignal,
|
||||
timeoutMs: number,
|
||||
timers: AbortTimerSnapshot,
|
||||
additionalSignals: readonly AbortSignal[] = [],
|
||||
) {
|
||||
const operation = createAbortableOperation({
|
||||
signal: external,
|
||||
timeoutMs,
|
||||
setTimer: timers.setTimer,
|
||||
clearTimer: timers.clearTimer,
|
||||
});
|
||||
const releases: (() => void)[] = [];
|
||||
for (const extra of additionalSignals) {
|
||||
if (!extra) continue;
|
||||
if (extra.aborted) {
|
||||
operation.close();
|
||||
continue;
|
||||
}
|
||||
const onAbort = () => operation.close();
|
||||
try {
|
||||
extra.addEventListener("abort", onAbort, { once: true });
|
||||
releases.push(() => {
|
||||
try {
|
||||
extra.removeEventListener("abort", onAbort);
|
||||
} catch {
|
||||
// A hostile signal facade cannot block the rest of cleanup.
|
||||
}
|
||||
});
|
||||
} catch {
|
||||
// A signal that refuses a listener cannot bound this operation, so the
|
||||
// operation closes rather than running unbounded.
|
||||
operation.close();
|
||||
}
|
||||
}
|
||||
const releaseExtras = () => {
|
||||
for (const release of releases.splice(0)) release();
|
||||
};
|
||||
return Object.freeze({
|
||||
signal: operation.signal,
|
||||
timedOut: () => operation.terminal() === "DEADLINE",
|
||||
/** Bounds a fetch that ignores its signal. */
|
||||
async race<Value>(task: Promise<Value>): Promise<Value | typeof SCOPE_ENDED> {
|
||||
const outcome = await operation.race(
|
||||
task,
|
||||
(value) => compensateLateResponseValue(value),
|
||||
);
|
||||
if (outcome.kind === "VALUE") return outcome.value;
|
||||
// A collaborator's own rejection stays a rejection: the caller's existing
|
||||
// catch classifies it, and it is never forged into a cancellation.
|
||||
if (outcome.kind === "REJECTED") throw outcome.reason;
|
||||
return SCOPE_ENDED;
|
||||
},
|
||||
/** TR-RR-01. Ends the physical work, not just the bookkeeping. */
|
||||
abort() {
|
||||
operation.close();
|
||||
releaseExtras();
|
||||
},
|
||||
release() {
|
||||
operation.close();
|
||||
releaseExtras();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function compensateLateResponseValue(value: unknown): void {
|
||||
const body = (value as { body?: { cancel(): Promise<void> } | null } | null)
|
||||
?.body;
|
||||
void body?.cancel().catch(() => undefined);
|
||||
}
|
||||
|
||||
function transferFailure(
|
||||
signal: AbortSignal,
|
||||
timedOut: boolean,
|
||||
): BrowserDataResult<never> {
|
||||
if (signal.aborted) {
|
||||
return browserDataFailure("ABORTED", "PRESIGNED_TRANSFER");
|
||||
}
|
||||
return browserDataFailure(
|
||||
timedOut ? "UNAVAILABLE" : "NOT_READABLE",
|
||||
"PRESIGNED_TRANSFER",
|
||||
{ retryable: true, recovery: "REISSUE_CAPABILITY" },
|
||||
);
|
||||
}
|
||||
|
||||
function isAbortSignal(value: unknown): value is AbortSignal {
|
||||
try {
|
||||
if (!value || typeof value !== "object") return false;
|
||||
const abortedGetter = Object.getOwnPropertyDescriptor(
|
||||
AbortSignal.prototype,
|
||||
"aborted",
|
||||
)?.get;
|
||||
return Boolean(
|
||||
abortedGetter &&
|
||||
typeof abortedGetter.call(value) === "boolean" &&
|
||||
typeof (value as AbortSignal).addEventListener === "function" &&
|
||||
typeof (value as AbortSignal).removeEventListener === "function",
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function byteBucket(
|
||||
byteLength: number | undefined,
|
||||
):
|
||||
| "ZERO"
|
||||
| "LT1MIB"
|
||||
| "1_TO_9MIB"
|
||||
| "10_TO_99MIB"
|
||||
| "GTE100MIB"
|
||||
| undefined {
|
||||
if (
|
||||
byteLength === undefined ||
|
||||
!Number.isSafeInteger(byteLength) ||
|
||||
byteLength < 0
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
if (byteLength === 0) return "ZERO";
|
||||
if (byteLength < 1_048_576) return "LT1MIB";
|
||||
if (byteLength < 10_485_760) return "1_TO_9MIB";
|
||||
if (byteLength < 104_857_600) return "10_TO_99MIB";
|
||||
return "GTE100MIB";
|
||||
}
|
||||
|
||||
function strictRecord(
|
||||
value: unknown,
|
||||
keys: readonly string[],
|
||||
|
||||
@@ -275,18 +275,14 @@ export function createPresignedCapabilityVault(options: Readonly<{
|
||||
const invalid = validatePresignedCapabilityRegistration(snapshot);
|
||||
if (invalid) return invalid;
|
||||
pruneExpired();
|
||||
if (
|
||||
byReceipt.has(registration.capabilityReceipt) ||
|
||||
byReceipt.size >= maxActiveCapabilities
|
||||
) {
|
||||
// Q-6.1-11. The duplicate check reads the snapshot too; the issuer's
|
||||
// object is never read again once the snapshot exists.
|
||||
const duplicate = byReceipt.has(snapshot.capabilityReceipt);
|
||||
if (duplicate || byReceipt.size >= maxActiveCapabilities) {
|
||||
return browserDataFailure(
|
||||
byReceipt.has(registration.capabilityReceipt)
|
||||
? "CONFLICT"
|
||||
: "LIMIT_EXCEEDED",
|
||||
duplicate ? "CONFLICT" : "LIMIT_EXCEEDED",
|
||||
"PRESIGNED_TRANSFER",
|
||||
byReceipt.has(registration.capabilityReceipt)
|
||||
? { recovery: "REISSUE_CAPABILITY" }
|
||||
: undefined,
|
||||
duplicate ? { recovery: "REISSUE_CAPABILITY" } : undefined,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -9,9 +9,9 @@ import type {
|
||||
PresignedUploadPartPort,
|
||||
} from "../../../application/ports/browser-transfer/presigned-transfer.ts";
|
||||
import {
|
||||
createAbortableOperation,
|
||||
cancelBody,
|
||||
cancelReader,
|
||||
snapshotAbortTimers,
|
||||
type AbortTimerSnapshot,
|
||||
} from "../../platform/abortable-operation.ts";
|
||||
import { RESUMABLE_UPLOAD_PROTOCOL } from "../../../application/ports/browser-transfer/resumable-upload.ts";
|
||||
import type {
|
||||
@@ -34,10 +34,23 @@ import type {
|
||||
PresignedCapabilityBinding,
|
||||
PresignedCapabilityVault,
|
||||
} from "./presigned-capability-vault.ts";
|
||||
import { SAFE_TRANSFER_ID } from "../resumable-upload/checkpoint-schema.ts";
|
||||
|
||||
const SHA256 = /^[a-f0-9]{64}$/;
|
||||
const RECEIPT_TOKEN = /^[A-Za-z0-9][A-Za-z0-9._~:+/=-]{0,511}$/;
|
||||
import {
|
||||
byteBucket,
|
||||
createAbortScope,
|
||||
isAbortSignal,
|
||||
normalizedContentLength,
|
||||
observeTransferResult,
|
||||
readWithSignal,
|
||||
SCOPE_ENDED,
|
||||
statusFailure,
|
||||
transferFailure,
|
||||
type PresignedAbortScope,
|
||||
} from "./http-common.ts";
|
||||
import {
|
||||
isSafeUploadReceiptToken,
|
||||
SAFE_TRANSFER_ID,
|
||||
SHA256_HEX as SHA256,
|
||||
} from "../resumable-upload/checkpoint-schema.ts";
|
||||
|
||||
type Scheduler = Readonly<{
|
||||
setTimeout(callback: () => void, milliseconds: number): unknown;
|
||||
@@ -436,12 +449,12 @@ export function createPresignedTransferExecutor(
|
||||
|
||||
function createDownloadSource(input: Readonly<{
|
||||
start: (
|
||||
scope: ReturnType<typeof createAbortScope>,
|
||||
scope: PresignedAbortScope,
|
||||
) => Promise<Response>;
|
||||
validateResponse: (response: Response) => BrowserDataResult<unknown>;
|
||||
createScope: (
|
||||
consumerSignal?: AbortSignal,
|
||||
) => ReturnType<typeof createAbortScope>;
|
||||
) => PresignedAbortScope;
|
||||
recheckExpiry: () => BrowserDataResult<unknown>;
|
||||
binding: PresignedCapabilityBinding;
|
||||
capability: PresignedDownloadCapability;
|
||||
@@ -454,7 +467,7 @@ function createDownloadSource(input: Readonly<{
|
||||
}>): PresignedDownloadByteSource {
|
||||
/** BT-PRE-01. One state machine shared by `stream()` and `close()`. */
|
||||
let state: "READY" | "STREAMING" | "CLOSED" = "READY";
|
||||
let activeScope: ReturnType<typeof createAbortScope> | undefined;
|
||||
let activeScope: PresignedAbortScope | undefined;
|
||||
let activeResponse: Response | undefined;
|
||||
|
||||
// TR-RR-01. Releasing the scope only dropped listeners and the timer, so a
|
||||
@@ -784,8 +797,7 @@ function validateDownloadResponse(
|
||||
const contentEncoding = response.headers.get("content-encoding");
|
||||
if (
|
||||
mediaType !== binding.mediaType ||
|
||||
declaredLength === null ||
|
||||
Number(declaredLength) !== binding.byteLength ||
|
||||
normalizedContentLength(declaredLength) !== binding.byteLength ||
|
||||
digestHeader === null ||
|
||||
response.headers.get(digestHeader)?.trim().toLowerCase() !==
|
||||
binding.expectedSha256 ||
|
||||
@@ -929,17 +941,6 @@ function validateRequiredHeaders(
|
||||
);
|
||||
}
|
||||
|
||||
function normalizedContentLength(
|
||||
value: string | null,
|
||||
allowImplicitZero: boolean,
|
||||
): number | null {
|
||||
if (value === null) return allowImplicitZero ? 0 : null;
|
||||
const trimmed = value.trim();
|
||||
if (!/^(?:0|[1-9][0-9]{0,15})$/.test(trimmed)) return null;
|
||||
const length = Number(trimmed);
|
||||
return Number.isSafeInteger(length) ? length : null;
|
||||
}
|
||||
|
||||
function headersFor(binding: PresignedCapabilityBinding): Headers {
|
||||
const headers = new Headers();
|
||||
for (const header of binding.requestHeaders) {
|
||||
@@ -995,189 +996,6 @@ function validateExpiry(
|
||||
);
|
||||
}
|
||||
|
||||
function statusFailure(
|
||||
status: number,
|
||||
): BrowserDataResult<never> {
|
||||
let code: BrowserDataFailureCode = "UNAVAILABLE";
|
||||
let recovery: BrowserDataRecovery = "REISSUE_CAPABILITY";
|
||||
let retryable = status === 429 || status >= 500;
|
||||
if (status === 401 || status === 403) {
|
||||
code = "PERMISSION_DENIED";
|
||||
recovery = "REISSUE_CAPABILITY";
|
||||
retryable = false;
|
||||
} else if (status === 404) {
|
||||
code = "NOT_FOUND";
|
||||
recovery = "NONE";
|
||||
retryable = false;
|
||||
} else if (status === 409) {
|
||||
code = "CONFLICT";
|
||||
retryable = false;
|
||||
} else if (status === 410) {
|
||||
code = "EXPIRED_RESOURCE";
|
||||
retryable = false;
|
||||
} else if (status === 413) {
|
||||
code = "LIMIT_EXCEEDED";
|
||||
recovery = "NONE";
|
||||
retryable = false;
|
||||
} else if (status >= 400 && status < 500 && status !== 429) {
|
||||
code = "POLICY_REJECTED";
|
||||
recovery = "NONE";
|
||||
retryable = false;
|
||||
}
|
||||
return browserDataFailure(code, "PRESIGNED_TRANSFER", {
|
||||
retryable,
|
||||
recovery,
|
||||
});
|
||||
}
|
||||
|
||||
function transferFailure(
|
||||
externalSignal: AbortSignal,
|
||||
timedOut: boolean,
|
||||
): BrowserDataResult<never> {
|
||||
if (externalSignal.aborted) {
|
||||
return browserDataFailure("ABORTED", "PRESIGNED_TRANSFER");
|
||||
}
|
||||
return browserDataFailure(
|
||||
timedOut ? "UNAVAILABLE" : "NOT_READABLE",
|
||||
"PRESIGNED_TRANSFER",
|
||||
{
|
||||
retryable: true,
|
||||
recovery: "REISSUE_CAPABILITY",
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/** BT-PRE-03. The scope ended before the task settled. */
|
||||
const SCOPE_ENDED = Symbol("presigned-scope-ended");
|
||||
|
||||
function compensateLateResponse(task: Promise<unknown>): void {
|
||||
void task
|
||||
.then(async (value) => {
|
||||
const body = (value as { body?: { cancel(): Promise<void> } | null })
|
||||
?.body;
|
||||
await body?.cancel();
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}
|
||||
|
||||
/**
|
||||
* TR-RR-01 / TR-RR-05. A projection of the shared `createAbortableOperation`
|
||||
* primitive into this subsystem's vocabulary, replacing a second hand-written
|
||||
* copy of the same mechanics.
|
||||
*
|
||||
* `additionalSignals` lets a consumer's stream signal join the operation's
|
||||
* ownership before any I/O begins, and `abort()` ends the physical work rather
|
||||
* than only releasing bookkeeping.
|
||||
*/
|
||||
function createAbortScope(
|
||||
external: AbortSignal,
|
||||
timeoutMs: number,
|
||||
timers: AbortTimerSnapshot,
|
||||
additionalSignals: readonly AbortSignal[] = [],
|
||||
) {
|
||||
const operation = createAbortableOperation({
|
||||
signal: external,
|
||||
timeoutMs,
|
||||
setTimer: timers.setTimer,
|
||||
clearTimer: timers.clearTimer,
|
||||
});
|
||||
const releases: (() => void)[] = [];
|
||||
for (const extra of additionalSignals) {
|
||||
if (!extra) continue;
|
||||
if (extra.aborted) {
|
||||
operation.close();
|
||||
continue;
|
||||
}
|
||||
const onAbort = () => operation.close();
|
||||
try {
|
||||
extra.addEventListener("abort", onAbort, { once: true });
|
||||
releases.push(() => {
|
||||
try {
|
||||
extra.removeEventListener("abort", onAbort);
|
||||
} catch {
|
||||
// A hostile signal facade cannot block the rest of cleanup.
|
||||
}
|
||||
});
|
||||
} catch {
|
||||
operation.close();
|
||||
}
|
||||
}
|
||||
const releaseExtras = () => {
|
||||
for (const release of releases.splice(0)) release();
|
||||
};
|
||||
return Object.freeze({
|
||||
signal: operation.signal,
|
||||
timedOut: () => operation.terminal() === "DEADLINE",
|
||||
async race<Value>(task: Promise<Value>): Promise<Value | typeof SCOPE_ENDED> {
|
||||
const outcome = await operation.race(task, (value) => {
|
||||
const body = (
|
||||
value as { body?: { cancel(): Promise<void> } | null } | null
|
||||
)?.body;
|
||||
void body?.cancel().catch(() => undefined);
|
||||
});
|
||||
if (outcome.kind === "VALUE") return outcome.value;
|
||||
if (outcome.kind === "REJECTED") throw outcome.reason;
|
||||
return SCOPE_ENDED;
|
||||
},
|
||||
abort() {
|
||||
operation.close();
|
||||
releaseExtras();
|
||||
},
|
||||
release() {
|
||||
operation.close();
|
||||
releaseExtras();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function cancelBody(response: Response): void {
|
||||
try {
|
||||
void response.body?.cancel().catch(() => {
|
||||
// Cancellation is best effort after the result is classified.
|
||||
});
|
||||
} catch {
|
||||
// A response already classified as failure/success is not reclassified by
|
||||
// best-effort body cancellation.
|
||||
}
|
||||
}
|
||||
|
||||
function cancelReader(
|
||||
reader: ReadableStreamDefaultReader<Uint8Array>,
|
||||
): void {
|
||||
try {
|
||||
void reader.cancel().catch(() => {
|
||||
// Cancellation is best effort after the result is classified.
|
||||
});
|
||||
} catch {
|
||||
// Reader cancellation cannot alter the terminal closed result.
|
||||
}
|
||||
}
|
||||
|
||||
function readWithSignal(
|
||||
reader: ReadableStreamDefaultReader<Uint8Array>,
|
||||
signal: AbortSignal,
|
||||
): Promise<ReadableStreamReadResult<Uint8Array>> {
|
||||
if (signal.aborted) {
|
||||
return Promise.reject(new DOMException("Aborted", "AbortError"));
|
||||
}
|
||||
return new Promise((resolve, reject) => {
|
||||
const onAbort = () => {
|
||||
reject(new DOMException("Aborted", "AbortError"));
|
||||
};
|
||||
signal.addEventListener("abort", onAbort, { once: true });
|
||||
reader.read().then(
|
||||
(result) => {
|
||||
signal.removeEventListener("abort", onAbort);
|
||||
resolve(result);
|
||||
},
|
||||
(error: unknown) => {
|
||||
signal.removeEventListener("abort", onAbort);
|
||||
reject(error);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeReceiptToken(value: string | null): string | null {
|
||||
if (!value) return null;
|
||||
const trimmed = value.trim();
|
||||
@@ -1187,9 +1005,7 @@ function normalizeReceiptToken(value: string | null): string | null {
|
||||
trimmed.endsWith("\"")
|
||||
? trimmed.slice(1, -1)
|
||||
: trimmed;
|
||||
return RECEIPT_TOKEN.test(unquoted) && !unquoted.includes("://")
|
||||
? unquoted
|
||||
: null;
|
||||
return isSafeUploadReceiptToken(unquoted) ? unquoted : null;
|
||||
}
|
||||
|
||||
function responseUrlMatches(
|
||||
@@ -1247,24 +1063,6 @@ async function digestSha256WithWebCrypto(
|
||||
).join("");
|
||||
}
|
||||
|
||||
function isAbortSignal(value: unknown): value is AbortSignal {
|
||||
try {
|
||||
if (!value || typeof value !== "object") return false;
|
||||
const abortedGetter = Object.getOwnPropertyDescriptor(
|
||||
AbortSignal.prototype,
|
||||
"aborted",
|
||||
)?.get;
|
||||
return Boolean(
|
||||
abortedGetter &&
|
||||
typeof abortedGetter.call(value) === "boolean" &&
|
||||
typeof (value as AbortSignal).addEventListener === "function" &&
|
||||
typeof (value as AbortSignal).removeEventListener === "function",
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function safeInputByteLength(value: unknown): number | undefined {
|
||||
try {
|
||||
if (!value || typeof value !== "object") return undefined;
|
||||
@@ -1300,41 +1098,3 @@ function safeInputByteLength(value: unknown): number | undefined {
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function observeTransferResult(
|
||||
observer: BrowserDataObserver | undefined,
|
||||
operation: BrowserDataOperation,
|
||||
result: BrowserDataResult<unknown>,
|
||||
byteLength?: number,
|
||||
): void {
|
||||
const bucket = byteBucket(byteLength);
|
||||
observeBrowserData(observer, {
|
||||
operation,
|
||||
outcome: result.ok ? "SUCCEEDED" : "FAILED",
|
||||
...(!result.ok ? { failureCode: result.error.code } : {}),
|
||||
...(bucket !== undefined ? { byteBucket: bucket } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
function byteBucket(
|
||||
byteLength: number | undefined,
|
||||
):
|
||||
| "ZERO"
|
||||
| "LT1MIB"
|
||||
| "1_TO_9MIB"
|
||||
| "10_TO_99MIB"
|
||||
| "GTE100MIB"
|
||||
| undefined {
|
||||
if (
|
||||
byteLength === undefined ||
|
||||
!Number.isSafeInteger(byteLength) ||
|
||||
byteLength < 0
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
if (byteLength === 0) return "ZERO";
|
||||
if (byteLength < 1_048_576) return "LT1MIB";
|
||||
if (byteLength < 10_485_760) return "1_TO_9MIB";
|
||||
if (byteLength < 104_857_600) return "10_TO_99MIB";
|
||||
return "GTE100MIB";
|
||||
}
|
||||
|
||||
@@ -5,6 +5,10 @@ import type {
|
||||
UploadPartReceipt,
|
||||
} from "../../../application/ports/browser-transfer/resumable-upload.ts";
|
||||
import { RESUMABLE_UPLOAD_PROTOCOL } from "../../../application/ports/browser-transfer/resumable-upload.ts";
|
||||
import {
|
||||
isPositiveSafeInteger as positiveSafeInteger,
|
||||
isNonNegativeSafeInteger as nonNegativeSafeInteger,
|
||||
} from "../../../application/ports/browser-file-storage/shared.ts";
|
||||
|
||||
export const SAFE_UPLOAD_KEY = /^[A-Za-z0-9][A-Za-z0-9._~:-]{7,127}$/u;
|
||||
export const SAFE_REGISTRY_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;
|
||||
@@ -17,7 +21,7 @@ export const SAFE_OPAQUE_ID = /^[A-Za-z0-9_-]{8,512}$/u;
|
||||
*/
|
||||
export const SAFE_TRANSFER_ID = /^[A-Za-z0-9_-][A-Za-z0-9._:-]{0,511}$/u;
|
||||
export const SHA256_HEX = /^[a-f0-9]{64}$/u;
|
||||
export const RECEIPT_TOKEN =
|
||||
const RECEIPT_TOKEN =
|
||||
/^[A-Za-z0-9][A-Za-z0-9._~:+/=-]{0,511}$/u;
|
||||
export const MEDIA_TYPE =
|
||||
/^[a-z0-9!#$&^_.+-]{1,63}\/[a-z0-9!#$&^_.+-]{1,63}$/u;
|
||||
@@ -67,7 +71,7 @@ export function isUploadFileFingerprint(
|
||||
);
|
||||
}
|
||||
|
||||
export function isUploadPartDescriptor(
|
||||
function isUploadPartDescriptor(
|
||||
value: unknown,
|
||||
): value is UploadPartDescriptor {
|
||||
if (!exactRecord(value, PART_KEYS)) return false;
|
||||
@@ -138,7 +142,7 @@ export function isResumableUploadCheckpoint(
|
||||
return true;
|
||||
}
|
||||
|
||||
export function partMatchesFingerprint(
|
||||
function partMatchesFingerprint(
|
||||
part: UploadPartDescriptor,
|
||||
fingerprint: UploadFileFingerprint,
|
||||
): boolean {
|
||||
@@ -168,7 +172,7 @@ export function samePart(
|
||||
);
|
||||
}
|
||||
|
||||
function exactRecord<const Keys extends readonly string[]>(
|
||||
export function exactRecord<const Keys extends readonly string[]>(
|
||||
value: unknown,
|
||||
keys: Keys,
|
||||
): value is Record<Keys[number], unknown> {
|
||||
@@ -183,10 +187,17 @@ function exactRecord<const Keys extends readonly string[]>(
|
||||
);
|
||||
}
|
||||
|
||||
function positiveSafeInteger(value: unknown): value is number {
|
||||
return Number.isSafeInteger(value) && (value as number) > 0;
|
||||
}
|
||||
|
||||
function nonNegativeSafeInteger(value: unknown): value is number {
|
||||
return Number.isSafeInteger(value) && (value as number) >= 0;
|
||||
/**
|
||||
* BT-UP-01. The structural guard must cover every method cleanup will call.
|
||||
* Admitting a signal without `removeEventListener` turned a `finally` into a
|
||||
* Promise rejection instead of the typed terminal result.
|
||||
*/
|
||||
export function isAbortSignal(value: unknown): value is AbortSignal {
|
||||
return Boolean(
|
||||
value &&
|
||||
typeof value === "object" &&
|
||||
typeof (value as AbortSignal).aborted === "boolean" &&
|
||||
typeof (value as AbortSignal).addEventListener === "function" &&
|
||||
typeof (value as AbortSignal).removeEventListener === "function",
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,23 +2,26 @@ import type {
|
||||
UploadProviderFailure,
|
||||
UploadProviderResult,
|
||||
} from "../../../application/ports/browser-transfer/resumable-upload.ts";
|
||||
import type {
|
||||
BrowserDataFailureCode,
|
||||
BrowserDataRecovery,
|
||||
import {
|
||||
hasControlCharacter,
|
||||
type BrowserDataFailureCode,
|
||||
type BrowserDataRecovery,
|
||||
} from "../../../application/ports/browser-file-storage/shared.ts";
|
||||
import {
|
||||
browserDataFailure,
|
||||
browserDataSuccess,
|
||||
} from "../../browser-file-storage/result.ts";
|
||||
import {
|
||||
cancelBody,
|
||||
cancelReader,
|
||||
createAbortableOperation,
|
||||
type AbortRace,
|
||||
type AbortTerminalReason,
|
||||
type AbortableOperation,
|
||||
} from "../../platform/abortable-operation.ts";
|
||||
import type {
|
||||
ResumableUploadControlOperation,
|
||||
ResumableUploadJsonTransport,
|
||||
} from "./http-control-plane-adapter.ts";
|
||||
import { isAbortSignal } from "./checkpoint-schema.ts";
|
||||
|
||||
export type ResumableUploadEndpointMap = Readonly<
|
||||
Record<ResumableUploadControlOperation, string>
|
||||
@@ -182,14 +185,17 @@ export function createResumableUploadFetchJsonTransport(
|
||||
"NONE",
|
||||
);
|
||||
}
|
||||
const attempt = createFetchAttempt(
|
||||
// X-AUDIT-02 / TR-RR-05. The attempt is the shared abort primitive:
|
||||
// the listener and the timer are installed together, so a throwing
|
||||
// scheduler closes the attempt instead of rejecting `execute()`.
|
||||
const attempt = createAbortableOperation({
|
||||
signal,
|
||||
timeoutMs,
|
||||
setTimer,
|
||||
clearTimer,
|
||||
);
|
||||
});
|
||||
try {
|
||||
if (attempt.terminalKind() !== null) {
|
||||
if (attempt.terminal() !== null) {
|
||||
// The attempt was closed before it could be bounded, so no request is
|
||||
// ever put on the wire.
|
||||
return attemptFailure(attempt, operation);
|
||||
@@ -210,7 +216,7 @@ export function createResumableUploadFetchJsonTransport(
|
||||
const raced = await attempt.race(
|
||||
Promise.resolve(fetchPromise),
|
||||
(late) => {
|
||||
cancelResponseBody(late);
|
||||
cancelBody(late);
|
||||
},
|
||||
);
|
||||
if (raced.kind !== "VALUE") {
|
||||
@@ -222,7 +228,7 @@ export function createResumableUploadFetchJsonTransport(
|
||||
response.type === "opaqueredirect" ||
|
||||
!sameUrl(response.url, endpoint)
|
||||
) {
|
||||
cancelResponseBody(response);
|
||||
cancelBody(response);
|
||||
return failure(
|
||||
"POLICY_REJECTED",
|
||||
operation,
|
||||
@@ -237,11 +243,11 @@ export function createResumableUploadFetchJsonTransport(
|
||||
maxRetryAfterMs,
|
||||
safeNowEpochMs(),
|
||||
);
|
||||
cancelResponseBody(response);
|
||||
cancelBody(response);
|
||||
return failed;
|
||||
}
|
||||
if (!jsonContentType(response.headers.get("content-type"))) {
|
||||
cancelResponseBody(response);
|
||||
cancelBody(response);
|
||||
return failure(
|
||||
"CORRUPT_DATA",
|
||||
operation,
|
||||
@@ -261,7 +267,9 @@ export function createResumableUploadFetchJsonTransport(
|
||||
} catch {
|
||||
return attemptFailure(attempt, operation);
|
||||
} finally {
|
||||
attempt.release();
|
||||
// BT-UP-01. Cleanup is best effort and never replaces the classified
|
||||
// terminal result with a rejection.
|
||||
attempt.close();
|
||||
}
|
||||
},
|
||||
};
|
||||
@@ -341,7 +349,7 @@ function snapshotHeaders(
|
||||
seen.has(name) ||
|
||||
typeof header.value !== "string" ||
|
||||
header.value.length > 2048 ||
|
||||
hasForbiddenHeaderValueCharacter(header.value)
|
||||
hasControlCharacter(header.value)
|
||||
) {
|
||||
throw new TypeError("Upload request header is invalid.");
|
||||
}
|
||||
@@ -405,7 +413,7 @@ async function readBoundedJson(
|
||||
response: Response,
|
||||
maxBytes: number,
|
||||
operation: ResumableUploadControlOperation,
|
||||
attempt: FetchAttempt,
|
||||
attempt: AbortableOperation,
|
||||
): Promise<UploadProviderResult<unknown>> {
|
||||
const contentLength = response.headers.get("content-length");
|
||||
let declaredLength: number | null = null;
|
||||
@@ -414,7 +422,7 @@ async function readBoundedJson(
|
||||
(!/^(0|[1-9][0-9]*)$/u.test(contentLength) ||
|
||||
Number(contentLength) > maxBytes)
|
||||
) {
|
||||
cancelResponseBody(response);
|
||||
cancelBody(response);
|
||||
return failure(
|
||||
"LIMIT_EXCEEDED",
|
||||
operation,
|
||||
@@ -574,89 +582,15 @@ function failure(
|
||||
return Object.freeze({ ok: false, error });
|
||||
}
|
||||
|
||||
type FetchAttemptTerminalKind = "ABORT" | "TIMEOUT" | "CLOSED";
|
||||
|
||||
type FetchAttempt = Readonly<{
|
||||
signal: AbortSignal;
|
||||
terminalKind(): FetchAttemptTerminalKind | null;
|
||||
race<Value>(
|
||||
task: Promise<Value>,
|
||||
compensate?: (value: Value) => void,
|
||||
): Promise<AbortRace<Value>>;
|
||||
release(): void;
|
||||
}>;
|
||||
|
||||
/**
|
||||
* X-AUDIT-02 / TR-RR-05. The attempt is the shared abort primitive with this
|
||||
* subsystem's vocabulary on top. Owning a private copy meant the listener was
|
||||
* attached before the timer was installed, so a scheduler that threw rejected
|
||||
* the public `execute()` promise and left the listener on the caller's signal.
|
||||
*/
|
||||
function createFetchAttempt(
|
||||
parent: AbortSignal,
|
||||
timeoutMs: number,
|
||||
setTimer: (callback: () => void, delayMs: number) => unknown,
|
||||
clearTimer: (handle: unknown) => void,
|
||||
): FetchAttempt {
|
||||
const operation = createAbortableOperation({
|
||||
signal: parent,
|
||||
timeoutMs,
|
||||
setTimer,
|
||||
clearTimer,
|
||||
});
|
||||
const kindOf = (
|
||||
reason: AbortTerminalReason | null,
|
||||
): FetchAttemptTerminalKind | null => {
|
||||
if (reason === null) return null;
|
||||
if (reason === "CALLER_ABORT") return "ABORT";
|
||||
return reason === "DEADLINE" ? "TIMEOUT" : "CLOSED";
|
||||
};
|
||||
return Object.freeze({
|
||||
signal: operation.signal,
|
||||
terminalKind: () => kindOf(operation.terminal()),
|
||||
race: <Value,>(
|
||||
task: Promise<Value>,
|
||||
compensate?: (value: Value) => void,
|
||||
) => operation.race(task, compensate),
|
||||
release() {
|
||||
// BT-UP-01. Cleanup is best effort and must never replace the already
|
||||
// classified terminal result with a rejection.
|
||||
operation.close();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function attemptFailure(
|
||||
attempt: FetchAttempt,
|
||||
attempt: AbortableOperation,
|
||||
operation: ResumableUploadControlOperation,
|
||||
): UploadProviderResult<never> {
|
||||
return attempt.terminalKind() === "ABORT"
|
||||
return attempt.terminal() === "CALLER_ABORT"
|
||||
? failure("ABORTED", operation, false, "NONE")
|
||||
: failure("UNAVAILABLE", operation, true, "RESUME");
|
||||
}
|
||||
|
||||
function cancelResponseBody(response: Response): void {
|
||||
try {
|
||||
void response.body?.cancel().catch(() => {
|
||||
// Response cancellation is best effort after closed classification.
|
||||
});
|
||||
} catch {
|
||||
// A cancellation failure cannot change the already classified result.
|
||||
}
|
||||
}
|
||||
|
||||
function cancelReader(
|
||||
reader: ReadableStreamDefaultReader<Uint8Array>,
|
||||
): void {
|
||||
try {
|
||||
void reader.cancel().catch(() => {
|
||||
// Reader cancellation is best effort after closed classification.
|
||||
});
|
||||
} catch {
|
||||
// A cancellation failure cannot change the already classified result.
|
||||
}
|
||||
}
|
||||
|
||||
function releaseReader(
|
||||
reader: ReadableStreamDefaultReader<Uint8Array>,
|
||||
): void {
|
||||
@@ -721,21 +655,6 @@ function boundedPositiveInteger(
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* BT-UP-01. The structural guard must cover every method cleanup will call.
|
||||
* Admitting a signal without `removeEventListener` turned a `finally` into a
|
||||
* Promise rejection instead of the typed terminal result.
|
||||
*/
|
||||
function isAbortSignal(value: unknown): value is AbortSignal {
|
||||
return Boolean(
|
||||
value &&
|
||||
typeof value === "object" &&
|
||||
typeof (value as AbortSignal).aborted === "boolean" &&
|
||||
typeof (value as AbortSignal).addEventListener === "function" &&
|
||||
typeof (value as AbortSignal).removeEventListener === "function",
|
||||
);
|
||||
}
|
||||
|
||||
function isControlOperation(
|
||||
value: unknown,
|
||||
): value is ResumableUploadControlOperation {
|
||||
@@ -766,13 +685,6 @@ function snapshotTransportRequest(
|
||||
}
|
||||
}
|
||||
|
||||
function hasForbiddenHeaderValueCharacter(value: string): boolean {
|
||||
return [...value].some((character) => {
|
||||
const codePoint = character.codePointAt(0);
|
||||
return codePoint !== undefined && (codePoint <= 31 || codePoint === 127);
|
||||
});
|
||||
}
|
||||
|
||||
function isPlainRecord(
|
||||
value: unknown,
|
||||
): value is Readonly<Record<string, unknown>> {
|
||||
|
||||
@@ -30,6 +30,10 @@ import {
|
||||
SAFE_UPLOAD_KEY,
|
||||
SHA256_HEX,
|
||||
} from "./checkpoint-schema.ts";
|
||||
import {
|
||||
isPositiveSafeInteger as positiveSafeInteger,
|
||||
isNonNegativeSafeInteger as nonNegativeSafeInteger,
|
||||
} from "../../../application/ports/browser-file-storage/shared.ts";
|
||||
|
||||
export type ResumableUploadControlOperation =
|
||||
| "CREATE_SESSION"
|
||||
@@ -679,11 +683,3 @@ function safeIdempotencyKey(value: string): boolean {
|
||||
/^[A-Za-z0-9._~-]+$/u.test(value)
|
||||
);
|
||||
}
|
||||
|
||||
function positiveSafeInteger(value: unknown): value is number {
|
||||
return Number.isSafeInteger(value) && (value as number) > 0;
|
||||
}
|
||||
|
||||
function nonNegativeSafeInteger(value: unknown): value is number {
|
||||
return Number.isSafeInteger(value) && (value as number) >= 0;
|
||||
}
|
||||
|
||||
@@ -285,6 +285,35 @@ export function createIndexedDbResumableUploadCheckpointRuntime(
|
||||
}),
|
||||
});
|
||||
|
||||
/**
|
||||
* Every store operation reads the row it guards inside the same transaction
|
||||
* it may then write in, so the guard and the write cannot interleave with
|
||||
* another context.
|
||||
*/
|
||||
async function withCheckpointRow<Value>(
|
||||
uploadKey: string,
|
||||
mode: "readonly" | "readwrite",
|
||||
signal: AbortSignal | undefined,
|
||||
onRow: (
|
||||
row: unknown,
|
||||
store: IDBObjectStore,
|
||||
context: CheckpointTransactionContext<Value>,
|
||||
) => void,
|
||||
): Promise<BrowserDataResult<Value>> {
|
||||
const opened = await connection.acquire(signal);
|
||||
if (!opened.ok) return opened;
|
||||
return await runCheckpointTransaction<Value>(
|
||||
opened.value,
|
||||
mode,
|
||||
signal,
|
||||
(nativeStore, context) => {
|
||||
const request = nativeStore.get(uploadKey);
|
||||
request.onerror = () => context.fail(mappedFailure(request.error));
|
||||
request.onsuccess = () => onRow(request.result, nativeStore, context);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const storeValue: ResumableUploadCheckpointStore = {
|
||||
async read(
|
||||
uploadKey: string,
|
||||
@@ -295,32 +324,22 @@ export function createIndexedDbResumableUploadCheckpointRuntime(
|
||||
if (!SAFE_UPLOAD_KEY.test(uploadKey)) {
|
||||
return browserDataFailure("INVALID_INPUT", OPERATION);
|
||||
}
|
||||
const opened = await connection.acquire(signal);
|
||||
if (!opened.ok) return opened;
|
||||
return await runCheckpointTransaction<
|
||||
ResumableUploadCheckpoint | null
|
||||
>(
|
||||
opened.value,
|
||||
return await withCheckpointRow<ResumableUploadCheckpoint | null>(
|
||||
uploadKey,
|
||||
"readonly",
|
||||
signal,
|
||||
(nativeStore, context) => {
|
||||
const request = nativeStore.get(uploadKey);
|
||||
request.onerror = () => context.fail(mappedFailure(request.error));
|
||||
request.onsuccess = () => {
|
||||
if (request.result === undefined) {
|
||||
context.succeed(null);
|
||||
return;
|
||||
}
|
||||
if (!isResumableUploadCheckpoint(request.result)) {
|
||||
context.fail(
|
||||
checkpointFailure("CORRUPT_DATA", { recovery: "RECONCILE" }),
|
||||
);
|
||||
return;
|
||||
}
|
||||
context.succeed(
|
||||
snapshotCheckpoint(request.result),
|
||||
(row, _nativeStore, context) => {
|
||||
if (row === undefined) {
|
||||
context.succeed(null);
|
||||
return;
|
||||
}
|
||||
if (!isResumableUploadCheckpoint(row)) {
|
||||
context.fail(
|
||||
checkpointFailure("CORRUPT_DATA", { recovery: "RECONCILE" }),
|
||||
);
|
||||
};
|
||||
return;
|
||||
}
|
||||
context.succeed(snapshotCheckpoint(row));
|
||||
},
|
||||
);
|
||||
},
|
||||
@@ -345,32 +364,25 @@ export function createIndexedDbResumableUploadCheckpointRuntime(
|
||||
) {
|
||||
return browserDataFailure("INVALID_INPUT", OPERATION);
|
||||
}
|
||||
const opened = await connection.acquire(inputValue.signal);
|
||||
if (!opened.ok) return opened;
|
||||
return await runCheckpointTransaction<ResumableUploadCheckpoint>(
|
||||
opened.value,
|
||||
return await withCheckpointRow<ResumableUploadCheckpoint>(
|
||||
checkpoint.uploadKey,
|
||||
"readwrite",
|
||||
inputValue.signal,
|
||||
(nativeStore, context) => {
|
||||
const request = nativeStore.get(checkpoint.uploadKey);
|
||||
request.onerror = () => context.fail(mappedFailure(request.error));
|
||||
request.onsuccess = () => {
|
||||
const current = request.result;
|
||||
if (
|
||||
(expectedRevision === null && current !== undefined) ||
|
||||
(expectedRevision !== null &&
|
||||
(!isResumableUploadCheckpoint(current) ||
|
||||
current.revision !== expectedRevision))
|
||||
) {
|
||||
context.fail(
|
||||
checkpointFailure("CONFLICT", { recovery: "RECONCILE" }),
|
||||
);
|
||||
return;
|
||||
}
|
||||
const put = nativeStore.put(checkpoint);
|
||||
put.onerror = () => context.fail(mappedFailure(put.error));
|
||||
put.onsuccess = () => context.succeed(checkpoint);
|
||||
};
|
||||
(current, nativeStore, context) => {
|
||||
if (
|
||||
(expectedRevision === null && current !== undefined) ||
|
||||
(expectedRevision !== null &&
|
||||
(!isResumableUploadCheckpoint(current) ||
|
||||
current.revision !== expectedRevision))
|
||||
) {
|
||||
context.fail(
|
||||
checkpointFailure("CONFLICT", { recovery: "RECONCILE" }),
|
||||
);
|
||||
return;
|
||||
}
|
||||
const put = nativeStore.put(checkpoint);
|
||||
put.onerror = () => context.fail(mappedFailure(put.error));
|
||||
put.onsuccess = () => context.succeed(checkpoint);
|
||||
},
|
||||
);
|
||||
},
|
||||
@@ -387,30 +399,51 @@ export function createIndexedDbResumableUploadCheckpointRuntime(
|
||||
) {
|
||||
return browserDataFailure("INVALID_INPUT", OPERATION);
|
||||
}
|
||||
const opened = await connection.acquire(inputValue.signal);
|
||||
if (!opened.ok) return opened;
|
||||
return await runCheckpointTransaction<void>(
|
||||
opened.value,
|
||||
return await withCheckpointRow<void>(
|
||||
inputValue.uploadKey,
|
||||
"readwrite",
|
||||
inputValue.signal,
|
||||
(nativeStore, context) => {
|
||||
const request = nativeStore.get(inputValue.uploadKey);
|
||||
request.onerror = () => context.fail(mappedFailure(request.error));
|
||||
request.onsuccess = () => {
|
||||
if (
|
||||
!isResumableUploadCheckpoint(request.result) ||
|
||||
request.result.revision !== inputValue.expectedRevision
|
||||
) {
|
||||
context.fail(
|
||||
checkpointFailure("CONFLICT", { recovery: "RECONCILE" }),
|
||||
);
|
||||
return;
|
||||
}
|
||||
const deletion = nativeStore.delete(inputValue.uploadKey);
|
||||
deletion.onerror = () =>
|
||||
context.fail(mappedFailure(deletion.error));
|
||||
deletion.onsuccess = () => context.succeed(undefined);
|
||||
};
|
||||
(row, nativeStore, context) => {
|
||||
if (
|
||||
!isResumableUploadCheckpoint(row) ||
|
||||
row.revision !== inputValue.expectedRevision
|
||||
) {
|
||||
context.fail(
|
||||
checkpointFailure("CONFLICT", { recovery: "RECONCILE" }),
|
||||
);
|
||||
return;
|
||||
}
|
||||
deleteCheckpointRow(nativeStore, inputValue.uploadKey, context);
|
||||
},
|
||||
);
|
||||
},
|
||||
|
||||
async removeUnreadable(
|
||||
inputValue: Parameters<
|
||||
NonNullable<ResumableUploadCheckpointStore["removeUnreadable"]>
|
||||
>[0],
|
||||
): Promise<BrowserDataResult<void>> {
|
||||
if (!SAFE_UPLOAD_KEY.test(inputValue.uploadKey)) {
|
||||
return browserDataFailure("INVALID_INPUT", OPERATION);
|
||||
}
|
||||
return await withCheckpointRow<void>(
|
||||
inputValue.uploadKey,
|
||||
"readwrite",
|
||||
inputValue.signal,
|
||||
(row, nativeStore, context) => {
|
||||
// Checked in the same transaction as the delete, so a row another
|
||||
// context rewrote as a valid checkpoint is never dropped.
|
||||
if (row === undefined) {
|
||||
context.succeed(undefined);
|
||||
return;
|
||||
}
|
||||
if (isResumableUploadCheckpoint(row)) {
|
||||
context.fail(
|
||||
checkpointFailure("CONFLICT", { recovery: "RECONCILE" }),
|
||||
);
|
||||
return;
|
||||
}
|
||||
deleteCheckpointRow(nativeStore, inputValue.uploadKey, context);
|
||||
},
|
||||
);
|
||||
},
|
||||
@@ -477,6 +510,21 @@ export function createIndexedDbResumableUploadCheckpointRuntime(
|
||||
return Object.freeze({ store, admin });
|
||||
}
|
||||
|
||||
type CheckpointTransactionContext<Value> = Readonly<{
|
||||
succeed(value: Value): void;
|
||||
fail(failure: BrowserDataFailure): void;
|
||||
}>;
|
||||
|
||||
function deleteCheckpointRow(
|
||||
store: IDBObjectStore,
|
||||
uploadKey: string,
|
||||
context: CheckpointTransactionContext<void>,
|
||||
): void {
|
||||
const deletion = store.delete(uploadKey);
|
||||
deletion.onerror = () => context.fail(mappedFailure(deletion.error));
|
||||
deletion.onsuccess = () => context.succeed(undefined);
|
||||
}
|
||||
|
||||
/**
|
||||
* `durability` is deliberately `undefined` rather than `"default"`: that opens
|
||||
* the transaction with no options bag at all, which is what checkpoint writes
|
||||
@@ -494,10 +542,7 @@ async function runCheckpointTransaction<Value>(
|
||||
signal: AbortSignal | undefined,
|
||||
execute: (
|
||||
store: IDBObjectStore,
|
||||
context: Readonly<{
|
||||
succeed(value: Value): void;
|
||||
fail(failure: BrowserDataFailure): void;
|
||||
}>,
|
||||
context: CheckpointTransactionContext<Value>,
|
||||
) => void,
|
||||
): Promise<BrowserDataResult<Value>> {
|
||||
return await runIndexedDbTransaction<Value, BrowserDataFailure>({
|
||||
|
||||
@@ -91,7 +91,9 @@ export function createPresignedUploadPartExecutor(
|
||||
byteLength: input.part.byteLength,
|
||||
checksumSha256: input.part.checksumSha256,
|
||||
idempotencyKey: input.idempotencyKey,
|
||||
bytes: Uint8Array.from(input.bytes),
|
||||
// Q-6.1-3b. The presigned port snapshots `bytes` before any await,
|
||||
// so a second copy here only doubled the per-part buffer.
|
||||
bytes: input.bytes,
|
||||
signal: input.signal,
|
||||
});
|
||||
} catch {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,378 @@
|
||||
import type {
|
||||
ResumableUploadCheckpointStore,
|
||||
ResumableUploadControlPlane,
|
||||
UploadPartExecutor,
|
||||
} from "../../../application/ports/browser-transfer/resumable-upload.ts";
|
||||
import type {
|
||||
BrowserDataObserver,
|
||||
BrowserDataOperation,
|
||||
BrowserDataResult,
|
||||
} from "../../../application/ports/browser-file-storage/shared.ts";
|
||||
import {
|
||||
browserDataFailure,
|
||||
browserDataSuccess,
|
||||
} from "../../browser-file-storage/result.ts";
|
||||
import { createAbortableOperation } from "../../platform/abortable-operation.ts";
|
||||
import { snapshotUploadCrypto, type UploadCrypto } from "./upload-byte-source.ts";
|
||||
import {
|
||||
resolveResumableUploadRuntimePolicy,
|
||||
type ResumableUploadRuntimePolicy,
|
||||
} from "./runtime-policy.ts";
|
||||
import type { UploadCancellationChannel } from "./upload-cancellation-channel.ts";
|
||||
import type { UploadMutationLock } from "./upload-mutation-lock.ts";
|
||||
|
||||
/**
|
||||
* Q-6.1-10. The resumable upload runtime's injected collaborators. Each one is
|
||||
* validated and its methods captured once at composition, so replacing a
|
||||
* method afterwards cannot change what an upload in flight calls.
|
||||
*/
|
||||
|
||||
export type ResumableUploadRuntimeDependencies<Capability> = Readonly<{
|
||||
controlPlane: ResumableUploadControlPlane<Capability>;
|
||||
partExecutor: UploadPartExecutor<Capability>;
|
||||
checkpoints: ResumableUploadCheckpointStore;
|
||||
mutationLock: UploadMutationLock;
|
||||
/**
|
||||
* Runtime-owned ephemeral BroadcastChannel coordination. When omitted,
|
||||
* explicit abort is still correct but may wait for another context's lock.
|
||||
*/
|
||||
crossContextCancellation?: UploadCancellationChannel;
|
||||
crypto: Crypto;
|
||||
policy?: Partial<ResumableUploadRuntimePolicy>;
|
||||
now?: () => number;
|
||||
random?: () => number;
|
||||
sleep?: (delayMs: number, signal: AbortSignal) => Promise<void>;
|
||||
observer?: BrowserDataObserver;
|
||||
}>;
|
||||
|
||||
export type RuntimeDependencies<Capability> = Readonly<{
|
||||
controlPlane: ResumableUploadControlPlane<Capability>;
|
||||
partExecutor: UploadPartExecutor<Capability>;
|
||||
checkpoints: ResumableUploadCheckpointStore;
|
||||
mutationLock: UploadMutationLock;
|
||||
crossContextCancellation?: UploadCancellationChannel;
|
||||
crypto: UploadCrypto;
|
||||
policy: ResumableUploadRuntimePolicy;
|
||||
now(): number;
|
||||
random(): number;
|
||||
sleep(delayMs: number, signal: AbortSignal): Promise<void>;
|
||||
observer?: BrowserDataObserver;
|
||||
/**
|
||||
* TR-04. Every raw provider promise, from the moment the collaborator is
|
||||
* called until it actually settles. The wrapper that bounds the attempt can
|
||||
* settle long before the provider does, so the wrapper registry alone could
|
||||
* report an empty set while physical work was still running.
|
||||
*/
|
||||
physicalTasks: Set<Promise<unknown>>;
|
||||
}>;
|
||||
|
||||
export function snapshotDependencies<Capability>(
|
||||
input: ResumableUploadRuntimeDependencies<Capability>,
|
||||
physicalTasks: Set<Promise<unknown>>,
|
||||
): RuntimeDependencies<Capability> {
|
||||
const policy = resolveResumableUploadRuntimePolicy(input.policy);
|
||||
const controlPlane = snapshotControlPlane(input.controlPlane);
|
||||
const partExecutor = snapshotPartExecutor(input.partExecutor);
|
||||
const checkpoints = snapshotCheckpointStore(input.checkpoints);
|
||||
const mutationLock = snapshotMutationLock(input.mutationLock);
|
||||
const crossContextCancellation = snapshotCancellationChannel(
|
||||
input.crossContextCancellation,
|
||||
);
|
||||
const crypto = snapshotUploadCrypto(input.crypto);
|
||||
const nowSource = input.now ?? Date.now;
|
||||
const randomSource = input.random ?? Math.random;
|
||||
const sleepSource = input.sleep ?? abortableSleep;
|
||||
const observer = snapshotObserver(input.observer);
|
||||
if (
|
||||
typeof nowSource !== "function" ||
|
||||
typeof randomSource !== "function" ||
|
||||
typeof sleepSource !== "function"
|
||||
) {
|
||||
throw new TypeError("Upload runtime dependency is invalid.");
|
||||
}
|
||||
return Object.freeze({
|
||||
physicalTasks,
|
||||
controlPlane,
|
||||
partExecutor,
|
||||
checkpoints,
|
||||
mutationLock,
|
||||
...(crossContextCancellation
|
||||
? { crossContextCancellation }
|
||||
: {}),
|
||||
crypto,
|
||||
policy,
|
||||
now: () => nowSource(),
|
||||
random: () => randomSource(),
|
||||
sleep: async (delayMs, signal) =>
|
||||
await sleepSource(delayMs, signal),
|
||||
...(observer ? { observer } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
function snapshotCancellationChannel(
|
||||
value: UploadCancellationChannel | undefined,
|
||||
): UploadCancellationChannel | undefined {
|
||||
if (!value) return undefined;
|
||||
const publish = value.publish;
|
||||
const subscribe = value.subscribe;
|
||||
const close = value.close;
|
||||
if (
|
||||
typeof publish !== "function" ||
|
||||
typeof subscribe !== "function" ||
|
||||
typeof close !== "function"
|
||||
) {
|
||||
throw new TypeError(
|
||||
"Upload cancellation channel is invalid.",
|
||||
);
|
||||
}
|
||||
return Object.freeze({
|
||||
publish(uploadKey: string): boolean {
|
||||
try {
|
||||
return publish.call(value, uploadKey) === true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
subscribe(
|
||||
listener: (uploadKey: string) => void,
|
||||
): () => void {
|
||||
const release = subscribe.call(value, listener);
|
||||
if (typeof release !== "function") {
|
||||
throw new TypeError(
|
||||
"Upload cancellation subscription is invalid.",
|
||||
);
|
||||
}
|
||||
let active = true;
|
||||
return () => {
|
||||
if (!active) return;
|
||||
active = false;
|
||||
try {
|
||||
release();
|
||||
} catch {
|
||||
// Runtime close remains terminal.
|
||||
}
|
||||
};
|
||||
},
|
||||
close(): void {
|
||||
try {
|
||||
close.call(value);
|
||||
} catch {
|
||||
// Runtime close remains terminal.
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function snapshotObserver(
|
||||
value: BrowserDataObserver | undefined,
|
||||
): BrowserDataObserver | undefined {
|
||||
if (!value) return undefined;
|
||||
const record = value.record;
|
||||
if (typeof record !== "function") {
|
||||
throw new TypeError("Upload observer is invalid.");
|
||||
}
|
||||
return Object.freeze({
|
||||
record(
|
||||
observation: Parameters<BrowserDataObserver["record"]>[0],
|
||||
) {
|
||||
record.call(value, Object.freeze({ ...observation }));
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function snapshotControlPlane<Capability>(
|
||||
value: ResumableUploadControlPlane<Capability>,
|
||||
): ResumableUploadControlPlane<Capability> {
|
||||
const createSession = value?.createSession;
|
||||
const getStatus = value?.getStatus;
|
||||
const issuePartCapability = value?.issuePartCapability;
|
||||
const complete = value?.complete;
|
||||
const abort = value?.abort;
|
||||
if (
|
||||
typeof createSession !== "function" ||
|
||||
typeof getStatus !== "function" ||
|
||||
typeof issuePartCapability !== "function" ||
|
||||
typeof complete !== "function" ||
|
||||
typeof abort !== "function"
|
||||
) {
|
||||
throw new TypeError("Upload control plane is invalid.");
|
||||
}
|
||||
const snapshot: ResumableUploadControlPlane<Capability> = {
|
||||
async createSession(
|
||||
input: Parameters<
|
||||
ResumableUploadControlPlane<Capability>["createSession"]
|
||||
>[0],
|
||||
) {
|
||||
return await createSession.call(value, input);
|
||||
},
|
||||
async getStatus(
|
||||
input: Parameters<
|
||||
ResumableUploadControlPlane<Capability>["getStatus"]
|
||||
>[0],
|
||||
) {
|
||||
return await getStatus.call(value, input);
|
||||
},
|
||||
async issuePartCapability(
|
||||
input: Parameters<
|
||||
ResumableUploadControlPlane<Capability>["issuePartCapability"]
|
||||
>[0],
|
||||
) {
|
||||
return await issuePartCapability.call(value, input);
|
||||
},
|
||||
async complete(
|
||||
input: Parameters<
|
||||
ResumableUploadControlPlane<Capability>["complete"]
|
||||
>[0],
|
||||
) {
|
||||
return await complete.call(value, input);
|
||||
},
|
||||
async abort(
|
||||
input: Parameters<
|
||||
ResumableUploadControlPlane<Capability>["abort"]
|
||||
>[0],
|
||||
) {
|
||||
return await abort.call(value, input);
|
||||
},
|
||||
};
|
||||
return Object.freeze(snapshot);
|
||||
}
|
||||
|
||||
function snapshotPartExecutor<Capability>(
|
||||
value: UploadPartExecutor<Capability>,
|
||||
): UploadPartExecutor<Capability> {
|
||||
const uploadPart = value?.uploadPart;
|
||||
if (typeof uploadPart !== "function") {
|
||||
throw new TypeError("Upload part executor is invalid.");
|
||||
}
|
||||
const snapshot: UploadPartExecutor<Capability> = {
|
||||
async uploadPart(
|
||||
input: Parameters<UploadPartExecutor<Capability>["uploadPart"]>[0],
|
||||
) {
|
||||
return await uploadPart.call(value, input);
|
||||
},
|
||||
};
|
||||
return Object.freeze(snapshot);
|
||||
}
|
||||
|
||||
function snapshotCheckpointStore(
|
||||
value: ResumableUploadCheckpointStore,
|
||||
): ResumableUploadCheckpointStore {
|
||||
const read = value?.read;
|
||||
const compareAndSwap = value?.compareAndSwap;
|
||||
const remove = value?.remove;
|
||||
const removeUnreadable = value?.removeUnreadable;
|
||||
const close = value?.close;
|
||||
if (
|
||||
typeof read !== "function" ||
|
||||
typeof compareAndSwap !== "function" ||
|
||||
typeof remove !== "function" ||
|
||||
(removeUnreadable !== undefined &&
|
||||
typeof removeUnreadable !== "function") ||
|
||||
typeof close !== "function"
|
||||
) {
|
||||
throw new TypeError("Upload checkpoint store is invalid.");
|
||||
}
|
||||
const snapshot: ResumableUploadCheckpointStore = {
|
||||
async read(
|
||||
uploadKey: string,
|
||||
signal?: AbortSignal,
|
||||
) {
|
||||
return await read.call(value, uploadKey, signal);
|
||||
},
|
||||
async compareAndSwap(
|
||||
input: Parameters<
|
||||
ResumableUploadCheckpointStore["compareAndSwap"]
|
||||
>[0],
|
||||
) {
|
||||
return await compareAndSwap.call(value, input);
|
||||
},
|
||||
async remove(
|
||||
input: Parameters<ResumableUploadCheckpointStore["remove"]>[0],
|
||||
) {
|
||||
return await remove.call(value, input);
|
||||
},
|
||||
...(removeUnreadable
|
||||
? {
|
||||
async removeUnreadable(
|
||||
input: Parameters<typeof removeUnreadable>[0],
|
||||
) {
|
||||
return await removeUnreadable.call(value, input);
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
close() {
|
||||
close.call(value);
|
||||
},
|
||||
};
|
||||
return Object.freeze(snapshot);
|
||||
}
|
||||
|
||||
function snapshotMutationLock(value: UploadMutationLock): UploadMutationLock {
|
||||
const run = value?.run;
|
||||
if (typeof run !== "function") {
|
||||
throw new TypeError("Upload mutation lock is invalid.");
|
||||
}
|
||||
return Object.freeze({
|
||||
async run<Value>(
|
||||
uploadKey: string,
|
||||
signal: AbortSignal,
|
||||
task: () => Promise<Value>,
|
||||
): Promise<Value> {
|
||||
return await (run.call(
|
||||
value,
|
||||
uploadKey,
|
||||
signal,
|
||||
task,
|
||||
) as Promise<Value>);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function safeNow<Capability>(
|
||||
dependencies: RuntimeDependencies<Capability>,
|
||||
operation: BrowserDataOperation,
|
||||
): BrowserDataResult<number> {
|
||||
try {
|
||||
const value = dependencies.now();
|
||||
return Number.isSafeInteger(value) && value >= 0
|
||||
? browserDataSuccess(value)
|
||||
: browserDataFailure("UNAVAILABLE", operation, {
|
||||
recovery: "RESUME",
|
||||
});
|
||||
} catch {
|
||||
return browserDataFailure("UNAVAILABLE", operation, {
|
||||
recovery: "RESUME",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export function safeRandom<Capability>(
|
||||
dependencies: RuntimeDependencies<Capability>,
|
||||
): BrowserDataResult<number> {
|
||||
try {
|
||||
const value = dependencies.random();
|
||||
return Number.isFinite(value) && value >= 0 && value <= 1
|
||||
? browserDataSuccess(value)
|
||||
: browserDataFailure("UNAVAILABLE", "UPLOAD_RECONCILE", {
|
||||
recovery: "RESUME",
|
||||
});
|
||||
} catch {
|
||||
return browserDataFailure("UNAVAILABLE", "UPLOAD_RECONCILE", {
|
||||
recovery: "RESUME",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function abortableSleep(
|
||||
delayMs: number,
|
||||
signal: AbortSignal,
|
||||
): Promise<void> {
|
||||
// The kernel owns the timer and the abort listener; the sleep only waits
|
||||
// for whichever of the two ends the operation first.
|
||||
const sleep = createAbortableOperation({ signal, timeoutMs: delayMs });
|
||||
const ended = await sleep.race(new Promise<never>(() => {}));
|
||||
sleep.close();
|
||||
if (ended.kind !== "TERMINAL" || ended.terminal !== "DEADLINE") {
|
||||
throw new DOMException("The operation was aborted.", "AbortError");
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,8 @@
|
||||
import {
|
||||
isPositiveSafeInteger as positiveSafeInteger,
|
||||
isNonNegativeSafeInteger as nonNegativeSafeInteger,
|
||||
} from "../../../application/ports/browser-file-storage/shared.ts";
|
||||
|
||||
export type ResumableUploadRuntimePolicy = Readonly<{
|
||||
partSizeBytes: number;
|
||||
maxFileBytes: number;
|
||||
@@ -116,11 +121,3 @@ export function resolveResumableUploadRuntimePolicy(
|
||||
}
|
||||
return policy;
|
||||
}
|
||||
|
||||
function positiveSafeInteger(value: number): boolean {
|
||||
return Number.isSafeInteger(value) && value > 0;
|
||||
}
|
||||
|
||||
function nonNegativeSafeInteger(value: number): boolean {
|
||||
return Number.isSafeInteger(value) && value >= 0;
|
||||
}
|
||||
|
||||
@@ -13,6 +13,9 @@ import {
|
||||
browserDataSuccess,
|
||||
} from "../../browser-file-storage/result.ts";
|
||||
import { samePart } from "./checkpoint-schema.ts";
|
||||
import {
|
||||
isPositiveSafeInteger as positiveSafeInteger,
|
||||
} from "../../../application/ports/browser-file-storage/shared.ts";
|
||||
|
||||
export type UploadCrypto = Readonly<{
|
||||
digestSha256(bytes: Uint8Array): Promise<ArrayBuffer>;
|
||||
@@ -594,7 +597,3 @@ function remapFailure(
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
function positiveSafeInteger(value: unknown): value is number {
|
||||
return Number.isSafeInteger(value) && (value as number) > 0;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,296 @@
|
||||
import type {
|
||||
ActiveUploadStatus,
|
||||
ResumableUploadCheckpoint,
|
||||
UploadFileFingerprint,
|
||||
UploadPartCapability,
|
||||
UploadPartReceipt,
|
||||
UploadSession,
|
||||
UploadSessionStatus,
|
||||
} from "../../../application/ports/browser-transfer/resumable-upload.ts";
|
||||
import { RESUMABLE_UPLOAD_PROTOCOL } from "../../../application/ports/browser-transfer/resumable-upload.ts";
|
||||
import type {
|
||||
BrowserDataOperation,
|
||||
BrowserDataResult,
|
||||
} from "../../../application/ports/browser-file-storage/shared.ts";
|
||||
import {
|
||||
browserDataFailure,
|
||||
browserDataSuccess,
|
||||
} from "../../browser-file-storage/result.ts";
|
||||
import {
|
||||
exactRecord,
|
||||
isUploadFileFingerprint,
|
||||
isUploadPartReceipt,
|
||||
SAFE_OPAQUE_ID,
|
||||
SHA256_HEX,
|
||||
} from "./checkpoint-schema.ts";
|
||||
import { safeNow, type RuntimeDependencies } from "./runtime-dependencies.ts";
|
||||
import {
|
||||
verifyPartAgainstManifest,
|
||||
type UploadPartManifest,
|
||||
} from "./upload-byte-source.ts";
|
||||
|
||||
/**
|
||||
* Q-6.1-10. Strict decoders for what the control plane returns: a session, a
|
||||
* status, a part capability and the accepted receipts. Every failure is closed
|
||||
* with the recovery the runtime reports unchanged.
|
||||
*/
|
||||
|
||||
export function validatePartCapability<Capability>(
|
||||
value: UploadPartCapability<Capability>,
|
||||
checkpoint: ResumableUploadCheckpoint,
|
||||
uploadBindingSha256: string,
|
||||
dependencies: RuntimeDependencies<Capability>,
|
||||
): BrowserDataResult<UploadPartCapability<Capability>> {
|
||||
if (
|
||||
!exactRecord(value, [
|
||||
"capability",
|
||||
"uploadBindingSha256",
|
||||
"expiresAtEpochMs",
|
||||
]) ||
|
||||
value.uploadBindingSha256 !== uploadBindingSha256 ||
|
||||
!SHA256_HEX.test(value.uploadBindingSha256) ||
|
||||
!Number.isSafeInteger(value.expiresAtEpochMs)
|
||||
) {
|
||||
return browserDataFailure("CORRUPT_DATA", "UPLOAD_PART", {
|
||||
recovery: "REISSUE_CAPABILITY",
|
||||
});
|
||||
}
|
||||
const now = safeNow(dependencies, "UPLOAD_PART");
|
||||
if (!now.ok) return now;
|
||||
if (
|
||||
value.expiresAtEpochMs <=
|
||||
now.value + dependencies.policy.capabilityRefreshSkewMs
|
||||
) {
|
||||
return browserDataFailure("EXPIRED_RESOURCE", "UPLOAD_PART", {
|
||||
retryable: true,
|
||||
recovery: "REISSUE_CAPABILITY",
|
||||
});
|
||||
}
|
||||
if (value.expiresAtEpochMs > checkpoint.sessionExpiresAtEpochMs) {
|
||||
return browserDataFailure("POLICY_REJECTED", "UPLOAD_PART", {
|
||||
recovery: "REISSUE_CAPABILITY",
|
||||
});
|
||||
}
|
||||
return browserDataSuccess(value);
|
||||
}
|
||||
|
||||
export function validateStatus<Capability>(
|
||||
value: UploadSessionStatus,
|
||||
checkpoint: ResumableUploadCheckpoint,
|
||||
manifest: UploadPartManifest,
|
||||
dependencies: RuntimeDependencies<Capability>,
|
||||
): BrowserDataResult<UploadSessionStatus> {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
||||
return browserDataFailure("CORRUPT_DATA", "UPLOAD_RECONCILE", {
|
||||
recovery: "RECONCILE",
|
||||
});
|
||||
}
|
||||
if (value.state === "ACTIVE") {
|
||||
if (!exactRecord(value, ["state", "session", "acceptedParts"])) {
|
||||
return browserDataFailure(
|
||||
"CORRUPT_DATA",
|
||||
"UPLOAD_RECONCILE",
|
||||
{ recovery: "RECONCILE" },
|
||||
);
|
||||
}
|
||||
const session = validateSession(
|
||||
value.session,
|
||||
checkpoint.requestBindingSha256,
|
||||
manifest.fingerprint,
|
||||
dependencies,
|
||||
true,
|
||||
);
|
||||
if (
|
||||
!session.ok ||
|
||||
session.value.sessionId !== checkpoint.sessionId ||
|
||||
session.value.maxConcurrency !== checkpoint.sessionMaxConcurrency ||
|
||||
session.value.expiresAtEpochMs !==
|
||||
checkpoint.sessionExpiresAtEpochMs
|
||||
) {
|
||||
return browserDataFailure(
|
||||
"INTEGRITY_FAILED",
|
||||
"UPLOAD_RECONCILE",
|
||||
{ recovery: "RECONCILE" },
|
||||
);
|
||||
}
|
||||
const receipts = validateServerReceipts(
|
||||
value,
|
||||
manifest,
|
||||
"UPLOAD_RECONCILE",
|
||||
);
|
||||
if (!receipts.ok) return receipts;
|
||||
return browserDataSuccess(
|
||||
Object.freeze({
|
||||
state: "ACTIVE" as const,
|
||||
session: session.value,
|
||||
acceptedParts: receipts.value,
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (value.state === "QUARANTINED") {
|
||||
if (!exactRecord(value, ["state", "session", "resourceId"])) {
|
||||
return browserDataFailure(
|
||||
"CORRUPT_DATA",
|
||||
"UPLOAD_RECONCILE",
|
||||
{ recovery: "RECONCILE" },
|
||||
);
|
||||
}
|
||||
const session = validateSession(
|
||||
value.session,
|
||||
checkpoint.requestBindingSha256,
|
||||
manifest.fingerprint,
|
||||
dependencies,
|
||||
false,
|
||||
);
|
||||
if (
|
||||
!session.ok ||
|
||||
session.value.sessionId !== checkpoint.sessionId ||
|
||||
session.value.maxConcurrency !== checkpoint.sessionMaxConcurrency ||
|
||||
session.value.expiresAtEpochMs !==
|
||||
checkpoint.sessionExpiresAtEpochMs ||
|
||||
!SAFE_OPAQUE_ID.test(value.resourceId)
|
||||
) {
|
||||
return browserDataFailure(
|
||||
"INTEGRITY_FAILED",
|
||||
"UPLOAD_RECONCILE",
|
||||
{ recovery: "RECONCILE" },
|
||||
);
|
||||
}
|
||||
return browserDataSuccess(
|
||||
Object.freeze({
|
||||
state: "QUARANTINED" as const,
|
||||
session: session.value,
|
||||
resourceId: value.resourceId,
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (
|
||||
!["ABORTED", "EXPIRED", "NOT_FOUND"].includes(value.state) ||
|
||||
!exactRecord(value, [
|
||||
"state",
|
||||
"protocol",
|
||||
"sessionId",
|
||||
"requestBindingSha256",
|
||||
]) ||
|
||||
value.protocol !== RESUMABLE_UPLOAD_PROTOCOL ||
|
||||
value.sessionId !== checkpoint.sessionId ||
|
||||
value.requestBindingSha256 !== checkpoint.requestBindingSha256
|
||||
) {
|
||||
return browserDataFailure("INTEGRITY_FAILED", "UPLOAD_RECONCILE", {
|
||||
recovery: "RECONCILE",
|
||||
});
|
||||
}
|
||||
return browserDataSuccess(
|
||||
Object.freeze({
|
||||
state: value.state,
|
||||
protocol: RESUMABLE_UPLOAD_PROTOCOL,
|
||||
sessionId: value.sessionId,
|
||||
requestBindingSha256: value.requestBindingSha256,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export function validateSession<Capability>(
|
||||
value: UploadSession,
|
||||
requestBindingSha256: string,
|
||||
fingerprint: UploadFileFingerprint,
|
||||
dependencies: RuntimeDependencies<Capability>,
|
||||
requireActiveExpiry = true,
|
||||
): BrowserDataResult<UploadSession> {
|
||||
if (
|
||||
!exactRecord(value, [
|
||||
"protocol",
|
||||
"sessionId",
|
||||
"requestBindingSha256",
|
||||
"fingerprint",
|
||||
"partSizeBytes",
|
||||
"partCount",
|
||||
"maxConcurrency",
|
||||
"expiresAtEpochMs",
|
||||
]) ||
|
||||
value.protocol !== RESUMABLE_UPLOAD_PROTOCOL ||
|
||||
!SAFE_OPAQUE_ID.test(value.sessionId) ||
|
||||
value.requestBindingSha256 !== requestBindingSha256 ||
|
||||
!SHA256_HEX.test(value.requestBindingSha256) ||
|
||||
!isUploadFileFingerprint(value.fingerprint) ||
|
||||
!sameFingerprint(value.fingerprint, fingerprint) ||
|
||||
value.partSizeBytes !== fingerprint.partSizeBytes ||
|
||||
value.partCount !== fingerprint.partCount ||
|
||||
!Number.isSafeInteger(value.maxConcurrency) ||
|
||||
value.maxConcurrency < 1 ||
|
||||
value.maxConcurrency > dependencies.policy.maxConcurrency ||
|
||||
!Number.isSafeInteger(value.expiresAtEpochMs)
|
||||
) {
|
||||
return browserDataFailure("INTEGRITY_FAILED", "UPLOAD_SESSION", {
|
||||
recovery: "RECONCILE",
|
||||
});
|
||||
}
|
||||
const now = safeNow(dependencies, "UPLOAD_SESSION");
|
||||
if (!now.ok) return now;
|
||||
if (
|
||||
requireActiveExpiry &&
|
||||
(value.expiresAtEpochMs <= now.value ||
|
||||
value.expiresAtEpochMs - now.value >
|
||||
dependencies.policy.maxSessionLifetimeMs)
|
||||
) {
|
||||
return browserDataFailure("EXPIRED_RESOURCE", "UPLOAD_SESSION", {
|
||||
recovery: "RESTART",
|
||||
});
|
||||
}
|
||||
return browserDataSuccess(
|
||||
Object.freeze({
|
||||
...value,
|
||||
fingerprint: Object.freeze({ ...value.fingerprint }),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function validateServerReceipts(
|
||||
status: ActiveUploadStatus,
|
||||
manifest: UploadPartManifest,
|
||||
operation: BrowserDataOperation,
|
||||
): BrowserDataResult<readonly UploadPartReceipt[]> {
|
||||
if (
|
||||
!Array.isArray(status.acceptedParts) ||
|
||||
status.acceptedParts.length > manifest.parts.length
|
||||
) {
|
||||
return browserDataFailure("CORRUPT_DATA", operation, {
|
||||
recovery: "RECONCILE",
|
||||
});
|
||||
}
|
||||
let previousPart = 0;
|
||||
for (const receipt of status.acceptedParts) {
|
||||
if (
|
||||
!isUploadPartReceipt(receipt) ||
|
||||
receipt.partNumber <= previousPart ||
|
||||
!verifyPartAgainstManifest(receipt, manifest)
|
||||
) {
|
||||
return browserDataFailure("INTEGRITY_FAILED", operation, {
|
||||
recovery: "RECONCILE",
|
||||
});
|
||||
}
|
||||
previousPart = receipt.partNumber;
|
||||
}
|
||||
return browserDataSuccess(snapshotReceipts(status.acceptedParts));
|
||||
}
|
||||
|
||||
export function sameFingerprint(
|
||||
left: UploadFileFingerprint,
|
||||
right: UploadFileFingerprint,
|
||||
): boolean {
|
||||
return (
|
||||
left.algorithm === right.algorithm &&
|
||||
left.digestHex === right.digestHex &&
|
||||
left.byteLength === right.byteLength &&
|
||||
left.partSizeBytes === right.partSizeBytes &&
|
||||
left.partCount === right.partCount
|
||||
);
|
||||
}
|
||||
|
||||
export function snapshotReceipts(
|
||||
parts: readonly UploadPartReceipt[],
|
||||
): readonly UploadPartReceipt[] {
|
||||
return Object.freeze(
|
||||
parts.map((part) => Object.freeze({ ...part })),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,656 @@
|
||||
import type {
|
||||
PublicCacheAsset,
|
||||
PublicCacheHeader,
|
||||
PublicCacheReleaseManifest,
|
||||
} from "../../application/ports/browser-file-storage/cache-storage-ports.ts";
|
||||
import type {
|
||||
BrowserDataFailure,
|
||||
BrowserDataFailureCode,
|
||||
BrowserDataOperation,
|
||||
BrowserDataResult,
|
||||
} from "../../application/ports/browser-file-storage/shared.ts";
|
||||
import {
|
||||
browserDataFailure,
|
||||
mapBrowserDataException,
|
||||
} from "../browser-file-storage/result.ts";
|
||||
import {
|
||||
isAllowedPublicCacheOrigin,
|
||||
type PublicCacheRuntimePolicy,
|
||||
} from "./public-cache-policy.ts";
|
||||
|
||||
/**
|
||||
* Q-6.2-11. Release manifest, marker and active-pointer codec for the public
|
||||
* response cache: normalization, canonical digest input, bounded control JSON
|
||||
* decoding, owned cache naming, and the mapping of a validation failure to a
|
||||
* browser-data Result. Moved verbatim out of the adapter.
|
||||
*/
|
||||
|
||||
export type PublicCacheCryptoFacade = Readonly<{
|
||||
digestSha256(bytes: Uint8Array): Promise<ArrayBuffer>;
|
||||
}>;
|
||||
|
||||
export type NormalizedAsset = Readonly<{
|
||||
absoluteUrl: string;
|
||||
expectedByteLength: number;
|
||||
expectedContentType: string;
|
||||
digestHex: string;
|
||||
requestHeaders: readonly PublicCacheHeader[];
|
||||
}>;
|
||||
|
||||
export type NormalizedReleaseManifest = Readonly<{
|
||||
releaseRegistryId: string;
|
||||
manifestDigestHex: string;
|
||||
assets: readonly NormalizedAsset[];
|
||||
}>;
|
||||
|
||||
export type ReleaseMarker = Readonly<{
|
||||
schemaVersion: 1;
|
||||
verified: true;
|
||||
releaseRegistryId: string;
|
||||
manifestDigestHex: string;
|
||||
entryCount: number;
|
||||
totalBytes: number;
|
||||
stagedAtEpochMs: number;
|
||||
assets: readonly NormalizedAsset[];
|
||||
}>;
|
||||
|
||||
export type ActiveReleasePointer = Readonly<{
|
||||
schemaVersion: 1;
|
||||
releaseRegistryId: string;
|
||||
manifestDigestHex: string;
|
||||
candidateCacheName: string;
|
||||
rollbackCandidateCacheNames: readonly string[];
|
||||
activatedAtEpochMs: number;
|
||||
}>;
|
||||
|
||||
export type BrowserFailureResult = Readonly<{
|
||||
ok: false;
|
||||
error: BrowserDataFailure;
|
||||
}>;
|
||||
|
||||
export class CacheValidationFailure extends Error {
|
||||
readonly code: BrowserDataFailureCode;
|
||||
|
||||
constructor(code: BrowserDataFailureCode) {
|
||||
super("Public cache validation failed.");
|
||||
this.name = "CacheValidationFailure";
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
||||
export async function normalizeAndVerifyManifest(
|
||||
manifest: PublicCacheReleaseManifest,
|
||||
policy: PublicCacheRuntimePolicy,
|
||||
crypto: PublicCacheCryptoFacade,
|
||||
): Promise<NormalizedReleaseManifest> {
|
||||
const snapshot = Object.freeze({
|
||||
releaseRegistryId: manifest.releaseRegistryId,
|
||||
manifestDigestHex: manifest.manifestDigestHex,
|
||||
assets: normalizeAssets(manifest.assets, policy),
|
||||
});
|
||||
if (
|
||||
!policy.isReleaseRegistryIdAllowed(snapshot.releaseRegistryId) ||
|
||||
!SHA256_HEX.test(snapshot.manifestDigestHex)
|
||||
) {
|
||||
throw new CacheValidationFailure("INVALID_INPUT");
|
||||
}
|
||||
const actualDigest = await sha256Hex(
|
||||
crypto,
|
||||
new TextEncoder().encode(
|
||||
canonicalManifest(snapshot.releaseRegistryId, snapshot.assets),
|
||||
),
|
||||
);
|
||||
if (actualDigest !== snapshot.manifestDigestHex) {
|
||||
throw new CacheValidationFailure("INTEGRITY_FAILED");
|
||||
}
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
export function normalizeAssets(
|
||||
assets: readonly PublicCacheAsset[],
|
||||
policy: PublicCacheRuntimePolicy,
|
||||
): readonly NormalizedAsset[] {
|
||||
if (
|
||||
!Array.isArray(assets) ||
|
||||
assets.length < 1 ||
|
||||
assets.length > policy.maxEntriesPerRelease
|
||||
) {
|
||||
throw new CacheValidationFailure("LIMIT_EXCEEDED");
|
||||
}
|
||||
const normalized = assets.map((asset) =>
|
||||
normalizeAsset(asset, policy),
|
||||
);
|
||||
const keys = normalized.map(assetKey);
|
||||
if (new Set(keys).size !== keys.length) {
|
||||
throw new CacheValidationFailure("CONFLICT");
|
||||
}
|
||||
const declaredTotal = normalized.reduce(
|
||||
(total, asset) => total + asset.expectedByteLength,
|
||||
0,
|
||||
);
|
||||
if (
|
||||
!Number.isSafeInteger(declaredTotal) ||
|
||||
declaredTotal > policy.maxReleaseBytes
|
||||
) {
|
||||
throw new CacheValidationFailure("LIMIT_EXCEEDED");
|
||||
}
|
||||
return Object.freeze(normalized);
|
||||
}
|
||||
|
||||
export function normalizeAsset(
|
||||
asset: PublicCacheAsset,
|
||||
policy: PublicCacheRuntimePolicy,
|
||||
): NormalizedAsset {
|
||||
if (
|
||||
!asset ||
|
||||
typeof asset !== "object" ||
|
||||
!Number.isSafeInteger(asset.expectedByteLength) ||
|
||||
asset.expectedByteLength < 0 ||
|
||||
asset.expectedByteLength > policy.maxEntryBytes ||
|
||||
asset.integrity?.algorithm !== "SHA-256" ||
|
||||
!SHA256_HEX.test(asset.integrity.digestHex)
|
||||
) {
|
||||
throw new CacheValidationFailure("INVALID_INPUT");
|
||||
}
|
||||
return Object.freeze({
|
||||
absoluteUrl: normalizePublicUrl(asset.absoluteUrl, policy),
|
||||
expectedByteLength: asset.expectedByteLength,
|
||||
expectedContentType: normalizeContentType(
|
||||
asset.expectedContentType,
|
||||
policy,
|
||||
),
|
||||
digestHex: asset.integrity.digestHex,
|
||||
requestHeaders: normalizeRequestHeaders(
|
||||
asset.requestHeaders,
|
||||
policy,
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
export function normalizeLookupRequest(
|
||||
absoluteUrl: string,
|
||||
requestHeaders: readonly PublicCacheHeader[] | undefined,
|
||||
policy: PublicCacheRuntimePolicy,
|
||||
): NormalizedAsset {
|
||||
return {
|
||||
absoluteUrl: normalizePublicUrl(absoluteUrl, policy),
|
||||
expectedByteLength: 0,
|
||||
expectedContentType: "",
|
||||
digestHex: ZERO_SHA256,
|
||||
requestHeaders: normalizeRequestHeaders(requestHeaders, policy),
|
||||
};
|
||||
}
|
||||
|
||||
export function normalizeContentType(
|
||||
input: string,
|
||||
policy: PublicCacheRuntimePolicy,
|
||||
): string {
|
||||
if (
|
||||
typeof input !== "string" ||
|
||||
input.length < 1 ||
|
||||
input.length > 256 ||
|
||||
/[\r\n\0]/u.test(input) ||
|
||||
!policy.isContentTypeAllowed(input)
|
||||
) {
|
||||
throw new CacheValidationFailure("POLICY_REJECTED");
|
||||
}
|
||||
return input
|
||||
.split(";")
|
||||
.map((part) => part.trim())
|
||||
.filter((part) => part.length > 0)
|
||||
.map((part, index) =>
|
||||
index === 0 ? part.toLowerCase() : part,
|
||||
)
|
||||
.join("; ");
|
||||
}
|
||||
|
||||
export function normalizePublicUrl(
|
||||
input: string,
|
||||
policy: PublicCacheRuntimePolicy,
|
||||
): string {
|
||||
if (typeof input !== "string" || input.length > 2_048) {
|
||||
throw new CacheValidationFailure("INVALID_INPUT");
|
||||
}
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(input);
|
||||
} catch {
|
||||
throw new CacheValidationFailure("INVALID_INPUT");
|
||||
}
|
||||
if (
|
||||
url.origin !== policy.origin ||
|
||||
!isAllowedPublicCacheOrigin(url) ||
|
||||
url.username.length > 0 ||
|
||||
url.password.length > 0 ||
|
||||
url.hash.length > 0 ||
|
||||
url.href === markerRequestUrl(policy) ||
|
||||
url.href === activePointerRequestUrl(policy)
|
||||
) {
|
||||
throw new CacheValidationFailure("POLICY_REJECTED");
|
||||
}
|
||||
const forbidden = new Set(policy.forbiddenQueryParameterNames);
|
||||
const allowed = new Set(policy.allowedQueryParameterNames);
|
||||
const seenNames = new Set<string>();
|
||||
for (const [rawName, value] of url.searchParams.entries()) {
|
||||
const name = rawName.toLowerCase();
|
||||
if (
|
||||
forbidden.has(name) ||
|
||||
!allowed.has(name) ||
|
||||
seenNames.has(name) ||
|
||||
!policy.isQueryParameterValueAllowed(name, value)
|
||||
) {
|
||||
throw new CacheValidationFailure("POLICY_REJECTED");
|
||||
}
|
||||
seenNames.add(name);
|
||||
}
|
||||
return url.href;
|
||||
}
|
||||
|
||||
export function normalizeRequestHeaders(
|
||||
input: readonly PublicCacheHeader[] | undefined,
|
||||
policy: PublicCacheRuntimePolicy,
|
||||
): readonly PublicCacheHeader[] {
|
||||
const allowed = new Set(policy.allowedRequestHeaderNames);
|
||||
const forbidden = new Set([
|
||||
"authorization",
|
||||
"cookie",
|
||||
"proxy-authorization",
|
||||
"range",
|
||||
]);
|
||||
const headers = new Headers();
|
||||
for (const pair of input ?? []) {
|
||||
if (
|
||||
!Array.isArray(pair) ||
|
||||
pair.length !== 2 ||
|
||||
typeof pair[0] !== "string" ||
|
||||
typeof pair[1] !== "string"
|
||||
) {
|
||||
throw new CacheValidationFailure("INVALID_INPUT");
|
||||
}
|
||||
const name = pair[0].toLowerCase();
|
||||
if (
|
||||
forbidden.has(name) ||
|
||||
!allowed.has(name) ||
|
||||
pair[1].length > 1_024 ||
|
||||
/[\r\n\0]/u.test(pair[1])
|
||||
) {
|
||||
throw new CacheValidationFailure("POLICY_REJECTED");
|
||||
}
|
||||
headers.append(name, pair[1].trim());
|
||||
}
|
||||
return Object.freeze(
|
||||
[...headers.entries()]
|
||||
.sort(([left], [right]) => left.localeCompare(right))
|
||||
.map(
|
||||
([name, value]) =>
|
||||
Object.freeze([name, value]) as PublicCacheHeader,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export async function readBoundedJson(
|
||||
response: Response,
|
||||
maximumBytes: number,
|
||||
): Promise<unknown> {
|
||||
const contentLength = response.headers.get("content-length");
|
||||
if (
|
||||
!Number.isSafeInteger(maximumBytes) ||
|
||||
maximumBytes <= 0 ||
|
||||
(contentLength !== null &&
|
||||
(!/^\d+$/u.test(contentLength) ||
|
||||
Number(contentLength) > maximumBytes))
|
||||
) {
|
||||
throw new CacheValidationFailure("CORRUPT_DATA");
|
||||
}
|
||||
if (!response.body) {
|
||||
throw new CacheValidationFailure("CORRUPT_DATA");
|
||||
}
|
||||
|
||||
const reader = response.body.getReader();
|
||||
// Q-6.2-6. Chunks are kept as read; the budget is enforced on their total,
|
||||
// never by preallocating it.
|
||||
const chunks: Uint8Array[] = [];
|
||||
let byteLength = 0;
|
||||
let completelyRead = false;
|
||||
try {
|
||||
while (true) {
|
||||
const chunk = await reader.read();
|
||||
if (chunk.done) {
|
||||
completelyRead = true;
|
||||
break;
|
||||
}
|
||||
if (chunk.value.byteLength > maximumBytes - byteLength) {
|
||||
throw new CacheValidationFailure("CORRUPT_DATA");
|
||||
}
|
||||
chunks.push(chunk.value);
|
||||
byteLength += chunk.value.byteLength;
|
||||
}
|
||||
} catch (error) {
|
||||
if (!completelyRead) {
|
||||
cancelReaderSafely(
|
||||
reader,
|
||||
"Cache control JSON exceeded its read budget.",
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
|
||||
const bytes = new Uint8Array(byteLength);
|
||||
let offset = 0;
|
||||
for (const chunk of chunks) {
|
||||
bytes.set(chunk, offset);
|
||||
offset += chunk.byteLength;
|
||||
}
|
||||
let text: string;
|
||||
try {
|
||||
text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
||||
} catch {
|
||||
throw new CacheValidationFailure("CORRUPT_DATA");
|
||||
}
|
||||
try {
|
||||
return JSON.parse(text);
|
||||
} catch {
|
||||
throw new CacheValidationFailure("CORRUPT_DATA");
|
||||
}
|
||||
}
|
||||
|
||||
export function cancelReaderSafely(
|
||||
reader: ReadableStreamDefaultReader<Uint8Array>,
|
||||
reason: string,
|
||||
): void {
|
||||
try {
|
||||
void reader.cancel(reason).catch(() => undefined);
|
||||
} catch {
|
||||
// Cancellation is best effort once the bounded consumer has stopped.
|
||||
}
|
||||
}
|
||||
|
||||
export function isReleaseMarker(
|
||||
value: unknown,
|
||||
policy: PublicCacheRuntimePolicy,
|
||||
): value is ReleaseMarker {
|
||||
if (
|
||||
!value ||
|
||||
typeof value !== "object" ||
|
||||
!("schemaVersion" in value) ||
|
||||
value.schemaVersion !== 1 ||
|
||||
!("verified" in value) ||
|
||||
value.verified !== true ||
|
||||
!("releaseRegistryId" in value) ||
|
||||
typeof value.releaseRegistryId !== "string" ||
|
||||
!policy.isReleaseRegistryIdAllowed(value.releaseRegistryId) ||
|
||||
!("manifestDigestHex" in value) ||
|
||||
typeof value.manifestDigestHex !== "string" ||
|
||||
!SHA256_HEX.test(value.manifestDigestHex) ||
|
||||
!("entryCount" in value) ||
|
||||
typeof value.entryCount !== "number" ||
|
||||
!Number.isSafeInteger(value.entryCount) ||
|
||||
!("totalBytes" in value) ||
|
||||
typeof value.totalBytes !== "number" ||
|
||||
!Number.isSafeInteger(value.totalBytes) ||
|
||||
!("stagedAtEpochMs" in value) ||
|
||||
typeof value.stagedAtEpochMs !== "number" ||
|
||||
!Number.isSafeInteger(value.stagedAtEpochMs) ||
|
||||
!("assets" in value) ||
|
||||
!Array.isArray(value.assets) ||
|
||||
value.assets.length > policy.maxEntriesPerRelease
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
const normalized = normalizeAssets(
|
||||
value.assets.map((asset) => markerAssetToPublicAsset(asset)),
|
||||
policy,
|
||||
);
|
||||
return stableJson(normalized) === stableJson(value.assets);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function markerAssetToPublicAsset(value: unknown): PublicCacheAsset {
|
||||
if (!value || typeof value !== "object") {
|
||||
throw new CacheValidationFailure("CORRUPT_DATA");
|
||||
}
|
||||
const asset = value as Partial<NormalizedAsset>;
|
||||
return {
|
||||
absoluteUrl: asset.absoluteUrl ?? "",
|
||||
expectedByteLength: asset.expectedByteLength ?? -1,
|
||||
expectedContentType: asset.expectedContentType ?? "",
|
||||
integrity: {
|
||||
algorithm: "SHA-256",
|
||||
digestHex: asset.digestHex ?? "",
|
||||
},
|
||||
requestHeaders: asset.requestHeaders,
|
||||
};
|
||||
}
|
||||
|
||||
export function isActivePointer(
|
||||
value: unknown,
|
||||
policy: PublicCacheRuntimePolicy,
|
||||
): value is ActiveReleasePointer {
|
||||
return Boolean(
|
||||
value &&
|
||||
typeof value === "object" &&
|
||||
"schemaVersion" in value &&
|
||||
value.schemaVersion === 1 &&
|
||||
"releaseRegistryId" in value &&
|
||||
typeof value.releaseRegistryId === "string" &&
|
||||
policy.isReleaseRegistryIdAllowed(value.releaseRegistryId) &&
|
||||
"manifestDigestHex" in value &&
|
||||
typeof value.manifestDigestHex === "string" &&
|
||||
SHA256_HEX.test(value.manifestDigestHex) &&
|
||||
"candidateCacheName" in value &&
|
||||
typeof value.candidateCacheName === "string" &&
|
||||
value.candidateCacheName ===
|
||||
releaseCacheName(
|
||||
policy,
|
||||
value.releaseRegistryId,
|
||||
value.manifestDigestHex,
|
||||
) &&
|
||||
"rollbackCandidateCacheNames" in value &&
|
||||
Array.isArray(value.rollbackCandidateCacheNames) &&
|
||||
value.rollbackCandidateCacheNames.length <=
|
||||
policy.retainedPreviousReleaseCount &&
|
||||
new Set(value.rollbackCandidateCacheNames).size ===
|
||||
value.rollbackCandidateCacheNames.length &&
|
||||
value.rollbackCandidateCacheNames.every(
|
||||
(name) =>
|
||||
typeof name === "string" &&
|
||||
name !== value.candidateCacheName &&
|
||||
isOwnedReleaseCacheName(name, policy),
|
||||
) &&
|
||||
"activatedAtEpochMs" in value &&
|
||||
typeof value.activatedAtEpochMs === "number" &&
|
||||
Number.isSafeInteger(value.activatedAtEpochMs),
|
||||
);
|
||||
}
|
||||
|
||||
export function isOwnedReleaseCacheName(
|
||||
name: string,
|
||||
policy: PublicCacheRuntimePolicy,
|
||||
): boolean {
|
||||
if (!name.startsWith(`${policy.ownedCachePrefix}release:`)) {
|
||||
return false;
|
||||
}
|
||||
const remainder = name.slice(
|
||||
`${policy.ownedCachePrefix}release:`.length,
|
||||
);
|
||||
const separator = remainder.lastIndexOf(":");
|
||||
if (separator < 1) return false;
|
||||
const releaseRegistryId = remainder.slice(0, separator);
|
||||
const digestHex = remainder.slice(separator + 1);
|
||||
return (
|
||||
policy.isReleaseRegistryIdAllowed(releaseRegistryId) &&
|
||||
SHA256_HEX.test(digestHex)
|
||||
);
|
||||
}
|
||||
|
||||
export function canonicalManifest(
|
||||
releaseRegistryId: string,
|
||||
assets: readonly NormalizedAsset[],
|
||||
): string {
|
||||
return [
|
||||
"ca-public-cache-manifest-v1",
|
||||
`release:${releaseRegistryId}`,
|
||||
...[...assets]
|
||||
.sort((left, right) => assetKey(left).localeCompare(assetKey(right)))
|
||||
.map(
|
||||
(asset) =>
|
||||
`${assetKey(asset)}:${asset.expectedByteLength}:${JSON.stringify(asset.expectedContentType)}:${asset.digestHex}`,
|
||||
),
|
||||
"",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
export function assetKey(
|
||||
asset: Pick<NormalizedAsset, "absoluteUrl" | "requestHeaders">,
|
||||
): string {
|
||||
return JSON.stringify([asset.absoluteUrl, asset.requestHeaders]);
|
||||
}
|
||||
|
||||
export function markerRequest(policy: PublicCacheRuntimePolicy): Request {
|
||||
return new Request(markerRequestUrl(policy), { method: "GET" });
|
||||
}
|
||||
|
||||
export function activePointerRequest(policy: PublicCacheRuntimePolicy): Request {
|
||||
return new Request(activePointerRequestUrl(policy), { method: "GET" });
|
||||
}
|
||||
|
||||
export function markerRequestUrl(policy: PublicCacheRuntimePolicy): string {
|
||||
return `${policy.origin}/.well-known/ca-public-cache-v1/candidate`;
|
||||
}
|
||||
|
||||
export function activePointerRequestUrl(policy: PublicCacheRuntimePolicy): string {
|
||||
return `${policy.origin}/.well-known/ca-public-cache-v1/active`;
|
||||
}
|
||||
|
||||
export function controlCacheName(policy: PublicCacheRuntimePolicy): string {
|
||||
return `${policy.ownedCachePrefix}control`;
|
||||
}
|
||||
|
||||
export function releaseCacheName(
|
||||
policy: PublicCacheRuntimePolicy,
|
||||
releaseRegistryId: string,
|
||||
manifestDigestHex: string,
|
||||
): string {
|
||||
return `${policy.ownedCachePrefix}release:${releaseRegistryId}:${manifestDigestHex}`;
|
||||
}
|
||||
|
||||
export function jsonResponse(value: unknown): Response {
|
||||
return new Response(JSON.stringify(value), {
|
||||
status: 200,
|
||||
headers: {
|
||||
"cache-control": "no-store",
|
||||
"content-type": "application/json; charset=utf-8",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function validationFailure(
|
||||
error: unknown,
|
||||
operation: BrowserDataOperation,
|
||||
): BrowserFailureResult {
|
||||
return error instanceof CacheValidationFailure
|
||||
? failureForCode(error.code, operation)
|
||||
: asFailure(browserDataFailure("INVALID_INPUT", operation));
|
||||
}
|
||||
|
||||
export function exceptionFailure(
|
||||
error: unknown,
|
||||
operation: BrowserDataOperation,
|
||||
): BrowserFailureResult {
|
||||
if (error instanceof CacheValidationFailure) {
|
||||
return failureForCode(error.code, operation);
|
||||
}
|
||||
const mapped = mapBrowserDataException(error, operation);
|
||||
if (mapped.ok) {
|
||||
return asFailure(
|
||||
browserDataFailure("UNAVAILABLE", operation, {
|
||||
retryable: true,
|
||||
recovery: "RETRY",
|
||||
}),
|
||||
);
|
||||
}
|
||||
return mapped;
|
||||
}
|
||||
|
||||
export function failureForCode(
|
||||
code: BrowserDataFailureCode,
|
||||
operation: BrowserDataOperation,
|
||||
): BrowserFailureResult {
|
||||
if (code === "ABORTED") {
|
||||
return asFailure(browserDataFailure(code, operation));
|
||||
}
|
||||
if (code === "INTEGRITY_FAILED" || code === "CORRUPT_DATA") {
|
||||
return asFailure(
|
||||
browserDataFailure(code, operation, { recovery: "REHYDRATE" }),
|
||||
);
|
||||
}
|
||||
if (code === "QUOTA_EXCEEDED") {
|
||||
return asFailure(
|
||||
browserDataFailure(code, operation, {
|
||||
retryable: true,
|
||||
recovery: "ONLINE_ONLY",
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (code === "BLOCKED" || code === "UNAVAILABLE") {
|
||||
return asFailure(
|
||||
browserDataFailure(code, operation, {
|
||||
retryable: true,
|
||||
recovery: "RETRY",
|
||||
}),
|
||||
);
|
||||
}
|
||||
return asFailure(browserDataFailure(code, operation));
|
||||
}
|
||||
|
||||
export function asFailure(
|
||||
result: BrowserDataResult<never>,
|
||||
): BrowserFailureResult {
|
||||
if (result.ok) {
|
||||
throw new TypeError("Expected a browser data failure.");
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function sha256Hex(
|
||||
crypto: PublicCacheCryptoFacade,
|
||||
bytes: Uint8Array,
|
||||
): Promise<string> {
|
||||
const digest = await crypto.digestSha256(bytes);
|
||||
let hex = "";
|
||||
for (const byte of new Uint8Array(digest)) {
|
||||
hex += byte.toString(16).padStart(2, "0");
|
||||
}
|
||||
return hex;
|
||||
}
|
||||
|
||||
export function stableJson(value: unknown): string {
|
||||
if (
|
||||
value === null ||
|
||||
typeof value === "string" ||
|
||||
typeof value === "boolean" ||
|
||||
typeof value === "number"
|
||||
) {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
return `[${value.map(stableJson).join(",")}]`;
|
||||
}
|
||||
if (typeof value === "object") {
|
||||
const record = value as Record<string, unknown>;
|
||||
return `{${Object.keys(record)
|
||||
.sort()
|
||||
.map((key) => `${JSON.stringify(key)}:${stableJson(record[key])}`)
|
||||
.join(",")}}`;
|
||||
}
|
||||
throw new CacheValidationFailure("CORRUPT_DATA");
|
||||
}
|
||||
|
||||
export const SHA256_HEX = /^[a-f0-9]{64}$/u;
|
||||
export const ZERO_SHA256 = "0".repeat(64);
|
||||
export const MAX_CONTROL_JSON_BYTES = 2 * 1024 * 1024;
|
||||
@@ -0,0 +1,239 @@
|
||||
import type { PublicCacheHeader } from "../../application/ports/browser-file-storage/cache-storage-ports.ts";
|
||||
import type { BrowserDataResult } from "../../application/ports/browser-file-storage/shared.ts";
|
||||
import { browserDataSuccess } from "../browser-file-storage/result.ts";
|
||||
import { createAbortableOperation } from "../platform/abortable-operation.ts";
|
||||
import {
|
||||
CacheValidationFailure,
|
||||
cancelReaderSafely,
|
||||
exceptionFailure,
|
||||
normalizeContentType,
|
||||
sha256Hex,
|
||||
type NormalizedAsset,
|
||||
type PublicCacheCryptoFacade,
|
||||
} from "./public-cache-codec.ts";
|
||||
import type { PublicCacheRuntimePolicy } from "./public-cache-policy.ts";
|
||||
|
||||
/**
|
||||
* Q-6.2-11. Admission of a network or cached response for one manifest asset:
|
||||
* status, cache directives, content type, Vary, bounded body read and digest.
|
||||
* Moved verbatim out of the adapter.
|
||||
*/
|
||||
|
||||
export type CacheReadResult = Readonly<{
|
||||
bytes: Uint8Array;
|
||||
headers: readonly PublicCacheHeader[];
|
||||
}>;
|
||||
|
||||
export async function readAndValidateResponse(
|
||||
response: Response,
|
||||
asset: NormalizedAsset,
|
||||
policy: PublicCacheRuntimePolicy,
|
||||
crypto: PublicCacheCryptoFacade,
|
||||
signal: AbortSignal | undefined,
|
||||
): Promise<BrowserDataResult<CacheReadResult>> {
|
||||
try {
|
||||
if (
|
||||
response.status !== 200 ||
|
||||
!response.ok ||
|
||||
response.redirected ||
|
||||
response.type === "opaque" ||
|
||||
response.type === "opaqueredirect" ||
|
||||
response.type === "error" ||
|
||||
(response.url.length > 0 &&
|
||||
new URL(response.url).href !== asset.absoluteUrl)
|
||||
) {
|
||||
throw new CacheValidationFailure("POLICY_REJECTED");
|
||||
}
|
||||
const cacheControl = response.headers.get("cache-control") ?? "";
|
||||
const directives = new Set(
|
||||
cacheControl
|
||||
.split(",")
|
||||
.map((part) => part.trim().split("=", 1)[0]?.toLowerCase())
|
||||
.filter((part): part is string => Boolean(part)),
|
||||
);
|
||||
if (
|
||||
directives.has("private") ||
|
||||
directives.has("no-store") ||
|
||||
directives.has("no-cache") ||
|
||||
(response.headers.get("pragma") ?? "")
|
||||
.toLowerCase()
|
||||
.includes("no-cache") ||
|
||||
response.headers.has("set-cookie") ||
|
||||
response.headers.has("set-cookie2") ||
|
||||
response.headers.has("www-authenticate")
|
||||
) {
|
||||
throw new CacheValidationFailure("POLICY_REJECTED");
|
||||
}
|
||||
const contentType = response.headers.get("content-type");
|
||||
if (!contentType || !policy.isContentTypeAllowed(contentType)) {
|
||||
throw new CacheValidationFailure("POLICY_REJECTED");
|
||||
}
|
||||
if (
|
||||
normalizeContentType(contentType, policy) !==
|
||||
asset.expectedContentType
|
||||
) {
|
||||
throw new CacheValidationFailure("INTEGRITY_FAILED");
|
||||
}
|
||||
validateVary(response.headers.get("vary"), asset, policy);
|
||||
const declaredLength = response.headers.get("content-length");
|
||||
if (
|
||||
declaredLength !== null &&
|
||||
(!/^\d+$/u.test(declaredLength) ||
|
||||
Number(declaredLength) > policy.maxEntryBytes)
|
||||
) {
|
||||
throw new CacheValidationFailure("LIMIT_EXCEEDED");
|
||||
}
|
||||
|
||||
const bytes = await readBodyBounded(
|
||||
response,
|
||||
asset.expectedByteLength,
|
||||
policy.maxEntryBytes,
|
||||
signal,
|
||||
);
|
||||
const digestHex = await sha256Hex(crypto, bytes);
|
||||
if (digestHex !== asset.digestHex) {
|
||||
throw new CacheValidationFailure("INTEGRITY_FAILED");
|
||||
}
|
||||
const headers = sanitizedResponseHeaders(response.headers, policy);
|
||||
return browserDataSuccess({ bytes, headers });
|
||||
} catch (error) {
|
||||
return exceptionFailure(error, "CACHE_STAGE");
|
||||
}
|
||||
}
|
||||
|
||||
export async function readBodyBounded(
|
||||
response: Response,
|
||||
expectedByteLength: number,
|
||||
maxEntryBytes: number,
|
||||
signal: AbortSignal | undefined,
|
||||
): Promise<Uint8Array> {
|
||||
if (expectedByteLength > maxEntryBytes) {
|
||||
throw new CacheValidationFailure("LIMIT_EXCEEDED");
|
||||
}
|
||||
if (!response.body) {
|
||||
if (expectedByteLength === 0) return new Uint8Array();
|
||||
throw new CacheValidationFailure("INTEGRITY_FAILED");
|
||||
}
|
||||
const output = new Uint8Array(expectedByteLength);
|
||||
const reader = response.body.getReader();
|
||||
let offset = 0;
|
||||
// The kernel owner ends a pending read on abort instead of a listener pair.
|
||||
const owner = createAbortableOperation({ signal });
|
||||
const abortRead = (): CacheValidationFailure => {
|
||||
cancelReaderSafely(reader, "Public cache body read was aborted.");
|
||||
return new CacheValidationFailure("ABORTED");
|
||||
};
|
||||
try {
|
||||
while (true) {
|
||||
if (owner.signal.aborted) throw abortRead();
|
||||
const raced = await owner.race(reader.read());
|
||||
if (raced.kind === "REJECTED") throw raced.reason;
|
||||
if (raced.kind === "TERMINAL" || owner.signal.aborted) {
|
||||
throw abortRead();
|
||||
}
|
||||
const part = raced.value;
|
||||
if (part.done) break;
|
||||
if (
|
||||
!(part.value instanceof Uint8Array) ||
|
||||
offset + part.value.byteLength > expectedByteLength ||
|
||||
offset + part.value.byteLength > maxEntryBytes
|
||||
) {
|
||||
cancelReaderSafely(
|
||||
reader,
|
||||
"Public cache body exceeded its read budget.",
|
||||
);
|
||||
throw new CacheValidationFailure(
|
||||
offset + part.value.byteLength > maxEntryBytes
|
||||
? "LIMIT_EXCEEDED"
|
||||
: "INTEGRITY_FAILED",
|
||||
);
|
||||
}
|
||||
output.set(part.value, offset);
|
||||
offset += part.value.byteLength;
|
||||
}
|
||||
} finally {
|
||||
owner.close();
|
||||
reader.releaseLock();
|
||||
}
|
||||
if (offset !== expectedByteLength) {
|
||||
throw new CacheValidationFailure("INTEGRITY_FAILED");
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
export function validateVary(
|
||||
vary: string | null,
|
||||
asset: NormalizedAsset,
|
||||
policy: PublicCacheRuntimePolicy,
|
||||
): void {
|
||||
const expected = new Set(
|
||||
asset.requestHeaders.map(([name]) => name.toLowerCase()),
|
||||
);
|
||||
const actual = new Set<string>();
|
||||
if (!vary) {
|
||||
if (expected.size > 0) {
|
||||
throw new CacheValidationFailure("POLICY_REJECTED");
|
||||
}
|
||||
return;
|
||||
}
|
||||
const allowed = new Set(policy.allowedVaryHeaderNames);
|
||||
for (const item of vary.split(",")) {
|
||||
const name = item.trim().toLowerCase();
|
||||
// Browser-managed: Accept-Encoding is a forbidden request header, so no
|
||||
// script-built Request carries it. Stored and lookup requests both lack it
|
||||
// and Cache.match still matches exactly. nginx `gzip_vary` and most CDNs
|
||||
// send it on every compressible asset.
|
||||
if (name === "accept-encoding") continue;
|
||||
if (
|
||||
name === "*" ||
|
||||
name === "authorization" ||
|
||||
name === "cookie" ||
|
||||
!allowed.has(name)
|
||||
) {
|
||||
throw new CacheValidationFailure("POLICY_REJECTED");
|
||||
}
|
||||
actual.add(name);
|
||||
}
|
||||
if (
|
||||
actual.size !== expected.size ||
|
||||
[...actual].some((name) => !expected.has(name))
|
||||
) {
|
||||
throw new CacheValidationFailure("POLICY_REJECTED");
|
||||
}
|
||||
}
|
||||
|
||||
export function sanitizedResponseHeaders(
|
||||
headers: Headers,
|
||||
policy: PublicCacheRuntimePolicy,
|
||||
): readonly PublicCacheHeader[] {
|
||||
const allowed = new Set(policy.allowedResponseHeaderNames);
|
||||
const sanitized: PublicCacheHeader[] = [];
|
||||
for (const [name, value] of headers.entries()) {
|
||||
if (!allowed.has(name)) {
|
||||
if (policy.unknownResponseHeaderAction === "REJECT") {
|
||||
throw new CacheValidationFailure("POLICY_REJECTED");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
sanitized.push(Object.freeze([name, value]));
|
||||
}
|
||||
return Object.freeze(sanitized);
|
||||
}
|
||||
|
||||
export function createNativeRequest(
|
||||
asset: NormalizedAsset,
|
||||
signal?: AbortSignal,
|
||||
): Request {
|
||||
return new Request(asset.absoluteUrl, {
|
||||
method: "GET",
|
||||
headers: new Headers(
|
||||
asset.requestHeaders.map(([name, value]) => [name, value]),
|
||||
),
|
||||
credentials: "omit",
|
||||
cache: "no-store",
|
||||
redirect: "error",
|
||||
referrerPolicy: "no-referrer",
|
||||
mode: "same-origin",
|
||||
signal,
|
||||
});
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -36,6 +36,20 @@ const CHANNEL_NAME = "ca-client-cache-invalidation-v1";
|
||||
const STORAGE_PULSE_KEY =
|
||||
STORAGE_REGISTRY.CACHE_INVALIDATION_PULSE.physicalKey;
|
||||
|
||||
/**
|
||||
* Q-6.2-9. A release ID may hold any character (`1.2.3+sha.abc`, `feature/x`,
|
||||
* `app@1.2.3`) and any length, but a cache epoch is an opaque identifier. The
|
||||
* epoch is a stable 64-bit FNV-1a digest of the ID, so every tab of one release
|
||||
* agrees on it and it always passes the wire rule.
|
||||
*/
|
||||
export function crossContextCacheEpochForRelease(releaseId: string): string {
|
||||
let hash = 0xcbf29ce484222325n;
|
||||
for (const byte of new TextEncoder().encode(releaseId)) {
|
||||
hash = ((hash ^ BigInt(byte)) * 0x100000001b3n) & 0xffffffffffffffffn;
|
||||
}
|
||||
return `release.${hash.toString(16).padStart(16, "0")}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Captures native capabilities without allowing a SecurityError getter or a
|
||||
* missing random source to fail application boot.
|
||||
@@ -49,17 +63,38 @@ export function createBrowserCrossContextInvalidationFromHost(
|
||||
const host =
|
||||
dependencies.host ??
|
||||
(globalThis as unknown as Record<string, unknown>);
|
||||
// Q-6.2-9. Ending inactive is reported, so cross-tab invalidation is never
|
||||
// switched off without a diagnostic.
|
||||
const inactive = (
|
||||
reason: "INVALID_CACHE_EPOCH" | "SECURE_RANDOM_UNAVAILABLE",
|
||||
): undefined => {
|
||||
try {
|
||||
dependencies.observe?.(
|
||||
Object.freeze({
|
||||
operation: "OPEN" as const,
|
||||
outcome: "FAILED" as const,
|
||||
transport: "NONE" as const,
|
||||
reason,
|
||||
}),
|
||||
);
|
||||
} catch {
|
||||
// Diagnostics cannot change the capability decision.
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
if (
|
||||
!isCacheInvalidationOpaqueIdentifier(dependencies.cacheEpoch)
|
||||
) {
|
||||
return undefined;
|
||||
return inactive("INVALID_CACHE_EPOCH");
|
||||
}
|
||||
const createOpaqueId = randomIdFactory(host);
|
||||
if (!createOpaqueId) return undefined;
|
||||
if (!createOpaqueId) return inactive("SECURE_RANDOM_UNAVAILABLE");
|
||||
|
||||
const sourceId = createOpaqueId("tab");
|
||||
const sourceEpoch = createOpaqueId("page");
|
||||
if (!sourceId || !sourceEpoch) return undefined;
|
||||
if (!sourceId || !sourceEpoch) {
|
||||
return inactive("SECURE_RANDOM_UNAVAILABLE");
|
||||
}
|
||||
|
||||
const capturedLocalStorage = captureLocalStorage(host);
|
||||
|
||||
|
||||
@@ -43,9 +43,11 @@ export type CrossContextInvalidationObservationReason =
|
||||
| "DELIVERED"
|
||||
| "DUPLICATE"
|
||||
| "HANDLER_FAILED"
|
||||
| "INVALID_CACHE_EPOCH"
|
||||
| "OPENED"
|
||||
| "PUBLISHED"
|
||||
| "SELF_ECHO"
|
||||
| "SECURE_RANDOM_UNAVAILABLE"
|
||||
| "SEQUENCE_EXHAUSTED"
|
||||
| "STALE"
|
||||
| "STORAGE_CLEANUP_FAILED"
|
||||
|
||||
@@ -19,5 +19,6 @@ export {
|
||||
} from "./browser-cross-context-invalidation.ts";
|
||||
export {
|
||||
createBrowserCrossContextInvalidationFromHost,
|
||||
crossContextCacheEpochForRelease,
|
||||
type BrowserCrossContextHostDependencies,
|
||||
} from "./browser-cross-context-host.ts";
|
||||
|
||||
+32
-16
@@ -40,7 +40,7 @@ import type { ClockPort } from "../../application/ports/clock-port.ts";
|
||||
import type { DiagnosticsPort } from "../../application/ports/diagnostics-port.ts";
|
||||
import type { TelemetryPort } from "../../application/ports/telemetry-port.ts";
|
||||
import type { ApiOperation } from "../../contracts/api-operations.ts";
|
||||
import type { ApiFailure } from "../../contracts/errors.ts";
|
||||
import type { ApiFailure, FailureKind } from "../../contracts/errors.ts";
|
||||
import type { OperationRequestInput } from "./request-builder.ts";
|
||||
import { readBoundedJson } from "./bounded-json.ts";
|
||||
import { admitCredentialHeaders } from "./http-contract-bridge.ts";
|
||||
@@ -48,7 +48,7 @@ import type { MappingResult } from "../../contracts/boundary-mapper.ts";
|
||||
import {
|
||||
createRestProviderProfile,
|
||||
resolveRestSecurityProfiles,
|
||||
REST_AUTH_PROFILES,
|
||||
INSTALLED_REST_AUTH_PROFILES,
|
||||
REST_CSRF_PROFILES,
|
||||
type RestAuthProfile,
|
||||
type RestCsrfProfile,
|
||||
@@ -336,12 +336,11 @@ export function createHttpClient(
|
||||
);
|
||||
}
|
||||
|
||||
// Q-6.3-11. Recovery is its own single replay, bounded by
|
||||
// `recoveryUsed` and the deadline, not by the retry budget: a disabled
|
||||
// or spent budget must not turn a recoverable 401 into a logout.
|
||||
if (outcome.error.httpStatus === 401 && !recoveryUsed) {
|
||||
recoveryUsed = true;
|
||||
if (physicalAttemptCount >= maxRetryAttempts + 1) {
|
||||
authSession.onUnauthenticated();
|
||||
return finalize(outcome, "failed");
|
||||
}
|
||||
let recovered: SessionRecoveryOutcome;
|
||||
// LEG-01. The recovery collaborator receives the request lifetime, and
|
||||
// the transport races the same signal so a non-cooperative owner cannot
|
||||
@@ -562,7 +561,7 @@ export function createHttpClient(
|
||||
security = resolveRestSecurityProfiles(
|
||||
operation,
|
||||
provider,
|
||||
dependencies.authProfiles ?? REST_AUTH_PROFILES,
|
||||
dependencies.authProfiles ?? INSTALLED_REST_AUTH_PROFILES,
|
||||
dependencies.csrfProfiles ?? REST_CSRF_PROFILES,
|
||||
);
|
||||
}
|
||||
@@ -842,6 +841,17 @@ export function createHttpClient(
|
||||
|
||||
class LogicalDeadlineError extends Error {}
|
||||
|
||||
/**
|
||||
* Q-6.3-3b. A gateway 5xx/408/425 with an HTML, empty or broken body is a
|
||||
* server outage, not a contract breach: it keeps its status and the normal
|
||||
* SERVER_FAILURE retry rule instead of a non-retryable body error.
|
||||
*/
|
||||
function gatewayFailureOr(status: number, kind: FailureKind): FailureKind {
|
||||
return status >= 500 || status === 408 || status === 425
|
||||
? "SERVER_FAILURE"
|
||||
: kind;
|
||||
}
|
||||
|
||||
async function parseResponse(
|
||||
response: Response,
|
||||
operation: ApiOperation,
|
||||
@@ -862,10 +872,12 @@ async function parseResponse(
|
||||
void response.body?.cancel().catch(() => {});
|
||||
return {
|
||||
ok: false,
|
||||
error: failure("CONTENT_TYPE_MISMATCH", operation.operationId, attempt, {
|
||||
code: "CONTENT_TYPE_MISMATCH",
|
||||
httpStatus: response.status,
|
||||
}),
|
||||
error: failure(
|
||||
gatewayFailureOr(response.status, "CONTENT_TYPE_MISMATCH"),
|
||||
operation.operationId,
|
||||
attempt,
|
||||
{ code: "CONTENT_TYPE_MISMATCH", httpStatus: response.status },
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -876,10 +888,12 @@ async function parseResponse(
|
||||
if (!decoded.ok) {
|
||||
return {
|
||||
ok: false,
|
||||
error: failure(decoded.code, operation.operationId, attempt, {
|
||||
code: decoded.code,
|
||||
httpStatus: response.status,
|
||||
}),
|
||||
error: failure(
|
||||
gatewayFailureOr(response.status, decoded.code),
|
||||
operation.operationId,
|
||||
attempt,
|
||||
{ code: decoded.code, httpStatus: response.status },
|
||||
),
|
||||
};
|
||||
}
|
||||
const envelope = decoded.value;
|
||||
@@ -889,7 +903,9 @@ async function parseResponse(
|
||||
return {
|
||||
ok: false,
|
||||
error: failure(
|
||||
response.ok ? "ENVELOPE_MISMATCH" : statusKind(response.status),
|
||||
response.ok
|
||||
? "ENVELOPE_MISMATCH"
|
||||
: gatewayFailureOr(response.status, statusKind(response.status)),
|
||||
operation.operationId,
|
||||
attempt,
|
||||
{
|
||||
|
||||
@@ -504,6 +504,17 @@ export function createContractHttpExecutor(
|
||||
kind: HttpTransportFailure["kind"],
|
||||
): HttpExecutionOutcome<WireOutput, Problem> =>
|
||||
transportFailure(kind, false, abandonedCertainty());
|
||||
/**
|
||||
* Q-6.3-7. What the attempts that were retried settled on. The logical
|
||||
* accumulator above is raised at dispatch, before the attempt's own answer
|
||||
* is known, so it cannot tell a rejected attempt from a lost one.
|
||||
*/
|
||||
let retriedCertainty: MutationEffectCertainty = "NOT_STARTED";
|
||||
const rememberRetried = (settled: MutationEffectCertainty) => {
|
||||
if (isCommand) {
|
||||
retriedCertainty = joinMutationEffectCertainty(retriedCertainty, settled);
|
||||
}
|
||||
};
|
||||
let terminalCancellation: CancellationOwner | null = null;
|
||||
const lifetimeController = new AbortController();
|
||||
const forwardCallerToLifetime = () => {
|
||||
@@ -582,6 +593,31 @@ export function createContractHttpExecutor(
|
||||
return outcome;
|
||||
};
|
||||
|
||||
/**
|
||||
* Q-6.3-6. The one classifier for a wait that a terminal owner ended. The
|
||||
* caller cancels and the deadline times out. A scope fence during a `WAIT`
|
||||
* (credentials, lease, dispatch, backoff) aborts the transport; during
|
||||
* `ADMISSION` the response headers prove the request reached the server,
|
||||
* so a stale generation stays the `SCOPE_FENCED` contract violation.
|
||||
*/
|
||||
const terminalOutcomeFor = (
|
||||
phase: "WAIT" | "ADMISSION",
|
||||
): HttpExecutionOutcome<WireOutput, Problem> => {
|
||||
switch (terminalCancellation) {
|
||||
case "CALLER":
|
||||
return finish(cancelled(abandonedCertainty()), "CANCELLED");
|
||||
case "SCOPE_FENCE":
|
||||
return phase === "ADMISSION"
|
||||
? finish(scopeFenced(abandonedCertainty()), "SCOPE_FENCED")
|
||||
: finish(
|
||||
abandonedTransportFailure("ABORTED_BY_SCOPE"),
|
||||
"SCOPE_FENCED",
|
||||
);
|
||||
default:
|
||||
return finish(abandonedTransportFailure("TIMEOUT"), "TIMEOUT");
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
|
||||
// §7.7. The installed registry is the only source of a profile. Composition
|
||||
@@ -684,20 +720,7 @@ export function createContractHttpExecutor(
|
||||
"AUTH_INTEGRATION_FAILURE",
|
||||
);
|
||||
}
|
||||
if (patchResult === ABORTED) {
|
||||
if (terminalCancellation === "SCOPE_FENCE") {
|
||||
return finish(
|
||||
abandonedTransportFailure("ABORTED_BY_SCOPE"),
|
||||
"SCOPE_FENCED",
|
||||
);
|
||||
}
|
||||
return terminalCancellation === "CALLER"
|
||||
? finish(cancelled("NOT_STARTED"), "CANCELLED")
|
||||
: finish(
|
||||
abandonedTransportFailure("TIMEOUT"),
|
||||
"TIMEOUT",
|
||||
);
|
||||
}
|
||||
if (patchResult === ABORTED) return terminalOutcomeFor("WAIT");
|
||||
// NS-01. The whole answer is decoded once, inside the auth boundary, before
|
||||
// any field is used. Reading `kind` and `headers` off the raw object left
|
||||
// the decode outside that boundary: a throwing getter escaped into the
|
||||
@@ -818,16 +841,7 @@ export function createContractHttpExecutor(
|
||||
"TRAFFIC_BUDGET_EXCEEDED",
|
||||
);
|
||||
}
|
||||
if (terminalCancellation === "CALLER") {
|
||||
return finish(cancelled(abandonedCertainty()), "CANCELLED");
|
||||
}
|
||||
if (terminalCancellation === "SCOPE_FENCE") {
|
||||
return finish(
|
||||
abandonedTransportFailure("ABORTED_BY_SCOPE"),
|
||||
"SCOPE_FENCED",
|
||||
);
|
||||
}
|
||||
return finish(abandonedTransportFailure("TIMEOUT"), "TIMEOUT");
|
||||
return terminalOutcomeFor("WAIT");
|
||||
}
|
||||
try {
|
||||
const controller = new AbortController();
|
||||
@@ -919,22 +933,10 @@ export function createContractHttpExecutor(
|
||||
} else {
|
||||
clearTimeout(deadlineTimer);
|
||||
lifetimeController.signal.removeEventListener("abort", forwardLifetime);
|
||||
const owner = terminalCancellation;
|
||||
if (owner === "CALLER") {
|
||||
return finish(
|
||||
cancelled(abandonedCertainty()),
|
||||
"CANCELLED",
|
||||
);
|
||||
if (terminalCancellation !== null) {
|
||||
return terminalOutcomeFor("WAIT");
|
||||
}
|
||||
if (owner === "SCOPE_FENCE") {
|
||||
return finish(
|
||||
abandonedTransportFailure("ABORTED_BY_SCOPE"),
|
||||
"SCOPE_FENCED",
|
||||
);
|
||||
}
|
||||
const kind = owner === "DEADLINE" ? "TIMEOUT" : "NETWORK_FAILURE";
|
||||
if (
|
||||
owner === null &&
|
||||
canRetryTransport(contract.retrySemantics, attemptState) &&
|
||||
retryIndex < retryCeiling &&
|
||||
remaining() > 0
|
||||
@@ -946,23 +948,14 @@ export function createContractHttpExecutor(
|
||||
sleep(delay, lifetimeController.signal),
|
||||
lifetimeController.signal,
|
||||
);
|
||||
if (slept === ABORTED) {
|
||||
return terminalCancellation === "CALLER"
|
||||
? finish(
|
||||
cancelled(abandonedCertainty()),
|
||||
"CANCELLED",
|
||||
)
|
||||
: finish(
|
||||
abandonedTransportFailure("TIMEOUT"),
|
||||
"TIMEOUT",
|
||||
);
|
||||
}
|
||||
if (slept === ABORTED) return terminalOutcomeFor("WAIT");
|
||||
rememberRetried(certaintyForAbandonedAttempt(attemptState, isCommand));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
return finish(
|
||||
abandonedTransportFailure(kind),
|
||||
kind,
|
||||
abandonedTransportFailure("NETWORK_FAILURE"),
|
||||
"NETWORK_FAILURE",
|
||||
);
|
||||
}
|
||||
|
||||
@@ -983,44 +976,28 @@ export function createContractHttpExecutor(
|
||||
controller.signal,
|
||||
() => cancelResponseBody(response),
|
||||
);
|
||||
// LIVE-04. Once response headers are in hand the request demonstrably
|
||||
// reached the server, so a terminal owner that lands during admission
|
||||
// keeps the dispatched classification: a stale generation stays the
|
||||
// `SCOPE_FENCED` contract violation it has always been, and only the
|
||||
// deadline and the caller reclassify the outcome.
|
||||
const abandonAdmission = ():
|
||||
| HttpExecutionOutcome<WireOutput, Problem>
|
||||
| null => {
|
||||
switch (terminalCancellation) {
|
||||
case "DEADLINE":
|
||||
return finish(abandonedTransportFailure("TIMEOUT"), "TIMEOUT");
|
||||
case "CALLER":
|
||||
return finish(cancelled(abandonedCertainty()), "CANCELLED");
|
||||
case "SCOPE_FENCE":
|
||||
return finish(
|
||||
scopeFenced(abandonedCertainty()),
|
||||
"SCOPE_FENCED",
|
||||
);
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
};
|
||||
// LIVE-04. A terminal owner that lands during admission wins over the
|
||||
// admitted answer.
|
||||
if (admission.kind !== "VALUE") {
|
||||
cancelResponseBody(response);
|
||||
return (
|
||||
abandonAdmission() ??
|
||||
finish(
|
||||
abandonedTransportFailure("NETWORK_FAILURE"),
|
||||
"NETWORK_FAILURE",
|
||||
)
|
||||
);
|
||||
return terminalCancellation === null
|
||||
? finish(
|
||||
abandonedTransportFailure("NETWORK_FAILURE"),
|
||||
"NETWORK_FAILURE",
|
||||
)
|
||||
: terminalOutcomeFor("ADMISSION");
|
||||
}
|
||||
const outcome = admission.value;
|
||||
attemptState = "SETTLED";
|
||||
const abandoned = abandonAdmission();
|
||||
if (abandoned) return abandoned;
|
||||
if (terminalCancellation !== null) {
|
||||
return terminalOutcomeFor("ADMISSION");
|
||||
}
|
||||
if (
|
||||
outcome.retryHint &&
|
||||
// Q-6.3-7. An answer that says the command may already be applied
|
||||
// is not replayed; reconciliation owns it from here.
|
||||
outcome.certainty !== "MAYBE_APPLIED" &&
|
||||
outcome.certainty !== "APPLIED_CONFIRMED" &&
|
||||
retryIndex < retryCeiling &&
|
||||
isRetryableSemantics(contract.retrySemantics)
|
||||
) {
|
||||
@@ -1036,21 +1013,28 @@ export function createContractHttpExecutor(
|
||||
sleep(delay, lifetimeController.signal),
|
||||
lifetimeController.signal,
|
||||
);
|
||||
if (slept === ABORTED) {
|
||||
return terminalCancellation === "CALLER"
|
||||
? finish(
|
||||
cancelled(abandonedCertainty()),
|
||||
"CANCELLED",
|
||||
)
|
||||
: finish(
|
||||
abandonedTransportFailure("TIMEOUT"),
|
||||
"TIMEOUT",
|
||||
);
|
||||
}
|
||||
if (slept === ABORTED) return terminalOutcomeFor("WAIT");
|
||||
rememberRetried(outcome.result.effect as MutationEffectCertainty);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
return finish(outcome.result, outcome.certainty);
|
||||
// Q-6.3-7. A retry never reports less than an earlier attempt of the
|
||||
// same command already established.
|
||||
const effect = isCommand
|
||||
? joinMutationEffectCertainty(
|
||||
retriedCertainty,
|
||||
outcome.result.effect as MutationEffectCertainty,
|
||||
)
|
||||
: outcome.result.effect;
|
||||
return finish(
|
||||
effect === outcome.result.effect
|
||||
? outcome.result
|
||||
: (Object.freeze({
|
||||
...outcome.result,
|
||||
effect,
|
||||
}) as HttpExecutionOutcome<WireOutput, Problem>),
|
||||
outcome.certainty,
|
||||
);
|
||||
} finally {
|
||||
clearTimeout(deadlineTimer);
|
||||
lifetimeController.signal.removeEventListener("abort", forwardLifetime);
|
||||
|
||||
@@ -42,7 +42,9 @@ export type { CredentialPatchOutcome } from "./http-contract-bridge.ts";
|
||||
*
|
||||
* 이 템플릿은 V2의 오퍼레이션 레지스트리와 payload 매퍼를 비워서 출하한다.
|
||||
* 제품이 `RuntimeHttpContract`(`src/bootstrap/runtime-adapters.ts`)의 네
|
||||
* 슬롯을 주입해야 동작한다 — 주입 없이 V3에서 되돌리면 모든 요청이 실패한다.
|
||||
* 슬롯을 주입해야 동작한다. V3의 롤백 경로는 아니다 — V2는
|
||||
* `{ success, data, meta }` 봉투를, V3는 DTO 자체를 검증하므로 V2로 되돌리려면
|
||||
* 슬롯 주입과 함께 서버 응답도 V2 봉투여야 한다.
|
||||
*/
|
||||
export {
|
||||
createHttpClient,
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { parseRetryAfterDelay } from "../platform/retry-after.ts";
|
||||
|
||||
const retryKinds: ReadonlySet<string> = new Set([
|
||||
"NETWORK_UNREACHABLE",
|
||||
"REQUEST_TIMEOUT",
|
||||
@@ -18,16 +20,7 @@ export function parseRetryAfter(
|
||||
value: string | null | undefined,
|
||||
now = Date.now(),
|
||||
): number | null {
|
||||
if (!value) return null;
|
||||
|
||||
const seconds = Number(value);
|
||||
if (Number.isFinite(seconds)) {
|
||||
return seconds < 0 ? null : seconds * 1_000;
|
||||
}
|
||||
|
||||
const timestamp = Date.parse(value);
|
||||
if (!Number.isFinite(timestamp)) return null;
|
||||
return Math.max(0, timestamp - now);
|
||||
return parseRetryAfterDelay(value, now);
|
||||
}
|
||||
|
||||
export type RetryOperation = Readonly<{
|
||||
|
||||
@@ -267,3 +267,27 @@ export function compensateLateHandle(
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}
|
||||
|
||||
/**
|
||||
* Best-effort release of a response body whose result is already classified.
|
||||
* Neither a synchronous throw nor a rejected cancellation can change that
|
||||
* result.
|
||||
*/
|
||||
export function cancelBody(response: Response): void {
|
||||
try {
|
||||
void response.body?.cancel().catch(() => undefined);
|
||||
} catch {
|
||||
// The classified result wins over body cancellation.
|
||||
}
|
||||
}
|
||||
|
||||
/** `cancelBody` for a reader that already holds the body's lock. */
|
||||
export function cancelReader(
|
||||
reader: ReadableStreamDefaultReader<Uint8Array>,
|
||||
): void {
|
||||
try {
|
||||
void reader.cancel().catch(() => undefined);
|
||||
} catch {
|
||||
// The classified result wins over reader cancellation.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -332,7 +332,9 @@ export function openIndexedDbDatabase<Failure>(
|
||||
// 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) {
|
||||
// Q-6.5-10. An open that already settled (caller abort, BLOCKED, close)
|
||||
// must not commit a migration behind its caller's back either.
|
||||
if (settled || !transaction || newVersion === null || !input.upgrade) {
|
||||
upgradeRejection = { kind: "UPGRADE_REJECTED", oldVersion, newVersion };
|
||||
abortUpgrade();
|
||||
return;
|
||||
|
||||
@@ -26,7 +26,8 @@ export type IndexedDbDurability = "default" | "strict" | "relaxed";
|
||||
*/
|
||||
export type IndexedDbRequestSink<Failure> = Readonly<{
|
||||
/**
|
||||
* Records the failure and aborts the transaction. The first failure wins.
|
||||
* Records the failure and aborts the transaction. The first failure wins,
|
||||
* and it wins over an earlier `succeed`.
|
||||
* This is `indexeddb-runtime.ts:1047-1054`'s `fail`.
|
||||
*/
|
||||
fail(failure: Failure): void;
|
||||
@@ -266,7 +267,9 @@ export function runIndexedDbTransaction<Value, Failure>(
|
||||
candidate ??= succeeded(value);
|
||||
},
|
||||
fail(failure) {
|
||||
candidate ??= failed(failure);
|
||||
// Q-6.5-10. A failure replaces an earlier `succeed`; only an earlier
|
||||
// failure outranks it.
|
||||
if (candidate?.ok !== false) candidate = failed(failure);
|
||||
try {
|
||||
transaction.abort();
|
||||
} catch {
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* Parses an HTTP Retry-After value: delta-seconds (digits only, surrounding
|
||||
* whitespace allowed) or an IMF-fixdate. Anything else — decimals, exponents,
|
||||
* blank text, other date spellings — is `null`, never a guessed delay.
|
||||
* No runtime ceiling is applied; callers reject a value above their budget.
|
||||
*/
|
||||
export function parseRetryAfterDelay(
|
||||
value: string | null | undefined,
|
||||
nowEpochMs: number,
|
||||
): number | null {
|
||||
if (
|
||||
typeof value !== "string" ||
|
||||
value.length === 0 ||
|
||||
value.length > 128 ||
|
||||
!Number.isFinite(nowEpochMs)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const normalized = value.trim();
|
||||
if (/^\d+$/u.test(normalized)) {
|
||||
const seconds = Number(normalized);
|
||||
return Number.isSafeInteger(seconds) &&
|
||||
seconds <= Math.floor(Number.MAX_SAFE_INTEGER / 1_000)
|
||||
? seconds * 1_000
|
||||
: null;
|
||||
}
|
||||
if (
|
||||
!/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), \d{2} (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{4} \d{2}:\d{2}:\d{2} GMT$/u.test(
|
||||
normalized,
|
||||
)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const timestamp = Date.parse(normalized);
|
||||
return Number.isFinite(timestamp)
|
||||
? Math.max(0, timestamp - nowEpochMs)
|
||||
: null;
|
||||
}
|
||||
@@ -138,12 +138,11 @@ export function createConditionalValidatorStore(
|
||||
|
||||
function isSafeEntityTag(value: string): boolean {
|
||||
if (value.length < 3 || value.length > 256) return false;
|
||||
const opaque = value.startsWith('W/"')
|
||||
? value.slice(3, -1)
|
||||
: value.startsWith('"')
|
||||
? value.slice(1, -1)
|
||||
: null;
|
||||
if (opaque === null || !value.endsWith('"')) return false;
|
||||
const start = value.startsWith('W/"') ? 3 : value.startsWith('"') ? 1 : -1;
|
||||
// Q-6.3-12. The closing quote must follow the opening one: a bare `W/"`
|
||||
// ends with its opening quote and is unclosed.
|
||||
if (start < 0 || value.length <= start || !value.endsWith('"')) return false;
|
||||
const opaque = value.slice(start, -1);
|
||||
return [...opaque].every((character) => {
|
||||
const code = character.codePointAt(0) ?? 0;
|
||||
return code === 0x21 || (code >= 0x23 && code <= 0x7e) ||
|
||||
|
||||
@@ -68,6 +68,7 @@ export function createCursorPaginationRuntime<Value>(dependencies: Readonly<{
|
||||
return Object.freeze({
|
||||
async loadAll(context) {
|
||||
const items: Value[] = [];
|
||||
let pageBytes = 0;
|
||||
const cursors = new Set<string>();
|
||||
let cursor: string | null = null;
|
||||
let snapshot: string | null | undefined;
|
||||
@@ -108,16 +109,21 @@ export function createCursorPaginationRuntime<Value>(dependencies: Readonly<{
|
||||
"PAGINATION_SNAPSHOT_CHANGED",
|
||||
);
|
||||
}
|
||||
items.push(...page.items);
|
||||
// Q-6.3-12. Each page is measured once (the sum errs high by at most
|
||||
// one byte per page) and appended item by item: re-serializing the
|
||||
// accumulated items was O(pages × total), and `push(...items)`
|
||||
// throws a RangeError for a large page.
|
||||
pageBytes += estimatedBytes(page.items);
|
||||
if (
|
||||
items.length > profile.maxTotalItems ||
|
||||
estimatedBytes(items) > profile.maxEstimatedBytes
|
||||
items.length + page.items.length > profile.maxTotalItems ||
|
||||
pageBytes > profile.maxEstimatedBytes
|
||||
) {
|
||||
return failure(
|
||||
"RESULT_LIMIT_EXCEEDED",
|
||||
"PAGINATION_RESULT_LIMIT",
|
||||
);
|
||||
}
|
||||
for (const item of page.items) items.push(item);
|
||||
if (!page.hasMore) return { ok: true, value: Object.freeze(items) };
|
||||
const nextCursor: string | null = page.nextCursor;
|
||||
if (!nextCursor || cursors.has(nextCursor)) {
|
||||
|
||||
@@ -76,16 +76,19 @@ export function createTanStackCacheCoordinator(
|
||||
namespaces.set(queryNamespaceIdentityKey(namespace), namespace);
|
||||
}
|
||||
}
|
||||
for (const namespace of namespaces.values()) {
|
||||
try {
|
||||
await dependencies.queryClient.invalidateQueries({
|
||||
// Q-6.3-8. invalidateQueries resolves only after the active refetches
|
||||
// finish, so the namespaces run side by side instead of one after another.
|
||||
const results = await Promise.allSettled(
|
||||
[...namespaces.values()].map(async (namespace) =>
|
||||
dependencies.queryClient.invalidateQueries({
|
||||
queryKey: createQueryInvalidationPrefix(namespace),
|
||||
exact: false,
|
||||
refetchType: "active",
|
||||
});
|
||||
} catch {
|
||||
report("invalidate");
|
||||
}
|
||||
}),
|
||||
),
|
||||
);
|
||||
for (const result of results) {
|
||||
if (result.status === "rejected") report("invalidate");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -24,14 +24,16 @@ import {
|
||||
} from "../../contracts/schema-registry.ts";
|
||||
import {
|
||||
hasDuplicateJsonMembers,
|
||||
} from "./json-member-scanner.ts";
|
||||
} from "../platform/json-member-scanner.ts";
|
||||
|
||||
export type ValidatedRealtimeEventDto = Readonly<{
|
||||
envelope: RealtimeEventEnvelope;
|
||||
wireBytes: number;
|
||||
/**
|
||||
* Adapter-private semantic identity used only by the bounded conflict
|
||||
* detector. It must never be logged or projected into diagnostics.
|
||||
* detector: a fixed-size hash of the canonical envelope, so dedupe memory
|
||||
* does not grow with payload size. It must never be logged or projected
|
||||
* into diagnostics.
|
||||
*/
|
||||
semanticFingerprint: string;
|
||||
fingerprintBytes: number;
|
||||
@@ -99,13 +101,13 @@ function decodeUnsafe(
|
||||
if (typeof raw !== "string") {
|
||||
return realtimeFailure("MALFORMED_EVENT", "DECODE");
|
||||
}
|
||||
if (
|
||||
raw.length > REALTIME_HARD_LIMITS.maxEventBytes ||
|
||||
encoder.encode(raw).byteLength > REALTIME_HARD_LIMITS.maxEventBytes
|
||||
) {
|
||||
if (raw.length > REALTIME_HARD_LIMITS.maxEventBytes) {
|
||||
return realtimeFailure("EVENT_TOO_LARGE", "DECODE");
|
||||
}
|
||||
const wireBytes = encoder.encode(raw).byteLength;
|
||||
if (wireBytes > REALTIME_HARD_LIMITS.maxEventBytes) {
|
||||
return realtimeFailure("EVENT_TOO_LARGE", "DECODE");
|
||||
}
|
||||
|
||||
let input: unknown;
|
||||
if (
|
||||
@@ -186,11 +188,8 @@ function decodeUnsafe(
|
||||
eventType,
|
||||
payloadSnapshot,
|
||||
);
|
||||
const semanticFingerprint = canonicalJson(envelope);
|
||||
const fingerprintBytes = encoder.encode(semanticFingerprint).byteLength;
|
||||
if (fingerprintBytes > stream.limits.maxEventBytes) {
|
||||
return realtimeFailure("EVENT_TOO_LARGE", "DECODE");
|
||||
}
|
||||
const semanticFingerprint = hash64(canonicalJson(envelope));
|
||||
const fingerprintBytes = semanticFingerprint.length;
|
||||
|
||||
const dto = Object.freeze({
|
||||
envelope,
|
||||
@@ -367,6 +366,26 @@ function snapshotJson(
|
||||
return visit(value, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Two differently seeded 32-bit FNV-1a hashes as 16 hex characters.
|
||||
* ponytail: not collision-proof against a hostile server; a collision only
|
||||
* lets a conflicting redelivery pass as a duplicate. Use SHA-256 if the
|
||||
* server is not trusted to keep event IDs unique.
|
||||
*/
|
||||
function hash64(text: string): string {
|
||||
let first = 0x811c9dc5;
|
||||
let second = 0x9e3779b9;
|
||||
for (let index = 0; index < text.length; index += 1) {
|
||||
const unit = text.charCodeAt(index);
|
||||
first = Math.imul(first ^ unit, 0x01000193);
|
||||
second = Math.imul(second ^ unit, 0x01000193);
|
||||
}
|
||||
return (
|
||||
(first >>> 0).toString(16).padStart(8, "0") +
|
||||
(second >>> 0).toString(16).padStart(8, "0")
|
||||
);
|
||||
}
|
||||
|
||||
function canonicalJson(value: unknown): string {
|
||||
if (
|
||||
value === null ||
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
import { systemClock } from "../platform/system-clock.ts";
|
||||
import {
|
||||
isRealtimeResult,
|
||||
raceRealtimeTask,
|
||||
realtimeFailure,
|
||||
realtimeSuccess,
|
||||
} from "./result.ts";
|
||||
@@ -132,8 +133,6 @@ type InternalProbe<Value> = {
|
||||
facade: LiveProbeLease<Value>;
|
||||
readonly buffer: BufferedValue<Value>[];
|
||||
bufferedBytes: number;
|
||||
acceptedEvents: number;
|
||||
acceptedBytes: number;
|
||||
};
|
||||
|
||||
type QuiescenceOutcome = "QUIESCED" | "TIMER_FAILED" | "TIMED_OUT";
|
||||
@@ -224,8 +223,6 @@ export function createLivePollHandoffCoordinator<Value>(
|
||||
lease,
|
||||
buffer: [],
|
||||
bufferedBytes: 0,
|
||||
acceptedEvents: 0,
|
||||
acceptedBytes: 0,
|
||||
facade: null as unknown as LiveProbeLease<Value>,
|
||||
};
|
||||
selected.facade = Object.freeze({
|
||||
@@ -263,11 +260,11 @@ export function createLivePollHandoffCoordinator<Value>(
|
||||
value: Value,
|
||||
wireBytes: number,
|
||||
): RealtimeResult<LivePollWriteReceipt> {
|
||||
// Bounded by what is still buffered: activation drains the buffer while
|
||||
// the probe keeps receiving.
|
||||
if (
|
||||
selected.acceptedEvents + 1 >
|
||||
limits.maxProbeBufferedEvents ||
|
||||
selected.acceptedBytes + wireBytes >
|
||||
limits.maxProbeBufferedBytes
|
||||
selected.buffer.length + 1 > limits.maxProbeBufferedEvents ||
|
||||
selected.bufferedBytes + wireBytes > limits.maxProbeBufferedBytes
|
||||
) {
|
||||
if (transitioning) {
|
||||
failClosed();
|
||||
@@ -282,8 +279,6 @@ export function createLivePollHandoffCoordinator<Value>(
|
||||
}
|
||||
selected.buffer.push(Object.freeze({ value, wireBytes }));
|
||||
selected.bufferedBytes += wireBytes;
|
||||
selected.acceptedEvents += 1;
|
||||
selected.acceptedBytes += wireBytes;
|
||||
return realtimeSuccess(
|
||||
Object.freeze({
|
||||
kind: "BUFFERED" as const,
|
||||
@@ -555,24 +550,6 @@ export function createLivePollHandoffCoordinator<Value>(
|
||||
from: LivePollWriterKind,
|
||||
candidate: InternalWriterLease<Value>,
|
||||
): Promise<RealtimeResult<void>> {
|
||||
const timer = new AbortController();
|
||||
let releaseAbortGate = (): void => undefined;
|
||||
const aborted = new Promise<
|
||||
Readonly<{ kind: "ABORTED" }>
|
||||
>((resolve) => {
|
||||
const onAbort = () => resolve({ kind: "ABORTED" });
|
||||
candidate.controller.signal.addEventListener(
|
||||
"abort",
|
||||
onAbort,
|
||||
{ once: true },
|
||||
);
|
||||
releaseAbortGate = () =>
|
||||
candidate.controller.signal.removeEventListener(
|
||||
"abort",
|
||||
onAbort,
|
||||
);
|
||||
if (candidate.controller.signal.aborted) onAbort();
|
||||
});
|
||||
const operation = Promise.resolve()
|
||||
.then(() =>
|
||||
dependencies.establishAuthoritativeCheckpoint(
|
||||
@@ -585,59 +562,30 @@ export function createLivePollHandoffCoordinator<Value>(
|
||||
isCheckpointCandidateCurrent(candidate),
|
||||
}),
|
||||
),
|
||||
)
|
||||
.then(
|
||||
(value) => ({ kind: "VALUE" as const, value }),
|
||||
() => ({ kind: "REJECTED" as const }),
|
||||
);
|
||||
// RT-RR-04. Registered at the moment the authority is called, and removed
|
||||
// only when it settles, so `close()` cannot report quiescence over it.
|
||||
checkpointTasks.add(operation);
|
||||
void operation.finally(() => {
|
||||
checkpointTasks.delete(operation);
|
||||
const settled = operation.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
checkpointTasks.add(settled);
|
||||
void settled.then(() => {
|
||||
checkpointTasks.delete(settled);
|
||||
});
|
||||
const timeout = Promise.resolve()
|
||||
.then(async () => {
|
||||
await clock.sleep(
|
||||
limits.quiescenceTimeoutMs,
|
||||
timer.signal,
|
||||
);
|
||||
return { kind: "TIMED_OUT" as const };
|
||||
})
|
||||
.catch(() => ({
|
||||
kind: timer.signal.aborted
|
||||
? ("CANCELED" as const)
|
||||
: ("TIMER_FAILED" as const),
|
||||
}));
|
||||
const selected = await Promise.race([
|
||||
operation,
|
||||
timeout,
|
||||
aborted,
|
||||
]);
|
||||
timer.abort();
|
||||
releaseAbortGate();
|
||||
const selected = await raceRealtimeTask(
|
||||
() => operation,
|
||||
candidate.controller.signal,
|
||||
(signal) => clock.sleep(limits.quiescenceTimeoutMs, signal),
|
||||
);
|
||||
|
||||
if (selected.kind === "ABORTED") {
|
||||
return handoffFailure("ABORTED", "RECOVER");
|
||||
}
|
||||
if (selected.kind === "TIMED_OUT") {
|
||||
if (selected.kind === "TIMEOUT") {
|
||||
candidate.controller.abort();
|
||||
return handoffFailure("IDLE_TIMEOUT", "RECOVER");
|
||||
}
|
||||
if (
|
||||
selected.kind === "TIMER_FAILED" ||
|
||||
selected.kind === "REJECTED"
|
||||
) {
|
||||
candidate.controller.abort();
|
||||
return handoffFailure(
|
||||
"PROVIDER_UNAVAILABLE",
|
||||
"RECOVER",
|
||||
true,
|
||||
);
|
||||
}
|
||||
if (selected.kind === "CANCELED") {
|
||||
return handoffFailure("ABORTED", "RECOVER");
|
||||
}
|
||||
if (selected.kind !== "VALUE") {
|
||||
candidate.controller.abort();
|
||||
return handoffFailure(
|
||||
@@ -673,50 +621,22 @@ export function createLivePollHandoffCoordinator<Value>(
|
||||
async function awaitTaskQuiescence(
|
||||
task: Promise<unknown>,
|
||||
): Promise<QuiescenceOutcome> {
|
||||
const timer = new AbortController();
|
||||
const settled = task.then(
|
||||
() => "QUIESCED" as const,
|
||||
() => "QUIESCED" as const,
|
||||
const outcome = await raceRealtimeTask(
|
||||
() => task,
|
||||
undefined,
|
||||
(signal) => clock.sleep(limits.quiescenceTimeoutMs, signal),
|
||||
);
|
||||
const timeout = Promise.resolve()
|
||||
.then(async () => {
|
||||
await clock.sleep(limits.quiescenceTimeoutMs, timer.signal);
|
||||
return "TIMED_OUT" as const;
|
||||
})
|
||||
.catch(() =>
|
||||
timer.signal.aborted
|
||||
? ("QUIESCED" as const)
|
||||
: ("TIMER_FAILED" as const),
|
||||
);
|
||||
const outcome = await Promise.race([settled, timeout]);
|
||||
timer.abort();
|
||||
return outcome;
|
||||
return outcome.kind === "TIMEOUT"
|
||||
? "TIMED_OUT"
|
||||
: outcome.kind === "CLOCK_FAILED"
|
||||
? "TIMER_FAILED"
|
||||
: "QUIESCED";
|
||||
}
|
||||
|
||||
async function awaitQuiescence(
|
||||
function awaitQuiescence(
|
||||
lease: InternalWriterLease<Value>,
|
||||
): Promise<QuiescenceOutcome> {
|
||||
const timer = new AbortController();
|
||||
const settled = lease.tail.then(
|
||||
() => "QUIESCED" as const,
|
||||
() => "QUIESCED" as const,
|
||||
);
|
||||
const timeout = Promise.resolve()
|
||||
.then(async () => {
|
||||
await clock.sleep(
|
||||
limits.quiescenceTimeoutMs,
|
||||
timer.signal,
|
||||
);
|
||||
return "TIMED_OUT" as const;
|
||||
})
|
||||
.catch(() =>
|
||||
timer.signal.aborted
|
||||
? ("QUIESCED" as const)
|
||||
: ("TIMER_FAILED" as const),
|
||||
);
|
||||
const outcome = await Promise.race([settled, timeout]);
|
||||
timer.abort();
|
||||
return outcome;
|
||||
return awaitTaskQuiescence(lease.tail);
|
||||
}
|
||||
|
||||
function close(): Promise<RealtimeResult<void>> {
|
||||
|
||||
@@ -13,8 +13,12 @@ import {
|
||||
} from "../../../application/ports/realtime/shared.ts";
|
||||
import { systemClock } from "../../platform/system-clock.ts";
|
||||
import {
|
||||
captureRealtimeDataSnapshot,
|
||||
hasExactSnapshotKeys,
|
||||
raceRealtimeTask,
|
||||
realtimeFailure,
|
||||
realtimeSuccess,
|
||||
type RealtimeRace,
|
||||
} from "../result.ts";
|
||||
|
||||
/**
|
||||
@@ -216,7 +220,7 @@ export function createBoundedPollCoordinator<Value>(
|
||||
) {
|
||||
return pollFailure("POLL_BUDGET_EXHAUSTED");
|
||||
}
|
||||
const cadenceOutcome = await awaitTaskOrAbort(
|
||||
const cadenceOutcome = await raceRealtimeTask(
|
||||
() => clock.sleep(nextDelayMs, controller.signal),
|
||||
controller.signal,
|
||||
);
|
||||
@@ -231,7 +235,7 @@ export function createBoundedPollCoordinator<Value>(
|
||||
);
|
||||
return pollFailure(
|
||||
afterSleepFailure ??
|
||||
(cadenceOutcome.kind === "THREW"
|
||||
(cadenceOutcome.kind === "REJECTED"
|
||||
? "PROVIDER_UNAVAILABLE"
|
||||
: "ABORTED"),
|
||||
afterSleepFailure === "OFFLINE",
|
||||
@@ -281,7 +285,7 @@ export function createBoundedPollCoordinator<Value>(
|
||||
);
|
||||
if (attemptOutcome.kind === "VALUE") {
|
||||
result = attemptOutcome.value;
|
||||
} else if (attemptOutcome.kind === "THREW") {
|
||||
} else if (attemptOutcome.kind === "REJECTED") {
|
||||
result = realtimeFailure(
|
||||
controller.signal.aborted ? "ABORTED" : "OFFLINE",
|
||||
"POLL",
|
||||
@@ -347,7 +351,12 @@ export function createBoundedPollCoordinator<Value>(
|
||||
!result.error.retryable ||
|
||||
!isPollRetryableFailureKind(result.error.kind)
|
||||
) {
|
||||
return pollFailure(result.error.kind);
|
||||
// OFFLINE (a thrown executor included) ends this lease but stays
|
||||
// retryable, like every other OFFLINE here.
|
||||
return pollFailure(
|
||||
result.error.kind,
|
||||
result.error.kind === "OFFLINE" && result.error.retryable,
|
||||
);
|
||||
}
|
||||
consecutiveFailures += 1;
|
||||
const failureDelay = retryDelay(
|
||||
@@ -411,7 +420,7 @@ export function createBoundedPollCoordinator<Value>(
|
||||
controller.signal,
|
||||
() => stop("POLL_BUDGET_EXHAUSTED"),
|
||||
);
|
||||
if (applyOutcome.kind === "THREW") {
|
||||
if (applyOutcome.kind === "REJECTED") {
|
||||
return applyFailure();
|
||||
}
|
||||
if (applyOutcome.kind !== "VALUE") {
|
||||
@@ -550,156 +559,24 @@ function currentFailure(
|
||||
return null;
|
||||
}
|
||||
|
||||
type TaskOutcome<Value> =
|
||||
| Readonly<{ kind: "VALUE"; value: Value }>
|
||||
| Readonly<{ kind: "THREW" }>
|
||||
| Readonly<{ kind: "ABORTED" }>;
|
||||
|
||||
type LeaseTaskOutcome<Value> =
|
||||
| TaskOutcome<Value>
|
||||
| Readonly<{ kind: "LEASE_EXPIRED" }>
|
||||
| Readonly<{ kind: "CLOCK_FAILED" }>;
|
||||
|
||||
async function awaitTaskOrAbort<Value>(
|
||||
task: () => Promise<Value>,
|
||||
signal: AbortSignal,
|
||||
): Promise<TaskOutcome<Value>> {
|
||||
if (signal.aborted) return Object.freeze({ kind: "ABORTED" });
|
||||
|
||||
let removeAbortListener: () => void = () => undefined;
|
||||
const aborted = new Promise<Readonly<{ kind: "ABORTED" }>>(
|
||||
(resolve) => {
|
||||
const onAbort = () => resolve(Object.freeze({ kind: "ABORTED" }));
|
||||
signal.addEventListener("abort", onAbort, { once: true });
|
||||
removeAbortListener = () =>
|
||||
signal.removeEventListener("abort", onAbort);
|
||||
if (signal.aborted) onAbort();
|
||||
},
|
||||
);
|
||||
if (signal.aborted) {
|
||||
removeAbortListener();
|
||||
return Object.freeze({ kind: "ABORTED" });
|
||||
}
|
||||
let taskPromise: Promise<Value>;
|
||||
try {
|
||||
taskPromise = task();
|
||||
} catch {
|
||||
removeAbortListener();
|
||||
return Object.freeze({ kind: "THREW" });
|
||||
}
|
||||
const completed = taskPromise.then<
|
||||
TaskOutcome<Value>,
|
||||
TaskOutcome<Value>
|
||||
>(
|
||||
(value) => Object.freeze({ kind: "VALUE", value }),
|
||||
() => Object.freeze({ kind: "THREW" }),
|
||||
);
|
||||
|
||||
try {
|
||||
return await Promise.race([completed, aborted]);
|
||||
} finally {
|
||||
removeAbortListener();
|
||||
}
|
||||
}
|
||||
const LEASE_EXPIRED = Object.freeze({ kind: "TIMEOUT" as const });
|
||||
|
||||
/** Bounds work by the lease's remaining time; expiry stops the whole run. */
|
||||
async function awaitWithinLease<Value>(
|
||||
task: () => Promise<Value>,
|
||||
remainingMs: number,
|
||||
clock: ClockPort,
|
||||
signal: AbortSignal,
|
||||
onLeaseExpired: () => void,
|
||||
): Promise<LeaseTaskOutcome<Value>> {
|
||||
if (!Number.isFinite(remainingMs) || remainingMs <= 0) {
|
||||
onLeaseExpired();
|
||||
return Object.freeze({ kind: "LEASE_EXPIRED" });
|
||||
}
|
||||
if (signal.aborted) return Object.freeze({ kind: "ABORTED" });
|
||||
|
||||
const deadlineController = new AbortController();
|
||||
let resolveInterruption:
|
||||
| ((outcome: LeaseTaskOutcome<Value>) => void)
|
||||
| undefined;
|
||||
let removeAbortListener: () => void = () => undefined;
|
||||
let interruptionSettled = false;
|
||||
const finishInterruption = (
|
||||
outcome: LeaseTaskOutcome<Value>,
|
||||
): boolean => {
|
||||
if (interruptionSettled) return false;
|
||||
interruptionSettled = true;
|
||||
resolveInterruption?.(outcome);
|
||||
return true;
|
||||
};
|
||||
const interrupted = new Promise<LeaseTaskOutcome<Value>>((resolve) => {
|
||||
resolveInterruption = resolve;
|
||||
const onAbort = () =>
|
||||
finishInterruption(Object.freeze({ kind: "ABORTED" }));
|
||||
signal.addEventListener("abort", onAbort, { once: true });
|
||||
removeAbortListener = () =>
|
||||
signal.removeEventListener("abort", onAbort);
|
||||
if (signal.aborted) onAbort();
|
||||
});
|
||||
if (signal.aborted) {
|
||||
removeAbortListener();
|
||||
return Object.freeze({ kind: "ABORTED" });
|
||||
}
|
||||
let deadlineSleep: Promise<void>;
|
||||
try {
|
||||
deadlineSleep = clock.sleep(
|
||||
remainingMs,
|
||||
deadlineController.signal,
|
||||
);
|
||||
} catch {
|
||||
removeAbortListener();
|
||||
deadlineController.abort();
|
||||
return Object.freeze({ kind: "CLOCK_FAILED" });
|
||||
}
|
||||
const deadline = deadlineSleep.then(
|
||||
() => {
|
||||
if (deadlineController.signal.aborted) return;
|
||||
if (
|
||||
finishInterruption(
|
||||
Object.freeze({ kind: "LEASE_EXPIRED" }),
|
||||
): Promise<RealtimeRace<Value>> {
|
||||
const outcome =
|
||||
Number.isFinite(remainingMs) && remainingMs > 0
|
||||
? await raceRealtimeTask(task, signal, (lease) =>
|
||||
clock.sleep(remainingMs, lease),
|
||||
)
|
||||
) {
|
||||
onLeaseExpired();
|
||||
}
|
||||
},
|
||||
() => {
|
||||
if (!deadlineController.signal.aborted) {
|
||||
finishInterruption(
|
||||
Object.freeze({ kind: "CLOCK_FAILED" }),
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
if (signal.aborted) {
|
||||
removeAbortListener();
|
||||
deadlineController.abort();
|
||||
void deadline;
|
||||
return Object.freeze({ kind: "ABORTED" });
|
||||
}
|
||||
let taskPromise: Promise<Value>;
|
||||
try {
|
||||
taskPromise = task();
|
||||
} catch {
|
||||
taskPromise = Promise.reject(new Error("Task failed."));
|
||||
}
|
||||
const completed = taskPromise.then<
|
||||
LeaseTaskOutcome<Value>,
|
||||
LeaseTaskOutcome<Value>
|
||||
>(
|
||||
(value) => Object.freeze({ kind: "VALUE", value }),
|
||||
() => Object.freeze({ kind: "THREW" }),
|
||||
);
|
||||
|
||||
try {
|
||||
const outcome = await Promise.race([completed, interrupted]);
|
||||
void deadline;
|
||||
return outcome;
|
||||
} finally {
|
||||
removeAbortListener();
|
||||
deadlineController.abort();
|
||||
}
|
||||
: LEASE_EXPIRED;
|
||||
if (outcome.kind === "TIMEOUT") onLeaseExpired();
|
||||
return outcome;
|
||||
}
|
||||
|
||||
function parseAttemptResult<Value>(
|
||||
@@ -790,42 +667,10 @@ function snapshotDataRecord(
|
||||
value: unknown,
|
||||
allowedKeySets: readonly (readonly string[])[],
|
||||
): Readonly<Record<string, unknown>> | null {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
if (Object.getPrototypeOf(value) !== Object.prototype) {
|
||||
return null;
|
||||
}
|
||||
const keys = Reflect.ownKeys(value);
|
||||
if (keys.some((key) => typeof key !== "string")) return null;
|
||||
const sortedKeys = (keys as string[]).sort();
|
||||
if (
|
||||
!allowedKeySets.some((allowed) => {
|
||||
const sortedAllowed = [...allowed].sort();
|
||||
return (
|
||||
sortedKeys.length === sortedAllowed.length &&
|
||||
sortedKeys.every(
|
||||
(key, index) => key === sortedAllowed[index],
|
||||
)
|
||||
);
|
||||
})
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const descriptors = Object.getOwnPropertyDescriptors(value);
|
||||
const snapshot: Record<string, unknown> = {};
|
||||
for (const key of sortedKeys) {
|
||||
const descriptor = descriptors[key];
|
||||
if (!descriptor || !Object.hasOwn(descriptor, "value")) {
|
||||
return null;
|
||||
}
|
||||
snapshot[key] = descriptor.value;
|
||||
}
|
||||
return Object.freeze(snapshot);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
const snapshot = captureRealtimeDataSnapshot(value);
|
||||
return snapshot && hasExactSnapshotKeys(snapshot, ...allowedKeySets)
|
||||
? snapshot.values
|
||||
: null;
|
||||
}
|
||||
|
||||
function retryDelay(
|
||||
|
||||
@@ -16,9 +16,14 @@ import {
|
||||
type ReconnectPolicy,
|
||||
} from "./reconnect-policy.ts";
|
||||
import {
|
||||
captureRealtimeDataSnapshot,
|
||||
hasExactSnapshotKeys,
|
||||
isRealtimeResult,
|
||||
isRealtimeTransportEventOutcome,
|
||||
raceRealtimeTask,
|
||||
realtimeFailure,
|
||||
timerDeadline,
|
||||
type RealtimeDataSnapshot,
|
||||
} from "./result.ts";
|
||||
|
||||
type FailureResult = Extract<RealtimeResult<never>, { ok: false }>;
|
||||
@@ -226,12 +231,6 @@ type ParsedCloseClassification =
|
||||
directive: ParsedRecoveryDirective;
|
||||
}>;
|
||||
|
||||
type DataSnapshot = Readonly<{
|
||||
source: object;
|
||||
keys: readonly string[];
|
||||
values: Readonly<Record<string, unknown>>;
|
||||
}>;
|
||||
|
||||
type ParsedRunInput = Readonly<{
|
||||
signal: AbortSignal | undefined;
|
||||
initialRecovery: ParsedRecoveryDirective | null;
|
||||
@@ -590,6 +589,22 @@ export function createRealtimeReconnectCoordinator<ClosedReceipt>(
|
||||
activeRecoveryGate = null;
|
||||
}
|
||||
};
|
||||
/**
|
||||
* Ends this attempt: settles its barrier gate when given a result,
|
||||
* closes the opened session, and aborts and releases the phase.
|
||||
*/
|
||||
const endAttempt = (
|
||||
gateResult: RealtimeResult<void> | null,
|
||||
opened?: RealtimeReconnectSession<ClosedReceipt>,
|
||||
) => {
|
||||
if (gateResult) settleAttemptGate(gateResult);
|
||||
if (opened) {
|
||||
safelyClose(opened);
|
||||
if (session === opened) session = null;
|
||||
}
|
||||
phase.controller.abort();
|
||||
phase.dispose();
|
||||
};
|
||||
const isAttemptCurrent = () =>
|
||||
state === "RUNNING" &&
|
||||
generation === runGeneration &&
|
||||
@@ -653,24 +668,19 @@ export function createRealtimeReconnectCoordinator<ClosedReceipt>(
|
||||
continue;
|
||||
}
|
||||
const interrupted = currentFailure() ?? "ABORTED";
|
||||
settleAttemptGate(recoveryFailure(interrupted));
|
||||
phase.dispose();
|
||||
endAttempt(recoveryFailure(interrupted));
|
||||
return failure(interrupted);
|
||||
}
|
||||
|
||||
const afterAttempt = currentFailure();
|
||||
if (afterAttempt) {
|
||||
closeLateSession(attempted);
|
||||
settleAttemptGate(recoveryFailure(afterAttempt));
|
||||
phase.controller.abort();
|
||||
phase.dispose();
|
||||
endAttempt(recoveryFailure(afterAttempt));
|
||||
return failure(afterAttempt);
|
||||
}
|
||||
if (attemptOffline) {
|
||||
closeLateSession(attempted);
|
||||
settleAttemptGate(recoveryFailure("OFFLINE"));
|
||||
phase.controller.abort();
|
||||
phase.dispose();
|
||||
endAttempt(recoveryFailure("OFFLINE"));
|
||||
retry = offlineRetry(
|
||||
safeNow(clock) ?? beforeAttempt,
|
||||
"CONNECT",
|
||||
@@ -684,9 +694,7 @@ export function createRealtimeReconnectCoordinator<ClosedReceipt>(
|
||||
"CONNECT",
|
||||
pendingRecovery?.terminalFailure.result,
|
||||
);
|
||||
settleAttemptGate(nextRetry.result);
|
||||
phase.controller.abort();
|
||||
phase.dispose();
|
||||
endAttempt(nextRetry.result);
|
||||
retry = nextRetry;
|
||||
continue;
|
||||
}
|
||||
@@ -696,27 +704,19 @@ export function createRealtimeReconnectCoordinator<ClosedReceipt>(
|
||||
);
|
||||
if (!opened) {
|
||||
const mismatch = failure("PROTOCOL_MISMATCH");
|
||||
settleAttemptGate(mismatch);
|
||||
phase.controller.abort();
|
||||
phase.dispose();
|
||||
endAttempt(mismatch);
|
||||
return mismatch;
|
||||
}
|
||||
|
||||
const afterAttemptValidation = currentFailure();
|
||||
if (afterAttemptValidation) {
|
||||
if (opened.ok) safelyClose(opened.value.session);
|
||||
settleAttemptGate(
|
||||
recoveryFailure(afterAttemptValidation),
|
||||
);
|
||||
phase.controller.abort();
|
||||
phase.dispose();
|
||||
endAttempt(recoveryFailure(afterAttemptValidation));
|
||||
return failure(afterAttemptValidation);
|
||||
}
|
||||
|
||||
if (!opened.ok) {
|
||||
settleAttemptGate(opened.failure.result);
|
||||
phase.controller.abort();
|
||||
phase.dispose();
|
||||
endAttempt(opened.failure.result);
|
||||
if (!reconnectable(opened.failure)) {
|
||||
return opened.failure.result;
|
||||
}
|
||||
@@ -743,21 +743,13 @@ export function createRealtimeReconnectCoordinator<ClosedReceipt>(
|
||||
const mismatch = recoveryFailure(
|
||||
"PROTOCOL_MISMATCH",
|
||||
);
|
||||
settleAttemptGate(mismatch);
|
||||
safelyClose(active);
|
||||
phase.controller.abort();
|
||||
phase.dispose();
|
||||
endAttempt(mismatch, active);
|
||||
return mismatch;
|
||||
}
|
||||
|
||||
const beforeConfirmation = currentFailure();
|
||||
if (beforeConfirmation) {
|
||||
settleAttemptGate(
|
||||
recoveryFailure(beforeConfirmation),
|
||||
);
|
||||
safelyClose(active);
|
||||
phase.controller.abort();
|
||||
phase.dispose();
|
||||
endAttempt(recoveryFailure(beforeConfirmation), active);
|
||||
return failure(beforeConfirmation);
|
||||
}
|
||||
|
||||
@@ -773,28 +765,17 @@ export function createRealtimeReconnectCoordinator<ClosedReceipt>(
|
||||
const mismatch = recoveryFailure(
|
||||
"PROTOCOL_MISMATCH",
|
||||
);
|
||||
settleAttemptGate(mismatch);
|
||||
safelyClose(active);
|
||||
phase.controller.abort();
|
||||
phase.dispose();
|
||||
endAttempt(mismatch, active);
|
||||
return mismatch;
|
||||
}
|
||||
|
||||
const afterConfirmation = currentFailure();
|
||||
if (afterConfirmation) {
|
||||
settleAttemptGate(
|
||||
recoveryFailure(afterConfirmation),
|
||||
);
|
||||
safelyClose(active);
|
||||
phase.controller.abort();
|
||||
phase.dispose();
|
||||
endAttempt(recoveryFailure(afterConfirmation), active);
|
||||
return failure(afterConfirmation);
|
||||
}
|
||||
if (!confirmation.ok) {
|
||||
settleAttemptGate(confirmation.failure.result);
|
||||
safelyClose(active);
|
||||
phase.controller.abort();
|
||||
phase.dispose();
|
||||
endAttempt(confirmation.failure.result, active);
|
||||
return confirmation.failure.result;
|
||||
}
|
||||
|
||||
@@ -805,9 +786,7 @@ export function createRealtimeReconnectCoordinator<ClosedReceipt>(
|
||||
} else {
|
||||
settleAttemptGate(noPendingRecovery);
|
||||
if (opened.value.hasRecoveryBarrier) {
|
||||
safelyClose(active);
|
||||
phase.controller.abort();
|
||||
phase.dispose();
|
||||
endAttempt(null, active);
|
||||
return noPendingRecovery;
|
||||
}
|
||||
}
|
||||
@@ -821,9 +800,7 @@ export function createRealtimeReconnectCoordinator<ClosedReceipt>(
|
||||
openedAt,
|
||||
) <= 0
|
||||
) {
|
||||
safelyClose(active);
|
||||
phase.controller.abort();
|
||||
phase.dispose();
|
||||
endAttempt(null, active);
|
||||
return (
|
||||
retry?.terminalResult ??
|
||||
failure("PROVIDER_UNAVAILABLE")
|
||||
@@ -841,10 +818,7 @@ export function createRealtimeReconnectCoordinator<ClosedReceipt>(
|
||||
|
||||
const afterWaitClosed = currentFailure();
|
||||
if (afterWaitClosed) {
|
||||
safelyClose(active);
|
||||
session = null;
|
||||
phase.controller.abort();
|
||||
phase.dispose();
|
||||
endAttempt(null, active);
|
||||
return failure(afterWaitClosed);
|
||||
}
|
||||
if (closed.kind === "INTERRUPTED") {
|
||||
@@ -879,10 +853,7 @@ export function createRealtimeReconnectCoordinator<ClosedReceipt>(
|
||||
}
|
||||
|
||||
if (closeOffline) {
|
||||
safelyClose(active);
|
||||
session = null;
|
||||
phase.controller.abort();
|
||||
phase.dispose();
|
||||
endAttempt(null, active);
|
||||
retry = offlineRetry(
|
||||
safeNow(clock) ?? openedAt,
|
||||
"RECEIVE",
|
||||
@@ -890,10 +861,7 @@ export function createRealtimeReconnectCoordinator<ClosedReceipt>(
|
||||
continue;
|
||||
}
|
||||
if (closed.kind === "THREW") {
|
||||
safelyClose(active);
|
||||
session = null;
|
||||
phase.controller.abort();
|
||||
phase.dispose();
|
||||
endAttempt(null, active);
|
||||
retry = providerRetry(
|
||||
safeNow(clock) ?? openedAt,
|
||||
"RECEIVE",
|
||||
@@ -908,10 +876,7 @@ export function createRealtimeReconnectCoordinator<ClosedReceipt>(
|
||||
rawClassification = null;
|
||||
}
|
||||
const afterClassification = currentFailure();
|
||||
safelyClose(active);
|
||||
session = null;
|
||||
phase.controller.abort();
|
||||
phase.dispose();
|
||||
endAttempt(null, active);
|
||||
if (afterClassification) {
|
||||
return failure(afterClassification);
|
||||
}
|
||||
@@ -1023,65 +988,31 @@ export function createRealtimeReconnectCoordinator<ClosedReceipt>(
|
||||
});
|
||||
}
|
||||
|
||||
const INTERRUPTED = Object.freeze({ kind: "INTERRUPTED" as const });
|
||||
|
||||
async function race<Value>(
|
||||
task: Promise<Settled<Value>>,
|
||||
signal: AbortSignal,
|
||||
): Promise<AwaitedTask<Value>> {
|
||||
if (signal.aborted) return Object.freeze({ kind: "INTERRUPTED" });
|
||||
let cleanup: () => void = () => undefined;
|
||||
const interrupted = new Promise<
|
||||
Readonly<{ kind: "INTERRUPTED" }>
|
||||
>((resolve) => {
|
||||
const abort = () =>
|
||||
resolve(Object.freeze({ kind: "INTERRUPTED" }));
|
||||
signal.addEventListener("abort", abort, { once: true });
|
||||
cleanup = () => signal.removeEventListener("abort", abort);
|
||||
if (signal.aborted) abort();
|
||||
});
|
||||
try {
|
||||
return await Promise.race([task, interrupted]);
|
||||
} finally {
|
||||
cleanup();
|
||||
}
|
||||
const raced = await raceRealtimeTask(() => task, signal);
|
||||
return raced.kind === "VALUE" ? raced.value : INTERRUPTED;
|
||||
}
|
||||
|
||||
async function drainWithinCeiling<Value>(
|
||||
task: Promise<Settled<Value>>,
|
||||
signal: AbortSignal,
|
||||
): Promise<DrainedTask<Value>> {
|
||||
if (signal.aborted) return Object.freeze({ kind: "INTERRUPTED" });
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
let cleanup: () => void = () => undefined;
|
||||
const boundary = new Promise<
|
||||
| Readonly<{ kind: "INTERRUPTED" }>
|
||||
| Readonly<{ kind: "TIMED_OUT" }>
|
||||
>((resolve) => {
|
||||
const abort = () =>
|
||||
resolve(Object.freeze({ kind: "INTERRUPTED" }));
|
||||
cleanup = () => safelyRemoveAbortListener(signal, abort);
|
||||
try {
|
||||
signal.addEventListener("abort", abort, { once: true });
|
||||
timer = setTimeout(
|
||||
() => resolve(Object.freeze({ kind: "TIMED_OUT" })),
|
||||
REALTIME_RECONNECT_CEILINGS.drainTimeoutMs,
|
||||
);
|
||||
} catch {
|
||||
resolve(Object.freeze({ kind: "TIMED_OUT" }));
|
||||
}
|
||||
if (signal.aborted) abort();
|
||||
});
|
||||
try {
|
||||
return await Promise.race([task, boundary]);
|
||||
} finally {
|
||||
cleanup();
|
||||
if (timer !== undefined) {
|
||||
try {
|
||||
clearTimeout(timer);
|
||||
} catch {
|
||||
// The generation remains fenced if host timer cleanup fails.
|
||||
}
|
||||
}
|
||||
}
|
||||
// A host timer, not the clock: a non-cooperative clock is one of the things
|
||||
// this drain has to bound.
|
||||
const raced = await raceRealtimeTask(
|
||||
() => task,
|
||||
signal,
|
||||
timerDeadline(REALTIME_RECONNECT_CEILINGS.drainTimeoutMs),
|
||||
);
|
||||
if (raced.kind === "VALUE") return raced.value;
|
||||
return raced.kind === "ABORTED"
|
||||
? INTERRUPTED
|
||||
: Object.freeze({ kind: "TIMED_OUT" });
|
||||
}
|
||||
|
||||
function createBarrierGate(): BarrierGate {
|
||||
@@ -1104,15 +1035,16 @@ function createBarrierGate(): BarrierGate {
|
||||
}
|
||||
|
||||
function parseRunInput(value: unknown): ParsedRunInput | null {
|
||||
const snapshot = captureDataSnapshot(value);
|
||||
const snapshot = captureRealtimeDataSnapshot(value);
|
||||
if (
|
||||
!snapshot ||
|
||||
!hasOneExactKeySet(snapshot, [
|
||||
!hasExactSnapshotKeys(
|
||||
snapshot,
|
||||
[],
|
||||
["signal"],
|
||||
["initialRecovery"],
|
||||
["initialRecovery", "signal"],
|
||||
])
|
||||
)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
@@ -1130,7 +1062,7 @@ function parseRunInput(value: unknown): ParsedRunInput | null {
|
||||
initialValue === undefined
|
||||
? null
|
||||
: parseRecoveryDirectiveSnapshot(
|
||||
captureDataSnapshot(initialValue),
|
||||
captureRealtimeDataSnapshot(initialValue),
|
||||
);
|
||||
if (initialValue !== undefined && !initialRecovery) return null;
|
||||
return Object.freeze({
|
||||
@@ -1143,28 +1075,29 @@ function parseAttemptOutcome<ClosedReceipt>(
|
||||
value: unknown,
|
||||
): ParsedOutcome<ParsedAttemptSuccess<ClosedReceipt>> | null {
|
||||
return parseOutcomeSnapshot(
|
||||
captureDataSnapshot(value),
|
||||
captureRealtimeDataSnapshot(value),
|
||||
(candidate) =>
|
||||
parseAttemptSuccess<ClosedReceipt>(
|
||||
captureDataSnapshot(candidate),
|
||||
captureRealtimeDataSnapshot(candidate),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function parseAttemptSuccess<ClosedReceipt>(
|
||||
snapshot: DataSnapshot | null,
|
||||
snapshot: RealtimeDataSnapshot | null,
|
||||
): ParsedValue<ParsedAttemptSuccess<ClosedReceipt>> | null {
|
||||
if (
|
||||
!snapshot ||
|
||||
!hasOneExactKeySet(snapshot, [
|
||||
!hasExactSnapshotKeys(
|
||||
snapshot,
|
||||
["session"],
|
||||
["establishedRecoveryBarrier", "session"],
|
||||
])
|
||||
)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const session = parseSession<ClosedReceipt>(
|
||||
captureDataSnapshot(snapshot.values.session),
|
||||
captureRealtimeDataSnapshot(snapshot.values.session),
|
||||
);
|
||||
if (!session) return null;
|
||||
const hasRecoveryBarrier = snapshot.keys.includes(
|
||||
@@ -1181,11 +1114,11 @@ function parseAttemptSuccess<ClosedReceipt>(
|
||||
}
|
||||
|
||||
function parseSession<ClosedReceipt>(
|
||||
snapshot: DataSnapshot | null,
|
||||
snapshot: RealtimeDataSnapshot | null,
|
||||
): RealtimeReconnectSession<ClosedReceipt> | null {
|
||||
if (
|
||||
!snapshot ||
|
||||
!hasExactKeys(snapshot, [
|
||||
!hasExactSnapshotKeys(snapshot, [
|
||||
"classifyClosed",
|
||||
"close",
|
||||
"waitClosed",
|
||||
@@ -1221,7 +1154,7 @@ function parseSession<ClosedReceipt>(
|
||||
function parseCloseClassification(
|
||||
value: unknown,
|
||||
): ParsedCloseClassification | null {
|
||||
const snapshot = captureDataSnapshot(value);
|
||||
const snapshot = captureRealtimeDataSnapshot(value);
|
||||
if (!snapshot) return null;
|
||||
if (snapshot.values.kind === "RECOVERY_RECONNECT") {
|
||||
const directive = parseRecoveryDirectiveSnapshot(snapshot);
|
||||
@@ -1245,11 +1178,12 @@ function parseCloseClassification(
|
||||
}
|
||||
|
||||
function parseRecoveryDirectiveSnapshot(
|
||||
snapshot: DataSnapshot | null,
|
||||
snapshot: RealtimeDataSnapshot | null,
|
||||
): ParsedRecoveryDirective | null {
|
||||
if (
|
||||
!snapshot ||
|
||||
!hasOneExactKeySet(snapshot, [
|
||||
!hasExactSnapshotKeys(
|
||||
snapshot,
|
||||
["kind", "recovery", "terminalResult"],
|
||||
[
|
||||
"kind",
|
||||
@@ -1257,13 +1191,13 @@ function parseRecoveryDirectiveSnapshot(
|
||||
"serverNotBeforeMs",
|
||||
"terminalResult",
|
||||
],
|
||||
]) ||
|
||||
) ||
|
||||
snapshot.values.kind !== "RECOVERY_RECONNECT"
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const recovery = parseCommittedRecovery(
|
||||
captureDataSnapshot(snapshot.values.recovery),
|
||||
captureRealtimeDataSnapshot(snapshot.values.recovery),
|
||||
);
|
||||
const terminalFailure = parseFailureResult(
|
||||
snapshot.values.terminalResult,
|
||||
@@ -1286,32 +1220,32 @@ function parseRecoveryDirectiveSnapshot(
|
||||
}
|
||||
|
||||
function parseCommittedRecovery(
|
||||
snapshot: DataSnapshot | null,
|
||||
snapshot: RealtimeDataSnapshot | null,
|
||||
): RealtimeCommittedRecovery | null {
|
||||
if (
|
||||
!snapshot ||
|
||||
!hasExactKeys(snapshot, [
|
||||
!hasExactSnapshotKeys(snapshot, [
|
||||
"checkpoint",
|
||||
"kind",
|
||||
"streamId",
|
||||
]) ||
|
||||
snapshot.values.kind !== "RECOVERY_COMMITTED" ||
|
||||
!safeFrozen(snapshot.source)
|
||||
!snapshot.frozen
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const checkpoint = captureDataSnapshot(
|
||||
const checkpoint = captureRealtimeDataSnapshot(
|
||||
snapshot.values.checkpoint,
|
||||
);
|
||||
if (
|
||||
!checkpoint ||
|
||||
!hasExactKeys(checkpoint, [
|
||||
!hasExactSnapshotKeys(checkpoint, [
|
||||
"lastAppliedSequence",
|
||||
"recoveryMode",
|
||||
"resumeCursor",
|
||||
"streamEpoch",
|
||||
]) ||
|
||||
!safeFrozen(checkpoint.source)
|
||||
!checkpoint.frozen
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
@@ -1347,22 +1281,23 @@ function parseVoidResult(
|
||||
}
|
||||
|
||||
function parseOutcomeSnapshot<Value>(
|
||||
snapshot: DataSnapshot | null,
|
||||
snapshot: RealtimeDataSnapshot | null,
|
||||
parseValue: (candidate: unknown) => ParsedValue<Value> | null,
|
||||
): ParsedOutcome<Value> | null {
|
||||
if (
|
||||
!snapshot ||
|
||||
!hasOneExactKeySet(snapshot, [
|
||||
!hasExactSnapshotKeys(
|
||||
snapshot,
|
||||
["result"],
|
||||
["result", "serverNotBeforeMs"],
|
||||
])
|
||||
)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const result = parseResult(snapshot.values.result, parseValue);
|
||||
if (!result) return null;
|
||||
if (result.ok) {
|
||||
return hasExactKeys(snapshot, ["result"])
|
||||
return hasExactSnapshotKeys(snapshot, ["result"])
|
||||
? Object.freeze({
|
||||
ok: true,
|
||||
result: result.result,
|
||||
@@ -1385,11 +1320,11 @@ function parseResult<Value>(
|
||||
value: unknown,
|
||||
parseValue: (candidate: unknown) => ParsedValue<Value> | null,
|
||||
): ParsedResult<Value> | null {
|
||||
const snapshot = captureDataSnapshot(value);
|
||||
if (!snapshot || !safeFrozen(snapshot.source)) return null;
|
||||
const snapshot = captureRealtimeDataSnapshot(value);
|
||||
if (!snapshot || !snapshot.frozen) return null;
|
||||
|
||||
if (snapshot.values.ok === true) {
|
||||
if (!hasExactKeys(snapshot, ["ok", "value"])) return null;
|
||||
if (!hasExactSnapshotKeys(snapshot, ["ok", "value"])) return null;
|
||||
const parsedValue = parseValue(snapshot.values.value);
|
||||
const canonical = Object.freeze({
|
||||
ok: true,
|
||||
@@ -1420,29 +1355,29 @@ function parseResult<Value>(
|
||||
function parseFailureResult(
|
||||
value: unknown,
|
||||
): FailureSnapshot | null {
|
||||
return parseFailureResultSnapshot(captureDataSnapshot(value));
|
||||
return parseFailureResultSnapshot(captureRealtimeDataSnapshot(value));
|
||||
}
|
||||
|
||||
function parseFailureResultSnapshot(
|
||||
snapshot: DataSnapshot | null,
|
||||
snapshot: RealtimeDataSnapshot | null,
|
||||
): FailureSnapshot | null {
|
||||
if (
|
||||
!snapshot ||
|
||||
!hasExactKeys(snapshot, ["error", "ok"]) ||
|
||||
!hasExactSnapshotKeys(snapshot, ["error", "ok"]) ||
|
||||
snapshot.values.ok !== false ||
|
||||
!safeFrozen(snapshot.source)
|
||||
!snapshot.frozen
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const error = captureDataSnapshot(snapshot.values.error);
|
||||
const error = captureRealtimeDataSnapshot(snapshot.values.error);
|
||||
if (
|
||||
!error ||
|
||||
!hasExactKeys(error, [
|
||||
!hasExactSnapshotKeys(error, [
|
||||
"kind",
|
||||
"operation",
|
||||
"retryable",
|
||||
]) ||
|
||||
!safeFrozen(error.source)
|
||||
!error.frozen
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
@@ -1472,69 +1407,6 @@ function parseFailureResultSnapshot(
|
||||
});
|
||||
}
|
||||
|
||||
function captureDataSnapshot(value: unknown): DataSnapshot | null {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const prototype = Object.getPrototypeOf(value);
|
||||
if (
|
||||
prototype !== Object.prototype &&
|
||||
prototype !== null
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const descriptors = Object.getOwnPropertyDescriptors(value);
|
||||
const ownKeys = Reflect.ownKeys(descriptors);
|
||||
if (ownKeys.some((key) => typeof key !== "string")) {
|
||||
return null;
|
||||
}
|
||||
const keys = (ownKeys as string[]).sort();
|
||||
const values = Object.create(null) as Record<string, unknown>;
|
||||
for (const key of keys) {
|
||||
const descriptor = descriptors[key];
|
||||
if (
|
||||
!descriptor ||
|
||||
!("value" in descriptor) ||
|
||||
descriptor.enumerable !== true
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
Object.defineProperty(values, key, {
|
||||
configurable: false,
|
||||
enumerable: true,
|
||||
value: descriptor.value,
|
||||
writable: false,
|
||||
});
|
||||
}
|
||||
return Object.freeze({
|
||||
source: value,
|
||||
keys: Object.freeze(keys),
|
||||
values: Object.freeze(values),
|
||||
});
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function hasOneExactKeySet(
|
||||
snapshot: DataSnapshot,
|
||||
expected: readonly (readonly string[])[],
|
||||
): boolean {
|
||||
return expected.some((keys) => hasExactKeys(snapshot, keys));
|
||||
}
|
||||
|
||||
function hasExactKeys(
|
||||
snapshot: DataSnapshot,
|
||||
expected: readonly string[],
|
||||
): boolean {
|
||||
const sorted = [...expected].sort();
|
||||
return (
|
||||
snapshot.keys.length === sorted.length &&
|
||||
snapshot.keys.every((key, index) => key === sorted[index])
|
||||
);
|
||||
}
|
||||
|
||||
function parseNotBefore(
|
||||
value: unknown,
|
||||
): number | null | undefined {
|
||||
@@ -1709,14 +1581,6 @@ function safeSignalAborted(
|
||||
}
|
||||
}
|
||||
|
||||
function safeFrozen(value: object): boolean {
|
||||
try {
|
||||
return Object.isFrozen(value);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function safelyAddAbortListener(
|
||||
signal: AbortSignal | undefined,
|
||||
listener: () => void,
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
export { parseRetryAfterDelay } from "../platform/retry-after.ts";
|
||||
|
||||
export const REALTIME_RECONNECT_CEILINGS = Object.freeze({
|
||||
drainTimeoutMs: 2_000,
|
||||
maxAttempts: 10,
|
||||
@@ -126,57 +128,26 @@ export function reconnectBudgetRemaining(
|
||||
return Math.max(0, policy.maxElapsedMs - (nowMs - startedAtMs));
|
||||
}
|
||||
|
||||
/**
|
||||
* A connection earns a fresh retry budget only when it both proved itself
|
||||
* with a valid heartbeat/event and stayed open for `stableOpenMs`. Either
|
||||
* alone lets a server that sends one comment and drops keep the budget at
|
||||
* zero forever.
|
||||
*/
|
||||
export function isReconnectAttemptResetEligible(input: Readonly<{
|
||||
policy: ReconnectPolicy;
|
||||
openedAtMs: number;
|
||||
nowMs: number;
|
||||
observedValidHeartbeatOrEvent: boolean;
|
||||
}>): boolean {
|
||||
if (input.observedValidHeartbeatOrEvent) return true;
|
||||
return (
|
||||
input.observedValidHeartbeatOrEvent &&
|
||||
Number.isFinite(input.openedAtMs) &&
|
||||
Number.isFinite(input.nowMs) &&
|
||||
input.nowMs - input.openedAtMs >= input.policy.stableOpenMs
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses the HTTP Retry-After delay without applying a runtime ceiling.
|
||||
* Callers must reject a value that exceeds their remaining/max-delay budget.
|
||||
*/
|
||||
export function parseRetryAfterDelay(
|
||||
value: string | null | undefined,
|
||||
nowEpochMs: number,
|
||||
): number | null {
|
||||
if (
|
||||
typeof value !== "string" ||
|
||||
value.length === 0 ||
|
||||
value.length > 128 ||
|
||||
!Number.isFinite(nowEpochMs)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const normalized = value.trim();
|
||||
if (/^\d+$/u.test(normalized)) {
|
||||
const seconds = Number(normalized);
|
||||
return Number.isSafeInteger(seconds) &&
|
||||
seconds <= Math.floor(Number.MAX_SAFE_INTEGER / 1_000)
|
||||
? seconds * 1_000
|
||||
: null;
|
||||
}
|
||||
if (
|
||||
!/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), \d{2} (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{4} \d{2}:\d{2}:\d{2} GMT$/u.test(
|
||||
normalized,
|
||||
)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const timestamp = Date.parse(normalized);
|
||||
return Number.isFinite(timestamp)
|
||||
? Math.max(0, timestamp - nowEpochMs)
|
||||
: null;
|
||||
}
|
||||
|
||||
function positiveInteger(value: number): boolean {
|
||||
return Number.isSafeInteger(value) && value > 0;
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
isRealtimeOpaqueIdentifier,
|
||||
isRealtimeResumeCursor,
|
||||
} from "../../contracts/realtime-events.ts";
|
||||
import { createAbortableOperation } from "../platform/abortable-operation.ts";
|
||||
|
||||
export type {
|
||||
RealtimeFailure,
|
||||
@@ -35,6 +36,8 @@ const FAILURE_KINDS = new Set<unknown>(REALTIME_FAILURE_KINDS);
|
||||
const OPERATIONS = new Set<unknown>(REALTIME_OPERATIONS);
|
||||
|
||||
export type RealtimeDataSnapshot = Readonly<{
|
||||
/** The object that was read; never read its properties again. */
|
||||
source: object;
|
||||
keys: readonly string[];
|
||||
values: Readonly<Record<string, unknown>>;
|
||||
frozen: boolean;
|
||||
@@ -67,6 +70,100 @@ export function isRealtimeFailure(
|
||||
return parseRealtimeFailure(value, true) !== null;
|
||||
}
|
||||
|
||||
export type RealtimeRace<Value> =
|
||||
| Readonly<{ kind: "VALUE"; value: Value }>
|
||||
| Readonly<{ kind: "REJECTED" }>
|
||||
| Readonly<{ kind: "ABORTED" }>
|
||||
| Readonly<{ kind: "TIMEOUT" }>
|
||||
| Readonly<{ kind: "CLOCK_FAILED" }>;
|
||||
|
||||
const REJECTED = Object.freeze({ kind: "REJECTED" as const });
|
||||
const ABORTED = Object.freeze({ kind: "ABORTED" as const });
|
||||
const TIMEOUT = Object.freeze({ kind: "TIMEOUT" as const });
|
||||
const CLOCK_FAILED = Object.freeze({ kind: "CLOCK_FAILED" as const });
|
||||
|
||||
/**
|
||||
* Realtime's one abort/deadline race, on the kernel abortable operation.
|
||||
* Settles with whichever comes first: the task's value or rejection (a
|
||||
* synchronous throw counts as one), `signal` aborting, or `deadline`
|
||||
* resolving. A deadline that throws or rejects on its own is CLOCK_FAILED.
|
||||
* Nothing starts when `signal` is already aborted.
|
||||
*
|
||||
* The task gets the operation signal, which aborts with `signal`, at the
|
||||
* deadline and once the race is over. The deadline is armed before the task
|
||||
* starts, so it wins a tie, but the task always starts (a cancel must not be
|
||||
* skipped because the clock broke).
|
||||
*/
|
||||
export function raceRealtimeTask<Value>(
|
||||
task: (signal: AbortSignal) => Value | PromiseLike<Value>,
|
||||
signal?: AbortSignal,
|
||||
deadline?: (signal: AbortSignal) => PromiseLike<unknown>,
|
||||
): Promise<RealtimeRace<Value>> {
|
||||
if (signal?.aborted) return Promise.resolve(ABORTED);
|
||||
const timer = new AbortController();
|
||||
const operation = createAbortableOperation({
|
||||
signal,
|
||||
...(deadline && {
|
||||
timeoutMs: 0,
|
||||
setTimer: (fire: () => void) =>
|
||||
Promise.resolve(deadline(timer.signal)).then(fire, () =>
|
||||
operation.close(),
|
||||
),
|
||||
clearTimer: () => timer.abort(),
|
||||
}),
|
||||
});
|
||||
let running: Promise<Value>;
|
||||
try {
|
||||
running = Promise.resolve(task(operation.signal));
|
||||
} catch (error) {
|
||||
running = Promise.reject(error);
|
||||
}
|
||||
const raced = operation.race(running);
|
||||
// Registered after the race, so the outcome is claimed first.
|
||||
void running.then(operation.close, operation.close);
|
||||
return raced.then((outcome) =>
|
||||
outcome.kind === "VALUE"
|
||||
? outcome
|
||||
: outcome.kind === "REJECTED"
|
||||
? REJECTED
|
||||
: outcome.terminal === "CALLER_ABORT"
|
||||
? ABORTED
|
||||
: outcome.terminal === "DEADLINE"
|
||||
? TIMEOUT
|
||||
: CLOCK_FAILED,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A `raceRealtimeTask` deadline on a host timer instead of the injected
|
||||
* clock, for bounds that must hold even when the clock itself hangs.
|
||||
*/
|
||||
export function timerDeadline(
|
||||
delayMs: number,
|
||||
schedule: (callback: () => void, delayMs: number) => unknown = (
|
||||
callback,
|
||||
delay,
|
||||
) => setTimeout(callback, delay),
|
||||
cancel: (handle: unknown) => void = (handle) =>
|
||||
clearTimeout(handle as ReturnType<typeof setTimeout>),
|
||||
): (signal: AbortSignal) => Promise<void> {
|
||||
return (signal) =>
|
||||
new Promise((resolve) => {
|
||||
const handle = schedule(resolve, delayMs);
|
||||
signal.addEventListener(
|
||||
"abort",
|
||||
() => {
|
||||
try {
|
||||
cancel(handle);
|
||||
} catch {
|
||||
// A broken scheduler cannot change the race outcome.
|
||||
}
|
||||
},
|
||||
{ once: true },
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Captures an external result through own data descriptors exactly once and
|
||||
* returns a new canonical value. Callers that need to use the validated fields
|
||||
@@ -186,6 +283,7 @@ export function captureRealtimeDataSnapshot(
|
||||
descriptor.writable === false;
|
||||
}
|
||||
return Object.freeze({
|
||||
source: value,
|
||||
keys: Object.freeze(keys),
|
||||
values: Object.freeze(values),
|
||||
frozen,
|
||||
@@ -266,13 +364,16 @@ function parseRealtimeFailure(
|
||||
});
|
||||
}
|
||||
|
||||
function hasExactSnapshotKeys(
|
||||
/** True when the snapshot's keys are exactly one of the given key sets. */
|
||||
export function hasExactSnapshotKeys(
|
||||
snapshot: RealtimeDataSnapshot,
|
||||
expectedKeys: readonly string[],
|
||||
...keySets: readonly (readonly string[])[]
|
||||
): boolean {
|
||||
const expected = [...expectedKeys].sort();
|
||||
return (
|
||||
snapshot.keys.length === expected.length &&
|
||||
snapshot.keys.every((key, index) => key === expected[index])
|
||||
);
|
||||
return keySets.some((keySet) => {
|
||||
const expected = [...keySet].sort();
|
||||
return (
|
||||
snapshot.keys.length === expected.length &&
|
||||
snapshot.keys.every((key, index) => key === expected[index])
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ import { parseRetryAfterDelay } from "../reconnect-policy.ts";
|
||||
import {
|
||||
isRealtimeResult,
|
||||
isRealtimeTransportEventOutcome,
|
||||
raceRealtimeTask,
|
||||
realtimeFailure,
|
||||
realtimeSuccess,
|
||||
} from "../result.ts";
|
||||
@@ -100,6 +101,7 @@ const MAX_CONNECT_TIMEOUT_MS = 30_000;
|
||||
const MAX_IDLE_TIMEOUT_MS = 120_000;
|
||||
const MAX_CURSOR_BYTES = 1_024;
|
||||
const READER_CANCEL_TIMEOUT_MS = 2_000;
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
export function createFetchSseConnection(
|
||||
dependencies: FetchSseConnectionDependencies,
|
||||
@@ -162,30 +164,36 @@ export function createFetchSseConnection(
|
||||
once: true,
|
||||
});
|
||||
if (input.signal?.aborted) onCallerAbort();
|
||||
const timed = <Value>(
|
||||
task: () => Value | PromiseLike<Value>,
|
||||
timeoutMs: number,
|
||||
) =>
|
||||
raceRealtimeTask(task, controller.signal, (signal) =>
|
||||
clock.sleep(timeoutMs, signal),
|
||||
);
|
||||
|
||||
try {
|
||||
const request = timed(
|
||||
Promise.resolve().then(() =>
|
||||
fetcher(endpoint.href, {
|
||||
method: "GET",
|
||||
credentials: "same-origin",
|
||||
redirect: "error",
|
||||
cache: "no-store",
|
||||
referrerPolicy: "no-referrer",
|
||||
headers: {
|
||||
Accept: "text/event-stream",
|
||||
...(input.resumeCursor === null
|
||||
? {}
|
||||
: { "Last-Event-ID": input.resumeCursor }),
|
||||
},
|
||||
signal: controller.signal,
|
||||
}),
|
||||
),
|
||||
const responseResult = await timed(
|
||||
// The fetcher starts on the next microtask, like other collaborators.
|
||||
() =>
|
||||
Promise.resolve().then(() =>
|
||||
fetcher(endpoint.href, {
|
||||
method: "GET",
|
||||
credentials: "same-origin",
|
||||
redirect: "error",
|
||||
cache: "no-store",
|
||||
referrerPolicy: "no-referrer",
|
||||
headers: {
|
||||
Accept: "text/event-stream",
|
||||
...(input.resumeCursor === null
|
||||
? {}
|
||||
: { "Last-Event-ID": input.resumeCursor }),
|
||||
},
|
||||
signal: controller.signal,
|
||||
}),
|
||||
),
|
||||
connectTimeoutMs,
|
||||
clock,
|
||||
controller.signal,
|
||||
);
|
||||
const responseResult = await request;
|
||||
if (responseResult.kind === "CLOCK_FAILED") {
|
||||
controller.abort();
|
||||
return failed("PROVIDER_UNAVAILABLE", "CONNECT", true);
|
||||
@@ -241,23 +249,11 @@ export function createFetchSseConnection(
|
||||
const reader = response.body.getReader();
|
||||
activeReader = reader;
|
||||
let retryHintMs: number | null = null;
|
||||
if (input.onOpen) {
|
||||
let opening: Promise<RealtimeResult<void>>;
|
||||
try {
|
||||
opening = Promise.resolve(input.onOpen(controller.signal));
|
||||
} catch {
|
||||
await cancelReader(reader, clock, controller);
|
||||
return failed(
|
||||
"PROVIDER_UNAVAILABLE",
|
||||
"CONNECT",
|
||||
false,
|
||||
);
|
||||
}
|
||||
const onOpen = input.onOpen;
|
||||
if (onOpen) {
|
||||
const opened = await timed(
|
||||
opening,
|
||||
() => onOpen(controller.signal),
|
||||
connectTimeoutMs,
|
||||
clock,
|
||||
controller.signal,
|
||||
);
|
||||
if (opened.kind !== "VALUE") {
|
||||
await cancelReader(reader, clock, controller);
|
||||
@@ -305,7 +301,7 @@ export function createFetchSseConnection(
|
||||
(!item.hasExplicitId ||
|
||||
!item.id ||
|
||||
!isRealtimeResumeCursor(item.id) ||
|
||||
new TextEncoder().encode(item.id).byteLength >
|
||||
encoder.encode(item.id).byteLength >
|
||||
maxCursorBytes)
|
||||
) {
|
||||
await cancelReader(reader, clock, controller);
|
||||
@@ -318,22 +314,9 @@ export function createFetchSseConnection(
|
||||
await cancelReader(reader, clock, controller);
|
||||
return failed("PROTOCOL_MISMATCH", "DECODE", false);
|
||||
}
|
||||
let handler: Promise<
|
||||
RealtimeResult<SseInboundEventOutcome>
|
||||
>;
|
||||
try {
|
||||
handler = Promise.resolve(
|
||||
input.onEvent(item, controller.signal),
|
||||
);
|
||||
} catch {
|
||||
await cancelReader(reader, clock, controller);
|
||||
return failed("APPLY_FAILED", "APPLY", false);
|
||||
}
|
||||
const handled = await timed(
|
||||
handler,
|
||||
() => input.onEvent(item, controller.signal),
|
||||
idleTimeoutMs,
|
||||
clock,
|
||||
controller.signal,
|
||||
);
|
||||
if (handled.kind === "ABORTED") {
|
||||
await cancelReader(reader, clock, controller);
|
||||
@@ -384,10 +367,8 @@ export function createFetchSseConnection(
|
||||
|
||||
while (true) {
|
||||
const readResult = await timed(
|
||||
reader.read(),
|
||||
() => reader.read(),
|
||||
idleTimeoutMs,
|
||||
clock,
|
||||
controller.signal,
|
||||
);
|
||||
if (readResult.kind === "ABORTED") {
|
||||
await cancelReader(reader, clock, controller);
|
||||
@@ -434,13 +415,20 @@ export function createFetchSseConnection(
|
||||
await cancelReader(reader, clock, controller);
|
||||
return failed("MALFORMED_EVENT", "DECODE", false);
|
||||
}
|
||||
const parsed = parser.push(readResult.value.value);
|
||||
if (!parsed.ok) {
|
||||
await cancelReader(reader, clock, controller);
|
||||
return parsed;
|
||||
// Items past the parser's per-call cap arrive through drain().
|
||||
for (
|
||||
let parsed = parser.push(readResult.value.value);
|
||||
;
|
||||
parsed = parser.drain()
|
||||
) {
|
||||
if (!parsed.ok) {
|
||||
await cancelReader(reader, clock, controller);
|
||||
return parsed;
|
||||
}
|
||||
if (parsed.value.length === 0) break;
|
||||
const dispatchFailure = await handleParserItems(parsed.value);
|
||||
if (dispatchFailure) return dispatchFailure;
|
||||
}
|
||||
const dispatchFailure = await handleParserItems(parsed.value);
|
||||
if (dispatchFailure) return dispatchFailure;
|
||||
}
|
||||
} catch {
|
||||
return failed(
|
||||
@@ -532,7 +520,7 @@ function validResumeCursor(
|
||||
return (
|
||||
typeof cursor === "string" &&
|
||||
isRealtimeResumeCursor(cursor) &&
|
||||
new TextEncoder().encode(cursor).byteLength <= maxCursorBytes
|
||||
encoder.encode(cursor).byteLength <= maxCursorBytes
|
||||
);
|
||||
}
|
||||
|
||||
@@ -591,66 +579,6 @@ function responseFailure(
|
||||
return failed("PROTOCOL_MISMATCH", "CONNECT", false);
|
||||
}
|
||||
|
||||
type TimedResult<Value> =
|
||||
| Readonly<{ kind: "VALUE"; value: Value }>
|
||||
| Readonly<{ kind: "REJECTED" }>
|
||||
| Readonly<{ kind: "ABORTED" }>
|
||||
| Readonly<{ kind: "CLOCK_FAILED" }>
|
||||
| Readonly<{ kind: "TIMEOUT" }>;
|
||||
|
||||
async function timed<Value>(
|
||||
operation: Promise<Value>,
|
||||
timeoutMs: number,
|
||||
clock: ClockPort,
|
||||
signal: AbortSignal,
|
||||
): Promise<TimedResult<Value>> {
|
||||
if (signal.aborted) {
|
||||
return Object.freeze({ kind: "ABORTED" });
|
||||
}
|
||||
const timer = new AbortController();
|
||||
let abortListener: (() => void) | undefined;
|
||||
const operationResult = operation.then<
|
||||
TimedResult<Value>,
|
||||
TimedResult<Value>
|
||||
>(
|
||||
(value) => Object.freeze({ kind: "VALUE", value }),
|
||||
() => Object.freeze({ kind: "REJECTED" }),
|
||||
);
|
||||
let timeoutResult: Promise<TimedResult<Value>>;
|
||||
try {
|
||||
timeoutResult = clock.sleep(timeoutMs, timer.signal).then<
|
||||
TimedResult<Value>,
|
||||
TimedResult<Value>
|
||||
>(
|
||||
() => Object.freeze({ kind: "TIMEOUT" }),
|
||||
() =>
|
||||
Object.freeze({
|
||||
kind: timer.signal.aborted
|
||||
? ("ABORTED" as const)
|
||||
: ("CLOCK_FAILED" as const),
|
||||
}),
|
||||
);
|
||||
} catch {
|
||||
return Object.freeze({ kind: "CLOCK_FAILED" });
|
||||
}
|
||||
const abortedResult = new Promise<TimedResult<Value>>((resolve) => {
|
||||
abortListener = () =>
|
||||
resolve(Object.freeze({ kind: "ABORTED" }));
|
||||
signal.addEventListener("abort", abortListener, { once: true });
|
||||
if (signal.aborted) abortListener();
|
||||
});
|
||||
const result = await Promise.race([
|
||||
operationResult,
|
||||
timeoutResult,
|
||||
abortedResult,
|
||||
]);
|
||||
timer.abort();
|
||||
if (abortListener) {
|
||||
signal.removeEventListener("abort", abortListener);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function readClockNow(clock: ClockPort): number | null {
|
||||
try {
|
||||
const value = clock.now();
|
||||
@@ -666,29 +594,11 @@ async function cancelReader(
|
||||
generation?: AbortController,
|
||||
): Promise<void> {
|
||||
generation?.abort();
|
||||
let cancellation: Promise<void>;
|
||||
try {
|
||||
cancellation = Promise.resolve(reader.cancel()).then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
const timeout = new AbortController();
|
||||
let timeoutPromise: Promise<void>;
|
||||
try {
|
||||
timeoutPromise = clock
|
||||
.sleep(READER_CANCEL_TIMEOUT_MS, timeout.signal)
|
||||
.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
} catch {
|
||||
timeoutPromise = Promise.resolve();
|
||||
}
|
||||
await Promise.race([cancellation, timeoutPromise]);
|
||||
timeout.abort();
|
||||
await raceRealtimeTask(
|
||||
() => reader.cancel(),
|
||||
undefined,
|
||||
(signal) => clock.sleep(READER_CANCEL_TIMEOUT_MS, signal),
|
||||
);
|
||||
}
|
||||
|
||||
function safelyNotify(
|
||||
|
||||
@@ -14,6 +14,10 @@ export const SSE_PARSER_CEILINGS = Object.freeze({
|
||||
});
|
||||
|
||||
const LINE_BREAK = /[\r\n]/gu;
|
||||
const NO_ITEMS: readonly SseParserItem[] = Object.freeze([]);
|
||||
const COMMENT_ITEMS: readonly SseParserItem[] = Object.freeze([
|
||||
Object.freeze({ kind: "COMMENT" as const }),
|
||||
]);
|
||||
|
||||
export type SseParserLimits = Readonly<{
|
||||
maxLineBytes: number;
|
||||
@@ -47,7 +51,13 @@ export type SseParserFinish = Readonly<{
|
||||
}>;
|
||||
|
||||
export type IncrementalSseParser = Readonly<{
|
||||
/**
|
||||
* Returns at most `maxItemsPerChunk` items. Text past that cap is kept and
|
||||
* must be taken with `drain()` until it returns no items; pushing or
|
||||
* finishing before then fails with QUEUE_OVERFLOW.
|
||||
*/
|
||||
push(chunk: Uint8Array): RealtimeResult<readonly SseParserItem[]>;
|
||||
drain(): RealtimeResult<readonly SseParserItem[]>;
|
||||
finish(): RealtimeResult<SseParserFinish>;
|
||||
}>;
|
||||
|
||||
@@ -55,6 +65,8 @@ export function createIncrementalSseParser(
|
||||
limits: Partial<SseParserLimits> = {},
|
||||
): IncrementalSseParser {
|
||||
const resolved = resolveLimits(limits);
|
||||
// ignoreBOM: false makes the decoder strip the one leading BOM the
|
||||
// stream grammar allows; a second one is ordinary text.
|
||||
const decoder = new TextDecoder("utf-8", {
|
||||
fatal: true,
|
||||
ignoreBOM: false,
|
||||
@@ -62,10 +74,10 @@ export function createIncrementalSseParser(
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
let state: "OPEN" | "FAILED" | "FINISHED" = "OPEN";
|
||||
let atStart = true;
|
||||
let pendingCarriageReturn = false;
|
||||
let line = "";
|
||||
let lineBytes = 0;
|
||||
let undrained = "";
|
||||
let blockBytes = 0;
|
||||
let dataLines: string[] = [];
|
||||
let eventType = "";
|
||||
@@ -84,6 +96,7 @@ export function createIncrementalSseParser(
|
||||
if (chunk.byteLength > resolved.maxChunkBytes) {
|
||||
return fail("EVENT_TOO_LARGE");
|
||||
}
|
||||
if (undrained.length > 0) return fail("QUEUE_OVERFLOW");
|
||||
let text: string;
|
||||
try {
|
||||
text = decoder.decode(chunk, { stream: true });
|
||||
@@ -93,10 +106,20 @@ export function createIncrementalSseParser(
|
||||
return consumeText(text);
|
||||
}
|
||||
|
||||
function drain(): RealtimeResult<readonly SseParserItem[]> {
|
||||
if (state !== "OPEN") {
|
||||
return realtimeFailure("CLOSED", "DECODE");
|
||||
}
|
||||
const text = undrained;
|
||||
undrained = "";
|
||||
return consumeText(text);
|
||||
}
|
||||
|
||||
function finish(): RealtimeResult<SseParserFinish> {
|
||||
if (state !== "OPEN") {
|
||||
return realtimeFailure("CLOSED", "DECODE");
|
||||
}
|
||||
if (undrained.length > 0) return fail("QUEUE_OVERFLOW");
|
||||
let tail: string;
|
||||
try {
|
||||
tail = decoder.decode();
|
||||
@@ -110,9 +133,13 @@ export function createIncrementalSseParser(
|
||||
pendingCarriageReturn = false;
|
||||
const processed = processLine(1);
|
||||
if (!processed.ok) return processed;
|
||||
if (!appendItems(items, processed.value)) {
|
||||
return fail("QUEUE_OVERFLOW");
|
||||
}
|
||||
items.push(...processed.value);
|
||||
}
|
||||
if (
|
||||
undrained.length > 0 ||
|
||||
items.length > resolved.maxItemsPerChunk
|
||||
) {
|
||||
return fail("QUEUE_OVERFLOW");
|
||||
}
|
||||
const incompleteEventDiscarded =
|
||||
lineBytes > 0 ||
|
||||
@@ -136,31 +163,27 @@ export function createIncrementalSseParser(
|
||||
* Works a line at a time: find the next CR/LF, append the text before it
|
||||
* and count its UTF-8 bytes once. Byte counts only grow within a line, so
|
||||
* checking the limits per segment fails exactly where a per-character check
|
||||
* would.
|
||||
* would. Stops at `maxItemsPerChunk` items and keeps the rest for `drain()`.
|
||||
*/
|
||||
function consumeText(
|
||||
text: string,
|
||||
): RealtimeResult<readonly SseParserItem[]> {
|
||||
const items: SseParserItem[] = [];
|
||||
let index = 0;
|
||||
if (atStart && text.length > 0) {
|
||||
atStart = false;
|
||||
if (text.charCodeAt(0) === 0xfeff) index = 1;
|
||||
}
|
||||
|
||||
while (index < text.length) {
|
||||
if (items.length >= resolved.maxItemsPerChunk) {
|
||||
undrained = text.slice(index);
|
||||
break;
|
||||
}
|
||||
if (pendingCarriageReturn) {
|
||||
pendingCarriageReturn = false;
|
||||
const lineFeed = text.charCodeAt(index) === 0x0a;
|
||||
const processed = processLine(lineFeed ? 2 : 1);
|
||||
if (!processed.ok) return processed;
|
||||
if (!appendItems(items, processed.value)) {
|
||||
return fail("QUEUE_OVERFLOW");
|
||||
}
|
||||
if (lineFeed) {
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
items.push(...processed.value);
|
||||
if (lineFeed) index += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
LINE_BREAK.lastIndex = index;
|
||||
@@ -185,9 +208,7 @@ export function createIncrementalSseParser(
|
||||
}
|
||||
const processed = processLine(1);
|
||||
if (!processed.ok) return processed;
|
||||
if (!appendItems(items, processed.value)) {
|
||||
return fail("QUEUE_OVERFLOW");
|
||||
}
|
||||
items.push(...processed.value);
|
||||
}
|
||||
return success(Object.freeze(items));
|
||||
}
|
||||
@@ -217,13 +238,7 @@ export function createIncrementalSseParser(
|
||||
return success(Object.freeze(items));
|
||||
}
|
||||
|
||||
if (currentLine.startsWith(":")) {
|
||||
return success(
|
||||
Object.freeze([
|
||||
Object.freeze({ kind: "COMMENT" as const }),
|
||||
]),
|
||||
);
|
||||
}
|
||||
if (currentLine.startsWith(":")) return success(COMMENT_ITEMS);
|
||||
|
||||
blockBytes += currentLineBytes + terminatorBytes;
|
||||
if (blockBytes > resolved.maxEventBytes) {
|
||||
@@ -244,18 +259,18 @@ export function createIncrementalSseParser(
|
||||
|
||||
if (field === "data") {
|
||||
dataLines.push(value);
|
||||
return success(Object.freeze([]));
|
||||
return success(NO_ITEMS);
|
||||
}
|
||||
if (field === "event") {
|
||||
eventType = value;
|
||||
return success(Object.freeze([]));
|
||||
return success(NO_ITEMS);
|
||||
}
|
||||
if (field === "id") {
|
||||
if (!value.includes("\0")) {
|
||||
lastEventId = value;
|
||||
hasExplicitId = true;
|
||||
}
|
||||
return success(Object.freeze([]));
|
||||
return success(NO_ITEMS);
|
||||
}
|
||||
if (field === "retry" && /^\d+$/u.test(value)) {
|
||||
const retryMs = Number(value);
|
||||
@@ -270,7 +285,7 @@ export function createIncrementalSseParser(
|
||||
);
|
||||
}
|
||||
}
|
||||
return success(Object.freeze([]));
|
||||
return success(NO_ITEMS);
|
||||
}
|
||||
|
||||
function clearBlock(): void {
|
||||
@@ -289,25 +304,12 @@ export function createIncrementalSseParser(
|
||||
state = "FAILED";
|
||||
line = "";
|
||||
lineBytes = 0;
|
||||
undrained = "";
|
||||
clearBlock();
|
||||
return realtimeFailure(kind, "DECODE");
|
||||
}
|
||||
|
||||
function appendItems(
|
||||
target: SseParserItem[],
|
||||
additions: readonly SseParserItem[],
|
||||
): boolean {
|
||||
if (
|
||||
target.length + additions.length >
|
||||
resolved.maxItemsPerChunk
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
target.push(...additions);
|
||||
return true;
|
||||
}
|
||||
|
||||
return Object.freeze({ push, finish });
|
||||
return Object.freeze({ push, drain, finish });
|
||||
}
|
||||
|
||||
function resolveLimits(
|
||||
|
||||
@@ -35,6 +35,9 @@ import {
|
||||
} from "./event-codec.ts";
|
||||
import {
|
||||
captureRealtimeDataSnapshot,
|
||||
hasExactSnapshotKeys,
|
||||
raceRealtimeTask,
|
||||
timerDeadline,
|
||||
realtimeFailure,
|
||||
realtimeSuccess,
|
||||
snapshotRealtimeResult,
|
||||
@@ -184,15 +187,8 @@ export function createRealtimeStreamCoordinator(
|
||||
});
|
||||
const states = new Map<StreamRegistrationId, StreamState>();
|
||||
let closed = false;
|
||||
|
||||
/** RT-02. Releasing a timer is best effort and never a public failure. */
|
||||
const clearTimerSafely = (handle: unknown): void => {
|
||||
try {
|
||||
clearScheduledTimeout(handle);
|
||||
} catch {
|
||||
// A broken scheduler cannot change an already classified outcome.
|
||||
}
|
||||
};
|
||||
const deadline = (delayMs: number) =>
|
||||
timerDeadline(delayMs, scheduleTimeout, clearScheduledTimeout);
|
||||
|
||||
const TASK_TIMED_OUT = Symbol("REALTIME_TASK_TIMED_OUT");
|
||||
|
||||
@@ -227,26 +223,18 @@ export function createRealtimeStreamCoordinator(
|
||||
if (!state.closed) state.freshness = "STALE";
|
||||
}
|
||||
});
|
||||
// RT-02. A scheduler that cannot install the deadline leaves the wait
|
||||
// unbounded. Letting the exception escape turned a typed realtime result
|
||||
// into a native rejection and — through the caller's own catch — started a
|
||||
// recovery that overlapped the effect still running, so an install failure
|
||||
// fails closed as an expired deadline instead.
|
||||
let handle: unknown;
|
||||
let installed = false;
|
||||
const timeout = new Promise<typeof TASK_TIMED_OUT>((resolve) => {
|
||||
try {
|
||||
handle = scheduleTimeout(() => resolve(TASK_TIMED_OUT), timeoutMs);
|
||||
installed = true;
|
||||
} catch {
|
||||
resolve(TASK_TIMED_OUT);
|
||||
}
|
||||
});
|
||||
const outcome = await Promise.race([task, timeout]);
|
||||
if (installed) clearTimerSafely(handle);
|
||||
if (outcome !== TASK_TIMED_OUT) return outcome;
|
||||
|
||||
// The commit capability is revoked immediately; the work itself is not.
|
||||
const outcome = await raceRealtimeTask(
|
||||
() => task,
|
||||
undefined,
|
||||
deadline(timeoutMs),
|
||||
);
|
||||
if (outcome.kind === "VALUE") return outcome.value;
|
||||
// The collaborator's own rejection reaches the caller unchanged.
|
||||
if (outcome.kind === "REJECTED") return await task;
|
||||
// Expired, or (RT-02) a scheduler that could not install the deadline and
|
||||
// left the wait unbounded: both fail closed as an expired deadline, not a
|
||||
// native rejection that would start an overlapping recovery. The commit
|
||||
// capability is revoked immediately; the work itself is not.
|
||||
revokeAndAbort();
|
||||
state.lifecycle = "DRAINING";
|
||||
state.timedOutTasks.add(task);
|
||||
@@ -487,20 +475,6 @@ export function createRealtimeStreamCoordinator(
|
||||
signal,
|
||||
);
|
||||
}
|
||||
if (
|
||||
state.eventIds.size + 1 >
|
||||
state.registration.limits.maxDedupeEntries ||
|
||||
state.dedupeBytes + event.fingerprintBytes >
|
||||
state.registration.limits.maxDedupeBytes
|
||||
) {
|
||||
return recoverForAccept(
|
||||
state,
|
||||
"DEDUPE_OVERFLOW",
|
||||
true,
|
||||
signal,
|
||||
);
|
||||
}
|
||||
|
||||
const eventType = dependencies.registry.findStreamEventType(
|
||||
state.registration.id,
|
||||
event.envelope.eventType,
|
||||
@@ -626,6 +600,17 @@ export function createRealtimeStreamCoordinator(
|
||||
fingerprintBytes: event.fingerprintBytes,
|
||||
appliedAt: safeNow(state),
|
||||
});
|
||||
// The dedupe window is the newest entries: drop the oldest to make room.
|
||||
for (const [eventId, oldest] of state.eventIds) {
|
||||
if (
|
||||
state.eventIds.size < state.registration.limits.maxDedupeEntries &&
|
||||
state.dedupeBytes + entry.fingerprintBytes <=
|
||||
state.registration.limits.maxDedupeBytes
|
||||
) {
|
||||
break;
|
||||
}
|
||||
forgetDedupe(state, eventId, oldest);
|
||||
}
|
||||
state.eventIds.set(entry.eventId, entry);
|
||||
state.sequences.set(entry.sequence, entry);
|
||||
state.dedupeBytes += entry.fingerprintBytes;
|
||||
@@ -923,32 +908,13 @@ export function createRealtimeStreamCoordinator(
|
||||
const active = state.recoveryPromise;
|
||||
const reason = state.activeRecoveryReason ?? "INITIALIZE";
|
||||
if (!active) return dropped("RECOVERY_IN_PROGRESS");
|
||||
if (signal?.aborted) {
|
||||
return realtimeFailure("ABORTED", "RECEIVE");
|
||||
}
|
||||
let removeAbortListener: () => void = () => undefined;
|
||||
const aborted = new Promise<Readonly<{ kind: "ABORTED" }>>(
|
||||
(resolve) => {
|
||||
if (!signal) return;
|
||||
const onAbort = () => resolve({ kind: "ABORTED" });
|
||||
signal.addEventListener("abort", onAbort, { once: true });
|
||||
removeAbortListener = () =>
|
||||
signal.removeEventListener("abort", onAbort);
|
||||
if (signal.aborted) onAbort();
|
||||
},
|
||||
);
|
||||
const settled = await Promise.race([
|
||||
active.then((result) => ({
|
||||
kind: "RESULT" as const,
|
||||
result,
|
||||
})),
|
||||
aborted,
|
||||
]);
|
||||
removeAbortListener();
|
||||
const settled = await raceRealtimeTask(() => active, signal);
|
||||
if (settled.kind === "ABORTED") {
|
||||
return realtimeFailure("ABORTED", "RECEIVE");
|
||||
}
|
||||
const result = settled.result;
|
||||
// Only VALUE or REJECTED remain; a rejection propagates as before.
|
||||
const result =
|
||||
settled.kind === "VALUE" ? settled.value : await active;
|
||||
if (!result.ok) return result;
|
||||
return realtimeSuccess(
|
||||
Object.freeze({
|
||||
@@ -1043,26 +1009,14 @@ export function createRealtimeStreamCoordinator(
|
||||
for (const state of states.values()) state.lifecycle = "CLOSED";
|
||||
return realtimeSuccess(undefined);
|
||||
}
|
||||
let handle: unknown;
|
||||
let installed = false;
|
||||
const drained = await Promise.race([
|
||||
Promise.allSettled(retained).then(() => true),
|
||||
new Promise<false>((resolve) => {
|
||||
try {
|
||||
handle = scheduleTimeout(
|
||||
() => resolve(false),
|
||||
limits.drainTimeoutMs,
|
||||
);
|
||||
installed = true;
|
||||
} catch {
|
||||
// RT-02. Without a drain bound this call cannot prove quiescence, so
|
||||
// it reports the honest failure rather than rejecting natively.
|
||||
resolve(false);
|
||||
}
|
||||
}),
|
||||
]);
|
||||
if (installed) clearTimerSafely(handle);
|
||||
if (!drained) {
|
||||
// RT-02. Without a drain bound (CLOCK_FAILED) this call cannot prove
|
||||
// quiescence, so it reports the honest failure rather than rejecting.
|
||||
const drained = await raceRealtimeTask(
|
||||
() => Promise.allSettled(retained),
|
||||
undefined,
|
||||
deadline(limits.drainTimeoutMs),
|
||||
);
|
||||
if (drained.kind !== "VALUE") {
|
||||
// Still DRAINING: the caller must not treat this as quiescence.
|
||||
return realtimeFailure("IDLE_TIMEOUT", "CLOSE", false);
|
||||
}
|
||||
@@ -1113,6 +1067,7 @@ export function createRealtimeStreamCoordinator(
|
||||
return candidate;
|
||||
}
|
||||
|
||||
/** Entries are kept in apply order and `appliedAt` never decreases. */
|
||||
function pruneDedupe(state: StreamState): void {
|
||||
const selectedNow = safeNow(state);
|
||||
for (const [eventId, entry] of state.eventIds) {
|
||||
@@ -1120,19 +1075,27 @@ export function createRealtimeStreamCoordinator(
|
||||
selectedNow - entry.appliedAt <
|
||||
state.registration.limits.dedupeTtlMs
|
||||
) {
|
||||
continue;
|
||||
break;
|
||||
}
|
||||
state.eventIds.delete(eventId);
|
||||
if (state.sequences.get(entry.sequence) === entry) {
|
||||
state.sequences.delete(entry.sequence);
|
||||
}
|
||||
state.dedupeBytes = Math.max(
|
||||
0,
|
||||
state.dedupeBytes - entry.fingerprintBytes,
|
||||
);
|
||||
forgetDedupe(state, eventId, entry);
|
||||
}
|
||||
}
|
||||
|
||||
function forgetDedupe(
|
||||
state: StreamState,
|
||||
eventId: string,
|
||||
entry: DedupeEntry,
|
||||
): void {
|
||||
state.eventIds.delete(eventId);
|
||||
if (state.sequences.get(entry.sequence) === entry) {
|
||||
state.sequences.delete(entry.sequence);
|
||||
}
|
||||
state.dedupeBytes = Math.max(
|
||||
0,
|
||||
state.dedupeBytes - entry.fingerprintBytes,
|
||||
);
|
||||
}
|
||||
|
||||
function fenceState(state: StreamState): void {
|
||||
state.processingGeneration += 1;
|
||||
state.activeEffectAbort?.abort();
|
||||
@@ -1408,14 +1371,3 @@ function captureSnapshotCheckpoint(
|
||||
? checkpoint
|
||||
: null;
|
||||
}
|
||||
|
||||
function hasExactSnapshotKeys(
|
||||
snapshot: RealtimeDataSnapshot,
|
||||
expected: readonly string[],
|
||||
): boolean {
|
||||
const selected = [...expected].sort();
|
||||
return (
|
||||
snapshot.keys.length === selected.length &&
|
||||
snapshot.keys.every((key, index) => key === selected[index])
|
||||
);
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import type {
|
||||
import {
|
||||
isRealtimeResult,
|
||||
isRealtimeTransportEventOutcome,
|
||||
raceRealtimeTask,
|
||||
realtimeFailure,
|
||||
realtimeSuccess,
|
||||
} from "../result.ts";
|
||||
@@ -306,7 +307,6 @@ export function createWebSocketConnection(
|
||||
"PROTOCOL_MISMATCH",
|
||||
"CONNECT",
|
||||
false,
|
||||
"NONE",
|
||||
),
|
||||
"PROTOCOL_MISMATCH",
|
||||
{
|
||||
@@ -348,12 +348,7 @@ export function createWebSocketConnection(
|
||||
failureKind: code,
|
||||
});
|
||||
terminate(
|
||||
failure(
|
||||
code,
|
||||
"RECEIVE",
|
||||
false,
|
||||
code === "EVENT_TOO_LARGE" ? "SNAPSHOT" : "NONE",
|
||||
),
|
||||
failure(code, "RECEIVE", false),
|
||||
"PROTOCOL_MISMATCH",
|
||||
{
|
||||
subscriptionId: null,
|
||||
@@ -390,7 +385,6 @@ export function createWebSocketConnection(
|
||||
"QUEUE_OVERFLOW",
|
||||
"RECEIVE",
|
||||
false,
|
||||
"SNAPSHOT",
|
||||
),
|
||||
"CURSOR_RESET",
|
||||
{
|
||||
@@ -435,7 +429,6 @@ export function createWebSocketConnection(
|
||||
? "CONNECT"
|
||||
: "RECEIVE",
|
||||
true,
|
||||
"RECONNECT",
|
||||
),
|
||||
"NETWORK_LOST",
|
||||
undefined,
|
||||
@@ -450,7 +443,6 @@ export function createWebSocketConnection(
|
||||
"CLOSED",
|
||||
"CONNECT",
|
||||
false,
|
||||
"NONE",
|
||||
);
|
||||
}
|
||||
if (connectPromise) return connectPromise;
|
||||
@@ -459,7 +451,6 @@ export function createWebSocketConnection(
|
||||
"CLOSED",
|
||||
"CONNECT",
|
||||
false,
|
||||
"NONE",
|
||||
);
|
||||
}
|
||||
if (signal?.aborted) {
|
||||
@@ -467,7 +458,6 @@ export function createWebSocketConnection(
|
||||
"ABORTED",
|
||||
"CONNECT",
|
||||
false,
|
||||
"NONE",
|
||||
);
|
||||
terminate(
|
||||
aborted.error,
|
||||
@@ -497,7 +487,6 @@ export function createWebSocketConnection(
|
||||
"PROVIDER_UNAVAILABLE",
|
||||
"CONNECT",
|
||||
true,
|
||||
"RECONNECT",
|
||||
),
|
||||
"NETWORK_LOST",
|
||||
undefined,
|
||||
@@ -512,7 +501,6 @@ export function createWebSocketConnection(
|
||||
"ABORTED",
|
||||
"CONNECT",
|
||||
false,
|
||||
"NONE",
|
||||
),
|
||||
"NORMAL",
|
||||
undefined,
|
||||
@@ -543,7 +531,6 @@ export function createWebSocketConnection(
|
||||
status === "OPEN" ? "PROTOCOL_MISMATCH" : "CLOSED",
|
||||
"SUBSCRIBE",
|
||||
false,
|
||||
"NONE",
|
||||
);
|
||||
}
|
||||
const eventWindowStartedAt = readClockNow(dependencies.clock);
|
||||
@@ -552,7 +539,6 @@ export function createWebSocketConnection(
|
||||
"PROVIDER_UNAVAILABLE",
|
||||
"SUBSCRIBE",
|
||||
true,
|
||||
"RECONNECT",
|
||||
);
|
||||
terminate(
|
||||
unavailable.error,
|
||||
@@ -595,7 +581,6 @@ export function createWebSocketConnection(
|
||||
status === "OPEN" ? "PROTOCOL_MISMATCH" : "CLOSED",
|
||||
"SUBSCRIBE",
|
||||
false,
|
||||
"NONE",
|
||||
);
|
||||
}
|
||||
const sent = sendCritical(
|
||||
@@ -637,7 +622,7 @@ export function createWebSocketConnection(
|
||||
if (sent.ok) drainOutboundQueue();
|
||||
}
|
||||
terminate(
|
||||
failure("CLOSED", "CLOSE", false, "NONE"),
|
||||
failure("CLOSED", "CLOSE", false),
|
||||
category,
|
||||
undefined,
|
||||
);
|
||||
@@ -664,7 +649,6 @@ export function createWebSocketConnection(
|
||||
"CONNECT_TIMEOUT",
|
||||
"CONNECT",
|
||||
true,
|
||||
"RECONNECT",
|
||||
),
|
||||
"NETWORK_LOST",
|
||||
undefined,
|
||||
@@ -680,7 +664,6 @@ export function createWebSocketConnection(
|
||||
"PROVIDER_UNAVAILABLE",
|
||||
"CONNECT",
|
||||
true,
|
||||
"RECONNECT",
|
||||
),
|
||||
"NETWORK_LOST",
|
||||
undefined,
|
||||
@@ -761,7 +744,6 @@ export function createWebSocketConnection(
|
||||
resetFailureCode(frame.reason),
|
||||
"RECEIVE",
|
||||
false,
|
||||
"SNAPSHOT",
|
||||
),
|
||||
"CURSOR_RESET",
|
||||
undefined,
|
||||
@@ -868,7 +850,6 @@ export function createWebSocketConnection(
|
||||
"SEQUENCE_GAP",
|
||||
"RECEIVE",
|
||||
false,
|
||||
"SNAPSHOT",
|
||||
),
|
||||
"CURSOR_RESET",
|
||||
undefined,
|
||||
@@ -882,91 +863,63 @@ export function createWebSocketConnection(
|
||||
terminateProtocol();
|
||||
return;
|
||||
}
|
||||
if (dependencies.onSubscribed) {
|
||||
const barrierController = new AbortController();
|
||||
const abortBarrier = () => barrierController.abort();
|
||||
generation.signal.addEventListener("abort", abortBarrier, {
|
||||
once: true,
|
||||
});
|
||||
if (generation.signal.aborted) abortBarrier();
|
||||
try {
|
||||
const outcome = await Promise.race([
|
||||
Promise.resolve()
|
||||
.then(() =>
|
||||
dependencies.onSubscribed!(
|
||||
Object.freeze({
|
||||
subscriptionId: frame.subscriptionId,
|
||||
streamId: subscription.request.streamId,
|
||||
streamEpoch: frame.streamEpoch,
|
||||
acceptedCursor: frame.acceptedCursor,
|
||||
nextExpectedSequence: frame.nextExpectedSequence,
|
||||
}),
|
||||
barrierController.signal,
|
||||
),
|
||||
)
|
||||
.then((value) =>
|
||||
const onSubscribed = dependencies.onSubscribed;
|
||||
if (onSubscribed) {
|
||||
const outcome = await raceRealtimeTask(
|
||||
(signal) =>
|
||||
Promise.resolve().then(() =>
|
||||
onSubscribed(
|
||||
Object.freeze({
|
||||
kind: "HANDLED" as const,
|
||||
value,
|
||||
subscriptionId: frame.subscriptionId,
|
||||
streamId: subscription.request.streamId,
|
||||
streamEpoch: frame.streamEpoch,
|
||||
acceptedCursor: frame.acceptedCursor,
|
||||
nextExpectedSequence: frame.nextExpectedSequence,
|
||||
}),
|
||||
signal,
|
||||
),
|
||||
dependencies.clock
|
||||
.sleep(
|
||||
ceilings.maxApplyMs,
|
||||
barrierController.signal,
|
||||
)
|
||||
.then(() =>
|
||||
Object.freeze({ kind: "TIMED_OUT" as const }),
|
||||
),
|
||||
]);
|
||||
if (
|
||||
outcome.kind === "TIMED_OUT" &&
|
||||
status !== "CLOSED"
|
||||
) {
|
||||
requestRecovery({
|
||||
subscriptionId: frame.subscriptionId,
|
||||
reason: "APPLY_FAILED",
|
||||
});
|
||||
terminate(
|
||||
failure(
|
||||
"APPLY_FAILED",
|
||||
),
|
||||
generation.signal,
|
||||
(signal) => dependencies.clock.sleep(ceilings.maxApplyMs, signal),
|
||||
);
|
||||
if (outcome.kind === "TIMEOUT" && status !== "CLOSED") {
|
||||
requestRecovery({
|
||||
subscriptionId: frame.subscriptionId,
|
||||
reason: "APPLY_FAILED",
|
||||
});
|
||||
terminate(
|
||||
failure(
|
||||
"APPLY_FAILED",
|
||||
"RECOVER",
|
||||
false,
|
||||
),
|
||||
"CURSOR_RESET",
|
||||
undefined,
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (outcome.kind === "VALUE" && status !== "CLOSED") {
|
||||
if (!isRealtimeResult(outcome.value, isUndefined)) {
|
||||
terminateInboundFailure(
|
||||
realtimeFailure(
|
||||
"PROTOCOL_MISMATCH",
|
||||
"RECOVER",
|
||||
false,
|
||||
"SNAPSHOT",
|
||||
),
|
||||
"CURSOR_RESET",
|
||||
undefined,
|
||||
).error,
|
||||
frame.subscriptionId,
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
outcome.kind === "HANDLED" &&
|
||||
status !== "CLOSED"
|
||||
) {
|
||||
if (!isRealtimeResult(outcome.value, isUndefined)) {
|
||||
terminateInboundFailure(
|
||||
realtimeFailure(
|
||||
"PROTOCOL_MISMATCH",
|
||||
"RECOVER",
|
||||
false,
|
||||
).error,
|
||||
frame.subscriptionId,
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (!outcome.value.ok) {
|
||||
terminateInboundFailure(
|
||||
outcome.value.error,
|
||||
frame.subscriptionId,
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (!outcome.value.ok) {
|
||||
terminateInboundFailure(
|
||||
outcome.value.error,
|
||||
frame.subscriptionId,
|
||||
);
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
if (
|
||||
status !== "CLOSED" &&
|
||||
!generation.signal.aborted
|
||||
) {
|
||||
}
|
||||
if (outcome.kind !== "TIMEOUT" && outcome.kind !== "VALUE") {
|
||||
if (status !== "CLOSED" && !generation.signal.aborted) {
|
||||
terminateInboundFailure(
|
||||
realtimeFailure(
|
||||
"PROVIDER_UNAVAILABLE",
|
||||
@@ -977,12 +930,6 @@ export function createWebSocketConnection(
|
||||
);
|
||||
}
|
||||
return;
|
||||
} finally {
|
||||
generation.signal.removeEventListener(
|
||||
"abort",
|
||||
abortBarrier,
|
||||
);
|
||||
barrierController.abort();
|
||||
}
|
||||
}
|
||||
if (
|
||||
@@ -1023,7 +970,6 @@ export function createWebSocketConnection(
|
||||
"PROVIDER_UNAVAILABLE",
|
||||
"RECEIVE",
|
||||
true,
|
||||
"RECONNECT",
|
||||
),
|
||||
"NETWORK_LOST",
|
||||
undefined,
|
||||
@@ -1049,7 +995,6 @@ export function createWebSocketConnection(
|
||||
"QUEUE_OVERFLOW",
|
||||
"RECEIVE",
|
||||
false,
|
||||
"SNAPSHOT",
|
||||
),
|
||||
"CURSOR_RESET",
|
||||
undefined,
|
||||
@@ -1057,28 +1002,24 @@ export function createWebSocketConnection(
|
||||
return;
|
||||
}
|
||||
|
||||
const applyController = new AbortController();
|
||||
const abortApply = () => applyController.abort();
|
||||
generation.signal.addEventListener("abort", abortApply, {
|
||||
once: true,
|
||||
});
|
||||
try {
|
||||
const outcome = await Promise.race([
|
||||
dependencies
|
||||
.onEvent(frame, applyController.signal)
|
||||
.then((value) =>
|
||||
Object.freeze({
|
||||
kind: "HANDLED" as const,
|
||||
value,
|
||||
}),
|
||||
),
|
||||
dependencies.clock
|
||||
.sleep(ceilings.maxApplyMs, applyController.signal)
|
||||
.then(() =>
|
||||
Object.freeze({ kind: "TIMED_OUT" as const }),
|
||||
),
|
||||
]);
|
||||
if (outcome.kind === "TIMED_OUT" && status !== "CLOSED") {
|
||||
const outcome = await raceRealtimeTask(
|
||||
(signal) => dependencies.onEvent(frame, signal),
|
||||
generation.signal,
|
||||
(signal) => dependencies.clock.sleep(ceilings.maxApplyMs, signal),
|
||||
);
|
||||
const handled =
|
||||
outcome.kind === "VALUE" &&
|
||||
isRealtimeResult(outcome.value, isRealtimeTransportEventOutcome)
|
||||
? outcome.value
|
||||
: null;
|
||||
if (!handled) {
|
||||
// Timed out, returned no valid result, or failed while still current.
|
||||
if (
|
||||
status !== "CLOSED" &&
|
||||
(outcome.kind === "TIMEOUT" ||
|
||||
outcome.kind === "VALUE" ||
|
||||
!generation.signal.aborted)
|
||||
) {
|
||||
requestRecovery({
|
||||
subscriptionId: frame.subscriptionId,
|
||||
reason: "APPLY_FAILED",
|
||||
@@ -1088,74 +1029,27 @@ export function createWebSocketConnection(
|
||||
"APPLY_FAILED",
|
||||
"RECEIVE",
|
||||
false,
|
||||
"SNAPSHOT",
|
||||
),
|
||||
"CURSOR_RESET",
|
||||
undefined,
|
||||
);
|
||||
} else if (outcome.kind === "HANDLED" && status !== "CLOSED") {
|
||||
if (
|
||||
!isRealtimeResult(
|
||||
outcome.value,
|
||||
isRealtimeTransportEventOutcome,
|
||||
)
|
||||
) {
|
||||
requestRecovery({
|
||||
subscriptionId: frame.subscriptionId,
|
||||
reason: "APPLY_FAILED",
|
||||
});
|
||||
terminate(
|
||||
failure(
|
||||
"APPLY_FAILED",
|
||||
"RECEIVE",
|
||||
false,
|
||||
"SNAPSHOT",
|
||||
),
|
||||
"CURSOR_RESET",
|
||||
undefined,
|
||||
);
|
||||
} else if (!outcome.value.ok) {
|
||||
terminateInboundFailure(
|
||||
outcome.value.error,
|
||||
frame.subscriptionId,
|
||||
);
|
||||
} else if (
|
||||
outcome.value.value.kind === "RECOVERY_COMMITTED"
|
||||
) {
|
||||
terminate(
|
||||
failure(
|
||||
"CURSOR_EXPIRED",
|
||||
"RECEIVE",
|
||||
false,
|
||||
"SNAPSHOT",
|
||||
),
|
||||
"CURSOR_RESET",
|
||||
undefined,
|
||||
true,
|
||||
outcome.value.value,
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
if (status !== "CLOSED" && !generation.signal.aborted) {
|
||||
requestRecovery({
|
||||
subscriptionId: frame.subscriptionId,
|
||||
reason: "APPLY_FAILED",
|
||||
});
|
||||
} else if (status !== "CLOSED") {
|
||||
if (!handled.ok) {
|
||||
terminateInboundFailure(handled.error, frame.subscriptionId);
|
||||
} else if (handled.value.kind === "RECOVERY_COMMITTED") {
|
||||
terminate(
|
||||
failure(
|
||||
"APPLY_FAILED",
|
||||
"CURSOR_EXPIRED",
|
||||
"RECEIVE",
|
||||
false,
|
||||
"SNAPSHOT",
|
||||
),
|
||||
"CURSOR_RESET",
|
||||
undefined,
|
||||
true,
|
||||
handled.value,
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
generation.signal.removeEventListener("abort", abortApply);
|
||||
applyController.abort();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1256,7 +1150,6 @@ export function createWebSocketConnection(
|
||||
"PROVIDER_UNAVAILABLE",
|
||||
"RECEIVE",
|
||||
true,
|
||||
"RECONNECT",
|
||||
),
|
||||
"NETWORK_LOST",
|
||||
undefined,
|
||||
@@ -1269,7 +1162,6 @@ export function createWebSocketConnection(
|
||||
"IDLE_TIMEOUT",
|
||||
"RECEIVE",
|
||||
true,
|
||||
"RECONNECT",
|
||||
),
|
||||
"NETWORK_LOST",
|
||||
undefined,
|
||||
@@ -1286,7 +1178,6 @@ export function createWebSocketConnection(
|
||||
"PROTOCOL_MISMATCH",
|
||||
"RECEIVE",
|
||||
false,
|
||||
"NONE",
|
||||
),
|
||||
"PROTOCOL_MISMATCH",
|
||||
undefined,
|
||||
@@ -1303,7 +1194,7 @@ export function createWebSocketConnection(
|
||||
socket.readyState !== NATIVE_OPEN ||
|
||||
!effectiveLimits
|
||||
) {
|
||||
return connectionFailure("CLOSED", operation, false, "NONE");
|
||||
return connectionFailure("CLOSED", operation, false);
|
||||
}
|
||||
const encoded = encodeWebSocketClientFrame(
|
||||
frame,
|
||||
@@ -1316,7 +1207,6 @@ export function createWebSocketConnection(
|
||||
: "PROTOCOL_MISMATCH",
|
||||
operation,
|
||||
false,
|
||||
"NONE",
|
||||
);
|
||||
}
|
||||
if (
|
||||
@@ -1333,7 +1223,6 @@ export function createWebSocketConnection(
|
||||
"PROVIDER_UNAVAILABLE",
|
||||
operation,
|
||||
true,
|
||||
"RECONNECT",
|
||||
);
|
||||
terminate(result.error, "NETWORK_LOST", undefined);
|
||||
return result;
|
||||
@@ -1384,7 +1273,6 @@ export function createWebSocketConnection(
|
||||
"PROVIDER_UNAVAILABLE",
|
||||
queued.operation,
|
||||
true,
|
||||
"RECONNECT",
|
||||
),
|
||||
"NETWORK_LOST",
|
||||
undefined,
|
||||
@@ -1408,7 +1296,6 @@ export function createWebSocketConnection(
|
||||
"PROVIDER_UNAVAILABLE",
|
||||
queued.operation,
|
||||
true,
|
||||
"RECONNECT",
|
||||
),
|
||||
"NETWORK_LOST",
|
||||
undefined,
|
||||
@@ -1428,7 +1315,6 @@ export function createWebSocketConnection(
|
||||
"QUEUE_OVERFLOW",
|
||||
operation,
|
||||
false,
|
||||
"NONE",
|
||||
);
|
||||
terminate(result.error, "OVERLOADED", {
|
||||
subscriptionId: null,
|
||||
@@ -1543,7 +1429,6 @@ export function createWebSocketConnection(
|
||||
"IDLE_TIMEOUT",
|
||||
"SUBSCRIBE",
|
||||
true,
|
||||
"RECONNECT",
|
||||
),
|
||||
"NETWORK_LOST",
|
||||
undefined,
|
||||
@@ -1562,7 +1447,6 @@ export function createWebSocketConnection(
|
||||
"PROVIDER_UNAVAILABLE",
|
||||
"SUBSCRIBE",
|
||||
true,
|
||||
"RECONNECT",
|
||||
),
|
||||
"NETWORK_LOST",
|
||||
undefined,
|
||||
@@ -1919,49 +1803,43 @@ function closeFailure(
|
||||
): RealtimeFailure {
|
||||
switch (category) {
|
||||
case "NORMAL":
|
||||
return failure("CLOSED", "CLOSE", false, "NONE");
|
||||
return failure("CLOSED", "CLOSE", false);
|
||||
case "RESTART":
|
||||
case "NETWORK_LOST":
|
||||
return failure(
|
||||
"PROVIDER_UNAVAILABLE",
|
||||
"RECEIVE",
|
||||
true,
|
||||
"RECONNECT",
|
||||
);
|
||||
case "OVERLOADED":
|
||||
return failure(
|
||||
"PROVIDER_UNAVAILABLE",
|
||||
"RECEIVE",
|
||||
false,
|
||||
"NONE",
|
||||
);
|
||||
case "AUTH_REQUIRED":
|
||||
return failure(
|
||||
"AUTH_REQUIRED",
|
||||
"RECEIVE",
|
||||
false,
|
||||
"SESSION_REVALIDATE",
|
||||
);
|
||||
case "FORBIDDEN":
|
||||
return failure(
|
||||
"FORBIDDEN",
|
||||
"RECEIVE",
|
||||
false,
|
||||
"NONE",
|
||||
);
|
||||
case "PROTOCOL_MISMATCH":
|
||||
return failure(
|
||||
"PROTOCOL_MISMATCH",
|
||||
"RECEIVE",
|
||||
false,
|
||||
"NONE",
|
||||
);
|
||||
case "CURSOR_RESET":
|
||||
return failure(
|
||||
"CURSOR_EXPIRED",
|
||||
"RECEIVE",
|
||||
false,
|
||||
"SNAPSHOT",
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1988,7 +1866,6 @@ function failure(
|
||||
kind: RealtimeFailureKind,
|
||||
operation: RealtimeOperation,
|
||||
retryable: boolean,
|
||||
_recovery: "NONE" | "RECONNECT" | "SNAPSHOT" | "SESSION_REVALIDATE",
|
||||
): RealtimeFailure {
|
||||
return realtimeFailure(kind, operation, retryable).error;
|
||||
}
|
||||
@@ -1997,7 +1874,6 @@ function connectionFailure(
|
||||
kind: RealtimeFailureKind,
|
||||
operation: RealtimeOperation,
|
||||
retryable: boolean,
|
||||
_recovery: "NONE" | "RECONNECT" | "SNAPSHOT" | "SESSION_REVALIDATE",
|
||||
): Extract<RealtimeResult<never>, { ok: false }> {
|
||||
return realtimeFailure(kind, operation, retryable);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import {
|
||||
hasDuplicateJsonMembers,
|
||||
} from "../json-member-scanner.ts";
|
||||
} from "../../platform/json-member-scanner.ts";
|
||||
|
||||
export const REALTIME_WEBSOCKET_PROTOCOL = "realtime.v1" as const;
|
||||
|
||||
@@ -469,6 +469,12 @@ function isUnsignedSequence(input: unknown): input is string {
|
||||
}
|
||||
}
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
function utf8ByteLength(input: string): number {
|
||||
return encoder.encode(input).byteLength;
|
||||
}
|
||||
|
||||
/**
|
||||
* R-05. Admission before allocation.
|
||||
*
|
||||
@@ -479,10 +485,6 @@ function isUnsignedSequence(input: unknown): input is string {
|
||||
* bytes and a lone surrogate as the three-byte replacement sequence, exactly
|
||||
* like `TextEncoder`.
|
||||
*/
|
||||
function utf8ByteLength(input: string): number {
|
||||
return new TextEncoder().encode(input).byteLength;
|
||||
}
|
||||
|
||||
function exceedsUtf8ByteLimit(input: string, maxBytes: number): boolean {
|
||||
if (input.length > maxBytes) return true;
|
||||
let bytes = 0;
|
||||
|
||||
@@ -94,24 +94,18 @@ self.addEventListener("activate", (event) => {
|
||||
if (handlers.includes("PWA_STATIC_ASSETS")) {
|
||||
self.addEventListener("fetch", (event) => {
|
||||
const request = event.request;
|
||||
// R-6.6. Decided synchronously: only a GET for a verified static asset of
|
||||
// this release is answered. Navigations, API calls and cross-origin
|
||||
// requests are left to the browser untouched.
|
||||
if (
|
||||
request.method !== "GET" ||
|
||||
request.mode === "navigate" ||
|
||||
!runtime.manifestUrls.has(request.url)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const described = {
|
||||
method: request.method,
|
||||
url: request.url,
|
||||
mode: request.mode,
|
||||
};
|
||||
// R-6.6 / Q-6.6-6b. Decided synchronously: only a same-origin GET for a
|
||||
// verified asset of this release or a content-hashed old-build chunk is
|
||||
// answered. Navigations, API calls, cross-origin and unhashed requests are
|
||||
// left to the browser untouched. Every cache miss goes to the network.
|
||||
if (!runtime.intercepts(described)) return;
|
||||
event.respondWith(
|
||||
runtime
|
||||
.onFetch({
|
||||
method: request.method,
|
||||
url: request.url,
|
||||
mode: request.mode,
|
||||
})
|
||||
.then((cached) => cached ?? fetch(request)),
|
||||
runtime.onFetch(described).then((cached) => cached ?? fetch(request)),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -157,6 +157,14 @@ export function createServiceWorkerRuntime(
|
||||
const highestOld = await highestMarkedCache(names, current);
|
||||
const currentMarker = await readActivationMarker(currentCache, current);
|
||||
const previous = highestOld?.cacheName ?? oldCaches.at(-1) ?? null;
|
||||
// Q-6.6-9. Stale caches go first: when storage is full the marker write
|
||||
// below is what fails, and deleting is the only way space comes back.
|
||||
const stale = selectCachesToDelete(names, current, previous);
|
||||
let deleted = 0;
|
||||
for (const name of stale) {
|
||||
if (await scope.caches.delete(name).catch(() => false)) deleted += 1;
|
||||
}
|
||||
void SERVICE_WORKER_BOUNDS.retainedPreviousCaches;
|
||||
if (
|
||||
!currentMarker ||
|
||||
currentMarker.activationSequence < (highestOld?.activationSequence ?? 0)
|
||||
@@ -165,27 +173,26 @@ export function createServiceWorkerRuntime(
|
||||
if (!Number.isSafeInteger(nextSequence)) {
|
||||
throw new Error("SERVICE_WORKER_ACTIVATION_SEQUENCE_EXHAUSTED");
|
||||
}
|
||||
await currentCache.put(
|
||||
ACTIVATION_MARKER_URL,
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
cacheName: current,
|
||||
activationSequence: nextSequence,
|
||||
}),
|
||||
{
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
},
|
||||
),
|
||||
);
|
||||
try {
|
||||
await currentCache.put(
|
||||
ACTIVATION_MARKER_URL,
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
cacheName: current,
|
||||
activationSequence: nextSequence,
|
||||
}),
|
||||
{
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
},
|
||||
),
|
||||
);
|
||||
} catch {
|
||||
// Q-6.6-9. Activation stands without a marker; the next release just
|
||||
// cannot find this cache as its previous one for the hashed fallback.
|
||||
}
|
||||
}
|
||||
const stale = selectCachesToDelete(names, current, previous);
|
||||
let deleted = 0;
|
||||
for (const name of stale) {
|
||||
if (await scope.caches.delete(name)) deleted += 1;
|
||||
}
|
||||
void SERVICE_WORKER_BOUNDS.retainedPreviousCaches;
|
||||
return deleted;
|
||||
}
|
||||
|
||||
@@ -238,30 +245,54 @@ export function createServiceWorkerRuntime(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* §18.5–§18.7. A verified cache hit is returned; anything else goes to the
|
||||
* network and is never written back into the active cache at runtime.
|
||||
*/
|
||||
async function onFetch(
|
||||
request: Readonly<{ method: string; url: string; mode?: string }>,
|
||||
): Promise<Response | null> {
|
||||
const classification = classifyFetch({
|
||||
type FetchRequest = Readonly<{ method: string; url: string; mode?: string }>;
|
||||
|
||||
function classify(request: FetchRequest) {
|
||||
if (!staticEnabled) return "NETWORK_PASSTHROUGH";
|
||||
return classifyFetch({
|
||||
method: request.method,
|
||||
requestUrl: request.url,
|
||||
isNavigation: request.mode === "navigate",
|
||||
runtimeConfigUrl: config.runtimeConfigUrl,
|
||||
releaseManifestUrl: config.releaseManifestUrl,
|
||||
manifestUrls,
|
||||
scopeUrl: scope.registrationScope,
|
||||
});
|
||||
if (classification !== "VERIFIED_CACHE_FIRST") return null;
|
||||
}
|
||||
|
||||
// SW-01. Only the current release cache may answer. A CacheStorage-wide
|
||||
// match could return a previous release's response for the same URL, and
|
||||
// the subsequent delete would then target a cache that was never read.
|
||||
/**
|
||||
* R-6.6 / Q-6.6-6b. Synchronous, so the fetch listener decides before it
|
||||
* calls `respondWith`. Only a manifest asset of this release or a
|
||||
* same-origin content-hashed URL (an old build's chunk) is answered;
|
||||
* navigations, API calls, cross-origin and unhashed URLs are left alone.
|
||||
*/
|
||||
function intercepts(request: FetchRequest): boolean {
|
||||
const classification = classify(request);
|
||||
return (
|
||||
classification === "VERIFIED_CACHE_FIRST" ||
|
||||
classification === "PREVIOUS_RELEASE_FALLBACK"
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* §18.5–§18.7. A verified cache hit is returned; anything else goes to the
|
||||
* network and is never written back into the active cache at runtime.
|
||||
*/
|
||||
async function onFetch(request: FetchRequest): Promise<Response | null> {
|
||||
const classification = classify(request);
|
||||
// SW-01. Only the current release cache may answer a manifest URL. A
|
||||
// CacheStorage-wide match could return a previous release's response for
|
||||
// the same URL, and the subsequent delete would then target a cache that
|
||||
// was never read.
|
||||
const currentCacheName = config.manifest
|
||||
? staticCacheName(config.manifest.setDigest)
|
||||
: null;
|
||||
if (!currentCacheName) return null;
|
||||
if (classification === "PREVIOUS_RELEASE_FALLBACK") {
|
||||
// Q-6.6-6b. Not listed by this release, so not in the current cache.
|
||||
return matchPreviousRelease(request.url, currentCacheName);
|
||||
}
|
||||
if (classification !== "VERIFIED_CACHE_FIRST") return null;
|
||||
// SW-RR-04. Both `open` and `match` are storage calls that can throw
|
||||
// synchronously or reject. Either one escaping here rejects `respondWith`
|
||||
// itself, so the entry never reaches its network fallback and the page
|
||||
@@ -475,6 +506,7 @@ export function createServiceWorkerRuntime(
|
||||
onInstall,
|
||||
onActivate,
|
||||
onFetch,
|
||||
intercepts,
|
||||
onActivateRequest,
|
||||
onClientMessage,
|
||||
onCacheResetRequest,
|
||||
|
||||
@@ -38,6 +38,8 @@ export type PageControllerDependencies = Readonly<{
|
||||
buildId: string;
|
||||
container?: ServiceWorkerContainer;
|
||||
caches?: CacheStorage;
|
||||
/** Q-6.6-12. The host page; without it the global `document`, if any. */
|
||||
document?: Pick<Document, "visibilityState">;
|
||||
/** §17.10. Any blocker returning true rejects automatic activation. */
|
||||
blockers?: readonly ActivationBlocker[];
|
||||
now?: () => number;
|
||||
@@ -349,10 +351,11 @@ export function createServiceWorkerPageController(
|
||||
function scheduleUpdateChecks(): void {
|
||||
// §17.14. At most one check per 6 hours, and none while the page is hidden.
|
||||
if (updateTimer) return;
|
||||
const page =
|
||||
dependencies.document ??
|
||||
(typeof document === "undefined" ? undefined : document);
|
||||
updateTimer = setInterval(() => {
|
||||
if (typeof document !== "undefined" && document.visibilityState === "hidden") {
|
||||
return;
|
||||
}
|
||||
if (page?.visibilityState === "hidden") return;
|
||||
void registration?.update().catch(() => {
|
||||
// A failed update check never fails a product flow.
|
||||
});
|
||||
@@ -381,7 +384,12 @@ export function createServiceWorkerPageController(
|
||||
}
|
||||
|
||||
const nonce = nonces.issue();
|
||||
const deadline = now() + SERVICE_WORKER_BOUNDS.clientDrainMs;
|
||||
// Q-6.6-10b. With equal deadlines a tab draining at 29s left this page at
|
||||
// TIMEOUT while the worker still committed skipWaiting().
|
||||
const deadline =
|
||||
now() +
|
||||
SERVICE_WORKER_BOUNDS.clientDrainMs +
|
||||
SERVICE_WORKER_BOUNDS.activationReplySlackMs;
|
||||
const accepted = await new Promise<ServiceWorkerActivationOutcome>(
|
||||
(resolve) => {
|
||||
const container = dependencies.container;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
HASHED_STATIC_ASSET_NAME,
|
||||
isOwnedStaticCacheName,
|
||||
SERVICE_WORKER_BOUNDS,
|
||||
staticCacheName,
|
||||
@@ -17,7 +18,13 @@ import {
|
||||
export type FetchClassification =
|
||||
| "NETWORK_PASSTHROUGH"
|
||||
| "NETWORK_ONLY"
|
||||
| "VERIFIED_CACHE_FIRST";
|
||||
| "VERIFIED_CACHE_FIRST"
|
||||
/**
|
||||
* Q-6.6-6b. A same-origin content-hashed URL this release does not list,
|
||||
* typically a lazy chunk of the build a tab still runs. Only the previous
|
||||
* release cache may answer it; otherwise it goes to the network.
|
||||
*/
|
||||
| "PREVIOUS_RELEASE_FALLBACK";
|
||||
|
||||
export type ClassificationInput = Readonly<{
|
||||
method: string;
|
||||
@@ -26,6 +33,8 @@ export type ClassificationInput = Readonly<{
|
||||
runtimeConfigUrl: string;
|
||||
releaseManifestUrl: string;
|
||||
manifestUrls: ReadonlySet<string>;
|
||||
/** The registration scope; a hashed URL outside its origin is never cached. */
|
||||
scopeUrl: string;
|
||||
}>;
|
||||
|
||||
/**
|
||||
@@ -42,9 +51,24 @@ export function classifyFetch(input: ClassificationInput): FetchClassification {
|
||||
return "NETWORK_ONLY";
|
||||
}
|
||||
if (input.manifestUrls.has(input.requestUrl)) return "VERIFIED_CACHE_FIRST";
|
||||
if (isSameOriginHashedAsset(input.requestUrl, input.scopeUrl)) {
|
||||
return "PREVIOUS_RELEASE_FALLBACK";
|
||||
}
|
||||
return "NETWORK_PASSTHROUGH";
|
||||
}
|
||||
|
||||
function isSameOriginHashedAsset(requestUrl: string, scopeUrl: string): boolean {
|
||||
try {
|
||||
const request = new URL(requestUrl);
|
||||
return (
|
||||
request.origin === new URL(scopeUrl).origin &&
|
||||
HASHED_STATIC_ASSET_NAME.test(request.pathname)
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function sameResource(left: string, right: string): boolean {
|
||||
try {
|
||||
const a = new URL(left);
|
||||
@@ -77,6 +101,8 @@ export type InstallDependencies = Readonly<{
|
||||
caches: Readonly<{
|
||||
open(cacheName: string): Promise<Cache>;
|
||||
delete(cacheName: string): Promise<boolean>;
|
||||
/** Q-6.6-8. Without it every failed candidate is treated as new. */
|
||||
keys?(): Promise<readonly string[]>;
|
||||
}>;
|
||||
fetcher: typeof fetch;
|
||||
digest(bytes: Uint8Array): Promise<string>;
|
||||
@@ -114,7 +140,8 @@ export function validateStaticAssetManifest(
|
||||
|
||||
/**
|
||||
* §17.9. A partial candidate is never used: any failure deletes the candidate
|
||||
* cache and rejects install, leaving the previous verified revision in place.
|
||||
* cache this install created and rejects install, leaving the previous
|
||||
* verified revision in place.
|
||||
*/
|
||||
export async function installStaticAssets(
|
||||
manifest: StaticAssetManifestV1,
|
||||
@@ -124,6 +151,12 @@ export async function installStaticAssets(
|
||||
if (invalid) return invalid;
|
||||
|
||||
const cacheName = staticCacheName(manifest.setDigest);
|
||||
// Q-6.6-8. The name is the asset-set digest, so a worker whose assets did
|
||||
// not change installs into the cache the active (or retained previous)
|
||||
// worker serves from. Rewriting it only puts identical verified bytes, but
|
||||
// deleting it on failure would take the serving cache and its marker away.
|
||||
// Only a cache this install created is rolled back.
|
||||
const rollBack = !(await cacheExists(dependencies.caches, cacheName));
|
||||
const abortController = new AbortController();
|
||||
let deadlineExceeded = false;
|
||||
let deadlineTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
@@ -147,7 +180,7 @@ export async function installStaticAssets(
|
||||
? rejected("INSTALL_DEADLINE_EXCEEDED")
|
||||
: raced;
|
||||
|
||||
if (outcome.kind === "REJECTED") {
|
||||
if (outcome.kind === "REJECTED" && rollBack) {
|
||||
await dependencies.caches.delete(cacheName).catch(() => false);
|
||||
// SW-09. A non-cooperative fetch, digest or `cache.put` started before the
|
||||
// deadline cannot be cancelled, so it may recreate the candidate cache
|
||||
@@ -166,6 +199,17 @@ export async function installStaticAssets(
|
||||
return outcome;
|
||||
}
|
||||
|
||||
async function cacheExists(
|
||||
caches: InstallDependencies["caches"],
|
||||
cacheName: string,
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
return (await caches.keys?.())?.includes(cacheName) ?? false;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function installCandidate(
|
||||
manifest: StaticAssetManifestV1,
|
||||
cacheName: string,
|
||||
|
||||
@@ -3,9 +3,12 @@ import {
|
||||
assertValidStoragePolicy,
|
||||
type BrowserStoragePolicy,
|
||||
} from "../../../application/ports/browser-file-storage/shared.ts";
|
||||
import {
|
||||
INDEXEDDB_DATASET_BUDGET_KEY,
|
||||
isStoredDatasetBudget,
|
||||
} from "./indexeddb-records.ts";
|
||||
|
||||
export const INDEXEDDB_DATASET_BINDING_KEY = "dataset-binding";
|
||||
export const INDEXEDDB_DATASET_BUDGET_KEY = "dataset-budget";
|
||||
|
||||
const OPAQUE_SCOPE_TOKEN = /^[A-Za-z0-9_-]{16,48}$/u;
|
||||
|
||||
@@ -280,27 +283,8 @@ export function verifyIndexedDbDatasetBinding(
|
||||
} else if (!sameIndexedDbDatasetBinding(observed, expected)) {
|
||||
finish({ ok: false, reason: "MISMATCH" });
|
||||
} else if (
|
||||
!observedBudget ||
|
||||
typeof observedBudget !== "object" ||
|
||||
(observedBudget as { bindingKey?: unknown }).bindingKey !==
|
||||
INDEXEDDB_DATASET_BUDGET_KEY ||
|
||||
(observedBudget as { budgetVersion?: unknown }).budgetVersion !==
|
||||
1 ||
|
||||
!Number.isSafeInteger(
|
||||
(observedBudget as { usedBytes?: unknown }).usedBytes,
|
||||
) ||
|
||||
typeof (observedBudget as { usedBytes?: unknown }).usedBytes !==
|
||||
"number" ||
|
||||
(observedBudget as { usedBytes: number }).usedBytes < 0 ||
|
||||
(observedBudget as { usedBytes: number }).usedBytes >
|
||||
expected.storagePolicy.hardBudgetBytes
|
||||
||
|
||||
!Number.isSafeInteger(
|
||||
(observedBudget as { receiptCount?: unknown }).receiptCount,
|
||||
) ||
|
||||
typeof (observedBudget as { receiptCount?: unknown })
|
||||
.receiptCount !== "number" ||
|
||||
(observedBudget as { receiptCount: number }).receiptCount < 0
|
||||
!isStoredDatasetBudget(observedBudget) ||
|
||||
observedBudget.usedBytes > expected.storagePolicy.hardBudgetBytes
|
||||
) {
|
||||
finish({ ok: false, reason: "CORRUPT" });
|
||||
} else {
|
||||
|
||||
@@ -27,23 +27,29 @@ import {
|
||||
import { mapIndexedDbException } from "./indexeddb-failure.ts";
|
||||
import {
|
||||
createIndexedDbDatasetBinding,
|
||||
INDEXEDDB_DATASET_BUDGET_KEY,
|
||||
indexedDbPhysicalDatabaseName,
|
||||
verifyIndexedDbDatasetBinding,
|
||||
} from "./indexeddb-governance.ts";
|
||||
import {
|
||||
countBucket,
|
||||
failureOf,
|
||||
INDEXEDDB_DATASET_BUDGET_KEY,
|
||||
isPositiveInteger,
|
||||
isStoredDatasetBudget,
|
||||
isStoredReceipt,
|
||||
isStoredRecord,
|
||||
isStoredRetentionRecord,
|
||||
isValidBoundaryIdentifier,
|
||||
measureRecordBytes,
|
||||
type StoredDatasetBudget,
|
||||
type StoredRecord,
|
||||
type StoredRetentionRecord,
|
||||
} from "./indexeddb-records.ts";
|
||||
import type {
|
||||
IndexedDbCountBucket,
|
||||
IndexedDbMaintenanceDependencies,
|
||||
IndexedDbObservation,
|
||||
} from "./indexeddb-types.ts";
|
||||
|
||||
type StoredRecord = Readonly<{
|
||||
key: string;
|
||||
codecVersion: number;
|
||||
revision: number;
|
||||
payload: unknown;
|
||||
}>;
|
||||
|
||||
type StoredCheckpoint = Readonly<{
|
||||
checkpointKey: string;
|
||||
migrationId: string;
|
||||
@@ -52,32 +58,6 @@ type StoredCheckpoint = Readonly<{
|
||||
state: "MORE" | "COMPLETE";
|
||||
}>;
|
||||
|
||||
type StoredIdempotencyReceipt = Readonly<{
|
||||
idempotencyKey: string;
|
||||
operation: "PUT" | "DELETE";
|
||||
recordKey: string;
|
||||
expectedRevision: number | null;
|
||||
fingerprint: string;
|
||||
synchronization: "NONE" | "PENDING" | "CONFIRMED";
|
||||
revision: number;
|
||||
expiresAtEpochMs: number;
|
||||
}>;
|
||||
|
||||
type StoredRetentionRecord = Readonly<{
|
||||
recordKey: string;
|
||||
writtenAtEpochMs: number;
|
||||
synchronization: "NONE" | "PENDING" | "CONFIRMED";
|
||||
measuredBytes: number;
|
||||
eligibleAtEpochMs?: number;
|
||||
}>;
|
||||
|
||||
type StoredDatasetBudget = Readonly<{
|
||||
bindingKey: typeof INDEXEDDB_DATASET_BUDGET_KEY;
|
||||
budgetVersion: 1;
|
||||
usedBytes: number;
|
||||
receiptCount: number;
|
||||
}>;
|
||||
|
||||
type CheckpointState = Readonly<{
|
||||
persisted: StoredCheckpoint | null;
|
||||
effective: Readonly<{
|
||||
@@ -86,57 +66,22 @@ type CheckpointState = Readonly<{
|
||||
}>;
|
||||
}>;
|
||||
|
||||
type ScannedRecord = Readonly<{
|
||||
key: string;
|
||||
codecVersion: number;
|
||||
revision: number;
|
||||
payload: unknown;
|
||||
}>;
|
||||
|
||||
type ScanBatch = Readonly<{
|
||||
rows: readonly ScannedRecord[];
|
||||
rows: readonly StoredRecord[];
|
||||
reachedEnd: boolean;
|
||||
budgetExhausted: boolean;
|
||||
}>;
|
||||
|
||||
type PreparedRecord<WireValue> = Readonly<{
|
||||
source: ScannedRecord;
|
||||
source: StoredRecord;
|
||||
needsMigration: boolean;
|
||||
migratedPayload: WireValue | undefined;
|
||||
measuredBytes: number | undefined;
|
||||
}>;
|
||||
|
||||
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;
|
||||
const MAX_BATCH_DURATION_MS = 30_000;
|
||||
const RECORD_ENVELOPE_RESERVATION_BYTES = 512;
|
||||
const MAX_MEASURED_RECORD_BYTES = 2_147_483_647;
|
||||
|
||||
function isPositiveInteger(value: unknown): value is number {
|
||||
return (
|
||||
typeof value === "number" &&
|
||||
Number.isSafeInteger(value) &&
|
||||
value >= 1
|
||||
);
|
||||
}
|
||||
|
||||
function isStoredRecord(
|
||||
value: unknown,
|
||||
expectedKey?: string,
|
||||
): value is StoredRecord {
|
||||
if (!value || typeof value !== "object") return false;
|
||||
const record = value as Partial<StoredRecord>;
|
||||
return (
|
||||
typeof record.key === "string" &&
|
||||
record.key.length > 0 &&
|
||||
record.key.length <= 200 &&
|
||||
(expectedKey === undefined || record.key === expectedKey) &&
|
||||
isPositiveInteger(record.codecVersion) &&
|
||||
isPositiveInteger(record.revision) &&
|
||||
Object.hasOwn(record, "payload")
|
||||
);
|
||||
}
|
||||
|
||||
function isStoredCheckpoint(
|
||||
value: unknown,
|
||||
@@ -150,84 +95,12 @@ function isStoredCheckpoint(
|
||||
SAFE_IDENTIFIER.test(checkpoint.migrationId) &&
|
||||
isPositiveInteger(checkpoint.targetCodecVersion) &&
|
||||
(checkpoint.lastKey === null ||
|
||||
(typeof checkpoint.lastKey === "string" &&
|
||||
checkpoint.lastKey.length > 0 &&
|
||||
checkpoint.lastKey.length <= 200)) &&
|
||||
isValidBoundaryIdentifier(checkpoint.lastKey)) &&
|
||||
(checkpoint.state === "MORE" ||
|
||||
checkpoint.state === "COMPLETE")
|
||||
);
|
||||
}
|
||||
|
||||
function isStoredReceipt(
|
||||
value: unknown,
|
||||
): value is StoredIdempotencyReceipt {
|
||||
if (!value || typeof value !== "object") return false;
|
||||
const receipt = value as Partial<StoredIdempotencyReceipt>;
|
||||
return (
|
||||
typeof receipt.idempotencyKey === "string" &&
|
||||
receipt.idempotencyKey.length > 0 &&
|
||||
receipt.idempotencyKey.length <= 200 &&
|
||||
(receipt.operation === "PUT" ||
|
||||
receipt.operation === "DELETE") &&
|
||||
typeof receipt.recordKey === "string" &&
|
||||
receipt.recordKey.length > 0 &&
|
||||
receipt.recordKey.length <= 200 &&
|
||||
(receipt.expectedRevision === null ||
|
||||
isPositiveInteger(receipt.expectedRevision)) &&
|
||||
typeof receipt.fingerprint === "string" &&
|
||||
OPAQUE_SHA256_FINGERPRINT.test(receipt.fingerprint) &&
|
||||
(receipt.synchronization === "NONE" ||
|
||||
receipt.synchronization === "PENDING" ||
|
||||
receipt.synchronization === "CONFIRMED") &&
|
||||
isPositiveInteger(receipt.revision) &&
|
||||
typeof receipt.expiresAtEpochMs === "number" &&
|
||||
Number.isSafeInteger(receipt.expiresAtEpochMs) &&
|
||||
receipt.expiresAtEpochMs >= 0
|
||||
);
|
||||
}
|
||||
|
||||
function isStoredRetentionRecord(
|
||||
value: unknown,
|
||||
expectedKey: string,
|
||||
): value is StoredRetentionRecord {
|
||||
if (!value || typeof value !== "object") return false;
|
||||
const record = value as Partial<StoredRetentionRecord>;
|
||||
return (
|
||||
record.recordKey === expectedKey &&
|
||||
typeof record.writtenAtEpochMs === "number" &&
|
||||
Number.isSafeInteger(record.writtenAtEpochMs) &&
|
||||
record.writtenAtEpochMs >= 0 &&
|
||||
(record.synchronization === "NONE" ||
|
||||
record.synchronization === "PENDING" ||
|
||||
record.synchronization === "CONFIRMED") &&
|
||||
typeof record.measuredBytes === "number" &&
|
||||
Number.isSafeInteger(record.measuredBytes) &&
|
||||
record.measuredBytes >= 1 &&
|
||||
record.measuredBytes <= MAX_MEASURED_RECORD_BYTES &&
|
||||
(record.eligibleAtEpochMs === undefined ||
|
||||
(typeof record.eligibleAtEpochMs === "number" &&
|
||||
Number.isSafeInteger(record.eligibleAtEpochMs) &&
|
||||
record.eligibleAtEpochMs >= record.writtenAtEpochMs))
|
||||
);
|
||||
}
|
||||
|
||||
function isStoredDatasetBudget(
|
||||
value: unknown,
|
||||
): value is StoredDatasetBudget {
|
||||
if (!value || typeof value !== "object") return false;
|
||||
const budget = value as Partial<StoredDatasetBudget>;
|
||||
return (
|
||||
budget.bindingKey === INDEXEDDB_DATASET_BUDGET_KEY &&
|
||||
budget.budgetVersion === 1 &&
|
||||
typeof budget.usedBytes === "number" &&
|
||||
Number.isSafeInteger(budget.usedBytes) &&
|
||||
budget.usedBytes >= 0 &&
|
||||
typeof budget.receiptCount === "number" &&
|
||||
Number.isSafeInteger(budget.receiptCount) &&
|
||||
budget.receiptCount >= 0
|
||||
);
|
||||
}
|
||||
|
||||
function sameCheckpoint(
|
||||
left: StoredCheckpoint | null,
|
||||
right: StoredCheckpoint | null,
|
||||
@@ -242,14 +115,6 @@ function sameCheckpoint(
|
||||
);
|
||||
}
|
||||
|
||||
function countBucket(count: number): IndexedDbCountBucket {
|
||||
if (count <= 0) return "0";
|
||||
if (count === 1) return "1";
|
||||
if (count <= 10) return "2-10";
|
||||
if (count <= 100) return "11-100";
|
||||
return "101+";
|
||||
}
|
||||
|
||||
function invalidInput(): BrowserDataResult<never> {
|
||||
return browserDataFailure("INVALID_INPUT", "INDEXEDDB_MIGRATE");
|
||||
}
|
||||
@@ -273,19 +138,6 @@ function unsupported(): BrowserDataResult<never> {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* `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<never>): BrowserDataFailure {
|
||||
if (result.ok) {
|
||||
throw new TypeError("A browser data failure was expected.");
|
||||
}
|
||||
return result.error;
|
||||
}
|
||||
|
||||
function invalidInputFailure(): BrowserDataFailure {
|
||||
return failureOf(invalidInput());
|
||||
}
|
||||
@@ -705,7 +557,7 @@ export function createIndexedDbMaintenance<WireValue>(
|
||||
return;
|
||||
}
|
||||
|
||||
const rows: ScannedRecord[] = [];
|
||||
const rows: StoredRecord[] = [];
|
||||
// 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.
|
||||
@@ -830,28 +682,10 @@ export function createIndexedDbMaintenance<WireValue>(
|
||||
} catch {
|
||||
return migrationFailed();
|
||||
}
|
||||
let measuredPayloadBytes: number;
|
||||
try {
|
||||
measuredPayloadBytes =
|
||||
dependencies.migrationPolicy.measureStoredBytes(
|
||||
migratedPayload,
|
||||
);
|
||||
} catch {
|
||||
return migrationFailed();
|
||||
}
|
||||
const measuredBytes =
|
||||
measuredPayloadBytes +
|
||||
RECORD_ENVELOPE_RESERVATION_BYTES +
|
||||
source.key.length * 2;
|
||||
if (
|
||||
!Number.isSafeInteger(measuredPayloadBytes) ||
|
||||
measuredPayloadBytes < 0 ||
|
||||
!Number.isSafeInteger(measuredBytes) ||
|
||||
measuredBytes < 1 ||
|
||||
measuredBytes > MAX_MEASURED_RECORD_BYTES
|
||||
) {
|
||||
return migrationFailed();
|
||||
}
|
||||
const measuredBytes = measureRecordBytes(source.key, () =>
|
||||
dependencies.migrationPolicy.measureStoredBytes(migratedPayload),
|
||||
);
|
||||
if (measuredBytes === null) return migrationFailed();
|
||||
const afterMigration = clock();
|
||||
if (!afterMigration.ok) return afterMigration;
|
||||
if (afterMigration.value >= deadline) {
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
import type { IndexedDbSynchronizationState } from "../../../application/ports/browser-file-storage/indexeddb-port.ts";
|
||||
import type {
|
||||
BrowserDataFailure,
|
||||
BrowserDataResult,
|
||||
} from "../../../application/ports/browser-file-storage/shared.ts";
|
||||
import type { IndexedDbCountBucket } from "./indexeddb-types.ts";
|
||||
|
||||
/**
|
||||
* Q-6.5-7. The one definition of the rows the runtime and maintenance store:
|
||||
* their shapes, their validators and how a record is charged against the
|
||||
* dataset budget. Each call site used to carry its own copy, so a field added
|
||||
* to one copy made the other judge a healthy row corrupt.
|
||||
*/
|
||||
|
||||
export const INDEXEDDB_DATASET_BUDGET_KEY = "dataset-budget";
|
||||
|
||||
export const OPAQUE_SHA256_FINGERPRINT = /^[a-f0-9]{64}$/u;
|
||||
const RECORD_ENVELOPE_RESERVATION_BYTES = 512;
|
||||
const MAX_MEASURED_RECORD_BYTES = 2_147_483_647;
|
||||
|
||||
type StoredSynchronization = IndexedDbSynchronizationState | "NONE";
|
||||
|
||||
export type StoredRecord = Readonly<{
|
||||
key: string;
|
||||
codecVersion: number;
|
||||
revision: number;
|
||||
payload: unknown;
|
||||
}>;
|
||||
|
||||
export type StoredIdempotencyReceipt = Readonly<{
|
||||
idempotencyKey: string;
|
||||
operation: "PUT" | "DELETE";
|
||||
recordKey: string;
|
||||
expectedRevision: number | null;
|
||||
fingerprint: string;
|
||||
synchronization: StoredSynchronization;
|
||||
revision: number;
|
||||
expiresAtEpochMs: number;
|
||||
}>;
|
||||
|
||||
export type StoredRetentionRecord = Readonly<{
|
||||
recordKey: string;
|
||||
writtenAtEpochMs: number;
|
||||
synchronization: StoredSynchronization;
|
||||
measuredBytes: number;
|
||||
eligibleAtEpochMs?: number;
|
||||
}>;
|
||||
|
||||
export type StoredDatasetBudget = Readonly<{
|
||||
bindingKey: typeof INDEXEDDB_DATASET_BUDGET_KEY;
|
||||
budgetVersion: 1;
|
||||
usedBytes: number;
|
||||
receiptCount: number;
|
||||
}>;
|
||||
|
||||
export function isPositiveInteger(value: unknown): value is number {
|
||||
return typeof value === "number" && Number.isSafeInteger(value) && value >= 1;
|
||||
}
|
||||
|
||||
export function isValidBoundaryIdentifier(value: unknown): value is string {
|
||||
return typeof value === "string" && value.length > 0 && value.length <= 200;
|
||||
}
|
||||
|
||||
function isNonNegativeInteger(value: unknown): value is number {
|
||||
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
|
||||
}
|
||||
|
||||
function isStoredSynchronization(value: unknown): boolean {
|
||||
return value === "NONE" || value === "PENDING" || value === "CONFIRMED";
|
||||
}
|
||||
|
||||
export function isStoredRecord(
|
||||
value: unknown,
|
||||
expectedKey?: string,
|
||||
): value is StoredRecord {
|
||||
if (!value || typeof value !== "object") return false;
|
||||
const record = value as Partial<StoredRecord>;
|
||||
return (
|
||||
isValidBoundaryIdentifier(record.key) &&
|
||||
(expectedKey === undefined || record.key === expectedKey) &&
|
||||
isPositiveInteger(record.codecVersion) &&
|
||||
isPositiveInteger(record.revision) &&
|
||||
Object.hasOwn(record, "payload")
|
||||
);
|
||||
}
|
||||
|
||||
export function isStoredReceipt(
|
||||
value: unknown,
|
||||
): value is StoredIdempotencyReceipt {
|
||||
if (!value || typeof value !== "object") return false;
|
||||
const receipt = value as Partial<StoredIdempotencyReceipt>;
|
||||
return (
|
||||
isValidBoundaryIdentifier(receipt.idempotencyKey) &&
|
||||
(receipt.operation === "PUT" || receipt.operation === "DELETE") &&
|
||||
isValidBoundaryIdentifier(receipt.recordKey) &&
|
||||
(receipt.expectedRevision === null ||
|
||||
isPositiveInteger(receipt.expectedRevision)) &&
|
||||
typeof receipt.fingerprint === "string" &&
|
||||
OPAQUE_SHA256_FINGERPRINT.test(receipt.fingerprint) &&
|
||||
isStoredSynchronization(receipt.synchronization) &&
|
||||
isPositiveInteger(receipt.revision) &&
|
||||
isNonNegativeInteger(receipt.expiresAtEpochMs)
|
||||
);
|
||||
}
|
||||
|
||||
export function isStoredRetentionRecord(
|
||||
value: unknown,
|
||||
expectedKey?: string,
|
||||
): value is StoredRetentionRecord {
|
||||
if (!value || typeof value !== "object") return false;
|
||||
const record = value as Partial<StoredRetentionRecord>;
|
||||
return (
|
||||
isValidBoundaryIdentifier(record.recordKey) &&
|
||||
(expectedKey === undefined || record.recordKey === expectedKey) &&
|
||||
isNonNegativeInteger(record.writtenAtEpochMs) &&
|
||||
isStoredSynchronization(record.synchronization) &&
|
||||
isPositiveInteger(record.measuredBytes) &&
|
||||
record.measuredBytes <= MAX_MEASURED_RECORD_BYTES &&
|
||||
(record.eligibleAtEpochMs === undefined ||
|
||||
(Number.isSafeInteger(record.eligibleAtEpochMs) &&
|
||||
record.eligibleAtEpochMs >= record.writtenAtEpochMs))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A budget row's own shape. The dataset binding check additionally bounds
|
||||
* `usedBytes` by the policy's `hardBudgetBytes`; transactions check the bytes
|
||||
* they are about to add instead.
|
||||
*/
|
||||
export function isStoredDatasetBudget(
|
||||
value: unknown,
|
||||
): value is StoredDatasetBudget {
|
||||
if (!value || typeof value !== "object") return false;
|
||||
const budget = value as Partial<StoredDatasetBudget>;
|
||||
return (
|
||||
budget.bindingKey === INDEXEDDB_DATASET_BUDGET_KEY &&
|
||||
budget.budgetVersion === 1 &&
|
||||
isNonNegativeInteger(budget.usedBytes) &&
|
||||
isNonNegativeInteger(budget.receiptCount)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The bytes a record is charged: the codec's payload size, a fixed envelope
|
||||
* reservation and the key as UTF-16. `null` when the codec throws or the size
|
||||
* is out of range; each caller maps that to its own failure code.
|
||||
*/
|
||||
export function measureRecordBytes(
|
||||
key: string,
|
||||
measurePayload: () => number,
|
||||
): number | null {
|
||||
let payloadBytes: number;
|
||||
try {
|
||||
payloadBytes = measurePayload();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
const measuredBytes =
|
||||
payloadBytes + RECORD_ENVELOPE_RESERVATION_BYTES + key.length * 2;
|
||||
return isNonNegativeInteger(payloadBytes) &&
|
||||
isPositiveInteger(measuredBytes) &&
|
||||
measuredBytes <= MAX_MEASURED_RECORD_BYTES
|
||||
? measuredBytes
|
||||
: null;
|
||||
}
|
||||
|
||||
export function countBucket(count: number): IndexedDbCountBucket {
|
||||
if (count <= 0) return "0";
|
||||
if (count === 1) return "1";
|
||||
if (count <= 10) return "2-10";
|
||||
if (count <= 100) return "11-100";
|
||||
return "101+";
|
||||
}
|
||||
|
||||
/**
|
||||
* `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.
|
||||
*/
|
||||
export function failureOf(
|
||||
result: BrowserDataResult<never>,
|
||||
): BrowserDataFailure {
|
||||
if (result.ok) {
|
||||
throw new TypeError("A browser data failure was expected.");
|
||||
}
|
||||
return result.error;
|
||||
}
|
||||
@@ -38,7 +38,6 @@ import {
|
||||
import { mapIndexedDbException } from "./indexeddb-failure.ts";
|
||||
import {
|
||||
createIndexedDbDatasetBinding,
|
||||
INDEXEDDB_DATASET_BUDGET_KEY,
|
||||
indexedDbPhysicalDatabaseName,
|
||||
queueIndexedDbUpgradeBinding,
|
||||
verifyIndexedDbDatasetBinding,
|
||||
@@ -48,47 +47,30 @@ import {
|
||||
assertIndexedDbRuntimeStores,
|
||||
validateIndexedDbMigrations,
|
||||
} from "./indexeddb-migrations.ts";
|
||||
import {
|
||||
countBucket,
|
||||
failureOf,
|
||||
INDEXEDDB_DATASET_BUDGET_KEY,
|
||||
isPositiveInteger,
|
||||
isStoredDatasetBudget,
|
||||
isStoredReceipt,
|
||||
isStoredRecord,
|
||||
isStoredRetentionRecord,
|
||||
isValidBoundaryIdentifier,
|
||||
measureRecordBytes,
|
||||
OPAQUE_SHA256_FINGERPRINT,
|
||||
type StoredDatasetBudget,
|
||||
type StoredIdempotencyReceipt,
|
||||
type StoredRecord,
|
||||
type StoredRetentionRecord,
|
||||
} from "./indexeddb-records.ts";
|
||||
import type {
|
||||
IndexedDbCountBucket,
|
||||
IndexedDbKeyRangePlan,
|
||||
IndexedDbObservation,
|
||||
IndexedDbQueryPlan,
|
||||
IndexedDbRuntimeDependencies,
|
||||
} from "./indexeddb-types.ts";
|
||||
|
||||
type StoredRecord = Readonly<{
|
||||
key: string;
|
||||
codecVersion: number;
|
||||
revision: number;
|
||||
payload: unknown;
|
||||
}>;
|
||||
|
||||
type StoredIdempotencyReceipt = Readonly<{
|
||||
idempotencyKey: string;
|
||||
operation: "PUT" | "DELETE";
|
||||
recordKey: string;
|
||||
expectedRevision: number | null;
|
||||
fingerprint: string;
|
||||
synchronization: IndexedDbSynchronizationState | "NONE";
|
||||
revision: number;
|
||||
expiresAtEpochMs: number;
|
||||
}>;
|
||||
|
||||
type StoredRetentionRecord = Readonly<{
|
||||
recordKey: string;
|
||||
writtenAtEpochMs: number;
|
||||
synchronization: IndexedDbSynchronizationState | "NONE";
|
||||
measuredBytes: number;
|
||||
eligibleAtEpochMs?: number;
|
||||
}>;
|
||||
|
||||
type StoredDatasetBudget = Readonly<{
|
||||
bindingKey: typeof INDEXEDDB_DATASET_BUDGET_KEY;
|
||||
budgetVersion: 1;
|
||||
usedBytes: number;
|
||||
receiptCount: number;
|
||||
}>;
|
||||
|
||||
type ReceiptLookup =
|
||||
| Readonly<{ kind: "MISSING" | "EXPIRED" }>
|
||||
| Readonly<{
|
||||
@@ -102,7 +84,6 @@ type TransactionContext<Value> = IndexedDbTransactionContext<
|
||||
>;
|
||||
|
||||
const SAFE_DATABASE_NAME = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/u;
|
||||
const OPAQUE_SHA256_FINGERPRINT = /^[a-f0-9]{64}$/u;
|
||||
const DELETE_OPERATION_FINGERPRINT =
|
||||
"65daeb378bdec35d90224389f6e10917bcc0b94c90c489014ba156dd6cbf9350";
|
||||
const MAX_QUERY_LIMIT = 1_000;
|
||||
@@ -113,31 +94,9 @@ const MAX_RECEIPT_RETENTION_MS = 31 * 24 * 60 * 60 * 1_000;
|
||||
const MAX_LIFECYCLE_ROWS = 500;
|
||||
const MAX_LIFECYCLE_DURATION_MS = 30_000;
|
||||
const OPAQUE_AUTHORITY_PROOF = /^[A-Za-z0-9_-]{16,128}$/u;
|
||||
const RECORD_ENVELOPE_RESERVATION_BYTES = 512;
|
||||
const MAX_MEASURED_RECORD_BYTES = 2_147_483_647;
|
||||
const MAX_QUERY_SCANNED_ROWS = 5_000;
|
||||
const MAX_IDEMPOTENCY_RECEIPTS = 1_000_000;
|
||||
|
||||
function countBucket(count: number): IndexedDbCountBucket {
|
||||
if (count <= 0) return "0";
|
||||
if (count === 1) return "1";
|
||||
if (count <= 10) return "2-10";
|
||||
if (count <= 100) return "11-100";
|
||||
return "101+";
|
||||
}
|
||||
|
||||
function isValidBoundaryIdentifier(value: string): boolean {
|
||||
return (
|
||||
typeof value === "string" &&
|
||||
value.length > 0 &&
|
||||
value.length <= 200
|
||||
);
|
||||
}
|
||||
|
||||
function isRevision(value: unknown): value is number {
|
||||
return Number.isSafeInteger(value) && typeof value === "number" && value >= 1;
|
||||
}
|
||||
|
||||
function isBoundedCursorKey(value: unknown): value is IDBValidKey {
|
||||
const pending: Array<Readonly<{ value: unknown; depth: number }>> = [
|
||||
{ value, depth: 0 },
|
||||
@@ -222,86 +181,6 @@ function isBoundedRangePlan(
|
||||
}
|
||||
}
|
||||
|
||||
function isStoredRecord(value: unknown, expectedKey?: string): value is StoredRecord {
|
||||
if (!value || typeof value !== "object") return false;
|
||||
const record = value as Partial<StoredRecord>;
|
||||
return (
|
||||
typeof record.key === "string" &&
|
||||
isValidBoundaryIdentifier(record.key) &&
|
||||
(expectedKey === undefined || record.key === expectedKey) &&
|
||||
isRevision(record.codecVersion) &&
|
||||
isRevision(record.revision) &&
|
||||
Object.hasOwn(record, "payload")
|
||||
);
|
||||
}
|
||||
|
||||
function isStoredReceipt(value: unknown): value is StoredIdempotencyReceipt {
|
||||
if (!value || typeof value !== "object") return false;
|
||||
const receipt = value as Partial<StoredIdempotencyReceipt>;
|
||||
return (
|
||||
typeof receipt.idempotencyKey === "string" &&
|
||||
isValidBoundaryIdentifier(receipt.idempotencyKey) &&
|
||||
(receipt.operation === "PUT" || receipt.operation === "DELETE") &&
|
||||
typeof receipt.recordKey === "string" &&
|
||||
isValidBoundaryIdentifier(receipt.recordKey) &&
|
||||
(receipt.expectedRevision === null ||
|
||||
isRevision(receipt.expectedRevision)) &&
|
||||
typeof receipt.fingerprint === "string" &&
|
||||
OPAQUE_SHA256_FINGERPRINT.test(receipt.fingerprint) &&
|
||||
(receipt.synchronization === "NONE" ||
|
||||
receipt.synchronization === "PENDING" ||
|
||||
receipt.synchronization === "CONFIRMED") &&
|
||||
isRevision(receipt.revision) &&
|
||||
typeof receipt.expiresAtEpochMs === "number" &&
|
||||
Number.isSafeInteger(receipt.expiresAtEpochMs) &&
|
||||
receipt.expiresAtEpochMs >= 0
|
||||
);
|
||||
}
|
||||
|
||||
function isStoredRetentionRecord(
|
||||
value: unknown,
|
||||
expectedKey?: string,
|
||||
): value is StoredRetentionRecord {
|
||||
if (!value || typeof value !== "object") return false;
|
||||
const record = value as Partial<StoredRetentionRecord>;
|
||||
return (
|
||||
typeof record.recordKey === "string" &&
|
||||
isValidBoundaryIdentifier(record.recordKey) &&
|
||||
(expectedKey === undefined || record.recordKey === expectedKey) &&
|
||||
typeof record.writtenAtEpochMs === "number" &&
|
||||
Number.isSafeInteger(record.writtenAtEpochMs) &&
|
||||
record.writtenAtEpochMs >= 0 &&
|
||||
(record.synchronization === "NONE" ||
|
||||
record.synchronization === "PENDING" ||
|
||||
record.synchronization === "CONFIRMED") &&
|
||||
typeof record.measuredBytes === "number" &&
|
||||
Number.isSafeInteger(record.measuredBytes) &&
|
||||
record.measuredBytes >= 1 &&
|
||||
record.measuredBytes <= MAX_MEASURED_RECORD_BYTES &&
|
||||
(record.eligibleAtEpochMs === undefined ||
|
||||
(typeof record.eligibleAtEpochMs === "number" &&
|
||||
Number.isSafeInteger(record.eligibleAtEpochMs) &&
|
||||
record.eligibleAtEpochMs >= record.writtenAtEpochMs))
|
||||
);
|
||||
}
|
||||
|
||||
function isStoredDatasetBudget(
|
||||
value: unknown,
|
||||
): value is StoredDatasetBudget {
|
||||
if (!value || typeof value !== "object") return false;
|
||||
const budget = value as Partial<StoredDatasetBudget>;
|
||||
return (
|
||||
budget.bindingKey === INDEXEDDB_DATASET_BUDGET_KEY &&
|
||||
budget.budgetVersion === 1 &&
|
||||
typeof budget.usedBytes === "number" &&
|
||||
Number.isSafeInteger(budget.usedBytes) &&
|
||||
budget.usedBytes >= 0 &&
|
||||
typeof budget.receiptCount === "number" &&
|
||||
Number.isSafeInteger(budget.receiptCount) &&
|
||||
budget.receiptCount >= 0
|
||||
);
|
||||
}
|
||||
|
||||
function normalizeCursorKey(value: IDBValidKey): IndexedDbCursorKey {
|
||||
if (Array.isArray(value)) {
|
||||
return Object.freeze(value.map((entry) => normalizeCursorKey(entry)));
|
||||
@@ -405,18 +284,6 @@ 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<never>): BrowserDataFailure {
|
||||
if (result.ok) {
|
||||
throw new TypeError("A browser data failure was expected.");
|
||||
}
|
||||
return result.error;
|
||||
}
|
||||
|
||||
function mappedFailure(
|
||||
error: unknown,
|
||||
operation: BrowserDataOperation,
|
||||
@@ -1475,7 +1342,7 @@ export function createIndexedDbRuntime<Value, WireValue, Query>(
|
||||
!isValidBoundaryIdentifier(input.key) ||
|
||||
!isValidBoundaryIdentifier(input.idempotencyKey) ||
|
||||
(input.expectedRevision !== null &&
|
||||
!isRevision(input.expectedRevision)) ||
|
||||
!isPositiveInteger(input.expectedRevision)) ||
|
||||
(storagePolicySnapshot.retention.kind === "UNTIL_SYNCED"
|
||||
? input.synchronization !== "PENDING" &&
|
||||
input.synchronization !== "CONFIRMED"
|
||||
@@ -1499,26 +1366,10 @@ export function createIndexedDbRuntime<Value, WireValue, Query>(
|
||||
} catch (error) {
|
||||
return mapIndexedDbException(error, operation);
|
||||
}
|
||||
let measuredPayloadBytes: number;
|
||||
try {
|
||||
measuredPayloadBytes =
|
||||
dependencies.codec.measureStoredBytes(wireValue);
|
||||
} catch {
|
||||
return invalidInput(operation);
|
||||
}
|
||||
const measuredBytes =
|
||||
measuredPayloadBytes +
|
||||
RECORD_ENVELOPE_RESERVATION_BYTES +
|
||||
input.key.length * 2;
|
||||
if (
|
||||
!Number.isSafeInteger(measuredPayloadBytes) ||
|
||||
measuredPayloadBytes < 0 ||
|
||||
!Number.isSafeInteger(measuredBytes) ||
|
||||
measuredBytes < 1 ||
|
||||
measuredBytes > MAX_MEASURED_RECORD_BYTES
|
||||
) {
|
||||
return invalidInput(operation);
|
||||
}
|
||||
const measuredBytes = measureRecordBytes(input.key, () =>
|
||||
dependencies.codec.measureStoredBytes(wireValue),
|
||||
);
|
||||
if (measuredBytes === null) return invalidInput(operation);
|
||||
const cancelled = abortedResult(input.signal, operation);
|
||||
if (cancelled) return cancelled;
|
||||
|
||||
@@ -1887,7 +1738,7 @@ export function createIndexedDbRuntime<Value, WireValue, Query>(
|
||||
if (
|
||||
!isValidBoundaryIdentifier(sourceInput.key) ||
|
||||
!isValidBoundaryIdentifier(sourceInput.idempotencyKey) ||
|
||||
!isRevision(sourceInput.expectedRevision)
|
||||
!isPositiveInteger(sourceInput.expectedRevision)
|
||||
) {
|
||||
return observeResult(operation, invalidInput(operation));
|
||||
}
|
||||
|
||||
@@ -246,19 +246,12 @@ export function createOpfsByteStoreAdapter(
|
||||
onProgress: request.onProgress,
|
||||
});
|
||||
if (!prepared.ok) {
|
||||
const compensated = await compensatePreparedPut(
|
||||
begun.value,
|
||||
physicalGenerationId,
|
||||
);
|
||||
if (!compensated.ok) {
|
||||
return observeFailure(
|
||||
compensated,
|
||||
dependencies.observer,
|
||||
request.source.byteLength!,
|
||||
);
|
||||
}
|
||||
return observeFailure(
|
||||
prepared,
|
||||
await compensatePreparedPut(
|
||||
begun.value,
|
||||
physicalGenerationId,
|
||||
prepared.error,
|
||||
),
|
||||
dependencies.observer,
|
||||
request.source.byteLength!,
|
||||
);
|
||||
@@ -270,19 +263,12 @@ export function createOpfsByteStoreAdapter(
|
||||
prepared.value,
|
||||
);
|
||||
if (!filesReady.ok) {
|
||||
const compensated = await compensatePreparedPut(
|
||||
begun.value,
|
||||
physicalGenerationId,
|
||||
);
|
||||
if (!compensated.ok) {
|
||||
return observeFailure(
|
||||
compensated,
|
||||
dependencies.observer,
|
||||
request.source.byteLength!,
|
||||
);
|
||||
}
|
||||
return observeFailure(
|
||||
rebaseFailure(filesReady.error, "OBJECT_WRITE"),
|
||||
await compensatePreparedPut(
|
||||
begun.value,
|
||||
physicalGenerationId,
|
||||
filesReady.error,
|
||||
),
|
||||
dependencies.observer,
|
||||
request.source.byteLength!,
|
||||
);
|
||||
@@ -928,29 +914,36 @@ export function createOpfsByteStoreAdapter(
|
||||
* `ALREADY_CLEAN`. A timeout, crash, malformed response or `EFFECT_UNKNOWN`
|
||||
* keeps `PREPARING`/`FILES_READY` in place and asks for reconciliation.
|
||||
*/
|
||||
/**
|
||||
* Compensates a put that failed before commit and returns that failure.
|
||||
* Q-6.5-9. When the cleanup or the journal rollback does not complete, the
|
||||
* journal row stays for reconciliation: the put keeps its own code and only
|
||||
* its recovery becomes RECONCILE.
|
||||
*/
|
||||
async function compensatePreparedPut(
|
||||
transaction: OpfsJournalTransaction,
|
||||
physicalGenerationId: OpfsPhysicalGenerationId,
|
||||
): Promise<BrowserDataResult<void>> {
|
||||
failure: BrowserDataFailure,
|
||||
): Promise<BrowserFailureResult> {
|
||||
const cleanup = await dependencies.worker.abortPreparedPut({
|
||||
scope: transaction.scope,
|
||||
transactionId: transaction.transactionId,
|
||||
physicalGenerationId,
|
||||
...(compensationSignal ? { signal: compensationSignal } : {}),
|
||||
});
|
||||
if (!cleanup.ok || cleanup.value.kind === "EFFECT_UNKNOWN") {
|
||||
return browserDataFailure("CONFLICT", "OBJECT_RECONCILE", {
|
||||
recovery: "RETRY",
|
||||
});
|
||||
}
|
||||
const rolledBack = await dependencies.journal.rollback(
|
||||
transaction.transactionId,
|
||||
transaction.fencingToken,
|
||||
const compensated =
|
||||
cleanup.ok &&
|
||||
cleanup.value.kind !== "EFFECT_UNKNOWN" &&
|
||||
(
|
||||
await dependencies.journal.rollback(
|
||||
transaction.transactionId,
|
||||
transaction.fencingToken,
|
||||
)
|
||||
).ok;
|
||||
return rebaseFailure(
|
||||
compensated ? failure : { ...failure, recovery: "RECONCILE" },
|
||||
"OBJECT_WRITE",
|
||||
);
|
||||
if (!rolledBack.ok) {
|
||||
return rebaseFailure(rolledBack.error, "OBJECT_RECONCILE");
|
||||
}
|
||||
return browserDataSuccess(undefined);
|
||||
}
|
||||
|
||||
async function reconcileTransaction(
|
||||
|
||||
@@ -342,7 +342,7 @@ export function createOpfsWorkerGateway(
|
||||
) {
|
||||
const verified = await invoke(
|
||||
"OBJECT_READ",
|
||||
{ kind: "VERIFY_OBJECT", preparedObject },
|
||||
{ kind: "VERIFY_OBJECT", preparedObject, manifestOnly: true },
|
||||
signal,
|
||||
[],
|
||||
(value) => (typeof value === "boolean" ? value : null),
|
||||
|
||||
@@ -77,6 +77,12 @@ export type OpfsWorkerRequest =
|
||||
protocolVersion: typeof OPFS_WORKER_PROTOCOL_VERSION;
|
||||
kind: "VERIFY_OBJECT";
|
||||
preparedObject: OpfsPreparedObject;
|
||||
/**
|
||||
* Q-6.5-6. Compare the stored manifest only. `openObject` sends it: the
|
||||
* stream then verifies each chunk as it reads it and the root digest
|
||||
* before it releases the last chunk, so an object is not read twice.
|
||||
*/
|
||||
manifestOnly?: true;
|
||||
}>
|
||||
| Readonly<{
|
||||
requestId: string;
|
||||
|
||||
@@ -248,7 +248,10 @@ export function createOpfsWorkerRuntime(
|
||||
return success(
|
||||
request.requestId,
|
||||
request.kind,
|
||||
await verifyObject(request.preparedObject),
|
||||
await verifyObject(
|
||||
request.preparedObject,
|
||||
request.manifestOnly === true,
|
||||
),
|
||||
);
|
||||
case "READ_CHUNK":
|
||||
return success(
|
||||
@@ -693,6 +696,7 @@ export function createOpfsWorkerRuntime(
|
||||
|
||||
async function verifyObject(
|
||||
expected: OpfsPreparedObject,
|
||||
manifestOnly: boolean,
|
||||
): Promise<boolean> {
|
||||
if (!isPreparedObject(expected)) return false;
|
||||
let stored: unknown;
|
||||
@@ -708,15 +712,10 @@ export function createOpfsWorkerRuntime(
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
const rootDigestHex = await treeDigestHex(
|
||||
dependencies.crypto,
|
||||
expected.descriptor.integrity.chunkSizeBytes,
|
||||
expected.descriptor.byteLength,
|
||||
expected.chunks,
|
||||
);
|
||||
if (rootDigestHex !== expected.descriptor.integrity.rootDigestHex) {
|
||||
return false;
|
||||
}
|
||||
// Q-6.5-6. READ_CHUNK checks the root digest at the last chunk; an empty
|
||||
// object has no chunk to read, so its stream ends here.
|
||||
if (manifestOnly && expected.chunks.length > 0) return true;
|
||||
if (!(await rootDigestMatches(expected))) return false;
|
||||
for (const chunk of expected.chunks) {
|
||||
let bytes: Uint8Array;
|
||||
try {
|
||||
@@ -737,6 +736,19 @@ export function createOpfsWorkerRuntime(
|
||||
return true;
|
||||
}
|
||||
|
||||
async function rootDigestMatches(
|
||||
expected: OpfsPreparedObject,
|
||||
): Promise<boolean> {
|
||||
return (
|
||||
(await treeDigestHex(
|
||||
dependencies.crypto,
|
||||
expected.descriptor.integrity.chunkSizeBytes,
|
||||
expected.descriptor.byteLength,
|
||||
expected.chunks,
|
||||
)) === expected.descriptor.integrity.rootDigestHex
|
||||
);
|
||||
}
|
||||
|
||||
async function readVerifiedChunk(
|
||||
expected: OpfsPreparedObject,
|
||||
sequence: number,
|
||||
@@ -757,7 +769,12 @@ export function createOpfsWorkerRuntime(
|
||||
);
|
||||
if (
|
||||
bytes.byteLength !== reference.byteLength ||
|
||||
(await sha256Hex(dependencies.crypto, bytes)) !== reference.digestHex
|
||||
(await sha256Hex(dependencies.crypto, bytes)) !== reference.digestHex ||
|
||||
// Q-6.5-6. The last chunk is not released until the chunk list is
|
||||
// proven against the root digest, so a stream never ends as a success
|
||||
// on an unverified object.
|
||||
(sequence === expected.chunks.length - 1 &&
|
||||
!(await rootDigestMatches(expected)))
|
||||
) {
|
||||
throw new OpfsRuntimeFailure("INTEGRITY_FAILED");
|
||||
}
|
||||
|
||||
@@ -6,6 +6,10 @@ import type {
|
||||
} from "../../contracts/telemetry.ts";
|
||||
import type { TelemetryPort } from "../../application/ports/telemetry-port.ts";
|
||||
import { assertBoundedCapacity } from "../platform/bounded-capacity.ts";
|
||||
import {
|
||||
createTelemetryCollector,
|
||||
type TelemetryCollector,
|
||||
} from "./telemetry-collector.ts";
|
||||
|
||||
export type TelemetryAdapter = TelemetryPort &
|
||||
Readonly<{
|
||||
@@ -36,10 +40,14 @@ export type TelemetryAdapterOptions = Readonly<{
|
||||
monotonicNow?: () => number;
|
||||
setTimer?: (callback: () => void, ms: number) => unknown;
|
||||
clearTimer?: (handle: unknown) => void;
|
||||
/**
|
||||
* Q-6.9-4. The collector transport shared with feature telemetry. When set,
|
||||
* it owns `fetcher`, `lifecycle`, `maxSendsPerMinute` and `monotonicNow`.
|
||||
*/
|
||||
collector?: TelemetryCollector;
|
||||
}>;
|
||||
|
||||
export const DEFAULT_TELEMETRY_SENDS_PER_MINUTE = 20;
|
||||
const SEND_WINDOW_MS = 60_000;
|
||||
export { DEFAULT_TELEMETRY_SENDS_PER_MINUTE } from "./telemetry-collector.ts";
|
||||
|
||||
export const noOpTelemetry: TelemetryAdapter = Object.freeze({
|
||||
emit: () => {},
|
||||
@@ -67,27 +75,28 @@ export function createTelemetryAdapter(
|
||||
return noOpTelemetry;
|
||||
}
|
||||
|
||||
const endpoint = options.endpoint;
|
||||
const fetcher = options.fetcher ?? fetch;
|
||||
const maxQueue = assertBoundedCapacity(
|
||||
options.maxQueue ?? 100,
|
||||
MAX_TELEMETRY_QUEUE,
|
||||
"telemetry maxQueue",
|
||||
);
|
||||
const schedule = options.schedule ?? queueMicrotask;
|
||||
const maxSendsPerMinute = assertBoundedCapacity(
|
||||
options.maxSendsPerMinute ?? DEFAULT_TELEMETRY_SENDS_PER_MINUTE,
|
||||
MAX_TELEMETRY_QUEUE,
|
||||
"telemetry maxSendsPerMinute",
|
||||
);
|
||||
const monotonicNow = options.monotonicNow ?? (() => performance.now());
|
||||
const collector =
|
||||
options.collector ??
|
||||
createTelemetryCollector({
|
||||
endpoint: options.endpoint,
|
||||
...(options.fetcher === undefined ? {} : { fetcher: options.fetcher }),
|
||||
...(options.maxSendsPerMinute === undefined
|
||||
? {}
|
||||
: { maxSendsPerMinute: options.maxSendsPerMinute }),
|
||||
...(options.monotonicNow === undefined ? {} : { now: options.monotonicNow }),
|
||||
...(options.lifecycle === undefined ? {} : { lifecycle: options.lifecycle }),
|
||||
});
|
||||
const setTimer =
|
||||
options.setTimer ?? ((callback: () => void, ms: number) => setTimeout(callback, ms));
|
||||
const clearTimer =
|
||||
options.clearTimer ??
|
||||
((handle: unknown) => clearTimeout(handle as ReturnType<typeof setTimeout>));
|
||||
/** Send instants inside the current window; never longer than the limit. */
|
||||
const sendTimes: number[] = [];
|
||||
let rateTimer: unknown = null;
|
||||
const queue: TelemetryEvent[] = [];
|
||||
let lifecycleState: TelemetryLifecycle = "ACTIVE";
|
||||
@@ -99,12 +108,6 @@ export function createTelemetryAdapter(
|
||||
let dropped = 0;
|
||||
const dropReasons = new Map<string, number>();
|
||||
let lastDeliveryEvidence: TelemetryEvent | null = null;
|
||||
const lifecycle =
|
||||
options.lifecycle ??
|
||||
(typeof globalThis.addEventListener === "function" &&
|
||||
typeof globalThis.removeEventListener === "function"
|
||||
? globalThis
|
||||
: undefined);
|
||||
|
||||
function recordDrop(reason: string, count = 1): void {
|
||||
const safeReason =
|
||||
@@ -173,16 +176,8 @@ export function createTelemetryAdapter(
|
||||
scheduleFlush();
|
||||
}
|
||||
|
||||
function rateAllows(at: number): boolean {
|
||||
while (sendTimes.length > 0 && at - (sendTimes[0] as number) >= SEND_WINDOW_MS) {
|
||||
sendTimes.shift();
|
||||
}
|
||||
return sendTimes.length < maxSendsPerMinute;
|
||||
}
|
||||
|
||||
function armRateTimer(at: number): void {
|
||||
function armRateTimer(reopenIn: number): void {
|
||||
if (rateTimer !== null || lifecycleState === "DISPOSED") return;
|
||||
const reopenIn = Math.max(1, (sendTimes[0] ?? at) + SEND_WINDOW_MS - at);
|
||||
rateTimer = setTimer(() => {
|
||||
rateTimer = null;
|
||||
void flush();
|
||||
@@ -198,31 +193,18 @@ export function createTelemetryAdapter(
|
||||
if (lifecycleState === "DISPOSED" || queue.length === 0) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
const at = monotonicNow();
|
||||
if (!rateAllows(at)) {
|
||||
if (!bypassRate) {
|
||||
armRateTimer(at);
|
||||
return Promise.resolve();
|
||||
}
|
||||
const reopenIn = collector.sendRate.take(bypassRate);
|
||||
if (reopenIn > 0) {
|
||||
armRateTimer(reopenIn);
|
||||
return Promise.resolve();
|
||||
}
|
||||
sendTimes.push(at);
|
||||
if (sendTimes.length > maxSendsPerMinute) sendTimes.shift();
|
||||
const generation = scheduleGeneration;
|
||||
const run = async () => {
|
||||
const batch = queue.splice(0, queue.length);
|
||||
const controller = new AbortController();
|
||||
activeSink = controller;
|
||||
try {
|
||||
const response = await fetcher(endpoint, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ events: batch }),
|
||||
keepalive: true,
|
||||
signal: controller.signal,
|
||||
});
|
||||
// A sink that ignored the abort must not update post-dispose state.
|
||||
if (generation !== scheduleGeneration) return;
|
||||
if (!response.ok) recordDrop("sink-failure", batch.length);
|
||||
await collector.post(batch, controller.signal);
|
||||
} catch {
|
||||
if (generation !== scheduleGeneration) return;
|
||||
recordDrop("sink-failure", batch.length);
|
||||
@@ -239,10 +221,9 @@ export function createTelemetryAdapter(
|
||||
}
|
||||
|
||||
// Page exit is the last chance to deliver: it may exceed the window once.
|
||||
const flushBeforePageExit = () => {
|
||||
const stopPageExitFlush = collector.onPageExit(() => {
|
||||
void flush(true);
|
||||
};
|
||||
lifecycle?.addEventListener("pagehide", flushBeforePageExit);
|
||||
});
|
||||
|
||||
/**
|
||||
* N-04. Terminal disposal: one state transition, no further admission, no
|
||||
@@ -253,7 +234,7 @@ export function createTelemetryAdapter(
|
||||
lifecycleState = "DISPOSED";
|
||||
scheduleGeneration += 1;
|
||||
scheduled = false;
|
||||
lifecycle?.removeEventListener("pagehide", flushBeforePageExit);
|
||||
stopPageExitFlush();
|
||||
if (rateTimer !== null) clearTimer(rateTimer);
|
||||
rateTimer = null;
|
||||
queue.length = 0;
|
||||
|
||||
@@ -6,6 +6,10 @@ import {
|
||||
type TelemetryPipelineBudget,
|
||||
type TelemetryTransport,
|
||||
} from "../../platform/telemetry/telemetry-pipeline.ts";
|
||||
import {
|
||||
createTelemetryCollector,
|
||||
type TelemetryCollector,
|
||||
} from "./telemetry-collector.ts";
|
||||
|
||||
/**
|
||||
* Spec §24–§27. Adapter side of the provider-neutral feature telemetry port.
|
||||
@@ -15,26 +19,31 @@ import {
|
||||
* transport here, never in feature code.
|
||||
*/
|
||||
export function createFetchTelemetryTransport(
|
||||
options: Readonly<{ endpoint: string; fetcher?: typeof fetch }>,
|
||||
options: Readonly<{
|
||||
endpoint: string;
|
||||
fetcher?: typeof fetch;
|
||||
/** Q-6.9-4. Posts through this shared collector instead of a private one. */
|
||||
collector?: TelemetryCollector;
|
||||
/** Aborts in-flight batches (feature telemetry disposal). */
|
||||
signal?: AbortSignal;
|
||||
}>,
|
||||
): TelemetryTransport {
|
||||
const fetcher = options.fetcher ?? fetch;
|
||||
const collector =
|
||||
options.collector ??
|
||||
createTelemetryCollector({
|
||||
endpoint: options.endpoint,
|
||||
...(options.fetcher === undefined ? {} : { fetcher: options.fetcher }),
|
||||
});
|
||||
return Object.freeze({
|
||||
async send(batch: readonly TelemetryBatchItem[]): Promise<void> {
|
||||
const response = await fetcher(options.endpoint, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
events: batch.map((item) => ({
|
||||
...item.event,
|
||||
fingerprint: item.fingerprint,
|
||||
occurrences: item.occurrences,
|
||||
})),
|
||||
}),
|
||||
keepalive: true,
|
||||
credentials: "omit",
|
||||
cache: "no-store",
|
||||
});
|
||||
if (!response.ok) throw new Error("telemetry collector rejected batch");
|
||||
send(batch: readonly TelemetryBatchItem[]): Promise<void> {
|
||||
return collector.post(
|
||||
batch.map((item) => ({
|
||||
...item.event,
|
||||
fingerprint: item.fingerprint,
|
||||
occurrences: item.occurrences,
|
||||
})),
|
||||
options.signal,
|
||||
);
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -65,14 +74,42 @@ export function createFeatureTelemetry(
|
||||
endpoint?: string;
|
||||
fetcher?: typeof fetch;
|
||||
budget?: TelemetryPipelineBudget;
|
||||
/**
|
||||
* Q-6.9-4. The collector shared with the application telemetry port: one
|
||||
* send-rate window and one page-exit flush for the endpoint. When set, it
|
||||
* owns `fetcher` and the send rate.
|
||||
*/
|
||||
collector?: TelemetryCollector;
|
||||
}>,
|
||||
): TelemetryPipeline {
|
||||
if (!options.enabled || !options.endpoint) return DISABLED_FEATURE_TELEMETRY;
|
||||
return createTelemetryPipeline({
|
||||
transport: createFetchTelemetryTransport({
|
||||
const budget = options.budget ?? DEFAULT_TELEMETRY_PIPELINE_BUDGET;
|
||||
const collector =
|
||||
options.collector ??
|
||||
createTelemetryCollector({
|
||||
endpoint: options.endpoint,
|
||||
...(options.fetcher === undefined ? {} : { fetcher: options.fetcher }),
|
||||
maxSendsPerMinute: budget.maxSendsPerMinute,
|
||||
});
|
||||
const lifetime = new AbortController();
|
||||
const pipeline = createTelemetryPipeline({
|
||||
transport: createFetchTelemetryTransport({
|
||||
endpoint: options.endpoint,
|
||||
collector,
|
||||
signal: lifetime.signal,
|
||||
}),
|
||||
budget: options.budget ?? DEFAULT_TELEMETRY_PIPELINE_BUDGET,
|
||||
budget,
|
||||
sendRate: collector.sendRate,
|
||||
});
|
||||
const stopPageExitFlush = collector.onPageExit(() => {
|
||||
void pipeline.flush();
|
||||
});
|
||||
return Object.freeze({
|
||||
...pipeline,
|
||||
dispose(): void {
|
||||
stopPageExitFlush();
|
||||
lifetime.abort();
|
||||
pipeline.dispose();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user