@dokebi/websocket 0.4.6 → 0.4.8

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
@@ -21,7 +21,8 @@ The hub style is chosen in dokebi.yaml `options.dokebi-websocket-hub.mode`. `loc
21
21
 
22
22
  | Key | Type | Default | Description |
23
23
  |---|---|---|---|
24
- | `maxPayloadBytes` | integer | 65536 | Message size |
24
+ | `maxPayloadBytes` | integer | 65536 | Message size of a route without its own (§3b) |
25
+ | `maxRoutePayloadBytes` | integer | 16777216 | The largest `maxPayloadBytes` a route may set (§3b); above it, `INVALID_ROUTE` at `route` |
25
26
  | `maxConnections` (reloadable) | integer | 128 | Connections of this process |
26
27
  | `maxPending` (reloadable) | integer | 32 | Waiting messages per connection (each connection runs in order); also bounds its waiting presence calls, separately |
27
28
  | `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) |
@@ -73,7 +74,7 @@ export const chatSocket = (app: AppContext) => defineSocket({
73
74
  - `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`.
74
75
  - 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.
75
76
  - 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.
76
- - Low level: `context.get(ws).route({ path, config?, origins?, constraints?, version?, seal?, 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.
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.
77
78
  - 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`.
78
79
 
79
80
  ## 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))
@@ -98,6 +99,26 @@ const stop = ws.onPresence(({ tenant, joined, left }) => {});
98
99
  - `onPresence`: joins and leaves of every server per tenant (the same meaning as route `presence`; a server seen for the first time may list existing connections as joined). A listener that throws or rejects is logged as error `PRESENCE_LISTENER_FAILED` (one line per 10 seconds) and the other listeners keep running.
99
100
  - debug: `WebSocket connections listed` (source `hub` or `presence`, count, ms), `WebSocket server broadcast sent` (tenants, failures, recipients, bytes), `WebSocket server kick sent`, `WebSocket presence listener added/removed`, and `listeners` on presence change logs.
100
101
 
102
+ ## 3b. A route's own message limit and compression (0.4.8, [D-0235](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0235-websocket-route-payload-and-deflate.md))
103
+
104
+ ```ts snippet
105
+ // The agent's socket carries reports of hundreds of KB; staff browser sockets keep the gateway's 64 KiB.
106
+ export const agentSocket = (app: AppContext) => defineSocket({
107
+ path: '/agent/ws',
108
+ config: { id: 'agent.ws', auth: false },
109
+ maxPayloadBytes: 4 * 1024 * 1024, // this route only; at most maxRoutePayloadBytes (16 MiB)
110
+ compress: true, // permessage-deflate when the client offers it
111
+ authenticate: agentKey,
112
+ on: { 'sales.report': (data) => sales.store(data) },
113
+ });
114
+ ```
115
+
116
+ - **`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
+ - **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
+ - **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
+ - 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
+
101
122
  ## 4. What the client does
102
123
 
103
124
  ```ts snippet
@@ -109,10 +130,10 @@ socket.onopen = () => reloadState(); // after
109
130
  setInterval(() => socket.send('{"$dokebi":"ping-v1","pong":true}'), 15000); // keeps it open under idleTimeoutMs; asks for a pong
110
131
  ```
111
132
 
112
- - **A dead server (0.4.6, [D-0232](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0232-websocket-pong.md)).** A server that died without closing (a silent network drop, a dev reload that left the TCP connection open) leaves the client's socket "open" until TCP gives up, often 15 minutes; protocol pings do not help, because Node's and browsers' `WebSocket` answer them out of sight of the script. A ping that asks — `{"$dokebi":"ping-v1","pong":true}` — is answered with `{"$dokebi":"pong-v1"}` (sealed on a sealed connection; never a route's message). A plain `ping-v1` stays unanswered (pages before @dokebi/seal 0.4.5 would report the answer as an unknown frame), and a gateway before 0.4.6 answers neither. When nothing at all (no pong, no other frame) arrived for twice the ping interval, the server is gone: reconnect at once, without waiting for `close()` to finish. `@dokebi/websocket/client` does this for any WHATWG `WebSocket` (Node's own, `ws`, a browser's) and has no imports: `heartbeat(socket, { intervalMs, onSilent, requirePong })` pings and calls `onSilent` once; silence counts only after the first pong (an older server is not taken for a dead one) unless `requirePong: true`. `isControlFrame(data)` tells a `$dokebi` frame from a message, and `PING_FRAME`, `PING_PONG_FRAME` and `PONG_FRAME` are the frames. The @dokebi/seal client does the same by itself (close 4001, reconnect).
133
+ - **A dead server (0.4.6, [D-0232](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0232-websocket-pong.md)).** A server that died without closing (a silent network drop, a dev reload that left the TCP connection open) leaves the client's socket "open" until TCP gives up, often 15 minutes; protocol pings do not help, because Node's and browsers' `WebSocket` answer them out of sight of the script. A ping that asks — `{"$dokebi":"ping-v1","pong":true}` — is answered with `{"$dokebi":"pong-v1"}` (sealed on a sealed connection; never a route's message). A plain `ping-v1` stays unanswered (pages before @dokebi/seal 0.4.5 would report the answer as an unknown frame), and a gateway before 0.4.6 answers neither. When nothing at all (no pong, no other frame) arrived for twice the ping interval, the server is gone: reconnect at once, without waiting for `close()` to finish. `@dokebi/websocket-client` (0.1.0, [D-0234](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0234-websocket-client-package.md); no dependencies — a process that only connects installs it alone, not this package's server stack; this package re-exports it as `@dokebi/websocket/client`) does this for any WHATWG `WebSocket` (Node's own, `ws`, a browser's): `heartbeat(socket, { intervalMs, onSilent, requirePong })` pings and calls `onSilent` once; silence counts only after the first pong (an older server is not taken for a dead one) unless `requirePong: true`. `isControlFrame(data)` tells a `$dokebi` frame from a message, and `PING_FRAME`, `PING_PONG_FRAME` and `PONG_FRAME` are the frames. The @dokebi/seal client does the same by itself (close 4001, reconnect).
113
134
 
114
135
  ```ts snippet
115
- import { heartbeat, isControlFrame } from '@dokebi/websocket/client';
136
+ import { heartbeat, isControlFrame } from '@dokebi/websocket-client';
116
137
 
117
138
  function connectAgent(): void {
118
139
  const socket = new WebSocket(CENTER_URL);
@@ -130,7 +151,7 @@ function connectAgent(): void {
130
151
  }
131
152
  ```
132
153
 
133
- - 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). Use only the standard `WebSocket` API. The `{"$dokebi":"ack-v1"}` that old pages send is ignored, not closed (debug `ACK_IGNORED`).
154
+ - 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`).
134
155
  - 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.
135
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.
136
157
 
package/README.md CHANGED
@@ -36,7 +36,8 @@ Prepare the required YAML of websocket-hub. The CLI registration order is redis
36
36
 
37
37
  | Key | Type | Default | Description |
38
38
  |---|---|---|---|
39
- | `maxPayloadBytes` | integer | 65536 | Message size |
39
+ | `maxPayloadBytes` | integer | 65536 | Message size of a route without its own |
40
+ | `maxRoutePayloadBytes` | integer | 16777216 | Largest `maxPayloadBytes` a route may set |
40
41
  | `maxConnections` (reloadable) | integer | 128 | Connections per process |
41
42
  | `maxPending` (reloadable) | integer | 32 | Waiting messages per connection; also bounds its waiting presence calls, separately |
42
43
  | `maxBufferedBytes` (reloadable) | integer | 1048576 | Send buffer before 1013 `Slow consumer` |
@@ -63,7 +64,7 @@ Browsers attach cookies to a WebSocket Upgrade even from another site's page. Wh
63
64
 
64
65
  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.
65
66
 
66
- 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, a send buffer limit and no compression. The hub's own payload and connection limits apply as well.
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.
67
68
 
68
69
  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.
69
70
 
@@ -75,7 +76,7 @@ stop blocks new work, waits for received handlers and broadcasts being sent, the
75
76
  - `defineSocket({ presence: true })` sends `{ type: 'presence', data: { tenant, joined, left } }` to each connection. Given a function, that function handles it as `(change, socket)`.
76
77
  - The first notice a server receives may list connections that existed before as `joined`. Screens should read the list again when this message arrives.
77
78
 
78
- **Is the page alive (`idleTimeoutMs`):** the browser's network layer answers WebSocket pings, so even a page frozen in bfcache or with stopped scripts looks alive. With `idleTimeoutMs` (default 0, off), a connection whose client sent nothing for that long is closed with `4408 Idle`. The client sends `{"$dokebi":"ping-v1"}` periodically from page script to show it is alive. This control frame never reaches the route. With `"pong": true` in it (0.4.6, D-0232) the gateway answers `{"$dokebi":"pong-v1"}`, so a client hears a server that died while its TCP connection stayed open: `heartbeat` of `@dokebi/websocket/client` pings and reports twice the interval of silence.
79
+ **Is the page alive (`idleTimeoutMs`):** the browser's network layer answers WebSocket pings, so even a page frozen in bfcache or with stopped scripts looks alive. With `idleTimeoutMs` (default 0, off), a connection whose client sent nothing for that long is closed with `4408 Idle`. The client sends `{"$dokebi":"ping-v1"}` periodically from page script to show it is alive. This control frame never reaches the route. With `"pong": true` in it (0.4.6, D-0232) the gateway answers `{"$dokebi":"pong-v1"}`, so a client hears a server that died while its TCP connection stayed open: `heartbeat` of `@dokebi/websocket-client` (a client installs that alone; also re-exported as `@dokebi/websocket/client`) pings and reports twice the interval of silence.
79
80
 
80
81
  **Connection lifecycle logs:** at debug it logs connect (`WebSocket connected`: connection ID, tenant, member, clientId, remote address, User-Agent, `Sec-Purpose`) and close (`WebSocket closed`: close code, reason, duration).
81
82
 
package/dist/client.d.ts CHANGED
@@ -1,44 +1 @@
1
- /** App-level keep-alive (D-0033): keeps a connection open under `idleTimeoutMs`; no answer. */
2
- export declare const PING_FRAME = "{\"$dokebi\":\"ping-v1\"}";
3
- /** The same ping asking for an answer (@dokebi/websocket 0.4.6, D-0232). Older servers stay silent. */
4
- export declare const PING_PONG_FRAME = "{\"$dokebi\":\"ping-v1\",\"pong\":true}";
5
- /** The gateway's answer to {@link PING_PONG_FRAME}; never a route's message. */
6
- export declare const PONG_FRAME = "{\"$dokebi\":\"pong-v1\"}";
7
- /** A `$dokebi` control frame (a pong, a sealed hello): not a route's message. */
8
- export declare function isControlFrame(data: unknown): boolean;
9
- /** What the heartbeat needs of a socket: the WHATWG shape (`ws` has it too). */
10
- export interface HeartbeatSocket {
11
- readonly readyState: number;
12
- send(data: string): void;
13
- addEventListener(type: 'open' | 'message' | 'close', listener: () => void): void;
14
- removeEventListener(type: 'open' | 'message' | 'close', listener: () => void): void;
15
- }
16
- export interface HeartbeatOptions {
17
- /** Ping interval (default 15000). Silence is declared after twice this. */
18
- readonly intervalMs?: number;
19
- /**
20
- * Called once when the server sent nothing for twice the interval (the heartbeat has stopped).
21
- * Reconnect from here: `close()` on a dead connection may not end before TCP gives up, so do not
22
- * wait for its `close` event.
23
- */
24
- readonly onSilent: () => void;
25
- /**
26
- * Count silence from the start even before the first pong (default false: only after one, so an
27
- * older server that never answers is not taken for a dead one). Set it when the server is known
28
- * to run @dokebi/websocket 0.4.6 or later.
29
- */
30
- readonly requirePong?: boolean;
31
- }
32
- export interface Heartbeat {
33
- /** Stops pinging and watching (also done by the socket's `close` and by `onSilent`). */
34
- stop(): void;
35
- /** Whether the server has answered a ping on this connection. */
36
- readonly answered: boolean;
37
- }
38
- /**
39
- * Pings the server every `intervalMs` asking for a pong, and calls `onSilent` when nothing (no
40
- * pong, no other frame) arrived for twice the interval. Any frame counts as a sign of life, so a
41
- * busy connection is never declared silent. One heartbeat per socket; start it right after
42
- * creating the socket (it waits for `open`).
43
- */
44
- export declare function heartbeat(socket: HeartbeatSocket, options: HeartbeatOptions): Heartbeat;
1
+ export * from '@dokebi/websocket-client';
package/dist/client.js CHANGED
@@ -1,86 +1,4 @@
1
- // @dokebi/websocket/client (D-0232): the keep-alive frames and a heartbeat for a client that talks
2
- // to a Dokebi socket with a plain WebSocket — Node's built-in `WebSocket`, the `ws` package, or a
3
- // browser's. No imports: it runs wherever a WebSocket does.
4
- //
5
- // A socket to a server that died without closing (a silent network drop, a dev reload that left
6
- // the TCP connection open) stays "open" until TCP gives up, often many minutes. Protocol pings
7
- // do not help: Node's and browsers' WebSocket answer them out of sight of the script. The client
8
- // asks with each app-level ping (`pong: true`), the gateway answers `pong-v1`, and silence past
9
- // twice the interval means the server is gone.
10
- /** App-level keep-alive (D-0033): keeps a connection open under `idleTimeoutMs`; no answer. */
11
- export const PING_FRAME = '{"$dokebi":"ping-v1"}';
12
- /** The same ping asking for an answer (@dokebi/websocket 0.4.6, D-0232). Older servers stay silent. */
13
- export const PING_PONG_FRAME = '{"$dokebi":"ping-v1","pong":true}';
14
- /** The gateway's answer to {@link PING_PONG_FRAME}; never a route's message. */
15
- export const PONG_FRAME = '{"$dokebi":"pong-v1"}';
16
- /** A `$dokebi` control frame (a pong, a sealed hello): not a route's message. */
17
- export function isControlFrame(data) {
18
- return typeof data === 'string' && data.startsWith('{"$dokebi":');
19
- }
20
- const OPEN = 1;
21
- const DEFAULT_INTERVAL_MS = 15_000;
22
- /**
23
- * Pings the server every `intervalMs` asking for a pong, and calls `onSilent` when nothing (no
24
- * pong, no other frame) arrived for twice the interval. Any frame counts as a sign of life, so a
25
- * busy connection is never declared silent. One heartbeat per socket; start it right after
26
- * creating the socket (it waits for `open`).
27
- */
28
- export function heartbeat(socket, options) {
29
- const intervalMs = options.intervalMs ?? DEFAULT_INTERVAL_MS;
30
- if (!Number.isSafeInteger(intervalMs) || intervalMs < 10)
31
- throw new RangeError('heartbeat intervalMs must be an integer of at least 10');
32
- if (typeof options.onSilent !== 'function')
33
- throw new TypeError('heartbeat needs onSilent');
34
- let answered = false;
35
- let last = Date.now();
36
- let timer;
37
- let stopped = false;
38
- const onMessage = (event) => {
39
- last = Date.now();
40
- const data = event?.data;
41
- if (data === PONG_FRAME ||
42
- (typeof data === 'string' && data.startsWith('{"$dokebi":"pong-v1"')))
43
- answered = true;
44
- };
45
- const tick = () => {
46
- if (stopped || socket.readyState !== OPEN)
47
- return;
48
- if ((answered || options.requirePong === true) && Date.now() - last > 2 * intervalMs) {
49
- stop();
50
- options.onSilent();
51
- return;
52
- }
53
- socket.send(PING_PONG_FRAME);
54
- };
55
- const begin = () => {
56
- if (stopped || timer !== undefined)
57
- return;
58
- last = Date.now();
59
- timer = setInterval(tick, intervalMs);
60
- // A process that only waits on its socket must still be able to exit when it closes.
61
- timer.unref?.();
62
- tick();
63
- };
64
- const stop = () => {
65
- if (stopped)
66
- return;
67
- stopped = true;
68
- if (timer !== undefined)
69
- clearInterval(timer);
70
- socket.removeEventListener('open', begin);
71
- socket.removeEventListener('message', onMessage);
72
- socket.removeEventListener('close', stop);
73
- };
74
- socket.addEventListener('message', onMessage);
75
- socket.addEventListener('close', stop);
76
- if (socket.readyState === OPEN)
77
- begin();
78
- else
79
- socket.addEventListener('open', begin);
80
- return {
81
- stop,
82
- get answered() {
83
- return answered;
84
- },
85
- };
86
- }
1
+ // @dokebi/websocket/client (D-0232): the client side now lives in @dokebi/websocket-client, which a
2
+ // client installs alone, without this package's server stack (D-0234). Kept here so imports of
3
+ // `@dokebi/websocket/client` keep working.
4
+ export * from '@dokebi/websocket-client';
package/dist/gateway.js CHANGED
@@ -3,7 +3,7 @@ import { randomUUID } from 'node:crypto';
3
3
  import { setTimeout as delay, setImmediate as immediate } from 'node:timers/promises';
4
4
  import { diagnostics } from '@dokebi/core/libraries';
5
5
  import { runBeforeHijack } from '@dokebi/web/points';
6
- import { PONG_FRAME } from './client.js';
6
+ import { PONG_FRAME } from '@dokebi/websocket-client';
7
7
  import { WebsocketError } from './errors.js';
8
8
  import { PLAIN_PROTOCOL, SEAL_PROTOCOL, } from './types.js';
9
9
  /** `WebSocket.OPEN` of ws (a constant, so ws itself loads only when a route needs it). */
@@ -98,6 +98,43 @@ function sameRoomsAndMetadata(a, b) {
98
98
  }
99
99
  return true;
100
100
  }
101
+ /**
102
+ * D-0235: the largest incoming message of this route, or undefined for the gateway's
103
+ * `maxPayloadBytes`; at most `maxRoutePayloadBytes`.
104
+ */
105
+ function payloadOf(route, most) {
106
+ const value = route.maxPayloadBytes;
107
+ if (value === undefined)
108
+ return undefined;
109
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1 || value > most)
110
+ throw new WebsocketError('INVALID_ROUTE', `WebSocket route maxPayloadBytes is a whole number of bytes from 1 to ${most} (maxRoutePayloadBytes)`);
111
+ return value;
112
+ }
113
+ /** D-0235: permessage-deflate on this route's connections (off unless `true`). */
114
+ function compressOf(route) {
115
+ const value = route.compress;
116
+ if (value === undefined || value === false)
117
+ return false;
118
+ if (value !== true)
119
+ throw new WebsocketError('INVALID_ROUTE', 'WebSocket route compress is true or false');
120
+ return true;
121
+ }
122
+ /**
123
+ * permessage-deflate of a `compress: true` route (D-0235): no context kept between messages on
124
+ * either side, messages under 1 KiB sent as they are, level 1 (most of the size for little CPU),
125
+ * an 8 KiB window and memLevel 7 (measured: the same ratio on JSON reports as the defaults, less
126
+ * memory per connection), at most 10 zlib jobs at once per process (ws). Inflated messages still
127
+ * stop at the route's maxPayloadBytes (a small compressed bomb is 1009).
128
+ */
129
+ const DEFLATE = Object.freeze({
130
+ serverNoContextTakeover: true,
131
+ clientNoContextTakeover: true,
132
+ threshold: 1024,
133
+ concurrencyLimit: 10,
134
+ zlibDeflateOptions: { level: 1, memLevel: 7 },
135
+ serverMaxWindowBits: 13,
136
+ clientMaxWindowBits: 13,
137
+ });
101
138
  function sealOf(route) {
102
139
  const value = route.seal;
103
140
  if (value !== undefined && typeof value !== 'boolean' && typeof value !== 'function')
@@ -237,6 +274,12 @@ export class Gateway {
237
274
  #upgraded = new WeakSet();
238
275
  /** Replies of authenticated upgrades, read when ws writes the 101 head (their Set-Cookie). */
239
276
  #replies = new WeakMap();
277
+ /**
278
+ * D-0235: the socket server of an upgrade whose route has its own message limit or compression
279
+ * (read by the base server's handleUpgrade), and the limit of every upgrade (for the 1009 log).
280
+ */
281
+ #servers = new WeakMap();
282
+ #limits = new WeakMap();
240
283
  #frozen = false;
241
284
  #closing = false;
242
285
  #loop;
@@ -276,11 +319,15 @@ export class Gateway {
276
319
  throw new WebsocketError('SEAL_PROVIDER_MISSING', `WebSocket route ${route.path} is sealed; register the dokebi-seal plugin`);
277
320
  const config = configOf(route);
278
321
  const id = typeof config?.id === 'string' ? config.id : null;
279
- this.#routes.push({ route: { ...route }, origins, config, id });
322
+ const maxPayloadBytes = payloadOf(route, settings.maxRoutePayloadBytes);
323
+ const compress = compressOf(route);
324
+ this.#routes.push({ route: { ...route }, origins, config, id, maxPayloadBytes, compress });
280
325
  context.logger.log('debug', 'WebSocket route registered', {
281
326
  path: route.path,
282
327
  routeId: id,
283
328
  version: route.version ?? null,
329
+ maxPayloadBytes: maxPayloadBytes ?? settings.maxPayloadBytes,
330
+ compress,
284
331
  });
285
332
  },
286
333
  list: (filter) => this.#list(filter),
@@ -343,30 +390,83 @@ export class Gateway {
343
390
  return;
344
391
  }
345
392
  const { default: fastifyWebsocket } = await import('@fastify/websocket');
393
+ // D-0059 §4: a client with a seal bridge offers `dokebi.seal` and `dokebi.plain`.
394
+ // A sealed upgrade selects `dokebi.seal` only (never plain; not offered: 4415 after the
395
+ // upgrade). A plain upgrade selects `dokebi.plain` when offered (browsers fail a handshake
396
+ // that selects none of the offered protocols), otherwise nothing, as for old clients.
397
+ const handleProtocols = (protocols, request) => {
398
+ if (this.#sealed.has(request))
399
+ return protocols.has(SEAL_PROTOCOL) ? SEAL_PROTOCOL : false;
400
+ return protocols.has(PLAIN_PROTOCOL) ? PLAIN_PROTOCOL : false;
401
+ };
346
402
  await scope.register(fastifyWebsocket, {
347
403
  options: {
348
404
  maxPayload: settings.maxPayloadBytes,
349
405
  perMessageDeflate: false,
350
- // D-0059 §4: a client with a seal bridge offers `dokebi.seal` and `dokebi.plain`.
351
- // A sealed upgrade selects `dokebi.seal` only (never plain; not offered: 4415 after the
352
- // upgrade). A plain upgrade selects `dokebi.plain` when offered (browsers fail a handshake
353
- // that selects none of the offered protocols), otherwise nothing, as for old clients.
354
- handleProtocols: (protocols, request) => {
355
- if (this.#sealed.has(request))
356
- return protocols.has(SEAL_PROTOCOL) ? SEAL_PROTOCOL : false;
357
- return protocols.has(PLAIN_PROTOCOL) ? PLAIN_PROTOCOL : false;
358
- },
406
+ handleProtocols,
359
407
  },
360
- // A wsHandler that threw: the client gets 1011, the cause goes to the log (D-0047).
361
- errorHandler: (error, socket) => {
408
+ errorHandler: (error, socket, request) => {
409
+ // D-0235: a message over the route's limit. ws has already closed the connection with
410
+ // 1009 (Message Too Big); a limit, not a defect, so it is logged at debug (counted).
411
+ if (error?.code === 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH') {
412
+ this.#throttle.log('debug', 'WebSocket message over the route limit; closed 1009', 'MESSAGE_TOO_BIG', undefined, {
413
+ routeId: request.routeOptions?.config?.id ?? null,
414
+ path: request.routeOptions?.url ?? null,
415
+ maxPayloadBytes: this.#limits.get(request.raw) ?? settings.maxPayloadBytes,
416
+ });
417
+ // ws sends the close frame and then ends the TCP connection itself (its reader
418
+ // failed), so the client sees 1009 at once.
419
+ return;
420
+ }
421
+ // A wsHandler that threw: the client gets 1011, the cause goes to the log (D-0047).
362
422
  this.#throttle.log('error', 'WebSocket handler failed', 'SOCKET_FAILURE', error);
363
423
  socket.close(1011, 'Socket failure');
364
424
  },
365
425
  });
426
+ // D-0235: one socket server per (message limit, compression) other than the gateway's:
427
+ // ws fixes both per server, at the upgrade. Same protocols and Set-Cookie handling; the
428
+ // gateway tracks its connections itself, so these do not.
429
+ const servers = new Map();
430
+ const special = this.#routes.filter((entry) => entry.compress ||
431
+ (entry.maxPayloadBytes !== undefined &&
432
+ entry.maxPayloadBytes !== settings.maxPayloadBytes));
433
+ if (special.length > 0) {
434
+ const { WebSocketServer } = await import('ws');
435
+ for (const entry of special) {
436
+ const limit = entry.maxPayloadBytes ?? settings.maxPayloadBytes;
437
+ const key = `${limit}:${entry.compress}`;
438
+ if (servers.has(key))
439
+ continue;
440
+ const server = new WebSocketServer({
441
+ noServer: true,
442
+ clientTracking: false,
443
+ maxPayload: limit,
444
+ perMessageDeflate: entry.compress ? DEFLATE : false,
445
+ handleProtocols,
446
+ });
447
+ server.on('headers', (headers, raw) => onHeaders(headers, raw));
448
+ servers.set(key, server);
449
+ this.context.logger.log('debug', 'WebSocket socket server for a route limit', {
450
+ maxPayloadBytes: limit,
451
+ compress: entry.compress,
452
+ });
453
+ }
454
+ // @dokebi/websocket hands every upgrade to its server's handleUpgrade: an upgrade of such
455
+ // a route goes to that route's server instead (ws's public API, same arguments).
456
+ const base = scope.websocketServer;
457
+ const upgrade = base.handleUpgrade.bind(base);
458
+ base.handleUpgrade = (request, socket, head, callback) => {
459
+ const own = this.#servers.get(request);
460
+ if (!own)
461
+ return upgrade(request, socket, head, callback);
462
+ this.#servers.delete(request);
463
+ own.handleUpgrade(request, socket, head, callback);
464
+ };
465
+ }
366
466
  // The upgrade hijacks the reply: ws writes the 101 head itself and no onSend hook runs.
367
467
  // Set-Cookie on the reply (authenticate's hooks, a guard, the before-hijack steps of the
368
468
  // upgrade's preValidation, D-0089) goes out with the 101.
369
- scope.websocketServer.on('headers', (headers, raw) => {
469
+ const onHeaders = (headers, raw) => {
370
470
  this.#upgraded.add(raw);
371
471
  const reply = this.#replies.get(raw);
372
472
  if (!reply)
@@ -383,7 +483,8 @@ export class Gateway {
383
483
  }
384
484
  headers.push(`Set-Cookie: ${cookie}`);
385
485
  }
386
- });
486
+ };
487
+ scope.websocketServer.on('headers', onHeaders);
387
488
  // An upgrade answered with a plain response (a refusal) is never handed to ws, so its raw
388
489
  // socket stays open: Node detached it for the 'upgrade' event and no HTTP server owns it.
389
490
  // @fastify/websocket destroys it in its onResponse hook only when its own onRequest hook ran
@@ -406,8 +507,10 @@ export class Gateway {
406
507
  }
407
508
  done();
408
509
  });
