diff --git a/pymongo/_kms_connect_shared.py b/pymongo/_kms_connect_shared.py index 3bdaa1f9b1..4620883978 100644 --- a/pymongo/_kms_connect_shared.py +++ b/pymongo/_kms_connect_shared.py @@ -94,7 +94,7 @@ def _remaining(deadline: float) -> float: """Seconds left before ``deadline``.""" left = deadline - time.monotonic() if left <= 0: - raise socket.timeout("timed out connecting through the proxy") + raise TimeoutError("timed out connecting through the proxy") return left @@ -423,12 +423,12 @@ def _connect_proxy(self, deadline: float) -> socket.socket: # Propagate the timeout from _remaining rather than report a # connect error. sock.settimeout(_remaining(deadline)) - except socket.timeout: + except TimeoutError: sock.close() raise try: sock.connect(sockaddr) - except socket.timeout: + except TimeoutError: # Preserve the timeout type rather than report a generic # connect error. sock.close() @@ -476,13 +476,13 @@ async def __call__(self, context: KMSConnectContext) -> socket.socket: # type: raise exc from None # The task succeeded right at the deadline. _close_late_bridge_sockets(late_sockets, future) - raise socket.timeout("timed out connecting through the proxy") from None + raise TimeoutError("timed out connecting through the proxy") from None if not future.done(): # The thread runs on regardless; close its late sockets. future.add_done_callback( functools.partial(_close_late_bridge_sockets, late_sockets) ) - raise socket.timeout("timed out connecting through the proxy") from None + raise TimeoutError("timed out connecting through the proxy") from None # Sphinx documents these classes under pymongo.encryption_options, the public diff --git a/pymongo/asynchronous/_kms_connect.py b/pymongo/asynchronous/_kms_connect.py index 0b2d8a8086..73e220cda4 100644 --- a/pymongo/asynchronous/_kms_connect.py +++ b/pymongo/asynchronous/_kms_connect.py @@ -102,11 +102,11 @@ async def _connect_kms( except asyncio.CancelledError: task.add_done_callback(_close_late_socket) raise - except asyncio.TimeoutError: + except TimeoutError: task.add_done_callback(_close_late_socket) _raise_connection_failure( address, - socket.timeout("timed out"), + TimeoutError("timed out"), timeout_details=_get_timeout_details(opts), ) if not isinstance(sock, socket.socket) or isinstance(sock, ssl.SSLSocket): diff --git a/pymongo/asynchronous/encryption.py b/pymongo/asynchronous/encryption.py index d0e9f17b25..ec3b2ac4df 100644 --- a/pymongo/asynchronous/encryption.py +++ b/pymongo/asynchronous/encryption.py @@ -18,7 +18,6 @@ import asyncio import functools -import socket import time as time # noqa: PLC0414 # needed in sync version import uuid import weakref @@ -210,7 +209,7 @@ async def kms_request(self, kms_context: MongoCryptKmsContext) -> None: except Exception as exc: # Wrap I/O errors in PyMongo exceptions. if isinstance(exc, BLOCKING_IO_ERRORS): - exc = socket.timeout("timed out") + exc = TimeoutError("timed out") # Async raises an OSError instead of returning empty bytes. if isinstance(exc, OSError): msg_prefix = "KMS connection closed" diff --git a/pymongo/lock.py b/pymongo/lock.py index eabe82f38e..a26c455212 100644 --- a/pymongo/lock.py +++ b/pymongo/lock.py @@ -84,7 +84,7 @@ def _release_locks() -> None: async def _async_cond_wait(condition: Condition, timeout: float | None) -> bool: try: return await wait_for(condition.wait(), timeout) - except asyncio.TimeoutError: + except TimeoutError: return False diff --git a/pymongo/network_layer.py b/pymongo/network_layer.py index ad068aaf5e..042ecb4ae4 100644 --- a/pymongo/network_layer.py +++ b/pymongo/network_layer.py @@ -85,9 +85,9 @@ async def async_socket_sendall(sock: socket.socket | _sslConn, buf: bytes) -> No await asyncio.wait_for(loop.sock_sendall(sock, buf), timeout=timeout) # type: ignore[arg-type] finally: sock.settimeout(timeout) - except asyncio.TimeoutError as exc: - # Convert the asyncio.wait_for timeout error to socket.timeout which pool.py understands. - raise socket.timeout("timed out") from exc + except TimeoutError as exc: + # asyncio.wait_for raises TimeoutError without a message. + raise TimeoutError("timed out") from exc if sys.platform != "win32": @@ -193,7 +193,7 @@ async def _async_blocking_socket_call( fut = asyncio.shield(inner) try: return await asyncio.wait_for(fut, timeout=timeout) - except (asyncio.CancelledError, asyncio.TimeoutError): + except (asyncio.CancelledError, TimeoutError): # Wait for the worker, shielded from further cancellations, so the # caller does not close the socket under it. while True: @@ -241,8 +241,9 @@ async def async_receive_data_socket(sock: socket.socket | _sslConn, length: int) _async_socket_receive(sock, length, loop), # type: ignore[arg-type] timeout=timeout, ) - except asyncio.TimeoutError as err: - raise socket.timeout("timed out") from err + except TimeoutError as err: + # asyncio.wait_for raises TimeoutError without a message. + raise TimeoutError("timed out") from err finally: sock.settimeout(timeout) @@ -294,7 +295,7 @@ def wait_for_read(conn: Connection, deadline: float | None) -> None: if readable: return if timed_out: - raise socket.timeout("timed out") + raise TimeoutError("timed out") def receive_data(conn: Connection, length: int, deadline: float | None) -> memoryview: @@ -329,8 +330,8 @@ def receive_data(conn: Connection, length: int, deadline: float | None) -> memor if conn.cancel_context.cancelled: raise _OperationCancelled("operation cancelled") from None # We reached the true deadline. - raise socket.timeout("timed out") from None - except socket.timeout: + raise TimeoutError("timed out") from None + except TimeoutError: if conn.cancel_context.cancelled: raise _OperationCancelled("operation cancelled") from None if _WINDOWS or ( @@ -672,9 +673,9 @@ async def wait_closed(self) -> None: async def async_sendall(conn: PyMongoProtocol, buf: bytes) -> None: try: await asyncio.wait_for(conn.write(buf), timeout=conn.gettimeout) - except asyncio.TimeoutError as exc: - # Convert the asyncio.wait_for timeout error to socket.timeout which pool.py understands. - raise socket.timeout("timed out") from exc + except TimeoutError as exc: + # asyncio.wait_for raises TimeoutError without a message. + raise TimeoutError("timed out") from exc async def async_receive_message( @@ -710,7 +711,7 @@ async def async_receive_message( if pending: await asyncio.wait(pending) if len(done) == 0: - raise socket.timeout("timed out") + raise TimeoutError("timed out") if read_task in done: data, op_code = read_task.result() try: diff --git a/pymongo/pool_shared.py b/pymongo/pool_shared.py index 7c6588fabb..513136194f 100644 --- a/pymongo/pool_shared.py +++ b/pymongo/pool_shared.py @@ -526,7 +526,7 @@ def _raise_connection_failure( msg = msg_prefix + msg if "configured timeouts" not in msg: msg += format_timeout_details(timeout_details) - if isinstance(error, socket.timeout) or ( + if isinstance(error, TimeoutError) or ( isinstance(error, SSLErrors) and "timed out" in str(error) ): raise NetworkTimeout(msg) from error @@ -643,7 +643,7 @@ async def _async_create_connection(address: _Address, options: PoolOptions) -> s if timeout is None: timeout = options.connect_timeout elif timeout <= 0: - raise socket.timeout("timed out") + raise TimeoutError("timed out") sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, True) _set_keepalive_times(sock) # Socket needs to be non-blocking during connection to not block the event loop @@ -653,9 +653,9 @@ async def _async_create_connection(address: _Address, options: PoolOptions) -> s ) sock.settimeout(timeout) return sock - except asyncio.TimeoutError as e: + except TimeoutError as e: sock.close() - err = socket.timeout("timed out") + err = TimeoutError("timed out") err.__cause__ = e except OSError as e: sock.close() @@ -889,7 +889,7 @@ def _create_connection(address: _Address, options: PoolOptions) -> socket.socket if timeout is None: timeout = options.connect_timeout elif timeout <= 0: - raise socket.timeout("timed out") + raise TimeoutError("timed out") sock.settimeout(timeout) sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, True) _set_keepalive_times(sock) diff --git a/pymongo/pyopenssl_context.py b/pymongo/pyopenssl_context.py index 629fb39639..e33ebe57b9 100644 --- a/pymongo/pyopenssl_context.py +++ b/pymongo/pyopenssl_context.py @@ -135,7 +135,7 @@ def _call(self, call: Callable[..., _T], *args: Any, **kwargs: Any) -> _T: # Check for closed socket. if self.fileno() == -1: if timeout and _time.monotonic() - start > timeout: - raise _socket.timeout("timed out") from None + raise TimeoutError("timed out") from None raise SSLError("Underlying socket has been closed") from None if isinstance(exc, _SSL.WantReadError): want_read = True @@ -148,7 +148,7 @@ def _call(self, call: Callable[..., _T], *args: Any, **kwargs: Any) -> _T: want_write = True self.socket_checker.select(self, want_read, want_write, timeout) if timeout and _time.monotonic() - start > timeout: - raise _socket.timeout("timed out") from None + raise TimeoutError("timed out") from None continue def do_handshake(self, *args: Any, **kwargs: Any) -> None: diff --git a/pymongo/synchronous/_kms_connect.py b/pymongo/synchronous/_kms_connect.py index 255b01e7f0..06d5be379f 100644 --- a/pymongo/synchronous/_kms_connect.py +++ b/pymongo/synchronous/_kms_connect.py @@ -102,11 +102,11 @@ def _connect_kms( except asyncio.CancelledError: task.add_done_callback(_close_late_socket) raise - except asyncio.TimeoutError: + except TimeoutError: task.add_done_callback(_close_late_socket) _raise_connection_failure( address, - socket.timeout("timed out"), + TimeoutError("timed out"), timeout_details=_get_timeout_details(opts), ) if not isinstance(sock, socket.socket) or isinstance(sock, ssl.SSLSocket): diff --git a/pymongo/synchronous/encryption.py b/pymongo/synchronous/encryption.py index 9ffd9331b1..0fe9196376 100644 --- a/pymongo/synchronous/encryption.py +++ b/pymongo/synchronous/encryption.py @@ -17,7 +17,6 @@ from __future__ import annotations import functools -import socket import time as time # noqa: PLC0414 # needed in sync version import uuid import weakref @@ -209,7 +208,7 @@ def kms_request(self, kms_context: MongoCryptKmsContext) -> None: except Exception as exc: # Wrap I/O errors in PyMongo exceptions. if isinstance(exc, BLOCKING_IO_ERRORS): - exc = socket.timeout("timed out") + exc = TimeoutError("timed out") # Async raises an OSError instead of returning empty bytes. if isinstance(exc, OSError): msg_prefix = "KMS connection closed" diff --git a/pyproject.toml b/pyproject.toml index 46a188d9b8..e8c68fa546 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -241,7 +241,6 @@ ignore = [ "C408", # Unnecessary `dict` call (rewrite as a literal) "SIM117", # Use a single `with` statement with multiple contexts instead of nested `with` statements "PLC0415", # `import` should be at the top-level of a file - "UP041", # `asyncio.TimeoutError` is an alias of `TimeoutError` on 3.11+ "ASYNC109", # Async function with a `timeout` parameter (CSOT timeouts are not `asyncio.timeout`) "UP042", # `str, Enum` should be `StrEnum` (changes `__str__` semantics) "UP017", # `timezone.utc` preferred over `datetime.UTC` (keep existing style) diff --git a/test/asynchronous/test_async_network_layer.py b/test/asynchronous/test_async_network_layer.py index ad146e1e79..96abf34240 100644 --- a/test/asynchronous/test_async_network_layer.py +++ b/test/asynchronous/test_async_network_layer.py @@ -265,7 +265,7 @@ def slow(arg): time.sleep(0.4) finished.set() - with self.assertRaises(asyncio.TimeoutError): + with self.assertRaises(TimeoutError): await _async_blocking_socket_call(asyncio.get_running_loop(), slow, None, 0.3) self.assertTrue(finished.is_set()) diff --git a/test/asynchronous/test_load_balancer.py b/test/asynchronous/test_load_balancer.py index 7866f1f7e6..ea25d43e9b 100644 --- a/test/asynchronous/test_load_balancer.py +++ b/test/asynchronous/test_load_balancer.py @@ -189,7 +189,7 @@ async def wait(self, event: Event, timeout: int): else: try: await asyncio.wait_for(event.wait(), timeout=timeout) - except asyncio.TimeoutError: + except TimeoutError: return False return True diff --git a/test/asynchronous/test_locks.py b/test/asynchronous/test_locks.py index 4d207b509b..19166f309f 100644 --- a/test/asynchronous/test_locks.py +++ b/test/asynchronous/test_locks.py @@ -296,7 +296,7 @@ async def test_context_manager(self): async def test_timeout_in_block(self): condition = _async_create_condition(_async_create_lock()) async with condition: - with self.assertRaises(asyncio.TimeoutError): + with self.assertRaises(TimeoutError): await asyncio.wait_for(condition.wait(), timeout=0.5) async def test_cancelled_error_wakeup(self): diff --git a/test/test_kms_connect.py b/test/test_kms_connect.py index f5e79b5048..f0873fcd34 100644 --- a/test/test_kms_connect.py +++ b/test/test_kms_connect.py @@ -839,7 +839,7 @@ def blocker(): task = asyncio.create_task(callback(_kms_context(timeout=1.0))) await asyncio.sleep(0.2) # Let the coroutine queue its connect. assert not task.done(), "connect finished before the deadline" - with pytest.raises(socket.timeout, match="timed out connecting through the proxy"): + with pytest.raises(TimeoutError, match="timed out connecting through the proxy"): await task elapsed = time.monotonic() - start assert elapsed < 2.5, f"the wait outlived the deadline: {elapsed:.1f}s" @@ -928,7 +928,7 @@ async def raced_wait_for(awaitable, timeout=None): with mock.patch.object(HTTPProxyKMSConnect, "_tunnel", spy_tunnel): with mock.patch("asyncio.wait_for", raced_wait_for): callback = api.proxy(f"https://{host}:{port}", _insecure_client_context()) - with pytest.raises(socket.timeout, match="timed out connecting through the proxy"): + with pytest.raises(TimeoutError, match="timed out connecting through the proxy"): await callback(_kms_context()) assert len(tunneled) == 1 @@ -937,12 +937,11 @@ async def raced_wait_for(awaitable, timeout=None): @both_apis async def test_connect_timeout_is_not_reclassified(api): - # A timed-out connect keeps its socket.timeout type. def timeout_connect(self, address): - raise socket.timeout("timed out") + raise TimeoutError("timed out") with mock.patch.object(socket.socket, "connect", timeout_connect): - with pytest.raises(socket.timeout): + with pytest.raises(TimeoutError): HTTPProxyKMSConnect("http://127.0.0.1:9999")._connect_proxy(time.monotonic() + 10) @@ -991,7 +990,7 @@ async def test_remaining_raises_once_the_deadline_passes(api): from pymongo._kms_connect_shared import _remaining assert _remaining(time.monotonic() + 5) > 0 - with pytest.raises(socket.timeout): + with pytest.raises(TimeoutError): _remaining(time.monotonic() - 1) diff --git a/test/test_load_balancer.py b/test/test_load_balancer.py index 66a410a5f1..8bd4056772 100644 --- a/test/test_load_balancer.py +++ b/test/test_load_balancer.py @@ -189,7 +189,7 @@ def wait(self, event: Event, timeout: int): else: try: asyncio.wait_for(event.wait(), timeout=timeout) - except asyncio.TimeoutError: + except TimeoutError: return False return True