Skip to content

PYTHON-3290 Nested pymongo.timeout() calls only shorten the deadline #966

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

Merged
merged 1 commit into from
Jun 7, 2022
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
7 changes: 4 additions & 3 deletions pymongo/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,16 +127,17 @@ def timeout(seconds: Optional[float]) -> ContextManager:
NetworkTimeout) as exc:
print(f"block timed out: {exc!r}")

When nesting :func:`~pymongo.timeout`, the nested block overrides the
timeout. When exiting the block, the previous deadline is restored::
When nesting :func:`~pymongo.timeout`, the newly computed deadline is capped to at most
the existing deadline. The deadline can only be shortened, not extended.
When exiting the block, the previous deadline is restored::

with pymongo.timeout(5):
coll.find_one() # Uses the 5 second deadline.
with pymongo.timeout(3):
coll.find_one() # Uses the 3 second deadline.
coll.find_one() # Uses the original 5 second deadline.
with pymongo.timeout(10):
coll.find_one() # Uses the 10 second deadline.
coll.find_one() # Still uses the original 5 second deadline.
coll.find_one() # Uses the original 5 second deadline.

:Parameters:
Expand Down
6 changes: 3 additions & 3 deletions pymongo/_csot.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,9 @@ def __init__(self, timeout: Optional[float]):

def __enter__(self):
timeout_token = TIMEOUT.set(self._timeout)
deadline_token = DEADLINE.set(
time.monotonic() + self._timeout if self._timeout else float("inf")
)
prev_deadline = DEADLINE.get()
next_deadline = time.monotonic() + self._timeout if self._timeout else float("inf")
deadline_token = DEADLINE.set(min(prev_deadline, next_deadline))
rtt_token = RTT.set(0.0)
self._tokens = (timeout_token, deadline_token, rtt_token)
return self
Expand Down
3 changes: 2 additions & 1 deletion test/test_csot.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,11 @@ def test_timeout_nested(self):
self.assertEqual(_csot.get_timeout(), 10)
deadline_10 = _csot.get_deadline()

# Capped at the original 10 deadline.
with pymongo.timeout(15):
coll.find_one()
self.assertEqual(_csot.get_timeout(), 15)
self.assertGreater(_csot.get_deadline(), deadline_10)
self.assertEqual(_csot.get_deadline(), deadline_10)

# Should be reset to previous values
self.assertEqual(_csot.get_timeout(), 10)
Expand Down