@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/node.js ADDED
@@ -0,0 +1,294 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { createServer } from 'node:net';
3
+ import { setTimeout as delay } from 'node:timers/promises';
4
+ import { Leader } from './leader.js';
5
+ import { PeerClient } from './peer-client.js';
6
+ import { hubStatus } from './status.js';
7
+ import { HubStore } from './store.js';
8
+ import { HubError } from './types.js';
9
+ export class HubNode {
10
+ context;
11
+ options;
12
+ redis;
13
+ nats;
14
+ api;
15
+ store;
16
+ client;
17
+ #server;
18
+ #identity;
19
+ #leader;
20
+ #timer;
21
+ #tick;
22
+ #subscription;
23
+ #notifications;
24
+ #closing = false;
25
+ #closed = false;
26
+ #lastFailure = false;
27
+ #failingSince = 0;
28
+ #configMismatch;
29
+ #started = false;
30
+ #startupCode;
31
+ constructor(context, options, redis,
32
+ /** Optional (D-0029): without NATS, peers notice a new leader by Redis polling (pollMs). */
33
+ nats) {
34
+ this.context = context;
35
+ this.options = options;
36
+ this.redis = redis;
37
+ this.nats = nats;
38
+ this.store = new HubStore(redis, options);
39
+ // A drop of a ready connection (revision gap, stale leader, socket closed) is otherwise
40
+ // silent until the next poll reconnects; it is when upgrades see the hub recovering.
41
+ this.client = new PeerClient(options, (code) => this.context.logger.log('debug', 'Hub connection dropped', { code }));
42
+ const self = this;
43
+ // Shared by every server of the namespace: the first to see a nonce wins (D-0038).
44
+ const nonces = Object.freeze({
45
+ shared: true,
46
+ setIfNotExists: (key, ttlSeconds) => this.store.claimNonce(key, ttlSeconds),
47
+ });
48
+ this.api = Object.freeze({
49
+ get state() {
50
+ return self.#closed
51
+ ? 'closed'
52
+ : self.#closing
53
+ ? 'closing'
54
+ : self.client.ready
55
+ ? 'ready'
56
+ : self.#server
57
+ ? 'recovering'
58
+ : 'starting';
59
+ },
60
+ get role() {
61
+ return self.#leader?.active ? 'active' : 'standby';
62
+ },
63
+ get ownerEpoch() {
64
+ return self.client.ownerEpoch;
65
+ },
66
+ get leader() {
67
+ return self.client.leader;
68
+ },
69
+ register: (value) => this.client.register(value),
70
+ list: (query) => this.client.list(query),
71
+ broadcast: (query, data) => this.client.broadcast(query, data),
72
+ acknowledge: (id, connections) => this.client.acknowledge(id, connections),
73
+ kick: (query, code, reason) => this.client.kick(query, code, reason),
74
+ events: () => this.client.events,
75
+ whenReady: (timeoutMs) => this.client.whenReady(timeoutMs),
76
+ status: async () => {
77
+ let lease;
78
+ try {
79
+ lease = await this.store.inspect();
80
+ }
81
+ catch {
82
+ lease = 'unreachable';
83
+ }
84
+ return hubStatus({
85
+ mode: 'cluster',
86
+ state: self.api.state,
87
+ role: self.api.role,
88
+ serverId: this.options.serverId,
89
+ lease,
90
+ });
91
+ },
92
+ nonces: () => nonces,
93
+ });
94
+ }
95
+ async start() {
96
+ const server = createServer((socket) => {
97
+ if (!this.#closing && this.#leader?.active)
98
+ this.#leader.accept(socket);
99
+ else
100
+ socket.destroy();
101
+ });
102
+ this.#server = server;
103
+ await new Promise((resolve, reject) => {
104
+ server.once('error', reject);
105
+ server.listen({ port: this.options.port, host: this.options.host, exclusive: true }, () => {
106
+ server.off('error', reject);
107
+ resolve();
108
+ });
109
+ });
110
+ server.on('error', () => {
111
+ this.client.disconnect();
112
+ });
113
+ const address = server.address();
114
+ if (!address || typeof address === 'string')
115
+ throw new HubError('LISTEN_FAILED');
116
+ this.#identity = {
117
+ epoch: randomUUID(),
118
+ host: this.options.advertiseHost,
119
+ port: address.port,
120
+ serverId: this.options.serverId,
121
+ };
122
+ if (this.nats) {
123
+ this.#subscription = this.nats.subscribe(`dokebi.websocket-hub.${this.options.namespace}.control`);
124
+ await this.#subscription.ready;
125
+ this.#notifications = this.#readNotifications(this.#subscription);
126
+ }
127
+ const deadline = performance.now() + this.options.startupMs;
128
+ while (!this.client.ready) {
129
+ this.context.signal.throwIfAborted();
130
+ await this.#poll();
131
+ if (this.#configMismatch)
132
+ throw this.#configMismatch;
133
+ if (performance.now() > deadline) {
134
+ this.context.logger.log('error', 'Hub did not become ready before startupMs', {
135
+ code: 'STARTUP_TIMEOUT',
136
+ lastError: this.#startupCode ?? 'NONE',
137
+ });
138
+ throw new HubError('STARTUP_TIMEOUT');
139
+ }
140
+ if (!this.client.ready)
141
+ await delay(this.options.pollMs);
142
+ }
143
+ this.#started = true;
144
+ this.#timer = setInterval(() => {
145
+ void this.#poll();
146
+ }, this.options.pollMs);
147
+ this.#timer.unref();
148
+ }
149
+ async #readNotifications(subscription) {
150
+ try {
151
+ for await (const _message of subscription) {
152
+ if (this.#closing)
153
+ break;
154
+ await this.#poll();
155
+ }
156
+ }
157
+ catch {
158
+ if (!this.#closing)
159
+ this.context.logger.log('warn', 'Hub control notifications unavailable; Redis discovery polling remains active');
160
+ }
161
+ }
162
+ #poll() {
163
+ if (this.#closing)
164
+ return Promise.resolve();
165
+ if (this.#tick)
166
+ return this.#tick;
167
+ this.#tick = this.#step()
168
+ .catch(async (error) => {
169
+ if (error instanceof HubError && error.code === 'CONFIG_MISMATCH') {
170
+ // Not transient: servers already running in this namespace use another secret or
171
+ // other shared limits. Startup fails at once instead of waiting for its deadline.
172
+ if (!this.#configMismatch)
173
+ this.context.logger.log('error', 'Hub configuration differs from the servers running in this namespace', { code: 'CONFIG_MISMATCH', namespace: this.options.namespace });
174
+ this.#configMismatch = error;
175
+ }
176
+ else if (!this.#started) {
177
+ // Startup retries are normal (peers race to reach a leader that is still opening);
178
+ // only the last code is kept and reported if startup times out.
179
+ this.#startupCode = hubCode(error);
180
+ }
181
+ else if (!this.#lastFailure) {
182
+ this.#failingSince = performance.now();
183
+ this.context.logger.log('warn', 'Hub transport or store unavailable; recovering', {
184
+ code: hubCode(error),
185
+ });
186
+ }
187
+ // Every further failure of the same outage, so a long recovery shows its causes.
188
+ else
189
+ this.context.logger.log('debug', 'Hub still recovering', {
190
+ code: hubCode(error),
191
+ ms: Math.round(performance.now() - this.#failingSince),
192
+ leader: this.client.leader?.serverId ?? null,
193
+ });
194
+ this.#lastFailure = true;
195
+ const leader = this.#leader;
196
+ this.#leader = undefined;
197
+ await leader?.stop();
198
+ this.client.disconnect();
199
+ })
200
+ .finally(() => {
201
+ this.#tick = undefined;
202
+ });
203
+ return this.#tick;
204
+ }
205
+ async #step() {
206
+ if (!this.#identity)
207
+ return;
208
+ if (this.#leader) {
209
+ await this.#leader.tick();
210
+ }
211
+ let discovered = await this.store.discover();
212
+ if (!discovered) {
213
+ this.#identity = { ...this.#identity, epoch: randomUUID() };
214
+ discovered = await this.store.elect(this.#identity);
215
+ }
216
+ if (discovered.epoch === this.#identity.epoch && !this.#leader) {
217
+ const leader = new Leader(discovered, this.store, this.options);
218
+ try {
219
+ await leader.start();
220
+ }
221
+ catch (error) {
222
+ await leader.stop();
223
+ throw error;
224
+ }
225
+ this.#leader = leader;
226
+ if (this.nats)
227
+ try {
228
+ await this.nats.publish(`dokebi.websocket-hub.${this.options.namespace}.control`, Buffer.from(JSON.stringify({ kind: 'leader-changed', epoch: discovered.epoch })));
229
+ }
230
+ catch {
231
+ this.context.logger.log('warn', 'Hub change notification failed; peers use Redis discovery');
232
+ }
233
+ }
234
+ if (this.#leader && this.#identity.epoch !== discovered.epoch) {
235
+ const previous = this.#leader;
236
+ this.#leader = undefined;
237
+ await previous.stop();
238
+ }
239
+ await this.client.connect(discovered);
240
+ if (this.#lastFailure && this.#started)
241
+ this.context.logger.log('info', 'Hub recovered', {
242
+ ms: Math.round(performance.now() - this.#failingSince),
243
+ leader: discovered.serverId,
244
+ });
245
+ this.#lastFailure = false;
246
+ }
247
+ async close() {
248
+ if (this.#closed)
249
+ return;
250
+ this.#closing = true;
251
+ if (this.#timer)
252
+ clearInterval(this.#timer);
253
+ this.#subscription?.unsubscribe();
254
+ await this.#tick;
255
+ const errors = [];
256
+ try {
257
+ await this.client.close();
258
+ }
259
+ catch (error) {
260
+ errors.push(error);
261
+ }
262
+ // If the leader went away first (whole cluster stopping), `bye` could not remove our record.
263
+ const session = this.client.session;
264
+ if (session)
265
+ try {
266
+ await this.store.run('leave', '', '', session, this.client.ownerEpoch);
267
+ }
268
+ catch (error) {
269
+ errors.push(error);
270
+ }
271
+ const leader = this.#leader;
272
+ this.#leader = undefined;
273
+ await leader?.stop();
274
+ if (leader) {
275
+ try {
276
+ await this.store.run('release', leader.identity.epoch);
277
+ }
278
+ catch (error) {
279
+ errors.push(error);
280
+ }
281
+ }
282
+ if (this.#server)
283
+ await new Promise((resolve) => this.#server?.close(() => resolve()));
284
+ await this.#notifications;
285
+ this.#closed = true;
286
+ if (errors.length)
287
+ throw new AggregateError(errors, 'Hub cleanup failed');
288
+ }
289
+ }
290
+ /** A short code for logs: hub/redis/nats error codes or system errno codes, never messages. */
291
+ function hubCode(error) {
292
+ const code = error?.code;
293
+ return typeof code === 'string' && /^[A-Z][A-Z0-9_]{0,63}$/.test(code) ? code : 'UNKNOWN';
294
+ }
@@ -0,0 +1,35 @@
1
+ export declare function object(value: unknown): Record<string, unknown>;
2
+ export declare function keys(value: Record<string, unknown>, allowed: readonly string[]): void;
3
+ export declare function integer(v: unknown, min: number, max: number): number;
4
+ export interface HubOptions {
5
+ /** `local` (default): one process, in memory. `cluster`: Redis leader, TCP, outbox (D-0029). */
6
+ mode: 'local' | 'cluster';
7
+ /** Lets `local` run in a node:cluster worker anyway (each worker then has its own hub). */
8
+ allowInCluster: boolean;
9
+ namespace: string;
10
+ serverId: string;
11
+ /** Required in cluster mode. */
12
+ redisConnection: string | undefined;
13
+ /** Optional: leader-change notifications; without it peers notice by Redis polling. */
14
+ natsConnection: string | undefined;
15
+ host: string;
16
+ advertiseHost: string;
17
+ port: number;
18
+ secret: string;
19
+ leaseMs: number;
20
+ pollMs: number;
21
+ ownerTtlMs: number;
22
+ startupMs: number;
23
+ maxFrameBytes: number;
24
+ maxPayloadBytes: number;
25
+ maxConnections: number;
26
+ maxOwners: number;
27
+ maxTotalConnections: number;
28
+ maxPending: number;
29
+ queueBytes: number;
30
+ deliveryTimeoutMs: number;
31
+ retryMs: number;
32
+ maxDeliveries: number;
33
+ deliveryBytes: number;
34
+ }
35
+ export declare function parseOptions(input: unknown): HubOptions;
@@ -0,0 +1,122 @@
1
+ import { types } from 'node:util';
2
+ import { HubError } from './types.js';
3
+ export function object(value) {
4
+ if (!value ||
5
+ typeof value !== 'object' ||
6
+ types.isProxy(value) ||
7
+ ![Object.prototype, null].includes(Object.getPrototypeOf(value)))
8
+ throw new HubError('INVALID_OPTIONS');
9
+ const result = Object.create(null);
10
+ for (const key of Reflect.ownKeys(value)) {
11
+ const desc = Object.getOwnPropertyDescriptor(value, key);
12
+ if (typeof key !== 'string' || !desc || !('value' in desc) || !desc.enumerable)
13
+ throw new HubError('INVALID_OPTIONS');
14
+ result[key] = desc.value;
15
+ }
16
+ return result;
17
+ }
18
+ export function keys(value, allowed) {
19
+ if (Object.keys(value).some((k) => !allowed.includes(k)))
20
+ throw new HubError('INVALID_OPTIONS');
21
+ }
22
+ export function integer(v, min, max) {
23
+ if (typeof v !== 'number' || !Number.isSafeInteger(v) || v < min || v > max)
24
+ throw new HubError('INVALID_OPTIONS');
25
+ return v;
26
+ }
27
+ export function parseOptions(input) {
28
+ const v = object(input);
29
+ keys(v, [
30
+ 'mode',
31
+ 'allowInCluster',
32
+ 'namespace',
33
+ 'serverId',
34
+ 'redisConnection',
35
+ 'natsConnection',
36
+ 'host',
37
+ 'advertiseHost',
38
+ 'port',
39
+ 'secret',
40
+ 'leaseMs',
41
+ 'pollMs',
42
+ 'ownerTtlMs',
43
+ 'startupMs',
44
+ 'maxFrameBytes',
45
+ 'maxPayloadBytes',
46
+ 'maxConnections',
47
+ 'maxOwners',
48
+ 'maxTotalConnections',
49
+ 'maxPending',
50
+ 'queueBytes',
51
+ 'deliveryTimeoutMs',
52
+ 'retryMs',
53
+ 'maxDeliveries',
54
+ 'deliveryBytes',
55
+ ]);
56
+ const id = (key) => {
57
+ const x = v[key];
58
+ if (typeof x !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(x))
59
+ throw new HubError('INVALID_OPTIONS');
60
+ return x;
61
+ };
62
+ const host = (key, fallback) => {
63
+ const x = v[key] === undefined ? fallback : v[key];
64
+ if (typeof x !== 'string' ||
65
+ !x ||
66
+ x.length > 253 ||
67
+ [...x].some((c) => c.charCodeAt(0) <= 32 || /\s/.test(c)))
68
+ throw new HubError('INVALID_OPTIONS');
69
+ return x;
70
+ };
71
+ const num = (k, d, min, max) => integer(v[k] === undefined ? d : v[k], min, max);
72
+ const mode = v.mode === undefined ? 'local' : v.mode;
73
+ if (mode !== 'local' && mode !== 'cluster')
74
+ throw new HubError('INVALID_OPTIONS');
75
+ if (v.allowInCluster !== undefined && typeof v.allowInCluster !== 'boolean')
76
+ throw new HubError('INVALID_OPTIONS');
77
+ const cluster = mode === 'cluster';
78
+ // Cluster mode shares state through Redis and authenticates peers with the secret.
79
+ if (cluster && (v.namespace === undefined || v.serverId === undefined))
80
+ throw new HubError('INVALID_OPTIONS');
81
+ if (cluster && v.redisConnection === undefined)
82
+ throw new HubError('REDIS_REQUIRED');
83
+ if ((cluster || v.secret !== undefined) &&
84
+ (typeof v.secret !== 'string' ||
85
+ Buffer.byteLength(v.secret) < 32 ||
86
+ Buffer.byteLength(v.secret) > 256))
87
+ throw new HubError('SECRET_REQUIRED');
88
+ const optional = (key, fallback) => (v[key] === undefined ? fallback : id(key));
89
+ const leaseMs = num('leaseMs', 3000, 500, 60000), pollMs = num('pollMs', 500, 25, 10000), ownerTtlMs = num('ownerTtlMs', 15000, 1500, 120000);
90
+ if (pollMs * 3 > leaseMs || ownerTtlMs < leaseMs * 3)
91
+ throw new HubError('INVALID_OPTIONS');
92
+ const maxFrameBytes = num('maxFrameBytes', 1048576, 16384, 4194304), maxPayloadBytes = num('maxPayloadBytes', 65536, 1, 262144);
93
+ if (Math.ceil(maxPayloadBytes / 3) * 4 + 8192 > maxFrameBytes)
94
+ throw new HubError('INVALID_OPTIONS');
95
+ return {
96
+ mode,
97
+ allowInCluster: v.allowInCluster === true,
98
+ namespace: optional('namespace', 'local'),
99
+ serverId: optional('serverId', 'local'),
100
+ redisConnection: optional('redisConnection'),
101
+ natsConnection: optional('natsConnection'),
102
+ secret: typeof v.secret === 'string' ? v.secret : '',
103
+ host: host('host', '127.0.0.1'),
104
+ advertiseHost: host('advertiseHost', '127.0.0.1'),
105
+ port: num('port', 0, 0, 65535),
106
+ leaseMs,
107
+ pollMs,
108
+ ownerTtlMs,
109
+ startupMs: num('startupMs', 15000, 1000, 120000),
110
+ maxFrameBytes,
111
+ maxPayloadBytes,
112
+ maxConnections: num('maxConnections', 128, 1, 4096),
113
+ maxOwners: num('maxOwners', 64, 1, 1024),
114
+ maxTotalConnections: num('maxTotalConnections', 8192, 1, 100000),
115
+ maxPending: num('maxPending', 128, 1, 4096),
116
+ deliveryTimeoutMs: num('deliveryTimeoutMs', 60000, 1000, 120000),
117
+ retryMs: num('retryMs', 1000, 100, 5000),
118
+ maxDeliveries: num('maxDeliveries', 10000, 1, 100000),
119
+ deliveryBytes: num('deliveryBytes', 67108864, 16384, 268435456),
120
+ queueBytes: num('queueBytes', 4194304, maxFrameBytes, 67108864),
121
+ };
122
+ }
@@ -0,0 +1,24 @@
1
+ import { EventQueue } from './event-queue.js';
2
+ import type { HubOptions } from './options.js';
3
+ import { type HubConnection, type HubLeader, type HubQuery, type HubReceipt, type HubRecord, type HubRegistration, type HubSnapshot } from './types.js';
4
+ export declare class PeerClient {
5
+ #private;
6
+ readonly options: HubOptions;
7
+ readonly ownerEpoch: `${string}-${string}-${string}-${string}-${string}`;
8
+ /** Session of the last hello; the owner record in Redis carries the same value. */
9
+ get session(): string | undefined;
10
+ readonly events: EventQueue;
11
+ constructor(options: HubOptions, onFail?: (code: string) => void);
12
+ get ready(): boolean;
13
+ get leader(): HubLeader | undefined;
14
+ get connections(): Map<string, HubRecord>;
15
+ connect(leader: HubLeader): Promise<void>;
16
+ register(input: HubRegistration): Promise<HubConnection>;
17
+ list(input: HubQuery): Promise<HubSnapshot>;
18
+ broadcast(input: HubQuery, data: Uint8Array): Promise<HubReceipt>;
19
+ acknowledge(id: string, connections: readonly string[]): void;
20
+ kick(input: HubQuery, code?: number, reason?: string): Promise<HubReceipt>;
21
+ close(): Promise<void>;
22
+ disconnect(): void;
23
+ whenReady(timeoutMs: number): Promise<boolean>;
24
+ }