@dokebi/websocket-hub 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/leader.js ADDED
@@ -0,0 +1,331 @@
1
+ import { randomUUID, timingSafeEqual } from 'node:crypto';
2
+ import { Deliveries, recipientKey } from './delivery.js';
3
+ import { integer } from './options.js';
4
+ import { encode, epoch, identifier, matches, query, records } from './protocol.js';
5
+ import { HubError } from './types.js';
6
+ import { Wire } from './wire.js';
7
+ export class Leader {
8
+ identity;
9
+ store;
10
+ options;
11
+ #peers = new Map();
12
+ #sockets = new Set();
13
+ #owners = new Map();
14
+ #revision = 0;
15
+ #deliveries;
16
+ #tail = Promise.resolve();
17
+ #pending = 0;
18
+ #active = true;
19
+ #deadline = 0;
20
+ constructor(identity, store, options) {
21
+ this.identity = identity;
22
+ this.store = store;
23
+ this.options = options;
24
+ this.#deliveries = new Deliveries(options, () => [...this.#owners.values()].flatMap((owner) => owner.connections), (owner, frame) => {
25
+ const peer = this.#peers.get(owner);
26
+ if (!peer)
27
+ return false;
28
+ try {
29
+ this.#send(peer, frame);
30
+ return true;
31
+ }
32
+ catch {
33
+ peer.wire.close();
34
+ return false;
35
+ }
36
+ });
37
+ }
38
+ get active() {
39
+ return this.#active && performance.now() < this.#deadline;
40
+ }
41
+ async start() {
42
+ await this.#renew();
43
+ const snapshot = await this.store.snapshot(this.identity.epoch);
44
+ this.#owners = snapshot.owners;
45
+ this.#revision = snapshot.revision;
46
+ await this.#expire(snapshot.now);
47
+ }
48
+ async #renew() {
49
+ const start = performance.now();
50
+ const now = Number(await this.store.run('renew', this.identity.epoch, String(this.options.leaseMs)));
51
+ this.#deadline = start + this.options.leaseMs;
52
+ if (!this.active)
53
+ throw new HubError('STALE_LEADER');
54
+ return now;
55
+ }
56
+ #queue(fn) {
57
+ if (this.#pending >= this.options.maxPending)
58
+ return Promise.reject(new HubError('BUSY'));
59
+ this.#pending++;
60
+ const work = this.#tail.then(async () => {
61
+ if (!this.#active)
62
+ throw new HubError('STALE_LEADER');
63
+ return fn();
64
+ });
65
+ this.#tail = work
66
+ .then(() => { }, () => { })
67
+ .finally(() => {
68
+ this.#pending--;
69
+ });
70
+ return work;
71
+ }
72
+ accept(socket) {
73
+ if (!this.active || this.#sockets.size >= this.options.maxOwners) {
74
+ socket.destroy();
75
+ return;
76
+ }
77
+ const peer = {
78
+ wire: new Wire(socket, this.options.maxFrameBytes, this.options.queueBytes, (frame) => {
79
+ // Broadcasts and ACKs stay in memory (D-0042): no Redis round trip and no wait behind
80
+ // owner updates. The lease is checked against its local deadline.
81
+ if (frame.op === 'broadcast' || frame.op === 'ack') {
82
+ this.#deliver(peer, frame);
83
+ return;
84
+ }
85
+ void this.#queue(() => this.#handle(peer, frame)).catch((error) => {
86
+ try {
87
+ peer.wire.send({
88
+ kind: 'reply',
89
+ id: frame.id,
90
+ epoch: this.identity.epoch,
91
+ ok: false,
92
+ code: error instanceof HubError ? error.code : 'STORE_UNAVAILABLE',
93
+ });
94
+ }
95
+ catch { }
96
+ if (!peer.owner || !this.active)
97
+ peer.wire.close();
98
+ });
99
+ }, () => {
100
+ this.#sockets.delete(peer);
101
+ if (peer.owner && this.#peers.get(peer.owner) === peer) {
102
+ this.#peers.delete(peer.owner);
103
+ if (this.#active)
104
+ void this.#queue(async () => {
105
+ await this.#renew();
106
+ await this.#remove(peer.owner, peer.session);
107
+ }).catch(() => this.stop());
108
+ }
109
+ }),
110
+ };
111
+ this.#sockets.add(peer);
112
+ socket.setTimeout(this.options.ownerTtlMs, () => socket.destroy());
113
+ }
114
+ #deliver(peer, f) {
115
+ let id;
116
+ try {
117
+ id = integer(f.id, 1, Number.MAX_SAFE_INTEGER);
118
+ if (!this.active)
119
+ throw new HubError('STALE_LEADER');
120
+ const ownerId = peer.owner;
121
+ if (!ownerId || this.#peers.get(ownerId) !== peer || f.epoch !== this.identity.epoch)
122
+ throw new HubError('STALE_PEER');
123
+ const owner = this.#owners.get(ownerId);
124
+ if (!owner || owner.session !== peer.session)
125
+ throw new HubError('STALE_PEER');
126
+ if (f.op === 'ack') {
127
+ this.#deliveries.acknowledge(f.acks, owner.connections);
128
+ this.#send(peer, { kind: 'reply', id, ok: true, result: {} });
129
+ return;
130
+ }
131
+ const reply = id;
132
+ this.#deliveries.accept(ownerId, f, (ok, recipients) => {
133
+ try {
134
+ this.#send(peer, {
135
+ kind: 'reply',
136
+ id: reply,
137
+ ok,
138
+ ...(ok
139
+ ? { result: { authorityEpoch: this.identity.epoch, id: f.messageId, recipients } }
140
+ : { code: 'DELIVERY_TIMEOUT' }),
141
+ });
142
+ }
143
+ catch {
144
+ peer.wire.close();
145
+ }
146
+ },
147
+ // The producer keeps the recipient list to resend it to the next leader.
148
+ (recipients) => {
149
+ try {
150
+ this.#send(peer, { kind: 'accepted', id: f.messageId, recipients });
151
+ }
152
+ catch {
153
+ peer.wire.close();
154
+ }
155
+ });
156
+ }
157
+ catch (error) {
158
+ try {
159
+ peer.wire.send({
160
+ kind: 'reply',
161
+ id,
162
+ epoch: this.identity.epoch,
163
+ ok: false,
164
+ code: error instanceof HubError ? error.code : 'PROTOCOL_ERROR',
165
+ });
166
+ }
167
+ catch { }
168
+ if (!peer.owner || !this.active)
169
+ peer.wire.close();
170
+ }
171
+ }
172
+ #send(peer, value) {
173
+ if (!this.active)
174
+ throw new HubError('STALE_LEADER');
175
+ peer.wire.send({ ...value, epoch: this.identity.epoch });
176
+ }
177
+ #notify(owner, connections) {
178
+ for (const peer of this.#peers.values()) {
179
+ try {
180
+ this.#send(peer, { kind: 'presence', revision: this.#revision, owner, connections });
181
+ }
182
+ catch {
183
+ peer.wire.close();
184
+ }
185
+ }
186
+ }
187
+ async #save(ownerId, value) {
188
+ const identities = new Set();
189
+ for (const [id, owner] of [...this.#owners.entries()]
190
+ .filter(([id]) => id !== ownerId)
191
+ .concat([[ownerId, value]])) {
192
+ void id;
193
+ for (const record of owner.connections) {
194
+ const key = recipientKey(record);
195
+ if (identities.has(key))
196
+ throw new HubError('DUPLICATE_CLIENT');
197
+ identities.add(key);
198
+ }
199
+ }
200
+ const total = [...this.#owners.entries()].reduce((n, [key, owner]) => n + (key === ownerId ? 0 : owner.connections.length), value.connections.length);
201
+ if (total > this.options.maxTotalConnections ||
202
+ (!this.#owners.has(ownerId) && this.#owners.size >= this.options.maxOwners))
203
+ throw new HubError('CONNECTION_LIMIT');
204
+ // A reconnect must always be able to carry the full authoritative snapshot in one bounded frame.
205
+ const snapshot = [...this.#owners.entries()]
206
+ .filter(([id]) => id !== ownerId)
207
+ .map(([id, v]) => [id, v.connections]);
208
+ snapshot.push([ownerId, value.connections]);
209
+ encode({ owners: snapshot }, this.options.maxFrameBytes - 4096);
210
+ const result = (await this.store.run('save', this.identity.epoch, String(this.options.ownerTtlMs), JSON.stringify({ ...value, connections: JSON.stringify(value.connections) }), ownerId));
211
+ this.#revision = result[0];
212
+ value.expires = result[1];
213
+ this.#owners.set(ownerId, value);
214
+ this.#notify(ownerId, value.connections);
215
+ }
216
+ async #remove(ownerId, session) {
217
+ const rev = Number(await this.store.run('remove', this.identity.epoch, '', session, ownerId));
218
+ if (rev) {
219
+ this.#owners.delete(ownerId);
220
+ this.#revision = rev;
221
+ this.#notify(ownerId, []);
222
+ }
223
+ }
224
+ async #expire(now) {
225
+ for (const [ownerId, owner] of this.#owners)
226
+ if (owner.expires <= now) {
227
+ this.#peers.get(ownerId)?.wire.close();
228
+ await this.#remove(ownerId, owner.session);
229
+ }
230
+ }
231
+ async #handle(peer, f) {
232
+ const id = integer(f.id, 1, Number.MAX_SAFE_INTEGER);
233
+ await this.#renew();
234
+ let result = {};
235
+ if (f.op === 'hello') {
236
+ if (peer.owner)
237
+ throw new HubError('ALREADY_REGISTERED');
238
+ const supplied = typeof f.secret === 'string' ? Buffer.from(f.secret) : Buffer.alloc(0), expected = Buffer.from(this.options.secret);
239
+ if (supplied.length !== expected.length || !timingSafeEqual(supplied, expected))
240
+ throw new HubError('UNAUTHORIZED');
241
+ const owner = epoch(f.owner), session = epoch(f.session);
242
+ const values = records(f.connections, owner, this.options.maxConnections);
243
+ const value = {
244
+ serverId: identifier(f.serverId),
245
+ session,
246
+ expires: 0,
247
+ connections: values,
248
+ };
249
+ // Do not include the joining peer in deltas until it receives its initial snapshot.
250
+ await this.#save(owner, value);
251
+ const previous = this.#peers.get(owner);
252
+ peer.owner = owner;
253
+ peer.session = session;
254
+ this.#peers.set(owner, peer);
255
+ previous?.wire.close();
256
+ result = {
257
+ revision: this.#revision,
258
+ owners: [...this.#owners].map(([key, v]) => [key, v.connections]),
259
+ };
260
+ }
261
+ else {
262
+ const ownerId = peer.owner;
263
+ if (!ownerId || this.#peers.get(ownerId) !== peer || f.epoch !== this.identity.epoch)
264
+ throw new HubError('STALE_PEER');
265
+ const owner = this.#owners.get(ownerId);
266
+ if (!owner || owner.session !== peer.session)
267
+ throw new HubError('STALE_PEER');
268
+ if (f.op === 'set') {
269
+ await this.#save(ownerId, {
270
+ ...owner,
271
+ connections: records(f.connections, ownerId, this.options.maxConnections),
272
+ });
273
+ }
274
+ else if (f.op === 'ping') {
275
+ owner.expires = Number(await this.store.run('touch', this.identity.epoch, String(this.options.ownerTtlMs), owner.session, ownerId));
276
+ result = { revision: this.#revision };
277
+ }
278
+ else if (f.op === 'bye') {
279
+ await this.#remove(ownerId, owner.session);
280
+ this.#peers.delete(ownerId);
281
+ }
282
+ else if (f.op === 'kick') {
283
+ const filter = query(f.query), messageId = randomUUID();
284
+ const code = f.op === 'kick' ? integer(f.code, 4000, 4999) : undefined;
285
+ const reason = f.op === 'kick' ? identifier(f.reason) : undefined;
286
+ if (reason && Buffer.byteLength(reason) > 123)
287
+ throw new HubError('INVALID_ARGUMENT');
288
+ for (const [key, target] of this.#owners) {
289
+ const selected = target.connections
290
+ .filter((r) => matches(r, filter))
291
+ .map((r) => r.connection);
292
+ if (!selected.length)
293
+ continue;
294
+ const destination = this.#peers.get(key);
295
+ if (!destination)
296
+ throw new HubError('OUTCOME_UNKNOWN');
297
+ try {
298
+ this.#send(destination, {
299
+ kind: 'kick',
300
+ id: messageId,
301
+ connections: selected,
302
+ code,
303
+ reason,
304
+ });
305
+ }
306
+ catch {
307
+ destination.wire.close();
308
+ throw new HubError('OUTCOME_UNKNOWN');
309
+ }
310
+ }
311
+ result = { authorityEpoch: this.identity.epoch, id: messageId };
312
+ }
313
+ else
314
+ throw new HubError('PROTOCOL_ERROR');
315
+ }
316
+ this.#send(peer, { kind: 'reply', id, ok: true, result });
317
+ }
318
+ tick() {
319
+ return this.#queue(async () => {
320
+ const now = await this.#renew();
321
+ await this.#expire(now);
322
+ this.#deliveries.tick();
323
+ });
324
+ }
325
+ async stop() {
326
+ this.#active = false;
327
+ for (const peer of this.#sockets)
328
+ peer.wire.close();
329
+ await this.#tail;
330
+ }
331
+ }
@@ -0,0 +1,20 @@
1
+ import type { HubOptions } from './options.js';
2
+ import { type HubApi } from './types.js';
3
+ /**
4
+ * The hub of one process (D-0029, `mode: 'local'`): the same HubApi as the cluster hub, kept in
5
+ * memory. Broadcasts still resolve only after every recipient acknowledged (D-0025) and are
6
+ * resent every retryMs until then; a recipient with a clientId that reconnects receives what it
7
+ * missed. Undelivered messages are lost with the process, and there is no failover.
8
+ */
9
+ export declare class LocalHub {
10
+ #private;
11
+ readonly options: HubOptions;
12
+ /** Told once when replay nonces are used where they cannot be shared (D-0038). */
13
+ readonly warn: (message: string, data: Record<string, unknown>) => void;
14
+ readonly api: HubApi;
15
+ readonly ownerEpoch: `${string}-${string}-${string}-${string}-${string}`;
16
+ constructor(options: HubOptions,
17
+ /** Told once when replay nonces are used where they cannot be shared (D-0038). */
18
+ warn?: (message: string, data: Record<string, unknown>) => void);
19
+ close(): Promise<void>;
20
+ }
package/dist/local.js ADDED
@@ -0,0 +1,243 @@
1
+ import cluster from 'node:cluster';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { recipientKey } from './delivery.js';
4
+ import { EventQueue } from './event-queue.js';
5
+ import { array, identifier, matches, metadata, query, record } from './protocol.js';
6
+ import { hubStatus, LocalNonceStore } from './status.js';
7
+ import { HubError, } from './types.js';
8
+ /**
9
+ * The hub of one process (D-0029, `mode: 'local'`): the same HubApi as the cluster hub, kept in
10
+ * memory. Broadcasts still resolve only after every recipient acknowledged (D-0025) and are
11
+ * resent every retryMs until then; a recipient with a clientId that reconnects receives what it
12
+ * missed. Undelivered messages are lost with the process, and there is no failover.
13
+ */
14
+ export class LocalHub {
15
+ options;
16
+ warn;
17
+ api;
18
+ ownerEpoch = randomUUID();
19
+ #authority = randomUUID();
20
+ #records = new Map();
21
+ #events;
22
+ #deliveries = new Map();
23
+ #deliveryBytes = 0;
24
+ #revision = 0;
25
+ #closed = false;
26
+ #timer;
27
+ constructor(options,
28
+ /** Told once when replay nonces are used where they cannot be shared (D-0038). */
29
+ warn = () => { }) {
30
+ this.options = options;
31
+ this.warn = warn;
32
+ this.#events = new EventQueue(options.maxPending, options.queueBytes);
33
+ const self = this;
34
+ const nonces = new LocalNonceStore();
35
+ let warned = false;
36
+ this.api = Object.freeze({
37
+ get state() {
38
+ return self.#closed ? 'closed' : 'ready';
39
+ },
40
+ role: 'active',
41
+ get ownerEpoch() {
42
+ return self.ownerEpoch;
43
+ },
44
+ leader: undefined,
45
+ register: (value) => this.#register(value),
46
+ list: (filter) => this.#list(filter),
47
+ broadcast: (filter, data) => this.#broadcast(filter, data),
48
+ acknowledge: (id, connections) => this.#acknowledge(id, connections),
49
+ kick: (filter, code, reason) => this.#kick(filter, code, reason),
50
+ events: () => this.#events,
51
+ // Always ready until closed: there is no leader to reconnect to.
52
+ whenReady: async () => !this.#closed,
53
+ status: async () => hubStatus({ mode: 'local', state: self.api.state, role: 'active' }),
54
+ nonces: () => {
55
+ // A local hub in a node:cluster worker (allowInCluster) keeps nonces per worker: a frame
56
+ // replayed to another worker passes. Say it once, where the defence is asked for.
57
+ if (cluster.isWorker && !warned) {
58
+ warned = true;
59
+ this.warn('Replay nonces are per worker with a local hub', {
60
+ code: 'HUB_NONCES_NOT_SHARED',
61
+ fix: 'Use mode: cluster (Redis) so every worker shares one nonce store',
62
+ });
63
+ }
64
+ return nonces;
65
+ },
66
+ });
67
+ this.#timer = setInterval(() => this.#tick(), Math.min(options.retryMs, 250));
68
+ this.#timer.unref();
69
+ }
70
+ #push(event) {
71
+ try {
72
+ this.#events.push(event);
73
+ }
74
+ catch (error) {
75
+ // The consumer fell too far behind: end the stream like the cluster client does.
76
+ this.#events.finish(error);
77
+ this.#closed = true;
78
+ }
79
+ }
80
+ #changed() {
81
+ this.#revision++;
82
+ this.#push({
83
+ kind: 'presence',
84
+ revision: this.#revision,
85
+ ownerEpoch: this.ownerEpoch,
86
+ connections: Object.freeze([...this.#records.values()]),
87
+ });
88
+ }
89
+ #ensureOpen() {
90
+ if (this.#closed)
91
+ throw new HubError('CLOSED');
92
+ }
93
+ async #register(input) {
94
+ this.#ensureOpen();
95
+ const value = record(input, this.ownerEpoch);
96
+ if (this.#records.has(value.connection))
97
+ throw new HubError('DUPLICATE_CONNECTION');
98
+ const key = recipientKey(value);
99
+ for (const existing of this.#records.values())
100
+ if (recipientKey(existing) === key)
101
+ throw new HubError('DUPLICATE_CLIENT');
102
+ if (this.#records.size >= this.options.maxConnections ||
103
+ this.#records.size >= this.options.maxTotalConnections)
104
+ throw new HubError('CONNECTION_LIMIT');
105
+ this.#records.set(value.connection, value);
106
+ this.#changed();
107
+ // A reconnect with the same clientId gets what it has not acknowledged yet.
108
+ for (const delivery of this.#deliveries.values())
109
+ if (delivery.remaining.has(key))
110
+ delivery.lastSent = 0;
111
+ let closed = false;
112
+ const change = async (next) => {
113
+ const current = this.#records.get(value.connection);
114
+ if (closed || !current)
115
+ throw new HubError('UNKNOWN_CONNECTION');
116
+ this.#records.set(value.connection, next(current));
117
+ this.#changed();
118
+ };
119
+ return Object.freeze({
120
+ identity: Object.freeze({ ownerEpoch: this.ownerEpoch, connection: value.connection }),
121
+ join: (room) => change((current) => record({ ...current, rooms: [...new Set([...current.rooms, identifier(room)])] }, this.ownerEpoch)),
122
+ leave: (room) => change((current) => record({ ...current, rooms: current.rooms.filter((item) => item !== identifier(room)) }, this.ownerEpoch)),
123
+ updateMetadata: (meta) => change((current) => record({ ...current, metadata: metadata(meta) }, this.ownerEpoch)),
124
+ close: async () => {
125
+ if (closed)
126
+ return;
127
+ closed = true;
128
+ if (this.#records.delete(value.connection) && !this.#closed)
129
+ this.#changed();
130
+ },
131
+ });
132
+ }
133
+ async #list(input) {
134
+ this.#ensureOpen();
135
+ const filter = query(input);
136
+ return Object.freeze({
137
+ authorityEpoch: this.#authority,
138
+ revision: this.#revision,
139
+ connections: Object.freeze([...this.#records.values()].filter((r) => matches(r, filter))),
140
+ });
141
+ }
142
+ #broadcast(input, data) {
143
+ if (this.#closed)
144
+ return Promise.reject(new HubError('CLOSED'));
145
+ if (!(data instanceof Uint8Array) || data.byteLength > this.options.maxPayloadBytes)
146
+ return Promise.reject(new HubError('INVALID_ARGUMENT'));
147
+ const filter = query(input);
148
+ if (this.#deliveries.size >= this.options.maxDeliveries ||
149
+ this.#deliveryBytes + data.byteLength > this.options.deliveryBytes)
150
+ return Promise.reject(new HubError('BUSY'));
151
+ const id = randomUUID();
152
+ const recipients = [
153
+ ...new Set([...this.#records.values()].filter((r) => matches(r, filter)).map(recipientKey)),
154
+ ];
155
+ if (!recipients.length)
156
+ return Promise.resolve(Object.freeze({ authorityEpoch: this.#authority, id, recipients }));
157
+ const copy = Uint8Array.from(data);
158
+ return new Promise((resolve, reject) => {
159
+ const delivery = {
160
+ id,
161
+ data: copy,
162
+ expiresAt: Date.now() + this.options.deliveryTimeoutMs,
163
+ recipients: Object.freeze(recipients),
164
+ remaining: new Set(recipients),
165
+ lastSent: 0,
166
+ done: (ok) => {
167
+ this.#deliveries.delete(id);
168
+ this.#deliveryBytes -= copy.byteLength;
169
+ if (ok)
170
+ resolve(Object.freeze({ authorityEpoch: this.#authority, id, recipients }));
171
+ else
172
+ reject(new HubError(this.#closed ? 'CLOSED' : 'DELIVERY_TIMEOUT'));
173
+ },
174
+ };
175
+ this.#deliveries.set(id, delivery);
176
+ this.#deliveryBytes += copy.byteLength;
177
+ this.#transmit(delivery);
178
+ });
179
+ }
180
+ /** Sends the message to the connections that still owe an ACK (at most once per retryMs). */
181
+ #transmit(delivery) {
182
+ const now = Date.now();
183
+ if (now - delivery.lastSent < this.options.retryMs)
184
+ return;
185
+ const connections = [...this.#records.values()]
186
+ .filter((r) => delivery.remaining.has(recipientKey(r)))
187
+ .map((r) => r.connection);
188
+ if (!connections.length)
189
+ return;
190
+ delivery.lastSent = now;
191
+ this.#push({
192
+ kind: 'message',
193
+ id: delivery.id,
194
+ connections: Object.freeze(connections),
195
+ data: delivery.data,
196
+ expiresAt: delivery.expiresAt,
197
+ });
198
+ }
199
+ #acknowledge(id, connections) {
200
+ const delivery = this.#deliveries.get(id);
201
+ if (!delivery)
202
+ return;
203
+ for (const connection of array(connections, this.options.maxConnections)) {
204
+ const value = this.#records.get(String(connection));
205
+ if (value)
206
+ delivery.remaining.delete(recipientKey(value));
207
+ }
208
+ if (!delivery.remaining.size)
209
+ delivery.done(Date.now() < delivery.expiresAt);
210
+ }
211
+ async #kick(input, code = 4403, reason = 'Disconnected by hub') {
212
+ this.#ensureOpen();
213
+ const filter = query(input);
214
+ if (!Number.isInteger(code) || code < 4000 || code > 4999)
215
+ throw new HubError('INVALID_ARGUMENT');
216
+ if (Buffer.byteLength(identifier(reason)) > 123)
217
+ throw new HubError('INVALID_ARGUMENT');
218
+ const id = randomUUID();
219
+ const connections = [...this.#records.values()]
220
+ .filter((r) => matches(r, filter))
221
+ .map((r) => r.connection);
222
+ if (connections.length)
223
+ this.#push({ kind: 'kick', id, connections: Object.freeze(connections), code, reason });
224
+ return Object.freeze({ authorityEpoch: this.#authority, id });
225
+ }
226
+ #tick() {
227
+ const now = Date.now();
228
+ for (const delivery of [...this.#deliveries.values()]) {
229
+ if (now >= delivery.expiresAt)
230
+ delivery.done(false);
231
+ else
232
+ this.#transmit(delivery);
233
+ }
234
+ }
235
+ async close() {
236
+ if (this.#timer)
237
+ clearInterval(this.#timer);
238
+ this.#closed = true;
239
+ for (const delivery of [...this.#deliveries.values()])
240
+ delivery.done(false);
241
+ this.#events.finish();
242
+ }
243
+ }
package/dist/node.d.ts ADDED
@@ -0,0 +1,23 @@
1
+ import type { PluginContext } from '@dokebi/core';
2
+ import type { NatsConnectionApi } from '@dokebi/nats';
3
+ import type { RedisConnection } from '@dokebi/redis';
4
+ import type { HubOptions } from './options.js';
5
+ import { PeerClient } from './peer-client.js';
6
+ import { HubStore } from './store.js';
7
+ import { type HubApi } from './types.js';
8
+ export declare class HubNode {
9
+ #private;
10
+ readonly context: PluginContext;
11
+ readonly options: HubOptions;
12
+ readonly redis: RedisConnection;
13
+ /** Optional (D-0029): without NATS, peers notice a new leader by Redis polling (pollMs). */
14
+ readonly nats: NatsConnectionApi | undefined;
15
+ readonly api: HubApi;
16
+ readonly store: HubStore;
17
+ readonly client: PeerClient;
18
+ constructor(context: PluginContext, options: HubOptions, redis: RedisConnection,
19
+ /** Optional (D-0029): without NATS, peers notice a new leader by Redis polling (pollMs). */
20
+ nats: NatsConnectionApi | undefined);
21
+ start(): Promise<void>;
22
+ close(): Promise<void>;
23
+ }