@dokebi/websocket 0.2.0 → 0.4.0
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 +144 -68
- package/README.md +86 -43
- package/dist/errors.d.ts +11 -0
- package/dist/errors.js +38 -0
- package/dist/gateway.d.ts +3 -2
- package/dist/gateway.js +487 -90
- package/dist/index.d.ts +3 -0
- package/dist/index.js +31 -19
- package/dist/options.d.ts +15 -20
- package/dist/options.js +38 -38
- package/dist/router.d.ts +3 -1
- package/dist/router.js +33 -10
- package/dist/transport.d.ts +30 -0
- package/dist/transport.js +72 -0
- package/dist/types.d.ts +108 -0
- package/dist/types.js +7 -1
- package/options.schema.json +40 -6
- package/package.json +39 -11
- package/dist/log.d.ts +0 -25
- package/dist/log.js +0 -102
package/AI.md
CHANGED
|
@@ -1,106 +1,182 @@
|
|
|
1
|
-
# AI
|
|
1
|
+
# AI guide — @dokebi/websocket 0.4.0
|
|
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) |
|
|
20
|
+
## 2. Configuration `options.dokebi-websocket`
|
|
30
21
|
|
|
31
|
-
|
|
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) |
|
|
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 |
|
|
32
33
|
|
|
33
|
-
|
|
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
|
|
34
45
|
import { defineSocket } from '@dokebi/websocket';
|
|
35
46
|
|
|
36
47
|
export const chatSocket = (app: AppContext) => defineSocket({
|
|
37
48
|
path: '/ws',
|
|
38
|
-
version: BUILD_VERSION, //
|
|
39
|
-
origins: ['https://app.a.com'], //
|
|
40
|
-
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
|
|
41
52
|
const user = await sessions.verify(request);
|
|
42
53
|
return user && { tenant: user.orgId, member: user.id, clientId: String(request.query.clientId) };
|
|
43
54
|
},
|
|
44
55
|
authorizeRoom: (identity, room) => rooms.canJoin(identity, room),
|
|
45
|
-
presence: true, //
|
|
56
|
+
presence: true, // joins and leaves of the same tenant arrive as { type: 'presence', data }
|
|
46
57
|
on: {
|
|
47
58
|
'chat.send': async (data, socket) => {
|
|
48
59
|
const { room, text } = data as { room: string; text: string };
|
|
49
60
|
void socket.broadcast('chat.message', { from: socket.identity.member, text }, { room })
|
|
50
61
|
.catch((error) => app.logger.log('warn', 'broadcast failed', { code: error.code }));
|
|
51
|
-
return { accepted: true }; //
|
|
62
|
+
return { accepted: true }; // with an id in the message, sent as { type: 'reply', id, data }
|
|
52
63
|
},
|
|
53
64
|
},
|
|
54
65
|
});
|
|
55
66
|
```
|
|
56
67
|
|
|
57
|
-
-
|
|
58
|
-
- `socket
|
|
59
|
-
-
|
|
60
|
-
-
|
|
61
|
-
|
|
62
|
-
## 4. 클라이언트가 할 일
|
|
63
|
-
|
|
64
|
-
```ts
|
|
65
|
-
const clientId = sessionStorage.getItem('cid') ?? crypto.randomUUID(); // 탭마다 다르게(localStorage 공유 금지)
|
|
66
|
-
sessionStorage.setItem('cid', clientId);
|
|
67
|
-
const socket = new WebSocket(`/ws?clientId=${clientId}&dokebiVersion=${BUILD_VERSION}`);
|
|
68
|
-
socket.onmessage = ({ data }) => handle(JSON.parse(data)); // 응답·방송 모두 { type, data } 텍스트
|
|
69
|
-
socket.onopen = () => reloadState(); // 재접속하면 놓친 것은 서버에서 다시 읽는다
|
|
70
|
-
setInterval(() => socket.send('{"$dokebi":"ping-v1"}'), 15000); // idleTimeoutMs를 쓸 때
|
|
71
|
-
```
|
|
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`.
|
|
72
73
|
|
|
73
|
-
|
|
74
|
-
- 연결이 끊긴 사이·느린 소비자로 닫힌 사이의 방송은 다시 오지 않는다. 화면은 다시 연결되면 서버에서 최신 상태를 읽는다.
|
|
75
|
-
- 닫힘 코드: 4426 새로고침, 4409 같은 clientId 중복(`Duplicate client`), 4408 idle, 1013 허브 불가·느린 소비자, 1012 서버 종료, 1011 handler 미처리 오류.
|
|
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))
|
|
76
75
|
|
|
77
|
-
|
|
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.
|
|
78
77
|
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
stop: 새 업무 차단 → 받은 handler·송신 중 방송 대기 → 1012로 닫기. core drain 기한이 지나면 남은 소켓을 끊는다. websocket drain이 web·hub drain보다 먼저 끝나고, 모든 drain 뒤 DB·허브가 닫힌다.
|
|
89
|
-
|
|
90
|
-
## 7. 로그(D-0047)
|
|
78
|
+
```ts snippet
|
|
79
|
+
const ws = context.get(websocket);
|
|
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)
|
|
84
|
+
await ws.kick({ tenant: 'shop:t1', member: 'u42' }, 4403, 'Removed');
|
|
85
|
+
const stop = ws.onPresence(({ tenant, joined, left }) => {});
|
|
86
|
+
```
|
|
91
87
|
|
|
92
|
-
-
|
|
93
|
-
-
|
|
94
|
-
-
|
|
95
|
-
-
|
|
96
|
-
-
|
|
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.
|
|
97
94
|
|
|
98
|
-
##
|
|
95
|
+
## 4. What the client does
|
|
99
96
|
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
97
|
+
```ts snippet
|
|
98
|
+
const clientId = sessionStorage.getItem('cid') ?? crypto.randomUUID(); // different per tab (never shared via localStorage)
|
|
99
|
+
sessionStorage.setItem('cid', clientId);
|
|
100
|
+
const socket = new WebSocket(`/ws?clientId=${clientId}&dokebiVersion=${BUILD_VERSION}`);
|
|
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
|
|
104
|
+
```
|
|
105
105
|
|
|
106
|
-
|
|
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 or slow consumer, 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.
|
|
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
|
+
|
|
131
|
+
## 6. Shutdown
|
|
132
|
+
|
|
133
|
+
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.
|
|
134
|
+
|
|
135
|
+
## 7. Logs ([D-0047](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0047-logging-and-no-silent-errors.md))
|
|
136
|
+
|
|
137
|
+
- 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`).
|
|
138
|
+
- 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.
|
|
139
|
+
- 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.
|
|
140
|
+
- 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`.
|
|
141
|
+
- `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).
|
|
142
|
+
- 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.
|
|
143
|
+
|
|
144
|
+
## 7a. Realtime transport contribution and errors (D-0063)
|
|
145
|
+
|
|
146
|
+
- 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`).
|
|
147
|
+
- 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`.
|
|
148
|
+
- 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).
|
|
149
|
+
|
|
150
|
+
## 8. Errors
|
|
151
|
+
|
|
152
|
+
<!-- docs-check: complete-error-codes WebsocketErrorCode -->
|
|
153
|
+
`WebsocketError` (`plugin: 'dokebi-websocket'`, `fix`):
|
|
154
|
+
|
|
155
|
+
| Code | When |
|
|
156
|
+
|---|---|
|
|
157
|
+
| `INVALID_ROUTE` | A wrong route definition (path, authenticate, message, origins, seal, `defineSocket` arguments) |
|
|
158
|
+
| `INVALID_ARGUMENT` | A non-function passed to `onPresence` |
|
|
159
|
+
| `INVALID_FILTER` | A server call filter that is not exactly one of `{ tenant }` and `{ tenantPrefix }`, or a string outside 1–256 bytes |
|
|
160
|
+
| `INVALID_TARGET` | A wrong namespace or target for the transport `handle` |
|
|
161
|
+
| `INVALID_TYPE` | The type format of `send` |
|
|
162
|
+
| `INVALID_DATA` | `send` data that is not JSON, `broadcast` data that is not a string or Uint8Array |
|
|
163
|
+
| `FROZEN` | `route` outside setup |
|
|
164
|
+
| `SEAL_PROVIDER_MISSING` | A sealed route without dokebi-seal |
|
|
165
|
+
| `SEAL_PROVIDER_INVALID` | dokebi-seal does not provide `forConnection` |
|
|
166
|
+
| `SEAL_BINARY_UNSUPPORTED` | Non-UTF-8 bytes to a sealed socket |
|
|
167
|
+
| `SEAL_ENCODE_FAILED` | Sealing a frame failed (`cause`) |
|
|
168
|
+
| `SOCKET_CLOSED` | `send` to a closed socket |
|
|
169
|
+
| `SLOW_CONSUMER` | The send buffer would exceed `maxBufferedBytes` |
|
|
170
|
+
| `ROOM_FORBIDDEN` | `authorizeRoom` did not allow the room (with `hint`) |
|
|
171
|
+
| `BROADCAST_FAILED` | Part of a `tenantPrefix` broadcast failed without a hub code (`receipt`, `cause`) |
|
|
172
|
+
| `KICK_FAILED` | Part of a `tenantPrefix` kick failed without a hub code (`receipt`, `cause`) |
|
|
173
|
+
|
|
174
|
+
## 9. Cautions
|
|
175
|
+
|
|
176
|
+
- 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`.
|
|
177
|
+
- Examples that trust a header value as the identity (example 23) are for tests only.
|
|
178
|
+
- `hub.events` is consumed only by this plugin. No other code reads it.
|
|
179
|
+
- Broadcasts are at most once. They can be missed across reconnects, leader changes and slow consumers, and resending after `OUTCOME_UNKNOWN` can deliver twice.
|
|
180
|
+
- 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).
|
|
181
|
+
|
|
182
|
+
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`).
|
package/README.md
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
1
|
# @dokebi/websocket
|
|
2
2
|
|
|
3
|
-
Node >=24, 0.
|
|
3
|
+
Node >=24, version 0.4.0 (unpublished). An optional plugin that connects the Dokebi Fastify web plugin with websocket-hub. It does not force templates or views on API servers. AI agents start with [AI.md](AI.md).
|
|
4
4
|
|
|
5
|
-
```ts
|
|
5
|
+
```ts snippet
|
|
6
6
|
import { Application, dependencyOf, loadConfig } from '@dokebi/core';
|
|
7
7
|
import { createPlugin } from '@dokebi/websocket';
|
|
8
8
|
const document = await loadConfig('./dokebi.yaml');
|
|
9
9
|
const app = new Application({config: document.options});
|
|
10
10
|
const ws = createPlugin({app: app.view});
|
|
11
11
|
app.register({
|
|
12
|
-
metadata: {name:'chat',version:'1.0.0',core:'^0.
|
|
12
|
+
metadata: {name:'chat',version:'1.0.0',core: '^0.4.0',dependencies:[dependencyOf(ws)]},
|
|
13
13
|
setup(context) {
|
|
14
14
|
context.get(ws).route({
|
|
15
15
|
path:'/ws',
|
|
16
|
-
//
|
|
16
|
+
// Omitted, browser Upgrades from other origins get 403. List only the origins you need, exactly.
|
|
17
17
|
origins:['https://app.example.com'],
|
|
18
|
-
//
|
|
18
|
+
// A real app decides tenant/member from a verified session or token.
|
|
19
19
|
authenticate(request) { return authenticateUser(request); },
|
|
20
20
|
authorizeRoom(identity, room) { return canJoinRoom(identity, room); },
|
|
21
21
|
async message(data, session) {
|
|
@@ -25,69 +25,112 @@ app.register({
|
|
|
25
25
|
}
|
|
26
26
|
});
|
|
27
27
|
await app.start();
|
|
28
|
-
//
|
|
28
|
+
// await app.stop() on a shutdown signal.
|
|
29
29
|
```
|
|
30
30
|
|
|
31
|
-
authenticateUser
|
|
31
|
+
`authenticateUser`/`canJoinRoom` are your authentication and authorization functions; this package does not provide them. `authenticate` returns `{ tenant, member, clientId?, rooms?, metadata? }` or undefined. The runnable example is examples/23-websocket in the repository; its header authentication is for tests only.
|
|
32
32
|
|
|
33
|
-
websocket-hub
|
|
33
|
+
Prepare the required YAML of websocket-hub. The CLI registration order is redis → nats → web → websocket-hub → websocket. The manifest is schemaVersion 2 and there is no install module. Servers start in setup/start.
|
|
34
34
|
|
|
35
|
-
##
|
|
35
|
+
## Options
|
|
36
36
|
|
|
37
|
-
|
|
37
|
+
| Key | Type | Default | Description |
|
|
38
|
+
|---|---|---|---|
|
|
39
|
+
| `maxPayloadBytes` | integer | 65536 | Message size |
|
|
40
|
+
| `maxConnections` | integer | 128 | Connections per process |
|
|
41
|
+
| `maxPending` | integer | 32 | Waiting messages per connection |
|
|
42
|
+
| `maxBufferedBytes` | integer | 1048576 | Send buffer before 1013 `Slow consumer` |
|
|
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 |
|
|
47
|
+
| `sealDriftMs` | integer ms | 60000 | Allowed clock difference of sealed frames |
|
|
38
48
|
|
|
39
|
-
|
|
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.
|
|
40
50
|
|
|
41
|
-
|
|
51
|
+
## Factory and dependencies (plugin contract v2)
|
|
42
52
|
|
|
43
|
-
-
|
|
44
|
-
- `origins: ['https://app.example.com']`: 같은 host에 더해 목록의 출처를 허용한다. 항목은 `scheme://host[:port]` 형태의 정확한 http(s) 출처여야 하며, 아니면 `route()`가 오류를 던진다.
|
|
45
|
-
- `origins: '*'`: 검사를 끈다. 쿠키 인증과 함께 쓰면 위의 위험이 그대로 남는다. 토큰을 메시지나 헤더로 직접 검증하는 경우에만 명시적으로 쓴다.
|
|
46
|
-
- 역방향 프록시가 `Host`를 바꾸면 같은 출처도 거부된다. 프록시가 원래 `Host`를 전달하게 하거나 공개 출처를 `origins`에 적는다.
|
|
53
|
+
The factory input is `{ app, options? }`; `app` is required. Without options it reads `app.config['dokebi-websocket']`. The `hub`, `web` and `dependencies` inputs were removed ([D-0028](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0028-plugin-contract-v2.md)). `dokebi-web` and `dokebi-websocket-hub` are wired through provider descriptors (`@dokebi/web/dependency`, `@dokebi/websocket-hub/dependency`). One registered under the same name is reused; otherwise it is created from `@dokebi/web` or `@dokebi/websocket-hub` with `app.config`. To use a specific instance, register it first, e.g. `app.register(createWeb({ app: app.view }))`. Both packages are `peerDependencies`, so the app installs them too.
|
|
47
54
|
|
|
48
|
-
|
|
55
|
+
## Cross-origin refusal (CSWSH)
|
|
49
56
|
|
|
50
|
-
|
|
57
|
+
Browsers attach cookies to a WebSocket Upgrade even from another site's page. When a cookie-authenticated route does not check the origin, a malicious page opens a socket with the user's rights (Cross-Site WebSocket Hijacking).
|
|
51
58
|
|
|
52
|
-
|
|
59
|
+
- Default: when an `Origin` header exists and its host (host:port) differs from the request `Host`, `preValidation` refuses with 403 (`ORIGIN_FORBIDDEN`). `authenticate` is not called. Requests without `Origin` (non-browser clients) pass.
|
|
60
|
+
- `origins: ['https://app.example.com']`: allows the listed origins in addition to the same host. Entries must be exact http(s) origins of the form `scheme://host[:port]`, otherwise `route()` throws.
|
|
61
|
+
- `origins: '*'`: turns the check off. With cookie authentication the risk above stays. Use it explicitly only when tokens are verified directly from messages or headers.
|
|
62
|
+
- When a reverse proxy rewrites `Host`, even the same origin is refused. Have the proxy pass the original `Host` or list the public origin in `origins`.
|
|
53
63
|
|
|
54
|
-
|
|
64
|
+
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.
|
|
55
65
|
|
|
56
|
-
|
|
66
|
+
Messages run in order per connection, and messages received during the initial registration are queued. Defaults: `maxPayloadBytes` 65536, `maxConnections` 128, `maxPending` 32, `maxBufferedBytes` 1048576, `shutdownTimeoutMs` 2000, `heartbeatMs` 10000. It uses ping/pong, a send buffer limit and no compression. The hub's own payload and connection limits apply as well.
|
|
57
67
|
|
|
68
|
+
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.
|
|
58
69
|
|
|
59
|
-
|
|
60
|
-
- `defineSocket({ presence: true })`면 각 연결에 `{ type: 'presence', data: { tenant, joined, left } }`를 보낸다. 함수를 주면 그 함수가 `(change, socket)`으로 처리한다.
|
|
61
|
-
- 한 서버에서 처음 받은 알림은 그전부터 있던 연결을 `joined`로 담을 수 있다. 화면은 이 메시지를 받으면 목록을 다시 읽는 방식이 안전하다.
|
|
70
|
+
stop blocks new work, waits for received handlers and broadcasts being sent, then closes with 1012. It also waits for remaining DB work of clients that disconnected first. `shutdownTimeoutMs` bounds the socket close wait, not the work. When core's drain deadline (`shutdown.drainTimeoutMs`, default 20000 ms) passes and `context.drainSignal` aborts, it stops waiting and cuts the remaining sockets; core reports the overrun as `DRAIN_TIMEOUT`. websocket depends on web and hub, so core finishes the websocket drain before starting the web and hub drains, and the DB and hub close after every drain.
|
|
62
71
|
|
|
63
|
-
|
|
72
|
+
`hub.events` is consumed only by this plugin. `broadcast` is at most once and returns the receipt `{ id, recipients }` once the hub sends it out ("Broadcast" below). `send` is a raw reply on the current socket with its own completion contract. Verified cross-server delivery between two real containers and four workers, a hub SIGKILL, NATS faults and DB drain do not mean full operational certification or verification on two physical machines.
|
|
64
73
|
|
|
65
|
-
|
|
74
|
+
**Joins and leaves (presence):** the hub tells every server the connection list of a server owner whenever connections come and go, including when a dead server's registration expires. This package turns that into per-tenant `{ tenant, joined, left }` and calls the route's `presence(change, session)` hook for each of its own connections open in the same tenant, in that connection's message order.
|
|
75
|
+
- `defineSocket({ presence: true })` sends `{ type: 'presence', data: { tenant, joined, left } }` to each connection. Given a function, that function handles it as `(change, socket)`.
|
|
76
|
+
- The first notice a server receives may list connections that existed before as `joined`. Screens should read the list again when this message arrives.
|
|
66
77
|
|
|
67
|
-
|
|
78
|
+
**Is the page alive (`idleTimeoutMs`):** the browser's network layer answers WebSocket pings, so even a page frozen in bfcache or with stopped scripts looks alive. With `idleTimeoutMs` (default 0, off), a connection whose client sent nothing for that long is closed with `4408 Idle`. The client sends `{"$dokebi":"ping-v1"}` periodically from page script to show it is alive. This control frame never reaches the route.
|
|
68
79
|
|
|
69
|
-
|
|
80
|
+
**Connection lifecycle logs:** at debug it logs connect (`WebSocket connected`: connection ID, tenant, member, clientId, remote address, User-Agent, `Sec-Purpose`) and close (`WebSocket closed`: close code, reason, duration).
|
|
70
81
|
|
|
71
|
-
|
|
82
|
+
**Client version (`version`, D-0033):** with `version` on a route (or `defineSocket`), a connection whose upgrade query `dokebiVersion` differs or is missing is not registered and is closed with `4426 Reload required`. The client reloads the page on this code. It keeps long-open tabs and pages restored from bfcache from joining server state with old code.
|
|
72
83
|
|
|
73
|
-
|
|
74
|
-
- 실패는 바로 오고 다시 보내지 않는다: `RECOVERING`(허브가 리더에 연결돼 있지 않음·리더 교체 중, 보내지 않음), `OUTCOME_UNKNOWN`(요청을 보낸 뒤 답 전에 끊김, 보내졌을 수 있음), `BUSY`(처리 중 방송이 허브 `maxPending`). 다시 보낼지는 호출자가 정한다. `OUTCOME_UNKNOWN` 뒤에 다시 보내면 두 번 받을 수 있다.
|
|
75
|
-
- 연결마다 메시지를 차례로 처리하지만 이제 broadcast를 기다려도 리더 왕복 한 번만 걸린다(가장 느린 탭을 기다리지 않는다). 결과가 필요 없으면 `void broadcast(...).catch(...)`로 바로 답해도 된다.
|
|
76
|
-
- **앱 지침:** 놓치면 안 되는 일(주문 상태·결제 결과)은 방송에 맡기지 않는다. DB에 저장하고, 페이지는 다시 연결될 때 서버에서 최신 상태를 읽는다. 방송은 「바뀌었으니 다시 읽어라」 알림으로 쓴다.
|
|
77
|
-
- 브라우저에는 방송 바이트가 그대로 간다. `defineSocket`의 `socket.broadcast(type, data)`는 `{ type, data }` JSON 텍스트 프레임이라 `send`의 응답과 같은 모양이다. `delivery-v1` 봉투와 클라이언트 `ack-v1`은 없어졌고, 브라우저 진입점 `@dokebi/websocket/client`(`DeliveryReceiver`)도 제거했다. 페이지는 표준 `WebSocket` API만 쓴다. 예전 페이지가 보내는 `{"$dokebi":"ack-v1"}`은 닫지 않고 무시한다(debug `WebSocket ACK from an old client ignored`, code `ACK_IGNORED`, 10초당 한 줄).
|
|
84
|
+
**Waiting for the hub to reconnect (`hubWaitMs`, D-0034):** while the hub is briefly `recovering` during a leader change or rolling restart, an upgrade waits up to `hubWaitMs` (default 5000; 0 refuses at once). If it is still not ready, 503. The refusal body is `{ error: 'UNAVAILABLE', reason }` with reason `CLOSING`, `HUB_<state>` or `CAPACITY`. The same reason is logged at debug as `WebSocket upgrade refused`.
|
|
78
85
|
|
|
79
|
-
|
|
86
|
+
## Broadcast: at most once (0.2.0, [D-0057](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0057-websocket-broadcast-without-ack.md))
|
|
87
|
+
|
|
88
|
+
- `session.broadcast(bytes, target?)` and `socket.broadcast(type, data, target?)` end with the receipt `{ id, recipients }` once the hub sends to the receiving servers. There is no client ACK, resend or deduplication (replacing the ACK of D-0025). `recipients` are the connections matching when it was sent and **not a confirmation of receipt.** Connections in the middle of reconnecting and connections closed with 1013 as slow consumers miss that broadcast.
|
|
89
|
+
- Failures come at once and nothing is resent: `RECOVERING` (the hub is not connected to the leader or the leader is changing; not sent), `OUTCOME_UNKNOWN` (disconnected after sending the request, before the answer; it may have been sent), `BUSY` (broadcasts in progress reached the hub's `maxPending`). The caller decides whether to send again; resending after `OUTCOME_UNKNOWN` can deliver twice.
|
|
90
|
+
- Messages are processed in order per connection, but awaiting broadcast now costs only one leader round trip (it never waits for the slowest tab). When the result is not needed, answer at once with `void broadcast(...).catch(...)`.
|
|
91
|
+
- **App guideline:** 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 from the server when it reconnects. Use broadcasts as "it changed, read again" notices.
|
|
92
|
+
- Browsers get the broadcast bytes as they are. `socket.broadcast(type, data)` of `defineSocket` is a `{ type, data }` JSON text frame, the same shape as a `send` reply. The `delivery-v1` envelope and the client `ack-v1` are gone, and so is the browser entry `@dokebi/websocket/client` (`DeliveryReceiver`). Pages use only the standard `WebSocket` API. The `{"$dokebi":"ack-v1"}` old pages send is ignored, not closed (debug `WebSocket ACK from an old client ignored`, code `ACK_IGNORED`, one line per 10 seconds).
|
|
93
|
+
|
|
94
|
+
```ts snippet
|
|
80
95
|
socket.onmessage = ({ data }) => {
|
|
81
|
-
const message = JSON.parse(data); //
|
|
82
|
-
if (message.type === 'order.changed') reloadOrder(message.data.id); //
|
|
96
|
+
const message = JSON.parse(data); // replies, presence and broadcasts are all { type, data? }
|
|
97
|
+
if (message.type === 'order.changed') reloadOrder(message.data.id); // a broadcast is a notice; read the content again
|
|
83
98
|
};
|
|
84
|
-
socket.onopen = () => reloadState(); //
|
|
99
|
+
socket.onopen = () => reloadState(); // broadcasts during a disconnect never come again
|
|
85
100
|
```
|
|
86
101
|
|
|
87
|
-
`clientId
|
|
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.
|
|
103
|
+
|
|
104
|
+
## Route constraints and the message router (D-0030)
|
|
105
|
+
|
|
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
|
+
- `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
|
+
- 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
|
+
## Listing and sending from server code (0.3.0, [D-0061](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0061-realtime-namespaces.md))
|
|
111
|
+
|
|
112
|
+
Server code outside a connection can read and send to connections by tenant. It wraps the hub's `list`, `broadcast` and `kick` (`app.realtime(namespace)` of @dokebi/app uses it).
|
|
88
113
|
|
|
89
|
-
|
|
114
|
+
- `list({ tenant | tenantPrefix, room?, member? })`: with `tenant` it asks the hub; with `tenantPrefix` it reads the presence this server received (every server), since the hub has no lookup across tenants.
|
|
115
|
+
- `send(filter, type, data?)`: the same `{ type, data }` text frame as a defineSocket broadcast. `broadcast(filter, bytes | text)`: raw bytes. Both are at most once, and sealed sockets get a per-socket sealed copy. `tenantPrefix` sends one hub broadcast per known tenant. Receipt `{ ids, recipients }`.
|
|
116
|
+
- `kick(filter, code?, reason?)`, `onPresence(listener)` (joins and leaves of every tenant; failures are error `PRESENCE_LISTENER_FAILED`).
|
|
117
|
+
- The `namespace` field of the authentication result belongs to @dokebi/app and is removed when registering with the hub.
|
|
118
|
+
- Detailed rules are in [AI.md](AI.md) §3a.
|
|
119
|
+
|
|
120
|
+
## Sealing per host (0.3.0, [D-0059](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0059-seal-and-websocket-client.md) §4)
|
|
121
|
+
|
|
122
|
+
Every frame of a connection can be sealed. This package does not know the algorithm; a codec provider found by the name `dokebi-seal` (the @dokebi/seal plugin) transforms frames per connection. This public package never imports @dokebi/seal (it looks up only the structural contract `SocketCodecProvider` with `optionalDependency({ name: 'dokebi-seal' })`).
|
|
123
|
+
|
|
124
|
+
```ts snippet
|
|
125
|
+
context.get(ws).route({
|
|
126
|
+
path: '/ws',
|
|
127
|
+
seal: (request) => request.headers.host === 'secure.example.com', // or true. @dokebi/app fills it from domains.<host>.seal
|
|
128
|
+
authenticate, message,
|
|
129
|
+
});
|
|
130
|
+
```
|
|
90
131
|
|
|
91
|
-
-
|
|
92
|
-
-
|
|
93
|
-
-
|
|
132
|
+
- When a sealed route exists but no `dokebi-seal` plugin does, setup fails with `SEAL_PROVIDER_MISSING`.
|
|
133
|
+
- Sealed connections: the client must offer the subprotocol `dokebi.seal` (otherwise 4415 `Seal required`). The server first sends a sealed `{"$dokebi":"hello-v1"}`, and opens incoming frames in the connection's order chain before passing them to control frames or the route. Frames that do not open (plain, binary, drift, replay) get 4400 `Bad frame`, with the reason only in the server warn log. Replies, presence and broadcasts go out sealed; plain sockets still share one broadcast buffer and only sealed sockets are sealed per recipient. Binary is not sent (`SEAL_BINARY_UNSUPPORTED`).
|
|
134
|
+
- Negotiation: clients with the seal bridge offer `dokebi.seal` and `dokebi.plain` (`PLAIN_PROTOCOL`) together. A sealed connection picks only `dokebi.seal` (never plain); a plain connection picks `dokebi.plain` when offered, otherwise nothing (old clients unchanged). So a page with the bridge still runs in plain on a plain host.
|
|
135
|
+
- `sealDriftMs` (default 60000): allowed frame time difference. Replay nonces stay in `hub.nonces()` (shared in Redis in cluster mode) for twice as long.
|
|
136
|
+
- Detailed rules, logs and costs are in [AI.md](AI.md) §4a.
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { DokebiError, type DokebiErrorOptions } from '@dokebi/core';
|
|
2
|
+
/** Codes of the errors this plugin throws (`WebsocketError`, `plugin: 'dokebi-websocket'`). */
|
|
3
|
+
export type WebsocketErrorCode = 'INVALID_ROUTE' | 'INVALID_ARGUMENT' | 'INVALID_FILTER' | 'INVALID_TARGET' | 'INVALID_TYPE' | 'INVALID_DATA' | 'FROZEN' | 'SEAL_PROVIDER_MISSING' | 'SEAL_PROVIDER_INVALID' | 'SEAL_BINARY_UNSUPPORTED' | 'SEAL_ENCODE_FAILED' | 'SOCKET_CLOSED' | 'SLOW_CONSUMER' | 'ROOM_FORBIDDEN' | 'BROADCAST_FAILED' | 'KICK_FAILED';
|
|
4
|
+
/**
|
|
5
|
+
* Errors of @dokebi/websocket; compare `code`, not the class (another installed copy may throw).
|
|
6
|
+
* A failed fan-out across tenants carries the first hub failure's code (for example RECOVERING)
|
|
7
|
+
* and `receipt`.
|
|
8
|
+
*/
|
|
9
|
+
export declare class WebsocketError<TCode extends string = WebsocketErrorCode> extends DokebiError<TCode> {
|
|
10
|
+
constructor(code: TCode, message: string, options?: DokebiErrorOptions);
|
|
11
|
+
}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { DokebiError } from '@dokebi/core';
|
|
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).',
|
|
4
|
+
INVALID_ARGUMENT: 'Pass a function to onPresence.',
|
|
5
|
+
INVALID_FILTER: 'Use { tenant } or { tenantPrefix } (exactly one), with room? and member?, strings of 1 to 256 bytes.',
|
|
6
|
+
INVALID_TARGET: 'A realtime namespace is 1 to 64 letters, digits, ., _ or -; a target is { tenant?, member?, room? }.',
|
|
7
|
+
INVALID_TYPE: 'Message types start with a letter: letters, digits, ., _, : or -, at most 64.',
|
|
8
|
+
INVALID_DATA: 'Send data that JSON.stringify accepts (no BigInt, no cycles).',
|
|
9
|
+
FROZEN: 'Register websocket routes during setup (dokebi-app sockets(), a plugin setup).',
|
|
10
|
+
SEAL_PROVIDER_MISSING: 'Register the dokebi-seal plugin (npx dokebi add @dokebi/seal), or remove seal from the route and the domains.',
|
|
11
|
+
SEAL_PROVIDER_INVALID: 'Register @dokebi/seal as the dokebi-seal plugin (it provides forConnection).',
|
|
12
|
+
SEAL_BINARY_UNSUPPORTED: 'Send text (UTF-8) on sealed sockets.',
|
|
13
|
+
SEAL_ENCODE_FAILED: 'Check the dokebi-seal plugin; the cause has the codec error.',
|
|
14
|
+
SOCKET_CLOSED: 'Send only while the connection is open; the client reconnects on its own.',
|
|
15
|
+
SLOW_CONSUMER: 'The client reads too slowly: send less, or raise maxBufferedBytes under dokebi-websocket in dokebi.yaml.',
|
|
16
|
+
ROOM_FORBIDDEN: 'Allow the room in the route authorizeRoom(identity, room).',
|
|
17
|
+
BROADCAST_FAILED: 'The cause lists the hub failures; the receipt has the tenants that worked.',
|
|
18
|
+
KICK_FAILED: 'The cause lists the hub failures; the receipt has the tenants that worked.',
|
|
19
|
+
};
|
|
20
|
+
const HINT = {
|
|
21
|
+
ROOM_FORBIDDEN: 'You cannot join this room.',
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* Errors of @dokebi/websocket; compare `code`, not the class (another installed copy may throw).
|
|
25
|
+
* A failed fan-out across tenants carries the first hub failure's code (for example RECOVERING)
|
|
26
|
+
* and `receipt`.
|
|
27
|
+
*/
|
|
28
|
+
export class WebsocketError extends DokebiError {
|
|
29
|
+
constructor(code, message, options = {}) {
|
|
30
|
+
super(code, message, {
|
|
31
|
+
plugin: 'dokebi-websocket',
|
|
32
|
+
...(Object.hasOwn(FIX, code) ? { fix: FIX[code] } : {}),
|
|
33
|
+
...(Object.hasOwn(HINT, code) ? { hint: HINT[code] } : {}),
|
|
34
|
+
...options,
|
|
35
|
+
});
|
|
36
|
+
this.name = 'WebsocketError';
|
|
37
|
+
}
|
|
38
|
+
}
|