Run ``coro`` but abort it (and raise) when ``cancel_event`` fires.
(coro: Any, cancel_event: asyncio.Event)
| 647 | |
| 648 | |
| 649 | async def _run_cancellable(coro: Any, cancel_event: asyncio.Event) -> None: |
| 650 | """Run ``coro`` but abort it (and raise) when ``cancel_event`` fires.""" |
| 651 | task = asyncio.ensure_future(coro) |
| 652 | waiter = asyncio.ensure_future(cancel_event.wait()) |
| 653 | try: |
| 654 | done, _ = await asyncio.wait({task, waiter}, return_when=asyncio.FIRST_COMPLETED) |
| 655 | if task in done: |
| 656 | exc = task.exception() |
| 657 | if exc is not None: |
| 658 | raise exc |
| 659 | return |
| 660 | # Cancellation fired first. |
| 661 | task.cancel() |
| 662 | try: |
| 663 | await task |
| 664 | except (asyncio.CancelledError, Exception): |
| 665 | # The awaited task was cancelled; its unwind exception is expected |
| 666 | # and irrelevant — we raise the cancellation result below. |
| 667 | pass |
| 668 | raise RuntimeError("Request cancelled by runtime") |
| 669 | finally: |
| 670 | if not waiter.done(): |
| 671 | waiter.cancel() |
| 672 | |
| 673 | |
| 674 | async def _build_httpx_request(exchange: _CopilotRequestExchange) -> httpx.Request: |
no test coverage detected
searching dependent graphs…