@dokebi/websocket 0.4.1 → 0.4.3

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
@@ -1,4 +1,4 @@
1
- # AI guide — @dokebi/websocket 0.4.1
1
+ # AI guide — @dokebi/websocket
2
2
 
3
3
  Opens WebSocket routes on dokebi-web (Fastify) and connects broadcasts and the connection list across servers and workers through @dokebi/websocket-hub. A broadcast is **at most once**: once the hub sends it out it is done; there is no client ACK or resend ([D-0057](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0057-websocket-broadcast-without-ack.md)). No views or DB are forced. Node >=24, core ^0.4.0, peers: @dokebi/web, @dokebi/websocket-hub. Details are in the [README](README.md).
4
4
 
@@ -22,14 +22,17 @@ The hub style is chosen in dokebi.yaml `options.dokebi-websocket-hub.mode`. `loc
22
22
  | Key | Type | Default | Description |
23
23
  |---|---|---|---|
24
24
  | `maxPayloadBytes` | integer | 65536 | Message size |
25
- | `maxConnections` | integer | 128 | Connections of this process |
26
- | `maxPending` | integer | 32 | Waiting messages per connection (each connection runs in order); also bounds its waiting presence calls, separately |
27
- | `maxBufferedBytes` | 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) |
25
+ | `maxConnections` (reloadable) | integer | 128 | Connections of this process |
26
+ | `maxPending` (reloadable) | integer | 32 | Waiting messages per connection (each connection runs in order); also bounds its waiting presence calls, separately |
27
+ | `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) |
28
28
  | `shutdownTimeoutMs` | integer ms | 2000 | Socket close wait at drain (not a limit on work) |
29
- | `heartbeatMs` | integer ms | 10000 | ping/pong |
30
- | `idleTimeoutMs` | integer ms | 0 (off) | Closes with 4408 `Idle` when the client sends nothing for this long. Pages send `{"$dokebi":"ping-v1"}` periodically |
31
- | `hubWaitMs` | integer ms | 5000 | How long an upgrade waits while the hub is recovering (0 = 503 at once) |
29
+ | `heartbeatMs` (reloadable) | integer ms | 10000 | ping/pong |
30
+ | `idleTimeoutMs` (reloadable) | integer ms | 0 (off) | Closes with 4408 `Idle` when the client sends nothing for this long. Pages send `{"$dokebi":"ping-v1"}` periodically |
31
+ | `hubWaitMs` (reloadable) | integer ms | 5000 | How long an upgrade waits while the hub is recovering (0 = 503 at once) |
32
32
  | `sealDriftMs` | integer 1000–600000 | 60000 | Sealed connections (§4a): a frame whose ts differs from the server clock by more is 4400. Nonces are remembered for twice as long |
33
+ | `beforeUpgradeTimeoutMs` (reloadable) | integer 100–600000 | 5000 | The longest wait for the before-hijack steps (session save, auth cookies; below); slower refuses the upgrade with 500 `COMMIT_FAILED`. Size it above the slowest session store write you accept |
34
+ | `hubFanOut` | integer 1–1024 | 16 | Hub calls one `tenantPrefix` send, broadcast, kick or list runs at once (one per tenant). Raise it when one prefix covers many tenants; each call holds one hub request (cluster: one message to the leader) |
35
+ | `logRepeatWindowMs` | integer 1000–3600000 | 10000 | Window of the repeated per-message and per-socket failure logs: the first is written in full, the rest of the window are counted (`repeated`, `intervalMs`) |
33
36
 
34
37
  Keys renamed in 0.4.0 ([D-0071](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0071-option-vocabulary.md)). The old name is accepted with the warning `OPTION_DEPRECATED`; old and new together fail with `INVALID_OPTIONS`; 0.5.0 rejects it.
35
38
 
@@ -46,6 +49,7 @@ import { defineSocket } from '@dokebi/websocket';
46
49
 
