@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/AI.md CHANGED
@@ -1,141 +1,183 @@
1
- # AI 작업 안내 — @dokebi/websocket 0.3.0
1
+ # AI guide — @dokebi/websocket 0.4.1
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) |
30
- | `sealDriftMs` | 60000 | 봉인 연결(§4a): 프레임 ts가 서버 시계와 이만큼(1000~600000) 넘게 다르면 4400. nonce는 두 배 동안 기억 |
20
+ ## 2. Configuration `options.dokebi-websocket`
31
21
 
32
- ## 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); also bounds its waiting presence calls, separately |
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 |
33
33
 
34
- ```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
35
45
  import { defineSocket } from '@dokebi/websocket';
36
46
 
37
47
  export const chatSocket = (app: AppContext) => defineSocket({
38
48
  path: '/ws',
39
- version: BUILD_VERSION, // 클라이언트 ?dokebiVersion=가 다르면 4426 Reload required
40
- origins: ['https://app.a.com'], // 생략하면 같은 Host만(다른 Origin은 403)
41
- 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
42
52
  const user = await sessions.verify(request);
43
53
  return user && { tenant: user.orgId, member: user.id, clientId: String(request.query.clientId) };
44
54
  },
45
55
  authorizeRoom: (identity, room) => rooms.canJoin(identity, room),
46
- presence: true, // 같은 tenant의 입·퇴장을 { type: 'presence', data } 로 받음
56
+ presence: true, // joins and leaves of the same tenant arrive as { type: 'presence', data }
47
57
  on: {
48
58
  'chat.send': async (data, socket) => {
49
59
  const { room, text } = data as { room: string; text: string };
50
60
  void socket.broadcast('chat.message', { from: socket.identity.member, text }, { room })
51
61
  .catch((error) => app.logger.log('warn', 'broadcast failed', { code: error.code }));
52
- return { accepted: true }; // 메시지에 id가 있으면 { type: 'reply', id, data }로 감
62
+ return { accepted: true }; // with an id in the message, sent as { type: 'reply', id, data }
53
63
  },
54
64
  },
55
65
  });
56
66
  ```
57
67
 
58
- - 메시지 형식: JSON `{ type, data?, id? }`. `reply`·`error`는 예약 type. 모르는 type은 `UNKNOWN_TYPE`, 잘못된 형식은 `INVALID_MESSAGE`, handler 오류는 오류의 `code`(대문자 형식) 또는 `HANDLER_FAILED`로 `{ type: 'error', id?, code }`(message·stack은 보내지 않고 서버 로그에 남김, §7).
59
- - `socket`: `session`·`identity`·`send(type, data)`(이 연결)·`broadcast(type, data, { room?, member? })`(허브로, tenant 고정 → receipt `{ id, recipients }`). 받는 소켓에는 `send`와 같은 `{ type, data }` 텍스트 프레임으로 간다.
60
- - 멀티 앱: @dokebi/app의 `sockets: (app) => [chatSocket(app)]`. 앱마다 같은 경로가 따로 등록되고 허브 tenant는 `<네임스페이스>:<tenant>`(기본 네임스페이스는 앱 이름, D-0061). `authenticate`가 돌려주는 `namespace`는 @dokebi/app이 읽고 지운다. 이 패키지는 허브에 등록할 때 `namespace`를 빼고 넘긴다.
61
- - 저수준: `context.get(ws).route({ path, origins?, constraints?, version?, seal?, authenticate, authorizeRoom?, message(data, session), presence? })`. session: `id`·`identity`·`send`·`broadcast(bytes, target?)`·`join(room)`·`leave(room)`·`close(code?, reason?)`·`reportError?(error, details)`(§7).
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`.
62
73
 
63
- ## 3a. 서버 코드에서 보내기·조회 (0.3.0, [D-0061](../../docs/decisions/D-0061-realtime-namespaces.md))
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))
64
75
 
65
- 연결 밖(서버 코드·작업·관리자 앱)에서 tenant를 지정해 쓰는 API. @dokebi/app 앱은 보통 이것을 감싼 `app.realtime(namespace)`를 쓴다.
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.
66
77
 
67
- ```ts
78
+ ```ts snippet
68
79
  const ws = context.get(websocket);
69
- await ws.list({ tenant: 'shop:t1' }); // 허브에 묻는다(클러스터 전체, 허브 code로 실패)
70
- await ws.list({ tenantPrefix: 'shop:', room: 'vip' }); // 이 서버가 받은 presence(모든 서버, 조금 늦을 수 있음)
71
- await ws.send({ tenant: 'shop:t1', member: 'u42' }, 'chat.message', { text: 'hi' }); // { type, data } 텍스트
72
- await ws.broadcast({ tenantPrefix: 'shop:' }, bytesOrText); // 원시 바이트(UTF-8이면 텍스트 프레임)
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)
73
84
  await ws.kick({ tenant: 'shop:t1', member: 'u42' }, 4403, 'Removed');
74
85
  const stop = ws.onPresence(({ tenant, joined, left }) => {});
75
86
  ```
