@arca-network/sdk 1.10.0 → 1.12.0

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/dist/websocket.js CHANGED
@@ -2,6 +2,59 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.WebSocketManager = void 0;
4
4
  const types_1 = require("./types");
5
+ /**
6
+ * Capabilities the SDK advertises at auth.
7
+ *
8
+ * `frames` opts this connection into watch protocol v2 — per-transition
9
+ * FRAME messages and, more importantly, the watermarks that let a watch
10
+ * resume across a reconnect instead of re-snapshotting. The server treats
11
+ * an unrecognised token as absent, so advertising it is safe against any
12
+ * platform version.
13
+ */
14
+ const WS_CAPABILITIES = ['frames'];
15
+ /**
16
+ * Reads a watermark off a wire message, in either shape the server sends
17
+ * it: nested (`watermark: {rseq, priceEpoch}`, used by snapshots) or
18
+ * flattened onto the envelope (`rseq` / `priceEpoch`, used by streamed
19
+ * events). Returns undefined when neither is present.
20
+ *
21
+ * Zero is filtered out rather than kept, because absence and position
22
+ * zero mean opposite things: absent is "nothing to resume from", zero is
23
+ * "resume from the beginning of the realm's history".
24
+ */
25
+ function readWatermark(msg) {
26
+ const nested = msg.watermark;
27
+ const rseq = typeof nested?.rseq === 'number' ? nested.rseq : msg.rseq;
28
+ const priceEpoch = typeof nested?.priceEpoch === 'number'
29
+ ? nested.priceEpoch
30
+ : msg.priceEpoch;
31
+ const wm = {};
32
+ if (typeof rseq === 'number' && rseq > 0)
33
+ wm.rseq = rseq;
34
+ if (typeof priceEpoch === 'number' && priceEpoch > 0)
35
+ wm.priceEpoch = priceEpoch;
36
+ return wm.rseq === undefined && wm.priceEpoch === undefined ? undefined : wm;
37
+ }
38
+ /**
39
+ * Merges a newly observed watermark into a tracked one, keeping the
40
+ * furthest position seen on each axis independently.
41
+ *
42
+ * `rseq` and `priceEpoch` advance for unrelated reasons — the ledger and
43
+ * the market — so an update that carries only one must not erase the
44
+ * other. Taking the max rather than the latest also makes the cursor
45
+ * immune to out-of-order delivery: a resume cursor that moved backwards
46
+ * would ask the server to replay positions the client already applied.
47
+ */
48
+ function advanceWatermark(prev, next) {
49
+ if (!next)
50
+ return prev;
51
+ if (!prev)
52
+ return next;
53
+ return {
54
+ rseq: Math.max(prev.rseq ?? 0, next.rseq ?? 0) || undefined,
55
+ priceEpoch: Math.max(prev.priceEpoch ?? 0, next.priceEpoch ?? 0) || undefined,
56
+ };
57
+ }
5
58
  function sameCoinSet(a, b) {
6
59
  if (a.length !== b.length)
7
60
  return false;
@@ -29,6 +82,9 @@ function getWS() {
29
82
  class WebSocketManager {
30
83
  config;
31
84
  ws = null;
85
+ // A replacement socket being warmed up while `ws` keeps serving. It is not
86
+ // visible to consumers and does not dispatch events; see `beginHandoff`.
87
+ handoffWs = null;
32
88
  reconnectTimer = null;
33
89
  reconnectAttempt = 0;
34
90
  maxReconnectDelay;
@@ -71,6 +127,24 @@ class WebSocketManager {
71
127
  // After resuming visibility we ping and wait this long for any inbound
72
128
  // message; absence is treated as a half-open TCP and forces a reconnect.
73
129
  static RESUME_PING_TIMEOUT_MS = 2_000;
130
+ // Default socket lifetime before a rotation. Sits below the 3600s cap the
131
+ // production load balancer imposes, leaving room for the retries below to
132
+ // land before the cap is reached.
133
+ static DEFAULT_CONNECTION_LIFETIME_MS = 50 * 60_000;
134
+ // Fraction of the known lifetime at which to rotate.
135
+ static ROTATE_AT = 0.85;
136
+ // Rotations are spread out by ±this fraction. Every rotation costs a
137
+ // resubscribe, and a resubscribe costs the server a full mids snapshot — so
138
+ // a fleet that rotated on a shared schedule would arrive as a thundering
139
+ // herd. The jitter is what keeps the cost flat instead of spiky.
140
+ static ROTATE_JITTER = 0.1;
141
+ // A warming socket that has not taken over within this budget is abandoned.
142
+ static HANDOFF_TIMEOUT_MS = 10_000;
143
+ // Retry delay after a failed handoff, and the wait between attempts to
144
+ // promote past in-flight requests.
145
+ static HANDOFF_RETRY_MS = 60_000;
146
+ static PROMOTE_RETRY_MS = 250;
147
+ static PROMOTE_MAX_ATTEMPTS = 20;
74
148
  pingTimer = null;
75
149
  lastMessageAt = Date.now();
76
150
  // Monotonic counter incremented on every inbound message; used by the
@@ -80,8 +154,37 @@ class WebSocketManager {
80
154
  messageCounter = 0;
81
155
  lastDeliverySeq = 0;
82
156
  gapCallbacks = new Set();
157
+ // Resume cursors. Path watches are re-issued by this manager on
158
+ // reconnect, so it holds their positions; standalone aggregation
159
+ // watches are recreated by their stream, so their positions are read
160
+ // back out via watermarkForWatch. Both survive a disconnect on
161
+ // purpose — the cursor is precisely what the reconnect needs.
162
+ pathWatermarks = new Map();
163
+ watchWatermarks = new Map();
164
+ connectionWatermark;
165
+ // In-flight replays, keyed by watch id. `watch_resumed` announces the
166
+ // head the replay will END at; recording that head before the replayed
167
+ // frames actually arrive would let a mid-replay disconnect resume from
168
+ // beyond the frames that never made it. So the head is parked here and
169
+ // the scope's cursor only advances from frames as they are applied —
170
+ // the head (plus any live positions that raced the replay, parked in
171
+ // `deferred`) is folded in when the announced count has arrived. A
172
+ // disconnect discards the entry: the cursor then sits at the last
173
+ // frame actually applied, which is exactly where resume must ask from.
174
+ pendingResumes = new Map();
83
175
  resumeCallbacks = new Set();
84
176
  authenticatedCallbacks = new Set();
177
+ rotatedCallbacks = new Set();
178
+ rotationTimer = null;
179
+ handoffTimer = null;
180
+ promoteTimer = null;
181
+ promoteAttempt = 0;
182
+ // Lifetime the server reported during auth, which outranks the configured
183
+ // one: the server sits behind the proxy enforcing the cap, so it is the only
184
+ // party that knows the real number. Reading it means retuning the cap is a
185
+ // server-side config change rather than an SDK release.
186
+ serverLifetimeMs = null;
187
+ connectionLifetimeMs;
85
188
  hiddenAt = null;
86
189
  removeVisibilityListener = null;
87
190
  resumePingTimer = null;
@@ -91,6 +194,8 @@ class WebSocketManager {
91
194
  this.config = config;
92
195
  this.maxReconnectDelay = config.maxReconnectDelay ?? 30000;
93
196
  this.maxReconnectAttempts = config.maxReconnectAttempts ?? Infinity;
197
+ this.connectionLifetimeMs = config.connectionLifetimeMs
198
+ ?? WebSocketManager.DEFAULT_CONNECTION_LIFETIME_MS;
94
199
  this.installVisibilityListener();
95
200
  }
96
201
  // ---- Ref-counted path watch management ----
@@ -135,6 +240,10 @@ class WebSocketManager {
135
240
  this.unsubTimers.delete(timerKey);
136
241
  if (!this.pathRefs.has(path)) {
137
242
  this.snapshotCache.delete(path);
243
+ // The cursor goes with the watch: a future re-watch starts
244
+ // from a fresh snapshot, so a position kept here would never
245
+ // be read again — it would only accumulate.
246
+ this.pathWatermarks.delete(path);
138
247
  if (this.ws?.readyState === getWS().OPEN) {
139
248
  this.ws.send(JSON.stringify({ action: 'unwatch', path }));
140
249
  }
@@ -485,26 +594,47 @@ class WebSocketManager {
485
594
  this.ensureConnected();
486
595
  });
487
596
  }
488
- doConnect() {
489
- if (this.ws) {
490
- // Neutralize the old socket's close handler before replacing it so
491
- // its (async) close event doesn't emit a spurious 'disconnected'
492
- // status or schedule a competing reconnect against the new socket.
493
- this.ws.onclose = null;
494
- this.ws.close();
495
- this.ws = null;
597
+ /**
598
+ * Open a socket.
599
+ *
600
+ * In `handoff` mode the existing socket is left untouched and serving; the
601
+ * new one warms up alongside it and only takes over once it is fully
602
+ * subscribed (see `beginHandoff`). Every other caller replaces the current
603
+ * socket outright, which is the correct behaviour when it is already gone.
604
+ */
605
+ doConnect(mode = 'primary') {
606
+ const isHandoff = mode === 'handoff';
607
+ if (!isHandoff) {
608
+ this.cancelRotation();
609
+ this.abortHandoff();
610
+ if (this.ws) {
611
+ // Neutralize the old socket's close handler before replacing it so
612
+ // its (async) close event doesn't emit a spurious 'disconnected'
613
+ // status or schedule a competing reconnect against the new socket.
614
+ this.ws.onclose = null;
615
+ this.ws.close();
616
+ this.ws = null;
617
+ }
496
618
  }
497
619
  const httpUrl = this.config.baseUrl.replace(/\/api\/v1$/, '');
498
620
  const wsUrl = httpUrl.replace(/^http/, 'ws') + '/api/v1/ws';
499
- this.emitStatus('connecting');
621
+ if (!isHandoff)
622
+ this.emitStatus('connecting');
500
623
  const ws = new (getWS())(wsUrl);
501
- this.ws = ws;
624
+ if (isHandoff) {
625
+ this.handoffWs = ws;
626
+ }
627
+ else {
628
+ this.ws = ws;
629
+ }
502
630
  ws.onopen = () => {
503
- this.reconnectAttempt = 0;
631
+ if (!isHandoff)
632
+ this.reconnectAttempt = 0;
504
633
  const sendAuth = (credential) => {
505
634
  const authMsg = {
506
635
  action: 'auth',
507
636
  realmId: this.config.getRealmId(),
637
+ capabilities: WS_CAPABILITIES,
508
638
  };
509
639
  if (this.config.credentialType === 'apiKey') {
510
640
  authMsg.apiKey = credential;
@@ -529,14 +659,54 @@ class WebSocketManager {
529
659
  ws.onmessage = (e) => {
530
660
  try {
531
661
  const msg = JSON.parse(e.data);
532
- this.lastMessageAt = Date.now();
533
- this.messageCounter++;
662
+ // A warming socket is not the one consumers are reading from yet, so
663
+ // it takes no part in liveness tracking or event delivery until it
664
+ // takes over.
665
+ const warming = this.handoffWs === ws && this.ws !== ws;
666
+ if (warming) {
667
+ if (msg.type === 'error') {
668
+ this.abortHandoff();
669
+ this.scheduleRotation(WebSocketManager.HANDOFF_RETRY_MS);
670
+ return;
671
+ }
672
+ if (msg.type === 'pong') {
673
+ // The server reads one connection's messages in order, so a reply
674
+ // to the ping queued behind the resubscribe batch proves every
675
+ // subscription in that batch is registered — from here on, live
676
+ // broadcasts reach this socket. That is what makes this the point
677
+ // where it can take over without leaving a gap.
678
+ //
679
+ // Any snapshot those subscriptions trigger is sent
680
+ // asynchronously and may well arrive after this pong, so it is not
681
+ // part of the barrier — and it is not needed, because the socket
682
+ // being retired has been delivering the same stream right up to
683
+ // this moment, leaving consumer state current at the swap.
684
+ this.clearHandoffTimeout();
685
+ this.promoteHandoff(ws);
686
+ return;
687
+ }
688
+ if (msg.type !== 'authenticated') {
689
+ // The live socket is carrying this same stream, so anything
690
+ // arriving here before the takeover duplicates something
691
+ // consumers already have. Dropping it avoids a double dispatch
692
+ // and keeps gap detection on a single sequence space.
693
+ return;
694
+ }
695
+ }
696
+ else {
697
+ this.lastMessageAt = Date.now();
698
+ this.messageCounter++;
699
+ }
534
700
  if (msg.type === 'pong')
535
701
  return;
536
702
  if (msg.type === 'authenticated') {
537
- this.lastDeliverySeq = 0;
538
- this.emitStatus('connected');
539
- this.startHeartbeat();
703
+ this.readServerLifetime(msg);
704
+ if (!warming) {
705
+ this.lastDeliverySeq = 0;
706
+ this.emitStatus('connected');
707
+ this.startHeartbeat();
708
+ this.scheduleRotation();
709
+ }
540
710
  // Re-subscribe mids based on current ref state (not the stale
541
711
  // `subscribedMids` cache, which may no longer reflect consumer intent
542
712
  // after unmounts/remounts across a disconnect).
@@ -594,10 +764,20 @@ class WebSocketManager {
594
764
  if (this.tradeRefs.size > 0 && !this.subscribedTrades) {
595
765
  ws.send(JSON.stringify({ action: 'subscribe_trades', coins: Array.from(this.tradeRefs.keys()) }));
596
766
  }
597
- // Re-watch all paths from ref-counted state
767
+ // Re-watch all paths from ref-counted state. Where we hold a
768
+ // fold position for the path, ask to resume from it instead of
769
+ // re-snapshotting: the server replays exactly the transitions
770
+ // that landed while the socket was down, so the client misses
771
+ // nothing and re-reads nothing. A position the server can no
772
+ // longer replay is not an error — it silently answers with a
773
+ // full snapshot, which is what would have happened anyway.
598
774
  for (const path of this.pathRefs.keys()) {
599
775
  const requestId = `watch-${++this.nextRequestId}`;
600
- ws.send(JSON.stringify({ action: 'watch', path, requestId }));
776
+ const msg = { action: 'watch', path, requestId };
777
+ const fromRseq = this.pathWatermarks.get(path)?.rseq;
778
+ if (fromRseq)
779
+ msg.fromRseq = fromRseq;
780
+ ws.send(JSON.stringify(msg));
601
781
  }
602
782
  for (const [watchId, req] of this.chartHistoryWatches) {
603
783
  ws.send(JSON.stringify({
@@ -608,6 +788,12 @@ class WebSocketManager {
608
788
  objectId: req.objectId,
609
789
  }));
610
790
  }
791
+ if (warming) {
792
+ // Queue a ping behind the batch above; its reply is the barrier
793
+ // this socket takes over on.
794
+ ws.send(JSON.stringify({ action: 'ping' }));
795
+ return;
796
+ }
611
797
  // Notify subscribers AFTER all subscriptions are re-issued so any
612
798
  // chart-history watch IDs they depend on are already registered.
613
799
  this.authenticatedCallbacks.forEach(cb => cb());
@@ -633,12 +819,14 @@ class WebSocketManager {
633
819
  return;
634
820
  }
635
821
  if (msg.type === 'aggregation_watch_created') {
822
+ const watermark = readWatermark(msg);
823
+ this.recordWatermark(watermark, undefined, msg.watchId);
636
824
  if (msg.requestId && this.pendingRequests.has(msg.requestId)) {
637
825
  const pending = this.pendingRequests.get(msg.requestId);
638
826
  this.pendingRequests.delete(msg.requestId);
639
827
  clearTimeout(pending.timeout);
640
828
  pending.onCleanup?.();
641
- pending.resolve({ watchId: msg.watchId, aggregation: msg.aggregation });
829
+ pending.resolve({ watchId: msg.watchId, aggregation: msg.aggregation, watermark });
642
830
  }
643
831
  return;
644
832
  }
@@ -653,6 +841,8 @@ class WebSocketManager {
653
841
  }
654
842
  // Path-scoped watch snapshot
655
843
  if (msg.type === 'watch_snapshot') {
844
+ const watermark = readWatermark(msg);
845
+ this.recordWatermark(watermark, msg.path, msg.watchId);
656
846
  const snapshot = {
657
847
  path: msg.path ?? '',
658
848
  balances: msg.balances ?? [],
@@ -662,6 +852,7 @@ class WebSocketManager {
662
852
  valuation: msg.valuation ?? null,
663
853
  valuations: msg.valuations ?? undefined,
664
854
  watchId: msg.watchId ?? null,
855
+ watermark,
665
856
  };
666
857
  if (msg.requestId && this.pendingSnapshots.has(msg.requestId)) {
667
858
  const pending = this.pendingSnapshots.get(msg.requestId);
@@ -672,6 +863,74 @@ class WebSocketManager {
672
863
  this.dispatchEvent({ type: 'watch_snapshot', ...msg });
673
864
  return;
674
865
  }
866
+ // The server accepted a resume: the frames that follow carry
867
+ // everything this scope missed, so there is no snapshot coming.
868
+ //
869
+ // The quoted watermark is where the replay will END, not where
870
+ // the scope currently is — it becomes true of this client only
871
+ // once every announced frame has arrived. An empty replay is
872
+ // caught up already, so its head is recorded on the spot; a
873
+ // non-empty one parks the head until the count is met (see
874
+ // pendingResumes), so a disconnect mid-replay resumes from the
875
+ // last frame that actually arrived instead of skipping the rest.
876
+ if (msg.type === 'watch_resumed') {
877
+ const watermark = readWatermark(msg);
878
+ const expect = typeof msg.frames === 'number' ? msg.frames : 0;
879
+ if (expect > 0 && watermark && msg.watchId) {
880
+ this.pendingResumes.set(msg.watchId, {
881
+ expect, seen: 0, head: watermark, path: msg.path,
882
+ });
883
+ }
884
+ else {
885
+ this.recordWatermark(watermark, msg.path, msg.watchId);
886
+ }
887
+ if (msg.requestId && this.pendingSnapshots.has(msg.requestId)) {
888
+ // A resume answers with deltas, not with the snapshot the
889
+ // waiter is holding out for. The SDK only resumes watches it
890
+ // re-establishes itself (no waiter), so this is unreachable
891
+ // in practice — but failing fast beats a 15s timeout with a
892
+ // message that blames the network.
893
+ const pending = this.pendingSnapshots.get(msg.requestId);
894
+ this.pendingSnapshots.delete(msg.requestId);
895
+ clearTimeout(pending.timeout);
896
+ pending.reject(new Error(`watchPath: server resumed ${msg.path ?? 'watch'} from rseq ${watermark?.rseq ?? 0} instead of sending a snapshot`));
897
+ }
898
+ this.dispatchEvent({ type: 'watch_resumed', ...msg });
899
+ return;
900
+ }
901
+ // One committed transition, scoped to a watch. Carries absolutes,
902
+ // so applying it twice is a no-op — which is what makes an
903
+ // overlapping resume safe.
904
+ if (msg.type === 'frame') {
905
+ if (typeof msg.deliverySeq === 'number') {
906
+ this.checkDeliveryGap(msg.deliverySeq);
907
+ }
908
+ const wm = readWatermark(msg);
909
+ const pending = msg.watchId ? this.pendingResumes.get(msg.watchId) : undefined;
910
+ if (pending && !msg.replayed) {
911
+ // A live frame racing an unfinished replay sits ABOVE the
912
+ // replay's head. Filing its position now would let a
913
+ // disconnect strand the un-replayed range below it, so it
914
+ // is parked and folded in when the replay completes. The
915
+ // frame itself is still dispatched — payloads are
916
+ // absolutes, only the cursor waits.
917
+ pending.deferred = advanceWatermark(pending.deferred, wm);
918
+ this.connectionWatermark = advanceWatermark(this.connectionWatermark, wm);
919
+ }
920
+ else {
921
+ // Replayed frames arrive in rseq order from the resume
922
+ // point, so each one is a position this scope has genuinely
923
+ // reached — safe to record as it lands.
924
+ this.recordWatermark(wm, msg.path, msg.watchId);
925
+ if (pending && ++pending.seen >= pending.expect) {
926
+ this.pendingResumes.delete(msg.watchId);
927
+ this.recordWatermark(pending.head, pending.path, msg.watchId);
928
+ this.recordWatermark(pending.deferred, pending.path, msg.watchId);
929
+ }
930
+ }
931
+ this.dispatchEvent(this.withWatermark(msg));
932
+ return;
933
+ }
675
934
  if (msg.type === 'mids.snapshot' && msg.mids) {
676
935
  // Server-side `mids.snapshot` is a full current-state read sent
677
936
  // immediately after subscribe (and after reconnect). It has
@@ -729,17 +988,42 @@ class WebSocketManager {
729
988
  if (typeof msg.deliverySeq === 'number') {
730
989
  this.checkDeliveryGap(msg.deliverySeq);
731
990
  }
732
- const event = msg;
733
- this.dispatchEvent(event);
991
+ // `entityId` doubles as the watch id ONLY on aggregation.updated
992
+ // (the server labels the watch that way on the wire). On every
993
+ // other event it names an object or account, and filing cursors
994
+ // under those ids would grow watchWatermarks with keys nothing
995
+ // ever resumes from.
996
+ const watchKey = msg.watchId
997
+ ?? (msg.type === types_1.EventType.AggregationUpdated ? msg.entityId : undefined);
998
+ this.recordWatermark(readWatermark(msg), msg.path, watchKey);
999
+ this.dispatchEvent(this.withWatermark(msg));
734
1000
  }
735
1001
  catch {
736
1002
  // Ignore parse errors
737
1003
  }
738
1004
  };
739
1005
  ws.onclose = () => {
1006
+ if (this.handoffWs === ws && this.ws !== ws) {
1007
+ // A warming socket died before taking over. The live socket never
1008
+ // stopped serving, so consumers see nothing; try again later rather
1009
+ // than escalating to the reconnect path.
1010
+ this.handoffWs = null;
1011
+ this.clearHandoffTimeout();
1012
+ this.clearPromoteTimer();
1013
+ this.scheduleRotation(WebSocketManager.HANDOFF_RETRY_MS);
1014
+ return;
1015
+ }
1016
+ // The live socket is gone, so a warming replacement for it is moot —
1017
+ // the reconnect path below supersedes it.
1018
+ this.cancelRotation();
1019
+ this.abortHandoff();
740
1020
  this.stopHeartbeat();
741
1021
  this.rejectPendingRequests('WebSocket disconnected');
742
1022
  this.rejectPendingSnapshots('WebSocket disconnected');
1023
+ // Replays die with their socket. Dropping the parked heads leaves
1024
+ // each scope's cursor at the last frame that actually arrived,
1025
+ // which is the position the next resume must ask from.
1026
+ this.pendingResumes.clear();
743
1027
  this.emitStatus('disconnected');
744
1028
  if (this.shouldReconnect) {
745
1029
  this.scheduleReconnect();
@@ -749,6 +1033,170 @@ class WebSocketManager {
749
1033
  // onclose will fire after onerror
750
1034
  };
751
1035
  }
1036
+ /**
1037
+ * Replace the current socket with a fresh one without interrupting delivery.
1038
+ *
1039
+ * The replacement authenticates and re-issues every subscription while the
1040
+ * current socket keeps streaming. Only once the server confirms those
1041
+ * subscriptions are live does it take over, and only then does the old
1042
+ * socket close — so there is no window in which nothing is subscribed. A
1043
+ * failure anywhere along the way leaves the current socket untouched and
1044
+ * serving, which makes the worst case "nothing happened".
1045
+ *
1046
+ * Returns false when there is no healthy socket to hand off from, or when a
1047
+ * handoff is already under way.
1048
+ */
1049
+ rotateConnection() {
1050
+ if (!this.shouldReconnect)
1051
+ return false;
1052
+ if (this.handoffWs)
1053
+ return false;
1054
+ if (this.lastStatus !== 'connected')
1055
+ return false;
1056
+ if (this.ws?.readyState !== getWS().OPEN)
1057
+ return false;
1058
+ this.promoteAttempt = 0;
1059
+ // Armed before the socket exists so a half-built one can never be left
1060
+ // hanging around unnoticed.
1061
+ this.clearHandoffTimeout();
1062
+ this.handoffTimer = setTimeout(() => {
1063
+ this.handoffTimer = null;
1064
+ this.abortHandoff();
1065
+ this.scheduleRotation(WebSocketManager.HANDOFF_RETRY_MS);
1066
+ }, WebSocketManager.HANDOFF_TIMEOUT_MS);
1067
+ this.doConnect('handoff');
1068
+ return true;
1069
+ }
1070
+ /**
1071
+ * Hand delivery over to the warmed socket and retire the current one.
1072
+ */
1073
+ promoteHandoff(ws) {
1074
+ if (this.handoffWs !== ws)
1075
+ return;
1076
+ if (ws.readyState !== getWS().OPEN) {
1077
+ this.abortHandoff();
1078
+ this.scheduleRotation(WebSocketManager.HANDOFF_RETRY_MS);
1079
+ return;
1080
+ }
1081
+ // Retiring the old socket rejects anything still awaiting a reply on it. A
1082
+ // rotation has slack by construction — it runs well before the lifetime it
1083
+ // exists to avoid — so wait for the reply instead of turning it into a
1084
+ // spurious failure.
1085
+ if ((this.pendingRequests.size > 0 || this.pendingSnapshots.size > 0)
1086
+ && this.promoteAttempt < WebSocketManager.PROMOTE_MAX_ATTEMPTS) {
1087
+ this.promoteAttempt++;
1088
+ this.clearPromoteTimer();
1089
+ this.promoteTimer = setTimeout(() => {
1090
+ this.promoteTimer = null;
1091
+ this.promoteHandoff(ws);
1092
+ }, WebSocketManager.PROMOTE_RETRY_MS);
1093
+ return;
1094
+ }
1095
+ this.clearPromoteTimer();
1096
+ this.clearHandoffTimeout();
1097
+ this.handoffWs = null;
1098
+ const retired = this.ws;
1099
+ if (retired && retired !== ws) {
1100
+ // Silence it before closing: its close must not emit a status change or
1101
+ // schedule a competing reconnect, and anything left in its buffer must
1102
+ // not reach consumers a second time.
1103
+ retired.onclose = null;
1104
+ retired.onmessage = null;
1105
+ retired.onerror = null;
1106
+ retired.onopen = null;
1107
+ try {
1108
+ retired.close();
1109
+ }
1110
+ catch { /* already closing */ }
1111
+ }
1112
+ this.ws = ws;
1113
+ // Replays die with the socket that was serving them. Dropping the parked
1114
+ // heads leaves each scope's cursor at the last frame actually applied,
1115
+ // which is the position a later resume must ask from.
1116
+ this.pendingResumes.clear();
1117
+ // New connection, new sequence space.
1118
+ this.lastDeliverySeq = 0;
1119
+ this.lastMessageAt = Date.now();
1120
+ this.promoteAttempt = 0;
1121
+ this.startHeartbeat();
1122
+ this.scheduleRotation();
1123
+ // Status deliberately does not move. Delivery never stopped, so emitting
1124
+ // 'disconnected' would put consumers into a reconnecting state and run gap
1125
+ // recovery for a gap that did not happen. State the swap genuinely cannot
1126
+ // carry over is re-established via `onRotated` instead.
1127
+ this.rotatedCallbacks.forEach(cb => cb());
1128
+ }
1129
+ /** Abandon a warming socket. The live socket is left exactly as it was. */
1130
+ abortHandoff() {
1131
+ const ws = this.handoffWs;
1132
+ this.handoffWs = null;
1133
+ this.clearHandoffTimeout();
1134
+ this.clearPromoteTimer();
1135
+ this.promoteAttempt = 0;
1136
+ if (ws) {
1137
+ ws.onclose = null;
1138
+ ws.onmessage = null;
1139
+ ws.onerror = null;
1140
+ ws.onopen = null;
1141
+ try {
1142
+ ws.close();
1143
+ }
1144
+ catch { /* may not have opened */ }
1145
+ }
1146
+ }
1147
+ /**
1148
+ * Arm the next rotation. `delayMs` overrides the schedule, which is how a
1149
+ * failed handoff retries before the lifetime it is racing runs out.
1150
+ */
1151
+ scheduleRotation(delayMs) {
1152
+ this.cancelRotation();
1153
+ const lifetime = this.serverLifetimeMs ?? this.connectionLifetimeMs;
1154
+ if (delayMs === undefined && !(lifetime > 0))
1155
+ return;
1156
+ let delay = delayMs;
1157
+ if (delay === undefined) {
1158
+ const base = lifetime * WebSocketManager.ROTATE_AT;
1159
+ const spread = base * WebSocketManager.ROTATE_JITTER;
1160
+ delay = base - spread + Math.random() * spread * 2;
1161
+ }
1162
+ this.rotationTimer = setTimeout(() => {
1163
+ this.rotationTimer = null;
1164
+ this.rotateConnection();
1165
+ }, delay);
1166
+ }
1167
+ cancelRotation() {
1168
+ if (this.rotationTimer) {
1169
+ clearTimeout(this.rotationTimer);
1170
+ this.rotationTimer = null;
1171
+ }
1172
+ }
1173
+ clearHandoffTimeout() {
1174
+ if (this.handoffTimer) {
1175
+ clearTimeout(this.handoffTimer);
1176
+ this.handoffTimer = null;
1177
+ }
1178
+ }
1179
+ clearPromoteTimer() {
1180
+ if (this.promoteTimer) {
1181
+ clearTimeout(this.promoteTimer);
1182
+ this.promoteTimer = null;
1183
+ }
1184
+ }
1185
+ /**
1186
+ * Adopt the socket lifetime the server reports at auth.
1187
+ *
1188
+ * The server sits behind the proxy that enforces the cap, so it is the only
1189
+ * party that knows the real figure. Taking it from the wire means retuning
1190
+ * the cap is a server config change rather than an SDK release — otherwise
1191
+ * every deployed client keeps rotating against a number that silently went
1192
+ * stale.
1193
+ */
1194
+ readServerLifetime(msg) {
1195
+ const sec = msg?.maxConnectionLifetimeSec;
1196
+ if (typeof sec === 'number' && Number.isFinite(sec) && sec > 0) {
1197
+ this.serverLifetimeMs = sec * 1000;
1198
+ }
1199
+ }
752
1200
  subscribeMids(exchange, coins = []) {
753
1201
  this.subscribedMids = { exchange, coins };
754
1202
  if (this.ws?.readyState === getWS().OPEN) {
@@ -913,7 +1361,18 @@ class WebSocketManager {
913
1361
  this.off(t, h);
914
1362
  };
915
1363
  }
916
- createAggregationWatch(sources, flowsSince) {
1364
+ /**
1365
+ * Create a standalone aggregation watch.
1366
+ *
1367
+ * The second parameter accepts either the bare `flowsSince` string it
1368
+ * has always taken or an options object; the string form is kept
1369
+ * because it is public API and silently changing its meaning would
1370
+ * break callers with no compile error.
1371
+ */
1372
+ createAggregationWatch(sources, options) {
1373
+ const { flowsSince, fromRseq } = typeof options === 'string'
1374
+ ? { flowsSince: options, fromRseq: undefined }
1375
+ : { flowsSince: options?.flowsSince, fromRseq: options?.fromRseq };
917
1376
  return new Promise((resolve, reject) => {
918
1377
  this.ensureConnected();
919
1378
  const requestId = String(++this.nextRequestId);
@@ -929,6 +1388,8 @@ class WebSocketManager {
929
1388
  const msg = { action: 'create_aggregation_watch', sources, requestId };
930
1389
  if (flowsSince)
931
1390
  msg.flowsSince = flowsSince;
1391
+ if (fromRseq)
1392
+ msg.fromRseq = fromRseq;
932
1393
  this.ws.send(JSON.stringify(msg));
933
1394
  }
934
1395
  };
@@ -954,6 +1415,10 @@ class WebSocketManager {
954
1415
  });
955
1416
  }
956
1417
  destroyAggregationWatch(watchId) {
1418
+ // Server-side watch ids are never reused, so a destroyed watch's
1419
+ // cursor (and any replay parked against it) is dead weight.
1420
+ this.watchWatermarks.delete(watchId);
1421
+ this.pendingResumes.delete(watchId);
957
1422
  if (this.ws?.readyState === getWS().OPEN) {
958
1423
  this.ws.send(JSON.stringify({ action: 'destroy_aggregation_watch', watchId }));
959
1424
  }
@@ -1130,6 +1595,23 @@ class WebSocketManager {
1130
1595
  this.on(types_1.EventType.AggregationUpdated, handler);
1131
1596
  return () => this.off(types_1.EventType.AggregationUpdated, handler);
1132
1597
  }
1598
+ /**
1599
+ * Subscribe to per-transition frames.
1600
+ *
1601
+ * Optional by design: frames tell you *what moved*, while the
1602
+ * `aggregation.updated` / `object.valuation` delivered alongside each
1603
+ * one carries the resulting total. Code that only needs totals should
1604
+ * ignore frames entirely. Reach for them to drive per-account UI
1605
+ * without recomputing, or to attribute a change to the operation that
1606
+ * caused it (`operationId` / `opType`).
1607
+ */
1608
+ onFrame(cb) {
1609
+ const handler = (event) => {
1610
+ cb(event);
1611
+ };
1612
+ this.on(types_1.EventType.Frame, handler);
1613
+ return () => this.off(types_1.EventType.Frame, handler);
1614
+ }
1133
1615
  onChartSnapshotUpdated(cb) {
1134
1616
  const handler = (event) => {
1135
1617
  const watchId = event.watchId;
@@ -1191,6 +1673,8 @@ class WebSocketManager {
1191
1673
  disconnect() {
1192
1674
  this.shouldReconnect = false;
1193
1675
  this.stopHeartbeat();
1676
+ this.cancelRotation();
1677
+ this.abortHandoff();
1194
1678
  if (this.reconnectTimer) {
1195
1679
  clearTimeout(this.reconnectTimer);
1196
1680
  this.reconnectTimer = null;
@@ -1231,18 +1715,82 @@ class WebSocketManager {
1231
1715
  checkDeliveryGap(seq) {
1232
1716
  if (this.lastDeliverySeq > 0 && seq > this.lastDeliverySeq + 1) {
1233
1717
  const missed = seq - this.lastDeliverySeq - 1;
1234
- this.gapCallbacks.forEach(cb => cb(missed));
1718
+ const info = {
1719
+ missed,
1720
+ resumable: (this.connectionWatermark?.rseq ?? 0) > 0,
1721
+ watermark: this.connectionWatermark,
1722
+ };
1723
+ this.gapCallbacks.forEach(cb => cb(missed, info));
1235
1724
  }
1236
1725
  this.lastDeliverySeq = seq;
1237
1726
  }
1238
1727
  /**
1239
- * Register a callback for delivery sequence gaps. The callback receives the
1240
- * number of missed events. Watch streams use this to trigger targeted refetches.
1728
+ * Register a callback for delivery-sequence gaps.
1729
+ *
1730
+ * Historically this was the SDK's only repair mechanism: a gap meant
1731
+ * "something was lost, go refetch it over REST". On a frame-served
1732
+ * realm it is informational — the connection knows the fold position
1733
+ * each scope reached, and resuming from it recovers precisely what was
1734
+ * missed with no duplicate work. Check `info.resumable` before
1735
+ * reaching for a refetch.
1736
+ *
1737
+ * The first argument is unchanged, so existing callbacks keep working.
1241
1738
  */
1242
1739
  onGap(cb) {
1243
1740
  this.gapCallbacks.add(cb);
1244
1741
  return () => { this.gapCallbacks.delete(cb); };
1245
1742
  }
1743
+ /**
1744
+ * The furthest fold position this connection has observed, across every
1745
+ * scope. Undefined on a realm that is not frame-served.
1746
+ */
1747
+ watermark() {
1748
+ return this.connectionWatermark;
1749
+ }
1750
+ /** The fold position a path watch has been delivered up to. */
1751
+ watermarkForPath(path) {
1752
+ return this.pathWatermarks.get(path);
1753
+ }
1754
+ /**
1755
+ * The fold position an aggregation watch has been delivered up to.
1756
+ *
1757
+ * Read by {@link AggregationWatchStream} before it recreates its watch
1758
+ * on reconnect: the new watch resumes from the old one's position, so
1759
+ * the recreate stops being a re-snapshot.
1760
+ */
1761
+ watermarkForWatch(watchId) {
1762
+ return this.watchWatermarks.get(watchId);
1763
+ }
1764
+ /**
1765
+ * Files an observed position under the scopes it belongs to, plus the
1766
+ * connection-wide cursor.
1767
+ *
1768
+ * Positions only ever advance (see {@link advanceWatermark}) and are
1769
+ * kept across a disconnect, because the cursor's whole purpose is to
1770
+ * survive the outage it is used to repair.
1771
+ */
1772
+ recordWatermark(wm, path, watchId) {
1773
+ if (!wm)
1774
+ return;
1775
+ this.connectionWatermark = advanceWatermark(this.connectionWatermark, wm);
1776
+ if (path) {
1777
+ this.pathWatermarks.set(path, advanceWatermark(this.pathWatermarks.get(path), wm));
1778
+ }
1779
+ if (watchId) {
1780
+ this.watchWatermarks.set(watchId, advanceWatermark(this.watchWatermarks.get(watchId), wm));
1781
+ }
1782
+ }
1783
+ /**
1784
+ * Normalizes the wire's flat `rseq` / `priceEpoch` into the structured
1785
+ * `watermark` handlers read, leaving the raw fields in place so nothing
1786
+ * written against them breaks.
1787
+ */
1788
+ withWatermark(msg) {
1789
+ const wm = readWatermark(msg);
1790
+ if (wm)
1791
+ msg.watermark = wm;
1792
+ return msg;
1793
+ }
1246
1794
  /**
1247
1795
  * Register a callback fired when the page returns from a backgrounded /
1248
1796
  * tab-frozen state (visibility transition `hidden -> visible` after at
@@ -1267,6 +1815,26 @@ class WebSocketManager {
1267
1815
  this.authenticatedCallbacks.add(cb);
1268
1816
  return () => { this.authenticatedCallbacks.delete(cb); };
1269
1817
  }
1818
+ /**
1819
+ * Fires when delivery has moved to a new socket without an outage
1820
+ * (see {@link rotateConnection}).
1821
+ *
1822
+ * This is not a reconnect: no status change is emitted, nothing was missed,
1823
+ * and there is no gap to recover. It exists for state the server holds
1824
+ * per-connection and therefore cannot survive the swap — a standalone
1825
+ * aggregation watch has to be re-created against the new socket, because the
1826
+ * old one died with the connection it was registered on. Anything the
1827
+ * manager re-issues itself (mids, candles, OI, trades, path watches,
1828
+ * chart-history watches) is already handled and needs no hook.
1829
+ *
1830
+ * Do NOT use this to refetch history or run gap recovery; `onAuthenticated`
1831
+ * is the hook for that. Rotations are routine, so a refetch here multiplies
1832
+ * into steady background load across every connected client.
1833
+ */
1834
+ onRotated(cb) {
1835
+ this.rotatedCallbacks.add(cb);
1836
+ return () => { this.rotatedCallbacks.delete(cb); };
1837
+ }
1270
1838
  installVisibilityListener() {
1271
1839
  // Idempotent: if a listener is already installed, return. The constructor
1272
1840
  // calls this once and `connect()` re-calls it after a `disconnect()`