@dokebi/websocket 0.4.7 → 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 +23 -2
- package/README.md +3 -2
- package/dist/gateway.js +121 -15
- package/dist/index.js +1 -1
- package/dist/options.d.ts +1 -0
- package/dist/options.js +1 -0
- package/dist/router.d.ts +4 -0
- package/dist/router.js +4 -0
- package/dist/types.d.ts +15 -0
- package/options.schema.json +7 -0
- package/package.json +1 -1
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
|
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
|
|
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
|
|
package/dist/gateway.js
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
361
|
-
|
|
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
|
-
|
|
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.
|
|
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>;
|
package/options.schema.json
CHANGED
|
@@ -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,
|