@dokebi/websocket-hub 0.1.1 → 0.3.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 +21 -13
- package/README.md +17 -10
- package/dist/delivery.d.ts +15 -32
- package/dist/delivery.js +21 -146
- package/dist/event-queue.d.ts +6 -0
- package/dist/event-queue.js +21 -3
- package/dist/eviction.d.ts +9 -0
- package/dist/eviction.js +57 -0
- package/dist/index.js +14 -3
- package/dist/leader.d.ts +3 -1
- package/dist/leader.js +232 -54
- package/dist/local.d.ts +7 -7
- package/dist/local.js +77 -96
- package/dist/log.d.ts +24 -0
- package/dist/log.js +101 -0
- package/dist/node.js +78 -16
- package/dist/options.d.ts +8 -5
- package/dist/options.js +13 -8
- package/dist/peer-client.d.ts +13 -4
- package/dist/peer-client.js +288 -153
- package/dist/protocol.d.ts +6 -0
- package/dist/protocol.js +6 -0
- package/dist/status-cli.js +7 -2
- package/dist/store.js +15 -42
- package/dist/types.d.ts +18 -5
- package/dist/types.js +2 -2
- package/dist/wire.d.ts +8 -1
- package/dist/wire.js +14 -3
- package/options.schema.json +8 -12
- package/package.json +3 -3
package/AI.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
# AI 작업 안내 — @dokebi/websocket-hub 0.
|
|
1
|
+
# AI 작업 안내 — @dokebi/websocket-hub 0.3.0
|
|
2
2
|
|
|
3
|
-
WebSocket 접속자 목록·방·방송·kick
|
|
3
|
+
WebSocket 접속자 목록·방·방송·kick을 관리하는 허브다(옛 `dokebi-sync`를 대체). 방송은 **많아야 한 번(at-most-once)** 이며 수신 ACK·재전송이 없다([D-0057](../../docs/decisions/D-0057-websocket-broadcast-without-ack.md)). 보통 **@dokebi/websocket이 단독으로 쓰고**, 앱 코드는 websocket의 `defineSocket`을 쓴다. 직접 쓰는 일은 운영 상태 조회(`status()`, `dokebi-hub-status`)와 봉인 프레임 재생 방어(`nonces()`) 정도다. Node >=24, core ^0.2.0, peer: @dokebi/redis·@dokebi/nats(cluster 모드). 세부는 [README](README.md)다.
|
|
4
4
|
|
|
5
5
|
## 1. 모드(D-0029)
|
|
6
6
|
|
|
@@ -8,10 +8,10 @@ WebSocket 접속자 목록·방·방송·kick·수신 ACK를 관리하는 허브
|
|
|
8
8
|
|---|---|---|
|
|
9
9
|
| 범위 | 프로세스 하나(메모리) | 여러 프로세스·서버 공유 |
|
|
10
10
|
| 필요 | 없음 | Redis(필수), NATS(선택: 리더 변경 즉시 알림, 없으면 Redis 폴링) |
|
|
11
|
-
| 장애 |
|
|
11
|
+
| 장애 | 상태는 프로세스와 함께 사라짐, 인계 없음 | 모든 워커가 허브 후보, Redis 임대로 리더 선출, 리더가 죽어도 실제 소켓은 유지되고 새 허브로 재접속 |
|
|
12
12
|
| cluster 워커 | `HUB_LOCAL_IN_CLUSTER`로 거부(`allowInCluster: true`로만 허용) | 정상 |
|
|
13
13
|
|
|
14
|
-
API와
|
|
14
|
+
API와 방송 의미(많아야 한 번)는 두 모드가 같다.
|
|
15
15
|
|
|
16
16
|
## 2. 설정 `options.dokebi-websocket-hub`
|
|
17
17
|
|
|
@@ -34,16 +34,17 @@ dokebi-websocket-hub:
|
|
|
34
34
|
| `ownerTtlMs` / `startupMs` | 15000 / 15000 | 서버 등록 만료 / 시작 대기 |
|
|
35
35
|
| `maxFrameBytes` / `maxPayloadBytes` | 1048576 / 65536 | 허브 TCP 프레임 / 메시지 |
|
|
36
36
|
| `maxConnections` / `maxOwners` / `maxTotalConnections` | 128 / 64 / 8192 | 서버별·서버 수·전체 연결 |
|
|
37
|
-
| `maxPending` / `queueBytes` | 128 / 4194304 | 대기 상한 |
|
|
38
|
-
|
|
39
|
-
|
|
37
|
+
| `maxPending` / `queueBytes` | 128 / 4194304 | 대기 상한(동시에 처리 중인 방송이 넘으면 `BUSY`) |
|
|
38
|
+
|
|
39
|
+
**없어진 옵션(0.3.0, D-0057)**: `deliveryTimeoutMs`·`retryMs`·`maxDeliveries`·`deliveryBytes`. dokebi.yaml에 남아 있어도 시작은 된다: 키마다 warn `OPTION_REMOVED`(`option`)를 한 번 남기고 값은 무시한다(스키마에는 deprecated로 남아 있다가 다음 판에서 빠진다). 지운다.
|
|
40
40
|
|
|
41
41
|
같은 namespace에서 설정(secret·한도)이 다른 서버가 살아 있으면 `CONFIG_MISMATCH`로 즉시 거부하고, 옛 설정의 서버가 모두 내려가면 새 설정으로 바뀐다.
|
|
42
42
|
|
|
43
43
|
## 3. API(`import { dependency } from '@dokebi/websocket-hub'` → `getDependency`)
|
|
44
44
|
|
|
45
45
|
- `state`(starting·ready·recovering·closing·closed), `role`(active·standby), `leader`, `whenReady(timeoutMs)` → boolean.
|
|
46
|
-
- `register(...)`·`list(query)`·`broadcast(query, bytes)`·`
|
|
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 }`.
|
|
47
48
|
- `status()`(D-0038) → `{ mode, state, role, leaseState?, leader?, leaseRemainingMs?, servers?, connections?, serverId? }`. 모르는 값은 0으로 채우지 않고 **빠진다**(Redis 무응답이면 `leaseState: 'unreachable'`).
|
|
48
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`)에 넘긴다.
|
|
49
50
|
|
|
@@ -56,11 +57,15 @@ npx dokebi-hub-status --config dokebi.yaml --json # 기계용
|
|
|
56
57
|
|
|
57
58
|
앱 프로세스 밖에서 Redis만 읽어 리더·lease 남은 시간·살아 있는 서버 수·연결 수를 보여 준다(허브를 시작하거나 선출에 끼지 않는다). Redis 무응답이면 종료 코드 1. local 모드는 프로세스 안에만 상태가 있다고 알린다.
|
|
58
59
|
|
|
59
|
-
## 5. 전달 의미
|
|
60
|
+
## 5. 전달 의미(D-0057)
|
|
60
61
|
|
|
61
|
-
-
|
|
62
|
+
- **성공 = 내보냄.** cluster: 리더가 지금 조건에 맞는 연결을 고르고, 그 연결을 가진 서버(owner)마다 메시지 프레임 하나를 쓴 뒤 보낸 서버에 receipt를 준다. local: 이 프로세스의 이벤트 큐(websocket gateway가 읽는다)에 넣으면 끝이다. 수신 확인·재전송·중복 제거·완료 기록·기한 대기가 없다. **많아야 한 번**이다.
|
|
63
|
+
- **receipt** `{ id, recipients }`: `recipients`는 보낸 시점에 조건에 맞은 연결의 식별자(tenant·member·clientId, clientId가 없으면 owner·connection의 SHA-256)다. **받았다는 뜻이 아니다.** 재접속 중이던 연결, 프레임이 써지기 전에 떠난 연결, 느려서 1013으로 닫힌 연결은 못 받는다. 나중에 들어온 연결도 받지 않는다(보관하지 않는다).
|
|
64
|
+
- **실패는 바로, 다시 보내지 않는다(중복 없음)**: `RECOVERING`·`OUTCOME_UNKNOWN`·`BUSY`. 다시 보낼지는 호출자가 정한다(`OUTCOME_UNKNOWN` 뒤에 다시 보내면 두 번 받을 수 있다).
|
|
65
|
+
- **앱 지침**: 놓치면 안 되는 일(주문 상태·결제 결과)은 방송에 맡기지 않는다. DB에 저장하고, 페이지는 다시 연결될 때 서버에서 최신 상태를 읽는다. 방송은 「바뀌었으니 다시 읽어라」 알림으로 쓴다. 반드시 처리돼야 하는 업무는 @dokebi/job.
|
|
66
|
+
- **허브 서버끼리의 판(protocol 2)**: hello에 `protocol: 2`를 싣는다. 리더는 다른 판을 `PROTOCOL_MISMATCH`로 거절하고(warn `Hub peer refused; protocol differs`), 거절된 서버는 error `Hub protocol differs from the leader; retrying`(`protocol`·`leaderProtocol`)을 남기며 재시도한다. 0.2 리더(판 없음)에 붙은 0.3 서버도 같은 오류로 끊는다. 롤링 재시작 중 판이 다른 서버는 리더에 붙지 못하므로(시작 중이면 `startupMs` 뒤 `STARTUP_TIMEOUT`) 모든 서버를 같은 판으로 올린다. 설정 지문은 0.2와 같게 두어 `CONFIG_MISMATCH`가 아니라 이 판 검사가 갈라 낸다.
|
|
67
|
+
- 방송은 Redis를 거치지 않는다(접속자 등록·변경만 Redis에 저장, D-0042). 리더 메모리에 남는 방송 기록도 없다.
|
|
62
68
|
- presence 이벤트는 owner(서버)별 전체 목록으로 온다. 재접속·리더 변경 뒤에는 스냅샷과 달라진 owner와 사라진 owner를 다시 알린다.
|
|
63
|
-
- 실제 소비자 없이 acknowledge하지 않는다. 재전송을 업무의 정확히 한 번으로 설명하지 않는다.
|
|
64
69
|
|
|
65
70
|
## 6. 주의 사항
|
|
66
71
|
|
|
@@ -68,6 +73,9 @@ npx dokebi-hub-status --config dokebi.yaml --json # 기계용
|
|
|
68
73
|
- secret은 dokebi.yaml에만, 32바이트 이상 무작위. 같은 namespace의 모든 서버가 같은 secret·옵션·Redis/NATS를 쓴다.
|
|
69
74
|
- 서버마다 다른 serverId와 다른 서버에서 접근 가능한 `advertiseHost`·TCP 포트가 필요하다(방화벽).
|
|
70
75
|
- 전체 drain 전에 허브·Redis·NATS를 닫지 않는다(core 순서가 지킨다).
|
|
71
|
-
-
|
|
76
|
+
- **운영(D-0049)**: cluster 모드의 Redis는 `maxmemory-policy noeviction`으로 둔다. 키를 지우는 정책이면 리더 키가 축출돼 `STALE_LEADER`·`RECOVERING`을 거친다(OPS-002 G). 캐시는 별도 Redis(`allkeys-lru`)에 둔다. 노드 시작 때 한 번 `CONFIG GET maxmemory*`를 읽어 `maxmemory > 0`이고 `noeviction`이 아니면 **`error` `REDIS_EVICTION_UNSAFE`**(`policy`·`maxmemory`·`connection`)를 남기고 **그래도 시작한다**(운영자가 위험을 받아들일 수 있다). 정상이면 debug `REDIS_EVICTION_CHECKED`, CONFIG가 막힌 관리형 Redis·ACL이면 debug `REDIS_EVICTION_CHECK_SKIPPED`(`reason: rejected` + 전체 `error`), 옛 @dokebi/redis면 같은 코드(`reason: unsupported`), 그 밖의 실패는 `error` `REDIS_EVICTION_CHECK_FAILED`. Redis 오류 응답(OOM 등)은 이제 `COMMAND_REJECTED`로 `STORE_UNAVAILABLE`의 cause에 서버 응답과 함께 남는다.
|
|
77
|
+
- 로그(D-0047): 예외를 조용히 버리지 않는다. 정해진 오류·응답 코드로 바꾸지 못하는 실패는 `error`로 남긴다: 고정 영어 메시지 + `code` + `error`(원본 오류 전문: 이름·메시지 전체·스택과 cause마다 `Caused by: …`, 주소·포트·errno 메시지도 그대로, URL 자격 증명만 `//***@`로 가림, 16KB 초과분만 잘라 표시). 예: 리더 연결 끊김 `Hub connection dropped`(스스로 끊은 `RECOVERING`·`CLOSED`, `bye` 중, 리더가 `leaving`을 알린 뒤의 끊김은 debug — D-0056), 복구 시작 `Hub transport or store unavailable; recovering`, 피어 송신 실패 `PEER_SEND_FAILED`(백프레셔 포함), 피어 소켓·프레임 `PEER_SOCKET_ERROR`·`PEER_FRAME_REJECTED`(hello 전 소켓 오류는 debug `Hub peer connection failed before it was established`이고 시작 재시도·복구 로그가 원인과 함께 보고), 리더가 먼저 사라져 `bye`를 못 보냈어도 Redis `leave`가 되면 debug `Hub goodbye not delivered; left through Redis`(정지 성공), 판이 다른 리더 `PROTOCOL_MISMATCH`(error, 거절한 리더는 warn), 없어진 옵션 `OPTION_REMOVED`(warn, 시작 때 키마다 한 번), NATS `NATS_PUBLISH_FAILED`·`NATS_SUBSCRIPTION_FAILED`, local 이벤트 큐 넘침 `EVENT_OVERFLOW`, `status()`의 Redis 실패 `STATUS_UNREACHABLE`. Redis 실패는 `STORE_UNAVAILABLE`의 `cause`로 남는다. 프레임·메시지마다 도는 자리는 같은 메시지·code를 간격(10초)당 한 줄로 쓰고 나머지는 `repeated` 개수로 묶는다(종료 때 남은 개수도 씀). 본문·secret·토큰은 쓰지 않는다.
|
|
78
|
+
- debug(`DOKEBI_LOG_LEVEL=debug`): 선출·리더 시작/중지·임대 상실, 리더 연결·재연결(`Hub connected to leader`, 걸린 ms·resync 수), 서버 등록·제거·만료, 연결 목록 변화, 방송 `Hub broadcast sent`(리더·local: `id`·`recipients`·`owners`·`ms`, 본문 없음), 결과를 모르는 방송 `OUTCOME_UNKNOWN`(다시 보내지 않음), 거절(`BUSY`·`STALE_*`), 복구 중 실패(`Hub still recovering`), 복구 시간은 info(`Hub recovered`).
|
|
79
|
+
- `dokebi-hub-status`는 Redis 실패 원인을 stderr에 쓴다(stdout JSON은 그대로).
|
|
72
80
|
|
|
73
|
-
근거: `examples/18-websocket-hub`(실제 TCP 피어·리더 인계), `examples/23-websocket`, `examples/25-playground`, `tests/status.test.ts`(status·nonces·명령), D-0024·D-
|
|
81
|
+
근거: `examples/18-websocket-hub`(실제 TCP 피어·리더 인계), `examples/23-websocket`, `examples/25-playground`, `tests/status.test.ts`(status·nonces·명령), D-0024·D-0029·D-0034·D-0038·D-0057(D-0025·D-0042의 ACK·재전송을 대체).
|
package/README.md
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
# @dokebi/websocket-hub
|
|
2
2
|
|
|
3
|
-
Node >=24, 0.
|
|
3
|
+
Node >=24, 0.3.0. Dokebi `@dokebi/core ^0.2.1`의 선택 플러그인. 기존 `@dokebi/sync`를 대체하는 TCP 허브다.
|
|
4
4
|
|
|
5
5
|
모드는 두 가지다([D-0029](../../docs/decisions/D-0029-hub-and-cluster-infrastructure.md)).
|
|
6
6
|
|
|
7
|
-
- **`mode: local`(기본):** 프로세스 하나의 허브다. Redis·NATS 없이 접속 목록·방·방송·kick
|
|
8
|
-
- API와
|
|
9
|
-
-
|
|
7
|
+
- **`mode: local`(기본):** 프로세스 하나의 허브다. Redis·NATS 없이 접속 목록·방·방송·kick을 메모리에서 처리한다.
|
|
8
|
+
- API와 방송 의미는 cluster 모드와 같다(많아야 한 번, 아래 「방송」). 방송은 websocket이 읽는 이벤트 큐에 넣으면 끝난다. 그 큐의 절반이 아직 읽히지 않았으면 `BUSY`로 거절한다(presence·kick 자리를 남긴다).
|
|
9
|
+
- 장애 인계는 없다.
|
|
10
10
|
- `node:cluster` 워커에서 쓰면 워커끼리 접속자를 공유하지 못하므로 `HUB_LOCAL_IN_CLUSTER`로 시작을 거부한다. 의도적으로 쓸 때만 `allowInCluster: true`로 허용한다.
|
|
11
11
|
- **`mode: cluster`:** 여러 프로세스·서버가 접속자를 공유한다.
|
|
12
12
|
- 모든 WebSocket 워커가 허브 후보가 되고, Redis 임대로 하나를 선출한다. TCP로 유저 등록·snapshot·전체/대상 메시지·kick을 전달하고, Redis에 접속 목록을 보관한다.
|
|
@@ -54,24 +54,31 @@ const connection = await hub.register({tenant:'demo',member:'alice',connection:'
|
|
|
54
54
|
// websocket 플러그인을 사용하면 이것 대신 해당 플러그인이 단독 소비한다.
|
|
55
55
|
const consumer = (async () => {
|
|
56
56
|
for await (const event of hub.events()) {
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
hub.acknowledge(event.id, event.connections);
|
|
60
|
-
}
|
|
57
|
+
// message 이벤트가 전달의 전부다: 이 서버의 event.connections에 event.data를 쓴다(ACK 없음).
|
|
58
|
+
if (event.kind === 'message') writeToSockets(event.connections, event.data);
|
|
61
59
|
}
|
|
62
60
|
})();
|
|
63
61
|
const snapshot = await hub.list({tenant:'demo'});
|
|
64
62
|
const receipt = await hub.broadcast({tenant:'demo',member:'alice'}, new TextEncoder().encode('hello'));
|
|
63
|
+
// receipt: { id, recipients } — 보낸 시점에 조건에 맞은 연결(받았다는 뜻은 아니다)
|
|
65
64
|
await connection.close();
|
|
66
65
|
await app.stop();
|
|
67
66
|
await consumer;
|
|
68
67
|
```
|
|
69
68
|
|
|
70
|
-
HubConnection: identity(ownerEpoch/connection), join(room), leave(room), updateMetadata(record), close(). HubApi: state, role, ownerEpoch, leader, register, list, broadcast, kick, events. query는 필수tenant와 선택room/member/connection의 AND다. events는 presence/message/kick의 단일 async iterator다. kick 기본코드4403,
|
|
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. query는 필수tenant와 선택room/member/connection의 AND다. events는 presence/message/kick의 단일 async iterator다. kick 기본코드4403, `{authorityEpoch,id}`를 돌려주는 TCP 요청이다.
|
|
71
70
|
|
|
72
71
|
기본 lease3000ms/poll500ms/ownerTTL15000ms. maxOwners64, 워커 접속128, 총8192, 프레임1MiB, payload64KiB, pending128, queue4MiB. 전체 snapshot도 프레임 한도를 지킨다. [옵션 스키마](options.schema.json)를 확인한다. poll×3≤lease, ownerTTL≥lease×3을 요구한다.
|
|
73
72
|
|
|
74
|
-
|
|
73
|
+
## 방송: 많아야 한 번 (0.3.0, [D-0057](../../docs/decisions/D-0057-websocket-broadcast-without-ack.md))
|
|
74
|
+
|
|
75
|
+
- **성공 = 내보냄.** cluster에서 리더는 지금 조건에 맞는 연결을 고르고, 그 연결을 가진 서버마다 메시지 프레임 하나를 쓴 뒤 보낸 서버에 receipt `{ id, recipients }`를 준다. local은 이벤트 큐에 넣으면 끝이다. 클라이언트 ACK·재전송·중복 제거·완료 기록·기한 대기가 없다. 방송은 Redis를 거치지 않고 리더 메모리에도 남지 않는다.
|
|
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`로 거절한다.
|
|
75
82
|
|
|
76
83
|
## 운영 상태와 재생 방어 (D-0038)
|
|
77
84
|
|
package/dist/delivery.d.ts
CHANGED
|
@@ -1,34 +1,17 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
import type { HubQuery, HubRecord } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* The identity of a connection in a broadcast receipt: SHA-256 (base64url) of tenant, member and
|
|
4
|
+
* clientId, or of the owner and connection when the client has no clientId.
|
|
5
|
+
*/
|
|
4
6
|
export declare function recipientKey(record: HubRecord): string;
|
|
5
|
-
interface
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
recipients: string;
|
|
11
|
-
expiresAt: number;
|
|
12
|
-
status: 'pending' | 'done' | 'expired';
|
|
7
|
+
export interface Selection {
|
|
8
|
+
/** Identities of the matching connections, once each (the receipt). */
|
|
9
|
+
readonly recipients: string[];
|
|
10
|
+
/** Matching connections by the server (owner epoch) that holds them: one frame per owner. */
|
|
11
|
+
readonly owners: Map<string, string[]>;
|
|
13
12
|
}
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
export declare class Deliveries {
|
|
20
|
-
#private;
|
|
21
|
-
readonly store: HubStore;
|
|
22
|
-
readonly token: string;
|
|
23
|
-
readonly options: HubOptions;
|
|
24
|
-
readonly connections: () => readonly HubRecord[];
|
|
25
|
-
readonly send: (owner: string, frame: Record<string, unknown>) => boolean;
|
|
26
|
-
readonly pending: Map<string, Delivery>;
|
|
27
|
-
readonly waiters: Map<string, Map<string, (ok: boolean, recipients: readonly string[]) => void>>;
|
|
28
|
-
constructor(store: HubStore, token: string, options: HubOptions, connections: () => readonly HubRecord[], send: (owner: string, frame: Record<string, unknown>) => boolean);
|
|
29
|
-
start(): Promise<void>;
|
|
30
|
-
accept(producer: string, frame: Record<string, unknown>, reply: (ok: boolean, recipients: readonly string[]) => void): Promise<void>;
|
|
31
|
-
acknowledge(input: unknown, records: readonly HubRecord[]): Promise<void>;
|
|
32
|
-
tick(): Promise<void>;
|
|
33
|
-
}
|
|
34
|
-
export {};
|
|
13
|
+
/**
|
|
14
|
+
* The recipients of a broadcast (D-0057): the connections that match `filter` now. Nothing is
|
|
15
|
+
* remembered; a connection that comes later, or leaves before its frame is written, misses it.
|
|
16
|
+
*/
|
|
17
|
+
export declare function select(records: Iterable<HubRecord>, filter: HubQuery): Selection;
|
package/dist/delivery.js
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
|
-
import {
|
|
3
|
-
import { array, epoch, matches, payload, query, sequence } from './protocol.js';
|
|
4
|
-
import { HubError } from './types.js';
|
|
2
|
+
import { matches } from './protocol.js';
|
|
5
3
|
const recipientKeys = new WeakMap();
|
|
4
|
+
/**
|
|
5
|
+
* The identity of a connection in a broadcast receipt: SHA-256 (base64url) of tenant, member and
|
|
6
|
+
* clientId, or of the owner and connection when the client has no clientId.
|
|
7
|
+
*/
|
|
6
8
|
export function recipientKey(record) {
|
|
7
9
|
const cached = recipientKeys.get(record);
|
|
8
10
|
if (cached)
|
|
@@ -15,149 +17,22 @@ export function recipientKey(record) {
|
|
|
15
17
|
recipientKeys.set(record, key);
|
|
16
18
|
return key;
|
|
17
19
|
}
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
this.connections = connections;
|
|
32
|
-
this.send = send;
|
|
33
|
-
}
|
|
34
|
-
async start() {
|
|
35
|
-
for (const raw of (await this.store.run('deliveries', this.token))) {
|
|
36
|
-
const saved = this.#parse(raw);
|
|
37
|
-
if (saved.status === 'pending')
|
|
38
|
-
this.#remember(saved);
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
#parse(raw) {
|
|
42
|
-
const value = object(JSON.parse(raw));
|
|
43
|
-
epoch(value.id);
|
|
44
|
-
epoch(value.producer);
|
|
45
|
-
sequence(value.expiresAt);
|
|
46
|
-
if (typeof value.digest !== 'string' ||
|
|
47
|
-
!/^[a-f0-9]{64}$/.test(value.digest) ||
|
|
48
|
-
!['pending', 'done', 'expired'].includes(String(value.status)) ||
|
|
49
|
-
typeof value.recipients !== 'string')
|
|
50
|
-
throw new HubError('CHECKPOINT_INVALID');
|
|
51
|
-
payload(value.data, this.options.maxPayloadBytes);
|
|
52
|
-
const recipients = array(JSON.parse(value.recipients), this.options.maxTotalConnections);
|
|
53
|
-
if (new Set(recipients).size !== recipients.length ||
|
|
54
|
-
recipients.some((key) => typeof key !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(key)))
|
|
55
|
-
throw new HubError('CHECKPOINT_INVALID');
|
|
56
|
-
return value;
|
|
57
|
-
}
|
|
58
|
-
#remember(saved) {
|
|
59
|
-
const value = {
|
|
60
|
-
saved,
|
|
61
|
-
remaining: new Set(JSON.parse(saved.recipients)),
|
|
62
|
-
lastSent: 0,
|
|
63
|
-
};
|
|
64
|
-
this.pending.set(saved.id, value);
|
|
65
|
-
return value;
|
|
66
|
-
}
|
|
67
|
-
async accept(producer, frame, reply) {
|
|
68
|
-
const id = epoch(frame.messageId), filter = query(frame.query);
|
|
69
|
-
payload(frame.data, this.options.maxPayloadBytes);
|
|
70
|
-
const expiresAt = sequence(frame.expiresAt);
|
|
71
|
-
const digest = createHash('sha256')
|
|
72
|
-
.update(JSON.stringify([filter, frame.data, expiresAt]))
|
|
73
|
-
.digest('hex');
|
|
74
|
-
const recipients = [
|
|
75
|
-
...new Set(this.connections()
|
|
76
|
-
.filter((r) => matches(r, filter))
|
|
77
|
-
.map(recipientKey)),
|
|
78
|
-
];
|
|
79
|
-
const saved = this.#parse(String(await this.store.run('put-delivery', this.token, JSON.stringify({
|
|
80
|
-
timeout: this.options.deliveryTimeoutMs,
|
|
81
|
-
count: this.options.maxDeliveries,
|
|
82
|
-
bytes: this.options.deliveryBytes,
|
|
83
|
-
}), JSON.stringify({
|
|
84
|
-
id,
|
|
85
|
-
producer,
|
|
86
|
-
digest,
|
|
87
|
-
data: frame.data,
|
|
88
|
-
recipients: JSON.stringify(recipients),
|
|
89
|
-
expiresAt,
|
|
90
|
-
status: 'pending',
|
|
91
|
-
}), id)));
|
|
92
|
-
if (saved.status !== 'pending') {
|
|
93
|
-
reply(saved.status === 'done', JSON.parse(saved.recipients));
|
|
94
|
-
return;
|
|
95
|
-
}
|
|
96
|
-
const waiters = this.waiters.get(id) ?? new Map();
|
|
97
|
-
waiters.set(producer, reply);
|
|
98
|
-
this.waiters.set(id, waiters);
|
|
99
|
-
const value = this.pending.get(id) ?? this.#remember(saved);
|
|
100
|
-
if (!value.remaining.size)
|
|
101
|
-
await this.#finish(value, true);
|
|
102
|
-
else
|
|
103
|
-
this.#transmit(value, this.connections());
|
|
104
|
-
}
|
|
105
|
-
#transmit(value, records) {
|
|
106
|
-
const now = Date.now();
|
|
107
|
-
if (now >= value.saved.expiresAt || now - value.lastSent < this.options.retryMs)
|
|
108
|
-
return;
|
|
109
|
-
value.lastSent = now;
|
|
110
|
-
const targets = new Map();
|
|
111
|
-
for (const record of records) {
|
|
112
|
-
if (!value.remaining.has(recipientKey(record)))
|
|
113
|
-
continue;
|
|
114
|
-
const connections = targets.get(record.ownerEpoch) ?? [];
|
|
20
|
+
/**
|
|
21
|
+
* The recipients of a broadcast (D-0057): the connections that match `filter` now. Nothing is
|
|
22
|
+
* remembered; a connection that comes later, or leaves before its frame is written, misses it.
|
|
23
|
+
*/
|
|
24
|
+
export function select(records, filter) {
|
|
25
|
+
const recipients = new Set();
|
|
26
|
+
const owners = new Map();
|
|
27
|
+
for (const record of records) {
|
|
28
|
+
if (!matches(record, filter))
|
|
29
|
+
continue;
|
|
30
|
+
recipients.add(recipientKey(record));
|
|
31
|
+
const connections = owners.get(record.ownerEpoch);
|
|
32
|
+
if (connections)
|
|
115
33
|
connections.push(record.connection);
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
for (const [owner, connections] of targets)
|
|
119
|
-
this.send(owner, {
|
|
120
|
-
kind: 'message',
|
|
121
|
-
id: value.saved.id,
|
|
122
|
-
data: value.saved.data,
|
|
123
|
-
expiresAt: value.saved.expiresAt,
|
|
124
|
-
connections,
|
|
125
|
-
});
|
|
126
|
-
}
|
|
127
|
-
async acknowledge(input, records) {
|
|
128
|
-
const identities = new Map(records.map((r) => [r.connection, recipientKey(r)]));
|
|
129
|
-
const completed = new Set();
|
|
130
|
-
for (const raw of array(input, 256)) {
|
|
131
|
-
const ack = object(raw), delivery = this.pending.get(epoch(ack.id));
|
|
132
|
-
if (!delivery)
|
|
133
|
-
continue;
|
|
134
|
-
for (const connection of array(ack.connections, this.options.maxConnections)) {
|
|
135
|
-
const recipient = identities.get(String(connection));
|
|
136
|
-
if (recipient)
|
|
137
|
-
delivery.remaining.delete(recipient);
|
|
138
|
-
}
|
|
139
|
-
if (!delivery.remaining.size)
|
|
140
|
-
completed.add(delivery);
|
|
141
|
-
}
|
|
142
|
-
for (const delivery of completed)
|
|
143
|
-
await this.#finish(delivery, Date.now() < delivery.saved.expiresAt);
|
|
144
|
-
}
|
|
145
|
-
async #finish(value, ok) {
|
|
146
|
-
const saved = { ...value.saved, data: '', status: ok ? 'done' : 'expired' };
|
|
147
|
-
await this.store.run('finish-delivery', this.token, '', JSON.stringify(saved), saved.id);
|
|
148
|
-
this.pending.delete(saved.id);
|
|
149
|
-
const waiters = this.waiters.get(saved.id);
|
|
150
|
-
this.waiters.delete(saved.id);
|
|
151
|
-
for (const reply of waiters?.values() ?? [])
|
|
152
|
-
reply(ok, JSON.parse(saved.recipients));
|
|
153
|
-
}
|
|
154
|
-
async tick() {
|
|
155
|
-
const records = this.connections(), now = Date.now();
|
|
156
|
-
for (const value of this.pending.values()) {
|
|
157
|
-
if (now >= value.saved.expiresAt)
|
|
158
|
-
await this.#finish(value, false);
|
|
159
|
-
else
|
|
160
|
-
this.#transmit(value, records);
|
|
161
|
-
}
|
|
34
|
+
else
|
|
35
|
+
owners.set(record.ownerEpoch, [record.connection]);
|
|
162
36
|
}
|
|
37
|
+
return { recipients: [...recipients], owners };
|
|
163
38
|
}
|
package/dist/event-queue.d.ts
CHANGED
|
@@ -5,6 +5,12 @@ export declare class EventQueue implements AsyncIterableIterator<HubEvent> {
|
|
|
5
5
|
readonly maxBytes: number;
|
|
6
6
|
constructor(capacity: number, maxBytes: number);
|
|
7
7
|
[Symbol.asyncIterator](): this;
|
|
8
|
+
/**
|
|
9
|
+
* Pushes `value` unless the queue already holds `share` of its capacity or bytes; false when
|
|
10
|
+
* refused. A waiting reader always takes it. Lets a producer back off (BUSY) and leaves the
|
|
11
|
+
* rest of the queue to events that cannot be refused (presence).
|
|
12
|
+
*/
|
|
13
|
+
offer(value: HubEvent, share: number): boolean;
|
|
8
14
|
push(value: HubEvent): void;
|
|
9
15
|
next(): Promise<IteratorResult<HubEvent>>;
|
|
10
16
|
finish(error?: unknown): void;
|
package/dist/event-queue.js
CHANGED
|
@@ -14,12 +14,30 @@ export class EventQueue {
|
|
|
14
14
|
[Symbol.asyncIterator]() {
|
|
15
15
|
return this;
|
|
16
16
|
}
|
|
17
|
+
#size(value) {
|
|
18
|
+
return value.kind === 'message'
|
|
19
|
+
? value.data.byteLength + value.connections.join('').length
|
|
20
|
+
: Buffer.byteLength(JSON.stringify(value));
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Pushes `value` unless the queue already holds `share` of its capacity or bytes; false when
|
|
24
|
+
* refused. A waiting reader always takes it. Lets a producer back off (BUSY) and leaves the
|
|
25
|
+
* rest of the queue to events that cannot be refused (presence).
|
|
26
|
+
*/
|
|
27
|
+
offer(value, share) {
|
|
28
|
+
if (this.#ended)
|
|
29
|
+
return false;
|
|
30
|
+
if (!this.#waiter &&
|
|
31
|
+
(this.#values.length >= Math.ceil(this.capacity * share) ||
|
|
32
|
+
this.#bytes + this.#size(value) > this.maxBytes * share))
|
|
33
|
+
return false;
|
|
34
|
+
this.push(value);
|
|
35
|
+
return true;
|
|
36
|
+
}
|
|
17
37
|
push(value) {
|
|
18
38
|
if (this.#ended)
|
|
19
39
|
return;
|
|
20
|
-
const bytes = value
|
|
21
|
-
? value.data.byteLength + value.connections.join('').length
|
|
22
|
-
: Buffer.byteLength(JSON.stringify(value));
|
|
40
|
+
const bytes = this.#size(value);
|
|
23
41
|
if (this.#waiter) {
|
|
24
42
|
const w = this.#waiter;
|
|
25
43
|
this.#waiter = undefined;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { Logger } from '@dokebi/core';
|
|
2
|
+
import type { RedisConnection } from '@dokebi/redis';
|
|
3
|
+
/**
|
|
4
|
+
* D-0049: a Redis that evicts keys under maxmemory deletes the hub's leader and owner keys, and
|
|
5
|
+
* the cluster falls into STALE_LEADER/RECOVERING. Read once when a cluster node starts; warns
|
|
6
|
+
* (error, `REDIS_EVICTION_UNSAFE`) and never refuses to start — operators may accept the risk.
|
|
7
|
+
* Never rejects: every outcome is a log entry.
|
|
8
|
+
*/
|
|
9
|
+
export declare function checkEviction(redis: RedisConnection, logger: Logger): Promise<void>;
|
package/dist/eviction.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { errorText } from './log.js';
|
|
2
|
+
function rejected(error) {
|
|
3
|
+
if (error === null || typeof error !== 'object')
|
|
4
|
+
return false;
|
|
5
|
+
const { name, code } = error;
|
|
6
|
+
return name === 'RedisProviderError' && code === 'COMMAND_REJECTED';
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* D-0049: a Redis that evicts keys under maxmemory deletes the hub's leader and owner keys, and
|
|
10
|
+
* the cluster falls into STALE_LEADER/RECOVERING. Read once when a cluster node starts; warns
|
|
11
|
+
* (error, `REDIS_EVICTION_UNSAFE`) and never refuses to start — operators may accept the risk.
|
|
12
|
+
* Never rejects: every outcome is a log entry.
|
|
13
|
+
*/
|
|
14
|
+
export async function checkEviction(redis, logger) {
|
|
15
|
+
const fields = { connection: redis.name };
|
|
16
|
+
if (typeof redis.memoryPolicy !== 'function') {
|
|
17
|
+
logger.log('debug', 'Redis eviction check skipped', {
|
|
18
|
+
code: 'REDIS_EVICTION_CHECK_SKIPPED',
|
|
19
|
+
...fields,
|
|
20
|
+
reason: 'unsupported',
|
|
21
|
+
});
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
try {
|
|
25
|
+
const memory = await redis.memoryPolicy();
|
|
26
|
+
if (memory.evicts)
|
|
27
|
+
logger.log('error', 'Redis evicts keys at maxmemory; the WebSocket hub needs maxmemory-policy noeviction (its leader key can be evicted)', {
|
|
28
|
+
code: 'REDIS_EVICTION_UNSAFE',
|
|
29
|
+
...fields,
|
|
30
|
+
policy: memory.policy,
|
|
31
|
+
maxmemory: memory.maxmemory,
|
|
32
|
+
});
|
|
33
|
+
else
|
|
34
|
+
logger.log('debug', 'Redis eviction policy checked', {
|
|
35
|
+
code: 'REDIS_EVICTION_CHECKED',
|
|
36
|
+
...fields,
|
|
37
|
+
policy: memory.policy,
|
|
38
|
+
maxmemory: memory.maxmemory,
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
catch (error) {
|
|
42
|
+
// CONFIG refused (managed Redis, ACL): the check is skipped, the full reply says why.
|
|
43
|
+
if (rejected(error))
|
|
44
|
+
logger.log('debug', 'Redis eviction check skipped', {
|
|
45
|
+
code: 'REDIS_EVICTION_CHECK_SKIPPED',
|
|
46
|
+
...fields,
|
|
47
|
+
reason: 'rejected',
|
|
48
|
+
error: errorText(error),
|
|
49
|
+
});
|
|
50
|
+
else
|
|
51
|
+
logger.log('error', 'Redis eviction check failed', {
|
|
52
|
+
code: 'REDIS_EVICTION_CHECK_FAILED',
|
|
53
|
+
...fields,
|
|
54
|
+
error: errorText(error),
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
}
|
package/dist/index.js
CHANGED
|
@@ -24,6 +24,13 @@ class HubRuntime {
|
|
|
24
24
|
}
|
|
25
25
|
async setup(context) {
|
|
26
26
|
const options = this.#options;
|
|
27
|
+
// D-0057 removed these with client ACKs; an old dokebi.yaml still starts.
|
|
28
|
+
for (const option of options.removedOptions)
|
|
29
|
+
context.logger.log('warn', 'Hub option removed; ignored', {
|
|
30
|
+
code: 'OPTION_REMOVED',
|
|
31
|
+
option,
|
|
32
|
+
fix: `Delete ${option} from the dokebi-websocket-hub settings (D-0057)`,
|
|
33
|
+
});
|
|
27
34
|
if (options.mode === 'local') {
|
|
28
35
|
// Workers of node:cluster would each hold their own presence list, so a broadcast would
|
|
29
36
|
// reach only the users of one worker (D-0029 §5).
|
|
@@ -33,8 +40,12 @@ class HubRuntime {
|
|
|
33
40
|
});
|
|
34
41
|
throw new HubError('HUB_LOCAL_IN_CLUSTER');
|
|
35
42
|
}
|
|
36
|
-
const hub = new LocalHub(options,
|
|
43
|
+
const hub = new LocalHub(options, context.logger);
|
|
37
44
|
context.defer(() => hub.close());
|
|
45
|
+
context.logger.log('debug', 'Local WebSocket hub started', {
|
|
46
|
+
maxConnections: options.maxConnections,
|
|
47
|
+
maxPending: options.maxPending,
|
|
48
|
+
});
|
|
38
49
|
return hub.api;
|
|
39
50
|
}
|
|
40
51
|
const node = new HubNode(context, options, context.getDependency(redis).connection(options.redisConnection), options.natsConnection === undefined
|
|
@@ -48,7 +59,7 @@ class HubRuntime {
|
|
|
48
59
|
/** Factory input: `{ app, options? }`. Options default to `app.config['dokebi-websocket-hub']`. */
|
|
49
60
|
export const createPlugin = definePlugin({
|
|
50
61
|
name: 'dokebi-websocket-hub',
|
|
51
|
-
version: '0.
|
|
62
|
+
version: '0.3.0',
|
|
52
63
|
core: '^0.2.0',
|
|
53
64
|
options: parseOptions,
|
|
54
65
|
// local: nothing. cluster: Redis, and NATS only when natsConnection is set (D-0029).
|
|
@@ -60,7 +71,7 @@ export const createPlugin = definePlugin({
|
|
|
60
71
|
/** Use with `context.getDependency(dependency)`; a registered `dokebi-websocket-hub` instance is reused. */
|
|
61
72
|
export const dependency = providerDependency({
|
|
62
73
|
name: 'dokebi-websocket-hub',
|
|
63
|
-
version: '^0.
|
|
74
|
+
version: '^0.3.0',
|
|
64
75
|
packageName: '@dokebi/websocket-hub',
|
|
65
76
|
load: () => import('./index.js'),
|
|
66
77
|
});
|
package/dist/leader.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { Socket } from 'node:net';
|
|
2
|
+
import type { Logger } from '@dokebi/core';
|
|
2
3
|
import type { HubOptions } from './options.js';
|
|
3
4
|
import type { HubStore } from './store.js';
|
|
4
5
|
import { type HubLeader } from './types.js';
|
|
@@ -7,7 +8,8 @@ export declare class Leader {
|
|
|
7
8
|
readonly identity: HubLeader;
|
|
8
9
|
readonly store: HubStore;
|
|
9
10
|
readonly options: HubOptions;
|
|
10
|
-
|
|
11
|
+
readonly logger: Logger;
|
|
12
|
+
constructor(identity: HubLeader, store: HubStore, options: HubOptions, logger: Logger);
|
|
11
13
|
get active(): boolean;
|
|
12
14
|
start(): Promise<void>;
|
|
13
15
|
accept(socket: Socket): void;
|