@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
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
import { RedisWebSocketDeadlineError, withDeadline } from "./deadline.js";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { createClient } from "redis";
|
|
4
|
+
// src/connection.ts
|
|
5
|
+
function isSentinelInput(input) {
|
|
6
|
+
return "getMasterNode" in input;
|
|
7
|
+
}
|
|
8
|
+
function isClientInput(input) {
|
|
9
|
+
return "connect" in input;
|
|
10
|
+
}
|
|
11
|
+
function toCount(value) {
|
|
12
|
+
return Number.isFinite(value) ? value : 0;
|
|
13
|
+
}
|
|
14
|
+
function toVoid() {}
|
|
15
|
+
function clientCommands(client) {
|
|
16
|
+
return {
|
|
17
|
+
get isReady() {
|
|
18
|
+
return client.isReady;
|
|
19
|
+
},
|
|
20
|
+
evalSha: async (sha, keys, args) => toCount(Number(await client.evalSha(sha, {
|
|
21
|
+
keys,
|
|
22
|
+
arguments: args
|
|
23
|
+
}))),
|
|
24
|
+
scriptLoad: (source) => client.scriptLoad(source),
|
|
25
|
+
zAdd: (key, score, member) => client.zAdd(key, {
|
|
26
|
+
score,
|
|
27
|
+
value: member
|
|
28
|
+
}).then(toVoid),
|
|
29
|
+
zRemRangeByScore: (key, min, max) => client.zRemRangeByScore(key, min, max).then(toVoid),
|
|
30
|
+
zRangeByScore: (key, min, max) => client.zRangeByScore(key, min, max),
|
|
31
|
+
zRem: (key, member) => client.zRem(key, member).then(toVoid),
|
|
32
|
+
pExpire: (key, ms) => client.pExpire(key, ms).then((reply) => reply === 1),
|
|
33
|
+
del: (keys) => client.del(keys).then(toVoid),
|
|
34
|
+
publish: (channel, message) => client.publish(channel, message).then(toVoid)
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
function sentinelCommands(sentinel) {
|
|
38
|
+
return {
|
|
39
|
+
get isReady() {
|
|
40
|
+
return sentinel.isReady;
|
|
41
|
+
},
|
|
42
|
+
evalSha: async (sha, keys, args) => toCount(Number(await sentinel.evalSha(sha, {
|
|
43
|
+
keys,
|
|
44
|
+
arguments: args
|
|
45
|
+
}))),
|
|
46
|
+
scriptLoad: (source) => sentinel.scriptLoad(source),
|
|
47
|
+
zAdd: (key, score, member) => sentinel.zAdd(key, {
|
|
48
|
+
score,
|
|
49
|
+
value: member
|
|
50
|
+
}).then(toVoid),
|
|
51
|
+
zRemRangeByScore: (key, min, max) => sentinel.zRemRangeByScore(key, min, max).then(toVoid),
|
|
52
|
+
zRangeByScore: (key, min, max) => sentinel.zRangeByScore(key, min, max),
|
|
53
|
+
zRem: (key, member) => sentinel.zRem(key, member).then(toVoid),
|
|
54
|
+
pExpire: (key, ms) => sentinel.pExpire(key, ms).then((reply) => reply === 1),
|
|
55
|
+
del: (keys) => sentinel.del(keys).then(toVoid),
|
|
56
|
+
publish: (channel, message) => sentinel.publish(channel, message).then(toVoid)
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
function isNoScriptError(cause) {
|
|
60
|
+
return cause instanceof Error && cause.message.startsWith("NOSCRIPT");
|
|
61
|
+
}
|
|
62
|
+
const MasterChangeEventSchema = z.object({
|
|
63
|
+
type: z.literal("MASTER_CHANGE"),
|
|
64
|
+
node: z.object({
|
|
65
|
+
host: z.string(),
|
|
66
|
+
port: z.number()
|
|
67
|
+
})
|
|
68
|
+
});
|
|
69
|
+
function masterChangeNodeOf(event) {
|
|
70
|
+
const parsed = MasterChangeEventSchema.safeParse(event);
|
|
71
|
+
return parsed.success ? `${parsed.data.node.host}:${parsed.data.node.port}` : void 0;
|
|
72
|
+
}
|
|
73
|
+
function ignoreError() {}
|
|
74
|
+
/**
|
|
75
|
+
* 어댑터의 Redis 연결 상태와 소유권을 관리한다. presence store와 cluster bus가 하나를 공유한다.
|
|
76
|
+
* - 연결 옵션 입력: 명령용 client와 pub/sub용 duplicate()를 어댑터가 만들고 닫는다.
|
|
77
|
+
* - 호출자 client 입력: 호출자 client로 명령을 보내고, pub/sub용 duplicate() 하나만 어댑터가 소유한다.
|
|
78
|
+
* - 호출자 Sentinel 입력: 인스턴스 명령과 subscribe를 그대로 쓰며 duplicate()를 만들지 않는다.
|
|
79
|
+
* 호출자 소유 연결은 연결하거나 닫지 않는다.
|
|
80
|
+
*
|
|
81
|
+
* @internal createRedisWebSocketAdapter가 생성한다.
|
|
82
|
+
*/
|
|
83
|
+
var RedisWebSocketConnection = class {
|
|
84
|
+
kind;
|
|
85
|
+
options;
|
|
86
|
+
commands;
|
|
87
|
+
ownedClient;
|
|
88
|
+
callerClient;
|
|
89
|
+
sentinel;
|
|
90
|
+
subscriberClient;
|
|
91
|
+
started = false;
|
|
92
|
+
everReady = false;
|
|
93
|
+
readyWaitExpired = false;
|
|
94
|
+
readyWait;
|
|
95
|
+
resolveReadyWait;
|
|
96
|
+
scriptLoads = /* @__PURE__ */ new Map();
|
|
97
|
+
readyCallbacks = /* @__PURE__ */ new Set();
|
|
98
|
+
masterChangeCallbacks = /* @__PURE__ */ new Set();
|
|
99
|
+
/**
|
|
100
|
+
* 마지막으로 관찰한 master 주소(`host:port`).
|
|
101
|
+
* node-redis Sentinel은 nodeAddressMap을 쓰면 master가 그대로여도 scan마다 MASTER_CHANGE를 다시 보내므로,
|
|
102
|
+
* 직전 master와 다를 때만 진짜 master 변경으로 본다. A→B→A처럼 되돌아가는 변경도 매번 변경이다.
|
|
103
|
+
*/
|
|
104
|
+
lastMaster;
|
|
105
|
+
released = /* @__PURE__ */ new Set();
|
|
106
|
+
closePromise;
|
|
107
|
+
onReady = () => {
|
|
108
|
+
this.markReady();
|
|
109
|
+
for (const callback of this.readyCallbacks) callback();
|
|
110
|
+
};
|
|
111
|
+
onTopologyChange = (event) => {
|
|
112
|
+
const master = masterChangeNodeOf(event);
|
|
113
|
+
if (master === void 0 || master === this.lastMaster) return;
|
|
114
|
+
this.lastMaster = master;
|
|
115
|
+
for (const callback of this.masterChangeCallbacks) callback();
|
|
116
|
+
};
|
|
117
|
+
constructor(input, options) {
|
|
118
|
+
this.options = options;
|
|
119
|
+
if (isSentinelInput(input)) {
|
|
120
|
+
this.kind = "sentinel";
|
|
121
|
+
this.sentinel = input;
|
|
122
|
+
this.commands = sentinelCommands(input);
|
|
123
|
+
} else if (isClientInput(input)) {
|
|
124
|
+
this.kind = "client";
|
|
125
|
+
this.callerClient = input;
|
|
126
|
+
this.commands = clientCommands(input);
|
|
127
|
+
} else {
|
|
128
|
+
this.kind = "owned";
|
|
129
|
+
this.ownedClient = this.createOwnedClient(input);
|
|
130
|
+
this.commands = clientCommands(this.ownedClient);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
get isReady() {
|
|
134
|
+
return this.commands.isReady;
|
|
135
|
+
}
|
|
136
|
+
get commandDeadlineMs() {
|
|
137
|
+
return this.options.commandDeadlineMs;
|
|
138
|
+
}
|
|
139
|
+
/** 명령용 연결이 (재)연결되어 ready가 될 때마다 호출된다. */
|
|
140
|
+
onConnectionReady(callback) {
|
|
141
|
+
this.readyCallbacks.add(callback);
|
|
142
|
+
}
|
|
143
|
+
/** Sentinel이 master 변경(MASTER_CHANGE)을 알릴 때마다 호출된다. */
|
|
144
|
+
onMasterChange(callback) {
|
|
145
|
+
this.masterChangeCallbacks.add(callback);
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* 첫 사용 때 연결을 시작한다(lazy connect). 어댑터 소유 client만 connect하고, 호출자 연결에는 이벤트 리스너만 붙인다.
|
|
149
|
+
*/
|
|
150
|
+
start() {
|
|
151
|
+
if (this.started || this.closePromise) return;
|
|
152
|
+
this.started = true;
|
|
153
|
+
if (this.ownedClient) {
|
|
154
|
+
this.ownedClient.on("ready", this.onReady);
|
|
155
|
+
this.ownedClient.connect().catch(ignoreError);
|
|
156
|
+
} else if (this.callerClient) this.callerClient.on("ready", this.onReady);
|
|
157
|
+
else if (this.sentinel) {
|
|
158
|
+
this.sentinel.on("ready", this.onReady);
|
|
159
|
+
this.sentinel.on("topology-change", this.onTopologyChange);
|
|
160
|
+
}
|
|
161
|
+
if (this.commands.isReady) this.markReady();
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* 명령을 보내도 되는 시점까지 기다린다. 한 번도 ready가 된 적 없으면 readyTimeoutMs까지만 기다리고,
|
|
165
|
+
* 그 뒤나 이미 한 번 ready였던 연결은 기다리지 않는다(오프라인이면 명령이 바로 실패한다).
|
|
166
|
+
* 기다릴 필요가 없으면 undefined를 돌려줘 호출자가 같은 tick에 명령을 보내 순서를 지키게 한다.
|
|
167
|
+
*/
|
|
168
|
+
whenUsable() {
|
|
169
|
+
this.start();
|
|
170
|
+
if (this.commands.isReady) this.markReady();
|
|
171
|
+
if (this.everReady || this.readyWaitExpired) return;
|
|
172
|
+
this.readyWait ??= new Promise((resolve) => {
|
|
173
|
+
const timer = setTimeout(() => {
|
|
174
|
+
this.readyWaitExpired = true;
|
|
175
|
+
this.resolveReadyWait = void 0;
|
|
176
|
+
resolve();
|
|
177
|
+
}, this.options.readyTimeoutMs);
|
|
178
|
+
timer.unref();
|
|
179
|
+
this.resolveReadyWait = () => {
|
|
180
|
+
clearTimeout(timer);
|
|
181
|
+
resolve();
|
|
182
|
+
};
|
|
183
|
+
});
|
|
184
|
+
return this.readyWait;
|
|
185
|
+
}
|
|
186
|
+
/** commandDeadlineMs deadline 안에서 명령 묶음을 실행한다. */
|
|
187
|
+
run(operation) {
|
|
188
|
+
return withDeadline((token) => operation(this.commands, token), this.options.commandDeadlineMs);
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* EVALSHA로 스크립트를 실행한다. NOSCRIPT(스크립트 캐시 flush, failover 뒤의 새 master)면 SCRIPT LOAD 후 한 번만 재시도한다.
|
|
192
|
+
* EVAL로 대체하지 않으며, deadline이 지났으면 재시도하지 않는다.
|
|
193
|
+
*
|
|
194
|
+
* 인자는 보내기 직전에 `prepareArgs`로 만든다. 재시도 때도 다시 만들므로 SCRIPT LOAD를 기다리는 동안 바뀐 메모리 상태가
|
|
195
|
+
* 반영되고, 오래된 snapshot을 다시 보내지 않는다. `prepareArgs`가 undefined를 돌려주면(예: shutdown 시작) 보내지 않고 0을 돌려준다.
|
|
196
|
+
*/
|
|
197
|
+
async evalScript(commands, token, script, keys, prepareArgs) {
|
|
198
|
+
const firstArgs = prepareArgs();
|
|
199
|
+
if (firstArgs === void 0) return 0;
|
|
200
|
+
try {
|
|
201
|
+
return await commands.evalSha(script.sha, keys, firstArgs);
|
|
202
|
+
} catch (cause) {
|
|
203
|
+
if (!isNoScriptError(cause) || token.expired) throw cause;
|
|
204
|
+
}
|
|
205
|
+
await this.loadScript(commands, script);
|
|
206
|
+
if (token.expired) throw new RedisWebSocketDeadlineError(this.options.commandDeadlineMs);
|
|
207
|
+
const retryArgs = prepareArgs();
|
|
208
|
+
if (retryArgs === void 0) return 0;
|
|
209
|
+
return commands.evalSha(script.sha, keys, retryArgs);
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* pub/sub 연결. standalone은 어댑터 소유 duplicate()를, Sentinel은 인스턴스 subscribe를 쓴다.
|
|
213
|
+
* duplicate()는 첫 구독 때 만들고 연결한다.
|
|
214
|
+
*/
|
|
215
|
+
subscriber(onSubscriberReady) {
|
|
216
|
+
if (this.sentinel) {
|
|
217
|
+
const sentinel = this.sentinel;
|
|
218
|
+
return {
|
|
219
|
+
subscribe: (channel, listener) => sentinel.subscribe(channel, listener).then(toVoid),
|
|
220
|
+
unsubscribe: (channel, listener) => sentinel.unsubscribe(channel, listener).then(toVoid)
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
if (!this.subscriberClient) {
|
|
224
|
+
const base = this.ownedClient ?? this.callerClient;
|
|
225
|
+
if (!base) throw new Error("Redis WebSocket adapter has no client to duplicate.");
|
|
226
|
+
const subscriberClient = base.duplicate({
|
|
227
|
+
disableOfflineQueue: true,
|
|
228
|
+
commandOptions: { timeout: this.options.commandDeadlineMs }
|
|
229
|
+
});
|
|
230
|
+
subscriberClient.on("error", ignoreError);
|
|
231
|
+
subscriberClient.on("ready", onSubscriberReady);
|
|
232
|
+
subscriberClient.connect().catch(ignoreError);
|
|
233
|
+
this.subscriberClient = subscriberClient;
|
|
234
|
+
}
|
|
235
|
+
const client = this.subscriberClient;
|
|
236
|
+
return {
|
|
237
|
+
subscribe: (channel, listener) => client.subscribe(channel, listener).then(toVoid),
|
|
238
|
+
unsubscribe: (channel, listener) => client.unsubscribe(channel, listener).then(toVoid)
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
get subscriberReady() {
|
|
242
|
+
if (this.sentinel) return this.sentinel.isReady;
|
|
243
|
+
return this.subscriberClient?.isReady ?? false;
|
|
244
|
+
}
|
|
245
|
+
/** 어댑터 소유 pub/sub 연결을 닫는다. 호출자 Sentinel의 구독 해제는 bus가 직접 한다. */
|
|
246
|
+
async closeSubscriber() {
|
|
247
|
+
const client = this.subscriberClient;
|
|
248
|
+
this.subscriberClient = void 0;
|
|
249
|
+
if (client) await this.closeOwnedClient(client);
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* store와 bus가 모두 종료되면 어댑터 소유 연결을 닫고 호출자 연결에 붙인 리스너를 뗀다.
|
|
253
|
+
*/
|
|
254
|
+
release(owner) {
|
|
255
|
+
this.released.add(owner);
|
|
256
|
+
if (this.released.size < 2) return Promise.resolve();
|
|
257
|
+
this.closePromise ??= this.close();
|
|
258
|
+
return this.closePromise;
|
|
259
|
+
}
|
|
260
|
+
async close() {
|
|
261
|
+
this.resolveReadyWait?.();
|
|
262
|
+
this.readyCallbacks.clear();
|
|
263
|
+
this.masterChangeCallbacks.clear();
|
|
264
|
+
if (this.ownedClient) {
|
|
265
|
+
this.ownedClient.off("ready", this.onReady);
|
|
266
|
+
if (this.started) await this.closeOwnedClient(this.ownedClient);
|
|
267
|
+
} else if (this.callerClient) this.callerClient.off("ready", this.onReady);
|
|
268
|
+
else if (this.sentinel) {
|
|
269
|
+
this.sentinel.off("ready", this.onReady);
|
|
270
|
+
this.sentinel.off("topology-change", this.onTopologyChange);
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* 대기 중인 명령이 끝나기를 commandDeadlineMs까지만 기다리고, 그래도 남아 있으면 강제로 끊는다.
|
|
275
|
+
* Redis가 응답하지 않으면 close()가 끝나지 않기 때문이다.
|
|
276
|
+
*/
|
|
277
|
+
async closeOwnedClient(client) {
|
|
278
|
+
if (!client.isOpen) return;
|
|
279
|
+
try {
|
|
280
|
+
await withDeadline(() => client.close(), this.options.commandDeadlineMs);
|
|
281
|
+
} catch {
|
|
282
|
+
client.destroy();
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
createOwnedClient(options) {
|
|
286
|
+
const client = createClient({
|
|
287
|
+
...options,
|
|
288
|
+
disableOfflineQueue: true,
|
|
289
|
+
commandOptions: {
|
|
290
|
+
...options.commandOptions,
|
|
291
|
+
timeout: this.options.commandDeadlineMs
|
|
292
|
+
}
|
|
293
|
+
});
|
|
294
|
+
client.on("error", ignoreError);
|
|
295
|
+
return client;
|
|
296
|
+
}
|
|
297
|
+
markReady() {
|
|
298
|
+
this.everReady = true;
|
|
299
|
+
const resolve = this.resolveReadyWait;
|
|
300
|
+
this.resolveReadyWait = void 0;
|
|
301
|
+
resolve?.();
|
|
302
|
+
}
|
|
303
|
+
loadScript(commands, script) {
|
|
304
|
+
const pending = this.scriptLoads.get(script.sha);
|
|
305
|
+
if (pending) return pending;
|
|
306
|
+
const loading = commands.scriptLoad(script.source).finally(() => {
|
|
307
|
+
this.scriptLoads.delete(script.sha);
|
|
308
|
+
});
|
|
309
|
+
this.scriptLoads.set(script.sha, loading);
|
|
310
|
+
return loading;
|
|
311
|
+
}
|
|
312
|
+
};
|
|
313
|
+
export { RedisWebSocketConnection };
|
|
314
|
+
|
|
315
|
+
//# sourceMappingURL=connection.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"connection.js","names":[],"sources":["../src/connection.ts"],"sourcesContent":["import {\n createClient,\n type RedisClientOptions,\n type RedisClientType,\n type RedisSentinelType,\n} from \"redis\";\nimport { z } from \"zod\";\n\nimport { type DeadlineToken, RedisWebSocketDeadlineError, withDeadline } from \"./deadline\";\nimport {\n type RedisWebSocketAdapterRedisInput,\n type ResolvedRedisWebSocketAdapterOptions,\n} from \"./options\";\nimport { type LuaScript } from \"./scripts\";\n\n// node-redis는 buffer 모드 구독이면 Buffer를 넘기므로 둘 다 받는다\nexport type RedisPubSubListener = (message: string | Buffer) => void;\n\n/**\n * 어댑터가 쓰는 명령만 모은 인터페이스. standalone client와 Sentinel을 같은 방식으로 다룬다.\n * 키를 담는 명령은 모두 node-redis 명령 메서드로 보내 client keyPrefix가 한 번만 붙게 한다(sendCommand 금지).\n */\ntype RedisCommandTarget = {\n readonly isReady: boolean;\n // 어댑터 스크립트는 모두 정수를 반환한다\n evalSha(sha: string, keys: string[], args: string[]): Promise<number>;\n scriptLoad(source: string): Promise<string>;\n zAdd(key: string, score: number, member: string): Promise<void>;\n zRemRangeByScore(key: string, min: string, max: number): Promise<void>;\n zRangeByScore(key: string, min: number, max: string): Promise<string[]>;\n zRem(key: string, member: string): Promise<void>;\n // 키가 있어 만료 시간을 설정했으면 true\n pExpire(key: string, ms: number): Promise<boolean>;\n del(keys: string[]): Promise<void>;\n publish(channel: string, message: string): Promise<void>;\n};\n\nexport type RedisSubscriberTarget = {\n subscribe(channel: string, listener: RedisPubSubListener): Promise<void>;\n unsubscribe(channel: string, listener: RedisPubSubListener): Promise<void>;\n};\n\ntype ConnectionOwner = \"store\" | \"bus\";\n\n// Sentinel 인스턴스만 master/replica 조회 메서드를 가진다\nfunction isSentinelInput(input: RedisWebSocketAdapterRedisInput): input is RedisSentinelType {\n return \"getMasterNode\" in input;\n}\n\n// 연결 옵션 객체에는 connect 메서드가 없다\nfunction isClientInput(\n input: RedisWebSocketAdapterRedisInput,\n): input is RedisClientType | RedisSentinelType {\n return \"connect\" in input;\n}\n\n// 어댑터 스크립트는 정수를 반환한다. 숫자가 아니면 0으로 본다\nfunction toCount(value: number): number {\n return Number.isFinite(value) ? value : 0;\n}\n\nfunction toVoid(): void {}\n\nfunction clientCommands(client: RedisClientType): RedisCommandTarget {\n return {\n get isReady() {\n return client.isReady;\n },\n evalSha: async (sha, keys, args) =>\n toCount(Number(await client.evalSha(sha, { keys, arguments: args }))),\n scriptLoad: (source) => client.scriptLoad(source),\n zAdd: (key, score, member) => client.zAdd(key, { score, value: member }).then(toVoid),\n zRemRangeByScore: (key, min, max) => client.zRemRangeByScore(key, min, max).then(toVoid),\n zRangeByScore: (key, min, max) => client.zRangeByScore(key, min, max),\n zRem: (key, member) => client.zRem(key, member).then(toVoid),\n pExpire: (key, ms) => client.pExpire(key, ms).then((reply) => reply === 1),\n del: (keys) => client.del(keys).then(toVoid),\n publish: (channel, message) => client.publish(channel, message).then(toVoid),\n };\n}\n\nfunction sentinelCommands(sentinel: RedisSentinelType): RedisCommandTarget {\n return {\n get isReady() {\n return sentinel.isReady;\n },\n evalSha: async (sha, keys, args) =>\n toCount(Number(await sentinel.evalSha(sha, { keys, arguments: args }))),\n scriptLoad: (source) => sentinel.scriptLoad(source),\n zAdd: (key, score, member) => sentinel.zAdd(key, { score, value: member }).then(toVoid),\n zRemRangeByScore: (key, min, max) => sentinel.zRemRangeByScore(key, min, max).then(toVoid),\n zRangeByScore: (key, min, max) => sentinel.zRangeByScore(key, min, max),\n zRem: (key, member) => sentinel.zRem(key, member).then(toVoid),\n pExpire: (key, ms) => sentinel.pExpire(key, ms).then((reply) => reply === 1),\n del: (keys) => sentinel.del(keys).then(toVoid),\n publish: (channel, message) => sentinel.publish(channel, message).then(toVoid),\n };\n}\n\nfunction isNoScriptError(cause: unknown): boolean {\n return cause instanceof Error && cause.message.startsWith(\"NOSCRIPT\");\n}\n\n// node-redis Sentinel의 topology-change 이벤트 중 어댑터가 쓰는 MASTER_CHANGE 형식\nconst MasterChangeEventSchema = z.object({\n type: z.literal(\"MASTER_CHANGE\"),\n node: z.object({ host: z.string(), port: z.number() }),\n});\n\ntype TopologyChangeEvent = { type: string; node?: { host: string; port: number } };\n\n// MASTER_CHANGE면 새 master 주소를 `host:port`로 돌려준다\nfunction masterChangeNodeOf(event: TopologyChangeEvent): string | undefined {\n const parsed = MasterChangeEventSchema.safeParse(event);\n return parsed.success ? `${parsed.data.node.host}:${parsed.data.node.port}` : undefined;\n}\n\nfunction ignoreError(): void {}\n\n/**\n * 어댑터의 Redis 연결 상태와 소유권을 관리한다. presence store와 cluster bus가 하나를 공유한다.\n * - 연결 옵션 입력: 명령용 client와 pub/sub용 duplicate()를 어댑터가 만들고 닫는다.\n * - 호출자 client 입력: 호출자 client로 명령을 보내고, pub/sub용 duplicate() 하나만 어댑터가 소유한다.\n * - 호출자 Sentinel 입력: 인스턴스 명령과 subscribe를 그대로 쓰며 duplicate()를 만들지 않는다.\n * 호출자 소유 연결은 연결하거나 닫지 않는다.\n *\n * @internal createRedisWebSocketAdapter가 생성한다.\n */\nexport class RedisWebSocketConnection {\n readonly kind: \"owned\" | \"client\" | \"sentinel\";\n readonly options: ResolvedRedisWebSocketAdapterOptions;\n private readonly commands: RedisCommandTarget;\n private readonly ownedClient: RedisClientType | undefined;\n private readonly callerClient: RedisClientType | undefined;\n private readonly sentinel: RedisSentinelType | undefined;\n private subscriberClient: RedisClientType | undefined;\n\n private started = false;\n private everReady = false;\n private readyWaitExpired = false;\n private readyWait: Promise<void> | undefined;\n private resolveReadyWait: (() => void) | undefined;\n private readonly scriptLoads = new Map<string, Promise<string>>();\n private readonly readyCallbacks = new Set<() => void>();\n private readonly masterChangeCallbacks = new Set<() => void>();\n /**\n * 마지막으로 관찰한 master 주소(`host:port`).\n * node-redis Sentinel은 nodeAddressMap을 쓰면 master가 그대로여도 scan마다 MASTER_CHANGE를 다시 보내므로,\n * 직전 master와 다를 때만 진짜 master 변경으로 본다. A→B→A처럼 되돌아가는 변경도 매번 변경이다.\n */\n private lastMaster: string | undefined;\n private readonly released = new Set<ConnectionOwner>();\n private closePromise: Promise<void> | undefined;\n\n private readonly onReady = () => {\n this.markReady();\n for (const callback of this.readyCallbacks) {\n callback();\n }\n };\n\n private readonly onTopologyChange = (event: TopologyChangeEvent) => {\n const master = masterChangeNodeOf(event);\n if (master === undefined || master === this.lastMaster) {\n return;\n }\n this.lastMaster = master;\n for (const callback of this.masterChangeCallbacks) {\n callback();\n }\n };\n\n constructor(\n input: RedisWebSocketAdapterRedisInput,\n options: ResolvedRedisWebSocketAdapterOptions,\n ) {\n this.options = options;\n if (isSentinelInput(input)) {\n this.kind = \"sentinel\";\n this.sentinel = input;\n this.commands = sentinelCommands(input);\n } else if (isClientInput(input)) {\n this.kind = \"client\";\n this.callerClient = input;\n this.commands = clientCommands(input);\n } else {\n this.kind = \"owned\";\n this.ownedClient = this.createOwnedClient(input);\n this.commands = clientCommands(this.ownedClient);\n }\n }\n\n get isReady(): boolean {\n return this.commands.isReady;\n }\n\n get commandDeadlineMs(): number {\n return this.options.commandDeadlineMs;\n }\n\n /** 명령용 연결이 (재)연결되어 ready가 될 때마다 호출된다. */\n onConnectionReady(callback: () => void): void {\n this.readyCallbacks.add(callback);\n }\n\n /** Sentinel이 master 변경(MASTER_CHANGE)을 알릴 때마다 호출된다. */\n onMasterChange(callback: () => void): void {\n this.masterChangeCallbacks.add(callback);\n }\n\n /**\n * 첫 사용 때 연결을 시작한다(lazy connect). 어댑터 소유 client만 connect하고, 호출자 연결에는 이벤트 리스너만 붙인다.\n */\n start(): void {\n if (this.started || this.closePromise) {\n return;\n }\n this.started = true;\n if (this.ownedClient) {\n this.ownedClient.on(\"ready\", this.onReady);\n // 연결 실패는 error 이벤트와 재연결 전략이 처리한다. ready 대기는 whenUsable이 상한을 둔다\n this.ownedClient.connect().catch(ignoreError);\n } else if (this.callerClient) {\n this.callerClient.on(\"ready\", this.onReady);\n } else if (this.sentinel) {\n this.sentinel.on(\"ready\", this.onReady);\n this.sentinel.on(\"topology-change\", this.onTopologyChange);\n }\n if (this.commands.isReady) {\n this.markReady();\n }\n }\n\n /**\n * 명령을 보내도 되는 시점까지 기다린다. 한 번도 ready가 된 적 없으면 readyTimeoutMs까지만 기다리고,\n * 그 뒤나 이미 한 번 ready였던 연결은 기다리지 않는다(오프라인이면 명령이 바로 실패한다).\n * 기다릴 필요가 없으면 undefined를 돌려줘 호출자가 같은 tick에 명령을 보내 순서를 지키게 한다.\n */\n whenUsable(): Promise<void> | undefined {\n this.start();\n if (this.commands.isReady) {\n this.markReady();\n }\n if (this.everReady || this.readyWaitExpired) {\n return undefined;\n }\n this.readyWait ??= new Promise<void>((resolve) => {\n const timer = setTimeout(() => {\n this.readyWaitExpired = true;\n this.resolveReadyWait = undefined;\n resolve();\n }, this.options.readyTimeoutMs);\n // ready 대기만으로 프로세스 종료를 막지 않는다. 연결 중인 소켓이 있으면 그쪽이 event loop를 유지한다\n timer.unref();\n this.resolveReadyWait = () => {\n clearTimeout(timer);\n resolve();\n };\n });\n return this.readyWait;\n }\n\n /** commandDeadlineMs deadline 안에서 명령 묶음을 실행한다. */\n run<T>(\n operation: (commands: RedisCommandTarget, token: DeadlineToken) => Promise<T>,\n ): Promise<T> {\n return withDeadline((token) => operation(this.commands, token), this.options.commandDeadlineMs);\n }\n\n /**\n * EVALSHA로 스크립트를 실행한다. NOSCRIPT(스크립트 캐시 flush, failover 뒤의 새 master)면 SCRIPT LOAD 후 한 번만 재시도한다.\n * EVAL로 대체하지 않으며, deadline이 지났으면 재시도하지 않는다.\n *\n * 인자는 보내기 직전에 `prepareArgs`로 만든다. 재시도 때도 다시 만들므로 SCRIPT LOAD를 기다리는 동안 바뀐 메모리 상태가\n * 반영되고, 오래된 snapshot을 다시 보내지 않는다. `prepareArgs`가 undefined를 돌려주면(예: shutdown 시작) 보내지 않고 0을 돌려준다.\n */\n async evalScript(\n commands: RedisCommandTarget,\n token: DeadlineToken,\n script: LuaScript,\n keys: string[],\n prepareArgs: () => string[] | undefined,\n ): Promise<number> {\n const firstArgs = prepareArgs();\n if (firstArgs === undefined) {\n return 0;\n }\n try {\n return await commands.evalSha(script.sha, keys, firstArgs);\n } catch (cause) {\n if (!isNoScriptError(cause) || token.expired) {\n throw cause;\n }\n }\n await this.loadScript(commands, script);\n if (token.expired) {\n throw new RedisWebSocketDeadlineError(this.options.commandDeadlineMs);\n }\n // SCRIPT LOAD가 끝난 tick에서 snapshot을 만들고 바로 보낸다\n const retryArgs = prepareArgs();\n if (retryArgs === undefined) {\n return 0;\n }\n return commands.evalSha(script.sha, keys, retryArgs);\n }\n\n /**\n * pub/sub 연결. standalone은 어댑터 소유 duplicate()를, Sentinel은 인스턴스 subscribe를 쓴다.\n * duplicate()는 첫 구독 때 만들고 연결한다.\n */\n subscriber(onSubscriberReady: () => void): RedisSubscriberTarget {\n if (this.sentinel) {\n const sentinel = this.sentinel;\n return {\n subscribe: (channel, listener) => sentinel.subscribe(channel, listener).then(toVoid),\n unsubscribe: (channel, listener) => sentinel.unsubscribe(channel, listener).then(toVoid),\n };\n }\n\n if (!this.subscriberClient) {\n const base = this.ownedClient ?? this.callerClient;\n if (!base) {\n throw new Error(\"Redis WebSocket adapter has no client to duplicate.\");\n }\n const subscriberClient = base.duplicate({\n disableOfflineQueue: true,\n commandOptions: { timeout: this.options.commandDeadlineMs },\n });\n subscriberClient.on(\"error\", ignoreError);\n subscriberClient.on(\"ready\", onSubscriberReady);\n subscriberClient.connect().catch(ignoreError);\n this.subscriberClient = subscriberClient;\n }\n const client = this.subscriberClient;\n return {\n subscribe: (channel, listener) => client.subscribe(channel, listener).then(toVoid),\n unsubscribe: (channel, listener) => client.unsubscribe(channel, listener).then(toVoid),\n };\n }\n\n get subscriberReady(): boolean {\n if (this.sentinel) {\n return this.sentinel.isReady;\n }\n return this.subscriberClient?.isReady ?? false;\n }\n\n /** 어댑터 소유 pub/sub 연결을 닫는다. 호출자 Sentinel의 구독 해제는 bus가 직접 한다. */\n async closeSubscriber(): Promise<void> {\n const client = this.subscriberClient;\n this.subscriberClient = undefined;\n if (client) {\n await this.closeOwnedClient(client);\n }\n }\n\n /**\n * store와 bus가 모두 종료되면 어댑터 소유 연결을 닫고 호출자 연결에 붙인 리스너를 뗀다.\n */\n release(owner: ConnectionOwner): Promise<void> {\n this.released.add(owner);\n if (this.released.size < 2) {\n return Promise.resolve();\n }\n this.closePromise ??= this.close();\n return this.closePromise;\n }\n\n private async close(): Promise<void> {\n this.resolveReadyWait?.();\n this.readyCallbacks.clear();\n this.masterChangeCallbacks.clear();\n if (this.ownedClient) {\n this.ownedClient.off(\"ready\", this.onReady);\n if (this.started) {\n await this.closeOwnedClient(this.ownedClient);\n }\n } else if (this.callerClient) {\n this.callerClient.off(\"ready\", this.onReady);\n } else if (this.sentinel) {\n this.sentinel.off(\"ready\", this.onReady);\n this.sentinel.off(\"topology-change\", this.onTopologyChange);\n }\n }\n\n /**\n * 대기 중인 명령이 끝나기를 commandDeadlineMs까지만 기다리고, 그래도 남아 있으면 강제로 끊는다.\n * Redis가 응답하지 않으면 close()가 끝나지 않기 때문이다.\n */\n private async closeOwnedClient(client: RedisClientType): Promise<void> {\n if (!client.isOpen) {\n return;\n }\n try {\n await withDeadline(() => client.close(), this.options.commandDeadlineMs);\n } catch {\n client.destroy();\n }\n }\n\n private createOwnedClient(options: RedisClientOptions): RedisClientType {\n const client = createClient({\n ...options,\n // 오프라인이면 명령을 쌓지 않고 즉시 실패시켜 rebuild 대기로 넘긴다\n disableOfflineQueue: true,\n commandOptions: { ...options.commandOptions, timeout: this.options.commandDeadlineMs },\n });\n // 처리되지 않은 error 이벤트는 프로세스를 종료시키므로 반드시 리스너를 둔다\n client.on(\"error\", ignoreError);\n return client;\n }\n\n private markReady(): void {\n this.everReady = true;\n const resolve = this.resolveReadyWait;\n this.resolveReadyWait = undefined;\n resolve?.();\n }\n\n private loadScript(commands: RedisCommandTarget, script: LuaScript): Promise<string> {\n const pending = this.scriptLoads.get(script.sha);\n if (pending) {\n return pending;\n }\n const loading = commands.scriptLoad(script.source).finally(() => {\n this.scriptLoads.delete(script.sha);\n });\n this.scriptLoads.set(script.sha, loading);\n return loading;\n }\n}\n"],"mappings":";;;;AA6CA,SAAS,gBAAgB,OAAoE;CAC3F,OAAO,mBAAmB;AAC5B;AAGA,SAAS,cACP,OAC8C;CAC9C,OAAO,aAAa;AACtB;AAGA,SAAS,QAAQ,OAAuB;CACtC,OAAO,OAAO,SAAS,KAAK,IAAI,QAAQ;AAC1C;AAEA,SAAS,SAAe,CAAC;AAEzB,SAAS,eAAe,QAA6C;CACnE,OAAO;EACL,IAAI,UAAU;GACZ,OAAO,OAAO;EAChB;EACA,SAAS,OAAO,KAAK,MAAM,SACzB,QAAQ,OAAO,MAAM,OAAO,QAAQ,KAAK;GAAE;GAAM,WAAW;EAAK,CAAC,CAAC,CAAC;EACtE,aAAa,WAAW,OA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AAgB,SAAS,KAAK,QAAQ;GAAkB;EACvF,CAAC;EAED,OAAO,GAAG,SAAS,WAAW;EAC9B,OAAO;CACT;CAEA,YAA0B;EACxB,KAAK,YAAY;EACjB,MAAM,UAAU,KAAK;EACrB,KAAK,mBAAmB,KAAA;EACxB,UAAU;CACZ;CAEA,WAAmB,UAA8B,QAAoC;EACnF,MAAM,UAAU,KAAK,YAAY,IAAI,OAAO,GAAG;EAC/C,IAAI,SACF,OAAO;EAET,MAAM,UAAU,SAAS,WAAW,OAAO,MAAM,CAAC,CAAC,cAAc;GAC/D,KAAK,YAAY,OAAO,OAAO,GAAG;EACpC,CAAC;EACD,KAAK,YAAY,IAAI,OAAO,KAAK,OAAO;EACxC,OAAO;CACT;AACF"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export declare class RedisWebSocketDeadlineError extends Error {
|
|
2
|
+
readonly name = "RedisWebSocketDeadlineError";
|
|
3
|
+
constructor(deadlineMs: number);
|
|
4
|
+
}
|
|
5
|
+
export type DeadlineToken = {
|
|
6
|
+
readonly expired: boolean;
|
|
7
|
+
};
|
|
8
|
+
/**
|
|
9
|
+
* 작업을 deadline으로 감싼다. node-redis의 timeout은 이미 전송된 명령을 끝내지 못하므로 어댑터가 직접 상한을 둔다.
|
|
10
|
+
* deadline 뒤에 도착한 결과는 무시하고, 늦은 rejection은 삼켜 unhandledRejection이 생기지 않게 한다.
|
|
11
|
+
* 작업은 token.expired로 deadline 경과를 확인해 재시도 같은 후속 명령을 보내지 않을 수 있다.
|
|
12
|
+
*/
|
|
13
|
+
export declare function withDeadline<T>(operation: (token: DeadlineToken) => Promise<T>, deadlineMs: number): Promise<T>;
|
|
14
|
+
//# sourceMappingURL=deadline.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"deadline.d.ts","sourceRoot":"","sources":["../src/deadline.ts"],"names":[],"mappings":"AAAA,qBAAa,2BAA4B,SAAQ,KAAK;IACpD,SAAkB,IAAI,iCAAiC;IAEvD,YAAY,UAAU,EAAE,MAAM,EAE7B;CACF;AAED,MAAM,MAAM,aAAa,GAAG;IAC1B,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;CAC3B,CAAC;AAEF;;;;GAIG;AACH,wBAAgB,YAAY,CAAC,CAAC,EAC5B,SAAS,EAAE,CAAC,KAAK,EAAE,aAAa,KAAK,OAAO,CAAC,CAAC,CAAC,EAC/C,UAAU,EAAE,MAAM,GACjB,OAAO,CAAC,CAAC,CAAC,CAgBZ"}
|
package/dist/deadline.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// src/deadline.ts
|
|
2
|
+
var RedisWebSocketDeadlineError = class extends Error {
|
|
3
|
+
name = "RedisWebSocketDeadlineError";
|
|
4
|
+
constructor(deadlineMs) {
|
|
5
|
+
super(`Redis 호출이 ${deadlineMs}ms deadline 안에 끝나지 않았습니다.`);
|
|
6
|
+
}
|
|
7
|
+
};
|
|
8
|
+
/**
|
|
9
|
+
* 작업을 deadline으로 감싼다. node-redis의 timeout은 이미 전송된 명령을 끝내지 못하므로 어댑터가 직접 상한을 둔다.
|
|
10
|
+
* deadline 뒤에 도착한 결과는 무시하고, 늦은 rejection은 삼켜 unhandledRejection이 생기지 않게 한다.
|
|
11
|
+
* 작업은 token.expired로 deadline 경과를 확인해 재시도 같은 후속 명령을 보내지 않을 수 있다.
|
|
12
|
+
*/
|
|
13
|
+
function withDeadline(operation, deadlineMs) {
|
|
14
|
+
const token = { expired: false };
|
|
15
|
+
const work = Promise.resolve().then(() => operation(token));
|
|
16
|
+
work.catch(() => {});
|
|
17
|
+
let timer;
|
|
18
|
+
const deadline = new Promise((_resolve, reject) => {
|
|
19
|
+
timer = setTimeout(() => {
|
|
20
|
+
token.expired = true;
|
|
21
|
+
reject(new RedisWebSocketDeadlineError(deadlineMs));
|
|
22
|
+
}, deadlineMs);
|
|
23
|
+
});
|
|
24
|
+
return Promise.race([work, deadline]).finally(() => {
|
|
25
|
+
clearTimeout(timer);
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
export { RedisWebSocketDeadlineError, withDeadline };
|
|
29
|
+
|
|
30
|
+
//# sourceMappingURL=deadline.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"deadline.js","names":[],"sources":["../src/deadline.ts"],"sourcesContent":["export class RedisWebSocketDeadlineError extends Error {\n override readonly name = \"RedisWebSocketDeadlineError\";\n\n constructor(deadlineMs: number) {\n super(`Redis 호출이 ${deadlineMs}ms deadline 안에 끝나지 않았습니다.`);\n }\n}\n\nexport type DeadlineToken = {\n readonly expired: boolean;\n};\n\n/**\n * 작업을 deadline으로 감싼다. node-redis의 timeout은 이미 전송된 명령을 끝내지 못하므로 어댑터가 직접 상한을 둔다.\n * deadline 뒤에 도착한 결과는 무시하고, 늦은 rejection은 삼켜 unhandledRejection이 생기지 않게 한다.\n * 작업은 token.expired로 deadline 경과를 확인해 재시도 같은 후속 명령을 보내지 않을 수 있다.\n */\nexport function withDeadline<T>(\n operation: (token: DeadlineToken) => Promise<T>,\n deadlineMs: number,\n): Promise<T> {\n const token = { expired: false };\n const work = Promise.resolve().then(() => operation(token));\n work.catch(() => {});\n\n let timer: ReturnType<typeof setTimeout> | undefined;\n const deadline = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n token.expired = true;\n reject(new RedisWebSocketDeadlineError(deadlineMs));\n }, deadlineMs);\n });\n\n return Promise.race([work, deadline]).finally(() => {\n clearTimeout(timer);\n });\n}\n"],"mappings":";AAAA,IAAa,8BAAb,cAAiD,MAAM;CACrD,OAAyB;CAEzB,YAAY,YAAoB;EAC9B,MAAM,aAAa,WAAW,0BAA0B;CAC1D;AACF;;;;;;AAWA,SAAgB,aACd,WACA,YACY;CACZ,MAAM,QAAQ,EAAE,SAAS,MAAM;CAC/B,MAAM,OAAO,QAAQ,QAAQ,CAAC,CAAC,WAAW,UAAU,KAAK,CAAC;CAC1D,KAAK,YAAY,CAAC,CAAC;CAEnB,IAAI;CACJ,MAAM,WAAW,IAAI,SAAgB,UAAU,WAAW;EACxD,QAAQ,iBAAiB;GACvB,MAAM,UAAU;GAChB,OAAO,IAAI,4BAA4B,UAAU,CAAC;EACpD,GAAG,UAAU;CACf,CAAC;CAED,OAAO,QAAQ,KAAK,CAAC,MAAM,QAAQ,CAAC,CAAC,CAAC,cAAc;EAClD,aAAa,KAAK;CACpB,CAAC;AACH"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { RedisWebSocketClusterBus } from "./cluster-bus";
|
|
2
|
+
import { type RedisWebSocketAdapterOptions } from "./options";
|
|
3
|
+
import { RedisWebSocketPresenceStore } from "./presence-store";
|
|
4
|
+
export { RedisWebSocketClusterBus } from "./cluster-bus";
|
|
5
|
+
export { RedisWebSocketDeadlineError } from "./deadline";
|
|
6
|
+
export { REDIS_WEBSOCKET_ADAPTER_DEFAULTS, type RedisWebSocketAdapterOptions, type RedisWebSocketAdapterRedisInput, } from "./options";
|
|
7
|
+
export { RedisWebSocketPresenceStore, type RedisWebSocketPresenceStoreStatus, } from "./presence-store";
|
|
8
|
+
export type RedisWebSocketAdapter = {
|
|
9
|
+
nodeId: string;
|
|
10
|
+
presenceStore: RedisWebSocketPresenceStore;
|
|
11
|
+
clusterBus: RedisWebSocketClusterBus;
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* Redis presence store와 cluster bus를 만든다. 결과를 WebSocket 런타임 옵션에 그대로 펼쳐 넣으면
|
|
15
|
+
* runtime, store, bus가 같은 nodeId를 쓴다.
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* ```ts
|
|
19
|
+
* websocket: {
|
|
20
|
+
* ...createRedisWebSocketAdapter({ redis: { url: process.env.REDIS_URL }, prefix: "my-app:ws" }),
|
|
21
|
+
* }
|
|
22
|
+
* ```
|
|
23
|
+
*
|
|
24
|
+
* 생성만으로는 Redis에 연결하지 않으며 첫 사용 때 연결한다.
|
|
25
|
+
*/
|
|
26
|
+
export declare function createRedisWebSocketAdapter(options: RedisWebSocketAdapterOptions): RedisWebSocketAdapter;
|
|
27
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,wBAAwB,EAAE,MAAM,eAAe,CAAC;AAEzD,OAAO,EAAE,KAAK,4BAA4B,EAAyB,MAAM,WAAW,CAAC;AACrF,OAAO,EAAE,2BAA2B,EAAE,MAAM,kBAAkB,CAAC;AAE/D,OAAO,EAAE,wBAAwB,EAAE,MAAM,eAAe,CAAC;AACzD,OAAO,EAAE,2BAA2B,EAAE,MAAM,YAAY,CAAC;AACzD,OAAO,EACL,gCAAgC,EAChC,KAAK,4BAA4B,EACjC,KAAK,+BAA+B,GACrC,MAAM,WAAW,CAAC;AACnB,OAAO,EACL,2BAA2B,EAC3B,KAAK,iCAAiC,GACvC,MAAM,kBAAkB,CAAC;AAE1B,MAAM,MAAM,qBAAqB,GAAG;IAClC,MAAM,EAAE,MAAM,CAAC;IACf,aAAa,EAAE,2BAA2B,CAAC;IAC3C,UAAU,EAAE,wBAAwB,CAAC;CACtC,CAAC;AAEF;;;;;;;;;;;;GAYG;AACH,wBAAgB,2BAA2B,CACzC,OAAO,EAAE,4BAA4B,GACpC,qBAAqB,CAQvB"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { RedisWebSocketDeadlineError } from "./deadline.js";
|
|
2
|
+
import { RedisWebSocketClusterBus } from "./cluster-bus.js";
|
|
3
|
+
import { RedisWebSocketConnection } from "./connection.js";
|
|
4
|
+
import { REDIS_WEBSOCKET_ADAPTER_DEFAULTS, resolveAdapterOptions } from "./options.js";
|
|
5
|
+
import { RedisWebSocketPresenceStore } from "./presence-store.js";
|
|
6
|
+
// src/index.ts
|
|
7
|
+
/**
|
|
8
|
+
* Redis presence store와 cluster bus를 만든다. 결과를 WebSocket 런타임 옵션에 그대로 펼쳐 넣으면
|
|
9
|
+
* runtime, store, bus가 같은 nodeId를 쓴다.
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* ```ts
|
|
13
|
+
* websocket: {
|
|
14
|
+
* ...createRedisWebSocketAdapter({ redis: { url: process.env.REDIS_URL }, prefix: "my-app:ws" }),
|
|
15
|
+
* }
|
|
16
|
+
* ```
|
|
17
|
+
*
|
|
18
|
+
* 생성만으로는 Redis에 연결하지 않으며 첫 사용 때 연결한다.
|
|
19
|
+
*/
|
|
20
|
+
function createRedisWebSocketAdapter(options) {
|
|
21
|
+
const resolved = resolveAdapterOptions(options);
|
|
22
|
+
const connection = new RedisWebSocketConnection(options.redis, resolved);
|
|
23
|
+
return {
|
|
24
|
+
nodeId: resolved.nodeId,
|
|
25
|
+
presenceStore: new RedisWebSocketPresenceStore(connection),
|
|
26
|
+
clusterBus: new RedisWebSocketClusterBus(connection)
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
export { REDIS_WEBSOCKET_ADAPTER_DEFAULTS, RedisWebSocketClusterBus, RedisWebSocketDeadlineError, RedisWebSocketPresenceStore, createRedisWebSocketAdapter };
|
|
30
|
+
|
|
31
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["import { RedisWebSocketClusterBus } from \"./cluster-bus\";\nimport { RedisWebSocketConnection } from \"./connection\";\nimport { type RedisWebSocketAdapterOptions, resolveAdapterOptions } from \"./options\";\nimport { RedisWebSocketPresenceStore } from \"./presence-store\";\n\nexport { RedisWebSocketClusterBus } from \"./cluster-bus\";\nexport { RedisWebSocketDeadlineError } from \"./deadline\";\nexport {\n REDIS_WEBSOCKET_ADAPTER_DEFAULTS,\n type RedisWebSocketAdapterOptions,\n type RedisWebSocketAdapterRedisInput,\n} from \"./options\";\nexport {\n RedisWebSocketPresenceStore,\n type RedisWebSocketPresenceStoreStatus,\n} from \"./presence-store\";\n\nexport type RedisWebSocketAdapter = {\n nodeId: string;\n presenceStore: RedisWebSocketPresenceStore;\n clusterBus: RedisWebSocketClusterBus;\n};\n\n/**\n * Redis presence store와 cluster bus를 만든다. 결과를 WebSocket 런타임 옵션에 그대로 펼쳐 넣으면\n * runtime, store, bus가 같은 nodeId를 쓴다.\n *\n * @example\n * ```ts\n * websocket: {\n * ...createRedisWebSocketAdapter({ redis: { url: process.env.REDIS_URL }, prefix: \"my-app:ws\" }),\n * }\n * ```\n *\n * 생성만으로는 Redis에 연결하지 않으며 첫 사용 때 연결한다.\n */\nexport function createRedisWebSocketAdapter(\n options: RedisWebSocketAdapterOptions,\n): RedisWebSocketAdapter {\n const resolved = resolveAdapterOptions(options);\n const connection = new RedisWebSocketConnection(options.redis, resolved);\n return {\n nodeId: resolved.nodeId,\n presenceStore: new RedisWebSocketPresenceStore(connection),\n clusterBus: new RedisWebSocketClusterBus(connection),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAoCA,SAAgB,4BACd,SACuB;CACvB,MAAM,WAAW,sBAAsB,OAAO;CAC9C,MAAM,aAAa,IAAI,yBAAyB,QAAQ,OAAO,QAAQ;CACvE,OAAO;EACL,QAAQ,SAAS;EACjB,eAAe,IAAI,4BAA4B,UAAU;EACzD,YAAY,IAAI,yBAAyB,UAAU;CACrD;AACF"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { type RedisClientOptions, type RedisClientType, type RedisSentinelType } from "redis";
|
|
2
|
+
/**
|
|
3
|
+
* Redis 연결 입력입니다.
|
|
4
|
+
* - `RedisClientOptions`: 어댑터가 클라이언트를 생성하고 소유합니다.
|
|
5
|
+
* - `RedisClientType`: 호출자 소유 클라이언트이며, 어댑터는 pub/sub용 duplicate()만 소유합니다.
|
|
6
|
+
* - `RedisSentinelType`: 호출자 소유 Sentinel이며, 인스턴스 subscribe를 사용합니다.
|
|
7
|
+
*/
|
|
8
|
+
export type RedisWebSocketAdapterRedisInput = RedisClientOptions | RedisClientType | RedisSentinelType;
|
|
9
|
+
export type RedisWebSocketAdapterOptions = {
|
|
10
|
+
redis: RedisWebSocketAdapterRedisInput;
|
|
11
|
+
nodeId?: string;
|
|
12
|
+
prefix?: string;
|
|
13
|
+
heartbeatIntervalMs?: number;
|
|
14
|
+
nodeTimeoutMs?: number;
|
|
15
|
+
keyTtlMs?: number;
|
|
16
|
+
commandDeadlineMs?: number;
|
|
17
|
+
readyTimeoutMs?: number;
|
|
18
|
+
drainTimeoutMs?: number;
|
|
19
|
+
};
|
|
20
|
+
export type ResolvedRedisWebSocketAdapterOptions = Required<Omit<RedisWebSocketAdapterOptions, "redis">>;
|
|
21
|
+
export declare const REDIS_WEBSOCKET_ADAPTER_DEFAULTS: {
|
|
22
|
+
readonly prefix: "sonamu:ws";
|
|
23
|
+
readonly heartbeatIntervalMs: 5000;
|
|
24
|
+
readonly nodeTimeoutMs: 15000;
|
|
25
|
+
readonly keyTtlMs: 30000;
|
|
26
|
+
readonly commandDeadlineMs: 2000;
|
|
27
|
+
readonly readyTimeoutMs: 3000;
|
|
28
|
+
readonly drainTimeoutMs: 5000;
|
|
29
|
+
};
|
|
30
|
+
export declare function resolveAdapterOptions(options: RedisWebSocketAdapterOptions): ResolvedRedisWebSocketAdapterOptions;
|
|
31
|
+
//# sourceMappingURL=options.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"options.d.ts","sourceRoot":"","sources":["../src/options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,kBAAkB,EAAE,KAAK,eAAe,EAAE,KAAK,iBAAiB,EAAE,MAAM,OAAO,CAAC;AAG9F;;;;;GAKG;AACH,MAAM,MAAM,+BAA+B,GACvC,kBAAkB,GAClB,eAAe,GACf,iBAAiB,CAAC;AAEtB,MAAM,MAAM,4BAA4B,GAAG;IACzC,KAAK,EAAE,+BAA+B,CAAC;IAEvC,MAAM,CAAC,EAAE,MAAM,CAAC;IAEhB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB,CAAC;AAEF,MAAM,MAAM,oCAAoC,GAAG,QAAQ,CACzD,IAAI,CAAC,4BAA4B,EAAE,OAAO,CAAC,CAC5C,CAAC;AAEF,eAAO,MAAM,gCAAgC;aAC3C,MAAM,EAAE,WAAW;aACnB,mBAAmB,EAAE,IAAI;aAEzB,aAAa,EAAE,KAAK;aAEpB,QAAQ,EAAE,KAAK;aACf,iBAAiB,EAAE,IAAI;aACvB,cAAc,EAAE,IAAI;aAEpB,cAAc,EAAE,IAAI;CACZ,CAAC;AAEX,wBAAgB,qBAAqB,CACnC,OAAO,EAAE,4BAA4B,GACpC,oCAAoC,CAkCtC"}
|
package/dist/options.js
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { createWebSocketNodeId } from "sonamu";
|
|
2
|
+
// src/options.ts
|
|
3
|
+
const REDIS_WEBSOCKET_ADAPTER_DEFAULTS = {
|
|
4
|
+
prefix: "sonamu:ws",
|
|
5
|
+
heartbeatIntervalMs: 5e3,
|
|
6
|
+
nodeTimeoutMs: 15e3,
|
|
7
|
+
keyTtlMs: 3e4,
|
|
8
|
+
commandDeadlineMs: 2e3,
|
|
9
|
+
readyTimeoutMs: 3e3,
|
|
10
|
+
drainTimeoutMs: 5e3
|
|
11
|
+
};
|
|
12
|
+
function resolveAdapterOptions(options) {
|
|
13
|
+
const resolved = {
|
|
14
|
+
nodeId: options.nodeId ?? createWebSocketNodeId(),
|
|
15
|
+
prefix: options.prefix ?? REDIS_WEBSOCKET_ADAPTER_DEFAULTS.prefix,
|
|
16
|
+
heartbeatIntervalMs: options.heartbeatIntervalMs ?? REDIS_WEBSOCKET_ADAPTER_DEFAULTS.heartbeatIntervalMs,
|
|
17
|
+
nodeTimeoutMs: options.nodeTimeoutMs ?? REDIS_WEBSOCKET_ADAPTER_DEFAULTS.nodeTimeoutMs,
|
|
18
|
+
keyTtlMs: options.keyTtlMs ?? REDIS_WEBSOCKET_ADAPTER_DEFAULTS.keyTtlMs,
|
|
19
|
+
commandDeadlineMs: options.commandDeadlineMs ?? REDIS_WEBSOCKET_ADAPTER_DEFAULTS.commandDeadlineMs,
|
|
20
|
+
readyTimeoutMs: options.readyTimeoutMs ?? REDIS_WEBSOCKET_ADAPTER_DEFAULTS.readyTimeoutMs,
|
|
21
|
+
drainTimeoutMs: options.drainTimeoutMs ?? REDIS_WEBSOCKET_ADAPTER_DEFAULTS.drainTimeoutMs
|
|
22
|
+
};
|
|
23
|
+
if (resolved.nodeId === "") throw new Error("Redis WebSocket adapter nodeId must not be empty.");
|
|
24
|
+
if (resolved.prefix === "") throw new Error("Redis WebSocket adapter prefix must not be empty.");
|
|
25
|
+
for (const name of [
|
|
26
|
+
"heartbeatIntervalMs",
|
|
27
|
+
"nodeTimeoutMs",
|
|
28
|
+
"keyTtlMs",
|
|
29
|
+
"commandDeadlineMs",
|
|
30
|
+
"readyTimeoutMs",
|
|
31
|
+
"drainTimeoutMs"
|
|
32
|
+
]) {
|
|
33
|
+
const value = resolved[name];
|
|
34
|
+
if (!Number.isFinite(value) || value <= 0) throw new Error(`Redis WebSocket adapter ${name} must be a positive number.`);
|
|
35
|
+
}
|
|
36
|
+
return resolved;
|
|
37
|
+
}
|
|
38
|
+
export { REDIS_WEBSOCKET_ADAPTER_DEFAULTS, resolveAdapterOptions };
|
|
39
|
+
|
|
40
|
+
//# sourceMappingURL=options.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"options.js","names":[],"sources":["../src/options.ts"],"sourcesContent":["import { type RedisClientOptions, type RedisClientType, type RedisSentinelType } from \"redis\";\nimport { createWebSocketNodeId } from \"sonamu\";\n\n/**\n * Redis 연결 입력입니다.\n * - `RedisClientOptions`: 어댑터가 클라이언트를 생성하고 소유합니다.\n * - `RedisClientType`: 호출자 소유 클라이언트이며, 어댑터는 pub/sub용 duplicate()만 소유합니다.\n * - `RedisSentinelType`: 호출자 소유 Sentinel이며, 인스턴스 subscribe를 사용합니다.\n */\nexport type RedisWebSocketAdapterRedisInput =\n | RedisClientOptions\n | RedisClientType\n | RedisSentinelType;\n\nexport type RedisWebSocketAdapterOptions = {\n redis: RedisWebSocketAdapterRedisInput;\n // 기본값은 sonamu createWebSocketNodeId()로 만든 `${hostname}-${pid}-${랜덤}`\n nodeId?: string;\n // 키와 pub/sub 채널 접두사. 채널에는 client keyPrefix가 붙지 않으므로 Redis를 공유하는 앱마다 다르게 설정한다\n prefix?: string;\n heartbeatIntervalMs?: number;\n nodeTimeoutMs?: number;\n keyTtlMs?: number;\n commandDeadlineMs?: number;\n readyTimeoutMs?: number;\n drainTimeoutMs?: number;\n};\n\nexport type ResolvedRedisWebSocketAdapterOptions = Required<\n Omit<RedisWebSocketAdapterOptions, \"redis\">\n>;\n\nexport const REDIS_WEBSOCKET_ADAPTER_DEFAULTS = {\n prefix: \"sonamu:ws\",\n heartbeatIntervalMs: 5000,\n // heartbeat 3회 누락. GC나 event loop 지연에 여유를 둔다\n nodeTimeoutMs: 15000,\n // nodeTimeoutMs의 2배. 라우팅은 nodes score로 먼저 거르므로 느리지만 살아 있는 노드의 키가 먼저 만료되지 않게 한다\n keyTtlMs: 30000,\n commandDeadlineMs: 2000,\n readyTimeoutMs: 3000,\n // 진행 중 명령의 deadline보다 길게 잡아 마지막 쓰기를 마칠 여유를 준다\n drainTimeoutMs: 5000,\n} as const;\n\nexport function resolveAdapterOptions(\n options: RedisWebSocketAdapterOptions,\n): ResolvedRedisWebSocketAdapterOptions {\n const resolved = {\n nodeId: options.nodeId ?? createWebSocketNodeId(),\n prefix: options.prefix ?? REDIS_WEBSOCKET_ADAPTER_DEFAULTS.prefix,\n heartbeatIntervalMs:\n options.heartbeatIntervalMs ?? REDIS_WEBSOCKET_ADAPTER_DEFAULTS.heartbeatIntervalMs,\n nodeTimeoutMs: options.nodeTimeoutMs ?? REDIS_WEBSOCKET_ADAPTER_DEFAULTS.nodeTimeoutMs,\n keyTtlMs: options.keyTtlMs ?? REDIS_WEBSOCKET_ADAPTER_DEFAULTS.keyTtlMs,\n commandDeadlineMs:\n options.commandDeadlineMs ?? REDIS_WEBSOCKET_ADAPTER_DEFAULTS.commandDeadlineMs,\n readyTimeoutMs: options.readyTimeoutMs ?? REDIS_WEBSOCKET_ADAPTER_DEFAULTS.readyTimeoutMs,\n drainTimeoutMs: options.drainTimeoutMs ?? REDIS_WEBSOCKET_ADAPTER_DEFAULTS.drainTimeoutMs,\n };\n\n if (resolved.nodeId === \"\") {\n throw new Error(\"Redis WebSocket adapter nodeId must not be empty.\");\n }\n if (resolved.prefix === \"\") {\n throw new Error(\"Redis WebSocket adapter prefix must not be empty.\");\n }\n for (const name of [\n \"heartbeatIntervalMs\",\n \"nodeTimeoutMs\",\n \"keyTtlMs\",\n \"commandDeadlineMs\",\n \"readyTimeoutMs\",\n \"drainTimeoutMs\",\n ] as const) {\n const value = resolved[name];\n if (!Number.isFinite(value) || value <= 0) {\n throw new Error(`Redis WebSocket adapter ${name} must be a positive number.`);\n }\n }\n return resolved;\n}\n"],"mappings":";;AAgCA,MAAa,mCAAmC;CAC9C,QAAQ;CACR,qBAAqB;CAErB,eAAe;CAEf,UAAU;CACV,mBAAmB;CACnB,gBAAgB;CAEhB,gBAAgB;AAClB;AAEA,SAAgB,sBACd,SACsC;CACtC,MAAM,WAAW;EACf,QAAQ,QAAQ,UAAU,sBAAsB;EAChD,QAAQ,QAAQ,UAAU,iCAAiC;EAC3D,qBACE,QAAQ,uBAAuB,iCAAiC;EAClE,eAAe,QAAQ,iBAAiB,iCAAiC;EACzE,UAAU,QAAQ,YAAY,iCAAiC;EAC/D,mBACE,QAAQ,qBAAqB,iCAAiC;EAChE,gBAAgB,QAAQ,kBAAkB,iCAAiC;EAC3E,gBAAgB,QAAQ,kBAAkB,iCAAiC;CAC7E;CAEA,IAAI,SAAS,WAAW,IACtB,MAAM,IAAI,MAAM,mDAAmD;CAErE,IAAI,SAAS,WAAW,IACtB,MAAM,IAAI,MAAM,mDAAmD;CAErE,KAAK,MAAM,QAAQ;EACjB;EACA;EACA;EACA;EACA;EACA;CACF,GAAY;EACV,MAAM,QAAQ,SAAS;EACvB,IAAI,CAAC,OAAO,SAAS,KAAK,KAAK,SAAS,GACtC,MAAM,IAAI,MAAM,2BAA2B,KAAK,4BAA4B;CAEhF;CACA,OAAO;AACT"}
|