Skip to content

Commit 06db052

Browse files
authored
Revert: Close the socket if there's a failure in start_connection() #10464 (#10656)
Reverts #10464 While this change improved the situation for uvloop users, it caused a regression with `SelectorEventLoop` (issue #10617) The alternative fix is MagicStack/uvloop#646 (not merged at the time of this PR) issue #10617 appears to be very similar to python/cpython@d5aeccf If someone can come up with a working reproducer for #10617 we can revisit this. cc @top-oai Minimal implementation that shows on cancellation the socket is cleaned up without the explicit `close` #10617 (comment) so this should be unneeded unless I've missed something (very possible with all the moving parts here) ## Related issue number fixes #10617
1 parent f3b0610 commit 06db052

File tree

5 files changed

+6
-65
lines changed

5 files changed

+6
-65
lines changed

CHANGES/10464.bugfix.rst

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
10656.bugfix.rst

CHANGES/10617.bugfix.rst

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
10656.bugfix.rst

CHANGES/10656.bugfix.rst

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Reverted explicitly closing sockets if an exception is raised during ``create_connection`` -- by :user:`bdraco`.
2+
3+
This change originally appeared in aiohttp 3.11.13

aiohttp/connector.py

+1-15
Original file line numberDiff line numberDiff line change
@@ -1119,7 +1119,6 @@ async def _wrap_create_connection(
11191119
client_error: Type[Exception] = ClientConnectorError,
11201120
**kwargs: Any,
11211121
) -> Tuple[asyncio.Transport, ResponseHandler]:
1122-
sock: Union[socket.socket, None] = None
11231122
try:
11241123
async with ceil_timeout(
11251124
timeout.sock_connect, ceil_threshold=timeout.ceil_threshold
@@ -1132,11 +1131,7 @@ async def _wrap_create_connection(
11321131
loop=self._loop,
11331132
socket_factory=self._socket_factory,
11341133
)
1135-
connection = await self._loop.create_connection(
1136-
*args, **kwargs, sock=sock
1137-
)
1138-
sock = None
1139-
return connection
1134+
return await self._loop.create_connection(*args, **kwargs, sock=sock)
11401135
except cert_errors as exc:
11411136
raise ClientConnectorCertificateError(req.connection_key, exc) from exc
11421137
except ssl_errors as exc:
@@ -1145,15 +1140,6 @@ async def _wrap_create_connection(
11451140
if exc.errno is None and isinstance(exc, asyncio.TimeoutError):
11461141
raise
11471142
raise client_error(req.connection_key, exc) from exc
1148-
finally:
1149-
if sock is not None:
1150-
# Will be hit if an exception is thrown before the event loop takes the socket.
1151-
# In that case, proactively close the socket to guard against event loop leaks.
1152-
# For example, see https://github.com/MagicStack/uvloop/issues/653.
1153-
try:
1154-
sock.close()
1155-
except OSError as exc:
1156-
raise client_error(req.connection_key, exc) from exc
11571143

11581144
def _warn_about_tls_in_tls(
11591145
self,

tests/test_connector.py

-50
Original file line numberDiff line numberDiff line change
@@ -646,56 +646,6 @@ async def test_tcp_connector_certificate_error(
646646
await conn.close()
647647

648648

649-
async def test_tcp_connector_closes_socket_on_error(
650-
loop: asyncio.AbstractEventLoop, start_connection: mock.AsyncMock
651-
) -> None:
652-
req = ClientRequest("GET", URL("https://127.0.0.1:443"), loop=loop)
653-
654-
conn = aiohttp.TCPConnector()
655-
with (
656-
mock.patch.object(
657-
conn._loop,
658-
"create_connection",
659-
autospec=True,
660-
spec_set=True,
661-
side_effect=ValueError,
662-
),
663-
pytest.raises(ValueError),
664-
):
665-
await conn.connect(req, [], ClientTimeout())
666-
667-
assert start_connection.return_value.close.called
668-
669-
await conn.close()
670-
671-
672-
async def test_tcp_connector_closes_socket_on_error_results_in_another_error(
673-
loop: asyncio.AbstractEventLoop, start_connection: mock.AsyncMock
674-
) -> None:
675-
"""Test that when error occurs while closing the socket."""
676-
req = ClientRequest("GET", URL("https://127.0.0.1:443"), loop=loop)
677-
start_connection.return_value.close.side_effect = OSError(
678-
1, "error from closing socket"
679-
)
680-
681-
conn = aiohttp.TCPConnector()
682-
with (
683-
mock.patch.object(
684-
conn._loop,
685-
"create_connection",
686-
autospec=True,
687-
spec_set=True,
688-
side_effect=ValueError,
689-
),
690-
pytest.raises(aiohttp.ClientConnectionError, match="error from closing socket"),
691-
):
692-
await conn.connect(req, [], ClientTimeout())
693-
694-
assert start_connection.return_value.close.called
695-
696-
await conn.close()
697-
698-
699649
async def test_tcp_connector_server_hostname_default(
700650
loop: asyncio.AbstractEventLoop, start_connection: mock.AsyncMock
701651
) -> None:

0 commit comments

Comments
 (0)