Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 42 additions & 11 deletions lib/DataHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,16 +206,18 @@ export default class DataHandler {
case "sunsubscribe":
case "unsubscribe":
case "punsubscribe": {
const count = reply[2] as string | Buffer | number;

if (this.redis.condition.subscriber) {
const channel = reply[1] ? reply[1].toString() : null;
if (channel) {
// `""` is a valid channel name, so both guards test for a missing
// reply element rather than truthiness — skipping `del()` for it
// would keep the set non-empty and strand subscriber mode below.
const channel = reply[1] == null ? null : reply[1].toString();
if (channel !== null) {
this.redis.condition.subscriber.del(replyType, channel);
}
}

const count = reply[2] as string | Buffer | number;
if (Number(count) === 0) {
this.redis.condition.subscriber = false;
leaveSubscriberModeIfDone(this.redis.condition, count);
}

if (this.handleUnsolicitedUnsubscribe(replyType)) {
Expand Down Expand Up @@ -313,14 +315,13 @@ export default class DataHandler {
case "sunsubscribe":
case "unsubscribe":
case "punsubscribe": {
const channel = reply[1] ? reply[1].toString() : null;
if (channel) {
// See the matching comment in `returnPush` about the empty channel name.
const channel = reply[1] == null ? null : reply[1].toString();
if (channel !== null) {
this.redis.condition.subscriber.del(replyType, channel);
}
const count = reply[2];
if (Number(count) === 0) {
this.redis.condition.subscriber = false;
}
leaveSubscriberModeIfDone(this.redis.condition, count);
if (this.handleUnsolicitedUnsubscribe(replyType)) {
break;
}
Expand Down Expand Up @@ -391,6 +392,36 @@ export default class DataHandler {
}
}

// Both the count carried by the reply and the subscription set are partial
// views of the connection's subscriptions, and neither one alone answers
// "is this connection still in subscriber mode?":
//
// - The count only covers channels of the same kind as the command
// (SUNSUBSCRIBE reports remaining shard channels, and UNSUBSCRIBE /
// PUNSUBSCRIBE ignore shard channels), so it reaching zero says nothing
// about the other kinds.
// - The set is keyed by the utf8 rendering of the channel name, so channel
// names that are distinct as bytes but decode alike (e.g. the invalid
// sequences `<80>` and `<81>`, which both render as U+FFFD) share one key.
// Unsubscribing either one empties that key, so the set can read empty
// while the server still holds a same-kind subscription.
//
// Requiring both covers each one's blind spot with the other: the count rules
// out a same-kind subscription the set collapsed, and the set rules out the
// kinds the count ignores. A reply carrying no count is not authoritative
// about anything, so it does not hold the connection in subscriber mode on its
// own.
function leaveSubscriberModeIfDone(
condition: Condition,
count: string | Buffer | number
) {
const remaining = Number(count);
const subscriber = condition.subscriber as SubscriptionSet;
if (subscriber.isEmpty() && !(remaining > 0)) {
condition.subscriber = false;
Comment thread
askalf marked this conversation as resolved.
Resolved
Comment thread
askalf marked this conversation as resolved.
Resolved
}
}

// All string RESP types (simple, blob, verbatim) decode to Buffer rather than
// utf8 strings. This keeps the parser encoding-agnostic: ioredis decides
// utf8-vs-Buffer per command afterwards via `replyEncoding`. Decoding to utf8
Expand Down
18 changes: 14 additions & 4 deletions lib/SubscriptionSet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,24 @@ import { CommandNameFlags } from "./Command";
type AddSet = CommandNameFlags["ENTER_SUBSCRIBER_MODE"][number];
type DelSet = CommandNameFlags["EXIT_SUBSCRIBER_MODE"][number];

type ChannelSet = { [channel: string]: boolean };

// Channel names come from the server, so they can collide with the names
// inherited from `Object.prototype`. Assigning `__proto__` on a plain object
// hits the prototype setter instead of creating an own key, which would hide
// the channel from `channels()` and from `isEmpty()`.
function createChannelSet(): ChannelSet {
return Object.create(null) as ChannelSet;
}

/**
* Tiny class to simplify dealing with subscription set
*/
export default class SubscriptionSet {
private set: { [key: string]: { [channel: string]: boolean } } = {
subscribe: {},
psubscribe: {},
ssubscribe: {},
private set: { [key: string]: ChannelSet } = {
subscribe: createChannelSet(),
psubscribe: createChannelSet(),
ssubscribe: createChannelSet(),
};

add(set: AddSet, channel: string) {
Expand Down
32 changes: 32 additions & 0 deletions test/helpers/mock_server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -222,3 +222,35 @@ export function pubSubReply(
}
return [type, channel, value];
}

// `pubSubReply` goes through the string-based writer, which cannot carry a
// channel name that is not valid utf8. This builds the same reply as raw bytes
// instead, for the binary-safe channel names, and returns a Buffer to write to
// the socket directly (RESP3 push frame or RESP2 array, as the protocol asks).
export function rawPubSubReply(
protocol: MockServerProtocol,
type: string,
channel: string | Buffer,
value: string | number = 1
): Buffer {
const channelBytes = Buffer.isBuffer(channel)
? channel
: Buffer.from(channel);
const parts = [
Buffer.from(`${protocol === 3 ? ">" : "*"}3\r\n`),
blobString(Buffer.from(type)),
blobString(channelBytes),
typeof value === "number"
? Buffer.from(`:${value}\r\n`)
: blobString(Buffer.from(value)),
];
return Buffer.concat(parts);
}

function blobString(payload: Buffer): Buffer {
return Buffer.concat([
Buffer.from(`$${payload.length}\r\n`),
payload,
Buffer.from("\r\n"),
]);
}
Loading