@dokebi/websocket 0.4.8 → 0.4.9

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 CHANGED
@@ -24,6 +24,7 @@ The hub style is chosen in dokebi.yaml `options.dokebi-websocket-hub.mode`. `loc
24
24
  | `maxPayloadBytes` | integer | 65536 | Message size of a route without its own (§3b) |
25
25
  | `maxRoutePayloadBytes` | integer | 16777216 | The largest `maxPayloadBytes` a route may set (§3b); above it, `INVALID_ROUTE` at `route` |
26
26
  | `maxConnections` (reloadable) | integer | 128 | Connections of this process |
27
+ | `maxConnectionsPerIdentity` (reloadable) | integer 0–67108864 | 0 (off) | Connections of one identity (the same tenant and member, every clientId) across the cluster; one more closes with 4429 `CONNECTION_LIMIT_IDENTITY` (§3c). A route may set its own |
27
28
  | `maxPending` (reloadable) | integer | 32 | Waiting messages per connection (each connection runs in order); also bounds its waiting presence calls, separately |
28
29
  | `maxBufferedBytes` (reloadable) | integer | 1048576 | Send buffer. Beyond it the socket is closed with 1013 `Slow consumer` and warn `WebSocket slow consumer closed` (code `SLOW_CONSUMER`) is logged. Replies meant for that socket are dropped (not counted as handler failures) |
29
30
  | `shutdownTimeoutMs` | integer ms | 2000 | Socket close wait at drain (not a limit on work) |
@@ -74,7 +75,7 @@ export const chatSocket = (app: AppContext) => defineSocket({
74
75
  - `socket` (`SocketContext`): `session`, `identity`, `send(type, data)` (this connection), `broadcast(type, data, { room?, member? })` (through the hub, tenant fixed → receipt `{ id, recipients }`). Receiving sockets get the same `{ type, data }` text frame as `send`.
75
76
  - Multi-app: `sockets: (app) => [chatSocket(app)]` of @dokebi/app. The same path is registered separately per app, and the hub tenant is `<namespace>:<tenant>` (the default namespace is the app name, D-0061). The `namespace` that `authenticate` returns is read and removed by @dokebi/app; this package leaves `namespace` out when it registers with the hub.
76
77
  - Route id (D-0140): `config: { id }` (`defineSocket` or `route`) becomes the Fastify config of the upgrade route, so `dokebi describe` lists it as `routes[].id`, `web.routes()` and the per-route hooks of dokebi-web (`web.routeHook`, an audit log's `onResponse`) see it, and the upgrade request reads it as `request.routeOptions.config.id`. dokebi-web checks it at start exactly like a web route's id: 1 to 64 letters, digits, `.`, `_` or `-`, starting with a letter (`INVALID_ROUTE_CONFIG`); the same id on two routes of one app (a web route, a socket or an event stream) fails the start with `DUPLICATE_ROUTE_ID`. `config` takes only `id`: null, a string or another key (`auth`, `csrf`, …) is `INVALID_ROUTE` at `route`. The refusal logs carry it as `routeId` (§7). **`auth: false`** (0.4.5, [D-0230](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0230-machine-sockets-dev-modules-vue-imports.md)): `config: { id, auth: false }` leaves @dokebi/auth's route check out of the upgrade, so the route's own `authenticate` is its only check — a machine client with a key of its own (another server's agent: `Authorization: Bearer <key>`) under `default: required`. `auth` takes only `false` (`INVALID_ROUTE` otherwise; a socket already follows the default), and any other key is `INVALID_ROUTE` too. Example 85.
77
- - Low level: `context.get(ws).route({ path, config?, origins?, constraints?, version?, seal?, maxPayloadBytes?, compress?, authenticate, authorizeRoom?, message(data, session), presence? })` (`WebsocketRoute`). session (`WebsocketSession`): `id`, `identity`, `send`, `broadcast(bytes, target?)`, `join(room)`, `leave(room)`, `close(code?, reason?)`, `reportError?(error, details)` (§7). `connections` is the number of open connections of this process, and `sealing` says whether a seal provider is registered.
78
+ - Low level: `context.get(ws).route({ path, config?, origins?, constraints?, version?, seal?, maxPayloadBytes?, compress?, maxConnectionsPerIdentity?, authenticate, authorizeRoom?, message(data, session), presence? })` (`WebsocketRoute`). session (`WebsocketSession`): `id`, `identity`, `send`, `broadcast(bytes, target?)`, `join(room)`, `leave(room)`, `close(code?, reason?)`, `reportError?(error, details)` (§7). `connections` is the number of open connections of this process, and `sealing` says whether a seal provider is registered.
78
79
  - Exports: `createPlugin`, `defineSocket`, `options`, `WebsocketError`, `SEAL_PROTOCOL`, `PLAIN_PROTOCOL`, types `WebsocketApi`, `WebsocketOptions`, `WebsocketRoute`, `WebsocketRouteConfig`, `WebsocketSession`, `WebsocketIdentity`, `WebsocketPeer`, `WebsocketPresence`, `WebsocketErrorDetails`, `WebsocketConnectionInfo`, `WebsocketFilter`, `WebsocketReceipt`, `WebsocketKickReceipt`, `SocketDefinition`, `SocketContext`, `SocketHandler`, `SocketCodecProvider`, `SocketCodec`, `SocketCodecConnection`, `SocketNonceStore`, `WebsocketTransport`, `WebsocketNamespaceHandle`, `WebsocketNamespaceTarget`, `WebsocketErrorCode`.
79
80
 
80
81
  ## 3a. Sending and listing from server code (0.3.0, [D-0061](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0061-realtime-namespaces.md))
@@ -115,10 +116,29 @@ export const agentSocket = (app: AppContext) => defineSocket({
115
116
 
116
117
  - **`maxPayloadBytes`** on a route (`defineSocket` or `route`): the largest message its connections may send, in bytes — 1 to `maxRoutePayloadBytes` (default 16 MiB), else `INVALID_ROUTE` at `route`. Other routes keep the gateway's `maxPayloadBytes`. Give the large limit only to the socket that needs it (a machine client with its own key); every connection of a route may hold one message of its limit in memory while it arrives.
117
118
  - **Over the limit**: the connection is closed with **1009** (`Message Too Big`) at once — the close frame, then the TCP connection — and the message never reaches the route. debug `WebSocket message over the route limit; closed 1009` (code `MESSAGE_TOO_BIG`, with `routeId`, `path`, `maxPayloadBytes`; repeats in `logRepeatWindowMs` are counted) tells it from a defect. ws does not report the size of the refused message, only that it passed the limit. On a sealed route the limit is on the sealed frame.
118
- - **`compress: true`**: permessage-deflate on that route's connections when the client offers it (browsers and the `ws` package do; Node's built-in `WebSocket` does not, and then the route works uncompressed). Off by default. Settings: no compression context kept between messages on either side, messages under 1 KiB sent as they are, level 1, memLevel 7, 13 window bits, at most 10 zlib jobs at once (ws). An inflated message still stops at the route's limit: 200 KB of zeros that arrive as a few hundred bytes is 1009.
119
+ - **`compress: true`**: permessage-deflate on that route's connections when the client offers it (browsers and the `ws` package do; Node's built-in `WebSocket` does not, and then the route works uncompressed — a Node client that wants it creates its socket with `ws`, see @dokebi/websocket-client AI.md §3). Off by default. Settings: no compression context kept between messages on either side, messages under 1 KiB sent as they are, level 1, memLevel 7, 13 window bits, at most 10 zlib jobs at once (ws). An inflated message still stops at the route's limit: 200 KB of zeros that arrive as a few hundred bytes is 1009.
119
120
  - **The cost** (measured, [benchmarks/websocket-deflate.mjs](https://git.nyx-zone.com/dokebi/framework/-/blob/main/benchmarks/websocket-deflate.mjs), 2026-11-19, a 180 KB JSON sales report, client and server in one process): on the wire 180 KB → 37 KB from the server and 31 KB to it (about 5×); CPU per message 0.18 → 1.14 ms (server sends) and 0.48 → 2.17 ms (server receives), both ends together; each connection that has carried a message holds about 430 KiB more (both ends; zlib state ws keeps per connection). So: compress a route of few connections with large messages (machine sockets, reports), not browser sockets of many small messages.
120
121
  - Each distinct (limit, compression) other than the gateway's runs on its own socket server (ws fixes both per server at the upgrade); nothing changes for routes without them.
121
122
 
123
+ ## 3c. Connections of one identity (0.4.9, [D-0246](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0246-websocket-connections-per-identity.md))
124
+
125
+ `maxConnections` bounds the whole process: without a limit per identity, one signed-in member who opens 128 sockets leaves none for anyone else on that process. `maxConnectionsPerIdentity` (gateway option, reloadable) or a route's own `maxConnectionsPerIdentity` bounds the open connections of one identity — the same `tenant` and `member`, whatever their `clientId` (each tab has its own).
126
+
127
+ ```ts snippet
128
+ // Members 10 tabs, staff 20 — read for every upgrade, so a reloaded app config applies to the next one.
129
+ export const liveSocket = (app: AppContext, realm: 'site' | 'admin') => defineSocket({
130
+ path: '/live',
131
+ maxConnectionsPerIdentity: () => (realm === 'admin' ? 20 : 10),
132
+ authenticate: liveIdentity,
133
+ on: {},
134
+ });
135
+ ```
136
+
137
+ - **Value**: a whole number from 0 (never limits) to 67108864, or a function of the authenticated identity that returns one (one value per realm, tenant or plan). Without it the route takes the gateway's `maxConnectionsPerIdentity` (default 0: off). A number out of range fails `route` with `INVALID_ROUTE`; a function that throws or returns something else refuses that upgrade with 500 `LIMIT_FAILED` and logs error `WebSocket identity limit failed; upgrade refused` (code `IDENTITY_LIMIT_FAILED`, the whole cause).
138
+ - **Refusal**: the connection one over the limit is upgraded and then closed at once with **4429**, reason `CONNECTION_LIMIT_IDENTITY`, before the hub registers it (no presence join or leave, no route call). Do not reconnect on 4429 until one of the identity's other connections has closed (a tab closed); show the user that too many windows are open. warn `WebSocket connection refused: identity limit` (code `CONNECTION_LIMIT_IDENTITY`, with `path`, `routeId`, `tenant`, `member`, `limit` and `open`), once per `logRepeatWindowMs` and the rest counted (`repeated`).
139
+ - **What is counted**: this process's open connections of the identity exactly (upgrades racing on one process included: the count is taken when the socket attaches, synchronously), plus the identity's connections on the other servers of the cluster as the hub listed them when the upgrade was checked. A connection counts until its socket closes. Every route of the identity's tenant counts; the limit is the upgrading route's.
140
+ - **Across the cluster**: the other servers' connections reach this server with the hub's presence changes (usually within milliseconds). Upgrades of one identity that land on different servers inside that delay can each pass, so for a moment the identity can hold more than the limit — at most the limit on every server — never more than the limit on one server. With `mode: local` (one process) the count is exact. The lookup reads the hub's in-memory list of that member (websocket-hub 0.4.5 indexes it; an older hub scans every connection of the cluster on each upgrade while a limit is on).
141
+
122
142
  ## 4. What the client does
123
143
 
124
144
  ```ts snippet
