@dokebi/websocket 0.3.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 +137 -96
- package/README.md +74 -59
- package/dist/errors.d.ts +11 -0
- package/dist/errors.js +38 -0
- package/dist/gateway.js +54 -57
- 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/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,97 +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.
|
|
88
103
|
|
|
89
|
-
##
|
|
104
|
+
## Route constraints and the message router (D-0030)
|
|
90
105
|
|
|
91
|
-
- `route({ constraints })`:
|
|
92
|
-
- `defineSocket({ path, authenticate, on: { '<type>': handler } })
|
|
93
|
-
- 2026-10-14
|
|
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.
|
|
94
109
|
|
|
95
|
-
##
|
|
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))
|
|
96
111
|
|
|
97
|
-
|
|
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).
|
|
98
113
|
|
|
99
|
-
- `list({ tenant | tenantPrefix, room?, member? })`: `tenant
|
|
100
|
-
- `send(filter, type, data?)`:
|
|
101
|
-
- `kick(filter, code?, reason?)`, `onPresence(listener)`(
|
|
102
|
-
-
|
|
103
|
-
-
|
|
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.
|
|
104
119
|
|
|
105
|
-
##
|
|
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)
|
|
106
121
|
|
|
107
|
-
|
|
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' })`).
|
|
108
123
|
|
|
109
|
-
```ts
|
|
124
|
+
```ts snippet
|
|
110
125
|
context.get(ws).route({
|
|
111
126
|
path: '/ws',
|
|
112
|
-
seal: (request) => request.headers.host === 'secure.example.com', //
|
|
127
|
+
seal: (request) => request.headers.host === 'secure.example.com', // or true. @dokebi/app fills it from domains.<host>.seal
|
|
113
128
|
authenticate, message,
|
|
114
129
|
});
|
|
115
130
|
```
|
|
116
131
|
|
|
117
|
-
-
|
|
118
|
-
-
|
|
119
|
-
-
|
|
120
|
-
- `sealDriftMs`(
|
|
121
|
-
-
|
|
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
|
+
}
|