@dokebi/websocket 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,21 +1,21 @@
1
1
  # @dokebi/websocket
2
2
 
3
- Node >=24, 0.3.0. Dokebi Fastify 웹과 websocket-hub를 연결하는 선택 플러그인. API 서버에 템플릿/뷰를 강제하지 않는다.
3
+ Node >=24, version 0.4.1 (unreleased). An optional plugin that connects the Dokebi Fastify web plugin with websocket-hub. It does not force templates or views on API servers. AI agents start with [AI.md](AI.md).
4
4
 
5
- ```ts
5
+ ```ts snippet
6
6
  import { Application, dependencyOf, loadConfig } from '@dokebi/core';
7
7
  import { createPlugin } from '@dokebi/websocket';
8
8
  const document = await loadConfig('./dokebi.yaml');
9
9
  const app = new Application({config: document.options});
10
10
  const ws = createPlugin({app: app.view});
11
11
  app.register({
12
- metadata: {name:'chat',version:'1.0.0',core:'^0.2.0',dependencies:[dependencyOf(ws)]},
12
+ metadata: {name:'chat',version:'1.0.0',core: '^0.4.0',dependencies:[dependencyOf(ws)]},
13
13
  setup(context) {
14
14
  context.get(ws).route({
15
15
  path:'/ws',
16
- // 생략하면 다른 출처의 브라우저 Upgrade를 403으로 거부한다. 필요한 출처만 정확히 적는다.
16
+ // Omitted, browser Upgrades from other origins get 403. List only the origins you need, exactly.
17
17
  origins:['https://app.example.com'],
18
- // 실제 앱에서는 검증된 세션/토큰으로 tenant/member를 결정한다.
18
+ // A real app decides tenant/member from a verified session or token.
19
19
  authenticate(request) { return authenticateUser(request); },
20
20
  authorizeRoom(identity, room) { return canJoinRoom(identity, room); },
21
21
  async message(data, session) {
@@ -25,97 +25,112 @@ app.register({
25
25
  }
26
26
  });
27
27
  await app.start();
28
- // 종료 신호에서 await app.stop().
28
+ // await app.stop() on a shutdown signal.
29
29
  ```
30
30
 
31
- authenticateUser/canJoinRoom은 사용자 인증·권한 함수이며 이 패키지가 제공하지 않는다. authenticate는 `{tenant,member,clientId?,rooms?,metadata?}` 또는 undefined를 반환한다. 실제 실행 가능한 예제는 저장소 examples/23-websocket이며 예제의 헤더 인증은 테스트 전용이다.
31
+ `authenticateUser`/`canJoinRoom` are your authentication and authorization functions; this package does not provide them. `authenticate` returns `{ tenant, member, clientId?, rooms?, metadata? }` or undefined. The runnable example is examples/23-websocket in the repository; its header authentication is for tests only.
32
32
 
33
- websocket-hub의 필수 YAML을 준비한다. CLI 등록은 redis→nats→web→websocket-hub→websocket 순서다. manifest는 schemaVersion 2이고 설치 모듈은 없다. 서버 시작은 setup/start에서 이루어진다.
33
+ Prepare the required YAML of websocket-hub. The CLI registration order is redis → nats → web → websocket-hub → websocket. The manifest is schemaVersion 2 and there is no install module. Servers start in setup/start.
34
34
 
35
- ## 팩토리와 의존성(플러그인 계약 v2)
35
+ ## Options
36
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`이므로 앱이 함께 설치한다.
37
+ | Key | Type | Default | Description |
38
+ |---|---|---|---|
39
+ | `maxPayloadBytes` | integer | 65536 | Message size |
40
+ | `maxConnections` | integer | 128 | Connections per process |
41
+ | `maxPending` | integer | 32 | Waiting messages per connection; also bounds its waiting presence calls, separately |
42
+ | `maxBufferedBytes` | integer | 1048576 | Send buffer before 1013 `Slow consumer` |
43
+ | `shutdownTimeoutMs` | integer ms | 2000 | Socket close wait at drain |
44
+ | `heartbeatMs` | integer ms | 10000 | ping/pong interval |
45
+ | `idleTimeoutMs` | integer ms | 0 (off) | Close silent clients with 4408 |
46
+ | `hubWaitMs` | integer ms | 5000 | Upgrade wait while the hub recovers |
47
+ | `sealDriftMs` | integer ms | 60000 | Allowed clock difference of sealed frames |
38
48
 
39
- ## 교차 출처 거부(CSWSH)
49
+ 0.4.0 renamed `maxPayload` → `maxPayloadBytes`, `maxPendingMessages` → `maxPending` and `closeTimeoutMs` → `shutdownTimeoutMs` ([D-0071](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0071-option-vocabulary.md)); the old names still work in 0.4.0 with an `OPTION_DEPRECATED` warning. The [schema](options.schema.json) has the limits.
40
50
 
41
- 브라우저는 다른 사이트의 페이지에서도 쿠키를 붙여 WebSocket Upgrade를 보낸다. 쿠키로 인증하는 라우트가 출처를 확인하지 않으면 악성 페이지가 사용자 권한으로 소켓을 연다(Cross-Site WebSocket Hijacking).
51
+ ## Factory and dependencies (plugin contract v2)
42
52
 
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`에 적는다.
53
+ The factory input is `{ app, options? }`; `app` is required. Without options it reads `app.config['dokebi-websocket']`. The `hub`, `web` and `dependencies` inputs were removed ([D-0028](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0028-plugin-contract-v2.md)). `dokebi-web` and `dokebi-websocket-hub` are wired through provider descriptors (`@dokebi/web/dependency`, `@dokebi/websocket-hub/dependency`). One registered under the same name is reused; otherwise it is created from `@dokebi/web` or `@dokebi/websocket-hub` with `app.config`. To use a specific instance, register it first, e.g. `app.register(createWeb({ app: app.view }))`. Both packages are `peerDependencies`, so the app installs them too.
47
54
 
48
- 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로 종료한다.
55
+ ## Cross-origin refusal (CSWSH)
49
56
 
50
- 메시지는 연결별 순차 실행하며 초기 등록 중 수신도 큐에 보관한다. maxPayload65536, maxConnections128, maxPendingMessages32, maxBufferedBytes1048576, closeTimeoutMs2000, heartbeatMs10000이 기본값이다. [스키마](options.schema.json)에 한도가 있다. ping/pong, 송신 버퍼 상한, 압축 비활성화를 사용한다. hub 자체의 payload/접속 한도도 함께 적용된다.
57
+ Browsers attach cookies to a WebSocket Upgrade even from another site's page. When a cookie-authenticated route does not check the origin, a malicious page opens a socket with the user's rights (Cross-Site WebSocket Hijacking).
51
58
 
52
- 방송 전달은 대상 소켓마다 송신 완료를 기다리지 않는다. 방송 바이트를 그대로(UTF-8이면 텍스트 프레임, 아니면 바이너리 프레임) 버퍼 하나로 모든 수신 소켓이 나눠 쓰며 열린 소켓의 `ws` 송신 큐에 넣고(같은 소켓 안의 순서는 그 큐가 보장한다), 송신 오류가 나면 그 소켓만 끊는다. `bufferedAmount`에 프레임을 더한 값이 maxBufferedBytes를 넘으면 그 소켓을 1013 `Slow consumer`로 닫는다. 그래서 느린 클라이언트 하나가 다른 소켓의 방송을 늦추지 않는다. 대기 중인 허브 이벤트를 한 번에 처리하다가 정상 소켓까지 한도를 넘기지 않도록, 송신 중인 프레임이 있으면 이벤트 사이에 이벤트 루프를 한 번 양보한다.
59
+ - Default: when an `Origin` header exists and its host (host:port) differs from the request `Host`, `preValidation` refuses with 403 (`ORIGIN_FORBIDDEN`). `authenticate` is not called. Requests without `Origin` (non-browser clients) pass.
60
+ - `origins: ['https://app.example.com']`: allows the listed origins in addition to the same host. Entries must be exact http(s) origins of the form `scheme://host[:port]`, otherwise `route()` throws.
61
+ - `origins: '*'`: turns the check off. With cookie authentication the risk above stays. Use it explicitly only when tokens are verified directly from messages or headers.
62
+ - When a reverse proxy rewrites `Host`, even the same origin is refused. Have the proxy pass the original `Host` or list the public origin in `origins`.
53
63
 
54
- 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/허브가 닫힌다.
64
+ The API is `route({ path, origins?, authenticate, authorizeRoom?, message })` registration in setup and the `connections` count. A session offers `id`/`identity`, `send`, `broadcast`, `join`, `leave` and `close`. `broadcast` is fixed to the authenticated tenant. `join` requires `authorizeRoom` to return true. Origin refused 403, authentication failure 401, hub not ready or shutting down 503, plain HTTP 426. An unhandled handler error closes with 1011.
55
65
 
56
- hub.events는 이 플러그인이 단독 소비한다. broadcast는 많아야 한 번이며 허브가 내보내면 receipt `{ id, recipients }`를 반환한다(아래 「방송」). send는 현재 소켓의 원시 응답으로 별도 송신 완료 계약이다. 실제 두 컨테이너·네 워커의 교차 서버 전달/허브 SIGKILL/NATS 장애/DB drain 검증은 운영 전체 인증이나 실제 두 물리 장비 검증을 뜻하지 않는다.
66
+ Messages run in order per connection, and messages received during the initial registration are queued. Defaults: `maxPayloadBytes` 65536, `maxConnections` 128, `maxPending` 32, `maxBufferedBytes` 1048576, `shutdownTimeoutMs` 2000, `heartbeatMs` 10000. It uses ping/pong, a send buffer limit and no compression. The hub's own payload and connection limits apply as well.
57
67
 
68
+ Broadcast delivery does not wait for each target socket to finish sending. The broadcast bytes as they are (a text frame for UTF-8, otherwise a binary frame) are shared as one buffer by every receiving socket and put into the `ws` send queue of each open socket (that queue keeps the order within a socket); a socket with a send error is the only one cut. When `bufferedAmount` plus the frame exceeds `maxBufferedBytes`, that socket is closed with 1013 `Slow consumer`. So one slow client never delays broadcasts to other sockets. To avoid pushing healthy sockets over the limit while processing queued hub events at once, it yields the event loop once between events while frames are being sent.
58
69
 
59
- **접속자 입·퇴장(presence):** 허브는 연결이 들고 날 때마다 모든 서버에 그 서버 소유자(owner)의 연결 목록을 알린다. 서버가 죽어 등록이 만료된 경우도 포함한다. 이 패키지는 그 알림을 tenant별 `{ tenant, joined, left }`로 바꾼다. 그리고 같은 tenant에 열린 자기 서버의 연결마다 라우트의 `presence(change, session)` 훅을 그 연결의 메시지 처리 순서대로 부른다.
60
- - `defineSocket({ presence: true })`면 각 연결에 `{ type: 'presence', data: { tenant, joined, left } }`를 보낸다. 함수를 주면 그 함수가 `(change, socket)`으로 처리한다.
61
- - 한 서버에서 처음 받은 알림은 그전부터 있던 연결을 `joined`로 담을 수 있다. 화면은 이 메시지를 받으면 목록을 다시 읽는 방식이 안전하다.
70
+ stop blocks new work, waits for received handlers and broadcasts being sent, then closes with 1012. It also waits for remaining DB work of clients that disconnected first. `shutdownTimeoutMs` bounds the socket close wait, not the work. When core's drain deadline (`shutdown.drainTimeoutMs`, default 20000 ms) passes and `context.drainSignal` aborts, it stops waiting and cuts the remaining sockets; core reports the overrun as `DRAIN_TIMEOUT`. websocket depends on web and hub, so core finishes the websocket drain before starting the web and hub drains, and the DB and hub close after every drain.
62
71
 
63
- **페이지가 살아 있는지(`idleTimeoutMs`):** WebSocket ping은 브라우저의 네트워크 계층이 대신 답한다. 그래서 bfcache에 얼린 페이지나 스크립트가 멈춘 페이지도 연결이 살아 있는 것처럼 보인다. `idleTimeoutMs`(기본 0, 끔)를 주면 그 시간 동안 클라이언트가 아무것도 보내지 않은 연결을 `4408 Idle`로 닫는다. 클라이언트는 페이지 스크립트에서 주기적으로 `{"$dokebi":"ping-v1"}`을 보내 살아 있음을 알린다. 이 제어 프레임은 라우트로 가지 않는다.
72
+ `hub.events` is consumed only by this plugin. `broadcast` is at most once and returns the receipt `{ id, recipients }` once the hub sends it out ("Broadcast" below). `send` is a raw reply on the current socket with its own completion contract. Verified cross-server delivery between two real containers and four workers, a hub SIGKILL, NATS faults and DB drain do not mean full operational certification or verification on two physical machines.
64
73
 
65
- **연결 생애 로그:** debug 레벨에서 접속(`WebSocket connected`: 연결 ID·tenant·member·clientId·원격 주소·User-Agent·`Sec-Purpose`)과 종료(`WebSocket closed`: 닫힘 코드·이유·유지 시간)를 남긴다.
74
+ **Joins and leaves (presence):** the hub tells every server the connection list of a server owner whenever connections come and go, including when a dead server's registration expires. This package turns that into per-tenant `{ tenant, joined, left }` and calls the route's `presence(change, session)` hook for each of its own connections open in the same tenant, in that connection's message order. At most `maxPending` presence calls wait per connection; changes that come while that many wait are merged into one net change (joins and leaves of the same connection cancel out) and handed over when a call ends, with warn `PRESENCE_MERGED` once per 10 seconds. Nothing is dropped: applying the calls in order gives the same list.
75
+ - `defineSocket({ presence: true })` sends `{ type: 'presence', data: { tenant, joined, left } }` to each connection. Given a function, that function handles it as `(change, socket)`.
76
+ - The first notice a server receives may list connections that existed before as `joined`. Screens should read the list again when this message arrives.
66
77
 
67
- **클라이언트 버전(`version`, D-0033):** 라우트(또는 `defineSocket`)에 `version`을 주면, 업그레이드 질의 `dokebiVersion`이 다르거나 없는 연결을 등록하지 않고 `4426 Reload required`로 닫는다. 클라이언트는 이 코드를 받으면 페이지를 다시 읽는다. 오래 열린 탭이나 bfcache에서 되살아난 페이지가 옛 코드로 서버 상태에 끼어들지 못하게 한다.
78
+ **Is the page alive (`idleTimeoutMs`):** the browser's network layer answers WebSocket pings, so even a page frozen in bfcache or with stopped scripts looks alive. With `idleTimeoutMs` (default 0, off), a connection whose client sent nothing for that long is closed with `4408 Idle`. The client sends `{"$dokebi":"ping-v1"}` periodically from page script to show it is alive. This control frame never reaches the route.
68
79
 
69
- **허브 재연결 대기(`hubWaitMs`, D-0034):** 허브가 리더 교체·순차 재시작으로 잠시 `recovering`이면 업그레이드는 최대 `hubWaitMs`(기본 5000, 0이면 바로 거절)까지 기다린다. 그래도 준비되지 않으면 503이다. 거절 본문은 `{ error: 'UNAVAILABLE', reason }`이고 reason은 `CLOSING`·`HUB_<상태>`·`CAPACITY`다. 같은 이유를 debug 로그 `WebSocket upgrade refused`에도 남긴다.
80
+ **Connection lifecycle logs:** at debug it logs connect (`WebSocket connected`: connection ID, tenant, member, clientId, remote address, User-Agent, `Sec-Purpose`) and close (`WebSocket closed`: close code, reason, duration).
70
81
 
71
- ## 방송: 많아야 한 번 (0.2.0, [D-0057](../../docs/decisions/D-0057-websocket-broadcast-without-ack.md))
82
+ **Client version (`version`, D-0033):** with `version` on a route (or `defineSocket`), a connection whose upgrade query `dokebiVersion` differs or is missing is not registered and is closed with `4426 Reload required`. The client reloads the page on this code. It keeps long-open tabs and pages restored from bfcache from joining server state with old code.
72
83
 
73
- - `session.broadcast(bytes, target?)`·`socket.broadcast(type, data, target?)`는 허브가 수신 서버들에 내보내면 receipt `{ id, recipients }`로 끝난다. 클라이언트 ACK·재전송·중복 제거가 없다(D-0025의 ACK를 대체). `recipients`는 보낸 시점에 조건에 맞은 연결이며 **받았다는 확인이 아니다.** 재접속 중이던 연결, 느린 소비자로 1013 닫힌 연결은 그 방송을 못 받는다.
74
- - 실패는 바로 오고 다시 보내지 않는다: `RECOVERING`(허브가 리더에 연결돼 있지 않음·리더 교체 중, 보내지 않음), `OUTCOME_UNKNOWN`(요청을 보낸 뒤 답 전에 끊김, 보내졌을 수 있음), `BUSY`(처리 중 방송이 허브 `maxPending`). 다시 보낼지는 호출자가 정한다. `OUTCOME_UNKNOWN` 뒤에 다시 보내면 두 번 받을 수 있다.
75
- - 연결마다 메시지를 차례로 처리하지만 이제 broadcast를 기다려도 리더 왕복 한 번만 걸린다(가장 느린 탭을 기다리지 않는다). 결과가 필요 없으면 `void broadcast(...).catch(...)`로 바로 답해도 된다.
76
- - **앱 지침:** 놓치면 안 되는 일(주문 상태·결제 결과)은 방송에 맡기지 않는다. DB에 저장하고, 페이지는 다시 연결될 때 서버에서 최신 상태를 읽는다. 방송은 「바뀌었으니 다시 읽어라」 알림으로 쓴다.
77
- - 브라우저에는 방송 바이트가 그대로 간다. `defineSocket`의 `socket.broadcast(type, data)`는 `{ type, data }` JSON 텍스트 프레임이라 `send`의 응답과 같은 모양이다. `delivery-v1` 봉투와 클라이언트 `ack-v1`은 없어졌고, 브라우저 진입점 `@dokebi/websocket/client`(`DeliveryReceiver`)도 제거했다. 페이지는 표준 `WebSocket` API만 쓴다. 예전 페이지가 보내는 `{"$dokebi":"ack-v1"}`은 닫지 않고 무시한다(debug `WebSocket ACK from an old client ignored`, code `ACK_IGNORED`, 10초당 한 줄).
84
+ **Waiting for the hub to reconnect (`hubWaitMs`, D-0034):** while the hub is briefly `recovering` during a leader change or rolling restart, an upgrade waits up to `hubWaitMs` (default 5000; 0 refuses at once). If it is still not ready, 503. The refusal body is `{ error: 'UNAVAILABLE', reason }` with reason `CLOSING`, `HUB_<state>` or `CAPACITY`. The same reason is logged at debug as `WebSocket upgrade refused`.
78
85
 
79
- ```ts
86
+ ## Broadcast: at most once (0.2.0, [D-0057](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0057-websocket-broadcast-without-ack.md))
87
+
88
+ - `session.broadcast(bytes, target?)` and `socket.broadcast(type, data, target?)` end with the receipt `{ id, recipients }` once the hub sends to the receiving servers. There is no client ACK, resend or deduplication (replacing the ACK of D-0025). `recipients` are the connections matching when it was sent and **not a confirmation of receipt.** Connections in the middle of reconnecting and connections closed with 1013 as slow consumers miss that broadcast.
89
+ - Failures come at once and nothing is resent: `RECOVERING` (the hub is not connected to the leader or the leader is changing; not sent), `OUTCOME_UNKNOWN` (disconnected after sending the request, before the answer; it may have been sent), `BUSY` (broadcasts in progress reached the hub's `maxPending`). The caller decides whether to send again; resending after `OUTCOME_UNKNOWN` can deliver twice.
90
+ - Messages are processed in order per connection, but awaiting broadcast now costs only one leader round trip (it never waits for the slowest tab). When the result is not needed, answer at once with `void broadcast(...).catch(...)`.
91
+ - **App guideline:** never leave work that must not be missed (order state, payment results) to a broadcast. Store it in the DB and let the page read the latest state from the server when it reconnects. Use broadcasts as "it changed, read again" notices.
92
+ - Browsers get the broadcast bytes as they are. `socket.broadcast(type, data)` of `defineSocket` is a `{ type, data }` JSON text frame, the same shape as a `send` reply. The `delivery-v1` envelope and the client `ack-v1` are gone, and so is the browser entry `@dokebi/websocket/client` (`DeliveryReceiver`). Pages use only the standard `WebSocket` API. The `{"$dokebi":"ack-v1"}` old pages send is ignored, not closed (debug `WebSocket ACK from an old client ignored`, code `ACK_IGNORED`, one line per 10 seconds).
93
+
94
+ ```ts snippet
80
95
  socket.onmessage = ({ data }) => {
81
- const message = JSON.parse(data); // 응답·presence·방송 모두 { type, data? }
82
- if (message.type === 'order.changed') reloadOrder(message.data.id); // 방송은 알림, 내용은 다시 읽기
96
+ const message = JSON.parse(data); // replies, presence and broadcasts are all { type, data? }
97
+ if (message.type === 'order.changed') reloadOrder(message.data.id); // a broadcast is a notice; read the content again
83
98
  };
84
- socket.onopen = () => reloadState(); // 끊긴 사이의 방송은 다시 오지 않는다
99
+ socket.onopen = () => reloadState(); // broadcasts during a disconnect never come again
85
100
  ```
86
101
 
87
- `clientId`는 탭(페이지)마다 달라야 한다. 같은 `(tenant, member, clientId)`가 이미 연결돼 있으면 허브가 등록을 거절한다. 이때 소켓은 **4409 `Duplicate client`**로 닫힌다. 허브 장애(1013 `Hub unavailable`)와 구별된다. 같은 clientId로 바로 다시 붙으면 또 거절되므로, 브라우저에서 clientId를 localStorage처럼 탭끼리 공유하는 곳에 두지 않는다. 페이지 메모리나 탭 단위 저장소에 둔다.
102
+ `clientId` must differ per tab (page). When the same `(tenant, member, clientId)` is already connected, the hub refuses the registration and the socket closes with **4409 `Duplicate client`**, distinct from a hub failure (1013 `Hub unavailable`). Reconnecting at once with the same clientId is refused again, so never keep the clientId where tabs share it, such as localStorage. Keep it in page memory or tab-scoped storage.
88
103
 
89
- ## 라우트 제약과 메시지 라우터 (D-0030)
104
+ ## Route constraints and the message router (D-0030)
90
105
 
91
- - `route({ constraints })`: 업그레이드 라우트에 Fastify 라우트 제약을 붙인다. @dokebi/app이 `{ dokebiApp: '<앱>' }`으로 앱마다 같은 경로(`/ws`)를 따로 등록한다.
92
- - `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은 보내지 않고, 게이트웨이가 서버 로그에 error `WebSocket handler failed.`(code `SOCKET_HANDLER_FAILED`, 오류 전문)로 남긴다(세션의 `reportError`, D-0047). `reply`·`error`는 예약 type이다.
93
- - 2026-10-14 수정([ISSUE-0005](../../docs/issues/ISSUE-0005-playground-findings.md) PG-14): WebSocket 라우트가 없는 경로로 온 업그레이드 요청이 404 뒤에도 원시 소켓을 열어 둬 앱 종료가 정리 시한까지 멈췄다. @fastify/websocket을 캡슐화 없이 등록해 그 훅이 모든 업그레이드에 적용되게 했다.
106
+ - `route({ constraints })`: adds Fastify route constraints to the upgrade route. @dokebi/app registers the same path (`/ws`) separately per app with `{ dokebiApp: '<app>' }`.
107
+ - `defineSocket({ path, authenticate, on: { '<type>': handler } })` creates a route with a message router. Messages are JSON `{ type, data?, id? }`. A handler `(data, socket)` return value goes out as `{ type: 'reply', id, data }` when there is an `id`. `socket.send(type, data)` sends to this connection, `socket.broadcast(type, data, target?)` through the hub. An unknown type answers `UNKNOWN_TYPE`, an invalid message `INVALID_MESSAGE`, a handler error `{ type: 'error', id?, code }` with the error's `code` (when upper-case) or `HANDLER_FAILED`. The error message and stack are not sent; the gateway logs error `WebSocket handler failed.` (code `SOCKET_HANDLER_FAILED`, full error) on the server (the session's `reportError`, D-0047). A Dokebi error (`DokebiError`) also sends its `message` and `hint`, plus `fix` outside production (D-0063). `reply` and `error` are reserved types.
108
+ - Fixed 2026-10-14 ([ISSUE-0005](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/issues/ISSUE-0005-playground-findings.md) PG-14): an upgrade request to a path without a WebSocket route kept its raw socket open after the 404, so app shutdown hung until the cleanup deadline. @fastify/websocket is now registered without encapsulation so its hook applies to every upgrade.
94
109
 
95
- ## 서버 코드의 조회·전송 (0.3.0, [D-0061](../../docs/decisions/D-0061-realtime-namespaces.md))
110
+ ## Listing and sending from server code (0.3.0, [D-0061](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0061-realtime-namespaces.md))
96
111
 
97
- 연결 밖의 서버 코드가 tenant를 지정해 접속자를 읽고 보낼 수 있다. 허브의 `list`·`broadcast`·`kick`을 감싼 것이다(@dokebi/app의 `app.realtime(namespace)`가 이것을 쓴다).
112
+ Server code outside a connection can read and send to connections by tenant. It wraps the hub's `list`, `broadcast` and `kick` (`app.realtime(namespace)` of @dokebi/app uses it).
98
113
 
99
- - `list({ tenant | tenantPrefix, room?, member? })`: `tenant`면 허브에 묻고, `tenantPrefix`면 이 서버가 받은 presence(모든 서버)에서 읽는다(허브에는 tenant를 넘는 조회가 없다).
100
- - `send(filter, type, data?)`: defineSocket 방송과 같은 `{ type, data }` 텍스트 프레임. `broadcast(filter, bytes | text)`: 원시 바이트. 둘 다 많아야 한 번이고, 봉인 소켓에는 소켓마다 봉인되어 간다. `tenantPrefix`는 아는 tenant마다 허브 방송 하나를 보낸다. 영수증 `{ ids, recipients }`.
101
- - `kick(filter, code?, reason?)`, `onPresence(listener)`(모든 tenant의 입·퇴장, 실패는 error `PRESENCE_LISTENER_FAILED`).
102
- - 인증 결과의 `namespace` 필드는 @dokebi/app 몫이라 허브 등록 때 뺀다.
103
- - 자세한 규칙은 [AI.md](AI.md) §3a.
114
+ - `list({ tenant | tenantPrefix, room?, member? })`: with `tenant` it asks the hub; with `tenantPrefix` it reads the presence this server received (every server), since the hub has no lookup across tenants.
115
+ - `send(filter, type, data?)`: the same `{ type, data }` text frame as a defineSocket broadcast. `broadcast(filter, bytes | text)`: raw bytes. Both are at most once, and sealed sockets get a per-socket sealed copy. `tenantPrefix` sends one hub broadcast per known tenant. Receipt `{ ids, recipients }`.
116
+ - `kick(filter, code?, reason?)`, `onPresence(listener)` (joins and leaves of every tenant; failures are error `PRESENCE_LISTENER_FAILED`).
117
+ - The `namespace` field of the authentication result belongs to @dokebi/app and is removed when registering with the hub.
118
+ - Detailed rules are in [AI.md](AI.md) §3a.
104
119
 
105
- ## 호스트별 봉인 (0.3.0, [D-0059](../../docs/decisions/D-0059-seal-and-websocket-client.md) §4)
120
+ ## Sealing per host (0.3.0, [D-0059](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0059-seal-and-websocket-client.md) §4)
106
121
 
107
- 연결마다 모든 프레임을 봉인할 수 있다. 이 패키지는 알고리즘을 모르고, 이름 `dokebi-seal`로 찾는 코덱 제공자(@dokebi/seal 플러그인)가 연결별로 프레임을 바꾼다. 이 공개 패키지는 @dokebi/seal을 import하지 않는다(`optionalDependency({ name: 'dokebi-seal' })`로 구조적 계약 `SocketCodecProvider`만 찾는다).
122
+ Every frame of a connection can be sealed. This package does not know the algorithm; a codec provider found by the name `dokebi-seal` (the @dokebi/seal plugin) transforms frames per connection. This public package never imports @dokebi/seal (it looks up only the structural contract `SocketCodecProvider` with `optionalDependency({ name: 'dokebi-seal' })`).
108
123
 
109
- ```ts
124
+ ```ts snippet
110
125
  context.get(ws).route({
111
126
  path: '/ws',
112
- seal: (request) => request.headers.host === 'secure.example.com', // 또는 true. @dokebi/app은 domains.<host>.seal로 채운다
127
+ seal: (request) => request.headers.host === 'secure.example.com', // or true. @dokebi/app fills it from domains.<host>.seal
113
128
  authenticate, message,
114
129
  });
115
130
  ```
116
131
 
117
- - 봉인 라우트가 있는데 `dokebi-seal` 플러그인이 없으면 setup이 `SEAL_PROVIDER_MISSING`으로 실패한다.
118
- - 봉인 연결: 클라이언트가 서브프로토콜 `dokebi.seal`을 제안해야 한다(없으면 4415 `Seal required`). 서버는 봉인된 `{"$dokebi":"hello-v1"}`을 먼저 보내고, 들어오는 프레임을 연결의 순서 사슬 안에서 연 뒤 제어 프레임·라우트로 넘긴다. 열리지 않는 프레임(평문·바이너리·drift·재전송)은 4400 `Bad frame`이며 이유는 서버 warn 로그에만 남는다. 응답·presence·방송은 봉인되어 나가고, 방송은 평문 소켓이 버퍼 하나를 나눠 쓰는 그대로이며 봉인 소켓만 수신자마다 봉인한다. 바이너리는 보내지 않는다(`SEAL_BINARY_UNSUPPORTED`).
119
- - 협상: 봉인 다리가 있는 클라이언트는 `dokebi.seal`과 `dokebi.plain`(`PLAIN_PROTOCOL`)을 함께 제안한다. 봉인 연결은 `dokebi.seal`만 고르고(plain은 고르지 않음), 평문 연결은 `dokebi.plain`이 제안됐으면 그것을, 아니면 아무것도 고르지 않는다(옛 클라이언트 그대로). 그래서 다리를 준 페이지도 평문 호스트에서는 평문으로 돈다.
120
- - `sealDriftMs`(기본 60000): 프레임 시각 허용 차이. 재전송 nonce는 `hub.nonces()`(cluster면 Redis 공유)에 두 배 동안 남는다.
121
- - 자세한 규칙·로그·비용은 [AI.md](AI.md) §4a.
132
+ - When a sealed route exists but no `dokebi-seal` plugin does, setup fails with `SEAL_PROVIDER_MISSING`.
133
+ - Sealed connections: the client must offer the subprotocol `dokebi.seal` (otherwise 4415 `Seal required`). The server first sends a sealed `{"$dokebi":"hello-v1"}`, and opens incoming frames in the connection's order chain before passing them to control frames or the route. Frames that do not open (plain, binary, drift, replay) get 4400 `Bad frame`, with the reason only in the server warn log. A frame refused because the local replay nonce store is full of live nonces (fail closed, D-0075) closes with 1013 `Try again later` instead, so the client reconnects. Replies, presence and broadcasts go out sealed; plain sockets still share one broadcast buffer and only sealed sockets are sealed per recipient. Binary is not sent (`SEAL_BINARY_UNSUPPORTED`).
134
+ - Negotiation: clients with the seal bridge offer `dokebi.seal` and `dokebi.plain` (`PLAIN_PROTOCOL`) together. A sealed connection picks only `dokebi.seal` (never plain); a plain connection picks `dokebi.plain` when offered, otherwise nothing (old clients unchanged). So a page with the bridge still runs in plain on a plain host.
135
+ - `sealDriftMs` (default 60000): allowed frame time difference. Replay nonces stay in `hub.nonces()` (shared in Redis in cluster mode) for twice as long.
136
+ - Detailed rules, logs and costs are in [AI.md](AI.md) §4a.
@@ -0,0 +1,11 @@
1
+ import { DokebiError, type DokebiErrorOptions } from '@dokebi/core';
2
+ /** Codes of the errors this plugin throws (`WebsocketError`, `plugin: 'dokebi-websocket'`). */
3
+ export type WebsocketErrorCode = 'INVALID_ROUTE' | 'INVALID_ARGUMENT' | 'INVALID_FILTER' | 'INVALID_TARGET' | 'INVALID_TYPE' | 'INVALID_DATA' | 'FROZEN' | 'SEAL_PROVIDER_MISSING' | 'SEAL_PROVIDER_INVALID' | 'SEAL_BINARY_UNSUPPORTED' | 'SEAL_ENCODE_FAILED' | 'SOCKET_CLOSED' | 'SLOW_CONSUMER' | 'ROOM_FORBIDDEN' | 'BROADCAST_FAILED' | 'KICK_FAILED';
4
+ /**
5
+ * Errors of @dokebi/websocket; compare `code`, not the class (another installed copy may throw).
6
+ * A failed fan-out across tenants carries the first hub failure's code (for example RECOVERING)
7
+ * and `receipt`.
8
+ */
9
+ export declare class WebsocketError<TCode extends string = WebsocketErrorCode> extends DokebiError<TCode> {
10
+ constructor(code: TCode, message: string, options?: DokebiErrorOptions);
11
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,38 @@
1
+ import { DokebiError } from '@dokebi/core';
2
+ const FIX = {
3
+ INVALID_ROUTE: 'Give a websocket route a path starting with /, authenticate and message functions, origins as exact http(s) origins or "*", and seal as a boolean or a function (defineSocket builds one).',
4
+ INVALID_ARGUMENT: 'Pass a function to onPresence.',
5
+ INVALID_FILTER: 'Use { tenant } or { tenantPrefix } (exactly one), with room? and member?, strings of 1 to 256 bytes.',
6
+ INVALID_TARGET: 'A realtime namespace is 1 to 64 letters, digits, ., _ or -; a target is { tenant?, member?, room? }.',
7
+ INVALID_TYPE: 'Message types start with a letter: letters, digits, ., _, : or -, at most 64.',
8
+ INVALID_DATA: 'Send data that JSON.stringify accepts (no BigInt, no cycles).',
9
+ FROZEN: 'Register websocket routes during setup (dokebi-app sockets(), a plugin setup).',
10
+ SEAL_PROVIDER_MISSING: 'Register the dokebi-seal plugin (npx dokebi add @dokebi/seal), or remove seal from the route and the domains.',
11
+ SEAL_PROVIDER_INVALID: 'Register @dokebi/seal as the dokebi-seal plugin (it provides forConnection).',
12
+ SEAL_BINARY_UNSUPPORTED: 'Send text (UTF-8) on sealed sockets.',
13
+ SEAL_ENCODE_FAILED: 'Check the dokebi-seal plugin; the cause has the codec error.',
14
+ SOCKET_CLOSED: 'Send only while the connection is open; the client reconnects on its own.',
15
+ SLOW_CONSUMER: 'The client reads too slowly: send less, or raise maxBufferedBytes under dokebi-websocket in dokebi.yaml.',
16
+ ROOM_FORBIDDEN: 'Allow the room in the route authorizeRoom(identity, room).',
17
+ BROADCAST_FAILED: 'The cause lists the hub failures; the receipt has the tenants that worked.',
18
+ KICK_FAILED: 'The cause lists the hub failures; the receipt has the tenants that worked.',
19
+ };
20
+ const HINT = {
21
+ ROOM_FORBIDDEN: 'You cannot join this room.',
22
+ };
23
+ /**
24
+ * Errors of @dokebi/websocket; compare `code`, not the class (another installed copy may throw).
25
+ * A failed fan-out across tenants carries the first hub failure's code (for example RECOVERING)
26
+ * and `receipt`.
27
+ */
28
+ export class WebsocketError extends DokebiError {
29
+ constructor(code, message, options = {}) {
30
+ super(code, message, {
31
+ plugin: 'dokebi-websocket',
32
+ ...(Object.hasOwn(FIX, code) ? { fix: FIX[code] } : {}),
33
+ ...(Object.hasOwn(HINT, code) ? { hint: HINT[code] } : {}),
34
+ ...options,
35
+ });
36
+ this.name = 'WebsocketError';
37
+ }
38
+ }