madeonsol 2.27.0 → 2.29.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/stream.js CHANGED
@@ -7,9 +7,36 @@
7
7
  * tokens do not expire: `getToken()` is called on every (re)connect and returns
8
8
  * the same value until the subscription lapses or you explicitly rotate it.
9
9
  *
10
- * Works in Node (global `WebSocket` on Node 22+, else lazily imports the
11
- * optional `ws` package) and the browser (native WebSocket). Zero required deps.
10
+ * Recovery (v1 resume): the client remembers a cursor `{instance, seq, ts}` —
11
+ * the last frame whose handlers finished — and on every reconnect asks the
12
+ * server to resume after it (`subscribe {…, resume}`); against an older server
13
+ * it falls back to `replay_since_seq` (same process) / `replay_since_ts`
14
+ * (restarted). Delivery is at-least-once, de-duplicated by event `id`; a
15
+ * `"gap"` event says what could NOT be recovered. `seq` gaps are normal and
16
+ * never mean loss. Close codes: 4001 re-fetches the token (bounded, then
17
+ * `"fatal"`), 4002 (connection limit) waits ≥ 60 s, 4003 stops with
18
+ * `"fatal"`, 4008 (slow consumer) reconnects and resumes.
19
+ *
20
+ * Works in Node (uses the global `WebSocket` on Node 22+, else lazily imports
21
+ * the optional `ws` package) and the browser (native WebSocket). Zero required
22
+ * dependencies.
12
23
  */
