File: queue.py

package info (click to toggle)
python-aio-pika 9.5.6-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,428 kB
  • sloc: python: 8,009; makefile: 36; xml: 1
file content (619 lines) | stat: -rw-r--r-- 19,586 bytes parent folder | download
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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
import asyncio
from asyncio import Future
from functools import partial
from types import TracebackType
from typing import (
    Any, Awaitable, Callable, Literal, Optional, Type, cast, overload,
)

import aiormq
from aiormq.abc import DeliveredMessage
try:
    ExceptionGroup
except NameError:
    from exceptiongroup import ExceptionGroup
from pamqp.common import Arguments

from .abc import (
    AbstractChannel, AbstractIncomingMessage, AbstractQueue,
    AbstractQueueIterator, ConsumerTag, TimeoutType, get_exchange_name,
)
from .exceptions import QueueEmpty
from .exchange import ExchangeParamType
from .log import get_logger
from .message import IncomingMessage
from .tools import CallbackCollection, create_task, ensure_awaitable


log = get_logger(__name__)


async def consumer(
    callback: Callable[[AbstractIncomingMessage], Any],
    msg: DeliveredMessage, *,
    no_ack: bool,
) -> Any:
    message = IncomingMessage(msg, no_ack=no_ack)
    return await create_task(callback, message)


