Debian Codegraph @

pika/adapters/blocking_connection.py

raw
1 """The blocking connection adapter module implements blocking semantics on top
2 of Pika's core AMQP driver. While most of the asynchronous expectations are
3 removed when using the blocking connection adapter, it attempts to remain true
4 to the asynchronous RPC nature of the AMQP protocol, supporting server sent
5 RPC commands.
6
7 The user facing classes in the module consist of the
8 :py:class:`~pika.adapters.blocking_connection.BlockingConnection`
9 and the :class:`~pika.adapters.blocking_connection.BlockingChannel`
10 classes.
11
12 """
13 # Suppress too-many-lines
14 # pylint: disable=C0302
15
16 # Disable "access to protected member warnings: this wrapper implementation is
17 # a friend of those instances
18 # pylint: disable=W0212
19
20 from __future__ import annotations
21
22 from collections import namedtuple, deque
23 import contextlib
24 import functools
25 import logging
26 import threading
27 from typing import Any, Callable, Dict, Generator, Generic, List, Optional, Sequence, Set, Tuple, TypeVar, Union, TYPE_CHECKING
28
29 import pika.channel
30 import pika.compat as compat
31 import pika.connection
32 import pika.exceptions as exceptions
33 import pika.exceptions
34 import pika.spec
35 import pika.validators as validators
36 from pika.adapters.utils import connection_workflow
37
38 # NOTE: import SelectConnection after others to avoid circular depenency
39 from pika.adapters import select_connection
40 from pika.exchange_type import ExchangeType
41
42 if TYPE_CHECKING:
43 from traceback import TracebackException
44 from types import TracebackType
45 import pika.frame
46
47 T = TypeVar(
48 'T', bound='pika.spec.Connection.Blocked | pika.spec.Connection.Unblocked')
49
50 LOGGER = logging.getLogger(__name__)
51
52
53 class _CallbackResult:
54 """ CallbackResult is a non-thread-safe implementation for receiving
55 callback results; INTERNAL USE ONLY!
56 """
57 __slots__ = ('_value_class', '_ready', '_values')
58
59 def __init__(self, value_class: Optional[Callable[..., Any]] = None):
60 """
61 :param callable value_class: only needed if the CallbackResult
62 instance will be used with
63 `set_value_once` and `append_element`.
64 *args and **kwargs of the value setter
65 methods will be passed to this class.
66
67 """
68 self._value_class = value_class
69 self._ready: bool = None # type: ignore
70 self._values: Optional[List[Any]] = None
71 self.reset()
72
73 def reset(self) -> None:
74 """Reset value, but not _value_class"""
75 self._ready = False
76 self._values = None
77
78 def __bool__(self) -> bool:
79 """Called by python runtime to implement truth value testing and the
80 built-in operation bool()
81 """
82 return self.is_ready()
83
84 def __enter__(self) -> _CallbackResult:
85 """Entry into context manager that automatically resets the object
86 on exit; this usage pattern helps garbage-collection by eliminating
87 potential circular references.
88 """
89 return self
90
91 def __exit__(self, *args: Any, **kwargs: Any) -> None:
92 """Reset value"""
93 self.reset()
94
95 def is_ready(self) -> bool:
96 """
97 :returns: True if the object is in a signaled state
98 :rtype: bool
99 """
100 return self._ready
101
102 @property
103 def ready(self) -> bool:
104 """True if the object is in a signaled state"""
105 return self._ready
106
107 def signal_once(self, *_args: Any, **_kwargs: Any) -> None:
108 """Set as ready
109
110 :raises AssertionError: if result was already signalled
111 """
112 assert not self._ready, '_CallbackResult was already set'
113 self._ready = True
114
115 def set_value_once(self, *args: Any, **kwargs: Any) -> None:
116 """Set as ready with value; the value may be retrieved via the `value`
117 property getter
118
119 :raises AssertionError: if result was already set
120 """
121 self.signal_once()
122 try:
123 self._values = (self._value_class(*args, **kwargs),) # type: ignore
124 except Exception:
125 LOGGER.error(
126 "set_value_once failed: value_class=%r; args=%r; kwargs=%r",
127 self._value_class, args, kwargs)
128 raise
129
130 def append_element(self, *args: Any, **kwargs: Any) -> None:
131 """Append an element to values"""
132 assert not self._ready or isinstance(self._values, list), (
133 '_CallbackResult state is incompatible with append_element: '
134 'ready=%r; values=%r' % (self._ready, self._values))
135
136 try:
137 value = self._value_class(*args, **kwargs) # type: ignore
138 except Exception:
139 LOGGER.error(
140 "append_element failed: value_class=%r; args=%r; kwargs=%r",
141 self._value_class, args, kwargs)
142 raise
143
144 if self._values is None:
145 self._values = [value]
146 else:
147 self._values.append(value)
148
149 self._ready = True
150
151 @property
152 def value(self) -> Any:
153 """
154 :returns: a reference to the value that was set via `set_value_once`
155 :rtype: object
156 :raises AssertionError: if result was not set or value is incompatible
157 with `set_value_once`
158 """
159 assert self._ready, '_CallbackResult was not set'
160 assert isinstance(self._values, tuple) and len(self._values) == 1, (
161 '_CallbackResult value is incompatible with set_value_once: %r' %
162 (self._values,))
163
164 return self._values[0]
165
166 @property
167 def elements(self) -> List[Any]:
168 """
169 :returns: a reference to the list containing one or more elements that
170 were added via `append_element`
171 :rtype: list
172 :raises AssertionError: if result was not set or value is incompatible
173 with `append_element`
174 """
175 assert self._ready, '_CallbackResult was not set'
176 assert isinstance(self._values, list) and self._values, (
177 '_CallbackResult value is incompatible with append_element: %r' %
178 (self._values,))
179
180 return self._values
181
182
183 class _IoloopTimerContext:
184 """Context manager for registering and safely unregistering a
185 SelectConnection ioloop-based timer
186 """
187
188 def __init__(self, duration: float,
189 connection: select_connection.SelectConnection) -> None:
190 """
191 :param float duration: non-negative timer duration in seconds
192 :param select_connection.SelectConnection connection:
193 """
194 assert hasattr(connection, '_adapter_call_later'), connection
195 self._duration = duration
196 self._connection = connection
197 self._callback_result = _CallbackResult()
198 self._timer_handle: object = None
199
200 def __enter__(self) -> _IoloopTimerContext:
201 """Register a timer"""
202 self._timer_handle = self._connection._adapter_call_later(
203 self._duration, self._callback_result.signal_once)
204 return self
205
206 def __exit__(self, *_args: Any, **_kwargs: Any) -> None:
207 """Unregister timer if it hasn't fired yet"""
208 if not self._callback_result:
209 self._connection._adapter_remove_timeout(self._timer_handle)
210 self._timer_handle = None
211
212 def is_ready(self) -> bool:
213 """
214 :returns: True if timer has fired, False otherwise
215 :rtype: bool
216 """
217 return self._callback_result.is_ready()
218
219
220 class _TimerEvt:
221 """Represents a timer created via `BlockingConnection.call_later`"""
222 __slots__ = ('timer_id', '_callback')
223
224 def __init__(self, callback: Callable[..., None]):
225 """
226 :param callback: see callback in `BlockingConnection.call_later`
227 """
228 self._callback = callback
229
230 # Will be set to timer id returned from the underlying implementation's
231 # `_adapter_call_later` method
232 self.timer_id: Optional[object] = None
233
234 def __repr__(self) -> str:
235 return '<{} timer_id={} callback={}>'.format(self.__class__.__name__,
236 self.timer_id,
237 self._callback)
238
239 def dispatch(self) -> None:
240 """Dispatch the user's callback method"""
241 LOGGER.debug('_TimerEvt.dispatch: invoking callback=%r', self._callback)
242 self._callback()
243
244
245 class _ConnectionBlockedUnblockedEvtBase(Generic[T]):
246 """Base class for `_ConnectionBlockedEvt` and `_ConnectionUnblockedEvt`"""
247 __slots__ = ('_callback', '_method_frame')
248
249 def __init__(self, callback: Callable[[pika.frame.Method[T]], None],
250 method_frame: pika.frame.Method[T]) -> None:
251 """
252 :param callback: see callback parameter in
253 `BlockingConnection.add_on_connection_blocked_callback` and
254 `BlockingConnection.add_on_connection_unblocked_callback`
255 :param pika.frame.Method method_frame: with method_frame.method of type
256 `pika.spec.Connection.Blocked` or `pika.spec.Connection.Unblocked`
257 """
258 self._callback = callback
259 self._method_frame = method_frame
260
261 def __repr__(self) -> str:
262 return '<{} callback={}, frame={}>'.format(self.__class__.__name__,
263 self._callback,
264 self._method_frame)
265
266 def dispatch(self) -> None:
267 """Dispatch the user's callback method"""
268 self._callback(self._method_frame)
269
270
271 class _ConnectionBlockedEvt(_ConnectionBlockedUnblockedEvtBase):
272 """Represents a Connection.Blocked notification from RabbitMQ broker`"""
273
274
275 class _ConnectionUnblockedEvt(_ConnectionBlockedUnblockedEvtBase):
276 """Represents a Connection.Unblocked notification from RabbitMQ broker`"""
277
278
279 class BlockingConnection:
280 """The BlockingConnection creates a layer on top of Pika's asynchronous core
281 providing methods that will block until their expected response has
282 returned. Due to the asynchronous nature of the `Basic.Deliver` and
283 `Basic.Return` calls from RabbitMQ to your application, you can still
284 implement continuation-passing style asynchronous methods if you'd like to
285 receive messages from RabbitMQ using
286 :meth:`basic_consume <BlockingChannel.basic_consume>` or if you want to be
287 notified of a delivery failure when using
288 :meth:`basic_publish <BlockingChannel.basic_publish>`.
289
290 For more information about communicating with the blocking_connection
291 adapter, be sure to check out the
292 :class:`BlockingChannel <BlockingChannel>` class which implements the
293 :class:`Channel <pika.channel.Channel>` based communication for the
294 blocking_connection adapter.
295
296 To prevent recursion/reentrancy, the blocking connection and channel
297 implementations queue asynchronously-delivered events received
298 in nested context (e.g., while waiting for `BlockingConnection.channel` or
299 `BlockingChannel.queue_declare` to complete), dispatching them synchronously
300 once nesting returns to the desired context. This concerns all callbacks,
301 such as those registered via `BlockingConnection.call_later`,
302 `BlockingConnection.add_on_connection_blocked_callback`,
303 `BlockingConnection.add_on_connection_unblocked_callback`,
304 `BlockingChannel.basic_consume`, etc.
305
306 Blocked Connection deadlock avoidance: when RabbitMQ becomes low on
307 resources, it emits Connection.Blocked (AMQP extension) to the client
308 connection when client makes a resource-consuming request on that connection
309 or its channel (e.g., `Basic.Publish`); subsequently, RabbitMQ suspsends
310 processing requests from that connection until the affected resources are
311 restored. See https://www.rabbitmq.com/connection-blocked.html. This
312 may impact `BlockingConnection` and `BlockingChannel` operations in a
313 way that users might not be expecting. For example, if the user dispatches
314 `BlockingChannel.basic_publish` in non-publisher-confirmation mode while
315 RabbitMQ is in this low-resource state followed by a synchronous request
316 (e.g., `BlockingConnection.channel`, `BlockingChannel.consume`,
317 `BlockingChannel.basic_consume`, etc.), the synchronous request will block
318 indefinitely (until Connection.Unblocked) waiting for RabbitMQ to reply. If
319 the blocked state persists for a long time, the blocking operation will
320 appear to hang. In this state, `BlockingConnection` instance and its
321 channels will not dispatch user callbacks. SOLUTION: To break this potential
322 deadlock, applications may configure the `blocked_connection_timeout`
323 connection parameter when instantiating `BlockingConnection`. Upon blocked
324 connection timeout, this adapter will raise ConnectionBlockedTimeout
325 exception`. See `pika.connection.ConnectionParameters` documentation to
326 learn more about the `blocked_connection_timeout` configuration.
327
328 """
329 # Connection-closing callback args
330 _OnClosedArgs = namedtuple( # type: ignore[name-match]
331 'BlockingConnection__OnClosedArgs', 'connection error')
332
333 # Channel-opened callback args
334 _OnChannelOpenedArgs = namedtuple( # type: ignore[name-match]
335 'BlockingConnection__OnChannelOpenedArgs', 'channel')
336
337 def __init__(
338 self,
339 parameters: Optional[
340 Union[pika.connection.Parameters,
341 Sequence[pika.connection.Parameters]]] = None,
342 _impl_class: Optional[select_connection.SelectConnection] = None
343 ) -> None:
344 """Create a new instance of the Connection object.
345
346 :param None | pika.connection.Parameters | sequence parameters:
347 Connection parameters instance or non-empty sequence of them. If
348 None, a `pika.connection.Parameters` instance will be created with
349 default settings. See `pika.AMQPConnectionWorkflow` for more
350 details about multiple parameter configurations and retries.
351 :param _impl_class: for tests/debugging only; implementation class;
352 None=default
353
354 :raises RuntimeError:
355
356 """
357 # Used for mutual exclusion to avoid race condition between
358 # BlockingConnection._cleanup() and another thread calling
359 # BlockingConnection.add_callback_threadsafe() against a closed
360 # ioloop.
361 self._cleanup_mutex = threading.Lock()
362
363 # Used by the _acquire_event_dispatch decorator; when already greater
364 # than 0, event dispatch is already acquired higher up the call stack
365 self._event_dispatch_suspend_depth = 0
366
367 # Connection-specific events that are ready for dispatch: _TimerEvt,
368 # _ConnectionBlockedEvt, _ConnectionUnblockedEvt
369 self._ready_events: deque[Any] = deque()
370
371 # Channel numbers of channels that are requesting a call to their
372 # BlockingChannel._dispatch_events method; See
373 # `_request_channel_dispatch`
374 self._channels_pending_dispatch: Set[int] = set()
375
376 # Receives on_close_callback args from Connection
377 self._closed_result = _CallbackResult(self._OnClosedArgs)
378
379 # Perform connection workflow
380 self._impl: select_connection.SelectConnection = None # type: ignore # so that attribute is created in case below raises
381 self._impl = self._create_connection(parameters, _impl_class)
382 self._impl.add_on_close_callback(self._closed_result.set_value_once)
383
384 def __repr__(self) -> str:
385 return '<{} impl={!r}>'.format(self.__class__.__name__, self._impl)
386
387 def __enter__(self) -> BlockingConnection:
388 # Prepare `with` context
389 return self
390
391 def __exit__(self, exc_type: Exception, value: TracebackException,
392 traceback: TracebackType) -> None:
393 # Close connection after `with` context
394 if self.is_open:
395 self.close()
396
397 def _cleanup(self) -> None:
398 """Clean up members that might inhibit garbage collection
399
400 """
401 with self._cleanup_mutex:
402 if self._impl is not None:
403 self._impl.ioloop.close()
404 self._ready_events.clear()
405 self._closed_result.reset()
406
407 @contextlib.contextmanager
408 def _acquire_event_dispatch(self) -> Generator[bool, Any, None]:
409 """ Context manager that controls access to event dispatcher for
410 preventing reentrancy.
411
412 The "as" value is True if the managed code block owns the event
413 dispatcher and False if caller higher up in the call stack already owns
414 it. Only managed code that gets ownership (got True) is permitted to
415 dispatch
416 """
417 try:
418 # __enter__ part
419 self._event_dispatch_suspend_depth += 1
420 yield self._event_dispatch_suspend_depth == 1
421 finally:
422 # __exit__ part
423 self._event_dispatch_suspend_depth -= 1
424
425 def _create_connection(
426 self,
427 configs: Optional[Union[pika.connection.Parameters,
428 Sequence[pika.connection.Parameters]]] = None,
429 impl_class: Optional[select_connection.SelectConnection] = None
430 ) -> select_connection.SelectConnection:
431 """Run connection workflow, blocking until it completes.
432
433 :param None | pika.connection.Parameters | sequence configs: Connection
434 parameters instance or non-empty sequence of them.
435 :param None | SelectConnection impl_class: for tests/debugging only;
436 implementation class;
437
438 :rtype: impl_class
439
440 :raises: exception on failure
441 """
442
443 if configs is None:
444 configs = (pika.connection.Parameters(),)
445
446 if isinstance(configs, pika.connection.Parameters):
447 configs = (configs,)
448
449 if not configs:
450 raise ValueError('Expected a non-empty sequence of connection '
451 'parameters, but got {!r}.'.format(configs))
452
453 # Connection workflow completion args
454 # `result` may be an instance of connection on success or exception on
455 # failure.
456 on_cw_done_result = _CallbackResult(
457 namedtuple('BlockingConnection_OnConnectionWorkflowDoneArgs',
458 'result'))
459
460 impl_class = impl_class or select_connection.SelectConnection # type: ignore
461
462 ioloop = select_connection.IOLoop()
463
464 ioloop.activate_poller()
465 try:
466 impl_class.create_connection( # type: ignore
467 configs,
468 on_done=on_cw_done_result.set_value_once,
469 custom_ioloop=ioloop)
470
471 while not on_cw_done_result.ready:
472 ioloop.poll()
473 ioloop.process_timeouts()
474
475 if isinstance(on_cw_done_result.value.result, BaseException):
476 error = on_cw_done_result.value.result
477 LOGGER.error('Connection workflow failed: %r', error)
478 raise self._reap_last_connection_workflow_error(error)
479 else:
480 LOGGER.info('Connection workflow succeeded: %r',
481 on_cw_done_result.value.result)
482 return on_cw_done_result.value.result
483 except Exception:
484 LOGGER.exception('Error in _create_connection().')
485 ioloop.close()
486 self._cleanup()
487 raise
488
489 @staticmethod
490 def _reap_last_connection_workflow_error(
491 error: BaseException) -> BaseException:
492 """Extract exception value from the last connection attempt
493
494 :param Exception error: error passed by the `AMQPConnectionWorkflow`
495 completion callback.
496
497 :returns: Exception value from the last connection attempt
498 :rtype: Exception
499 """
500 if isinstance(error, connection_workflow.AMQPConnectionWorkflowFailed):
501 # Extract exception value from the last connection attempt
502 error = error.exceptions[-1]
503 if isinstance(error,
504 connection_workflow.AMQPConnectorSocketConnectError):
505 error = exceptions.AMQPConnectionError(error)
506 elif isinstance(error,
507 connection_workflow.AMQPConnectorPhaseErrorBase):
508 error = error.exception
509
510 return error
511
512 def _flush_output(self, *waiters: Callable[[], bool]) -> None:
513 """ Flush output and process input while waiting for any of the given
514 callbacks to return true. The wait is aborted upon connection-close.
515 Otherwise, processing continues until the output is flushed AND at least
516 one of the callbacks returns true. If there are no callbacks, then
517 processing ends when all output is flushed.
518
519 :param waiters: sequence of zero or more callables taking no args and
520 returning true when it's time to stop processing.
521 Their results are OR'ed together.
522 :raises: exceptions passed by impl if opening of connection fails or
523 connection closes.
524 """
525 if self.is_closed:
526 raise exceptions.ConnectionWrongStateError()
527
528 # Conditions for terminating the processing loop:
529 # connection closed
530 # OR
531 # empty outbound buffer and no waiters
532 # OR
533 # empty outbound buffer and any waiter is ready
534 def is_done():
535 return (self._closed_result.ready or
536 ((not self._impl._transport or
537 self._impl._get_write_buffer_size() == 0) and
538 (not waiters or any(ready() for ready in waiters))))
539
540 # Process I/O until our completion condition is satisfied
541 while not is_done():
542 self._impl.ioloop.poll()
543 self._impl.ioloop.process_timeouts()
544
545 if self._closed_result.ready:
546 try:
547 if not isinstance(self._closed_result.value.error,
548 exceptions.ConnectionClosedByClient):
549 LOGGER.error('Unexpected connection close detected: %r',
550 self._closed_result.value.error)
551 raise self._closed_result.value.error
552 else:
553 LOGGER.info('User-initiated close: result=%r',
554 self._closed_result.value)
555 finally:
556 self._cleanup()
557
558 def _request_channel_dispatch(self, channel_number: int) -> None:
559 """Called by BlockingChannel instances to request a call to their
560 _dispatch_events method or to terminate `process_data_events`;
561 BlockingConnection will honor these requests from a safe context.
562
563 :param int channel_number: positive channel number to request a call
564 to the channel's `_dispatch_events`; a negative channel number to
565 request termination of `process_data_events`
566 """
567 self._channels_pending_dispatch.add(channel_number)
568
569 def _dispatch_channel_events(self) -> None:
570 """Invoke the `_dispatch_events` method on open channels that requested
571 it
572 """
573 if not self._channels_pending_dispatch:
574 return
575
576 with self._acquire_event_dispatch() as dispatch_acquired:
577 if not dispatch_acquired:
578 # Nested dispatch or dispatch blocked higher in call stack
579 return
580
581 candidates = list(self._channels_pending_dispatch)
582 self._channels_pending_dispatch.clear()
583
584 for channel_number in candidates:
585 if channel_number < 0:
586 # This was meant to terminate process_data_events
587 continue
588
589 try:
590 impl_channel = self._impl._channels[channel_number]
591 except KeyError:
592 continue
593
594 if impl_channel.is_open:
595 impl_channel._get_cookie()._dispatch_events()
596
597 def _on_timer_ready(self, evt: _TimerEvt) -> None:
598 """Handle expiry of a timer that was registered via
599 `_adapter_call_later()`
600
601 :param _TimerEvt evt:
602
603 """
604 self._ready_events.append(evt)
605
606 def _on_threadsafe_callback(self, user_callback: Callable[[],
607 None]) -> None:
608 """Handle callback that was registered via
609 `self._impl._adapter_add_callback_threadsafe`.
610
611 :param user_callback: callback passed to our
612 `add_callback_threadsafe` by the application.
613
614 """
615 # Turn it into a 0-delay timeout to take advantage of our existing logic
616 # that deals with reentrancy
617 self.call_later(0, user_callback)
618
619 def _on_connection_blocked(
620 self, user_callback: Callable[
621 [pika.frame.Method[pika.spec.Connection.Blocked]],
622 None], _impl: select_connection.SelectConnection,
623 method_frame: pika.frame.Method[pika.spec.Connection.Blocked]
624 ) -> None:
625 """Handle Connection.Blocked notification from RabbitMQ broker
626
627 :param callable user_callback: callback passed to
628 `add_on_connection_blocked_callback`
629 :param select_connection.SelectConnection _impl:
630 :param pika.frame.Method method_frame: method frame having `method`
631 member of type `pika.spec.Connection.Blocked`
632 """
633 self._ready_events.append(
634 _ConnectionBlockedEvt(user_callback, method_frame))
635
636 def _on_connection_unblocked(
637 self, user_callback: Callable[
638 [pika.frame.Method[pika.spec.Connection.Unblocked]],
639 None], _impl: select_connection.SelectConnection,
640 method_frame: pika.frame.Method[pika.spec.Connection.Unblocked]
641 ) -> None:
642 """Handle Connection.Unblocked notification from RabbitMQ broker
643
644 :param callable user_callback: callback passed to
645 `add_on_connection_unblocked_callback`
646 :param select_connection.SelectConnection _impl:
647 :param pika.frame.Method method_frame: method frame having `method`
648 member of type `pika.spec.Connection.Blocked`
649 """
650 self._ready_events.append(
651 _ConnectionUnblockedEvt(user_callback, method_frame))
652
653 def _dispatch_connection_events(self) -> None:
654 """Dispatch ready connection events"""
655 if not self._ready_events:
656 return
657
658 with self._acquire_event_dispatch() as dispatch_acquired:
659 if not dispatch_acquired:
660 # Nested dispatch or dispatch blocked higher in call stack
661 return
662
663 # Limit dispatch to the number of currently ready events to avoid
664 # getting stuck in this loop
665 for _ in range(len(self._ready_events)):
666 try:
667 evt = self._ready_events.popleft()
668 except IndexError:
669 # Some events (e.g., timers) must have been cancelled
670 break
671
672 evt.dispatch()
673
674 def add_on_connection_blocked_callback(
675 self, callback: Callable[[
676 pika.connection.Connection, pika.frame.Method[pika.spec.Connection.
677 Blocked]
678 ], None]
679 ) -> None:
680 """RabbitMQ AMQP extension - Add a callback to be notified when the
681 connection gets blocked (`Connection.Blocked` received from RabbitMQ)
682 due to the broker running low on resources (memory or disk). In this
683 state RabbitMQ suspends processing incoming data until the connection
684 is unblocked, so it's a good idea for publishers receiving this
685 notification to suspend publishing until the connection becomes
686 unblocked.
687
688 NOTE: due to the blocking nature of BlockingConnection, if it's sending
689 outbound data while the connection is/becomes blocked, the call may
690 remain blocked until the connection becomes unblocked, if ever. You
691 may use `ConnectionParameters.blocked_connection_timeout` to abort a
692 BlockingConnection method call with an exception when the connection
693 remains blocked longer than the given timeout value.
694
695 See also `Connection.add_on_connection_unblocked_callback()`
696
697 See also `ConnectionParameters.blocked_connection_timeout`.
698
699 :param callable callback: Callback to call on `Connection.Blocked`,
700 having the signature `callback(connection, pika.frame.Method)`,
701 where connection is the `BlockingConnection` instance and the method
702 frame's `method` member is of type `pika.spec.Connection.Blocked`
703
704 """
705 self._impl.add_on_connection_blocked_callback(
706 functools.partial(self._on_connection_blocked,
707 functools.partial(callback,
708 self))) # type: ignore
709
710 def add_on_connection_unblocked_callback(
711 self, callback: Callable[[
712 pika.connection.Connection, pika.frame.Method[pika.spec.Connection.
713 Unblocked]
714 ], None]
715 ) -> None:
716 """RabbitMQ AMQP extension - Add a callback to be notified when the
717 connection gets unblocked (`Connection.Unblocked` frame is received from
718 RabbitMQ) letting publishers know it's ok to start publishing again.
719
720 :param callable callback: Callback to call on Connection.Unblocked`,
721 having the signature `callback(connection, pika.frame.Method)`,
722 where connection is the `BlockingConnection` instance and the method
723 frame's `method` member is of type `pika.spec.Connection.Unblocked`
724
725 """
726 self._impl.add_on_connection_unblocked_callback(
727 functools.partial(self._on_connection_unblocked,
728 functools.partial(callback,
729 self))) # type: ignore
730
731 def call_later(self, delay: float, callback: Callable[[], None]) -> int:
732 """Create a single-shot timer to fire after delay seconds. Do not
733 confuse with Tornado's timeout where you pass in the time you want to
734 have your callback called. Only pass in the seconds until it's to be
735 called.
736
737 NOTE: the timer callbacks are dispatched only in the scope of
738 specially-designated methods: see
739 `BlockingConnection.process_data_events()` and
740 `BlockingChannel.start_consuming()`.
741
742 :param float delay: The number of seconds to wait to call callback
743 :param callable callback: The callback method with the signature
744 callback()
745 :returns: Opaque timer id
746 :rtype: int
747
748 """
749 validators.require_callback(callback)
750
751 evt = _TimerEvt(callback=callback)
752 timer_id = self._impl._adapter_call_later(
753 delay, functools.partial(self._on_timer_ready, evt))
754 evt.timer_id = timer_id
755
756 return timer_id # type: ignore
757
758 def add_callback_threadsafe(self, callback: Callable[..., None]) -> None:
759 """Requests a call to the given function as soon as possible in the
760 context of this connection's thread.
761
762 NOTE: This is the only thread-safe method in `BlockingConnection`. All
763 other manipulations of `BlockingConnection` must be performed from the
764 connection's thread.
765
766 NOTE: the callbacks are dispatched only in the scope of
767 specially-designated methods: see
768 `BlockingConnection.process_data_events()` and
769 `BlockingChannel.start_consuming()`.
770
771 For example, a thread may request a call to the
772 `BlockingChannel.basic_ack` method of a `BlockingConnection` that is
773 running in a different thread via::
774
775 connection.add_callback_threadsafe(
776 functools.partial(channel.basic_ack, delivery_tag=...))
777
778 NOTE: if you know that the requester is running on the same thread as
779 the connection it is more efficient to use the
780 `BlockingConnection.call_later()` method with a delay of 0.
781
782 :param callable callback: The callback method; must be callable
783 :raises pika.exceptions.ConnectionWrongStateError: if connection is
784 closed
785 """
786 with self._cleanup_mutex:
787 # NOTE: keep in mind that we may be called from another thread and
788 # this mutex only synchronizes us with our connection cleanup logic,
789 # so a simple check for "is_closed" is pretty much all we're allowed
790 # to do here besides calling the only thread-safe method
791 # _adapter_add_callback_threadsafe().
792 if self.is_closed:
793 raise exceptions.ConnectionWrongStateError(
794 'BlockingConnection.add_callback_threadsafe() called on '
795 'closed or closing connection.')
796
797 self._impl._adapter_add_callback_threadsafe(
798 functools.partial(self._on_threadsafe_callback, callback))
799
800 def remove_timeout(self, timeout_id: int) -> None:
801 """Remove a timer if it's still in the timeout stack
802
803 :param timeout_id: The opaque timer id to remove
804
805 """
806 # Remove from the impl's timeout stack
807 self._impl._adapter_remove_timeout(timeout_id)
808
809 # Remove from ready events, if the timer fired already
810 for i, evt in enumerate(self._ready_events):
811 if isinstance(evt, _TimerEvt) and evt.timer_id == timeout_id:
812 index_to_remove = i
813 break
814 else:
815 # Not found
816 return
817
818 del self._ready_events[index_to_remove]
819
820 def update_secret(self, new_secret: str, reason: str) -> None:
821 """RabbitMQ AMQP extension - This method updates the secret used to authenticate this connection.
822 It is used when secrets have an expiration date and need to be renewed, like OAuth 2 tokens.
823
824 :param string new_secret: The new secret
825 :param string reason: The reason for the secret update
826
827 :raises pika.exceptions.ConnectionWrongStateError: if connection is
828 not open.
829 """
830
831 result = _CallbackResult()
832 self._impl.update_secret(new_secret, reason, result.signal_once)
833 self._flush_output(result.is_ready)
834
835 def close(self,
836 reply_code: int = 200,
837 reply_text: str = 'Normal shutdown') -> None:
838 """Disconnect from RabbitMQ. If there are any open channels, it will
839 attempt to close them prior to fully disconnecting. Channels which
840 have active consumers will attempt to send a Basic.Cancel to RabbitMQ
841 to cleanly stop the delivery of messages prior to closing the channel.
842
843 :param int reply_code: The code number for the close
844 :param str reply_text: The text reason for the close
845
846 :raises pika.exceptions.ConnectionWrongStateError: if called on a closed
847 connection (NEW in v1.0.0)
848 """
849 if not self.is_open:
850 msg = '{}.close({}, {!r}) called on closed connection.'.format(
851 self.__class__.__name__, reply_code, reply_text)
852 LOGGER.error(msg)
853 raise exceptions.ConnectionWrongStateError(msg)
854
855 LOGGER.info('Closing connection (%s): %s', reply_code, reply_text)
856
857 # Close channels that remain opened
858 for impl_channel in list(self._impl._channels.values()):
859 channel = impl_channel._get_cookie()
860 if channel.is_open:
861 try:
862 channel.close(reply_code, reply_text)
863 except exceptions.ChannelClosed as exc:
864 # Log and suppress broker-closed channel
865 LOGGER.warning(
866 'Got ChannelClosed while closing channel '
867 'from connection.close: %r', exc)
868
869 # Close the connection
870 self._impl.close(reply_code, reply_text)
871
872 self._flush_output(self._closed_result.is_ready)
873
874 def process_data_events(self, time_limit: Optional[float] = 0) -> None:
875 """Will make sure that data events are processed. Dispatches timer and
876 channel callbacks if not called from the scope of BlockingConnection or
877 BlockingChannel callback. Your app can block on this method. If your
878 application maintains a long-lived publisher connection, this method
879 should be called periodically in order to respond to heartbeats and other
880 data events. See `examples/long_running_publisher.py` for an example.
881
882 :param float time_limit: suggested upper bound on processing time in
883 seconds. The actual blocking time depends on the granularity of the
884 underlying ioloop. Zero means return as soon as possible. None means
885 there is no limit on processing time and the function will block
886 until I/O produces actionable events. Defaults to 0 for backward
887 compatibility. This parameter is NEW in pika 0.10.0.
888 """
889 with self._acquire_event_dispatch() as dispatch_acquired:
890 # Check if we can actually process pending events
891 def common_terminator():
892 return bool(
893 dispatch_acquired and
894 (self._channels_pending_dispatch or self._ready_events))
895
896 if time_limit is None:
897 self._flush_output(common_terminator)
898 else:
899 with _IoloopTimerContext(time_limit, self._impl) as timer:
900 self._flush_output(timer.is_ready, common_terminator)
901
902 if self._ready_events:
903 self._dispatch_connection_events()
904
905 if self._channels_pending_dispatch:
906 self._dispatch_channel_events()
907
908 def sleep(self, duration: float) -> None:
909 """A safer way to sleep than calling time.sleep() directly that would
910 keep the adapter from ignoring frames sent from the broker. The
911 connection will "sleep" or block the number of seconds specified in
912 duration in small intervals.
913
914 :param float duration: The time to sleep in seconds
915
916 """
917 assert duration >= 0, duration
918
919 deadline = compat.time_now() + duration
920 time_limit = duration
921 # Process events at least once
922 while True:
923 self.process_data_events(time_limit)
924 time_limit = deadline - compat.time_now()
925 if time_limit <= 0:
926 break
927
928 def channel(self, channel_number: Optional[int] = None) -> BlockingChannel:
929 """Create a new channel with the next available channel number or pass
930 in a channel number to use. Must be non-zero if you would like to
931 specify but it is recommended that you let Pika manage the channel
932 numbers.
933
934 :rtype: pika.adapters.blocking_connection.BlockingChannel
935 """
936 with _CallbackResult(self._OnChannelOpenedArgs) as opened_args:
937 impl_channel = self._impl.channel(
938 channel_number=channel_number,
939 on_open_callback=opened_args.set_value_once)
940
941 # Create our proxy channel
942 channel = BlockingChannel(impl_channel, self)
943
944 # Link implementation channel with our proxy channel
945 impl_channel._set_cookie(channel)
946
947 # Drive I/O until Channel.Open-ok
948 channel._flush_output(opened_args.is_ready)
949
950 return channel
951
952 #
953 # Connections state properties
954 #
955
956 @property
957 def is_closed(self) -> bool:
958 """
959 Returns a boolean reporting the current connection state.
960 """
961 return self._impl.is_closed
962
963 @property
964 def is_open(self) -> bool:
965 """
966 Returns a boolean reporting the current connection state.
967 """
968 return self._impl.is_open
969
970 #
971 # Properties that reflect server capabilities for the current connection
972 #
973
974 @property
975 def basic_nack_supported(self) -> bool:
976 """Specifies if the server supports basic.nack on the active connection.
977
978 :rtype: bool
979
980 """
981 return self._impl.basic_nack
982
983 @property
984 def consumer_cancel_notify_supported(self) -> bool:
985 """Specifies if the server supports consumer cancel notification on the
986 active connection.
987
988 :rtype: bool
989
990 """
991 return self._impl.consumer_cancel_notify
992
993 @property
994 def exchange_exchange_bindings_supported(self) -> bool:
995 """Specifies if the active connection supports exchange to exchange
996 bindings.
997
998 :rtype: bool
999
1000 """
1001 return self._impl.exchange_exchange_bindings
1002
1003 @property
1004 def publisher_confirms_supported(self) -> bool:
1005 """Specifies if the active connection can use publisher confirmations.
1006
1007 :rtype: bool
1008
1009 """
1010 return self._impl.publisher_confirms
1011
1012 # Legacy property names for backward compatibility
1013 basic_nack = basic_nack_supported
1014 consumer_cancel_notify = consumer_cancel_notify_supported
1015 exchange_exchange_bindings = exchange_exchange_bindings_supported
1016 publisher_confirms = publisher_confirms_supported
1017
1018
1019 class _ChannelPendingEvt:
1020 """Base class for BlockingChannel pending events"""
1021
1022
1023 class _ConsumerDeliveryEvt(_ChannelPendingEvt):
1024 """This event represents consumer message delivery `Basic.Deliver`; it
1025 contains method, properties, and body of the delivered message.
1026 """
1027
1028 __slots__ = ('method', 'properties', 'body')
1029
1030 def __init__(self, method: pika.spec.Basic.Deliver,
1031 properties: pika.spec.BasicProperties, body: bytes) -> None:
1032 """
1033 :param spec.Basic.Deliver method: NOTE: consumer_tag and delivery_tag
1034 are valid only within source channel
1035 :param spec.BasicProperties properties: message properties
1036 :param bytes body: message body; empty string if no body
1037 """
1038 self.method = method
1039 self.properties = properties
1040 self.body = body
1041
1042
1043 class _ConsumerCancellationEvt(_ChannelPendingEvt):
1044 """This event represents server-initiated consumer cancellation delivered to
1045 client via Basic.Cancel. After receiving Basic.Cancel, there will be no
1046 further deliveries for the consumer identified by `consumer_tag` in
1047 `Basic.Cancel`
1048 """
1049
1050 __slots__ = ('method_frame',)
1051
1052 def __init__(
1053 self,
1054 method_frame: pika.frame.Method[pika.spec.Basic.Cancel]) -> None:
1055 """
1056 :param pika.frame.Method method_frame: method frame with method of type
1057 `spec.Basic.Cancel`
1058 """
1059 self.method_frame = method_frame
1060
1061 def __repr__(self) -> str:
1062 return '<{} method_frame={!r}>'.format(self.__class__.__name__,
1063 self.method_frame)
1064
1065 @property
1066 def method(self):
1067 """method of type spec.Basic.Cancel"""
1068 return self.method_frame.method
1069
1070
1071 class _ReturnedMessageEvt(_ChannelPendingEvt):
1072 """This event represents a message returned by broker via `Basic.Return`"""
1073
1074 __slots__ = ('callback', 'channel', 'method', 'properties', 'body')
1075
1076 def __init__(self, callback: Callable[[
1077 BlockingChannel, pika.spec.Basic.Return, pika.spec.
1078 BasicProperties, bytes
1079 ], None], channel: BlockingChannel, method: pika.spec.Basic.Return,
1080 properties: pika.spec.BasicProperties, body: bytes) -> None:
1081 """
1082 :param callable callback: user's callback, having the signature
1083 callback(channel, method, properties, body), where
1084 - channel: pika.Channel
1085 - method: pika.spec.Basic.Return
1086 - properties: pika.spec.BasicProperties
1087 - body: bytes
1088 :param pika.Channel channel:
1089 :param pika.spec.Basic.Return method:
1090 :param pika.spec.BasicProperties properties:
1091 :param bytes body:
1092 """
1093 self.callback = callback
1094 self.channel = channel
1095 self.method = method
1096 self.properties = properties
1097 self.body = body
1098
1099 def __repr__(self) -> str:
1100 return ('<%s callback=%r channel=%r method=%r properties=%r '
1101 'body=%.300r>') % (self.__class__.__name__, self.callback,
1102 self.channel, self.method, self.properties,
1103 self.body)
1104
1105 def dispatch(self) -> None:
1106 """Dispatch user's callback"""
1107 self.callback(self.channel, self.method, self.properties, self.body)
1108
1109
1110 class ReturnedMessage:
1111 """Represents a message returned via Basic.Return in publish-acknowledgments
1112 mode
1113 """
1114
1115 __slots__ = ('method', 'properties', 'body')
1116
1117 def __init__(self, method: pika.spec.Basic.Return,
1118 properties: pika.spec.BasicProperties, body: bytes) -> None:
1119 """
1120 :param spec.Basic.Return method:
1121 :param spec.BasicProperties properties: message properties
1122 :param bytes body: message body; empty string if no body
1123 """
1124 self.method = method
1125 self.properties = properties
1126 self.body = body
1127
1128
1129 class _ConsumerInfo:
1130 """Information about an active consumer"""
1131
1132 __slots__ = ('consumer_tag', 'auto_ack', 'on_message_callback',
1133 'alternate_event_sink', 'state')
1134
1135 # Consumer states
1136 SETTING_UP = 1
1137 ACTIVE = 2
1138 TEARING_DOWN = 3
1139 CANCELLED_BY_BROKER = 4
1140
1141 def __init__(self,
1142 consumer_tag: str,
1143 auto_ack: bool,
1144 on_message_callback: Optional[Callable[[
1145 BlockingChannel, pika.spec.Basic.Deliver, pika.spec.
1146 BasicProperties, bytes
1147 ], None]] = None,
1148 alternate_event_sink: Optional[Callable[[_ChannelPendingEvt],
1149 None]] = None):
1150 """
1151 NOTE: exactly one of callback/alternate_event_sink musts be non-None.
1152
1153 :param str consumer_tag:
1154 :param bool auto_ack: the no-ack value for the consumer
1155 :param callable on_message_callback: The function for dispatching messages to
1156 user, having the signature:
1157 on_message_callback(channel, method, properties, body)
1158 - channel: BlockingChannel
1159 - method: spec.Basic.Deliver
1160 - properties: spec.BasicProperties
1161 - body: bytes
1162 :param callable alternate_event_sink: if specified, _ConsumerDeliveryEvt
1163 and _ConsumerCancellationEvt objects will be diverted to this
1164 callback instead of being deposited in the channel's
1165 `_pending_events` container. Signature:
1166 alternate_event_sink(evt)
1167 """
1168 assert (on_message_callback is None) != (
1169 alternate_event_sink is None
1170 ), ('exactly one of on_message_callback/alternate_event_sink must be non-None',
1171 on_message_callback, alternate_event_sink)
1172 self.consumer_tag = consumer_tag
1173 self.auto_ack = auto_ack
1174 self.on_message_callback = on_message_callback
1175 self.alternate_event_sink = alternate_event_sink
1176 self.state = self.SETTING_UP
1177
1178 @property
1179 def setting_up(self) -> bool:
1180 """True if in SETTING_UP state"""
1181 return self.state == self.SETTING_UP
1182
1183 @property
1184 def active(self) -> bool:
1185 """True if in ACTIVE state"""
1186 return self.state == self.ACTIVE
1187
1188 @property
1189 def tearing_down(self) -> bool:
1190 """True if in TEARING_DOWN state"""
1191 return self.state == self.TEARING_DOWN
1192
1193 @property
1194 def cancelled_by_broker(self) -> bool:
1195 """True if in CANCELLED_BY_BROKER state"""
1196 return self.state == self.CANCELLED_BY_BROKER
1197
1198
1199 class _QueueConsumerGeneratorInfo:
1200 """Container for information about the active queue consumer generator """
1201 __slots__ = ('params', 'consumer_tag', 'pending_events')
1202
1203 def __init__(self, params: Tuple[str, bool, bool],
1204 consumer_tag: str) -> None:
1205 """
1206 :params tuple params: a three-tuple (queue, auto_ack, exclusive) that were
1207 used to create the queue consumer
1208 :param str consumer_tag: consumer tag
1209 """
1210 self.params = params
1211 self.consumer_tag = consumer_tag
1212 #self.messages = deque()
1213
1214 # Holds pending events of types _ConsumerDeliveryEvt and
1215 # _ConsumerCancellationEvt
1216 self.pending_events: deque[Any] = deque()
1217
1218 def __repr__(self) -> str:
1219 return '<{} params={!r} consumer_tag={!r}>'.format(
1220 self.__class__.__name__, self.params, self.consumer_tag)
1221
1222
1223 class BlockingChannel:
1224 """The BlockingChannel implements blocking semantics for most things that
1225 one would use callback-passing-style for with the
1226 :py:class:`~pika.channel.Channel` class. In addition,
1227 the `BlockingChannel` class implements a :term:`generator` that allows
1228 you to :doc:`consume messages </examples/blocking_consumer_generator>`
1229 without using callbacks.
1230
1231 Example of creating a BlockingChannel::
1232
1233 import pika
1234
1235 # Create our connection object
1236 connection = pika.BlockingConnection()
1237
1238 # The returned object will be a synchronous channel
1239 channel = connection.channel()
1240
1241 """
1242
1243 # Used as value_class with _CallbackResult for receiving Basic.GetOk args
1244 _RxMessageArgs = namedtuple( # type: ignore
1245 'BlockingChannel__RxMessageArgs',
1246 [
1247 'channel', # implementation pika.Channel instance
1248 'method', # Basic.GetOk
1249 'properties', # pika.spec.BasicProperties
1250 'body' # str, unicode, or bytes (python 3.x)
1251 ])
1252
1253 # For use as value_class with any _CallbackResult that expects method_frame
1254 # as the only arg
1255 _MethodFrameCallbackResultArgs = namedtuple( # type: ignore
1256 'BlockingChannel__MethodFrameCallbackResultArgs', 'method_frame')
1257
1258 # Broker's basic-ack/basic-nack args when delivery confirmation is enabled;
1259 # may concern a single or multiple messages
1260 _OnMessageConfirmationReportArgs = namedtuple( # type: ignore
1261 'BlockingChannel__OnMessageConfirmationReportArgs', 'method_frame')
1262
1263 # For use as value_class with _CallbackResult expecting Channel.Flow
1264 # confirmation.
1265 _FlowOkCallbackResultArgs = namedtuple( # type: ignore
1266 'BlockingChannel__FlowOkCallbackResultArgs',
1267 'active' # True if broker will start or continue sending; False if not
1268 )
1269
1270 _CONSUMER_CANCELLED_CB_KEY = 'blocking_channel_consumer_cancelled'
1271
1272 def __init__(self, channel_impl: pika.channel.Channel,
1273 connection: BlockingConnection):
1274 """Create a new instance of the Channel
1275
1276 :param pika.channel.Channel channel_impl: Channel implementation object
1277 as returned from SelectConnection.channel()
1278 :param BlockingConnection connection: The connection object
1279
1280 """
1281 self._impl = channel_impl
1282 self._connection = connection
1283
1284 # A mapping of consumer tags to _ConsumerInfo for active consumers
1285 self._consumer_infos: Dict[Any, Any] = dict()
1286
1287 # Queue consumer generator generator info of type
1288 # _QueueConsumerGeneratorInfo created by BlockingChannel.consume
1289 self._queue_consumer_generator: Optional[
1290 _QueueConsumerGeneratorInfo] = None
1291
1292 # Whether RabbitMQ delivery confirmation has been enabled
1293 self._delivery_confirmation = False
1294
1295 # Receives message delivery confirmation report (Basic.ack or
1296 # Basic.nack) from broker when delivery confirmations are enabled
1297 self._message_confirmation_result = _CallbackResult(
1298 self._OnMessageConfirmationReportArgs)
1299
1300 # deque of pending events: _ConsumerDeliveryEvt and
1301 # _ConsumerCancellationEvt objects that will be returned by
1302 # `BlockingChannel.get_event()`
1303 self._pending_events: deque[Any] = deque()
1304
1305 # Holds a ReturnedMessage object representing a message received via
1306 # Basic.Return in publisher-acknowledgments mode.
1307 self._puback_return: Optional[ReturnedMessage] = None
1308
1309 # self._on_channel_closed() saves the reason exception here
1310 self._closing_reason = None # type: None | Exception
1311
1312 # Receives Basic.ConsumeOk reply from server
1313 self._basic_consume_ok_result = _CallbackResult()
1314
1315 # Receives args from Basic.GetEmpty response
1316 # https://www.rabbitmq.com/amqp-0-9-1-reference.html#basic.get
1317 self._basic_getempty_result = _CallbackResult(
1318 self._MethodFrameCallbackResultArgs)
1319
1320 self._impl.add_on_cancel_callback(self._on_consumer_cancelled_by_broker)
1321
1322 self._impl.add_callback(self._basic_consume_ok_result.signal_once,
1323 replies=[pika.spec.Basic.ConsumeOk],
1324 one_shot=False)
1325
1326 self._impl.add_on_close_callback(self._on_channel_closed)
1327
1328 self._impl.add_callback(self._basic_getempty_result.set_value_once,
1329 replies=[pika.spec.Basic.GetEmpty],
1330 one_shot=False)
1331
1332 LOGGER.info("Created channel=%s", self.channel_number)
1333
1334 def __int__(self) -> int:
1335 """Return the channel object as its channel number
1336
1337 NOTE: inherited from legacy BlockingConnection; might be error-prone;
1338 use `channel_number` property instead.
1339
1340 :rtype: int
1341
1342 """
1343 return self.channel_number
1344
1345 def __repr__(self) -> str:
1346 return '<{} impl={!r}>'.format(self.__class__.__name__, self._impl)
1347
1348 def __enter__(self) -> BlockingChannel:
1349 return self
1350
1351 def __exit__(self, exc_type: Exception, value: TracebackException,
1352 traceback: TracebackType) -> None:
1353 if self.is_open:
1354 self.close()
1355
1356 def _cleanup(self) -> None:
1357 """Clean up members that might inhibit garbage collection"""
1358 self._message_confirmation_result.reset()
1359 self._pending_events = deque()
1360 self._consumer_infos = dict()
1361 self._queue_consumer_generator = None
1362
1363 @property
1364 def channel_number(self) -> int:
1365 """Channel number"""
1366 return self._impl.channel_number
1367
1368 @property
1369 def connection(self) -> BlockingConnection:
1370 """The channel's BlockingConnection instance"""
1371 return self._connection
1372
1373 @property
1374 def is_closed(self) -> bool:
1375 """Returns True if the channel is closed.
1376
1377 :rtype: bool
1378
1379 """
1380 return self._impl.is_closed
1381
1382 @property
1383 def is_open(self) -> bool:
1384 """Returns True if the channel is open.
1385
1386 :rtype: bool
1387
1388 """
1389 return self._impl.is_open
1390
1391 @property
1392 def consumer_tags(self) -> List[str]:
1393 """Property method that returns a list of consumer tags for active
1394 consumers
1395
1396 :rtype: list
1397
1398 """
1399 return list(self._consumer_infos.keys())
1400
1401 _ALWAYS_READY_WAITERS = ((lambda: True),)
1402
1403 def _flush_output(self, *waiters: Callable[[], bool]):
1404 """ Flush output and process input while waiting for any of the given
1405 callbacks to return true. The wait is aborted upon channel-close or
1406 connection-close.
1407 Otherwise, processing continues until the output is flushed AND at least
1408 one of the callbacks returns true. If there are no callbacks, then
1409 processing ends when all output is flushed.
1410
1411 :param waiters: sequence of zero or more callables taking no args and
1412 returning true when it's time to stop processing.
1413 Their results are OR'ed together. An empty sequence is
1414 treated as equivalent to a waiter always returning true.
1415 """
1416 if self.is_closed:
1417 self._impl._raise_if_not_open()
1418
1419 if not waiters:
1420 waiters = self._ALWAYS_READY_WAITERS
1421
1422 self._connection._flush_output(lambda: self.is_closed, *waiters)
1423
1424 if self.is_closed and isinstance(self._closing_reason,
1425 exceptions.ChannelClosedByBroker):
1426 raise self._closing_reason # pylint: disable=E0702
1427
1428 def _on_puback_message_returned(self, channel: pika.channel.Channel,
1429 method: pika.spec.Basic.Return,
1430 properties: pika.spec.BasicProperties,
1431 body: bytes) -> None:
1432 """Called as the result of Basic.Return from broker in
1433 publisher-acknowledgements mode. Saves the info as a ReturnedMessage
1434 instance in self._puback_return.
1435
1436 :param pika.Channel channel: our self._impl channel
1437 :param pika.spec.Basic.Return method:
1438 :param pika.spec.BasicProperties properties: message properties
1439 :param bytes body: returned message body; empty string if no body
1440 """
1441 assert channel is self._impl, (channel.channel_number,
1442 self.channel_number)
1443
1444 assert isinstance(method, pika.spec.Basic.Return), method
1445 assert isinstance(properties, pika.spec.BasicProperties), (properties)
1446
1447 LOGGER.warning(
1448 "Published message was returned: _delivery_confirmation=%s; "
1449 "channel=%s; method=%r; properties=%r; body_size=%d; "
1450 "body_prefix=%.255r", self._delivery_confirmation,
1451 channel.channel_number, method, properties,
1452 len(body) if body is not None else None, body)
1453
1454 self._puback_return = ReturnedMessage(method, properties, body)
1455
1456 def _add_pending_event(self, evt: _ChannelPendingEvt):
1457 """Append an event to the channel's list of events that are ready for
1458 dispatch to user and signal our connection that this channel is ready
1459 for event dispatch
1460
1461 :param _ChannelPendingEvt evt: an event derived from _ChannelPendingEvt
1462 """
1463 self._pending_events.append(evt)
1464 self.connection._request_channel_dispatch(self.channel_number)
1465
1466 def _on_channel_closed(self, _channel: pika.channel.Channel,
1467 reason: Exception) -> None:
1468 """Callback from impl notifying us that the channel has been closed.
1469 This may be as the result of user-, broker-, or internal connection
1470 clean-up initiated closing or meta-closing of the channel.
1471
1472 If it resulted from receiving `Channel.Close` from broker, we will
1473 expedite waking up of the event subsystem so that it may respond by
1474 raising `ChannelClosed` from user's context.
1475
1476 NOTE: We can't raise exceptions in callbacks in order to protect
1477 the integrity of the underlying implementation. BlockingConnection's
1478 underlying asynchronous connection adapter (SelectConnection) uses
1479 callbacks to communicate with us. If BlockingConnection leaks exceptions
1480 back into the I/O loop or the asynchronous connection adapter, we
1481 interrupt their normal workflow and introduce a high likelihood of state
1482 inconsistency.
1483
1484 See `pika.Channel.add_on_close_callback()` for additional documentation.
1485
1486 :param pika.Channel _channel: (unused)
1487 :param Exception reason:
1488
1489 """
1490 LOGGER.debug('_on_channel_closed: %r; %r', reason, self)
1491
1492 self._closing_reason = reason
1493
1494 if isinstance(reason, exceptions.ChannelClosedByBroker):
1495 self._cleanup()
1496
1497 # Request urgent termination of `process_data_events()`, in case
1498 # it's executing or next time it will execute
1499 self.connection._request_channel_dispatch(-self.channel_number)
1500
1501 def _on_consumer_cancelled_by_broker(
1502 self,
1503 method_frame: pika.frame.Method[pika.spec.Basic.Cancel]) -> None:
1504 """Called by impl when broker cancels consumer via Basic.Cancel.
1505
1506 This is a RabbitMQ-specific feature. The circumstances include deletion
1507 of queue being consumed as well as failure of a HA node responsible for
1508 the queue being consumed.
1509
1510 :param pika.frame.Method method_frame: method frame with the
1511 `spec.Basic.Cancel` method
1512
1513 """
1514 evt = _ConsumerCancellationEvt(method_frame)
1515
1516 consumer = self._consumer_infos[method_frame.method.consumer_tag]
1517
1518 # Don't interfere with client-initiated cancellation flow
1519 if not consumer.tearing_down:
1520 consumer.state = _ConsumerInfo.CANCELLED_BY_BROKER
1521
1522 if consumer.alternate_event_sink is not None:
1523 consumer.alternate_event_sink(evt)
1524 else:
1525 self._add_pending_event(evt)
1526
1527 def _on_consumer_message_delivery(self, _channel: pika.channel.Channel,
1528 method: pika.spec.Basic.Deliver,
1529 properties: pika.spec.BasicProperties,
1530 body: bytes):
1531 """Called by impl when a message is delivered for a consumer
1532
1533 :param Channel channel: The implementation channel object
1534 :param spec.Basic.Deliver method:
1535 :param pika.spec.BasicProperties properties: message properties
1536 :param bytes body: delivered message body; empty string if no body
1537 """
1538 evt = _ConsumerDeliveryEvt(method, properties, body)
1539
1540 consumer = self._consumer_infos[method.consumer_tag]
1541
1542 if consumer.alternate_event_sink is not None:
1543 consumer.alternate_event_sink(evt)
1544 else:
1545 self._add_pending_event(evt)
1546
1547 def _on_consumer_generator_event(self, evt: _ChannelPendingEvt) -> None:
1548 """Sink for the queue consumer generator's consumer events; append the
1549 event to queue consumer generator's pending events buffer.
1550
1551 :param evt: an object of type _ConsumerDeliveryEvt or
1552 _ConsumerCancellationEvt
1553 """
1554 self._queue_consumer_generator.pending_events.append( # type: ignore[union-attr]
1555 evt)
1556 # Schedule termination of connection.process_data_events using a
1557 # negative channel number
1558 self.connection._request_channel_dispatch(-self.channel_number)
1559
1560 def _cancel_all_consumers(self) -> None:
1561 """Cancel all consumers.
1562
1563 NOTE: pending non-ackable messages will be lost; pending ackable
1564 messages will be rejected.
1565
1566 """
1567 if self._consumer_infos:
1568 LOGGER.debug('Cancelling %i consumers', len(self._consumer_infos))
1569
1570 if self._queue_consumer_generator is not None:
1571 # Cancel queue consumer generator
1572 self.cancel()
1573
1574 # Cancel consumers created via basic_consume
1575 for consumer_tag in list(self._consumer_infos.keys()):
1576 self.basic_cancel(consumer_tag)
1577
1578 def _dispatch_events(self) -> None:
1579 """Called by BlockingConnection to dispatch pending events.
1580
1581 `BlockingChannel` schedules this callback via
1582 `BlockingConnection._request_channel_dispatch`
1583 """
1584 while self._pending_events:
1585 evt = self._pending_events.popleft()
1586
1587 if type(evt) is _ConsumerDeliveryEvt: # pylint: disable=C0123
1588 consumer_info = self._consumer_infos[evt.method.consumer_tag]
1589 consumer_info.on_message_callback(self, evt.method,
1590 evt.properties, evt.body)
1591
1592 elif type(evt) is _ConsumerCancellationEvt: # pylint: disable=C0123
1593 del self._consumer_infos[evt.method_frame.method.consumer_tag]
1594
1595 self._impl.callbacks.process(self.channel_number,
1596 self._CONSUMER_CANCELLED_CB_KEY,
1597 self, evt.method_frame)
1598 else:
1599 evt.dispatch()
1600
1601 def close(self,
1602 reply_code: int = 0,
1603 reply_text: str = "Normal shutdown") -> None:
1604 """Will invoke a clean shutdown of the channel with the AMQP Broker.
1605
1606 :param int reply_code: The reply code to close the channel with
1607 :param str reply_text: The reply text to close the channel with
1608
1609 """
1610 LOGGER.debug('Channel.close(%s, %s)', reply_code, reply_text)
1611
1612 self._impl._raise_if_not_open()
1613
1614 try:
1615 # Cancel remaining consumers
1616 self._cancel_all_consumers()
1617
1618 # Close the channel
1619 self._impl.close(reply_code=reply_code, reply_text=reply_text)
1620 self._flush_output(lambda: self.is_closed)
1621 finally:
1622 self._cleanup()
1623
1624 def flow(self, active: bool) -> bool:
1625 """Turn Channel flow control off and on.
1626
1627 NOTE: RabbitMQ doesn't support active=False; per
1628 https://www.rabbitmq.com/specification.html: "active=false is not
1629 supported by the server. Limiting prefetch with basic.qos provides much
1630 better control"
1631
1632 For more information, please reference:
1633
1634 https://www.rabbitmq.com/amqp-0-9-1-reference.html#channel.flow
1635
1636 :param bool active: Turn flow on (True) or off (False)
1637 :returns: True if broker will start or continue sending; False if not
1638 :rtype: bool
1639
1640 """
1641 with _CallbackResult(self._FlowOkCallbackResultArgs) as flow_ok_result:
1642 self._impl.flow(active=active,
1643 callback=flow_ok_result.set_value_once)
1644 self._flush_output(flow_ok_result.is_ready)
1645 return flow_ok_result.value.active
1646
1647 def add_on_cancel_callback(
1648 self, callback: Callable[[pika.frame.Method[pika.spec.Basic.Cancel]],
1649 None]
1650 ) -> None:
1651 """Pass a callback function that will be called when Basic.Cancel
1652 is sent by the broker. The callback function should receive a method
1653 frame parameter.
1654
1655 :param callable callback: a callable for handling broker's Basic.Cancel
1656 notification with the call signature: callback(method_frame)
1657 where method_frame is of type `pika.frame.Method` with method of
1658 type `spec.Basic.Cancel`
1659
1660 """
1661 self._impl.callbacks.add(self.channel_number,
1662 self._CONSUMER_CANCELLED_CB_KEY,
1663 callback,
1664 one_shot=False)
1665
1666 def add_on_return_callback(
1667 self, callback: Callable[[
1668 BlockingChannel, pika.spec.Basic.Return, pika.spec.
1669 BasicProperties, bytes
1670 ], None]
1671 ) -> None:
1672 """Pass a callback function that will be called when a published
1673 message is rejected and returned by the server via `Basic.Return`.
1674
1675 :param callable callback: The method to call on callback with the
1676 signature callback(channel, method, properties, body), where
1677 - channel: pika.Channel
1678 - method: pika.spec.Basic.Return
1679 - properties: pika.spec.BasicProperties
1680 - body: bytes
1681
1682 """
1683 self._impl.add_on_return_callback(
1684 lambda _channel, method, properties, body: (self._add_pending_event(
1685 _ReturnedMessageEvt(callback, self, method, properties, body))))
1686
1687 def basic_consume(self,
1688 queue: str,
1689 on_message_callback: Callable[[
1690 BlockingChannel, pika.spec.Basic.Deliver, pika.spec.
1691 BasicProperties, bytes
1692 ], None],
1693 auto_ack: bool = False,
1694 exclusive: bool = False,
1695 consumer_tag: Optional[str] = None,
1696 arguments: Optional[Dict[str, Any]] = None):
1697 """Sends the AMQP command Basic.Consume to the broker and binds messages
1698 for the consumer_tag to the consumer callback. If you do not pass in
1699 a consumer_tag, one will be automatically generated for you. Returns
1700 the consumer tag.
1701
1702 NOTE: the consumer callbacks are dispatched only in the scope of
1703 specially-designated methods: see
1704 `BlockingConnection.process_data_events` and
1705 `BlockingChannel.start_consuming`.
1706
1707 For more information about Basic.Consume, see:
1708 https://www.rabbitmq.com/amqp-0-9-1-reference.html#basic.consume
1709
1710 :param str queue: The queue from which to consume
1711 :param callable on_message_callback: Required function for dispatching messages
1712 to user, having the signature:
1713 on_message_callback(channel, method, properties, body)
1714 - channel: BlockingChannel
1715 - method: spec.Basic.Deliver
1716 - properties: spec.BasicProperties
1717 - body: bytes
1718 :param bool auto_ack: if set to True, automatic acknowledgement mode will be used
1719 (see https://www.rabbitmq.com/confirms.html). This corresponds
1720 with the 'no_ack' parameter in the basic.consume AMQP 0.9.1
1721 method
1722 :param bool exclusive: Don't allow other consumers on the queue
1723 :param str consumer_tag: You may specify your own consumer tag; if left
1724 empty, a consumer tag will be generated automatically
1725 :param dict arguments: Custom key/value pair arguments for the consumer
1726 :returns: consumer tag
1727 :rtype: str
1728 :raises pika.exceptions.DuplicateConsumerTag: if consumer with given
1729 consumer_tag is already present.
1730
1731 """
1732 validators.require_string(queue, 'queue')
1733 validators.require_callback(on_message_callback, 'on_message_callback')
1734 return self._basic_consume_impl(queue=queue,
1735 on_message_callback=on_message_callback,
1736 auto_ack=auto_ack,
1737 exclusive=exclusive,
1738 consumer_tag=consumer_tag,
1739 arguments=arguments)
1740
1741 def _basic_consume_impl(
1742 self,
1743 queue: str,
1744 auto_ack: bool,
1745 exclusive: bool,
1746 consumer_tag: Optional[str],
1747 arguments: Optional[Dict[str, Any]] = None,
1748 on_message_callback: Optional[Callable[[
1749 BlockingChannel, pika.spec.Basic.Deliver, pika.spec.
1750 BasicProperties, bytes
1751 ], None]] = None,
1752 alternate_event_sink: Optional[Callable[[_ChannelPendingEvt],
1753 None]] = None):
1754 """The low-level implementation used by `basic_consume` and `consume`.
1755 See `basic_consume` docstring for more info.
1756
1757 NOTE: exactly one of on_message_callback/alternate_event_sink musts be
1758 non-None.
1759
1760 This method has one additional parameter alternate_event_sink over the
1761 args described in `basic_consume`.
1762
1763 :param callable alternate_event_sink: if specified, _ConsumerDeliveryEvt
1764 and _ConsumerCancellationEvt objects will be diverted to this
1765 callback instead of being deposited in the channel's
1766 `_pending_events` container. Signature:
1767 alternate_event_sink(evt)
1768
1769 :raises pika.exceptions.DuplicateConsumerTag: if consumer with given
1770 consumer_tag is already present.
1771
1772 """
1773 if (on_message_callback is None) == (alternate_event_sink is None):
1774 raise ValueError(
1775 ('exactly one of on_message_callback/alternate_event_sink must '
1776 'be non-None', on_message_callback, alternate_event_sink))
1777
1778 if not consumer_tag:
1779 # Need a consumer tag to register consumer info before sending
1780 # request to broker, because I/O might dispatch incoming messages
1781 # immediately following Basic.Consume-ok before _flush_output
1782 # returns
1783 consumer_tag = self._impl._generate_consumer_tag()
1784
1785 if consumer_tag in self._consumer_infos:
1786 raise exceptions.DuplicateConsumerTag(consumer_tag)
1787
1788 # Create new consumer
1789 self._consumer_infos[consumer_tag] = _ConsumerInfo(
1790 consumer_tag,
1791 auto_ack=auto_ack,
1792 on_message_callback=on_message_callback,
1793 alternate_event_sink=alternate_event_sink)
1794
1795 try:
1796 with self._basic_consume_ok_result as ok_result:
1797 tag = self._impl.basic_consume(
1798 on_message_callback=self._on_consumer_message_delivery,
1799 queue=queue,
1800 auto_ack=auto_ack,
1801 exclusive=exclusive,
1802 consumer_tag=consumer_tag,
1803 arguments=arguments)
1804
1805 assert tag == consumer_tag, (tag, consumer_tag)
1806
1807 self._flush_output(ok_result.is_ready)
1808 except Exception:
1809 # If channel was closed, self._consumer_infos will be empty
1810 if consumer_tag in self._consumer_infos:
1811 del self._consumer_infos[consumer_tag]
1812 # Schedule termination of connection.process_data_events using a
1813 # negative channel number
1814 self.connection._request_channel_dispatch(-self.channel_number)
1815 raise
1816
1817 # NOTE: Consumer could get cancelled by broker immediately after opening
1818 # (e.g., queue getting deleted externally)
1819 if self._consumer_infos[consumer_tag].setting_up:
1820 self._consumer_infos[consumer_tag].state = _ConsumerInfo.ACTIVE
1821
1822 return consumer_tag
1823
1824 def basic_cancel(
1825 self, consumer_tag: str
1826 ) -> Sequence[Tuple[pika.spec.Basic.Deliver, pika.spec.BasicProperties,
1827 bytes]]:
1828 """This method cancels a consumer. This does not affect already
1829 delivered messages, but it does mean the server will not send any more
1830 messages for that consumer. The client may receive an arbitrary number
1831 of messages in between sending the cancel method and receiving the
1832 cancel-ok reply.
1833
1834 NOTE: When cancelling an auto_ack=False consumer, this implementation
1835 automatically Nacks and suppresses any incoming messages that have not
1836 yet been dispatched to the consumer's callback. However, when cancelling
1837 a auto_ack=True consumer, this method will return any pending messages
1838 that arrived before broker confirmed the cancellation.
1839
1840 :param str consumer_tag: Identifier for the consumer; the result of
1841 passing a consumer_tag that was created on another channel is
1842 undefined (bad things will happen)
1843 :returns: (NEW IN pika 0.10.0) empty sequence for a auto_ack=False
1844 consumer; for a auto_ack=True consumer, returns a (possibly empty)
1845 sequence of pending messages that arrived before broker confirmed
1846 the cancellation (this is done instead of via consumer's callback in
1847 order to prevent reentrancy/recursion. Each message is three-tuple:
1848 (method, properties, body)
1849 - method: spec.Basic.Deliver
1850 - properties: spec.BasicProperties
1851 - body: bytes
1852 :rtype: list
1853 """
1854 try:
1855 consumer_info = self._consumer_infos[consumer_tag]
1856 except KeyError:
1857 LOGGER.warning(
1858 "User is attempting to cancel an unknown consumer=%s; "
1859 "already cancelled by user or broker?", consumer_tag)
1860 return []
1861
1862 try:
1863 # Assertion failure here is most likely due to reentrance
1864 assert consumer_info.active or consumer_info.cancelled_by_broker, (
1865 consumer_info.state)
1866
1867 # Assertion failure here signals disconnect between consumer state
1868 # in BlockingChannel and Channel
1869 assert (consumer_info.cancelled_by_broker or
1870 consumer_tag in self._impl._consumers), consumer_tag
1871
1872 auto_ack = consumer_info.auto_ack
1873
1874 consumer_info.state = _ConsumerInfo.TEARING_DOWN
1875
1876 with _CallbackResult() as cancel_ok_result:
1877 # Nack pending messages for auto_ack=False consumer
1878 if not auto_ack:
1879 pending_messages = self._remove_pending_deliveries(
1880 consumer_tag)
1881 if pending_messages:
1882 # NOTE: we use impl's basic_reject to avoid the
1883 # possibility of redelivery before basic_cancel takes
1884 # control of nacking.
1885 # NOTE: we can't use basic_nack with the multiple option
1886 # to avoid nacking messages already held by our client.
1887 for message in pending_messages:
1888 self._impl.basic_reject(
1889 message.method.delivery_tag, requeue=True
1890 ) # pyright: ignore[reportArgumentType]
1891
1892 # Cancel the consumer; impl takes care of rejecting any
1893 # additional deliveries that arrive for a auto_ack=False
1894 # consumer
1895 self._impl.basic_cancel(consumer_tag=consumer_tag,
1896 callback=cancel_ok_result.signal_once)
1897
1898 # Flush output and wait for Basic.Cancel-ok or
1899 # broker-initiated Basic.Cancel
1900 self._flush_output(
1901 cancel_ok_result.is_ready,
1902 lambda: consumer_tag not in self._impl._consumers)
1903
1904 if auto_ack:
1905 # Return pending messages for auto_ack=True consumer
1906 return [(evt.method, evt.properties, evt.body)
1907 for evt in self._remove_pending_deliveries(consumer_tag)
1908 ]
1909 else:
1910 # impl takes care of rejecting any incoming deliveries during
1911 # cancellation
1912 messages = self._remove_pending_deliveries(consumer_tag)
1913 assert not messages, messages
1914
1915 return []
1916 finally:
1917 # NOTE: The entry could be purged if channel or connection closes
1918 if consumer_tag in self._consumer_infos:
1919 del self._consumer_infos[consumer_tag]
1920 # Schedule termination of connection.process_data_events using a
1921 # negative channel number
1922 self.connection._request_channel_dispatch(-self.channel_number)
1923
1924 def _remove_pending_deliveries(
1925 self, consumer_tag: str) -> Sequence[_ConsumerDeliveryEvt]:
1926 """Extract _ConsumerDeliveryEvt objects destined for the given consumer
1927 from pending events, discarding the _ConsumerCancellationEvt, if any
1928
1929 :param str consumer_tag:
1930
1931 :returns: a (possibly empty) sequence of _ConsumerDeliveryEvt destined
1932 for the given consumer tag
1933 :rtype: list
1934 """
1935 remaining_events: deque[Any] = deque()
1936 unprocessed_messages: List[Any] = []
1937 while self._pending_events:
1938 evt = self._pending_events.popleft()
1939 if type(evt) is _ConsumerDeliveryEvt: # pylint: disable=C0123
1940 if evt.method.consumer_tag == consumer_tag:
1941 unprocessed_messages.append(evt)
1942 continue
1943 if type(evt) is _ConsumerCancellationEvt: # pylint: disable=C0123
1944 if evt.method_frame.method.consumer_tag == consumer_tag:
1945 # A broker-initiated Basic.Cancel must have arrived
1946 # before our cancel request completed
1947 continue
1948
1949 remaining_events.append(evt)
1950
1951 self._pending_events = remaining_events
1952
1953 return unprocessed_messages
1954
1955 def start_consuming(self) -> None:
1956 """Processes I/O events and dispatches timers and `basic_consume`
1957 callbacks until all consumers are cancelled.
1958
1959 NOTE: this blocking function may not be called from the scope of a
1960 pika callback, because dispatching `basic_consume` callbacks from this
1961 context would constitute recursion.
1962
1963 :raises pika.exceptions.ReentrancyError: if called from the scope of a
1964 `BlockingConnection` or `BlockingChannel` callback
1965 :raises ChannelClosed: when this channel is closed by broker.
1966 """
1967 # Check if called from the scope of an event dispatch callback
1968 with self.connection._acquire_event_dispatch() as dispatch_allowed:
1969 if not dispatch_allowed:
1970 raise exceptions.ReentrancyError(
1971 'start_consuming may not be called from the scope of '
1972 'another BlockingConnection or BlockingChannel callback')
1973
1974 self._impl._raise_if_not_open()
1975
1976 # Process events as long as consumers exist on this channel
1977 while self._consumer_infos:
1978 # This will raise ChannelClosed if channel is closed by broker
1979 self._process_data_events(time_limit=None)
1980
1981 def stop_consuming(self, consumer_tag: Optional[str] = None) -> None:
1982 """ Cancels all consumers, signalling the `start_consuming` loop to
1983 exit.
1984
1985 NOTE: pending non-ackable messages will be lost; pending ackable
1986 messages will be rejected.
1987
1988 """
1989 if consumer_tag:
1990 self.basic_cancel(consumer_tag)
1991 else:
1992 self._cancel_all_consumers()
1993
1994 def consume(
1995 self,
1996 queue: str,
1997 auto_ack: bool = False,
1998 exclusive: bool = False,
1999 arguments: Optional[Dict[str, Any]] = None,
2000 inactivity_timeout: Optional[float] = None,
2001 consumer_tag: Optional[str] = None
2002 ) -> Generator[Tuple[Optional[pika.spec.Basic.Deliver],
2003 Optional[pika.spec.BasicProperties], Optional[bytes]],
2004 None, None]:
2005 """Blocking consumption of a queue instead of via a callback. This
2006 method is a generator that yields each message as a tuple of method,
2007 properties, and body. The active generator iterator terminates when the
2008 consumer is cancelled by client via `BlockingChannel.cancel()` or by
2009 broker.
2010
2011 Example:
2012 ::
2013 for method, properties, body in channel.consume('queue'):
2014 print(body)
2015 channel.basic_ack(method.delivery_tag)
2016
2017 You should call `BlockingChannel.cancel()` when you escape out of the
2018 generator loop.
2019
2020 If you don't cancel this consumer, then next call on the same channel
2021 to `consume()` with the exact same (queue, auto_ack, exclusive) parameters
2022 will resume the existing consumer generator; however, calling with
2023 different parameters will result in an exception.
2024
2025 :param str queue: The queue name to consume
2026 :param bool auto_ack: Tell the broker to not expect a ack/nack response
2027 :param bool exclusive: Don't allow other consumers on the queue
2028 :param dict arguments: Custom key/value pair arguments for the consumer
2029 :param float inactivity_timeout: if a number is given (in
2030 seconds), will cause the method to yield (None, None, None) after the
2031 given period of inactivity; this permits for pseudo-regular maintenance
2032 activities to be carried out by the user while waiting for messages
2033 to arrive. If None is given (default), then the method blocks until
2034 the next event arrives. NOTE that timing granularity is limited by
2035 the timer resolution of the underlying implementation.
2036 NEW in pika 0.10.0.
2037 :param str consumer_tag: Specify your own consumer tag
2038
2039 :yields: tuple(spec.Basic.Deliver, spec.BasicProperties, str or unicode)
2040
2041 :raises ValueError: if consumer-creation parameters don't match those
2042 of the existing queue consumer generator, if any.
2043 NEW in pika 0.10.0
2044 :raises ChannelClosed: when this channel is closed by broker.
2045
2046 """
2047 self._impl._raise_if_not_open()
2048
2049 params = (queue, auto_ack, exclusive)
2050
2051 if self._queue_consumer_generator is not None:
2052 if params != self._queue_consumer_generator.params:
2053 raise ValueError(
2054 'Consume with different params not allowed on existing '
2055 'queue consumer generator; previous params: %r; '
2056 'new params: %r' % (self._queue_consumer_generator.params,
2057 (queue, auto_ack, exclusive)))
2058 else:
2059 LOGGER.debug('Creating new queue consumer generator; params: %r',
2060 params)
2061 # Need a consumer tag to register consumer info before sending
2062 # request to broker, because I/O might pick up incoming messages
2063 # in addition to Basic.Consume-ok
2064 if not consumer_tag:
2065 consumer_tag = self._impl._generate_consumer_tag()
2066
2067 self._queue_consumer_generator = _QueueConsumerGeneratorInfo(
2068 params, consumer_tag)
2069
2070 try:
2071 self._basic_consume_impl(
2072 queue=queue,
2073 auto_ack=auto_ack,
2074 exclusive=exclusive,
2075 consumer_tag=consumer_tag,
2076 arguments=arguments,
2077 alternate_event_sink=self._on_consumer_generator_event)
2078 except Exception:
2079 self._queue_consumer_generator = None
2080 raise
2081
2082 LOGGER.info('Created new queue consumer generator %r',
2083 self._queue_consumer_generator)
2084
2085 while self._queue_consumer_generator is not None:
2086 # Process pending events
2087 if self._queue_consumer_generator.pending_events:
2088 evt = self._queue_consumer_generator.pending_events.popleft()
2089 if type(evt) is _ConsumerCancellationEvt: # pylint: disable=C0123
2090 # Consumer was cancelled by broker
2091 self._queue_consumer_generator = None
2092 break
2093 else:
2094 yield (evt.method, evt.properties, evt.body)
2095 continue
2096
2097 if inactivity_timeout is None:
2098 # Wait indefinitely for a message to arrive, while processing
2099 # I/O events and triggering ChannelClosed exception when the
2100 # channel fails
2101 self._process_data_events(time_limit=None)
2102 continue
2103
2104 # Wait with inactivity timeout
2105 wait_start_time = compat.time_now()
2106 wait_deadline = wait_start_time + inactivity_timeout
2107 delta = inactivity_timeout
2108
2109 while (self._queue_consumer_generator is not None and
2110 not self._queue_consumer_generator.pending_events):
2111
2112 self._process_data_events(time_limit=delta)
2113
2114 if not self._queue_consumer_generator:
2115 # Consumer was cancelled by client
2116 break
2117
2118 if self._queue_consumer_generator.pending_events:
2119 # Got message(s)
2120 break
2121
2122 delta = wait_deadline - compat.time_now()
2123 if delta <= 0.0:
2124 # Signal inactivity timeout
2125 yield (None, None, None)
2126 break
2127
2128 def _process_data_events(self, time_limit: Optional[float]) -> None:
2129 """Wrapper for `BlockingConnection.process_data_events()` with common
2130 channel-specific logic that raises ChannelClosed if broker closed this
2131 channel.
2132
2133 NOTE: We need to raise an exception in the context of user's call into
2134 our API to protect the integrity of the underlying implementation.
2135 BlockingConnection's underlying asynchronous connection adapter
2136 (SelectConnection) uses callbacks to communicate with us. If
2137 BlockingConnection leaks exceptions back into the I/O loop or the
2138 asynchronous connection adapter, we interrupt their normal workflow and
2139 introduce a high likelihood of state inconsistency.
2140
2141 See `BlockingConnection.process_data_events()` for documentation of args
2142 and behavior.
2143
2144 :param float time_limit:
2145
2146 """
2147 self.connection.process_data_events(time_limit=time_limit)
2148 if self.is_closed and isinstance(self._closing_reason,
2149 exceptions.ChannelClosedByBroker):
2150 LOGGER.debug('Channel close by broker detected, raising %r; %r',
2151 self._closing_reason, self)
2152 raise self._closing_reason # pylint: disable=E0702
2153
2154 def get_waiting_message_count(self) -> int:
2155 """Returns the number of messages that may be retrieved from the current
2156 queue consumer generator via `BlockingChannel.consume` without blocking.
2157 NEW in pika 0.10.0
2158
2159 :returns: The number of waiting messages
2160 :rtype: int
2161 """
2162 if self._queue_consumer_generator is not None:
2163 pending_events = self._queue_consumer_generator.pending_events
2164 count = len(pending_events)
2165 if count and type(pending_events[-1]) is _ConsumerCancellationEvt: # pylint: disable=C0123
2166 count -= 1
2167 else:
2168 count = 0
2169
2170 return count
2171
2172 def cancel(self) -> int:
2173 """Cancel the queue consumer created by `BlockingChannel.consume`,
2174 rejecting all pending ackable messages.
2175
2176 NOTE: If you're looking to cancel a consumer issued with
2177 BlockingChannel.basic_consume then you should call
2178 BlockingChannel.basic_cancel.
2179
2180 :returns: The number of messages requeued by Basic.Nack.
2181 NEW in 0.10.0: returns 0
2182 :rtype: int
2183
2184 """
2185 if self._queue_consumer_generator is None:
2186 LOGGER.warning('cancel: queue consumer generator is inactive '
2187 '(already cancelled by client or broker?)')
2188 return 0
2189
2190 try:
2191 _, auto_ack, _ = self._queue_consumer_generator.params
2192 if not auto_ack:
2193 # Reject messages held by queue consumer generator; NOTE: we
2194 # can't use basic_nack with the multiple option to avoid nacking
2195 # messages already held by our client.
2196 pending_events = self._queue_consumer_generator.pending_events
2197 # NOTE `get_waiting_message_count` adjusts for `Basic.Cancel`
2198 # from the server at the end (if any)
2199 for _ in range(self.get_waiting_message_count()):
2200 evt = pending_events.popleft()
2201 self._impl.basic_reject(evt.method.delivery_tag,
2202 requeue=True)
2203
2204 self.basic_cancel(self._queue_consumer_generator.consumer_tag)
2205 finally:
2206 self._queue_consumer_generator = None
2207
2208 # Return 0 for compatibility with legacy implementation; the number of
2209 # nacked messages is not meaningful since only messages consumed with
2210 # auto_ack=False may be nacked, and those arriving after calling
2211 # basic_cancel will be rejected automatically by impl channel, so we'll
2212 # never know how many of those were nacked.
2213 return 0
2214
2215 def basic_ack(self, delivery_tag: int = 0, multiple: bool = False) -> None:
2216 """Acknowledge one or more messages. When sent by the client, this
2217 method acknowledges one or more messages delivered via the Deliver or
2218 Get-Ok methods. When sent by server, this method acknowledges one or
2219 more messages published with the Publish method on a channel in
2220 confirm mode. The acknowledgement can be for a single message or a
2221 set of messages up to and including a specific message.
2222
2223 :param int delivery_tag: The server-assigned delivery tag
2224 :param bool multiple: If set to True, the delivery tag is treated as
2225 "up to and including", so that multiple messages
2226 can be acknowledged with a single method. If set
2227 to False, the delivery tag refers to a single
2228 message. If the multiple field is 1, and the
2229 delivery tag is zero, this indicates
2230 acknowledgement of all outstanding messages.
2231 """
2232 self._impl.basic_ack(delivery_tag=delivery_tag, multiple=multiple)
2233 self._flush_output()
2234
2235 def basic_nack(self,
2236 delivery_tag: int = 0,
2237 multiple: bool = False,
2238 requeue: bool = True) -> None:
2239 """This method allows a client to reject one or more incoming messages.
2240 It can be used to interrupt and cancel large incoming messages, or
2241 return untreatable messages to their original queue.
2242
2243 :param int delivery_tag: The server-assigned delivery tag
2244 :param bool multiple: If set to True, the delivery tag is treated as
2245 "up to and including", so that multiple messages
2246 can be acknowledged with a single method. If set
2247 to False, the delivery tag refers to a single
2248 message. If the multiple field is 1, and the
2249 delivery tag is zero, this indicates
2250 acknowledgement of all outstanding messages.
2251 :param bool requeue: If requeue is true, the server will attempt to
2252 requeue the message. If requeue is false or the
2253 requeue attempt fails the messages are discarded or
2254 dead-lettered.
2255
2256 """
2257 self._impl.basic_nack(delivery_tag=delivery_tag,
2258 multiple=multiple,
2259 requeue=requeue)
2260 self._flush_output()
2261
2262 def basic_get(
2263 self,
2264 queue: str,
2265 auto_ack: bool = False
2266 ) -> Tuple[Optional[pika.spec.Basic.GetOk],
2267 Optional[pika.spec.BasicProperties], Optional[bytes]]:
2268 """Get a single message from the AMQP broker. Returns a sequence with
2269 the method frame, message properties, and body.
2270
2271 :param str queue: Name of queue from which to get a message
2272 :param bool auto_ack: Tell the broker to not expect a reply
2273 :returns: a three-tuple; (None, None, None) if the queue was empty;
2274 otherwise (method, properties, body); NOTE: body may be None
2275 :rtype: (spec.Basic.GetOk|None, spec.BasicProperties|None, bytes|None)
2276 """
2277 assert not self._basic_getempty_result
2278
2279 validators.require_string(queue, 'queue')
2280
2281 # NOTE: nested with for python 2.6 compatibility
2282 with _CallbackResult(self._RxMessageArgs) as get_ok_result:
2283 with self._basic_getempty_result:
2284 self._impl.basic_get(queue=queue,
2285 auto_ack=auto_ack,
2286 callback=get_ok_result.set_value_once)
2287 self._flush_output(get_ok_result.is_ready,
2288 self._basic_getempty_result.is_ready)
2289 if get_ok_result:
2290 evt = get_ok_result.value
2291 return evt.method, evt.properties, evt.body
2292 else:
2293 assert self._basic_getempty_result, (
2294 "wait completed without GetOk and GetEmpty")
2295 return None, None, None
2296
2297 def basic_publish(self,
2298 exchange: str,
2299 routing_key: str,
2300 body: bytes,
2301 properties: Optional[pika.spec.BasicProperties] = None,
2302 mandatory: bool = False) -> None:
2303 """Publish to the channel with the given exchange, routing key, and
2304 body.
2305
2306 For more information on basic_publish and what the parameters do, see:
2307
2308 https://www.rabbitmq.com/amqp-0-9-1-reference.html#basic.publish
2309
2310 NOTE: mandatory may be enabled even without delivery
2311 confirmation, but in the absence of delivery confirmation the
2312 synchronous implementation has no way to know how long to wait for
2313 the Basic.Return.
2314
2315 :param str exchange: The exchange to publish to
2316 :param str routing_key: The routing key to bind on
2317 :param bytes body: The message body; empty string if no body
2318 :param pika.spec.BasicProperties properties: message properties
2319 :param bool mandatory: The mandatory flag
2320
2321 :raises UnroutableError: raised when a message published in
2322 publisher-acknowledgments mode (see
2323 `BlockingChannel.confirm_delivery`) is returned via `Basic.Return`
2324 followed by `Basic.Ack`.
2325 :raises NackError: raised when a message published in
2326 publisher-acknowledgements mode is Nack'ed by the broker. See
2327 `BlockingChannel.confirm_delivery`.
2328
2329 """
2330 if self._delivery_confirmation:
2331 # In publisher-acknowledgments mode
2332 with self._message_confirmation_result:
2333 self._impl.basic_publish(exchange=exchange,
2334 routing_key=routing_key,
2335 body=body,
2336 properties=properties,
2337 mandatory=mandatory)
2338
2339 self._flush_output(self._message_confirmation_result.is_ready)
2340 conf_method = (
2341 self._message_confirmation_result.value.method_frame.method)
2342
2343 if isinstance(conf_method, pika.spec.Basic.Nack):
2344 # Broker was unable to process the message due to internal
2345 # error
2346 LOGGER.warning(
2347 "Message was Nack'ed by broker: nack=%r; channel=%s; "
2348 "exchange=%s; routing_key=%s; mandatory=%r; ",
2349 conf_method, self.channel_number, exchange, routing_key,
2350 mandatory)
2351 if self._puback_return is not None:
2352 returned_messages: List[ReturnedMessage] = [
2353 self._puback_return
2354 ]
2355 self._puback_return = None
2356 else:
2357 returned_messages = []
2358 raise exceptions.NackError(returned_messages)
2359
2360 else:
2361 assert isinstance(conf_method,
2362 pika.spec.Basic.Ack), (conf_method)
2363
2364 if self._puback_return is not None:
2365 # Unroutable message was returned
2366 messages = [self._puback_return]
2367 self._puback_return = None
2368 raise exceptions.UnroutableError(messages)
2369 else:
2370 # In non-publisher-acknowledgments mode
2371 self._impl.basic_publish(exchange=exchange,
2372 routing_key=routing_key,
2373 body=body,
2374 properties=properties,
2375 mandatory=mandatory)
2376 self._flush_output()
2377
2378 def basic_qos(self,
2379 prefetch_size: int = 0,
2380 prefetch_count: int = 0,
2381 global_qos: bool = False) -> None:
2382 """Specify quality of service. This method requests a specific quality
2383 of service. The QoS can be specified for the current channel or for all
2384 channels on the connection. The client can request that messages be sent
2385 in advance so that when the client finishes processing a message, the
2386 following message is already held locally, rather than needing to be
2387 sent down the channel. Prefetching gives a performance improvement.
2388
2389 :param int prefetch_size: This field specifies the prefetch window
2390 size. The server will send a message in
2391 advance if it is equal to or smaller in size
2392 than the available prefetch size (and also
2393 falls into other prefetch limits). May be set
2394 to zero, meaning "no specific limit",
2395 although other prefetch limits may still
2396 apply. The prefetch-size is ignored if the
2397 no-ack option is set in the consumer.
2398 :param int prefetch_count: Specifies a prefetch window in terms of whole
2399 messages. This field may be used in
2400 combination with the prefetch-size field; a
2401 message will only be sent in advance if both
2402 prefetch windows (and those at the channel
2403 and connection level) allow it. The
2404 prefetch-count is ignored if the no-ack
2405 option is set in the consumer.
2406 :param bool global_qos: Should the QoS apply to all channels on the
2407 connection.
2408
2409 """
2410 with _CallbackResult() as qos_ok_result:
2411 self._impl.basic_qos(callback=qos_ok_result.signal_once,
2412 prefetch_size=prefetch_size,
2413 prefetch_count=prefetch_count,
2414 global_qos=global_qos)
2415 self._flush_output(qos_ok_result.is_ready)
2416
2417 def basic_recover(self, requeue: bool = False) -> None:
2418 """This method asks the server to redeliver all unacknowledged messages
2419 on a specified channel. Zero or more messages may be redelivered. This
2420 method replaces the asynchronous Recover.
2421
2422 :param bool requeue: If False, the message will be redelivered to the
2423 original recipient. If True, the server will
2424 attempt to requeue the message, potentially then
2425 delivering it to an alternative subscriber.
2426
2427 """
2428 with _CallbackResult() as recover_ok_result:
2429 self._impl.basic_recover(requeue=requeue,
2430 callback=recover_ok_result.signal_once)
2431 self._flush_output(recover_ok_result.is_ready)
2432
2433 def basic_reject(self, delivery_tag: int = 0, requeue: bool = True) -> None:
2434 """Reject an incoming message. This method allows a client to reject a
2435 message. It can be used to interrupt and cancel large incoming messages,
2436 or return untreatable messages to their original queue.
2437
2438 :param int delivery_tag: The server-assigned delivery tag
2439 :param bool requeue: If requeue is true, the server will attempt to
2440 requeue the message. If requeue is false or the
2441 requeue attempt fails the messages are discarded or
2442 dead-lettered.
2443
2444 """
2445 self._impl.basic_reject(delivery_tag=delivery_tag, requeue=requeue)
2446 self._flush_output()
2447
2448 def confirm_delivery(self) -> None:
2449 """Turn on RabbitMQ-proprietary Confirm mode in the channel.
2450
2451 For more information see:
2452 https://www.rabbitmq.com/confirms.html
2453 """
2454 if self._delivery_confirmation:
2455 LOGGER.error(
2456 'confirm_delivery: confirmation was already enabled '
2457 'on channel=%s', self.channel_number)
2458 return
2459
2460 with _CallbackResult() as select_ok_result:
2461 self._impl.confirm_delivery(
2462 ack_nack_callback=self._message_confirmation_result.
2463 set_value_once,
2464 callback=select_ok_result.signal_once)
2465
2466 self._flush_output(select_ok_result.is_ready)
2467
2468 self._delivery_confirmation = True
2469
2470 # Unroutable messages returned after this point will be in the context
2471 # of publisher acknowledgments
2472 self._impl.add_on_return_callback(self._on_puback_message_returned)
2473
2474 def exchange_declare(self,
2475 exchange: str,
2476 exchange_type: Union[ExchangeType,
2477 str] = ExchangeType.direct,
2478 passive: bool = False,
2479 durable: bool = False,
2480 auto_delete: bool = False,
2481 internal: bool = False,
2482 arguments: Optional[Dict[str, Any]] = None) -> None:
2483 """This method creates an exchange if it does not already exist, and if
2484 the exchange exists, verifies that it is of the correct and expected
2485 class.
2486
2487 If passive set, the server will reply with Declare-Ok if the exchange
2488 already exists with the same name, and raise an error if not and if the
2489 exchange does not already exist, the server MUST raise a channel
2490 exception with reply code 404 (not found).
2491
2492 :param str exchange: The exchange name consists of a non-empty sequence of
2493 these characters: letters, digits, hyphen, underscore,
2494 period, or colon.
2495 :param str exchange_type: The exchange type to use
2496 :param bool passive: Perform a declare or just check to see if it exists
2497 :param bool durable: Survive a reboot of RabbitMQ
2498 :param bool auto_delete: Remove when no more queues are bound to it
2499 :param bool internal: Can only be published to by other exchanges
2500 :param dict arguments: Custom key/value pair arguments for the exchange
2501 :returns: Method frame from the Exchange.Declare-ok response
2502 :rtype: `pika.frame.Method` having `method` attribute of type
2503 `spec.Exchange.DeclareOk`
2504
2505 """
2506 validators.require_string(exchange, 'exchange')
2507 with _CallbackResult(
2508 self._MethodFrameCallbackResultArgs) as declare_ok_result:
2509 self._impl.exchange_declare(
2510 exchange=exchange,
2511 exchange_type=exchange_type,
2512 passive=passive,
2513 durable=durable,
2514 auto_delete=auto_delete,
2515 internal=internal,
2516 arguments=arguments,
2517 callback=declare_ok_result.set_value_once)
2518
2519 self._flush_output(declare_ok_result.is_ready)
2520 return declare_ok_result.value.method_frame
2521
2522 def exchange_delete(self,
2523 exchange: Optional[str] = None,
2524 if_unused: bool = False
2525 ) -> pika.frame.Method[pika.spec.Exchange.DeleteOk]:
2526 """Delete the exchange.
2527
2528 :param str exchange: The exchange name
2529 :param bool if_unused: only delete if the exchange is unused
2530 :returns: Method frame from the Exchange.Delete-ok response
2531 :rtype: `pika.frame.Method` having `method` attribute of type
2532 `spec.Exchange.DeleteOk`
2533
2534 """
2535 with _CallbackResult(
2536 self._MethodFrameCallbackResultArgs) as delete_ok_result:
2537 self._impl.exchange_delete(exchange=exchange,
2538 if_unused=if_unused,
2539 callback=delete_ok_result.set_value_once)
2540
2541 self._flush_output(delete_ok_result.is_ready)
2542 return delete_ok_result.value.method_frame
2543
2544 def exchange_bind(
2545 self,
2546 destination: str,
2547 source: str,
2548 routing_key: str = '',
2549 arguments: Optional[Dict[str, Any]] = None
2550 ) -> pika.frame.Method[pika.spec.Exchange.BindOk]:
2551 """Bind an exchange to another exchange.
2552
2553 :param str destination: The destination exchange to bind
2554 :param str source: The source exchange to bind to
2555 :param str routing_key: The routing key to bind on
2556 :param dict arguments: Custom key/value pair arguments for the binding
2557 :returns: Method frame from the Exchange.Bind-ok response
2558 :rtype: `pika.frame.Method` having `method` attribute of type
2559 `spec.Exchange.BindOk`
2560
2561 """
2562 validators.require_string(destination, 'destination')
2563 validators.require_string(source, 'source')
2564 with _CallbackResult(self._MethodFrameCallbackResultArgs) as \
2565 bind_ok_result:
2566 self._impl.exchange_bind(destination=destination,
2567 source=source,
2568 routing_key=routing_key,
2569 arguments=arguments,
2570 callback=bind_ok_result.set_value_once)
2571
2572 self._flush_output(bind_ok_result.is_ready)
2573 return bind_ok_result.value.method_frame
2574
2575 def exchange_unbind(
2576 self,
2577 destination: Optional[str] = None,
2578 source: Optional[str] = None,
2579 routing_key: str = '',
2580 arguments: Optional[Dict[str, Any]] = None
2581 ) -> pika.frame.Method[pika.spec.Exchange.UnbindOk]:
2582 """Unbind an exchange from another exchange.
2583
2584 :param str destination: The destination exchange to unbind
2585 :param str source: The source exchange to unbind from
2586 :param str routing_key: The routing key to unbind
2587 :param dict arguments: Custom key/value pair arguments for the binding
2588 :returns: Method frame from the Exchange.Unbind-ok response
2589 :rtype: `pika.frame.Method` having `method` attribute of type
2590 `spec.Exchange.UnbindOk`
2591
2592 """
2593 with _CallbackResult(
2594 self._MethodFrameCallbackResultArgs) as unbind_ok_result:
2595 self._impl.exchange_unbind(destination=destination,
2596 source=source,
2597 routing_key=routing_key,
2598 arguments=arguments,
2599 callback=unbind_ok_result.set_value_once)
2600
2601 self._flush_output(unbind_ok_result.is_ready)
2602 return unbind_ok_result.value.method_frame
2603
2604 def queue_declare(
2605 self,
2606 queue: str,
2607 passive: bool = False,
2608 durable: bool = False,
2609 exclusive: bool = False,
2610 auto_delete: bool = False,
2611 arguments: Optional[Dict[str, Any]] = None
2612 ) -> pika.frame.Method[pika.spec.Queue.DeclareOk]:
2613 """Declare queue, create if needed. This method creates or checks a
2614 queue. When creating a new queue the client can specify various
2615 properties that control the durability of the queue and its contents,
2616 and the level of sharing for the queue.
2617
2618 Use an empty string as the queue name for the broker to auto-generate
2619 one. Retrieve this auto-generated queue name from the returned
2620 `spec.Queue.DeclareOk` method frame.
2621
2622 :param str queue: The queue name; if empty string, the broker will
2623 create a unique queue name
2624 :param bool passive: Only check to see if the queue exists and raise
2625 `ChannelClosed` if it doesn't
2626 :param bool durable: Survive reboots of the broker
2627 :param bool exclusive: Only allow access by the current connection
2628 :param bool auto_delete: Delete after consumer cancels or disconnects
2629 :param dict arguments: Custom key/value arguments for the queue
2630 :returns: Method frame from the Queue.Declare-ok response
2631 :rtype: `pika.frame.Method` having `method` attribute of type
2632 `spec.Queue.DeclareOk`
2633
2634 """
2635 validators.require_string(queue, 'queue')
2636 with _CallbackResult(self._MethodFrameCallbackResultArgs) as \
2637 declare_ok_result:
2638 self._impl.queue_declare(queue=queue,
2639 passive=passive,
2640 durable=durable,
2641 exclusive=exclusive,
2642 auto_delete=auto_delete,
2643 arguments=arguments,
2644 callback=declare_ok_result.set_value_once)
2645
2646 self._flush_output(declare_ok_result.is_ready)
2647 return declare_ok_result.value.method_frame
2648
2649 def queue_delete(self,
2650 queue: str,
2651 if_unused: bool = False,
2652 if_empty: bool = False
2653 ) -> pika.frame.Method[pika.spec.Queue.DeleteOk]:
2654 """Delete a queue from the broker.
2655
2656 :param str queue: The queue to delete
2657 :param bool if_unused: only delete if it's unused
2658 :param bool if_empty: only delete if the queue is empty
2659 :returns: Method frame from the Queue.Delete-ok response
2660 :rtype: `pika.frame.Method` having `method` attribute of type
2661 `spec.Queue.DeleteOk`
2662
2663 """
2664 with _CallbackResult(self._MethodFrameCallbackResultArgs) as \
2665 delete_ok_result:
2666 self._impl.queue_delete(queue=queue,
2667 if_unused=if_unused,
2668 if_empty=if_empty,
2669 callback=delete_ok_result.set_value_once)
2670
2671 self._flush_output(delete_ok_result.is_ready)
2672 return delete_ok_result.value.method_frame
2673
2674 def queue_purge(self,
2675 queue: str) -> pika.frame.Method[pika.spec.Queue.PurgeOk]:
2676 """Purge all of the messages from the specified queue
2677
2678 :param str queue: The queue to purge
2679 :returns: Method frame from the Queue.Purge-ok response
2680 :rtype: `pika.frame.Method` having `method` attribute of type
2681 `spec.Queue.PurgeOk`
2682
2683 """
2684 with _CallbackResult(self._MethodFrameCallbackResultArgs) as \
2685 purge_ok_result:
2686 self._impl.queue_purge(queue=queue,
2687 callback=purge_ok_result.set_value_once)
2688 self._flush_output(purge_ok_result.is_ready)
2689 return purge_ok_result.value.method_frame
2690
2691 def queue_bind(
2692 self,
2693 queue: str,
2694 exchange: str,
2695 routing_key: Optional[str] = None,
2696 arguments: Optional[Dict[str, Any]] = None
2697 ) -> pika.frame.Method[pika.spec.Queue.BindOk]:
2698 """Bind the queue to the specified exchange
2699
2700 :param str queue: The queue to bind to the exchange
2701 :param str exchange: The source exchange to bind to
2702 :param str routing_key: The routing key to bind on
2703 :param dict arguments: Custom key/value pair arguments for the binding
2704
2705 :returns: Method frame from the Queue.Bind-ok response
2706 :rtype: `pika.frame.Method` having `method` attribute of type
2707 `spec.Queue.BindOk`
2708
2709 """
2710 validators.require_string(queue, 'queue')
2711 validators.require_string(exchange, 'exchange')
2712 with _CallbackResult(
2713 self._MethodFrameCallbackResultArgs) as bind_ok_result:
2714 self._impl.queue_bind(queue=queue,
2715 exchange=exchange,
2716 routing_key=routing_key,
2717 arguments=arguments,
2718 callback=bind_ok_result.set_value_once)
2719 self._flush_output(bind_ok_result.is_ready)
2720 return bind_ok_result.value.method_frame
2721
2722 def queue_unbind(
2723 self,
2724 queue: str,
2725 exchange: str,
2726 routing_key: Optional[str] = None,
2727 arguments: Optional[Dict[str, Any]] = None
2728 ) -> pika.frame.Method[pika.spec.Queue.UnbindOk]:
2729 """Unbind a queue from an exchange.
2730
2731 :param str queue: The queue to unbind from the exchange
2732 :param str exchange: The source exchange to bind from
2733 :param str routing_key: The routing key to unbind
2734 :param dict arguments: Custom key/value pair arguments for the binding
2735
2736 :returns: Method frame from the Queue.Unbind-ok response
2737 :rtype: `pika.frame.Method` having `method` attribute of type
2738 `spec.Queue.UnbindOk`
2739
2740 """
2741 with _CallbackResult(self._MethodFrameCallbackResultArgs) as \
2742 unbind_ok_result:
2743 self._impl.queue_unbind(queue=queue,
2744 exchange=exchange,
2745 routing_key=routing_key,
2746 arguments=arguments,
2747 callback=unbind_ok_result.set_value_once)
2748 self._flush_output(unbind_ok_result.is_ready)
2749 return unbind_ok_result.value.method_frame
2750
2751 def tx_select(self) -> pika.frame.Method[pika.spec.Tx.SelectOk]:
2752 """Select standard transaction mode. This method sets the channel to use
2753 standard transactions. The client must use this method at least once on
2754 a channel before using the Commit or Rollback methods.
2755
2756 :returns: Method frame from the Tx.Select-ok response
2757 :rtype: `pika.frame.Method` having `method` attribute of type
2758 `spec.Tx.SelectOk`
2759
2760 """
2761 with _CallbackResult(self._MethodFrameCallbackResultArgs) as \
2762 select_ok_result:
2763 self._impl.tx_select(select_ok_result.set_value_once)
2764
2765 self._flush_output(select_ok_result.is_ready)
2766 return select_ok_result.value.method_frame
2767
2768 def tx_commit(self) -> pika.frame.Method[pika.spec.Tx.CommitOk]:
2769 """Commit a transaction.
2770
2771 :returns: Method frame from the Tx.Commit-ok response
2772 :rtype: `pika.frame.Method` having `method` attribute of type
2773 `spec.Tx.CommitOk`
2774
2775 """
2776 with _CallbackResult(self._MethodFrameCallbackResultArgs) as \
2777 commit_ok_result:
2778 self._impl.tx_commit(commit_ok_result.set_value_once)
2779
2780 self._flush_output(commit_ok_result.is_ready)
2781 return commit_ok_result.value.method_frame
2782
2783 def tx_rollback(self) -> pika.frame.Method[pika.spec.Tx.RollbackOk]:
2784 """Rollback a transaction.
2785
2786 :returns: Method frame from the Tx.Rollback-ok response
2787 :rtype: `pika.frame.Method` having `method` attribute of type
2788 `spec.Tx.RollbackOk`
2789
2790 """
2791 with _CallbackResult(self._MethodFrameCallbackResultArgs) as \
2792 rollback_ok_result:
2793 self._impl.tx_rollback(rollback_ok_result.set_value_once)
2794
2795 self._flush_output(rollback_ok_result.is_ready)
2796 return rollback_ok_result.value.method_frame