-
Notifications
You must be signed in to change notification settings - Fork 1.2k
PYTHON-5867 - Close sockets on interruption or cancellation during async connection creation #2858
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
NoahStapp
wants to merge
8
commits into
mongodb:master
Choose a base branch
from
NoahStapp:PYTHON-5867
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.
+138
−23
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
cb2307a
PYTHON-5867 - Close sockets on interruption or cancellation during as…
NoahStapp 0499642
Fix in-use socket re-use
NoahStapp 15eba94
Merge branch 'master' into PYTHON-5867
NoahStapp 7822321
Isolate test patching
NoahStapp e5930f0
Fix test
NoahStapp 784c6cd
More tests
NoahStapp 5b92f74
Remove racy closes
NoahStapp 3cfeb77
Merge branch 'master' into PYTHON-5867
sophiayangDB 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
Some comments aren't visible on the classic Files Changed page.
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 |
|---|---|---|
|
|
@@ -16,14 +16,20 @@ | |
| from __future__ import annotations | ||
|
|
||
| import asyncio | ||
| import functools | ||
| import socket as _socket | ||
| import ssl as _ssl | ||
|
Contributor
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. Do |
||
| import sys | ||
| from test.asynchronous.utils import async_get_pool | ||
| from test.utils_shared import delay, one | ||
| from unittest.mock import patch | ||
|
|
||
| sys.path[0:0] = [""] | ||
|
|
||
| from test.asynchronous import AsyncIntegrationTest, async_client_context, connected | ||
|
|
||
| from pymongo import pool_shared | ||
|
|
||
|
|
||
| class TestAsyncCancellation(AsyncIntegrationTest): | ||
| async def test_async_cancellation_closes_connection(self): | ||
|
|
@@ -127,3 +133,100 @@ async def task(): | |
| await task | ||
|
|
||
| self.assertTrue(change_stream._closed) | ||
|
|
||
| async def test_cancellation_closes_socket_during_create_connection(self): | ||
| address = (await async_client_context.host, await async_client_context.port) | ||
| options = (await async_get_pool(self.client)).opts | ||
|
|
||
| created_sockets: list[_socket.socket] = [] | ||
| real_socket_cls = _socket.socket | ||
| target_task = None | ||
|
|
||
| def tracking_socket(*args, **kwargs): | ||
| s = real_socket_cls(*args, **kwargs) | ||
| if asyncio.current_task() is target_task: | ||
| created_sockets.append(s) | ||
| return s | ||
|
|
||
| loop = asyncio.get_running_loop() | ||
| real_sock_connect = loop.sock_connect | ||
| started = asyncio.Event() | ||
| block_forever = asyncio.Event() | ||
|
|
||
| async def slow_sock_connect(sock, addr): | ||
| if sock in created_sockets: | ||
| started.set() | ||
| await block_forever.wait() | ||
| return None | ||
| return await real_sock_connect(sock, addr) | ||
|
|
||
| with ( | ||
| patch.object(_socket, "socket", tracking_socket), | ||
| patch.object(loop, "sock_connect", slow_sock_connect), | ||
| ): | ||
| task = asyncio.create_task(pool_shared._async_create_connection(address, options)) | ||
| target_task = task | ||
| await asyncio.wait_for(started.wait(), timeout=5) | ||
| task.cancel() | ||
| with self.assertRaises(asyncio.CancelledError): | ||
| await task | ||
| self.assertTrue(created_sockets, "expected at least one socket to be created") | ||
| for sock in created_sockets: | ||
| self.assertEqual( | ||
| sock.fileno(), | ||
| -1, | ||
| f"socket leaked across cancellation: {sock!r}", | ||
| ) | ||
|
|
||
| async def test_cancellation_closes_socket_during_ssl_wrap_socket(self): | ||
| address = (await async_client_context.host, await async_client_context.port) | ||
| options = (await async_get_pool(self.client)).opts | ||
| fake_ssl_context = _ssl.create_default_context() | ||
|
|
||
| created_sockets: list[_socket.socket] = [] | ||
| real_socket_cls = _socket.socket | ||
| target_task = None | ||
|
|
||
| def tracking_socket(*args, **kwargs): | ||
| s = real_socket_cls(*args, **kwargs) | ||
| if asyncio.current_task() is target_task: | ||
| created_sockets.append(s) | ||
| return s | ||
|
|
||
| loop = asyncio.get_running_loop() | ||
| real_run_in_executor = loop.run_in_executor | ||
| started = asyncio.Event() | ||
|
|
||
| def slow_run_in_executor(executor, func, *args): | ||
| # Need to unwrap the SNI branch here if present | ||
| inner = func.func if isinstance(func, functools.partial) else func | ||
| # Each `ctx.wrap_socket` access returns a fresh bound-method | ||
| # object, so we check the bound instance (__self__) instead | ||
| if ( | ||
| getattr(inner, "__self__", None) is fake_ssl_context | ||
| and asyncio.current_task() is target_task | ||
| ): | ||
| started.set() | ||
| # Return a future that never completes for cancellation. | ||
| return asyncio.get_running_loop().create_future() | ||
| return real_run_in_executor(executor, func, *args) | ||
|
|
||
| with ( | ||
| patch.object(_socket, "socket", tracking_socket), | ||
| patch.object(loop, "run_in_executor", slow_run_in_executor), | ||
| patch.object(options, "_PoolOptions__ssl_context", fake_ssl_context), | ||
| ): | ||
| task = asyncio.create_task(pool_shared._async_configured_socket(address, options)) | ||
| target_task = task | ||
| await asyncio.wait_for(started.wait(), timeout=5) | ||
| task.cancel() | ||
| with self.assertRaises(asyncio.CancelledError): | ||
| await task | ||
|
|
||
| self.assertTrue(created_sockets, "expected at least one socket to be created") | ||
| for sock in created_sockets: | ||
| self.assertEqual( | ||
| sock.fileno(), | ||
| -1, | ||
| f"socket leaked across cancellation: {sock!r}", | ||
| ) | ||
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.