@@ -153,7 +173,7 @@ function connectAgent(): void {
153
173
 
154
174
  - Broadcasts arrive as the bytes the server sent: a text frame when UTF-8 (`defineSocket`'s `{ type, data }` JSON), otherwise a binary frame. There is no envelope to unwrap (`delivery-v1`) and no ACK to send. The old browser entry `DeliveryReceiver` was removed in 0.2.0 (`@dokebi/websocket/client` is now the heartbeat above, 0.4.6, re-exported from `@dokebi/websocket-client` since 0.4.7). Use only the standard `WebSocket` API. The `{"$dokebi":"ack-v1"}` that old pages send is ignored, not closed (debug `ACK_IGNORED`).
155
175
  - Broadcasts sent while disconnected or while closed as a slow consumer never come again. The screen reads the latest state from the server after reconnecting.
156
- - Close codes: 4426 reload, 4409 `Replaced` (the same tenant, member and clientId connected again, on any server: the newest connection wins and the older one is closed; with a hub before that rule the newer one is refused instead, 4409 `Duplicate client`), 4408 idle, 1013 hub unavailable, slow consumer, or a replay nonce store that is full (D-0075) or failed (D-0096) (`Try again later`), 1012 server shutting down, 1011 unhandled handler error, 4415 sealed host but no `dokebi.seal` offered, 4400 sealed frame refused (§4a). 4400 and 4415 repeat on reconnect, so do not reconnect. Never reconnect after 4409 with the same clientId: it would replace the newer connection of that clientId, and the two would replace each other in turn. A tab that must stay live (a duplicated tab copies sessionStorage) takes a new clientId and connects again. A tab whose old socket was half open (a network switch) is not affected: its new connection is the newer one.
176
+ - Close codes: 4426 reload, 4429 `CONNECTION_LIMIT_IDENTITY` (the identity holds `maxConnectionsPerIdentity` connections already, §3c; reconnect only after one of them closed), 4409 `Replaced` (the same tenant, member and clientId connected again, on any server: the newest connection wins and the older one is closed; with a hub before that rule the newer one is refused instead, 4409 `Duplicate client`), 4408 idle, 1013 hub unavailable, slow consumer, or a replay nonce store that is full (D-0075) or failed (D-0096) (`Try again later`), 1012 server shutting down, 1011 unhandled handler error, 4415 sealed host but no `dokebi.seal` offered, 4400 sealed frame refused (§4a). 4400 and 4415 repeat on reconnect, so do not reconnect. Never reconnect after 4409 with the same clientId: it would replace the newer connection of that clientId, and the two would replace each other in turn. A tab that must stay live (a duplicated tab copies sessionStorage) takes a new clientId and connects again. A tab whose old socket was half open (a network switch) is not affected: its new connection is the newer one.
157
177
 
158
178
  ## 4a. Sealed connections (0.3.0, [D-0059](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0059-seal-and-websocket-client.md) §4)
159
179
 
package/README.md CHANGED
@@ -39,6 +39,7 @@ Prepare the required YAML of websocket-hub. The CLI registration order is redis
39
39
  | `maxPayloadBytes` | integer | 65536 | Message size of a route without its own |
40
40
  | `maxRoutePayloadBytes` | integer | 16777216 | Largest `maxPayloadBytes` a route may set |
41
41
  | `maxConnections` (reloadable) | integer | 128 | Connections per process |
42
+ | `maxConnectionsPerIdentity` (reloadable) | integer | 0 (off) | Connections of one tenant and member across the cluster; one more closes with 4429 `CONNECTION_LIMIT_IDENTITY` (a route may set its own) |
42
43
  | `maxPending` (reloadable) | integer | 32 | Waiting messages per connection; also bounds its waiting presence calls, separately |
43
44
  | `maxBufferedBytes` (reloadable) | integer | 1048576 | Send buffer before 1013 `Slow consumer` |
44
45
  | `shutdownTimeoutMs` | integer ms | 2000 | Socket close wait at drain |
@@ -64,7 +65,7 @@ Browsers attach cookies to a WebSocket Upgrade even from another site's page. Wh
64
65
 
65
66
  The API is `route({ path, origins?, authenticate, authorizeRoom?, message })` registration in setup and the `connections` count. A session offers `id`/`identity`, `send`, `broadcast`, `join`, `leave` and `close`. `broadcast` is fixed to the authenticated tenant. `join` requires `authorizeRoom` to return true. Origin refused 403, authentication failure 401, hub not ready or shutting down 503, plain HTTP 426. An unhandled handler error closes with 1011.
66
67
 
67
- Messages run in order per connection, and messages received during the initial registration are queued. Defaults: `maxPayloadBytes` 65536, `maxConnections` 128, `maxPending` 32, `maxBufferedBytes` 1048576, `shutdownTimeoutMs` 2000, `heartbeatMs` 10000. It uses ping/pong and a send buffer limit. A route may set its own `maxPayloadBytes` (up to `maxRoutePayloadBytes`) and `compress: true` (permessage-deflate, off by default); a message over the limit closes with 1009 and a debug `MESSAGE_TOO_BIG` (0.4.8, D-0235; costs measured in AI.md §3b). The hub's own payload and connection limits apply as well.
68
+ Messages run in order per connection, and messages received during the initial registration are queued. Defaults: `maxPayloadBytes` 65536, `maxConnections` 128, `maxPending` 32, `maxBufferedBytes` 1048576, `shutdownTimeoutMs` 2000, `heartbeatMs` 10000. It uses ping/pong and a send buffer limit. A route may set its own `maxPayloadBytes` (up to `maxRoutePayloadBytes`) and `compress: true` (permessage-deflate, off by default); a message over the limit closes with 1009 and a debug `MESSAGE_TOO_BIG` (0.4.8, D-0235; costs measured in AI.md §3b). The hub's own payload and connection limits apply as well. `maxConnectionsPerIdentity` (0.4.9, D-0246; off by default) bounds the connections of one identity — the same tenant and member, every clientId — so one signed-in user cannot take every connection of a process: one more is closed with 4429 `CONNECTION_LIMIT_IDENTITY` (warn, counted per window). A route may set its own, a number or a function of the identity (one value per realm). It counts this process exactly and the other servers of the cluster as the hub last reported them, so upgrades landing on different servers at the same moment can briefly pass it (never more than the limit on one server).
68
69
 
69
70
  Broadcast delivery does not wait for each target socket to finish sending. The broadcast bytes as they are (a text frame for UTF-8, otherwise a binary frame) are shared as one buffer by every receiving socket and put into the `ws` send queue of each open socket (that queue keeps the order within a socket); a socket with a send error is the only one cut. When `bufferedAmount` plus the frame exceeds `maxBufferedBytes`, that socket is closed with 1013 `Slow consumer`. So one slow client never delays broadcasts to other sockets. To avoid pushing healthy sockets over the limit while processing queued hub events at once, it yields the event loop once between events while frames are being sent.
70
71
 
package/dist/gateway.js CHANGED
@@ -13,6 +13,8 @@ const BINARY = Object.freeze({ binary: true });
13
13
  /** Close codes of sealed connections (D-0059 §4); the client does not reconnect after them. */
14
14
  const BAD_FRAME = 4400;
15
15
  const SEAL_REQUIRED = 4415;
16
+ /** D-0246: one identity has `maxConnectionsPerIdentity` connections open already. */
17
+ const IDENTITY_LIMIT = 4429;
16
18
  /** Why a sealed frame was refused, as a bounded log group (codec reasons look like `replay`). */
17
19
  const REASON = /^[a-z][a-z-]{0,31}$/;
18
20
  /**
@@ -110,6 +112,30 @@ function payloadOf(route, most) {
110
112
  throw new WebsocketError('INVALID_ROUTE', `WebSocket route maxPayloadBytes is a whole number of bytes from 1 to ${most} (maxRoutePayloadBytes)`);
111
113
  return value;
112
114
  }
115
+ /** The largest `maxConnectionsPerIdentity` (the options' integer limit). */
116
+ const MOST_PER_IDENTITY = 67108864;
117
+ function perIdentityValid(value) {
118
+ return (typeof value === 'number' &&
119
+ Number.isSafeInteger(value) &&
120
+ value >= 0 &&
121
+ value <= MOST_PER_IDENTITY);
122
+ }
123
+ /**
124
+ * D-0246: the route's own `maxConnectionsPerIdentity` (a number or a function of the identity),
125
+ * or undefined for the gateway's.
126
+ */
127
+ function perIdentityOf(route) {
128
+ const value = route.maxConnectionsPerIdentity;
129
+ if (value === undefined || typeof value === 'function')
130
+ return value;
131
+ if (!perIdentityValid(value))
132
+ throw new WebsocketError('INVALID_ROUTE', `WebSocket route maxConnectionsPerIdentity is a whole number from 0 to ${MOST_PER_IDENTITY}, or a function of the identity that returns one`);
133
+ return value;
134
+ }
135
+ /** The key of one identity (D-0246): its tenant and member; every clientId counts. */
136
+ function identityKey(identity) {
137
+ return `${identity.tenant}\u0000${identity.member}`;
138
+ }
113
139
  /** D-0235: permessage-deflate on this route's connections (off unless `true`). */
114
140
  function compressOf(route) {
115
141
  const value = route.compress;
@@ -266,6 +292,13 @@ export class Gateway {
266
292
  #sends = 0;
267
293
  #sendsIdle;
268
294
  #identities = new WeakMap();
295
+ /** D-0246: open connections of this process per identity (`identityKey`), kept whatever the limit. */
296
+ #perIdentity = new Map();
297
+ /**
298
+ * D-0246: an upgrade's identity limit and the connections of that identity on the other servers
299
+ * of the cluster when it was checked (preValidation), read when the socket attaches.
300
+ */
301
+ #identityLimits = new WeakMap();
269
302
  /** `api.onPresence` listeners (D-0061). */
270
303
  #listeners = new Set();
271
304
  /** Upgrades decided as sealed in preValidation, read by handleProtocols and the wsHandler. */
@@ -321,13 +354,23 @@ export class Gateway {
321
354
  const id = typeof config?.id === 'string' ? config.id : null;
322
355
  const maxPayloadBytes = payloadOf(route, settings.maxRoutePayloadBytes);
323
356
  const compress = compressOf(route);
324
- this.#routes.push({ route: { ...route }, origins, config, id, maxPayloadBytes, compress });
357
+ const perIdentity = perIdentityOf(route);
358
+ this.#routes.push({
359
+ route: { ...route },
360
+ origins,
361
+ config,
362
+ id,
363
+ maxPayloadBytes,
364
+ compress,
365
+ perIdentity,
366
+ });
325
367
  context.logger.log('debug', 'WebSocket route registered', {
326
368
  path: route.path,
327
369
  routeId: id,
328
370
  version: route.version ?? null,
329
371
  maxPayloadBytes: maxPayloadBytes ?? settings.maxPayloadBytes,
330
372
  compress,
373
+ maxConnectionsPerIdentity: typeof perIdentity === 'function' ? 'function' : (perIdentity ?? null),
331
374
  });
332
375
  },
333
376
  list: (filter) => this.#list(filter),
@@ -507,7 +550,8 @@ export class Gateway {
507
550
  }
508
551
  done();
509
552
  });
