Skip to content

Commit fc73cb8

Browse files
committed
fix #1718 - add support for buffers in pubsub
1 parent 51b640b commit fc73cb8

File tree

5 files changed

+244
-88
lines changed

5 files changed

+244
-88
lines changed

.github/README.md

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,18 @@ Publish a message on a channel:
150150
await publisher.publish('channel', 'message');
151151
```
152152

153+
There is support for buffers as well:
154+
155+
```typescript
156+
await subscriber.subscribe('channel', (message) => {
157+
console.log(message); // <Buffer 6d 65 73 73 61 67 65>
158+
}, true);
159+
160+
await subscriber.pSubscribe('channe*', (message, channel) => {
161+
console.log(message, channel); // <Buffer 6d 65 73 73 61 67 65>, <Buffer 63 68 61 6e 6e 65 6c>
162+
}, true);
163+
```
164+
153165
### Scan Iterator
154166

155167
[`SCAN`](https://redis.io/commands/scan) results can be looped over using [async iterators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/asyncIterator):

packages/client/lib/client/commands-queue.ts

Lines changed: 145 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -39,9 +39,29 @@ export enum PubSubUnsubscribeCommands {
3939
PUNSUBSCRIBE = 'PUNSUBSCRIBE'
4040
}
4141

42-
export type PubSubListener = (message: string, channel: string) => unknown;
42+
type PubSubArgumentTypes = Buffer | string;
4343

44-
export type PubSubListenersMap = Map<string, Set<PubSubListener>>;
44+
export type PubSubListener<
45+
BUFFER_MODE extends boolean = false,
46+
T = BUFFER_MODE extends true ? Buffer : string
47+
> = (message: T, channel: T) => unknown;
48+
49+
interface PubSubListeners {
50+
buffers: Set<PubSubListener<true>>;
51+
strings: Set<PubSubListener<false>>;
52+
}
53+
54+
type PubSubListenersMap = Map<string, PubSubListeners>;
55+
56+
interface PubSubState {
57+
subscribing: number;
58+
subscribed: number;
59+
unsubscribing: number;
60+
listeners: {
61+
channels: PubSubListenersMap;
62+
patterns: PubSubListenersMap;
63+
};
64+
}
4565

4666
export default class RedisCommandsQueue {
4767
static #flushQueue<T extends CommandWaitingForReply>(queue: LinkedList<T>, err: Error): void {
@@ -50,10 +70,20 @@ export default class RedisCommandsQueue {
5070
}
5171
}
5272

53-
static #emitPubSubMessage(listeners: Set<PubSubListener>, message: string, channel: string): void {
54-
for (const listener of listeners) {
73+
static #emitPubSubMessage(listenersMap: PubSubListenersMap, message: Buffer, channel: Buffer, pattern?: Buffer): void {
74+
const keyString = (pattern || channel).toString(),
75+
listeners = listenersMap.get(keyString)!;
76+
for (const listener of listeners.buffers) {
5577
listener(message, channel);
5678
}
79+
80+
if (!listeners.strings.size) return;
81+
82+
const messageString = message.toString(),
83+
channelString = pattern ? channel.toString() : keyString;
84+
for (const listener of listeners.strings) {
85+
listener(messageString, channelString);
86+
}
5787
}
5888

5989
readonly #maxLength: number | null | undefined;
@@ -62,41 +92,43 @@ export default class RedisCommandsQueue {
6292

6393
readonly #waitingForReply = new LinkedList<CommandWaitingForReply>();
6494

65-
readonly #pubSubState = {
66-
subscribing: 0,
67-
subscribed: 0,
68-
unsubscribing: 0
69-
};
95+
#pubSubState: PubSubState | undefined;
7096

71-
readonly #pubSubListeners = {
72-
channels: <PubSubListenersMap>new Map(),
73-
patterns: <PubSubListenersMap>new Map()
97+
static readonly #PUB_SUB_MESSAGES = {
98+
message: Buffer.from('message'),
99+
pMessage: Buffer.from('pmessage'),
100+
subscribe: Buffer.from('subscribe'),
101+
pSubscribe: Buffer.from('psubscribe'),
102+
unsubscribe: Buffer.from('unsunscribe'),
103+
pUnsubscribe: Buffer.from('punsubscribe')
74104
};
75105

76106
readonly #parser = new RedisParser({
77107
returnReply: (reply: unknown) => {
78-
if ((this.#pubSubState.subscribing || this.#pubSubState.subscribed) && Array.isArray(reply)) {
79-
switch (reply[0]) {
80-
case 'message':
81-
return RedisCommandsQueue.#emitPubSubMessage(
82-
this.#pubSubListeners.channels.get(reply[1])!,
83-
reply[2],
84-
reply[1]
85-
);
86-
87-
case 'pmessage':
88-
return RedisCommandsQueue.#emitPubSubMessage(
89-
this.#pubSubListeners.patterns.get(reply[1])!,
90-
reply[3],
91-
reply[2]
92-
);
93-
94-
case 'subscribe':
95-
case 'psubscribe':
96-
if (--this.#waitingForReply.head!.value.channelsCounter! === 0) {
97-
this.#shiftWaitingForReply().resolve();
98-
}
99-
return;
108+
if (this.#pubSubState && Array.isArray(reply)) {
109+
if (RedisCommandsQueue.#PUB_SUB_MESSAGES.message.equals(reply[0])) {
110+
return RedisCommandsQueue.#emitPubSubMessage(
111+
this.#pubSubState.listeners.channels,
112+
reply[2],
113+
reply[1]
114+
);
115+
} else if (RedisCommandsQueue.#PUB_SUB_MESSAGES.pMessage.equals(reply[0])) {
116+
return RedisCommandsQueue.#emitPubSubMessage(
117+
this.#pubSubState.listeners.patterns,
118+
reply[3],
119+
reply[2],
120+
reply[1]
121+
);
122+
} else if (
123+
RedisCommandsQueue.#PUB_SUB_MESSAGES.subscribe.equals(reply[0]) ||
124+
RedisCommandsQueue.#PUB_SUB_MESSAGES.pSubscribe.equals(reply[0]) ||
125+
RedisCommandsQueue.#PUB_SUB_MESSAGES.unsubscribe.equals(reply[0]) ||
126+
RedisCommandsQueue.#PUB_SUB_MESSAGES.pUnsubscribe.equals(reply[0])
127+
) {
128+
if (--this.#waitingForReply.head!.value.channelsCounter! === 0) {
129+
this.#shiftWaitingForReply().resolve();
130+
}
131+
return;
100132
}
101133
}
102134

@@ -112,7 +144,7 @@ export default class RedisCommandsQueue {
112144
}
113145

114146
addCommand<T = RedisCommandRawReply>(args: RedisCommandArguments, options?: QueueCommandOptions, bufferMode?: boolean): Promise<T> {
115-
if (this.#pubSubState.subscribing || this.#pubSubState.subscribed) {
147+
if (this.#pubSubState) {
116148
return Promise.reject(new Error('Cannot send commands in PubSub mode'));
117149
} else if (this.#maxLength && this.#waitingToBeSent.length + this.#waitingForReply.length >= this.#maxLength) {
118150
return Promise.reject(new Error('The queue is full'));
@@ -126,7 +158,7 @@ export default class RedisCommandsQueue {
126158
chainId: options?.chainId,
127159
bufferMode,
128160
resolve,
129-
reject,
161+
reject
130162
});
131163

132164
if (options?.signal) {
@@ -153,17 +185,41 @@ export default class RedisCommandsQueue {
153185
});
154186
}
155187

156-
subscribe(command: PubSubSubscribeCommands, channels: string | Array<string>, listener: PubSubListener): Promise<void> {
157-
const channelsToSubscribe: Array<string> = [],
158-
listeners = command === PubSubSubscribeCommands.SUBSCRIBE ? this.#pubSubListeners.channels : this.#pubSubListeners.patterns;
188+
#initiatePubSubState(): PubSubState {
189+
return this.#pubSubState ??= {
190+
subscribed: 0,
191+
subscribing: 0,
192+
unsubscribing: 0,
193+
listeners: {
194+
channels: new Map(),
195+
patterns: new Map()
196+
}
197+
};
198+
}
199+
200+
subscribe<T extends boolean>(
201+
command: PubSubSubscribeCommands,
202+
channels: PubSubArgumentTypes | Array<PubSubArgumentTypes>,
203+
listener: PubSubListener<T>,
204+
bufferMode?: T
205+
): Promise<void> {
206+
const pubSubState = this.#initiatePubSubState(),
207+
channelsToSubscribe: Array<PubSubArgumentTypes> = [],
208+
listenersMap = command === PubSubSubscribeCommands.SUBSCRIBE ? pubSubState.listeners.channels : pubSubState.listeners.patterns;
159209
for (const channel of (Array.isArray(channels) ? channels : [channels])) {
160-
if (listeners.has(channel)) {
161-
listeners.get(channel)!.add(listener);
162-
continue;
210+
const channelString = typeof channel === 'string' ? channel : channel.toString();
211+
let listeners = listenersMap.get(channelString);
212+
if (!listeners) {
213+
listeners = {
214+
buffers: new Set(),
215+
strings: new Set()
216+
};
217+
listenersMap.set(channelString, listeners);
218+
channelsToSubscribe.push(channel);
163219
}
164220

165-
listeners.set(channel, new Set([listener]));
166-
channelsToSubscribe.push(channel);
221+
// https://github.com/microsoft/TypeScript/issues/23132
222+
(bufferMode ? listeners.buffers : listeners.strings).add(listener as any);
167223
}
168224

169225
if (!channelsToSubscribe.length) {
@@ -173,8 +229,20 @@ export default class RedisCommandsQueue {
173229
return this.#pushPubSubCommand(command, channelsToSubscribe);
174230
}
175231

176-
unsubscribe(command: PubSubUnsubscribeCommands, channels?: string | Array<string>, listener?: PubSubListener): Promise<void> {
177-
const listeners = command === PubSubUnsubscribeCommands.UNSUBSCRIBE ? this.#pubSubListeners.channels : this.#pubSubListeners.patterns;
232+
unsubscribe<T extends boolean>(
233+
command: PubSubUnsubscribeCommands,
234+
channels?: string | Array<string>,
235+
listener?: PubSubListener<T>,
236+
bufferMode?: T
237+
): Promise<void> {
238+
if (!this.#pubSubState) {
239+
return Promise.resolve();
240+
}
241+
242+
const listeners = command === PubSubUnsubscribeCommands.UNSUBSCRIBE ?
243+
this.#pubSubState.listeners.channels :
244+
this.#pubSubState.listeners.patterns;
245+
178246
if (!channels) {
179247
const size = listeners.size;
180248
listeners.clear();
@@ -183,13 +251,16 @@ export default class RedisCommandsQueue {
183251

184252
const channelsToUnsubscribe = [];
185253
for (const channel of (Array.isArray(channels) ? channels : [channels])) {
186-
const set = listeners.get(channel);
187-
if (!set) continue;
254+
const sets = listeners.get(channel);
255+
if (!sets) continue;
188256

189-
let shouldUnsubscribe = !listener;
257+
let shouldUnsubscribe;
190258
if (listener) {
191-
set.delete(listener);
192-
shouldUnsubscribe = set.size === 0;
259+
// https://github.com/microsoft/TypeScript/issues/23132
260+
(bufferMode ? sets.buffers : sets.strings).delete(listener as any);
261+
shouldUnsubscribe = !sets.buffers.size && !sets.strings.size;
262+
} else {
263+
shouldUnsubscribe = true;
193264
}
194265

195266
if (shouldUnsubscribe) {
@@ -205,11 +276,12 @@ export default class RedisCommandsQueue {
205276
return this.#pushPubSubCommand(command, channelsToUnsubscribe);
206277
}
207278

208-
#pushPubSubCommand(command: PubSubSubscribeCommands | PubSubUnsubscribeCommands, channels: number | Array<string>): Promise<void> {
279+
#pushPubSubCommand(command: PubSubSubscribeCommands | PubSubUnsubscribeCommands, channels: number | Array<PubSubArgumentTypes>): Promise<void> {
209280
return new Promise((resolve, reject) => {
210-
const isSubscribe = command === PubSubSubscribeCommands.SUBSCRIBE || command === PubSubSubscribeCommands.PSUBSCRIBE,
281+
const pubSubState = this.#initiatePubSubState(),
282+
isSubscribe = command === PubSubSubscribeCommands.SUBSCRIBE || command === PubSubSubscribeCommands.PSUBSCRIBE,
211283
inProgressKey = isSubscribe ? 'subscribing' : 'unsubscribing',
212-
commandArgs: Array<string> = [command];
284+
commandArgs: Array<PubSubArgumentTypes> = [command];
213285

214286
let channelsCounter: number;
215287
if (typeof channels === 'number') { // unsubscribe only
@@ -219,35 +291,41 @@ export default class RedisCommandsQueue {
219291
channelsCounter = channels.length;
220292
}
221293

222-
this.#pubSubState[inProgressKey] += channelsCounter;
294+
pubSubState[inProgressKey] += channelsCounter;
223295

224296
this.#waitingToBeSent.push({
225297
args: commandArgs,
226298
channelsCounter,
299+
bufferMode: true,
227300
resolve: () => {
228-
this.#pubSubState[inProgressKey] -= channelsCounter;
229-
this.#pubSubState.subscribed += channelsCounter * (isSubscribe ? 1 : -1);
301+
pubSubState[inProgressKey] -= channelsCounter;
302+
if (isSubscribe) {
303+
pubSubState.subscribed += channelsCounter;
304+
} else {
305+
pubSubState.subscribed -= channelsCounter;
306+
if (!pubSubState.subscribed && !pubSubState.subscribing && !pubSubState.subscribed) {
307+
this.#pubSubState = undefined;
308+
}
309+
}
230310
resolve();
231311
},
232312
reject: () => {
233-
this.#pubSubState[inProgressKey] -= channelsCounter;
313+
pubSubState[inProgressKey] -= channelsCounter * (isSubscribe ? 1 : -1);
234314
reject();
235315
}
236316
});
237317
});
238318
}
239319

240320
resubscribe(): Promise<any> | undefined {
241-
if (!this.#pubSubState.subscribed && !this.#pubSubState.subscribing) {
321+
if (!this.#pubSubState) {
242322
return;
243323
}
244324

245-
this.#pubSubState.subscribed = this.#pubSubState.subscribing = 0;
246-
247325
// TODO: acl error on one channel/pattern will reject the whole command
248326
return Promise.all([
249-
this.#pushPubSubCommand(PubSubSubscribeCommands.SUBSCRIBE, [...this.#pubSubListeners.channels.keys()]),
250-
this.#pushPubSubCommand(PubSubSubscribeCommands.PSUBSCRIBE, [...this.#pubSubListeners.patterns.keys()])
327+
this.#pushPubSubCommand(PubSubSubscribeCommands.SUBSCRIBE, [...this.#pubSubState.listeners.channels.keys()]),
328+
this.#pushPubSubCommand(PubSubSubscribeCommands.PSUBSCRIBE, [...this.#pubSubState.listeners.patterns.keys()])
251329
]);
252330
}
253331

@@ -269,7 +347,10 @@ export default class RedisCommandsQueue {
269347
}
270348

271349
parseResponse(data: Buffer): void {
272-
this.#parser.setReturnBuffers(!!this.#waitingForReply.head?.value.bufferMode);
350+
this.#parser.setReturnBuffers(
351+
!!this.#waitingForReply.head?.value.bufferMode ||
352+
!!this.#pubSubState?.subscribed
353+
);
273354
this.#parser.execute(data);
274355
}
275356

packages/client/lib/client/index.spec.ts

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -561,17 +561,27 @@ describe('Client', () => {
561561
}, GLOBAL.SERVERS.OPEN);
562562

563563
testUtils.testWithClient('PubSub', async publisher => {
564+
function assertStringListener(message: string, channel: string) {
565+
assert.ok(typeof message === 'string');
566+
assert.ok(typeof channel === 'string');
567+
}
568+
569+
function assertBufferListener(message: Buffer, channel: Buffer) {
570+
assert.ok(Buffer.isBuffer(message));
571+
assert.ok(Buffer.isBuffer(channel));
572+
}
573+
564574
const subscriber = publisher.duplicate();
565575

566576
await subscriber.connect();
567577

568578
try {
569-
const channelListener1 = spy(),
570-
channelListener2 = spy(),
571-
patternListener = spy();
579+
const channelListener1 = spy(assertBufferListener),
580+
channelListener2 = spy(assertStringListener),
581+
patternListener = spy(assertStringListener);
572582

573583
await Promise.all([
574-
subscriber.subscribe('channel', channelListener1),
584+
subscriber.subscribe('channel', channelListener1, true),
575585
subscriber.subscribe('channel', channelListener2),
576586
subscriber.pSubscribe('channel*', patternListener)
577587
]);
@@ -580,14 +590,14 @@ describe('Client', () => {
580590
waitTillBeenCalled(channelListener1),
581591
waitTillBeenCalled(channelListener2),
582592
waitTillBeenCalled(patternListener),
583-
publisher.publish('channel', 'message')
593+
publisher.publish(Buffer.from('channel'), Buffer.from('message'))
584594
]);
585595

586-
assert.ok(channelListener1.calledOnceWithExactly('message', 'channel'));
596+
assert.ok(channelListener1.calledOnceWithExactly(Buffer.from('message'), Buffer.from('channel')));
587597
assert.ok(channelListener2.calledOnceWithExactly('message', 'channel'));
588598
assert.ok(patternListener.calledOnceWithExactly('message', 'channel'));
589599

590-
await subscriber.unsubscribe('channel', channelListener1);
600+
await subscriber.unsubscribe('channel', channelListener1, true);
591601
await Promise.all([
592602
waitTillBeenCalled(channelListener2),
593603
waitTillBeenCalled(patternListener),

0 commit comments

Comments
 (0)