47
50
  export const chatSocket = (app: AppContext) => defineSocket({
48
51
  path: '/ws',
52
+ config: { id: 'chat' }, // optional: the route id (D-0140), as config.id of a web route
49
53
  version: BUILD_VERSION, // a different client ?dokebiVersion= gets 4426 Reload required
50
54
  origins: ['https://app.a.com'], // omitted: same Host only (other Origins get 403)
51
55
  async authenticate(request) { // from a verified session or token; undefined → 401
@@ -53,7 +57,7 @@ export const chatSocket = (app: AppContext) => defineSocket({
53
57
  return user && { tenant: user.orgId, member: user.id, clientId: String(request.query.clientId) };
54
58
  },
55
59
  authorizeRoom: (identity, room) => rooms.canJoin(identity, room),
56
- presence: true, // joins and leaves of the same tenant arrive as { type: 'presence', data }
60
+ presence: true, // joins and leaves of the same tenant arrive as { type: 'presence', data }; one change is serialized once for all its sockets (D-0107)
57
61
  on: {
58
62
  'chat.send': async (data, socket) => {
59
63
  const { room, text } = data as { room: string; text: string };
@@ -68,8 +72,9 @@ export const chatSocket = (app: AppContext) => defineSocket({
68
72
  - Message format: JSON `{ type, data?, id? }`. `reply` and `error` are reserved types. An unknown type is `UNKNOWN_TYPE`, a malformed message `INVALID_MESSAGE`, and a handler error answers `{ type: 'error', id?, code }` with the error's `code` (upper-case form) or `HANDLER_FAILED` (message and stack are not sent; they go to the server log, §7).
69
73
  - `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`.
70
74
  - 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.
71
- - Low level: `context.get(ws).route({ path, 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.
72
- - Exports: `createPlugin`, `defineSocket`, `options`, `WebsocketError`, `SEAL_PROTOCOL`, `PLAIN_PROTOCOL`, types `WebsocketApi`, `WebsocketOptions`, `WebsocketRoute`, `WebsocketSession`, `WebsocketIdentity`, `WebsocketPeer`, `WebsocketPresence`, `WebsocketErrorDetails`, `WebsocketConnectionInfo`, `WebsocketFilter`, `WebsocketReceipt`, `WebsocketKickReceipt`, `SocketDefinition`, `SocketContext`, `SocketHandler`, `SocketCodecProvider`, `SocketCodec`, `SocketCodecConnection`, `SocketNonceStore`, `WebsocketTransport`, `WebsocketNamespaceHandle`, `WebsocketNamespaceTarget`, `WebsocketErrorCode`.
75
+ - 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).
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
+ - 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`.
73
78
 
74
79
  ## 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))
75
80
 
@@ -86,8 +91,9 @@ const stop = ws.onPresence(({ tenant, joined, left }) => {});
86
91
  ```
87
92
 
88
93
  - Filter (`WebsocketFilter`): **exactly one** of `tenant` and `tenantPrefix`, plus `room?` and `member?` (both: that person in that room). Strings of 1–256 bytes. Otherwise `INVALID_FILTER`. The `send` type follows the handler type rules (`INVALID_TYPE`); data that is not JSON is `INVALID_DATA`.
89
- - `tenant`: one hub call; failures keep the hub code (`RECOVERING`, `BUSY`, `OUTCOME_UNKNOWN`). `tenantPrefix`: the hub has no lookup across tenants, so the tenants matching the prefix are collected from this server's presence mirror and called per tenant (16 at a time). When some fail it rejects with the first failure's code and attaches `receipt` (the successful tenants' part) and `cause` (an AggregateError). With no known tenant nothing is sent and it returns `{ ids: [], recipients: [] }`.
94
+ - `tenant`: one hub call; failures keep the hub code (`RECOVERING`, `BUSY`, `OUTCOME_UNKNOWN`). `tenantPrefix`: the hub has no lookup across tenants, so the tenants matching the prefix are collected from this server's presence mirror and called per tenant (`hubFanOut` at a time, 16 by default). When some fail it rejects with the first failure's code and attaches `receipt` (the successful tenants' part) and `cause` (an AggregateError). With no known tenant nothing is sent and it returns `{ ids: [], recipients: [] }`.
90
95
  - Receipt `{ ids, recipients }`: the hub broadcast id per tenant and the connections matching at that moment. Not a delivery confirmation (D-0057). kick (close code 4000–4999, default 4403) returns `{ ids }`.
96
+ - **A kick that fails with `OUTCOME_UNKNOWN` may have left matching sockets open.** The hub sends it to every server connected to its leader; a server that is not (just after a leader failover, before it has reconnected, or one that died with the old leader, until its record expires) does not get it, and the call fails once the others were sent. The kick is not kept for later: when it must take effect (removing a member), call it again until it resolves; each call closes the sockets that match at that moment. Measured with three cluster servers whose leader was killed: the first kick on the new leader closed its own socket and failed with `OUTCOME_UNKNOWN` (the socket of the server that had not reconnected yet stayed open); the second, five seconds later, resolved and closed it.
91
97
  - Sealing: it uses the broadcast delivery path as is, so sealed sockets get a per-socket sealed copy and plain sockets share one buffer. Binary is never sent to sealed sockets (§4a).
92
98
  - `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.
93
99
  - 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.
@@ -105,7 +111,7 @@ setInterval(() => socket.send('{"$dokebi":"ping-v1"}'), 15000); // when
105
111
 
106
112
  - 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 browser entry `@dokebi/websocket/client` (`DeliveryReceiver`) was removed in 0.2.0 (importing it fails to resolve). Use only the standard `WebSocket` API. The `{"$dokebi":"ack-v1"}` that old pages send is ignored, not closed (debug `ACK_IGNORED`).
107
113
  - 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.
108
- - Close codes: 4426 reload, 4409 duplicate clientId (`Duplicate client`), 4408 idle, 1013 hub unavailable, slow consumer or a full replay nonce store (`Try again later`, D-0075), 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.
114
+ - 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.
109
115
 
110
116
  ## 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)
111
117
 
@@ -115,13 +121,15 @@ Every frame is sealed per host (or route). **This package does not know the seal
115
121
  - Contract (shape only): `SocketCodecProvider { forConnection({ host, path, userAgent, nonces, driftMs }): SocketCodec }`, `SocketCodec { decode(frame): Promise<string>; encode(text): string; hello(): string }`. `host` is the web `requestHost` (with trustProxy applied) in lower case without the port, `path` the upgrade path (no query), `nonces` is `hub.nonces()` (cluster = shared in Redis, local = in process), `driftMs` is `sealDriftMs`.
116
122
  - Negotiation: a client with the seal bridge offers the subprotocols `['dokebi.seal', 'dokebi.plain']` (constants `SEAL_PROTOCOL`, `PLAIN_PROTOCOL`). A sealed connection picks only `dokebi.seal` (never plain). When it is not offered, the connection is closed after the upgrade with **4415** `Seal required` (no reconnect). A plain connection picks `dokebi.plain` when offered, otherwise nothing (old clients). Clients decide sealing only by `ws.protocol === 'dokebi.seal'`, so the same page code runs in plain on a plain host.
117
123
  - Flow: the server first sends a sealed `{"$dokebi":"hello-v1"}` (the client measures clock offset from its ts). Incoming frames are opened in the connection's order chain, then go to control frames (`$dokebi` ping, ack) or the route (counted in waiting messages). Routes and handlers see plain text.
118
- - Refusal: unsealed frames, binary frames, frames that fail to open, drift and replays get **4400** `Bad frame`. The reason (`no-prefix`, `plain-rejected`, `drift`, `replay`, `open-failed`, `binary`) goes only to the warn log, never to the client (so replay success cannot be probed). After a refusal no further frames of that connection are read. One exception: when the hub's local nonce store is full of live nonces (seal reason `capacity`, [D-0075](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0075-replay-capacity.md)), the frame is refused and the connection closes with **1013** `Try again later` (temporary: the client reconnects with backoff), warn `SEAL_FRAME_REFUSED` with `reason: capacity`.
124
+ - Refusal: unsealed frames, binary frames, frames that fail to open, drift and replays get **4400** `Bad frame`. The reason (`no-prefix`, `plain-rejected`, `drift`, `replay`, `open-failed`, `binary`) goes only to the warn log, never to the client (so replay success cannot be probed). After a refusal no further frames of that connection are read. One exception: when the hub's local nonce store is full of live nonces (seal reason `capacity`, [D-0075](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0075-replay-capacity.md)), the frame is refused and the connection closes with **1013** `Try again later` (temporary: the client reconnects with backoff), warn `SEAL_FRAME_REFUSED` with `reason: capacity`. Likewise a frame the nonce store could not check — the store failed or timed out (seal reason `unavailable`), or the codec failed without a reason of the list above ([D-0096](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0096-seal-shared-nonces.md) §2) — is never the client's fault: 1013 `Try again later`, error `SEAL_FRAME_UNCHECKED` with `reason` and the whole cause. A frame stamped before the nonce store lost its nonces (seal reason `nonces-lost`, `SEAL_NONCES_LOST`: a Redis restart without persistence, a FLUSHALL, a new process) is refused the same way, 1013 `Try again later` (the client reconnects and seals again), with its own warn `SEAL_NONCES_LOST` (`reason`, the cause; once per `logRepeatWindowMs` + `repeated`): the store works, so it is not `SEAL_FRAME_UNCHECKED`.
119
125
  - Outgoing: replies, `send`, presence and broadcasts are all sealed. Plain sockets share one broadcast buffer; only sealed sockets are sealed per recipient. UTF-8 bytes are sealed as text; `send` of non-UTF-8 bytes is refused with `SEAL_BINARY_UNSUPPORTED` (in `defineSocket`, an error reply with that code). Binary broadcasts are not sent to sealed sockets and are counted (warn `SEAL_BINARY_UNSUPPORTED`, `dropped`).
120
126
  - Cost (2026-10-15, `benchmarks/results/2026-10-15-websocket-seal.json`): one seal plus open about 15–17 µs (1 KB), a broadcast to 500 recipients p50 about 14.5 ms (plain 1.6 ms), a request round trip with a Redis nonce p50 0.38 ms (plain 0.04 ms).
121
127
 
122
128
  ## 5. Response codes and delivery semantics
123
129
 
124
- - Upgrade: origin refused 403 (`ORIGIN_FORBIDDEN`; authenticate is not called), authentication failure 401, hub not ready, shutting down or at capacity 503 `{ error: 'UNAVAILABLE', reason: CLOSING | HUB_<state> | CAPACITY }`, a plain HTTP request 426.
130
+ - Without any WebSocket route the plugin handles no upgrades (2026-10-31, D-0182): `@fastify/websocket` and `ws` are not loaded and no Fastify hook is added, so the HTTP routes of the app pay nothing for it (its hooks, and an `onResponse` hook's per-request response listeners); an upgrade request is then an ordinary request (404), debug `WebSocket upgrades not handled: no WebSocket route` (`WEBSOCKET_NO_ROUTES`). With a route, both load when the server starts.
131
+ - Cookies on the upgrade (D-0089): the upgrade hijacks the Fastify reply (ws writes the 101 head), so **no onSend hook runs**. After origin, availability and `authenticate`, the upgrade runs the before-hijack steps that plugins register for the work they otherwise do in onSend — the @dokebi/session save (or rolling refresh) and the @dokebi/auth cookies (a remember-me restore by a `required` guard rotates the token) — and waits for them, at most `beforeUpgradeTimeoutMs` (5 s). Then every `Set-Cookie` on the reply (those steps, a hook, a guard) is sent with the 101; browsers apply it there. A value with a line break is dropped, error `UPGRADE_COOKIE_INVALID`. A step that fails or times out refuses the upgrade before the 101: 500 `{ error: 'COMMIT_FAILED' }`, error `UPGRADE_COMMIT_FAILED` (the full cause). After the 101 the request's session is final (a change throws `CLOSED`). The steps are matched by name only (`Symbol.for('dokebi.web.beforeHijack')` on the Fastify instance): this package imports neither plugin.
132
+ - Upgrade: origin refused 403 (`ORIGIN_FORBIDDEN`; authenticate is not called), authentication failure 401, an `authorization.valid()` that throws 500 `{ error: 'AUTHORIZATION_FAILED' }` (error `SOCKET_AUTHORIZATION_FAILED`), hub not ready, shutting down or at capacity 503 `{ error: 'UNAVAILABLE', reason: CLOSING | HUB_<state> | CAPACITY }`, the session save before the 101 failed 500 `{ error: 'COMMIT_FAILED' }`, a plain HTTP request 426.
125
133
  - `broadcast` ends with the receipt `{ id, recipients }` once the hub sends it out (D-0057). `recipients` are the connections matching when it was sent, not a confirmation of receipt. Failures come at once: `RECOVERING` (the hub is not connected to the leader; not sent), `OUTCOME_UNKNOWN` (disconnected after sending, before the answer; it may have been sent), `BUSY` (broadcasts in progress reached the hub's `maxPending`). Nothing is resent; the handler decides whether to send again. Messages per connection run in order, so awaiting in a handler holds only one leader round trip (milliseconds). When the result is not needed, use `void ...catch()`.
126
134
  - **Never leave work that must not be missed (order state, payment results) to a broadcast.** Store it in the DB and let the page read the latest state when it reconnects. Use broadcasts as "it changed, read again" notices.
127
135
  - Sending a broadcast does not wait per socket; it goes into the send queue (order kept per socket). Only slow sockets are closed.
@@ -135,10 +143,10 @@ stop: block new work → wait for received handlers and broadcasts being sent
135
143
 
136
144
  ## 7. Logs ([D-0047](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0047-logging-and-no-silent-errors.md))
137
145
 
138
- - Exceptions are never dropped silently. Failures other than those turned into close codes or error replies are `error`: a fixed English message + `code` + `error` (the full original error: name, whole message, stack and `Caused by: …` for each cause, address, port and errno text included; only URL credentials masked as `//***@`; cut only beyond 16 KB). Examples: handler failure `WebSocket message handler failed` (code from the error or `HANDLER_FAILED`, closed with 1011), socket error `SOCKET_ERROR`, broadcast write failure `BROADCAST_WRITE_FAILED`, presence handler `PRESENCE_HANDLER_FAILED`, lost hub events `HUB_EVENTS_FAILED` (every socket 1013), delayed cleanup `PRESENCE_CLEANUP_DEFERRED`. Registration failures are warn (closed with 4409 or 1013), slow consumers warn `SLOW_CONSUMER`. A reply or presence that could not be written to an already closed socket is warn `REPLY_DROPPED` (the client simply left; not a server failure; once per 10 seconds + `repeated`).
139
- - Places that run per message or socket write the same message and code once per 10 seconds and group the rest as a `repeated` count (the remaining count is written at drain end too). Bodies and tokens are never logged.
140
- - Sealing (§4a): a refused frame is warn `WebSocket sealed frame refused; closed` (code `SEAL_FRAME_REFUSED`, `reason`, `error`; one line per reason per 10 seconds + `repeated`), codec creation failure error `SEAL_CODEC_FAILED` (1011), broadcast seal failure error `SEAL_ENCODE_FAILED` (1011), hello send failure warn `SEAL_HELLO_FAILED`. debug: provider present (`WebSocket seal provider`), the decision per upgrade (`WebSocket seal decision`: path, sealed, offered), `WebSocket seal hello sent`, 4415 (`WebSocket seal required; closed`), `sealed` on connection logs, the `sealed` count on broadcast logs.
141
- - debug: connect, close, refused upgrades, hub registration ms, room join, leave and refusal, presence changes (counts), kick, broadcast delivery (ID, connection count, `binary`; after checking `isEnabled`), ignored `ack-v1` from old clients (`ACK_IGNORED`, one line per 10 seconds + `repeated`), idle and heartbeat closes, drain start and end. Too many waiting messages (1013 `Too many messages`) is warn `TOO_MANY_MESSAGES`; presence changes merged behind a slow presence handler are warn `PRESENCE_MERGED` (once per 10 seconds + `repeated`).
146
+ - Exceptions are never dropped silently. Failures other than those turned into close codes or error replies are `error`: a fixed English message + `code` + `error` (the full original error: name, whole message, stack and `Caused by: …` for each cause, address, port and errno text included; only URL credentials masked as `//***@`; cut only beyond 16 KB). Examples: handler failure `WebSocket message handler failed` (code from the error or `HANDLER_FAILED`, closed with 1011), socket error `SOCKET_ERROR`, broadcast write failure `BROADCAST_WRITE_FAILED`, presence handler `PRESENCE_HANDLER_FAILED`, lost hub events `HUB_EVENTS_FAILED` (every socket 1013), delayed cleanup `PRESENCE_CLEANUP_DEFERRED`. Registration failures are warn (closed with 4409 or 1013), slow consumers warn `SLOW_CONSUMER`. A reply or presence that could not be written to an already closed socket is warn `REPLY_DROPPED` (the client simply left; not a server failure; once per 10 seconds + `repeated`). That holds for the connection's own socket: a route's `message` that rejects with the `SOCKET_CLOSED` or `SLOW_CONSUMER` of a `send` to another connection (a relay awaiting a peer's `send`) while its own socket is open is a handler failure like any other (error, closed with 1011); catch it in `message` when a peer that left is expected (a `defineSocket` handler answers an error frame instead, as for every failure).
147
+ - Places that run per message or socket write the same message and code once per `logRepeatWindowMs` (10 seconds) and group the rest as a `repeated` count (the remaining count is written at drain end too). Bodies and tokens are never logged.
148
+ - Sealing (§4a): a refused frame is warn `WebSocket sealed frame refused; closed` (code `SEAL_FRAME_REFUSED`, `reason`, `error`; one line per reason per `logRepeatWindowMs` + `repeated`), codec creation failure error `SEAL_CODEC_FAILED` (1011), broadcast seal failure error `SEAL_ENCODE_FAILED` (1011), hello send failure warn `SEAL_HELLO_FAILED`. debug: provider present (`WebSocket seal provider`), the decision per upgrade (`WebSocket seal decision`: path, sealed, offered), `WebSocket seal hello sent`, 4415 (`WebSocket seal required; closed`), `sealed` on connection logs, the `sealed` count on broadcast logs.
149
+ - debug: route registration (`WebSocket route registered`: path, `routeId`, version), connect, close, refused upgrades (`WebSocket upgrade unauthorized` for a 401, `WebSocket upgrade refused; authorization expired` for a 401 of an invalid lease, `WebSocket origin refused` for a 403, `WebSocket upgrade refused` for a 503; each with `path` and `routeId`, the route's `config.id` or null, D-0140), hub registration ms, room join, leave and refusal, presence changes (counts), kick, broadcast delivery (ID, connection count, `binary`; after checking `isEnabled`), ignored `ack-v1` from old clients (`ACK_IGNORED`, one line per 10 seconds + `repeated`), idle and heartbeat closes, drain start and end. Too many waiting messages (1013 `Too many messages`) is warn `TOO_MANY_MESSAGES`; presence changes merged behind a slow presence handler are warn `PRESENCE_MERGED` (once per 10 seconds + `repeated`).
142
150
  - `defineSocket` handler errors: the client still gets only `{ type: 'error', id?, code }` (no message or stack; the socket stays open), and the server logs error `WebSocket handler failed.` (code `SOCKET_HANDLER_FAILED`, `type` = message type, `reply` = the code sent to the client, `connection`, `error` = full text). Repeats are one line per type + reply code per 10 seconds. Malformed messages and unknown types (client mistakes) are debug `WebSocket client message refused` (code `INVALID_MESSAGE` or `UNKNOWN_TYPE`, counted and grouped per code).
143
151
  - This report goes through `session.reportError?(error, { source: 'handler' | 'client', code, type? })`. Only sessions the gateway created have it; with a hand-made session (tests and the like) `defineSocket` only sends the reply. A low-level `route.message` can report through the same method.
144
152
 
@@ -155,7 +163,7 @@ stop: block new work → wait for received handlers and broadcasts being sent
155
163
 
156
164
  | Code | When |
157
165
  |---|---|
158
- | `INVALID_ROUTE` | A wrong route definition (path, authenticate, message, origins, seal, `defineSocket` arguments) |
166
+ | `INVALID_ROUTE` | A wrong route definition (path, authenticate, message, origins, seal, `config` other than `{ id }`, `defineSocket` arguments) |
159
167
  | `INVALID_ARGUMENT` | A non-function passed to `onPresence` |
160
168
  | `INVALID_FILTER` | A server call filter that is not exactly one of `{ tenant }` and `{ tenantPrefix }`, or a string outside 1–256 bytes |
161
169
  | `INVALID_TARGET` | A wrong namespace or target for the transport `handle` |
@@ -164,9 +172,9 @@ stop: block new work → wait for received handlers and broadcasts being sent
164
172
  | `FROZEN` | `route` outside setup |
165
173
  | `SEAL_PROVIDER_MISSING` | A sealed route without dokebi-seal |
166
174
  | `SEAL_PROVIDER_INVALID` | dokebi-seal does not provide `forConnection` |
167
- | `SEAL_BINARY_UNSUPPORTED` | Non-UTF-8 bytes to a sealed socket |
168
- | `SEAL_ENCODE_FAILED` | Sealing a frame failed (`cause`) |
169
- | `SOCKET_CLOSED` | `send` to a closed socket |
175
+ | `SEAL_BINARY_UNSUPPORTED` | Non-UTF-8 bytes to a sealed socket. `send` logs it at error and marks the rejection handled, like `SOCKET_CLOSED` (a `send` nobody awaits does not end the worker) |
176
+ | `SEAL_ENCODE_FAILED` | Sealing a frame failed (`cause`); `send` logs it at error and marks the rejection handled |
177
+ | `SOCKET_CLOSED` | `send` to a closed socket (or one whose authorization ended, or that closed while the frame was written). The rejection is marked handled: a `send` nobody awaits (a loop over the sockets of a board, a callback typed `=> void`) does not end the worker with an unhandled rejection (AI-M43), and is logged at debug `WebSocket send refused`; an awaited `send` still rejects. Any other write failure is logged at error (`SOCKET_WRITE_FAILED`) |
170
178
  | `SLOW_CONSUMER` | The send buffer would exceed `maxBufferedBytes` |
171
179
  | `ROOM_FORBIDDEN` | `authorizeRoom` did not allow the room (with `hint`) |
172
180
  | `BROADCAST_FAILED` | Part of a `tenantPrefix` broadcast failed without a hub code (`receipt`, `cause`) |
@@ -181,3 +189,11 @@ stop: block new work → wait for received handlers and broadcasts being sent
181
189
  - Cross delivery between two real containers and four workers, a hub SIGKILL and NATS faults were verified, but not two physical machines or a WAN (OPS-002).
182
190
 
183
191
  Evidence: `examples/23-websocket` (two Docker servers, four workers), `examples/25-playground` (per-app sockets, presence, load test), D-0024, D-0033, D-0034, D-0057 (replacing the ACK of D-0025), D-0059 §4 (sealing — real server tests and the Chromium check live in @dokebi/seal: `npm run seal:test`, `seal:browser-check`).
192
+
193
+ ## Authorization lifetime and change subscriptions (0.4.2)
194
+
195
+ An authenticated identity may carry `authorization: { valid(): boolean; subscribe(invalidated: () => void): () => void }`. Use `await request.auth.live()` when session auth is installed (a Bearer upgrade too, auth 0.4.1, D-0124; an OAuth access token uses `oauth.live(request)`) and reject a missing lease. A lease that is already invalid when `authenticate` returns is refused with 401 before the upgrade (like SSE); one that expires while the socket attaches closes with 4403 without a hub registration. The gateway checks incoming/queued handlers, direct sends, broadcasts, room joins and hub delivery. Invalidation closes with 4403; close unsubscribes. A `valid`, `subscribe` or unsubscribe that throws is logged at error `SOCKET_AUTHORIZATION_FAILED` (a failed `subscribe` closes with 4403, since that connection could not be revoked later). The guard is local and is never included in hub registration or public presence. Existing unguarded identities retain their behavior; handshake-only authentication does not provide revocation.
196
+
197
+ `WebsocketApi.onChange(listener)` returns an unsubscribe function. The listener receives the fully scoped tenant string after a hub snapshot changes connections, rooms or metadata (including remote owners). Identical snapshots do not trigger it. It is an invalidation hint: coalesce callbacks, read the current snapshot with list(), and publish versioned deltas from a shared per-worker read model. Listener failures are logged at error `SNAPSHOT_LISTENER_FAILED` (one line per 10 seconds + `repeated`); adding and removing a listener is logged at debug. Unsubscribe at application shutdown. Keep initial/reconnect snapshots ordered against deltas; do not poll an entire list independently from every tab. Existing onPresence retains its join/leave semantics.
198
+
199
+ Application code can import the typed `dependency` from `@dokebi/websocket/dependency`, list it in app requires, and use app.getDependency(dependency).onChange. The descriptor requires websocket >=0.4.2.
package/README.md CHANGED
@@ -37,13 +37,13 @@ Prepare the required YAML of websocket-hub. The CLI registration order is redis
37
37
  | Key | Type | Default | Description |
38
38
  |---|---|---|---|
39
39
  | `maxPayloadBytes` | integer | 65536 | Message size |
40
- | `maxConnections` | integer | 128 | Connections per process |
41
- | `maxPending` | integer | 32 | Waiting messages per connection; also bounds its waiting presence calls, separately |
42
- | `maxBufferedBytes` | integer | 1048576 | Send buffer before 1013 `Slow consumer` |
40
+ | `maxConnections` (reloadable) | integer | 128 | Connections per process |
41
+ | `maxPending` (reloadable) | integer | 32 | Waiting messages per connection; also bounds its waiting presence calls, separately |
42
+ | `maxBufferedBytes` (reloadable) | integer | 1048576 | Send buffer before 1013 `Slow consumer` |
43
43
  | `shutdownTimeoutMs` | integer ms | 2000 | Socket close wait at drain |
44
- | `heartbeatMs` | integer ms | 10000 | ping/pong interval |
45
- | `idleTimeoutMs` | integer ms | 0 (off) | Close silent clients with 4408 |
46
- | `hubWaitMs` | integer ms | 5000 | Upgrade wait while the hub recovers |
44
+ | `heartbeatMs` (reloadable) | integer ms | 10000 | ping/pong interval |
45
+ | `idleTimeoutMs` (reloadable) | integer ms | 0 (off) | Close silent clients with 4408 |
46
+ | `hubWaitMs` (reloadable) | integer ms | 5000 | Upgrade wait while the hub recovers |
47
47
  | `sealDriftMs` | integer ms | 60000 | Allowed clock difference of sealed frames |
48
48
 
49
49
  0.4.0 renamed `maxPayload` → `maxPayloadBytes`, `maxPendingMessages` → `maxPending` and `closeTimeoutMs` → `shutdownTimeoutMs` ([D-0071](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0071-option-vocabulary.md)); the old names still work in 0.4.0 with an `OPTION_DEPRECATED` warning. The [schema](options.schema.json) has the limits.
@@ -99,11 +99,12 @@ socket.onmessage = ({ data }) => {
99
99
  socket.onopen = () => reloadState(); // broadcasts during a disconnect never come again
100
100
  ```
101
101
 
102
- `clientId` must differ per tab (page). When the same `(tenant, member, clientId)` is already connected, the hub refuses the registration and the socket closes with **4409 `Duplicate client`**, distinct from a hub failure (1013 `Hub unavailable`). Reconnecting at once with the same clientId is refused again, so never keep the clientId where tabs share it, such as localStorage. Keep it in page memory or tab-scoped storage.
102
+ `clientId` must differ per tab (page). The newest connection of a `(tenant, member, clientId)` wins: when the same one connects again (on any server), the older socket closes with **4409 `Replaced`**, distinct from a hub failure (1013 `Hub unavailable`). A tab that reconnects after a network switch (its old socket half open) therefore keeps working, and the replaced socket must not reconnect with the same clientId (it would replace the newer one). Never keep the clientId where tabs share it, such as localStorage; keep it in page memory or tab-scoped storage, and give a duplicated tab a new one. With a hub before this rule the newer registration is refused instead (4409 `Duplicate client`).
103
103
 
104
104
  ## Route constraints and the message router (D-0030)
105
105
 
106
106
  - `route({ constraints })`: adds Fastify route constraints to the upgrade route. @dokebi/app registers the same path (`/ws`) separately per app with `{ dokebiApp: '<app>' }`.
107
+ - `route({ config: { id } })` / `defineSocket({ config: { id } })` (D-0140): the route id of the upgrade route, as `config.id` of a web route. `dokebi describe` lists it (`routes[].id`), dokebi-web's route hooks and `request.routeOptions.config.id` see it, and the refusal logs (401, 403, 503) carry it as `routeId`. Checked at start like a web route id (`INVALID_ROUTE_CONFIG`); the same id twice in one app is `DUPLICATE_ROUTE_ID`. Only `id` is allowed in `config` (`INVALID_ROUTE` otherwise).
107
108
  - `defineSocket({ path, authenticate, on: { '<type>': handler } })` creates a route with a message router. Messages are JSON `{ type, data?, id? }`. A handler `(data, socket)` return value goes out as `{ type: 'reply', id, data }` when there is an `id`. `socket.send(type, data)` sends to this connection, `socket.broadcast(type, data, target?)` through the hub. An unknown type answers `UNKNOWN_TYPE`, an invalid message `INVALID_MESSAGE`, a handler error `{ type: 'error', id?, code }` with the error's `code` (when upper-case) or `HANDLER_FAILED`. The error message and stack are not sent; the gateway logs error `WebSocket handler failed.` (code `SOCKET_HANDLER_FAILED`, full error) on the server (the session's `reportError`, D-0047). A Dokebi error (`DokebiError`) also sends its `message` and `hint`, plus `fix` outside production (D-0063). `reply` and `error` are reserved types.
108
109
  - Fixed 2026-10-14 ([ISSUE-0005](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/issues/ISSUE-0005-playground-findings.md) PG-14): an upgrade request to a path without a WebSocket route kept its raw socket open after the 404, so app shutdown hung until the cleanup deadline. @fastify/websocket is now registered without encapsulation so its hook applies to every upgrade.
109
110
 
@@ -0,0 +1,4 @@
1
+ import type { WebsocketApi } from './types.js';
2
+ /** Typed dependency for application-owned live collection subscriptions. */
3
+ export declare const provider: import("@dokebi/core").ProviderDescriptor<WebsocketApi>;
4
+ export declare const dependency: import("@dokebi/core").PluginDependency<WebsocketApi>;
@@ -0,0 +1,9 @@
1
+ import { defineProvider } from '@dokebi/core';
2
+ /** Typed dependency for application-owned live collection subscriptions. */
3
+ export const provider = defineProvider({
4
+ name: 'dokebi-websocket',
5
+ version: '^0.4.2',
6
+ packageName: '@dokebi/websocket',
7
+ load: () => import('./index.js'),
8
+ });
9
+ export const dependency = provider.dependency;
package/dist/errors.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { DokebiError } from '@dokebi/core';
2
2
  const FIX = {
3
- INVALID_ROUTE: 'Give a websocket route a path starting with /, authenticate and message functions, origins as exact http(s) origins or "*", and seal as a boolean or a function (defineSocket builds one).',
3
+ INVALID_ROUTE: 'Give a websocket route a path starting with /, authenticate and message functions, origins as exact http(s) origins or "*", seal as a boolean or a function (defineSocket builds one), and config as { id } only (D-0140).',
4
4
  INVALID_ARGUMENT: 'Pass a function to onPresence.',
5
5
  INVALID_FILTER: 'Use { tenant } or { tenantPrefix } (exactly one), with room? and member?, strings of 1 to 256 bytes.',
6
6
  INVALID_TARGET: 'A realtime namespace is 1 to 64 letters, digits, ., _ or -; a target is { tenant?, member?, room? }.',
package/dist/gateway.d.ts CHANGED
@@ -8,11 +8,17 @@ export declare class Gateway {
8
8
  readonly context: PluginContext;
9
9
  readonly web: WebApi;
10
10
  readonly hub: HubApi;
11
- readonly settings: Options;
11
+ settings: Options;
12
12
  readonly codecs: SocketCodecProvider | undefined;
13
13
  readonly api: WebsocketApi;
14
14
  constructor(context: PluginContext, web: WebApi, hub: HubApi, settings: Options, codecs?: SocketCodecProvider | undefined);
15
15
  start(): void;
16
+ /**
17
+ * D-0154: reloaded limits (maxConnections, maxPending, maxBufferedBytes, idleTimeoutMs,
18
+ * hubWaitMs, beforeUpgradeTimeoutMs) for the next connection or message, and the ping
19
+ * interval (the timer starts again). maxPayloadBytes is the socket server's and needs a restart.
20
+ */
21
+ reconfigure(next: Options): void;
16
22
  /** Stops waiting as soon as `signal` (the core drain deadline) aborts; sockets are then cut. */
17
23
  drain(signal: AbortSignal): Promise<void>;
18
24
  }