queue.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. # util/queue.py
  2. # Copyright (C) 2005-2025 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. def empty(self) -> bool:
  46. raise NotImplementedError()
  47. def full(self) -> bool:
  48. raise NotImplementedError()
  49. def qsize(self) -> int:
  50. raise NotImplementedError()
  51. def put_nowait(self, item: _T) -> None:
  52. raise NotImplementedError()
  53. def put(
  54. self, item: _T, block: bool = True, timeout: Optional[float] = None
  55. ) -> None:
  56. raise NotImplementedError()
  57. def get_nowait(self) -> _T:
  58. raise NotImplementedError()
  59. def get(self, block: bool = True, timeout: Optional[float] = None) -> _T:
  60. raise NotImplementedError()
  61. class Queue(QueueCommon[_T]):
  62. queue: Deque[_T]
  63. def __init__(self, maxsize: int = 0, use_lifo: bool = False):
  64. """Initialize a queue object with a given maximum size.
  65. If `maxsize` is <= 0, the queue size is infinite.
  66. If `use_lifo` is True, this Queue acts like a Stack (LIFO).
  67. """
  68. self._init(maxsize)
  69. # mutex must be held whenever the queue is mutating. All methods
  70. # that acquire mutex must release it before returning. mutex
  71. # is shared between the two conditions, so acquiring and
  72. # releasing the conditions also acquires and releases mutex.
  73. self.mutex = threading.RLock()
  74. # Notify not_empty whenever an item is added to the queue; a
  75. # thread waiting to get is notified then.
  76. self.not_empty = threading.Condition(self.mutex)
  77. # Notify not_full whenever an item is removed from the queue;
  78. # a thread waiting to put is notified then.
  79. self.not_full = threading.Condition(self.mutex)
  80. # If this queue uses LIFO or FIFO
  81. self.use_lifo = use_lifo
  82. def qsize(self) -> int:
  83. """Return the approximate size of the queue (not reliable!)."""
  84. with self.mutex:
  85. return self._qsize()
  86. def empty(self) -> bool:
  87. """Return True if the queue is empty, False otherwise (not
  88. reliable!)."""
  89. with self.mutex:
  90. return self._empty()
  91. def full(self) -> bool:
  92. """Return True if the queue is full, False otherwise (not
  93. reliable!)."""
  94. with self.mutex:
  95. return self._full()
  96. def put(
  97. self, item: _T, block: bool = True, timeout: Optional[float] = None
  98. ) -> None:
  99. """Put an item into the queue.
  100. If optional args `block` is True and `timeout` is None (the
  101. default), block if necessary until a free slot is
  102. available. If `timeout` is a positive number, it blocks at
  103. most `timeout` seconds and raises the ``Full`` exception if no
  104. free slot was available within that time. Otherwise (`block`
  105. is false), put an item on the queue if a free slot is
  106. immediately available, else raise the ``Full`` exception
  107. (`timeout` is ignored in that case).
  108. """
  109. with self.not_full:
  110. if not block:
  111. if self._full():
  112. raise Full
  113. elif timeout is None:
  114. while self._full():
  115. self.not_full.wait()
  116. else:
  117. if timeout < 0:
  118. raise ValueError("'timeout' must be a positive number")
  119. endtime = _time() + timeout
  120. while self._full():
  121. remaining = endtime - _time()
  122. if remaining <= 0.0:
  123. raise Full
  124. self.not_full.wait(remaining)
  125. self._put(item)
  126. self.not_empty.notify()
  127. def put_nowait(self, item: _T) -> None:
  128. """Put an item into the queue without blocking.
  129. Only enqueue the item if a free slot is immediately available.
  130. Otherwise raise the ``Full`` exception.
  131. """
  132. return self.put(item, False)
  133. def get(self, block: bool = True, timeout: Optional[float] = None) -> _T:
  134. """Remove and return an item from the queue.
  135. If optional args `block` is True and `timeout` is None (the
  136. default), block if necessary until an item is available. If
  137. `timeout` is a positive number, it blocks at most `timeout`
  138. seconds and raises the ``Empty`` exception if no item was
  139. available within that time. Otherwise (`block` is false),
  140. return an item if one is immediately available, else raise the
  141. ``Empty`` exception (`timeout` is ignored in that case).
  142. """
  143. with self.not_empty:
  144. if not block:
  145. if self._empty():
  146. raise Empty
  147. elif timeout is None:
  148. while self._empty():
  149. self.not_empty.wait()
  150. else:
  151. if timeout < 0:
  152. raise ValueError("'timeout' must be a positive number")
  153. endtime = _time() + timeout
  154. while self._empty():
  155. remaining = endtime - _time()
  156. if remaining <= 0.0:
  157. raise Empty
  158. self.not_empty.wait(remaining)
  159. item = self._get()
  160. self.not_full.notify()
  161. return item
  162. def get_nowait(self) -> _T:
  163. """Remove and return an item from the queue without blocking.
  164. Only get an item if one is immediately available. Otherwise
  165. raise the ``Empty`` exception.
  166. """
  167. return self.get(False)
  168. def _init(self, maxsize: int) -> None:
  169. self.maxsize = maxsize
  170. self.queue = deque()
  171. def _qsize(self) -> int:
  172. return len(self.queue)
  173. def _empty(self) -> bool:
  174. return not self.queue
  175. def _full(self) -> bool:
  176. return self.maxsize > 0 and len(self.queue) == self.maxsize
  177. def _put(self, item: _T) -> None:
  178. self.queue.append(item)
  179. def _get(self) -> _T:
  180. if self.use_lifo:
  181. # LIFO
  182. return self.queue.pop()
  183. else:
  184. # FIFO
  185. return self.queue.popleft()
  186. class AsyncAdaptedQueue(QueueCommon[_T]):
  187. if typing.TYPE_CHECKING:
  188. @staticmethod
  189. def await_(coroutine: Awaitable[Any]) -> _T: ...
  190. else:
  191. await_ = staticmethod(await_only)
  192. def __init__(self, maxsize: int = 0, use_lifo: bool = False):
  193. self.use_lifo = use_lifo
  194. self.maxsize = maxsize
  195. def empty(self) -> bool:
  196. return self._queue.empty()
  197. def full(self):
  198. return self._queue.full()
  199. def qsize(self):
  200. return self._queue.qsize()
  201. @memoized_property
  202. def _queue(self) -> asyncio.Queue[_T]:
  203. # Delay creation of the queue until it is first used, to avoid
  204. # binding it to a possibly wrong event loop.
  205. # By delaying the creation of the pool we accommodate the common
  206. # usage pattern of instantiating the engine at module level, where a
  207. # different event loop is in present compared to when the application
  208. # is actually run.
  209. queue: asyncio.Queue[_T]
  210. if self.use_lifo:
  211. queue = asyncio.LifoQueue(maxsize=self.maxsize)
  212. else:
  213. queue = asyncio.Queue(maxsize=self.maxsize)
  214. return queue
  215. def put_nowait(self, item: _T) -> None:
  216. try:
  217. self._queue.put_nowait(item)
  218. except asyncio.QueueFull as err:
  219. raise Full() from err
  220. def put(
  221. self, item: _T, block: bool = True, timeout: Optional[float] = None
  222. ) -> None:
  223. if not block:
  224. return self.put_nowait(item)
  225. try:
  226. if timeout is not None:
  227. self.await_(asyncio.wait_for(self._queue.put(item), timeout))
  228. else:
  229. self.await_(self._queue.put(item))
  230. except (asyncio.QueueFull, asyncio.TimeoutError) as err:
  231. raise Full() from err
  232. def get_nowait(self) -> _T:
  233. try:
  234. return self._queue.get_nowait()
  235. except asyncio.QueueEmpty as err:
  236. raise Empty() from err
  237. def get(self, block: bool = True, timeout: Optional[float] = None) -> _T:
  238. if not block:
  239. return self.get_nowait()
  240. try:
  241. if timeout is not None:
  242. return self.await_(
  243. asyncio.wait_for(self._queue.get(), timeout)
  244. )
  245. else:
  246. return self.await_(self._queue.get())
  247. except (asyncio.QueueEmpty, asyncio.TimeoutError) as err:
  248. raise Empty() from err
  249. class FallbackAsyncAdaptedQueue(AsyncAdaptedQueue[_T]):
  250. if not typing.TYPE_CHECKING:
  251. await_ = staticmethod(await_fallback)