-
Notifications
You must be signed in to change notification settings - Fork 2.6k
Fix async client safety #3512
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
Open
abrookins
wants to merge
12
commits into
redis:master
Choose a base branch
from
abrookins:fix-async-client-safety
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+119
−5
Open
Fix async client safety #3512
Changes from 3 commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
c87e01f
Add an "invoke formatters" command
abrookins 95693c8
Fix async safety when Redis client is used as an async context manager
abrookins 3953ac3
Remove now unnecessary lock from testing
abrookins 34ce3de
Clean up variable
abrookins 955df70
fix test, apply logic to async cluster client
abrookins 1580dd4
linting
abrookins cf079d1
Merge branch 'master' into fix-async-client-safety
abrookins a12aff3
Merge branch 'master' into fix-async-client-safety
petyaslavova 2c9af66
Merge branch 'master' into fix-async-client-safety
abrookins fa43e6b
Fix PR feedback
abrookins 31e6a44
Merge branch 'master' into fix-async-client-safety
petyaslavova 91575b7
Merge branch 'master' into fix-async-client-safety
abrookins File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -362,6 +362,12 @@ def __init__( | |
# on a set of redis commands | ||
self._single_conn_lock = asyncio.Lock() | ||
|
||
# When used as an async context manager, we need to increment and decrement | ||
# a usage counter so that we can close the connection pool when no one is | ||
# using the client. | ||
self._usage_counter = 0 | ||
self._usage_lock = asyncio.Lock() | ||
|
||
def __repr__(self): | ||
return ( | ||
f"<{self.__class__.__module__}.{self.__class__.__name__}" | ||
|
@@ -562,10 +568,40 @@ def client(self) -> "Redis": | |
) | ||
|
||
async def __aenter__(self: _RedisT) -> _RedisT: | ||
return await self.initialize() | ||
""" | ||
Async context manager entry. Increments a usage counter so that the | ||
connection pool is only closed (via aclose()) when no one is using the client. | ||
""" | ||
async with self._usage_lock: | ||
self._usage_counter += 1 | ||
current_usage = self._usage_counter | ||
try: | ||
# Initialize the client (i.e. establish connection, etc.) | ||
return await self.initialize() | ||
except Exception: | ||
# If initialization fails, decrement the counter to keep it in sync | ||
async with self._usage_lock: | ||
abrookins marked this conversation as resolved.
Show resolved
Hide resolved
|
||
self._usage_counter -= 1 | ||
raise | ||
|
||
async def _decrement_usage(self) -> int: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. A helper method is required so we can use it in the |
||
""" | ||
Helper coroutine to decrement the usage counter while holding the lock. | ||
Returns the new value of the usage counter. | ||
""" | ||
async with self._usage_lock: | ||
self._usage_counter -= 1 | ||
return self._usage_counter | ||
|
||
async def __aexit__(self, exc_type, exc_value, traceback): | ||
await self.aclose() | ||
""" | ||
Async context manager exit. Decrements a usage counter. If this is the | ||
last exit (counter becomes zero), the client closes its connection pool. | ||
""" | ||
current_usage = await asyncio.shield(self._decrement_usage()) | ||
if current_usage == 0: | ||
# This was the last active context, so disconnect the pool. | ||
await asyncio.shield(self.aclose()) | ||
|
||
_DEL_MESSAGE = "Unclosed Redis client" | ||
|
||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -33,6 +33,12 @@ def linters(c): | |
run("vulture redis whitelist.py --min-confidence 80") | ||
run("flynt --fail-on-change --dry-run tests redis") | ||
|
||
@task | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. That formatter logic is no longer valid. We migrated from black and isort to ruff |
||
def formatters(c): | ||
"""Format code""" | ||
run("black --target-version py37 tests redis") | ||
run("isort tests redis") | ||
|
||
|
||
@task | ||
def all_tests(c): | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
import asyncio | ||
|
||
import pytest | ||
|
||
|
||
@pytest.mark.asyncio | ||
async def test_usage_counter(create_redis): | ||
r = await create_redis(decode_responses=True) | ||
|
||
async def dummy_task(): | ||
async with r: | ||
await asyncio.sleep(0.01) | ||
|
||
tasks = [dummy_task() for _ in range(20)] | ||
await asyncio.gather(*tasks) | ||
|
||
# After all tasks have completed, the usage counter should be back to zero. | ||
assert r._usage_counter == 0 |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.