|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import asyncio |
| 4 | +import sys |
| 5 | + |
| 6 | +if sys.version_info >= (3, 13): |
| 7 | + QueueShutDown = asyncio.QueueShutDown # type: ignore[assignment] |
| 8 | + |
| 9 | + class Queue[T](asyncio.Queue[T]): |
| 10 | + """Asyncio Queue with shutdown support.""" |
| 11 | + |
| 12 | +else: |
| 13 | + |
| 14 | + class QueueShutDown(Exception): |
| 15 | + """Raised when operating on a shut down queue.""" |
| 16 | + |
| 17 | + class _Shutdown: |
| 18 | + """Sentinel for queue shutdown.""" |
| 19 | + |
| 20 | + _SHUTDOWN = _Shutdown() |
| 21 | + |
| 22 | + class Queue[T](asyncio.Queue[T | _Shutdown]): |
| 23 | + """Asyncio Queue with shutdown support for Python < 3.13.""" |
| 24 | + |
| 25 | + def __init__(self) -> None: |
| 26 | + super().__init__() |
| 27 | + self._shutdown = False |
| 28 | + |
| 29 | + def shutdown(self, immediate: bool = False) -> None: |
| 30 | + if self._shutdown: |
| 31 | + return |
| 32 | + self._shutdown = True |
| 33 | + if immediate: |
| 34 | + self._queue.clear() |
| 35 | + |
| 36 | + getters = list(getattr(self, "_getters", [])) |
| 37 | + count = max(1, len(getters)) |
| 38 | + self._enqueue_shutdown(count) |
| 39 | + |
| 40 | + def _enqueue_shutdown(self, count: int) -> None: |
| 41 | + for _ in range(count): |
| 42 | + try: |
| 43 | + super().put_nowait(_SHUTDOWN) |
| 44 | + except asyncio.QueueFull: |
| 45 | + self._queue.clear() |
| 46 | + super().put_nowait(_SHUTDOWN) |
| 47 | + |
| 48 | + async def get(self) -> T: |
| 49 | + if self._shutdown and self.empty(): |
| 50 | + raise QueueShutDown |
| 51 | + item = await super().get() |
| 52 | + if isinstance(item, _Shutdown): |
| 53 | + raise QueueShutDown |
| 54 | + return item |
| 55 | + |
| 56 | + def get_nowait(self) -> T: |
| 57 | + if self._shutdown and self.empty(): |
| 58 | + raise QueueShutDown |
| 59 | + item = super().get_nowait() |
| 60 | + if isinstance(item, _Shutdown): |
| 61 | + raise QueueShutDown |
| 62 | + return item |
| 63 | + |
| 64 | + async def put(self, item: T) -> None: |
| 65 | + if self._shutdown: |
| 66 | + raise QueueShutDown |
| 67 | + await super().put(item) |
| 68 | + |
| 69 | + def put_nowait(self, item: T) -> None: |
| 70 | + if self._shutdown: |
| 71 | + raise QueueShutDown |
| 72 | + super().put_nowait(item) |
0 commit comments