_concurrency_py3k.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. # util/_concurrency_py3k.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. import asyncio
  8. import sys
  9. from typing import Any
  10. from typing import Callable
  11. from typing import Coroutine
  12. import greenlet
  13. from . import compat
  14. from .langhelpers import memoized_property
  15. from .. import exc
  16. # If greenlet.gr_context is present in current version of greenlet,
  17. # it will be set with the current context on creation.
  18. # Refs: https://github.com/python-greenlet/greenlet/pull/198
  19. _has_gr_context = hasattr(greenlet.getcurrent(), "gr_context")
  20. def is_exit_exception(e):
  21. # note asyncio.CancelledError is already BaseException
  22. # so was an exit exception in any case
  23. return not isinstance(e, Exception) or isinstance(
  24. e, (asyncio.TimeoutError, asyncio.CancelledError)
  25. )
  26. # implementation based on snaury gist at
  27. # https://gist.github.com/snaury/202bf4f22c41ca34e56297bae5f33fef
  28. # Issue for context: https://github.com/python-greenlet/greenlet/issues/173
  29. class _AsyncIoGreenlet(greenlet.greenlet):
  30. __sqlalchemy_greenlet_provider__ = True
  31. def __init__(self, fn, driver):
  32. greenlet.greenlet.__init__(self, fn, driver)
  33. if _has_gr_context:
  34. self.gr_context = driver.gr_context
  35. def await_only(awaitable: Coroutine) -> Any:
  36. """Awaits an async function in a sync method.
  37. The sync method must be inside a :func:`greenlet_spawn` context.
  38. :func:`await_only` calls cannot be nested.
  39. :param awaitable: The coroutine to call.
  40. """
  41. # this is called in the context greenlet while running fn
  42. current = greenlet.getcurrent()
  43. if not getattr(current, "__sqlalchemy_greenlet_provider__", False):
  44. raise exc.MissingGreenlet(
  45. "greenlet_spawn has not been called; can't call await_only() "
  46. "here. Was IO attempted in an unexpected place?"
  47. )
  48. # returns the control to the driver greenlet passing it
  49. # a coroutine to run. Once the awaitable is done, the driver greenlet
  50. # switches back to this greenlet with the result of awaitable that is
  51. # then returned to the caller (or raised as error)
  52. return current.parent.switch(awaitable)
  53. def await_fallback(awaitable: Coroutine) -> Any:
  54. """Awaits an async function in a sync method.
  55. The sync method must be inside a :func:`greenlet_spawn` context.
  56. :func:`await_fallback` calls cannot be nested.
  57. :param awaitable: The coroutine to call.
  58. """
  59. # this is called in the context greenlet while running fn
  60. current = greenlet.getcurrent()
  61. if not getattr(current, "__sqlalchemy_greenlet_provider__", False):
  62. loop = get_event_loop()
  63. if loop.is_running():
  64. raise exc.MissingGreenlet(
  65. "greenlet_spawn has not been called and asyncio event "
  66. "loop is already running; can't call await_fallback() here. "
  67. "Was IO attempted in an unexpected place?"
  68. )
  69. return loop.run_until_complete(awaitable)
  70. return current.parent.switch(awaitable)
  71. async def greenlet_spawn(
  72. fn: Callable, *args, _require_await=False, **kwargs
  73. ) -> Any:
  74. """Runs a sync function ``fn`` in a new greenlet.
  75. The sync function can then use :func:`await_only` to wait for async
  76. functions.
  77. :param fn: The sync callable to call.
  78. :param \\*args: Positional arguments to pass to the ``fn`` callable.
  79. :param \\*\\*kwargs: Keyword arguments to pass to the ``fn`` callable.
  80. """
  81. context = _AsyncIoGreenlet(fn, greenlet.getcurrent())
  82. # runs the function synchronously in gl greenlet. If the execution
  83. # is interrupted by await_only, context is not dead and result is a
  84. # coroutine to wait. If the context is dead the function has
  85. # returned, and its result can be returned.
  86. switch_occurred = False
  87. result = context.switch(*args, **kwargs)
  88. while not context.dead:
  89. switch_occurred = True
  90. try:
  91. # wait for a coroutine from await_only and then return its
  92. # result back to it.
  93. value = await result
  94. except BaseException:
  95. # this allows an exception to be raised within
  96. # the moderated greenlet so that it can continue
  97. # its expected flow.
  98. result = context.throw(*sys.exc_info())
  99. else:
  100. result = context.switch(value)
  101. if _require_await and not switch_occurred:
  102. raise exc.AwaitRequired(
  103. "The current operation required an async execution but none was "
  104. "detected. This will usually happen when using a non compatible "
  105. "DBAPI driver. Please ensure that an async DBAPI is used."
  106. )
  107. return result
  108. class AsyncAdaptedLock:
  109. @memoized_property
  110. def mutex(self):
  111. # there should not be a race here for coroutines creating the
  112. # new lock as we are not using await, so therefore no concurrency
  113. return asyncio.Lock()
  114. def __enter__(self):
  115. # await is used to acquire the lock only after the first calling
  116. # coroutine has created the mutex.
  117. await_fallback(self.mutex.acquire())
  118. return self
  119. def __exit__(self, *arg, **kw):
  120. self.mutex.release()
  121. def _util_async_run_coroutine_function(fn, *args, **kwargs):
  122. """for test suite/ util only"""
  123. loop = get_event_loop()
  124. if loop.is_running():
  125. raise Exception(
  126. "for async run coroutine we expect that no greenlet or event "
  127. "loop is running when we start out"
  128. )
  129. return loop.run_until_complete(fn(*args, **kwargs))
  130. def _util_async_run(fn, *args, **kwargs):
  131. """for test suite/ util only"""
  132. loop = get_event_loop()
  133. if not loop.is_running():
  134. return loop.run_until_complete(greenlet_spawn(fn, *args, **kwargs))
  135. else:
  136. # allow for a wrapped test function to call another
  137. assert getattr(
  138. greenlet.getcurrent(), "__sqlalchemy_greenlet_provider__", False
  139. )
  140. return fn(*args, **kwargs)
  141. def get_event_loop():
  142. """vendor asyncio.get_event_loop() for python 3.7 and above.
  143. Python 3.10 deprecates get_event_loop() as a standalone.
  144. """
  145. if compat.py37:
  146. try:
  147. return asyncio.get_running_loop()
  148. except RuntimeError:
  149. return asyncio.get_event_loop_policy().get_event_loop()
  150. else:
  151. return asyncio.get_event_loop()