class Queue(AbstractQueue):
    """ AMQP queue abstraction """

    __slots__ = (
        "__weakref__",
        "__get_lock",
        "close_callbacks",
        "channel",
        "name",
        "durable",
        "exclusive",
        "auto_delete",
        "arguments",
        "passive",
        "declaration_result",
    )

    def __init__(
        self,
        channel: AbstractChannel,
        name: Optional[str],
        durable: bool,
        exclusive: bool,
        auto_delete: bool,
        arguments: Arguments,
        passive: bool = False,
    ):
        self.__get_lock = asyncio.Lock()
        self.close_callbacks = CallbackCollection(self)
        self.channel = channel
        self.name = name or ""
        self.durable = durable
        self.exclusive = exclusive
        self.auto_delete = auto_delete
        self.arguments = arguments
        self.passive = passive

    def __str__(self) -> str:
        return f"{self.name}"

    def __repr__(self) -> str:
        return (
            f"<{self.__class__.__name__}({self}): "
            f"auto_delete={self.auto_delete}, "
            f"durable={self.durable}, "
            f"exclusive={self.exclusive}, "
            f"arguments={self.arguments!r}"
        )

    async def declare(
        self, timeout: TimeoutType = None,
    ) -> aiormq.spec.Queue.DeclareOk:
        """ Declare queue.

        :param timeout: execution timeout
        :return: :class:`None`
        """
        log.debug("Declaring queue: %r", self)
        channel = await self.channel.get_underlay_channel()
        self.declaration_result = await channel.queue_declare(
            queue=self.name,
            durable=self.durable,
            exclusive=self.exclusive,
            auto_delete=self.auto_delete,
            arguments=self.arguments,
            passive=self.passive,
            timeout=timeout,
        )

        if self.declaration_result.queue is not None:
            self.name = self.declaration_result.queue
        else:
            self.name = "<UNNAMED>"
        return self.declaration_result

    async def bind(
        self,
        exchange: ExchangeParamType,
        routing_key: Optional[str] = None,
        *,
        arguments: Arguments = None,
        timeout: TimeoutType = None,
    ) -> aiormq.spec.Queue.BindOk:

        """ A binding is a relationship between an exchange and a queue.
        This can be simply read as: the queue is interested in messages
        from this exchange.

        Bindings can take an extra routing_key parameter. To avoid
        the confusion with a basic_publish parameter we're going to
        call it a binding key.

        :param exchange: :class:`aio_pika.exchange.Exchange` instance
        :param routing_key: routing key
        :param arguments: additional arguments
        :param timeout: execution timeout
        :raises asyncio.TimeoutError:
            when the binding timeout period has elapsed.
        :return: :class:`None`
        """

        if routing_key is None:
            routing_key = self.name

        log.debug(
            "Binding queue %r: exchange=%r, routing_key=%r, arguments=%r",
            self,
            exchange,
            routing_key,
            arguments,
        )

        channel = await self.channel.get_underlay_channel()
        return await channel.queue_bind(
            self.name,
            exchange=get_exchange_name(exchange),
            routing_key=routing_key,
            arguments=arguments,
            timeout=timeout,
        )

    async def unbind(
        self,
        exchange: ExchangeParamType,
        routing_key: Optional[str] = None,
        arguments: Arguments = None,
        timeout: TimeoutType = None,
    ) -> aiormq.spec.Queue.UnbindOk:

        """ Remove binding from exchange for this :class:`Queue` instance

        :param exchange: :class:`aio_pika.exchange.Exchange` instance
        :param routing_key: routing key
        :param arguments: additional arguments
        :param timeout: execution timeout
        :raises asyncio.TimeoutError:
            when the unbinding timeout period has elapsed.
        :return: :class:`None`
        """

        if routing_key is None:
            routing_key = self.name

        log.debug(
            "Unbinding queue %r: exchange=%r, routing_key=%r, arguments=%r",
            self,
            exchange,
            routing_key,
            arguments,
        )

        channel = await self.channel.get_underlay_channel()
        return await channel.queue_unbind(
            queue=self.name,
            exchange=get_exchange_name(exchange),
            routing_key=routing_key,
            arguments=arguments,
            timeout=timeout,
        )

    async def consume(
        self,
        callback: Callable[[AbstractIncomingMessage], Awaitable[Any]],
        no_ack: bool = False,
        exclusive: bool = False,
        arguments: Arguments = None,
        consumer_tag: Optional[ConsumerTag] = None,
        timeout: TimeoutType = None,
    ) -> ConsumerTag:

        """ Start to consuming the :class:`Queue`.

        :param timeout: :class:`asyncio.TimeoutError` will be raises when the
                        Future was not finished after this time.
        :param callback: Consuming callback. Should be a coroutine function.
        :param no_ack:
            if :class:`True` you don't need to call
            :func:`aio_pika.message.IncomingMessage.ack`
        :param exclusive:
            Makes this queue exclusive. Exclusive queues may only
            be accessed by the current connection, and are deleted
            when that connection closes. Passive declaration of an
            exclusive queue by other connections are not allowed.
        :param arguments: additional arguments
        :param consumer_tag: optional consumer tag

        :raises asyncio.TimeoutError:
            when the consuming timeout period has elapsed.
        :return str: consumer tag :class:`str`

        """

        log.debug("Start to consuming queue: %r", self)
        callback = ensure_awaitable(callback)

        channel = await self.channel.get_underlay_channel()
        consume_result = await channel.basic_consume(
            queue=self.name,
            consumer_callback=partial(
                consumer,
                callback,
                no_ack=no_ack,
            ),
            exclusive=exclusive,
            no_ack=no_ack,
            arguments=arguments,
            consumer_tag=consumer_tag,
            timeout=timeout,
        )

        # consumer_tag property is Optional[str] in practice this check
        # should never take place, however, it protects against the case
        # if the `None` comes from pamqp
        if consume_result.consumer_tag is None:
            raise RuntimeError("Consumer tag is None")

        return consume_result.consumer_tag

    async def cancel(
        self, consumer_tag: ConsumerTag,
        timeout: TimeoutType = None,
        nowait: bool = False,
    ) -> aiormq.spec.Basic.CancelOk:
        """ This method cancels a consumer. This does not affect already
        delivered messages, but it does mean the server will not send any more
        messages for that consumer. The client may receive an arbitrary number
        of messages in between sending the cancel method and receiving the
        cancel-ok reply. It may also be sent from the server to the client in
        the event of the consumer being unexpectedly cancelled (i.e. cancelled
        for any reason other than the server receiving the corresponding
        basic.cancel from the client). This allows clients to be notified of
        the loss of consumers due to events such as queue deletion.

        :param consumer_tag:
            consumer tag returned by :func:`~aio_pika.Queue.consume`
        :param timeout: execution timeout
        :param bool nowait: Do not expect a Basic.CancelOk response
        :return: Basic.CancelOk when operation completed successfully
        """

        channel = await self.channel.get_underlay_channel()
        return await channel.basic_cancel(
            consumer_tag=consumer_tag, nowait=nowait, timeout=timeout,
        )

    @overload
    async def get(
        self, *, no_ack: bool = False,
        fail: Literal[True] = ..., timeout: TimeoutType = ...,
    ) -> IncomingMessage:
        ...

    @overload
    async def get(
        self, *, no_ack: bool = False,
        fail: Literal[False] = ..., timeout: TimeoutType = ...,
    ) -> Optional[IncomingMessage]:
        ...

    async def get(
        self, *, no_ack: bool = False,
        fail: bool = True, timeout: TimeoutType = 5,
    ) -> Optional[IncomingMessage]:

        """ Get message from the queue.

        :param no_ack: if :class:`True` you don't need to call
                       :func:`aio_pika.message.IncomingMessage.ack`
        :param timeout: execution timeout
        :param fail: Should return :class:`None` instead of raise an
                     exception :class:`aio_pika.exceptions.QueueEmpty`.
        :return: :class:`aio_pika.message.IncomingMessage`
        """

        channel = await self.channel.get_underlay_channel()
        msg: DeliveredMessage = await channel.basic_get(
            self.name, no_ack=no_ack, timeout=timeout,
        )

        if isinstance(msg.delivery, aiormq.spec.Basic.GetEmpty):
            if fail:
                raise QueueEmpty
            return None

        return IncomingMessage(msg, no_ack=no_ack)

    async def purge(
        self, no_wait: bool = False, timeout: TimeoutType = None,
    ) -> aiormq.spec.Queue.PurgeOk:
        """ Purge all messages from the queue.

        :param no_wait: no wait response
        :param timeout: execution timeout
        :return: :class:`None`
        """

        log.info("Purging queue: %r", self)

        channel = await self.channel.get_underlay_channel()
        return await channel.queue_purge(
            self.name, nowait=no_wait, timeout=timeout,
        )

    async def delete(
        self, *, if_unused: bool = True,
        if_empty: bool = True, timeout: TimeoutType = None,
    ) -> aiormq.spec.Queue.DeleteOk:

        """ Delete the queue.

        :param if_unused: Perform delete only when unused
        :param if_empty: Perform delete only when empty
        :param timeout: execution timeout
        :return: :class:`None`
        """

        log.info("Deleting %r", self)

        channel = await self.channel.get_underlay_channel()
        return await channel.queue_delete(
            self.name,
            if_unused=if_unused,
            if_empty=if_empty,
            timeout=timeout,
        )

    def __aiter__(self) -> "AbstractQueueIterator":
        return self.iterator()

    def iterator(self, **kwargs: Any) -> "AbstractQueueIterator":
        """ Returns an iterator for async for expression.

        Full example:

        .. code-block:: python

            import aio_pika

            async def main():
                connection = await aio_pika.connect()

                async with connection:
                    channel = await connection.channel()

                    queue = await channel.declare_queue('test')

                    async with queue.iterator() as q:
                        async for message in q:
                            print(message.body)

        When your program runs with run_forever the iterator will be closed
        in background. In this case the context processor for iterator might
        be skipped and the queue might be used in the "async for"
        expression directly.

        .. code-block:: python

            import aio_pika

            async def main():
                connection = await aio_pika.connect()

                async with connection:
                    channel = await connection.channel()

                    queue = await channel.declare_queue('test')

                    async for message in queue:
                        print(message.body)

        :return: QueueIterator
        """

        return QueueIterator(self, **kwargs)


