wenay-common2 1.0.64 → 1.0.65
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/doc/REPLAY-PLAN.md +5 -1
- package/doc/ROADMAP.md +131 -0
- package/doc/changes/1.0.65.md +7 -0
- package/doc/wenay-common2-rare.md +5 -2
- package/doc/wenay-common2.md +6 -2
- package/lib/Common/Observe/store-replay.d.ts +8 -0
- package/lib/Common/Observe/store-replay.js +5 -0
- package/lib/Common/events/replay-index.d.ts +1 -0
- package/lib/Common/events/replay-index.js +1 -0
- package/lib/Common/events/replay-route.d.ts +25 -0
- package/lib/Common/events/replay-route.js +174 -0
- package/package.json +1 -1
package/doc/REPLAY-PLAN.md
CHANGED
|
@@ -75,7 +75,11 @@ For seek into the past — not needed for live sync:
|
|
|
75
75
|
## Stages
|
|
76
76
|
|
|
77
77
|
1. `withReplayListen` decorator + seq handover (layer A) — the core, small.
|
|
78
|
-
2. Patch journal in `exposeStore` + `since`-sync in mirror (layer B).
|
|
78
|
+
2. Patch journal in `exposeStore` + `since`-sync in mirror (layer B).
|
|
79
|
+
2.5. **Route hand-off helper** — `replayRouteSubscribe` / `syncStoreReplayRoute`: keep the
|
|
80
|
+
old route live, catch up the replacement from the last delivered `seq`, then close the old
|
|
81
|
+
route. This is the replay-level foundation for relay ↔ direct promotion; signaling and
|
|
82
|
+
direct-transport setup remain outside this layer.
|
|
79
83
|
3. Conflation + snapshot recovery on the wire (first item of D) — this is what turns
|
|
80
84
|
"semi-pro" into pro for fan-out.
|
|
81
85
|
4. C and the rest of D — on demand.
|
package/doc/ROADMAP.md
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
# wenay-common2 — Roadmap (open / deferred)
|
|
2
|
+
|
|
3
|
+
> Forward-looking backlog of distributed-state / transport features that are **not fully built**.
|
|
4
|
+
> Everything here sits on top of the existing seams — `{emit,on}` transport, `exposeStore` /
|
|
5
|
+
> `createStoreMirror`, and the replay `seq` / `keyframe` / `frame` contract. None of it requires
|
|
6
|
+
> changing the store core; the store stays single-authority (one `seq` sequencer, last-writer-wins
|
|
7
|
+
> per path), and these features are layers or adapters above that.
|
|
8
|
+
> Status: 🔴 not started · 🟡 partial / ongoing · 🧊 deliberately shelved.
|
|
9
|
+
|
|
10
|
+
## 0. Distributed Runtime Model
|
|
11
|
+
|
|
12
|
+
The strategic direction is not "RPC plus store helpers"; it is a small distributed-state runtime:
|
|
13
|
+
application code keeps a stable typed API while lower layers can choose the transport, route, replay
|
|
14
|
+
source, and authority model.
|
|
15
|
+
|
|
16
|
+
Four concerns must stay explicit:
|
|
17
|
+
|
|
18
|
+
- **Transport** - how two endpoints exchange `{emit,on}` messages: socket.io, in-process loopback,
|
|
19
|
+
relay, WebRTC/direct channel, or a future adapter. Transport is replaceable infrastructure.
|
|
20
|
+
- **Routing** - where a logical call or stream goes: server, peer through relay, peer directly, or a
|
|
21
|
+
promoted relay <-> direct path. Routing must be allowed to change without changing the facade API.
|
|
22
|
+
- **Authority** - who is allowed to write truth: one server, partitioned peer-owned slices, server
|
|
23
|
+
authority with client prediction, or true multi-writer conflict resolution. This is a semantic
|
|
24
|
+
decision, not a transport decision.
|
|
25
|
+
- **Replay** - how live state survives reconnect, lag, transport swap, and history playback:
|
|
26
|
+
`seq` + keyframe/frame + deltas. Replay is the continuity layer that makes route changes boring.
|
|
27
|
+
|
|
28
|
+
Design rule: direct peer links and relay hand-offs are optimizations of transport/routing. They must
|
|
29
|
+
not silently change auth, ownership, validation, or conflict semantics. If a method is exposed as
|
|
30
|
+
`api.hit(playerId)`, it may travel through the server or a direct channel, but the authority rules
|
|
31
|
+
behind that method must remain the same.
|
|
32
|
+
|
|
33
|
+
This implies a useful split:
|
|
34
|
+
|
|
35
|
+
- **API surface** remains facade-shaped and typed.
|
|
36
|
+
- **Transport/routing layer** may substitute sockets and promote paths.
|
|
37
|
+
- **Replay layer** resumes streams and mirrors from the last known `seq`.
|
|
38
|
+
- **Authority layer** decides whether an incoming write is accepted, predicted, reconciled, or merged.
|
|
39
|
+
|
|
40
|
+
### 0.1 Optional account-to-account route plane ("wrapper over wrappers") 🔴
|
|
41
|
+
|
|
42
|
+
Some deployments need separate client/account identities to communicate directly when policy and
|
|
43
|
+
network conditions allow it, while still allowing the server/relay to step back into the path later.
|
|
44
|
+
This is not just a socket trick; it is an account-aware routing shell above the existing facade,
|
|
45
|
+
mirror, and replay primitives.
|
|
46
|
+
|
|
47
|
+
- **Account model:** every participant has its own account/session identity and a scoped facade/store
|
|
48
|
+
set. Runtime-account maps are a dynamic keyspace, so they should look like `noStrict(accountMap)`
|
|
49
|
+
rather than a fixed schema. Access checks stay in the facade/policy layer; `noStrict` is not an ACL.
|
|
50
|
+
- **Wrapper over wrappers:** an app-level coordinator owns the set of per-account clients, exposed
|
|
51
|
+
facades, mirrors, replay subscriptions, and route state. "State of other accounts" is represented as
|
|
52
|
+
selected `Observe` mirrors/replay/offline resources, ideally started and stopped through
|
|
53
|
+
`createStoreManager`, not as a new global store core.
|
|
54
|
+
- **Route states:** a pair of accounts may be `relay`, `direct`, `direct+shadowRelay` (audit/observe
|
|
55
|
+
copy), `blocked`, or `fallback`. Direct links are optional optimizations, useful for latency or
|
|
56
|
+
traffic cost, not a semantic change.
|
|
57
|
+
- **Re-interposition:** if NDA/privacy policy, audit, moderation, throttling, reauth, direct-link
|
|
58
|
+
failure, or group topology changes require it, the relay must be able to re-enter the data path.
|
|
59
|
+
This is the reverse of direct promotion: open the replacement route, resume from the last `seq`,
|
|
60
|
+
switch consumers after catch-up, then close or demote the old route.
|
|
61
|
+
- **Privacy rule:** direct account links are opt-in and policy-gated. Peers only receive the endpoint
|
|
62
|
+
and session material needed for that specific relationship; no implicit broad account discovery.
|
|
63
|
+
|
|
64
|
+
Open questions: account ACL/policy shape; signaling format; whether the relay sees payloads or only
|
|
65
|
+
coordinates encrypted direct streams; how route state is exposed to the app; backpressure across
|
|
66
|
+
multi-hop and direct paths; revocation in the middle of a live stream.
|
|
67
|
+
|
|
68
|
+
Status: 🔴 not started. This belongs to project-0 architecture: no store-core change, but it defines
|
|
69
|
+
the account/routing shell that later direct-connection work plugs into.
|
|
70
|
+
|
|
71
|
+
## 1. Connection hand-off — relay ↔ direct promotion ("port forwarding") 🟡
|
|
72
|
+
|
|
73
|
+
A relay/intermediary bootstraps a connection between two parties, then — on a signal — **steps out
|
|
74
|
+
of the middle**: both ends open a second, direct socket and migrate the live stream onto it,
|
|
75
|
+
bypassing the relay. The same mechanism must work in reverse: the relay can deliberately
|
|
76
|
+
**re-interpose** and become the middleman again. Under the hood the socket substitutes itself; data
|
|
77
|
+
starts flowing on the new path.
|
|
78
|
+
|
|
79
|
+
- Family: NAT hole-punching / WebRTC TURN→direct promotion, expressed over the existing `{emit,on}`
|
|
80
|
+
abstraction rather than a specific transport.
|
|
81
|
+
- **Design lead (reuse what exists):** the socket swap is a *stream resume*, which the replay layer
|
|
82
|
+
already solves. Migrate with `replaySubscribe(..., {since: prev.seq()})` /
|
|
83
|
+
`syncStoreReplay(..., {since})` on the new socket — the consumer fold is gap-free by contract, so a
|
|
84
|
+
mid-stream transport change is not a special case. The transport carries only `seq`; the semantics
|
|
85
|
+
never learn the socket changed.
|
|
86
|
+
- **Implemented foundation (2026-07-08):** `Replay.replayRouteSubscribe(...)` and
|
|
87
|
+
`Observe.syncStoreReplayRoute(...)` keep the old route alive, subscribe the replacement route,
|
|
88
|
+
catch it up from the last delivered `seq`, then close the old route. This covers relay → direct
|
|
89
|
+
promotion and direct → relay re-interposition for any ordered `ReplayRemote`; overlap is deduped by
|
|
90
|
+
`seq`, and a failed replacement leaves the old route active.
|
|
91
|
+
- Open questions: signaling channel that negotiates the direct endpoint; fallback if the direct path
|
|
92
|
+
never establishes (stay on relay); auth continuity across the swap; per-socketKey vs whole-connection
|
|
93
|
+
hand-off; policy trigger and catch-up boundary for direct → relay re-interposition.
|
|
94
|
+
- Status: 🟡 partial. Route hand-off/resume helper is implemented and covered by `replay/route-handoff.test.ts`; signaling, direct endpoint negotiation, NAT/WebRTC adapter, auth-continuity policy, and trigger rules remain open.
|
|
95
|
+
|
|
96
|
+
## 2. Coordinated fan-out send to a large group 🧊
|
|
97
|
+
|
|
98
|
+
Synchronized/batched send to a very large audience "at once", as opposed to the current model where
|
|
99
|
+
**each connection is paced independently** (per-connection lag gate + `frame` policy).
|
|
100
|
+
|
|
101
|
+
- Current reality: pacing is per-recipient by design — every client's link is unique. Even in video
|
|
102
|
+
fan-out no two receivers drain at the same rate, so the per-connection gate is usually the *correct*
|
|
103
|
+
answer. That is why this is shelved.
|
|
104
|
+
- When it would matter: true lockstep broadcast (all-or-nothing / same-instant delivery) — rare.
|
|
105
|
+
- Status: 🧊 deliberately shelved. Revisit only against a concrete lockstep requirement.
|
|
106
|
+
|
|
107
|
+
## 3. Multi-authority stores — two truths, one reconciliation (games) 🔴
|
|
108
|
+
|
|
109
|
+
Two stores, each **dynamically filled by its own authority ("truth")**, that must agree on a shared
|
|
110
|
+
source of truth. Decompose by write topology:
|
|
111
|
+
|
|
112
|
+
- **Partitioned authority — fits today.** Each peer authoritative over its own slice → two
|
|
113
|
+
`exposeStore` / `createStoreMirror` pairs crossed over one duplex `{emit,on}`. No new primitive.
|
|
114
|
+
"Confirmation" = the per-direction `seq` ack.
|
|
115
|
+
- **Authoritative server + client prediction — small layer on top.** Server store is the truth; the
|
|
116
|
+
client applies optimistically, then reconciles when the authoritative patch arrives. Build a
|
|
117
|
+
`predictedStore` = confirmed mirror + a pending-input list, rebased on each `mirror.each()` /
|
|
118
|
+
`changed` tick. Helper factory, not a core change.
|
|
119
|
+
- **Symmetric co-write of the same path — needs a different model.** LWW-per-path converges but can
|
|
120
|
+
silently drop a concurrent write. This is the one case that genuinely needs CRDT/OT. Design lead:
|
|
121
|
+
wrap a Yjs/Automerge doc as a `RemoteStore`-shaped source and mirror from it — the store↔transport
|
|
122
|
+
decoupling makes this a small adapter, not a rewrite.
|
|
123
|
+
- Status: 🔴 prediction layer + CRDT adapter not started; partitioned-authority already expressible.
|
|
124
|
+
|
|
125
|
+
## 4. Data-transfer optimization backlog (ongoing) 🟡
|
|
126
|
+
|
|
127
|
+
Open-ended transfer/perf work, especially for backend-heavy models. Never "done".
|
|
128
|
+
|
|
129
|
+
- Candidates: tighter `frame` condensation per line; delta/patch minimization; binary framing for hot
|
|
130
|
+
paths; batching heuristics beyond the current `pipe` / `space` modes.
|
|
131
|
+
- Status: 🟡 ongoing; pick items as real bottlenecks surface, not speculatively.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
# 1.0.65
|
|
2
|
+
|
|
3
|
+
- Add `Replay.replayRouteSubscribe` for transport-agnostic replay route hand-off: keep the old route live, catch up the replacement route by `seq`, then close the old route.
|
|
4
|
+
- Add `Observe.syncStoreReplayRoute` for store mirrors that can switch relay/direct routes without gaps or duplicate patch delivery.
|
|
5
|
+
- Add `replay/route-handoff.test.ts` covering relay -> direct promotion, direct -> relay re-interposition, failed replacement fallback, and store mirror convergence.
|
|
6
|
+
- Update roadmap/replay docs to mark connection hand-off as partially implemented and keep signaling/WebRTC/policy triggers explicitly open.
|
|
7
|
+
- Normalize package metadata for `wenay-common2@1.0.65`.
|
|
@@ -420,7 +420,9 @@ exposeReplay(replay) <-> replaySubscribe(remote, cb, {since?, onSeq?, staleMs?
|
|
|
420
420
|
// on the line (RPC_STOP — e.g. the gate's loud sacred failure) surfaces via onError + off, never silence.
|
|
421
421
|
// hint reaches the frame lambda on catch-up and on every explicit frame(seq, hint) call (pull); the push-gate's
|
|
422
422
|
// drain recovery uses the line's DEFAULT condensation — client-specific rules/pace = the pull path.
|
|
423
|
-
// off.ready (catch-up done) · off.seq() (reconnect point) · off.isStale()/off.lastTs(); reconnect = call again with {since: prev.seq()}
|
|
423
|
+
// off.ready (catch-up done) · off.seq() (reconnect point) · off.isStale()/off.lastTs(); reconnect = call again with {since: prev.seq()}
|
|
424
|
+
replayRouteSubscribe(remote, cb, {label?, since?, onSeq?, onError?, onRoute?}) -> off & {ready, switch(nextRemote, {label?, since?, reset?, policy?, hint?}), seq(), label(), active()}
|
|
425
|
+
// transport hand-off helper: old route remains live, replacement subscribes+catches up from seq, then old closes; overlap is seq-deduped. Use for relay -> direct and direct -> relay over any ordered ReplayRemote.
|
|
424
426
|
// DELIVERY CONTRACT (guaranteed, not best-effort): the subscriber's cb sees ONE uniform stream —
|
|
425
427
|
// first delivery = the snapshot (keyframe as an event of the SAME type; store: root patch),
|
|
426
428
|
// then only strictly-newer events, seq-ascending, no gaps, no dups. Live events racing ahead of the
|
|
@@ -439,7 +441,8 @@ exposeReplay(replay) <-> replaySubscribe(remote, cb, {since?, onSeq?, staleMs?
|
|
|
439
441
|
// of clock skew) + ENVELOPE-TS AGE checked at delivery (producer clock — a stale keyframe reports stale
|
|
440
442
|
// IMMEDIATELY; clock-skew caveat: producer/client clocks may disagree, skewMs tolerance absorbs it, default 0).
|
|
441
443
|
// A since-tail's historical ts never flaps mid-catch-up (one assessment after handover); off() disarms the timer.
|
|
442
|
-
exposeStoreReplay(store, opts?) <-> syncStoreReplay(mirror, remote, opts?) // layer B: patch line; keyframe = root patch ({path: [], value: snapshot})
|
|
444
|
+
exposeStoreReplay(store, opts?) <-> syncStoreReplay(mirror, remote, opts?) // layer B: patch line; keyframe = root patch ({path: [], value: snapshot})
|
|
445
|
+
syncStoreReplayRoute(mirror, remote, opts?) -> off & {ready, switch(nextRemote, opts), seq(), label(), active()} // same patch fold, but route-replaceable for relay/direct promotion
|
|
443
446
|
syncStoreReplayEach<T>(remote, cb, opts?) -> off & {store, ready, seq(), isStale(), lastTs()} // one-call per-key fold over the patch line (mirror + syncStoreReplay + store.each()); most-used surface — full contract + example in wenay-common2.md
|
|
444
447
|
createOfflineStore({key, remote?, initial, storage, version?, debounceMs?, syncOpts?}) -> Promise<OfflineStore<T>>
|
|
445
448
|
// snapshot-mode persisted mirror: read local {version,seq,snapshot,savedAt}, create a normal Store immediately,
|
package/doc/wenay-common2.md
CHANGED
|
@@ -136,7 +136,9 @@ l.ticks.once(v => console.log(v)) // one event, then aut
|
|
|
136
136
|
const [tick, ticks] = replayListen<[number]>({history: 1024, current: 'last'}) // after — same facade, same key
|
|
137
137
|
// legacy subscribers unchanged (byte-for-byte). Replay consumers now also get:
|
|
138
138
|
const sub = replaySubscribe(l.ticks, v => {}, {since: saved, onSeq: s => saved = s}) // catch-up + live, no gaps/dups
|
|
139
|
-
const sub2 = replaySubscribe(c.math.func.ticks, v => {}) // replay members project on func/strict directly — no cast needed
|
|
139
|
+
const sub2 = replaySubscribe(c.math.func.ticks, v => {}) // replay members project on func/strict directly — no cast needed
|
|
140
|
+
const routed = replayRouteSubscribe(l.ticks, v => {}, {label: 'relay'})
|
|
141
|
+
await routed.switch(nextRemoteTicks, {label: 'direct'}) // relay/direct hand-off: old route closes after catch-up
|
|
140
142
|
await l.ticks.frame(mySeq) // pull at YOUR pace (50ms timer etc.) — server condenses via the line's frame lambda
|
|
141
143
|
// full guide + examples → rpc.md; frame model / lag policies → 🎞️ recipe below and rare docs
|
|
142
144
|
```
|
|
@@ -186,7 +188,9 @@ Observe.exposeStoreReplay(store, {history? = 1024}) -> { api /* spread into the
|
|
|
186
188
|
Observe.syncStoreReplay(mirror, remote /*{line, since, keyframe, frame?} of api.replay*/, {since?, onSeq?}) -> off
|
|
187
189
|
// off.ready (catch-up done) · off.seq() (save for reconnect: syncStoreReplay(..., {since: prev.seq()}))
|
|
188
190
|
// lagging/late client NEVER gets a backlog: evicted seq -> ONE fresh keyframe + live
|
|
189
|
-
// freshness is an option, not consumer boilerplate: {staleMs, onStale} flags a silent line / stale keyframe (edge-triggered both ways; 🎞️ in rare docs)
|
|
191
|
+
// freshness is an option, not consumer boilerplate: {staleMs, onStale} flags a silent line / stale keyframe (edge-triggered both ways; 🎞️ in rare docs)
|
|
192
|
+
Observe.syncStoreReplayRoute(mirror, remote, {label?}) -> off & {switch(nextRemote, opts), ready, seq(), label(), active()}
|
|
193
|
+
// relay/direct promotion and re-interposition: replacement route catches up by seq before the old route closes
|
|
190
194
|
Observe.syncStoreReplayEach<T>(remote, (key, value, ctx) => {}, opts?) -> off & {store, ready, seq(), isStale(), lastTs()}
|
|
191
195
|
// one-call remote fold: mirror store + syncStoreReplay + store.each() — the callback fires per CHANGED
|
|
192
196
|
// top-level key; first delivery = keyframe EXPANDED per key; (key, undefined) = key deleted
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { Store, StorePatch, StoreDrain, StoreEachCtx } from './store';
|
|
2
2
|
import { ReplayListenOptions, ReplayEvent } from '../events/replay-listen';
|
|
3
3
|
import { ReplayRemote, ReplaySubscribeOpts } from '../events/replay-wire';
|
|
4
|
+
import { ReplayRouteSubscribeOpts } from '../events/replay-route';
|
|
4
5
|
import { ReplayStorage } from '../events/replay-history';
|
|
5
6
|
export type StoreReplayOpts = Pick<ReplayListenOptions<[StorePatch]>, 'history' | 'getSince' | 'onJournal' | 'now'>;
|
|
6
7
|
export declare function storePatchKey(patch: StorePatch): string | null;
|
|
@@ -48,6 +49,13 @@ export declare function syncStoreReplay<T extends object>(store: Store<T>, remot
|
|
|
48
49
|
isStale: () => boolean;
|
|
49
50
|
lastTs: () => number;
|
|
50
51
|
};
|
|
52
|
+
export declare function syncStoreReplayRoute<T extends object>(store: Store<T>, remote: ReplayRemote<[StorePatch]>, opts?: ReplayRouteSubscribeOpts): (() => void) & {
|
|
53
|
+
ready: Promise<void>;
|
|
54
|
+
switch: (nextRemote: ReplayRemote<[StorePatch]>, nextOpts?: import("../events/replay-route").ReplayRouteSwitchOpts) => Promise<void>;
|
|
55
|
+
seq: () => number;
|
|
56
|
+
label: () => string | undefined;
|
|
57
|
+
active: () => boolean;
|
|
58
|
+
};
|
|
51
59
|
export declare function syncStoreReplayEach<T extends object>(remote: ReplayRemote<[StorePatch]>, cb: (key: string, value: T[keyof T] | undefined, ctx: StoreEachCtx) => void, opts?: ReplaySubscribeOpts & {
|
|
52
60
|
drain?: StoreDrain;
|
|
53
61
|
initial?: T;
|
|
@@ -3,11 +3,13 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.storePatchKey = storePatchKey;
|
|
4
4
|
exports.exposeStoreReplay = exposeStoreReplay;
|
|
5
5
|
exports.syncStoreReplay = syncStoreReplay;
|
|
6
|
+
exports.syncStoreReplayRoute = syncStoreReplayRoute;
|
|
6
7
|
exports.syncStoreReplayEach = syncStoreReplayEach;
|
|
7
8
|
exports.storeReplayAt = storeReplayAt;
|
|
8
9
|
const store_1 = require("./store");
|
|
9
10
|
const replay_listen_1 = require("../events/replay-listen");
|
|
10
11
|
const replay_wire_1 = require("../events/replay-wire");
|
|
12
|
+
const replay_route_1 = require("../events/replay-route");
|
|
11
13
|
const replay_history_1 = require("../events/replay-history");
|
|
12
14
|
function makeStorePatch(store, path) {
|
|
13
15
|
let node = store.node;
|
|
@@ -55,6 +57,9 @@ function exposeStoreReplay(store, opts = {}) {
|
|
|
55
57
|
function syncStoreReplay(store, remote, opts = {}) {
|
|
56
58
|
return (0, replay_wire_1.replaySubscribe)(remote, function applyLine(patch) { (0, store_1.applyStorePatch)(store, patch); }, opts);
|
|
57
59
|
}
|
|
60
|
+
function syncStoreReplayRoute(store, remote, opts = {}) {
|
|
61
|
+
return (0, replay_route_1.replayRouteSubscribe)(remote, function applyRoutePatch(patch) { (0, store_1.applyStorePatch)(store, patch); }, opts);
|
|
62
|
+
}
|
|
58
63
|
function syncStoreReplayEach(remote, cb, opts = {}) {
|
|
59
64
|
const { drain, initial, ...wireOpts } = opts;
|
|
60
65
|
const store = (0, store_1.createStore)((initial ?? {}), drain !== undefined ? { drain } : {});
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { Listener } from './Listen';
|
|
2
|
+
import { ReplayRemote, ReplaySubscribeOpts } from './replay-wire';
|
|
3
|
+
export type ReplayRoutePhase = 'switching' | 'ready' | 'error' | 'closed';
|
|
4
|
+
export type ReplayRouteEvent = {
|
|
5
|
+
phase: ReplayRoutePhase;
|
|
6
|
+
seq: number;
|
|
7
|
+
from?: string;
|
|
8
|
+
to?: string;
|
|
9
|
+
error?: unknown;
|
|
10
|
+
};
|
|
11
|
+
export type ReplayRouteSwitchOpts = Pick<ReplaySubscribeOpts, 'policy' | 'hint'> & {
|
|
12
|
+
label?: string;
|
|
13
|
+
since?: number;
|
|
14
|
+
reset?: boolean;
|
|
15
|
+
};
|
|
16
|
+
export type ReplayRouteSubscribeOpts = ReplayRouteSwitchOpts & Pick<ReplaySubscribeOpts, 'onSeq' | 'onError'> & {
|
|
17
|
+
onRoute?: (ev: ReplayRouteEvent) => void;
|
|
18
|
+
};
|
|
19
|
+
export declare function replayRouteSubscribe<Z extends any[]>(remote: ReplayRemote<Z>, cb: Listener<Z>, opts?: ReplayRouteSubscribeOpts): (() => void) & {
|
|
20
|
+
ready: Promise<void>;
|
|
21
|
+
switch: (nextRemote: ReplayRemote<Z>, nextOpts?: ReplayRouteSwitchOpts) => Promise<void>;
|
|
22
|
+
seq: () => number;
|
|
23
|
+
label: () => string | undefined;
|
|
24
|
+
active: () => boolean;
|
|
25
|
+
};
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.replayRouteSubscribe = replayRouteSubscribe;
|
|
4
|
+
function unsubscribeHandle(handle) {
|
|
5
|
+
if (typeof handle == 'function') {
|
|
6
|
+
handle();
|
|
7
|
+
return;
|
|
8
|
+
}
|
|
9
|
+
if (typeof handle?.off == 'function')
|
|
10
|
+
handle.off();
|
|
11
|
+
else if (typeof handle?.unsubscribe == 'function')
|
|
12
|
+
handle.unsubscribe();
|
|
13
|
+
}
|
|
14
|
+
function replayRouteSubscribe(remote, cb, opts = {}) {
|
|
15
|
+
const { onSeq, onError, onRoute } = opts;
|
|
16
|
+
let lastDelivered = opts.since ?? -1;
|
|
17
|
+
let closed = false;
|
|
18
|
+
let active = null;
|
|
19
|
+
let currentLabel = opts.label;
|
|
20
|
+
let switchChain = Promise.resolve();
|
|
21
|
+
const slots = new Set();
|
|
22
|
+
function emitRoute(ev) {
|
|
23
|
+
if (!onRoute)
|
|
24
|
+
return;
|
|
25
|
+
try {
|
|
26
|
+
onRoute(ev);
|
|
27
|
+
}
|
|
28
|
+
catch (e) {
|
|
29
|
+
setTimeout(function rethrowRouteEvent() { throw e; }, 0);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
function deliver(ev) {
|
|
33
|
+
if (closed || ev.seq <= lastDelivered)
|
|
34
|
+
return;
|
|
35
|
+
lastDelivered = ev.seq;
|
|
36
|
+
cb(...ev.event);
|
|
37
|
+
onSeq?.(ev.seq);
|
|
38
|
+
}
|
|
39
|
+
function deliverMany(envs, allowReset) {
|
|
40
|
+
if (allowReset && envs.length && envs[0].seq <= lastDelivered) {
|
|
41
|
+
lastDelivered = envs[0].seq - 1;
|
|
42
|
+
}
|
|
43
|
+
for (const ev of envs)
|
|
44
|
+
deliver(ev);
|
|
45
|
+
}
|
|
46
|
+
function attach(nextRemote, since, nextOpts, allowReset) {
|
|
47
|
+
const { policy = 'queue', hint, label } = nextOpts;
|
|
48
|
+
let slot;
|
|
49
|
+
let slotClosed = false;
|
|
50
|
+
let replaying = true;
|
|
51
|
+
let lineError;
|
|
52
|
+
const queue = [];
|
|
53
|
+
const liveLine = policy == 'frame' && nextRemote.frameLine ? nextRemote.frameLine : nextRemote.line;
|
|
54
|
+
const handle = liveLine.on(function liveTap(ev) {
|
|
55
|
+
if (slotClosed)
|
|
56
|
+
return;
|
|
57
|
+
if (ev == null || typeof ev.seq != 'number') {
|
|
58
|
+
lineError = new Error('replayRouteSubscribe: line ended by route (' + String(ev) + ')');
|
|
59
|
+
slot.close();
|
|
60
|
+
if (!replaying)
|
|
61
|
+
onError?.(lineError);
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
if (replaying)
|
|
65
|
+
queue.push(ev);
|
|
66
|
+
else
|
|
67
|
+
deliver(ev);
|
|
68
|
+
});
|
|
69
|
+
function closeSlot() {
|
|
70
|
+
if (slotClosed)
|
|
71
|
+
return;
|
|
72
|
+
slotClosed = true;
|
|
73
|
+
unsubscribeHandle(handle);
|
|
74
|
+
slots.delete(slot);
|
|
75
|
+
}
|
|
76
|
+
async function catchUp() {
|
|
77
|
+
try {
|
|
78
|
+
let done = false;
|
|
79
|
+
if (since >= 0 && nextRemote.frame) {
|
|
80
|
+
const envs = await nextRemote.frame(since, hint);
|
|
81
|
+
if (slotClosed)
|
|
82
|
+
return;
|
|
83
|
+
if (envs) {
|
|
84
|
+
deliverMany(envs, allowReset);
|
|
85
|
+
done = true;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
if (!done) {
|
|
89
|
+
const tail = since >= 0 ? await nextRemote.since(since) : null;
|
|
90
|
+
if (slotClosed)
|
|
91
|
+
return;
|
|
92
|
+
if (tail) {
|
|
93
|
+
deliverMany(tail, false);
|
|
94
|
+
}
|
|
95
|
+
else {
|
|
96
|
+
const kf = await nextRemote.keyframe();
|
|
97
|
+
if (slotClosed)
|
|
98
|
+
return;
|
|
99
|
+
if (kf)
|
|
100
|
+
deliverMany([kf], allowReset);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
if (lineError)
|
|
104
|
+
throw lineError;
|
|
105
|
+
while (queue.length)
|
|
106
|
+
deliver(queue.shift());
|
|
107
|
+
replaying = false;
|
|
108
|
+
}
|
|
109
|
+
catch (e) {
|
|
110
|
+
closeSlot();
|
|
111
|
+
throw e;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
slot = {
|
|
115
|
+
label,
|
|
116
|
+
ready: catchUp(),
|
|
117
|
+
close: closeSlot,
|
|
118
|
+
closed: () => slotClosed,
|
|
119
|
+
};
|
|
120
|
+
slots.add(slot);
|
|
121
|
+
return slot;
|
|
122
|
+
}
|
|
123
|
+
async function doSwitch(nextRemote, nextOpts = {}, initial = false) {
|
|
124
|
+
if (closed)
|
|
125
|
+
throw new Error('replayRouteSubscribe: closed');
|
|
126
|
+
const from = active;
|
|
127
|
+
const fromLabel = from?.label ?? currentLabel;
|
|
128
|
+
const toLabel = nextOpts.label;
|
|
129
|
+
const since = nextOpts.since ?? lastDelivered;
|
|
130
|
+
const allowReset = nextOpts.reset ?? (initial || !from);
|
|
131
|
+
const slot = attach(nextRemote, since, nextOpts, allowReset);
|
|
132
|
+
emitRoute({ phase: 'switching', from: fromLabel, to: toLabel, seq: lastDelivered });
|
|
133
|
+
try {
|
|
134
|
+
await slot.ready;
|
|
135
|
+
if (closed || slot.closed())
|
|
136
|
+
return;
|
|
137
|
+
active = slot;
|
|
138
|
+
currentLabel = slot.label;
|
|
139
|
+
if (from && from !== slot)
|
|
140
|
+
from.close();
|
|
141
|
+
emitRoute({ phase: 'ready', from: fromLabel, to: toLabel, seq: lastDelivered });
|
|
142
|
+
}
|
|
143
|
+
catch (e) {
|
|
144
|
+
slot.close();
|
|
145
|
+
emitRoute({ phase: 'error', from: fromLabel, to: toLabel, seq: lastDelivered, error: e });
|
|
146
|
+
onError?.(e);
|
|
147
|
+
throw e;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
const ready = doSwitch(remote, opts, true);
|
|
151
|
+
switchChain = ready.catch(() => { });
|
|
152
|
+
function switchRoute(nextRemote, nextOpts = {}) {
|
|
153
|
+
const run = () => doSwitch(nextRemote, nextOpts, false);
|
|
154
|
+
const p = switchChain.then(run, run);
|
|
155
|
+
switchChain = p.catch(() => { });
|
|
156
|
+
return p;
|
|
157
|
+
}
|
|
158
|
+
function off() {
|
|
159
|
+
if (closed)
|
|
160
|
+
return;
|
|
161
|
+
closed = true;
|
|
162
|
+
for (const slot of Array.from(slots))
|
|
163
|
+
slot.close();
|
|
164
|
+
active = null;
|
|
165
|
+
emitRoute({ phase: 'closed', seq: lastDelivered, to: currentLabel });
|
|
166
|
+
}
|
|
167
|
+
return Object.assign(off, {
|
|
168
|
+
ready,
|
|
169
|
+
switch: switchRoute,
|
|
170
|
+
seq: () => lastDelivered,
|
|
171
|
+
label: () => currentLabel,
|
|
172
|
+
active: () => active != null && !active.closed(),
|
|
173
|
+
});
|
|
174
|
+
}
|