@dokebi/websocket 0.3.0 → 0.4.1
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/AI.md +138 -96
- package/README.md +74 -59
- package/dist/errors.d.ts +11 -0
- package/dist/errors.js +38 -0
- package/dist/gateway.js +125 -73
- package/dist/index.d.ts +3 -0
- package/dist/index.js +19 -21
- package/dist/options.d.ts +15 -25
- package/dist/options.js +38 -40
- package/dist/router.d.ts +1 -1
- package/dist/router.js +32 -10
- package/dist/transport.d.ts +30 -0
- package/dist/transport.js +72 -0
- package/options.schema.json +33 -6
- package/package.json +35 -12
- package/dist/log.d.ts +0 -25
- package/dist/log.js +0 -102
package/dist/gateway.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { isUtf8 } from 'node:buffer';
|
|
2
2
|
import { randomUUID } from 'node:crypto';
|
|
3
3
|
import { setTimeout as delay, setImmediate as immediate } from 'node:timers/promises';
|
|
4
|
+
import { diagnostics } from '@dokebi/core/libraries';
|
|
4
5
|
import fastifyWebsocket from '@fastify/websocket';
|
|
5
6
|
import { WebSocket } from 'ws';
|
|
6
|
-
import {
|
|
7
|
+
import { WebsocketError } from './errors.js';
|
|
7
8
|
import { PLAIN_PROTOCOL, SEAL_PROTOCOL, } from './types.js';
|
|
8
9
|
const TEXT = Object.freeze({ binary: false });
|
|
9
10
|
const BINARY = Object.freeze({ binary: true });
|
|
@@ -17,9 +18,7 @@ const TYPE = /^[A-Za-z][A-Za-z0-9._:-]{0,63}$/;
|
|
|
17
18
|
/** Hub calls a `tenantPrefix` broadcast or kick runs at once. */
|
|
18
19
|
const FAN_OUT = 16;
|
|
19
20
|
const encoder = new TextEncoder();
|
|
20
|
-
|
|
21
|
-
return Object.assign(new Error(message), { code });
|
|
22
|
-
}
|
|
21
|
+
const { describeError, errorCode, Repeats } = diagnostics;
|
|
23
22
|
/** A host without its port, lower case; IPv6 literals keep their brackets (like the browser). */
|
|
24
23
|
function withoutPort(host) {
|
|
25
24
|
const raw = host.toLowerCase();
|
|
@@ -42,7 +41,7 @@ function checkFilter(filter) {
|
|
|
42
41
|
(value.tenantPrefix !== undefined && !filterText(value.tenantPrefix)) ||
|
|
43
42
|
(value.room !== undefined && !filterText(value.room)) ||
|
|
44
43
|
(value.member !== undefined && !filterText(value.member)))
|
|
45
|
-
throw
|
|
44
|
+
throw new WebsocketError('INVALID_FILTER', 'A websocket filter is { tenant } or { tenantPrefix }, with room? and member?, strings of 1 to 256 bytes');
|
|
46
45
|
return value;
|
|
47
46
|
}
|
|
48
47
|
function connectionInfo(record) {
|
|
@@ -59,7 +58,7 @@ function connectionInfo(record) {
|
|
|
59
58
|
function sealOf(route) {
|
|
60
59
|
const value = route.seal;
|
|
61
60
|
if (value !== undefined && typeof value !== 'boolean' && typeof value !== 'function')
|
|
62
|
-
throw new
|
|
61
|
+
throw new WebsocketError('INVALID_ROUTE', 'Invalid websocket route');
|
|
63
62
|
return value;
|
|
64
63
|
}
|
|
65
64
|
/** Allow-list entries must be exact http(s) origins such as `https://app.example.com`. */
|
|
@@ -69,7 +68,7 @@ function parseOrigins(value) {
|
|
|
69
68
|
if (value === '*')
|
|
70
69
|
return '*';
|
|
71
70
|
if (!Array.isArray(value))
|
|
72
|
-
throw new
|
|
71
|
+
throw new WebsocketError('INVALID_ROUTE', 'Invalid websocket route');
|
|
73
72
|
const result = new Set();
|
|
74
73
|
for (const item of value) {
|
|
75
74
|
let url;
|
|
@@ -77,10 +76,10 @@ function parseOrigins(value) {
|
|
|
77
76
|
url = typeof item === 'string' ? new URL(item) : undefined;
|
|
78
77
|
}
|
|
79
78
|
catch (error) {
|
|
80
|
-
throw new
|
|
79
|
+
throw new WebsocketError('INVALID_ROUTE', 'Invalid websocket route', { cause: error });
|
|
81
80
|
}
|
|
82
81
|
if (!url || (url.protocol !== 'http:' && url.protocol !== 'https:') || url.origin !== item)
|
|
83
|
-
throw new
|
|
82
|
+
throw new WebsocketError('INVALID_ROUTE', 'Invalid websocket route');
|
|
84
83
|
result.add(url.origin);
|
|
85
84
|
}
|
|
86
85
|
return result;
|
|
@@ -122,6 +121,19 @@ function aborted(signal) {
|
|
|
122
121
|
signal.addEventListener('abort', () => resolve(), { once: true });
|
|
123
122
|
});
|
|
124
123
|
}
|
|
124
|
+
/**
|
|
125
|
+
* Folds `change` into `buffer`: a peer that joined and then left (or left and then joined)
|
|
126
|
+
* before the handler saw either cancels out, so the buffer holds the net change and never more
|
|
127
|
+
* peers than the tenant has.
|
|
128
|
+
*/
|
|
129
|
+
function mergePresence(buffer, change) {
|
|
130
|
+
for (const peer of change.joined)
|
|
131
|
+
if (!buffer.left.delete(peer.connection))
|
|
132
|
+
buffer.joined.set(peer.connection, peer);
|
|
133
|
+
for (const peer of change.left)
|
|
134
|
+
if (!buffer.joined.delete(peer.connection))
|
|
135
|
+
buffer.left.set(peer.connection, peer);
|
|
136
|
+
}
|
|
125
137
|
export class Gateway {
|
|
126
138
|
context;
|
|
127
139
|
web;
|
|
@@ -155,7 +167,7 @@ export class Gateway {
|
|
|
155
167
|
this.settings = settings;
|
|
156
168
|
this.codecs = codecs;
|
|
157
169
|
const self = this;
|
|
158
|
-
this.#throttle = new
|
|
170
|
+
this.#throttle = new Repeats({ logger: context.logger });
|
|
159
171
|
this.api = Object.freeze({
|
|
160
172
|
get connections() {
|
|
161
173
|
return self.#clients.size;
|
|
@@ -163,38 +175,36 @@ export class Gateway {
|
|
|
163
175
|
sealing: codecs !== undefined,
|
|
164
176
|
route: (route) => {
|
|
165
177
|
if (this.#frozen || context.app.state !== 'starting')
|
|
166
|
-
throw new
|
|
178
|
+
throw new WebsocketError('FROZEN', 'Register websocket routes during setup');
|
|
167
179
|
if (!route.path.startsWith('/') ||
|
|
168
180
|
typeof route.authenticate !== 'function' ||
|
|
169
181
|
typeof route.message !== 'function')
|
|
170
|
-
throw new
|
|
182
|
+
throw new WebsocketError('INVALID_ROUTE', 'Invalid websocket route');
|
|
171
183
|
const origins = parseOrigins(route.origins);
|
|
172
184
|
const seal = sealOf(route);
|
|
173
185
|
// Fail closed: a route that may seal must not quietly run in plain text.
|
|
174
186
|
if (seal && !codecs)
|
|
175
|
-
throw
|
|
187
|
+
throw new WebsocketError('SEAL_PROVIDER_MISSING', `WebSocket route ${route.path} is sealed; register the dokebi-seal plugin`);
|
|
176
188
|
this.#routes.push({ route: { ...route }, origins });
|
|
177
189
|
},
|
|
178
190
|
list: (filter) => this.#list(filter),
|
|
179
191
|
broadcast: (filter, data) => this.#broadcast(filter, data),
|
|
180
192
|
send: (filter, type, data) => {
|
|
181
193
|
if (typeof type !== 'string' || !TYPE.test(type))
|
|
182
|
-
return Promise.reject(
|
|
194
|
+
return Promise.reject(new WebsocketError('INVALID_TYPE', 'Message types match ' + TYPE.source));
|
|
183
195
|
let text;
|
|
184
196
|
try {
|
|
185
197
|
text = JSON.stringify(data === undefined ? { type } : { type, data });
|
|
186
198
|
}
|
|
187
199
|
catch (error) {
|
|
188
|
-
return Promise.reject(
|
|
189
|
-
code: 'INVALID_DATA',
|
|
190
|
-
}));
|
|
200
|
+
return Promise.reject(new WebsocketError('INVALID_DATA', 'Message data is not JSON', { cause: error }));
|
|
191
201
|
}
|
|
192
202
|
return this.#broadcast(filter, text);
|
|
193
203
|
},
|
|
194
204
|
kick: (filter, code, reason) => this.#kick(filter, code, reason),
|
|
195
205
|
onPresence: (listener) => {
|
|
196
206
|
if (typeof listener !== 'function')
|
|
197
|
-
throw new
|
|
207
|
+
throw new WebsocketError('INVALID_ARGUMENT', 'Invalid presence listener');
|
|
198
208
|
this.#listeners.add(listener);
|
|
199
209
|
context.logger.log('debug', 'WebSocket presence listener added', {
|
|
200
210
|
listeners: this.#listeners.size,
|
|
@@ -214,7 +224,7 @@ export class Gateway {
|
|
|
214
224
|
this.#frozen = true;
|
|
215
225
|
await scope.register(fastifyWebsocket, {
|
|
216
226
|
options: {
|
|
217
|
-
maxPayload: settings.
|
|
227
|
+
maxPayload: settings.maxPayloadBytes,
|
|
218
228
|
perMessageDeflate: false,
|
|
219
229
|
// D-0059 §4: a client with a seal bridge offers `dokebi.seal` and `dokebi.plain`.
|
|
220
230
|
// A sealed upgrade selects `dokebi.seal` only (never plain; not offered: 4415 after the
|
|
@@ -228,7 +238,7 @@ export class Gateway {
|
|
|
228
238
|
},
|
|
229
239
|
// A wsHandler that threw: the client gets 1011, the cause goes to the log (D-0047).
|
|
230
240
|
errorHandler: (error, socket) => {
|
|
231
|
-
this.#throttle.
|
|
241
|
+
this.#throttle.log('error', 'WebSocket handler failed', 'SOCKET_FAILURE', error);
|
|
232
242
|
socket.close(1011, 'Socket failure');
|
|
233
243
|
},
|
|
234
244
|
});
|
|
@@ -291,7 +301,7 @@ export class Gateway {
|
|
|
291
301
|
#send(value, data) {
|
|
292
302
|
const socket = value.socket;
|
|
293
303
|
if (socket.readyState !== WebSocket.OPEN)
|
|
294
|
-
return Promise.reject(
|
|
304
|
+
return Promise.reject(new WebsocketError('SOCKET_CLOSED', 'Socket closed'));
|
|
295
305
|
if (value.codec) {
|
|
296
306
|
// Sealed connections carry text only: UTF-8 bytes are sent as text, other bytes refused.
|
|
297
307
|
let text;
|
|
@@ -300,22 +310,20 @@ export class Gateway {
|
|
|
300
310
|
else {
|
|
301
311
|
const buffer = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
|
|
302
312
|
if (!isUtf8(buffer))
|
|
303
|
-
return Promise.reject(
|
|
313
|
+
return Promise.reject(new WebsocketError('SEAL_BINARY_UNSUPPORTED', 'Binary data cannot be sent on a sealed socket'));
|
|
304
314
|
text = buffer.toString();
|
|
305
315
|
}
|
|
306
316
|
try {
|
|
307
317
|
data = value.codec.encode(text);
|
|
308
318
|
}
|
|
309
319
|
catch (error) {
|
|
310
|
-
return Promise.reject(
|
|
311
|
-
code: 'SEAL_ENCODE_FAILED',
|
|
312
|
-
}));
|
|
320
|
+
return Promise.reject(new WebsocketError('SEAL_ENCODE_FAILED', 'Sealing a frame failed', { cause: error }));
|
|
313
321
|
}
|
|
314
322
|
}
|
|
315
323
|
const bytes = typeof data === 'string' ? Buffer.byteLength(data) : data.byteLength;
|
|
316
324
|
if (socket.bufferedAmount + bytes > this.settings.maxBufferedBytes) {
|
|
317
325
|
this.#slow(socket);
|
|
318
|
-
return Promise.reject(
|
|
326
|
+
return Promise.reject(new WebsocketError('SLOW_CONSUMER', 'Socket backpressure'));
|
|
319
327
|
}
|
|
320
328
|
return this.#watch(new Promise((resolve, reject) => socket.send(data, (error) => (error ? reject(error) : resolve()))));
|
|
321
329
|
}
|
|
@@ -341,7 +349,7 @@ export class Gateway {
|
|
|
341
349
|
this.#sends++;
|
|
342
350
|
socket.send(frame, kind, (error) => {
|
|
343
351
|
if (error) {
|
|
344
|
-
this.#throttle.
|
|
352
|
+
this.#throttle.log('error', 'WebSocket broadcast write failed; socket terminated', 'BROADCAST_WRITE_FAILED', error);
|
|
345
353
|
socket.terminate();
|
|
346
354
|
}
|
|
347
355
|
if (--this.#sends === 0 && this.#sendsIdle) {
|
|
@@ -409,7 +417,7 @@ export class Gateway {
|
|
|
409
417
|
hello = codec.hello();
|
|
410
418
|
}
|
|
411
419
|
catch (error) {
|
|
412
|
-
this.#throttle.
|
|
420
|
+
this.#throttle.log('error', 'WebSocket seal codec failed; closed', 'SEAL_CODEC_FAILED', error, { connection: id });
|
|
413
421
|
socket.close(1011, 'Socket failure');
|
|
414
422
|
return;
|
|
415
423
|
}
|
|
@@ -417,7 +425,9 @@ export class Gateway {
|
|
|
417
425
|
// reports 'open' only after it (D-0059 §4).
|
|
418
426
|
socket.send(hello, TEXT, (error) => {
|
|
419
427
|
if (error)
|
|
420
|
-
this.#throttle.
|
|
428
|
+
this.#throttle.log('warn', 'WebSocket seal hello not sent', 'SEAL_HELLO_FAILED', error, {
|
|
429
|
+
connection: id,
|
|
430
|
+
});
|
|
421
431
|
});
|
|
422
432
|
if (this.context.logger.isEnabled('debug'))
|
|
423
433
|
this.context.logger.log('debug', 'WebSocket seal hello sent', { connection: id });
|
|
@@ -429,6 +439,8 @@ export class Gateway {
|
|
|
429
439
|
session: undefined,
|
|
430
440
|
tail: Promise.resolve(),
|
|
431
441
|
pending: 0,
|
|
442
|
+
presencePending: 0,
|
|
443
|
+
presenceBuffer: undefined,
|
|
432
444
|
registration: undefined,
|
|
433
445
|
alive: true,
|
|
434
446
|
failed: false,
|
|
@@ -461,7 +473,7 @@ export class Gateway {
|
|
|
461
473
|
join: async (room) => {
|
|
462
474
|
if (!route.authorizeRoom || !(await route.authorizeRoom(identity, room))) {
|
|
463
475
|
this.context.logger.log('debug', 'WebSocket room refused', { connection: id });
|
|
464
|
-
throw new
|
|
476
|
+
throw new WebsocketError('ROOM_FORBIDDEN', 'Room access denied');
|
|
465
477
|
}
|
|
466
478
|
await value.registration?.join(room);
|
|
467
479
|
this.context.logger.log('debug', 'WebSocket room joined', {
|
|
@@ -484,11 +496,11 @@ export class Gateway {
|
|
|
484
496
|
// repeats are counted per type and reply code; client errors are counted per code only.
|
|
485
497
|
reportError: (error, details) => {
|
|
486
498
|
if (details.source === 'handler') {
|
|
487
|
-
this.#throttle.
|
|
499
|
+
this.#throttle.log('error', 'WebSocket handler failed.', 'SOCKET_HANDLER_FAILED', error === undefined ? 'NonError: undefined' : error, // `throw undefined` still shows
|
|
488
500
|
{ type: details.type ?? null, reply: details.code, connection: id }, `${details.type ?? ''}\u0000${details.code}`);
|
|
489
501
|
return;
|
|
490
502
|
}
|
|
491
|
-
this.#throttle.
|
|
503
|
+
this.#throttle.log('debug', 'WebSocket client message refused', details.code, error, {
|
|
492
504
|
type: details.type?.slice(0, 64) ?? null,
|
|
493
505
|
connection: id,
|
|
494
506
|
});
|
|
@@ -509,7 +521,7 @@ export class Gateway {
|
|
|
509
521
|
const registered = value.tail;
|
|
510
522
|
void value.tail.catch((error) => {
|
|
511
523
|
// Converted to a close code (4409 or 1013) for the client; logged here for the operator.
|
|
512
|
-
this.#throttle.
|
|
524
|
+
this.#throttle.log('warn', 'WebSocket registration failed', errorCode(error, 'REGISTRATION_FAILED'), error, { connection: id });
|
|
513
525
|
value.failed = true;
|
|
514
526
|
// The same (tenant, member, clientId) is already connected (D-0025): a client error, not
|
|
515
527
|
// a hub outage. A client that retries with the same clientId is refused again.
|
|
@@ -525,16 +537,20 @@ export class Gateway {
|
|
|
525
537
|
});
|
|
526
538
|
// ws emits 'close' after 'error'; the close cleans up, the error is reported here.
|
|
527
539
|
socket.on('error', (error) => {
|
|
528
|
-
this.#throttle.
|
|
540
|
+
this.#throttle.log('error', 'WebSocket socket error', 'SOCKET_ERROR', error, {
|
|
529
541
|
reason: errorCode(error, 'UNKNOWN'),
|
|
530
542
|
});
|
|
531
543
|
});
|
|
532
544
|
// Attach synchronously, before awaiting Redis/TCP registration, so early frames are queued.
|
|
533
545
|
socket.on('message', (raw, isBinary) => {
|
|
534
546
|
value.seen = performance.now();
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
547
|
+
// ws hands each message its own Buffer (unmasked once, never reused): take it as it is
|
|
548
|
+
// instead of copying every frame (D-0068). Fragments are joined; an ArrayBuffer is wrapped.
|
|
549
|
+
const bytes = Buffer.isBuffer(raw)
|
|
550
|
+
? raw
|
|
551
|
+
: Array.isArray(raw)
|
|
552
|
+
? Buffer.concat(raw)
|
|
553
|
+
: Buffer.from(raw);
|
|
538
554
|
if (codec) {
|
|
539
555
|
// Sealed: the frame is opened in this connection's order chain, then handled like a
|
|
540
556
|
// plain one (control frames, then the route). Nothing is read before it opens.
|
|
@@ -590,7 +606,7 @@ export class Gateway {
|
|
|
590
606
|
});
|
|
591
607
|
void this.#watch(cleanup).catch((error) => {
|
|
592
608
|
// The hub drops this connection when it recovers (owner snapshot or expiry).
|
|
593
|
-
this.#throttle.
|
|
609
|
+
this.#throttle.log('error', 'WebSocket presence cleanup deferred to hub recovery', 'PRESENCE_CLEANUP_DEFERRED', error, { connection: id });
|
|
594
610
|
});
|
|
595
611
|
});
|
|
596
612
|
}
|
|
@@ -612,7 +628,7 @@ export class Gateway {
|
|
|
612
628
|
// A page loaded before D-0057 still acknowledges broadcasts: nothing to do, and no
|
|
613
629
|
// reason to close it. Counted at debug until it reloads.
|
|
614
630
|
if (control?.$dokebi === 'ack-v1') {
|
|
615
|
-
this.#throttle.
|
|
631
|
+
this.#throttle.log('debug', 'WebSocket ACK from an old client ignored', 'ACK_IGNORED', undefined, { connection: id });
|
|
616
632
|
return true;
|
|
617
633
|
}
|
|
618
634
|
return false;
|
|
@@ -621,22 +637,30 @@ export class Gateway {
|
|
|
621
637
|
* A sealed frame that did not open (plain text, binary, drift, replay, bad seal): 4400 and the
|
|
622
638
|
* connection takes nothing more. The reason goes to the log only, never to the client: telling
|
|
623
639
|
* `replay` from `drift` would let an attacker probe the defence (D-0059 §4).
|
|
640
|
+
* One exception: `capacity` (the in-process nonce store is full of live nonces, D-0075) is the
|
|
641
|
+
* server's state, not the frame's, so it closes with 1013 `Try again later` and the client
|
|
642
|
+
* reconnects with backoff.
|
|
624
643
|
*/
|
|
625
644
|
#refuse(value, id, error) {
|
|
626
645
|
const given = error?.reason;
|
|
627
646
|
const reason = typeof given === 'string' && REASON.test(given) ? given : 'unknown';
|
|
628
647
|
value.failed = true;
|
|
629
|
-
|
|
648
|
+
if (reason === 'capacity') {
|
|
649
|
+
this.#throttle.log('warn', 'WebSocket sealed frame refused: replay nonce store full; closed', 'SEAL_FRAME_REFUSED', error, { connection: id, reason }, reason);
|
|
650
|
+
value.socket.close(1013, 'Try again later');
|
|
651
|
+
return;
|
|
652
|
+
}
|
|
653
|
+
this.#throttle.log('warn', 'WebSocket sealed frame refused; closed', 'SEAL_FRAME_REFUSED', error, { connection: id, reason }, reason);
|
|
630
654
|
value.socket.close(BAD_FRAME, 'Bad frame');
|
|
631
655
|
}
|
|
632
656
|
/** Runs `work` after this connection's earlier messages and presence calls, in order. */
|
|
633
657
|
#enqueue(value, id, work) {
|
|
634
658
|
const socket = value.socket;
|
|
635
|
-
if (++value.pending > this.settings.
|
|
659
|
+
if (++value.pending > this.settings.maxPending) {
|
|
636
660
|
value.pending--;
|
|
637
661
|
// The server closing a client is worth seeing (like SLOW_CONSUMER): usually a handler
|
|
638
662
|
// that waits long (a slow database call) while the client keeps sending.
|
|
639
|
-
this.#throttle.
|
|
663
|
+
this.#throttle.log('warn', 'WebSocket message queue full; closed', 'TOO_MANY_MESSAGES', undefined, {
|
|
640
664
|
connection: id,
|
|
641
665
|
pending: value.pending,
|
|
642
666
|
});
|
|
@@ -655,10 +679,10 @@ export class Gateway {
|
|
|
655
679
|
if (code === 'SLOW_CONSUMER')
|
|
656
680
|
return;
|
|
657
681
|
if (code === 'SOCKET_CLOSED') {
|
|
658
|
-
this.#throttle.
|
|
682
|
+
this.#throttle.log('warn', 'WebSocket reply dropped; socket closed', 'REPLY_DROPPED', error, { connection: id });
|
|
659
683
|
return;
|
|
660
684
|
}
|
|
661
|
-
this.#throttle.
|
|
685
|
+
this.#throttle.log('error', 'WebSocket message handler failed', errorCode(error, 'HANDLER_FAILED'), error, { connection: id });
|
|
662
686
|
socket.close(1011, 'Message failed');
|
|
663
687
|
})
|
|
664
688
|
.finally(() => {
|
|
@@ -723,25 +747,57 @@ export class Gateway {
|
|
|
723
747
|
!value.registration ||
|
|
724
748
|
value.socket.readyState !== WebSocket.OPEN)
|
|
725
749
|
continue;
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
left:
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
const code = error?.code;
|
|
736
|
-
if (code === 'SLOW_CONSUMER')
|
|
737
|
-
return; // Logged where the socket was closed.
|
|
738
|
-
this.#throttle.report(code === 'SOCKET_CLOSED' ? 'warn' : 'error', code === 'SOCKET_CLOSED'
|
|
739
|
-
? 'WebSocket presence dropped; socket closed'
|
|
740
|
-
: 'WebSocket presence handler failed', code === 'SOCKET_CLOSED' ? 'REPLY_DROPPED' : 'PRESENCE_HANDLER_FAILED', error, { connection: session.id });
|
|
741
|
-
});
|
|
742
|
-
this.#watch(value.tail);
|
|
750
|
+
// At most maxPending presence calls wait per connection (like its messages); changes
|
|
751
|
+
// that come while that many wait are merged and handed over when a call ends.
|
|
752
|
+
if (value.presencePending >= this.settings.maxPending) {
|
|
753
|
+
value.presenceBuffer ??= { joined: new Map(), left: new Map() };
|
|
754
|
+
mergePresence(value.presenceBuffer, change);
|
|
755
|
+
this.#throttle.log('warn', 'WebSocket presence changes merged; handler behind', 'PRESENCE_MERGED', undefined, { connection: session.id, maxPending: this.settings.maxPending });
|
|
756
|
+
continue;
|
|
757
|
+
}
|
|
758
|
+
this.#presenceCall(value, route, session, change.joined, change.left);
|
|
743
759
|
}
|
|
744
760
|
}
|
|
761
|
+
/** Queues one presence call on the connection, in order with its messages. */
|
|
762
|
+
#presenceCall(value, route, session, joined, left) {
|
|
763
|
+
const presence = Object.freeze({
|
|
764
|
+
tenant: session.identity.tenant,
|
|
765
|
+
joined: Object.freeze([...joined]),
|
|
766
|
+
left: Object.freeze([...left]),
|
|
767
|
+
});
|
|
768
|
+
value.presencePending++;
|
|
769
|
+
// In order with this connection's messages, like a message handler.
|
|
770
|
+
value.tail = value.tail
|
|
771
|
+
.then(() => route.presence?.(presence, session))
|
|
772
|
+
.then(() => { }, (error) => {
|
|
773
|
+
const code = error?.code;
|
|
774
|
+
if (code === 'SLOW_CONSUMER')
|
|
775
|
+
return; // Logged where the socket was closed.
|
|
776
|
+
this.#throttle.log(code === 'SOCKET_CLOSED' ? 'warn' : 'error', code === 'SOCKET_CLOSED'
|
|
777
|
+
? 'WebSocket presence dropped; socket closed'
|
|
778
|
+
: 'WebSocket presence handler failed', code === 'SOCKET_CLOSED' ? 'REPLY_DROPPED' : 'PRESENCE_HANDLER_FAILED', error, { connection: session.id });
|
|
779
|
+
})
|
|
780
|
+
.finally(() => {
|
|
781
|
+
value.presencePending--;
|
|
782
|
+
const buffer = value.presenceBuffer;
|
|
783
|
+
if (!buffer)
|
|
784
|
+
return;
|
|
785
|
+
value.presenceBuffer = undefined;
|
|
786
|
+
const open = !value.failed && value.registration && value.socket.readyState === WebSocket.OPEN;
|
|
787
|
+
if (this.context.logger.isEnabled('debug'))
|
|
788
|
+
this.context.logger.log('debug', open ? 'WebSocket merged presence handed over' : 'WebSocket merged presence dropped', {
|
|
789
|
+
connection: session.id,
|
|
790
|
+
joined: buffer.joined.size,
|
|
791
|
+
left: buffer.left.size,
|
|
792
|
+
...(open ? {} : { reason: 'socket closing' }),
|
|
793
|
+
});
|
|
794
|
+
// Everything cancelled out, or the socket is closing: nothing to tell.
|
|
795
|
+
if (!open || (!buffer.joined.size && !buffer.left.size))
|
|
796
|
+
return;
|
|
797
|
+
this.#presenceCall(value, route, session, [...buffer.joined.values()], [...buffer.left.values()]);
|
|
798
|
+
});
|
|
799
|
+
this.#watch(value.tail);
|
|
800
|
+
}
|
|
745
801
|
/** Records of the presence mirror (every server, as the hub reported them) that match. */
|
|
746
802
|
#mirror(filter) {
|
|
747
803
|
const result = [];
|
|
@@ -803,7 +859,7 @@ export class Gateway {
|
|
|
803
859
|
async #broadcast(input, data) {
|
|
804
860
|
const filter = checkFilter(input);
|
|
805
861
|
if (typeof data !== 'string' && !(data instanceof Uint8Array))
|
|
806
|
-
throw
|
|
862
|
+
throw new WebsocketError('INVALID_DATA', 'Broadcast data is a string or a Uint8Array');
|
|
807
863
|
const bytes = typeof data === 'string' ? encoder.encode(data) : data;
|
|
808
864
|
const queries = this.#queries(filter);
|
|
809
865
|
// A single tenant keeps the hub's own error (RECOVERING, BUSY, OUTCOME_UNKNOWN).
|
|
@@ -832,9 +888,7 @@ export class Gateway {
|
|
|
832
888
|
bytes: bytes.byteLength,
|
|
833
889
|
});
|
|
834
890
|
if (failures.length)
|
|
835
|
-
throw Object.assign(new
|
|
836
|
-
cause: new AggregateError(failures, 'Hub broadcast failures'),
|
|
837
|
-
}), { code: errorCode(failures[0], 'BROADCAST_FAILED'), receipt });
|
|
891
|
+
throw Object.assign(new WebsocketError(errorCode(failures[0], 'BROADCAST_FAILED'), `WebSocket broadcast failed for ${failures.length} of ${queries.length} tenants`, { cause: new AggregateError(failures, 'Hub broadcast failures'), data: { receipt } }), { receipt });
|
|
838
892
|
return receipt;
|
|
839
893
|
}
|
|
840
894
|
async #kick(input, code, reason) {
|
|
@@ -854,9 +908,7 @@ export class Gateway {
|
|
|
854
908
|
if (failures.length === 1 && queries.length === 1)
|
|
855
909
|
throw failures[0];
|
|
856
910
|
if (failures.length)
|
|
857
|
-
throw Object.assign(new
|
|
858
|
-
cause: new AggregateError(failures, 'Hub kick failures'),
|
|
859
|
-
}), { code: errorCode(failures[0], 'KICK_FAILED'), receipt });
|
|
911
|
+
throw Object.assign(new WebsocketError(errorCode(failures[0], 'KICK_FAILED'), `WebSocket kick failed for ${failures.length} of ${queries.length} tenants`, { cause: new AggregateError(failures, 'Hub kick failures'), data: { receipt } }), { receipt });
|
|
860
912
|
return receipt;
|
|
861
913
|
}
|
|
862
914
|
/** Hands each tenant's change to the `api.onPresence` listeners; their failures are logged. */
|
|
@@ -868,7 +920,7 @@ export class Gateway {
|
|
|
868
920
|
left: Object.freeze([...change.left]),
|
|
869
921
|
});
|
|
870
922
|
for (const listener of this.#listeners) {
|
|
871
|
-
const failed = (error) => this.#throttle.
|
|
923
|
+
const failed = (error) => this.#throttle.log('error', 'WebSocket presence listener failed', 'PRESENCE_LISTENER_FAILED', error);
|
|
872
924
|
try {
|
|
873
925
|
const result = listener(presence);
|
|
874
926
|
if (result && typeof result.then === 'function')
|
|
@@ -928,7 +980,7 @@ export class Gateway {
|
|
|
928
980
|
sealedFrame = value.codec.encode(text);
|
|
929
981
|
}
|
|
930
982
|
catch (error) {
|
|
931
|
-
this.#throttle.
|
|
983
|
+
this.#throttle.log('error', 'WebSocket broadcast not sealed; socket closed', 'SEAL_ENCODE_FAILED', error, { connection: id });
|
|
932
984
|
value.socket.close(1011, 'Socket failure');
|
|
933
985
|
continue;
|
|
934
986
|
}
|
|
@@ -936,7 +988,7 @@ export class Gateway {
|
|
|
936
988
|
this.#deliver(value.socket, sealedFrame, TEXT);
|
|
937
989
|
}
|
|
938
990
|
if (dropped)
|
|
939
|
-
this.#throttle.
|
|
991
|
+
this.#throttle.log('warn', 'WebSocket binary broadcast not sent to sealed sockets', 'SEAL_BINARY_UNSUPPORTED', undefined, { id: event.id, dropped });
|
|
940
992
|
if (this.context.logger.isEnabled('debug'))
|
|
941
993
|
this.context.logger.log('debug', 'WebSocket broadcast delivered', {
|
|
942
994
|
id: event.id,
|
|
@@ -954,7 +1006,7 @@ export class Gateway {
|
|
|
954
1006
|
// The hub ended its event stream (overflow, closed): every socket gets 1013 and reconnects.
|
|
955
1007
|
this.context.logger.log('error', 'WebSocket hub event stream failed; sockets closed', {
|
|
956
1008
|
code: 'HUB_EVENTS_FAILED',
|
|
957
|
-
error:
|
|
1009
|
+
error: describeError(error),
|
|
958
1010
|
open: this.#clients.size,
|
|
959
1011
|
});
|
|
960
1012
|
for (const value of this.#clients.values())
|
|
@@ -1002,7 +1054,7 @@ export class Gateway {
|
|
|
1002
1054
|
await this.#idle(signal, stop, false);
|
|
1003
1055
|
for (const value of this.#clients.values())
|
|
1004
1056
|
value.socket.close(1012, 'Server restarting');
|
|
1005
|
-
const deadline = performance.now() + this.settings.
|
|
1057
|
+
const deadline = performance.now() + this.settings.shutdownTimeoutMs;
|
|
1006
1058
|
while (this.#clients.size && performance.now() < deadline && !signal.aborted)
|
|
1007
1059
|
await Promise.race([delay(10), stop]);
|
|
1008
1060
|
if (this.#clients.size)
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import type { WebsocketApi } from './types.js';
|
|
2
|
+
export { WebsocketError, type WebsocketErrorCode } from './errors.js';
|
|
3
|
+
export { type Options as WebsocketOptions, options } from './options.js';
|
|
2
4
|
export * from './router.js';
|
|
5
|
+
export type { WebsocketNamespaceHandle, WebsocketNamespaceTarget, WebsocketTransport, } from './transport.js';
|
|
3
6
|
export * from './types.js';
|
|
4
7
|
/** Factory input: `{ app, options? }`. Options default to `app.config['dokebi-websocket']`. */
|
|
5
8
|
export declare const createPlugin: import("@dokebi/core").PluginFactory<WebsocketApi>;
|
package/dist/index.js
CHANGED
|
@@ -1,25 +1,22 @@
|
|
|
1
|
-
import { definePlugin, optionalDependency
|
|
1
|
+
import { definePlugin, optionalDependency } from '@dokebi/core';
|
|
2
|
+
import { dependency as web } from '@dokebi/web/dependency';
|
|
3
|
+
import { realtime } from '@dokebi/web/points';
|
|
4
|
+
// Always installed with this plugin (peer, required in the manifest): the provider's own file
|
|
5
|
+
// holds the name, package and range (D-0063 §6).
|
|
6
|
+
import { dependency as hub } from '@dokebi/websocket-hub/dependency';
|
|
7
|
+
import { WebsocketError } from './errors.js';
|
|
2
8
|
import { Gateway } from './gateway.js';
|
|
3
|
-
import {
|
|
9
|
+
import { options } from './options.js';
|
|
10
|
+
import { websocketTransport } from './transport.js';
|
|
11
|
+
export { WebsocketError } from './errors.js';
|
|
12
|
+
export { options } from './options.js';
|
|
4
13
|
export * from './router.js';
|
|
5
14
|
export * from './types.js';
|
|
6
|
-
const hub = providerDependency({
|
|
7
|
-
name: 'dokebi-websocket-hub',
|
|
8
|
-
version: '^0.3.0',
|
|
9
|
-
packageName: '@dokebi/websocket-hub',
|
|
10
|
-
load: () => import('@dokebi/websocket-hub'),
|
|
11
|
-
});
|
|
12
15
|
/**
|
|
13
16
|
* The socket codec provider (D-0059 §4): the private dokebi-seal plugin when it is registered.
|
|
14
17
|
* Looked up by name only; this package never imports @dokebi/seal.
|
|
15
18
|
*/
|
|
16
|
-
const seal = optionalDependency({ name: 'dokebi-seal', version: '^0.
|
|
17
|
-
const web = providerDependency({
|
|
18
|
-
name: 'dokebi-web',
|
|
19
|
-
version: '^0.1.0 || ^0.2.0',
|
|
20
|
-
packageName: '@dokebi/web',
|
|
21
|
-
load: () => import('@dokebi/web'),
|
|
22
|
-
});
|
|
19
|
+
const seal = optionalDependency({ name: 'dokebi-seal', version: '^0.4.0' });
|
|
23
20
|
class WebsocketRuntime {
|
|
24
21
|
#options;
|
|
25
22
|
#gateway;
|
|
@@ -29,14 +26,14 @@ class WebsocketRuntime {
|
|
|
29
26
|
setup(context) {
|
|
30
27
|
const codecs = context.getOptionalDependency(seal);
|
|
31
28
|
if (codecs !== undefined && typeof codecs?.forConnection !== 'function')
|
|
32
|
-
throw
|
|
33
|
-
code: 'SEAL_PROVIDER_INVALID',
|
|
34
|
-
});
|
|
29
|
+
throw new WebsocketError('SEAL_PROVIDER_INVALID', 'dokebi-seal does not provide forConnection');
|
|
35
30
|
context.logger.log('debug', 'WebSocket seal provider', {
|
|
36
31
|
present: codecs !== undefined,
|
|
37
32
|
sealDriftMs: this.#options.sealDriftMs,
|
|
38
33
|
});
|
|
39
34
|
this.#gateway = new Gateway(context, context.getDependency(web), context.getDependency(hub), this.#options, codecs);
|
|
35
|
+
// D-0063 §5: the `websocket` transport for dokebi-app (inert until a plugin collects it).
|
|
36
|
+
context.contribute(realtime, websocketTransport(this.#gateway.api, context.logger));
|
|
40
37
|
return this.#gateway.api;
|
|
41
38
|
}
|
|
42
39
|
start() {
|
|
@@ -49,9 +46,10 @@ class WebsocketRuntime {
|
|
|
49
46
|
/** Factory input: `{ app, options? }`. Options default to `app.config['dokebi-websocket']`. */
|
|
50
47
|
export const createPlugin = definePlugin({
|
|
51
48
|
name: 'dokebi-websocket',
|
|
52
|
-
version: '0.
|
|
53
|
-
core: '^0.
|
|
54
|
-
options
|
|
49
|
+
version: '0.4.1',
|
|
50
|
+
core: '^0.4.0',
|
|
51
|
+
options,
|
|
52
|
+
contributes: [realtime],
|
|
55
53
|
dependencies: () => [hub, web, seal],
|
|
56
54
|
instance: ({ options }) => new WebsocketRuntime(options),
|
|
57
55
|
});
|
package/dist/options.d.ts
CHANGED
|
@@ -1,26 +1,16 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
* How long an upgrade waits for the hub while it reconnects (a leader change, a rolling
|
|
17
|
-
* restart) before it is refused with 503 HUB_RECOVERING. 0 refuses at once.
|
|
18
|
-
*/
|
|
19
|
-
hubWaitMs: number;
|
|
20
|
-
/**
|
|
21
|
-
* How far the timestamp of a sealed frame may differ from this server's clock (D-0059 §4):
|
|
22
|
-
* older or newer frames are refused (4400). Replay nonces are kept twice as long.
|
|
23
|
-
*/
|
|
24
|
-
sealDriftMs: number;
|
|
25
|
-
}
|
|
1
|
+
import { type OptionsOf } from '@dokebi/core';
|
|
2
|
+
export declare const options: import("@dokebi/core").OptionsDeclaration<{
|
|
3
|
+
readonly heartbeatMs: number;
|
|
4
|
+
readonly hubWaitMs: number;
|
|
5
|
+
readonly idleTimeoutMs: number;
|
|
6
|
+
readonly maxBufferedBytes: number;
|
|
7
|
+
readonly maxConnections: number;
|
|
8
|
+
readonly maxPayloadBytes: number;
|
|
9
|
+
readonly maxPending: number;
|
|
10
|
+
readonly sealDriftMs: number;
|
|
11
|
+
readonly shutdownTimeoutMs: number;
|
|
12
|
+
}>;
|
|
13
|
+
/** The parsed options of dokebi-websocket (`options.dokebi-websocket`). */
|
|
14
|
+
export type Options = OptionsOf<typeof options>;
|
|
15
|
+
/** Parses `options.dokebi-websocket`; fails with core `INVALID_OPTIONS` (`details.issues`). */
|
|
26
16
|
export declare function parseOptions(input: unknown): Options;
|