510
- for (const { route, origins, config, id, maxPayloadBytes, compress } of this.#routes) {
553
+ for (const { route, origins, config, id, maxPayloadBytes, compress, perIdentity } of this
554
+ .#routes) {
511
555
  const logger = this.context.logger;
512
556
  const limit = maxPayloadBytes ?? settings.maxPayloadBytes;
513
557
  const server = servers.get(`${limit}:${compress}`);
@@ -576,6 +620,28 @@ export class Gateway {
576
620
  });
577
621
  return reply.code(401).send({ error: 'UNAUTHORIZED' });
578
622
  }
623
+ // D-0246: the identity's limit, and its connections on the other servers now; the
624
+ // socket is counted against them when it attaches (this process exactly, then).
625
+ const identityLimit = this.#limitOf(perIdentity, identity, route.path, id);
626
+ if (identityLimit === undefined)
627
+ return reply.code(500).send({ error: 'LIMIT_FAILED' });
628
+ if (identityLimit > 0) {
629
+ let others;
630
+ try {
631
+ others = await this.#othersOf(identity);
632
+ }
633
+ catch (error) {
634
+ // A hub that went away since the state check: refused like a hub not ready.
635
+ logger.log('debug', 'WebSocket upgrade refused', {
636
+ path: route.path,
637
+ routeId: id,
638
+ reason: 'HUB_UNAVAILABLE',
639
+ code: errorCode(error, 'UNKNOWN'),
640
+ });
641
+ return reply.code(503).send({ error: 'UNAVAILABLE', reason: 'HUB_UNAVAILABLE' });
642
+ }
643
+ this.#identityLimits.set(request, { limit: identityLimit, others });
644
+ }
579
645
  // The upgrade hijacks the reply and no onSend hook runs: the session save and auth
