|
| 1 | +import asyncio |
| 2 | +from collections import deque |
| 3 | +from concurrent.futures import Future |
| 4 | +import threading |
| 5 | +from typing import Tuple, Optional, Any, Deque |
| 6 | + |
| 7 | + |
| 8 | +class Queuey: |
| 9 | + """Hybrid queue allowing to interface sync and async(io) code. |
| 10 | +
|
| 11 | + It is widely inspired by a talk by David Beazley on the subject: |
| 12 | + https://www.youtube.com/watch?v=x1ndXuw7S0s |
| 13 | +
|
| 14 | + One big difference with a normal queue is that even with a maxsize |
| 15 | + set to a fixed number, this queue can still end up taking an |
| 16 | + infinite amount of memory since pending get/put operation are kept |
| 17 | + as futures. |
| 18 | +
|
| 19 | + It is an alternative to the 3rd-party Janus library which had |
| 20 | + shortcomings when used in Spinach: |
| 21 | + - Janus queues have to be created in an asyncio coroutine, turning |
| 22 | + the creation of the queue in the Workers class into a strange dance. |
| 23 | + - It was not obvious to me how to implement showing the queue as full |
| 24 | + if there are unfinished tasks. |
| 25 | + - It adds a few dependencies only needed by a fractions of users, adds a |
| 26 | + ton of code for something that should be simple. |
| 27 | + """ |
| 28 | + |
| 29 | + def __init__(self, maxsize: int): |
| 30 | + self.maxsize = maxsize |
| 31 | + self._mutex = threading.Lock() |
| 32 | + self._items: Deque[Any] = deque() |
| 33 | + self._getters: Deque[Future] = deque() |
| 34 | + self._putters: Deque[Tuple[Any, Future]] = deque() |
| 35 | + self._unfinished_tasks = 0 |
| 36 | + |
| 37 | + def _get_noblock(self) -> Tuple[Optional[Any], Optional[Future]]: |
| 38 | + with self._mutex: |
| 39 | + if self._items: |
| 40 | + if self._putters: |
| 41 | + # About to remove one item from the queue which means |
| 42 | + # that a new spot will be available. Since there are |
| 43 | + # putters waiting, wake up one and take its item. |
| 44 | + item, put_fut = self._putters.popleft() |
| 45 | + self._items.append(item) |
| 46 | + put_fut.set_result(True) |
| 47 | + return self._items.popleft(), None |
| 48 | + |
| 49 | + else: |
| 50 | + fut = Future() |
| 51 | + self._getters.append(fut) |
| 52 | + return None, fut |
| 53 | + |
| 54 | + def _put_noblock(self, item: Any) -> Optional[Future]: |
| 55 | + with self._mutex: |
| 56 | + if len(self._items) < self.maxsize: |
| 57 | + self._items.append(item) |
| 58 | + self._unfinished_tasks += 1 |
| 59 | + if self._getters: |
| 60 | + self._getters.popleft().set_result(self._items.popleft()) |
| 61 | + else: |
| 62 | + fut = Future() |
| 63 | + self._putters.append((item, fut)) |
| 64 | + return fut |
| 65 | + |
| 66 | + def get_sync(self) -> Any: |
| 67 | + item, fut = self._get_noblock() |
| 68 | + if fut: |
| 69 | + item = fut.result() |
| 70 | + return item |
| 71 | + |
| 72 | + def put_sync(self, item: Any) -> None: |
| 73 | + fut = self._put_noblock(item) |
| 74 | + if fut is None: |
| 75 | + return |
| 76 | + |
| 77 | + fut.result() |
| 78 | + |
| 79 | + async def get_async(self) -> Any: |
| 80 | + item, fut = self._get_noblock() |
| 81 | + if fut: |
| 82 | + item = await asyncio.wait_for(asyncio.wrap_future(fut), None) |
| 83 | + return item |
| 84 | + |
| 85 | + async def put_async(self, item: Any) -> None: |
| 86 | + fut = self._put_noblock(item) |
| 87 | + if fut is None: |
| 88 | + return |
| 89 | + |
| 90 | + await asyncio.wait_for(asyncio.wrap_future(fut), None) |
| 91 | + |
| 92 | + def task_done(self) -> None: |
| 93 | + """Indicate that a formerly enqueued task is complete. |
| 94 | +
|
| 95 | + Raises a ValueError if called more times than there were items |
| 96 | + placed in the queue. |
| 97 | + """ |
| 98 | + with self._mutex: |
| 99 | + unfinished = self._unfinished_tasks - 1 |
| 100 | + if unfinished < 0: |
| 101 | + raise ValueError('task_done() called too many times') |
| 102 | + |
| 103 | + self._unfinished_tasks = unfinished |
| 104 | + |
| 105 | + def empty(self) -> bool: |
| 106 | + with self._mutex: |
| 107 | + return self._unfinished_tasks == 0 |
| 108 | + |
| 109 | + def full(self) -> bool: |
| 110 | + with self._mutex: |
| 111 | + return self.maxsize <= self._unfinished_tasks |
| 112 | + |
| 113 | + def available_slots(self) -> int: |
| 114 | + with self._mutex: |
| 115 | + return self.maxsize - self._unfinished_tasks |
0 commit comments