@dokebi/websocket 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/AI.md CHANGED
@@ -1,106 +1,182 @@
1
- # AI 작업 안내 — @dokebi/websocket 0.2.0
1
+ # AI guide — @dokebi/websocket 0.4.0
2
2
 
3
- dokebi-web(Fastify) 위에 WebSocket 라우트를 열고 @dokebi/websocket-hub로 서버·워커 사이 방송·접속자 목록을 잇는다. 방송은 **많아야 한 번(at-most-once)** 이다: 허브가 내보내면 끝나고 클라이언트 ACK·재전송이 없다([D-0057](../../docs/decisions/D-0057-websocket-broadcast-without-ack.md)). 뷰·DB를 강제하지 않는다. Node >=24, core ^0.2.0, peer: @dokebi/web·@dokebi/websocket-hub. 세부는 [README](README.md)다.
3
+ Opens WebSocket routes on dokebi-web (Fastify) and connects broadcasts and the connection list across servers and workers through @dokebi/websocket-hub. A broadcast is **at most once**: once the hub sends it out it is done; there is no client ACK or resend ([D-0057](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0057-websocket-broadcast-without-ack.md)). No views or DB are forced. Node >=24, core ^0.4.0, peers: @dokebi/web, @dokebi/websocket-hub. Details are in the [README](README.md).
4
4
 
5
- ## 1. 설치
5
+ ## 1. Install
6
6
 
7
7
  ```sh
8
- # 프로세스 하나(fork 포함): 허브는 mode local(기본) — 메모리 안, 허브 서버·포트·Redis·NATS·secret 없음
8
+ # One process (forks included): the hub in mode local (default) — in memory, no hub server, port, Redis, NATS or secret
9
9
  npx dokebi add @dokebi/websocket-hub
10
10
  npx dokebi add @dokebi/websocket
11
11
 
12
- # 여러 프로세스·서버(node:cluster 워커 둘 이상): 순서 redis → nats(선택) → web → websocket-hub → websocket
13
- npx dokebi add @dokebi/websocket-hub --set mode=cluster --set namespace=shop --set serverId=web-1 --set redisConnection=main # secret은 dokebi.yaml에 직접 쓰는 것이 안전
12
+ # Several processes or servers (two or more node:cluster workers): order redis → nats (optional) → web → websocket-hub → websocket
13
+ npx dokebi add @dokebi/websocket-hub --set mode=cluster --set namespace=shop --set serverId=web-1 --set redisConnection=main # writing the secret directly in dokebi.yaml is safer
14
14
  ```
15
15
 
16
- 허브 사용 여부는 dokebi.yaml `options.dokebi-websocket-hub.mode`로 고른다. `local`(기본)은 같은 HubApi를 프로세스 안 메모리로 준다(허브 서버를 띄우지 않음). node:cluster 워커에서는 워커마다 접속자 목록이 갈라지므로 `HUB_LOCAL_IN_CLUSTER`로 거부한다. 워커가 하나뿐이면 `allowInCluster: true`로 허용한다. 여러 워커·서버가 방송을 나누려면 `cluster`.
16
+ > `npx dokebi` is the @dokebi/cli installed in the project (`dokebi init` adds it to devDependencies). The npm package named `dokebi` is not this CLI, so never run `npx -y dokebi`. Without a local install use `npx -y @dokebi/cli …`.
17
17
 
18
- ## 2. 설정 `options.dokebi-websocket`
18
+ The hub style is chosen in dokebi.yaml `options.dokebi-websocket-hub.mode`. `local` (default) offers the same HubApi in process memory (no hub server). In node:cluster workers each worker would have its own connection list, so the hub refuses with `LOCAL_IN_CLUSTER` (log code `HUB_LOCAL_IN_CLUSTER`). With a single worker, `allowInCluster: true` allows it. To share broadcasts across several workers or servers, use `cluster`.
19
19
 
20
- | 키 | 기본 | 뜻 |
21
- |---|---|---|
22
- | `maxPayload` | 65536 | 메시지 크기 |
23
- | `maxConnections` | 128 | 이 프로세스의 연결 수 |
24
- | `maxPendingMessages` | 32 | 연결별 대기 메시지(연결마다 순차 처리) |
25
- | `maxBufferedBytes` | 1048576 | 송신 버퍼. 넘으면 그 소켓을 1013 `Slow consumer`로 닫고 warn `WebSocket slow consumer closed`(code `SLOW_CONSUMER`)를 남김. 그 소켓에 쓰려던 응답은 버려진다(핸들러 실패로 세지 않음) |
26
- | `closeTimeoutMs` | 2000 | 소켓 종료 대기(업무 제한 아님) |
27
- | `heartbeatMs` | 10000 | ping/pong |
28
- | `idleTimeoutMs` | 0(끔) | 클라이언트가 이 시간 동안 아무것도 안 보내면 4408 `Idle`. 페이지가 `{"$dokebi":"ping-v1"}`을 주기적으로 보낸다 |
29
- | `hubWaitMs` | 5000 | 허브가 recovering일 때 업그레이드가 기다리는 시간(0이면 바로 503) |
20
+ ## 2. Configuration `options.dokebi-websocket`
30
21
 
