@dokebi/websocket-hub 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 +96 -53
- package/README.md +69 -48
- package/dist/dependency.d.ts +4 -0
- package/dist/dependency.js +14 -0
- package/dist/event-queue.d.ts +6 -1
- package/dist/event-queue.js +9 -4
- package/dist/eviction.js +5 -5
- package/dist/hub-index.d.ts +29 -0
- package/dist/hub-index.js +146 -0
- package/dist/index.d.ts +5 -3
- package/dist/index.js +21 -25
- package/dist/leader.js +27 -24
- package/dist/local.d.ts +5 -1
- package/dist/local.js +80 -25
- package/dist/node.d.ts +2 -2
- package/dist/node.js +16 -16
- package/dist/options.d.ts +28 -33
- package/dist/options.js +106 -116
- package/dist/peer-client.js +13 -13
- package/dist/protocol.js +1 -1
- package/dist/status-cli.js +3 -3
- package/dist/status.d.ts +16 -4
- package/dist/status.js +112 -16
- package/dist/store.js +1 -1
- package/dist/types.d.ts +9 -4
- package/dist/types.js +22 -5
- package/dist/values.d.ts +4 -0
- package/dist/values.js +32 -0
- package/options.schema.json +105 -24
- package/package.json +35 -11
- package/dist/log.d.ts +0 -24
- package/dist/log.js +0 -101
package/AI.md
CHANGED
|
@@ -1,81 +1,124 @@
|
|
|
1
|
-
# AI
|
|
1
|
+
# AI guide — @dokebi/websocket-hub 0.4.1
|
|
2
2
|
|
|
3
|
-
WebSocket
|
|
3
|
+
The hub that manages WebSocket connection lists, rooms, broadcasts and kicks (it replaces the old `dokebi-sync`). A broadcast is **at most once**, with no receipt ACK or resend ([D-0057](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0057-websocket-broadcast-without-ack.md)). Usually **@dokebi/websocket uses it alone**, and app code uses websocket's `defineSocket`. Direct use is mostly operational status (`status()`, `dokebi-hub-status`) and replay defense for sealed frames (`nonces()`). Node >=24, core ^0.4.0, peers: @dokebi/redis, @dokebi/nats (cluster mode). Details are in the [README](README.md).
|
|
4
4
|
|
|
5
|
-
## 1.
|
|
5
|
+
## 1. Modes ([D-0029](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0029-hub-and-cluster-infrastructure.md))
|
|
6
6
|
|
|
7
|
-
| | `mode: local`(
|
|
7
|
+
| | `mode: local` (default) | `mode: cluster` |
|
|
8
8
|
|---|---|---|
|
|
9
|
-
|
|
|
10
|
-
|
|
|
11
|
-
|
|
|
12
|
-
| cluster
|
|
9
|
+
| Scope | one process (memory) | shared by processes and servers |
|
|
10
|
+
| Needs | nothing | Redis (required), NATS (optional: instant leader change notices; otherwise Redis polling) |
|
|
11
|
+
| Failure | state disappears with the process, no handover | every worker is a hub candidate, the leader is elected by a Redis lease, and when the leader dies real sockets stay and reconnect to the new hub |
|
|
12
|
+
| cluster workers | refused with `LOCAL_IN_CLUSTER` (allowed only with `allowInCluster: true`) | normal |
|
|
13
13
|
|
|
14
|
-
API
|
|
14
|
+
The API and broadcast semantics (at most once) are the same in both modes. `mode` keeps its name in 0.4.0: it names the deployment style, not a driver ([D-0071](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0071-option-vocabulary.md)).
|
|
15
15
|
|
|
16
|
-
## 2.
|
|
16
|
+
## 2. Configuration `options.dokebi-websocket-hub`
|
|
17
17
|
|
|
18
18
|
```yaml
|
|
19
19
|
dokebi-websocket-hub:
|
|
20
20
|
mode: cluster
|
|
21
|
-
namespace: shop #
|
|
22
|
-
serverId: web-a #
|
|
23
|
-
host: 0.0.0.0 #
|
|
21
|
+
namespace: shop # servers of the same namespace share a hub
|
|
22
|
+
serverId: web-a # different per server
|
|
23
|
+
host: 0.0.0.0 # hub TCP listen address
|
|
24
24
|
port: 0
|
|
25
|
-
advertiseHost: web-a.internal #
|
|
25
|
+
advertiseHost: web-a.internal # the address other servers use to reach this server's hub
|
|
26
26
|
redisConnection: primary
|
|
27
|
-
natsConnection: primary #
|
|
28
|
-
secret: (32
|
|
27
|
+
natsConnection: primary # optional
|
|
28
|
+
secret: (32+ random bytes, only in dokebi.yaml) # the same secret for the same namespace
|
|
29
29
|
```
|
|
30
30
|
|
|
31
|
-
|
|
|
32
|
-
|
|
33
|
-
| `
|
|
34
|
-
| `
|
|
35
|
-
| `
|
|
36
|
-
| `
|
|
37
|
-
| `
|
|
31
|
+
| Key | Type | Default | Description |
|
|
32
|
+
|---|---|---|---|
|
|
33
|
+
| `mode` | `local` \| `cluster` | `local` | §1 |
|
|
34
|
+
| `allowInCluster` | boolean | false | Allow local mode in a cluster worker |
|
|
35
|
+
| `namespace` / `serverId` | string ≤ 64 | `local` / `local` | Shared area / this server's id (`^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$`) |
|
|
36
|
+
| `redisConnection` / `natsConnection` | string | — | dokebi-redis (required in cluster) / dokebi-nats (optional) connection names |
|
|
37
|
+
| `host` / `advertiseHost` / `port` | string / string / integer 0–65535 | `127.0.0.1` / `127.0.0.1` / 0 | Hub TCP listen address, address announced to peers, port (0 = any) |
|
|
38
|
+
| `secret` | string, secret | — (required in cluster) | 32–256 characters and 32–256 bytes |
|
|
39
|
+
| `leaseMs` / `pollIntervalMs` | integer ms | 3000 / 500 | Leader lease / polling without NATS |
|
|
40
|
+
| `ownerTtlMs` / `startupTimeoutMs` | integer ms | 15000 / 15000 | Server registration expiry / startup wait |
|
|
41
|
+
| `maxFrameBytes` / `maxPayloadBytes` | integer | 1048576 / 65536 | Hub TCP frame / message |
|
|
42
|
+
| `maxConnections` / `maxOwners` / `maxTotalConnections` | integer | 128 / 64 / 8192 | Per server / number of servers / all connections |
|
|
43
|
+
| `maxPending` / `maxPendingBytes` | integer | 128 / 4194304 | Pending limits (more broadcasts in progress than this give `BUSY`) |
|
|
44
|
+
|
|
45
|
+
Keys renamed in 0.4.0 (D-0071). The old name is accepted with the warning `OPTION_DEPRECATED`; old and new together fail with `INVALID_OPTIONS`; 0.5.0 rejects it.
|
|
46
|
+
|
|
47
|
+
| Old key | New key |
|
|
48
|
+
|---|---|
|
|
49
|
+
| `pollMs` | `pollIntervalMs` |
|
|
50
|
+
| `startupMs` | `startupTimeoutMs` |
|
|
51
|
+
| `queueBytes` | `maxPendingBytes` |
|
|
38
52
|
|
|
39
|
-
|
|
53
|
+
**Removed options (0.3.0, D-0057)**: `deliveryTimeoutMs`, `retryMs`, `maxDeliveries`, `deliveryBytes`. Start still works when they remain in dokebi.yaml: each key logs warn `OPTION_REMOVED` (`option`, `reason`; since 0.4.0 core logs it at setup) once and the value is ignored (the schema keeps them as deprecated until the next version drops them). Delete them.
|
|
40
54
|
|
|
41
|
-
|
|
55
|
+
**Checks (0.4.0, [D-0063](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0063-core-primitives.md))**: the options are one `defineOptions` declaration in `src/options.ts` that is the parser, and `options.schema.json` is generated from it at build time. Rules that only the hand parser used to keep are in the schema now: connection names (`namespace`, `serverId`, `redisConnection`, `natsConnection`) `^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$`, no spaces or control characters in `host` and `advertiseHost`, and the defaults the parser filled in (`namespace` and `serverId` = `local`, `host` and `advertiseHost` = `127.0.0.1`). Cross-field rules are unchanged: `pollIntervalMs × 3 ≤ leaseMs`, `ownerTtlMs ≥ leaseMs × 3`, base64(`maxPayloadBytes`) + 8192 ≤ `maxFrameBytes`, `maxPendingBytes ≥ maxFrameBytes`. `secret` must be 32–256 **characters** and 32–256 **bytes** (the old schema counted characters, the parser only bytes). On failure the core `INVALID_OPTIONS` is the cause of `INVALID_PLUGIN_OPTIONS`, with paths and issue codes in `details.issues` (no values): `REDIS_REQUIRED` in cluster mode without a Redis connection, `SECRET_REQUIRED` when the secret is missing or has the wrong byte count, otherwise `required`, `pattern`, `check` and so on.
|
|
42
56
|
|
|
43
|
-
|
|
57
|
+
While a server with different settings (secret, limits) is alive in the same namespace, a new one is refused at once with `CONFIG_MISMATCH`; once every server with the old settings is down, the new settings take over.
|
|
44
58
|
|
|
45
|
-
|
|
46
|
-
- `register(...)`·`list(query)`·`broadcast(query, bytes)`·`kick(query)`·`events()`: websocket 플러그인이 쓰는 저수준 API. **`events()`의 소비자는 하나뿐**이며 websocket이 쓰고 있으면 따로 읽지 않는다. `message` 이벤트(`{ id, connections, data }`)가 전달의 전부다: 확인할 것(`acknowledge`)은 없다(0.3.0에서 제거).
|
|
47
|
-
- `broadcast` → receipt `{ id, recipients }`. 실패: `RECOVERING`(리더에 연결돼 있지 않음·리더 교체 중, 보내지 않음), `OUTCOME_UNKNOWN`(보낸 뒤 답 전에 연결이 끊김, 보내졌을 수 있음), `BUSY`(처리 중 방송이 `maxPending`; local은 이벤트 큐의 절반이 아직 안 읽힘). 허브는 다시 보내지 않는다. `kick` → `{ authorityEpoch, id }`.
|
|
48
|
-
- `status()`(D-0038) → `{ mode, state, role, leaseState?, leader?, leaseRemainingMs?, servers?, connections?, serverId? }`. 모르는 값은 0으로 채우지 않고 **빠진다**(Redis 무응답이면 `leaseState: 'unreachable'`).
|
|
49
|
-
- `nonces()`(D-0038) → `{ shared, setIfNotExists(key, ttlSeconds) }`. cluster는 Redis `SET NX PX`로 서버들이 공유하고(`shared: true`), local은 프로세스 안(`shared: false`, cluster 워커에서 쓰면 `HUB_NONCES_NOT_SHARED` 경고 한 번). 봉인 프레임의 재생 방어(@dokebi/crypto `SealTerminator`)에 넘긴다.
|
|
59
|
+
## 3. API (`import { dependency } from '@dokebi/websocket-hub/dependency'` → `getDependency`)
|
|
50
60
|
|
|
51
|
-
|
|
61
|
+
The provider descriptor lives in the subpath `@dokebi/websocket-hub/dependency` (D-0063 §6; a small module that loads neither the hub nor Redis nor NATS), and the package entry's `dependency` is the same object. Plugins and app code that always install the hub use the subpath. When the hub is optional (an optional peer), do not import it; keep `optionalDependency({ name: 'dokebi-websocket-hub', version: '^0.4.0' })` in your own file.
|
|
62
|
+
|
|
63
|
+
- `state` (`starting`, `ready`, `recovering`, `closing`, `closed`), `role` (`active`, `standby`), `ownerEpoch`, `leader`, `whenReady(timeoutMs)` → boolean.
|
|
64
|
+
- `register(...)` → `HubConnection` (`identity`, `join`, `leave`, `updateMetadata`, `close`), `list(query)` → `HubSnapshot`, `broadcast(query, bytes)`, `kick(query)`, `events()`: the low-level API websocket uses. A query (`HubQuery`) is a required `tenant` plus optional `room`, `member`, `connection` (AND). **`events()` has a single consumer**; when websocket uses it, never read it separately. The `message` event (`{ id, connections, data }`) is the whole delivery: there is nothing to confirm (`acknowledge` was removed in 0.3.0).
|
|
65
|
+
- `broadcast` → receipt `HubReceipt` `{ id, recipients }`. Failures: `RECOVERING` (not connected to the leader, or the leader is changing; not sent), `OUTCOME_UNKNOWN` (the connection dropped after sending, before the answer; it may have been sent), `BUSY` (broadcasts in progress reached `maxPending`; in local mode, half of the event queue is still unread). The hub never resends. `kick` → `HubKickReceipt` `{ authorityEpoch, id }` (default code 4403).
|
|
66
|
+
- `status()` (D-0038) → `HubStatus` `{ mode, state, role, leaseState?, leader?, leaseRemainingMs?, servers?, connections?, serverId? }`. Unknown values are **left out**, not filled with 0 (`leaseState: 'unreachable'` when Redis does not answer).
|
|
67
|
+
- `nonces()` (D-0038) → `HubNonceStore` `{ shared, setIfNotExists(key, ttlSeconds) }`. cluster shares it between servers through Redis `SET NX PX` (`shared: true`); local keeps it in the process (`shared: false`; used in a cluster worker it warns `HUB_NONCES_NOT_SHARED` once). Pass it to the replay defense of sealed frames (@dokebi/seal `SealTerminator`). Only the shape matches; seal is never imported. The local store holds at most 100000 live nonces and **fails closed** ([D-0075](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0075-replay-capacity.md)): it never forgets a live nonce; expired ones make room first (every expired entry, earliest expiry first, through an expiry heap), otherwise `setIfNotExists` rejects with `HubError` `NONCE_STORE_FULL` (seal answers it as a retryable `SEAL_REPLAY_CAPACITY`: web 503, websocket 1013) and warns `NONCE_STORE_FULL` once per 10 seconds with `max`, `live` and `repeated`. Nonces live 2 × the seal drift (120 s by default), so one local process takes about 830 sealed frames or bodies per second at most; above that use `mode: cluster` (Redis `SET NX PX`, no such limit).
|
|
68
|
+
- Exports: `createPlugin`, `dependency`, `HubError`, types `HubApi`, `HubConnection`, `HubRegistration`, `HubRecord`, `HubQuery`, `HubLeader`, `HubSnapshot`, `HubReceipt`, `HubKickReceipt`, `HubEvent`, `HubLease`, `HubStatus`, `HubNonceStore`.
|
|
69
|
+
|
|
70
|
+
## 4. Operations command `dokebi-hub-status`
|
|
52
71
|
|
|
53
72
|
```sh
|
|
54
|
-
npx dokebi-hub-status --config dokebi.yaml #
|
|
55
|
-
npx dokebi-hub-status --config dokebi.yaml --json #
|
|
73
|
+
npx dokebi-hub-status --config dokebi.yaml # human-readable
|
|
74
|
+
npx dokebi-hub-status --config dokebi.yaml --json # for machines
|
|
56
75
|
```
|
|
57
76
|
|
|
58
|
-
|
|
77
|
+
From outside the app process it reads only Redis and shows the leader, the remaining lease time, the number of live servers and the connection count (it never starts a hub or joins the election). When Redis does not answer it exits with code 1. In local mode it says the state lives only inside the process.
|
|
78
|
+
|
|
79
|
+
## 5. Delivery semantics (D-0057)
|
|
80
|
+
|
|
81
|
+
- **Success = sent out.** cluster: the leader picks the connections matching right now, writes one message frame to each server (owner) holding them, then gives the sending server a receipt. local: it is done once it is in this process's event queue (read by the websocket gateway). There is no receipt confirmation, resend, deduplication, completion record or deadline wait. It is **at most once**.
|
|
82
|
+
- **receipt** `{ id, recipients }`: `recipients` are the identifiers of the connections matching when it was sent (the SHA-256 of tenant, member and clientId, or of owner and connection without a clientId). **It does not mean they received it.** Connections that were reconnecting, that left before the frame was written, or that were closed with 1013 for being slow do not get it. Connections that arrive later do not get it either (nothing is kept).
|
|
83
|
+
- **Failures come at once and are never resent (no duplicates)**: `RECOVERING`, `OUTCOME_UNKNOWN`, `BUSY`. The caller decides whether to send again (resending after `OUTCOME_UNKNOWN` can deliver twice).
|
|
84
|
+
- **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. Work that must happen goes to @dokebi/job.
|
|
85
|
+
- **Protocol between hub servers (protocol 2)**: hello carries `protocol: 2`. The leader refuses other versions with `PROTOCOL_MISMATCH` (warn `Hub peer refused; protocol differs`), and the refused server logs error `Hub protocol differs from the leader; retrying` (`protocol`, `leaderProtocol`) and retries. A 0.3 server connected to a 0.2 leader (no version) is cut with the same error. During a rolling restart a server of another version cannot join the leader (while starting, `STARTUP_TIMEOUT` after `startupTimeoutMs`), so upgrade every server to the same version. The configuration fingerprint stays the same as 0.2 so that this version check, not `CONFIG_MISMATCH`, tells them apart.
|
|
86
|
+
- Broadcasts never go through Redis (only connection registrations and changes are stored in Redis, D-0042). No broadcast record stays in leader memory either.
|
|
87
|
+
- presence events come as the full list per owner (server). After a reconnect or leader change, owners that differ from the snapshot and owners that disappeared are announced again.
|
|
88
|
+
|
|
89
|
+
## 6. Index and performance ([D-0068](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0068-performance-stage4.md) §3)
|
|
90
|
+
|
|
91
|
+
- `HubIndex` (`src/hub-index.ts`) keeps tenant → member → connections, tenant → room → connections (insertion-ordered sets), owner → connection → record and recipientKey → record. local updates it on every register, change and close; the leader when the server list changes (`setOwner`/`removeOwner`, rebuilt from the snapshot at start).
|
|
92
|
+
- Selection walks only the smallest matching set (a named connection → one; member and room → the smaller; member; room; the whole tenant) and checks each with `matches`, so the answer equals a full scan (receipt semantics, presence and roster unchanged). The `DUPLICATE_CLIENT` check is O(1); `list` and `kick` use the same index.
|
|
93
|
+
- Evidence: a randomized 2000-step test (add, room change, remove, owner swap) compares every filter with the full scan; `benchmarks/scenarios/micro/hub-select.mjs` measures `select`; `websocket-load.bench.mjs 1024 300` passed with no missed, duplicated or misdirected messages and baseline receive p50/p95/p99 6.8/10.8/17.0 ms.
|
|
94
|
+
|
|
95
|
+
## 7. Errors
|
|
96
|
+
|
|
97
|
+
`HubError` (branch on `code`).
|
|
59
98
|
|
|
60
|
-
|
|
99
|
+
`HubError` is a `DokebiError` (0.4.0, D-0063): `plugin: 'dokebi-websocket-hub'`, and the message stays `WebSocket hub: <code>`. Codes an operator fixes carry a `fix`.
|
|
61
100
|
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
101
|
+
| Code | When |
|
|
102
|
+
|---|---|
|
|
103
|
+
| `LOCAL_IN_CLUSTER` | local mode started in a node:cluster worker (the role comes from core `context.runtime.role`). `fix`: `mode: cluster` or `allowInCluster: true`. Before 0.4.0 this error was HUB_LOCAL_IN_CLUSTER; the error log keeps that code |
|
|
104
|
+
| `LISTEN_FAILED` · `STARTUP_TIMEOUT` | Could not open the hub TCP · could not join the leader within `startupTimeoutMs` (with `fix`) |
|
|
105
|
+
| `CONFIG_MISMATCH` · `PROTOCOL_MISMATCH` · `UNAUTHORIZED` | Different settings, version or secret in the same namespace (with `fix`) |
|
|
106
|
+
| `RECOVERING` · `OUTCOME_UNKNOWN` · `BUSY` | Broadcast failures (§5) |
|
|
107
|
+
| `STORE_UNAVAILABLE` | Redis failure (the cause is in `cause`) |
|
|
108
|
+
| `INVALID_ARGUMENT` · `INVALID_OPTIONS` | Wrong API arguments or hub frame values (frame value codes are compared between servers, so they stay as in 0.3) |
|
|
109
|
+
| `NONCE_STORE_FULL` | The local nonce store holds 100000 live nonces: the new nonce is refused (fail closed, D-0075). Retryable; `fix`: `mode: cluster` or a smaller seal drift |
|
|
110
|
+
| `CONNECTION_LIMIT` · `MESSAGE_TOO_LARGE` · `DUPLICATE_CLIENT` · `DUPLICATE_CONNECTION` · `CLOSED` · `EVENT_OVERFLOW` | Limits, duplicates, shutdown |
|
|
69
111
|
|
|
70
|
-
##
|
|
112
|
+
## 8. Cautions
|
|
71
113
|
|
|
72
|
-
-
|
|
73
|
-
- secret
|
|
74
|
-
-
|
|
75
|
-
-
|
|
76
|
-
-
|
|
77
|
-
-
|
|
78
|
-
- debug(`DOKEBI_LOG_LEVEL=debug`):
|
|
79
|
-
- `dokebi-hub-status
|
|
114
|
+
- Never trust tenant, member or rooms sent by the client (the authentication function decides them).
|
|
115
|
+
- The secret lives only in dokebi.yaml, at least 32 random bytes. Every server of a namespace uses the same secret, options and Redis/NATS.
|
|
116
|
+
- Each server needs a different `serverId` and an `advertiseHost` and TCP port reachable from other servers (firewalls). The hub TCP has no built-in TLS; use a trusted private network or an encrypted tunnel.
|
|
117
|
+
- Never close the hub, Redis or NATS before the whole drain (core ordering ensures it).
|
|
118
|
+
- **Operations ([D-0049](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0049-redis-rejections-and-eviction.md))**: Redis for cluster mode uses `maxmemory-policy noeviction`. With an evicting policy the leader key gets evicted and the hub goes through `STALE_LEADER` and `RECOVERING` (OPS-002 G). Put caches on a separate Redis (`allkeys-lru`). At node start it reads `CONFIG GET maxmemory*` once; with `maxmemory > 0` and a policy other than `noeviction` it logs **error `REDIS_EVICTION_UNSAFE`** (`policy`, `maxmemory`, `connection`) and **starts anyway** (an operator may accept the risk). When safe, debug `REDIS_EVICTION_CHECKED`; a managed Redis or ACL that blocks CONFIG gives debug `REDIS_EVICTION_CHECK_SKIPPED` (`reason: rejected` + the full `error`); an older @dokebi/redis the same code (`reason: unsupported`); any other failure error `REDIS_EVICTION_CHECK_FAILED`. Redis error replies (OOM and so on) now stay as `COMMAND_REJECTED` with the server reply in the cause of `STORE_UNAVAILABLE`.
|
|
119
|
+
- Logs ([D-0047](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0047-logging-and-no-silent-errors.md)): exceptions are never dropped silently. Failures that cannot be turned into a defined error or response code are logged at `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: lost leader connection `Hub connection dropped` (debug when the node itself closed it with `RECOVERING` or `CLOSED`, during `bye`, or after the leader announced `leaving` — D-0056), recovery start `Hub transport or store unavailable; recovering`, peer send failure `PEER_SEND_FAILED` (backpressure included), peer socket and frame `PEER_SOCKET_ERROR`, `PEER_FRAME_REJECTED` (a socket error before hello is debug `Hub peer connection failed before it was established`, and the startup retry or recovery log reports it with the cause), when the leader vanished first and `bye` could not be sent but Redis `leave` worked, debug `Hub goodbye not delivered; left through Redis` (a successful stop), a leader of another version `PROTOCOL_MISMATCH` (error; the refusing leader logs warn), removed options `OPTION_REMOVED` (warn, once per key at start), NATS `NATS_PUBLISH_FAILED`, `NATS_SUBSCRIPTION_FAILED`, local event queue overflow `EVENT_OVERFLOW`, a Redis failure of `status()` `STATUS_UNREACHABLE`. Redis failures stay as the `cause` of `STORE_UNAVAILABLE`. Places that run per frame or message write the same message and code once per interval (10 seconds) and group the rest as a `repeated` count (the remaining count is written at shutdown too). Bodies, secrets and tokens are never logged.
|
|
120
|
+
- debug (`DOKEBI_LOG_LEVEL=debug`): election, leader start and stop, lease loss, leader connection and reconnect (`Hub connected to leader`, ms taken, resync count), server registration, removal and expiry, connection list changes, broadcasts `Hub broadcast sent` (leader and local: `id`, `recipients`, `owners`, `ms`; no body), broadcasts of unknown outcome `OUTCOME_UNKNOWN` (not resent), refusals (`BUSY`, `STALE_*`), failures while still recovering (`Hub still recovering`), and the recovery time at info (`Hub recovered`).
|
|
121
|
+
- `dokebi-hub-status` writes the cause of a Redis failure to stderr (the stdout JSON stays as it is).
|
|
122
|
+
- Extension hooks for the hub are listed as candidates in [D-0064](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0064-extension-contract.md) §9; there is no extension class yet.
|
|
80
123
|
|
|
81
|
-
|
|
124
|
+
Evidence: `examples/18-websocket-hub` (real TCP peers, leader handover), `examples/23-websocket`, `examples/25-playground`, `tests/status.test.ts` (status, nonces, the command), D-0024, D-0029, D-0034, D-0038, D-0057 (replacing the ACK and resend of D-0025 and D-0042).
|
package/README.md
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
1
|
# @dokebi/websocket-hub
|
|
2
2
|
|
|
3
|
-
Node >=24, 0.
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
- **`mode: local`(
|
|
8
|
-
- API
|
|
9
|
-
-
|
|
10
|
-
- `node:cluster`
|
|
11
|
-
- **`mode: cluster`:**
|
|
12
|
-
-
|
|
13
|
-
- `namespace
|
|
14
|
-
- NATS(`natsConnection`)
|
|
15
|
-
-
|
|
16
|
-
-
|
|
17
|
-
- **`whenReady(timeoutMs)`(D-0034):**
|
|
18
|
-
- **presence
|
|
3
|
+
Node >=24, version 0.4.1 (unreleased). An optional plugin of Dokebi `@dokebi/core ^0.4.0`: a TCP hub that replaces the former `@dokebi/sync`. AI agents start with [AI.md](AI.md).
|
|
4
|
+
|
|
5
|
+
There are two modes ([D-0029](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0029-hub-and-cluster-infrastructure.md)).
|
|
6
|
+
|
|
7
|
+
- **`mode: local` (default):** a hub for one process. It handles connection lists, rooms, broadcasts and kicks in memory, without Redis or NATS.
|
|
8
|
+
- The API and broadcast semantics are those of cluster mode (at most once, "Broadcast" below). A broadcast is done once it is in the event queue websocket reads. When half of that queue is still unread it is refused with `BUSY` (leaving room for presence and kicks).
|
|
9
|
+
- There is no failover.
|
|
10
|
+
- In `node:cluster` workers the workers cannot share connections, so start is refused with `LOCAL_IN_CLUSTER`. Allow it with `allowInCluster: true` only on purpose.
|
|
11
|
+
- **`mode: cluster`:** connections are shared by processes and servers.
|
|
12
|
+
- Every WebSocket worker is a hub candidate, and a Redis lease elects one. TCP carries user registrations, snapshots, broadcast and targeted messages and kicks, and Redis keeps the connection list.
|
|
13
|
+
- `namespace`, `serverId`, `redisConnection` and `secret` are required.
|
|
14
|
+
- NATS (`natsConnection`) is optional. With it, leader changes are announced at once; without it other servers notice through Redis polling (`pollIntervalMs`).
|
|
15
|
+
- When the hub dies, the real WebSockets of healthy servers stay and reconnect to the new hub.
|
|
16
|
+
- **Install check:** the install module's `check` looks at the mode and reports the required plugins: Redis in cluster mode, and NATS too when a NATS connection is set.
|
|
17
|
+
- **`whenReady(timeoutMs)` (D-0034):** true once ready, false when the time passes or it closes. websocket uses it to wait out short reconnects when accepting upgrades. It logs why the leader connection dropped (`Hub connection dropped`), failures while recovery continues (`Hub still recovering`) and the recovery time (`Hub recovered`).
|
|
18
|
+
- **presence events:** they come as the full list per owner (server) when connections come and go. When a peer reconnects or the leader changes, owners that differ from the snapshot and owners that disappeared are announced again as presence events, so consumers never miss connections that left meanwhile.
|
|
19
19
|
|
|
20
20
|
```yaml
|
|
21
21
|
schemaVersion: 1
|
|
@@ -39,9 +39,9 @@ options:
|
|
|
39
39
|
secret: replace-with-your-random-secret-at-least-32-bytes
|
|
40
40
|
```
|
|
41
41
|
|
|
42
|
-
serverId
|
|
42
|
+
`serverId`/`advertiseHost` are per server; `namespace`, `secret`, shared stores and distributed limits must match across the area. Each worker opens its own TCP port (`port` default 0), which must be reachable from other servers. The TCP has no built-in TLS, so use a trusted private network or an encrypted tunnel.
|
|
43
43
|
|
|
44
|
-
```ts
|
|
44
|
+
```ts snippet
|
|
45
45
|
import { Application, loadConfig } from '@dokebi/core';
|
|
46
46
|
import { createPlugin } from '@dokebi/websocket-hub';
|
|
47
47
|
const config = await loadConfig('./dokebi.yaml');
|
|
@@ -51,59 +51,80 @@ app.register(plugin);
|
|
|
51
51
|
await app.start();
|
|
52
52
|
const hub = app.get(plugin);
|
|
53
53
|
const connection = await hub.register({tenant:'demo',member:'alice',connection:'socket-1'});
|
|
54
|
-
// websocket
|
|
54
|
+
// With the websocket plugin, that plugin is the sole consumer instead.
|
|
55
55
|
const consumer = (async () => {
|
|
56
56
|
for await (const event of hub.events()) {
|
|
57
|
-
// message
|
|
57
|
+
// the message event is the whole delivery: write event.data to this server's event.connections (no ACK).
|
|
58
58
|
if (event.kind === 'message') writeToSockets(event.connections, event.data);
|
|
59
59
|
}
|
|
60
60
|
})();
|
|
61
61
|
const snapshot = await hub.list({tenant:'demo'});
|
|
62
62
|
const receipt = await hub.broadcast({tenant:'demo',member:'alice'}, new TextEncoder().encode('hello'));
|
|
63
|
-
// receipt: { id, recipients } —
|
|
63
|
+
// receipt: { id, recipients } — connections matching when sent (not a confirmation of receipt)
|
|
64
64
|
await connection.close();
|
|
65
65
|
await app.stop();
|
|
66
66
|
await consumer;
|
|
67
67
|
```
|
|
68
68
|
|
|
69
|
-
HubConnection
|
|
69
|
+
`HubConnection`: `identity` (ownerEpoch/connection), `join(room)`, `leave(room)`, `updateMetadata(record)`, `close()`. `HubApi`: `state`, `role`, `ownerEpoch`, `leader`, `register`, `list`, `broadcast`, `kick`, `events`, `whenReady`, `status`, `nonces`. A query is the AND of a required `tenant` and optional `room`/`member`/`connection`. `events` is the single async iterator of presence, message and kick events. kick (default code 4403) is a TCP request that returns `{ authorityEpoch, id }`.
|
|
70
70
|
|
|
71
|
-
|
|
71
|
+
| Key | Type | Default | Description |
|
|
72
|
+
|---|---|---|---|
|
|
73
|
+
| `leaseMs` | integer ms | 3000 | Leader lease |
|
|
74
|
+
| `pollIntervalMs` | integer ms | 500 | Polling without NATS |
|
|
75
|
+
| `ownerTtlMs` | integer ms | 15000 | Server registration expiry |
|
|
76
|
+
| `startupTimeoutMs` | integer ms | 15000 | Startup wait |
|
|
77
|
+
| `maxOwners` | integer | 64 | Servers |
|
|
78
|
+
| `maxConnections` | integer | 128 | Connections per worker |
|
|
79
|
+
| `maxTotalConnections` | integer | 8192 | All connections |
|
|
80
|
+
| `maxFrameBytes` | integer | 1048576 | Hub TCP frame |
|
|
81
|
+
| `maxPayloadBytes` | integer | 65536 | Message |
|
|
82
|
+
| `maxPending` | integer | 128 | Broadcasts in progress |
|
|
83
|
+
| `maxPendingBytes` | integer | 4194304 | Queue bytes |
|
|
72
84
|
|
|
73
|
-
|
|
85
|
+
A full snapshot also stays within the frame limit. Check the [option schema](options.schema.json). It requires `pollIntervalMs × 3 ≤ leaseMs` and `ownerTtlMs ≥ leaseMs × 3`. 0.4.0 renamed `pollMs` → `pollIntervalMs`, `startupMs` → `startupTimeoutMs` and `queueBytes` → `maxPendingBytes` ([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.
|
|
74
86
|
|
|
75
|
-
|
|
76
|
-
- **receipt의 `recipients`** 는 보낸 시점에 조건에 맞은 연결의 식별자다(tenant·member·clientId의 SHA-256, clientId가 없으면 owner·connection). 받았다는 확인이 아니다. 재접속 중이던 연결, 프레임이 써지기 전에 떠난 연결, 느려서 1013으로 닫힌 연결은 못 받고, 나중에 들어온 연결은 받지 않는다.
|
|
77
|
-
- **실패는 바로 알리고 다시 보내지 않는다.** `RECOVERING`: 리더에 연결돼 있지 않다(리더 교체 중 포함) — 보내지 않았다. `OUTCOME_UNKNOWN`: 요청을 보낸 뒤 답 전에 연결이 끊겼다 — 보내졌을 수 있다. `BUSY`: 처리 중인 방송이 `maxPending`이다. 다시 보낼지는 호출자가 정한다.
|
|
78
|
-
- **앱 지침:** 놓치면 안 되는 일(주문 상태·결제 결과)은 방송에 맡기지 않는다. DB에 저장하고, 페이지는 다시 연결될 때 서버에서 최신 상태를 읽는다. 방송은 「바뀌었으니 다시 읽어라」 알림으로 쓴다. 반드시 처리돼야 하는 업무는 @dokebi/job으로 보낸다.
|
|
79
|
-
- **없어진 옵션:** `deliveryTimeoutMs`·`retryMs`·`maxDeliveries`·`deliveryBytes`. 남아 있어도 시작은 되며 키마다 warn `OPTION_REMOVED`를 한 번 남기고 무시한다. 스키마에는 deprecated로 남는다(다음 판에서 삭제).
|
|
80
|
-
- **허브 서버끼리의 판:** hello에 `protocol: 2`. 리더는 다른 판의 서버를 `PROTOCOL_MISMATCH`로 거절하고(warn), 거절된 서버는 양쪽 판을 담은 error를 남기며 재시도한다. 0.2 리더에 붙은 0.3 서버도 끊는다. 롤링 재시작 중 판이 섞이면 옛 판 서버는 새 리더에 붙지 못하므로 namespace의 모든 서버를 같은 판으로 올린다. 설정 지문은 0.2와 같게 두어 판 검사가 갈라 낸다(0.1.x Redis outbox와는 여전히 `CONFIG_MISMATCH`).
|
|
81
|
-
- `clientId`는 인증된 기기·탭별 식별자다. 같은 `(tenant, member, clientId)`의 동시 등록은 `DUPLICATE_CLIENT`로 거절한다.
|
|
87
|
+
## Broadcast: at most once (0.3.0, [D-0057](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0057-websocket-broadcast-without-ack.md))
|
|
82
88
|
|
|
83
|
-
|
|
89
|
+
- **Success = sent out.** In cluster mode the leader picks the connections matching right now, writes one message frame to each server holding them, then gives the sending server the receipt `{ id, recipients }`. local is done once it is in the event queue. There is no client ACK, resend, deduplication, completion record or deadline wait. Broadcasts never go through Redis and never stay in leader memory.
|
|
90
|
+
- **`recipients` of the receipt** are the identifiers of the connections matching when it was sent (the SHA-256 of tenant, member and clientId, or of owner and connection without a clientId). It is not a confirmation of receipt. Connections that were reconnecting, that left before the frame was written or that were closed with 1013 for being slow do not get it, and connections arriving later do not get it.
|
|
91
|
+
- **Failures are reported at once and never resent.** `RECOVERING`: not connected to the leader (leader change included) — not sent. `OUTCOME_UNKNOWN`: the connection dropped after sending the request, before the answer — it may have been sent. `BUSY`: broadcasts in progress reached `maxPending`. The caller decides whether to send again.
|
|
92
|
+
- **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. Work that must happen goes to @dokebi/job.
|
|
93
|
+
- **Removed options:** `deliveryTimeoutMs`, `retryMs`, `maxDeliveries`, `deliveryBytes`. Start still works when they remain; each key logs warn `OPTION_REMOVED` once and is ignored. The schema keeps them as deprecated (removed in the next version).
|
|
94
|
+
- **Version between hub servers:** hello carries `protocol: 2`. The leader refuses servers of another version with `PROTOCOL_MISMATCH` (warn), and the refused server logs an error with both versions and retries. A 0.3 server connected to a 0.2 leader is cut too. When versions mix during a rolling restart, old servers cannot join the new leader, so upgrade every server of the namespace to the same version. The configuration fingerprint stays the same as 0.2 so the version check tells them apart (against a 0.1.x Redis outbox it is still `CONFIG_MISMATCH`).
|
|
95
|
+
- `clientId` is an identifier per authenticated device or tab. A concurrent registration of the same `(tenant, member, clientId)` is refused with `DUPLICATE_CLIENT`.
|
|
84
96
|
|
|
85
|
-
|
|
86
|
-
- **`dokebi-hub-status --config dokebi.yaml [--json]`:** 앱 밖에서 같은 질문에 답한다. Redis 플러그인만 띄워 리더 기록과 소유자 기록을 읽고, 선출에 끼거나 등록하지 않는다. Redis 가 답하지 않으면 exit 1 이다. local 모드는 상태가 프로세스 안에만 있다고 말한다.
|
|
87
|
-
- **`nonces()`:** 봉인 프레임의 1회용 nonce 저장소다(@dokebi/crypto `SealTerminator` 의 `nonces` 에 그대로 넣는다 · 모양만 맞추고 crypto 를 import 하지 않는다). cluster 모드는 Redis `SET NX PX`(`shared: true`)라 다른 서버로 재전송한 프레임도 거절된다. local 모드는 프로세스 안(`shared: false`)이고, cluster 워커에서 쓰면 처음 한 번 `HUB_NONCES_NOT_SHARED` 경고를 낸다.
|
|
97
|
+
## Operational status and replay defense (D-0038)
|
|
88
98
|
|
|
89
|
-
|
|
99
|
+
- **`status()`:** returns this process (`mode`, `state`, `role`, `serverId`) together with the hub as Redis sees it (`leaseState`, `leader`, `leaseRemainingMs`, `servers`, `connections`). The calculation is one pure function, `hubStatus`. Unknown values are left out, not filled with 0 — with `leaseState: 'unreachable'` (Redis does not answer) there are no `servers` or `connections`. `none` means no leader (failover in progress, or no server is up).
|
|
100
|
+
- **`dokebi-hub-status --config dokebi.yaml [--json]`:** answers the same question from outside the app. It starts only the Redis plugin and reads the leader and owner records, without joining the election or registering. When Redis does not answer it exits with 1. In local mode it says the state lives only inside the process.
|
|
101
|
+
- **`nonces()`:** the one-time nonce store for sealed frames (passed as is to `nonces` of @dokebi/seal `SealTerminator`; only the shape matches and seal is never imported). cluster mode uses Redis `SET NX PX` (`shared: true`), so a frame replayed to another server is refused too. local mode keeps it in the process (`shared: false`) and warns `HUB_NONCES_NOT_SHARED` once when used in a cluster worker. The local store keeps at most 100000 live nonces and fails closed (D-0075): it never drops a live nonce to make room, so when it is full of live nonces (more than about 830 sealed frames or bodies per second for 2 × drift = 120 s) new ones are refused with `NONCE_STORE_FULL` (retryable: web 503 `SEAL_BUSY`, websocket 1013), with a warn `NONCE_STORE_FULL` once per 10 seconds. This keeps replay protection at the cost of availability under such a flood; use cluster mode (Redis) for more.
|
|
90
102
|
|
|
91
|
-
|
|
103
|
+
## Factory and dependencies (plugin contract v2)
|
|
92
104
|
|
|
93
|
-
|
|
94
|
-
- `@dokebi/redis`·`@dokebi/nats`는 `peerDependencies`다. 앱이 두 패키지를 함께 설치해야 한다.
|
|
95
|
-
- 다른 플러그인은 `import { dependency } from '@dokebi/websocket-hub'`를 `metadata.dependencies`에 넣고 `context.getDependency(dependency)`로 API를 얻는다.
|
|
96
|
-
- Redis 권한 스크립트는 저장소마다 `redis.script()`로 한 번 만들고 `EVALSHA`로 실행한다. 서버에 스크립트가 없을 때(`NOSCRIPT`)만 `EVAL`을 한 번 다시 보낸다.
|
|
105
|
+
The factory input is `{ app, options? }`; `app` is required. Without options it reads `app.config['dokebi-websocket-hub']`. It takes no `dependencies` record and no Redis or NATS instance inputs ([D-0028](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0028-plugin-contract-v2.md)).
|
|
97
106
|
|
|
98
|
-
|
|
107
|
+
- Redis and NATS are wired through the `dokebi-redis` and `dokebi-nats` provider descriptors. A plugin registered under the same name is reused; otherwise it is created from the `@dokebi/redis` or `@dokebi/nats` package with `app.config`. To choose one, register it first, e.g. `app.register(createRedis({ app: app.view }))`.
|
|
108
|
+
- `@dokebi/redis` and `@dokebi/nats` are `peerDependencies`. The app installs both packages.
|
|
109
|
+
- Other plugins put `import { dependency } from '@dokebi/websocket-hub/dependency'` (the provider descriptor, the same object as the package entry's `dependency`) in `metadata.dependencies` and get the API with `context.getDependency(dependency)`. Plugins for which the hub is optional keep their own `optionalDependency`.
|
|
110
|
+
- The Redis authority script is created once per store with `redis.script()` and runs as `EVALSHA`. Only when the server lacks the script (`NOSCRIPT`) is `EVAL` sent once more.
|
|
99
111
|
|
|
100
|
-
|
|
112
|
+
With the CLI, prepare the YAML and register in the order `npx dokebi add @dokebi/redis` → `@dokebi/nats` → `@dokebi/websocket-hub`. The manifest is schemaVersion 2, and its install module (`dist/install.js`) only reports required plugins; it creates no files. Installing makes no server connections. The hub has no drain hook and closes its resources in cleanup after the app drain finished.
|
|
101
113
|
|
|
102
|
-
|
|
114
|
+
Example 18 in the repository covers the public API and a local TCP baseline; example 23 verifies two Docker servers, four workers, hub and server faults and a real DB drain. That does not mean a full port of XFramework's extra media and nonce features or full operational certification.
|
|
103
115
|
|
|
104
|
-
|
|
116
|
+
## Configuration fingerprint (2026-10-14)
|
|
105
117
|
|
|
106
|
-
|
|
118
|
+
Servers of one namespace need the same secret, lease and limit settings (the configuration fingerprint in Redis). While a server with different settings is alive, a new server fails to start at once with `CONFIG_MISMATCH` and logs an error (`code: CONFIG_MISMATCH`). Once every leader and owner with the old settings is gone (a full restart), the new settings replace the fingerprint. So rotating the secret is a full stop and start, without deleting Redis keys ([ISSUE-0005](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/issues/ISSUE-0005-playground-findings.md) PG-16).
|
|
107
119
|
|
|
108
|
-
|
|
109
|
-
|
|
120
|
+
## Shutdown cleanup and startup logs (2026-10-14)
|
|
121
|
+
|
|
122
|
+
- On a normal shutdown a node deletes its own owner record from Redis directly (`leave`: without the leader, only for the same session). Even when everything stops at once, records do not stay until `ownerTtlMs`, so a restart right after a settings change works (PG-21).
|
|
123
|
+
- Retries during startup (such as connecting to a leader TCP that is not open yet) log no warnings. Past the startup deadline (`startupTimeoutMs`) the error log `STARTUP_TIMEOUT` records the last error code (`lastError`). Fault warnings after start carry a `code` (PG-19).
|
|
124
|
+
|
|
125
|
+
## 0.4.0 shared base (D-0063)
|
|
126
|
+
|
|
127
|
+
- The options are one declaration in `src/options.ts` that is both the parser and `options.schema.json` (generated at build time; `npm run check:options` compares bytes). The connection name and host rules and defaults that only the hand parser kept are in the schema now, and `secret` counts characters and bytes together. Core logs the warn `OPTION_REMOVED` for removed options.
|
|
128
|
+
- `HubError` is a `DokebiError` (`plugin`, `fix` for codes an operator fixes). Log helpers and repeat suppression use core `diagnostics` (`describeError`, `Repeats`).
|
|
129
|
+
- The cluster worker check uses core `context.runtime.role` instead of `node:cluster` (`LOCAL_IN_CLUSTER`, `HUB_NONCES_NOT_SHARED`). The cluster error code was `HUB_LOCAL_IN_CLUSTER` before 0.4.0 (D-0071); the error log keeps that code.
|
|
130
|
+
- The hub index ([D-0068](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0068-performance-stage4.md) §3: per tenant, member, room, owner and recipient key, so selection walks the smallest matching set) and the delivery semantics are unchanged. Possible future extension hooks are listed in [D-0064](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0064-extension-contract.md) §9 (there is no extension class yet).
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { HubApi } from './types.js';
|
|
2
|
+
export declare const provider: import("@dokebi/core").ProviderDescriptor<HubApi>;
|
|
3
|
+
/** Required: created from @dokebi/websocket-hub when no `dokebi-websocket-hub` plugin is registered. */
|
|
4
|
+
export declare const dependency: import("@dokebi/core").PluginDependency<HubApi>;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { defineProvider } from '@dokebi/core';
|
|
2
|
+
/*
|
|
3
|
+
* The one place dokebi-websocket-hub states its name, package and range (D-0063 §6). Plugins and
|
|
4
|
+
* user code that always install @dokebi/websocket-hub import `dependency` from
|
|
5
|
+
* '@dokebi/websocket-hub/dependency' (a small module: it does not load the hub, Redis or NATS).
|
|
6
|
+
*/
|
|
7
|
+
export const provider = defineProvider({
|
|
8
|
+
name: 'dokebi-websocket-hub',
|
|
9
|
+
version: '^0.4.0',
|
|
10
|
+
packageName: '@dokebi/websocket-hub',
|
|
11
|
+
load: () => import('./index.js'),
|
|
12
|
+
});
|
|
13
|
+
/** Required: created from @dokebi/websocket-hub when no `dokebi-websocket-hub` plugin is registered. */
|
|
14
|
+
export const dependency = provider.dependency;
|
package/dist/event-queue.d.ts
CHANGED
|
@@ -11,7 +11,12 @@ export declare class EventQueue implements AsyncIterableIterator<HubEvent> {
|
|
|
11
11
|
* rest of the queue to events that cannot be refused (presence).
|
|
12
12
|
*/
|
|
13
13
|
offer(value: HubEvent, share: number): boolean;
|
|
14
|
-
|
|
14
|
+
/**
|
|
15
|
+
* Queues `value`, or hands it to a waiting reader. `bytes` is its size when the producer keeps
|
|
16
|
+
* it already (the local hub sums its roster as it changes): sizing a presence event here would
|
|
17
|
+
* serialize the whole roster on every change, O(N) per registration (review PERF-B).
|
|
18
|
+
*/
|
|
19
|
+
push(value: HubEvent, bytes?: number): void;
|
|
15
20
|
next(): Promise<IteratorResult<HubEvent>>;
|
|
16
21
|
finish(error?: unknown): void;
|
|
17
22
|
return(): Promise<IteratorResult<HubEvent>>;
|
package/dist/event-queue.js
CHANGED
|
@@ -27,17 +27,22 @@ export class EventQueue {
|
|
|
27
27
|
offer(value, share) {
|
|
28
28
|
if (this.#ended)
|
|
29
29
|
return false;
|
|
30
|
+
const bytes = this.#size(value);
|
|
30
31
|
if (!this.#waiter &&
|
|
31
32
|
(this.#values.length >= Math.ceil(this.capacity * share) ||
|
|
32
|
-
this.#bytes +
|
|
33
|
+
this.#bytes + bytes > this.maxBytes * share))
|
|
33
34
|
return false;
|
|
34
|
-
this.push(value);
|
|
35
|
+
this.push(value, bytes);
|
|
35
36
|
return true;
|
|
36
37
|
}
|
|
37
|
-
|
|
38
|
+
/**
|
|
39
|
+
* Queues `value`, or hands it to a waiting reader. `bytes` is its size when the producer keeps
|
|
40
|
+
* it already (the local hub sums its roster as it changes): sizing a presence event here would
|
|
41
|
+
* serialize the whole roster on every change, O(N) per registration (review PERF-B).
|
|
42
|
+
*/
|
|
43
|
+
push(value, bytes = this.#size(value)) {
|
|
38
44
|
if (this.#ended)
|
|
39
45
|
return;
|
|
40
|
-
const bytes = this.#size(value);
|
|
41
46
|
if (this.#waiter) {
|
|
42
47
|
const w = this.#waiter;
|
|
43
48
|
this.#waiter = undefined;
|
package/dist/eviction.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { diagnostics } from '@dokebi/core/libraries';
|
|
2
2
|
function rejected(error) {
|
|
3
3
|
if (error === null || typeof error !== 'object')
|
|
4
4
|
return false;
|
|
5
|
-
const {
|
|
6
|
-
return
|
|
5
|
+
const { plugin, code } = error;
|
|
6
|
+
return plugin === 'dokebi-redis' && code === 'COMMAND_REJECTED';
|
|
7
7
|
}
|
|
8
8
|
/**
|
|
9
9
|
* D-0049: a Redis that evicts keys under maxmemory deletes the hub's leader and owner keys, and
|
|
@@ -45,13 +45,13 @@ export async function checkEviction(redis, logger) {
|
|
|
45
45
|
code: 'REDIS_EVICTION_CHECK_SKIPPED',
|
|
46
46
|
...fields,
|
|
47
47
|
reason: 'rejected',
|
|
48
|
-
error:
|
|
48
|
+
error: diagnostics.describeError(error),
|
|
49
49
|
});
|
|
50
50
|
else
|
|
51
51
|
logger.log('error', 'Redis eviction check failed', {
|
|
52
52
|
code: 'REDIS_EVICTION_CHECK_FAILED',
|
|
53
53
|
...fields,
|
|
54
|
-
error:
|
|
54
|
+
error: diagnostics.describeError(error),
|
|
55
55
|
});
|
|
56
56
|
}
|
|
57
57
|
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { type Selection } from './delivery.js';
|
|
2
|
+
import type { HubQuery, HubRecord } from './types.js';
|
|
3
|
+
/**
|
|
4
|
+
* The hub's connections indexed for selection (D-0068): tenant → member → connections, tenant →
|
|
5
|
+
* room → connections, and owner → connection → record. A targeted send (member, connection)
|
|
6
|
+
* costs O(1) plus its recipients and a room or tenant broadcast O(recipients), instead of a scan
|
|
7
|
+
* of every connection. Every candidate is still checked with `matches`, so the answer is the
|
|
8
|
+
* same as filtering all records (D-0057).
|
|
9
|
+
*/
|
|
10
|
+
export declare class HubIndex {
|
|
11
|
+
#private;
|
|
12
|
+
get size(): number;
|
|
13
|
+
/** The record of a connection, or undefined. */
|
|
14
|
+
get(ownerEpoch: string, connection: string): HubRecord | undefined;
|
|
15
|
+
/** The record already registered under the same recipient identity, if any. */
|
|
16
|
+
client(record: HubRecord): HubRecord | undefined;
|
|
17
|
+
/** Adds a record; a record of the same owner and connection is replaced. */
|
|
18
|
+
add(record: HubRecord): void;
|
|
19
|
+
/** Removes a record (by identity); false when it is not indexed. */
|
|
20
|
+
remove(record: HubRecord): boolean;
|
|
21
|
+
/** Replaces every record of one owner (a cluster server's full list). */
|
|
22
|
+
setOwner(ownerEpoch: string, records: readonly HubRecord[]): void;
|
|
23
|
+
removeOwner(ownerEpoch: string): void;
|
|
24
|
+
clear(): void;
|
|
25
|
+
/** The records that match `filter`, in the order they were indexed. */
|
|
26
|
+
matching(filter: HubQuery): Generator<HubRecord>;
|
|
27
|
+
/** What `select` of delivery.ts returns for all indexed records, without the scan. */
|
|
28
|
+
select(filter: HubQuery): Selection;
|
|
29
|
+
}
|