76
87
 
77
- - 필터: `tenant`와 `tenantPrefix` 중 **정확히 하나**, 더해 `room?`·`member?`(둘 다면 그 방의 그 사람). 문자열 1~256바이트. 어기면 `INVALID_FILTER`. `send`의 type은 handler type 규칙(`INVALID_TYPE`), JSON이 안 되는 data는 `INVALID_DATA`.
78
- - `tenant`: 허브 호출 하나. 실패는 허브 code 그대로(`RECOVERING`·`BUSY`·`OUTCOME_UNKNOWN`). `tenantPrefix`: 허브에는 tenant를 넘는 조회가 없으므로 이 서버의 presence 거울에서 접두가 맞는 tenant를 모아 tenant마다 호출한다(16개씩 동시). 일부가 실패하면 첫 실패의 code로 거부하고 오류에 `receipt`(성공한 tenant 몫)와 `cause`(AggregateError)를 단다. 아는 tenant가 없으면 아무것도 보내지 않고 `{ ids: [], recipients: [] }`.
79
- - 영수증 `{ ids, recipients }`: tenant마다 허브 방송 id, 그때 조건에 맞은 연결. 받았다는 확인이 아니다(D-0057). kick은 `{ ids }`.
80
- - 봉인: 방송 전달 경로 그대로라 봉인 소켓은 소켓마다 봉인된 사본을, 평문 소켓은 같은 버퍼를 받는다. 바이너리는 봉인 소켓에 가지 않는다(§4a).
81
- - `onPresence`: 모든 서버의 입·퇴장을 tenant마다(route `presence`와 같은 의미, 처음 보는 서버는 이미 있던 연결을 joined로 담을 수 있음). 던지거나 거부한 listener는 error `PRESENCE_LISTENER_FAILED`(10초당 한 줄)로 남고 다른 listener는 계속 돈다.
82
- - debug: `WebSocket connections listed`(source `hub`·`presence`, 수, ms), `WebSocket server broadcast sent`(tenant 수·실패 수·recipients·bytes), `WebSocket server kick sent`, `WebSocket presence listener added/removed`, presence 변화 로그의 `listeners`.
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.
83
94
 
84
- ## 4. 클라이언트가 할 일
95
+ ## 4. What the client does
85
96
 
86
- ```ts
87
- const clientId = sessionStorage.getItem('cid') ?? crypto.randomUUID(); // 탭마다 다르게(localStorage 공유 금지)
97
+ ```ts snippet
98
+ const clientId = sessionStorage.getItem('cid') ?? crypto.randomUUID(); // different per tab (never shared via localStorage)
88
99
  sessionStorage.setItem('cid', clientId);
89
100
  const socket = new WebSocket(`/ws?clientId=${clientId}&dokebiVersion=${BUILD_VERSION}`);
