Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions pymongo/_kms_connect_shared.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions pymongo/asynchronous/_kms_connect.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
3 changes: 1 addition & 2 deletions pymongo/asynchronous/encryption.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@

import asyncio
import functools
import socket
import time as time # noqa: PLC0414 # needed in sync version
import uuid
import weakref
Expand Down Expand Up @@ -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"
Expand Down
2 changes: 1 addition & 1 deletion pymongo/lock.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down
27 changes: 14 additions & 13 deletions pymongo/network_layer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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":
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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 (
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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:
Expand Down
10 changes: 5 additions & 5 deletions pymongo/pool_shared.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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()
Expand Down Expand Up @@ -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)
Expand Down
4 changes: 2 additions & 2 deletions pymongo/pyopenssl_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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:
Expand Down
4 changes: 2 additions & 2 deletions pymongo/synchronous/_kms_connect.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
3 changes: 1 addition & 2 deletions pymongo/synchronous/encryption.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"
Expand Down
1 change: 0 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion test/asynchronous/test_async_network_layer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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())

Expand Down
2 changes: 1 addition & 1 deletion test/asynchronous/test_load_balancer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion test/asynchronous/test_locks.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
11 changes: 5 additions & 6 deletions test/test_kms_connect.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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
Expand All @@ -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)


Expand Down Expand Up @@ -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)


Expand Down
2 changes: 1 addition & 1 deletion test/test_load_balancer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Loading