24
+ /** Every Solana channel, in the server's order. */
25
+ export const STREAM_CHANNELS = [
26
+ "kol:trades",
27
+ "kol:coordination",
28
+ "kol:first_touches",
29
+ "deployer:alerts",
30
+ "wallet_tracker:events",
31
+ "copytrade:signals",
32
+ "price_alert:events",
33
+ "sniper:deploys",
34
+ "token:graduations",
35
+ "token:prices",
36
+ "token:locks",
37
+ "token:fee_claims",
38
+ "token:surges",
39
+ ];
13
40
  async function resolveWebSocket(override) {
14
41
  if (override)
15
42
  return override;
@@ -18,7 +45,8 @@ async function resolveWebSocket(override) {
18
45
  // (undici) WebSocket on Node 22+ keeps its TLS socket open after close() —
19
46
  // it has no terminate() and no reachable socket handle — which hangs the
20
47
  // event loop. In the browser this import rejects and we fall back to the
21
- // platform's native WebSocket.
48
+ // platform's native WebSocket. Cast the specifier to string so TS doesn't
49
+ // require the module to be installed at build time.
22
50
  try {
23
51
  const mod = (await import("ws"));
24
52
  const impl = mod.default ?? mod.WebSocket;
@@ -34,25 +62,95 @@ async function resolveWebSocket(override) {
34
62
  throw new Error("No WebSocket implementation available. On Node < 22, install `ws` (npm i ws) or pass { WebSocketImpl }.");
35
63
  }
36
64
  const OPEN = 1;
65
+ const HELD_LIVE_CAP = 10000;
66
+ const DEFAULT_SUB_ID = "default";
67
+ const SUB_ID_RE = /^[A-Za-z0-9_.-]{1,64}$/;
68
+ const subIdOf = (f) => (typeof f.sub_id === "string" && f.sub_id ? f.sub_id : DEFAULT_SUB_ID);
69
+ function isThenable(v) {
70
+ return !!v && (typeof v === "object" || typeof v === "function") && typeof v.then === "function";
71
+ }
72
+ /**
73
+ * Fallback classification for servers that send no `retryable` flag: reasons
74
+ * asking again can never fill.
75
+ */
76
+ const PERMANENT_GAPS = new Set(["not_reconstructable", "state_stream", "window_exceeded", "ring_truncated", "instance_changed"]);
77
+ /** The server's transient list — a channel with one of these is worth asking again. */
78
+ const TRANSIENT_GAPS = new Set(["backpressure", "closed", "source_busy", "source_error", "late_ingest_possible", "row_cap"]);
79
+ function isPermanentGap(reason) {
80
+ return PERMANENT_GAPS.has(reason);
81
+ }
82
+ /** Move a cursor to `pos`: never back within one instance; seq:null frames only advance time. */
83
+ function stepCursor(c, pos) {
84
+ if (pos.seq !== null && pos.instance) {
85
+ if (c && c.instance === pos.instance)
86
+ return { instance: c.instance, seq: Math.max(c.seq, pos.seq), ts: Math.max(c.ts, pos.ts) };
87
+ return { instance: pos.instance, seq: pos.seq, ts: pos.ts };
88
+ }
89
+ // Unsequenced frame (durable backfill, seq:null): keep the last real seq, advance time.
90
+ return c ? { ...c, ts: Math.max(c.ts, pos.ts) } : null;
91
+ }
92
+ function validCursor(c) {
93
+ if (!c || typeof c !== "object")
94
+ return null;
95
+ const { instance, seq, ts } = c;
96
+ if (typeof instance !== "string" || !instance)
97
+ return null;
98
+ if (typeof seq !== "number" || !Number.isFinite(seq) || seq < 0)
99
+ return null;
100
+ if (typeof ts !== "number" || !Number.isFinite(ts) || ts < 0)
101
+ return null;
102
+ return { instance, seq, ts };
103
+ }
37
104
  export class MadeOnSolStream {
38
105
  constructor(opts) {
39
106
  this.ws = null;
40
107
  this.listeners = new Map();
41
108
  this.desired = { channels: new Set(), filters: {} };
109
+ /** Named subscriptions (Phase 2), in creation order; the default one is `desired`. */
110
+ this.named = new Map();
111
+ /** sub_ids of the subscribes sent on this connection whose `subscribed` ack is still due (acks arrive in order). */
112
+ this.ackExpect = [];
113
+ this.namedUnsupportedWarned = false;
114
+ this.listWaiters = [];
42
115
  this.closedByUser = false;
116
+ this.stopped = false;
43
117
  this.attempt = 0;
118
+ this.authFailures = 0;
44
119
  this.hbTimer = null;
45
120
  this.reconnectTimer = null;
46
121
  this.connecting = false;
122
+ /** Server process id of the CURRENT connection (from connected/subscribed). */
123
+ this.serverInstance = null;
124
+ /** Whether this connection already sent its first subscribe (the only one that resumes). */
125
+ this.firstSubscribeSent = false;
126
+ /** true after an incomplete recovery: live frames are not committed until one completes. */
127
+ this.unsafe = false;
128
+ this.seen = new Map();
129
+ this.inflight = [];
130
+ this.recovery = null;
131
+ /** Automatic re-resume after a retryable gap. */
132
+ this.retryTimer = null;
133
+ this.resumeRetries = 0;
134
+ /** The last gap reported (for acceptGap()'s report). */
135
+ this.lastGap = null;
47
136
  this.opts = {
48
137
  getToken: opts.getToken,
49
138
  autoReconnect: opts.autoReconnect ?? true,
50
139
  maxBackoffMs: opts.maxBackoffMs ?? 30000,
51
140
  heartbeatTimeoutMs: opts.heartbeatTimeoutMs ?? 90000,
52
141
  WebSocketImpl: opts.WebSocketImpl,
142
+ dedupeSize: Math.max(0, opts.dedupeSize ?? 10000),
143
+ maxAuthRetries: Math.max(0, opts.maxAuthRetries ?? 3),
144
+ connectionLimitBackoffMs: Math.max(0, opts.connectionLimitBackoffMs ?? 60000),
145
+ resumeDetectMs: Math.max(0, opts.resumeDetectMs ?? 3000),
146
+ legacyReplayTimeoutMs: Math.max(0, opts.legacyReplayTimeoutMs ?? 15000),
147
+ maxResumeRetries: Math.max(0, opts.maxResumeRetries ?? 5),
148
+ resumeRetryDelayMs: Math.max(0, opts.resumeRetryDelayMs ?? 30000),
149
+ onUnrecoverableGap: opts.onUnrecoverableGap === "stop" ? "stop" : "advance",
53
150
  };
151
+ this.cursor = validCursor(opts.resume);
152
+ this.progress = this.cursor ? { ...this.cursor } : null;
54
153
  }
55
- /** Register a handler. Use an event name, `"*"` for every event, or a lifecycle event. */
56
154
  on(event, fn) {
57
155
  if (!this.listeners.has(event))
58
156
  this.listeners.set(event, new Set());
@@ -67,6 +165,44 @@ export class MadeOnSolStream {
67
165
  this.listeners.get(event)?.delete(fn);
68
166
  return this;
69
167
  }
168
+ /** The COMMITTED resume cursor (last safe point) — persist this one. Null before the first. */
169
+ getCursor() {
170
+ return this.cursor ? { ...this.cursor } : null;
171
+ }
172
+ /** Received progress: the last handled frame, replayed ones included (NOT safe to resume from). */
173
+ getProgress() {
174
+ return this.progress ? { ...this.progress } : null;
175
+ }
176
+ /** true while an incomplete recovery holds the committed cursor back. */
177
+ isRecoveryIncomplete() {
178
+ return this.unsafe;
179
+ }
180
+ /**
181
+ * Accept the last reported gap: commit the received progress as the cursor
182
+ * and let live frames commit again. Call it after you backfilled the range
183
+ * the `"gap"` event named (or decided you do not need it). It re-reports the
184
+ * gap first, with `source: "manual"` and the range being skipped.
185
+ */
186
+ acceptGap() {
187
+ this.unsafe = false;
188
+ const p = this.progress;
189
+ const c = this.cursor;
190
+ const moves = !!p && !(c && c.instance === p.instance && c.seq === p.seq && c.ts === p.ts);
191
+ if (this.lastGap) {
192
+ const g = {
193
+ ...this.lastGap,
194
+ advancedPastGap: moves,
195
+ source: "manual",
196
+ skipped: { channels: this.lastGap.skipped.channels, from: c ? { ...c } : null, to: moves ? { ...p } : null },
197
+ };
198
+ this.lastGap = null;
199
+ this.emit("gap", g);
200
+ }
201
+ if (!moves)
202
+ return;
203
+ this.cursor = { ...p };
204
+ this.emit("cursor", { ...p });
205
+ }
70
206
  emit(event, data, evt) {
71
207
  const set = this.listeners.get(event);
72
208
  if (set)
@@ -77,31 +213,146 @@ export class MadeOnSolStream {
77
213
  catch { /* user handler */ }
78
214
  }
79
215
  }
80
- /** Subscribe to one or more channels (connects on first call). Optional server-side filters. */
81
- subscribe(channels, filters) {
82
- for (const c of channels)
83
- this.desired.channels.add(c);
84
- if (filters)
85
- this.desired.filters = { ...this.desired.filters, ...filters };
216
+ /** Call every handler for a data frame; collect what they returned (for completion tracking). */
217
+ callHandlers(event, data, evt, out) {
218
+ const set = this.listeners.get(event);
219
+ if (!set)
220
+ return;
221
+ for (const fn of set) {
222
+ try {
223
+ out.push(fn(data, evt));
224
+ }
225
+ catch (err) {
226
+ this.emit("error", err);
227
+ }
228
+ }
229
+ }
230
+ subscribe(arg, filters) {
231
+ if (Array.isArray(arg)) {
232
+ for (const c of arg)
233
+ this.desired.channels.add(c);
234
+ if (filters)
235
+ this.desired.filters = { ...this.desired.filters, ...filters };
236
+ if (this.ws && this.ws.readyState === OPEN)
237
+ this.sendSubscribe({ only: [DEFAULT_SUB_ID] });
238
+ else
239
+ void this.connect();
240
+ return this;
241
+ }
242
+ const subId = arg.subId;
243
+ if (typeof subId !== "string" || !SUB_ID_RE.test(subId))
244
+ throw new Error("subId must be 1-64 characters of A-Z a-z 0-9 _ . -");
245
+ if (subId === DEFAULT_SUB_ID)
246
+ return this.subscribe(arg.channels, arg.filters);
247
+ const entry = this.named.get(subId) ?? { channels: new Set(), filters: {} };
248
+ for (const c of arg.channels)
249
+ entry.channels.add(c);
250
+ // A named subscription's filters are REPLACED when given (the server does the same).
251
+ if (arg.filters)
252
+ entry.filters = { ...arg.filters };
253
+ this.named.set(subId, entry);
86
254
  if (this.ws && this.ws.readyState === OPEN)
87
- this.sendSubscribe();
255
+ this.sendSubscribe({ only: [subId] });
88
256
  else
89
257
  void this.connect();
90
258
  return this;
91
259
  }
92
- /** Stop receiving the given channels. */
93
- unsubscribe(channels) {
94
- for (const c of channels)
260
+ /**
261
+ * Replace the filters of a subscription (`"default"` for the plain one).
262
+ * The server acks with an `updated` frame; a refused update (for example a
263
+ * `token:prices` subscription without valid `mints`) arrives as a `warning`
264
+ * with code `invalid_filters` and the previous filters stay.
265
+ */
266
+ updateSubscription(subId, filters) {
267
+ if (subId === DEFAULT_SUB_ID)
268
+ this.desired.filters = { ...filters };
269
+ else {
270
+ const entry = this.named.get(subId);
271
+ if (!entry)
272
+ throw new Error(`unknown subscription ${subId}`);
273
+ entry.filters = { ...filters };
274
+ }
275
+ if (this.ws && this.ws.readyState === OPEN) {
276
+ this.ws.send(JSON.stringify({ type: "update", ...(subId === DEFAULT_SUB_ID ? {} : { sub_id: subId }), filters }));
277
+ }
278
+ return this;
279
+ }
280
+ unsubscribe(arg) {
281
+ if (typeof arg === "string") {
282
+ if (arg === DEFAULT_SUB_ID)
283
+ return this.unsubscribe(Array.from(this.desired.channels));
284
+ this.named.delete(arg);
285
+ this.forgetPending(arg);
286
+ if (this.ws && this.ws.readyState === OPEN)
287
+ this.ws.send(JSON.stringify({ type: "unsubscribe", sub_id: arg }));
288
+ return this;
289
+ }
290
+ for (const c of arg)
95
291
  this.desired.channels.delete(c);
96
292
  if (this.ws && this.ws.readyState === OPEN) {
97
- this.ws.send(JSON.stringify({ type: "unsubscribe", channels }));
293
+ this.ws.send(JSON.stringify({ type: "unsubscribe", channels: arg }));
98
294
  }
99
295
  return this;
100
296
  }
101
- /** Open the connection (also called implicitly by subscribe). */
297
+ /** Every subscription this client asks for (local view, no round trip). */
298
+ getSubscriptions() {
299
+ const out = [];
300
+ if (this.desired.channels.size > 0)
301
+ out.push({ subId: DEFAULT_SUB_ID, channels: Array.from(this.desired.channels), filters: { ...this.desired.filters } });
302
+ for (const [subId, e] of this.named)
303
+ out.push({ subId, channels: Array.from(e.channels), filters: { ...e.filters } });
304
+ return out;
305
+ }
306
+ /**
307
+ * Ask the server what this connection holds (`list` → `subscriptions`).
308
+ * Resolves with the local view when not connected or when the server does
309
+ * not answer within `timeoutMs`.
310
+ */
311
+ listSubscriptions(timeoutMs = 5000) {
312
+ if (!this.ws || this.ws.readyState !== OPEN)
313
+ return Promise.resolve(this.getSubscriptions());
314
+ return new Promise((resolve) => {
315
+ const w = { resolve, timer: setTimeout(() => { this.listWaiters = this.listWaiters.filter((x) => x !== w); resolve(this.getSubscriptions()); }, timeoutMs) };
316
+ this.listWaiters.push(w);
317
+ try {
318
+ this.ws.send(JSON.stringify({ type: "list" }));
319
+ }
320
+ catch { /* closing: the timer answers */ }
321
+ });
322
+ }
323
+ /**
324
+ * A pre-Phase-2 server (ignores sub_id) answers every resume with ONE
325
+ * replay for the whole connection, reported without sub_id: only "default"
326
+ * can still be awaited. Finishes the recovery at once when that one has
327
+ * already ended.
328
+ */
329
+ collapsePending(r) {
330
+ if (r.pending.size === 1 && r.pending.has(DEFAULT_SUB_ID))
331
+ return;
332
+ r.pending.clear();
333
+ if (!r.ends.has(DEFAULT_SUB_ID))
334
+ r.pending.add(DEFAULT_SUB_ID);
335
+ if (r.pending.size === 0 && r.protocol !== "detect")
336
+ this.finishRecovery(r.ends.get(DEFAULT_SUB_ID) ?? null);
337
+ }
338
+ /** A subscription removed while its replay was still awaited: stop waiting for it. */
339
+ forgetPending(subId) {
340
+ const r = this.recovery;
341
+ if (!r || !r.pending.has(subId))
342
+ return;
343
+ r.pending.delete(subId);
344
+ if (r.pending.size === 0 && r.protocol !== "detect")
345
+ this.finishRecovery(r.ends.size ? [...r.ends.values()].pop() : null);
346
+ }
347
+ /** Open the connection (also called implicitly by subscribe). Restarts a stream that went `"fatal"`. */
102
348
  async connect() {
103
349
  if (this.connecting || (this.ws && this.ws.readyState === OPEN))
104
350
  return;
351
+ if (this.stopped) {
352
+ this.stopped = false;
353
+ this.authFailures = 0;
354
+ this.attempt = 0;
355
+ }
105
356
  this.closedByUser = false;
106
357
  this.connecting = true;
107
358
  try {
@@ -109,29 +360,47 @@ export class MadeOnSolStream {
109
360
  resolveWebSocket(this.opts.WebSocketImpl),
110
361
  this.opts.getToken(),
111
362
  ]);
363
+ if (this.closedByUser || this.stopped)
364
+ return;
112
365
  const url = `${token.ws_url}?token=${encodeURIComponent(token.token)}`;
113
366
  const ws = new WS(url);
114
367
  this.ws = ws;
368
+ this.serverInstance = null;
369
+ this.firstSubscribeSent = false;
370
+ // The automatic re-resume budget is per CONNECTION (the docs say so).
371
+ this.resumeRetries = 0;
115
372
  ws.onopen = () => {
116
- this.attempt = 0;
373
+ if (this.ws !== ws)
374
+ return;
375
+ // The backoff attempt is NOT reset here — only a `subscribed` ack proves
376
+ // the connection is usable (an auth/limit close follows a successful open).
117
377
  this.resetHeartbeat();
118
- if (this.desired.channels.size > 0)
378
+ this.ackExpect = [];
379
+ if (this.desired.channels.size > 0 || this.named.size > 0)
119
380
  this.sendSubscribe();
120
381
  this.emit("open", undefined);
121
382
  };
122
- ws.onmessage = (ev) => this.handleMessage(ev.data);
123
- ws.onerror = (err) => this.emit("error", err instanceof Error ? err : new Error("WebSocket error"));
383
+ ws.onmessage = (ev) => { if (this.ws === ws)
384
+ this.handleMessage(ev.data); };
385
+ ws.onerror = (err) => { if (this.ws === ws)
386
+ this.emit("error", err instanceof Error ? err : new Error("WebSocket error")); };
124
387
  ws.onclose = (ev) => {
125
- this.clearHeartbeat();
126
- this.ws = null;
127
- this.emit("close", { code: ev?.code, reason: ev?.reason });
128
- if (!this.closedByUser && this.opts.autoReconnect)
129
- this.scheduleReconnect();
388
+ if (this.ws !== null && this.ws !== ws)
389
+ return; // superseded socket
390
+ this.handleClose(typeof ev?.code === "number" ? ev.code : null, typeof ev?.reason === "string" ? ev.reason : "");
130
391
  };
131
392
  }
132
393
  catch (err) {
133
394
  this.emit("error", err);
134
- if (!this.closedByUser && this.opts.autoReconnect)
395
+ if (this.authFailures > 0) {
396
+ // Token re-fetch after a 4001 failed — counts toward the bounded retries.
397
+ this.authFailures++;
398
+ if (this.authFailures > this.opts.maxAuthRetries) {
399
+ this.fatal(4001, "stream token refresh failed");
400
+ return;
401
+ }
402
+ }
403
+ if (!this.closedByUser && !this.stopped && this.opts.autoReconnect)
135
404
  this.scheduleReconnect();
136
405
  }
137
406
  finally {
@@ -146,6 +415,7 @@ export class MadeOnSolStream {
146
415
  this.reconnectTimer = null;
147
416
  }
148
417
  this.clearHeartbeat();
418
+ this.dropRecovery();
149
419
  const sock = this.ws;
150
420
  this.ws = null;
151
421
  try {
@@ -159,14 +429,430 @@ export class MadeOnSolStream {
159
429
  }
160
430
  catch { /* ignore */ }
161
431
  }
162
- sendSubscribe() {
163
- const channels = Array.from(this.desired.channels);
164
- if (channels.length === 0)
432
+ handleClose(code, reason) {
433
+ this.clearHeartbeat();
434
+ this.ws = null;
435
+ this.serverInstance = null;
436
+ // An unfinished recovery is abandoned: its held live frames are dropped
437
+ // undelivered, and replayed frames never moved the cursor, so the next
438
+ // resume starts from the same pre-resume position.
439
+ this.dropRecovery();
440
+ this.emit("close", { code, reason });
441
+ if (this.closedByUser || this.stopped)
442
+ return;
443
+ if (code === 4003) {
444
+ this.fatal(code, reason || "authentication error");
445
+ return;
446
+ }
447
+ if (code === 4001) {
448
+ // Token rejected (rotated / lapsed): the reconnect re-fetches it via getToken().
449
+ this.authFailures++;
450
+ if (this.authFailures > this.opts.maxAuthRetries) {
451
+ this.fatal(code, reason || "stream token rejected");
452
+ return;
453
+ }
454
+ }
455
+ if (!this.opts.autoReconnect)
456
+ return;
457
+ if (code === 4002) {
458
+ // Connection limit: another socket holds the slot. Never retry tightly.
459
+ const err = new Error(`stream connection limit reached${reason ? `: ${reason}` : ""}`);
460
+ err.code = 4002;
461
+ err.reason = reason;
462
+ this.emit("error", err);
463
+ this.scheduleReconnect(code, this.opts.connectionLimitBackoffMs);
464
+ return;
465
+ }
466
+ // 4008 (slow consumer) and everything else: reconnect and resume from the cursor.
467
+ this.scheduleReconnect(code);
468
+ }
469
+ /** `onUnrecoverableGap: "stop"`: stop the stream and hand the decision to the caller. */
470
+ haltForGap(gap) {
471
+ this.closedByUser = true; // no reconnect; connect() restarts if the caller wants
472
+ if (this.retryTimer) {
473
+ clearTimeout(this.retryTimer);
474
+ this.retryTimer = null;
475
+ }
476
+ this.clearHeartbeat();
477
+ const sock = this.ws;
478
+ this.ws = null;
479
+ try {
480
+ if (typeof sock?.terminate === "function")
481
+ sock.terminate();
482
+ else
483
+ sock?.close(1000, "unrecoverable gap");
484
+ }
485
+ catch { /* ignore */ }
486
+ this.stopped = true;
487
+ this.emit("fatal", { code: null, reason: `unrecoverable gap: ${gap.reason}`, gap });
488
+ }
489
+ fatal(code, reason) {
490
+ this.stopped = true;
491
+ if (this.reconnectTimer) {
492
+ clearTimeout(this.reconnectTimer);
493
+ this.reconnectTimer = null;
494
+ }
495
+ this.emit("fatal", { code, reason });
496
+ }
497
+ /** The subscribe frames for the given subscriptions (default first, then named in creation order). */
498
+ subscribeFrames(only) {
499
+ const out = [];
500
+ const want = (id) => !only || only.includes(id);
501
+ if (want(DEFAULT_SUB_ID) && this.desired.channels.size > 0) {
502
+ const msg = { type: "subscribe", channels: Array.from(this.desired.channels) };
503
+ if (Object.keys(this.desired.filters).length > 0)
504
+ msg.filters = this.desired.filters;
505
+ out.push({ subId: DEFAULT_SUB_ID, msg });
506
+ }
507
+ for (const [subId, e] of this.named) {
508
+ if (!want(subId) || e.channels.size === 0)
509
+ continue;
510
+ out.push({ subId, msg: { type: "subscribe", sub_id: subId, channels: Array.from(e.channels), filters: e.filters } });
511
+ }
512
+ return out;
513
+ }
514
+ /**
515
+ * Send the subscribe(s). On a connection's FIRST subscribe (or an explicit
516
+ * retry after a retryable gap) every subscription is sent with the SAME
517
+ * resume cursor: the server serves one replay per subscription, one after
518
+ * another, and holds live frames until the last replay_end. A later
519
+ * subscribe adds channels live (no resume).
520
+ */
521
+ sendSubscribe({ resumeOverride, only } = {}) {
522
+ if (!this.ws)
523
+ return;
524
+ const frames = this.subscribeFrames(only);
525
+ if (frames.length === 0)
526
+ return;
527
+ if ((!this.firstSubscribeSent || resumeOverride) && this.cursor && !this.recovery) {
528
+ const from = resumeOverride ?? { ...this.cursor };
529
+ const pending = new Set();
530
+ const channels = new Set();
531
+ for (const f of frames) {
532
+ f.msg.resume = from;
533
+ pending.add(f.subId);
534
+ for (const c of f.msg.channels)
535
+ channels.add(c);
536
+ }
537
+ this.recovery = {
538
+ protocol: "detect", from, channels: Array.from(channels), request: { resume: from }, acked: false, suppressAck: false,
539
+ instanceChanged: false, start: null, received: 0, delivered: 0, duplicates: 0, held: [], timer: null,
540
+ maxSeq: null, maxTs: null, pending, starts: new Map(), ends: new Map(),
541
+ };
542
+ }
543
+ this.firstSubscribeSent = true;
544
+ for (const f of frames) {
545
+ this.ackExpect.push(f.subId);
546
+ this.ws.send(JSON.stringify(f.msg));
547
+ }
548
+ }
549
+ /**
550
+ * The server did not answer `resume` (older deployment): retry with the
551
+ * legacy fields. Such a server has no named subscriptions either, so the
552
+ * one legacy replay covers the union of channels and resolves every pending
553
+ * subscription at once.
554
+ */
555
+ fallbackToLegacy() {
556
+ const r = this.recovery;
557
+ if (!r || r.protocol !== "detect" || !r.from || !this.ws)
165
558
  return;
166
- const msg = { type: "subscribe", channels };
559
+ if (r.timer) {
560
+ clearTimeout(r.timer);
561
+ r.timer = null;
562
+ }
563
+ r.protocol = "legacy";
564
+ r.pending = new Set([DEFAULT_SUB_ID]);
565
+ r.instanceChanged = !this.serverInstance || this.serverInstance !== r.from.instance;
566
+ // Same process → its ring still indexes our seq. Restarted → seq restarted, use time.
567
+ const legacy = r.instanceChanged ? { replay_since_ts: r.from.ts } : { replay_since_seq: r.from.seq };
568
+ r.request = legacy;
569
+ r.suppressAck = true;
570
+ const msg = { type: "subscribe", channels: r.channels, ...legacy };
167
571
  if (Object.keys(this.desired.filters).length > 0)
168
572
  msg.filters = this.desired.filters;
169
- this.ws?.send(JSON.stringify(msg));
573
+ try {
574
+ this.ws.send(JSON.stringify(msg));
575
+ }
576
+ catch { /* closing */ }
577
+ r.timer = setTimeout(() => this.finishRecovery(null), this.opts.legacyReplayTimeoutMs);
578
+ }
579
+ dropRecovery() {
580
+ if (this.recovery?.timer)
581
+ clearTimeout(this.recovery.timer);
582
+ this.recovery = null;
583
+ if (this.retryTimer) {
584
+ clearTimeout(this.retryTimer);
585
+ this.retryTimer = null;
586
+ }
587
+ // A `list` still awaiting its answer resolves with the local view; the
588
+ // ack order of the dead connection means nothing on the next one.
589
+ this.ackExpect = [];
590
+ const waiters = this.listWaiters;
591
+ this.listWaiters = [];
592
+ for (const w of waiters) {
593
+ clearTimeout(w.timer);
594
+ w.resolve(this.getSubscriptions());
595
+ }
596
+ }
597
+ /**
598
+ * A retryable gap: ask the server again on this connection after its
599
+ * retry_after_ms (row_cap resumes from resume_ts_hint). Bounded — the next
600
+ * reconnect resumes anyway.
601
+ */
602
+ scheduleResumeRetry(retryAfterMs, hintTs, only) {
603
+ if (this.retryTimer || !this.cursor)
604
+ return;
605
+ if (this.resumeRetries >= this.opts.maxResumeRetries)
606
+ return;
607
+ this.resumeRetries++;
608
+ const delay = retryAfterMs !== null && retryAfterMs >= 0 ? retryAfterMs : this.opts.resumeRetryDelayMs;
609
+ const from = hintTs !== null && hintTs > this.cursor.ts ? { ...this.cursor, ts: hintTs } : { ...this.cursor };
610
+ this.retryTimer = setTimeout(() => {
611
+ this.retryTimer = null;
612
+ // Only the subscriptions whose replay was incomplete are asked again.
613
+ if (this.ws && this.ws.readyState === OPEN && !this.recovery)
614
+ this.sendSubscribe({ resumeOverride: from, only });
615
+ }, delay);
616
+ }
617
+ /**
618
+ * One `replay_end` per subscription → one aggregate the single-replay logic
619
+ * can run on unchanged: complete only when every subscription is; the
620
+ * commit position is the SMALLEST last_seq / last_ts across them (a later
621
+ * subscription's replay covered more, but the earlier one's live frames
622
+ * from that point on are still only in the live flush); channel entries
623
+ * keyed `"<sub_id>/<channel>"` for named subscriptions; `retryable` when
624
+ * any subscription says so.
625
+ */
626
+ aggregateEnds(r, lastEnd) {
627
+ const ends = [...r.ends.entries()];
628
+ if (ends.length === 0)
629
+ return lastEnd;
630
+ if (ends.length === 1 && ends[0][0] === DEFAULT_SUB_ID)
631
+ return ends[0][1];
632
+ const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : null);
633
+ const agg = { ...(lastEnd ?? ends[ends.length - 1][1]) };
634
+ const channels = {};
635
+ let complete = true, retryableKnown = true, retryable = false, truncated = false;
636
+ let lastSeq = null, lastTs = null, liveFrom = null, retryAfter = null, hint = null;
637
+ let count = 0, sent = 0, matched = 0, reason = null, limits = null;
638
+ const min = (a, b) => (a === null ? b : b === null ? a : Math.min(a, b));
639
+ for (const [subId, e] of ends) {
640
+ if (e.complete === false) {
641
+ complete = false;
642
+ if (!reason && typeof e.reason === "string")
643
+ reason = e.reason;
644
+ }
645
+ if (typeof e.retryable !== "boolean")
646
+ retryableKnown = false;
647
+ else if (e.retryable)
648
+ retryable = true;
649
+ if (e.replay_truncated === true)
650
+ truncated = true;
651
+ const chs = e.channels;
652
+ if (chs && typeof chs === "object")
653
+ for (const [ch, raw] of Object.entries(chs))
654
+ channels[subId === DEFAULT_SUB_ID ? ch : `${subId}/${ch}`] = raw;
655
+ lastSeq = min(lastSeq, num(e.last_seq));
656
+ lastTs = min(lastTs, num(e.last_ts));
657
+ liveFrom = min(liveFrom, num(e.live_from_seq));
658
+ const ra = num(e.retry_after_ms);
659
+ if (ra !== null)
660
+ retryAfter = retryAfter === null ? ra : Math.max(retryAfter, ra);
661
+ hint = min(hint, num(e.resume_ts_hint));
662
+ count += num(e.count) ?? 0;
663
+ sent += num(e.sent) ?? 0;
664
+ matched += num(e.matched) ?? 0;
665
+ if (!limits && e.limits && typeof e.limits === "object")
666
+ limits = e.limits;
667
+ }
668
+ agg.complete = complete;
669
+ agg.reason = complete ? null : reason ?? "incomplete";
670
+ agg.channels = channels;
671
+ if (retryableKnown)
672
+ agg.retryable = retryable;
673
+ else
674
+ delete agg.retryable;
675
+ if (truncated)
676
+ agg.replay_truncated = true;
677
+ agg.last_seq = lastSeq;
678
+ agg.last_ts = lastTs;
679
+ agg.live_from_seq = liveFrom;
680
+ if (retryAfter !== null)
681
+ agg.retry_after_ms = retryAfter;
682
+ else
683
+ delete agg.retry_after_ms;
684
+ if (hint !== null)
685
+ agg.resume_ts_hint = hint;
686
+ else
687
+ delete agg.resume_ts_hint;
688
+ agg.count = count;
689
+ agg.sent = sent;
690
+ agg.matched = matched;
691
+ if (limits)
692
+ agg.limits = limits;
693
+ return agg;
694
+ }
695
+ finishRecovery(lastEnd) {
696
+ const r = this.recovery;
697
+ if (!r)
698
+ return;
699
+ if (r.timer) {
700
+ clearTimeout(r.timer);
701
+ r.timer = null;
702
+ }
703
+ this.recovery = null;
704
+ const end = this.aggregateEnds(r, lastEnd);
705
+ // Subscriptions whose own replay_end was incomplete and retryable (or, on a
706
+ // server that does not say, incomplete): the automatic retry asks only for them.
707
+ const retrySubs = [...r.ends.entries()].filter(([, e]) => e.complete === false && e.retryable !== false).map(([id]) => id);
708
+ const reasons = [];
709
+ /** Reasons of the channels the server reported incomplete, with their retryability. */
710
+ const channelReasons = [];
711
+ const retryableChannelReasons = [];
712
+ const gapChannels = {};
713
+ const str = (v) => (typeof v === "string" && v ? v : null);
714
+ const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : null);
715
+ // A v1 server answers with complete/sent/matched; an older one with count only.
716
+ const v1 = !!end && ("complete" in end || "sent" in end || "matched" in end);
717
+ if ([...r.starts.values()].some((s) => s.replay_truncated === true) || r.start?.replay_truncated === true || end?.replay_truncated === true)
718
+ reasons.push("ring_truncated");
719
+ if (!end)
720
+ reasons.push("replay_timeout");
721
+ else if (v1) {
722
+ if (end.complete === false)
723
+ reasons.push(str(end.reason) ?? "incomplete");
724
+ const chs = end.channels;
725
+ if (chs && typeof chs === "object") {
726
+ for (const [ch, raw] of Object.entries(chs)) {
727
+ // token:prices is a state stream: the server re-sends a snapshot, never a log.
728
+ if (ch === "token:prices")
729
+ continue;
730
+ const info = (raw && typeof raw === "object" ? raw : {});
731
+ const gap = info.gap;
732
+ const late = info.late_ingest_possible === true;
733
+ if (info.complete === false || gap || info.mode === "none" || late) {
734
+ gapChannels[ch] = raw; // raw entry: mode, reason, gap, time_basis, retry_after_ms, …
735
+ const gr = gap && typeof gap === "object" ? gap.reason : gap;
736
+ const chReason = str(info.reason) ?? str(gr) ?? (info.mode === "none" ? "not_reconstructable" : late ? "late_ingest_possible" : "incomplete");
737
+ reasons.push(chReason);
738
+ channelReasons.push(chReason);
739
+ if (info.retryable === true || (info.retryable !== false && TRANSIENT_GAPS.has(chReason)))
740
+ retryableChannelReasons.push(chReason);
741
+ }
742
+ }
743
+ }
744
+ }
745
+ else {
746
+ // Legacy server: `count` is what it meant to send; fewer arrived → it stopped on backpressure.
747
+ if (typeof end.count === "number" && r.received < end.count)
748
+ reasons.push("backpressure");
749
+ // Legacy server + restart: the old process's buffer is gone and there is no durable backfill.
750
+ if (r.protocol === "legacy" && r.instanceChanged)
751
+ reasons.push("instance_changed");
752
+ }
753
+ const uniq = Array.from(new Set(reasons));
754
+ const result = {
755
+ protocol: v1 || r.protocol === "resume" ? "resume" : "legacy",
756
+ from: r.from,
757
+ request: r.request,
758
+ received: r.received,
759
+ delivered: r.delivered,
760
+ duplicates: r.duplicates,
761
+ complete: uniq.length === 0,
762
+ mode: typeof end?.mode === "string" ? end.mode : null,
763
+ resumeReason: typeof end?.resume_reason === "string" ? end.resume_reason : null,
764
+ start: r.start,
765
+ end,
766
+ subscriptions: r.ends.size ? [...r.ends.keys()] : r.pending.size ? [...r.pending] : [DEFAULT_SUB_ID],
767
+ ends: Object.fromEntries(r.ends),
768
+ };
769
+ // Final vs retryable. The server says which (`retryable`): true only when an
770
+ // incomplete channel's reason is transient (backpressure, closed,
771
+ // source_busy, source_error, late_ingest_possible, row_cap). Older servers
772
+ // send no `retryable`; then the reason list decides (isPermanentGap).
773
+ const serverSays = !!end && typeof end.retryable === "boolean";
774
+ const retryable = uniq.length > 0 && (serverSays ? end.retryable === true : !uniq.every(isPermanentGap));
775
+ const permanent = uniq.length > 0 && !retryable;
776
+ // Commit point: complete, or only FINAL gaps (reported once, then treated as
777
+ // complete so the stream never stays stuck on something asking again cannot
778
+ // fill). Retryable: keep the pre-resume cursor, do not commit live frames,
779
+ // and resume again after retry_after_ms (row_cap: from resume_ts_hint).
780
+ // The position the server says is safe to continue from.
781
+ let pos = null;
782
+ if (!retryable) {
783
+ let seq;
784
+ let cts;
785
+ if (v1) {
786
+ // {seq: last_seq ?? previous, ts: last_ts ?? previous}
787
+ seq = num(end?.last_seq);
788
+ cts = num(end?.last_ts) ?? (seq !== null ? this.cursor?.ts ?? null : null);
789
+ }
790
+ else {
791
+ // Older servers: held live frames (not yet handled) may sit below live_from_seq.
792
+ const liveFrom = num(end?.live_from_seq);
793
+ const heldMin = r.held.reduce((m, f) => (typeof f.seq === "number" ? (m === null ? f.seq : Math.min(m, f.seq)) : m), null);
794
+ seq = r.maxSeq ?? (heldMin !== null ? heldMin - 1 : liveFrom !== null ? liveFrom - 1 : null);
795
+ cts = r.maxTs ?? this.cursor?.ts ?? null;
796
+ }
797
+ if (cts !== null)
798
+ pos = { instance: this.serverInstance, seq: seq !== null && seq >= 0 ? seq : null, ts: cts };
799
+ }
800
+ // Continuing past a FINAL gap is the SDK's own decision, never the user's
801
+ // approval: it is reported on the gap event (advancedPastGap / skipped) and
802
+ // `onUnrecoverableGap: "stop"` turns it off.
803
+ // resume_ts_hint is a row_cap device: it says "everything up to here was
804
+ // sent for the capped channel". If another channel is incomplete for a
805
+ // RETRYABLE reason (source_error, source_busy, …), resuming from the hint
806
+ // would step past its unread range and the next reply would claim complete.
807
+ // Channels with a FINAL gap are ignored here: asking again never recovers
808
+ // them anyway, and the gap event reports them. Same predicate as the
809
+ // server, checked here so the client never depends on it.
810
+ const capCandidates = retryableChannelReasons.length > 0
811
+ ? retryableChannelReasons
812
+ : channelReasons.length > 0 ? [] : uniq.filter((x) => TRANSIENT_GAPS.has(x));
813
+ const capOnly = capCandidates.length > 0 && capCandidates.every((x) => x === "row_cap");
814
+ const exhausted = retryable && this.resumeRetries >= this.opts.maxResumeRetries;
815
+ const strict = uniq.length > 0 && !retryable && this.opts.onUnrecoverableGap === "stop";
816
+ const willAdvance = !retryable && !strict;
817
+ this.emit("replay", result);
818
+ let gap = null;
819
+ if (uniq.length > 0) {
820
+ gap = {
821
+ reason: uniq[0], reasons: uniq, permanent, retryable,
822
+ retryAfterMs: num(end?.retry_after_ms), resumeTsHint: num(end?.resume_ts_hint),
823
+ channels: gapChannels, from: r.from, replay: result, exhausted,
824
+ limits: (end?.limits && typeof end.limits === "object" ? end.limits : r.start?.limits && typeof r.start.limits === "object" ? r.start.limits : null),
825
+ // What the client does about it — always reported BEFORE it happens.
826
+ advancedPastGap: willAdvance,
827
+ source: "auto",
828
+ skipped: {
829
+ channels: Object.keys(gapChannels),
830
+ from: this.cursor ? { ...this.cursor } : null,
831
+ to: willAdvance && pos ? stepCursor(this.cursor, pos) : null,
832
+ },
833
+ };
834
+ this.lastGap = gap;
835
+ this.emit("gap", gap);
836
+ }
837
+ if (willAdvance) {
838
+ this.unsafe = false;
839
+ this.resumeRetries = 0;
840
+ if (pos)
841
+ this.enqueue(pos, true);
842
+ }
843
+ else if (retryable) {
844
+ this.unsafe = true;
845
+ if (serverSays)
846
+ this.scheduleResumeRetry(num(end?.retry_after_ms), capOnly ? num(end?.resume_ts_hint) : null, retrySubs.length ? retrySubs : undefined);
847
+ }
848
+ else {
849
+ // strict: stop instead of skipping what cannot be recovered.
850
+ this.unsafe = true;
851
+ this.haltForGap(gap);
852
+ }
853
+ // Live frames that arrived during a client-side replay go out now, after it.
854
+ for (const f of r.held)
855
+ this.deliver(f);
170
856
  }
171
857
  handleMessage(raw) {
172
858
  let msg;
@@ -178,31 +864,292 @@ export class MadeOnSolStream {
178
864
  this.emit("error", new Error("Failed to parse stream message"));
179
865
  return;
180
866
  }
181
- if (msg.type === "heartbeat") {
182
- this.resetHeartbeat();
183
- this.emit("heartbeat", msg.ts);
867
+ switch (msg.type) {
868
+ case "heartbeat":
869
+ this.resetHeartbeat();
870
+ this.emit("heartbeat", msg.ts);
871
+ return;
872
+ case "connected":
873
+ if (typeof msg.instance === "string")
874
+ this.serverInstance = msg.instance;
875
+ // Nothing to subscribe to → this frame is as far as a healthy connection gets.
876
+ if (this.desired.channels.size === 0 && this.named.size === 0) {
877
+ this.attempt = 0;
878
+ this.authFailures = 0;
879
+ }
880
+ return;
881
+ case "subscribed": {
882
+ if (typeof msg.instance === "string")
883
+ this.serverInstance = msg.instance;
884
+ this.attempt = 0;
885
+ this.authFailures = 0;
886
+ const r = this.recovery;
887
+ if (r && r.suppressAck) {
888
+ r.suppressAck = false;
889
+ return;
890
+ } // ack of our own fallback subscribe
891
+ // Acks arrive in the order the subscribes were sent: a named subscribe
892
+ // answered WITHOUT sub_id means the server ignores sub_id (older
893
+ // deployment) — every subscription then collapsed into one on the
894
+ // server. Said once, never silently.
895
+ const expected = this.ackExpect.shift() ?? DEFAULT_SUB_ID;
896
+ // The subscription this ack is about: the server's sub_id, else the
897
+ // one we sent in this position (an older server echoes none).
898
+ const ackedId = typeof msg.sub_id === "string" && msg.sub_id ? msg.sub_id : expected;
899
+ if (expected !== DEFAULT_SUB_ID && typeof msg.sub_id !== "string") {
900
+ if (!this.namedUnsupportedWarned) {
901
+ this.namedUnsupportedWarned = true;
902
+ this.emit("warning", { code: "named_subscriptions_unsupported", sub_id: expected, message: "The server ignored sub_id: it predates named subscriptions, so every subscription on this connection shares one channel set and one filter object." });
903
+ }
904
+ // Such a server runs ONE replay for the whole connection and reports
905
+ // it without sub_id ("default"): every named id must leave `pending`
906
+ // or the recovery would never finish and the cursor would freeze.
907
+ if (r)
908
+ this.collapsePending(r);
909
+ }
910
+ this.emit("subscribed", msg.channels, msg);
911
+ if (r && r.protocol === "detect" && !r.acked) {
912
+ r.acked = true;
913
+ if ("resume" in msg)
914
+ r.protocol = "resume"; // server echoed resume: it understood
915
+ else
916
+ r.timer = setTimeout(() => this.fallbackToLegacy(), this.opts.resumeDetectMs);
917
+ }
918
+ const echo = msg.resume;
919
+ if (r && echo && typeof echo === "object" && echo.accepted === false) {
920
+ // Refused for THIS subscription (replay_in_progress: it already has a
921
+ // replay running or queued): no replay_end will come for it. When
922
+ // nothing at all was accepted, nothing was recovered, so the
923
+ // committed cursor must not move until a later recovery completes.
924
+ r.pending.delete(ackedId);
925
+ if (r.pending.size === 0 && r.ends.size === 0) {
926
+ this.dropRecovery();
927
+ this.unsafe = true;
928
+ }
929
+ else if (r.pending.size === 0 && r.protocol !== "detect")
930
+ this.finishRecovery([...r.ends.values()].pop() ?? null);
931
+ }
932
+ return;
933
+ }
934
+ case "replay_start": {
935
+ let r = this.recovery;
936
+ if (!r) {
937
+ // A replay we did not ask for in this state (e.g. a late answer) — track it anyway.
938
+ r = this.recovery = {
939
+ protocol: "resume", from: null, channels: [], request: {}, acked: true, suppressAck: false,
940
+ instanceChanged: false, start: null, received: 0, delivered: 0, duplicates: 0, held: [], timer: null,
941
+ maxSeq: null, maxTs: null, pending: new Set([subIdOf(msg)]), starts: new Map(), ends: new Map(),
942
+ };
943
+ }
944
+ if (r.protocol === "detect") {
945
+ r.protocol = "resume";
946
+ if (r.timer) {
947
+ clearTimeout(r.timer);
948
+ r.timer = null;
949
+ }
950
+ }
951
+ r.starts.set(subIdOf(msg), msg);
952
+ if (!r.start)
953
+ r.start = msg;
954
+ return;
955
+ }
956
+ case "replay_end": {
957
+ const r = this.recovery;
958
+ if (!r)
959
+ return;
960
+ const sid = subIdOf(msg);
961
+ r.ends.set(sid, msg);
962
+ r.pending.delete(sid);
963
+ // Every subscription's replay has ended (a legacy server answers once,
964
+ // for the whole connection) → aggregate and commit.
965
+ if (r.pending.size === 0 || r.protocol === "legacy")
966
+ this.finishRecovery(msg);
967
+ return;
968
+ }
969
+ case "updated":
970
+ this.emit("updated", msg);
971
+ return;
972
+ case "unsubscribed":
973
+ this.emit("unsubscribed", msg);
974
+ return;
975
+ case "subscriptions": {
976
+ const list = Array.isArray(msg.list)
977
+ ? msg.list.map((s) => ({
978
+ subId: typeof s.sub_id === "string" ? s.sub_id : DEFAULT_SUB_ID,
979
+ channels: (Array.isArray(s.channels) ? s.channels : []),
980
+ filters: (s.filters && typeof s.filters === "object" ? s.filters : {}),
981
+ }))
982
+ : [];
983
+ const waiters = this.listWaiters;
984
+ this.listWaiters = [];
985
+ for (const w of waiters) {
986
+ clearTimeout(w.timer);
987
+ w.resolve(list);
988
+ }
989
+ return;
990
+ }
991
+ case "warning": {
992
+ const sid = typeof msg.sub_id === "string" ? msg.sub_id : null;
993
+ if (msg.code === "channels_revoked") {
994
+ // The server dropped these (e.g. plan downgrade): stop re-subscribing them.
995
+ const names = new Set();
996
+ if (Array.isArray(msg.channels))
997
+ for (const c of msg.channels)
998
+ if (typeof c === "string")
999
+ names.add(c);
1000
+ if (Array.isArray(msg.revoked)) {
1001
+ for (const x of msg.revoked) {
1002
+ if (typeof x === "string")
1003
+ names.add(x);
1004
+ else if (x && typeof x === "object" && typeof x.channel === "string")
1005
+ names.add(x.channel);
1006
+ }
1007
+ }
1008
+ const target = sid && sid !== DEFAULT_SUB_ID ? this.named.get(sid)?.channels : this.desired.channels;
1009
+ if (target)
1010
+ for (const c of names)
1011
+ target.delete(c);
1012
+ if (sid && sid !== DEFAULT_SUB_ID && this.named.get(sid)?.channels.size === 0)
1013
+ this.named.delete(sid);
1014
+ }
1015
+ else if ((msg.code === "too_many_subscriptions" || msg.code === "invalid_sub_id") && sid && sid !== DEFAULT_SUB_ID) {
1016
+ // The server will refuse it on every reconnect too: forget it, and do not wait for its replay.
1017
+ this.named.delete(sid);
1018
+ this.forgetPending(sid);
1019
+ }
1020
+ // Never swallow a server warning: a rejected/revoked channel is silent.
1021
+ this.emit("warning", msg);
1022
+ return;
1023
+ }
1024
+ default:
1025
+ break;
1026
+ }
1027
+ if (!msg.channel || !msg.event)
184
1028
  return;
1029
+ // Bus-recovered frames (recovered:"bus") are re-sent live, not part of a replay.
1030
+ const inReplay = msg.replayed === true && msg.recovered !== "bus";
1031
+ const r = this.recovery;
1032
+ if (r) {
1033
+ if (!inReplay && r.protocol === "detect" && r.acked)
1034
+ this.fallbackToLegacy(); // live before replay_start → old server
1035
+ if (!inReplay && r.protocol === "legacy") {
1036
+ if (r.held.length < HELD_LIVE_CAP) {
1037
+ r.held.push(msg);
1038
+ return;
1039
+ }
1040
+ // Too much live traffic to hold: stop holding, deliver in arrival order.
1041
+ const held = r.held;
1042
+ r.held = [];
1043
+ for (const f of held)
1044
+ this.deliver(f);
1045
+ }
1046
+ if (inReplay)
1047
+ r.received++;
1048
+ }
1049
+ this.deliver(msg);
1050
+ }
1051
+ /** Dedupe by id, hand the frame to the handlers, track completion for the cursor. */
1052
+ deliver(msg) {
1053
+ const inReplay = msg.replayed === true && msg.recovered !== "bus";
1054
+ if (inReplay && this.recovery) {
1055
+ const r = this.recovery;
1056
+ if (typeof msg.seq === "number" && Number.isFinite(msg.seq))
1057
+ r.maxSeq = Math.max(r.maxSeq ?? msg.seq, msg.seq);
1058
+ if (typeof msg.ts === "number" && Number.isFinite(msg.ts))
1059
+ r.maxTs = Math.max(r.maxTs ?? msg.ts, msg.ts);
185
1060
  }
186
- if (msg.type === "connected") {
1061
+ const id = typeof msg.id === "string" || typeof msg.id === "number" ? String(msg.id) : null;
1062
+ if (id !== null && this.opts.dedupeSize > 0) {
1063
+ // Dedupe is per (sub_id, channel, id): the same event delivered under two
1064
+ // named subscriptions is two legitimate deliveries.
1065
+ const key = `${subIdOf(msg)}\u0000${String(msg.channel)}\u0000${id}`;
1066
+ if (this.seen.has(key)) {
1067
+ this.seen.delete(key);
1068
+ this.seen.set(key, true);
1069
+ if (inReplay && this.recovery)
1070
+ this.recovery.duplicates++;
1071
+ return;
1072
+ }
1073
+ this.seen.set(key, true);
1074
+ if (this.seen.size > this.opts.dedupeSize) {
1075
+ const oldest = this.seen.keys().next().value;
1076
+ if (oldest !== undefined)
1077
+ this.seen.delete(oldest);
1078
+ }
1079
+ }
1080
+ if (inReplay && this.recovery)
1081
+ this.recovery.delivered++;
1082
+ const data = msg.data;
1083
+ const evt = { ...msg, replayed: msg.replayed === true || (!!data && typeof data === "object" && data.replayed === true) };
1084
+ const seq = typeof msg.seq === "number" && Number.isFinite(msg.seq) ? msg.seq : null;
1085
+ const ts = typeof msg.ts === "number" && Number.isFinite(msg.ts) ? msg.ts : null;
1086
+ // Only sequenced/identified frames move the cursor (token:price ticks are
1087
+ // state, not a log) — and none while a recovery runs: finishRecovery()
1088
+ // commits the server's replay_end position if, and only if, it is complete.
1089
+ const pos = (seq !== null || id !== null) && ts !== null ? { instance: this.serverInstance, seq, ts } : null;
1090
+ // Progress always moves; the COMMITTED cursor only for live frames outside
1091
+ // a recovery and not after an incomplete one (see finishRecovery).
1092
+ const commit = !this.recovery && !this.unsafe;
1093
+ const results = [];
1094
+ this.callHandlers(evt.event, evt.data, evt, results);
1095
+ this.callHandlers("*", evt.data, evt, results);
1096
+ const pending = results.filter(isThenable);
1097
+ if (pending.length === 0 && this.inflight.length === 0) {
1098
+ if (pos)
1099
+ this.apply(pos, commit);
187
1100
  return;
188
1101
  }
189
- if (msg.type === "subscribed") {
190
- this.emit("subscribed", msg.channels);
1102
+ const entry = { pos, commit, done: pending.length === 0 };
1103
+ this.inflight.push(entry);
1104
+ if (entry.done) {
1105
+ this.drainInflight();
191
1106
  return;
192
1107
  }
193
- if (msg.channel && msg.event) {
194
- const evt = msg;
195
- this.emit(evt.event, evt.data, evt);
196
- this.emit("*", evt.data, evt);
1108
+ void Promise.allSettled(pending).then((settled) => {
1109
+ for (const s of settled)
1110
+ if (s.status === "rejected")
1111
+ this.emit("error", s.reason);
1112
+ entry.done = true;
1113
+ this.drainInflight();
1114
+ });
1115
+ }
1116
+ drainInflight() {
1117
+ while (this.inflight.length > 0 && this.inflight[0].done) {
1118
+ const e = this.inflight.shift();
1119
+ if (e.pos)
1120
+ this.apply(e.pos, e.commit);
197
1121
  }
198
1122
  }
199
- scheduleReconnect() {
200
- if (this.reconnectTimer)
1123
+ /** Queue a position behind every frame still being handled (or apply it now). */
1124
+ enqueue(pos, commit) {
1125
+ if (this.inflight.length === 0)
1126
+ this.apply(pos, commit);
1127
+ else
1128
+ this.inflight.push({ pos, commit, done: true });
1129
+ }
1130
+ /** Move `progress` (always) and the committed cursor (when `commit`) to `pos`. */
1131
+ apply(pos, commit) {
1132
+ const p = stepCursor(this.progress, pos);
1133
+ if (p)
1134
+ this.progress = p;
1135
+ if (!commit)
1136
+ return;
1137
+ const c = this.cursor;
1138
+ const next = stepCursor(c, pos);
1139
+ if (!next || (c && c.instance === next.instance && c.seq === next.seq && c.ts === next.ts))
1140
+ return;
1141
+ this.cursor = next;
1142
+ this.emit("cursor", { ...next });
1143
+ }
1144
+ scheduleReconnect(code = null, minDelayMs = 0) {
1145
+ if (this.reconnectTimer || this.stopped)
201
1146
  return;
202
1147
  const base = Math.min(1000 * 2 ** this.attempt, this.opts.maxBackoffMs);
203
- const delay = base / 2 + Math.floor((base / 2) * Math.random());
1148
+ let delay = base / 2 + Math.floor((base / 2) * Math.random()); // jitter
1149
+ if (minDelayMs > 0)
1150
+ delay = Math.max(delay, minDelayMs + Math.floor((minDelayMs / 2) * Math.random()));
204
1151
  this.attempt++;
205
- this.emit("reconnect", { attempt: this.attempt, delayMs: delay });
1152
+ this.emit("reconnect", { attempt: this.attempt, delayMs: delay, code });
206
1153
  this.reconnectTimer = setTimeout(() => {
207
1154
  this.reconnectTimer = null;
208
1155
  void this.connect();
@@ -211,6 +1158,7 @@ export class MadeOnSolStream {
211
1158
  resetHeartbeat() {
212
1159
  this.clearHeartbeat();
213
1160
  this.hbTimer = setTimeout(() => {
1161
+ // Server went quiet — force a reconnect.
214
1162
  try {
215
1163
  this.ws?.close(4000, "heartbeat timeout");
216
1164
  }