409
- for (const { route, origins, config, id } of this.#routes) {
510
+ for (const { route, origins, config, id, maxPayloadBytes, compress } of this.#routes) {
410
511
  const logger = this.context.logger;
512
+ const limit = maxPayloadBytes ?? settings.maxPayloadBytes;
513
+ const server = servers.get(`${limit}:${compress}`);
411
514
  scope.route({
412
515
  method: 'GET',
413
516
  url: route.path,
@@ -495,6 +598,9 @@ export class Gateway {
495
598
  });
496
599
  this.#identities.set(request, identity);
497
600
  this.#replies.set(request.raw, reply);
601
+ this.#limits.set(request.raw, limit);
602
+ if (server)
603
+ this.#servers.set(request.raw, server);
498
604
  const seal = route.seal;
499
605
  if (seal === undefined || seal === false)
500
606
  return;
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.6',
62
+ version: '0.4.8',
63
63
  core: '^0.4.2',
64
64
  options,
65
65
  contributes: [realtime],
package/dist/options.d.ts CHANGED
@@ -10,6 +10,7 @@ export declare const options: import("@dokebi/core").OptionsDeclaration<{
10
10
  readonly maxConnections: number;
11
11
  readonly maxPayloadBytes: number;
12
12
  readonly maxPending: number;
13
+ readonly maxRoutePayloadBytes: number;
13
14
  readonly sealDriftMs: number;
14
15
  readonly shutdownTimeoutMs: number;
15
16
  }>;
package/dist/options.js CHANGED
@@ -10,6 +10,7 @@ const live = { reloadable: true };
10
10
  export const options = defineOptions({
11
11
  maxPayloadBytes: limit(65536, 'Largest incoming frame in bytes.'),
12
12
  maxPayload: o.alias('maxPayloadBytes'),
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.'),
13
14
  maxConnections: limit(128, 'Open connections this process accepts at most.', live),
14
15
  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),
15
16
  maxPendingMessages: o.alias('maxPending'),
package/dist/router.d.ts CHANGED
@@ -32,6 +32,10 @@ export interface SocketDefinition {
32
32
  readonly version?: string;
33
33
  /** Seals this route's frames (D-0059 §4; needs the dokebi-seal plugin). See `WebsocketRoute.seal`. */
34
34
  readonly seal?: WebsocketRoute['seal'];
35
+ /** D-0235: this route's message limit in bytes. See `WebsocketRoute.maxPayloadBytes`. */
36
+ readonly maxPayloadBytes?: number;
37
+ /** D-0235: permessage-deflate on this route. See `WebsocketRoute.compress`. */
38
+ readonly compress?: boolean;
35
39
  authenticate(request: FastifyRequest): Awaitable<WebsocketIdentity | undefined>;
36
40
  authorizeRoom?(identity: WebsocketIdentity, room: string): Awaitable<boolean>;
37
41
  /** Handlers by message type, e.g. `{ 'chat.send': (data, socket) => ... }`. */
package/dist/router.js CHANGED
@@ -64,6 +64,10 @@ export function defineSocket(definition) {
64
64
  ...(definition.constraints === undefined ? {} : { constraints: definition.constraints }),
65
65
  ...(definition.version === undefined ? {} : { version: definition.version }),
66
66
  ...(definition.seal === undefined ? {} : { seal: definition.seal }),
67
+ ...(definition.maxPayloadBytes === undefined
68
+ ? {}
69
+ : { maxPayloadBytes: definition.maxPayloadBytes }),
70
+ ...(definition.compress === undefined ? {} : { compress: definition.compress }),
67
71
  authenticate: (request) => definition.authenticate(request),
68
72
  ...(definition.authorizeRoom
69
73
  ? {
package/dist/types.d.ts CHANGED
@@ -126,6 +126,21 @@ export interface WebsocketRoute {
126
126
  * `Bad frame` on a frame that does not open. Routes and handlers see plain text either way.
127
127
  */
128
128
  readonly seal?: boolean | ((request: FastifyRequest) => boolean);
129
+ /**
130
+ * D-0235: the largest message this route's connections may send, in bytes (default: the
131
+ * gateway's `maxPayloadBytes`; at most `maxRoutePayloadBytes`). A larger one closes the
132
+ * connection with 1009 `Message Too Big` (debug `MESSAGE_TOO_BIG` names the route and limit).
133
+ * For a machine socket that carries large results; leave browser sockets at the default. On a
134
+ * sealed route the limit is on the sealed frame.
135
+ */
136
+ readonly maxPayloadBytes?: number;
137
+ /**
138
+ * D-0235: permessage-deflate on this route's connections when the client offers it (browsers
139
+ * and `ws` do; Node's built-in WebSocket does not). Off by default. No zlib context is kept
140
+ * between messages, messages under 1 KiB go as they are, level 1. JSON reports shrink several
141
+ * times for some CPU per message; see AI.md for the measurement.
142
+ */
143
+ readonly compress?: boolean;
129
144
  authenticate(request: FastifyRequest): Awaitable<WebsocketIdentity | undefined>;
130
145
  authorizeRoom?(identity: WebsocketIdentity, room: string): Awaitable<boolean>;
131
146
  message(data: Uint8Array, session: WebsocketSession): Awaitable<void>;
@@ -18,6 +18,13 @@
18
18
  "x-dokebi-alias-of": "maxPayloadBytes",
19
19
  "description": "Deprecated name of maxPayloadBytes; use that key."
20
20
  },
21
+ "maxRoutePayloadBytes": {
22
+ "type": "integer",
23
+ "minimum": 1,
24
+ "maximum": 67108864,
25
+ "default": 16777216,
26
+ "description": "Largest maxPayloadBytes a route may set for its own connections (D-0235); a route above it fails setup with INVALID_ROUTE."
27
+ },
21
28
  "maxConnections": {
22
29
  "type": "integer",
23
30
  "minimum": 1,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dokebi/websocket",
3
- "version": "0.4.6",
3
+ "version": "0.4.8",
4
4
  "description": "WebSocket routes on @dokebi/web with rooms and broadcast across servers through @dokebi/websocket-hub.",
5
5
  "keywords": [
6
6
  "dokebi",
@@ -44,6 +44,7 @@
44
44
  "test": "node -e \"require('node:fs').rmSync('.tmp/tests',{recursive:true,force:true})\" && tsc -p tsconfig.test.json && node --test \".tmp/tests/tests/*.test.js\""
45
45
  },
46
46
  "dependencies": {
47
+ "@dokebi/websocket-client": "^0.1.0",
47
48
  "@fastify/websocket": "11.3.4",
48
49
  "ws": "8.22.0"
49
50
  },