31
- ## 3. 라우트 — defineSocket(권장)
22
+ | Key | Type | Default | Description |
23
+ |---|---|---|---|
24
+ | `maxPayloadBytes` | integer | 65536 | Message size |
25
+ | `maxConnections` | integer | 128 | Connections of this process |
26
+ | `maxPending` | integer | 32 | Waiting messages per connection (each connection runs in order) |
27
+ | `maxBufferedBytes` | integer | 1048576 | Send buffer. Beyond it the socket is closed with 1013 `Slow consumer` and warn `WebSocket slow consumer closed` (code `SLOW_CONSUMER`) is logged. Replies meant for that socket are dropped (not counted as handler failures) |
28
+ | `shutdownTimeoutMs` | integer ms | 2000 | Socket close wait at drain (not a limit on work) |
29
+ | `heartbeatMs` | integer ms | 10000 | ping/pong |
30
+ | `idleTimeoutMs` | integer ms | 0 (off) | Closes with 4408 `Idle` when the client sends nothing for this long. Pages send `{"$dokebi":"ping-v1"}` periodically |
31
+ | `hubWaitMs` | integer ms | 5000 | How long an upgrade waits while the hub is recovering (0 = 503 at once) |
32
+ | `sealDriftMs` | integer 1000–600000 | 60000 | Sealed connections (§4a): a frame whose ts differs from the server clock by more is 4400. Nonces are remembered for twice as long |
32
33
 
33
- ```ts
34
+ Keys renamed in 0.4.0 ([D-0071](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0071-option-vocabulary.md)). The old name is accepted with the warning `OPTION_DEPRECATED`; old and new together fail with `INVALID_OPTIONS`; 0.5.0 rejects it.
35
+
36
+ | Old key | New key |
37
+ |---|---|
38
+ | `maxPayload` | `maxPayloadBytes` |
39
+ | `maxPendingMessages` | `maxPending` |
40
+ | `closeTimeoutMs` | `shutdownTimeoutMs` |
41
+
42
+ ## 3. Routes — defineSocket (recommended)
43
+
44
+ ```ts snippet
34
45
  import { defineSocket } from '@dokebi/websocket';
35
46
 
