@dokebi/websocket 0.3.0 → 0.4.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/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 { errorCode, errorText, LogThrottle } from './log.js';
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
- function coded(message, code) {
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 coded('A websocket filter is { tenant } or { tenantPrefix }, with room? and member?, strings of 1 to 256 bytes', 'INVALID_FILTER');
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 Error('Invalid websocket route');
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 Error('Invalid websocket route');
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 Error('Invalid websocket route', { cause: error });
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 Error('Invalid websocket route');
82
+ throw new WebsocketError('INVALID_ROUTE', 'Invalid websocket route');
84
83
  result.add(url.origin);
85
84
  }
86
85
  return result;
@@ -155,7 +154,7 @@ export class Gateway {
155
154
  this.settings = settings;
156
155
  this.codecs = codecs;
157
156
  const self = this;
158
- this.#throttle = new LogThrottle(context.logger);
157
+ this.#throttle = new Repeats({ logger: context.logger });
159
158
  this.api = Object.freeze({
160
159
  get connections() {
161
160
  return self.#clients.size;
@@ -163,38 +162,36 @@ export class Gateway {
163
162
  sealing: codecs !== undefined,
164
163
  route: (route) => {
165
164
  if (this.#frozen || context.app.state !== 'starting')
166
- throw new Error('Register websocket routes during setup');
165
+ throw new WebsocketError('FROZEN', 'Register websocket routes during setup');
167
166
  if (!route.path.startsWith('/') ||
168
167
  typeof route.authenticate !== 'function' ||
169
168
  typeof route.message !== 'function')
170
- throw new Error('Invalid websocket route');
169
+ throw new WebsocketError('INVALID_ROUTE', 'Invalid websocket route');
171
170
  const origins = parseOrigins(route.origins);
172
171
  const seal = sealOf(route);
173
172
  // Fail closed: a route that may seal must not quietly run in plain text.
174
173
  if (seal && !codecs)
175
- throw coded(`WebSocket route ${route.path} is sealed; register the dokebi-seal plugin`, 'SEAL_PROVIDER_MISSING');
174
+ throw new WebsocketError('SEAL_PROVIDER_MISSING', `WebSocket route ${route.path} is sealed; register the dokebi-seal plugin`);
176
175
  this.#routes.push({ route: { ...route }, origins });
177
176
  },
178
177
  list: (filter) => this.#list(filter),
179
178
  broadcast: (filter, data) => this.#broadcast(filter, data),
180
179
  send: (filter, type, data) => {
181
180
  if (typeof type !== 'string' || !TYPE.test(type))
182
- return Promise.reject(coded('Message types match ' + TYPE.source, 'INVALID_TYPE'));
181
+ return Promise.reject(new WebsocketError('INVALID_TYPE', 'Message types match ' + TYPE.source));
183
182
  let text;
184
183
  try {
185
184
  text = JSON.stringify(data === undefined ? { type } : { type, data });
186
185
  }
187
186
  catch (error) {
188
- return Promise.reject(Object.assign(new Error('Message data is not JSON', { cause: error }), {
189
- code: 'INVALID_DATA',
190
- }));
187
+ return Promise.reject(new WebsocketError('INVALID_DATA', 'Message data is not JSON', { cause: error }));
191
188
  }
192
189
  return this.#broadcast(filter, text);
193
190
  },
194
191
  kick: (filter, code, reason) => this.#kick(filter, code, reason),
195
192
  onPresence: (listener) => {
196
193
  if (typeof listener !== 'function')
197
- throw new TypeError('Invalid presence listener');
194
+ throw new WebsocketError('INVALID_ARGUMENT', 'Invalid presence listener');
198
195
  this.#listeners.add(listener);
199
196
  context.logger.log('debug', 'WebSocket presence listener added', {
200
197
  listeners: this.#listeners.size,
@@ -214,7 +211,7 @@ export class Gateway {
214
211
  this.#frozen = true;
215
212
  await scope.register(fastifyWebsocket, {
216
213
  options: {
217
- maxPayload: settings.maxPayload,
214
+ maxPayload: settings.maxPayloadBytes,
218
215
  perMessageDeflate: false,
219
216
  // D-0059 §4: a client with a seal bridge offers `dokebi.seal` and `dokebi.plain`.
220
217
  // A sealed upgrade selects `dokebi.seal` only (never plain; not offered: 4415 after the
@@ -228,7 +225,7 @@ export class Gateway {
228
225
  },
229
226
  // A wsHandler that threw: the client gets 1011, the cause goes to the log (D-0047).
230
227
  errorHandler: (error, socket) => {
231
- this.#throttle.report('error', 'WebSocket handler failed', 'SOCKET_FAILURE', error);
228
+ this.#throttle.log('error', 'WebSocket handler failed', 'SOCKET_FAILURE', error);
232
229
  socket.close(1011, 'Socket failure');
233
230
  },
234
231
  });
@@ -291,7 +288,7 @@ export class Gateway {
291
288
  #send(value, data) {
292
289
  const socket = value.socket;
293
290
  if (socket.readyState !== WebSocket.OPEN)
294
- return Promise.reject(Object.assign(new Error('Socket closed'), { code: 'SOCKET_CLOSED' }));
291
+ return Promise.reject(new WebsocketError('SOCKET_CLOSED', 'Socket closed'));
295
292
  if (value.codec) {
296
293
  // Sealed connections carry text only: UTF-8 bytes are sent as text, other bytes refused.
297
294
  let text;
@@ -300,22 +297,20 @@ export class Gateway {
300
297
  else {
301
298
  const buffer = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
302
299
  if (!isUtf8(buffer))
303
- return Promise.reject(coded('Binary data cannot be sent on a sealed socket', 'SEAL_BINARY_UNSUPPORTED'));
300
+ return Promise.reject(new WebsocketError('SEAL_BINARY_UNSUPPORTED', 'Binary data cannot be sent on a sealed socket'));
304
301
  text = buffer.toString();
305
302
  }
306
303
  try {
307
304
  data = value.codec.encode(text);
308
305
  }
309
306
  catch (error) {
310
- return Promise.reject(Object.assign(new Error('Sealing a frame failed', { cause: error }), {
311
- code: 'SEAL_ENCODE_FAILED',
312
- }));
307
+ return Promise.reject(new WebsocketError('SEAL_ENCODE_FAILED', 'Sealing a frame failed', { cause: error }));
313
308
  }
314
309
  }
315
310
  const bytes = typeof data === 'string' ? Buffer.byteLength(data) : data.byteLength;
316
311
  if (socket.bufferedAmount + bytes > this.settings.maxBufferedBytes) {
317
312
  this.#slow(socket);
318
- return Promise.reject(Object.assign(new Error('Socket backpressure'), { code: 'SLOW_CONSUMER' }));
313
+ return Promise.reject(new WebsocketError('SLOW_CONSUMER', 'Socket backpressure'));
319
314
  }
320
315
  return this.#watch(new Promise((resolve, reject) => socket.send(data, (error) => (error ? reject(error) : resolve()))));
321
316
  }
@@ -341,7 +336,7 @@ export class Gateway {
341
336
  this.#sends++;
342
337
  socket.send(frame, kind, (error) => {
343
338
  if (error) {
344
- this.#throttle.report('error', 'WebSocket broadcast write failed; socket terminated', 'BROADCAST_WRITE_FAILED', error);
339
+ this.#throttle.log('error', 'WebSocket broadcast write failed; socket terminated', 'BROADCAST_WRITE_FAILED', error);
345
340
  socket.terminate();
346
341
  }
347
342
  if (--this.#sends === 0 && this.#sendsIdle) {
@@ -409,7 +404,7 @@ export class Gateway {
409
404
  hello = codec.hello();
410
405
  }
411
406
  catch (error) {
412
- this.#throttle.report('error', 'WebSocket seal codec failed; closed', 'SEAL_CODEC_FAILED', error, { connection: id });
407
+ this.#throttle.log('error', 'WebSocket seal codec failed; closed', 'SEAL_CODEC_FAILED', error, { connection: id });
413
408
  socket.close(1011, 'Socket failure');
414
409
  return;
415
410
  }
@@ -417,7 +412,9 @@ export class Gateway {
417
412
  // reports 'open' only after it (D-0059 §4).
418
413
  socket.send(hello, TEXT, (error) => {
419
414
  if (error)
420
- this.#throttle.report('warn', 'WebSocket seal hello not sent', 'SEAL_HELLO_FAILED', error, { connection: id });
415
+ this.#throttle.log('warn', 'WebSocket seal hello not sent', 'SEAL_HELLO_FAILED', error, {
416
+ connection: id,
417
+ });
421
418
  });
422
419
  if (this.context.logger.isEnabled('debug'))
423
420
  this.context.logger.log('debug', 'WebSocket seal hello sent', { connection: id });
@@ -461,7 +458,7 @@ export class Gateway {
461
458
  join: async (room) => {
462
459
  if (!route.authorizeRoom || !(await route.authorizeRoom(identity, room))) {
463
460
  this.context.logger.log('debug', 'WebSocket room refused', { connection: id });
464
- throw new Error('Room access denied');
461
+ throw new WebsocketError('ROOM_FORBIDDEN', 'Room access denied');
465
462
  }
466
463
  await value.registration?.join(room);
467
464
  this.context.logger.log('debug', 'WebSocket room joined', {
@@ -484,11 +481,11 @@ export class Gateway {
484
481
  // repeats are counted per type and reply code; client errors are counted per code only.
485
482
  reportError: (error, details) => {
486
483
  if (details.source === 'handler') {
487
- this.#throttle.report('error', 'WebSocket handler failed.', 'SOCKET_HANDLER_FAILED', error === undefined ? 'NonError: undefined' : error, // `throw undefined` still shows
484
+ this.#throttle.log('error', 'WebSocket handler failed.', 'SOCKET_HANDLER_FAILED', error === undefined ? 'NonError: undefined' : error, // `throw undefined` still shows
488
485
  { type: details.type ?? null, reply: details.code, connection: id }, `${details.type ?? ''}\u0000${details.code}`);
489
486
  return;
490
487
  }
491
- this.#throttle.report('debug', 'WebSocket client message refused', details.code, error, {
488
+ this.#throttle.log('debug', 'WebSocket client message refused', details.code, error, {
492
489
  type: details.type?.slice(0, 64) ?? null,
493
490
  connection: id,
494
491
  });
@@ -509,7 +506,7 @@ export class Gateway {
509
506
  const registered = value.tail;
510
507
  void value.tail.catch((error) => {
511
508
  // Converted to a close code (4409 or 1013) for the client; logged here for the operator.
512
- this.#throttle.report('warn', 'WebSocket registration failed', errorCode(error, 'REGISTRATION_FAILED'), error, { connection: id });
509
+ this.#throttle.log('warn', 'WebSocket registration failed', errorCode(error, 'REGISTRATION_FAILED'), error, { connection: id });
513
510
  value.failed = true;
514
511
  // The same (tenant, member, clientId) is already connected (D-0025): a client error, not
515
512
  // a hub outage. A client that retries with the same clientId is refused again.
@@ -525,16 +522,20 @@ export class Gateway {
525
522
  });
526
523
  // ws emits 'close' after 'error'; the close cleans up, the error is reported here.
527
524
  socket.on('error', (error) => {
528
- this.#throttle.report('error', 'WebSocket socket error', 'SOCKET_ERROR', error, {
525
+ this.#throttle.log('error', 'WebSocket socket error', 'SOCKET_ERROR', error, {
529
526
  reason: errorCode(error, 'UNKNOWN'),
530
527
  });
531
528
  });
532
529
  // Attach synchronously, before awaiting Redis/TCP registration, so early frames are queued.
533
530
  socket.on('message', (raw, isBinary) => {
534
531
  value.seen = performance.now();
535
- const bytes = Array.isArray(raw)
536
- ? Buffer.concat(raw)
537
- : Buffer.from(raw instanceof ArrayBuffer ? new Uint8Array(raw) : raw);
532
+ // ws hands each message its own Buffer (unmasked once, never reused): take it as it is
533
+ // instead of copying every frame (D-0068). Fragments are joined; an ArrayBuffer is wrapped.
534
+ const bytes = Buffer.isBuffer(raw)
535
+ ? raw
536
+ : Array.isArray(raw)
537
+ ? Buffer.concat(raw)
538
+ : Buffer.from(raw);
538
539
  if (codec) {
539
540
  // Sealed: the frame is opened in this connection's order chain, then handled like a
540
541
  // plain one (control frames, then the route). Nothing is read before it opens.
@@ -590,7 +591,7 @@ export class Gateway {
590
591
  });
591
592
  void this.#watch(cleanup).catch((error) => {
592
593
  // The hub drops this connection when it recovers (owner snapshot or expiry).
593
- this.#throttle.report('error', 'WebSocket presence cleanup deferred to hub recovery', 'PRESENCE_CLEANUP_DEFERRED', error, { connection: id });
594
+ this.#throttle.log('error', 'WebSocket presence cleanup deferred to hub recovery', 'PRESENCE_CLEANUP_DEFERRED', error, { connection: id });
594
595
  });
595
596
  });
596
597
  }
@@ -612,7 +613,7 @@ export class Gateway {
612
613
  // A page loaded before D-0057 still acknowledges broadcasts: nothing to do, and no
613
614
  // reason to close it. Counted at debug until it reloads.
614
615
  if (control?.$dokebi === 'ack-v1') {
615
- this.#throttle.report('debug', 'WebSocket ACK from an old client ignored', 'ACK_IGNORED', undefined, { connection: id });
616
+ this.#throttle.log('debug', 'WebSocket ACK from an old client ignored', 'ACK_IGNORED', undefined, { connection: id });
616
617
  return true;
617
618
  }
618
619
  return false;
@@ -626,17 +627,17 @@ export class Gateway {
626
627
  const given = error?.reason;
627
628
  const reason = typeof given === 'string' && REASON.test(given) ? given : 'unknown';
628
629
  value.failed = true;
629
- this.#throttle.report('warn', 'WebSocket sealed frame refused; closed', 'SEAL_FRAME_REFUSED', error, { connection: id, reason }, reason);
630
+ this.#throttle.log('warn', 'WebSocket sealed frame refused; closed', 'SEAL_FRAME_REFUSED', error, { connection: id, reason }, reason);
630
631
  value.socket.close(BAD_FRAME, 'Bad frame');
631
632
  }
632
633
  /** Runs `work` after this connection's earlier messages and presence calls, in order. */
633
634
  #enqueue(value, id, work) {
634
635
  const socket = value.socket;
635
- if (++value.pending > this.settings.maxPendingMessages) {
636
+ if (++value.pending > this.settings.maxPending) {
636
637
  value.pending--;
637
638
  // The server closing a client is worth seeing (like SLOW_CONSUMER): usually a handler
638
639
  // that waits long (a slow database call) while the client keeps sending.
639
- this.#throttle.report('warn', 'WebSocket message queue full; closed', 'TOO_MANY_MESSAGES', undefined, {
640
+ this.#throttle.log('warn', 'WebSocket message queue full; closed', 'TOO_MANY_MESSAGES', undefined, {
640
641
  connection: id,
641
642
  pending: value.pending,
642
643
  });
@@ -655,10 +656,10 @@ export class Gateway {
655
656
  if (code === 'SLOW_CONSUMER')
656
657
  return;
657
658
  if (code === 'SOCKET_CLOSED') {
658
- this.#throttle.report('warn', 'WebSocket reply dropped; socket closed', 'REPLY_DROPPED', error, { connection: id });
659
+ this.#throttle.log('warn', 'WebSocket reply dropped; socket closed', 'REPLY_DROPPED', error, { connection: id });
659
660
  return;
660
661
  }
661
- this.#throttle.report('error', 'WebSocket message handler failed', errorCode(error, 'HANDLER_FAILED'), error, { connection: id });
662
+ this.#throttle.log('error', 'WebSocket message handler failed', errorCode(error, 'HANDLER_FAILED'), error, { connection: id });
662
663
  socket.close(1011, 'Message failed');
663
664
  })
664
665
  .finally(() => {
@@ -735,7 +736,7 @@ export class Gateway {
735
736
  const code = error?.code;
736
737
  if (code === 'SLOW_CONSUMER')
737
738
  return; // Logged where the socket was closed.
738
- this.#throttle.report(code === 'SOCKET_CLOSED' ? 'warn' : 'error', code === 'SOCKET_CLOSED'
739
+ this.#throttle.log(code === 'SOCKET_CLOSED' ? 'warn' : 'error', code === 'SOCKET_CLOSED'
739
740
  ? 'WebSocket presence dropped; socket closed'
740
741
  : 'WebSocket presence handler failed', code === 'SOCKET_CLOSED' ? 'REPLY_DROPPED' : 'PRESENCE_HANDLER_FAILED', error, { connection: session.id });
741
742
  });
@@ -803,7 +804,7 @@ export class Gateway {
803
804
  async #broadcast(input, data) {
804
805
  const filter = checkFilter(input);
805
806
  if (typeof data !== 'string' && !(data instanceof Uint8Array))
806
- throw coded('Broadcast data is a string or a Uint8Array', 'INVALID_DATA');
807
+ throw new WebsocketError('INVALID_DATA', 'Broadcast data is a string or a Uint8Array');
807
808
  const bytes = typeof data === 'string' ? encoder.encode(data) : data;
808
809
  const queries = this.#queries(filter);
809
810
  // A single tenant keeps the hub's own error (RECOVERING, BUSY, OUTCOME_UNKNOWN).
@@ -832,9 +833,7 @@ export class Gateway {
832
833
  bytes: bytes.byteLength,
833
834
  });
834
835
  if (failures.length)
835
- throw Object.assign(new Error(`WebSocket broadcast failed for ${failures.length} of ${queries.length} tenants`, {
836
- cause: new AggregateError(failures, 'Hub broadcast failures'),
837
- }), { code: errorCode(failures[0], 'BROADCAST_FAILED'), receipt });
836
+ 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
837
  return receipt;
839
838
  }
840
839
  async #kick(input, code, reason) {
@@ -854,9 +853,7 @@ export class Gateway {
854
853
  if (failures.length === 1 && queries.length === 1)
855
854
  throw failures[0];
856
855
  if (failures.length)
857
- throw Object.assign(new Error(`WebSocket kick failed for ${failures.length} of ${queries.length} tenants`, {
858
- cause: new AggregateError(failures, 'Hub kick failures'),
859
- }), { code: errorCode(failures[0], 'KICK_FAILED'), receipt });
856
+ 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
857
  return receipt;
861
858
  }
862
859
  /** Hands each tenant's change to the `api.onPresence` listeners; their failures are logged. */
@@ -868,7 +865,7 @@ export class Gateway {
868
865
  left: Object.freeze([...change.left]),
869
866
  });
870
867
  for (const listener of this.#listeners) {
871
- const failed = (error) => this.#throttle.report('error', 'WebSocket presence listener failed', 'PRESENCE_LISTENER_FAILED', error);
868
+ const failed = (error) => this.#throttle.log('error', 'WebSocket presence listener failed', 'PRESENCE_LISTENER_FAILED', error);
872
869
  try {
873
870
  const result = listener(presence);
874
871
  if (result && typeof result.then === 'function')
@@ -928,7 +925,7 @@ export class Gateway {
928
925
  sealedFrame = value.codec.encode(text);
929
926
  }
930
927
  catch (error) {
931
- this.#throttle.report('error', 'WebSocket broadcast not sealed; socket closed', 'SEAL_ENCODE_FAILED', error, { connection: id });
928
+ this.#throttle.log('error', 'WebSocket broadcast not sealed; socket closed', 'SEAL_ENCODE_FAILED', error, { connection: id });
932
929
  value.socket.close(1011, 'Socket failure');
933
930
  continue;
934
931
  }
@@ -936,7 +933,7 @@ export class Gateway {
936
933
  this.#deliver(value.socket, sealedFrame, TEXT);
937
934
  }
938
935
  if (dropped)
939
- this.#throttle.report('warn', 'WebSocket binary broadcast not sent to sealed sockets', 'SEAL_BINARY_UNSUPPORTED', undefined, { id: event.id, dropped });
936
+ this.#throttle.log('warn', 'WebSocket binary broadcast not sent to sealed sockets', 'SEAL_BINARY_UNSUPPORTED', undefined, { id: event.id, dropped });
940
937
  if (this.context.logger.isEnabled('debug'))
941
938
  this.context.logger.log('debug', 'WebSocket broadcast delivered', {
942
939
  id: event.id,
@@ -954,7 +951,7 @@ export class Gateway {
954
951
  // The hub ended its event stream (overflow, closed): every socket gets 1013 and reconnects.
955
952
  this.context.logger.log('error', 'WebSocket hub event stream failed; sockets closed', {
956
953
  code: 'HUB_EVENTS_FAILED',
957
- error: errorText(error),
954
+ error: describeError(error),
958
955
  open: this.#clients.size,
959
956
  });
960
957
  for (const value of this.#clients.values())
@@ -1002,7 +999,7 @@ export class Gateway {
1002
999
  await this.#idle(signal, stop, false);
1003
1000
  for (const value of this.#clients.values())
1004
1001
  value.socket.close(1012, 'Server restarting');
1005
- const deadline = performance.now() + this.settings.closeTimeoutMs;
1002
+ const deadline = performance.now() + this.settings.shutdownTimeoutMs;
1006
1003
  while (this.#clients.size && performance.now() < deadline && !signal.aborted)
1007
1004
  await Promise.race([delay(10), stop]);
1008
1005
  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, providerDependency, } from '@dokebi/core';
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 { parseOptions } from './options.js';
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.1.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 Object.assign(new Error('dokebi-seal does not provide forConnection'), {
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.3.0',
53
- core: '^0.2.0',
54
- options: parseOptions,
49
+ version: '0.4.0',
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
- export interface Options {
2
- maxPayload: number;
3
- maxConnections: number;
4
- maxPendingMessages: number;
5
- maxBufferedBytes: number;
6
- closeTimeoutMs: number;
7
- heartbeatMs: number;
8
- /**
9
- * Closes a connection (4408 `Idle`) that sent nothing for this long; 0 (default) never does.
10
- * WebSocket pings prove only that the browser's network stack is up: a hidden page that is
11
- * frozen (back/forward cache) still answers them. A client that sends `{"$dokebi":"ping-v1"}`
12
- * from its script proves that the page itself still runs.
13
- */
14
- idleTimeoutMs: number;
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;
package/dist/options.js CHANGED
@@ -1,42 +1,40 @@
1
- import { types } from 'node:util';
1
+ import { defineOptions, option as o } from '@dokebi/core';
2
+ /*
3
+ * Options of dokebi-websocket (D-0063 §3): one declaration is the parser and, at build time,
4
+ * options.schema.json. The rules are the hand parser's before wave B.
5
+ */
6
+ const LIMIT = 67108864;
7
+ const limit = (defaultValue, description) => o.integer({ minimum: 1, maximum: LIMIT, default: defaultValue, description });
8
+ export const options = defineOptions({
9
+ maxPayloadBytes: limit(65536, 'Largest incoming frame in bytes.'),
10
+ maxPayload: o.alias('maxPayloadBytes'),
11
+ maxConnections: limit(128, 'Open connections this process accepts at most.'),
12
+ maxPending: limit(32, 'Messages of one connection waiting for its handler at most.'),
13
+ maxPendingMessages: o.alias('maxPending'),
14
+ maxBufferedBytes: limit(1048576, 'Bytes waiting to be sent to one connection at most; a slower client is closed (SLOW_CONSUMER).'),
15
+ shutdownTimeoutMs: limit(2000, 'How long drain waits for closing connections (1012) before it cuts them, in ms.'),
16
+ closeTimeoutMs: o.alias('shutdownTimeoutMs'),
17
+ heartbeatMs: limit(10000, 'Interval of WebSocket pings, in ms.'),
18
+ idleTimeoutMs: o.integer({
19
+ minimum: 0,
20
+ maximum: LIMIT,
21
+ default: 0,
22
+ description: 'Close (4408 Idle) a connection that sent nothing for this long; 0 never. Clients send {"$dokebi":"ping-v1"} from their script to show the page still runs.',
23
+ }),
24
+ hubWaitMs: o.integer({
25
+ minimum: 0,
26
+ maximum: LIMIT,
27
+ default: 5000,
28
+ description: 'How long an upgrade waits for a reconnecting hub (leader change, rolling restart) before 503 HUB_RECOVERING; 0 refuses at once.',
29
+ }),
30
+ sealDriftMs: o.integer({
31
+ minimum: 1000,
32
+ maximum: 600000,
33
+ default: 60000,
34
+ description: 'Sealed connections (route.seal, dokebi-app domains.<host>.seal): how far a frame timestamp may differ from the server clock before the frame is refused (4400). Needs the dokebi-seal plugin.',
35
+ }),
36
+ });
37
+ /** Parses `options.dokebi-websocket`; fails with core `INVALID_OPTIONS` (`details.issues`). */
2
38
  export function parseOptions(input) {
3
- if (input === undefined)
4
- input = {};
5
- if (!input ||
6
- typeof input !== 'object' ||
7
- types.isProxy(input) ||
8
- ![Object.prototype, null].includes(Object.getPrototypeOf(input)))
9
- throw new Error('Invalid websocket options');
10
- const v = Object.create(null);
11
- for (const key of Reflect.ownKeys(input)) {
12
- const desc = Object.getOwnPropertyDescriptor(input, key);
13
- if (typeof key !== 'string' || !desc || !('value' in desc) || !desc.enumerable)
14
- throw new Error('Invalid websocket options');
15
- v[key] = desc.value;
16
- }
17
- const defaults = {
18
- maxPayload: 65536,
19
- maxConnections: 128,
20
- maxPendingMessages: 32,
21
- maxBufferedBytes: 1048576,
22
- closeTimeoutMs: 2000,
23
- heartbeatMs: 10000,
24
- idleTimeoutMs: 0,
25
- hubWaitMs: 5000,
26
- sealDriftMs: 60000,
27
- };
28
- if (Object.keys(v).some((k) => !Object.hasOwn(defaults, k)))
29
- throw new Error('Unknown websocket option');
30
- const result = { ...defaults };
31
- for (const key of Object.keys(defaults)) {
32
- if (v[key] !== undefined) {
33
- const x = v[key];
34
- const min = key === 'idleTimeoutMs' || key === 'hubWaitMs' ? 0 : key === 'sealDriftMs' ? 1000 : 1;
35
- const max = key === 'sealDriftMs' ? 600000 : 67108864;
36
- if (typeof x !== 'number' || !Number.isSafeInteger(x) || x < min || x > max)
37
- throw new Error('Invalid websocket limit');
38
- result[key] = x;
39
- }
40
- }
41
- return result;
39
+ return options.parse(input, { plugin: 'dokebi-websocket' });
42
40
  }
package/dist/router.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { Awaitable } from '@dokebi/core';
1
+ import { type Awaitable } from '@dokebi/core';
2
2
  import type { FastifyRequest } from 'fastify';
3
3
  import type { WebsocketIdentity, WebsocketPresence, WebsocketRoute, WebsocketSession } from './types.js';
4
4
  /** What a message handler receives besides the message data. */