Debian Codegraph @

src/async_interrupt/__init__.py

raw
1 """Interrupt context manager for asyncio.
2
3 This module provides a context manager that can be used to interrupt
4 a block of code as soon as possible when a future is done.
5
6 The purpose is to raise as soon as possible to avoid any race conditions.
7
8 This is based loosely on async_timeout by Andrew Svetlov and cpython asyncio.timeout
9 """
10
11 from __future__ import annotations
12
13 import asyncio
14 from types import TracebackType
15 from typing import TYPE_CHECKING, Any, final
16
17 __version__ = "1.2.2"
18
19 __all__ = ("interrupt",)
20
21
22 @final
23 class _Interrupt:
24 """Interrupt context manager.
25
26 Internal class, please don't instantiate it directly
27 Use interrupt() public factory instead.
28
29 exception is raised immediately when future is finished.
30
31 The purpose is to raise as soon as possible to avoid any race conditions.
32 """
33
34 __slots__ = (
35 "_exception",
36 "_future",
37 "_message",
38 "_interrupted",
39 "_task",
40 "_cancelling",
41 "_exited",
42 )
43
44 def __init__(
45 self,
46 future: asyncio.Future[Any],
47 exception: type[Exception],
48 message: str | None,
49 ) -> None:
50 """Initialize the interrupt context manager."""
51 self._future = future
52 self._interrupted = False
53 self._exception = exception
54 self._message = message
55 self._task: asyncio.Task[Any] | None
56 self._cancelling: int = 0
57 self._exited = False
58
59 async def __aenter__(self) -> _Interrupt:
60 """Enter the interrupt context manager."""
61 if self._exited:
62 raise RuntimeError("Already exited")
63 task = asyncio.current_task()
64 self._task = task
65 if cancelling := getattr(task, "cancelling", None):
66 self._cancelling = cancelling()
67 self._future.add_done_callback(self._on_interrupt)
68 return self
69
70 async def __aexit__(
71 self,
72 exc_type: type[BaseException] | None,
73 exc_val: BaseException | None,
74 exc_tb: TracebackType | None,
75 ) -> bool | None:
76 """Exit the interrupt context manager."""
77 self._exited = True
78 if self._interrupted:
79 if TYPE_CHECKING:
80 assert self._task is not None # nosec
81 if exc_type is asyncio.CancelledError and (
82 not (uncancel := getattr(self._task, "uncancel", None))
83 or uncancel() <= self._cancelling
84 ):
85 # Only py3.11 has uncancel, but this is OK since
86 # if there really is multiple cancel requests
87 # it will raise on the next loop anyways
88 if self._message:
89 raise self._exception(self._message) from exc_val
90 raise self._exception from exc_val
91 self._future.remove_done_callback(self._on_interrupt)
92 return None
93
94 def _on_interrupt(self, _: asyncio.Future[Any]) -> None:
95 """Handle interrupt."""
96 if self._exited:
97 # Must not cancel the task here if we already
98 # exited the context manager or the cancellation
99 # would raise upwards
100 return
101 if TYPE_CHECKING:
102 assert self._task is not None # nosec
103 self._interrupted = True
104 self._task.cancel("Interrupted by interrupt context manager")
105 self._future.remove_done_callback(self._on_interrupt)
106
107
108 if TYPE_CHECKING:
109
110 def interrupt(
111 future: asyncio.Future[Any],
112 exception: type[Exception],
113 message: str | None,
114 ) -> _Interrupt:
115 """Interrupt context manager.
116
117 Useful in cases when you want to apply interrupt logic around block
118 of code that uses await expression where an exception needs to be
119 raised as soon as possible to avoid race conditions.
120
121 >>> async with interrupt(
122 future,
123 APIUnavailableError,
124 'API is became unavailable'
125 ):
126 ... await api.call()
127
128
129 future - the future that will cause the block to be interrupted
130 exception - the exception to raise when the future is done
131 message - the message to pass when constructing the exception
132 """
133 return _Interrupt(future, exception, message)
134
135 else:
136 interrupt = _Interrupt