@dokebi/websocket 0.1.2 → 0.2.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 +31 -19
- package/README.md +15 -13
- package/dist/gateway.js +169 -47
- package/dist/index.js +2 -2
- package/dist/log.d.ts +25 -0
- package/dist/log.js +102 -0
- package/dist/router.d.ts +8 -5
- package/dist/router.js +19 -4
- package/dist/types.d.ts +26 -0
- package/package.json +5 -9
- package/dist/client.d.ts +0 -7
- package/dist/client.js +0 -60
package/AI.md
CHANGED
|
@@ -1,15 +1,20 @@
|
|
|
1
|
-
# AI 작업 안내 — @dokebi/websocket 0.
|
|
1
|
+
# AI 작업 안내 — @dokebi/websocket 0.2.0
|
|
2
2
|
|
|
3
|
-
dokebi-web(Fastify) 위에 WebSocket 라우트를 열고 @dokebi/websocket-hub로 서버·워커 사이 방송·접속자 목록을 잇는다. 방송은
|
|
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)다.
|
|
4
4
|
|
|
5
5
|
## 1. 설치
|
|
6
6
|
|
|
7
7
|
```sh
|
|
8
|
-
#
|
|
9
|
-
npx dokebi add @dokebi/websocket-hub
|
|
8
|
+
# 프로세스 하나(fork 포함): 허브는 mode local(기본) — 메모리 안, 허브 서버·포트·Redis·NATS·secret 없음
|
|
9
|
+
npx dokebi add @dokebi/websocket-hub
|
|
10
10
|
npx dokebi add @dokebi/websocket
|
|
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에 직접 쓰는 것이 안전
|
|
11
14
|
```
|
|
12
15
|
|
|
16
|
+
허브 사용 여부는 dokebi.yaml `options.dokebi-websocket-hub.mode`로 고른다. `local`(기본)은 같은 HubApi를 프로세스 안 메모리로 준다(허브 서버를 띄우지 않음). node:cluster 워커에서는 워커마다 접속자 목록이 갈라지므로 `HUB_LOCAL_IN_CLUSTER`로 거부한다. 워커가 하나뿐이면 `allowInCluster: true`로 허용한다. 여러 워커·서버가 방송을 나누려면 `cluster`.
|
|
17
|
+
|
|
13
18
|
## 2. 설정 `options.dokebi-websocket`
|
|
14
19
|
|
|
15
20
|
| 키 | 기본 | 뜻 |
|
|
@@ -17,7 +22,7 @@ npx dokebi add @dokebi/websocket
|
|
|
17
22
|
| `maxPayload` | 65536 | 메시지 크기 |
|
|
18
23
|
| `maxConnections` | 128 | 이 프로세스의 연결 수 |
|
|
19
24
|
| `maxPendingMessages` | 32 | 연결별 대기 메시지(연결마다 순차 처리) |
|
|
20
|
-
| `maxBufferedBytes` | 1048576 | 송신 버퍼. 넘으면 그 소켓을 1013 `Slow consumer`로
|
|
25
|
+
| `maxBufferedBytes` | 1048576 | 송신 버퍼. 넘으면 그 소켓을 1013 `Slow consumer`로 닫고 warn `WebSocket slow consumer closed`(code `SLOW_CONSUMER`)를 남김. 그 소켓에 쓰려던 응답은 버려진다(핸들러 실패로 세지 않음) |
|
|
21
26
|
| `closeTimeoutMs` | 2000 | 소켓 종료 대기(업무 제한 아님) |
|
|
22
27
|
| `heartbeatMs` | 10000 | ping/pong |
|
|
23
28
|
| `idleTimeoutMs` | 0(끔) | 클라이언트가 이 시간 동안 아무것도 안 보내면 4408 `Idle`. 페이지가 `{"$dokebi":"ping-v1"}`을 주기적으로 보낸다 |
|
|
@@ -49,46 +54,53 @@ export const chatSocket = (app: AppContext) => defineSocket({
|
|
|
49
54
|
});
|
|
50
55
|
```
|
|
51
56
|
|
|
52
|
-
- 메시지 형식: JSON `{ type, data?, id? }`. `reply`·`error`는 예약 type. 모르는 type은 `UNKNOWN_TYPE`, 잘못된 형식은 `INVALID_MESSAGE`, handler 오류는 오류의 `code`(대문자 형식) 또는 `HANDLER_FAILED`로 `{ type: 'error', id?, code }`(message·stack은 보내지
|
|
53
|
-
- `socket`: `session`·`identity`·`send(type, data)`(이 연결)·`broadcast(type, data, { room?, member? })`(허브로, tenant 고정).
|
|
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 }` 텍스트 프레임으로 간다.
|
|
54
59
|
- 멀티 앱: @dokebi/app의 `sockets: (app) => [chatSocket(app)]`. 앱마다 같은 경로가 따로 등록되고 허브 tenant는 `<앱>:<tenant>`.
|
|
55
|
-
- 저수준: `context.get(ws).route({ path, origins?, constraints?, version?, authenticate, authorizeRoom?, message(data, session), presence? })`. session: `id`·`identity`·`send`·`broadcast(bytes, target?)`·`join(room)`·`leave(room)`·`close(code?, reason?)
|
|
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).
|
|
56
61
|
|
|
57
62
|
## 4. 클라이언트가 할 일
|
|
58
63
|
|
|
59
64
|
```ts
|
|
60
|
-
import { DeliveryReceiver } from '@dokebi/websocket/client';
|
|
61
65
|
const clientId = sessionStorage.getItem('cid') ?? crypto.randomUUID(); // 탭마다 다르게(localStorage 공유 금지)
|
|
62
66
|
sessionStorage.setItem('cid', clientId);
|
|
63
|
-
const receiver = new DeliveryReceiver(); // 재접속에도 유지
|
|
64
67
|
const socket = new WebSocket(`/ws?clientId=${clientId}&dokebiVersion=${BUILD_VERSION}`);
|
|
65
|
-
socket.onmessage =
|
|
66
|
-
|
|
67
|
-
};
|
|
68
|
+
socket.onmessage = ({ data }) => handle(JSON.parse(data)); // 응답·방송 모두 { type, data } 텍스트
|
|
69
|
+
socket.onopen = () => reloadState(); // 재접속하면 놓친 것은 서버에서 다시 읽는다
|
|
68
70
|
setInterval(() => socket.send('{"$dokebi":"ping-v1"}'), 15000); // idleTimeoutMs를 쓸 때
|
|
69
71
|
```
|
|
70
72
|
|
|
71
|
-
- 방송은
|
|
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
|
+
- 연결이 끊긴 사이·느린 소비자로 닫힌 사이의 방송은 다시 오지 않는다. 화면은 다시 연결되면 서버에서 최신 상태를 읽는다.
|
|
72
75
|
- 닫힘 코드: 4426 새로고침, 4409 같은 clientId 중복(`Duplicate client`), 4408 idle, 1013 허브 불가·느린 소비자, 1012 서버 종료, 1011 handler 미처리 오류.
|
|
73
76
|
|
|
74
77
|
## 5. 응답 코드와 전달 의미
|
|
75
78
|
|
|
76
79
|
- 업그레이드: 출처 거부 403(`ORIGIN_FORBIDDEN`, authenticate 호출 안 함), 인증 실패 401, 허브 미준비·종료·용량 503 `{ error: 'UNAVAILABLE', reason: CLOSING | HUB_<상태> | CAPACITY }`, 일반 HTTP 426.
|
|
77
|
-
- `broadcast`는
|
|
80
|
+
- `broadcast`는 허브가 내보내면 receipt `{ id, recipients }`로 끝난다(D-0057). `recipients`는 보낸 시점에 조건에 맞은 연결이며 받았다는 확인이 아니다. 실패는 바로: `RECOVERING`(허브가 리더에 연결돼 있지 않음, 보내지 않음), `OUTCOME_UNKNOWN`(보낸 뒤 답 전에 끊김, 보내졌을 수 있음), `BUSY`(처리 중 방송이 허브 `maxPending`). 다시 보내지 않으며, 다시 보낼지는 handler가 정한다. 연결별 메시지는 순차 처리라 handler에서 await해도 리더 왕복 한 번(ms 단위)만 묶인다. 결과가 필요 없으면 `void ...catch()`.
|
|
81
|
+
- **놓치면 안 되는 일(주문 상태·결제 결과)은 방송에 맡기지 않는다.** DB에 저장하고, 페이지는 다시 연결될 때 최신 상태를 읽는다. 방송은 「바뀌었으니 다시 읽어라」 알림으로 쓴다.
|
|
78
82
|
- 방송 송신은 소켓마다 기다리지 않고 송신 큐에 넣는다(같은 소켓 순서 보장). 느린 소켓만 닫는다.
|
|
79
|
-
- `send`는 원시 응답(현재 소켓)
|
|
83
|
+
- `send`는 원시 응답(현재 소켓)이다. 송신 버퍼에 들어가면 끝난다.
|
|
80
84
|
- presence: 한 서버에서 처음 받은 변경은 이전부터 있던 연결을 joined로 담을 수 있다. 화면은 presence를 받으면 목록을 다시 읽는다.
|
|
81
85
|
|
|
82
86
|
## 6. 종료
|
|
83
87
|
|
|
84
88
|
stop: 새 업무 차단 → 받은 handler·송신 중 방송 대기 → 1012로 닫기. core drain 기한이 지나면 남은 소켓을 끊는다. websocket drain이 web·hub drain보다 먼저 끝나고, 모든 drain 뒤 DB·허브가 닫힌다.
|
|
85
89
|
|
|
86
|
-
## 7.
|
|
90
|
+
## 7. 로그(D-0047)
|
|
91
|
+
|
|
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`도 같은 메서드로 보고할 수 있다.
|
|
97
|
+
|
|
98
|
+
## 8. 주의 사항
|
|
87
99
|
|
|
88
100
|
- 쿠키 인증 라우트에 `origins: '*'`를 쓰지 않는다(Cross-Site WebSocket Hijacking). 프락시가 Host를 바꾸면 web `trustProxy`를 맞추거나 공개 출처를 `origins`에 적는다.
|
|
89
101
|
- 헤더 값을 그대로 신원으로 믿는 예제(예제 23)는 테스트 전용이다.
|
|
90
102
|
- `hub.events`는 이 플러그인이 단독 소비한다. 다른 코드가 읽지 않는다.
|
|
91
|
-
-
|
|
103
|
+
- 방송은 많아야 한 번이다. 재접속·리더 교체·느린 소비자에서는 빠질 수 있고, `OUTCOME_UNKNOWN` 뒤에 다시 보내면 두 번 받을 수 있다.
|
|
92
104
|
- 실제 두 컨테이너·네 워커 교차 전달, 허브 SIGKILL, NATS 장애 검증은 했지만 두 물리 장비·WAN 검증은 아니다(OPS-002).
|
|
93
105
|
|
|
94
|
-
근거: `examples/23-websocket`(두 Docker 서버·네 워커), `examples/25-playground`(앱별 소켓·presence·부하 시험), D-0024·D-
|
|
106
|
+
근거: `examples/23-websocket`(두 Docker 서버·네 워커), `examples/25-playground`(앱별 소켓·presence·부하 시험), D-0024·D-0033·D-0034·D-0057(D-0025의 ACK를 대체).
|
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @dokebi/websocket
|
|
2
2
|
|
|
3
|
-
Node >=24, 0.
|
|
3
|
+
Node >=24, 0.2.0. Dokebi Fastify 웹과 websocket-hub를 연결하는 선택 플러그인. API 서버에 템플릿/뷰를 강제하지 않는다.
|
|
4
4
|
|
|
5
5
|
```ts
|
|
6
6
|
import { Application, dependencyOf, loadConfig } from '@dokebi/core';
|
|
@@ -49,11 +49,11 @@ API는 setup 시 route({path,origins?,authenticate,authorizeRoom?,message}) 등
|
|
|
49
49
|
|
|
50
50
|
메시지는 연결별 순차 실행하며 초기 등록 중 수신도 큐에 보관한다. maxPayload65536, maxConnections128, maxPendingMessages32, maxBufferedBytes1048576, closeTimeoutMs2000, heartbeatMs10000이 기본값이다. [스키마](options.schema.json)에 한도가 있다. ping/pong, 송신 버퍼 상한, 압축 비활성화를 사용한다. hub 자체의 payload/접속 한도도 함께 적용된다.
|
|
51
51
|
|
|
52
|
-
방송 전달은 대상 소켓마다 송신 완료를 기다리지 않는다.
|
|
52
|
+
방송 전달은 대상 소켓마다 송신 완료를 기다리지 않는다. 방송 바이트를 그대로(UTF-8이면 텍스트 프레임, 아니면 바이너리 프레임) 버퍼 하나로 모든 수신 소켓이 나눠 쓰며 열린 소켓의 `ws` 송신 큐에 넣고(같은 소켓 안의 순서는 그 큐가 보장한다), 송신 오류가 나면 그 소켓만 끊는다. `bufferedAmount`에 프레임을 더한 값이 maxBufferedBytes를 넘으면 그 소켓을 1013 `Slow consumer`로 닫는다. 그래서 느린 클라이언트 하나가 다른 소켓의 방송을 늦추지 않는다. 대기 중인 허브 이벤트를 한 번에 처리하다가 정상 소켓까지 한도를 넘기지 않도록, 송신 중인 프레임이 있으면 이벤트 사이에 이벤트 루프를 한 번 양보한다.
|
|
53
53
|
|
|
54
54
|
stop은 새 업무를 차단하고 이미 받은 핸들러와 송신 중인 방송을 기다린 뒤1012로 종료한다. 먼저 끊긴 클라이언트의 잔여 DB 작업도 기다린다. closeTimeoutMs는 소켓 종료 대기 한도이며 업무 실행 제한이 아니다. core의 drain 기한(`shutdown.drainTimeoutMs`, 기본 20000ms)이 지나 `context.drainSignal`이 abort되면 기다림을 멈추고 남은 소켓을 끊는다. 기한 초과는 core가 `DRAIN_TIMEOUT`으로 보고한다. websocket은 web과 hub에 의존하므로 core가 websocket drain을 먼저 끝낸 뒤 web·hub drain을 시작하고, 모든 drain 뒤에 DB/허브가 닫힌다.
|
|
55
55
|
|
|
56
|
-
hub.events는 이 플러그인이 단독 소비한다. broadcast
|
|
56
|
+
hub.events는 이 플러그인이 단독 소비한다. broadcast는 많아야 한 번이며 허브가 내보내면 receipt `{ id, recipients }`를 반환한다(아래 「방송」). send는 현재 소켓의 원시 응답으로 별도 송신 완료 계약이다. 실제 두 컨테이너·네 워커의 교차 서버 전달/허브 SIGKILL/NATS 장애/DB drain 검증은 운영 전체 인증이나 실제 두 물리 장비 검증을 뜻하지 않는다.
|
|
57
57
|
|
|
58
58
|
|
|
59
59
|
**접속자 입·퇴장(presence):** 허브는 연결이 들고 날 때마다 모든 서버에 그 서버 소유자(owner)의 연결 목록을 알린다. 서버가 죽어 등록이 만료된 경우도 포함한다. 이 패키지는 그 알림을 tenant별 `{ tenant, joined, left }`로 바꾼다. 그리고 같은 tenant에 열린 자기 서버의 연결마다 라우트의 `presence(change, session)` 훅을 그 연결의 메시지 처리 순서대로 부른다.
|
|
@@ -68,24 +68,26 @@ hub.events는 이 플러그인이 단독 소비한다. broadcast receipt는 전
|
|
|
68
68
|
|
|
69
69
|
**허브 재연결 대기(`hubWaitMs`, D-0034):** 허브가 리더 교체·순차 재시작으로 잠시 `recovering`이면 업그레이드는 최대 `hubWaitMs`(기본 5000, 0이면 바로 거절)까지 기다린다. 그래도 준비되지 않으면 503이다. 거절 본문은 `{ error: 'UNAVAILABLE', reason }`이고 reason은 `CLOSING`·`HUB_<상태>`·`CAPACITY`다. 같은 이유를 debug 로그 `WebSocket upgrade refused`에도 남긴다.
|
|
70
70
|
|
|
71
|
-
|
|
71
|
+
## 방송: 많아야 한 번 (0.2.0, [D-0057](../../docs/decisions/D-0057-websocket-broadcast-without-ack.md))
|
|
72
72
|
|
|
73
|
-
`
|
|
74
|
-
|
|
75
|
-
|
|
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초당 한 줄).
|
|
76
78
|
|
|
77
79
|
```ts
|
|
78
|
-
|
|
79
|
-
const
|
|
80
|
-
|
|
81
|
-
if (!await receiver.receive(data, consumeBytes, ack => socket.send(ack))) consumeReply(data);
|
|
80
|
+
socket.onmessage = ({ data }) => {
|
|
81
|
+
const message = JSON.parse(data); // 응답·presence·방송 모두 { type, data? }
|
|
82
|
+
if (message.type === 'order.changed') reloadOrder(message.data.id); // 방송은 알림, 내용은 다시 읽기
|
|
82
83
|
};
|
|
84
|
+
socket.onopen = () => reloadState(); // 끊긴 사이의 방송은 다시 오지 않는다
|
|
83
85
|
```
|
|
84
86
|
|
|
85
|
-
|
|
87
|
+
`clientId`는 탭(페이지)마다 달라야 한다. 같은 `(tenant, member, clientId)`가 이미 연결돼 있으면 허브가 등록을 거절한다. 이때 소켓은 **4409 `Duplicate client`**로 닫힌다. 허브 장애(1013 `Hub unavailable`)와 구별된다. 같은 clientId로 바로 다시 붙으면 또 거절되므로, 브라우저에서 clientId를 localStorage처럼 탭끼리 공유하는 곳에 두지 않는다. 페이지 메모리나 탭 단위 저장소에 둔다.
|
|
86
88
|
|
|
87
89
|
## 라우트 제약과 메시지 라우터 (D-0030)
|
|
88
90
|
|
|
89
91
|
- `route({ constraints })`: 업그레이드 라우트에 Fastify 라우트 제약을 붙인다. @dokebi/app이 `{ dokebiApp: '<앱>' }`으로 앱마다 같은 경로(`/ws`)를 따로 등록한다.
|
|
90
|
-
- `defineSocket({ path, authenticate, on: { '<type>': handler } })`는 메시지 라우터가 붙은 라우트를 만든다. 메시지는 JSON `{ type, data?, id? }`다. 핸들러 `(data, socket)`의 반환값은 `id`가 있으면 `{ type: 'reply', id, data }`로 간다. `socket.send(type, data)`는 이 연결에, `socket.broadcast(type, data, target?)`는 허브로 보낸다. 모르는 type은 `UNKNOWN_TYPE`, 잘못된 메시지는 `INVALID_MESSAGE`, 핸들러 오류는 오류의 `code`(대문자 형식일 때) 또는 `HANDLER_FAILED`로 `{ type: 'error', id?, code }` 응답한다. 오류 메시지·stack은 보내지
|
|
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이다.
|
|
91
93
|
- 2026-10-14 수정([ISSUE-0005](../../docs/issues/ISSUE-0005-playground-findings.md) PG-14): WebSocket 라우트가 없는 경로로 온 업그레이드 요청이 404 뒤에도 원시 소켓을 열어 둬 앱 종료가 정리 시한까지 멈췄다. @fastify/websocket을 캡슐화 없이 등록해 그 훅이 모든 업그레이드에 적용되게 했다.
|
package/dist/gateway.js
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
|
+
import { isUtf8 } from 'node:buffer';
|
|
1
2
|
import { randomUUID } from 'node:crypto';
|
|
2
3
|
import { setTimeout as delay, setImmediate as immediate } from 'node:timers/promises';
|
|
3
4
|
import fastifyWebsocket from '@fastify/websocket';
|
|
4
5
|
import { WebSocket } from 'ws';
|
|
6
|
+
import { errorCode, errorText, LogThrottle } from './log.js';
|
|
5
7
|
const TEXT = Object.freeze({ binary: false });
|
|
8
|
+
const BINARY = Object.freeze({ binary: true });
|
|
6
9
|
/** Allow-list entries must be exact http(s) origins such as `https://app.example.com`. */
|
|
7
10
|
function parseOrigins(value) {
|
|
8
11
|
if (value === undefined)
|
|
@@ -17,7 +20,9 @@ function parseOrigins(value) {
|
|
|
17
20
|
try {
|
|
18
21
|
url = typeof item === 'string' ? new URL(item) : undefined;
|
|
19
22
|
}
|
|
20
|
-
catch {
|
|
23
|
+
catch (error) {
|
|
24
|
+
throw new Error('Invalid websocket route', { cause: error });
|
|
25
|
+
}
|
|
21
26
|
if (!url || (url.protocol !== 'http:' && url.protocol !== 'https:') || url.origin !== item)
|
|
22
27
|
throw new Error('Invalid websocket route');
|
|
23
28
|
result.add(url.origin);
|
|
@@ -80,12 +85,15 @@ export class Gateway {
|
|
|
80
85
|
#closing = false;
|
|
81
86
|
#loop;
|
|
82
87
|
#timer;
|
|
88
|
+
/** Failures on per-message and per-socket paths, logged once per interval with a count. */
|
|
89
|
+
#throttle;
|
|
83
90
|
constructor(context, web, hub, settings) {
|
|
84
91
|
this.context = context;
|
|
85
92
|
this.web = web;
|
|
86
93
|
this.hub = hub;
|
|
87
94
|
this.settings = settings;
|
|
88
95
|
const self = this;
|
|
96
|
+
this.#throttle = new LogThrottle(context.logger);
|
|
89
97
|
this.api = Object.freeze({
|
|
90
98
|
get connections() {
|
|
91
99
|
return self.#clients.size;
|
|
@@ -108,7 +116,9 @@ export class Gateway {
|
|
|
108
116
|
this.#frozen = true;
|
|
109
117
|
await scope.register(fastifyWebsocket, {
|
|
110
118
|
options: { maxPayload: settings.maxPayload, perMessageDeflate: false },
|
|
111
|
-
|
|
119
|
+
// A wsHandler that threw: the client gets 1011, the cause goes to the log (D-0047).
|
|
120
|
+
errorHandler: (error, socket) => {
|
|
121
|
+
this.#throttle.report('error', 'WebSocket handler failed', 'SOCKET_FAILURE', error);
|
|
112
122
|
socket.close(1011, 'Socket failure');
|
|
113
123
|
},
|
|
114
124
|
});
|
|
@@ -157,25 +167,37 @@ export class Gateway {
|
|
|
157
167
|
#send(socket, data) {
|
|
158
168
|
const bytes = typeof data === 'string' ? Buffer.byteLength(data) : data.byteLength;
|
|
159
169
|
if (socket.readyState !== WebSocket.OPEN)
|
|
160
|
-
return Promise.reject(new Error('Socket closed'));
|
|
170
|
+
return Promise.reject(Object.assign(new Error('Socket closed'), { code: 'SOCKET_CLOSED' }));
|
|
161
171
|
if (socket.bufferedAmount + bytes > this.settings.maxBufferedBytes) {
|
|
162
|
-
socket
|
|
163
|
-
return Promise.reject(new Error('Socket backpressure'));
|
|
172
|
+
this.#slow(socket);
|
|
173
|
+
return Promise.reject(Object.assign(new Error('Socket backpressure'), { code: 'SLOW_CONSUMER' }));
|
|
164
174
|
}
|
|
165
175
|
return this.#watch(new Promise((resolve, reject) => socket.send(data, (error) => (error ? reject(error) : resolve()))));
|
|
166
176
|
}
|
|
177
|
+
/** Closes a socket whose send buffer passed maxBufferedBytes (1013), logging it once. */
|
|
178
|
+
#slow(socket) {
|
|
179
|
+
if (socket.readyState !== WebSocket.OPEN)
|
|
180
|
+
return;
|
|
181
|
+
this.context.logger.log('warn', 'WebSocket slow consumer closed', {
|
|
182
|
+
code: 'SLOW_CONSUMER',
|
|
183
|
+
bufferedBytes: socket.bufferedAmount,
|
|
184
|
+
});
|
|
185
|
+
socket.close(1013, 'Slow consumer');
|
|
186
|
+
}
|
|
167
187
|
/** Queues one broadcast frame without waiting; a slow socket never delays the others. */
|
|
168
|
-
#deliver(socket, frame) {
|
|
188
|
+
#deliver(socket, frame, kind) {
|
|
169
189
|
if (socket.readyState !== WebSocket.OPEN)
|
|
170
190
|
return;
|
|
171
191
|
if (socket.bufferedAmount + frame.byteLength > this.settings.maxBufferedBytes) {
|
|
172
|
-
socket
|
|
192
|
+
this.#slow(socket);
|
|
173
193
|
return;
|
|
174
194
|
}
|
|
175
195
|
this.#sends++;
|
|
176
|
-
socket.send(frame,
|
|
177
|
-
if (error)
|
|
196
|
+
socket.send(frame, kind, (error) => {
|
|
197
|
+
if (error) {
|
|
198
|
+
this.#throttle.report('error', 'WebSocket broadcast write failed; socket terminated', 'BROADCAST_WRITE_FAILED', error);
|
|
178
199
|
socket.terminate();
|
|
200
|
+
}
|
|
179
201
|
if (--this.#sends === 0 && this.#sendsIdle) {
|
|
180
202
|
this.#sendsIdle.resolve();
|
|
181
203
|
this.#sendsIdle = undefined;
|
|
@@ -252,28 +274,55 @@ export class Gateway {
|
|
|
252
274
|
return this.hub.broadcast({ ...target, tenant: identity.tenant }, data);
|
|
253
275
|
},
|
|
254
276
|
join: async (room) => {
|
|
255
|
-
if (!route.authorizeRoom || !(await route.authorizeRoom(identity, room)))
|
|
277
|
+
if (!route.authorizeRoom || !(await route.authorizeRoom(identity, room))) {
|
|
278
|
+
this.context.logger.log('debug', 'WebSocket room refused', { connection: id });
|
|
256
279
|
throw new Error('Room access denied');
|
|
280
|
+
}
|
|
257
281
|
await value.registration?.join(room);
|
|
282
|
+
this.context.logger.log('debug', 'WebSocket room joined', {
|
|
283
|
+
connection: id,
|
|
284
|
+
room: room.slice(0, 64),
|
|
285
|
+
});
|
|
258
286
|
},
|
|
259
287
|
leave: async (room) => {
|
|
260
288
|
await value.registration?.leave(room);
|
|
289
|
+
this.context.logger.log('debug', 'WebSocket room left', {
|
|
290
|
+
connection: id,
|
|
291
|
+
room: room.slice(0, 64),
|
|
292
|
+
});
|
|
261
293
|
},
|
|
262
294
|
close: (code = 1000, reason = '') => {
|
|
263
295
|
socket.close(code, reason);
|
|
264
296
|
},
|
|
297
|
+
// What defineSocket answered with an error frame (D-0047): the client sees the code only,
|
|
298
|
+
// the operator gets the cause. Handler types are a bounded set (the route's handlers), so
|
|
299
|
+
// repeats are counted per type and reply code; client errors are counted per code only.
|
|
300
|
+
reportError: (error, details) => {
|
|
301
|
+
if (details.source === 'handler') {
|
|
302
|
+
this.#throttle.report('error', 'WebSocket handler failed.', 'SOCKET_HANDLER_FAILED', error === undefined ? 'NonError: undefined' : error, // `throw undefined` still shows
|
|
303
|
+
{ type: details.type ?? null, reply: details.code, connection: id }, `${details.type ?? ''}\u0000${details.code}`);
|
|
304
|
+
return;
|
|
305
|
+
}
|
|
306
|
+
this.#throttle.report('debug', 'WebSocket client message refused', details.code, error, {
|
|
307
|
+
type: details.type?.slice(0, 64) ?? null,
|
|
308
|
+
connection: id,
|
|
309
|
+
});
|
|
310
|
+
},
|
|
265
311
|
});
|
|
266
312
|
value.session = session;
|
|
267
313
|
const registration = { ...identity, connection: id };
|
|
268
314
|
value.tail = this.#watch(this.hub.register(registration).then((handle) => {
|
|
269
315
|
value.registration = handle;
|
|
316
|
+
if (this.context.logger.isEnabled('debug'))
|
|
317
|
+
this.context.logger.log('debug', 'WebSocket registered with hub', {
|
|
318
|
+
connection: id,
|
|
319
|
+
ms: Math.round(performance.now() - opened),
|
|
320
|
+
});
|
|
270
321
|
}));
|
|
271
322
|
const registered = value.tail;
|
|
272
323
|
void value.tail.catch((error) => {
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
code: error instanceof Error ? error.message : 'UNKNOWN',
|
|
276
|
-
});
|
|
324
|
+
// Converted to a close code (4409 or 1013) for the client; logged here for the operator.
|
|
325
|
+
this.#throttle.report('warn', 'WebSocket registration failed', errorCode(error, 'REGISTRATION_FAILED'), error, { connection: id });
|
|
277
326
|
value.failed = true;
|
|
278
327
|
// The same (tenant, member, clientId) is already connected (D-0025): a client error, not
|
|
279
328
|
// a hub outage. A client that retries with the same clientId is refused again.
|
|
@@ -287,11 +336,16 @@ export class Gateway {
|
|
|
287
336
|
socket.on('pong', () => {
|
|
288
337
|
value.alive = true;
|
|
289
338
|
});
|
|
290
|
-
|
|
339
|
+
// ws emits 'close' after 'error'; the close cleans up, the error is reported here.
|
|
340
|
+
socket.on('error', (error) => {
|
|
341
|
+
this.#throttle.report('error', 'WebSocket socket error', 'SOCKET_ERROR', error, {
|
|
342
|
+
reason: errorCode(error, 'UNKNOWN'),
|
|
343
|
+
});
|
|
344
|
+
});
|
|
291
345
|
// Attach synchronously, before awaiting Redis/TCP registration, so early frames are queued.
|
|
292
346
|
socket.on('message', (raw) => {
|
|
293
347
|
value.seen = performance.now();
|
|
294
|
-
//
|
|
348
|
+
// Control frames are answered here, outside the route's message queue.
|
|
295
349
|
const bytes = Array.isArray(raw)
|
|
296
350
|
? Buffer.concat(raw)
|
|
297
351
|
: Buffer.from(raw instanceof ArrayBuffer ? new Uint8Array(raw) : raw);
|
|
@@ -306,15 +360,10 @@ export class Gateway {
|
|
|
306
360
|
// The page is alive (idleTimeoutMs): nothing else to do.
|
|
307
361
|
if (control?.$dokebi === 'ping-v1')
|
|
308
362
|
return;
|
|
363
|
+
// A page loaded before D-0057 still acknowledges broadcasts: nothing to do, and no
|
|
364
|
+
// reason to close it. Counted at debug until it reloads.
|
|
309
365
|
if (control?.$dokebi === 'ack-v1') {
|
|
310
|
-
|
|
311
|
-
if (typeof control.id !== 'string')
|
|
312
|
-
throw new Error('Invalid ACK');
|
|
313
|
-
this.hub.acknowledge(control.id, [id]);
|
|
314
|
-
}
|
|
315
|
-
catch {
|
|
316
|
-
socket.close(1008, 'Invalid ACK');
|
|
317
|
-
}
|
|
366
|
+
this.#throttle.report('debug', 'WebSocket ACK from an old client ignored', 'ACK_IGNORED', undefined, { connection: id });
|
|
318
367
|
return;
|
|
319
368
|
}
|
|
320
369
|
}
|
|
@@ -322,6 +371,12 @@ export class Gateway {
|
|
|
322
371
|
return;
|
|
323
372
|
if (++value.pending > this.settings.maxPendingMessages) {
|
|
324
373
|
value.pending--;
|
|
374
|
+
// The server closing a client is worth seeing (like SLOW_CONSUMER): usually a handler
|
|
375
|
+
// that waits long (a slow database call) while the client keeps sending.
|
|
376
|
+
this.#throttle.report('warn', 'WebSocket message queue full; closed', 'TOO_MANY_MESSAGES', undefined, {
|
|
377
|
+
connection: id,
|
|
378
|
+
pending: value.pending,
|
|
379
|
+
});
|
|
325
380
|
socket.close(1013, 'Too many messages');
|
|
326
381
|
return;
|
|
327
382
|
}
|
|
@@ -336,11 +391,20 @@ export class Gateway {
|
|
|
336
391
|
return route.message(data, session);
|
|
337
392
|
});
|
|
338
393
|
value.tail = work
|
|
339
|
-
.then(() => { }, () => {
|
|
394
|
+
.then(() => { }, (error) => {
|
|
340
395
|
value.failed = true;
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
396
|
+
// A reply that cannot be written because the socket is closing is not a handler
|
|
397
|
+
// failure. A slow consumer was logged where it was closed; a client that left is
|
|
398
|
+
// counted here as warn, once per interval: the client is gone, nothing on this
|
|
399
|
+
// server failed (OPS-002 soak: thousands of these hid the real cause at error).
|
|
400
|
+
const code = error?.code;
|
|
401
|
+
if (code === 'SLOW_CONSUMER')
|
|
402
|
+
return;
|
|
403
|
+
if (code === 'SOCKET_CLOSED') {
|
|
404
|
+
this.#throttle.report('warn', 'WebSocket reply dropped; socket closed', 'REPLY_DROPPED', error, { connection: id });
|
|
405
|
+
return;
|
|
406
|
+
}
|
|
407
|
+
this.#throttle.report('error', 'WebSocket message handler failed', errorCode(error, 'HANDLER_FAILED'), error, { connection: id });
|
|
344
408
|
socket.close(1011, 'Message failed');
|
|
345
409
|
})
|
|
346
410
|
.finally(() => {
|
|
@@ -364,10 +428,9 @@ export class Gateway {
|
|
|
364
428
|
.finally(() => {
|
|
365
429
|
this.#clients.delete(id);
|
|
366
430
|
});
|
|
367
|
-
void this.#watch(cleanup).catch(() => {
|
|
368
|
-
this
|
|
369
|
-
|
|
370
|
-
});
|
|
431
|
+
void this.#watch(cleanup).catch((error) => {
|
|
432
|
+
// The hub drops this connection when it recovers (owner snapshot or expiry).
|
|
433
|
+
this.#throttle.report('error', 'WebSocket presence cleanup deferred to hub recovery', 'PRESENCE_CLEANUP_DEFERRED', error, { connection: id });
|
|
371
434
|
});
|
|
372
435
|
});
|
|
373
436
|
}
|
|
@@ -401,6 +464,19 @@ export class Gateway {
|
|
|
401
464
|
of(record.tenant).left.push(peer(record));
|
|
402
465
|
if (!changes.size)
|
|
403
466
|
return;
|
|
467
|
+
if (this.context.logger.isEnabled('debug')) {
|
|
468
|
+
let joined = 0, left = 0;
|
|
469
|
+
for (const change of changes.values()) {
|
|
470
|
+
joined += change.joined.length;
|
|
471
|
+
left += change.left.length;
|
|
472
|
+
}
|
|
473
|
+
this.context.logger.log('debug', 'WebSocket presence changed', {
|
|
474
|
+
owner,
|
|
475
|
+
tenants: changes.size,
|
|
476
|
+
joined,
|
|
477
|
+
left,
|
|
478
|
+
});
|
|
479
|
+
}
|
|
404
480
|
for (const value of this.#clients.values()) {
|
|
405
481
|
const { route, session } = value;
|
|
406
482
|
const change = session && changes.get(session.identity.tenant);
|
|
@@ -420,10 +496,13 @@ export class Gateway {
|
|
|
420
496
|
// In order with this connection's messages, like a message handler.
|
|
421
497
|
value.tail = value.tail
|
|
422
498
|
.then(() => route.presence?.(presence, session))
|
|
423
|
-
.then(() => { }, () => {
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
499
|
+
.then(() => { }, (error) => {
|
|
500
|
+
const code = error?.code;
|
|
501
|
+
if (code === 'SLOW_CONSUMER')
|
|
502
|
+
return; // Logged where the socket was closed.
|
|
503
|
+
this.#throttle.report(code === 'SOCKET_CLOSED' ? 'warn' : 'error', code === 'SOCKET_CLOSED'
|
|
504
|
+
? 'WebSocket presence dropped; socket closed'
|
|
505
|
+
: 'WebSocket presence handler failed', code === 'SOCKET_CLOSED' ? 'REPLY_DROPPED' : 'PRESENCE_HANDLER_FAILED', error, { connection: session.id });
|
|
427
506
|
});
|
|
428
507
|
this.#watch(value.tail);
|
|
429
508
|
}
|
|
@@ -437,39 +516,67 @@ export class Gateway {
|
|
|
437
516
|
continue;
|
|
438
517
|
}
|
|
439
518
|
if (event.kind === 'kick') {
|
|
519
|
+
this.context.logger.log('debug', 'WebSocket kick', {
|
|
520
|
+
id: event.id,
|
|
521
|
+
connections: event.connections.length,
|
|
522
|
+
code: event.code,
|
|
523
|
+
});
|
|
440
524
|
for (const id of event.connections)
|
|
441
525
|
this.#clients.get(id)?.socket.close(event.code, event.reason);
|
|
442
526
|
continue;
|
|
443
527
|
}
|
|
444
|
-
//
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
}));
|
|
528
|
+
// The broadcast bytes as they are (D-0057): a text frame when they are UTF-8 (the
|
|
529
|
+
// `{ type, data }` JSON of defineSocket), a binary frame otherwise. One buffer shared
|
|
530
|
+
// by every recipient; ws keeps per-socket order in its queue.
|
|
531
|
+
const frame = Buffer.from(event.data.buffer, event.data.byteOffset, event.data.byteLength);
|
|
532
|
+
const kind = isUtf8(frame) ? TEXT : BINARY;
|
|
533
|
+
let local = 0;
|
|
451
534
|
for (const id of event.connections) {
|
|
452
535
|
const value = this.#clients.get(id);
|
|
453
|
-
if (value)
|
|
454
|
-
|
|
536
|
+
if (value) {
|
|
537
|
+
local++;
|
|
538
|
+
this.#deliver(value.socket, frame, kind);
|
|
539
|
+
}
|
|
455
540
|
}
|
|
541
|
+
if (this.context.logger.isEnabled('debug'))
|
|
542
|
+
this.context.logger.log('debug', 'WebSocket broadcast delivered', {
|
|
543
|
+
id: event.id,
|
|
544
|
+
connections: event.connections.length,
|
|
545
|
+
local,
|
|
546
|
+
binary: kind === BINARY,
|
|
547
|
+
});
|
|
456
548
|
// Queued events would otherwise be fanned out in one tick, before any socket can flush,
|
|
457
549
|
// and a burst could exceed maxBufferedBytes on healthy sockets. One turn lets I/O run.
|
|
458
550
|
if (this.#sends)
|
|
459
551
|
await immediate();
|
|
460
552
|
}
|
|
461
|
-
})().catch(() => {
|
|
553
|
+
})().catch((error) => {
|
|
554
|
+
// The hub ended its event stream (overflow, closed): every socket gets 1013 and reconnects.
|
|
555
|
+
this.context.logger.log('error', 'WebSocket hub event stream failed; sockets closed', {
|
|
556
|
+
code: 'HUB_EVENTS_FAILED',
|
|
557
|
+
error: errorText(error),
|
|
558
|
+
open: this.#clients.size,
|
|
559
|
+
});
|
|
462
560
|
for (const value of this.#clients.values())
|
|
463
561
|
value.socket.close(1013, 'Hub unavailable');
|
|
464
562
|
});
|
|
563
|
+
this.context.logger.log('debug', 'WebSocket gateway started', {
|
|
564
|
+
routes: this.#routes.length,
|
|
565
|
+
heartbeatMs: this.settings.heartbeatMs,
|
|
566
|
+
idleTimeoutMs: this.settings.idleTimeoutMs,
|
|
567
|
+
});
|
|
465
568
|
this.#timer = setInterval(() => {
|
|
466
569
|
const idleBefore = performance.now() - this.settings.idleTimeoutMs;
|
|
467
|
-
for (const value of this.#clients
|
|
570
|
+
for (const [id, value] of this.#clients) {
|
|
468
571
|
if (this.settings.idleTimeoutMs && value.seen < idleBefore) {
|
|
572
|
+
this.context.logger.log('debug', 'WebSocket idle closed', { connection: id });
|
|
469
573
|
value.socket.close(4408, 'Idle');
|
|
470
574
|
continue;
|
|
471
575
|
}
|
|
472
576
|
if (!value.alive) {
|
|
577
|
+
this.context.logger.log('debug', 'WebSocket heartbeat missed; terminated', {
|
|
578
|
+
connection: id,
|
|
579
|
+
});
|
|
473
580
|
value.socket.terminate();
|
|
474
581
|
continue;
|
|
475
582
|
}
|
|
@@ -481,7 +588,12 @@ export class Gateway {
|
|
|
481
588
|
}
|
|
482
589
|
/** Stops waiting as soon as `signal` (the core drain deadline) aborts; sockets are then cut. */
|
|
483
590
|
async drain(signal) {
|
|
591
|
+
const started = performance.now();
|
|
484
592
|
this.#closing = true;
|
|
593
|
+
this.context.logger.log('debug', 'WebSocket drain started', {
|
|
594
|
+
open: this.#clients.size,
|
|
595
|
+
tasks: this.#tasks.size,
|
|
596
|
+
});
|
|
485
597
|
if (this.#timer)
|
|
486
598
|
clearInterval(this.#timer);
|
|
487
599
|
const stop = aborted(signal);
|
|
@@ -493,10 +605,20 @@ export class Gateway {
|
|
|
493
605
|
const deadline = performance.now() + this.settings.closeTimeoutMs;
|
|
494
606
|
while (this.#clients.size && performance.now() < deadline && !signal.aborted)
|
|
495
607
|
await Promise.race([delay(10), stop]);
|
|
608
|
+
if (this.#clients.size)
|
|
609
|
+
this.context.logger.log('debug', 'WebSocket drain terminating sockets', {
|
|
610
|
+
open: this.#clients.size,
|
|
611
|
+
aborted: signal.aborted,
|
|
612
|
+
});
|
|
496
613
|
for (const value of this.#clients.values())
|
|
497
614
|
value.socket.terminate();
|
|
498
615
|
await this.hub.events().return?.();
|
|
499
616
|
await Promise.race([this.#loop, stop]);
|
|
500
617
|
await this.#idle(signal, stop, true);
|
|
618
|
+
this.#throttle.flush();
|
|
619
|
+
this.context.logger.log('debug', 'WebSocket drain finished', {
|
|
620
|
+
ms: Math.round(performance.now() - started),
|
|
621
|
+
aborted: signal.aborted,
|
|
622
|
+
});
|
|
501
623
|
}
|
|
502
624
|
}
|
package/dist/index.js
CHANGED
|
@@ -5,7 +5,7 @@ export * from './router.js';
|
|
|
5
5
|
export * from './types.js';
|
|
6
6
|
const hub = providerDependency({
|
|
7
7
|
name: 'dokebi-websocket-hub',
|
|
8
|
-
version: '^0.
|
|
8
|
+
version: '^0.3.0',
|
|
9
9
|
packageName: '@dokebi/websocket-hub',
|
|
10
10
|
load: () => import('@dokebi/websocket-hub'),
|
|
11
11
|
});
|
|
@@ -35,7 +35,7 @@ class WebsocketRuntime {
|
|
|
35
35
|
/** Factory input: `{ app, options? }`. Options default to `app.config['dokebi-websocket']`. */
|
|
36
36
|
export const createPlugin = definePlugin({
|
|
37
37
|
name: 'dokebi-websocket',
|
|
38
|
-
version: '0.
|
|
38
|
+
version: '0.2.0',
|
|
39
39
|
core: '^0.2.0',
|
|
40
40
|
options: parseOptions,
|
|
41
41
|
dependencies: () => [hub, web],
|
package/dist/log.d.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { LogFields, Logger, LogLevel } from '@dokebi/core';
|
|
2
|
+
/**
|
|
3
|
+
* The full text of a caught value for the `error` log field (D-0047): name, whole message and
|
|
4
|
+
* stack, then each `cause` the same way. Only credentials in URLs (`//user:password@`) are
|
|
5
|
+
* removed; a text over 16 KB is cut and marked.
|
|
6
|
+
*/
|
|
7
|
+
export declare function errorText(error: unknown): string;
|
|
8
|
+
/** A stable code of an error (hub, ws or errno code), or `fallback`. */
|
|
9
|
+
export declare function errorCode(error: unknown, fallback: string): string;
|
|
10
|
+
/**
|
|
11
|
+
* Logs a repeating event once per interval (D-0047): the first occurrence at once, the following
|
|
12
|
+
* ones of the same message and code (and `group`, when given) are counted and reported together
|
|
13
|
+
* (`repeated`) when the interval ends. `group` must come from a bounded set (e.g. registered
|
|
14
|
+
* handler types), never from client input, since each value keeps an entry for an interval. Hot paths (per message, per frame) can report every failure without a burst
|
|
15
|
+
* flooding the log. Field and error text are built only for lines that are written.
|
|
16
|
+
*/
|
|
17
|
+
export declare class LogThrottle {
|
|
18
|
+
#private;
|
|
19
|
+
readonly logger: Logger;
|
|
20
|
+
readonly intervalMs: number;
|
|
21
|
+
constructor(logger: Logger, intervalMs?: number);
|
|
22
|
+
report(level: LogLevel, message: string, code: string, error?: unknown, fields?: LogFields, group?: string): void;
|
|
23
|
+
/** Writes the counts still pending (on close), so a burst at shutdown is not lost. */
|
|
24
|
+
flush(): void;
|
|
25
|
+
}
|
package/dist/log.js
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
const CODE = /^[A-Z][A-Z0-9_]{0,63}$/;
|
|
2
|
+
/**
|
|
3
|
+
* The full text of a caught value for the `error` log field (D-0047): name, whole message and
|
|
4
|
+
* stack, then each `cause` the same way. Only credentials in URLs (`//user:password@`) are
|
|
5
|
+
* removed; a text over 16 KB is cut and marked.
|
|
6
|
+
*/
|
|
7
|
+
export function errorText(error) {
|
|
8
|
+
const parts = [];
|
|
9
|
+
let current = error;
|
|
10
|
+
for (let depth = 0; current !== undefined && depth < 5; depth++) {
|
|
11
|
+
let text;
|
|
12
|
+
if (current instanceof Error)
|
|
13
|
+
text = current.stack ?? `${current.name}: ${current.message}`;
|
|
14
|
+
else if (typeof current === 'string')
|
|
15
|
+
text = current;
|
|
16
|
+
else {
|
|
17
|
+
try {
|
|
18
|
+
text = `NonError: ${JSON.stringify(current)}`;
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
text = `NonError: ${String(current)}`; // not serialisable (cycle, BigInt): its string form
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
parts.push(depth ? `Caused by: ${text}` : text);
|
|
25
|
+
current = current instanceof Error ? current.cause : undefined;
|
|
26
|
+
}
|
|
27
|
+
const text = parts.join('\n').replace(/\/\/[^\s/@]*@/g, '//***@');
|
|
28
|
+
return text.length > 16_384
|
|
29
|
+
? `${text.slice(0, 16_384)}… [truncated ${text.length - 16_384} characters]`
|
|
30
|
+
: text;
|
|
31
|
+
}
|
|
32
|
+
/** A stable code of an error (hub, ws or errno code), or `fallback`. */
|
|
33
|
+
export function errorCode(error, fallback) {
|
|
34
|
+
const code = error?.code;
|
|
35
|
+
return typeof code === 'string' && CODE.test(code) ? code : fallback;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Logs a repeating event once per interval (D-0047): the first occurrence at once, the following
|
|
39
|
+
* ones of the same message and code (and `group`, when given) are counted and reported together
|
|
40
|
+
* (`repeated`) when the interval ends. `group` must come from a bounded set (e.g. registered
|
|
41
|
+
* handler types), never from client input, since each value keeps an entry for an interval. Hot paths (per message, per frame) can report every failure without a burst
|
|
42
|
+
* flooding the log. Field and error text are built only for lines that are written.
|
|
43
|
+
*/
|
|
44
|
+
export class LogThrottle {
|
|
45
|
+
logger;
|
|
46
|
+
intervalMs;
|
|
47
|
+
#entries = new Map();
|
|
48
|
+
constructor(logger, intervalMs = 10_000) {
|
|
49
|
+
this.logger = logger;
|
|
50
|
+
this.intervalMs = intervalMs;
|
|
51
|
+
}
|
|
52
|
+
report(level, message, code, error, fields, group) {
|
|
53
|
+
if (!this.logger.isEnabled(level))
|
|
54
|
+
return;
|
|
55
|
+
const key = `${level}\u0000${code}\u0000${message}${group === undefined ? '' : `\u0000${group}`}`;
|
|
56
|
+
const entry = this.#entries.get(key);
|
|
57
|
+
if (entry) {
|
|
58
|
+
entry.count++;
|
|
59
|
+
entry.error = error;
|
|
60
|
+
entry.fields = fields;
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
this.#write(level, message, code, error, fields, 0);
|
|
64
|
+
const value = {
|
|
65
|
+
count: 0,
|
|
66
|
+
error: undefined,
|
|
67
|
+
fields: undefined,
|
|
68
|
+
timer: setTimeout(() => this.#elapsed(key, value, level, message, code), this.intervalMs),
|
|
69
|
+
};
|
|
70
|
+
value.timer.unref();
|
|
71
|
+
this.#entries.set(key, value);
|
|
72
|
+
}
|
|
73
|
+
#elapsed(key, entry, level, message, code) {
|
|
74
|
+
if (!entry.count) {
|
|
75
|
+
this.#entries.delete(key);
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
this.#write(level, message, code, entry.error, entry.fields, entry.count);
|
|
79
|
+
entry.count = 0;
|
|
80
|
+
entry.timer = setTimeout(() => this.#elapsed(key, entry, level, message, code), this.intervalMs);
|
|
81
|
+
entry.timer.unref();
|
|
82
|
+
}
|
|
83
|
+
#write(level, message, code, error, fields, repeated) {
|
|
84
|
+
this.logger.log(level, message, {
|
|
85
|
+
...fields,
|
|
86
|
+
code,
|
|
87
|
+
...(error === undefined ? {} : { error: errorText(error) }),
|
|
88
|
+
...(repeated ? { repeated, intervalMs: this.intervalMs } : {}),
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
/** Writes the counts still pending (on close), so a burst at shutdown is not lost. */
|
|
92
|
+
flush() {
|
|
93
|
+
for (const [key, entry] of this.#entries) {
|
|
94
|
+
clearTimeout(entry.timer);
|
|
95
|
+
if (entry.count) {
|
|
96
|
+
const [level, code, message] = key.split('\u0000');
|
|
97
|
+
this.#write(level, message, code, entry.error, entry.fields, entry.count);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
this.#entries.clear();
|
|
101
|
+
}
|
|
102
|
+
}
|
package/dist/router.d.ts
CHANGED
|
@@ -8,10 +8,12 @@ export interface SocketContext {
|
|
|
8
8
|
/** Sends `{ type, data }` to this connection only. */
|
|
9
9
|
send(type: string, data?: unknown): Promise<void>;
|
|
10
10
|
/**
|
|
11
|
-
* Sends `{ type, data }` through the hub to the tenant, a room or a member
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
11
|
+
* Sends `{ type, data }` through the hub to the tenant, a room or a member: each recipient
|
|
12
|
+
* socket gets it as a text frame, like `send`. Resolves with the receipt `{ id, recipients }`
|
|
13
|
+
* once the hub handed it out (D-0057): at most once, no client ACK and no resend, so a socket
|
|
14
|
+
* that is reconnecting or too slow (1013) misses it. Fails with RECOVERING, BUSY or
|
|
15
|
+
* OUTCOME_UNKNOWN (it may have been delivered); sending again is the caller's decision. For
|
|
16
|
+
* what must not be missed, save it and let pages read the current state when they reconnect.
|
|
15
17
|
*/
|
|
16
18
|
broadcast(type: string, data?: unknown, target?: {
|
|
17
19
|
room?: string;
|
|
@@ -40,6 +42,7 @@ export interface SocketDefinition {
|
|
|
40
42
|
* A WebSocket message router. Messages are JSON `{ type, data?, id? }`. A handler's return value
|
|
41
43
|
* is sent back as `{ type: 'reply', id, data }` when the message had an `id`. Unknown types,
|
|
42
44
|
* malformed messages and handler failures answer `{ type: 'error', id?, code }`; error messages
|
|
43
|
-
* and stacks are never sent.
|
|
45
|
+
* and stacks are never sent: they go to `session.reportError` when the session has it (the
|
|
46
|
+
* gateway's sessions log them). Use the result with `websocket.route(...)`.
|
|
44
47
|
*/
|
|
45
48
|
export declare function defineSocket(definition: SocketDefinition): WebsocketRoute;
|
package/dist/router.js
CHANGED
|
@@ -22,7 +22,8 @@ function errorCode(error) {
|
|
|
22
22
|
* A WebSocket message router. Messages are JSON `{ type, data?, id? }`. A handler's return value
|
|
23
23
|
* is sent back as `{ type: 'reply', id, data }` when the message had an `id`. Unknown types,
|
|
24
24
|
* malformed messages and handler failures answer `{ type: 'error', id?, code }`; error messages
|
|
25
|
-
* and stacks are never sent.
|
|
25
|
+
* and stacks are never sent: they go to `session.reportError` when the session has it (the
|
|
26
|
+
* gateway's sessions log them). Use the result with `websocket.route(...)`.
|
|
26
27
|
*/
|
|
27
28
|
export function defineSocket(definition) {
|
|
28
29
|
const handlers = new Map();
|
|
@@ -60,6 +61,8 @@ export function defineSocket(definition) {
|
|
|
60
61
|
message = JSON.parse(decoder.decode(data));
|
|
61
62
|
}
|
|
62
63
|
catch {
|
|
64
|
+
// Answered to the client (its own error); counted by the session's reporter.
|
|
65
|
+
session.reportError?.(undefined, { source: 'client', code: 'INVALID_MESSAGE' });
|
|
63
66
|
return session.send(frame({ type: 'error', code: 'INVALID_MESSAGE' }));
|
|
64
67
|
}
|
|
65
68
|
const id = message !== null &&
|
|
@@ -68,18 +71,30 @@ export function defineSocket(definition) {
|
|
|
68
71
|
ID.test(message.id)
|
|
69
72
|
? message.id
|
|
70
73
|
: undefined;
|
|
71
|
-
if (message === null || typeof message !== 'object' || typeof message.type !== 'string')
|
|
74
|
+
if (message === null || typeof message !== 'object' || typeof message.type !== 'string') {
|
|
75
|
+
session.reportError?.(undefined, { source: 'client', code: 'INVALID_MESSAGE' });
|
|
72
76
|
return session.send(frame({ type: 'error', ...(id ? { id } : {}), code: 'INVALID_MESSAGE' }));
|
|
77
|
+
}
|
|
73
78
|
const handler = handlers.get(message.type);
|
|
74
|
-
if (!handler)
|
|
79
|
+
if (!handler) {
|
|
80
|
+
session.reportError?.(undefined, {
|
|
81
|
+
source: 'client',
|
|
82
|
+
code: 'UNKNOWN_TYPE',
|
|
83
|
+
type: message.type,
|
|
84
|
+
});
|
|
75
85
|
return session.send(frame({ type: 'error', ...(id ? { id } : {}), code: 'UNKNOWN_TYPE' }));
|
|
86
|
+
}
|
|
76
87
|
const socket = context(session);
|
|
77
88
|
let result;
|
|
78
89
|
try {
|
|
79
90
|
result = await handler(message.data, socket);
|
|
80
91
|
}
|
|
81
92
|
catch (error) {
|
|
82
|
-
|
|
93
|
+
// The client gets the code only; the whole error goes to the session's reporter (the
|
|
94
|
+
// gateway logs it, D-0047). A session without a reporter is used outside the gateway.
|
|
95
|
+
const code = errorCode(error);
|
|
96
|
+
session.reportError?.(error, { source: 'handler', code, type: message.type });
|
|
97
|
+
return session.send(frame({ type: 'error', ...(id ? { id } : {}), code }));
|
|
83
98
|
}
|
|
84
99
|
if (id)
|
|
85
100
|
await session.send(frame(result === undefined ? { type: 'reply', id } : { type: 'reply', id, data: result }));
|
package/dist/types.d.ts
CHANGED
|
@@ -26,10 +26,29 @@ export interface WebsocketPresence {
|
|
|
26
26
|
readonly joined: readonly WebsocketPeer[];
|
|
27
27
|
readonly left: readonly WebsocketPeer[];
|
|
28
28
|
}
|
|
29
|
+
/**
|
|
30
|
+
* What a message router answered with an error frame instead of a reply (D-0047), passed to
|
|
31
|
+
* `WebsocketSession.reportError` so the cause reaches the server log.
|
|
32
|
+
*/
|
|
33
|
+
export interface WebsocketErrorDetails {
|
|
34
|
+
/** `handler`: a message handler threw. `client`: the message was malformed or of an unknown type. */
|
|
35
|
+
readonly source: 'handler' | 'client';
|
|
36
|
+
/** The code sent to the client, e.g. the error's code, `HANDLER_FAILED` or `UNKNOWN_TYPE`. */
|
|
37
|
+
readonly code: string;
|
|
38
|
+
/** The message type, when the message had one. */
|
|
39
|
+
readonly type?: string;
|
|
40
|
+
}
|
|
29
41
|
export interface WebsocketSession {
|
|
30
42
|
readonly id: string;
|
|
31
43
|
readonly identity: WebsocketIdentity;
|
|
32
44
|
send(data: string | Uint8Array): Promise<void>;
|
|
45
|
+
/**
|
|
46
|
+
* Hands `data` to the connections of this tenant (or a room or member of it) through the hub,
|
|
47
|
+
* at most once (D-0057). Each recipient socket gets the bytes as they are: a text frame when
|
|
48
|
+
* they are valid UTF-8, a binary frame otherwise. The receipt `{ id, recipients }` lists the
|
|
49
|
+
* connections that matched when it was sent, not ones that confirmed it. Fails with
|
|
50
|
+
* RECOVERING, BUSY or OUTCOME_UNKNOWN; nothing is resent.
|
|
51
|
+
*/
|
|
33
52
|
broadcast(data: Uint8Array, target?: {
|
|
34
53
|
room?: string;
|
|
35
54
|
member?: string;
|
|
@@ -37,6 +56,13 @@ export interface WebsocketSession {
|
|
|
37
56
|
join(room: string): Promise<void>;
|
|
38
57
|
leave(room: string): Promise<void>;
|
|
39
58
|
close(code?: number, reason?: string): void;
|
|
59
|
+
/**
|
|
60
|
+
* Reports a failure the route turned into a client error frame (D-0047). The gateway logs it
|
|
61
|
+
* (handler failures at error, client errors at debug, repeats counted); a session without it
|
|
62
|
+
* (a custom or test session) leaves reporting to the route. `error` is undefined for client
|
|
63
|
+
* errors that have no cause worth logging.
|
|
64
|
+
*/
|
|
65
|
+
reportError?(error: unknown, details: WebsocketErrorDetails): void;
|
|
40
66
|
}
|
|
41
67
|
export interface WebsocketRoute {
|
|
42
68
|
readonly path: string;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dokebi/websocket",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -10,10 +10,6 @@
|
|
|
10
10
|
".": {
|
|
11
11
|
"types": "./dist/index.d.ts",
|
|
12
12
|
"import": "./dist/index.js"
|
|
13
|
-
},
|
|
14
|
-
"./client": {
|
|
15
|
-
"types": "./dist/client.d.ts",
|
|
16
|
-
"import": "./dist/client.js"
|
|
17
13
|
}
|
|
18
14
|
},
|
|
19
15
|
"files": [
|
|
@@ -38,11 +34,11 @@
|
|
|
38
34
|
"peerDependencies": {
|
|
39
35
|
"@dokebi/core": "^0.2.0",
|
|
40
36
|
"@dokebi/web": "^0.1.0",
|
|
41
|
-
"@dokebi/websocket-hub": "^0.
|
|
37
|
+
"@dokebi/websocket-hub": "^0.3.0"
|
|
42
38
|
},
|
|
43
39
|
"devDependencies": {
|
|
44
|
-
"@dokebi/web": "0.1.
|
|
45
|
-
"@dokebi/websocket-hub": "0.
|
|
40
|
+
"@dokebi/web": "0.1.2",
|
|
41
|
+
"@dokebi/websocket-hub": "0.3.0"
|
|
46
42
|
},
|
|
47
43
|
"dokebi": {
|
|
48
44
|
"schemaVersion": 2,
|
|
@@ -51,7 +47,7 @@
|
|
|
51
47
|
"dependencies": [
|
|
52
48
|
{
|
|
53
49
|
"name": "dokebi-websocket-hub",
|
|
54
|
-
"version": "^0.
|
|
50
|
+
"version": "^0.3.0"
|
|
55
51
|
},
|
|
56
52
|
{
|
|
57
53
|
"name": "dokebi-web",
|
package/dist/client.d.ts
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
/** Keep one receiver per authenticated clientId across socket reconnects. No Node dependencies. */
|
|
2
|
-
export declare class DeliveryReceiver {
|
|
3
|
-
#private;
|
|
4
|
-
readonly capacity: number;
|
|
5
|
-
constructor(capacity?: number);
|
|
6
|
-
receive(raw: string | Uint8Array, deliver: (data: Uint8Array, id: string) => void | Promise<void>, acknowledge: (frame: string) => void): Promise<boolean>;
|
|
7
|
-
}
|
package/dist/client.js
DELETED
|
@@ -1,60 +0,0 @@
|
|
|
1
|
-
const decoder = new TextDecoder();
|
|
2
|
-
/** Keep one receiver per authenticated clientId across socket reconnects. No Node dependencies. */
|
|
3
|
-
export class DeliveryReceiver {
|
|
4
|
-
capacity;
|
|
5
|
-
#seen = new Map();
|
|
6
|
-
#sweepAt = 0;
|
|
7
|
-
constructor(capacity = 10000) {
|
|
8
|
-
this.capacity = capacity;
|
|
9
|
-
if (!Number.isSafeInteger(capacity) || capacity < 1)
|
|
10
|
-
throw new Error('Invalid capacity');
|
|
11
|
-
}
|
|
12
|
-
async receive(raw, deliver, acknowledge) {
|
|
13
|
-
const text = typeof raw === 'string' ? raw : decoder.decode(raw);
|
|
14
|
-
let frame;
|
|
15
|
-
try {
|
|
16
|
-
frame = JSON.parse(text);
|
|
17
|
-
}
|
|
18
|
-
catch {
|
|
19
|
-
return false;
|
|
20
|
-
}
|
|
21
|
-
if (frame?.$dokebi !== 'delivery-v1')
|
|
22
|
-
return false;
|
|
23
|
-
if (typeof frame.id !== 'string' ||
|
|
24
|
-
!/^[a-f0-9-]{36}$/.test(frame.id) ||
|
|
25
|
-
typeof frame.expiresAt !== 'number' ||
|
|
26
|
-
!Number.isSafeInteger(frame.expiresAt) ||
|
|
27
|
-
typeof frame.data !== 'string')
|
|
28
|
-
throw new Error('Invalid delivery');
|
|
29
|
-
const now = Date.now();
|
|
30
|
-
if (now > frame.expiresAt)
|
|
31
|
-
return true;
|
|
32
|
-
if (now >= this.#sweepAt) {
|
|
33
|
-
for (const [id, entry] of this.#seen)
|
|
34
|
-
if (entry.expiresAt + 5000 < now)
|
|
35
|
-
this.#seen.delete(id);
|
|
36
|
-
this.#sweepAt = now + 1000;
|
|
37
|
-
}
|
|
38
|
-
const id = frame.id;
|
|
39
|
-
let entry = this.#seen.get(id);
|
|
40
|
-
if (!entry) {
|
|
41
|
-
if (this.#seen.size >= this.capacity)
|
|
42
|
-
throw new Error('Delivery receiver capacity exceeded');
|
|
43
|
-
const binary = atob(frame.data), bytes = new Uint8Array(binary.length);
|
|
44
|
-
for (let index = 0; index < binary.length; index++)
|
|
45
|
-
bytes[index] = binary.charCodeAt(index);
|
|
46
|
-
entry = {
|
|
47
|
-
expiresAt: frame.expiresAt,
|
|
48
|
-
work: Promise.resolve().then(() => deliver(bytes, id)),
|
|
49
|
-
};
|
|
50
|
-
this.#seen.set(id, entry);
|
|
51
|
-
void entry.work?.catch(() => {
|
|
52
|
-
this.#seen.delete(id);
|
|
53
|
-
});
|
|
54
|
-
}
|
|
55
|
-
await entry.work;
|
|
56
|
-
entry.work = undefined;
|
|
57
|
-
acknowledge(JSON.stringify({ $dokebi: 'ack-v1', id }));
|
|
58
|
-
return true;
|
|
59
|
-
}
|
|
60
|
-
}
|