class QueueIterator(AbstractQueueIterator):
    DEFAULT_CLOSE_TIMEOUT = 5

    @property
    def consumer_tag(self) -> Optional[ConsumerTag]:
        return getattr(self, "_consumer_tag", None)

    async def close(self) -> None:
        await self._on_close(self._amqp_queue, None)
        if not self._closed.done():
            self._closed.set_result(True)

    async def _set_closed(
        self,
        _channel: Optional[AbstractQueue],
        exc: Optional[BaseException]
    ) -> None:
        if not self._closed.done():
            self._closed.set_result(True)

    async def _on_close(
        self,
        _channel: Optional[AbstractQueue],
        _exc: Optional[BaseException]
    ) -> None:
        log.debug("Cancelling queue iterator %r", self)

        if not hasattr(self, "_consumer_tag"):
            log.debug("Queue iterator %r already cancelled", self)
            return

        if self._amqp_queue.channel.is_closed:
            log.debug("Queue iterator %r channel closed", self)
            return

        log.debug("Basic.cancel for %r", self.consumer_tag)
        consumer_tag = self._consumer_tag
        del self._consumer_tag

        self._amqp_queue.close_callbacks.discard(self._on_close)
        await self._amqp_queue.cancel(consumer_tag)

        log.debug("Queue iterator %r closed", self)

        if self._queue.empty():
            return

        exceptions = []
        # Reject all messages that have been received and in the buffer/cache.
        while not self._queue.empty():
            msg = self._queue.get_nowait()

            if self._amqp_queue.channel.is_closed:
                log.warning(
                    "Message %r lost when queue iterator %r channel closed",
                    msg,
                    self,
                )
            elif self._consume_kwargs.get("no_ack", False):
                log.warning(
                    "Message %r lost for consumer with no_ack %r",
                    msg,
                    self,
                )
            else:
                try:
                    await msg.nack(requeue=True, multiple=False)
                except Exception as e:
                    log.warning(
                        "Failed to nack message %r",
                        msg,
                        exc_info=e,
                    )
                    exceptions.append(e)

        if exceptions:
            raise ExceptionGroup(
                "Unable to nack all messages",
                exceptions,
            )

    def __str__(self) -> str:
        return f"queue[{self._amqp_queue}](...)"

    def __repr__(self) -> str:
        return (
            f"<{self.__class__.__name__}: "
            f"queue={self._amqp_queue.name!r} "
            f"ctag={self.consumer_tag!r}>"
        )

    def __init__(self, queue: Queue, **kwargs: Any):
        self._consumer_tag: ConsumerTag
        self._amqp_queue: Queue = queue
        self._queue = asyncio.Queue()
        self._closed = asyncio.get_running_loop().create_future()
        self._message_or_closed = asyncio.Event()
        self._timeout_event = asyncio.Event()
        self._consume_kwargs = kwargs

        cast(
            asyncio.Future, self._amqp_queue.channel.closed()
        ).add_done_callback(self._propagate_closed)
        self._closed.add_done_callback(self._propagate_closed)

        self._amqp_queue.close_callbacks.add(self._on_close, weak=True)
        self._amqp_queue.close_callbacks.add(
            self._set_closed,
            weak=True
        )

    def _propagate_closed(self, _: Future) -> None:
        self._message_or_closed.set()

    async def on_message(self, message: AbstractIncomingMessage) -> None:
        await self._queue.put(message)
        self._message_or_closed.set()

    async def consume(self) -> None:
        self._consumer_tag = await self._amqp_queue.consume(
            self.on_message, **self._consume_kwargs,
        )

    def __aiter__(self) -> "AbstractQueueIterator":
        return self

    async def __aenter__(self) -> "AbstractQueueIterator":
        if not hasattr(self, "_consumer_tag"):
            await self.consume()
        return self

    async def __aexit__(
        self,
        exc_type: Optional[Type[BaseException]],
        exc_val: Optional[BaseException],
        exc_tb: Optional[TracebackType],
    ) -> None:
        if hasattr(self, "__closing"):
            try:
                await self.__closing
            finally:
                del self.__closing
        else:
            await self.close()

    async def __anext__(self) -> AbstractIncomingMessage:
        if self._closed.done():
            raise StopAsyncIteration

        if not hasattr(self, "_consumer_tag"):
            await self.consume()

        timeout: Optional[float] = self._consume_kwargs.get("timeout")

        if not self._message_or_closed.is_set():
            coroutine: Awaitable[Any] = self._message_or_closed.wait()
            if timeout is not None and timeout > 0:
                coroutine = asyncio.wait_for(coroutine, timeout=timeout)

            try:
                await coroutine
            except (asyncio.TimeoutError, asyncio.CancelledError):
                if timeout is not None:
                    timeout = (
                        timeout
                        if timeout > 0
                        else self.DEFAULT_CLOSE_TIMEOUT
                    )
                    log.info(
                        "%r closing with timeout %d seconds",
                        self, timeout,
                    )

                task = asyncio.create_task(self.close())
                coroutine = task
                if timeout is not None:
                    coroutine = asyncio.wait_for(
                        asyncio.shield(coroutine),
                        timeout=timeout,
                    )

                try:
                    await coroutine
                except asyncio.TimeoutError:
                    self.__closing = task

                raise

        if self._queue.empty():
            raise StopAsyncIteration

        msg = self._queue.get_nowait()

        if (
            self._queue.empty()
            and not self._amqp_queue.channel.is_closed
            and not self._closed.done()
        ):
            self._message_or_closed.clear()

        return msg


__all__ = ("Queue", "QueueIterator", "ConsumerTag")