queue.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. # util/queue.py
  2. # Copyright (C) 2005-2024 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: https://www.opensource.org/licenses/mit-license.php
  7. # mypy: allow-untyped-defs, allow-untyped-calls
  8. """An adaptation of Py2.3/2.4's Queue module which supports reentrant
  9. behavior, using RLock instead of Lock for its mutex object. The
  10. Queue object is used exclusively by the sqlalchemy.pool.QueuePool
  11. class.
  12. This is to support the connection pool's usage of weakref callbacks to return
  13. connections to the underlying Queue, which can in extremely
  14. rare cases be invoked within the ``get()`` method of the Queue itself,
  15. producing a ``put()`` inside the ``get()`` and therefore a reentrant
  16. condition.
  17. """
  18. from __future__ import annotations
  19. import asyncio
  20. from collections import deque
  21. import threading
  22. from time import time as _time
  23. import typing
  24. from typing import Any
  25. from typing import Awaitable
  26. from typing import Deque
  27. from typing import Generic
  28. from typing import Optional
  29. from typing import TypeVar
  30. from .concurrency import await_fallback
  31. from .concurrency import await_only
  32. from .langhelpers import memoized_property
  33. _T = TypeVar("_T", bound=Any)
  34. __all__ = ["Empty", "Full", "Queue"]
  35. class Empty(Exception):
  36. "Exception raised by Queue.get(block=0)/get_nowait()."
  37. pass
  38. class Full(Exception):
  39. "Exception raised by Queue.put(block=0)/put_nowait()."
  40. pass
  41. class QueueCommon(Generic[_T]):
  42. maxsize: int
  43. use_lifo: bool
  44. def __init__(self, maxsize: int = 0, use_lifo: bool = False):
  45. ...
  46. def empty(self) -> bool:
  47. raise NotImplementedError()
  48. def full(self) -> bool:
  49. raise NotImplementedError()
  50. def qsize(self) -> int:
  51. raise NotImplementedError()
  52. def put_nowait(self, item: _T) -> None:
  53. raise NotImplementedError()
  54. def put(
  55. self, item: _T, block: bool = True, timeout: Optional[float] = None
  56. ) -> None:
  57. raise NotImplementedError()
  58. def get_nowait(self) -> _T:
  59. raise NotImplementedError()
  60. def get(self, block: bool = True, timeout: Optional[float] = None) -> _T:
  61. raise NotImplementedError()
  62. class Queue(QueueCommon[_T]):
  63. queue: Deque[_T]
  64. def __init__(self, maxsize: int = 0, use_lifo: bool = False):
  65. """Initialize a queue object with a given maximum size.
  66. If `maxsize` is <= 0, the queue size is infinite.
  67. If `use_lifo` is True, this Queue acts like a Stack (LIFO).
  68. """
  69. self._init(maxsize)
  70. # mutex must be held whenever the queue is mutating. All methods
  71. # that acquire mutex must release it before returning. mutex
  72. # is shared between the two conditions, so acquiring and
  73. # releasing the conditions also acquires and releases mutex.
  74. self.mutex = threading.RLock()
  75. # Notify not_empty whenever an item is added to the queue; a
  76. # thread waiting to get is notified then.
  77. self.not_empty = threading.Condition(self.mutex)
  78. # Notify not_full whenever an item is removed from the queue;
  79. # a thread waiting to put is notified then.
  80. self.not_full = threading.Condition(self.mutex)
  81. # If this queue uses LIFO or FIFO
  82. self.use_lifo = use_lifo
  83. def qsize(self) -> int:
  84. """Return the approximate size of the queue (not reliable!)."""
  85. with self.mutex:
  86. return self._qsize()
  87. def empty(self) -> bool:
  88. """Return True if the queue is empty, False otherwise (not
  89. reliable!)."""
  90. with self.mutex:
  91. return self._empty()
  92. def full(self) -> bool:
  93. """Return True if the queue is full, False otherwise (not
  94. reliable!)."""
  95. with self.mutex:
  96. return self._full()
  97. def put(
  98. self, item: _T, block: bool = True, timeout: Optional[float] = None
  99. ) -> None:
  100. """Put an item into the queue.
  101. If optional args `block` is True and `timeout` is None (the
  102. default), block if necessary until a free slot is
  103. available. If `timeout` is a positive number, it blocks at
  104. most `timeout` seconds and raises the ``Full`` exception if no
  105. free slot was available within that time. Otherwise (`block`
  106. is false), put an item on the queue if a free slot is
  107. immediately available, else raise the ``Full`` exception
  108. (`timeout` is ignored in that case).
  109. """
  110. with self.not_full:
  111. if not block:
  112. if self._full():
  113. raise Full
  114. elif timeout is None:
  115. while self._full():
  116. self.not_full.wait()
  117. else:
  118. if timeout < 0:
  119. raise ValueError("'timeout' must be a positive number")
  120. endtime = _time() + timeout
  121. while self._full():
  122. remaining = endtime - _time()
  123. if remaining <= 0.0:
  124. raise Full
  125. self.not_full.wait(remaining)
  126. self._put(item)
  127. self.not_empty.notify()
  128. def put_nowait(self, item: _T) -> None:
  129. """Put an item into the queue without blocking.
  130. Only enqueue the item if a free slot is immediately available.
  131. Otherwise raise the ``Full`` exception.
  132. """
  133. return self.put(item, False)
  134. def get(self, block: bool = True, timeout: Optional[float] = None) -> _T:
  135. """Remove and return an item from the queue.
  136. If optional args `block` is True and `timeout` is None (the
  137. default), block if necessary until an item is available. If
  138. `timeout` is a positive number, it blocks at most `timeout`
  139. seconds and raises the ``Empty`` exception if no item was
  140. available within that time. Otherwise (`block` is false),
  141. return an item if one is immediately available, else raise the
  142. ``Empty`` exception (`timeout` is ignored in that case).
  143. """
  144. with self.not_empty:
  145. if not block:
  146. if self._empty():
  147. raise Empty
  148. elif timeout is None:
  149. while self._empty():
  150. self.not_empty.wait()
  151. else:
  152. if timeout < 0:
  153. raise ValueError("'timeout' must be a positive number")
  154. endtime = _time() + timeout
  155. while self._empty():
  156. remaining = endtime - _time()
  157. if remaining <= 0.0:
  158. raise Empty
  159. self.not_empty.wait(remaining)
  160. item = self._get()
  161. self.not_full.notify()
  162. return item
  163. def get_nowait(self) -> _T:
  164. """Remove and return an item from the queue without blocking.
  165. Only get an item if one is immediately available. Otherwise
  166. raise the ``Empty`` exception.
  167. """
  168. return self.get(False)
  169. def _init(self, maxsize: int) -> None:
  170. self.maxsize = maxsize
  171. self.queue = deque()
  172. def _qsize(self) -> int:
  173. return len(self.queue)
  174. def _empty(self) -> bool:
  175. return not self.queue
  176. def _full(self) -> bool:
  177. return self.maxsize > 0 and len(self.queue) == self.maxsize
  178. def _put(self, item: _T) -> None:
  179. self.queue.append(item)
  180. def _get(self) -> _T:
  181. if self.use_lifo:
  182. # LIFO
  183. return self.queue.pop()
  184. else:
  185. # FIFO
  186. return self.queue.popleft()
  187. class AsyncAdaptedQueue(QueueCommon[_T]):
  188. if typing.TYPE_CHECKING:
  189. @staticmethod
  190. def await_(coroutine: Awaitable[Any]) -> _T:
  191. ...
  192. else:
  193. await_ = staticmethod(await_only)
  194. def __init__(self, maxsize: int = 0, use_lifo: bool = False):
  195. self.use_lifo = use_lifo
  196. self.maxsize = maxsize
  197. def empty(self) -> bool:
  198. return self._queue.empty()
  199. def full(self):
  200. return self._queue.full()
  201. def qsize(self):
  202. return self._queue.qsize()
  203. @memoized_property
  204. def _queue(self) -> asyncio.Queue[_T]:
  205. # Delay creation of the queue until it is first used, to avoid
  206. # binding it to a possibly wrong event loop.
  207. # By delaying the creation of the pool we accommodate the common
  208. # usage pattern of instantiating the engine at module level, where a
  209. # different event loop is in present compared to when the application
  210. # is actually run.
  211. queue: asyncio.Queue[_T]
  212. if self.use_lifo:
  213. queue = asyncio.LifoQueue(maxsize=self.maxsize)
  214. else:
  215. queue = asyncio.Queue(maxsize=self.maxsize)
  216. return queue
  217. def put_nowait(self, item: _T) -> None:
  218. try:
  219. self._queue.put_nowait(item)
  220. except asyncio.QueueFull as err:
  221. raise Full() from err
  222. def put(
  223. self, item: _T, block: bool = True, timeout: Optional[float] = None
  224. ) -> None:
  225. if not block:
  226. return self.put_nowait(item)
  227. try:
  228. if timeout is not None:
  229. self.await_(asyncio.wait_for(self._queue.put(item), timeout))
  230. else:
  231. self.await_(self._queue.put(item))
  232. except (asyncio.QueueFull, asyncio.TimeoutError) as err:
  233. raise Full() from err
  234. def get_nowait(self) -> _T:
  235. try:
  236. return self._queue.get_nowait()
  237. except asyncio.QueueEmpty as err:
  238. raise Empty() from err
  239. def get(self, block: bool = True, timeout: Optional[float] = None) -> _T:
  240. if not block:
  241. return self.get_nowait()
  242. try:
  243. if timeout is not None:
  244. return self.await_(
  245. asyncio.wait_for(self._queue.get(), timeout)
  246. )
  247. else:
  248. return self.await_(self._queue.get())
  249. except (asyncio.QueueEmpty, asyncio.TimeoutError) as err:
  250. raise Empty() from err
  251. class FallbackAsyncAdaptedQueue(AsyncAdaptedQueue[_T]):
  252. if not typing.TYPE_CHECKING:
  253. await_ = staticmethod(await_fallback)