36
47
  export const chatSocket = (app: AppContext) => defineSocket({
37
48
  path: '/ws',
38
- version: BUILD_VERSION, // 클라이언트 ?dokebiVersion=가 다르면 4426 Reload required
39
- origins: ['https://app.a.com'], // 생략하면 같은 Host만(다른 Origin은 403)
40
- async authenticate(request) { // 검증된 세션·토큰으로. 실패면 undefined → 401
49
+ version: BUILD_VERSION, // a different client ?dokebiVersion= gets 4426 Reload required
50
+ origins: ['https://app.a.com'], // omitted: same Host only (other Origins get 403)
51
+ async authenticate(request) { // from a verified session or token; undefined → 401
41
52
  const user = await sessions.verify(request);
42
53
  return user && { tenant: user.orgId, member: user.id, clientId: String(request.query.clientId) };
43
54
  },
44
55
  authorizeRoom: (identity, room) => rooms.canJoin(identity, room),
45
- presence: true, // 같은 tenant의 입·퇴장을 { type: 'presence', data } 로 받음
56
+ presence: true, // joins and leaves of the same tenant arrive as { type: 'presence', data }
46
57
  on: {
47
58
  'chat.send': async (data, socket) => {
48
59
  const { room, text } = data as { room: string; text: string };
49
60
  void socket.broadcast('chat.message', { from: socket.identity.member, text }, { room })
50
61
  .catch((error) => app.logger.log('warn', 'broadcast failed', { code: error.code }));
51
- return { accepted: true }; // 메시지에 id가 있으면 { type: 'reply', id, data }로 감
62
+ return { accepted: true }; // with an id in the message, sent as { type: 'reply', id, data }
52
63
  },
53
64
  },
54
65
  });
55
66
  ```
56
67
 
57
- - 메시지 형식: JSON `{ type, data?, id? }`. `reply`·`error`는 예약 type. 모르는 type은 `UNKNOWN_TYPE`, 잘못된 형식은 `INVALID_MESSAGE`, handler 오류는 오류의 `code`(대문자 형식) 또는 `HANDLER_FAILED`로 `{ type: 'error', id?, code }`(message·stack은 보내지 않고 서버 로그에 남김, §7).
58
- - `socket`: `session`·`identity`·`send(type, data)`(이 연결)·`broadcast(type, data, { room?, member? })`(허브로, tenant 고정 → receipt `{ id, recipients }`). 받는 소켓에는 `send`와 같은 `{ type, data }` 텍스트 프레임으로 간다.
59
- - 멀티 앱: @dokebi/app의 `sockets: (app) => [chatSocket(app)]`. 앱마다 같은 경로가 따로 등록되고 허브 tenant는 `<앱>:<tenant>`.
60
- - 저수준: `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?)`·`reportError?(error, details)`(§7).
61
-
62
- ## 4. 클라이언트가 할 일
63
-
64
- ```ts
65
- const clientId = sessionStorage.getItem('cid') ?? crypto.randomUUID(); // 탭마다 다르게(localStorage 공유 금지)
66
- sessionStorage.setItem('cid', clientId);
67
- const socket = new WebSocket(`/ws?clientId=${clientId}&dokebiVersion=${BUILD_VERSION}`);
68
- socket.onmessage = ({ data }) => handle(JSON.parse(data)); // 응답·방송 모두 { type, data } 텍스트
69
- socket.onopen = () => reloadState(); // 재접속하면 놓친 것은 서버에서 다시 읽는다
70
- setInterval(() => socket.send('{"$dokebi":"ping-v1"}'), 15000); // idleTimeoutMs를 쓸 때
71
- ```
68
+ - Message format: JSON `{ type, data?, id? }`. `reply` and `error` are reserved types. An unknown type is `UNKNOWN_TYPE`, a malformed message `INVALID_MESSAGE`, and a handler error answers `{ type: 'error', id?, code }` with the error's `code` (upper-case form) or `HANDLER_FAILED` (message and stack are not sent; they go to the server log, §7).
69
+ - `socket` (`SocketContext`): `session`, `identity`, `send(type, data)` (this connection), `broadcast(type, data, { room?, member? })` (through the hub, tenant fixed → receipt `{ id, recipients }`). Receiving sockets get the same `{ type, data }` text frame as `send`.
70
+ - Multi-app: `sockets: (app) => [chatSocket(app)]` of @dokebi/app. The same path is registered separately per app, and the hub tenant is `<namespace>:<tenant>` (the default namespace is the app name, D-0061). The `namespace` that `authenticate` returns is read and removed by @dokebi/app; this package leaves `namespace` out when it registers with the hub.
71
+ - Low level: `context.get(ws).route({ path, origins?, constraints?, version?, seal?, authenticate, authorizeRoom?, message(data, session), presence? })` (`WebsocketRoute`). session (`WebsocketSession`): `id`, `identity`, `send`, `broadcast(bytes, target?)`, `join(room)`, `leave(room)`, `close(code?, reason?)`, `reportError?(error, details)` (§7). `connections` is the number of open connections of this process, and `sealing` says whether a seal provider is registered.
72
+ - Exports: `createPlugin`, `defineSocket`, `options`, `WebsocketError`, `SEAL_PROTOCOL`, `PLAIN_PROTOCOL`, types `WebsocketApi`, `WebsocketOptions`, `WebsocketRoute`, `WebsocketSession`, `WebsocketIdentity`, `WebsocketPeer`, `WebsocketPresence`, `WebsocketErrorDetails`, `WebsocketConnectionInfo`, `WebsocketFilter`, `WebsocketReceipt`, `WebsocketKickReceipt`, `SocketDefinition`, `SocketContext`, `SocketHandler`, `SocketCodecProvider`, `SocketCodec`, `SocketCodecConnection`, `SocketNonceStore`, `WebsocketTransport`, `WebsocketNamespaceHandle`, `WebsocketNamespaceTarget`, `WebsocketErrorCode`.
72
73
 
73
- - 방송은 서버가 보낸 바이트 그대로 온다: UTF-8이면 텍스트 프레임(`defineSocket`의 `{ type, data }` JSON), 아니면 바이너리 프레임. 풀 봉투(`delivery-v1`)도 보낼 ACK도 없다. 브라우저 진입점 `@dokebi/websocket/client`(`DeliveryReceiver`)는 0.2.0에서 없어졌다(import하면 모듈을 찾지 못함). 표준 `WebSocket` API만 쓴다. 옛 페이지가 보내는 `{"$dokebi":"ack-v1"}`은 닫지 않고 무시한다(debug `ACK_IGNORED`).
74
- - 연결이 끊긴 사이·느린 소비자로 닫힌 사이의 방송은 다시 오지 않는다. 화면은 다시 연결되면 서버에서 최신 상태를 읽는다.
75
- - 닫힘 코드: 4426 새로고침, 4409 같은 clientId 중복(`Duplicate client`), 4408 idle, 1013 허브 불가·느린 소비자, 1012 서버 종료, 1011 handler 미처리 오류.
74
+ ## 3a. Sending and listing from server code (0.3.0, [D-0061](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0061-realtime-namespaces.md))
76
75
 
77
- ## 5. 응답 코드와 전달 의미
76
+ An API for code outside a connection (server code, jobs, admin apps) that names a tenant. @dokebi/app apps usually use `app.realtime(namespace)`, which wraps it.
78
77
 
79
- - 업그레이드: 출처 거부 403(`ORIGIN_FORBIDDEN`, authenticate 호출 안 함), 인증 실패 401, 허브 미준비·종료·용량 503 `{ error: 'UNAVAILABLE', reason: CLOSING | HUB_<상태> | CAPACITY }`, 일반 HTTP 426.
80
- - `broadcast`는 허브가 내보내면 receipt `{ id, recipients }`로 끝난다(D-0057). `recipients`는 보낸 시점에 조건에 맞은 연결이며 받았다는 확인이 아니다. 실패는 바로: `RECOVERING`(허브가 리더에 연결돼 있지 않음, 보내지 않음), `OUTCOME_UNKNOWN`(보낸 뒤 답 전에 끊김, 보내졌을 수 있음), `BUSY`(처리 중 방송이 허브 `maxPending`). 다시 보내지 않으며, 다시 보낼지는 handler가 정한다. 연결별 메시지는 순차 처리라 handler에서 await해도 리더 왕복 한 번(ms 단위)만 묶인다. 결과가 필요 없으면 `void ...catch()`.
81
- - **놓치면 안 되는 일(주문 상태·결제 결과)은 방송에 맡기지 않는다.** DB에 저장하고, 페이지는 다시 연결될 때 최신 상태를 읽는다. 방송은 「바뀌었으니 다시 읽어라」 알림으로 쓴다.
82
- - 방송 송신은 소켓마다 기다리지 않고 송신 큐에 넣는다(같은 소켓 순서 보장). 느린 소켓만 닫는다.
83
- - `send`는 원시 응답(현재 소켓)이다. 송신 버퍼에 들어가면 끝난다.
84
- - presence: 한 서버에서 처음 받은 변경은 이전부터 있던 연결을 joined로 담을 수 있다. 화면은 presence를 받으면 목록을 다시 읽는다.
85
-
86
- ## 6. 종료
87
-
88
- stop: 새 업무 차단 → 받은 handler·송신 중 방송 대기 → 1012로 닫기. core drain 기한이 지나면 남은 소켓을 끊는다. websocket drain이 web·hub drain보다 먼저 끝나고, 모든 drain 뒤 DB·허브가 닫힌다.
89
-
90
- ## 7. 로그(D-0047)
78
+ ```ts snippet
79
+ const ws = context.get(websocket);
80
+ await ws.list({ tenant: 'shop:t1' }); // asks the hub (whole cluster; fails with hub codes)
81
+ await ws.list({ tenantPrefix: 'shop:', room: 'vip' }); // presence this server received (every server; may lag a little)
82
+ await ws.send({ tenant: 'shop:t1', member: 'u42' }, 'chat.message', { text: 'hi' }); // { type, data } text
83
+ await ws.broadcast({ tenantPrefix: 'shop:' }, bytesOrText); // raw bytes (a text frame when UTF-8)
84
+ await ws.kick({ tenant: 'shop:t1', member: 'u42' }, 4403, 'Removed');
85
+ const stop = ws.onPresence(({ tenant, joined, left }) => {});
86
+ ```
91
87
 
92
- - 예외를 조용히 버리지 않는다. 닫힘 코드·오류 응답으로 바꾸는 것 외의 실패는 `error`: 고정 영어 메시지 + `code` + `error`(원본 오류 전문: 이름·메시지 전체·스택과 cause마다 `Caused by: …`, 주소·포트·errno 메시지도 그대로, URL 자격 증명만 `//***@`로 가림, 16KB 초과분만 잘라 표시). 예: handler 실패 `WebSocket message handler failed`(code는 오류의 code 또는 `HANDLER_FAILED`, 1011로 닫음), 소켓 오류 `SOCKET_ERROR`, 방송 쓰기 실패 `BROADCAST_WRITE_FAILED`, presence handler `PRESENCE_HANDLER_FAILED`, 허브 이벤트 끊김 `HUB_EVENTS_FAILED`(모든 소켓 1013), 정리 지연 `PRESENCE_CLEANUP_DEFERRED`. 등록 실패는 warn(4409·1013로 닫음), 느린 소비자는 warn `SLOW_CONSUMER`. 이미 닫힌 소켓에 못 쓴 응답·presence는 warn `REPLY_DROPPED`(클라이언트가 떠났을 뿐 서버 실패가 아님, 10초에 한 번 + `repeated`).
93
- - 메시지·소켓마다 도는 자리는 같은 메시지·code를 10초당 한 줄로 쓰고 나머지는 `repeated` 개수로 묶는다(drain 끝에 남은 개수도 씀). 본문·토큰은 쓰지 않는다.
94
- - debug: 연결·닫힘·업그레이드 거절, 허브 등록 ms, 방 입장·퇴장·거절, presence 변화(개수), kick, 방송 전달(ID·연결 수·`binary`, `isEnabled` 확인 뒤), 옛 클라이언트의 `ack-v1` 무시(`ACK_IGNORED`, 10초당 한 줄 + `repeated`), idle·heartbeat 종료, drain 시작·끝. 대기 메시지 초과(1013 `Too many messages`)는 warn `TOO_MANY_MESSAGES`.
95
- - `defineSocket`의 handler 오류: 클라이언트에는 지금처럼 `{ type: 'error', id?, code }`만 가고(message·stack 없음, 소켓은 열린 채), 서버 로그에는 error `WebSocket handler failed.`(code `SOCKET_HANDLER_FAILED`, `type`=메시지 type, `reply`=클라이언트에 보낸 code, `connection`, `error`=전문)가 남는다. 반복은 type+reply code마다 10초당 한 줄. 잘못된 형식·모르는 type(클라이언트 잘못)은 debug `WebSocket client message refused`(code `INVALID_MESSAGE`·`UNKNOWN_TYPE`, code마다 세어 묶음).
96
- - 이 보고는 `session.reportError?(error, { source: 'handler' | 'client', code, type? })`로 간다. 게이트웨이가 만든 session에만 있고, 직접 만든 session(시험 등)에 없으면 `defineSocket`은 응답만 보낸다. 저수준 `route.message`도 같은 메서드로 보고할 수 있다.
88
+ - Filter (`WebsocketFilter`): **exactly one** of `tenant` and `tenantPrefix`, plus `room?` and `member?` (both: that person in that room). Strings of 1–256 bytes. Otherwise `INVALID_FILTER`. The `send` type follows the handler type rules (`INVALID_TYPE`); data that is not JSON is `INVALID_DATA`.
89
+ - `tenant`: one hub call; failures keep the hub code (`RECOVERING`, `BUSY`, `OUTCOME_UNKNOWN`). `tenantPrefix`: the hub has no lookup across tenants, so the tenants matching the prefix are collected from this server's presence mirror and called per tenant (16 at a time). When some fail it rejects with the first failure's code and attaches `receipt` (the successful tenants' part) and `cause` (an AggregateError). With no known tenant nothing is sent and it returns `{ ids: [], recipients: [] }`.
90
+ - Receipt `{ ids, recipients }`: the hub broadcast id per tenant and the connections matching at that moment. Not a delivery confirmation (D-0057). kick (close code 4000–4999, default 4403) returns `{ ids }`.
91
+ - Sealing: it uses the broadcast delivery path as is, so sealed sockets get a per-socket sealed copy and plain sockets share one buffer. Binary is never sent to sealed sockets (§4a).
92
+ - `onPresence`: joins and leaves of every server per tenant (the same meaning as route `presence`; a server seen for the first time may list existing connections as joined). A listener that throws or rejects is logged as error `PRESENCE_LISTENER_FAILED` (one line per 10 seconds) and the other listeners keep running.
93
+ - debug: `WebSocket connections listed` (source `hub` or `presence`, count, ms), `WebSocket server broadcast sent` (tenants, failures, recipients, bytes), `WebSocket server kick sent`, `WebSocket presence listener added/removed`, and `listeners` on presence change logs.
97
94
 
98
- ## 8. 주의 사항
95
+ ## 4. What the client does
99
96
 
100
- - 쿠키 인증 라우트에 `origins: '*'`를 쓰지 않는다(Cross-Site WebSocket Hijacking). 프락시가 Host를 바꾸면 web `trustProxy`를 맞추거나 공개 출처를 `origins`에 적는다.
101
- - 헤더 값을 그대로 신원으로 믿는 예제(예제 23)는 테스트 전용이다.
102
- - `hub.events`는 이 플러그인이 단독 소비한다. 다른 코드가 읽지 않는다.
103
- - 방송은 많아야 한 번이다. 재접속·리더 교체·느린 소비자에서는 빠질 수 있고, `OUTCOME_UNKNOWN` 뒤에 다시 보내면 두 번 받을 수 있다.
104
- - 실제 두 컨테이너·네 워커 교차 전달, 허브 SIGKILL, NATS 장애 검증은 했지만 두 물리 장비·WAN 검증은 아니다(OPS-002).
97
+ ```ts snippet
98
+ const clientId = sessionStorage.getItem('cid') ?? crypto.randomUUID(); // different per tab (never shared via localStorage)
99
+ sessionStorage.setItem('cid', clientId);
100
+ const socket = new WebSocket(`/ws?clientId=${clientId}&dokebiVersion=${BUILD_VERSION}`);
101
+ socket.onmessage = ({ data }) => handle(JSON.parse(data)); // replies and broadcasts are both { type, data } text
102
+ socket.onopen = () => reloadState(); // after reconnecting, read what was missed from the server
103
+ setInterval(() => socket.send('{"$dokebi":"ping-v1"}'), 15000); // when idleTimeoutMs is used
104
+ ```
105
105
 
106
- 근거: `examples/23-websocket`(두 Docker 서버·네 워커), `examples/25-playground`(앱별 소켓·presence·부하 시험), D-0024·D-0033·D-0034·D-0057(D-0025의 ACK를 대체).
106
+ - Broadcasts arrive as the bytes the server sent: a text frame when UTF-8 (`defineSocket`'s `{ type, data }` JSON), otherwise a binary frame. There is no envelope to unwrap (`delivery-v1`) and no ACK to send. The browser entry `@dokebi/websocket/client` (`DeliveryReceiver`) was removed in 0.2.0 (importing it fails to resolve). Use only the standard `WebSocket` API. The `{"$dokebi":"ack-v1"}` that old pages send is ignored, not closed (debug `ACK_IGNORED`).
107
+ - Broadcasts sent while disconnected or while closed as a slow consumer never come again. The screen reads the latest state from the server after reconnecting.
108
+ - Close codes: 4426 reload, 4409 duplicate clientId (`Duplicate client`), 4408 idle, 1013 hub unavailable or slow consumer, 1012 server shutting down, 1011 unhandled handler error, 4415 sealed host but no `dokebi.seal` offered, 4400 sealed frame refused (§4a). 4400 and 4415 repeat on reconnect, so do not reconnect.
109
+
110
+ ## 4a. Sealed connections (0.3.0, [D-0059](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0059-seal-and-websocket-client.md) §4)
111
+
112
+ Every frame is sealed per host (or route). **This package does not know the seal**: a codec provider found by the name `dokebi-seal` (the @dokebi/seal plugin) transforms frames per connection. The public package never imports @dokebi/seal.
113
+
114
+ - Turning it on: with @dokebi/app, `options.dokebi-app.domains.<host>.seal: true` (the app fills `route.seal`). Without the app: `route({ seal: true | (request) => boolean })` or `defineSocket({ seal })`. When a sealed route exists but no `dokebi-seal` plugin is registered, setup fails with `SEAL_PROVIDER_MISSING` (fail closed). `api.sealing` is true when the provider exists.
115
+ - Contract (shape only): `SocketCodecProvider { forConnection({ host, path, userAgent, nonces, driftMs }): SocketCodec }`, `SocketCodec { decode(frame): Promise<string>; encode(text): string; hello(): string }`. `host` is the web `requestHost` (with trustProxy applied) in lower case without the port, `path` the upgrade path (no query), `nonces` is `hub.nonces()` (cluster = shared in Redis, local = in process), `driftMs` is `sealDriftMs`.
116
+ - Negotiation: a client with the seal bridge offers the subprotocols `['dokebi.seal', 'dokebi.plain']` (constants `SEAL_PROTOCOL`, `PLAIN_PROTOCOL`). A sealed connection picks only `dokebi.seal` (never plain). When it is not offered, the connection is closed after the upgrade with **4415** `Seal required` (no reconnect). A plain connection picks `dokebi.plain` when offered, otherwise nothing (old clients). Clients decide sealing only by `ws.protocol === 'dokebi.seal'`, so the same page code runs in plain on a plain host.
117
+ - Flow: the server first sends a sealed `{"$dokebi":"hello-v1"}` (the client measures clock offset from its ts). Incoming frames are opened in the connection's order chain, then go to control frames (`$dokebi` ping, ack) or the route (counted in waiting messages). Routes and handlers see plain text.
118
+ - Refusal: unsealed frames, binary frames, frames that fail to open, drift and replays get **4400** `Bad frame`. The reason (`no-prefix`, `plain-rejected`, `drift`, `replay`, `open-failed`, `binary`) goes only to the warn log, never to the client (so replay success cannot be probed). After a refusal no further frames of that connection are read.
119
+ - Outgoing: replies, `send`, presence and broadcasts are all sealed. Plain sockets share one broadcast buffer; only sealed sockets are sealed per recipient. UTF-8 bytes are sealed as text; `send` of non-UTF-8 bytes is refused with `SEAL_BINARY_UNSUPPORTED` (in `defineSocket`, an error reply with that code). Binary broadcasts are not sent to sealed sockets and are counted (warn `SEAL_BINARY_UNSUPPORTED`, `dropped`).
120
+ - Cost (2026-10-15, `benchmarks/results/2026-10-15-websocket-seal.json`): one seal plus open about 15–17 µs (1 KB), a broadcast to 500 recipients p50 about 14.5 ms (plain 1.6 ms), a request round trip with a Redis nonce p50 0.38 ms (plain 0.04 ms).
121
+
122
+ ## 5. Response codes and delivery semantics
123
+
124
+ - Upgrade: origin refused 403 (`ORIGIN_FORBIDDEN`; authenticate is not called), authentication failure 401, hub not ready, shutting down or at capacity 503 `{ error: 'UNAVAILABLE', reason: CLOSING | HUB_<state> | CAPACITY }`, a plain HTTP request 426.
125
+ - `broadcast` ends with the receipt `{ id, recipients }` once the hub sends it out (D-0057). `recipients` are the connections matching when it was sent, not a confirmation of receipt. Failures come at once: `RECOVERING` (the hub is not connected to the leader; not sent), `OUTCOME_UNKNOWN` (disconnected after sending, before the answer; it may have been sent), `BUSY` (broadcasts in progress reached the hub's `maxPending`). Nothing is resent; the handler decides whether to send again. Messages per connection run in order, so awaiting in a handler holds only one leader round trip (milliseconds). When the result is not needed, use `void ...catch()`.
126
+ - **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 when it reconnects. Use broadcasts as "it changed, read again" notices.
127
+ - Sending a broadcast does not wait per socket; it goes into the send queue (order kept per socket). Only slow sockets are closed.
128
+ - `send` is a raw reply (current socket). It is done once it is in the send buffer.
129
+ - presence: the first change one server receives may list connections that existed before as joined. Screens read the list again when presence arrives.
130
+
131
+ ## 6. Shutdown
132
+
133
+ stop: block new work → wait for received handlers and broadcasts being sent → close with 1012. When core's drain deadline passes, remaining sockets are cut. The websocket drain finishes before the web and hub drains, and the DB and hub close after every drain.
134
+
135
+ ## 7. Logs ([D-0047](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0047-logging-and-no-silent-errors.md))
136
+
137
+ - Exceptions are never dropped silently. Failures other than those turned into close codes or error replies are `error`: a fixed English message + `code` + `error` (the full original error: name, whole message, stack and `Caused by: …` for each cause, address, port and errno text included; only URL credentials masked as `//***@`; cut only beyond 16 KB). Examples: handler failure `WebSocket message handler failed` (code from the error or `HANDLER_FAILED`, closed with 1011), socket error `SOCKET_ERROR`, broadcast write failure `BROADCAST_WRITE_FAILED`, presence handler `PRESENCE_HANDLER_FAILED`, lost hub events `HUB_EVENTS_FAILED` (every socket 1013), delayed cleanup `PRESENCE_CLEANUP_DEFERRED`. Registration failures are warn (closed with 4409 or 1013), slow consumers warn `SLOW_CONSUMER`. A reply or presence that could not be written to an already closed socket is warn `REPLY_DROPPED` (the client simply left; not a server failure; once per 10 seconds + `repeated`).
138
+ - Places that run per message or socket write the same message and code once per 10 seconds and group the rest as a `repeated` count (the remaining count is written at drain end too). Bodies and tokens are never logged.
139
+ - Sealing (§4a): a refused frame is warn `WebSocket sealed frame refused; closed` (code `SEAL_FRAME_REFUSED`, `reason`, `error`; one line per reason per 10 seconds + `repeated`), codec creation failure error `SEAL_CODEC_FAILED` (1011), broadcast seal failure error `SEAL_ENCODE_FAILED` (1011), hello send failure warn `SEAL_HELLO_FAILED`. debug: provider present (`WebSocket seal provider`), the decision per upgrade (`WebSocket seal decision`: path, sealed, offered), `WebSocket seal hello sent`, 4415 (`WebSocket seal required; closed`), `sealed` on connection logs, the `sealed` count on broadcast logs.
140
+ - debug: connect, close, refused upgrades, hub registration ms, room join, leave and refusal, presence changes (counts), kick, broadcast delivery (ID, connection count, `binary`; after checking `isEnabled`), ignored `ack-v1` from old clients (`ACK_IGNORED`, one line per 10 seconds + `repeated`), idle and heartbeat closes, drain start and end. Too many waiting messages (1013 `Too many messages`) is warn `TOO_MANY_MESSAGES`.
141
+ - `defineSocket` handler errors: the client still gets only `{ type: 'error', id?, code }` (no message or stack; the socket stays open), and the server logs error `WebSocket handler failed.` (code `SOCKET_HANDLER_FAILED`, `type` = message type, `reply` = the code sent to the client, `connection`, `error` = full text). Repeats are one line per type + reply code per 10 seconds. Malformed messages and unknown types (client mistakes) are debug `WebSocket client message refused` (code `INVALID_MESSAGE` or `UNKNOWN_TYPE`, counted and grouped per code).
142
+ - This report goes through `session.reportError?(error, { source: 'handler' | 'client', code, type? })`. Only sessions the gateway created have it; with a hand-made session (tests and the like) `defineSocket` only sends the reply. A low-level `route.message` can report through the same method.
143
+
144
+ ## 7a. Realtime transport contribution and errors (D-0063)
145
+
146
+ - This plugin contributes the `websocket` transport to the point `dokebi-web:realtime` of @dokebi/web: `mount(route, scope)` (attaches app and module routes with the scope's path, constraints, seal rule and tenant rule) and `handle(namespace)` (`list`, `send`, `kick`, `onPresence` with the `<namespace>:` prefix added, and removed from results). @dokebi/app collects it to handle `sockets` and `app.realtime(ns)` (types `WebsocketTransport`, `WebsocketNamespaceHandle`).
147
+ - When a `defineSocket` handler throws a Dokebi error (`DokebiError`, or the same shape with `plugin`), the error reply also carries `message` and `hint`, and outside production (`NODE_ENV=production`) `fix` too ([D-0063](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0063-core-primitives.md) §1). Other errors still send only `code`.
148
+ - Options are a `defineOptions` declaration in `src/options.ts`, and the build generates `options.schema.json`. Invalid options are core `INVALID_PLUGIN_OPTIONS` (cause `INVALID_OPTIONS`, with paths).
149
+
150
+ ## 8. Errors
151
+
152
+ <!-- docs-check: complete-error-codes WebsocketErrorCode -->
153
+ `WebsocketError` (`plugin: 'dokebi-websocket'`, `fix`):
154
+
155
+ | Code | When |
156
+ |---|---|
157
+ | `INVALID_ROUTE` | A wrong route definition (path, authenticate, message, origins, seal, `defineSocket` arguments) |
158
+ | `INVALID_ARGUMENT` | A non-function passed to `onPresence` |
159
+ | `INVALID_FILTER` | A server call filter that is not exactly one of `{ tenant }` and `{ tenantPrefix }`, or a string outside 1–256 bytes |
160
+ | `INVALID_TARGET` | A wrong namespace or target for the transport `handle` |
161
+ | `INVALID_TYPE` | The type format of `send` |
162
+ | `INVALID_DATA` | `send` data that is not JSON, `broadcast` data that is not a string or Uint8Array |
163
+ | `FROZEN` | `route` outside setup |
164
+ | `SEAL_PROVIDER_MISSING` | A sealed route without dokebi-seal |
165
+ | `SEAL_PROVIDER_INVALID` | dokebi-seal does not provide `forConnection` |
166
+ | `SEAL_BINARY_UNSUPPORTED` | Non-UTF-8 bytes to a sealed socket |
167
+ | `SEAL_ENCODE_FAILED` | Sealing a frame failed (`cause`) |
168
+ | `SOCKET_CLOSED` | `send` to a closed socket |
169
+ | `SLOW_CONSUMER` | The send buffer would exceed `maxBufferedBytes` |
170
+ | `ROOM_FORBIDDEN` | `authorizeRoom` did not allow the room (with `hint`) |
171
+ | `BROADCAST_FAILED` | Part of a `tenantPrefix` broadcast failed without a hub code (`receipt`, `cause`) |
172
+ | `KICK_FAILED` | Part of a `tenantPrefix` kick failed without a hub code (`receipt`, `cause`) |
173
+
174
+ ## 9. Cautions
175
+
176
+ - Never use `origins: '*'` on a cookie-authenticated route (Cross-Site WebSocket Hijacking). When a proxy rewrites Host, set web `trustProxy` accordingly or list the public origin in `origins`.
177
+ - Examples that trust a header value as the identity (example 23) are for tests only.
178
+ - `hub.events` is consumed only by this plugin. No other code reads it.
179
+ - Broadcasts are at most once. They can be missed across reconnects, leader changes and slow consumers, and resending after `OUTCOME_UNKNOWN` can deliver twice.
180
+ - Cross delivery between two real containers and four workers, a hub SIGKILL and NATS faults were verified, but not two physical machines or a WAN (OPS-002).
181
+
182
+ Evidence: `examples/23-websocket` (two Docker servers, four workers), `examples/25-playground` (per-app sockets, presence, load test), D-0024, D-0033, D-0034, D-0057 (replacing the ACK of D-0025), D-0059 §4 (sealing — real server tests and the Chromium check live in @dokebi/seal: `npm run seal:test`, `seal:browser-check`).
package/README.md CHANGED
@@ -1,21 +1,21 @@
1
1
  # @dokebi/websocket
2
2
 
3
- Node >=24, 0.2.0. Dokebi Fastify 웹과 websocket-hub를 연결하는 선택 플러그인. API 서버에 템플릿/뷰를 강제하지 않는다.
3
+ Node >=24, version 0.4.0 (unpublished). 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,69 +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 |
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.
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.
103
+
104
+ ## Route constraints and the message router (D-0030)
105
+
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.
109
+
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))
111
+
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).
88
113
 
89
- ## 라우트 제약과 메시지 라우터 (D-0030)
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.
119
+
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)
121
+
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' })`).
123
+
124
+ ```ts snippet
125
+ context.get(ws).route({
126
+ path: '/ws',
127
+ seal: (request) => request.headers.host === 'secure.example.com', // or true. @dokebi/app fills it from domains.<host>.seal
128
+ authenticate, message,
129
+ });
130
+ ```
90
131
 
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을 캡슐화 없이 등록해 그 훅이 모든 업그레이드에 적용되게 했다.
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. 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
+ }