popsub 0.0.0-stage → 0.2.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/engine.js ADDED
@@ -0,0 +1,1306 @@
1
+ /**
2
+ * The engine behind a `Client`: it owns the WebSocket and does what every
3
+ * application would otherwise have to.
4
+ *
5
+ * It connects, logs in and authenticates, then serves the connection until
6
+ * it ends. The close code decides what happens next: reconnect with
7
+ * jittered backoff, or stop for good (`session_taken_over`,
8
+ * `unsupported_protocol`, `auth_failed`, `account_disabled`, rejected
9
+ * credentials, and `token_expired` with token credentials). After
10
+ * reconnecting it resubscribes every topic from the next `seq` it expects
11
+ * (a topic the server lists as resumed for a durable session is instead
12
+ * subscribed again from `resume` when the server holds the session's
13
+ * topics, and otherwise left to the server unless a claim on it is still
14
+ * unanswered; see below), resends confirmed publishes that never got their `published` under the
15
+ * same request id and `message_id`, and sends QoS 0 publishes and
16
+ * unsubscribes queued while disconnected.
17
+ *
18
+ * Every message is checked against the next `seq` its topic expects, so a
19
+ * retry or a replay never reaches the application twice. A duplicate the
20
+ * application acknowledged before (or any duplicate in automatic mode,
21
+ * unless its acknowledgement is held back for a full buffer) is
22
+ * acknowledged again, so a lost acknowledgement can't stall the topic.
23
+ *
24
+ * A durable session outlives the process. When a new process connects
25
+ * with the same session id, the server lists the session's topics in
26
+ * `authenticated.resumed` before the application has subscribed to
27
+ * anything. The engine must never acknowledge a message the application
28
+ * couldn't have received, so with a session id its `auth` carries
29
+ * `hold_resumed: true`. A server that honours it answers `held: true` and
30
+ * sends nothing on a resumed topic until the engine subscribes to it. Then
31
+ * nothing is unclaimed, a subscribe to a resumed topic is an ordinary
32
+ * subscribe, a pattern needs no subscribes by name, and after a reconnect
33
+ * the engine subscribes again to every tracked topic the server lists as
34
+ * resumed, with `from: "resume"`, because the server no longer does it.
35
+ *
36
+ * A server that doesn't know `hold_resumed` answers without `held` and
37
+ * sends what it kept for the resumed topics at once. A resumed topic the engine
38
+ * isn't tracking is unclaimed: its messages are dropped without an
39
+ * acknowledgement, so the server keeps them for the session. Subscribing
40
+ * to an unclaimed topic by name, or to a pattern that matches it, claims
41
+ * it. A claimed topic is tracked, but its messages are still dropped
42
+ * unacknowledged until the `subscribed` that answers the claim arrives,
43
+ * because the subscribe replays them in order from `replay_from`. A
44
+ * pattern claims a topic by sending one more `subscribe` for it by name
45
+ * with `from: "resume"`, since the server skips topics the connection
46
+ * holds when it handles the pattern itself. After a reconnect a claim
47
+ * still unanswered is sent again even when the server lists the topic as
48
+ * resumed. A topic the application never subscribes to stays unclaimed.
49
+ *
50
+ * A wildcard subscription (`orders/#`) is one pattern with one channel.
51
+ * The server announces each topic it joins for the pattern with a
52
+ * `subscribed` frame that has no id; the engine then tracks that topic
53
+ * like any other, with its own next expected `seq` and acknowledgement
54
+ * memory, owned by the pattern and feeding the pattern's channel. A
55
+ * `subscribed` or `message` for an untracked topic is matched against the
56
+ * patterns, and the oldest matching one owns it. After a reconnect the
57
+ * tracked topics are resubscribed first, then each pattern is sent again
58
+ * with `from: {"seq": 1}`, which joins only topics created meanwhile.
59
+ * Subscribing again to a pattern the engine holds replaces the
60
+ * subscription: the topics it owned move to the new channel and keep
61
+ * their next expected `seq`, because the server sends nothing again for
62
+ * topics the connection holds, and the earlier channel ends.
63
+ *
64
+ * A shared subscription (a topic read through a `group`) gets only some of
65
+ * the topic's messages, out of order, so duplicates are found with a
66
+ * bounded set of delivered `seq`s instead of a next expected one, nothing
67
+ * moves on `subscribed.replay_from` or `truncated`, and after a reconnect
68
+ * it always rejoins the group with `from: "resume"`.
69
+ *
70
+ * An `unsubscribed` frame with no id means the server ended the
71
+ * subscription; every unsubscribe the engine sends carries an id so its
72
+ * reply is never mistaken for that.
73
+ *
74
+ * The browser `WebSocket` API can't pause reading, so backpressure works in
75
+ * two steps. While a subscription's buffer holds `subscriptionBuffer`
76
+ * messages or more, automatic acknowledgements of new QoS 1 messages wait
77
+ * until the application takes them; the server's per-subscription window
78
+ * (`limits.max_inflight`) then stops sending to it, QoS 0 included. If the
79
+ * buffer still reaches `subscriptionBuffer + max_inflight` (possible with
80
+ * QoS 0 traffic, which no window paces), the engine drops the connection,
81
+ * waits until the application has taken that buffer down to half of
82
+ * `subscriptionBuffer`, reconnects, and resubscribes that topic from the
83
+ * next `seq` it expects, so the log fills the gap. Memory per subscription
84
+ * stays below `subscriptionBuffer + max_inflight` messages.
85
+ *
86
+ * Nor does the API show the server's WebSocket pings, so silence is
87
+ * detected with the protocol's own `ping` request: after `heartbeat_secs`
88
+ * with nothing from the server the engine sends `ping` with an id, and
89
+ * again after each further `heartbeat_secs` of silence. Any frame,
90
+ * including the `pong` reply, counts as hearing from the server. Once
91
+ * `idle_timeout_secs + heartbeat_secs` pass with nothing at all, the
92
+ * connection is given up and the engine reconnects.
93
+ *
94
+ * @module
95
+ */
96
+ import { jitteredDelay } from "./backoff.js";
97
+ import { ACK_MEMORY, DeliveryTracker } from "./dedup.js";
98
+ import { Emitter } from "./events.js";
99
+ import { PopSubError } from "./errors.js";
100
+ import { Aborted, ConnectFailure, Handshake } from "./handshake.js";
101
+ import { isPattern, matchesPattern } from "./pattern.js";
102
+ import { closeCode, encodeFrame, errorCode, parseServerFrame, PROTOCOL_VERSION, publishFrame, shouldReconnect, } from "./protocol.js";
103
+ import { Channel, Message, Subscription } from "./subscription.js";
104
+ /** How many QoS 0 publishes and unsubscribes are held while disconnected; the oldest go first. */
105
+ export const OFFLINE_LIMIT = 10_000;
106
+ /** How long to wait for anything from the server before the server has announced its limits. */
107
+ const DEFAULT_SILENCE_MS = 120_000;
108
+ /** How long a connection may be silent before a `ping`, before the server has announced its limits. */
109
+ const DEFAULT_PING_MS = 30_000;
110
+ /** The window size assumed before the server has announced its limits. */
111
+ const DEFAULT_MAX_INFLIGHT = 100;
112
+ /**
113
+ * Creates a version 4 UUID, with `crypto.randomUUID` where the runtime has
114
+ * it (browsers only offer it on secure origins) and `getRandomValues`
115
+ * otherwise.
116
+ *
117
+ * @returns The UUID.
118
+ */
119
+ export function uuid() {
120
+ const crypto = globalThis.crypto;
121
+ if (typeof crypto.randomUUID === "function") {
122
+ return crypto.randomUUID();
123
+ }
124
+ const bytes = crypto.getRandomValues(new Uint8Array(16));
125
+ bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x40;
126
+ bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;
127
+ const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
128
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
129
+ }
130
+ /**
131
+ * Turns an unexpected reply during connecting into a failure.
132
+ *
133
+ * @param reply - What the server sent instead of the expected reply.
134
+ * @returns The failure; retryable only for the server's temporary refusals
135
+ * and for replies of the wrong type.
136
+ */
137
+ function refusal(reply) {
138
+ if (reply.type === "error") {
139
+ const error = PopSubError.server(errorCode(reply.code), reply.message, reply.retry_after ?? null);
140
+ return new ConnectFailure(error, error.isTemporary());
141
+ }
142
+ return new ConnectFailure(new PopSubError("protocol", `unexpected ${reply.type} while connecting`), true);
143
+ }
144
+ /** The state and the run loop behind one `Client`. */
145
+ export class Engine {
146
+ /** How to connect. */
147
+ #config;
148
+ /** Where events go. */
149
+ emitter = new Emitter();
150
+ /** Subscribed topics. */
151
+ #topics = new Map();
152
+ /** Wildcard subscriptions, by pattern. */
153
+ #patterns = new Map();
154
+ /**
155
+ * Topics the server restored for the session that the application hasn't
156
+ * subscribed to in this process. Their messages are dropped without an
157
+ * acknowledgement, so the server keeps them for the session.
158
+ */
159
+ #unclaimed = new Set();
160
+ /**
161
+ * Whether the server left the session's topics unattached on this
162
+ * connection (`authenticated.held`). Then nothing arrives on a topic
163
+ * until the engine subscribes to it, so nothing is unclaimed, and
164
+ * `#restore` subscribes to the resumed topics itself.
165
+ */
166
+ #held = false;
167
+ /** Subscribes waiting for `subscribed`, by topic. */
168
+ #subscribeWaiters = new Map();
169
+ /** Requests waiting for a reply, by id. */
170
+ #pending = new Map();
171
+ /** Confirmed publishes not yet confirmed, by request id, in id order, for resending. */
172
+ #unconfirmed = new Map();
173
+ /** QoS 0 publishes and unsubscribes to send once connected. */
174
+ #offline = [];
175
+ /** The next request id. */
176
+ #nextId = 1;
177
+ /** The next subscription generation. */
178
+ #nextGeneration = 1;
179
+ /** Whether a connection has ever succeeded, so `clean_start` is only sent once. */
180
+ #connectedOnce = false;
181
+ /** How long to wait for anything from the server before giving up on the connection. */
182
+ #silenceMs = DEFAULT_SILENCE_MS;
183
+ /** How long a connection may be silent before a `ping`, and between `ping`s while it stays silent. */
184
+ #pingMs = DEFAULT_PING_MS;
185
+ /** The server's per-subscription window. */
186
+ #maxInflight = DEFAULT_MAX_INFLIGHT;
187
+ /** The served connection, while there is one. */
188
+ #connection = null;
189
+ /** Ends the served connection, while there is one. */
190
+ #endServe = null;
191
+ /** Re-checks whatever the run loop is waiting for; set by each wait. */
192
+ #wake = null;
193
+ /** Whether the application asked to close. */
194
+ #closing = false;
195
+ /** Why the client stopped, once it has. */
196
+ #stopped = null;
197
+ /** Settles when the first connection is up, or rejects with what stopped the client first. */
198
+ ready;
199
+ /** Settles `ready`. */
200
+ #ready = null;
201
+ /** Settles when the run loop has finished and the client has stopped. */
202
+ finished;
203
+ /** Settles `finished`. */
204
+ #finish = () => undefined;
205
+ /**
206
+ * Builds an engine and starts its run loop.
207
+ *
208
+ * @param config - How to connect.
209
+ */
210
+ constructor(config) {
211
+ this.#config = config;
212
+ this.ready = new Promise((resolve, reject) => {
213
+ this.#ready = { resolve, reject };
214
+ });
215
+ this.ready.catch(() => undefined);
216
+ this.finished = new Promise((resolve) => {
217
+ this.#finish = resolve;
218
+ });
219
+ void this.#run();
220
+ }
221
+ /**
222
+ * Why the client stopped, if it has.
223
+ *
224
+ * @returns `{ code }` once stopped (the code is `null` when the
225
+ * application closed it or it ran out of attempts), `null` while running.
226
+ */
227
+ get stopped() {
228
+ return this.#stopped;
229
+ }
230
+ /**
231
+ * Subscribes to a topic or a wildcard pattern, replacing any earlier
232
+ * subscription to the same name. With a group it joins a shared
233
+ * subscription to the topic.
234
+ *
235
+ * Subscribing again to a topic by name starts over from `from`.
236
+ * Subscribing again to a pattern keeps the topics it owned (see
237
+ * `#replacePattern`).
238
+ *
239
+ * A topic the server held for the session, subscribed by name or matched
240
+ * by the pattern, is claimed: it is tracked with `claiming` set, so what
241
+ * the server sent on its own is dropped until the `subscribed` that
242
+ * answers the claim. A topic subscribed again while its claim is
243
+ * unanswered stays `claiming`. For a pattern each claimed topic gets its own
244
+ * subscribe by name with `from: "resume"`, sent after the pattern's.
245
+ * While disconnected nothing is sent; `#restore` sends the claims on the
246
+ * next connection.
247
+ *
248
+ * @param topic - The topic, or a pattern such as `orders/#`.
249
+ * @param from - Where replay starts.
250
+ * @param group - The shared subscription to join, or `null`.
251
+ * @returns The subscription, and a promise that settles when the server
252
+ * confirms it.
253
+ * @throws PopSubError of kind `closed` when the client has stopped.
254
+ */
255
+ subscribe(topic, from, group = null) {
256
+ this.#throwIfStopped();
257
+ const generation = this.#nextGeneration++;
258
+ const channel = new Channel(topic, {
259
+ taken: (message) => {
260
+ this.#taken(message.topic, generation, message);
261
+ },
262
+ leave: () => {
263
+ this.#forget(topic, generation);
264
+ },
265
+ });
266
+ const wildcard = group === null && isPattern(topic);
267
+ const stillClaiming = this.#topics.get(topic)?.claiming === true;
268
+ if (wildcard && this.#patterns.has(topic)) {
269
+ this.#replacePattern(topic, channel, generation);
270
+ }
271
+ else {
272
+ this.#release(topic, null);
273
+ }
274
+ this.#subscribeWaiters
275
+ .get(topic)
276
+ ?.reject(new PopSubError("protocol", `replaced by a later subscribe to '${topic}'`));
277
+ let claimed = [];
278
+ if (wildcard) {
279
+ this.#patterns.set(topic, { channel, generation });
280
+ claimed = this.#claimMatching(topic, channel, generation);
281
+ }
282
+ else {
283
+ this.#topics.set(topic, {
284
+ channel,
285
+ from,
286
+ generation,
287
+ tracker: new DeliveryTracker(ACK_MEMORY, group !== null),
288
+ overflowed: false,
289
+ owner: null,
290
+ group,
291
+ claiming: this.#unclaimed.delete(topic) || stillClaiming,
292
+ });
293
+ }
294
+ const done = new Promise((resolve, reject) => {
295
+ this.#subscribeWaiters.set(topic, { resolve, reject });
296
+ });
297
+ if (this.#connection !== null) {
298
+ this.#sendSubscribe(topic, generation, from, group);
299
+ for (const name of claimed) {
300
+ this.#sendSubscribe(name, generation, "resume", null);
301
+ }
302
+ }
303
+ return { subscription: new Subscription(channel), done };
304
+ }
305
+ /**
306
+ * Unsubscribes from a topic, or from a pattern and every topic joined
307
+ * through it. While disconnected the unsubscribes are queued and the
308
+ * call succeeds at once.
309
+ *
310
+ * @param topic - The topic or pattern.
311
+ * @returns A promise that settles with the server's reply to the
312
+ * unsubscribe for `topic` itself.
313
+ */
314
+ unsubscribe(topic) {
315
+ if (this.#stopped !== null) {
316
+ return Promise.reject(PopSubError.closed(this.#stopped.code));
317
+ }
318
+ const released = this.#release(topic, null);
319
+ const [first, ...owned] = released.length === 0 ? [topic] : released;
320
+ if (this.#connection === null) {
321
+ for (const name of [first ?? topic, ...owned]) {
322
+ this.#queueOffline({ type: "unsubscribe", topic: name });
323
+ }
324
+ return Promise.resolve();
325
+ }
326
+ return new Promise((resolve, reject) => {
327
+ const id = this.#takeId();
328
+ this.#pending.set(id, { kind: "unsubscribe", settle: { resolve, reject } });
329
+ this.#send({ type: "unsubscribe", topic: first ?? topic }, id);
330
+ for (const name of owned) {
331
+ this.#send({ type: "unsubscribe", topic: name }, this.#takeId());
332
+ }
333
+ });
334
+ }
335
+ /**
336
+ * Publishes at QoS 0. While disconnected the publish is queued.
337
+ *
338
+ * @param topic - The topic.
339
+ * @param payload - The body: text, or base64 when `encoding` says so.
340
+ * @param encoding - How `payload` encodes the body, or `null` for text.
341
+ * @throws PopSubError of kind `closed` when the client has stopped.
342
+ */
343
+ publish(topic, payload, encoding = null) {
344
+ this.#throwIfStopped();
345
+ this.#queueOffline(publishFrame(topic, payload, encoding));
346
+ this.#flushOffline();
347
+ }
348
+ /**
349
+ * Publishes at QoS 1 under a new `message_id`, resending it after every
350
+ * reconnect until the server confirms it.
351
+ *
352
+ * @param topic - The topic.
353
+ * @param payload - The body: text, or base64 when `encoding` says so.
354
+ * @param encoding - How `payload` encodes the body, or `null` for text.
355
+ * @returns A promise that settles with the `seq` and id once stored.
356
+ */
357
+ publishConfirmed(topic, payload, encoding = null) {
358
+ if (this.#stopped !== null) {
359
+ return Promise.reject(PopSubError.closed(this.#stopped.code));
360
+ }
361
+ return new Promise((resolve, reject) => {
362
+ const id = this.#takeId();
363
+ const message = {
364
+ ...publishFrame(topic, payload, encoding),
365
+ message_id: uuid(),
366
+ qos: 1,
367
+ };
368
+ this.#pending.set(id, { kind: "publish", settle: { resolve, reject } });
369
+ this.#unconfirmed.set(id, message);
370
+ if (this.#connection !== null) {
371
+ this.#send(message, id);
372
+ }
373
+ });
374
+ }
375
+ /**
376
+ * Acknowledges a message (from `Message.ack`). While disconnected it is
377
+ * only remembered, so a redelivery is acknowledged again.
378
+ *
379
+ * @param topic - The topic.
380
+ * @param seq - The message's `seq`.
381
+ */
382
+ ack(topic, seq) {
383
+ this.#topics.get(topic)?.tracker.acked.insert(seq);
384
+ this.#send({ type: "ack", topic, seq });
385
+ }
386
+ /**
387
+ * Sends a request that is never queued while disconnected and never
388
+ * resent (the admin requests), and returns its reply.
389
+ *
390
+ * @param message - The request.
391
+ * @returns A promise that settles with the reply, rejecting with a
392
+ * `server` error for an `error` frame, or `connect` when disconnected
393
+ * or when the connection drops first.
394
+ */
395
+ request(message) {
396
+ if (this.#stopped !== null) {
397
+ return Promise.reject(PopSubError.closed(this.#stopped.code));
398
+ }
399
+ if (this.#connection === null) {
400
+ return Promise.reject(new PopSubError("connect", "not connected; this request isn't queued while disconnected"));
401
+ }
402
+ return new Promise((resolve, reject) => {
403
+ const id = this.#takeId();
404
+ this.#pending.set(id, { kind: "request", settle: { resolve, reject } });
405
+ this.#send(message, id);
406
+ });
407
+ }
408
+ /**
409
+ * Closes the connection and stops the client. Pending requests fail with
410
+ * a `closed` error.
411
+ *
412
+ * @returns A promise that settles once the client has stopped.
413
+ */
414
+ close() {
415
+ if (this.#stopped === null) {
416
+ this.#closing = true;
417
+ this.#wake?.();
418
+ }
419
+ return this.finished;
420
+ }
421
+ /**
422
+ * Runs until the client stops, then stops it. An unexpected exception
423
+ * stops the client too, and becomes the cause of the error `ready`
424
+ * rejects with, so the returned promise never rejects.
425
+ */
426
+ async #run() {
427
+ try {
428
+ this.#stop(await this.#loop());
429
+ }
430
+ catch (error) {
431
+ this.#stop(null, error);
432
+ }
433
+ }
434
+ /**
435
+ * Connects, serves the connection, reconnects with backoff, and settles
436
+ * `ready` with the first outcome, until the client must stop.
437
+ *
438
+ * @returns The close code that stopped the client, or `null` when the
439
+ * application closed it, it ran out of attempts, or connecting failed
440
+ * in a way retrying can't fix.
441
+ */
442
+ async #loop() {
443
+ let attempt = 0;
444
+ let lastError = null;
445
+ while (!this.#closing) {
446
+ const outcome = await this.#connectOnce();
447
+ if (outcome.kind === "stopped") {
448
+ break;
449
+ }
450
+ if (outcome.kind === "connected") {
451
+ attempt = 0;
452
+ this.#connectedOnce = true;
453
+ this.#ready?.resolve();
454
+ this.#ready = null;
455
+ this.emitter.emit({ type: "connected", resumed: outcome.resumed });
456
+ const ending = await this.#serve(outcome.handshake, outcome.resumed);
457
+ if (ending.kind === "stop") {
458
+ break;
459
+ }
460
+ this.#failRequests();
461
+ if (ending.kind === "pause") {
462
+ this.emitter.emit({ type: "disconnected", code: null, reconnecting: true });
463
+ if (!(await this.#waitForRoom())) {
464
+ break;
465
+ }
466
+ continue;
467
+ }
468
+ const reconnecting = this.#shouldReconnect(ending.code);
469
+ this.emitter.emit({ type: "disconnected", code: ending.code, reconnecting });
470
+ if (!reconnecting) {
471
+ return ending.code;
472
+ }
473
+ }
474
+ else {
475
+ lastError = outcome.failure.error;
476
+ if (!outcome.failure.retry) {
477
+ this.#ready?.reject(outcome.failure.error);
478
+ this.#ready = null;
479
+ break;
480
+ }
481
+ }
482
+ attempt += 1;
483
+ const maxAttempts = this.#config.reconnect.maxAttempts;
484
+ if (maxAttempts !== null && attempt > maxAttempts) {
485
+ const reason = lastError === null ? "" : `; the last attempt failed: ${lastError.message}`;
486
+ this.#ready?.reject(new PopSubError("connect", `ran out of reconnect attempts${reason}`, { cause: lastError }));
487
+ this.#ready = null;
488
+ break;
489
+ }
490
+ if (!(await this.#sleep(jitteredDelay(this.#config.reconnect, attempt)))) {
491
+ break;
492
+ }
493
+ }
494
+ return null;
495
+ }
496
+ /**
497
+ * Decides whether to reconnect after a connection was lost.
498
+ *
499
+ * @param code - The server's close code, if it sent one.
500
+ * @returns True to reconnect. An expired token only allows it with
501
+ * password credentials, which log in again.
502
+ */
503
+ #shouldReconnect(code) {
504
+ if (code === null) {
505
+ return true;
506
+ }
507
+ if (code === 4004) {
508
+ return "password" in this.#config.credentials;
509
+ }
510
+ return shouldReconnect(code);
511
+ }
512
+ /**
513
+ * Waits before the next attempt, unless the application closes the client.
514
+ *
515
+ * @param ms - How long to wait.
516
+ * @returns False when the application closed the client while waiting.
517
+ */
518
+ #sleep(ms) {
519
+ return new Promise((resolve) => {
520
+ if (this.#closing) {
521
+ resolve(false);
522
+ return;
523
+ }
524
+ const timer = setTimeout(() => {
525
+ this.#wake = null;
526
+ resolve(true);
527
+ }, ms);
528
+ this.#wake = () => {
529
+ if (this.#closing) {
530
+ clearTimeout(timer);
531
+ this.#wake = null;
532
+ resolve(false);
533
+ }
534
+ };
535
+ });
536
+ }
537
+ /**
538
+ * After a buffer overflowed, waits until every overflowed topic's buffer
539
+ * is down to half of `subscriptionBuffer` (or the topic is gone).
540
+ *
541
+ * @returns False when the application closed the client while waiting.
542
+ */
543
+ #waitForRoom() {
544
+ const low = Math.floor(this.#config.subscriptionBuffer / 2);
545
+ const drained = () => [...this.#topics.values()].every((topic) => !topic.overflowed || topic.channel.size <= low);
546
+ return new Promise((resolve) => {
547
+ const check = () => {
548
+ if (this.#closing) {
549
+ this.#wake = null;
550
+ resolve(false);
551
+ }
552
+ else if (drained()) {
553
+ this.#wake = null;
554
+ resolve(true);
555
+ }
556
+ };
557
+ this.#wake = check;
558
+ check();
559
+ });
560
+ }
561
+ /**
562
+ * Opens a connection, logs in if needed, and authenticates. With a
563
+ * session id the `auth` asks the server to hold the session's topics
564
+ * (`hold_resumed`), and `#held` records whether it did.
565
+ *
566
+ * @returns The authenticated connection with the topics the server
567
+ * restored, a failure saying whether retrying could help, or `stopped`
568
+ * when the application closed the client meanwhile.
569
+ */
570
+ async #connectOnce() {
571
+ let handshake;
572
+ try {
573
+ handshake = new Handshake(this.#config.url, this.#config.requestTimeoutMs);
574
+ }
575
+ catch (error) {
576
+ const failure = error instanceof PopSubError ? error : new PopSubError("config", String(error), { cause: error });
577
+ return { kind: "failed", failure: new ConnectFailure(failure, false) };
578
+ }
579
+ this.#wake = () => {
580
+ if (this.#closing) {
581
+ handshake.abort();
582
+ }
583
+ };
584
+ try {
585
+ await handshake.opened();
586
+ const credentials = this.#config.credentials;
587
+ let token;
588
+ if ("token" in credentials) {
589
+ token = credentials.token;
590
+ }
591
+ else {
592
+ const reply = await handshake.exchange(this.#takeId(), {
593
+ type: "login",
594
+ username: credentials.username,
595
+ password: credentials.password,
596
+ });
597
+ if (reply.type !== "logged_in") {
598
+ throw refusal(reply);
599
+ }
600
+ token = reply.token;
601
+ }
602
+ const auth = { type: "auth", token, protocol: PROTOCOL_VERSION };
603
+ if (this.#config.sessionId !== null) {
604
+ auth.session_id = this.#config.sessionId;
605
+ auth.hold_resumed = true;
606
+ }
607
+ if (this.#config.cleanStart && !this.#connectedOnce) {
608
+ auth.clean_start = true;
609
+ }
610
+ const reply = await handshake.exchange(this.#takeId(), auth);
611
+ if (reply.type !== "authenticated") {
612
+ throw refusal(reply);
613
+ }
614
+ this.#applyLimits(reply.limits);
615
+ this.#held = reply.held === true;
616
+ return { kind: "connected", handshake, resumed: reply.resumed ?? [] };
617
+ }
618
+ catch (reason) {
619
+ handshake.close();
620
+ if (reason instanceof Aborted) {
621
+ return { kind: "stopped" };
622
+ }
623
+ if (reason instanceof ConnectFailure) {
624
+ return { kind: "failed", failure: reason };
625
+ }
626
+ const message = reason instanceof Error ? reason.message : String(reason);
627
+ return {
628
+ kind: "failed",
629
+ failure: new ConnectFailure(new PopSubError("connect", message, { cause: reason }), true),
630
+ };
631
+ }
632
+ finally {
633
+ this.#wake = null;
634
+ }
635
+ }
636
+ /**
637
+ * Reads the server's limits: when to `ping`, how much silence to allow,
638
+ * and the window size.
639
+ *
640
+ * @param limits - The limits from `authenticated`.
641
+ */
642
+ #applyLimits(limits) {
643
+ const idle = Math.max(1, limits.idle_timeout_secs);
644
+ const heartbeat = Math.max(1, limits.heartbeat_secs);
645
+ this.#pingMs = heartbeat * 1000;
646
+ this.#silenceMs = (idle + heartbeat) * 1000;
647
+ if (Number.isFinite(limits.max_inflight) && limits.max_inflight > 0) {
648
+ this.#maxInflight = limits.max_inflight;
649
+ }
650
+ }
651
+ /**
652
+ * Serves one connection until it ends. Works out which restored topics
653
+ * are unclaimed (those the engine isn't tracking, or none when the server
654
+ * holds the session's topics), restores subscriptions
655
+ * and resends, then handles frames as they arrive. A timer sends `ping` while
656
+ * the connection is silent and ends it as lost once the silence passes
657
+ * `idle_timeout_secs + heartbeat_secs`.
658
+ *
659
+ * @param handshake - The authenticated connection.
660
+ * @param resumed - Topics the server restored for the session.
661
+ * @returns How the connection ended.
662
+ */
663
+ #serve(handshake, resumed) {
664
+ return new Promise((resolve) => {
665
+ let lastHeard = Date.now();
666
+ let lastPing = lastHeard;
667
+ const tick = Math.max(50, Math.min(1000, this.#pingMs / 4));
668
+ const timer = setInterval(() => {
669
+ const now = Date.now();
670
+ if (now - lastHeard >= this.#silenceMs) {
671
+ finish({ kind: "lost", code: null });
672
+ }
673
+ else if (now - lastHeard >= this.#pingMs && now - lastPing >= this.#pingMs) {
674
+ lastPing = now;
675
+ const id = this.#takeId();
676
+ this.#pending.set(id, { kind: "ping" });
677
+ this.#send({ type: "ping" }, id);
678
+ }
679
+ }, tick);
680
+ const live = () => this.#connection === handshake;
681
+ const finish = (ending) => {
682
+ if (!live()) {
683
+ return;
684
+ }
685
+ clearInterval(timer);
686
+ this.#connection = null;
687
+ this.#endServe = null;
688
+ this.#wake = null;
689
+ handshake.close();
690
+ resolve(ending);
691
+ };
692
+ this.#connection = handshake;
693
+ this.#endServe = finish;
694
+ this.#wake = () => {
695
+ if (this.#closing) {
696
+ finish({ kind: "stop" });
697
+ }
698
+ };
699
+ const early = handshake.handOver({
700
+ text: (text) => {
701
+ lastHeard = Date.now();
702
+ lastPing = lastHeard;
703
+ this.#onText(text);
704
+ },
705
+ closed: (code) => {
706
+ finish({ kind: "lost", code: closeCode(code) });
707
+ },
708
+ });
709
+ this.#unclaimed = new Set(resumed.filter((name) => !this.#held && !this.#topics.has(name)));
710
+ this.#restore(resumed);
711
+ for (const text of early) {
712
+ if (!live()) {
713
+ return;
714
+ }
715
+ this.#onText(text);
716
+ }
717
+ });
718
+ }
719
+ /**
720
+ * Restores state on a new connection: resubscribes, resends unconfirmed
721
+ * publishes, and sends queued frames.
722
+ *
723
+ * When the server holds the session's topics (`#held`), each topic it
724
+ * lists as resumed that the engine tracks is subscribed again from
725
+ * `resume`, which is one past the session's cursor. Otherwise
726
+ * topics the server restored for the session are left to it, except
727
+ * those whose buffer overflowed and those still waiting for the
728
+ * `subscribed` that claims them, which are subscribed again the way the
729
+ * application asked (`resume` for one owned by a pattern); every other
730
+ * topic is subscribed again from the next `seq` it expects, so nothing
731
+ * still in the log is missed.
732
+ * A shared subscription always rejoins its group with `resume`, because
733
+ * the group's position is on the server. Wildcard patterns are sent
734
+ * after the topics, in name order, from `{"seq": 1}`: the server skips
735
+ * topics the connection holds, so that joins only topics created during
736
+ * the disconnect, from their first message.
737
+ *
738
+ * @param resumed - Topics the server restored.
739
+ */
740
+ #restore(resumed) {
741
+ const restored = new Set(resumed);
742
+ for (const [name, topic] of this.#topics) {
743
+ if (topic.group !== null) {
744
+ this.#sendSubscribe(name, topic.generation, "resume", topic.group);
745
+ }
746
+ else if (topic.claiming) {
747
+ this.#sendSubscribe(name, topic.generation, topic.owner === null ? topic.from : "resume", null);
748
+ }
749
+ else if (!restored.has(name) || topic.overflowed) {
750
+ const next = topic.tracker.nextExpected;
751
+ this.#sendSubscribe(name, topic.generation, next === null ? topic.from : { seq: next }, null);
752
+ }
753
+ else if (this.#held) {
754
+ this.#sendSubscribe(name, topic.generation, "resume", null);
755
+ }
756
+ topic.overflowed = false;
757
+ }
758
+ for (const name of [...this.#patterns.keys()].sort()) {
759
+ const pattern = this.#patterns.get(name);
760
+ if (pattern !== undefined) {
761
+ this.#sendSubscribe(name, pattern.generation, { seq: 1 }, null);
762
+ }
763
+ }
764
+ for (const [id, message] of this.#unconfirmed) {
765
+ this.#send(message, id);
766
+ }
767
+ this.#flushOffline();
768
+ }
769
+ /**
770
+ * Sends a subscribe and records it as pending.
771
+ *
772
+ * @param topic - The topic or pattern.
773
+ * @param generation - The subscription it is for.
774
+ * @param from - Where replay starts.
775
+ * @param group - The shared subscription to join, or `null`.
776
+ */
777
+ #sendSubscribe(topic, generation, from, group) {
778
+ const id = this.#takeId();
779
+ this.#pending.set(id, { kind: "subscribe", topic, generation });
780
+ this.#send(group === null ? { type: "subscribe", topic, from } : { type: "subscribe", topic, from, group }, id);
781
+ }
782
+ /**
783
+ * Queues a frame to send once connected, dropping the oldest beyond `OFFLINE_LIMIT`.
784
+ *
785
+ * @param message - A QoS 0 publish or an unsubscribe.
786
+ */
787
+ #queueOffline(message) {
788
+ if (this.#offline.length >= OFFLINE_LIMIT) {
789
+ this.#offline.shift();
790
+ }
791
+ this.#offline.push(message);
792
+ }
793
+ /** Sends every queued frame, if connected. Unsubscribes get an id. */
794
+ #flushOffline() {
795
+ if (this.#connection === null) {
796
+ return;
797
+ }
798
+ const queued = this.#offline;
799
+ this.#offline = [];
800
+ for (const message of queued) {
801
+ this.#send(message, message.type === "unsubscribe" ? this.#takeId() : undefined);
802
+ }
803
+ }
804
+ /**
805
+ * Sends a frame if connected. A frame sent while the socket is closing is
806
+ * lost with it; the close that follows decides what is resent.
807
+ *
808
+ * @param message - The frame.
809
+ * @param id - The request id, when a reply is expected.
810
+ */
811
+ #send(message, id) {
812
+ const socket = this.#connection?.socket;
813
+ if (socket?.readyState !== WebSocket.OPEN) {
814
+ return;
815
+ }
816
+ socket.send(encodeFrame(message, id));
817
+ }
818
+ /**
819
+ * Takes a request id.
820
+ *
821
+ * @returns A new id.
822
+ */
823
+ #takeId() {
824
+ const id = this.#nextId;
825
+ this.#nextId += 1;
826
+ return id;
827
+ }
828
+ /**
829
+ * Stops tracking one topic. A topic subscribed by name has its
830
+ * subscription ended; a topic owned by a pattern only stops, and the
831
+ * pattern's subscription carries on.
832
+ *
833
+ * @param topic - The topic.
834
+ * @returns Whether it was tracked.
835
+ */
836
+ #dropTopic(topic) {
837
+ const entry = this.#topics.get(topic);
838
+ if (entry === undefined) {
839
+ return false;
840
+ }
841
+ this.#topics.delete(topic);
842
+ if (entry.owner === null) {
843
+ entry.channel.end();
844
+ }
845
+ return true;
846
+ }
847
+ /**
848
+ * Starts tracking a topic the server joined for one of this client's
849
+ * wildcard subscriptions. When several patterns match, the oldest owns it.
850
+ *
851
+ * @param name - The topic.
852
+ * @param start - The first `seq` the server will send, or `null` when unknown.
853
+ * @returns The tracked topic, or `undefined` when no pattern matches.
854
+ */
855
+ #adopt(name, start) {
856
+ let owner = null;
857
+ let oldest = null;
858
+ for (const [pattern, entry] of this.#patterns) {
859
+ if (matchesPattern(pattern, name) && (oldest === null || entry.generation < oldest.generation)) {
860
+ owner = pattern;
861
+ oldest = entry;
862
+ }
863
+ }
864
+ if (owner === null || oldest === null) {
865
+ return undefined;
866
+ }
867
+ const tracker = new DeliveryTracker();
868
+ tracker.nextExpected = start;
869
+ const topic = {
870
+ channel: oldest.channel,
871
+ from: { seq: start ?? 1 },
872
+ generation: oldest.generation,
873
+ tracker,
874
+ overflowed: false,
875
+ owner,
876
+ group: null,
877
+ claiming: false,
878
+ };
879
+ this.#topics.set(name, topic);
880
+ return topic;
881
+ }
882
+ /**
883
+ * Moves a held pattern to a new subscription. The topics it owned are
884
+ * pointed at the new channel and generation and keep their trackers, so
885
+ * each keeps the next `seq` it expects: the server sends nothing again
886
+ * for topics the connection holds. The earlier channel ends; what it
887
+ * still holds can be taken or dropped without any effect on the topics.
888
+ * Acknowledgements held back for the earlier channel's full buffer are
889
+ * sent now, because nothing will report those messages as taken to the
890
+ * new subscription.
891
+ *
892
+ * @param pattern - The pattern, which must be held.
893
+ * @param channel - The new subscription's channel.
894
+ * @param generation - The new subscription.
895
+ */
896
+ #replacePattern(pattern, channel, generation) {
897
+ this.#patterns.get(pattern)?.channel.end();
898
+ for (const [name, topic] of this.#topics) {
899
+ if (topic.owner !== pattern) {
900
+ continue;
901
+ }
902
+ topic.channel = channel;
903
+ topic.generation = generation;
904
+ for (const seq of topic.tracker.deferred) {
905
+ topic.tracker.acked.insert(seq);
906
+ this.#send({ type: "ack", topic: name, seq });
907
+ }
908
+ topic.tracker.deferred.clear();
909
+ }
910
+ }
911
+ /**
912
+ * Claims every unclaimed topic of the session a pattern matches: each
913
+ * stops being unclaimed and is tracked as owned by the pattern, with
914
+ * `claiming` set until its own `subscribed` arrives.
915
+ *
916
+ * @param pattern - The pattern.
917
+ * @param channel - The pattern's channel.
918
+ * @param generation - The pattern's subscription.
919
+ * @returns The claimed topics in name order, each of which needs a
920
+ * subscribe by name with `from: "resume"`.
921
+ */
922
+ #claimMatching(pattern, channel, generation) {
923
+ const claimed = [...this.#unclaimed].filter((name) => matchesPattern(pattern, name)).sort();
924
+ for (const name of claimed) {
925
+ this.#unclaimed.delete(name);
926
+ this.#topics.set(name, {
927
+ channel,
928
+ from: "resume",
929
+ generation,
930
+ tracker: new DeliveryTracker(),
931
+ overflowed: false,
932
+ owner: pattern,
933
+ group: null,
934
+ claiming: true,
935
+ });
936
+ }
937
+ return claimed;
938
+ }
939
+ /**
940
+ * Stops tracking a subscription and ends it: a topic subscribed by name,
941
+ * or a wildcard pattern together with every topic joined through it.
942
+ *
943
+ * @param name - The topic or pattern.
944
+ * @param generation - Only release it if it is still this subscription;
945
+ * `null` releases whatever is there.
946
+ * @returns What to unsubscribe from on the server: the name first, and
947
+ * for a pattern the topics it owned. Empty when nothing was released.
948
+ */
949
+ #release(name, generation) {
950
+ const pattern = this.#patterns.get(name);
951
+ if (pattern !== undefined && (generation === null || pattern.generation === generation)) {
952
+ this.#patterns.delete(name);
953
+ pattern.channel.end();
954
+ const names = [name];
955
+ for (const [topic, entry] of this.#topics) {
956
+ if (entry.owner === name) {
957
+ this.#topics.delete(topic);
958
+ names.push(topic);
959
+ }
960
+ }
961
+ return names;
962
+ }
963
+ const topic = this.#topics.get(name);
964
+ if (topic?.owner === null && (generation === null || topic.generation === generation)) {
965
+ this.#topics.delete(name);
966
+ topic.channel.end();
967
+ return [name];
968
+ }
969
+ return [];
970
+ }
971
+ /**
972
+ * Unsubscribes without waiting, when the application closes a
973
+ * subscription, if the topic or pattern still belongs to it. A pattern's
974
+ * owned topics are unsubscribed with it.
975
+ *
976
+ * @param topic - The topic or pattern.
977
+ * @param generation - The subscription being closed.
978
+ */
979
+ #forget(topic, generation) {
980
+ const released = this.#release(topic, generation);
981
+ if (released.length === 0) {
982
+ return;
983
+ }
984
+ this.#subscribeWaiters.get(topic)?.reject(PopSubError.closed(null));
985
+ this.#subscribeWaiters.delete(topic);
986
+ for (const name of released) {
987
+ if (this.#connection === null) {
988
+ this.#queueOffline({ type: "unsubscribe", topic: name });
989
+ }
990
+ else {
991
+ this.#send({ type: "unsubscribe", topic: name }, this.#takeId());
992
+ }
993
+ }
994
+ this.#wake?.();
995
+ }
996
+ /**
997
+ * Called when the application takes a message: sends an acknowledgement
998
+ * held back for a full buffer, and lets a paused client reconnect once
999
+ * there is room.
1000
+ *
1001
+ * @param topic - The topic.
1002
+ * @param generation - The subscription the message came from.
1003
+ * @param message - The message taken.
1004
+ */
1005
+ #taken(topic, generation, message) {
1006
+ const entry = this.#topics.get(topic);
1007
+ if (entry?.generation === generation && entry.tracker.deferred.delete(message.seq)) {
1008
+ entry.tracker.acked.insert(message.seq);
1009
+ this.#send({ type: "ack", topic, seq: message.seq });
1010
+ }
1011
+ this.#wake?.();
1012
+ }
1013
+ /**
1014
+ * Parses a frame and acts on it; frames this client doesn't know are ignored.
1015
+ *
1016
+ * @param text - The frame's text.
1017
+ */
1018
+ #onText(text) {
1019
+ const frame = parseServerFrame(text);
1020
+ if (frame !== null) {
1021
+ this.#onFrame(frame);
1022
+ }
1023
+ }
1024
+ /**
1025
+ * Acts on a frame from the server. A reply's pending entry is removed by
1026
+ * its id first, so a `pong` needs nothing more: hearing it at all is what
1027
+ * keeps the connection from being given up as silent. A `subscribed` for
1028
+ * a topic being claimed ends the claim and starts its next expected `seq`
1029
+ * over at `replay_from`.
1030
+ *
1031
+ * @param frame - The frame.
1032
+ */
1033
+ #onFrame(frame) {
1034
+ const id = typeof frame.id === "number" ? frame.id : null;
1035
+ const pending = id === null ? undefined : this.#pending.get(id);
1036
+ if (id !== null) {
1037
+ this.#pending.delete(id);
1038
+ }
1039
+ if (pending?.kind === "request") {
1040
+ if (frame.type === "error") {
1041
+ pending.settle.reject(PopSubError.server(errorCode(frame.code), frame.message, frame.retry_after ?? null));
1042
+ }
1043
+ else {
1044
+ pending.settle.resolve(frame);
1045
+ }
1046
+ return;
1047
+ }
1048
+ const unprompted = frame.id === undefined || frame.id === null;
1049
+ switch (frame.type) {
1050
+ case "message":
1051
+ this.#deliver(frame);
1052
+ break;
1053
+ case "subscribed": {
1054
+ if (!this.#patterns.has(frame.topic)) {
1055
+ const tracked = this.#topics.get(frame.topic);
1056
+ if (tracked === undefined) {
1057
+ this.#adopt(frame.topic, frame.replay_from);
1058
+ }
1059
+ else {
1060
+ if (tracked.claiming) {
1061
+ tracked.claiming = false;
1062
+ tracked.tracker.nextExpected = null;
1063
+ }
1064
+ tracked.tracker.moveTo(frame.replay_from);
1065
+ }
1066
+ }
1067
+ const waiter = this.#subscribeWaiters.get(frame.topic);
1068
+ if (waiter !== undefined) {
1069
+ this.#subscribeWaiters.delete(frame.topic);
1070
+ waiter.resolve();
1071
+ }
1072
+ break;
1073
+ }
1074
+ case "unsubscribed":
1075
+ if (pending?.kind === "unsubscribe") {
1076
+ pending.settle.resolve();
1077
+ }
1078
+ else if (unprompted && this.#dropTopic(frame.topic)) {
1079
+ this.emitter.emit({ type: "unsubscribed", topic: frame.topic });
1080
+ }
1081
+ break;
1082
+ case "published":
1083
+ if (pending?.kind === "publish" && id !== null) {
1084
+ this.#unconfirmed.delete(id);
1085
+ pending.settle.resolve({ seq: frame.seq, messageId: frame.message_id });
1086
+ }
1087
+ break;
1088
+ case "truncated":
1089
+ this.#topics.get(frame.topic)?.tracker.moveTo(frame.first_available);
1090
+ this.emitter.emit({ type: "truncated", topic: frame.topic, firstAvailable: frame.first_available });
1091
+ break;
1092
+ case "stalled":
1093
+ this.emitter.emit({ type: "stalled", topic: frame.topic, seq: frame.seq });
1094
+ break;
1095
+ case "auth_expiring":
1096
+ this.emitter.emit({ type: "authExpiring", expiresAtMs: frame.expires_at_ms });
1097
+ if ("password" in this.#config.credentials) {
1098
+ const loginId = this.#takeId();
1099
+ this.#pending.set(loginId, { kind: "relogin" });
1100
+ const { username, password } = this.#config.credentials;
1101
+ this.#send({ type: "login", username, password }, loginId);
1102
+ }
1103
+ break;
1104
+ case "logged_in":
1105
+ if (pending?.kind === "relogin") {
1106
+ const authId = this.#takeId();
1107
+ this.#pending.set(authId, { kind: "reauth" });
1108
+ this.#send({ type: "auth", token: frame.token, protocol: PROTOCOL_VERSION }, authId);
1109
+ }
1110
+ break;
1111
+ case "authenticated":
1112
+ if (pending?.kind === "reauth") {
1113
+ this.emitter.emit({ type: "authRefreshed" });
1114
+ }
1115
+ break;
1116
+ case "pong":
1117
+ break;
1118
+ case "error":
1119
+ this.#onError(pending, id, frame);
1120
+ break;
1121
+ default:
1122
+ break;
1123
+ }
1124
+ }
1125
+ /**
1126
+ * Routes an error frame to the request it answers, or to the events. A
1127
+ * refused subscribe ends that subscription; a refused resubscribe of a
1128
+ * topic owned by a pattern only stops tracking that topic.
1129
+ *
1130
+ * @param pending - The request it answers, if its id matched one.
1131
+ * @param id - Its request id, if it had one.
1132
+ * @param frame - The error frame.
1133
+ */
1134
+ #onError(pending, id, frame) {
1135
+ const code = errorCode(frame.code);
1136
+ const error = PopSubError.server(code, frame.message, frame.retry_after ?? null);
1137
+ switch (pending?.kind) {
1138
+ case "subscribe": {
1139
+ const released = this.#release(pending.topic, pending.generation).length > 0;
1140
+ const owned = this.#topics.get(pending.topic);
1141
+ if (!released && owned?.owner != null && owned.generation === pending.generation) {
1142
+ this.#topics.delete(pending.topic);
1143
+ }
1144
+ if (released) {
1145
+ const waiter = this.#subscribeWaiters.get(pending.topic);
1146
+ this.#subscribeWaiters.delete(pending.topic);
1147
+ waiter?.reject(error);
1148
+ }
1149
+ break;
1150
+ }
1151
+ case "unsubscribe":
1152
+ pending.settle.reject(error);
1153
+ break;
1154
+ case "publish":
1155
+ if (id !== null) {
1156
+ this.#unconfirmed.delete(id);
1157
+ }
1158
+ pending.settle.reject(error);
1159
+ break;
1160
+ case "ping":
1161
+ break;
1162
+ default:
1163
+ this.emitter.emit({ type: "serverError", code, message: frame.message });
1164
+ break;
1165
+ }
1166
+ }
1167
+ /**
1168
+ * Hands a delivered message to its subscription, dropping duplicates,
1169
+ * acknowledging as the ack mode says, and holding back when the buffer is
1170
+ * full. A message for an untracked topic is adopted by the oldest
1171
+ * matching wildcard pattern; when none matches it is acknowledged and dropped.
1172
+ *
1173
+ * A message on a topic the server holds for the session that the
1174
+ * application hasn't subscribed to here, or whose subscribe is still
1175
+ * unanswered, is dropped without an acknowledgement: the server keeps it
1176
+ * and replays it when the application's subscribe is handled.
1177
+ *
1178
+ * @param delivery - The delivered message.
1179
+ */
1180
+ #deliver(delivery) {
1181
+ const { topic: name, seq } = delivery;
1182
+ const qos = delivery.qos === 1 ? 1 : 0;
1183
+ if (this.#unclaimed.has(name)) {
1184
+ return;
1185
+ }
1186
+ const topic = this.#topics.get(name) ?? this.#adopt(name, null);
1187
+ if (topic === undefined) {
1188
+ if (qos === 1) {
1189
+ this.#send({ type: "ack", topic: name, seq });
1190
+ }
1191
+ return;
1192
+ }
1193
+ if (topic.overflowed || topic.claiming) {
1194
+ return;
1195
+ }
1196
+ const automatic = this.#config.ackMode === "auto";
1197
+ if (topic.tracker.isDuplicate(seq)) {
1198
+ if (qos === 1 && topic.tracker.reacksDuplicate(seq, automatic)) {
1199
+ this.#send({ type: "ack", topic: name, seq });
1200
+ }
1201
+ return;
1202
+ }
1203
+ const buffered = topic.channel.size;
1204
+ if (buffered >= this.#config.subscriptionBuffer + this.#maxInflight) {
1205
+ topic.overflowed = true;
1206
+ this.#endServe?.({ kind: "pause" });
1207
+ return;
1208
+ }
1209
+ topic.tracker.accept(seq);
1210
+ let acker = null;
1211
+ if (qos === 1) {
1212
+ if (!automatic) {
1213
+ acker = () => {
1214
+ this.ack(name, seq);
1215
+ };
1216
+ }
1217
+ else if (buffered < this.#config.subscriptionBuffer) {
1218
+ topic.tracker.acked.insert(seq);
1219
+ this.#send({ type: "ack", topic: name, seq });
1220
+ }
1221
+ else {
1222
+ topic.tracker.deferred.add(seq);
1223
+ }
1224
+ }
1225
+ topic.channel.push(new Message({
1226
+ topic: name,
1227
+ seq,
1228
+ messageId: delivery.message_id,
1229
+ payload: delivery.payload,
1230
+ encoding: delivery.encoding === "base64" ? "base64" : null,
1231
+ qos,
1232
+ publishedAtMs: delivery.published_at_ms,
1233
+ }, acker));
1234
+ }
1235
+ /**
1236
+ * Fails every admin request still waiting when a connection ends: the
1237
+ * server may or may not have carried it out. `ping`s, token refreshes and
1238
+ * subscribes of the old connection are forgotten; subscribes are sent
1239
+ * again by `#restore`.
1240
+ */
1241
+ #failRequests() {
1242
+ for (const [id, pending] of this.#pending) {
1243
+ if (pending.kind === "request") {
1244
+ this.#pending.delete(id);
1245
+ pending.settle.reject(new PopSubError("connect", "the connection dropped before the reply; the request may or may not have been carried out"));
1246
+ }
1247
+ else if (pending.kind === "ping" ||
1248
+ pending.kind === "relogin" ||
1249
+ pending.kind === "reauth" ||
1250
+ pending.kind === "subscribe") {
1251
+ this.#pending.delete(id);
1252
+ }
1253
+ }
1254
+ }
1255
+ /**
1256
+ * Throws if the client has stopped.
1257
+ *
1258
+ * @throws PopSubError of kind `closed` with the close code that stopped it.
1259
+ */
1260
+ #throwIfStopped() {
1261
+ if (this.#stopped !== null) {
1262
+ throw PopSubError.closed(this.#stopped.code);
1263
+ }
1264
+ }
1265
+ /**
1266
+ * Stops the client for good: records why, fails everything waiting, ends
1267
+ * every subscription, and removes every event listener.
1268
+ *
1269
+ * @param code - The close code that stopped it, if any.
1270
+ * @param cause - The unexpected exception that stopped it, if any.
1271
+ */
1272
+ #stop(code, cause) {
1273
+ this.#endServe?.({ kind: "stop" });
1274
+ this.#wake = null;
1275
+ this.#stopped = { code };
1276
+ const error = PopSubError.closed(code);
1277
+ this.#ready?.reject(cause === undefined
1278
+ ? error
1279
+ : new PopSubError("closed", `the client stopped unexpectedly: ${cause instanceof Error ? cause.message : "unknown error"}`, { cause }));
1280
+ this.#ready = null;
1281
+ for (const waiter of this.#subscribeWaiters.values()) {
1282
+ waiter.reject(error);
1283
+ }
1284
+ this.#subscribeWaiters.clear();
1285
+ for (const pending of this.#pending.values()) {
1286
+ if (pending.kind === "unsubscribe" || pending.kind === "publish" || pending.kind === "request") {
1287
+ pending.settle.reject(error);
1288
+ }
1289
+ }
1290
+ this.#pending.clear();
1291
+ this.#unconfirmed.clear();
1292
+ this.#offline = [];
1293
+ for (const topic of this.#topics.values()) {
1294
+ topic.channel.end();
1295
+ }
1296
+ this.#topics.clear();
1297
+ for (const pattern of this.#patterns.values()) {
1298
+ pattern.channel.end();
1299
+ }
1300
+ this.#patterns.clear();
1301
+ this.#unclaimed.clear();
1302
+ this.emitter.clear();
1303
+ this.#finish();
1304
+ }
1305
+ }
1306
+ //# sourceMappingURL=engine.js.map