90
- socket.onmessage = ({ data }) => handle(JSON.parse(data)); // 응답·방송 모두 { type, data } 텍스트
91
- socket.onopen = () => reloadState(); // 재접속하면 놓친 것은 서버에서 다시 읽는다
92
- setInterval(() => socket.send('{"$dokebi":"ping-v1"}'), 15000); // idleTimeoutMs를 쓸 때
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
93
104
  ```
94
105
 
95
- - 방송은 서버가 보낸 바이트 그대로 온다: 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`).
96
- - 연결이 끊긴 사이·느린 소비자로 닫힌 사이의 방송은 다시 오지 않는다. 화면은 다시 연결되면 서버에서 최신 상태를 읽는다.
97
- - 닫힘 코드: 4426 새로고침, 4409 같은 clientId 중복(`Duplicate client`), 4408 idle, 1013 허브 불가·느린 소비자, 1012 서버 종료, 1011 handler 미처리 오류, 4415 봉인 호스트인데 `dokebi.seal` 제안 없음, 4400 봉인 프레임 거절(§4a). 4400·4415는 다시 붙어도 같으므로 재접속하지 않는다.
98
-
99
- ## 4a. 봉인 연결 (0.3.0, [D-0059](../../docs/decisions/D-0059-seal-and-websocket-client.md) §4)
100
-
101
- 호스트(또는 라우트)마다 모든 프레임을 봉인한다. **이 패키지는 봉인을 모른다**: 이름 `dokebi-seal`로 찾는 코덱 제공자(@dokebi/seal 플러그인)가 연결마다 프레임을 바꾼다. 공개 패키지는 @dokebi/seal을 import하지 않는다.
102
-
103
- - 켜기: @dokebi/app이면 `options.dokebi-app.domains.<host>.seal: true`(앱이 route.seal을 채운다). 앱 없이: `route({ seal: true | (request) => boolean })`·`defineSocket({ seal })`. 봉인 라우트가 있는데 `dokebi-seal` 플러그인이 등록돼 있지 않으면 setup이 `SEAL_PROVIDER_MISSING`으로 실패한다(fail closed). `api.sealing`은 제공자가 있으면 true.
104
- - 계약(구조만): `SocketCodecProvider { forConnection({ host, path, userAgent, nonces, driftMs }): SocketCodec }`, `SocketCodec { decode(frame): Promise<string>; encode(text): string; hello(): string }`. `host`는 web `requestHost`(trustProxy 반영)에서 포트를 뺀 소문자, `path`는 업그레이드 경로(질의 제외), `nonces`는 `hub.nonces()`(cluster = Redis 공유, local = 프로세스), `driftMs`는 `sealDriftMs`.
105
- - 협상: 봉인 다리가 있는 클라이언트는 서브프로토콜 `['dokebi.seal', 'dokebi.plain']`(상수 `SEAL_PROTOCOL`·`PLAIN_PROTOCOL`)을 제안한다. 봉인 연결은 `dokebi.seal`만 고른다(plain은 절대 고르지 않음). 그것이 제안에 없으면 업그레이드 뒤 **4415** `Seal required`(재접속 안 함). 평문 연결은 `dokebi.plain`이 제안됐으면 그것을, 아니면 아무것도 고르지 않는다(옛 클라이언트). 클라이언트는 `ws.protocol === 'dokebi.seal'`로만 봉인을 판단하므로 같은 페이지 코드가 평문 호스트에서는 평문으로 돈다.
106
- - 흐름: 서버가 맨 먼저 봉인된 `{"$dokebi":"hello-v1"}`을 보낸다(클라이언트는 그 ts로 시계 차이를 잡는다). 들어오는 프레임은 연결의 순서 사슬 안에서 열린 뒤 제어 프레임(`$dokebi` ping·ack)·라우트로 간다(대기 메시지 수에 포함). 라우트·handler는 평문 텍스트를 본다.
107
- - 거절: 봉인 안 된 프레임·바이너리 프레임·열지 못함·drift·재전송은 **4400** `Bad frame`. 이유(`no-prefix`·`plain-rejected`·`drift`·`replay`·`open-failed`·`binary`)는 warn 로그에만 남고 클라이언트에는 가지 않는다(재전송 성공 여부를 엿보지 못하게). 거절 뒤 그 연결의 프레임은 읽지 않는다.
108
- - 내보내기: 응답·`send`·presence·방송 모두 봉인. 평문 소켓은 방송 버퍼 하나를 나눠 쓰고 봉인 소켓만 수신자마다 봉인한다. UTF-8 바이트는 텍스트로 봉인해 보내고, UTF-8이 아닌 바이트를 `send`하면 `SEAL_BINARY_UNSUPPORTED`로 거절(`defineSocket`에서는 그 code의 오류 응답). 바이너리 방송은 봉인 소켓에 보내지 않고 센다(warn `SEAL_BINARY_UNSUPPORTED`, `dropped`).
109
- - 비용(2026-10-15, `benchmarks/results/2026-10-15-websocket-seal.json`): 봉인·해제 1회 약 15~17µs(1KB), 수신자 500 방송 p50 약 14.5ms(평문 1.6ms), Redis nonce 붙은 요청 왕복 p50 0.38ms(평문 0.04ms).
110
-
111
- ## 5. 응답 코드와 전달 의미
112
-
113
- - 업그레이드: 출처 거부 403(`ORIGIN_FORBIDDEN`, authenticate 호출 안 함), 인증 실패 401, 허브 미준비·종료·용량 503 `{ error: 'UNAVAILABLE', reason: CLOSING | HUB_<상태> | CAPACITY }`, 일반 HTTP 426.
114
- - `broadcast`는 허브가 내보내면 receipt `{ id, recipients }`로 끝난다(D-0057). `recipients`는 보낸 시점에 조건에 맞은 연결이며 받았다는 확인이 아니다. 실패는 바로: `RECOVERING`(허브가 리더에 연결돼 있지 않음, 보내지 않음), `OUTCOME_UNKNOWN`(보낸 뒤 답 전에 끊김, 보내졌을 수 있음), `BUSY`(처리 중 방송이 허브 `maxPending`). 다시 보내지 않으며, 다시 보낼지는 handler가 정한다. 연결별 메시지는 순차 처리라 handler에서 await해도 리더 왕복 한 번(ms 단위)만 묶인다. 결과가 필요 없으면 `void ...catch()`.
115
- - **놓치면 안 되는 일(주문 상태·결제 결과)은 방송에 맡기지 않는다.** DB에 저장하고, 페이지는 다시 연결될 때 최신 상태를 읽는다. 방송은 「바뀌었으니 다시 읽어라」 알림으로 쓴다.
116
- - 방송 송신은 소켓마다 기다리지 않고 송신 큐에 넣는다(같은 소켓 순서 보장). 느린 소켓만 닫는다.
117
- - `send`는 원시 응답(현재 소켓)이다. 송신 버퍼에 들어가면 끝난다.
118
- - presence: 한 서버에서 처음 받은 변경은 이전부터 있던 연결을 joined로 담을 수 있다. 화면은 presence를 받으면 목록을 다시 읽는다.
119
-
120
- ## 6. 종료
121
-
122
- stop: 새 업무 차단 → 받은 handler·송신 중 방송 대기 → 1012로 닫기. core drain 기한이 지나면 남은 소켓을 끊는다. websocket drain이 web·hub drain보다 먼저 끝나고, 모든 drain 뒤 DB·허브가 닫힌다.
123
-
124
- ## 7. 로그(D-0047)
125
-
126
- - 예외를 조용히 버리지 않는다. 닫힘 코드·오류 응답으로 바꾸는 것 외의 실패는 `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`).
127
- - 메시지·소켓마다 도는 자리는 같은 메시지·code를 10초당 한 줄로 쓰고 나머지는 `repeated` 개수로 묶는다(drain 끝에 남은 개수도 씀). 본문·토큰은 쓰지 않는다.
128
- - 봉인(§4a): 프레임 거절은 warn `WebSocket sealed frame refused; closed`(code `SEAL_FRAME_REFUSED`, `reason`, `error`, 이유마다 10초당 한 줄 + `repeated`), 코덱 생성 실패 error `SEAL_CODEC_FAILED`(1011), 방송 봉인 실패 error `SEAL_ENCODE_FAILED`(1011), hello 송신 실패 warn `SEAL_HELLO_FAILED`. debug: 제공자 유무(`WebSocket seal provider`), 업그레이드마다 결정(`WebSocket seal decision`: path·sealed·offered), `WebSocket seal hello sent`, 4415(`WebSocket seal required; closed`), 연결 로그의 `sealed`, 방송 로그의 `sealed` 개수.
129
- - debug: 연결·닫힘·업그레이드 거절, 허브 등록 ms, 방 입장·퇴장·거절, presence 변화(개수), kick, 방송 전달(ID·연결 수·`binary`, `isEnabled` 확인 뒤), 옛 클라이언트의 `ack-v1` 무시(`ACK_IGNORED`, 10초당 한 줄 + `repeated`), idle·heartbeat 종료, drain 시작·끝. 대기 메시지 초과(1013 `Too many messages`)는 warn `TOO_MANY_MESSAGES`.
130
- - `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마다 세어 묶음).
131
- - 이 보고는 `session.reportError?(error, { source: 'handler' | 'client', code, type? })`로 간다. 게이트웨이가 만든 session에만 있고, 직접 만든 session(시험 등)에 없으면 `defineSocket`은 응답만 보낸다. 저수준 `route.message`도 같은 메서드로 보고할 수 있다.
132
-
133
- ## 8. 주의 사항
134
-
135
- - 쿠키 인증 라우트에 `origins: '*'`를 쓰지 않는다(Cross-Site WebSocket Hijacking). 프락시가 Host를 바꾸면 web `trustProxy`를 맞추거나 공개 출처를 `origins`에 적는다.
136
- - 헤더 값을 그대로 신원으로 믿는 예제(예제 23)는 테스트 전용이다.
137
- - `hub.events`는 이 플러그인이 단독 소비한다. 다른 코드가 읽지 않는다.
138
- - 방송은 많아야 한 번이다. 재접속·리더 교체·느린 소비자에서는 빠질 수 있고, `OUTCOME_UNKNOWN` 뒤에 다시 보내면 두 번 받을 수 있다.
139
- - 실제 두 컨테이너·네 워커 교차 전달, 허브 SIGKILL, NATS 장애 검증은 했지만 두 물리 장비·WAN 검증은 아니다(OPS-002).
140
-
141
- 근거: `examples/23-websocket`(두 Docker 서버·네 워커), `examples/25-playground`(앱별 소켓·presence·부하 시험), D-0024·D-0033·D-0034·D-0057(D-0025의 ACK를 대체), D-0059 §4(봉인 — 실제 서버 시험과 Chromium 검사는 @dokebi/seal에 있다: `npm run seal:test`·`seal:browser-check`).
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, slow consumer or a full replay nonce store (`Try again later`, D-0075), 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. One exception: when the hub's local nonce store is full of live nonces (seal reason `capacity`, [D-0075](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0075-replay-capacity.md)), the frame is refused and the connection closes with **1013** `Try again later` (temporary: the client reconnects with backoff), warn `SEAL_FRAME_REFUSED` with `reason: capacity`.
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
+ - presence calls per connection are bounded by `maxPending` (counted apart from messages). A handler slower than the changes gets them merged: later changes become one net `{ joined, left }` (a connection that joined and left meanwhile appears in neither), handed over when a call ends; warn `PRESENCE_MERGED` once per 10 seconds. Apply `left` and `joined` to a kept list and it stays right.
131
+
132
+ ## 6. Shutdown
133
+
134
+ 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.
135
+
136
+ ## 7. Logs ([D-0047](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0047-logging-and-no-silent-errors.md))
137
+
138
+ - 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`).
139
+ - 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.
140
+ - 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.
141
+ - 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`; presence changes merged behind a slow presence handler are warn `PRESENCE_MERGED` (once per 10 seconds + `repeated`).
142
+ - `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).
143
+ - 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.
144
+
145
+ ## 7a. Realtime transport contribution and errors (D-0063)
146
+
147
+ - 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`).
148
+ - 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`.
149
+ - 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).
150
+
151
+ ## 8. Errors
152
+
153
+ <!-- docs-check: complete-error-codes WebsocketErrorCode -->
154
+ `WebsocketError` (`plugin: 'dokebi-websocket'`, `fix`):
155
+
156
+ | Code | When |
157
+ |---|---|
158
+ | `INVALID_ROUTE` | A wrong route definition (path, authenticate, message, origins, seal, `defineSocket` arguments) |
159
+ | `INVALID_ARGUMENT` | A non-function passed to `onPresence` |
160
+ | `INVALID_FILTER` | A server call filter that is not exactly one of `{ tenant }` and `{ tenantPrefix }`, or a string outside 1–256 bytes |
161
+ | `INVALID_TARGET` | A wrong namespace or target for the transport `handle` |
162
+ | `INVALID_TYPE` | The type format of `send` |
163
+ | `INVALID_DATA` | `send` data that is not JSON, `broadcast` data that is not a string or Uint8Array |
164
+ | `FROZEN` | `route` outside setup |
165
+ | `SEAL_PROVIDER_MISSING` | A sealed route without dokebi-seal |
166
+ | `SEAL_PROVIDER_INVALID` | dokebi-seal does not provide `forConnection` |
167
+ | `SEAL_BINARY_UNSUPPORTED` | Non-UTF-8 bytes to a sealed socket |
168
+ | `SEAL_ENCODE_FAILED` | Sealing a frame failed (`cause`) |
169
+ | `SOCKET_CLOSED` | `send` to a closed socket |
170
+ | `SLOW_CONSUMER` | The send buffer would exceed `maxBufferedBytes` |
171
+ | `ROOM_FORBIDDEN` | `authorizeRoom` did not allow the room (with `hint`) |
172
+ | `BROADCAST_FAILED` | Part of a `tenantPrefix` broadcast failed without a hub code (`receipt`, `cause`) |
173
+ | `KICK_FAILED` | Part of a `tenantPrefix` kick failed without a hub code (`receipt`, `cause`) |
174
+
175
+ ## 9. Cautions
176
+
177
+ - 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`.
178
+ - Examples that trust a header value as the identity (example 23) are for tests only.
179
+ - `hub.events` is consumed only by this plugin. No other code reads it.
180
+ - Broadcasts are at most once. They can be missed across reconnects, leader changes and slow consumers, and resending after `OUTCOME_UNKNOWN` can deliver twice.
181
+ - 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).
182
+
183
+ 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`).