@sonamu-kit/websocket-redis-adapter 0.0.0-stage → 0.13.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/README.md +147 -2
- package/dist/cluster-bus.d.ts +49 -0
- package/dist/cluster-bus.d.ts.map +1 -0
- package/dist/cluster-bus.js +199 -0
- package/dist/cluster-bus.js.map +1 -0
- package/dist/connection.d.ts +111 -0
- package/dist/connection.d.ts.map +1 -0
- package/dist/connection.js +315 -0
- package/dist/connection.js.map +1 -0
- package/dist/deadline.d.ts +14 -0
- package/dist/deadline.d.ts.map +1 -0
- package/dist/deadline.js +30 -0
- package/dist/deadline.js.map +1 -0
- package/dist/index.d.ts +27 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +31 -0
- package/dist/index.js.map +1 -0
- package/dist/options.d.ts +31 -0
- package/dist/options.d.ts.map +1 -0
- package/dist/options.js +40 -0
- package/dist/options.js.map +1 -0
- package/dist/presence-store.d.ts +113 -0
- package/dist/presence-store.d.ts.map +1 -0
- package/dist/presence-store.js +449 -0
- package/dist/presence-store.js.map +1 -0
- package/dist/scripts.d.ts +23 -0
- package/dist/scripts.d.ts.map +1 -0
- package/dist/scripts.js +180 -0
- package/dist/scripts.js.map +1 -0
- package/package.json +54 -3
package/README.md
CHANGED
|
@@ -1,3 +1,148 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @sonamu-kit/websocket-redis-adapter
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[node-redis](https://github.com/redis/node-redis) 기반 `WebSocketPresenceStore`와 `WebSocketClusterBus` 구현입니다. 여러 Sonamu 노드가 하나의 Redis(standalone 또는 Sentinel)를 공유해 room, user, connections, all, union audience 메시지를 노드 간에 전달합니다.
|
|
4
|
+
|
|
5
|
+
## 설치
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pnpm add @sonamu-kit/websocket-redis-adapter redis
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
| peer dependency | 범위 |
|
|
12
|
+
| --- | --- |
|
|
13
|
+
| `redis` | `^6` |
|
|
14
|
+
| `sonamu` | `>=0.12.0` |
|
|
15
|
+
|
|
16
|
+
`redis` v6은 Node.js 20 이상이 필요합니다.
|
|
17
|
+
|
|
18
|
+
## 사용법
|
|
19
|
+
|
|
20
|
+
`createRedisWebSocketAdapter(...)`의 반환값(`nodeId`, `presenceStore`, `clusterBus`)을 WebSocket 옵션에 그대로 펼쳐 넣습니다. 런타임은 store/bus의 `nodeId`가 자신의 `nodeId`와 다르면 생성 시점에 실패하므로, 펼쳐 넣으면 세 값이 항상 일치합니다.
|
|
21
|
+
|
|
22
|
+
```ts
|
|
23
|
+
// sonamu.config.ts
|
|
24
|
+
import { createRedisWebSocketAdapter } from "@sonamu-kit/websocket-redis-adapter";
|
|
25
|
+
|
|
26
|
+
export default defineConfig({
|
|
27
|
+
server: {
|
|
28
|
+
websocket: {
|
|
29
|
+
...createRedisWebSocketAdapter({
|
|
30
|
+
redis: { url: process.env.REDIS_URL },
|
|
31
|
+
// Redis를 여러 앱이 공유하면 앱마다 다르게 설정합니다
|
|
32
|
+
prefix: "my-app:ws",
|
|
33
|
+
}),
|
|
34
|
+
},
|
|
35
|
+
},
|
|
36
|
+
});
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
`createWebSocketRuntime`을 직접 쓰는 경우도 같습니다.
|
|
40
|
+
|
|
41
|
+
```ts
|
|
42
|
+
const runtime = createWebSocketRuntime({
|
|
43
|
+
...createRedisWebSocketAdapter({ redis: { url: process.env.REDIS_URL } }),
|
|
44
|
+
drainTimeoutMs: 5000,
|
|
45
|
+
});
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
생성만으로는 Redis에 연결하지 않습니다. 첫 등록, 조회, 구독, publish 때 연결합니다(lazy connect).
|
|
49
|
+
|
|
50
|
+
### Redis 입력과 소유권
|
|
51
|
+
|
|
52
|
+
| `redis` 입력 | 명령 연결 | pub/sub 연결 | connect/close |
|
|
53
|
+
| --- | --- | --- | --- |
|
|
54
|
+
| `RedisClientOptions` | 어댑터가 `createClient`로 생성 | 명령 client의 `duplicate()` | 둘 다 어댑터가 연결하고 닫습니다 |
|
|
55
|
+
| `RedisClientType` (`createClient(...)`) | 호출자 client | 호출자 client의 `duplicate()` 하나 | 호출자 client는 연결하거나 닫지 않습니다. `duplicate()`만 어댑터가 연결하고 닫습니다 |
|
|
56
|
+
| `RedisSentinelType` (`createSentinel(...)`) | 호출자 Sentinel | Sentinel 인스턴스의 `subscribe` | 연결하거나 닫지 않으며 `duplicate()`도 만들지 않습니다 |
|
|
57
|
+
|
|
58
|
+
호출자 client나 Sentinel은 직접 `connect()`해야 합니다. 연결되지 않은 상태에서 쓰면 아래 실패 규칙에 따라 로컬 전용으로 동작합니다.
|
|
59
|
+
|
|
60
|
+
어댑터가 만든 client(연결 옵션 입력의 client와 모든 `duplicate()`)는 `disableOfflineQueue: true`와 `commandOptions.timeout = commandDeadlineMs`로 만들고 `error` 리스너를 붙입니다. 처리되지 않은 `error` 이벤트가 프로세스를 종료시키지 않습니다. 호출자 client와 Sentinel의 `error` 리스너는 호출자가 붙여야 합니다.
|
|
61
|
+
|
|
62
|
+
### Sentinel
|
|
63
|
+
|
|
64
|
+
```ts
|
|
65
|
+
import { createSentinel } from "redis";
|
|
66
|
+
|
|
67
|
+
const sentinel = createSentinel({
|
|
68
|
+
name: "mymaster",
|
|
69
|
+
sentinelRootNodes: [{ host: "sentinel", port: 26379 }],
|
|
70
|
+
});
|
|
71
|
+
sentinel.on("error", (error) => logger.error(error));
|
|
72
|
+
await sentinel.connect();
|
|
73
|
+
|
|
74
|
+
const adapter = createRedisWebSocketAdapter({ redis: sentinel, prefix: "my-app:ws" });
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
- 구독은 Sentinel 인스턴스의 `subscribe`를 씁니다. Sentinel이 failover 때 구독을 새 master로 옮깁니다.
|
|
78
|
+
- Lua 스크립트 캐시는 복제되지 않으므로 failover 직후 `EVALSHA`가 `NOSCRIPT`로 실패합니다. 어댑터는 `SCRIPT LOAD` 뒤 한 번 재시도합니다.
|
|
79
|
+
- `topology-change`의 `MASTER_CHANGE`가 직전에 관찰한 master와 다른 master를 알리면 노드 키 rebuild를 예약합니다. A→B→A처럼 되돌아가는 변경도 매번 rebuild합니다. node-redis는 `nodeAddressMap`을 쓰면 master가 그대로여도 scan마다 같은 master로 `MASTER_CHANGE`를 다시 보내는데, 직전 master와 같은 이벤트는 무시합니다.
|
|
80
|
+
|
|
81
|
+
Redis Cluster(`createCluster`)와 sharded pub/sub는 아직 지원하지 않습니다. 키 레이아웃은 Cluster에서도 노드별 키가 한 slot에 놓이도록 해시태그를 씁니다.
|
|
82
|
+
|
|
83
|
+
## 옵션
|
|
84
|
+
|
|
85
|
+
| 옵션 | 기본값 | 설명 |
|
|
86
|
+
| --- | --- | --- |
|
|
87
|
+
| `redis` | (필수) | 연결 옵션, `RedisClientType`, `RedisSentinelType` 중 하나 |
|
|
88
|
+
| `nodeId` | `${hostname()}-${process.pid}-${랜덤}` | sonamu `createWebSocketNodeId()`와 같은 형식. 재시작한 노드가 이전 상태를 물려받지 않습니다 |
|
|
89
|
+
| `prefix` | `sonamu:ws` | 모든 키와 pub/sub 채널의 접두사 |
|
|
90
|
+
| `heartbeatIntervalMs` | `5000` | 노드 키 TTL과 `<prefix>:nodes` score를 갱신하는 주기 |
|
|
91
|
+
| `nodeTimeoutMs` | `15000` | heartbeat score가 이보다 오래된 노드는 라우팅에서 제외합니다(heartbeat 3회 누락) |
|
|
92
|
+
| `keyTtlMs` | `30000` | 노드 키의 TTL. crash한 노드의 키는 이 시간 뒤 만료됩니다 |
|
|
93
|
+
| `commandDeadlineMs` | `2000` | 모든 Redis 호출의 어댑터 deadline |
|
|
94
|
+
| `readyTimeoutMs` | `3000` | 첫 연결이 ready가 되기를 기다리는 상한 |
|
|
95
|
+
| `drainTimeoutMs` | `5000` | shutdown 때 진행 중인 쓰기를 기다리는 상한 |
|
|
96
|
+
|
|
97
|
+
## Redis 데이터 모델
|
|
98
|
+
|
|
99
|
+
| 키 | 타입 | 내용 |
|
|
100
|
+
| --- | --- | --- |
|
|
101
|
+
| `<prefix>:{<nodeId>}:sessions` | Hash | sessionId → presence JSON (`namespace`, `active`, `rooms` 배열, 타입 태그가 붙은 `userId`, epoch ms 날짜) |
|
|
102
|
+
| `<prefix>:{<nodeId>}:rooms` | Hash | namespace + roomId → 활성 세션 수 |
|
|
103
|
+
| `<prefix>:{<nodeId>}:users` | Hash | namespace + 타입 태그 userId → 활성 세션 수 (`1`과 `"1"`은 다른 사용자) |
|
|
104
|
+
| `<prefix>:{<nodeId>}:namespaces` | Hash | namespace → 활성 세션 수 |
|
|
105
|
+
| `<prefix>:nodes` | Sorted set | nodeId → 마지막 heartbeat 시각 |
|
|
106
|
+
| `<prefix>:node:<nodeId>` | pub/sub 채널 | 그 노드로 가는 envelope |
|
|
107
|
+
|
|
108
|
+
- 각 mutation은 Lua 스크립트 하나를 `EVALSHA`로 실행해 세션과 count를 원자적으로 갱신합니다. 스크립트가 다루는 키는 모두 `KEYS`로 전달합니다.
|
|
109
|
+
- 라우팅은 live 노드 목록을 읽고 노드별 count를 pipeline 한 번으로 조회합니다. 세션 목록은 읽지 않습니다.
|
|
110
|
+
- audience와 `getRoomMemberCount`의 namespace가 없거나 빈 문자열(`""`)이면 core와 같이 모든 namespace를 대상으로 합니다.
|
|
111
|
+
- `getRoomMemberCount`는 live 노드의 활성 방 인원수 합계입니다. 자기 노드 인원은 메모리에서 세고, 원격 노드 인원만 Redis count로 셉니다. 그래서 rebuild 대기 중이거나 자기 노드 키가 사라져도 자기 노드 인원은 정확합니다. `getRoomMembers`, `getConnection` 같은 다른 읽기 API는 노드 로컬입니다.
|
|
112
|
+
|
|
113
|
+
## `keyPrefix`와 어댑터 `prefix`
|
|
114
|
+
|
|
115
|
+
격리는 어댑터 `prefix`로 합니다. 호출자 client에 `keyPrefix`가 있으면 어댑터 키 앞에 정확히 한 번 더 붙습니다(`app:` + `sonamu:ws:{node}:sessions`). `EVALSHA`의 `KEYS`와 `duplicate()` 연결도 같은 규칙을 따릅니다.
|
|
116
|
+
|
|
117
|
+
pub/sub 채널에는 `keyPrefix`가 붙지 않습니다. **하나의 Redis를 여러 앱이 공유하면 앱마다 어댑터 `prefix`를 다르게 설정해야 합니다.** `keyPrefix`만 다르게 하면 키는 분리되지만 채널이 겹쳐 다른 앱의 envelope을 받습니다.
|
|
118
|
+
|
|
119
|
+
## 실패 동작
|
|
120
|
+
|
|
121
|
+
어댑터는 node-redis의 timeout에 의존하지 않습니다. node-redis의 `commandOptions.timeout`은 아직 소켓에 쓰지 않은 명령에만 적용되므로, 모든 Redis 호출을 `commandDeadlineMs` deadline으로 감싸고 늦게 도착한 결과는 무시합니다.
|
|
122
|
+
|
|
123
|
+
| 상황 | 동작 |
|
|
124
|
+
| --- | --- |
|
|
125
|
+
| mutation(등록, join, setUserId 등)이 실패하거나 deadline을 넘김 | 런타임 메모리는 이미 갱신됐으므로 로컬 전달은 계속됩니다. 서버에서 실행됐을 수 있으므로 노드를 rebuild 대기로 표시합니다 |
|
|
126
|
+
| 첫 연결이 `readyTimeoutMs` 안에 ready가 되지 않음 | `registerConnection`은 메모리 전용 등록으로 resolve하고 rebuild 대기가 됩니다 |
|
|
127
|
+
| 어댑터 소유 client가 오프라인 | 명령이 deadline을 기다리지 않고 즉시 실패합니다 |
|
|
128
|
+
| 라우팅 조회 실패 | 로컬 전달만 하고 원격은 건너뜁니다. publish는 resolve합니다 |
|
|
129
|
+
| `getRoomMemberCount` 실패 | 런타임이 로컬 수에 `partial: true`를 붙여 돌려줍니다 |
|
|
130
|
+
| 구독이 시간 안에 끝나지 않음 | `subscribe`는 reject하지만 구독 시도는 남아 연결이 ready가 되면 이어집니다 |
|
|
131
|
+
| crash한 노드 | heartbeat score가 `nodeTimeoutMs`보다 오래되면 라우팅에서 빠지고, 키는 `keyTtlMs` 뒤 만료됩니다 |
|
|
132
|
+
|
|
133
|
+
rebuild 대기 상태는 다음 중 먼저 오는 계기에 메모리 상태로 노드 키 전체를 스크립트 하나로 다시 써서 해소합니다. 실패한 `unregister`가 남긴 고스트 엔트리도 이때 사라집니다. 계기가 여러 번 와도 첫 계기부터 200ms 뒤에 한 번만 실행하며, 계기가 계속 와도 실행이 뒤로 밀리지 않습니다.
|
|
134
|
+
|
|
135
|
+
- standalone client의 `ready` 이벤트(재연결)
|
|
136
|
+
- Sentinel `MASTER_CHANGE`
|
|
137
|
+
- 다음에 성공한 heartbeat (연결은 유지된 채 응답만 멈췄던 경우)
|
|
138
|
+
- heartbeat가 메모리상 있어야 할 노드 키가 없다고 확인한 경우 (명령 실패 없이 키가 eviction이나 `FLUSHDB`로 사라진 경우). heartbeat는 노드 키 4개의 `PEXPIRE` 결과를 메모리와 비교합니다. `sessions`는 세션이 있을 때, `namespaces`는 활성 세션이 있을 때, `rooms`는 방에 들어간 활성 세션이 있을 때, `users`는 userId가 있는 활성 세션이 있을 때 있어야 합니다. 그 밖에 키가 없는 것은 정상이므로 rebuild하지 않습니다. rebuild 직후의 heartbeat가 키 유실을 확인하면 debounce를 거쳐 다시 rebuild합니다
|
|
139
|
+
|
|
140
|
+
rebuild와 세션별 쓰기는 모두 명령을 보내는 순간의 메모리 상태를 씁니다. `NOSCRIPT` 재시도나 ready 대기 뒤에도 상태를 다시 읽어 보내므로, rebuild가 그 사이에 성공한 mutation을 오래된 상태로 덮어쓰지 않습니다.
|
|
141
|
+
|
|
142
|
+
`presenceStore.getStatus()`는 `{ ready, rebuildPending }`을 돌려줍니다.
|
|
143
|
+
|
|
144
|
+
### shutdown
|
|
145
|
+
|
|
146
|
+
런타임 `shutdown()`이 store와 bus의 `shutdown()`을 호출합니다. store는 진행 중인 쓰기를 `drainTimeoutMs`까지 기다린 뒤 노드 키를 지우고 `<prefix>:nodes`에서 자기 노드를 뺍니다. drain이 시간 안에 끝나지 않아도 키 삭제는 진행합니다. shutdown이 시작된 뒤에는 새 mutation뿐 아니라 ready를 기다리던 쓰기, `NOSCRIPT` 재시도, heartbeat, rebuild도 Redis로 보내지 않으므로 정리한 노드 키가 다시 생기지 않습니다. drain 대기 타이머를 포함해 shutdown이 만든 타이머는 모두 정리되고, 어댑터가 소유한 연결만 닫습니다.
|
|
147
|
+
|
|
148
|
+
bus는 shutdown 뒤 구독을 새로 시작하지 않습니다. ready를 기다리던 구독은 보내지 않고 버리며, 어댑터 deadline이 지난 뒤 node-redis에서 늦게 끝난 구독은 끝나는 즉시 같은 연결에서 해제합니다. 따라서 호출자 Sentinel에 어댑터 채널 구독이 남지 않습니다.
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { type WebSocketClusterBus, type WebSocketClusterEnvelope, type WebSocketClusterEnvelopeHandler } from "sonamu";
|
|
2
|
+
import { type RedisWebSocketConnection } from "./connection";
|
|
3
|
+
/**
|
|
4
|
+
* 노드별 pub/sub 채널. 채널에는 client keyPrefix가 붙지 않으므로 어댑터 prefix만으로 앱을 구분한다.
|
|
5
|
+
*/
|
|
6
|
+
export declare function nodeChannelOf(prefix: string, nodeId: string): string;
|
|
7
|
+
/**
|
|
8
|
+
* 채널로 받은 envelope JSON을 검증한다. 형식이 맞지 않으면 undefined를 돌려 버린다.
|
|
9
|
+
*/
|
|
10
|
+
export declare function parseClusterEnvelope(message: string): WebSocketClusterEnvelope | undefined;
|
|
11
|
+
/**
|
|
12
|
+
* node-redis pub/sub 기반 cluster bus. 노드마다 채널 하나를 구독하고, envelope을 대상 노드 채널에만 publish한다.
|
|
13
|
+
* 한 노드의 publish는 같은 명령 연결로 순서대로 나가므로 수신 노드에도 보낸 순서대로 도착한다.
|
|
14
|
+
*/
|
|
15
|
+
export declare class RedisWebSocketClusterBus implements WebSocketClusterBus {
|
|
16
|
+
readonly nodeId: string;
|
|
17
|
+
private readonly connection;
|
|
18
|
+
private readonly channel;
|
|
19
|
+
private readonly handlers;
|
|
20
|
+
private subscribed;
|
|
21
|
+
private subscribing;
|
|
22
|
+
private pendingSubscribes;
|
|
23
|
+
private closed;
|
|
24
|
+
private shutdownPromise;
|
|
25
|
+
private readonly listener;
|
|
26
|
+
/** @internal createRedisWebSocketAdapter가 생성한다. */
|
|
27
|
+
constructor(connection: RedisWebSocketConnection);
|
|
28
|
+
publish(envelope: WebSocketClusterEnvelope): Promise<void>;
|
|
29
|
+
/**
|
|
30
|
+
* 자기 노드 채널을 구독한다. 구독이 끝나면 resolve하고, readyTimeoutMs와 commandDeadlineMs 안에 끝나지 않으면 reject한다.
|
|
31
|
+
* reject돼도 핸들러는 남아 있어 연결이 ready가 되면 구독이 이어진다(shutdown이나 해제 함수로 정리한다).
|
|
32
|
+
*/
|
|
33
|
+
subscribe(handler: WebSocketClusterEnvelopeHandler): Promise<() => void>;
|
|
34
|
+
shutdown(): Promise<void>;
|
|
35
|
+
private close;
|
|
36
|
+
private releaseSubscription;
|
|
37
|
+
private ensureSubscribed;
|
|
38
|
+
private subscribeChannel;
|
|
39
|
+
/**
|
|
40
|
+
* deadline과 무관하게 node-redis SUBSCRIBE가 실제로 끝나는 시점을 본다.
|
|
41
|
+
* 그때 bus가 닫혔거나 더 이상 구독할 핸들러가 없으면 같은 연결에서 바로 구독을 해제하고,
|
|
42
|
+
* 아직 구독이 필요하면 늦게 끝난 구독을 그대로 쓴다.
|
|
43
|
+
*/
|
|
44
|
+
private watchLateSubscribe;
|
|
45
|
+
private retrySubscription;
|
|
46
|
+
private dropSubscription;
|
|
47
|
+
private unsubscribeFrom;
|
|
48
|
+
}
|
|
49
|
+
//# sourceMappingURL=cluster-bus.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cluster-bus.d.ts","sourceRoot":"","sources":["../src/cluster-bus.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,mBAAmB,EACxB,KAAK,wBAAwB,EAC7B,KAAK,+BAA+B,EACrC,MAAM,QAAQ,CAAC;AAGhB,OAAO,EAGL,KAAK,wBAAwB,EAC9B,MAAM,cAAc,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
+
/**
|
|
5
|
+
* 노드별 pub/sub 채널. 채널에는 client keyPrefix가 붙지 않으므로 어댑터 prefix만으로 앱을 구분한다.
|
|
6
|
+
*/
|
|
7
|
+
function nodeChannelOf(prefix, nodeId) {
|
|
8
|
+
return `${prefix}:node:${nodeId}`;
|
|
9
|
+
}
|
|
10
|
+
const AudienceSchema = z.lazy(() => z.discriminatedUnion("type", [
|
|
11
|
+
z.object({
|
|
12
|
+
type: z.literal("all"),
|
|
13
|
+
namespace: z.string().optional()
|
|
14
|
+
}),
|
|
15
|
+
z.object({
|
|
16
|
+
type: z.literal("room"),
|
|
17
|
+
roomId: z.string(),
|
|
18
|
+
namespace: z.string().optional()
|
|
19
|
+
}),
|
|
20
|
+
z.object({
|
|
21
|
+
type: z.literal("user"),
|
|
22
|
+
userId: z.union([z.number(), z.string()]),
|
|
23
|
+
namespace: z.string().optional()
|
|
24
|
+
}),
|
|
25
|
+
z.object({
|
|
26
|
+
type: z.literal("connections"),
|
|
27
|
+
connectionIds: z.array(z.string()),
|
|
28
|
+
namespace: z.string().optional()
|
|
29
|
+
}),
|
|
30
|
+
z.object({
|
|
31
|
+
type: z.literal("union"),
|
|
32
|
+
audiences: z.array(AudienceSchema)
|
|
33
|
+
})
|
|
34
|
+
]));
|
|
35
|
+
const ClusterEnvelopeSchema = z.object({
|
|
36
|
+
id: z.string(),
|
|
37
|
+
sourceNodeId: z.string(),
|
|
38
|
+
targetNodeIds: z.array(z.string()),
|
|
39
|
+
audience: AudienceSchema,
|
|
40
|
+
event: z.string(),
|
|
41
|
+
frames: z.record(z.string(), z.string()),
|
|
42
|
+
emittedAt: z.number()
|
|
43
|
+
});
|
|
44
|
+
const ClusterMessageSchema = z.string().transform((message, context) => {
|
|
45
|
+
try {
|
|
46
|
+
return JSON.parse(message);
|
|
47
|
+
} catch {
|
|
48
|
+
context.addIssue({
|
|
49
|
+
code: "custom",
|
|
50
|
+
message: "envelope JSON을 파싱할 수 없습니다."
|
|
51
|
+
});
|
|
52
|
+
return z.NEVER;
|
|
53
|
+
}
|
|
54
|
+
}).pipe(ClusterEnvelopeSchema);
|
|
55
|
+
/**
|
|
56
|
+
* 채널로 받은 envelope JSON을 검증한다. 형식이 맞지 않으면 undefined를 돌려 버린다.
|
|
57
|
+
*/
|
|
58
|
+
function parseClusterEnvelope(message) {
|
|
59
|
+
const parsed = ClusterMessageSchema.safeParse(message);
|
|
60
|
+
return parsed.success ? parsed.data : void 0;
|
|
61
|
+
}
|
|
62
|
+
function ignoreError() {}
|
|
63
|
+
/**
|
|
64
|
+
* node-redis pub/sub 기반 cluster bus. 노드마다 채널 하나를 구독하고, envelope을 대상 노드 채널에만 publish한다.
|
|
65
|
+
* 한 노드의 publish는 같은 명령 연결로 순서대로 나가므로 수신 노드에도 보낸 순서대로 도착한다.
|
|
66
|
+
*/
|
|
67
|
+
var RedisWebSocketClusterBus = class {
|
|
68
|
+
nodeId;
|
|
69
|
+
connection;
|
|
70
|
+
channel;
|
|
71
|
+
handlers = /* @__PURE__ */ new Set();
|
|
72
|
+
subscribed = false;
|
|
73
|
+
subscribing;
|
|
74
|
+
pendingSubscribes = 0;
|
|
75
|
+
closed = false;
|
|
76
|
+
shutdownPromise;
|
|
77
|
+
listener = (message) => {
|
|
78
|
+
const envelope = parseClusterEnvelope(message.toString());
|
|
79
|
+
if (!envelope) return;
|
|
80
|
+
for (const handler of this.handlers) Promise.resolve().then(() => handler(envelope)).catch(ignoreError);
|
|
81
|
+
};
|
|
82
|
+
/** @internal createRedisWebSocketAdapter가 생성한다. */
|
|
83
|
+
constructor(connection) {
|
|
84
|
+
this.connection = connection;
|
|
85
|
+
this.nodeId = connection.options.nodeId;
|
|
86
|
+
this.channel = nodeChannelOf(connection.options.prefix, this.nodeId);
|
|
87
|
+
connection.onConnectionReady(() => {
|
|
88
|
+
this.retrySubscription();
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
async publish(envelope) {
|
|
92
|
+
if (this.closed) return;
|
|
93
|
+
const message = JSON.stringify(envelope);
|
|
94
|
+
const prefix = this.connection.options.prefix;
|
|
95
|
+
const targets = [...new Set(envelope.targetNodeIds)];
|
|
96
|
+
if (targets.length === 0) return;
|
|
97
|
+
const wait = this.connection.whenUsable();
|
|
98
|
+
if (wait) {
|
|
99
|
+
await wait;
|
|
100
|
+
if (this.closed) return;
|
|
101
|
+
}
|
|
102
|
+
await this.connection.run((commands) => Promise.all(targets.map((target) => commands.publish(nodeChannelOf(prefix, target), message))));
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* 자기 노드 채널을 구독한다. 구독이 끝나면 resolve하고, readyTimeoutMs와 commandDeadlineMs 안에 끝나지 않으면 reject한다.
|
|
106
|
+
* reject돼도 핸들러는 남아 있어 연결이 ready가 되면 구독이 이어진다(shutdown이나 해제 함수로 정리한다).
|
|
107
|
+
*/
|
|
108
|
+
async subscribe(handler) {
|
|
109
|
+
if (this.closed) throw new Error("Redis WebSocket cluster bus is shut down.");
|
|
110
|
+
this.handlers.add(handler);
|
|
111
|
+
const unsubscribe = () => {
|
|
112
|
+
this.handlers.delete(handler);
|
|
113
|
+
if (this.handlers.size === 0) this.dropSubscription();
|
|
114
|
+
};
|
|
115
|
+
await this.ensureSubscribed();
|
|
116
|
+
return unsubscribe;
|
|
117
|
+
}
|
|
118
|
+
shutdown() {
|
|
119
|
+
this.shutdownPromise ??= this.close();
|
|
120
|
+
return this.shutdownPromise;
|
|
121
|
+
}
|
|
122
|
+
async close() {
|
|
123
|
+
this.closed = true;
|
|
124
|
+
this.handlers.clear();
|
|
125
|
+
await Promise.all([this.releaseSubscription(), this.connection.release("bus")]);
|
|
126
|
+
}
|
|
127
|
+
async releaseSubscription() {
|
|
128
|
+
if (this.connection.kind === "sentinel") {
|
|
129
|
+
const wasSubscribed = this.subscribed || this.pendingSubscribes > 0;
|
|
130
|
+
this.subscribed = false;
|
|
131
|
+
this.subscribing = void 0;
|
|
132
|
+
if (wasSubscribed) await this.unsubscribeFrom(this.connection.subscriber(ignoreError)).catch(ignoreError);
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
this.subscribed = false;
|
|
136
|
+
this.subscribing = void 0;
|
|
137
|
+
await this.connection.closeSubscriber();
|
|
138
|
+
}
|
|
139
|
+
ensureSubscribed() {
|
|
140
|
+
if (this.subscribed) return Promise.resolve();
|
|
141
|
+
if (!this.subscribing) {
|
|
142
|
+
const subscribing = this.subscribeChannel().then(() => {
|
|
143
|
+
if (this.subscribing === subscribing) this.subscribed = true;
|
|
144
|
+
}, (cause) => {
|
|
145
|
+
if (this.subscribing === subscribing) this.subscribing = void 0;
|
|
146
|
+
throw cause;
|
|
147
|
+
});
|
|
148
|
+
subscribing.catch(ignoreError);
|
|
149
|
+
this.subscribing = subscribing;
|
|
150
|
+
}
|
|
151
|
+
return this.subscribing;
|
|
152
|
+
}
|
|
153
|
+
async subscribeChannel() {
|
|
154
|
+
const { readyTimeoutMs, commandDeadlineMs } = this.connection.options;
|
|
155
|
+
const wait = this.connection.kind === "sentinel" ? this.connection.whenUsable() : void 0;
|
|
156
|
+
if (wait) await wait;
|
|
157
|
+
if (this.closed) throw new Error("Redis WebSocket cluster bus is shut down.");
|
|
158
|
+
const subscriber = this.connection.subscriber(() => {
|
|
159
|
+
this.retrySubscription();
|
|
160
|
+
});
|
|
161
|
+
const sending = subscriber.subscribe(this.channel, this.listener);
|
|
162
|
+
this.watchLateSubscribe(subscriber, sending);
|
|
163
|
+
await withDeadline(() => sending, wait ? commandDeadlineMs : readyTimeoutMs + commandDeadlineMs);
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* deadline과 무관하게 node-redis SUBSCRIBE가 실제로 끝나는 시점을 본다.
|
|
167
|
+
* 그때 bus가 닫혔거나 더 이상 구독할 핸들러가 없으면 같은 연결에서 바로 구독을 해제하고,
|
|
168
|
+
* 아직 구독이 필요하면 늦게 끝난 구독을 그대로 쓴다.
|
|
169
|
+
*/
|
|
170
|
+
watchLateSubscribe(subscriber, sending) {
|
|
171
|
+
this.pendingSubscribes += 1;
|
|
172
|
+
sending.then(() => {
|
|
173
|
+
if (this.closed || this.handlers.size === 0) {
|
|
174
|
+
this.unsubscribeFrom(subscriber).catch(ignoreError);
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
this.subscribed = true;
|
|
178
|
+
}, ignoreError).finally(() => {
|
|
179
|
+
this.pendingSubscribes -= 1;
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
retrySubscription() {
|
|
183
|
+
if (this.closed || this.subscribed || this.subscribing || this.handlers.size === 0) return;
|
|
184
|
+
this.ensureSubscribed().catch(ignoreError);
|
|
185
|
+
}
|
|
186
|
+
dropSubscription() {
|
|
187
|
+
if (this.closed) return;
|
|
188
|
+
const wasSubscribed = this.subscribed;
|
|
189
|
+
this.subscribed = false;
|
|
190
|
+
this.subscribing = void 0;
|
|
191
|
+
if (wasSubscribed) this.unsubscribeFrom(this.connection.subscriber(ignoreError)).catch(ignoreError);
|
|
192
|
+
}
|
|
193
|
+
unsubscribeFrom(subscriber) {
|
|
194
|
+
return withDeadline(() => subscriber.unsubscribe(this.channel, this.listener), this.connection.options.commandDeadlineMs);
|
|
195
|
+
}
|
|
196
|
+
};
|
|
197
|
+
export { RedisWebSocketClusterBus, nodeChannelOf, parseClusterEnvelope };
|
|
198
|
+
|
|
199
|
+
//# sourceMappingURL=cluster-bus.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cluster-bus.js","names":[],"sources":["../src/cluster-bus.ts"],"sourcesContent":["import {\n type WebSocketAudience,\n type WebSocketClusterBus,\n type WebSocketClusterEnvelope,\n type WebSocketClusterEnvelopeHandler,\n} from \"sonamu\";\nimport { z } from \"zod\";\n\nimport {\n type RedisPubSubListener,\n type RedisSubscriberTarget,\n type RedisWebSocketConnection,\n} from \"./connection\";\nimport { withDeadline } from \"./deadline\";\n\n/**\n * 노드별 pub/sub 채널. 채널에는 client keyPrefix가 붙지 않으므로 어댑터 prefix만으로 앱을 구분한다.\n */\nexport function nodeChannelOf(prefix: string, nodeId: string): string {\n return `${prefix}:node:${nodeId}`;\n}\n\n// 수신한 envelope은 다른 노드가 보낸 외부 입력이므로 형식을 검증한 뒤에만 핸들러에 넘긴다\nconst AudienceSchema: z.ZodType<WebSocketAudience> = z.lazy(() =>\n z.discriminatedUnion(\"type\", [\n z.object({ type: z.literal(\"all\"), namespace: z.string().optional() }),\n z.object({ type: z.literal(\"room\"), roomId: z.string(), namespace: z.string().optional() }),\n z.object({\n type: z.literal(\"user\"),\n userId: z.union([z.number(), z.string()]),\n namespace: z.string().optional(),\n }),\n z.object({\n type: z.literal(\"connections\"),\n connectionIds: z.array(z.string()),\n namespace: z.string().optional(),\n }),\n z.object({ type: z.literal(\"union\"), audiences: z.array(AudienceSchema) }),\n ]),\n);\n\nconst ClusterEnvelopeSchema = z.object({\n id: z.string(),\n sourceNodeId: z.string(),\n targetNodeIds: z.array(z.string()),\n audience: AudienceSchema,\n event: z.string(),\n frames: z.record(z.string(), z.string()),\n emittedAt: z.number(),\n});\n\nconst ClusterMessageSchema = z\n .string()\n .transform((message, context) => {\n try {\n return /* SAFETY: 결과는 바로 아래 pipe의 ClusterEnvelopeSchema로 검증한다. */ JSON.parse(\n message,\n ) as z.input<typeof ClusterEnvelopeSchema>;\n } catch {\n context.addIssue({ code: \"custom\", message: \"envelope JSON을 파싱할 수 없습니다.\" });\n return z.NEVER;\n }\n })\n .pipe(ClusterEnvelopeSchema);\n\n/**\n * 채널로 받은 envelope JSON을 검증한다. 형식이 맞지 않으면 undefined를 돌려 버린다.\n */\nexport function parseClusterEnvelope(message: string): WebSocketClusterEnvelope | undefined {\n const parsed = ClusterMessageSchema.safeParse(message);\n return parsed.success ? parsed.data : undefined;\n}\n\nfunction ignoreError(): void {}\n\n/**\n * node-redis pub/sub 기반 cluster bus. 노드마다 채널 하나를 구독하고, envelope을 대상 노드 채널에만 publish한다.\n * 한 노드의 publish는 같은 명령 연결로 순서대로 나가므로 수신 노드에도 보낸 순서대로 도착한다.\n */\nexport class RedisWebSocketClusterBus implements WebSocketClusterBus {\n readonly nodeId: string;\n private readonly connection: RedisWebSocketConnection;\n private readonly channel: string;\n private readonly handlers = new Set<WebSocketClusterEnvelopeHandler>();\n private subscribed = false;\n private subscribing: Promise<void> | undefined;\n // node-redis에 보냈지만 아직 끝나지 않은 SUBSCRIBE 수. 어댑터 deadline이 지나도 node-redis 쪽 구독은 늦게 끝날 수 있다\n private pendingSubscribes = 0;\n private closed = false;\n private shutdownPromise: Promise<void> | undefined;\n\n private readonly listener: RedisPubSubListener = (message) => {\n const envelope = parseClusterEnvelope(message.toString());\n if (!envelope) {\n return;\n }\n for (const handler of this.handlers) {\n // 핸들러 실패가 다른 핸들러나 구독 연결로 번지지 않게 한다\n Promise.resolve()\n .then(() => handler(envelope))\n .catch(ignoreError);\n }\n };\n\n /** @internal createRedisWebSocketAdapter가 생성한다. */\n constructor(connection: RedisWebSocketConnection) {\n this.connection = connection;\n this.nodeId = connection.options.nodeId;\n this.channel = nodeChannelOf(connection.options.prefix, this.nodeId);\n // Sentinel 입력에서 연결 전에 구독이 실패했으면 ready 때 다시 시도한다\n connection.onConnectionReady(() => {\n this.retrySubscription();\n });\n }\n\n async publish(envelope: WebSocketClusterEnvelope): Promise<void> {\n if (this.closed) {\n return;\n }\n const message = JSON.stringify(envelope);\n const prefix = this.connection.options.prefix;\n const targets = [...new Set(envelope.targetNodeIds)];\n if (targets.length === 0) {\n return;\n }\n const wait = this.connection.whenUsable();\n if (wait) {\n await wait;\n // ready를 기다리는 사이 shutdown됐으면 보내지 않는다\n if (this.closed) {\n return;\n }\n }\n await this.connection.run((commands) =>\n Promise.all(\n targets.map((target) => commands.publish(nodeChannelOf(prefix, target), message)),\n ),\n );\n }\n\n /**\n * 자기 노드 채널을 구독한다. 구독이 끝나면 resolve하고, readyTimeoutMs와 commandDeadlineMs 안에 끝나지 않으면 reject한다.\n * reject돼도 핸들러는 남아 있어 연결이 ready가 되면 구독이 이어진다(shutdown이나 해제 함수로 정리한다).\n */\n async subscribe(handler: WebSocketClusterEnvelopeHandler): Promise<() => void> {\n if (this.closed) {\n throw new Error(\"Redis WebSocket cluster bus is shut down.\");\n }\n this.handlers.add(handler);\n const unsubscribe = () => {\n this.handlers.delete(handler);\n if (this.handlers.size === 0) {\n this.dropSubscription();\n }\n };\n await this.ensureSubscribed();\n return unsubscribe;\n }\n\n shutdown(): Promise<void> {\n this.shutdownPromise ??= this.close();\n return this.shutdownPromise;\n }\n\n private async close(): Promise<void> {\n this.closed = true;\n this.handlers.clear();\n await Promise.all([this.releaseSubscription(), this.connection.release(\"bus\")]);\n }\n\n private async releaseSubscription(): Promise<void> {\n if (this.connection.kind === \"sentinel\") {\n // 호출자 Sentinel은 닫지 않으므로 구독만 해제한다. 아직 끝나지 않은 SUBSCRIBE는 완료 시점에 따로 해제한다\n const wasSubscribed = this.subscribed || this.pendingSubscribes > 0;\n this.subscribed = false;\n this.subscribing = undefined;\n if (wasSubscribed) {\n await this.unsubscribeFrom(this.connection.subscriber(ignoreError)).catch(ignoreError);\n }\n return;\n }\n // 어댑터 소유 duplicate()를 닫으면 구독도 함께 사라진다\n this.subscribed = false;\n this.subscribing = undefined;\n await this.connection.closeSubscriber();\n }\n\n private ensureSubscribed(): Promise<void> {\n if (this.subscribed) {\n return Promise.resolve();\n }\n if (!this.subscribing) {\n const subscribing = this.subscribeChannel().then(\n () => {\n if (this.subscribing === subscribing) {\n this.subscribed = true;\n }\n },\n (cause: unknown) => {\n if (this.subscribing === subscribing) {\n this.subscribing = undefined;\n }\n throw cause;\n },\n );\n subscribing.catch(ignoreError);\n this.subscribing = subscribing;\n }\n return this.subscribing;\n }\n\n private async subscribeChannel(): Promise<void> {\n // node-redis는 연결 전 SUBSCRIBE를 큐에 두고 연결 뒤 보내므로, 대기 상한만 어댑터가 정한다\n const { readyTimeoutMs, commandDeadlineMs } = this.connection.options;\n const wait = this.connection.kind === \"sentinel\" ? this.connection.whenUsable() : undefined;\n if (wait) {\n await wait;\n }\n // ready를 기다리는 사이 shutdown됐으면 호출자 연결에 구독을 남기지 않는다\n if (this.closed) {\n throw new Error(\"Redis WebSocket cluster bus is shut down.\");\n }\n const subscriber = this.connection.subscriber(() => {\n this.retrySubscription();\n });\n const sending = subscriber.subscribe(this.channel, this.listener);\n this.watchLateSubscribe(subscriber, sending);\n await withDeadline(\n () => sending,\n wait ? commandDeadlineMs : readyTimeoutMs + commandDeadlineMs,\n );\n }\n\n /**\n * deadline과 무관하게 node-redis SUBSCRIBE가 실제로 끝나는 시점을 본다.\n * 그때 bus가 닫혔거나 더 이상 구독할 핸들러가 없으면 같은 연결에서 바로 구독을 해제하고,\n * 아직 구독이 필요하면 늦게 끝난 구독을 그대로 쓴다.\n */\n private watchLateSubscribe(subscriber: RedisSubscriberTarget, sending: Promise<void>): void {\n this.pendingSubscribes += 1;\n sending\n .then(() => {\n if (this.closed || this.handlers.size === 0) {\n this.unsubscribeFrom(subscriber).catch(ignoreError);\n return;\n }\n this.subscribed = true;\n }, ignoreError)\n .finally(() => {\n this.pendingSubscribes -= 1;\n });\n }\n\n private retrySubscription(): void {\n if (this.closed || this.subscribed || this.subscribing || this.handlers.size === 0) {\n return;\n }\n this.ensureSubscribed().catch(ignoreError);\n }\n\n private dropSubscription(): void {\n if (this.closed) {\n return;\n }\n // 구독한 적이 없으면 보낼 것이 없다. 진행 중인 SUBSCRIBE는 완료 시점에 해제한다\n const wasSubscribed = this.subscribed;\n this.subscribed = false;\n this.subscribing = undefined;\n if (wasSubscribed) {\n this.unsubscribeFrom(this.connection.subscriber(ignoreError)).catch(ignoreError);\n }\n }\n\n private unsubscribeFrom(subscriber: RedisSubscriberTarget): Promise<void> {\n return withDeadline(\n () => subscriber.unsubscribe(this.channel, this.listener),\n this.connection.options.commandDeadlineMs,\n );\n }\n}\n"],"mappings":";;;;;;AAkBA,SAAgB,cAAc,QAAgB,QAAwB;CACpE,OAAO,GAAG,OAAO,QAAQ;AAC3B;AAGA,MAA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M,aAAa,KAAK,WAAW,iBAAiB;GAClD,KAAK,kBAAkB;EACzB,CAAC;EACD,MAAM,UAAU,WAAW,UAAU,KAAK,SAAS,KAAK,QAAQ;EAChE,KAAK,mBAAmB,YAAY,OAAO;EAC3C,MAAM,mBACE,SACN,OAAO,oBAAoB,iBAAiB,iBAC9C;CACF;;;;;;CAOA,mBAA2B,YAAmC,SAA8B;EAC1F,KAAK,qBAAqB;EAC1B,QACG,WAAW;GACV,IAAI,KAAK,UAAU,KAAK,SAAS,SAAS,GAAG;IAC3C,KAAK,gBAAgB,UAAU,CAAC,CAAC,MAAM,WAAW;IAClD;GACF;GACA,KAAK,aAAa;EACpB,GAAG,WAAW,CAAC,CACd,cAAc;GACb,KAAK,qBAAqB;EAC5B,CAAC;CACL;CAEA,oBAAkC;EAChC,IAAI,KAAK,UAAU,KAAK,cAAc,KAAK,eAAe,KAAK,SAAS,SAAS,GAC/E;EAEF,KAAK,iBAAiB,CAAC,CAAC,MAAM,WAAW;CAC3C;CAEA,mBAAiC;EAC/B,IAAI,KAAK,QACP;EAGF,MAAM,gBAAgB,KAAK;EAC3B,KAAK,aAAa;EAClB,KAAK,cAAc,KAAA;EACnB,IAAI,eACF,KAAK,gBAAgB,KAAK,WAAW,WAAW,WAAW,CAAC,CAAC,CAAC,MAAM,WAAW;CAEnF;CAEA,gBAAwB,YAAkD;EACxE,OAAO,mBACC,WAAW,YAAY,KAAK,SAAS,KAAK,QAAQ,GACxD,KAAK,WAAW,QAAQ,iBAC1B;CACF;AACF"}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { type DeadlineToken } from "./deadline";
|
|
2
|
+
import { type RedisWebSocketAdapterRedisInput, type ResolvedRedisWebSocketAdapterOptions } from "./options";
|
|
3
|
+
import { type LuaScript } from "./scripts";
|
|
4
|
+
export type RedisPubSubListener = (message: string | Buffer) => void;
|
|
5
|
+
/**
|
|
6
|
+
* 어댑터가 쓰는 명령만 모은 인터페이스. standalone client와 Sentinel을 같은 방식으로 다룬다.
|
|
7
|
+
* 키를 담는 명령은 모두 node-redis 명령 메서드로 보내 client keyPrefix가 한 번만 붙게 한다(sendCommand 금지).
|
|
8
|
+
*/
|
|
9
|
+
type RedisCommandTarget = {
|
|
10
|
+
readonly isReady: boolean;
|
|
11
|
+
evalSha(sha: string, keys: string[], args: string[]): Promise<number>;
|
|
12
|
+
scriptLoad(source: string): Promise<string>;
|
|
13
|
+
zAdd(key: string, score: number, member: string): Promise<void>;
|
|
14
|
+
zRemRangeByScore(key: string, min: string, max: number): Promise<void>;
|
|
15
|
+
zRangeByScore(key: string, min: number, max: string): Promise<string[]>;
|
|
16
|
+
zRem(key: string, member: string): Promise<void>;
|
|
17
|
+
pExpire(key: string, ms: number): Promise<boolean>;
|
|
18
|
+
del(keys: string[]): Promise<void>;
|
|
19
|
+
publish(channel: string, message: string): Promise<void>;
|
|
20
|
+
};
|
|
21
|
+
export type RedisSubscriberTarget = {
|
|
22
|
+
subscribe(channel: string, listener: RedisPubSubListener): Promise<void>;
|
|
23
|
+
unsubscribe(channel: string, listener: RedisPubSubListener): Promise<void>;
|
|
24
|
+
};
|
|
25
|
+
type ConnectionOwner = "store" | "bus";
|
|
26
|
+
/**
|
|
27
|
+
* 어댑터의 Redis 연결 상태와 소유권을 관리한다. presence store와 cluster bus가 하나를 공유한다.
|
|
28
|
+
* - 연결 옵션 입력: 명령용 client와 pub/sub용 duplicate()를 어댑터가 만들고 닫는다.
|
|
29
|
+
* - 호출자 client 입력: 호출자 client로 명령을 보내고, pub/sub용 duplicate() 하나만 어댑터가 소유한다.
|
|
30
|
+
* - 호출자 Sentinel 입력: 인스턴스 명령과 subscribe를 그대로 쓰며 duplicate()를 만들지 않는다.
|
|
31
|
+
* 호출자 소유 연결은 연결하거나 닫지 않는다.
|
|
32
|
+
*
|
|
33
|
+
* @internal createRedisWebSocketAdapter가 생성한다.
|
|
34
|
+
*/
|
|
35
|
+
export declare class RedisWebSocketConnection {
|
|
36
|
+
readonly kind: "owned" | "client" | "sentinel";
|
|
37
|
+
readonly options: ResolvedRedisWebSocketAdapterOptions;
|
|
38
|
+
private readonly commands;
|
|
39
|
+
private readonly ownedClient;
|
|
40
|
+
private readonly callerClient;
|
|
41
|
+
private readonly sentinel;
|
|
42
|
+
private subscriberClient;
|
|
43
|
+
private started;
|
|
44
|
+
private everReady;
|
|
45
|
+
private readyWaitExpired;
|
|
46
|
+
private readyWait;
|
|
47
|
+
private resolveReadyWait;
|
|
48
|
+
private readonly scriptLoads;
|
|
49
|
+
private readonly readyCallbacks;
|
|
50
|
+
private readonly masterChangeCallbacks;
|
|
51
|
+
/**
|
|
52
|
+
* 마지막으로 관찰한 master 주소(`host:port`).
|
|
53
|
+
* node-redis Sentinel은 nodeAddressMap을 쓰면 master가 그대로여도 scan마다 MASTER_CHANGE를 다시 보내므로,
|
|
54
|
+
* 직전 master와 다를 때만 진짜 master 변경으로 본다. A→B→A처럼 되돌아가는 변경도 매번 변경이다.
|
|
55
|
+
*/
|
|
56
|
+
private lastMaster;
|
|
57
|
+
private readonly released;
|
|
58
|
+
private closePromise;
|
|
59
|
+
private readonly onReady;
|
|
60
|
+
private readonly onTopologyChange;
|
|
61
|
+
constructor(input: RedisWebSocketAdapterRedisInput, options: ResolvedRedisWebSocketAdapterOptions);
|
|
62
|
+
get isReady(): boolean;
|
|
63
|
+
get commandDeadlineMs(): number;
|
|
64
|
+
/** 명령용 연결이 (재)연결되어 ready가 될 때마다 호출된다. */
|
|
65
|
+
onConnectionReady(callback: () => void): void;
|
|
66
|
+
/** Sentinel이 master 변경(MASTER_CHANGE)을 알릴 때마다 호출된다. */
|
|
67
|
+
onMasterChange(callback: () => void): void;
|
|
68
|
+
/**
|
|
69
|
+
* 첫 사용 때 연결을 시작한다(lazy connect). 어댑터 소유 client만 connect하고, 호출자 연결에는 이벤트 리스너만 붙인다.
|
|
70
|
+
*/
|
|
71
|
+
start(): void;
|
|
72
|
+
/**
|
|
73
|
+
* 명령을 보내도 되는 시점까지 기다린다. 한 번도 ready가 된 적 없으면 readyTimeoutMs까지만 기다리고,
|
|
74
|
+
* 그 뒤나 이미 한 번 ready였던 연결은 기다리지 않는다(오프라인이면 명령이 바로 실패한다).
|
|
75
|
+
* 기다릴 필요가 없으면 undefined를 돌려줘 호출자가 같은 tick에 명령을 보내 순서를 지키게 한다.
|
|
76
|
+
*/
|
|
77
|
+
whenUsable(): Promise<void> | undefined;
|
|
78
|
+
/** commandDeadlineMs deadline 안에서 명령 묶음을 실행한다. */
|
|
79
|
+
run<T>(operation: (commands: RedisCommandTarget, token: DeadlineToken) => Promise<T>): Promise<T>;
|
|
80
|
+
/**
|
|
81
|
+
* EVALSHA로 스크립트를 실행한다. NOSCRIPT(스크립트 캐시 flush, failover 뒤의 새 master)면 SCRIPT LOAD 후 한 번만 재시도한다.
|
|
82
|
+
* EVAL로 대체하지 않으며, deadline이 지났으면 재시도하지 않는다.
|
|
83
|
+
*
|
|
84
|
+
* 인자는 보내기 직전에 `prepareArgs`로 만든다. 재시도 때도 다시 만들므로 SCRIPT LOAD를 기다리는 동안 바뀐 메모리 상태가
|
|
85
|
+
* 반영되고, 오래된 snapshot을 다시 보내지 않는다. `prepareArgs`가 undefined를 돌려주면(예: shutdown 시작) 보내지 않고 0을 돌려준다.
|
|
86
|
+
*/
|
|
87
|
+
evalScript(commands: RedisCommandTarget, token: DeadlineToken, script: LuaScript, keys: string[], prepareArgs: () => string[] | undefined): Promise<number>;
|
|
88
|
+
/**
|
|
89
|
+
* pub/sub 연결. standalone은 어댑터 소유 duplicate()를, Sentinel은 인스턴스 subscribe를 쓴다.
|
|
90
|
+
* duplicate()는 첫 구독 때 만들고 연결한다.
|
|
91
|
+
*/
|
|
92
|
+
subscriber(onSubscriberReady: () => void): RedisSubscriberTarget;
|
|
93
|
+
get subscriberReady(): boolean;
|
|
94
|
+
/** 어댑터 소유 pub/sub 연결을 닫는다. 호출자 Sentinel의 구독 해제는 bus가 직접 한다. */
|
|
95
|
+
closeSubscriber(): Promise<void>;
|
|
96
|
+
/**
|
|
97
|
+
* store와 bus가 모두 종료되면 어댑터 소유 연결을 닫고 호출자 연결에 붙인 리스너를 뗀다.
|
|
98
|
+
*/
|
|
99
|
+
release(owner: ConnectionOwner): Promise<void>;
|
|
100
|
+
private close;
|
|
101
|
+
/**
|
|
102
|
+
* 대기 중인 명령이 끝나기를 commandDeadlineMs까지만 기다리고, 그래도 남아 있으면 강제로 끊는다.
|
|
103
|
+
* Redis가 응답하지 않으면 close()가 끝나지 않기 때문이다.
|
|
104
|
+
*/
|
|
105
|
+
private closeOwnedClient;
|
|
106
|
+
private createOwnedClient;
|
|
107
|
+
private markReady;
|
|
108
|
+
private loadScript;
|
|
109
|
+
}
|
|
110
|
+
export {};
|
|
111
|
+
//# sourceMappingURL=connection.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"connection.d.ts","sourceRoot":"","sources":["../src/connection.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,KAAK,aAAa,EAA6C,MAAM,YAAY,CAAC;AAC3F,OAAO,EACL,KAAK,+BAA+B,EACpC,KAAK,oCAAoC,EAC1C,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,KAAK,SAAS,EAAE,MAAM,WAAW,CAAC;AAG3C,MAAM,MAAM,mBAAmB,GAAG,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,KAAK,IAAI,CAAC;AAErE;;;GAGG;AACH,KAAK,kBAAkB,GAAG;IACxB,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAE1B,OAAO,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IACtE,UAAU,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IAC5C,IAAI,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MA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