Skip to content

Commit dc856d2

Browse files
committed
PYTHON-5272 Fix PyPy failure: keep asyncio.sslproto import lazy
Module-level import of asyncio.sslproto on PyPy 3.11 changed GC timing and surfaced a pre-existing unclosed-socket ResourceWarning as a test error. Use a module-level None sentinel instead and initialise it on first use inside the function, which keeps the import lazy while still capturing the true original SSLProtocol before any patching occurs.
1 parent c9f62fe commit dc856d2

1 file changed

Lines changed: 12 additions & 8 deletions

File tree

pymongo/pool_shared.py

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -81,12 +81,10 @@ def _get_ssl_session(ssl_sock: Any) -> Optional[Any]:
8181
# On older Python, _SSLPipe.do_handshake calls wrap_bio and starts the handshake
8282
# atomically; session injection there requires copying private internals, so we skip it.
8383
_ASYNCIO_SSL_SESSION_SUPPORTED = sys.version_info >= (3, 11)
84-
if _ASYNCIO_SSL_SESSION_SUPPORTED:
85-
import asyncio.sslproto as _asyncio_sslproto
86-
87-
# Capture the true original once at import time so concurrent connections
88-
# always restore to it, not to a locally-captured (possibly stale) reference.
89-
_ORIGINAL_SSL_PROTOCOL = _asyncio_sslproto.SSLProtocol
84+
# Captured lazily on first SSL async connection; never reset thereafter so
85+
# concurrent connections always restore to the true original, not a locally-
86+
# captured (possibly stale) reference.
87+
_ORIGINAL_SSL_PROTOCOL: Any = None
9088

9189

9290
def _make_session_ssl_protocol(session: Any) -> Any:
@@ -389,8 +387,14 @@ async def _configured_protocol_interface(
389387
if ssl_session_cache is not None and _ASYNCIO_SSL_SESSION_SUPPORTED
390388
else None
391389
)
392-
if session is not None:
393-
_asyncio_sslproto.SSLProtocol = _make_session_ssl_protocol(session) # type: ignore[misc]
390+
if _ASYNCIO_SSL_SESSION_SUPPORTED:
391+
import asyncio.sslproto as _asyncio_sslproto
392+
393+
global _ORIGINAL_SSL_PROTOCOL # noqa: PLW0603
394+
if _ORIGINAL_SSL_PROTOCOL is None:
395+
_ORIGINAL_SSL_PROTOCOL = _asyncio_sslproto.SSLProtocol
396+
if session is not None:
397+
_asyncio_sslproto.SSLProtocol = _make_session_ssl_protocol(session) # type: ignore[misc]
394398
try:
395399
# We have to pass hostname / ip address to wrap_socket
396400
# to use SSLContext.check_hostname.

0 commit comments

Comments
 (0)