@dokebi/websocket 0.0.0-stage → 0.1.2

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,94 @@
1
+ # AI 작업 안내 — @dokebi/websocket 0.1.1
2
+
3
+ dokebi-web(Fastify) 위에 WebSocket 라우트를 열고 @dokebi/websocket-hub로 서버·워커 사이 방송·접속자 목록을 잇는다. 방송은 **모든 수신자의 ACK**를 받아야 끝난다(D-0025). 뷰·DB를 강제하지 않는다. Node >=24, core ^0.2.0, peer: @dokebi/web·@dokebi/websocket-hub. 세부는 [README](README.md)다.
4
+
5
+ ## 1. 설치
6
+
7
+ ```sh
8
+ # 순서: redis → nats(cluster 허브일 때) → web → websocket-hub → websocket
9
+ npx dokebi add @dokebi/websocket-hub --set mode=local --set namespace=shop --set serverId=web-1 --set secret=... # secret은 dokebi.yaml에 직접 쓰는 것이 안전
10
+ npx dokebi add @dokebi/websocket
11
+ ```
12
+
13
+ ## 2. 설정 `options.dokebi-websocket`
14
+
15
+ | 키 | 기본 | 뜻 |
16
+ |---|---|---|
17
+ | `maxPayload` | 65536 | 메시지 크기 |
18
+ | `maxConnections` | 128 | 이 프로세스의 연결 수 |
19
+ | `maxPendingMessages` | 32 | 연결별 대기 메시지(연결마다 순차 처리) |
20
+ | `maxBufferedBytes` | 1048576 | 송신 버퍼. 넘으면 그 소켓을 1013 `Slow consumer`로 닫음 |
21
+ | `closeTimeoutMs` | 2000 | 소켓 종료 대기(업무 제한 아님) |
22
+ | `heartbeatMs` | 10000 | ping/pong |
23
+ | `idleTimeoutMs` | 0(끔) | 클라이언트가 이 시간 동안 아무것도 안 보내면 4408 `Idle`. 페이지가 `{"$dokebi":"ping-v1"}`을 주기적으로 보낸다 |
24
+ | `hubWaitMs` | 5000 | 허브가 recovering일 때 업그레이드가 기다리는 시간(0이면 바로 503) |
25
+
26
+ ## 3. 라우트 — defineSocket(권장)
27
+
28
+ ```ts
29
+ import { defineSocket } from '@dokebi/websocket';
30
+
31
+ export const chatSocket = (app: AppContext) => defineSocket({
32
+ path: '/ws',
33
+ version: BUILD_VERSION, // 클라이언트 ?dokebiVersion=가 다르면 4426 Reload required
34
+ origins: ['https://app.a.com'], // 생략하면 같은 Host만(다른 Origin은 403)
35
+ async authenticate(request) { // 검증된 세션·토큰으로. 실패면 undefined → 401
36
+ const user = await sessions.verify(request);
37
+ return user && { tenant: user.orgId, member: user.id, clientId: String(request.query.clientId) };
38
+ },
39
+ authorizeRoom: (identity, room) => rooms.canJoin(identity, room),
40
+ presence: true, // 같은 tenant의 입·퇴장을 { type: 'presence', data } 로 받음
41
+ on: {
42
+ 'chat.send': async (data, socket) => {
43
+ const { room, text } = data as { room: string; text: string };
44
+ void socket.broadcast('chat.message', { from: socket.identity.member, text }, { room })
45
+ .catch((error) => app.logger.log('warn', 'broadcast failed', { code: error.code }));
46
+ return { accepted: true }; // 메시지에 id가 있으면 { type: 'reply', id, data }로 감
47
+ },
48
+ },
49
+ });
50
+ ```
51
+
52
+ - 메시지 형식: JSON `{ type, data?, id? }`. `reply`·`error`는 예약 type. 모르는 type은 `UNKNOWN_TYPE`, 잘못된 형식은 `INVALID_MESSAGE`, handler 오류는 오류의 `code`(대문자 형식) 또는 `HANDLER_FAILED`로 `{ type: 'error', id?, code }`(message·stack은 보내지 않음).
53
+ - `socket`: `session`·`identity`·`send(type, data)`(이 연결)·`broadcast(type, data, { room?, member? })`(허브로, tenant 고정).
54
+ - 멀티 앱: @dokebi/app의 `sockets: (app) => [chatSocket(app)]`. 앱마다 같은 경로가 따로 등록되고 허브 tenant는 `<앱>:<tenant>`.
55
+ - 저수준: `context.get(ws).route({ path, origins?, constraints?, version?, authenticate, authorizeRoom?, message(data, session), presence? })`. session: `id`·`identity`·`send`·`broadcast(bytes, target?)`·`join(room)`·`leave(room)`·`close(code?, reason?)`.
56
+
57
+ ## 4. 클라이언트가 할 일
58
+
59
+ ```ts
60
+ import { DeliveryReceiver } from '@dokebi/websocket/client';
61
+ const clientId = sessionStorage.getItem('cid') ?? crypto.randomUUID(); // 탭마다 다르게(localStorage 공유 금지)
62
+ sessionStorage.setItem('cid', clientId);
63
+ const receiver = new DeliveryReceiver(); // 재접속에도 유지
64
+ const socket = new WebSocket(`/ws?clientId=${clientId}&dokebiVersion=${BUILD_VERSION}`);
65
+ socket.onmessage = async ({ data }) => {
66
+ if (!(await receiver.receive(data, consumeBroadcast, (ack) => socket.send(ack)))) handleReply(data);
67
+ };
68
+ setInterval(() => socket.send('{"$dokebi":"ping-v1"}'), 15000); // idleTimeoutMs를 쓸 때
69
+ ```
70
+
71
+ - 방송은 소비 성공 뒤 ACK해야 한다(receiver가 처리, 중복 ID는 다시 소비하지 않음). ACK가 없으면 보낸 쪽이 `deliveryTimeoutMs`까지 기다리고 `DELIVERY_TIMEOUT`.
72
+ - 닫힘 코드: 4426 새로고침, 4409 같은 clientId 중복(`Duplicate client`), 4408 idle, 1013 허브 불가·느린 소비자, 1012 서버 종료, 1011 handler 미처리 오류.
73
+
74
+ ## 5. 응답 코드와 전달 의미
75
+
76
+ - 업그레이드: 출처 거부 403(`ORIGIN_FORBIDDEN`, authenticate 호출 안 함), 인증 실패 401, 허브 미준비·종료·용량 503 `{ error: 'UNAVAILABLE', reason: CLOSING | HUB_<상태> | CAPACITY }`, 일반 HTTP 426.
77
+ - `broadcast`는 모든 수신자 ACK와 Redis 완료 저장 뒤 끝난다. 숨겨진·멈춘 탭 하나가 `deliveryTimeoutMs`까지 늦출 수 있다. 연결별 메시지는 순차 처리이므로 **handler에서 broadcast를 await하면 그 연결의 다음 메시지도 묶인다.** 결과가 필요 없으면 `void ...catch()`.
78
+ - 방송 송신은 소켓마다 기다리지 않고 송신 큐에 넣는다(같은 소켓 순서 보장). 느린 소켓만 닫는다.
79
+ - `send`는 원시 응답(현재 소켓)이고 ACK 계약이 아니다.
80
+ - presence: 한 서버에서 처음 받은 변경은 이전부터 있던 연결을 joined로 담을 수 있다. 화면은 presence를 받으면 목록을 다시 읽는다.
81
+
82
+ ## 6. 종료
83
+
84
+ stop: 새 업무 차단 → 받은 handler·송신 중 방송 대기 → 1012로 닫기. core drain 기한이 지나면 남은 소켓을 끊는다. websocket drain이 web·hub drain보다 먼저 끝나고, 모든 drain 뒤 DB·허브가 닫힌다.
85
+
86
+ ## 7. 주의 사항
87
+
88
+ - 쿠키 인증 라우트에 `origins: '*'`를 쓰지 않는다(Cross-Site WebSocket Hijacking). 프락시가 Host를 바꾸면 web `trustProxy`를 맞추거나 공개 출처를 `origins`에 적는다.
89
+ - 헤더 값을 그대로 신원으로 믿는 예제(예제 23)는 테스트 전용이다.
90
+ - `hub.events`는 이 플러그인이 단독 소비한다. 다른 코드가 읽지 않는다.
91
+ - 페이지 재시작·업무 부작용까지 정확히 한 번은 아니다.
92
+ - 실제 두 컨테이너·네 워커 교차 전달, 허브 SIGKILL, NATS 장애 검증은 했지만 두 물리 장비·WAN 검증은 아니다(OPS-002).
93
+
94
+ 근거: `examples/23-websocket`(두 Docker 서버·네 워커), `examples/25-playground`(앱별 소켓·presence·부하 시험), D-0024·D-0025·D-0033·D-0034.
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,91 @@
1
- # Temporary Holding Version
1
+ # @dokebi/websocket
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 Fastify 웹과 websocket-hub를 연결하는 선택 플러그인. API 서버에 템플릿/뷰를 강제하지 않는다.
4
+
5
+ ```ts
6
+ import { Application, dependencyOf, loadConfig } from '@dokebi/core';
7
+ import { createPlugin } from '@dokebi/websocket';
8
+ const document = await loadConfig('./dokebi.yaml');
9
+ const app = new Application({config: document.options});
10
+ const ws = createPlugin({app: app.view});
11
+ app.register({
12
+ metadata: {name:'chat',version:'1.0.0',core:'^0.2.0',dependencies:[dependencyOf(ws)]},
13
+ setup(context) {
14
+ context.get(ws).route({
15
+ path:'/ws',
16
+ // 생략하면 다른 출처의 브라우저 Upgrade를 403으로 거부한다. 필요한 출처만 정확히 적는다.
17
+ origins:['https://app.example.com'],
18
+ // 실제 앱에서는 검증된 세션/토큰으로 tenant/member를 결정한다.
19
+ authenticate(request) { return authenticateUser(request); },
20
+ authorizeRoom(identity, room) { return canJoinRoom(identity, room); },
21
+ async message(data, session) {
22
+ await session.broadcast(data, {room:'lobby'});
23
+ }
24
+ });
25
+ }
26
+ });
27
+ await app.start();
28
+ // 종료 신호에서 await app.stop().
29
+ ```
30
+
31
+ authenticateUser/canJoinRoom은 사용자 인증·권한 함수이며 이 패키지가 제공하지 않는다. authenticate는 `{tenant,member,clientId?,rooms?,metadata?}` 또는 undefined를 반환한다. 실제 실행 가능한 예제는 저장소 examples/23-websocket이며 예제의 헤더 인증은 테스트 전용이다.
32
+
33
+ websocket-hub의 필수 YAML을 준비한다. CLI 등록은 redis→nats→web→websocket-hub→websocket 순서다. manifest는 schemaVersion 2이고 설치 모듈은 없다. 서버 시작은 setup/start에서 이루어진다.
34
+
35
+ ## 팩토리와 의존성(플러그인 계약 v2)
36
+
37
+ 팩토리 입력은 `{ app, options? }`이고 `app`은 필수다. 옵션을 생략하면 `app.config['dokebi-websocket']`를 읽는다. `hub`·`web`·`dependencies` 입력은 없앴다([D-0028](../../docs/decisions/D-0028-plugin-contract-v2.md)). `dokebi-web`·`dokebi-websocket-hub`는 공급자 descriptor로 연결한다. 같은 이름이 등록되어 있으면 재사용하고, 없으면 `@dokebi/web`·`@dokebi/websocket-hub`에서 `app.config`로 만든다. 특정 인스턴스를 쓰려면 `app.register(createWeb({ app: app.view }))`처럼 먼저 등록한다. 두 패키지는 `peerDependencies`이므로 앱이 함께 설치한다.
38
+
39
+ ## 교차 출처 거부(CSWSH)
40
+
41
+ 브라우저는 다른 사이트의 페이지에서도 쿠키를 붙여 WebSocket Upgrade를 보낸다. 쿠키로 인증하는 라우트가 출처를 확인하지 않으면 악성 페이지가 사용자 권한으로 소켓을 연다(Cross-Site WebSocket Hijacking).
42
+
43
+ - 기본값: `Origin` 헤더가 있고 그 host(host:port)가 요청 `Host`와 다르면 `preValidation`에서 403(`ORIGIN_FORBIDDEN`)으로 거부한다. `authenticate`는 호출하지 않는다. `Origin`이 없는 요청(브라우저가 아닌 클라이언트)은 통과한다.
44
+ - `origins: ['https://app.example.com']`: 같은 host에 더해 목록의 출처를 허용한다. 항목은 `scheme://host[:port]` 형태의 정확한 http(s) 출처여야 하며, 아니면 `route()`가 오류를 던진다.
45
+ - `origins: '*'`: 검사를 끈다. 쿠키 인증과 함께 쓰면 위의 위험이 그대로 남는다. 토큰을 메시지나 헤더로 직접 검증하는 경우에만 명시적으로 쓴다.
46
+ - 역방향 프록시가 `Host`를 바꾸면 같은 출처도 거부된다. 프록시가 원래 `Host`를 전달하게 하거나 공개 출처를 `origins`에 적는다.
47
+
48
+ API는 setup 시 route({path,origins?,authenticate,authorizeRoom?,message}) 등록과 connections 조회다. session은 id/identity, send, broadcast, join, leave, close를 제공한다. broadcast는 인증된 tenant로 고정된다. join은 authorizeRoom이 true를 반환해야 한다. 출처 거부403, 인증실패401, hub미준비/종료503, 일반HTTP426이다. 미처리 handler 오류는1011로 종료한다.
49
+
50
+ 메시지는 연결별 순차 실행하며 초기 등록 중 수신도 큐에 보관한다. maxPayload65536, maxConnections128, maxPendingMessages32, maxBufferedBytes1048576, closeTimeoutMs2000, heartbeatMs10000이 기본값이다. [스키마](options.schema.json)에 한도가 있다. ping/pong, 송신 버퍼 상한, 압축 비활성화를 사용한다. hub 자체의 payload/접속 한도도 함께 적용된다.
51
+
52
+ 방송 전달은 대상 소켓마다 송신 완료를 기다리지 않는다. envelope를 한 번 인코딩해 열린 소켓의 `ws` 송신 큐에 넣고(같은 소켓 안의 순서는 그 큐가 보장한다), 송신 오류가 나면 그 소켓만 끊는다. `bufferedAmount`에 프레임을 더한 값이 maxBufferedBytes를 넘으면 그 소켓을 1013 `Slow consumer`로 닫는다. 그래서 느린 클라이언트 하나가 다른 소켓의 방송을 늦추지 않는다. 대기 중인 허브 이벤트를 한 번에 처리하다가 정상 소켓까지 한도를 넘기지 않도록, 송신 중인 프레임이 있으면 이벤트 사이에 이벤트 루프를 한 번 양보한다.
53
+
54
+ stop은 새 업무를 차단하고 이미 받은 핸들러와 송신 중인 방송을 기다린 뒤1012로 종료한다. 먼저 끊긴 클라이언트의 잔여 DB 작업도 기다린다. closeTimeoutMs는 소켓 종료 대기 한도이며 업무 실행 제한이 아니다. core의 drain 기한(`shutdown.drainTimeoutMs`, 기본 20000ms)이 지나 `context.drainSignal`이 abort되면 기다림을 멈추고 남은 소켓을 끊는다. 기한 초과는 core가 `DRAIN_TIMEOUT`으로 보고한다. websocket은 web과 hub에 의존하므로 core가 websocket drain을 먼저 끝낸 뒤 web·hub drain을 시작하고, 모든 drain 뒤에 DB/허브가 닫힌다.
55
+
56
+ hub.events는 이 플러그인이 단독 소비한다. broadcast receipt는 전체 수신 ACK와 Redis 완료 저장 뒤 반환한다. 허브 인계 시 같은 ID로 재전송하며 기한 내 수신 실패는 DELIVERY_TIMEOUT이다. send는 현재 소켓의 원시 응답으로 별도 송신 완료 계약이다. 실제 두 컨테이너·네 워커의 교차 서버 전달/허브 SIGKILL/NATS 장애/DB drain 검증은 운영 전체 인증이나 실제 두 물리 장비 검증을 뜻하지 않는다.
57
+
58
+
59
+ **접속자 입·퇴장(presence):** 허브는 연결이 들고 날 때마다 모든 서버에 그 서버 소유자(owner)의 연결 목록을 알린다. 서버가 죽어 등록이 만료된 경우도 포함한다. 이 패키지는 그 알림을 tenant별 `{ tenant, joined, left }`로 바꾼다. 그리고 같은 tenant에 열린 자기 서버의 연결마다 라우트의 `presence(change, session)` 훅을 그 연결의 메시지 처리 순서대로 부른다.
60
+ - `defineSocket({ presence: true })`면 각 연결에 `{ type: 'presence', data: { tenant, joined, left } }`를 보낸다. 함수를 주면 그 함수가 `(change, socket)`으로 처리한다.
61
+ - 한 서버에서 처음 받은 알림은 그전부터 있던 연결을 `joined`로 담을 수 있다. 화면은 이 메시지를 받으면 목록을 다시 읽는 방식이 안전하다.
62
+
63
+ **페이지가 살아 있는지(`idleTimeoutMs`):** WebSocket ping은 브라우저의 네트워크 계층이 대신 답한다. 그래서 bfcache에 얼린 페이지나 스크립트가 멈춘 페이지도 연결이 살아 있는 것처럼 보인다. `idleTimeoutMs`(기본 0, 끔)를 주면 그 시간 동안 클라이언트가 아무것도 보내지 않은 연결을 `4408 Idle`로 닫는다. 클라이언트는 페이지 스크립트에서 주기적으로 `{"$dokebi":"ping-v1"}`을 보내 살아 있음을 알린다. 이 제어 프레임은 라우트로 가지 않는다.
64
+
65
+ **연결 생애 로그:** debug 레벨에서 접속(`WebSocket connected`: 연결 ID·tenant·member·clientId·원격 주소·User-Agent·`Sec-Purpose`)과 종료(`WebSocket closed`: 닫힘 코드·이유·유지 시간)를 남긴다.
66
+
67
+ **클라이언트 버전(`version`, D-0033):** 라우트(또는 `defineSocket`)에 `version`을 주면, 업그레이드 질의 `dokebiVersion`이 다르거나 없는 연결을 등록하지 않고 `4426 Reload required`로 닫는다. 클라이언트는 이 코드를 받으면 페이지를 다시 읽는다. 오래 열린 탭이나 bfcache에서 되살아난 페이지가 옛 코드로 서버 상태에 끼어들지 못하게 한다.
68
+
69
+ **허브 재연결 대기(`hubWaitMs`, D-0034):** 허브가 리더 교체·순차 재시작으로 잠시 `recovering`이면 업그레이드는 최대 `hubWaitMs`(기본 5000, 0이면 바로 거절)까지 기다린다. 그래도 준비되지 않으면 503이다. 거절 본문은 `{ error: 'UNAVAILABLE', reason }`이고 reason은 `CLOSING`·`HUB_<상태>`·`CAPACITY`다. 같은 이유를 debug 로그 `WebSocket upgrade refused`에도 남긴다.
70
+
71
+ **방송을 기다리는 시점:** `session.broadcast`·`socket.broadcast`는 **모든 수신자가 ACK한 뒤**에 끝난다(D-0025). 그래서 숨겨지거나 멈춘 브라우저 탭 하나가 있으면 `deliveryTimeoutMs`까지 끝나지 않는다. 연결마다 메시지를 차례로 처리하므로, 요청 핸들러에서 이를 기다리면 그 연결의 다음 메시지도 함께 묶인다. 전달 결과를 답할 필요가 없으면 기다리지 말고(`void broadcast(...).catch(...)`) 바로 답한다. 기다리지 않아도 허브는 전달·재전송을 계속한다.
72
+
73
+ `clientId`는 탭(페이지)마다 달라야 한다([D-0025](../../docs/decisions/D-0025-websocket-delivery-ack.md)). 같은 `(tenant, member, clientId)`가 이미 연결돼 있으면 허브가 등록을 거절한다. 이때 소켓은 **4409 `Duplicate client`**로 닫힌다. 허브 장애(1013 `Hub unavailable`)와 구별된다. 같은 clientId로 바로 다시 붙으면 또 거절되므로, 브라우저에서 clientId를 localStorage처럼 탭끼리 공유하는 곳에 두지 않는다. 페이지 메모리나 탭 단위 저장소에 둔다.
74
+
75
+ 클라이언트는 방송 envelope를 처리하고 수신 ACK를 보내야 한다. 인증 함수가 확인한 기기별 clientId와 receiver 인스턴스를 재접속 후에도 유지한다. 일반 원시 응답은 별도로 처리한다.
76
+
77
+ ```ts
78
+ import { DeliveryReceiver } from '@dokebi/websocket/client';
79
+ const receiver = new DeliveryReceiver(); // 연결 함수 바깥에서 clientId별 유지
80
+ socket.onmessage = async ({data}) => {
81
+ if (!await receiver.receive(data, consumeBytes, ack => socket.send(ack))) consumeReply(data);
82
+ };
83
+ ```
84
+
85
+ consumeBytes/consumeReply는 앱 함수다. receiver는 소비 성공 후 ACK하고 중복 ID는 다시 소비하지 않는다. 페이지 재시작이나 일부 업무 부작용 뒤 callback 실패까지 exactly-once로 만들지는 않는다. 실제 예제23은 이 helper를 사용한다. 기한60초, receiver 기본10000건이며 넘치면 거짓 ACK 없이 실패한다.
86
+
87
+ ## 라우트 제약과 메시지 라우터 (D-0030)
88
+
89
+ - `route({ constraints })`: 업그레이드 라우트에 Fastify 라우트 제약을 붙인다. @dokebi/app이 `{ dokebiApp: '<앱>' }`으로 앱마다 같은 경로(`/ws`)를 따로 등록한다.
90
+ - `defineSocket({ path, authenticate, on: { '<type>': handler } })`는 메시지 라우터가 붙은 라우트를 만든다. 메시지는 JSON `{ type, data?, id? }`다. 핸들러 `(data, socket)`의 반환값은 `id`가 있으면 `{ type: 'reply', id, data }`로 간다. `socket.send(type, data)`는 이 연결에, `socket.broadcast(type, data, target?)`는 허브로 보낸다. 모르는 type은 `UNKNOWN_TYPE`, 잘못된 메시지는 `INVALID_MESSAGE`, 핸들러 오류는 오류의 `code`(대문자 형식일 때) 또는 `HANDLER_FAILED`로 `{ type: 'error', id?, code }` 응답한다. 오류 메시지·stack은 보내지 않는다. `reply`·`error`는 예약 type이다.
91
+ - 2026-10-14 수정([ISSUE-0005](../../docs/issues/ISSUE-0005-playground-findings.md) PG-14): WebSocket 라우트가 없는 경로로 온 업그레이드 요청이 404 뒤에도 원시 소켓을 열어 둬 앱 종료가 정리 시한까지 멈췄다. @fastify/websocket을 캡슐화 없이 등록해 그 훅이 모든 업그레이드에 적용되게 했다.
@@ -0,0 +1,7 @@
1
+ /** Keep one receiver per authenticated clientId across socket reconnects. No Node dependencies. */
2
+ export declare class DeliveryReceiver {
3
+ #private;
4
+ readonly capacity: number;
5
+ constructor(capacity?: number);
6
+ receive(raw: string | Uint8Array, deliver: (data: Uint8Array, id: string) => void | Promise<void>, acknowledge: (frame: string) => void): Promise<boolean>;
7
+ }
package/dist/client.js ADDED
@@ -0,0 +1,60 @@
1
+ const decoder = new TextDecoder();
2
+ /** Keep one receiver per authenticated clientId across socket reconnects. No Node dependencies. */
3
+ export class DeliveryReceiver {
4
+ capacity;
5
+ #seen = new Map();
6
+ #sweepAt = 0;
7
+ constructor(capacity = 10000) {
8
+ this.capacity = capacity;
9
+ if (!Number.isSafeInteger(capacity) || capacity < 1)
10
+ throw new Error('Invalid capacity');
11
+ }
12
+ async receive(raw, deliver, acknowledge) {
13
+ const text = typeof raw === 'string' ? raw : decoder.decode(raw);
14
+ let frame;
15
+ try {
16
+ frame = JSON.parse(text);
17
+ }
18
+ catch {
19
+ return false;
20
+ }
21
+ if (frame?.$dokebi !== 'delivery-v1')
22
+ return false;
23
+ if (typeof frame.id !== 'string' ||
24
+ !/^[a-f0-9-]{36}$/.test(frame.id) ||
25
+ typeof frame.expiresAt !== 'number' ||
26
+ !Number.isSafeInteger(frame.expiresAt) ||
27
+ typeof frame.data !== 'string')
28
+ throw new Error('Invalid delivery');
29
+ const now = Date.now();
30
+ if (now > frame.expiresAt)
31
+ return true;
32
+ if (now >= this.#sweepAt) {
33
+ for (const [id, entry] of this.#seen)
34
+ if (entry.expiresAt + 5000 < now)
35
+ this.#seen.delete(id);
36
+ this.#sweepAt = now + 1000;
37
+ }
38
+ const id = frame.id;
39
+ let entry = this.#seen.get(id);
40
+ if (!entry) {
41
+ if (this.#seen.size >= this.capacity)
42
+ throw new Error('Delivery receiver capacity exceeded');
43
+ const binary = atob(frame.data), bytes = new Uint8Array(binary.length);
44
+ for (let index = 0; index < binary.length; index++)
45
+ bytes[index] = binary.charCodeAt(index);
46
+ entry = {
47
+ expiresAt: frame.expiresAt,
48
+ work: Promise.resolve().then(() => deliver(bytes, id)),
49
+ };
50
+ this.#seen.set(id, entry);
51
+ void entry.work?.catch(() => {
52
+ this.#seen.delete(id);
53
+ });
54
+ }
55
+ await entry.work;
56
+ entry.work = undefined;
57
+ acknowledge(JSON.stringify({ $dokebi: 'ack-v1', id }));
58
+ return true;
59
+ }
60
+ }
@@ -0,0 +1,17 @@
1
+ import type { PluginContext } from '@dokebi/core';
2
+ import type { WebApi } from '@dokebi/web';
3
+ import type { HubApi } from '@dokebi/websocket-hub';
4
+ import type { Options } from './options.js';
5
+ import type { WebsocketApi } from './types.js';
6
+ export declare class Gateway {
7
+ #private;
8
+ readonly context: PluginContext;
9
+ readonly web: WebApi;
10
+ readonly hub: HubApi;
11
+ readonly settings: Options;
12
+ readonly api: WebsocketApi;
13
+ constructor(context: PluginContext, web: WebApi, hub: HubApi, settings: Options);
14
+ start(): void;
15
+ /** Stops waiting as soon as `signal` (the core drain deadline) aborts; sockets are then cut. */
16
+ drain(signal: AbortSignal): Promise<void>;
17
+ }
@@ -0,0 +1,502 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { setTimeout as delay, setImmediate as immediate } from 'node:timers/promises';
3
+ import fastifyWebsocket from '@fastify/websocket';
4
+ import { WebSocket } from 'ws';
5
+ const TEXT = Object.freeze({ binary: false });
6
+ /** Allow-list entries must be exact http(s) origins such as `https://app.example.com`. */
7
+ function parseOrigins(value) {
8
+ if (value === undefined)
9
+ return undefined;
10
+ if (value === '*')
11
+ return '*';
12
+ if (!Array.isArray(value))
13
+ throw new Error('Invalid websocket route');
14
+ const result = new Set();
15
+ for (const item of value) {
16
+ let url;
17
+ try {
18
+ url = typeof item === 'string' ? new URL(item) : undefined;
19
+ }
20
+ catch { }
21
+ if (!url || (url.protocol !== 'http:' && url.protocol !== 'https:') || url.origin !== item)
22
+ throw new Error('Invalid websocket route');
23
+ result.add(url.origin);
24
+ }
25
+ return result;
26
+ }
27
+ /**
28
+ * Browsers always send Origin on WebSocket upgrades, so a foreign page cannot reuse the user's
29
+ * cookies (CSWSH) unless its origin is allowed. Clients without Origin are not browsers.
30
+ */
31
+ function originAllowed(origin, host, allowed) {
32
+ if (origin === undefined || allowed === '*')
33
+ return true;
34
+ if (typeof origin !== 'string')
35
+ return false;
36
+ let url;
37
+ try {
38
+ url = new URL(origin);
39
+ }
40
+ catch {
41
+ return false;
42
+ }
43
+ if (url.protocol !== 'http:' && url.protocol !== 'https:')
44
+ return false;
45
+ if (allowed?.has(url.origin))
46
+ return true;
47
+ if (typeof host !== 'string' || !host)
48
+ return false;
49
+ try {
50
+ return new URL(`${url.protocol}//${host}`).host === url.host;
51
+ }
52
+ catch {
53
+ return false;
54
+ }
55
+ }
56
+ function aborted(signal) {
57
+ return new Promise((resolve) => {
58
+ if (signal.aborted)
59
+ resolve();
60
+ else
61
+ signal.addEventListener('abort', () => resolve(), { once: true });
62
+ });
63
+ }
64
+ export class Gateway {
65
+ context;
66
+ web;
67
+ hub;
68
+ settings;
69
+ api;
70
+ #routes = [];
71
+ #clients = new Map();
72
+ /** Last connection list the hub reported per server (owner), to tell joins from leaves. */
73
+ #owners = new Map();
74
+ #tasks = new Set();
75
+ /** Broadcast writes in flight; tracked only so drain can wait for them. */
76
+ #sends = 0;
77
+ #sendsIdle;
78
+ #identities = new WeakMap();
79
+ #frozen = false;
80
+ #closing = false;
81
+ #loop;
82
+ #timer;
83
+ constructor(context, web, hub, settings) {
84
+ this.context = context;
85
+ this.web = web;
86
+ this.hub = hub;
87
+ this.settings = settings;
88
+ const self = this;
89
+ this.api = Object.freeze({
90
+ get connections() {
91
+ return self.#clients.size;
92
+ },
93
+ route: (route) => {
94
+ if (this.#frozen || context.app.state !== 'starting')
95
+ throw new Error('Register websocket routes during setup');
96
+ if (!route.path.startsWith('/') ||
97
+ typeof route.authenticate !== 'function' ||
98
+ typeof route.message !== 'function')
99
+ throw new Error('Invalid websocket route');
100
+ const origins = parseOrigins(route.origins);
101
+ this.#routes.push({ route: { ...route }, origins });
102
+ },
103
+ });
104
+ // Registered without encapsulation (skip-override) so @fastify/websocket's hooks run for
105
+ // every upgrade, including ones that match no websocket route: its onResponse hook then
106
+ // destroys the raw socket of a 404 upgrade instead of leaving it open (ISSUE-0005 PG-14).
107
+ const gateway = async (scope) => {
108
+ this.#frozen = true;
109
+ await scope.register(fastifyWebsocket, {
110
+ options: { maxPayload: settings.maxPayload, perMessageDeflate: false },
111
+ errorHandler: (_error, socket) => {
112
+ socket.close(1011, 'Socket failure');
113
+ },
114
+ });
115
+ for (const { route, origins } of this.#routes) {
116
+ scope.route({
117
+ method: 'GET',
118
+ url: route.path,
119
+ ...(route.constraints ? { constraints: { ...route.constraints } } : {}),
120
+ preValidation: async (request, reply) => {
121
+ if (!originAllowed(request.headers.origin, this.web.requestHost(request), origins))
122
+ return reply.code(403).send({ error: 'ORIGIN_FORBIDDEN' });
123
+ // A hub that is reconnecting (leader change, rolling restart) is usually back within
124
+ // a poll interval: wait for it instead of turning the client away (bounded).
125
+ if (!this.#closing && this.hub.state === 'recovering' && this.settings.hubWaitMs)
126
+ await this.hub.whenReady(this.settings.hubWaitMs);
127
+ // Why an upgrade is refused: shutting down, hub not ready (state), or full.
128
+ const reason = this.#closing
129
+ ? 'CLOSING'
130
+ : this.hub.state !== 'ready'
131
+ ? `HUB_${this.hub.state.toUpperCase()}`
132
+ : this.#clients.size >= this.settings.maxConnections
133
+ ? 'CAPACITY'
134
+ : undefined;
135
+ if (reason) {
136
+ this.context.logger.log('debug', 'WebSocket upgrade refused', { reason });
137
+ return reply.code(503).send({ error: 'UNAVAILABLE', reason });
138
+ }
139
+ const identity = await route.authenticate(request);
140
+ if (!identity)
141
+ return reply.code(401).send({ error: 'UNAUTHORIZED' });
142
+ this.#identities.set(request, identity);
143
+ },
144
+ handler: (_request, reply) => reply.code(426).send({ error: 'WEBSOCKET_REQUIRED' }),
145
+ wsHandler: (socket, request) => this.#attach(socket, request, route),
146
+ });
147
+ }
148
+ };
149
+ gateway[Symbol.for('skip-override')] = true;
150
+ web.register(gateway, {});
151
+ }
152
+ #watch(task) {
153
+ this.#tasks.add(task);
154
+ void task.then(() => this.#tasks.delete(task), () => this.#tasks.delete(task));
155
+ return task;
156
+ }
157
+ #send(socket, data) {
158
+ const bytes = typeof data === 'string' ? Buffer.byteLength(data) : data.byteLength;
159
+ if (socket.readyState !== WebSocket.OPEN)
160
+ return Promise.reject(new Error('Socket closed'));
161
+ if (socket.bufferedAmount + bytes > this.settings.maxBufferedBytes) {
162
+ socket.close(1013, 'Slow consumer');
163
+ return Promise.reject(new Error('Socket backpressure'));
164
+ }
165
+ return this.#watch(new Promise((resolve, reject) => socket.send(data, (error) => (error ? reject(error) : resolve()))));
166
+ }
167
+ /** Queues one broadcast frame without waiting; a slow socket never delays the others. */
168
+ #deliver(socket, frame) {
169
+ if (socket.readyState !== WebSocket.OPEN)
170
+ return;
171
+ if (socket.bufferedAmount + frame.byteLength > this.settings.maxBufferedBytes) {
172
+ socket.close(1013, 'Slow consumer');
173
+ return;
174
+ }
175
+ this.#sends++;
176
+ socket.send(frame, TEXT, (error) => {
177
+ if (error)
178
+ socket.terminate();
179
+ if (--this.#sends === 0 && this.#sendsIdle) {
180
+ this.#sendsIdle.resolve();
181
+ this.#sendsIdle = undefined;
182
+ }
183
+ });
184
+ }
185
+ /** Waits for handlers and registrations (and writes) unless the drain deadline passes first. */
186
+ async #idle(signal, stop, writes) {
187
+ while (!signal.aborted && (this.#tasks.size || (writes && this.#sends))) {
188
+ const waits = [...this.#tasks];
189
+ if (writes && this.#sends) {
190
+ if (!this.#sendsIdle) {
191
+ let resolve;
192
+ const promise = new Promise((done) => {
193
+ resolve = done;
194
+ });
195
+ this.#sendsIdle = { promise, resolve };
196
+ }
197
+ waits.push(this.#sendsIdle.promise);
198
+ }
199
+ await Promise.race([Promise.allSettled(waits), stop]);
200
+ }
201
+ }
202
+ #attach(socket, request, route) {
203
+ if (route.version !== undefined) {
204
+ const sent = request.query?.dokebiVersion;
205
+ if (sent !== route.version) {
206
+ this.context.logger.log('debug', 'WebSocket version refused', {
207
+ expected: route.version,
208
+ received: typeof sent === 'string' ? sent.slice(0, 64) : null,
209
+ });
210
+ socket.close(4426, 'Reload required');
211
+ return;
212
+ }
213
+ }
214
+ const identity = this.#identities.get(request);
215
+ if (!identity || this.#closing || this.#clients.size >= this.settings.maxConnections) {
216
+ socket.close(1013, 'Unavailable');
217
+ return;
218
+ }
219
+ const id = randomUUID();
220
+ const value = {
221
+ socket,
222
+ route,
223
+ session: undefined,
224
+ tail: Promise.resolve(),
225
+ pending: 0,
226
+ registration: undefined,
227
+ alive: true,
228
+ failed: false,
229
+ seen: performance.now(),
230
+ };
231
+ this.#clients.set(id, value);
232
+ const opened = performance.now();
233
+ // Connection lifecycle at debug level: who connected from where, and how it ended.
234
+ this.context.logger.log('debug', 'WebSocket connected', {
235
+ connection: id,
236
+ tenant: identity.tenant,
237
+ member: identity.member,
238
+ clientId: identity.clientId ?? null,
239
+ path: route.path,
240
+ remote: `${request.socket.remoteAddress ?? '?'}:${request.socket.remotePort ?? '?'}`,
241
+ userAgent: String(request.headers['user-agent'] ?? '').slice(0, 160),
242
+ // Browser context of the upgrade: a prerendered or prefetched page says so here.
243
+ secPurpose: String(request.headers['sec-purpose'] ?? '') || null,
244
+ secFetchSite: String(request.headers['sec-fetch-site'] ?? '') || null,
245
+ open: this.#clients.size,
246
+ });
247
+ const session = Object.freeze({
248
+ id,
249
+ identity,
250
+ send: (data) => this.#send(socket, data),
251
+ broadcast: async (data, target) => {
252
+ return this.hub.broadcast({ ...target, tenant: identity.tenant }, data);
253
+ },
254
+ join: async (room) => {
255
+ if (!route.authorizeRoom || !(await route.authorizeRoom(identity, room)))
256
+ throw new Error('Room access denied');
257
+ await value.registration?.join(room);
258
+ },
259
+ leave: async (room) => {
260
+ await value.registration?.leave(room);
261
+ },
262
+ close: (code = 1000, reason = '') => {
263
+ socket.close(code, reason);
264
+ },
265
+ });
266
+ value.session = session;
267
+ const registration = { ...identity, connection: id };
268
+ value.tail = this.#watch(this.hub.register(registration).then((handle) => {
269
+ value.registration = handle;
270
+ }));
271
+ const registered = value.tail;
272
+ void value.tail.catch((error) => {
273
+ this.context.logger.log('warn', 'WebSocket registration failed', {
274
+ connection: id,
275
+ code: error instanceof Error ? error.message : 'UNKNOWN',
276
+ });
277
+ value.failed = true;
278
+ // The same (tenant, member, clientId) is already connected (D-0025): a client error, not
279
+ // a hub outage. A client that retries with the same clientId is refused again.
280
+ const duplicate = error?.code === 'DUPLICATE_CLIENT' ||
281
+ (error instanceof Error && error.message.endsWith('DUPLICATE_CLIENT'));
282
+ if (duplicate)
283
+ socket.close(4409, 'Duplicate client');
284
+ else
285
+ socket.close(1013, 'Hub unavailable');
286
+ });
287
+ socket.on('pong', () => {
288
+ value.alive = true;
289
+ });
290
+ socket.on('error', () => { });
291
+ // Attach synchronously, before awaiting Redis/TCP registration, so early frames are queued.
292
+ socket.on('message', (raw) => {
293
+ value.seen = performance.now();
294
+ // ACKs bypass the business queue (including drain), which may itself await a broadcast.
295
+ const bytes = Array.isArray(raw)
296
+ ? Buffer.concat(raw)
297
+ : Buffer.from(raw instanceof ArrayBuffer ? new Uint8Array(raw) : raw);
298
+ if (bytes[0] === 123) {
299
+ let control;
300
+ try {
301
+ control = JSON.parse(bytes.toString());
302
+ }
303
+ catch {
304
+ /* The route owns non-control payload parsing. */
305
+ }
306
+ // The page is alive (idleTimeoutMs): nothing else to do.
307
+ if (control?.$dokebi === 'ping-v1')
308
+ return;
309
+ if (control?.$dokebi === 'ack-v1') {
310
+ try {
311
+ if (typeof control.id !== 'string')
312
+ throw new Error('Invalid ACK');
313
+ this.hub.acknowledge(control.id, [id]);
314
+ }
315
+ catch {
316
+ socket.close(1008, 'Invalid ACK');
317
+ }
318
+ return;
319
+ }
320
+ }
321
+ if (this.#closing)
322
+ return;
323
+ if (++value.pending > this.settings.maxPendingMessages) {
324
+ value.pending--;
325
+ socket.close(1013, 'Too many messages');
326
+ return;
327
+ }
328
+ const data = Array.isArray(raw)
329
+ ? Buffer.concat(raw)
330
+ : raw instanceof ArrayBuffer
331
+ ? Buffer.from(raw)
332
+ : Buffer.from(raw);
333
+ const work = value.tail.then(() => {
334
+ if (value.failed || !value.registration)
335
+ return;
336
+ return route.message(data, session);
337
+ });
338
+ value.tail = work
339
+ .then(() => { }, () => {
340
+ value.failed = true;
341
+ this.context.logger.log('error', 'WebSocket message handler failed', {
342
+ connection: id,
343
+ });
344
+ socket.close(1011, 'Message failed');
345
+ })
346
+ .finally(() => {
347
+ value.pending--;
348
+ });
349
+ this.#watch(value.tail);
350
+ });
351
+ socket.once('close', (code, reason) => {
352
+ this.context.logger.log('debug', 'WebSocket closed', {
353
+ connection: id,
354
+ member: identity.member,
355
+ code,
356
+ reason: reason.toString().slice(0, 123),
357
+ ms: Math.round(performance.now() - opened),
358
+ open: this.#clients.size - 1,
359
+ });
360
+ const cleanup = registered
361
+ .then(async () => {
362
+ await value.registration?.close();
363
+ })
364
+ .finally(() => {
365
+ this.#clients.delete(id);
366
+ });
367
+ void this.#watch(cleanup).catch(() => {
368
+ this.context.logger.log('warn', 'WebSocket presence cleanup deferred to hub recovery', {
369
+ connection: id,
370
+ });
371
+ });
372
+ });
373
+ }
374
+ /** Turns one server's new connection list into joins and leaves per tenant, for local routes. */
375
+ #presence(owner, connections) {
376
+ const before = this.#owners.get(owner) ?? [];
377
+ if (connections.length)
378
+ this.#owners.set(owner, connections);
379
+ else
380
+ this.#owners.delete(owner);
381
+ const peer = (record) => Object.freeze({
382
+ member: record.member,
383
+ connection: record.connection,
384
+ ownerEpoch: record.ownerEpoch,
385
+ ...(record.clientId === undefined ? {} : { clientId: record.clientId }),
386
+ metadata: record.metadata,
387
+ });
388
+ const was = new Set(before.map((record) => record.connection));
389
+ const now = new Set(connections.map((record) => record.connection));
390
+ const changes = new Map();
391
+ const of = (tenant) => {
392
+ const change = changes.get(tenant) ?? { joined: [], left: [] };
393
+ changes.set(tenant, change);
394
+ return change;
395
+ };
396
+ for (const record of connections)
397
+ if (!was.has(record.connection))
398
+ of(record.tenant).joined.push(peer(record));
399
+ for (const record of before)
400
+ if (!now.has(record.connection))
401
+ of(record.tenant).left.push(peer(record));
402
+ if (!changes.size)
403
+ return;
404
+ for (const value of this.#clients.values()) {
405
+ const { route, session } = value;
406
+ const change = session && changes.get(session.identity.tenant);
407
+ // A socket that is closing (its own leave is in this change) gets nothing more.
408
+ if (!route.presence ||
409
+ !session ||
410
+ !change ||
411
+ value.failed ||
412
+ !value.registration ||
413
+ value.socket.readyState !== WebSocket.OPEN)
414
+ continue;
415
+ const presence = Object.freeze({
416
+ tenant: session.identity.tenant,
417
+ joined: Object.freeze([...change.joined]),
418
+ left: Object.freeze([...change.left]),
419
+ });
420
+ // In order with this connection's messages, like a message handler.
421
+ value.tail = value.tail
422
+ .then(() => route.presence?.(presence, session))
423
+ .then(() => { }, () => {
424
+ this.context.logger.log('warn', 'WebSocket presence handler failed', {
425
+ connection: session.id,
426
+ });
427
+ });
428
+ this.#watch(value.tail);
429
+ }
430
+ }
431
+ start() {
432
+ const events = this.hub.events();
433
+ this.#loop = (async () => {
434
+ for await (const event of events) {
435
+ if (event.kind === 'presence') {
436
+ this.#presence(event.ownerEpoch, event.connections);
437
+ continue;
438
+ }
439
+ if (event.kind === 'kick') {
440
+ for (const id of event.connections)
441
+ this.#clients.get(id)?.socket.close(event.code, event.reason);
442
+ continue;
443
+ }
444
+ // Encoded once and shared by every recipient; ws keeps per-socket order in its queue.
445
+ const frame = Buffer.from(JSON.stringify({
446
+ $dokebi: 'delivery-v1',
447
+ id: event.id,
448
+ expiresAt: event.expiresAt,
449
+ data: Buffer.from(event.data).toString('base64'),
450
+ }));
451
+ for (const id of event.connections) {
452
+ const value = this.#clients.get(id);
453
+ if (value)
454
+ this.#deliver(value.socket, frame);
455
+ }
456
+ // Queued events would otherwise be fanned out in one tick, before any socket can flush,
457
+ // and a burst could exceed maxBufferedBytes on healthy sockets. One turn lets I/O run.
458
+ if (this.#sends)
459
+ await immediate();
460
+ }
461
+ })().catch(() => {
462
+ for (const value of this.#clients.values())
463
+ value.socket.close(1013, 'Hub unavailable');
464
+ });
465
+ this.#timer = setInterval(() => {
466
+ const idleBefore = performance.now() - this.settings.idleTimeoutMs;
467
+ for (const value of this.#clients.values()) {
468
+ if (this.settings.idleTimeoutMs && value.seen < idleBefore) {
469
+ value.socket.close(4408, 'Idle');
470
+ continue;
471
+ }
472
+ if (!value.alive) {
473
+ value.socket.terminate();
474
+ continue;
475
+ }
476
+ value.alive = false;
477
+ value.socket.ping();
478
+ }
479
+ }, this.settings.heartbeatMs);
480
+ this.#timer.unref();
481
+ }
482
+ /** Stops waiting as soon as `signal` (the core drain deadline) aborts; sockets are then cut. */
483
+ async drain(signal) {
484
+ this.#closing = true;
485
+ if (this.#timer)
486
+ clearInterval(this.#timer);
487
+ const stop = aborted(signal);
488
+ // Broadcast writes are not awaited here: each 1012 close frame is queued behind them, and a
489
+ // client that stopped reading must not hold the drain until the deadline.
490
+ await this.#idle(signal, stop, false);
491
+ for (const value of this.#clients.values())
492
+ value.socket.close(1012, 'Server restarting');
493
+ const deadline = performance.now() + this.settings.closeTimeoutMs;
494
+ while (this.#clients.size && performance.now() < deadline && !signal.aborted)
495
+ await Promise.race([delay(10), stop]);
496
+ for (const value of this.#clients.values())
497
+ value.socket.terminate();
498
+ await this.hub.events().return?.();
499
+ await Promise.race([this.#loop, stop]);
500
+ await this.#idle(signal, stop, true);
501
+ }
502
+ }
@@ -0,0 +1,5 @@
1
+ import type { WebsocketApi } from './types.js';
2
+ export * from './router.js';
3
+ export * from './types.js';
4
+ /** Factory input: `{ app, options? }`. Options default to `app.config['dokebi-websocket']`. */
5
+ export declare const createPlugin: import("@dokebi/core").PluginFactory<WebsocketApi>;
package/dist/index.js ADDED
@@ -0,0 +1,43 @@
1
+ import { definePlugin, providerDependency } from '@dokebi/core';
2
+ import { Gateway } from './gateway.js';
3
+ import { parseOptions } from './options.js';
4
+ export * from './router.js';
5
+ export * from './types.js';
6
+ const hub = providerDependency({
7
+ name: 'dokebi-websocket-hub',
8
+ version: '^0.1.0 || ^0.2.0',
9
+ packageName: '@dokebi/websocket-hub',
10
+ load: () => import('@dokebi/websocket-hub'),
11
+ });
12
+ const web = providerDependency({
13
+ name: 'dokebi-web',
14
+ version: '^0.1.0',
15
+ packageName: '@dokebi/web',
16
+ load: () => import('@dokebi/web'),
17
+ });
18
+ class WebsocketRuntime {
19
+ #options;
20
+ #gateway;
21
+ constructor(options) {
22
+ this.#options = options;
23
+ }
24
+ setup(context) {
25
+ this.#gateway = new Gateway(context, context.getDependency(web), context.getDependency(hub), this.#options);
26
+ return this.#gateway.api;
27
+ }
28
+ start() {
29
+ this.#gateway?.start();
30
+ }
31
+ async drain(context) {
32
+ await this.#gateway?.drain(context.drainSignal);
33
+ }
34
+ }
35
+ /** Factory input: `{ app, options? }`. Options default to `app.config['dokebi-websocket']`. */
36
+ export const createPlugin = definePlugin({
37
+ name: 'dokebi-websocket',
38
+ version: '0.1.2',
39
+ core: '^0.2.0',
40
+ options: parseOptions,
41
+ dependencies: () => [hub, web],
42
+ instance: ({ options }) => new WebsocketRuntime(options),
43
+ });
@@ -0,0 +1,21 @@
1
+ export interface Options {
2
+ maxPayload: number;
3
+ maxConnections: number;
4
+ maxPendingMessages: number;
5
+ maxBufferedBytes: number;
6
+ closeTimeoutMs: number;
7
+ heartbeatMs: number;
8
+ /**
9
+ * Closes a connection (4408 `Idle`) that sent nothing for this long; 0 (default) never does.
10
+ * WebSocket pings prove only that the browser's network stack is up: a hidden page that is
11
+ * frozen (back/forward cache) still answers them. A client that sends `{"$dokebi":"ping-v1"}`
12
+ * from its script proves that the page itself still runs.
13
+ */
14
+ idleTimeoutMs: number;
15
+ /**
16
+ * How long an upgrade waits for the hub while it reconnects (a leader change, a rolling
17
+ * restart) before it is refused with 503 HUB_RECOVERING. 0 refuses at once.
18
+ */
19
+ hubWaitMs: number;
20
+ }
21
+ export declare function parseOptions(input: unknown): Options;
@@ -0,0 +1,40 @@
1
+ import { types } from 'node:util';
2
+ export function parseOptions(input) {
3
+ if (input === undefined)
4
+ input = {};
5
+ if (!input ||
6
+ typeof input !== 'object' ||
7
+ types.isProxy(input) ||
8
+ ![Object.prototype, null].includes(Object.getPrototypeOf(input)))
9
+ throw new Error('Invalid websocket options');
10
+ const v = Object.create(null);
11
+ for (const key of Reflect.ownKeys(input)) {
12
+ const desc = Object.getOwnPropertyDescriptor(input, key);
13
+ if (typeof key !== 'string' || !desc || !('value' in desc) || !desc.enumerable)
14
+ throw new Error('Invalid websocket options');
15
+ v[key] = desc.value;
16
+ }
17
+ const defaults = {
18
+ maxPayload: 65536,
19
+ maxConnections: 128,
20
+ maxPendingMessages: 32,
21
+ maxBufferedBytes: 1048576,
22
+ closeTimeoutMs: 2000,
23
+ heartbeatMs: 10000,
24
+ idleTimeoutMs: 0,
25
+ hubWaitMs: 5000,
26
+ };
27
+ if (Object.keys(v).some((k) => !Object.hasOwn(defaults, k)))
28
+ throw new Error('Unknown websocket option');
29
+ const result = { ...defaults };
30
+ for (const key of Object.keys(defaults)) {
31
+ if (v[key] !== undefined) {
32
+ const x = v[key];
33
+ const min = key === 'idleTimeoutMs' || key === 'hubWaitMs' ? 0 : 1;
34
+ if (typeof x !== 'number' || !Number.isSafeInteger(x) || x < min || x > 67108864)
35
+ throw new Error('Invalid websocket limit');
36
+ result[key] = x;
37
+ }
38
+ }
39
+ return result;
40
+ }
@@ -0,0 +1,45 @@
1
+ import type { Awaitable } from '@dokebi/core';
2
+ import type { FastifyRequest } from 'fastify';
3
+ import type { WebsocketIdentity, WebsocketPresence, WebsocketRoute, WebsocketSession } from './types.js';
4
+ /** What a message handler receives besides the message data. */
5
+ export interface SocketContext {
6
+ readonly session: WebsocketSession;
7
+ readonly identity: WebsocketIdentity;
8
+ /** Sends `{ type, data }` to this connection only. */
9
+ send(type: string, data?: unknown): Promise<void>;
10
+ /**
11
+ * Sends `{ type, data }` through the hub to the tenant, a room or a member. The promise settles
12
+ * when every recipient has acknowledged (or the delivery times out, DELIVERY_TIMEOUT): one
13
+ * hidden or frozen browser tab delays it up to deliveryTimeoutMs. Do not await it before
14
+ * replying unless the reply must report delivery; the hub keeps delivering either way.
15
+ */
16
+ broadcast(type: string, data?: unknown, target?: {
17
+ room?: string;
18
+ member?: string;
19
+ }): ReturnType<WebsocketSession['broadcast']>;
20
+ }
21
+ /** Returns reply data for messages that carry an `id`; throw an error with `code` to report it. */
22
+ export type SocketHandler = (data: unknown, socket: SocketContext) => Awaitable<unknown>;
23
+ export interface SocketDefinition {
24
+ readonly path: string;
25
+ readonly origins?: WebsocketRoute['origins'];
26
+ readonly constraints?: WebsocketRoute['constraints'];
27
+ /** Client code version this route accepts; others are closed with 4426 (D-0033). */
28
+ readonly version?: string;
29
+ authenticate(request: FastifyRequest): Awaitable<WebsocketIdentity | undefined>;
30
+ authorizeRoom?(identity: WebsocketIdentity, room: string): Awaitable<boolean>;
31
+ /** Handlers by message type, e.g. `{ 'chat.send': (data, socket) => ... }`. */
32
+ readonly on: Readonly<Record<string, SocketHandler>>;
33
+ /**
34
+ * Joins and leaves of the same tenant (any server; also expired servers). `true` sends each
35
+ * connection `{ type: 'presence', data: { tenant, joined, left } }`; a function decides itself.
36
+ */
37
+ readonly presence?: boolean | ((change: WebsocketPresence, socket: SocketContext) => Awaitable<void>);
38
+ }
39
+ /**
40
+ * A WebSocket message router. Messages are JSON `{ type, data?, id? }`. A handler's return value
41
+ * is sent back as `{ type: 'reply', id, data }` when the message had an `id`. Unknown types,
42
+ * malformed messages and handler failures answer `{ type: 'error', id?, code }`; error messages
43
+ * and stacks are never sent. Use the result with `websocket.route(...)`.
44
+ */
45
+ export declare function defineSocket(definition: SocketDefinition): WebsocketRoute;
package/dist/router.js ADDED
@@ -0,0 +1,88 @@
1
+ const TYPE = /^[A-Za-z][A-Za-z0-9._:-]{0,63}$/;
2
+ const ID = /^[A-Za-z0-9._:-]{1,64}$/;
3
+ const CODE = /^[A-Z][A-Z0-9_]{0,63}$/;
4
+ const encoder = new TextEncoder();
5
+ const decoder = new TextDecoder('utf-8', { fatal: true });
6
+ function frame(value) {
7
+ return JSON.stringify(value);
8
+ }
9
+ function context(session) {
10
+ return Object.freeze({
11
+ session,
12
+ identity: session.identity,
13
+ send: (type, value) => session.send(frame(value === undefined ? { type } : { type, data: value })),
14
+ broadcast: (type, value, target) => session.broadcast(encoder.encode(frame(value === undefined ? { type } : { type, data: value })), target),
15
+ });
16
+ }
17
+ function errorCode(error) {
18
+ const code = error?.code;
19
+ return typeof code === 'string' && CODE.test(code) ? code : 'HANDLER_FAILED';
20
+ }
21
+ /**
22
+ * A WebSocket message router. Messages are JSON `{ type, data?, id? }`. A handler's return value
23
+ * is sent back as `{ type: 'reply', id, data }` when the message had an `id`. Unknown types,
24
+ * malformed messages and handler failures answer `{ type: 'error', id?, code }`; error messages
25
+ * and stacks are never sent. Use the result with `websocket.route(...)`.
26
+ */
27
+ export function defineSocket(definition) {
28
+ const handlers = new Map();
29
+ if (!definition || typeof definition.on !== 'object' || definition.on === null)
30
+ throw new TypeError('Invalid socket definition');
31
+ const presence = definition.presence;
32
+ if (presence !== undefined && typeof presence !== 'boolean' && typeof presence !== 'function')
33
+ throw new TypeError('Invalid socket presence');
34
+ for (const [type, handler] of Object.entries(definition.on)) {
35
+ if (!TYPE.test(type) || type === 'reply' || type === 'error' || typeof handler !== 'function')
36
+ throw new TypeError('Invalid socket handler: ' + type);
37
+ handlers.set(type, handler);
38
+ }
39
+ return Object.freeze({
40
+ path: definition.path,
41
+ ...(definition.origins === undefined ? {} : { origins: definition.origins }),
42
+ ...(definition.constraints === undefined ? {} : { constraints: definition.constraints }),
43
+ ...(definition.version === undefined ? {} : { version: definition.version }),
44
+ authenticate: (request) => definition.authenticate(request),
45
+ ...(definition.authorizeRoom
46
+ ? {
47
+ authorizeRoom: (identity, room) => definition.authorizeRoom(identity, room),
48
+ }
49
+ : {}),
50
+ ...(presence
51
+ ? {
52
+ presence: (change, session) => presence === true
53
+ ? session.send(frame({ type: 'presence', data: change }))
54
+ : presence(change, context(session)),
55
+ }
56
+ : {}),
57
+ async message(data, session) {
58
+ let message;
59
+ try {
60
+ message = JSON.parse(decoder.decode(data));
61
+ }
62
+ catch {
63
+ return session.send(frame({ type: 'error', code: 'INVALID_MESSAGE' }));
64
+ }
65
+ const id = message !== null &&
66
+ typeof message === 'object' &&
67
+ typeof message.id === 'string' &&
68
+ ID.test(message.id)
69
+ ? message.id
70
+ : undefined;
71
+ if (message === null || typeof message !== 'object' || typeof message.type !== 'string')
72
+ return session.send(frame({ type: 'error', ...(id ? { id } : {}), code: 'INVALID_MESSAGE' }));
73
+ const handler = handlers.get(message.type);
74
+ if (!handler)
75
+ return session.send(frame({ type: 'error', ...(id ? { id } : {}), code: 'UNKNOWN_TYPE' }));
76
+ const socket = context(session);
77
+ let result;
78
+ try {
79
+ result = await handler(message.data, socket);
80
+ }
81
+ catch (error) {
82
+ return session.send(frame({ type: 'error', ...(id ? { id } : {}), code: errorCode(error) }));
83
+ }
84
+ if (id)
85
+ await session.send(frame(result === undefined ? { type: 'reply', id } : { type: 'reply', id, data: result }));
86
+ },
87
+ });
88
+ }
@@ -0,0 +1,73 @@
1
+ import type { Awaitable } from '@dokebi/core';
2
+ import type { HubReceipt } from '@dokebi/websocket-hub';
3
+ import type { FastifyRequest } from 'fastify';
4
+ export interface WebsocketIdentity {
5
+ readonly tenant: string;
6
+ readonly member: string;
7
+ readonly clientId?: string;
8
+ readonly rooms?: readonly string[];
9
+ readonly metadata?: Readonly<Record<string, string>>;
10
+ }
11
+ /** A connection of the hub as presence changes report it (any server of the cluster). */
12
+ export interface WebsocketPeer {
13
+ readonly member: string;
14
+ readonly connection: string;
15
+ readonly ownerEpoch: string;
16
+ readonly clientId?: string;
17
+ readonly metadata: Readonly<Record<string, string>>;
18
+ }
19
+ /**
20
+ * Connections of one tenant that came or went, from the hub's presence events: joins and
21
+ * leaves on any server, and the connections of a server whose hub registration expired.
22
+ * The first change seen from a server may list connections that existed before.
23
+ */
24
+ export interface WebsocketPresence {
25
+ readonly tenant: string;
26
+ readonly joined: readonly WebsocketPeer[];
27
+ readonly left: readonly WebsocketPeer[];
28
+ }
29
+ export interface WebsocketSession {
30
+ readonly id: string;
31
+ readonly identity: WebsocketIdentity;
32
+ send(data: string | Uint8Array): Promise<void>;
33
+ broadcast(data: Uint8Array, target?: {
34
+ room?: string;
35
+ member?: string;
36
+ }): Promise<HubReceipt>;
37
+ join(room: string): Promise<void>;
38
+ leave(room: string): Promise<void>;
39
+ close(code?: number, reason?: string): void;
40
+ }
41
+ export interface WebsocketRoute {
42
+ readonly path: string;
43
+ /**
44
+ * Browser origins allowed to open this route. By default an upgrade whose `Origin` host differs
45
+ * from the request `Host` is rejected with 403. A list adds exact origins such as
46
+ * `https://app.example.com`; `'*'` disables the check (unsafe with cookie authentication).
47
+ */
48
+ readonly origins?: readonly string[] | '*';
49
+ /**
50
+ * Fastify route constraints for the upgrade route, for example `{ dokebiApp: 'shop' }` from
51
+ * @dokebi/app, so several routes may share one path.
52
+ */
53
+ readonly constraints?: Readonly<Record<string, unknown>>;
54
+ /**
55
+ * The client code version this route accepts (D-0033). A connection whose upgrade query
56
+ * `dokebiVersion` differs, or is missing, is closed with 4426 `Reload required` and never
57
+ * registered: a page that kept old code (a long-open tab, the back/forward cache) reloads
58
+ * instead of joining with an old protocol.
59
+ */
60
+ readonly version?: string;
61
+ authenticate(request: FastifyRequest): Awaitable<WebsocketIdentity | undefined>;
62
+ authorizeRoom?(identity: WebsocketIdentity, room: string): Awaitable<boolean>;
63
+ message(data: Uint8Array, session: WebsocketSession): Awaitable<void>;
64
+ /**
65
+ * Called on this server, for each of its open connections on this route, when connections of
66
+ * the same tenant came or went. Runs in order with that connection's messages.
67
+ */
68
+ presence?(change: WebsocketPresence, session: WebsocketSession): Awaitable<void>;
69
+ }
70
+ export interface WebsocketApi {
71
+ route(definition: WebsocketRoute): void;
72
+ readonly connections: number;
73
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,57 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "type": "object",
4
+ "additionalProperties": false,
5
+ "properties": {
6
+ "maxPayload": {
7
+ "type": "integer",
8
+ "minimum": 1,
9
+ "maximum": 67108864,
10
+ "default": 65536
11
+ },
12
+ "maxConnections": {
13
+ "type": "integer",
14
+ "minimum": 1,
15
+ "maximum": 67108864,
16
+ "default": 128
17
+ },
18
+ "maxPendingMessages": {
19
+ "type": "integer",
20
+ "minimum": 1,
21
+ "maximum": 67108864,
22
+ "default": 32
23
+ },
24
+ "maxBufferedBytes": {
25
+ "type": "integer",
26
+ "minimum": 1,
27
+ "maximum": 67108864,
28
+ "default": 1048576
29
+ },
30
+ "closeTimeoutMs": {
31
+ "type": "integer",
32
+ "minimum": 1,
33
+ "maximum": 67108864,
34
+ "default": 2000
35
+ },
36
+ "heartbeatMs": {
37
+ "type": "integer",
38
+ "minimum": 1,
39
+ "maximum": 67108864,
40
+ "default": 10000
41
+ },
42
+ "idleTimeoutMs": {
43
+ "type": "integer",
44
+ "minimum": 0,
45
+ "maximum": 67108864,
46
+ "default": 0,
47
+ "description": "Close (4408 Idle) a connection that sent nothing for this long; 0 never. Clients send {\"$dokebi\":\"ping-v1\"} from their script to show the page still runs."
48
+ },
49
+ "hubWaitMs": {
50
+ "type": "integer",
51
+ "minimum": 0,
52
+ "maximum": 67108864,
53
+ "default": 5000,
54
+ "description": "How long an upgrade waits for a reconnecting hub (leader change, rolling restart) before 503 HUB_RECOVERING; 0 refuses at once."
55
+ }
56
+ }
57
+ }
package/package.json CHANGED
@@ -1,6 +1,68 @@
1
1
  {
2
2
  "name": "@dokebi/websocket",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.2",
4
+ "private": false,
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "main": "dist/index.js",
8
+ "types": "dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js"
13
+ },
14
+ "./client": {
15
+ "types": "./dist/client.d.ts",
16
+ "import": "./dist/client.js"
17
+ }
18
+ },
19
+ "files": [
20
+ "dist",
21
+ "options.schema.json",
22
+ "README.md",
23
+ "AI.md",
24
+ "LICENSE"
25
+ ],
26
+ "engines": {
27
+ "node": ">=24.0.0"
28
+ },
29
+ "scripts": {
30
+ "build": "tsc -p tsconfig.json",
31
+ "typecheck": "tsc -p tsconfig.test.json --noEmit",
32
+ "test": "tsc -p tsconfig.test.json && node --test \".tmp/tests/tests/*.test.js\""
33
+ },
34
+ "dependencies": {
35
+ "@fastify/websocket": "11.3.4",
36
+ "ws": "8.22.0"
37
+ },
38
+ "peerDependencies": {
39
+ "@dokebi/core": "^0.2.0",
40
+ "@dokebi/web": "^0.1.0",
41
+ "@dokebi/websocket-hub": "^0.1.0 || ^0.2.0"
42
+ },
43
+ "devDependencies": {
44
+ "@dokebi/web": "0.1.1",
45
+ "@dokebi/websocket-hub": "0.2.0"
46
+ },
47
+ "dokebi": {
48
+ "schemaVersion": 2,
49
+ "id": "dokebi-websocket",
50
+ "core": "^0.2.0",
51
+ "dependencies": [
52
+ {
53
+ "name": "dokebi-websocket-hub",
54
+ "version": "^0.1.0 || ^0.2.0"
55
+ },
56
+ {
57
+ "name": "dokebi-web",
58
+ "version": "^0.1.0"
59
+ }
60
+ ],
61
+ "optionsSchema": "options.schema.json",
62
+ "documentation": "AI.md"
63
+ },
64
+ "publishConfig": {
65
+ "access": "public",
66
+ "registry": "https://registry.npmjs.org/"
67
+ }
68
+ }