Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add lock to Pubsub.execute_command to ensure only one connection is created #3051

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
19 changes: 11 additions & 8 deletions redis/client.py
Expand Up @@ -739,6 +739,7 @@ def __init__(
self.health_check_response = [b"pong", self.health_check_response_b]
if self.push_handler_func is None:
_set_info_logger()
self._connection_lock = threading.Lock()
self.reset()

def __enter__(self) -> "PubSub":
Expand Down Expand Up @@ -812,14 +813,16 @@ def execute_command(self, *args):
# subscribed to one or more channels

if self.connection is None:
self.connection = self.connection_pool.get_connection(
"pubsub", self.shard_hint
)
# register a callback that re-subscribes to any channels we
# were listening to when we were disconnected
self.connection.register_connect_callback(self.on_connect)
if self.push_handler_func is not None and not HIREDIS_AVAILABLE:
self.connection._parser.set_push_handler(self.push_handler_func)
with self._connection_lock:
if self.connection is None:
self.connection = self.connection_pool.get_connection(
"pubsub", self.shard_hint
)
# register a callback that re-subscribes to any channels we
# were listening to when we were disconnected
self.connection.register_connect_callback(self.on_connect)
if self.push_handler_func is not None and not HIREDIS_AVAILABLE:
self.connection._parser.set_push_handler(self.push_handler_func)
connection = self.connection
kwargs = {"check_health": not self.subscribed}
if not self.subscribed:
Expand Down
19 changes: 19 additions & 0 deletions tests/test_pubsub.py
Expand Up @@ -1153,3 +1153,22 @@ def get_msg():

# the timeout on the read should not cause disconnect
assert is_connected()


@pytest.mark.onlynoncluster
class TestConnectionLeak:
def test_connection_leak(self, r: redis.Redis):
pubsub = r.pubsub()

def test():
tid = threading.get_ident()
pubsub.subscribe(f"foo{tid}")

threads = [threading.Thread(target=test) for _ in range(10)]
for thread in threads:
thread.start()

for thread in threads:
thread.join()

assert r.connection_pool._created_connections == 2