refactor(realtime): merge snapshot and race helpers, move shared parsers to kernel (Q-6.4-8)
Realtime kept three DataSnapshot readers and about ten hand-written abort/timeout races, and two parsers had drifted copies in other adapters. Snapshot: reconnect-coordinator and bounded-poll now use result.ts captureRealtimeDataSnapshot (+ `source`, variadic hasExactSnapshotKeys). Kept the result.ts rules, the stricter ones: Object.hasOwn instead of `"value" in` (prototype pollution), enumerable fields only, keys read from one descriptor snapshot, frozen computed at snapshot time instead of a later Object.isFrozen. Poll therefore now rejects non-enumerable fields; it also accepts null-prototype records, which the other two copies already did (pure data, no inherited accessors). Characterization test added for both in bounded-poll-coordinator.test.ts. Race: one raceRealtimeTask(task, signal, deadline) in result.ts, built on kernel createAbortableOperation, replaces fetch-sse timed/cancelReader, reconnect race/drain (the drain keeps a host timer via timerDeadline, since the clock itself may hang), poll awaitTaskOrAbort/awaitWithinLease, live-poll checkpoint + two quiescence races (now one), stream-coordinator deadline/recovery-wait/close-drain, and the two WS inline races. Kept semantics: deadline armed first and wins a tie (poll lease), task still starts when the clock throws (reader cancel), collaborator rejections still reach stream-coordinator callers, scheduler install failure still fails closed as a timeout. Small change: nothing starts once the signal is already aborted (WS apply / SSE onEvent / reader.read could run just before being reported ABORTED). The mapping adds one microtask per race, so the reconnect test flush() helper gets 16 turns instead of 8. Kernel: parseRetryAfterDelay moves to platform/retry-after.ts (realtime re-exports it; http retry-policy parseRetryAfter now delegates, so it rejects "", " ", "1e3", "1.5", "0x10" and non-IMF dates it used to accept). json-member-scanner moves to platform/; web-push push-codec uses it instead of its top-level-only duplicate-key check, so nested duplicates are rejected too. INVENTORY 136 -> 137, detail tables updated. Tests: RED for http strict Retry-After, web-push nested duplicate, poll snapshot rules; new direct raceRealtimeTask tests. Gates: architecture, types app/test (+ service-worker/web-worker), lint, adapter-inventory (abort ratchet 21/21), test:unit, test:component, realtime-boundaries, integration/platform all pass. Realtime bundle 40346 -> 39433 gzip. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
54e6bce9d2
commit
ae2f006b6d
@@ -66,11 +66,13 @@ All 24 files below were read in full.
|
||||
| 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. |
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -85,73 +85,74 @@
|
||||
| 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/system-clock.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 79 | `src/adapters/query-cache/conditional-validator-store.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 80 | `src/adapters/query-cache/cursor-pagination-contract.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 81 | `src/adapters/query-cache/cursor-pagination-runtime.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 82 | `src/adapters/query-cache/index.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 83 | `src/adapters/query-cache/server-state-scope-runtime.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 84 | `src/adapters/query-cache/tanstack-cache-coordinator.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 85 | `src/adapters/query-cache/tanstack-query-cache.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 86 | `src/adapters/realtime/event-codec.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 87 | `src/adapters/realtime/event-consumer.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 88 | `src/adapters/realtime/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 89 | `src/adapters/realtime/json-member-scanner.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 90 | `src/adapters/realtime/live-poll-handoff-coordinator.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 91 | `src/adapters/realtime/polling/bounded-poll-coordinator.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 92 | `src/adapters/realtime/polling/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 93 | `src/adapters/realtime/reconnect-coordinator.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 94 | `src/adapters/realtime/reconnect-policy.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 95 | `src/adapters/realtime/result.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 96 | `src/adapters/realtime/sse/fetch-sse-connection.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 97 | `src/adapters/realtime/sse/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 98 | `src/adapters/realtime/sse/sse-parser.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 99 | `src/adapters/realtime/stream-coordinator.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 100 | `src/adapters/realtime/websocket/index.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 101 | `src/adapters/realtime/websocket/websocket-connection.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 102 | `src/adapters/realtime/websocket/websocket-protocol.ts` | [Realtime/RPC](./02-realtime-and-browser-rpc.md) |
|
||||
| 103 | `src/adapters/service-worker/index.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 104 | `src/adapters/service-worker/service-worker-entry.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 105 | `src/adapters/service-worker/service-worker-lifecycle.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 106 | `src/adapters/service-worker/service-worker-page-controller.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 107 | `src/adapters/service-worker/service-worker-protocol.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 108 | `src/adapters/service-worker/service-worker-removal.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 109 | `src/adapters/service-worker/service-worker-static-assets.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 110 | `src/adapters/storage/browser-storage-adapter.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 111 | `src/adapters/storage/browser-storage-codec.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 112 | `src/adapters/storage/index.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 113 | `src/adapters/storage/indexeddb/index.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 114 | `src/adapters/storage/indexeddb/indexeddb-failure.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 115 | `src/adapters/storage/indexeddb/indexeddb-governance.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 116 | `src/adapters/storage/indexeddb/indexeddb-maintenance.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 117 | `src/adapters/storage/indexeddb/indexeddb-migrations.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 118 | `src/adapters/storage/indexeddb/indexeddb-records.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 119 | `src/adapters/storage/indexeddb/indexeddb-runtime.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 120 | `src/adapters/storage/indexeddb/indexeddb-types.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 121 | `src/adapters/storage/opfs/browser-opfs-runtime.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 122 | `src/adapters/storage/opfs/index.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 123 | `src/adapters/storage/opfs/indexeddb-opfs-journal.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 124 | `src/adapters/storage/opfs/opfs-byte-store-adapter.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 125 | `src/adapters/storage/opfs/opfs-policy.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 126 | `src/adapters/storage/opfs/opfs-prepared-object.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 127 | `src/adapters/storage/opfs/opfs-worker-client.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 128 | `src/adapters/storage/opfs/opfs-worker-protocol.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 129 | `src/adapters/storage/opfs/opfs-worker-runtime.ts` | [Storage/files](./03-storage-and-browser-files.md) |
|
||||
| 130 | `src/adapters/telemetry/best-effort-telemetry.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 131 | `src/adapters/telemetry/feature-telemetry.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 132 | `src/adapters/telemetry/index.ts` | [Network/state](./01-network-and-state.md) |
|
||||
| 133 | `src/adapters/web-push/codec-primitives.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 134 | `src/adapters/web-push/inbound/notification-click-adapter.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 135 | `src/adapters/web-push/inbound/push-event-adapter.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 136 | `src/adapters/web-push/index.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 137 | `src/adapters/web-push/notification-registry.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 138 | `src/adapters/web-push/push-association-fence-store.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 139 | `src/adapters/web-push/push-codec.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 140 | `src/adapters/web-push/push-registration-gateway.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 141 | `src/adapters/web-push/push-subscription-adapter.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 142 | `src/adapters/web-push/runtime-support.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 143 | `src/adapters/web-push/service-worker-runtime.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 144 | `src/adapters/web-push/service-worker-scope-host.ts` | [Worker/push](./05-service-worker-and-web-push.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/web-push/codec-primitives.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 135 | `src/adapters/web-push/inbound/notification-click-adapter.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 136 | `src/adapters/web-push/inbound/push-event-adapter.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 137 | `src/adapters/web-push/index.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 138 | `src/adapters/web-push/notification-registry.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 139 | `src/adapters/web-push/push-association-fence-store.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 140 | `src/adapters/web-push/push-codec.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 141 | `src/adapters/web-push/push-registration-gateway.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 142 | `src/adapters/web-push/push-subscription-adapter.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 143 | `src/adapters/web-push/runtime-support.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 144 | `src/adapters/web-push/service-worker-runtime.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
| 145 | `src/adapters/web-push/service-worker-scope-host.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
|
||||
|
||||
합계: **144/144**. 새 adapter 파일이 추가되면 이 ledger와 해당 상세 리뷰 inventory를 같은 변경에서 갱신한다.
|
||||
합계: **145/145**. 새 adapter 파일이 추가되면 이 ledger와 해당 상세 리뷰 inventory를 같은 변경에서 갱신한다.
|
||||
|
||||
|
||||
@@ -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<{
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -24,7 +24,7 @@ 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;
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
import { systemClock } from "../platform/system-clock.ts";
|
||||
import {
|
||||
isRealtimeResult,
|
||||
raceRealtimeTask,
|
||||
realtimeFailure,
|
||||
realtimeSuccess,
|
||||
} from "./result.ts";
|
||||
@@ -555,24 +556,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 +568,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 +627,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",
|
||||
@@ -411,7 +415,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 +554,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 +662,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;
|
||||
@@ -1023,65 +1022,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 +1069,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 +1096,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 +1109,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 +1148,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 +1188,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 +1212,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 +1225,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 +1254,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 +1315,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 +1354,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 +1389,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 +1441,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 +1615,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,
|
||||
@@ -146,43 +148,6 @@ export function isReconnectAttemptResetEligible(input: Readonly<{
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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";
|
||||
@@ -162,30 +163,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 +248,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);
|
||||
@@ -318,22 +313,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 +366,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);
|
||||
@@ -598,66 +578,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();
|
||||
@@ -673,29 +593,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(
|
||||
|
||||
@@ -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);
|
||||
@@ -920,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({
|
||||
@@ -1040,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);
|
||||
}
|
||||
@@ -1414,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";
|
||||
@@ -882,91 +883,64 @@ 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,
|
||||
"SNAPSHOT",
|
||||
),
|
||||
"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 +951,6 @@ export function createWebSocketConnection(
|
||||
);
|
||||
}
|
||||
return;
|
||||
} finally {
|
||||
generation.signal.removeEventListener(
|
||||
"abort",
|
||||
abortBarrier,
|
||||
);
|
||||
barrierController.abort();
|
||||
}
|
||||
}
|
||||
if (
|
||||
@@ -1057,87 +1025,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") {
|
||||
requestRecovery({
|
||||
subscriptionId: frame.subscriptionId,
|
||||
reason: "APPLY_FAILED",
|
||||
});
|
||||
terminate(
|
||||
failure(
|
||||
"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) {
|
||||
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",
|
||||
@@ -1153,9 +1058,23 @@ export function createWebSocketConnection(
|
||||
undefined,
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
generation.signal.removeEventListener("abort", abortApply);
|
||||
applyController.abort();
|
||||
} else if (status !== "CLOSED") {
|
||||
if (!handled.ok) {
|
||||
terminateInboundFailure(handled.error, frame.subscriptionId);
|
||||
} else if (handled.value.kind === "RECOVERY_COMMITTED") {
|
||||
terminate(
|
||||
failure(
|
||||
"CURSOR_EXPIRED",
|
||||
"RECEIVE",
|
||||
false,
|
||||
"SNAPSHOT",
|
||||
),
|
||||
"CURSOR_RESET",
|
||||
undefined,
|
||||
true,
|
||||
handled.value,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
type WebPushResult,
|
||||
} from "../../contracts/web-push.ts";
|
||||
import { hasExactKeys, isRecord, validOpaqueId } from "./codec-primitives.ts";
|
||||
import { hasDuplicateJsonMembers } from "../platform/json-member-scanner.ts";
|
||||
|
||||
const REGISTRY_ID = /^[A-Z][A-Z0-9_]{0,63}$/u;
|
||||
const ISO_INSTANT =
|
||||
@@ -71,7 +72,13 @@ export function decodeWebPushHint(
|
||||
} catch {
|
||||
return webPushFailure("CONTRACT_REJECTED", "PUSH_DECODE");
|
||||
}
|
||||
if (hasDuplicateTopLevelJsonKeys(decoded)) {
|
||||
// The byte cap already bounds the scan, so the budget never trips first.
|
||||
if (
|
||||
hasDuplicateJsonMembers(decoded, {
|
||||
maxDepth: WEB_PUSH_LIMITS.decodedHintBytes,
|
||||
maxMembers: WEB_PUSH_LIMITS.decodedHintBytes,
|
||||
})
|
||||
) {
|
||||
return webPushFailure("CONTRACT_REJECTED", "PUSH_DECODE");
|
||||
}
|
||||
if (isRecord(value) && Object.hasOwn(value, "web_push")) {
|
||||
@@ -189,101 +196,3 @@ export function clickDataFromHint(
|
||||
expiresAt: hint.expiresAt,
|
||||
});
|
||||
}
|
||||
|
||||
function hasDuplicateTopLevelJsonKeys(source: string): boolean {
|
||||
let cursor = skipWhitespace(source, 0);
|
||||
if (source[cursor] !== "{") return false;
|
||||
cursor = skipWhitespace(source, cursor + 1);
|
||||
const keys = new Set<string>();
|
||||
while (cursor < source.length && source[cursor] !== "}") {
|
||||
if (source[cursor] !== "\"") return false;
|
||||
const keyEnd = jsonStringEnd(source, cursor);
|
||||
if (keyEnd === null) return false;
|
||||
let key: unknown;
|
||||
try {
|
||||
key = JSON.parse(source.slice(cursor, keyEnd));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
if (typeof key !== "string") return false;
|
||||
if (keys.has(key)) return true;
|
||||
keys.add(key);
|
||||
cursor = skipWhitespace(source, keyEnd);
|
||||
if (source[cursor] !== ":") return false;
|
||||
const valueEnd = jsonValueEnd(source, cursor + 1);
|
||||
if (valueEnd === null) return false;
|
||||
cursor = skipWhitespace(source, valueEnd);
|
||||
if (source[cursor] === ",") {
|
||||
cursor = skipWhitespace(source, cursor + 1);
|
||||
continue;
|
||||
}
|
||||
if (source[cursor] !== "}") return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function jsonStringEnd(
|
||||
source: string,
|
||||
start: number,
|
||||
): number | null {
|
||||
let escaped = false;
|
||||
for (let cursor = start + 1; cursor < source.length; cursor += 1) {
|
||||
const character = source[cursor];
|
||||
if (escaped) {
|
||||
escaped = false;
|
||||
} else if (character === "\\") {
|
||||
escaped = true;
|
||||
} else if (character === "\"") {
|
||||
return cursor + 1;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function jsonValueEnd(
|
||||
source: string,
|
||||
start: number,
|
||||
): number | null {
|
||||
let cursor = skipWhitespace(source, start);
|
||||
let depth = 0;
|
||||
let inString = false;
|
||||
let escaped = false;
|
||||
for (; cursor < source.length; cursor += 1) {
|
||||
const character = source[cursor];
|
||||
if (inString) {
|
||||
if (escaped) {
|
||||
escaped = false;
|
||||
} else if (character === "\\") {
|
||||
escaped = true;
|
||||
} else if (character === "\"") {
|
||||
inString = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (character === "\"") {
|
||||
inString = true;
|
||||
} else if (character === "{" || character === "[") {
|
||||
depth += 1;
|
||||
} else if (character === "}" || character === "]") {
|
||||
if (depth === 0) return cursor;
|
||||
depth -= 1;
|
||||
} else if (character === "," && depth === 0) {
|
||||
return cursor;
|
||||
}
|
||||
}
|
||||
return inString || depth !== 0 ? null : cursor;
|
||||
}
|
||||
|
||||
function skipWhitespace(source: string, start: number): number {
|
||||
let cursor = start;
|
||||
while (
|
||||
cursor < source.length &&
|
||||
(source[cursor] === " " ||
|
||||
source[cursor] === "\n" ||
|
||||
source[cursor] === "\r" ||
|
||||
source[cursor] === "\t")
|
||||
) {
|
||||
cursor += 1;
|
||||
}
|
||||
return cursor;
|
||||
}
|
||||
|
||||
@@ -835,6 +835,59 @@ describe("bounded poll coordinator", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("reads attempt results with the shared realtime snapshot rules", async () => {
|
||||
const runWith = async (result: unknown) => {
|
||||
const clock = new ManualClock();
|
||||
const coordinator = createBoundedPollCoordinator<string>({
|
||||
policy,
|
||||
operation,
|
||||
environment: new MutableEnvironment(),
|
||||
clock,
|
||||
execute: async () => result as BoundedPollAttemptResult<string>,
|
||||
});
|
||||
const running = coordinator.run();
|
||||
clock.advance(5_000);
|
||||
return running;
|
||||
};
|
||||
const terminalValue = () => ({
|
||||
kind: "VALUE",
|
||||
value: "done",
|
||||
responseBytes: 1,
|
||||
state: "COMPLETED",
|
||||
});
|
||||
|
||||
// A hidden (non-enumerable) field is not plain data: rejected.
|
||||
await expect(
|
||||
runWith(
|
||||
Object.defineProperties(
|
||||
{},
|
||||
{
|
||||
ok: { enumerable: false, value: true },
|
||||
value: { enumerable: true, value: terminalValue() },
|
||||
},
|
||||
),
|
||||
),
|
||||
).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: { kind: "PROTOCOL_MISMATCH" },
|
||||
});
|
||||
// A null-prototype record is plain data: accepted.
|
||||
await expect(
|
||||
runWith(
|
||||
Object.assign(Object.create(null) as object, {
|
||||
ok: true,
|
||||
value: Object.assign(
|
||||
Object.create(null) as object,
|
||||
terminalValue(),
|
||||
),
|
||||
}),
|
||||
),
|
||||
).resolves.toMatchObject({
|
||||
ok: true,
|
||||
value: { kind: "TERMINAL", value: "done" },
|
||||
});
|
||||
});
|
||||
|
||||
it("fails closed on response ceilings, concurrent runs and close", async () => {
|
||||
const clock = new ManualClock();
|
||||
const coordinator = createBoundedPollCoordinator<string>({
|
||||
|
||||
@@ -234,7 +234,8 @@ function deferred<Value>(): Readonly<{
|
||||
}
|
||||
|
||||
async function flush(): Promise<void> {
|
||||
for (let turn = 0; turn < 8; turn += 1) {
|
||||
// Enough turns for a retry loop iteration: sleep, attempt and close races.
|
||||
for (let turn = 0; turn < 16; turn += 1) {
|
||||
await Promise.resolve();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
isRealtimeResult,
|
||||
raceRealtimeTask,
|
||||
realtimeFailure,
|
||||
realtimeSuccess,
|
||||
snapshotRealtimeResult,
|
||||
timerDeadline,
|
||||
} from "../../../src/adapters/realtime/result.ts";
|
||||
|
||||
function isString(value: unknown): value is string {
|
||||
@@ -166,3 +168,78 @@ describe("realtime result boundary", () => {
|
||||
expect(snapshotRealtimeResult(source, isString)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("realtime abort/deadline race", () => {
|
||||
const never = () => new Promise<never>(() => undefined);
|
||||
|
||||
it("settles with the value, a rejection or a synchronous throw", async () => {
|
||||
await expect(raceRealtimeTask(() => 7)).resolves.toEqual({
|
||||
kind: "VALUE",
|
||||
value: 7,
|
||||
});
|
||||
await expect(
|
||||
raceRealtimeTask(() => Promise.reject(new Error("no"))),
|
||||
).resolves.toEqual({ kind: "REJECTED" });
|
||||
await expect(
|
||||
raceRealtimeTask(() => {
|
||||
throw new Error("sync");
|
||||
}),
|
||||
).resolves.toEqual({ kind: "REJECTED" });
|
||||
});
|
||||
|
||||
it("aborts without starting, or mid-flight with cleanup", async () => {
|
||||
const task = vi.fn(never);
|
||||
await expect(
|
||||
raceRealtimeTask(task, AbortSignal.abort()),
|
||||
).resolves.toEqual({ kind: "ABORTED" });
|
||||
expect(task).not.toHaveBeenCalled();
|
||||
|
||||
const caller = new AbortController();
|
||||
const remove = vi.spyOn(caller.signal, "removeEventListener");
|
||||
let lease: AbortSignal | undefined;
|
||||
const running = raceRealtimeTask((signal) => {
|
||||
lease = signal;
|
||||
return never();
|
||||
}, caller.signal);
|
||||
caller.abort();
|
||||
await expect(running).resolves.toEqual({ kind: "ABORTED" });
|
||||
expect(lease?.aborted).toBe(true);
|
||||
expect(remove).toHaveBeenCalledWith("abort", expect.any(Function));
|
||||
});
|
||||
|
||||
it("times out on the deadline and reports a broken deadline", async () => {
|
||||
let deadlineSignal: AbortSignal | undefined;
|
||||
await expect(
|
||||
raceRealtimeTask(never, undefined, (signal) => {
|
||||
deadlineSignal = signal;
|
||||
return Promise.resolve();
|
||||
}),
|
||||
).resolves.toEqual({ kind: "TIMEOUT" });
|
||||
expect(deadlineSignal?.aborted).toBe(true);
|
||||
|
||||
await expect(
|
||||
raceRealtimeTask(never, undefined, () => Promise.reject(new Error())),
|
||||
).resolves.toEqual({ kind: "CLOCK_FAILED" });
|
||||
|
||||
// A deadline that throws still lets the task start (e.g. a cancel).
|
||||
const task = vi.fn(never);
|
||||
await expect(
|
||||
raceRealtimeTask(task, undefined, () => {
|
||||
throw new Error("clock");
|
||||
}),
|
||||
).resolves.toEqual({ kind: "CLOCK_FAILED" });
|
||||
expect(task).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("clears a host-timer deadline when the task wins", async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
await expect(
|
||||
raceRealtimeTask(() => "done", undefined, timerDeadline(1_000)),
|
||||
).resolves.toEqual({ kind: "VALUE", value: "done" });
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -15,11 +15,21 @@ describe("HTTP retry policy", () => {
|
||||
|
||||
it("parses retry-after and chooses the longer bounded delay", () => {
|
||||
expect(parseRetryAfter("2", 0)).toBe(2_000);
|
||||
expect(parseRetryAfter(" 2 ", 0)).toBe(2_000);
|
||||
expect(parseRetryAfter("Thu, 01 Jan 1970 00:00:05 GMT", 1_000)).toBe(
|
||||
4_000,
|
||||
);
|
||||
expect(retryDelay({ kind: "RATE_LIMITED", retryAfterMs: 500 }, 0, () => 0)).toBe(
|
||||
500,
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects Retry-After values that are not delta-seconds or an HTTP date", () => {
|
||||
for (const value of ["", " ", "1e3", "1.5", "-1", "0x10", "2024-01-01"]) {
|
||||
expect(parseRetryAfter(value, 0)).toBeNull();
|
||||
}
|
||||
});
|
||||
|
||||
it("allows at most two retries for safe or keyed requests", () => {
|
||||
const failure = { kind: "SERVER_FAILURE" };
|
||||
expect(shouldRetry({ idempotency: "safe" }, failure, 0)).toBe(true);
|
||||
|
||||
@@ -137,6 +137,29 @@ describe("Web Push contracts", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects duplicate keys at any depth without a nesting budget", () => {
|
||||
const deepDeclarative = {
|
||||
web_push: 8030,
|
||||
notification: { title: "t", data: { a: [[[[{ b: 1 }]]]] } },
|
||||
};
|
||||
expect(
|
||||
decodeWebPushHint(encoded(deepDeclarative), now),
|
||||
).toMatchObject({
|
||||
ok: false,
|
||||
error: { code: "DECLARATIVE_PUSH_FORBIDDEN" },
|
||||
});
|
||||
const nestedDuplicate = JSON.stringify(deepDeclarative).replace(
|
||||
'"title":"t"',
|
||||
'"title":"t","title":"u"',
|
||||
);
|
||||
expect(
|
||||
decodeWebPushHint(new TextEncoder().encode(nestedDuplicate), now),
|
||||
).toMatchObject({
|
||||
ok: false,
|
||||
error: { code: "CONTRACT_REJECTED" },
|
||||
});
|
||||
});
|
||||
|
||||
it("uses an injected closed notification and route registry", async () => {
|
||||
const registry = createWebPushNotificationRegistry([
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user