@dokebi/websocket-hub 0.0.0-stage → 0.1.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 ADDED
@@ -0,0 +1,73 @@
1
+ # AI 작업 안내 — @dokebi/websocket-hub 0.1.1
2
+
3
+ WebSocket 접속자 목록·방·방송·kick·수신 ACK를 관리하는 허브다(옛 `dokebi-sync`를 대체). 보통 **@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
+
5
+ ## 1. 모드(D-0029)
6
+
7
+ | | `mode: local`(기본) | `mode: cluster` |
8
+ |---|---|---|
9
+ | 범위 | 프로세스 하나(메모리) | 여러 프로세스·서버 공유 |
10
+ | 필요 | 없음 | Redis(필수), NATS(선택: 리더 변경 즉시 알림, 없으면 Redis 폴링) |
11
+ | 장애 | 미완료 메시지는 프로세스와 함께 사라짐 | 모든 워커가 허브 후보, Redis 임대로 리더 선출, 리더가 죽어도 실제 소켓은 유지되고 새 허브로 재접속 |
12
+ | cluster 워커 | `HUB_LOCAL_IN_CLUSTER`로 거부(`allowInCluster: true`로만 허용) | 정상 |
13
+
14
+ API와 ACK 의미는 두 모드가 같다.
15
+
16
+ ## 2. 설정 `options.dokebi-websocket-hub`
17
+
18
+ ```yaml
19
+ dokebi-websocket-hub:
20
+ mode: cluster
21
+ namespace: shop # 같은 namespace의 서버끼리 허브를 공유
22
+ serverId: web-a # 서버마다 다르게
23
+ host: 0.0.0.0 # 허브 TCP 수신 주소
24
+ port: 0
25
+ advertiseHost: web-a.internal # 다른 서버가 이 서버의 허브에 붙을 주소
26
+ redisConnection: primary
27
+ natsConnection: primary # 선택
28
+ secret: (32바이트 이상 무작위, dokebi.yaml에만) # 같은 namespace는 같은 secret
29
+ ```
30
+
31
+ | 키 | 기본 | 뜻 |
32
+ |---|---|---|
33
+ | `leaseMs` / `pollMs` | 3000 / 500 | 리더 임대 / NATS 없을 때 폴링 |
34
+ | `ownerTtlMs` / `startupMs` | 15000 / 15000 | 서버 등록 만료 / 시작 대기 |
35
+ | `maxFrameBytes` / `maxPayloadBytes` | 1048576 / 65536 | 허브 TCP 프레임 / 메시지 |
36
+ | `maxConnections` / `maxOwners` / `maxTotalConnections` | 128 / 64 / 8192 | 서버별·서버 수·전체 연결 |
37
+ | `maxPending` / `queueBytes` | 128 / 4194304 | 대기 상한 |
38
+ | `deliveryTimeoutMs` / `retryMs` | 60000 / 1000 | 방송 ACK 기한 / 재전송 간격 |
39
+ | `maxDeliveries` / `deliveryBytes` | 10000 / 67108864 | 미완료 방송 보관 상한 |
40
+
41
+ 같은 namespace에서 설정(secret·한도)이 다른 서버가 살아 있으면 `CONFIG_MISMATCH`로 즉시 거부하고, 옛 설정의 서버가 모두 내려가면 새 설정으로 바뀐다.
42
+
43
+ ## 3. API(`import { dependency } from '@dokebi/websocket-hub'` → `getDependency`)
44
+
45
+ - `state`(starting·ready·recovering·closing·closed), `role`(active·standby), `leader`, `whenReady(timeoutMs)` → boolean.
46
+ - `register(...)`·`list(query)`·`broadcast(query, bytes)`·`acknowledge(id, connections)`·`kick(query)`·`events()`: websocket 플러그인이 쓰는 저수준 API. **`events()`의 소비자는 하나뿐**이며 websocket이 쓰고 있으면 따로 읽지 않는다.
47
+ - `status()`(D-0038) → `{ mode, state, role, leaseState?, leader?, leaseRemainingMs?, servers?, connections?, serverId? }`. 모르는 값은 0으로 채우지 않고 **빠진다**(Redis 무응답이면 `leaseState: 'unreachable'`).
48
+ - `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
+ ## 4. 운영 명령 `dokebi-hub-status`
51
+
52
+ ```sh
53
+ npx dokebi-hub-status --config dokebi.yaml # 사람이 읽는 형태
54
+ npx dokebi-hub-status --config dokebi.yaml --json # 기계용
55
+ ```
56
+
57
+ 앱 프로세스 밖에서 Redis만 읽어 리더·lease 남은 시간·살아 있는 서버 수·연결 수를 보여 준다(허브를 시작하거나 선출에 끼지 않는다). Redis 무응답이면 종료 코드 1. local 모드는 프로세스 안에만 상태가 있다고 알린다.
58
+
59
+ ## 5. 전달 의미
60
+
61
+ - broadcast는 대상 연결 전원의 ACK와 Redis 완료 저장 뒤 끝난다. 못 받으면 `retryMs`마다 재전송, 같은 clientId로 재접속하면 못 받은 것을 받는다. 기한을 넘기면 `DELIVERY_TIMEOUT`.
62
+ - presence 이벤트는 owner(서버)별 전체 목록으로 온다. 재접속·리더 변경 뒤에는 스냅샷과 달라진 owner와 사라진 owner를 다시 알린다.
63
+ - 실제 소비자 없이 acknowledge하지 않는다. 재전송을 업무의 정확히 한 번으로 설명하지 않는다.
64
+
65
+ ## 6. 주의 사항
66
+
67
+ - 클라이언트가 보낸 tenant·member·rooms를 믿지 않는다(인증 함수가 정한다).
68
+ - secret은 dokebi.yaml에만, 32바이트 이상 무작위. 같은 namespace의 모든 서버가 같은 secret·옵션·Redis/NATS를 쓴다.
69
+ - 서버마다 다른 serverId와 다른 서버에서 접근 가능한 `advertiseHost`·TCP 포트가 필요하다(방화벽).
70
+ - 전체 drain 전에 허브·Redis·NATS를 닫지 않는다(core 순서가 지킨다).
71
+ - 로그로 리더 연결 끊김(`Hub connection dropped`), 복구 중 실패(`Hub still recovering`), 복구 시간(`Hub recovered`)을 남긴다.
72
+
73
+ 근거: `examples/18-websocket-hub`(실제 TCP 피어·리더 인계), `examples/23-websocket`, `examples/25-playground`, `tests/status.test.ts`(status·nonces·명령), D-0024·D-0025·D-0029·D-0034·D-0038.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Dokebi contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,102 @@
1
- # Temporary Holding Version
1
+ # @dokebi/websocket-hub
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Node >=24, 0.1.1(npm 공개 패키지). Dokebi `@dokebi/core ^0.2.0`의 선택 플러그인. 기존 `@dokebi/sync`를 대체하는 TCP 허브다.
4
+
5
+ 모드는 두 가지다([D-0029](../../docs/decisions/D-0029-hub-and-cluster-infrastructure.md)).
6
+
7
+ - **`mode: local`(기본):** 프로세스 하나의 허브다. Redis·NATS 없이 접속 목록·방·방송·kick·수신 ACK를 메모리에서 처리한다.
8
+ - API와 ACK 의미는 cluster 모드와 같다. 방송은 전원 ACK 뒤에 끝나고, `retryMs`마다 재전송하며, 같은 clientId로 재접속하면 못 받은 것을 받는다.
9
+ - 다만 미완료 메시지는 프로세스와 함께 사라지고 장애 인계도 없다.
10
+ - `node:cluster` 워커에서 쓰면 워커끼리 접속자를 공유하지 못하므로 `HUB_LOCAL_IN_CLUSTER`로 시작을 거부한다. 의도적으로 쓸 때만 `allowInCluster: true`로 허용한다.
11
+ - **`mode: cluster`:** 여러 프로세스·서버가 접속자를 공유한다.
12
+ - 모든 WebSocket 워커가 허브 후보가 되고, Redis 임대로 하나를 선출한다. TCP로 유저 등록·snapshot·전체/대상 메시지·kick을 전달하고, Redis에 접속 목록을 보관한다.
13
+ - `namespace`·`serverId`·`redisConnection`·`secret`이 필요하다.
14
+ - NATS(`natsConnection`)는 선택이다. 있으면 리더 변경을 즉시 알리고, 없으면 다른 서버가 Redis 폴링(`pollMs`)으로 알아챈다.
15
+ - 허브가 죽어도 정상 서버의 실제 WebSocket은 유지되고 새 허브로 재접속한다.
16
+ - **설치 검사:** 설치 모듈의 check가 모드를 보고 요구 플러그인을 알린다. cluster면 Redis를, NATS 연결이 있으면 NATS도 요구한다.
17
+ - **`whenReady(timeoutMs)`(D-0034):** 준비되면 true, 시간이 지나거나 닫히면 false다. websocket은 업그레이드를 받을 때 이것으로 짧은 재연결을 기다린다. 리더 연결이 끊긴 이유(`Hub connection dropped`), 복구가 이어지는 동안의 실패(`Hub still recovering`), 복구 시간(`Hub recovered`)을 로그로 남긴다.
18
+ - **presence 이벤트:** 연결이 들고 날 때 owner(서버)별 전체 목록으로 온다. 피어가 재접속하거나 리더가 바뀌면 스냅샷과 달라진 owner와 사라진 owner를 presence 이벤트로 다시 알린다. 그래서 소비자는 그사이 나간 연결을 놓치지 않는다.
19
+
20
+ ```yaml
21
+ schemaVersion: 1
22
+ options:
23
+ dokebi-redis:
24
+ connections:
25
+ primary:
26
+ url: redis://redis.internal:6379
27
+ dokebi-nats:
28
+ connections:
29
+ primary:
30
+ servers: [nats://nats.internal:4222]
31
+ dokebi-websocket-hub:
32
+ mode: cluster
33
+ namespace: my-app
34
+ serverId: web-a
35
+ host: 0.0.0.0
36
+ advertiseHost: web-a.internal
37
+ redisConnection: primary
38
+ natsConnection: primary
39
+ secret: replace-with-your-random-secret-at-least-32-bytes
40
+ ```
41
+
42
+ serverId/advertiseHost는 서버별 설정, namespace/secret/공유 저장소·분산 한도는 같은 영역에서 일치해야 한다. 워커마다 별도 TCP 포트를 연다(port 기본0). 해당 포트가 다른 서버에서 접근 가능해야 한다. TCP는 TLS를 내장하지 않으므로 신뢰된 사설망/암호화 터널을 사용한다.
43
+
44
+ ```ts
45
+ import { Application, loadConfig } from '@dokebi/core';
46
+ import { createPlugin } from '@dokebi/websocket-hub';
47
+ const config = await loadConfig('./dokebi.yaml');
48
+ const app = new Application({ config: config.options });
49
+ const plugin = createPlugin({ app: app.view });
50
+ app.register(plugin);
51
+ await app.start();
52
+ const hub = app.get(plugin);
53
+ const connection = await hub.register({tenant:'demo',member:'alice',connection:'socket-1'});
54
+ // websocket 플러그인을 사용하면 이것 대신 해당 플러그인이 단독 소비한다.
55
+ const consumer = (async () => {
56
+ for await (const event of hub.events()) {
57
+ if (event.kind === 'message') {
58
+ await deliverAndWaitForClientAck(event); // 앱이 제공하는 실제 수신 ACK 처리
59
+ hub.acknowledge(event.id, event.connections);
60
+ }
61
+ }
62
+ })();
63
+ const snapshot = await hub.list({tenant:'demo'});
64
+ const receipt = await hub.broadcast({tenant:'demo',member:'alice'}, new TextEncoder().encode('hello'));
65
+ await connection.close();
66
+ await app.stop();
67
+ await consumer;
68
+ ```
69
+
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, 사용자 수신 ACK가 아닌 TCP 요청이다.
71
+
72
+ 기본 lease3000ms/poll500ms/ownerTTL15000ms. maxOwners64, 워커 접속128, 총8192, 프레임1MiB, payload64KiB, pending128, queue4MiB. 전체 snapshot도 프레임 한도를 지킨다. [옵션 스키마](options.schema.json)를 확인한다. poll×3≤lease, ownerTTL≥lease×3을 요구한다.
73
+
74
+ broadcast는 Redis에 본문·대상 스냅샷을 저장하고 전체 수신 ACK와 완료 저장 뒤 `{authorityEpoch,id,recipients}`를 반환한다. 허브 교체 시 동일 ID로 재전송한다. events 소비자는 실제 수신 확인 뒤 `acknowledge(event.id, event.connections)`를 호출한다. `clientId`는 인증된 기기별 재접속 식별자이며 생략 시 소켓 소실 후 복구할 수 없다. 기본 기한60초·재전송1초, 저장10000건/64MiB(완료 기록 포함). DELIVERY_TIMEOUT/OUTBOX_FULL은 성공이 아니다. 일부 소비 후 실패할 수 있으므로 새 ID로 무조건 재실행하지 않는다. Redis 데이터 손실이나 페이지 재시작의 업무 exactly-once는 제공하지 않는다.
75
+
76
+ ## 운영 상태와 재생 방어 (D-0038)
77
+
78
+ - **`status()`:** 이 프로세스(`mode`·`state`·`role`·`serverId`)와 Redis 가 말하는 허브(`leaseState`·`leader`·`leaseRemainingMs`·`servers`·`connections`)를 함께 준다. 계산은 순수 함수 `hubStatus` 한 자리다. 모르는 값은 0 으로 채우지 않고 뺀다 — `leaseState: 'unreachable'`(Redis 가 답하지 않음)이면 `servers`·`connections` 가 없다. `none` 은 리더가 없다(장애 인계 중이거나 아무 서버도 안 떴다).
79
+ - **`dokebi-hub-status --config dokebi.yaml [--json]`:** 앱 밖에서 같은 질문에 답한다. Redis 플러그인만 띄워 리더 기록과 소유자 기록을 읽고, 선출에 끼거나 등록하지 않는다. Redis 가 답하지 않으면 exit 1 이다. local 모드는 상태가 프로세스 안에만 있다고 말한다.
80
+ - **`nonces()`:** 봉인 프레임의 1회용 nonce 저장소다(@dokebi/crypto `SealTerminator` 의 `nonces` 에 그대로 넣는다 · 모양만 맞추고 crypto 를 import 하지 않는다). cluster 모드는 Redis `SET NX PX`(`shared: true`)라 다른 서버로 재전송한 프레임도 거절된다. local 모드는 프로세스 안(`shared: false`)이고, cluster 워커에서 쓰면 처음 한 번 `HUB_NONCES_NOT_SHARED` 경고를 낸다.
81
+
82
+ ## 팩토리와 의존성(플러그인 계약 v2)
83
+
84
+ 팩토리 입력은 `{ app, options? }`이고 `app`은 필수다. 옵션을 생략하면 `app.config['dokebi-websocket-hub']`를 읽는다. `dependencies` 레코드나 Redis·NATS 인스턴스 입력은 받지 않는다([D-0028](../../docs/decisions/D-0028-plugin-contract-v2.md)).
85
+
86
+ - Redis·NATS는 `dokebi-redis`·`dokebi-nats` 공급자 descriptor로 연결한다. 같은 이름의 플러그인이 등록되어 있으면 그것을 재사용하고, 없으면 `@dokebi/redis`·`@dokebi/nats` 패키지에서 `app.config`로 만든다. 직접 지정하려면 `app.register(createRedis({ app: app.view }))`처럼 먼저 등록한다.
87
+ - `@dokebi/redis`·`@dokebi/nats`는 `peerDependencies`다. 앱이 두 패키지를 함께 설치해야 한다.
88
+ - 다른 플러그인은 `import { dependency } from '@dokebi/websocket-hub'`를 `metadata.dependencies`에 넣고 `context.getDependency(dependency)`로 API를 얻는다.
89
+ - Redis 권한 스크립트는 저장소마다 `redis.script()`로 한 번 만들고 `EVALSHA`로 실행한다. 서버에 스크립트가 없을 때(`NOSCRIPT`)만 `EVAL`을 한 번 다시 보낸다.
90
+
91
+ CLI에서는 YAML을 준비하고 `dokebi add @dokebi/redis` → `@dokebi/nats` → `@dokebi/websocket-hub` 순서로 등록한다. manifest는 schemaVersion 2이고 설치 모듈은 없다(만드는 파일이 없다). 설치는 서버 연결을 만들지 않는다. 허브는 drain 훅이 없고, 앱 drain이 끝난 뒤 cleanup에서 자원을 닫는다.
92
+
93
+ 저장소 예제18은 공개 API·로컬 TCP 기준선, 예제23은 두 Docker 서버·네 워커·허브/서버 장애·실제 DB drain을 검증한다. 전체 XFramework 부가 media/nonce 이식이나 운영 전체 인증을 뜻하지 않는다.
94
+
95
+ ## 설정 지문 (2026-10-14)
96
+
97
+ 같은 namespace의 서버들은 secret·임대·한도 설정이 같아야 한다(Redis의 설정 지문). 다른 설정의 서버가 살아 있는 동안 새 서버는 `CONFIG_MISMATCH`로 즉시 시작에 실패하고 error 로그(`code: CONFIG_MISMATCH`)를 남긴다. 옛 설정의 리더·소유자가 모두 사라지면(전체 재시작) 새 설정이 지문을 대체한다. 그래서 비밀값 교체는 전체를 내렸다 올리면 되고 Redis 키를 지울 필요가 없다([ISSUE-0005](../../docs/issues/ISSUE-0005-playground-findings.md) PG-16).
98
+
99
+ ## 종료 정리와 시작 로그 (2026-10-14)
100
+
101
+ - 노드가 정상 종료하면 자기 소유자 기록을 Redis에서 직접 지운다(`leave`: 리더 없이, 같은 세션일 때만). 전체를 동시에 꺼도 기록이 ownerTtlMs까지 남지 않아, 설정을 바꾼 즉시 재시작할 수 있다(PG-21).
102
+ - 시작 중의 재시도(아직 열리지 않은 리더 TCP에 접속 등)는 경고를 남기지 않는다. 시작 기한(`startupMs`)을 넘기면 error 로그 `STARTUP_TIMEOUT`에 마지막 오류 코드(`lastError`)를 남긴다. 시작 뒤의 장애 경고에는 `code`가 붙는다(PG-19).
@@ -0,0 +1,34 @@
1
+ import { type HubOptions } from './options.js';
2
+ import type { HubStore } from './store.js';
3
+ import { type HubRecord } from './types.js';
4
+ export declare function recipientKey(record: HubRecord): string;
5
+ interface Saved {
6
+ id: string;
7
+ producer: string;
8
+ digest: string;
9
+ data: string;
10
+ recipients: string;
11
+ expiresAt: number;
12
+ status: 'pending' | 'done' | 'expired';
13
+ }
14
+ interface Delivery {
15
+ saved: Saved;
16
+ remaining: Set<string>;
17
+ lastSent: number;
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 {};
@@ -0,0 +1,163 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { object } from './options.js';
3
+ import { array, epoch, matches, payload, query, sequence } from './protocol.js';
4
+ import { HubError } from './types.js';
5
+ const recipientKeys = new WeakMap();
6
+ export function recipientKey(record) {
7
+ const cached = recipientKeys.get(record);
8
+ if (cached)
9
+ return cached;
10
+ const key = createHash('sha256')
11
+ .update(JSON.stringify(record.clientId === undefined
12
+ ? [record.tenant, record.member, record.ownerEpoch, record.connection]
13
+ : [record.tenant, record.member, record.clientId]))
14
+ .digest('base64url');
15
+ recipientKeys.set(record, key);
16
+ return key;
17
+ }
18
+ // ACK progress may be replayed after failover; only durable completion permits success.
19
+ export class Deliveries {
20
+ store;
21
+ token;
22
+ options;
23
+ connections;
24
+ send;
25
+ pending = new Map();
26
+ waiters = new Map();
27
+ constructor(store, token, options, connections, send) {
28
+ this.store = store;
29
+ this.token = token;
30
+ this.options = options;
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) ?? [];
115
+ connections.push(record.connection);
116
+ targets.set(record.ownerEpoch, connections);
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
+ }
162
+ }
163
+ }
@@ -0,0 +1,12 @@
1
+ import { type HubEvent } from './types.js';
2
+ export declare class EventQueue implements AsyncIterableIterator<HubEvent> {
3
+ #private;
4
+ readonly capacity: number;
5
+ readonly maxBytes: number;
6
+ constructor(capacity: number, maxBytes: number);
7
+ [Symbol.asyncIterator](): this;
8
+ push(value: HubEvent): void;
9
+ next(): Promise<IteratorResult<HubEvent>>;
10
+ finish(error?: unknown): void;
11
+ return(): Promise<IteratorResult<HubEvent>>;
12
+ }
@@ -0,0 +1,66 @@
1
+ import { HubError } from './types.js';
2
+ export class EventQueue {
3
+ capacity;
4
+ maxBytes;
5
+ #values = [];
6
+ #bytes = 0;
7
+ #ended = false;
8
+ #error;
9
+ #waiter;
10
+ constructor(capacity, maxBytes) {
11
+ this.capacity = capacity;
12
+ this.maxBytes = maxBytes;
13
+ }
14
+ [Symbol.asyncIterator]() {
15
+ return this;
16
+ }
17
+ push(value) {
18
+ if (this.#ended)
19
+ return;
20
+ const bytes = value.kind === 'message'
21
+ ? value.data.byteLength + value.connections.join('').length
22
+ : Buffer.byteLength(JSON.stringify(value));
23
+ if (this.#waiter) {
24
+ const w = this.#waiter;
25
+ this.#waiter = undefined;
26
+ w.resolve({ done: false, value });
27
+ return;
28
+ }
29
+ if (this.#values.length >= this.capacity || this.#bytes + bytes > this.maxBytes)
30
+ throw new HubError('EVENT_OVERFLOW');
31
+ this.#bytes += bytes;
32
+ this.#values.push({ value, bytes });
33
+ }
34
+ next() {
35
+ if (this.#error)
36
+ return Promise.reject(this.#error);
37
+ const item = this.#values.shift();
38
+ if (item) {
39
+ this.#bytes -= item.bytes;
40
+ return Promise.resolve({ done: false, value: item.value });
41
+ }
42
+ if (this.#ended)
43
+ return Promise.resolve({ done: true, value: undefined });
44
+ if (this.#waiter)
45
+ return Promise.reject(new HubError('CONCURRENT_READ'));
46
+ return new Promise((resolve, reject) => {
47
+ this.#waiter = { resolve, reject };
48
+ });
49
+ }
50
+ finish(error) {
51
+ this.#ended = true;
52
+ this.#error = error;
53
+ this.#values = [];
54
+ this.#bytes = 0;
55
+ const w = this.#waiter;
56
+ this.#waiter = undefined;
57
+ if (error)
58
+ w?.reject(error);
59
+ else
60
+ w?.resolve({ done: true, value: undefined });
61
+ }
62
+ return() {
63
+ this.finish();
64
+ return Promise.resolve({ done: true, value: undefined });
65
+ }
66
+ }
@@ -0,0 +1,7 @@
1
+ import { type PluginDependency } from '@dokebi/core';
2
+ import { type HubApi } from './types.js';
3
+ export * from './types.js';
4
+ /** Factory input: `{ app, options? }`. Options default to `app.config['dokebi-websocket-hub']`. */
5
+ export declare const createPlugin: import("@dokebi/core").PluginFactory<HubApi>;
6
+ /** Use with `context.getDependency(dependency)`; a registered `dokebi-websocket-hub` instance is reused. */
7
+ export declare const dependency: PluginDependency<HubApi>;
package/dist/index.js ADDED
@@ -0,0 +1,66 @@
1
+ import cluster from 'node:cluster';
2
+ import { definePlugin, providerDependency, } from '@dokebi/core';
3
+ import { LocalHub } from './local.js';
4
+ import { HubNode } from './node.js';
5
+ import { parseOptions } from './options.js';
6
+ import { HubError } from './types.js';
7
+ export * from './types.js';
8
+ const redis = providerDependency({
9
+ name: 'dokebi-redis',
10
+ version: '^0.1.0 || ^0.2.0',
11
+ packageName: '@dokebi/redis',
12
+ load: () => import('@dokebi/redis'),
13
+ });
14
+ const nats = providerDependency({
15
+ name: 'dokebi-nats',
16
+ version: '^0.1.0',
17
+ packageName: '@dokebi/nats',
18
+ load: () => import('@dokebi/nats'),
19
+ });
20
+ class HubRuntime {
21
+ #options;
22
+ constructor(options) {
23
+ this.#options = options;
24
+ }
25
+ async setup(context) {
26
+ const options = this.#options;
27
+ if (options.mode === 'local') {
28
+ // Workers of node:cluster would each hold their own presence list, so a broadcast would
29
+ // reach only the users of one worker (D-0029 §5).
30
+ if (cluster.isWorker && !options.allowInCluster) {
31
+ context.logger.log('error', 'Local WebSocket hub in a cluster worker', {
32
+ code: 'HUB_LOCAL_IN_CLUSTER',
33
+ });
34
+ throw new HubError('HUB_LOCAL_IN_CLUSTER');
35
+ }
36
+ const hub = new LocalHub(options, (message, data) => context.logger.log('warn', message, data));
37
+ context.defer(() => hub.close());
38
+ return hub.api;
39
+ }
40
+ const node = new HubNode(context, options, context.getDependency(redis).connection(options.redisConnection), options.natsConnection === undefined
41
+ ? undefined
42
+ : context.getDependency(nats).connection(options.natsConnection));
43
+ context.defer(() => node.close());
44
+ await node.start();
45
+ return node.api;
46
+ }
47
+ }
48
+ /** Factory input: `{ app, options? }`. Options default to `app.config['dokebi-websocket-hub']`. */
49
+ export const createPlugin = definePlugin({
50
+ name: 'dokebi-websocket-hub',
51
+ version: '0.1.1',
52
+ core: '^0.2.0',
53
+ options: parseOptions,
54
+ // local: nothing. cluster: Redis, and NATS only when natsConnection is set (D-0029).
55
+ dependencies: ({ options }) => options.mode === 'local'
56
+ ? []
57
+ : [redis, ...(options.natsConnection === undefined ? [] : [nats])],
58
+ instance: ({ options }) => new HubRuntime(options),
59
+ });
60
+ /** Use with `context.getDependency(dependency)`; a registered `dokebi-websocket-hub` instance is reused. */
61
+ export const dependency = providerDependency({
62
+ name: 'dokebi-websocket-hub',
63
+ version: '^0.1.0',
64
+ packageName: '@dokebi/websocket-hub',
65
+ load: () => import('./index.js'),
66
+ });
@@ -0,0 +1,11 @@
1
+ interface InstallContext {
2
+ readonly options: Readonly<Record<string, unknown>>;
3
+ }
4
+ export declare function planInstall(context: InstallContext): {
5
+ requires: string[];
6
+ };
7
+ export declare function check(context: InstallContext): {
8
+ requires: string[];
9
+ diagnostics: never[];
10
+ };
11
+ export {};
@@ -0,0 +1,12 @@
1
+ /** Cluster mode needs Redis, and NATS when natsConnection is set; local mode needs nothing. */
2
+ function requirements(options) {
3
+ if (options.mode !== 'cluster')
4
+ return [];
5
+ return options.natsConnection === undefined ? ['dokebi-redis'] : ['dokebi-redis', 'dokebi-nats'];
6
+ }
7
+ export function planInstall(context) {
8
+ return { requires: requirements(context.options) };
9
+ }
10
+ export function check(context) {
11
+ return { requires: requirements(context.options), diagnostics: [] };
12
+ }
@@ -0,0 +1,16 @@
1
+ import type { Socket } from 'node:net';
2
+ import type { HubOptions } from './options.js';
3
+ import type { HubStore } from './store.js';
4
+ import { type HubLeader } from './types.js';
5
+ export declare class Leader {
6
+ #private;
7
+ readonly identity: HubLeader;
8
+ readonly store: HubStore;
9
+ readonly options: HubOptions;
10
+ constructor(identity: HubLeader, store: HubStore, options: HubOptions);
11
+ get active(): boolean;
12
+ start(): Promise<void>;
13
+ accept(socket: Socket): void;
14
+ tick(): Promise<void>;
15
+ stop(): Promise<void>;
16
+ }