Describe the bug

redis-cli continue to be in pubsub/subscribed mode even if the server has unsubscribed the client for a given channel. This applies for both classic and sharded pubsub.

To reproduce

127.0.0.1:6379(subscribed mode)> SUBSCRIBE ch1
1) "subscribe"
2) "ch1"
3) (integer) 1
127.0.0.1:6379(subscribed mode)> unsubscribe ch1
1) "unsubscribe"
2) "ch1"
3) (integer) 0
127.0.0.1:6379(subscribed mode)>

Expected behavior

redis-cli should exit the subscribed mode

Additional information

Discussed in #12577

Comment From: hpatro

@zuiderkwast I think we need to maintain list(s) of active channel subscription for classic/shard pubsub on the client side and if the count reaches zero, we exit the subscribed mode. WDYT ?

Comment From: zuiderkwast

OK but I don't think it's a bug. The printout you get when you enter pubsub mode is "Reading messages... (press Ctrl-C to quit or any key to type command)". It means in redis-cli you need to press Ctrl-C to exit pubsub mode.

I would say what you are suggesting is a new feature. It would be nice to auto-exit pubsub mode, but I don't think it's strictly necessary.

Before the feature which let you enter commands in pubsub mode, it was the same behaviour except it wasn't possible to enter any commands at all. Ctrl-C was the only thing you could do in this mode. It is something similar in MONITOR mode still now.


Now, if we want to implement auto-exit, I don't think we need to track the lists of all the channels. We just need three flags: one for each kind of subscription (channel, pattern, shard-channel) indicating that we have one or more subscriptions of this kind. If we receive an unsubscribe message where the last element is zero, i.e. a message like

1) "unsubscribe"
2) "ch1"
3) (integer) 0

it means we don't have any more subscriptions of this kind, so we clear the flag. When all three flags are cleared, we exit pubsub mode.

Makes sense?

Comment From: hpatro

"It's not a bug, it's a feature"

Well if there is no subscription left, and it still continues in the subscription/pubsub mode, it looks like a bug to me since the start irrespective of the recent changes.

@zuiderkwast Thanks for looking at it. Yeah, the solution definitely makes sense, we can piggyback on the subscription count returned in the unsubscribe response. I'll pick it up shortly.