580
646
  // cookies happen now (D-0089), or the upgrade is refused before the 101.
581
647
  const started = performance.now();
@@ -624,6 +690,40 @@ export class Gateway {
624
690
  gateway[Symbol.for('skip-override')] = true;
625
691
  web.register(gateway, {});
626
692
  }
693
+ /**
694
+ * D-0246: the identity limit of one upgrade — the route's (a number, or its function of the
695
+ * identity) or the gateway's `maxConnectionsPerIdentity`; undefined when the route's function
696
+ * failed or answered something other than a whole number (logged at error).
697
+ */
698
+ #limitOf(perIdentity, identity, path, routeId) {
699
+ if (perIdentity === undefined)
700
+ return this.settings.maxConnectionsPerIdentity;
701
+ if (typeof perIdentity === 'number')
702
+ return perIdentity;
703
+ try {
704
+ const value = perIdentity(identity);
705
+ if (perIdentityValid(value))
706
+ return value;
707
+ throw new WebsocketError('INVALID_ROUTE', `WebSocket route maxConnectionsPerIdentity returned ${typeof value === 'number' ? value : typeof value}; a whole number from 0 to ${MOST_PER_IDENTITY}`);
708
+ }
709
+ catch (error) {
710
+ this.#throttle.log('error', 'WebSocket identity limit failed; upgrade refused', 'IDENTITY_LIMIT_FAILED', error, { path, routeId });
711
+ return undefined;
712
+ }
713
+ }
714
+ /** D-0246: connections of `identity` the hub lists on the other servers of the cluster. */
715
+ async #othersOf(identity) {
716
+ const own = this.hub.ownerEpoch;
717
+ const { connections } = await this.hub.list({
718
+ tenant: identity.tenant,
719
+ member: identity.member,
720
+ });
721
+ let others = 0;
722
+ for (const record of connections)
723
+ if (record.ownerEpoch !== own)
724
+ others++;
725
+ return others;
726
+ }
627
727
  #watch(task) {
