Debian Codegraph @

pika/adapters/twisted_connection.py

raw
1 """Using Pika with a Twisted reactor.
2
3 The interfaces in this module are Deferred-based when possible. This means that
4 the connection.channel() method and most of the channel methods return
5 Deferreds instead of taking a callback argument and that basic_consume()
6 returns a Twisted DeferredQueue where messages from the server will be
7 stored. Refer to the docstrings for TwistedProtocolConnection.channel() and the
8 TwistedChannel class for details.
9
10 """
11
12 from __future__ import annotations
13
14 import functools
15 import logging
16 from collections import namedtuple
17 from typing import Any, Callable, Dict, List, Optional, TYPE_CHECKING, Set, Type, Union
18
19 from twisted.internet import (defer, error as twisted_error, reactor, protocol)
20 import twisted.internet.base
21 import twisted.python
22 from twisted.python.failure import Failure
23 import twisted.python.failure
24
25 import pika.connection
26 from pika import exceptions, spec
27 from pika.adapters.utils import nbio_interface
28 from pika.adapters.utils.io_services_utils import check_callback_arg
29 from pika.exchange_type import ExchangeType
30 import pika.frame
31 import pika.spec
32
33 if TYPE_CHECKING:
34 from pika import channel
35 from pika import amqp_object
36 import twisted.internet.interfaces
37
38 # Twistisms
39 # pylint: disable=C0111,C0103
40 # Other
41 # pylint: disable=too-many-lines
42
43 LOGGER = logging.getLogger(__name__)
44
45
46 class ClosableDeferredQueue(defer.DeferredQueue):
47 """
48 Like the normal Twisted DeferredQueue, but after close() is called with an
49 exception instance all pending Deferreds are errbacked and further attempts
50 to call get() or put() return a Failure wrapping that exception.
51 """
52
53 def __init__(self,
54 size: Optional[int] = None,
55 backlog: Optional[int] = None):
56 self.closed: Optional[Exception] = None
57 super().__init__(size, backlog)
58
59 def put(self, obj: Any) -> Optional[ # type: ignore[override]
60 defer.Deferred[Any]]:
61 """
62 Like the original :meth:`DeferredQueue.put` method, but returns an
63 errback if the queue is closed.
64
65 """
66 if self.closed:
67 LOGGER.error('Impossible to put to the queue, it is closed.')
68 return defer.fail(self.closed)
69 return defer.DeferredQueue.put(self,
70 obj) # type: ignore[func-returns-value]
71
72 def get(self) -> defer.Deferred[Any]:
73 """
74 Returns a Deferred that will fire with the next item in the queue, when
75 it's available.
76
77 The Deferred will errback if the queue is closed.
78
79 :returns: Deferred that fires with the next item.
80 :rtype: Deferred
81
82 """
83 if self.closed:
84 LOGGER.error('Impossible to get from the queue, it is closed.')
85 return defer.fail(self.closed)
86 return defer.DeferredQueue.get(self)
87
88 def close(self, reason: Optional[Exception]) -> None:
89 """Closes the queue.
90
91 Errback the pending calls to :meth:`get()`.
92
93 """
94 if self.closed:
95 LOGGER.warning('Queue was already closed with reason: %s.',
96 self.closed)
97 self.closed = reason
98 while self.waiting:
99 self.waiting.pop().errback(reason)
100 self.pending = []
101
102
103 ReceivedMessage = namedtuple("ReceivedMessage",
104 ["channel", "method", "properties", "body"])
105
106
107 class TwistedChannel:
108 """A wrapper around Pika's Channel.
109
110 Channel methods that normally take a callback argument are wrapped to
111 return a Deferred that fires with whatever would be passed to the callback.
112 If the channel gets closed, all pending Deferreds are errbacked with a
113 ChannelClosed exception. The returned Deferreds fire with whatever
114 arguments the callback to the original method would receive.
115
116 Some methods like basic_consume and basic_get are wrapped in a special way,
117 see their docstrings for details.
118 """
119
120 def __init__(self, channel: channel.Channel) -> None:
121 self._channel = channel
122 self._closed: Optional[Exception] = None
123 self._calls: Set[defer.Deferred[Any]] = set()
124 self._consumers: Dict[str, ClosableDeferredQueue] = {}
125 # Store Basic.Get calls so we can handle GetEmpty replies
126 self._basic_get_deferred: Optional[defer.Deferred[Any]] = None
127 self._channel.add_callback(self._on_getempty, [spec.Basic.GetEmpty],
128 False)
129 # We need this mapping to close the ClosableDeferredQueue when a queue
130 # is deleted.
131 self._queue_name_to_consumer_tags: Dict[str, Set[str]] = {}
132 # Whether RabbitMQ delivery confirmation has been enabled
133 self._delivery_confirmation = False
134 self._delivery_message_id: int = None # type: ignore[assignment]
135 self._deliveries: Dict[int, defer.Deferred[Any]] = {}
136 # Holds a ReceivedMessage object representing a message received via
137 # Basic.Return in publisher-acknowledgments mode.
138 self._puback_return: Optional[ReceivedMessage] = None
139
140 self.on_closed: defer.Deferred[Any] = defer.Deferred()
141 self._channel.add_on_close_callback(self._on_channel_closed)
142 self._channel.add_on_cancel_callback(
143 self._on_consumer_cancelled_by_broker)
144
145 def __repr__(self) -> str:
146 return '<{cls} channel={chan!r}>'.format(cls=self.__class__.__name__,
147 chan=self._channel)
148
149 def _on_channel_closed(self, _channel: channel.Channel,
150 reason: Optional[Exception]) -> None:
151 # enter the closed state
152 self._closed = reason
153 # errback all pending calls
154 for d in self._calls:
155 d.errback(self._closed)
156 # errback all pending deliveries
157 for d in self._deliveries.values():
158 d.errback(self._closed)
159 # close all open queues
160 for consumer in self._consumers.values():
161 consumer.close(self._closed)
162 # release references to stored objects
163 self._calls = set()
164 self._deliveries = {}
165 self._consumers = {}
166 self.on_closed.callback(self._closed)
167
168 def _on_consumer_cancelled_by_broker(
169 self, method_frame: pika.frame.Method[pika.spec.Basic.Cancel]
170 ) -> Union[pika.frame.Method[pika.spec.Basic.Cancel],
171 pika.frame.Method[pika.spec.Basic.CancelOk]]:
172 """Called by impl when broker cancels consumer via Basic.Cancel.
173
174 This is a RabbitMQ-specific feature. The circumstances include deletion
175 of queue being consumed as well as failure of a HA node responsible for
176 the queue being consumed.
177
178 :param pika.frame.Method method_frame: method frame with the
179 `spec.Basic.Cancel` method
180
181 """
182 return self._on_consumer_cancelled(method_frame)
183
184 def _on_consumer_cancelled(
185 self, frame: Union[pika.frame.Method[pika.spec.Basic.Cancel],
186 pika.frame.Method[pika.spec.Basic.CancelOk]]
187 ) -> Union[pika.frame.Method[pika.spec.Basic.Cancel],
188 pika.frame.Method[pika.spec.Basic.CancelOk]]:
189 """Called when the broker cancels a consumer via Basic.Cancel or when
190 the broker responds to a Basic.Cancel request by Basic.CancelOk.
191
192 :param pika.frame.Method frame: method frame with the
193 `spec.Basic.Cancel` or `spec.Basic.CancelOk` method
194
195 """
196 consumer_tag = frame.method.consumer_tag
197 if consumer_tag not in self._consumers:
198 # Could be cancelled by user or broker earlier
199 LOGGER.warning('basic_cancel - consumer not found: %s',
200 consumer_tag)
201 return frame
202 self._consumers[consumer_tag].close(exceptions.ConsumerCancelled())
203 del self._consumers[consumer_tag]
204 # Remove from the queue-to-ctags index:
205 for ctags in self._queue_name_to_consumer_tags.values():
206 try:
207 ctags.remove(consumer_tag)
208 except KeyError:
209 continue
210 return frame
211
212 def _on_getempty(
213 self,
214 _method_frame: pika.frame.Method[pika.spec.Basic.Get]) -> None:
215 """Callback the Basic.Get deferred with None.
216 """
217 if self._basic_get_deferred is None:
218 LOGGER.warning("Got Basic.GetEmpty but no Basic.Get calls "
219 "were pending.")
220 return
221 self._basic_get_deferred.callback(None)
222
223 def _wrap_channel_method(self,
224 name: str) -> Callable[..., defer.Deferred[Any]]:
225 """Wrap Pika's Channel method to make it return a Deferred that fires
226 when the method completes and errbacks if the channel gets closed. If
227 the original method's callback would receive more than one argument,
228 the Deferred fires with a tuple of argument values.
229
230 """
231 method = getattr(self._channel, name)
232
233 @functools.wraps(method)
234 def wrapped(*args, **kwargs):
235 if self._closed:
236 return defer.fail(self._closed)
237
238 d: defer.Deferred = defer.Deferred()
239 self._calls.add(d)
240 d.addCallback(self._clear_call, d)
241
242 def single_argument(*args):
243 """
244 Make sure that the deferred is called with a single argument.
245 In case the original callback fires with more than one, convert
246 to a tuple.
247 """
248 if len(args) > 1:
249 d.callback(tuple(args))
250 else:
251 d.callback(*args)
252
253 kwargs['callback'] = single_argument
254
255 try:
256 method(*args, **kwargs)
257 except Exception: # pylint: disable=W0703
258 return defer.fail()
259 return d
260
261 return wrapped
262
263 def _clear_call(self, ret: Any, d: defer.Deferred[Any]) -> Any:
264 self._calls.discard(d)
265 return ret
266
267 # Public Channel attributes
268
269 @property
270 def channel_number(self) -> int:
271 return self._channel.channel_number
272
273 @property
274 def connection(self) -> pika.connection.Connection:
275 return self._channel.connection
276
277 @property
278 def is_closed(self) -> bool:
279 """Returns True if the channel is closed.
280
281 :rtype: bool
282
283 """
284 return self._channel.is_closed
285
286 @property
287 def is_closing(self) -> bool:
288 """Returns True if client-initiated closing of the channel is in
289 progress.
290
291 :rtype: bool
292
293 """
294 return self._channel.is_closing
295
296 @property
297 def is_open(self) -> bool:
298 """Returns True if the channel is open.
299
300 :rtype: bool
301
302 """
303 return self._channel.is_open
304
305 @property
306 def flow_active(self) -> bool:
307 return self._channel.flow_active
308
309 @property
310 def consumer_tags(self) -> List[str]:
311 return self._channel.consumer_tags
312
313 # Deferred-equivalents of public Channel methods
314
315 def callback_deferred(self, deferred: defer.Deferred[Any],
316 replies: List[Type[amqp_object.Method]]) -> None:
317 """Pass in a Deferred and a list replies from the RabbitMQ broker which
318 you'd like the Deferred to be callbacked on with the frame as callback
319 value.
320
321 :param Deferred deferred: The Deferred to callback
322 :param list replies: The replies to callback on
323
324 """
325 self._channel.add_callback(deferred.callback, replies)
326
327 # Public Channel methods
328
329 def add_on_return_callback(self, callback: Callable[[ReceivedMessage],
330 None]):
331 """Pass a callback function that will be called when a published
332 message is rejected and returned by the server via `Basic.Return`.
333
334 :param callable callback: The method to call on callback with the
335 message as only argument. The message is a named tuple with
336 the following attributes
337 - channel: this TwistedChannel
338 - method: pika.spec.Basic.Return
339 - properties: pika.spec.BasicProperties
340 - body: bytes
341 """
342 self._channel.add_on_return_callback(
343 lambda _channel, method, properties, body: callback(
344 ReceivedMessage(
345 channel=self,
346 method=method,
347 properties=properties,
348 body=body,
349 )))
350
351 def basic_ack(self, delivery_tag: int = 0, multiple: bool = False) -> None:
352 """Acknowledge one or more messages. When sent by the client, this
353 method acknowledges one or more messages delivered via the Deliver or
354 Get-Ok methods. When sent by server, this method acknowledges one or
355 more messages published with the Publish method on a channel in
356 confirm mode. The acknowledgement can be for a single message or a
357 set of messages up to and including a specific message.
358
359 :param integer delivery_tag: int/long The server-assigned delivery tag
360 :param bool multiple: If set to True, the delivery tag is treated as
361 "up to and including", so that multiple messages
362 can be acknowledged with a single method. If set
363 to False, the delivery tag refers to a single
364 message. If the multiple field is 1, and the
365 delivery tag is zero, this indicates
366 acknowledgement of all outstanding messages.
367
368 """
369 return self._channel.basic_ack(delivery_tag=delivery_tag,
370 multiple=multiple)
371
372 def basic_cancel(
373 self,
374 consumer_tag: str = ''
375 ) -> defer.Deferred[Union[pika.frame.Method[pika.spec.Basic.CancelOk],
376 pika.frame.Method[pika.spec.Basic.Cancel]]]:
377 """This method cancels a consumer. This does not affect already
378 delivered messages, but it does mean the server will not send any more
379 messages for that consumer. The client may receive an arbitrary number
380 of messages in between sending the cancel method and receiving the
381 cancel-ok reply. It may also be sent from the server to the client in
382 the event of the consumer being unexpectedly cancelled (i.e. cancelled
383 for any reason other than the server receiving the corresponding
384 basic.cancel from the client). This allows clients to be notified of
385 the loss of consumers due to events such as queue deletion.
386
387 This method wraps :meth:`Channel.basic_cancel
388 <pika.channel.Channel.basic_cancel>` and closes any deferred queue
389 associated with that consumer.
390
391 :param str consumer_tag: Identifier for the consumer
392 :returns: Deferred that fires on the Basic.CancelOk response
393 :rtype: Deferred
394 :raises ValueError:
395
396 """
397 wrapped = self._wrap_channel_method('basic_cancel')
398 d = wrapped(consumer_tag=consumer_tag)
399 return d.addCallback(self._on_consumer_cancelled)
400
401 def basic_consume(
402 self,
403 queue: str,
404 auto_ack: bool = False,
405 exclusive: bool = False,
406 consumer_tag: Optional[str] = None,
407 arguments: Optional[Dict[str, Any]] = None) -> defer.Deferred[Any]:
408 """Consume from a server queue.
409
410 Sends the AMQP 0-9-1 command Basic.Consume to the broker and binds
411 messages for the consumer_tag to a
412 :class:`ClosableDeferredQueue`. If you do not pass in a
413 consumer_tag, one will be automatically generated for you.
414
415 For more information on basic_consume, see:
416 Tutorial 2 at https://www.rabbitmq.com/getstarted.html
417 https://www.rabbitmq.com/confirms.html
418 https://www.rabbitmq.com/amqp-0-9-1-reference.html#basic.consume
419
420 :param str queue: The queue to consume from. Use the empty string to
421 specify the most recent server-named queue for this channel.
422 :param bool auto_ack: if set to True, automatic acknowledgement mode
423 will be used (see https://www.rabbitmq.com/confirms.html). This
424 corresponds with the 'no_ack' parameter in the basic.consume AMQP
425 0.9.1 method
426 :param bool exclusive: Don't allow other consumers on the queue
427 :param str consumer_tag: Specify your own consumer tag
428 :param dict arguments: Custom key/value pair arguments for the consumer
429 :returns: Deferred that fires with a tuple
430 ``(queue_object, consumer_tag)``. The Deferred will errback with an
431 instance of :class:`exceptions.ChannelClosed` if the call fails.
432 The queue object is an instance of :class:`ClosableDeferredQueue`,
433 where data received from the queue will be stored. Clients should
434 use its :meth:`get() <ClosableDeferredQueue.get>` method to fetch
435 an individual message, which will return a Deferred firing with a
436 namedtuple whose attributes are:
437 - channel: this TwistedChannel
438 - method: pika.spec.Basic.Deliver
439 - properties: pika.spec.BasicProperties
440 - body: bytes
441 :rtype: Deferred
442
443 """
444 if self._closed:
445 return defer.fail(self._closed)
446
447 queue_obj = ClosableDeferredQueue()
448 d: defer.Deferred[Any] = defer.Deferred()
449 self._calls.add(d)
450
451 def on_consume_ok(frame):
452 consumer_tag = frame.method.consumer_tag
453 self._queue_name_to_consumer_tags.setdefault(
454 queue, set()).add(consumer_tag)
455 self._consumers[consumer_tag] = queue_obj
456 self._calls.discard(d)
457 d.callback((queue_obj, consumer_tag))
458
459 def on_message_callback(_channel, method, properties, body):
460 """Add the ReceivedMessage to the queue, while replacing the
461 channel implementation.
462 """
463 queue_obj.put(
464 ReceivedMessage(
465 channel=self,
466 method=method,
467 properties=properties,
468 body=body,
469 ))
470
471 try:
472 self._channel.basic_consume(
473 queue=queue,
474 on_message_callback=on_message_callback,
475 auto_ack=auto_ack,
476 exclusive=exclusive,
477 consumer_tag=consumer_tag,
478 arguments=arguments,
479 callback=on_consume_ok,
480 )
481 except Exception: # pylint: disable=W0703
482 return defer.fail()
483
484 return d
485
486 def basic_get(self,
487 queue: str,
488 auto_ack: bool = False) -> defer.Deferred[Any]:
489 """Get a single message from the AMQP broker.
490
491 Will return If the queue is empty, it will return None.
492 If you want to
493 be notified of Basic.GetEmpty, use the Channel.add_callback method
494 adding your Basic.GetEmpty callback which should expect only one
495 parameter, frame. Due to implementation details, this cannot be called
496 a second time until the callback is executed. For more information on
497 basic_get and its parameters, see:
498
499 https://www.rabbitmq.com/amqp-0-9-1-reference.html#basic.get
500
501 This method wraps :meth:`Channel.basic_get
502 <pika.channel.Channel.basic_get>`.
503
504 :param str queue: The queue from which to get a message. Use the empty
505 string to specify the most recent server-named queue
506 for this channel.
507 :param bool auto_ack: Tell the broker to not expect a reply
508 :returns: Deferred that fires with a namedtuple whose attributes are:
509 - channel: this TwistedChannel
510 - method: pika.spec.Basic.GetOk
511 - properties: pika.spec.BasicProperties
512 - body: bytes
513 If the queue is empty, None will be returned.
514 :rtype: Deferred
515 :raises pika.exceptions.DuplicateGetOkCallback:
516
517 """
518 if self._basic_get_deferred is not None:
519 raise exceptions.DuplicateGetOkCallback()
520
521 def create_namedtuple(result):
522 if result is None:
523 return None
524 _channel, method, properties, body = result
525 return ReceivedMessage(
526 channel=self,
527 method=method,
528 properties=properties,
529 body=body,
530 )
531
532 def cleanup_attribute(result):
533 self._basic_get_deferred = None
534 return result
535
536 d = self._wrap_channel_method("basic_get")(queue=queue,
537 auto_ack=auto_ack)
538 d.addCallback(create_namedtuple)
539 d.addBoth(cleanup_attribute)
540 self._basic_get_deferred = d
541 return d
542
543 def basic_nack(self,
544 delivery_tag: int = 0,
545 multiple: bool = False,
546 requeue: bool = True) -> None:
547 """This method allows a client to reject one or more incoming messages.
548 It can be used to interrupt and cancel large incoming messages, or
549 return untreatable messages to their original queue.
550
551 :param integer delivery_tag: int/long The server-assigned delivery tag
552 :param bool multiple: If set to True, the delivery tag is treated as
553 "up to and including", so that multiple messages
554 can be acknowledged with a single method. If set
555 to False, the delivery tag refers to a single
556 message. If the multiple field is 1, and the
557 delivery tag is zero, this indicates
558 acknowledgement of all outstanding messages.
559 :param bool requeue: If requeue is true, the server will attempt to
560 requeue the message. If requeue is false or the
561 requeue attempt fails the messages are discarded
562 or dead-lettered.
563
564 """
565 return self._channel.basic_nack(
566 delivery_tag=delivery_tag,
567 multiple=multiple,
568 requeue=requeue,
569 )
570
571 def basic_publish(self,
572 exchange: str,
573 routing_key: str,
574 body: bytes,
575 properties: Optional[spec.BasicProperties] = None,
576 mandatory: bool = False) -> defer.Deferred[Any]:
577 """Publish to the channel with the given exchange, routing key and body.
578
579 This method wraps :meth:`Channel.basic_publish
580 <pika.channel.Channel.basic_publish>`, but makes sure the channel is
581 not closed before publishing.
582
583 For more information on basic_publish and what the parameters do, see:
584
585 https://www.rabbitmq.com/amqp-0-9-1-reference.html#basic.publish
586
587 :param str exchange: The exchange to publish to
588 :param str routing_key: The routing key to bind on
589 :param bytes body: The message body
590 :param pika.spec.BasicProperties properties: Basic.properties
591 :param bool mandatory: The mandatory flag
592 :returns: A Deferred that fires with the result of the channel's
593 basic_publish.
594 :rtype: Deferred
595 :raises UnroutableError: raised when a message published in
596 publisher-acknowledgments mode (see
597 `BlockingChannel.confirm_delivery`) is returned via `Basic.Return`
598 followed by `Basic.Ack`.
599 :raises NackError: raised when a message published in
600 publisher-acknowledgements mode is Nack'ed by the broker. See
601 `BlockingChannel.confirm_delivery`.
602
603 """
604 if self._closed:
605 return defer.fail(self._closed)
606 result = self._channel.basic_publish( # type: ignore[func-returns-value]
607 exchange=exchange,
608 routing_key=routing_key,
609 body=body,
610 properties=properties,
611 mandatory=mandatory)
612 if not self._delivery_confirmation:
613 return defer.succeed(result)
614 else:
615 # See https://www.rabbitmq.com/confirms.html#publisher-confirms
616 self._delivery_message_id += 1
617 self._deliveries[self._delivery_message_id] = defer.Deferred()
618 return self._deliveries[self._delivery_message_id]
619
620 def basic_qos(self,
621 prefetch_size: int = 0,
622 prefetch_count: int = 0,
623 global_qos: bool = False) -> defer.Deferred[Any]:
624 """Specify quality of service. This method requests a specific quality
625 of service. The QoS can be specified for the current channel or for all
626 channels on the connection. The client can request that messages be
627 sent in advance so that when the client finishes processing a message,
628 the following message is already held locally, rather than needing to
629 be sent down the channel. Prefetching gives a performance improvement.
630
631 :param int prefetch_size: This field specifies the prefetch window
632 size. The server will send a message in
633 advance if it is equal to or smaller in size
634 than the available prefetch size (and also
635 falls into other prefetch limits). May be
636 set to zero, meaning "no specific limit",
637 although other prefetch limits may still
638 apply. The prefetch-size is ignored by
639 consumers who have enabled the no-ack
640 option.
641 :param int prefetch_count: Specifies a prefetch window in terms of
642 whole messages. This field may be used in
643 combination with the prefetch-size field; a
644 message will only be sent in advance if both
645 prefetch windows (and those at the channel
646 and connection level) allow it. The
647 prefetch-count is ignored by consumers who
648 have enabled the no-ack option.
649 :param bool global_qos: Should the QoS apply to all channels on the
650 connection.
651 :returns: Deferred that fires on the Basic.QosOk response
652 :rtype: Deferred
653
654 """
655 return self._wrap_channel_method("basic_qos")(
656 prefetch_size=prefetch_size,
657 prefetch_count=prefetch_count,
658 global_qos=global_qos,
659 )
660
661 def basic_reject(self, delivery_tag: int, requeue: bool = True) -> None:
662 """Reject an incoming message. This method allows a client to reject a
663 message. It can be used to interrupt and cancel large incoming
664 messages, or return untreatable messages to their original queue.
665
666 :param integer delivery_tag: int/long The server-assigned delivery tag
667 :param bool requeue: If requeue is true, the server will attempt to
668 requeue the message. If requeue is false or the
669 requeue attempt fails the messages are discarded
670 or dead-lettered.
671 :raises: TypeError
672
673 """
674 return self._channel.basic_reject(delivery_tag=delivery_tag,
675 requeue=requeue)
676
677 def basic_recover(self, requeue: bool = False) -> defer.Deferred[Any]:
678 """This method asks the server to redeliver all unacknowledged messages
679 on a specified channel. Zero or more messages may be redelivered. This
680 method replaces the asynchronous Recover.
681
682 :param bool requeue: If False, the message will be redelivered to the
683 original recipient. If True, the server will
684 attempt to requeue the message, potentially then
685 delivering it to an alternative subscriber.
686 :returns: Deferred that fires on the Basic.RecoverOk response
687 :rtype: Deferred
688
689 """
690 return self._wrap_channel_method("basic_recover")(requeue=requeue)
691
692 def close(self,
693 reply_code: int = 0,
694 reply_text: str = "Normal shutdown") -> None:
695 """Invoke a graceful shutdown of the channel with the AMQP Broker.
696
697 If channel is OPENING, transition to CLOSING and suppress the incoming
698 Channel.OpenOk, if any.
699
700 :param int reply_code: The reason code to send to broker
701 :param str reply_text: The reason text to send to broker
702
703 :raises ChannelWrongStateError: if channel is closed or closing
704
705 """
706 return self._channel.close(reply_code=reply_code, reply_text=reply_text)
707
708 def confirm_delivery(self) -> defer.Deferred[Any]:
709 """Turn on Confirm mode in the channel. Pass in a callback to be
710 notified by the Broker when a message has been confirmed as received or
711 rejected (Basic.Ack, Basic.Nack) from the broker to the publisher.
712
713 For more information see:
714 https://www.rabbitmq.com/confirms.html#publisher-confirms
715
716 :returns: Deferred that fires on the Confirm.SelectOk response
717 :rtype: Deferred
718
719 """
720 if self._delivery_confirmation:
721 LOGGER.error('confirm_delivery: confirmation was already enabled.')
722 return defer.succeed(None)
723 wrapped = self._wrap_channel_method('confirm_delivery')
724 d = wrapped(ack_nack_callback=self._on_delivery_confirmation)
725
726 def set_delivery_confirmation(result):
727 self._delivery_confirmation = True
728 self._delivery_message_id = 0
729 LOGGER.debug("Delivery confirmation enabled.")
730 return result
731
732 d.addCallback(set_delivery_confirmation)
733 # Unroutable messages returned after this point will be in the context
734 # of publisher acknowledgments
735 self._channel.add_on_return_callback(self._on_puback_message_returned)
736 return d
737
738 def _on_delivery_confirmation(
739 self, method_frame: Union[pika.frame.Method[pika.spec.Basic.Ack],
740 pika.frame.Method[pika.spec.Basic.Nack]]
741 ) -> None:
742 """Invoked by pika when RabbitMQ responds to a Basic.Publish RPC
743 command, passing in either a Basic.Ack or Basic.Nack frame with
744 the delivery tag of the message that was published. The delivery tag
745 is an integer counter indicating the message number that was sent
746 on the channel via Basic.Publish. Here we're just doing house keeping
747 to keep track of stats and remove message numbers that we expect
748 a delivery confirmation of from the list used to keep track of messages
749 that are pending confirmation.
750
751 :param pika.frame.Method method_frame: Basic.Ack or Basic.Nack frame
752
753 """
754 delivery_tag = method_frame.method.delivery_tag
755 if delivery_tag not in self._deliveries:
756 LOGGER.error("Delivery tag %s not found in the pending deliveries",
757 delivery_tag)
758 return
759 if method_frame.method.multiple:
760 tags = [tag for tag in self._deliveries if tag <= delivery_tag]
761 tags.sort()
762 else:
763 tags = [delivery_tag]
764 for tag in tags:
765 d = self._deliveries[tag]
766 del self._deliveries[tag]
767 if isinstance(method_frame.method, pika.spec.Basic.Nack):
768 # Broker was unable to process the message due to internal
769 # error
770 LOGGER.warning(
771 "Message was Nack'ed by broker: nack=%r; channel=%s;",
772 method_frame.method, self.channel_number)
773 if self._puback_return is not None:
774 returned_messages: List[ReceivedMessage] = [
775 self._puback_return
776 ]
777 self._puback_return = None
778 else:
779 returned_messages = []
780 d.errback(
781 exceptions.NackError(returned_messages)) # type: ignore
782 else:
783 assert isinstance(method_frame.method, pika.spec.Basic.Ack)
784 if self._puback_return is not None:
785 # Unroutable message was returned
786 returned_messages = [self._puback_return]
787 self._puback_return = None
788 d.errback(exceptions.UnroutableError(
789 returned_messages)) # type: ignore
790 else:
791 d.callback(method_frame.method)
792
793 def _on_puback_message_returned(self, channel: channel.Channel,
794 method: spec.Basic.Return,
795 properties: spec.BasicProperties,
796 body: bytes) -> None:
797 """Called as the result of Basic.Return from broker in
798 publisher-acknowledgements mode. Saves the info as a ReturnedMessage
799 instance in self._puback_return.
800
801 :param pika.Channel channel: our self._impl channel
802 :param pika.spec.Basic.Return method:
803 :param pika.spec.BasicProperties properties: message properties
804 :param bytes body: returned message body; empty string if no body
805
806 """
807 assert isinstance(method, spec.Basic.Return), method
808 assert isinstance(properties, spec.BasicProperties), properties
809
810 LOGGER.warning(
811 "Published message was returned: _delivery_confirmation=%s; "
812 "channel=%s; method=%r; properties=%r; body_size=%d; "
813 "body_prefix=%.255r", self._delivery_confirmation,
814 channel.channel_number, method, properties,
815 len(body) if body is not None else None, body)
816
817 self._puback_return = ReceivedMessage(channel=self,
818 method=method,
819 properties=properties,
820 body=body)
821
822 def exchange_bind(
823 self,
824 destination: str,
825 source: str,
826 routing_key: str = '',
827 arguments: Optional[Dict[str, Any]] = None) -> defer.Deferred[Any]:
828 """Bind an exchange to another exchange.
829
830 :param str destination: The destination exchange to bind
831 :param str source: The source exchange to bind to
832 :param str routing_key: The routing key to bind on
833 :param dict arguments: Custom key/value pair arguments for the binding
834 :raises ValueError:
835 :returns: Deferred that fires on the Exchange.BindOk response
836 :rtype: Deferred
837
838 """
839 return self._wrap_channel_method("exchange_bind")(
840 destination=destination,
841 source=source,
842 routing_key=routing_key,
843 arguments=arguments,
844 )
845
846 def exchange_declare(
847 self,
848 exchange: str,
849 exchange_type: Union[str, ExchangeType] = ExchangeType.direct,
850 passive: bool = False,
851 durable: bool = False,
852 auto_delete: bool = False,
853 internal: bool = False,
854 arguments: Optional[Dict[str, Any]] = None) -> defer.Deferred[Any]:
855 """This method creates an exchange if it does not already exist, and if
856 the exchange exists, verifies that it is of the correct and expected
857 class.
858
859 If passive set, the server will reply with Declare-Ok if the exchange
860 already exists with the same name, and raise an error if not and if the
861 exchange does not already exist, the server MUST raise a channel
862 exception with reply code 404 (not found).
863
864 :param str exchange: The exchange name consists of a non-empty sequence
865 of these characters: letters, digits, hyphen, underscore, period,
866 or colon
867 :param str exchange_type: The exchange type to use
868 :param bool passive: Perform a declare or just check to see if it
869 exists
870 :param bool durable: Survive a reboot of RabbitMQ
871 :param bool auto_delete: Remove when no more queues are bound to it
872 :param bool internal: Can only be published to by other exchanges
873 :param dict arguments: Custom key/value pair arguments for the exchange
874 :returns: Deferred that fires on the Exchange.DeclareOk response
875 :rtype: Deferred
876 :raises ValueError:
877
878 """
879 return self._wrap_channel_method("exchange_declare")(
880 exchange=exchange,
881 exchange_type=exchange_type,
882 passive=passive,
883 durable=durable,
884 auto_delete=auto_delete,
885 internal=internal,
886 arguments=arguments,
887 )
888
889 def exchange_delete(self,
890 exchange: Optional[str] = None,
891 if_unused: bool = False) -> defer.Deferred[Any]:
892 """Delete the exchange.
893
894 :param str exchange: The exchange name
895 :param bool if_unused: only delete if the exchange is unused
896 :returns: Deferred that fires on the Exchange.DeleteOk response
897 :rtype: Deferred
898 :raises ValueError:
899
900 """
901 return self._wrap_channel_method("exchange_delete")(
902 exchange=exchange,
903 if_unused=if_unused,
904 )
905
906 def exchange_unbind(
907 self,
908 destination: str,
909 source: str,
910 routing_key: str = '',
911 arguments: Optional[Dict[str, Any]] = None) -> defer.Deferred[Any]:
912 """Unbind an exchange from another exchange.
913
914 :param str destination: The destination exchange to unbind
915 :param str source: The source exchange to unbind from
916 :param str routing_key: The routing key to unbind
917 :param dict arguments: Custom key/value pair arguments for the binding
918 :returns: Deferred that fires on the Exchange.UnbindOk response
919 :rtype: Deferred
920 :raises ValueError:
921
922 """
923 return self._wrap_channel_method("exchange_unbind")(
924 destination=destination,
925 source=source,
926 routing_key=routing_key,
927 arguments=arguments,
928 )
929
930 def flow(self, active: bool = True) -> defer.Deferred[Any]:
931 """Turn Channel flow control off and on.
932
933 Returns a Deferred that will fire with a bool indicating the channel
934 flow state. For more information, please reference:
935
936 https://www.rabbitmq.com/amqp-0-9-1-reference.html#channel.flow
937
938 :param bool active: Turn flow on or off
939 :returns: Deferred that fires with the channel flow state
940 :rtype: Deferred
941 :raises ValueError:
942
943 """
944 return self._wrap_channel_method("flow")(active=active)
945
946 def open(self) -> None:
947 """Open the channel"""
948 return self._channel.open()
949
950 def queue_bind(
951 self,
952 queue: str,
953 exchange: str,
954 routing_key: Optional[str] = None,
955 arguments: Optional[Dict[str, Any]] = None) -> defer.Deferred[Any]:
956 """Bind the queue to the specified exchange
957
958 :param str queue: The queue to bind to the exchange
959 :param str exchange: The source exchange to bind to
960 :param str routing_key: The routing key to bind on
961 :param dict arguments: Custom key/value pair arguments for the binding
962 :returns: Deferred that fires on the Queue.BindOk response
963 :rtype: Deferred
964 :raises ValueError:
965
966 """
967 return self._wrap_channel_method("queue_bind")(
968 queue=queue,
969 exchange=exchange,
970 routing_key=routing_key,
971 arguments=arguments,
972 )
973
974 def queue_declare(
975 self,
976 queue: str,
977 passive: bool = False,
978 durable: bool = False,
979 exclusive: bool = False,
980 auto_delete: bool = False,
981 arguments: Optional[Dict[str, Any]] = None) -> defer.Deferred[Any]:
982 """Declare queue, create if needed. This method creates or checks a
983 queue. When creating a new queue the client can specify various
984 properties that control the durability of the queue and its contents,
985 and the level of sharing for the queue.
986
987 Use an empty string as the queue name for the broker to auto-generate
988 one
989
990 :param str queue: The queue name; if empty string, the broker will
991 create a unique queue name
992 :param bool passive: Only check to see if the queue exists
993 :param bool durable: Survive reboots of the broker
994 :param bool exclusive: Only allow access by the current connection
995 :param bool auto_delete: Delete after consumer cancels or disconnects
996 :param dict arguments: Custom key/value arguments for the queue
997 :returns: Deferred that fires on the Queue.DeclareOk response
998 :rtype: Deferred
999 :raises ValueError:
1000
1001 """
1002 return self._wrap_channel_method("queue_declare")(
1003 queue=queue,
1004 passive=passive,
1005 durable=durable,
1006 exclusive=exclusive,
1007 auto_delete=auto_delete,
1008 arguments=arguments,
1009 )
1010
1011 def queue_delete(self,
1012 queue: str,
1013 if_unused: bool = False,
1014 if_empty: bool = False) -> defer.Deferred[Any]:
1015 """Delete a queue from the broker.
1016
1017
1018 This method wraps :meth:`Channel.queue_delete
1019 <pika.channel.Channel.queue_delete>`, and removes the reference to the
1020 queue object after it gets deleted on the server.
1021
1022 :param str queue: The queue to delete
1023 :param bool if_unused: only delete if it's unused
1024 :param bool if_empty: only delete if the queue is empty
1025 :returns: Deferred that fires on the Queue.DeleteOk response
1026 :rtype: Deferred
1027 :raises ValueError:
1028
1029 """
1030 wrapped = self._wrap_channel_method('queue_delete')
1031 d = wrapped(queue=queue, if_unused=if_unused, if_empty=if_empty)
1032
1033 def _clear_consumer(ret, queue_name):
1034 for consumer_tag in list(
1035 self._queue_name_to_consumer_tags.get(queue_name, set())):
1036 self._consumers[consumer_tag].close(
1037 exceptions.ConsumerCancelled("Queue %s was deleted." %
1038 queue_name))
1039 del self._consumers[consumer_tag]
1040 self._queue_name_to_consumer_tags[queue_name].remove(
1041 consumer_tag)
1042 return ret
1043
1044 return d.addCallback(_clear_consumer, queue)
1045
1046 def queue_purge(self, queue: str) -> defer.Deferred[Any]:
1047 """Purge all of the messages from the specified queue
1048
1049 :param str queue: The queue to purge
1050 :returns: Deferred that fires on the Queue.PurgeOk response
1051 :rtype: Deferred
1052 :raises ValueError:
1053
1054 """
1055 return self._wrap_channel_method("queue_purge")(queue=queue)
1056
1057 def queue_unbind(
1058 self,
1059 queue: str,
1060 exchange: Optional[str],
1061 routing_key: Optional[str] = None,
1062 arguments: Optional[Dict[str, Any]] = None) -> defer.Deferred[Any]:
1063 """Unbind a queue from an exchange.
1064
1065 :param str queue: The queue to unbind from the exchange
1066 :param str exchange: The source exchange to bind from
1067 :param str routing_key: The routing key to unbind
1068 :param dict arguments: Custom key/value pair arguments for the binding
1069 :returns: Deferred that fires on the Queue.UnbindOk response
1070 :rtype: Deferred
1071 :raises ValueError:
1072
1073 """
1074 return self._wrap_channel_method("queue_unbind")(
1075 queue=queue,
1076 exchange=exchange,
1077 routing_key=routing_key,
1078 arguments=arguments,
1079 )
1080
1081 def tx_commit(self) -> defer.Deferred[Any]:
1082 """Commit a transaction.
1083
1084 :returns: Deferred that fires on the Tx.CommitOk response
1085 :rtype: Deferred
1086 :raises ValueError:
1087
1088 """
1089 return self._wrap_channel_method("tx_commit")()
1090
1091 def tx_rollback(self) -> defer.Deferred[Any]:
1092 """Rollback a transaction.
1093
1094 :returns: Deferred that fires on the Tx.RollbackOk response
1095 :rtype: Deferred
1096 :raises ValueError:
1097
1098 """
1099 return self._wrap_channel_method("tx_rollback")()
1100
1101 def tx_select(self) -> defer.Deferred[Any]:
1102 """Select standard transaction mode. This method sets the channel to use
1103 standard transactions. The client must use this method at least once on
1104 a channel before using the Commit or Rollback methods.
1105
1106 :returns: Deferred that fires on the Tx.SelectOk response
1107 :rtype: Deferred
1108 :raises ValueError:
1109
1110 """
1111 return self._wrap_channel_method("tx_select")()
1112
1113
1114 class _TwistedConnectionAdapter(pika.connection.Connection):
1115 """A Twisted-specific implementation of a Pika Connection.
1116
1117 NOTE: since `base_connection.BaseConnection`'s primary responsibility is
1118 management of the transport, we use `pika.connection.Connection` directly
1119 as our base class because this adapter uses a different transport
1120 management strategy.
1121
1122 """
1123
1124 def __init__(
1125 self,
1126 parameters: Optional[pika.connection.Parameters],
1127 on_open_callback: Optional[Callable[[pika.connection.Connection],
1128 Any]],
1129 on_open_error_callback: Optional[Callable[
1130 [pika.connection.Connection, Exception], Any]],
1131 on_close_callback: Optional[Callable[
1132 [pika.connection.Connection, Exception], Any]],
1133 custom_reactor: Any = None):
1134 super().__init__(parameters=parameters,
1135 on_open_callback=on_open_callback,
1136 on_open_error_callback=on_open_error_callback,
1137 on_close_callback=on_close_callback,
1138 internal_connection_workflow=False)
1139
1140 self._reactor = custom_reactor or reactor
1141 self._transport: Optional[
1142 twisted.internet.interfaces.
1143 ITransport] = None # to be provided by `connection_made()`
1144
1145 def _adapter_call_later(self, delay: float, callback: Callable[..., None]):
1146 """Implement
1147 :py:meth:`pika.connection.Connection._adapter_call_later()`.
1148
1149 """
1150 check_callback_arg(callback, 'callback')
1151 return _TimerHandle(self._reactor.callLater(
1152 delay, callback)) # pyright: ignore[reportAttributeAccessIssue]
1153
1154 def _adapter_remove_timeout(self, timeout_id: Any) -> None:
1155 """Implement
1156 :py:meth:`pika.connection.Connection._adapter_remove_timeout()`.
1157
1158 """
1159 timeout_id.cancel()
1160
1161 def _adapter_add_callback_threadsafe(self,
1162 callback: Callable[..., None]) -> None:
1163 """Implement
1164 :py:meth:`pika.connection.Connection._adapter_add_callback_threadsafe()`.
1165
1166 """
1167 check_callback_arg(callback, 'callback')
1168 self._reactor.callFromThread(
1169 callback) # pyright: ignore[reportAttributeAccessIssue]
1170
1171 def _adapter_connect_stream(self) -> None:
1172 """Implement pure virtual
1173 :py:ref:meth:`pika.connection.Connection._adapter_connect_stream()`
1174 method.
1175
1176 NOTE: This should not be called due to our initialization of Connection
1177 via `internal_connection_workflow=False`
1178 """
1179 raise NotImplementedError
1180
1181 def _adapter_disconnect_stream(self) -> None:
1182 """Implement pure virtual
1183 :py:ref:meth:`pika.connection.Connection._adapter_disconnect_stream()`
1184 method.
1185
1186 """
1187 self._transport.loseConnection() # type: ignore
1188
1189 def _adapter_emit_data(self, data: bytes) -> None:
1190 """Implement pure virtual
1191 :py:ref:meth:`pika.connection.Connection._adapter_emit_data()` method.
1192
1193 """
1194 self._transport.write(data) # type: ignore
1195
1196 def connection_made(
1197 self, transport: twisted.internet.interfaces.ITransport) -> None:
1198 """Introduces transport to protocol after transport is connected.
1199
1200 :param twisted.internet.interfaces.ITransport transport:
1201 :raises Exception: Exception-based exception on error
1202
1203 """
1204 self._transport = transport
1205 # Let connection know that stream is available
1206 self._on_stream_connected()
1207
1208 def connection_lost(self, error: Any) -> None:
1209 """Called upon loss or closing of TCP connection.
1210
1211 NOTE: `connection_made()` and `connection_lost()` are each called just
1212 once and in that order. All other callbacks are called between them.
1213
1214 :param Failure: A Twisted Failure instance wrapping an exception.
1215
1216 """
1217 self._transport = None
1218 error = error.value # drop the Failure wrapper
1219 if isinstance(error, twisted_error.ConnectionDone):
1220 self._error = error
1221 error = None
1222 LOGGER.log(logging.DEBUG if error is None else logging.ERROR,
1223 'connection_lost: %r', error)
1224 self._on_stream_terminated(error)
1225
1226 def data_received(self, data: bytes) -> None:
1227 """Called to deliver incoming data from the server to the protocol.
1228
1229 :param data: Non-empty data bytes.
1230 :raises Exception: Exception-based exception on error
1231
1232 """
1233 self._on_data_available(data)
1234
1235
1236 class TwistedProtocolConnection(protocol.Protocol):
1237 """A Pika-specific implementation of a Twisted Protocol. Allows using
1238 Twisted's non-blocking connectTCP/connectSSL methods for connecting to the
1239 server.
1240
1241 TwistedProtocolConnection objects have a `ready` instance variable that's a
1242 Deferred which fires when the connection is ready to be used (the initial
1243 AMQP handshaking has been done). You *have* to wait for this Deferred to
1244 fire before requesting a channel.
1245
1246 Once the connection is ready, you will be able to use the `closed` instance
1247 variable: a Deferred which fires when the connection is closed.
1248
1249 Since it's Twisted handling connection establishing it does not accept
1250 connect callbacks, you have to implement that within Twisted. Also remember
1251 that the host, port and ssl values of the connection parameters are ignored
1252 because, yet again, it's Twisted who manages the connection.
1253
1254 """
1255
1256 def __init__(
1257 self,
1258 parameters: Optional[pika.connection.ConnectionParameters] = None,
1259 custom_reactor: Any = None):
1260 self.ready: Optional[defer.Deferred[Any]] = defer.Deferred()
1261 self.ready.addCallback(lambda _: self.connectionReady())
1262 self.closed: Optional[defer.Deferred[Any]] = None
1263 self._impl = _TwistedConnectionAdapter(
1264 parameters=parameters,
1265 on_open_callback=self._on_connection_ready,
1266 on_open_error_callback=self._on_connection_failed,
1267 on_close_callback=self._on_connection_closed,
1268 custom_reactor=custom_reactor,
1269 )
1270 self._calls: Set[defer.Deferred[Any]] = set()
1271
1272 def channel(self, channel_number: Optional[int] = None): # pylint: disable=W0221
1273 """Create a new channel with the next available channel number or pass
1274 in a channel number to use. Must be non-zero if you would like to
1275 specify but it is recommended that you let Pika manage the channel
1276 numbers.
1277
1278 :param int channel_number: The channel number to use, defaults to the
1279 next available.
1280 :returns: a Deferred that fires with an instance of a wrapper around
1281 the Pika Channel class.
1282 :rtype: Deferred
1283
1284 """
1285 d: defer.Deferred[Any] = defer.Deferred()
1286 self._impl.channel(channel_number, d.callback)
1287 self._calls.add(d)
1288 d.addCallback(self._clear_call, d)
1289 return d.addCallback(TwistedChannel)
1290
1291 @property
1292 def is_open(self) -> bool:
1293 # For compatibility with previous releases.
1294 return self._impl.is_open
1295
1296 @property
1297 def is_closed(self) -> bool:
1298 # For compatibility with previous releases.
1299 return self._impl.is_closed
1300
1301 def close(
1302 self,
1303 reply_code: int = 200,
1304 reply_text: str = 'Normal shutdown'
1305 ) -> Optional[defer.Deferred[Any]]:
1306 if not self._impl.is_closed:
1307 self._impl.close(reply_code, reply_text)
1308 return self.closed
1309
1310 # IProtocol methods
1311
1312 def dataReceived(self, data: bytes) -> None:
1313 # Pass the bytes to Pika for parsing
1314 self._impl.data_received(data)
1315
1316 def connectionLost(
1317 self,
1318 reason: twisted.python.failure.Failure = protocol.connectionDone
1319 ) -> None:
1320 self._impl.connection_lost(reason)
1321 # Let the caller know there's been an error
1322 d, self.ready = self.ready, None
1323 if d:
1324 d.errback(reason)
1325
1326 def makeConnection(
1327 self, transport: twisted.internet.interfaces.ITransport) -> None:
1328 self._impl.connection_made(transport)
1329 protocol.Protocol.makeConnection(self, transport)
1330
1331 # Our own methods
1332
1333 def connectionReady(
1334 self
1335 ) -> Union[TwistedProtocolConnection,
1336 defer.Deferred[TwistedProtocolConnection]]:
1337 """This method will be called when the underlying connection is ready.
1338 """
1339 return self
1340
1341 def _on_connection_ready(self,
1342 _connection: pika.connection.Connection) -> None:
1343 d, self.ready = self.ready, None
1344 if d:
1345 self.closed = defer.Deferred()
1346 d.callback(None)
1347
1348 def _on_connection_failed(
1349 self,
1350 _connection: pika.connection.Connection,
1351 _error_message: Optional[Exception] = None) -> None:
1352 d, self.ready = self.ready, None
1353 if d:
1354 attempts = self._impl.params.connection_attempts
1355 exc = exceptions.AMQPConnectionError(attempts)
1356 d.errback(exc)
1357
1358 def _on_connection_closed(self, _connection: pika.connection.Connection,
1359 exception: Exception) -> None:
1360 # errback all pending calls
1361 for d in self._calls:
1362 d.errback(exception)
1363 self._calls = set()
1364
1365 d, self.closed = self.closed, None # type: ignore[assignment]
1366 if d:
1367 if isinstance(exception, Failure):
1368 # Calling `callback` with a Failure instance will trigger the
1369 # errback path.
1370 exception = exception.value # type: ignore
1371 d.callback(exception)
1372
1373 def _clear_call(self, ret, d):
1374 self._calls.discard(d)
1375 return ret
1376
1377
1378 class _TimerHandle(nbio_interface.AbstractTimerReference):
1379 """This module's adaptation of `nbio_interface.AbstractTimerReference`.
1380
1381 """
1382
1383 def __init__(self, handle: twisted.internet.base.DelayedCall) -> None:
1384 """
1385
1386 :param twisted.internet.base.DelayedCall handle:
1387 """
1388 self._handle: Optional[twisted.internet.base.DelayedCall] = handle
1389
1390 def cancel(self) -> None:
1391 if self._handle is not None:
1392 try:
1393 self._handle.cancel()
1394 except (twisted_error.AlreadyCalled,
1395 twisted_error.AlreadyCancelled):
1396 pass
1397
1398 self._handle = None