| 1 |
"""Use pika with the Asyncio EventLoop""" |
| 2 |
from __future__ import annotations |
| 3 |
|
| 4 |
import asyncio |
| 5 |
import logging |
| 6 |
import sys |
| 7 |
from typing import Any, Awaitable, Callable, Optional, TYPE_CHECKING, Sequence, Union |
| 8 |
|
| 9 |
from pika.adapters import base_connection |
| 10 |
from pika.adapters.utils import connection_workflow, nbio_interface, io_services_utils |
| 11 |
|
| 12 |
if TYPE_CHECKING: |
| 13 |
from pika import connection |
| 14 |
|
| 15 |
LOGGER = logging.getLogger(__name__) |
| 16 |
|
| 17 |
if sys.platform == 'win32': |
| 18 |
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) |
| 19 |
|
| 20 |
|
| 21 |
class AsyncioConnection(base_connection.BaseConnection): |
| 22 |
""" The AsyncioConnection runs on the Asyncio EventLoop. |
| 23 |
|
| 24 |
""" |
| 25 |
|
| 26 |
def __init__(self, |
| 27 |
parameters: Optional[connection.Parameters] = None, |
| 28 |
on_open_callback: Optional[Callable[[connection.Connection], |
| 29 |
None]] = None, |
| 30 |
on_open_error_callback: Optional[Callable[ |
| 31 |
[connection.Connection, BaseException], None]] = None, |
| 32 |
on_close_callback: Optional[Callable[ |
| 33 |
[connection.Connection, BaseException], None]] = None, |
| 34 |
custom_ioloop: Optional[ |
| 35 |
Union[asyncio.AbstractEventLoop, |
| 36 |
nbio_interface.AbstractIOServices]] = None, |
| 37 |
internal_connection_workflow: bool = True) -> None: |
| 38 |
""" Create a new instance of the AsyncioConnection class, connecting |
| 39 |
to RabbitMQ automatically |
| 40 |
|
| 41 |
:param pika.connection.Parameters parameters: Connection parameters |
| 42 |
:param callable on_open_callback: The method to call when the connection |
| 43 |
is open |
| 44 |
:param None | method on_open_error_callback: Called if the connection |
| 45 |
can't be established or connection establishment is interrupted by |
| 46 |
`Connection.close()`: on_open_error_callback(Connection, exception). |
| 47 |
:param None | method on_close_callback: Called when a previously fully |
| 48 |
open connection is closed: |
| 49 |
`on_close_callback(Connection, exception)`, where `exception` is |
| 50 |
either an instance of `exceptions.ConnectionClosed` if closed by |
| 51 |
user or broker or exception of another type that describes the cause |
| 52 |
of connection failure. |
| 53 |
:param None | asyncio.AbstractEventLoop | |
| 54 |
nbio_interface.AbstractIOServices custom_ioloop: |
| 55 |
Defaults to the running event loop, or a new event loop when |
| 56 |
none is running. |
| 57 |
:param bool internal_connection_workflow: True for autonomous connection |
| 58 |
establishment which is default; False for externally-managed |
| 59 |
connection workflow via the `create_connection()` factory. |
| 60 |
|
| 61 |
""" |
| 62 |
if isinstance(custom_ioloop, nbio_interface.AbstractIOServices): |
| 63 |
nbio = custom_ioloop |
| 64 |
else: |
| 65 |
nbio = _AsyncioIOServicesAdapter(custom_ioloop) |
| 66 |
|
| 67 |
super().__init__( |
| 68 |
parameters, |
| 69 |
on_open_callback, |
| 70 |
on_open_error_callback, |
| 71 |
on_close_callback, |
| 72 |
nbio, |
| 73 |
internal_connection_workflow=internal_connection_workflow) |
| 74 |
|
| 75 |
@classmethod |
| 76 |
def create_connection( |
| 77 |
cls, |
| 78 |
connection_configs: Sequence[connection.Parameters], |
| 79 |
on_done: Callable[[ |
| 80 |
Union[connection.Connection, |
| 81 |
connection_workflow.AMQPConnectorException] |
| 82 |
], None], |
| 83 |
custom_ioloop: Optional[asyncio.AbstractEventLoop] = None, |
| 84 |
workflow: Optional[ |
| 85 |
connection_workflow.AbstractAMQPConnectionWorkflow] = None |
| 86 |
) -> connection_workflow.AbstractAMQPConnectionWorkflow: |
| 87 |
"""Implement |
| 88 |
:py:classmethod::`pika.adapters.BaseConnection.create_connection()`. |
| 89 |
|
| 90 |
""" |
| 91 |
nbio = _AsyncioIOServicesAdapter(custom_ioloop) |
| 92 |
|
| 93 |
def connection_factory(params): |
| 94 |
"""Connection factory.""" |
| 95 |
if params is None: |
| 96 |
raise ValueError('Expected pika.connection.Parameters ' |
| 97 |
'instance, but got None in params arg.') |
| 98 |
return cls(parameters=params, |
| 99 |
custom_ioloop=nbio, |
| 100 |
internal_connection_workflow=False) |
| 101 |
|
| 102 |
return cls._start_connection_workflow( |
| 103 |
connection_configs=connection_configs, |
| 104 |
connection_factory=connection_factory, |
| 105 |
nbio=nbio, |
| 106 |
workflow=workflow, |
| 107 |
on_done=on_done) |
| 108 |
|
| 109 |
|
| 110 |
class _AsyncioIOServicesAdapter(io_services_utils.SocketConnectionMixin, |
| 111 |
io_services_utils.StreamingConnectionMixin, |
| 112 |
nbio_interface.AbstractIOServices, |
| 113 |
nbio_interface.AbstractFileDescriptorServices): |
| 114 |
"""Implements |
| 115 |
:py:class:`.utils.nbio_interface.AbstractIOServices` interface |
| 116 |
on top of `asyncio`. |
| 117 |
|
| 118 |
NOTE: |
| 119 |
:py:class:`.utils.nbio_interface.AbstractFileDescriptorServices` |
| 120 |
interface is only required by the mixins. |
| 121 |
|
| 122 |
""" |
| 123 |
|
| 124 |
def __init__(self, loop: Optional[asyncio.AbstractEventLoop] = None): |
| 125 |
""" |
| 126 |
:param asyncio.AbstractEventLoop | None loop: If None, uses the |
| 127 |
running event loop via asyncio.get_running_loop(), or creates |
| 128 |
a new one via asyncio.new_event_loop() when no loop is running |
| 129 |
(e.g. when called from a non-async thread). |
| 130 |
|
| 131 |
""" |
| 132 |
if loop is None: |
| 133 |
try: |
| 134 |
loop = asyncio.get_running_loop() |
| 135 |
except RuntimeError: |
| 136 |
loop = asyncio.new_event_loop() |
| 137 |
self._loop = loop |
| 138 |
|
| 139 |
def get_native_ioloop(self) -> asyncio.AbstractEventLoop: |
| 140 |
"""Implement |
| 141 |
:py:meth:`.utils.nbio_interface.AbstractIOServices.get_native_ioloop()`. |
| 142 |
|
| 143 |
""" |
| 144 |
return self._loop |
| 145 |
|
| 146 |
def close(self) -> None: |
| 147 |
"""Implement |
| 148 |
:py:meth:`.utils.nbio_interface.AbstractIOServices.close()`. |
| 149 |
|
| 150 |
""" |
| 151 |
self._loop.close() |
| 152 |
|
| 153 |
def run(self) -> None: |
| 154 |
"""Implement :py:meth:`.utils.nbio_interface.AbstractIOServices.run()`. |
| 155 |
|
| 156 |
""" |
| 157 |
self._loop.run_forever() |
| 158 |
|
| 159 |
def stop(self) -> None: |
| 160 |
"""Implement :py:meth:`.utils.nbio_interface.AbstractIOServices.stop()`. |
| 161 |
|
| 162 |
""" |
| 163 |
self._loop.stop() |
| 164 |
|
| 165 |
def add_callback_threadsafe(self, callback: Callable[[], None]) -> None: |
| 166 |
"""Implement |
| 167 |
:py:meth:`.utils.nbio_interface.AbstractIOServices.add_callback_threadsafe()`. |
| 168 |
|
| 169 |
""" |
| 170 |
self._loop.call_soon_threadsafe(callback) |
| 171 |
|
| 172 |
def call_later(self, delay: float, |
| 173 |
callback: Callable[[], None]) -> _TimerHandle: |
| 174 |
"""Implement |
| 175 |
:py:meth:`.utils.nbio_interface.AbstractIOServices.call_later()`. |
| 176 |
|
| 177 |
""" |
| 178 |
return _TimerHandle(self._loop.call_later(delay, callback)) |
| 179 |
|
| 180 |
def getaddrinfo(self, |
| 181 |
host: str, |
| 182 |
port: int, |
| 183 |
on_done: Callable[..., None], |
| 184 |
family: int = 0, |
| 185 |
socktype: int = 0, |
| 186 |
proto: int = 0, |
| 187 |
flags: int = 0) -> nbio_interface.AbstractIOReference: |
| 188 |
"""Implement |
| 189 |
:py:meth:`.utils.nbio_interface.AbstractIOServices.getaddrinfo()`. |
| 190 |
|
| 191 |
""" |
| 192 |
return self._schedule_and_wrap_in_io_ref( |
| 193 |
self._loop.getaddrinfo(host, |
| 194 |
port, |
| 195 |
family=family, |
| 196 |
type=socktype, |
| 197 |
proto=proto, |
| 198 |
flags=flags), on_done) |
| 199 |
|
| 200 |
def set_reader(self, fd: int, on_readable: Callable[[], None]) -> None: |
| 201 |
"""Implement |
| 202 |
:py:meth:`.utils.nbio_interface.AbstractFileDescriptorServices.set_reader()`. |
| 203 |
|
| 204 |
""" |
| 205 |
self._loop.add_reader(fd, on_readable) |
| 206 |
LOGGER.debug('set_reader(%s, _)', fd) |
| 207 |
|
| 208 |
def remove_reader(self, fd: int) -> bool: |
| 209 |
"""Implement |
| 210 |
:py:meth:`.utils.nbio_interface.AbstractFileDescriptorServices.remove_reader()`. |
| 211 |
|
| 212 |
""" |
| 213 |
LOGGER.debug('remove_reader(%s)', fd) |
| 214 |
return self._loop.remove_reader(fd) |
| 215 |
|
| 216 |
def set_writer(self, fd: int, on_writable: Callable[[], None]) -> None: |
| 217 |
"""Implement |
| 218 |
:py:meth:`.utils.nbio_interface.AbstractFileDescriptorServices.set_writer()`. |
| 219 |
|
| 220 |
""" |
| 221 |
self._loop.add_writer(fd, on_writable) |
| 222 |
LOGGER.debug('set_writer(%s, _)', fd) |
| 223 |
|
| 224 |
def remove_writer(self, fd: int) -> bool: |
| 225 |
"""Implement |
| 226 |
:py:meth:`.utils.nbio_interface.AbstractFileDescriptorServices.remove_writer()`. |
| 227 |
|
| 228 |
""" |
| 229 |
LOGGER.debug('remove_writer(%s)', fd) |
| 230 |
return self._loop.remove_writer(fd) |
| 231 |
|
| 232 |
def _schedule_and_wrap_in_io_ref( |
| 233 |
self, coro: Awaitable[Any], on_done: Callable[ |
| 234 |
[Union[base_connection.BaseConnection, BaseException]], None] |
| 235 |
) -> _AsyncioIOReference: |
| 236 |
"""Schedule the coroutine to run and return _AsyncioIOReference |
| 237 |
|
| 238 |
:param coroutine-obj coro: |
| 239 |
:param callable on_done: user callback that takes the completion result |
| 240 |
or exception as its only arg. It will not be called if the operation |
| 241 |
was cancelled. |
| 242 |
:rtype: _AsyncioIOReference which is derived from |
| 243 |
nbio_interface.AbstractIOReference |
| 244 |
|
| 245 |
""" |
| 246 |
if not callable(on_done): |
| 247 |
raise TypeError( |
| 248 |
f'on_done arg must be callable, but got {on_done!r}') |
| 249 |
|
| 250 |
return _AsyncioIOReference(asyncio.ensure_future(coro, loop=self._loop), |
| 251 |
on_done) |
| 252 |
|
| 253 |
|
| 254 |
class _TimerHandle(nbio_interface.AbstractTimerReference): |
| 255 |
"""This module's adaptation of `nbio_interface.AbstractTimerReference`. |
| 256 |
|
| 257 |
""" |
| 258 |
|
| 259 |
def __init__(self, handle: asyncio.Handle) -> None: |
| 260 |
""" |
| 261 |
|
| 262 |
:param asyncio.Handle handle: |
| 263 |
""" |
| 264 |
self._handle: Optional[asyncio.Handle] = handle |
| 265 |
|
| 266 |
def cancel(self) -> None: |
| 267 |
if self._handle is not None: |
| 268 |
self._handle.cancel() |
| 269 |
self._handle = None |
| 270 |
|
| 271 |
|
| 272 |
class _AsyncioIOReference(nbio_interface.AbstractIOReference): |
| 273 |
"""This module's adaptation of `nbio_interface.AbstractIOReference`. |
| 274 |
|
| 275 |
""" |
| 276 |
|
| 277 |
def __init__( |
| 278 |
self, future: asyncio.Future, on_done: Callable[ |
| 279 |
[Union[base_connection.BaseConnection, BaseException]], None] |
| 280 |
) -> None: |
| 281 |
""" |
| 282 |
:param asyncio.Future future: |
| 283 |
:param callable on_done: user callback that takes the completion result |
| 284 |
or exception as its only arg. It will not be called if the operation |
| 285 |
was cancelled. |
| 286 |
|
| 287 |
""" |
| 288 |
if not callable(on_done): |
| 289 |
raise TypeError( |
| 290 |
f'on_done arg must be callable, but got {on_done!r}') |
| 291 |
|
| 292 |
self._future = future |
| 293 |
|
| 294 |
def on_done_adapter(future: asyncio.Future) -> None: |
| 295 |
"""Handle completion callback from the future instance""" |
| 296 |
|
| 297 |
# NOTE: Asyncio schedules callback for cancelled futures, but pika |
| 298 |
# doesn't want that |
| 299 |
if not future.cancelled(): |
| 300 |
on_done(future.exception() or future.result()) |
| 301 |
|
| 302 |
future.add_done_callback(on_done_adapter) |
| 303 |
|
| 304 |
def cancel(self) -> bool: |
| 305 |
"""Cancel pending operation |
| 306 |
|
| 307 |
:returns: False if was already done or cancelled; True otherwise |
| 308 |
:rtype: bool |
| 309 |
|
| 310 |
""" |
| 311 |
return self._future.cancel() |