@dokebi/websocket 0.3.0 → 0.4.1
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 +138 -96
- package/README.md +74 -59
- package/dist/errors.d.ts +11 -0
- package/dist/errors.js +38 -0
- package/dist/gateway.js +125 -73
- package/dist/index.d.ts +3 -0
- package/dist/index.js +19 -21
- package/dist/options.d.ts +15 -25
- package/dist/options.js +38 -40
- package/dist/router.d.ts +1 -1
- package/dist/router.js +32 -10
- package/dist/transport.d.ts +30 -0
- package/dist/transport.js +72 -0
- package/options.schema.json +33 -6
- package/package.json +35 -12
- package/dist/log.d.ts +0 -25
- package/dist/log.js +0 -102
package/AI.md
CHANGED
|
@@ -1,141 +1,183 @@
|
|
|
1
|
-
# AI
|
|
1
|
+
# AI guide — @dokebi/websocket 0.4.1
|
|
2
2
|
|
|
3
|
-
dokebi-web(Fastify)
|
|
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
|
|
|
5
|
-
## 1.
|
|
5
|
+
## 1. Install
|
|
6
6
|
|
|
7
7
|
```sh
|
|
8
|
-
#
|
|
8
|
+
# One process (forks included): the hub in mode local (default) — in memory, no hub server, port, Redis, NATS or secret
|
|
9
9
|
npx dokebi add @dokebi/websocket-hub
|
|
10
10
|
npx dokebi add @dokebi/websocket
|
|
11
11
|
|
|
12
|
-
#
|
|
13
|
-
npx dokebi add @dokebi/websocket-hub --set mode=cluster --set namespace=shop --set serverId=web-1 --set redisConnection=main # secret
|
|
12
|
+
# Several processes or servers (two or more node:cluster workers): order redis → nats (optional) → web → websocket-hub → websocket
|
|
13
|
+
npx dokebi add @dokebi/websocket-hub --set mode=cluster --set namespace=shop --set serverId=web-1 --set redisConnection=main # writing the secret directly in dokebi.yaml is safer
|
|
14
14
|
```
|
|
15
15
|
|
|
16
|
-
|
|
16
|
+
> `npx dokebi` is the @dokebi/cli installed in the project (`dokebi init` adds it to devDependencies). The npm package named `dokebi` is not this CLI, so never run `npx -y dokebi`. Without a local install use `npx -y @dokebi/cli …`.
|
|
17
17
|
|
|
18
|
-
|
|
18
|
+
The hub style is chosen in dokebi.yaml `options.dokebi-websocket-hub.mode`. `local` (default) offers the same HubApi in process memory (no hub server). In node:cluster workers each worker would have its own connection list, so the hub refuses with `LOCAL_IN_CLUSTER` (log code `HUB_LOCAL_IN_CLUSTER`). With a single worker, `allowInCluster: true` allows it. To share broadcasts across several workers or servers, use `cluster`.
|
|
19
19
|
|
|
20
|
-
|
|
21
|
-
|---|---|---|
|
|
22
|
-
| `maxPayload` | 65536 | 메시지 크기 |
|
|
23
|
-
| `maxConnections` | 128 | 이 프로세스의 연결 수 |
|
|
24
|
-
| `maxPendingMessages` | 32 | 연결별 대기 메시지(연결마다 순차 처리) |
|
|
25
|
-
| `maxBufferedBytes` | 1048576 | 송신 버퍼. 넘으면 그 소켓을 1013 `Slow consumer`로 닫고 warn `WebSocket slow consumer closed`(code `SLOW_CONSUMER`)를 남김. 그 소켓에 쓰려던 응답은 버려진다(핸들러 실패로 세지 않음) |
|
|
26
|
-
| `closeTimeoutMs` | 2000 | 소켓 종료 대기(업무 제한 아님) |
|
|
27
|
-
| `heartbeatMs` | 10000 | ping/pong |
|
|
28
|
-
| `idleTimeoutMs` | 0(끔) | 클라이언트가 이 시간 동안 아무것도 안 보내면 4408 `Idle`. 페이지가 `{"$dokebi":"ping-v1"}`을 주기적으로 보낸다 |
|
|
29
|
-
| `hubWaitMs` | 5000 | 허브가 recovering일 때 업그레이드가 기다리는 시간(0이면 바로 503) |
|
|
30
|
-
| `sealDriftMs` | 60000 | 봉인 연결(§4a): 프레임 ts가 서버 시계와 이만큼(1000~600000) 넘게 다르면 4400. nonce는 두 배 동안 기억 |
|
|
20
|
+
## 2. Configuration `options.dokebi-websocket`
|
|
31
21
|
|
|
32
|
-
|
|
22
|
+
| Key | Type | Default | Description |
|
|
23
|
+
|---|---|---|---|
|
|
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) |
|
|
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) |
|
|
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
33
|
|
|
34
|
-
|
|
34
|
+
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
|
+
|
|
36
|
+
| Old key | New key |
|
|
37
|
+
|---|---|
|
|
38
|
+
| `maxPayload` | `maxPayloadBytes` |
|
|
39
|
+
| `maxPendingMessages` | `maxPending` |
|
|
40
|
+
| `closeTimeoutMs` | `shutdownTimeoutMs` |
|
|
41
|
+
|
|
42
|
+
## 3. Routes — defineSocket (recommended)
|
|
43
|
+
|
|
44
|
+
```ts snippet
|
|
35
45
|
import { defineSocket } from '@dokebi/websocket';
|
|
36
46
|
|
|
37
47
|
export const chatSocket = (app: AppContext) => defineSocket({
|
|
38
48
|
path: '/ws',
|
|
39
|
-
version: BUILD_VERSION, //
|
|
40
|
-
origins: ['https://app.a.com'], //
|
|
41
|
-
async authenticate(request) { //
|
|
49
|
+
version: BUILD_VERSION, // a different client ?dokebiVersion= gets 4426 Reload required
|
|
50
|
+
origins: ['https://app.a.com'], // omitted: same Host only (other Origins get 403)
|
|
51
|
+
async authenticate(request) { // from a verified session or token; undefined → 401
|
|
42
52
|
const user = await sessions.verify(request);
|
|
43
53
|
return user && { tenant: user.orgId, member: user.id, clientId: String(request.query.clientId) };
|
|
44
54
|
},
|
|
45
55
|
authorizeRoom: (identity, room) => rooms.canJoin(identity, room),
|
|
46
|
-
presence: true, //
|
|
56
|
+
presence: true, // joins and leaves of the same tenant arrive as { type: 'presence', data }
|
|
47
57
|
on: {
|
|
48
58
|
'chat.send': async (data, socket) => {
|
|
49
59
|
const { room, text } = data as { room: string; text: string };
|
|
50
60
|
void socket.broadcast('chat.message', { from: socket.identity.member, text }, { room })
|
|
51
61
|
.catch((error) => app.logger.log('warn', 'broadcast failed', { code: error.code }));
|
|
52
|
-
return { accepted: true }; //
|
|
62
|
+
return { accepted: true }; // with an id in the message, sent as { type: 'reply', id, data }
|
|
53
63
|
},
|
|
54
64
|
},
|
|
55
65
|
});
|
|
56
66
|
```
|
|
57
67
|
|
|
58
|
-
-
|
|
59
|
-
- `socket
|
|
60
|
-
-
|
|
61
|
-
-
|
|
68
|
+
- 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
|
+
- `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
|
+
- 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`.
|
|
62
73
|
|
|
63
|
-
## 3a.
|
|
74
|
+
## 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))
|
|
64
75
|
|
|
65
|
-
|
|
76
|
+
An API for code outside a connection (server code, jobs, admin apps) that names a tenant. @dokebi/app apps usually use `app.realtime(namespace)`, which wraps it.
|
|
66
77
|
|
|
67
|
-
```ts
|
|
78
|
+
```ts snippet
|
|
68
79
|
const ws = context.get(websocket);
|
|
69
|
-
await ws.list({ tenant: 'shop:t1' }); //
|
|
70
|
-
await ws.list({ tenantPrefix: 'shop:', room: 'vip' }); //
|
|
71
|
-
await ws.send({ tenant: 'shop:t1', member: 'u42' }, 'chat.message', { text: 'hi' }); // { type, data }
|
|
72
|
-
await ws.broadcast({ tenantPrefix: 'shop:' }, bytesOrText); //
|
|
80
|
+
await ws.list({ tenant: 'shop:t1' }); // asks the hub (whole cluster; fails with hub codes)
|
|
81
|
+
await ws.list({ tenantPrefix: 'shop:', room: 'vip' }); // presence this server received (every server; may lag a little)
|
|
82
|
+
await ws.send({ tenant: 'shop:t1', member: 'u42' }, 'chat.message', { text: 'hi' }); // { type, data } text
|
|
83
|
+
await ws.broadcast({ tenantPrefix: 'shop:' }, bytesOrText); // raw bytes (a text frame when UTF-8)
|
|
73
84
|
await ws.kick({ tenant: 'shop:t1', member: 'u42' }, 4403, 'Removed');
|
|
74
85
|
const stop = ws.onPresence(({ tenant, joined, left }) => {});
|
|
75
86
|
```
|
|
76
87
|
|
|
77
|
-
-
|
|
78
|
-
- `tenant`:
|
|
79
|
-
-
|
|
80
|
-
-
|
|
81
|
-
- `onPresence`:
|
|
82
|
-
- debug: `WebSocket connections listed`(source `hub
|
|
88
|
+
- 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: [] }`.
|
|
90
|
+
- 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 }`.
|
|
91
|
+
- 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
|
+
- `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
|
+
- 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.
|
|
83
94
|
|
|
84
|
-
## 4.
|
|
95
|
+
## 4. What the client does
|
|
85
96
|
|
|
86
|
-
```ts
|
|
87
|
-
const clientId = sessionStorage.getItem('cid') ?? crypto.randomUUID(); //
|
|
97
|
+
```ts snippet
|
|
98
|
+
const clientId = sessionStorage.getItem('cid') ?? crypto.randomUUID(); // different per tab (never shared via localStorage)
|
|
88
99
|
sessionStorage.setItem('cid', clientId);
|
|
89
100
|
const socket = new WebSocket(`/ws?clientId=${clientId}&dokebiVersion=${BUILD_VERSION}`);
|
|
90
|
-
socket.onmessage = ({ data }) => handle(JSON.parse(data)); //
|
|
91
|
-
socket.onopen = () => reloadState(); //
|
|
92
|
-
setInterval(() => socket.send('{"$dokebi":"ping-v1"}'), 15000); // idleTimeoutMs
|
|
101
|
+
socket.onmessage = ({ data }) => handle(JSON.parse(data)); // replies and broadcasts are both { type, data } text
|
|
102
|
+
socket.onopen = () => reloadState(); // after reconnecting, read what was missed from the server
|
|
103
|
+
setInterval(() => socket.send('{"$dokebi":"ping-v1"}'), 15000); // when idleTimeoutMs is used
|
|
93
104
|
```
|
|
94
105
|
|
|
95
|
-
-
|
|
96
|
-
-
|
|
97
|
-
-
|
|
98
|
-
|
|
99
|
-
## 4a.
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
-
|
|
104
|
-
-
|
|
105
|
-
-
|
|
106
|
-
-
|
|
107
|
-
-
|
|
108
|
-
-
|
|
109
|
-
-
|
|
110
|
-
|
|
111
|
-
## 5.
|
|
112
|
-
|
|
113
|
-
-
|
|
114
|
-
- `broadcast
|
|
115
|
-
-
|
|
116
|
-
-
|
|
117
|
-
- `send
|
|
118
|
-
- presence:
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
-
|
|
128
|
-
-
|
|
129
|
-
-
|
|
130
|
-
-
|
|
131
|
-
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
-
|
|
137
|
-
- `
|
|
138
|
-
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
106
|
+
- 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
|
+
- 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.
|
|
109
|
+
|
|
110
|
+
## 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
|
+
|
|
112
|
+
Every frame is sealed per host (or route). **This package does not know the seal**: a codec provider found by the name `dokebi-seal` (the @dokebi/seal plugin) transforms frames per connection. The public package never imports @dokebi/seal.
|
|
113
|
+
|
|
114
|
+
- Turning it on: with @dokebi/app, `options.dokebi-app.domains.<host>.seal: true` (the app fills `route.seal`). Without the app: `route({ seal: true | (request) => boolean })` or `defineSocket({ seal })`. When a sealed route exists but no `dokebi-seal` plugin is registered, setup fails with `SEAL_PROVIDER_MISSING` (fail closed). `api.sealing` is true when the provider exists.
|
|
115
|
+
- 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
|
+
- 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
|
+
- 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`.
|
|
119
|
+
- 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
|
+
- 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
|
+
|
|
122
|
+
## 5. Response codes and delivery semantics
|
|
123
|
+
|
|
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.
|
|
125
|
+
- `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
|
+
- **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
|
+
- Sending a broadcast does not wait per socket; it goes into the send queue (order kept per socket). Only slow sockets are closed.
|
|
128
|
+
- `send` is a raw reply (current socket). It is done once it is in the send buffer.
|
|
129
|
+
- presence: the first change one server receives may list connections that existed before as joined. Screens read the list again when presence arrives.
|
|
130
|
+
- presence calls per connection are bounded by `maxPending` (counted apart from messages). A handler slower than the changes gets them merged: later changes become one net `{ joined, left }` (a connection that joined and left meanwhile appears in neither), handed over when a call ends; warn `PRESENCE_MERGED` once per 10 seconds. Apply `left` and `joined` to a kept list and it stays right.
|
|
131
|
+
|
|
132
|
+
## 6. Shutdown
|
|
133
|
+
|
|
134
|
+
stop: block new work → wait for received handlers and broadcasts being sent → close with 1012. When core's drain deadline passes, remaining sockets are cut. The websocket drain finishes before the web and hub drains, and the DB and hub close after every drain.
|
|
135
|
+
|
|
136
|
+
## 7. Logs ([D-0047](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0047-logging-and-no-silent-errors.md))
|
|
137
|
+
|
|
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`).
|
|
142
|
+
- `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
|
+
- 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
|
+
|
|
145
|
+
## 7a. Realtime transport contribution and errors (D-0063)
|
|
146
|
+
|
|
147
|
+
- This plugin contributes the `websocket` transport to the point `dokebi-web:realtime` of @dokebi/web: `mount(route, scope)` (attaches app and module routes with the scope's path, constraints, seal rule and tenant rule) and `handle(namespace)` (`list`, `send`, `kick`, `onPresence` with the `<namespace>:` prefix added, and removed from results). @dokebi/app collects it to handle `sockets` and `app.realtime(ns)` (types `WebsocketTransport`, `WebsocketNamespaceHandle`).
|
|
148
|
+
- When a `defineSocket` handler throws a Dokebi error (`DokebiError`, or the same shape with `plugin`), the error reply also carries `message` and `hint`, and outside production (`NODE_ENV=production`) `fix` too ([D-0063](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0063-core-primitives.md) §1). Other errors still send only `code`.
|
|
149
|
+
- Options are a `defineOptions` declaration in `src/options.ts`, and the build generates `options.schema.json`. Invalid options are core `INVALID_PLUGIN_OPTIONS` (cause `INVALID_OPTIONS`, with paths).
|
|
150
|
+
|
|
151
|
+
## 8. Errors
|
|
152
|
+
|
|
153
|
+
<!-- docs-check: complete-error-codes WebsocketErrorCode -->
|
|
154
|
+
`WebsocketError` (`plugin: 'dokebi-websocket'`, `fix`):
|
|
155
|
+
|
|
156
|
+
| Code | When |
|
|
157
|
+
|---|---|
|
|
158
|
+
| `INVALID_ROUTE` | A wrong route definition (path, authenticate, message, origins, seal, `defineSocket` arguments) |
|
|
159
|
+
| `INVALID_ARGUMENT` | A non-function passed to `onPresence` |
|
|
160
|
+
| `INVALID_FILTER` | A server call filter that is not exactly one of `{ tenant }` and `{ tenantPrefix }`, or a string outside 1–256 bytes |
|
|
161
|
+
| `INVALID_TARGET` | A wrong namespace or target for the transport `handle` |
|
|
162
|
+
| `INVALID_TYPE` | The type format of `send` |
|
|
163
|
+
| `INVALID_DATA` | `send` data that is not JSON, `broadcast` data that is not a string or Uint8Array |
|
|
164
|
+
| `FROZEN` | `route` outside setup |
|
|
165
|
+
| `SEAL_PROVIDER_MISSING` | A sealed route without dokebi-seal |
|
|
166
|
+
| `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 |
|
|
170
|
+
| `SLOW_CONSUMER` | The send buffer would exceed `maxBufferedBytes` |
|
|
171
|
+
| `ROOM_FORBIDDEN` | `authorizeRoom` did not allow the room (with `hint`) |
|
|
172
|
+
| `BROADCAST_FAILED` | Part of a `tenantPrefix` broadcast failed without a hub code (`receipt`, `cause`) |
|
|
173
|
+
| `KICK_FAILED` | Part of a `tenantPrefix` kick failed without a hub code (`receipt`, `cause`) |
|
|
174
|
+
|
|
175
|
+
## 9. Cautions
|
|
176
|
+
|
|
177
|
+
- Never use `origins: '*'` on a cookie-authenticated route (Cross-Site WebSocket Hijacking). When a proxy rewrites Host, set web `trustProxy` accordingly or list the public origin in `origins`.
|
|
178
|
+
- Examples that trust a header value as the identity (example 23) are for tests only.
|
|
179
|
+
- `hub.events` is consumed only by this plugin. No other code reads it.
|
|
180
|
+
- Broadcasts are at most once. They can be missed across reconnects, leader changes and slow consumers, and resending after `OUTCOME_UNKNOWN` can deliver twice.
|
|
181
|
+
- 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
|
+
|
|
183
|
+
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`).
|