628
728
  this.#tasks.add(task);
629
729
  void task.then(() => this.#tasks.delete(task), () => this.#tasks.delete(task));
@@ -834,6 +934,25 @@ export class Gateway {
834
934
  socket.close(1013, 'Unavailable');
835
935
  return;
836
936
  }
937
+ // D-0246: one identity may not hold every connection. Counted here, synchronously, so
938
+ // upgrades of the same identity racing on this process are counted exactly.
939
+ const key = identityKey(identity);
940
+ const limited = this.#identityLimits.get(request);
941
+ if (limited) {
942
+ const open = (this.#perIdentity.get(key) ?? 0) + limited.others;
943
+ if (open >= limited.limit) {
944
+ this.#throttle.log('warn', 'WebSocket connection refused: identity limit', 'CONNECTION_LIMIT_IDENTITY', undefined, {
945
+ path: route.path,
946
+ routeId: typeof route.config?.id === 'string' ? route.config.id : null,
947
+ tenant: identity.tenant,
948
+ member: identity.member,
949
+ limit: limited.limit,
950
+ open,
951
+ });
952
+ socket.close(IDENTITY_LIMIT, 'CONNECTION_LIMIT_IDENTITY');
953
+ return;
954
+ }
955
+ }
837
956
  const id = randomUUID();
