1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
|
import asyncio
from ssl import SSLContext
from types import TracebackType
from typing import (
Any, Awaitable, Dict, Literal, Optional, Tuple, Type, TypeVar, Union
)
import aiormq.abc
from aiormq.connection import parse_int
from pamqp.common import FieldTable
from yarl import URL
from .abc import (
AbstractChannel, AbstractConnection, ConnectionParameter, SSLOptions,
TimeoutType, UnderlayConnection,
)
from .channel import Channel
from .exceptions import ConnectionClosed
from .log import get_logger
from .tools import CallbackCollection
log = get_logger(__name__)
T = TypeVar("T")
class Connection(AbstractConnection):
""" Connection abstraction """
CHANNEL_CLASS: Type[Channel] = Channel
PARAMETERS: Tuple[ConnectionParameter, ...] = (
ConnectionParameter(
name="interleave",
parser=parse_int,
is_kwarg=True,
),
ConnectionParameter(
name="happy_eyeballs_delay",
parser=float,
is_kwarg=True,
),
)
_closed: asyncio.Future
@property
def is_closed(self) -> bool:
return self._closed.done()
async def close(
self, exc: Optional[aiormq.abc.ExceptionType] = ConnectionClosed,
) -> None:
transport, self.transport = self.transport, None
self._close_called = True
if not transport:
return
await transport.close(exc)
if not self._closed.done():
self._closed.set_result(True)
def closed(self) -> Awaitable[Literal[True]]:
return self._closed
@classmethod
def _parse_parameters(cls, kwargs: Dict[str, Any]) -> Dict[str, Any]:
result = {}
for parameter in cls.PARAMETERS:
value = kwargs.get(parameter.name, parameter.default)
if parameter.is_kwarg and value is None:
# skip optional value
continue
result[parameter.name] = parameter.parse(value)
return result
def __init__(
self, url: URL, loop: Optional[asyncio.AbstractEventLoop] = None,
ssl_context: Optional[SSLContext] = None, **kwargs: Any,
):
self.loop = loop or asyncio.get_event_loop()
self.transport = None
self._closed = self.loop.create_future()
self._close_called = False
self.url = URL(url)
self.kwargs: Dict[str, Any] = self._parse_parameters(
kwargs or dict(self.url.query),
)
self.kwargs["context"] = ssl_context
self.close_callbacks = CallbackCollection(self)
self.connected: asyncio.Event = asyncio.Event()
def __str__(self) -> str:
url = self.url
if url.password:
url = url.with_password("******")
return str(url)
def __repr__(self) -> str:
return f'<{self.__class__.__name__}: "{self}">'
async def _on_connection_close(self, closing: asyncio.Future) -> None:
try:
exc = closing.exception()
except asyncio.CancelledError as e:
exc = e
self.connected.clear()
await self.close_callbacks(exc)
async def _on_connected(self) -> None:
self.connected.set()
async def connect(self, timeout: TimeoutType = None) -> None:
""" Connect to AMQP server. This method should be called after
:func:`aio_pika.connection.Connection.__init__`
.. note::
This method is called by :func:`connect`.
You shouldn't call it explicitly.
"""
self.transport = await UnderlayConnection.connect(
self.url, self._on_connection_close,
timeout=timeout, **self.kwargs,
)
await self._on_connected()
def channel(
self,
channel_number: Optional[int] = None,
publisher_confirms: bool = True,
on_return_raises: bool = False,
) -> AbstractChannel:
""" Coroutine which returns new instance of :class:`Channel`.
Example:
.. code-block:: python
import aio_pika
async def main(loop):
connection = await aio_pika.connect(
"amqp://guest:guest@127.0.0.1/"
)
channel1 = connection.channel()
await channel1.close()
# Creates channel with specific channel number
channel42 = connection.channel(42)
await channel42.close()
# For working with transactions
channel_no_confirms = await connection.channel(
publisher_confirms=False
)
await channel_no_confirms.close()
Also available as an asynchronous context manager:
.. code-block:: python
import aio_pika
async def main(loop):
connection = await aio_pika.connect(
"amqp://guest:guest@127.0.0.1/"
)
async with connection.channel() as channel:
# channel is open and available
# channel is now closed
:param channel_number: specify the channel number explicit
:param publisher_confirms:
if `True` the :func:`aio_pika.Exchange.publish` method will be
return :class:`bool` after publish is complete. Otherwise the
:func:`aio_pika.Exchange.publish` method will be return
:class:`None`
:param on_return_raises:
raise an :class:`aio_pika.exceptions.DeliveryError`
when mandatory message will be returned
"""
if not self.transport:
raise RuntimeError("Connection was not opened")
log.debug("Creating AMQP channel for connection: %r", self)
channel = self.CHANNEL_CLASS(
connection=self,
channel_number=channel_number,
publisher_confirms=publisher_confirms,
on_return_raises=on_return_raises,
)
log.debug("Channel created: %r", channel)
return channel
async def ready(self) -> None:
await self.connected.wait()
def __del__(self) -> None:
if (
self.is_closed or
self.loop.is_closed()
):
return
asyncio.ensure_future(self.close())
async def __aenter__(self) -> "Connection":
return self
async def __aexit__(
self,
exc_type: Optional[Type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType],
) -> None:
await self.close()
async def update_secret(
self, new_secret: str, *,
reason: str = "", timeout: TimeoutType = None,
) -> aiormq.spec.Connection.UpdateSecretOk:
if self.transport is None:
raise RuntimeError("Connection is not ready")
result = await self.transport.connection.update_secret(
new_secret=new_secret, reason=reason, timeout=timeout,
)
self.url = self.url.with_password(new_secret)
return result
def make_url(
url: Union[str, URL, None] = None,
*,
host: str = "localhost",
port: int = 5672,
login: str = "guest",
password: str = "guest",
virtualhost: str = "/",
ssl: bool = False,
ssl_options: Optional[SSLOptions] = None,
client_properties: Optional[FieldTable] = None,
**kwargs: Any,
) -> URL:
if url is not None:
if not isinstance(url, URL):
return URL(url)
return url
kw = kwargs
kw.update(ssl_options or {})
kw.update(client_properties or {})
# sanitize keywords
kw = {k: v for k, v in kw.items() if v is not None}
return URL.build(
scheme="amqps" if ssl else "amqp",
host=host,
port=port,
user=login,
password=password,
# yarl >= 1.3.0 requires path beginning with slash
path="/" + virtualhost,
query=kw,
)
async def connect(
url: Union[str, URL, None] = None,
*,
host: str = "localhost",
port: int = 5672,
login: str = "guest",
password: str = "guest",
virtualhost: str = "/",
ssl: bool = False,
loop: Optional[asyncio.AbstractEventLoop] = None,
ssl_options: Optional[SSLOptions] = None,
ssl_context: Optional[SSLContext] = None,
timeout: TimeoutType = None,
client_properties: Optional[FieldTable] = None,
connection_class: Type[AbstractConnection] = Connection,
**kwargs: Any,
) -> AbstractConnection:
""" Make connection to the broker.
Example:
.. code-block:: python
import aio_pika
async def main():
connection = await aio_pika.connect(
"amqp://guest:guest@127.0.0.1/"
)
Connect to localhost with default credentials:
.. code-block:: python
import aio_pika
async def main():
connection = await aio_pika.connect()
.. note::
The available keys for ssl_options parameter are:
* cert_reqs
* certfile
* keyfile
* ssl_version
For an information on what the ssl_options can be set to reference the
`official Python documentation`_ .
Set connection name for RabbitMQ admin panel:
.. code-block:: python
# As URL parameter method
read_connection = await connect(
"amqp://guest:guest@localhost/?name=Read%20connection"
)
write_connection = await connect(
client_properties={
'connection_name': 'Write connection'
}
)
.. note:
``client_properties`` argument requires ``aiormq>=2.9``
URL string might be containing ssl parameters e.g.
`amqps://user:pass@host//?ca_certs=ca.pem&certfile=crt.pem&keyfile=key.pem`
:param client_properties: add custom client capability.
:param url:
RFC3986_ formatted broker address. When :class:`None`
will be used keyword arguments.
:param host: hostname of the broker
:param port: broker port 5672 by default
:param login: username string. `'guest'` by default.
:param password: password string. `'guest'` by default.
:param virtualhost: virtualhost parameter. `'/'` by default
:param ssl: use SSL for connection. Should be used with addition kwargs.
:param ssl_options: A dict of values for the SSL connection.
:param timeout: connection timeout in seconds
:param loop:
Event loop (:func:`asyncio.get_event_loop()` when :class:`None`)
:param ssl_context: ssl.SSLContext instance
:param connection_class: Factory of a new connection
:param kwargs: addition parameters which will be passed to the connection.
:return: :class:`aio_pika.connection.Connection`
.. _RFC3986: https://goo.gl/MzgYAs
.. _official Python documentation: https://goo.gl/pty9xA
"""
connection: AbstractConnection = connection_class(
make_url(
url,
host=host,
port=port,
login=login,
password=password,
virtualhost=virtualhost,
ssl=ssl,
ssl_options=ssl_options,
client_properties=client_properties,
**kwargs,
),
loop=loop,
ssl_context=ssl_context,
**kwargs,
)
await connection.connect(timeout=timeout)
return connection
__all__ = ("Connection", "connect", "make_url")
|