|
| 1 | +# Backports from Python/Lib/asyncio for older Pythons |
| 2 | +# |
| 3 | +# Copyright (c) 2001-2023 Python Software Foundation; All Rights Reserved |
| 4 | +# |
| 5 | +# SPDX-License-Identifier: PSF-2.0 |
| 6 | + |
| 7 | + |
| 8 | +import asyncio |
| 9 | +import functools |
| 10 | +import sys |
| 11 | + |
| 12 | +if sys.version_info < (3, 11): |
| 13 | + from async_timeout import timeout as timeout_ctx |
| 14 | +else: |
| 15 | + from asyncio import timeout as timeout_ctx |
| 16 | + |
| 17 | + |
| 18 | +async def wait_for(fut, timeout): |
| 19 | + """Wait for the single Future or coroutine to complete, with timeout. |
| 20 | +
|
| 21 | + Coroutine will be wrapped in Task. |
| 22 | +
|
| 23 | + Returns result of the Future or coroutine. When a timeout occurs, |
| 24 | + it cancels the task and raises TimeoutError. To avoid the task |
| 25 | + cancellation, wrap it in shield(). |
| 26 | +
|
| 27 | + If the wait is cancelled, the task is also cancelled. |
| 28 | +
|
| 29 | + If the task supresses the cancellation and returns a value instead, |
| 30 | + that value is returned. |
| 31 | +
|
| 32 | + This function is a coroutine. |
| 33 | + """ |
| 34 | + # The special case for timeout <= 0 is for the following case: |
| 35 | + # |
| 36 | + # async def test_waitfor(): |
| 37 | + # func_started = False |
| 38 | + # |
| 39 | + # async def func(): |
| 40 | + # nonlocal func_started |
| 41 | + # func_started = True |
| 42 | + # |
| 43 | + # try: |
| 44 | + # await asyncio.wait_for(func(), 0) |
| 45 | + # except asyncio.TimeoutError: |
| 46 | + # assert not func_started |
| 47 | + # else: |
| 48 | + # assert False |
| 49 | + # |
| 50 | + # asyncio.run(test_waitfor()) |
| 51 | + |
| 52 | + if timeout is not None and timeout <= 0: |
| 53 | + fut = asyncio.ensure_future(fut) |
| 54 | + |
| 55 | + if fut.done(): |
| 56 | + return fut.result() |
| 57 | + |
| 58 | + await _cancel_and_wait(fut) |
| 59 | + try: |
| 60 | + return fut.result() |
| 61 | + except asyncio.CancelledError as exc: |
| 62 | + raise TimeoutError from exc |
| 63 | + |
| 64 | + async with timeout_ctx(timeout): |
| 65 | + return await fut |
| 66 | + |
| 67 | + |
| 68 | +async def _cancel_and_wait(fut): |
| 69 | + """Cancel the *fut* future or task and wait until it completes.""" |
| 70 | + |
| 71 | + loop = asyncio.get_running_loop() |
| 72 | + waiter = loop.create_future() |
| 73 | + cb = functools.partial(_release_waiter, waiter) |
| 74 | + fut.add_done_callback(cb) |
| 75 | + |
| 76 | + try: |
| 77 | + fut.cancel() |
| 78 | + # We cannot wait on *fut* directly to make |
| 79 | + # sure _cancel_and_wait itself is reliably cancellable. |
| 80 | + await waiter |
| 81 | + finally: |
| 82 | + fut.remove_done_callback(cb) |
| 83 | + |
| 84 | + |
| 85 | +def _release_waiter(waiter, *args): |
| 86 | + if not waiter.done(): |
| 87 | + waiter.set_result(None) |
0 commit comments