838
957
  let codec;
839
958
  if (sealed) {
@@ -879,6 +998,7 @@ export class Gateway {
879
998
  seen: performance.now(),
880
999
  };
881
1000
  this.#clients.set(id, value);
1001
+ this.#perIdentity.set(key, (this.#perIdentity.get(key) ?? 0) + 1);
882
1002
  const opened = performance.now();
883
1003
  // Connection lifecycle at debug level: who connected from where, and how it ended.
884
1004
  this.context.logger.log('debug', 'WebSocket connected', {
@@ -1050,6 +1170,11 @@ export class Gateway {
1050
1170
  });
1051
1171
  });
1052
1172
  socket.once('close', (code, reason) => {
1173
+ const held = (this.#perIdentity.get(key) ?? 1) - 1;
1174
+ if (held > 0)
1175
+ this.#perIdentity.set(key, held);
1176
+ else
1177
+ this.#perIdentity.delete(key);
1053
1178
  // A failing unsubscribe must not skip the cleanup below (the connection would stay counted).
1054
1179
  this.#releaseAuthorization(value);
1055
1180
  this.context.logger.log('debug', 'WebSocket closed', {
package/dist/index.js CHANGED
@@ -59,7 +59,7 @@ class WebsocketRuntime {
59
59
  /** Factory input: `{ app, options? }`. Options default to `app.config['dokebi-websocket']`. */
60
60
  export const createPlugin = definePlugin({
61
61
  name: 'dokebi-websocket',
62
- version: '0.4.8',
62
+ version: '0.4.9',
63
63
  core: '^0.4.2',
64
64
  options,
65
65
  contributes: [realtime],
package/dist/options.d.ts CHANGED
@@ -8,6 +8,7 @@ export declare const options: import("@dokebi/core").OptionsDeclaration<{
8
8
  readonly logRepeatWindowMs: number;
9
9
  readonly maxBufferedBytes: number;
10
10
  readonly maxConnections: number;
11
+ readonly maxConnectionsPerIdentity: number;
11
12
  readonly maxPayloadBytes: number;
12
13
  readonly maxPending: number;
13
14
  readonly maxRoutePayloadBytes: number;
package/dist/options.js CHANGED
@@ -12,6 +12,13 @@ export const options = defineOptions({
12
12
  maxPayload: o.alias('maxPayloadBytes'),
13
13
  maxRoutePayloadBytes: limit(16_777_216, 'Largest maxPayloadBytes a route may set for its own connections (D-0235); a route above it fails setup with INVALID_ROUTE.'),
14
14
  maxConnections: limit(128, 'Open connections this process accepts at most.', live),
15
+ maxConnectionsPerIdentity: o.integer({
16
+ reloadable: true,
17
+ minimum: 0,
18
+ maximum: LIMIT,
19
+ default: 0,
20
+ description: 'Open connections of one identity (the same tenant and member, every clientId) at most, across the cluster as the hub reports it; one more closes with 4429 CONNECTION_LIMIT_IDENTITY (D-0246). A route may set its own. 0 never limits.',
21
+ }),
15
22
  maxPending: limit(32, 'Messages of one connection waiting for its handler at most; its presence calls are bounded by the same number, separately (later changes are merged).', live),
16
23
  maxPendingMessages: o.alias('maxPending'),
17
24
  maxBufferedBytes: limit(1048576, 'Bytes waiting to be sent to one connection at most; a slower client is closed (SLOW_CONSUMER).', live),
package/dist/router.d.ts CHANGED
@@ -36,6 +36,8 @@ export interface SocketDefinition {
36
36
  readonly maxPayloadBytes?: number;
37
37
  /** D-0235: permessage-deflate on this route. See `WebsocketRoute.compress`. */
38
38
  readonly compress?: boolean;
39
+ /** D-0246: connections of one identity at most on this route. See `WebsocketRoute.maxConnectionsPerIdentity`. */
40
+ readonly maxConnectionsPerIdentity?: WebsocketRoute['maxConnectionsPerIdentity'];
39
41
  authenticate(request: FastifyRequest): Awaitable<WebsocketIdentity | undefined>;
40
42
  authorizeRoom?(identity: WebsocketIdentity, room: string): Awaitable<boolean>;
41
43
  /** Handlers by message type, e.g. `{ 'chat.send': (data, socket) => ... }`. */
package/dist/router.js CHANGED
@@ -68,6 +68,9 @@ export function defineSocket(definition) {
68
68
  ? {}
69
69
  : { maxPayloadBytes: definition.maxPayloadBytes }),
70
70
  ...(definition.compress === undefined ? {} : { compress: definition.compress }),
71
+ ...(definition.maxConnectionsPerIdentity === undefined
72
+ ? {}
73
+ : { maxConnectionsPerIdentity: definition.maxConnectionsPerIdentity }),
71
74
  authenticate: (request) => definition.authenticate(request),
72
75
  ...(definition.authorizeRoom
73
76
  ? {
package/dist/types.d.ts CHANGED
@@ -141,6 +141,15 @@ export interface WebsocketRoute {
141
141
  * times for some CPU per message; see AI.md for the measurement.
142
142
  */
143
143
  readonly compress?: boolean;
144
+ /**
145
+ * D-0246: open connections of one identity (the same tenant and member, every clientId) at
146
+ * most, counted across the cluster as the hub reports it; one more closes with 4429
147
+ * `CONNECTION_LIMIT_IDENTITY`. A whole number from 0 (never limits) to 67108864, or a function
148
+ * of the authenticated identity that returns one (read for each upgrade, so it may follow
149
+ * reloaded app config — one value per realm, say). Without it, the gateway's
150
+ * `maxConnectionsPerIdentity` applies.
151
+ */
152
+ readonly maxConnectionsPerIdentity?: number | ((identity: WebsocketIdentity) => number);
144
153
  authenticate(request: FastifyRequest): Awaitable<WebsocketIdentity | undefined>;
145
154
  authorizeRoom?(identity: WebsocketIdentity, room: string): Awaitable<boolean>;
146
155
  message(data: Uint8Array, session: WebsocketSession): Awaitable<void>;
@@ -33,6 +33,14 @@
33
33
  "x-dokebi-reloadable": true,
34
34
  "description": "Open connections this process accepts at most."
35
35
  },
36
+ "maxConnectionsPerIdentity": {
37
+ "type": "integer",
38
+ "minimum": 0,
39
+ "maximum": 67108864,
40
+ "default": 0,
41
+ "x-dokebi-reloadable": true,
42
+ "description": "Open connections of one identity (the same tenant and member, every clientId) at most, across the cluster as the hub reports it; one more closes with 4429 CONNECTION_LIMIT_IDENTITY (D-0246). A route may set its own. 0 never limits."
43
+ },
36
44
  "maxPending": {
37
45
  "type": "integer",
38
46
  "minimum": 1,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dokebi/websocket",
3
- "version": "0.4.8",
3
+ "version": "0.4.9",
4
4
  "description": "WebSocket routes on @dokebi/web with rooms and broadcast across servers through @dokebi/websocket-hub.",
5
5
  "keywords": [
6
6
  "dokebi",
@@ -54,8 +54,8 @@
54
54
  "@dokebi/websocket-hub": "^0.4.0"
55
55
  },
56
56
  "devDependencies": {
57
- "@dokebi/web": "0.4.12",
58
- "@dokebi/websocket-hub": "0.4.3"
57
+ "@dokebi/web": "0.4.18",
58
+ "@dokebi/websocket-hub": "0.4.5"
59
59
  },
60
60
  "dokebi": {
61
61
  "schemaVersion": 2,