| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import math |
| 4 |
import sys |
| 5 |
from contextlib import contextmanager |
| 6 |
from typing import TYPE_CHECKING, NoReturn |
| 7 |
|
| 8 |
import trio |
| 9 |
|
| 10 |
if TYPE_CHECKING: |
| 11 |
from collections.abc import Generator |
| 12 |
|
| 13 |
|
| 14 |
def move_on_at(deadline: float, *, shield: bool = False) -> trio.CancelScope: |
| 15 |
"""Use as a context manager to create a cancel scope with the given |
| 16 |
absolute deadline. |
| 17 |
|
| 18 |
Args: |
| 19 |
deadline (float): The deadline. |
| 20 |
shield (bool): Initial value for the `~trio.CancelScope.shield` attribute |
| 21 |
of the newly created cancel scope. |
| 22 |
|
| 23 |
Raises: |
| 24 |
ValueError: if deadline is NaN. |
| 25 |
|
| 26 |
""" |
| 27 |
# CancelScope validates that deadline isn't math.nan |
| 28 |
return trio.CancelScope(deadline=deadline, shield=shield) |
| 29 |
|
| 30 |
|
| 31 |
def move_on_after( |
| 32 |
seconds: float, |
| 33 |
*, |
| 34 |
shield: bool = False, |
| 35 |
) -> trio.CancelScope: |
| 36 |
"""Use as a context manager to create a cancel scope whose deadline is |
| 37 |
set to now + *seconds*. |
| 38 |
|
| 39 |
The deadline of the cancel scope is calculated upon entering. |
| 40 |
|
| 41 |
Args: |
| 42 |
seconds (float): The timeout. |
| 43 |
shield (bool): Initial value for the `~trio.CancelScope.shield` attribute |
| 44 |
of the newly created cancel scope. |
| 45 |
|
| 46 |
Raises: |
| 47 |
ValueError: if ``seconds`` is less than zero or NaN. |
| 48 |
|
| 49 |
""" |
| 50 |
# duplicate validation logic to have the correct parameter name |
| 51 |
if seconds < 0: |
| 52 |
raise ValueError("`seconds` must be non-negative") |
| 53 |
if math.isnan(seconds): |
| 54 |
raise ValueError("`seconds` must not be NaN") |
| 55 |
return trio.CancelScope( |
| 56 |
shield=shield, |
| 57 |
relative_deadline=seconds, |
| 58 |
) |
| 59 |
|
| 60 |
|
| 61 |
async def sleep_forever() -> NoReturn: |
| 62 |
"""Pause execution of the current task forever (or until cancelled). |
| 63 |
|
| 64 |
Equivalent to calling ``await sleep(math.inf)``, except that if manually |
| 65 |
rescheduled this will raise a `RuntimeError`. |
| 66 |
|
| 67 |
Raises: |
| 68 |
RuntimeError: if rescheduled |
| 69 |
|
| 70 |
""" |
| 71 |
await trio.lowlevel.wait_task_rescheduled(lambda _: trio.lowlevel.Abort.SUCCEEDED) |
| 72 |
raise RuntimeError("Should never have been rescheduled!") |
| 73 |
|
| 74 |
|
| 75 |
async def sleep_until(deadline: float) -> None: |
| 76 |
"""Pause execution of the current task until the given time. |
| 77 |
|
| 78 |
The difference between :func:`sleep` and :func:`sleep_until` is that the |
| 79 |
former takes a relative time and the latter takes an absolute time |
| 80 |
according to Trio's internal clock (as returned by :func:`current_time`). |
| 81 |
|
| 82 |
Args: |
| 83 |
deadline (float): The time at which we should wake up again. May be in |
| 84 |
the past, in which case this function executes a checkpoint but |
| 85 |
does not block. |
| 86 |
|
| 87 |
Raises: |
| 88 |
ValueError: if deadline is NaN. |
| 89 |
|
| 90 |
""" |
| 91 |
with move_on_at(deadline): |
| 92 |
await sleep_forever() |
| 93 |
|
| 94 |
|
| 95 |
async def sleep(seconds: float) -> None: |
| 96 |
"""Pause execution of the current task for the given number of seconds. |
| 97 |
|
| 98 |
Args: |
| 99 |
seconds (float): The number of seconds to sleep. May be zero to |
| 100 |
insert a checkpoint without actually blocking. |
| 101 |
|
| 102 |
Raises: |
| 103 |
ValueError: if *seconds* is negative or NaN. |
| 104 |
|
| 105 |
""" |
| 106 |
if seconds < 0: |
| 107 |
raise ValueError("`seconds` must be non-negative") |
| 108 |
if seconds == 0: |
| 109 |
await trio.lowlevel.checkpoint() |
| 110 |
else: |
| 111 |
await sleep_until(trio.current_time() + seconds) |
| 112 |
|
| 113 |
|
| 114 |
class TooSlowError(Exception): |
| 115 |
"""Raised by :func:`fail_after` and :func:`fail_at` if the timeout |
| 116 |
expires. |
| 117 |
|
| 118 |
""" |
| 119 |
|
| 120 |
|
| 121 |
@contextmanager |
| 122 |
def fail_at( |
| 123 |
deadline: float, |
| 124 |
*, |
| 125 |
shield: bool = False, |
| 126 |
) -> Generator[trio.CancelScope, None, None]: |
| 127 |
"""Creates a cancel scope with the given deadline, and raises an error if it |
| 128 |
is actually cancelled. |
| 129 |
|
| 130 |
This function and :func:`move_on_at` are similar in that both create a |
| 131 |
cancel scope with a given absolute deadline, and if the deadline expires |
| 132 |
then both will cause :exc:`Cancelled` to be raised within the scope. The |
| 133 |
difference is that when the :exc:`Cancelled` exception reaches |
| 134 |
:func:`move_on_at`, it's caught and discarded. When it reaches |
| 135 |
:func:`fail_at`, then it's caught and :exc:`TooSlowError` is raised in its |
| 136 |
place. |
| 137 |
|
| 138 |
Args: |
| 139 |
deadline (float): The deadline. |
| 140 |
shield (bool): Initial value for the `~trio.CancelScope.shield` attribute |
| 141 |
of the newly created cancel scope. |
| 142 |
|
| 143 |
Raises: |
| 144 |
TooSlowError: if a :exc:`Cancelled` exception is raised in this scope |
| 145 |
and caught by the context manager. |
| 146 |
ValueError: if deadline is NaN. |
| 147 |
|
| 148 |
""" |
| 149 |
with move_on_at(deadline, shield=shield) as scope: |
| 150 |
yield scope |
| 151 |
if scope.cancelled_caught: |
| 152 |
raise TooSlowError |
| 153 |
|
| 154 |
|
| 155 |
@contextmanager |
| 156 |
def fail_after( |
| 157 |
seconds: float, |
| 158 |
*, |
| 159 |
shield: bool = False, |
| 160 |
) -> Generator[trio.CancelScope, None, None]: |
| 161 |
"""Creates a cancel scope with the given timeout, and raises an error if |
| 162 |
it is actually cancelled. |
| 163 |
|
| 164 |
This function and :func:`move_on_after` are similar in that both create a |
| 165 |
cancel scope with a given timeout, and if the timeout expires then both |
| 166 |
will cause :exc:`Cancelled` to be raised within the scope. The difference |
| 167 |
is that when the :exc:`Cancelled` exception reaches :func:`move_on_after`, |
| 168 |
it's caught and discarded. When it reaches :func:`fail_after`, then it's |
| 169 |
caught and :exc:`TooSlowError` is raised in its place. |
| 170 |
|
| 171 |
The deadline of the cancel scope is calculated upon entering. |
| 172 |
|
| 173 |
Args: |
| 174 |
seconds (float): The timeout. |
| 175 |
shield (bool): Initial value for the `~trio.CancelScope.shield` attribute |
| 176 |
of the newly created cancel scope. |
| 177 |
|
| 178 |
Raises: |
| 179 |
TooSlowError: if a :exc:`Cancelled` exception is raised in this scope |
| 180 |
and caught by the context manager. |
| 181 |
ValueError: if *seconds* is less than zero or NaN. |
| 182 |
|
| 183 |
""" |
| 184 |
with move_on_after(seconds, shield=shield) as scope: |
| 185 |
yield scope |
| 186 |
if scope.cancelled_caught: |
| 187 |
raise TooSlowError |
| 188 |
|
| 189 |
|
| 190 |
# Users don't need to know that fail_at & fail_after wraps move_on_at and move_on_after |
| 191 |
# and there is no functional difference. So we replace the return value when generating |
| 192 |
# documentation. |
| 193 |
if "sphinx.ext.autodoc" in sys.modules: |
| 194 |
import inspect |
| 195 |
|
| 196 |
for c in (fail_at, fail_after): |
| 197 |
c.__signature__ = inspect.Signature.from_callable(c).replace(return_annotation=trio.CancelScope) # type: ignore[union-attr] |