Debian Codegraph @

pika/adapters/utils/io_services_utils.py

raw
1 """Utilities for implementing `nbio_interface.AbstractIOServices` for
2 pika connection adapters.
3
4 """
5 from __future__ import annotations
6
7 import collections
8 import errno
9 import functools
10 import logging
11 import numbers
12 import os
13 import socket
14 import ssl
15 import sys
16 import traceback
17 from typing import Any, Callable, TYPE_CHECKING, Optional, Tuple, Union
18
19 from pika.adapters.utils.nbio_interface import (AbstractIOReference,
20 AbstractStreamTransport)
21 import pika.compat
22 import pika.diagnostic_utils
23
24 if TYPE_CHECKING:
25 from pika.adapters.utils import nbio_interface
26 import pika.connection
27
28 # "Try again" error codes for non-blocking socket I/O - send()/recv().
29 # NOTE: POSIX.1 allows either error to be returned for this case and doesn't require
30 # them to have the same value.
31 _TRY_IO_AGAIN_SOCK_ERROR_CODES = (
32 errno.EAGAIN,
33 errno.EWOULDBLOCK,
34 )
35
36 # "Connection establishment pending" error codes for non-blocking socket
37 # connect() call.
38 # NOTE: EINPROGRESS for Posix and EWOULDBLOCK for Windows
39 _CONNECTION_IN_PROGRESS_SOCK_ERROR_CODES = (
40 errno.EINPROGRESS,
41 errno.EWOULDBLOCK,
42 )
43
44 _LOGGER = logging.getLogger(__name__)
45
46 # Decorator that logs exceptions escaping from the decorated function
47 _log_exceptions = pika.diagnostic_utils.create_log_exception_decorator(_LOGGER) # pylint: disable=C0103
48
49
50 def check_callback_arg(callback: Any, name: str) -> None:
51 """Raise TypeError if callback is not callable
52
53 :param callback: callback to check
54 :param name: Name to include in exception text
55 :raises TypeError:
56
57 """
58 if not callable(callback):
59 raise TypeError('{} must be callable, but got {!r}'.format(
60 name, callback))
61
62
63 def check_fd_arg(fd: int) -> None:
64 """Raise TypeError if file descriptor is not an integer
65
66 :param fd: file descriptor
67 :raises TypeError:
68
69 """
70 if not isinstance(fd, numbers.Integral):
71 raise TypeError(f'Paramter must be a file descriptor, but got {fd!r}')
72
73
74 def _retry_on_sigint(func):
75 """Function decorator for retrying on SIGINT.
76
77 """
78
79 @functools.wraps(func)
80 def retry_sigint_wrap(*args, **kwargs):
81 """Wrapper for decorated function"""
82 while True:
83 try:
84 return func(*args, **kwargs)
85 except pika.compat.SOCKET_ERROR as error:
86 if error.errno == errno.EINTR:
87 continue
88 else:
89 raise
90
91 return retry_sigint_wrap
92
93
94 class SocketConnectionMixin:
95 """Implements
96 `pika.adapters.utils.nbio_interface.AbstractIOServices.connect_socket()`
97 on top of
98 `pika.adapters.utils.nbio_interface.AbstractFileDescriptorServices` and
99 basic `pika.adapters.utils.nbio_interface.AbstractIOServices`.
100
101 """
102
103 def connect_socket(
104 self, sock: socket.socket, resolved_addr: Tuple[str, int],
105 on_done: Callable[[Optional[BaseException]], None]
106 ) -> _AsyncServiceAsyncHandle:
107 """Implement
108 :py:meth:`.nbio_interface.AbstractIOServices.connect_socket()`.
109
110 """
111 return _AsyncSocketConnector(
112 nbio=self, # type: ignore[arg-type]
113 sock=sock,
114 resolved_addr=resolved_addr,
115 on_done=on_done).start()
116
117
118 class StreamingConnectionMixin:
119 """Implements
120 `.nbio_interface.AbstractIOServices.create_streaming_connection()` on
121 top of `.nbio_interface.AbstractFileDescriptorServices` and basic
122 `nbio_interface.AbstractIOServices` services.
123
124 """
125
126 def create_streaming_connection(
127 self,
128 protocol_factory: Callable[[],
129 nbio_interface.AbstractStreamProtocol],
130 sock: socket.socket,
131 on_done: Callable[[
132 Union[Tuple[nbio_interface.AbstractStreamTransport,
133 nbio_interface.AbstractStreamProtocol],
134 BaseException]
135 ], None],
136 ssl_context: Optional[ssl.SSLContext] = None,
137 server_hostname: Optional[str] = None) -> AbstractIOReference:
138 """Implement
139 :py:meth:`.nbio_interface.AbstractIOServices.create_streaming_connection()`.
140
141 """
142 try:
143 return _AsyncStreamConnector(
144 nbio=self, # type: ignore
145 protocol_factory=protocol_factory,
146 sock=sock,
147 ssl_context=ssl_context,
148 server_hostname=server_hostname,
149 on_done=on_done).start()
150 except Exception as error:
151 _LOGGER.error('create_streaming_connection(%s) failed: %r', sock,
152 error)
153 # Close the socket since this function takes ownership
154 try:
155 sock.close()
156 except Exception as error: # pylint: disable=W0703
157 # We log and suppress the exception from sock.close() so that
158 # the original error from _AsyncStreamConnector constructor will
159 # percolate
160 _LOGGER.error('%s.close() failed: %r', sock, error)
161
162 raise
163
164
165 class _AsyncServiceAsyncHandle(AbstractIOReference):
166 """This module's adaptation of `.nbio_interface.AbstractIOReference`
167
168 """
169
170 def __init__(self, subject):
171 """
172 :param subject: subject of the reference containing a `cancel()` method
173
174 """
175 self._cancel = subject.cancel
176
177 def cancel(self) -> bool:
178 """Cancel pending operation
179
180 :returns: False if was already done or cancelled; True otherwise
181 :rtype: bool
182
183 """
184 return self._cancel()
185
186
187 class _AsyncSocketConnector:
188 """Connects the given non-blocking socket asynchronously using
189 `.nbio_interface.AbstractFileDescriptorServices` and basic
190 `.nbio_interface.AbstractIOServices`. Used for implementing
191 `.nbio_interface.AbstractIOServices.connect_socket()`.
192 """
193
194 _STATE_NOT_STARTED = 0 # start() not called yet
195 _STATE_ACTIVE = 1 # workflow started
196 _STATE_CANCELED = 2 # workflow aborted by user's cancel() call
197 _STATE_COMPLETED = 3 # workflow completed: succeeded or failed
198
199 def __init__(self,
200 nbio: Union[nbio_interface.AbstractIOServices,
201 nbio_interface.AbstractFileDescriptorServices],
202 sock: socket.socket, resolved_addr: Tuple[str, int],
203 on_done: Callable[[Optional[BaseException]], None]):
204 """
205 :param AbstractIOServices | AbstractFileDescriptorServices nbio:
206 :param socket.socket sock: non-blocking socket that needs to be
207 connected via `socket.socket.connect()`
208 :param tuple resolved_addr: resolved destination address/port two-tuple
209 which is compatible with the given's socket's address family
210 :param callable on_done: user callback that takes None upon successful
211 completion or exception upon error (check for `BaseException`) as
212 its only arg. It will not be called if the operation was cancelled.
213 :raises ValueError: if host portion of `resolved_addr` is not an IP
214 address or is inconsistent with the socket's address family as
215 validated via `socket.inet_pton()`
216 """
217 check_callback_arg(on_done, 'on_done')
218
219 try:
220 socket.inet_pton(sock.family, resolved_addr[0])
221 except Exception as error: # pylint: disable=W0703
222 if not hasattr(socket, 'inet_pton'):
223 _LOGGER.debug(
224 'Unable to check resolved address: no socket.inet_pton().')
225 else:
226 msg = ('Invalid or unresolved IP address '
227 '{!r} for socket {}: {!r}').format(
228 resolved_addr, sock, error)
229 _LOGGER.error(msg)
230 raise ValueError(msg)
231
232 self._nbio = nbio
233 self._sock = sock
234 self._addr = resolved_addr
235 self._on_done = on_done
236 self._state = self._STATE_NOT_STARTED
237 self._watching_socket_events = False
238
239 @_log_exceptions
240 def _cleanup(self) -> None:
241 """Remove socket watcher, if any
242
243 """
244 if self._watching_socket_events:
245 self._watching_socket_events = False
246 self._nbio.remove_writer(self._sock.fileno(
247 )) # pyright: ignore[reportAttributeAccessIssue]
248
249 def start(self) -> AbstractIOReference:
250 """Start asynchronous connection establishment.
251
252 :rtype: AbstractIOReference
253 """
254 assert self._state == self._STATE_NOT_STARTED, (
255 '_AsyncSocketConnector.start(): expected _STATE_NOT_STARTED',
256 self._state)
257
258 self._state = self._STATE_ACTIVE
259
260 # Continue the rest of the operation on the I/O loop to avoid calling
261 # user's completion callback from the scope of user's call
262 self._nbio.add_callback_threadsafe(
263 self._start_async) # pyright: ignore[reportAttributeAccessIssue]
264
265 return _AsyncServiceAsyncHandle(self)
266
267 def cancel(self) -> bool:
268 """Cancel pending connection request without calling user's completion
269 callback.
270
271 :returns: False if was already done or cancelled; True otherwise
272 :rtype: bool
273
274 """
275 if self._state == self._STATE_ACTIVE:
276 self._state = self._STATE_CANCELED
277 _LOGGER.debug('User canceled connection request for %s to %s',
278 self._sock, self._addr)
279 self._cleanup()
280 return True
281
282 _LOGGER.debug(
283 '_AsyncSocketConnector cancel requested when not ACTIVE: '
284 'state=%s; %s', self._state, self._sock)
285 return False
286
287 @_log_exceptions
288 def _report_completion(self, result: Optional[BaseException]) -> None:
289 """Advance to COMPLETED state, remove socket watcher, and invoke user's
290 completion callback.
291
292 :param BaseException | None result: value to pass in user's callback
293
294 """
295 _LOGGER.debug('_AsyncSocketConnector._report_completion(%r); %s',
296 result, self._sock)
297
298 assert isinstance(result, (BaseException, type(None))), (
299 '_AsyncSocketConnector._report_completion() expected exception or '
300 'None as result.', result)
301 assert self._state == self._STATE_ACTIVE, (
302 '_AsyncSocketConnector._report_completion() expected '
303 '_STATE_NOT_STARTED', self._state)
304
305 self._state = self._STATE_COMPLETED
306 self._cleanup()
307
308 self._on_done(result)
309
310 @_log_exceptions
311 def _start_async(self) -> None:
312 """Called as callback from I/O loop to kick-start the workflow, so it's
313 safe to call user's completion callback from here, if needed
314
315 """
316 if self._state != self._STATE_ACTIVE:
317 # Must have been canceled by user before we were called
318 _LOGGER.debug(
319 'Abandoning sock=%s connection establishment to %s '
320 'due to inactive state=%s', self._sock, self._addr, self._state)
321 return
322
323 try:
324 self._sock.connect(self._addr)
325 except (Exception, pika.compat.SOCKET_ERROR) as error: # pylint: disable=W0703
326 if (isinstance(error, pika.compat.SOCKET_ERROR) and
327 error.errno in _CONNECTION_IN_PROGRESS_SOCK_ERROR_CODES):
328 # Connection establishment is pending
329 pass
330 else:
331 _LOGGER.error('%s.connect(%s) failed: %r', self._sock,
332 self._addr, error)
333 self._report_completion(error)
334 return
335
336 # Get notified when the socket becomes writable
337 try:
338 self._nbio.set_writer(self._sock.fileno(
339 ), self._on_writable) # pyright: ignore[reportAttributeAccessIssue]
340 except Exception as error: # pylint: disable=W0703
341 _LOGGER.exception('async.set_writer(%s) failed: %r', self._sock,
342 error)
343 self._report_completion(error)
344 return
345 else:
346 self._watching_socket_events = True
347 _LOGGER.debug('Connection-establishment is in progress for %s.',
348 self._sock)
349
350 @_log_exceptions
351 def _on_writable(self) -> None:
352 """Called when socket connects or fails to. Check for predicament and
353 invoke user's completion callback.
354
355 """
356 if self._state != self._STATE_ACTIVE:
357 # This should never happen since we remove the watcher upon
358 # `cancel()`
359 _LOGGER.error(
360 'Socket connection-establishment event watcher '
361 'called in inactive state (ignoring): %s; state=%s', self._sock,
362 self._state)
363 return
364
365 # The moment of truth...
366 error_code = self._sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
367 if not error_code:
368 _LOGGER.info('Socket connected: %s', self._sock)
369 result = None
370 else:
371 error_msg = os.strerror(error_code)
372 _LOGGER.error('Socket failed to connect: %s; error=%s (%s)',
373 self._sock, error_code, error_msg)
374 result = pika.compat.SOCKET_ERROR(error_code, error_msg)
375
376 self._report_completion(result)
377
378
379 class _AsyncStreamConnector:
380 """Performs asynchronous SSL session establishment, if requested, on the
381 already-connected socket and links the streaming transport to protocol.
382 Used for implementing
383 `.nbio_interface.AbstractIOServices.create_streaming_connection()`.
384
385 """
386 _STATE_NOT_STARTED = 0 # start() not called yet
387 _STATE_ACTIVE = 1 # start() called and kicked off the workflow
388 _STATE_CANCELED = 2 # workflow terminated by cancel() request
389 _STATE_COMPLETED = 3 # workflow terminated by success or failure
390
391 def __init__(
392 self, nbio: Union[nbio_interface.AbstractIOServices,
393 nbio_interface.AbstractFileDescriptorServices],
394 protocol_factory: Callable[[], nbio_interface.AbstractStreamProtocol],
395 sock: socket.socket, ssl_context: Optional[ssl.SSLContext],
396 server_hostname: Optional[str], on_done: Callable[[
397 Union[Tuple[nbio_interface.AbstractStreamTransport,
398 nbio_interface.AbstractStreamProtocol], BaseException]
399 ], None]
400 ) -> None:
401 """
402 NOTE: We take ownership of the given socket upon successful completion
403 of the constructor.
404
405 See `AbstractIOServices.create_streaming_connection()` for detailed
406 documentation of the corresponding args.
407
408 :param AbstractIOServices | AbstractFileDescriptorServices nbio:
409 :param callable protocol_factory:
410 :param socket.socket sock:
411 :param ssl.SSLContext | None ssl_context:
412 :param str | None server_hostname:
413 :param callable on_done:
414
415 """
416 check_callback_arg(protocol_factory, 'protocol_factory')
417 check_callback_arg(on_done, 'on_done')
418
419 if not isinstance(ssl_context, (type(None), ssl.SSLContext)):
420 raise ValueError('Expected ssl_context=None | ssl.SSLContext, but '
421 'got {!r}'.format(ssl_context))
422
423 if server_hostname is not None and ssl_context is None:
424 raise ValueError('Non-None server_hostname must not be passed '
425 'without ssl context')
426
427 # Check that the socket connection establishment had completed in order
428 # to avoid stalling while waiting for the socket to become readable
429 # and/or writable.
430 try:
431 sock.getpeername()
432 except Exception as error:
433 raise ValueError(
434 'Expected connected socket, but getpeername() failed: '
435 'error={!r}; {}; '.format(error, sock))
436
437 self._nbio: Optional[
438 Union[nbio_interface.AbstractIOServices,
439 nbio_interface.AbstractFileDescriptorServices]] = nbio
440 self._protocol_factory: Optional[Callable[
441 [], nbio_interface.AbstractStreamProtocol]] = protocol_factory
442 self._sock: Optional[socket.socket] = sock
443 self._ssl_context: Optional[ssl.SSLContext] = ssl_context
444 self._server_hostname: Optional[str] = server_hostname
445 self._on_done: Optional[Callable[[
446 Union[Tuple[nbio_interface.AbstractStreamTransport,
447 nbio_interface.AbstractStreamProtocol], BaseException]
448 ], None]] = on_done
449
450 self._state = self._STATE_NOT_STARTED
451 self._watching_socket = False
452
453 @_log_exceptions
454 def _cleanup(self, close: bool) -> None:
455 """Cancel pending async operations, if any
456
457 :param bool close: close the socket if true
458 """
459 _LOGGER.debug('_AsyncStreamConnector._cleanup(%r)', close)
460
461 if self._watching_socket:
462 _LOGGER.debug(
463 '_AsyncStreamConnector._cleanup(%r): removing RdWr; %s', close,
464 self._sock)
465 self._watching_socket = False
466 self._nbio.remove_reader(self._sock.fileno()) # type: ignore
467 self._nbio.remove_writer(self._sock.fileno()) # type: ignore
468
469 try:
470 if close:
471 _LOGGER.debug(
472 '_AsyncStreamConnector._cleanup(%r): closing socket; %s',
473 close, self._sock)
474 try:
475 self._sock.close() # type: ignore
476 except Exception as error: # pylint: disable=W0703
477 _LOGGER.exception('_sock.close() failed: error=%r; %s',
478 error, self._sock)
479 raise
480 finally:
481 self._sock = None
482 self._nbio = None
483 self._protocol_factory = None
484 self._ssl_context = None
485 self._server_hostname = None
486 self._on_done = None
487
488 def start(self) -> AbstractIOReference:
489 """Kick off the workflow
490
491 :rtype: AbstractIOReference
492 """
493 _LOGGER.debug('_AsyncStreamConnector.start(); %s', self._sock)
494
495 assert self._state == self._STATE_NOT_STARTED, (
496 '_AsyncStreamConnector.start() expected '
497 '_STATE_NOT_STARTED', self._state)
498
499 self._state = self._STATE_ACTIVE
500
501 # Request callback from I/O loop to start processing so that we don't
502 # end up making callbacks from the caller's scope
503 self._nbio.add_callback_threadsafe(self._start_async) # type: ignore
504
505 return _AsyncServiceAsyncHandle(self)
506
507 def cancel(self) -> bool:
508 """Cancel pending connection request without calling user's completion
509 callback.
510
511 :returns: False if was already done or cancelled; True otherwise
512 :rtype: bool
513
514 """
515 if self._state == self._STATE_ACTIVE:
516 self._state = self._STATE_CANCELED
517 _LOGGER.debug('User canceled streaming linkup for %s', self._sock)
518 # Close the socket, since we took ownership
519 self._cleanup(close=True)
520 return True
521
522 _LOGGER.debug(
523 '_AsyncStreamConnector cancel requested when not ACTIVE: '
524 'state=%s; %s', self._state, self._sock)
525 return False
526
527 @_log_exceptions
528 def _report_completion(
529 self,
530 result: Optional[Union[BaseException,
531 Tuple[nbio_interface.AbstractStreamTransport,
532 nbio_interface.AbstractStreamProtocol]]]
533 ) -> None:
534 """Advance to COMPLETED state, cancel async operation(s), and invoke
535 user's completion callback.
536
537 :param BaseException | tuple result: value to pass in user's callback.
538 `tuple(transport, protocol)` on success, exception on error
539
540 """
541 _LOGGER.debug('_AsyncStreamConnector._report_completion(%r); %s',
542 result, self._sock)
543
544 assert isinstance(result, (BaseException, tuple)), (
545 '_AsyncStreamConnector._report_completion() expected exception or '
546 'tuple as result.', result, self._state)
547 assert self._state == self._STATE_ACTIVE, (
548 '_AsyncStreamConnector._report_completion() expected '
549 '_STATE_ACTIVE', self._state)
550
551 self._state = self._STATE_COMPLETED
552
553 # Notify user
554 try:
555 self._on_done(result) # type: ignore
556 except Exception:
557 _LOGGER.exception('%r: _on_done(%r) failed.',
558 self._report_completion, result)
559 raise
560 finally:
561 # NOTE: Close the socket on error, since we took ownership of it
562 self._cleanup(close=isinstance(result, BaseException))
563
564 @_log_exceptions
565 def _start_async(self) -> None:
566 """Called as callback from I/O loop to kick-start the workflow, so it's
567 safe to call user's completion callback from here if needed
568
569 """
570 _LOGGER.debug('_AsyncStreamConnector._start_async(); %s', self._sock)
571
572 if self._state != self._STATE_ACTIVE:
573 # Must have been canceled by user before we were called
574 _LOGGER.debug(
575 'Abandoning streaming linkup due to inactive state '
576 'transition; state=%s; %s; .', self._state, self._sock)
577 return
578
579 # Link up protocol and transport if this is a plaintext linkup;
580 # otherwise kick-off SSL workflow first
581 if self._ssl_context is None:
582 self._linkup()
583 else:
584 _LOGGER.debug('Starting SSL handshake on %s', self._sock)
585
586 # Wrap our plain socket in ssl socket
587 try:
588 self._sock = self._ssl_context.wrap_socket(
589 self._sock, # type: ignore
590 server_side=False,
591 do_handshake_on_connect=False,
592 suppress_ragged_eofs=False, # False = error on incoming EOF
593 server_hostname=self._server_hostname)
594 except Exception as error: # pylint: disable=W0703
595 _LOGGER.exception('SSL wrap_socket(%s) failed: %r', self._sock,
596 error)
597 self._report_completion(error)
598 return
599
600 self._do_ssl_handshake()
601
602 @_log_exceptions
603 def _linkup(self) -> None:
604 """Connection is ready: instantiate and link up transport and protocol,
605 and invoke user's completion callback.
606
607 """
608 _LOGGER.debug('_AsyncStreamConnector._linkup()')
609
610 transport = None
611
612 try:
613 # Create the protocol
614 try:
615 protocol = self._protocol_factory() # type: ignore
616 except Exception as error:
617 _LOGGER.exception('protocol_factory() failed: error=%r; %s',
618 error, self._sock)
619 raise
620
621 if self._ssl_context is None:
622 # Create plaintext streaming transport
623 try:
624 transport = _AsyncPlaintextTransport(
625 self._sock, protocol, self._nbio) # type: ignore
626 except Exception as error:
627 _LOGGER.exception('PlainTransport() failed: error=%r; %s',
628 error, self._sock)
629 raise
630 else:
631 # Create SSL streaming transport
632 try:
633 transport = _AsyncSSLTransport(
634 self._sock, # type: ignore[arg-type]
635 protocol,
636 self._nbio) # type: ignore[arg-type]
637 except Exception as error:
638 _LOGGER.exception('SSLTransport() failed: error=%r; %s',
639 error, self._sock)
640 raise
641
642 _LOGGER.debug('_linkup(): created transport %r', transport)
643
644 # Acquaint protocol with its transport
645 try:
646 protocol.connection_made(transport)
647 except Exception as error:
648 _LOGGER.exception(
649 'protocol.connection_made(%r) failed: error=%r; %s',
650 transport, error, self._sock)
651 raise
652
653 _LOGGER.debug('_linkup(): introduced transport to protocol %r; %r',
654 transport, protocol)
655 except Exception as error: # pylint: disable=W0703
656 result: Union[BaseException,
657 Tuple[nbio_interface.AbstractStreamTransport,
658 nbio_interface.AbstractStreamProtocol]] = error
659 else:
660 result = (transport, protocol)
661
662 self._report_completion(result)
663
664 @_log_exceptions
665 def _do_ssl_handshake(self) -> None:
666 """Perform asynchronous SSL handshake on the already wrapped socket
667
668 """
669 _LOGGER.debug('_AsyncStreamConnector._do_ssl_handshake()')
670
671 if self._state != self._STATE_ACTIVE:
672 _LOGGER.debug(
673 '_do_ssl_handshake: Abandoning streaming linkup due '
674 'to inactive state transition; state=%s; %s; .', self._state,
675 self._sock)
676 return
677
678 assert self._nbio is not None
679
680 done = False
681
682 try:
683 try:
684 self._sock.do_handshake() # type: ignore
685 except ssl.SSLError as error:
686 if error.errno == ssl.SSL_ERROR_WANT_READ:
687 _LOGGER.debug('SSL handshake wants read; %s.', self._sock)
688 self._watching_socket = True
689 self._nbio.set_reader(
690 self._sock.fileno(), # type: ignore
691 self._do_ssl_handshake)
692 self._nbio.remove_writer(
693 self._sock.fileno()) # type: ignore
694 elif error.errno == ssl.SSL_ERROR_WANT_WRITE:
695 _LOGGER.debug('SSL handshake wants write. %s', self._sock)
696 self._watching_socket = True
697 self._nbio.set_writer(
698 self._sock.fileno(), # type: ignore
699 self._do_ssl_handshake)
700 self._nbio.remove_reader(
701 self._sock.fileno()) # type: ignore
702 else:
703 # Outer catch will report it
704 raise
705 else:
706 done = True
707 _LOGGER.info('SSL handshake completed successfully: %s',
708 self._sock)
709 except Exception as error: # pylint: disable=W0703
710 _LOGGER.exception('SSL do_handshake failed: error=%r; %s', error,
711 self._sock)
712 self._report_completion(error)
713 return
714
715 if done:
716 # Suspend I/O and link up transport with protocol
717 _LOGGER.debug(
718 '_do_ssl_handshake: removing watchers ahead of linkup: %s',
719 self._sock)
720 self._nbio.remove_reader(self._sock.fileno()) # type: ignore
721 self._nbio.remove_writer(self._sock.fileno()) # type: ignore
722 # So that our `_cleanup()` won't interfere with the transport's
723 # socket watcher configuration.
724 self._watching_socket = False
725 _LOGGER.debug(
726 '_do_ssl_handshake: pre-linkup removal of watchers is done; %s',
727 self._sock)
728
729 self._linkup()
730
731
732 class _AsyncTransportBase( # pylint: disable=W0223
733 AbstractStreamTransport):
734 """Base class for `_AsyncPlaintextTransport` and `_AsyncSSLTransport`.
735
736 """
737
738 _STATE_ACTIVE = 1
739 _STATE_FAILED = 2 # connection failed
740 _STATE_ABORTED_BY_USER = 3 # cancel() called
741 _STATE_COMPLETED = 4 # done with connection
742
743 _MAX_RECV_BYTES = 4096 # per socket.recv() documentation recommendation
744
745 # Max per consume call to prevent event starvation
746 _MAX_CONSUME_BYTES = 1024 * 100
747
748 class RxEndOfFile(OSError):
749 """We raise this internally when EOF (empty read) is detected on input.
750
751 """
752
753 def __init__(self) -> None:
754 super(_AsyncTransportBase.RxEndOfFile,
755 self).__init__(-1, 'End of input stream (EOF)')
756
757 def __init__(self, sock: Union[socket.socket, ssl.SSLSocket],
758 protocol: nbio_interface.AbstractStreamProtocol,
759 nbio: Union[nbio_interface.AbstractIOServices,
760 nbio_interface.AbstractFileDescriptorServices]):
761 """
762
763 :param socket.socket | ssl.SSLSocket sock: connected socket
764 :param pika.adapters.utils.nbio_interface.AbstractStreamProtocol protocol:
765 corresponding protocol in this transport/protocol pairing; the
766 protocol already had its `connection_made()` method called.
767 :param AbstractIOServices | AbstractFileDescriptorServices nbio:
768
769 """
770 _LOGGER.debug('_AsyncTransportBase.__init__: %s', sock)
771 self._sock = sock
772 self._protocol = protocol
773 self._nbio = nbio
774
775 self._state = self._STATE_ACTIVE
776 self._tx_buffers: collections.deque[bytes] = collections.deque()
777 self._tx_buffered_byte_count = 0
778
779 def abort(self) -> None:
780 """Close connection abruptly without waiting for pending I/O to
781 complete. Will invoke the corresponding protocol's `connection_lost()`
782 method asynchronously (not in context of the abort() call).
783
784 :raises Exception: Exception-based exception on error
785 """
786 _LOGGER.info('Aborting transport connection: state=%s; %s', self._state,
787 self._sock)
788
789 self._initiate_abort(None)
790
791 def get_protocol(self) -> nbio_interface.AbstractStreamProtocol:
792 """Return the protocol linked to this transport.
793
794 :rtype: pika.adapters.utils.nbio_interface.AbstractStreamProtocol
795 """
796 return self._protocol # pyright: ignore[reportReturnType]
797
798 def get_write_buffer_size(self) -> int:
799 """
800 :returns: Current size of output data buffered by the transport
801 :rtype: int
802 """
803 return self._tx_buffered_byte_count
804
805 def _buffer_tx_data(self, data: bytes) -> None:
806 """Buffer the given data until it can be sent asynchronously.
807
808 :param bytes data:
809 :raises ValueError: if called with empty data
810
811 """
812 if not data:
813 _LOGGER.error('write() called with empty data: state=%s; %s',
814 self._state, self._sock)
815 raise ValueError(f'write() called with empty data {data!r}')
816
817 if self._state != self._STATE_ACTIVE:
818 _LOGGER.debug(
819 'Ignoring write() called during inactive state: '
820 'state=%s; %s', self._state, self._sock)
821 return
822
823 self._tx_buffers.append(data)
824 self._tx_buffered_byte_count += len(data)
825
826 def _consume(self) -> None:
827 """Utility method for use by subclasses to ingest data from socket and
828 dispatch it to protocol's `data_received()` method socket-specific
829 "try again" exception, per-event data consumption limit is reached,
830 transport becomes inactive, or a fatal failure.
831
832 Consumes up to `self._MAX_CONSUME_BYTES` to prevent event starvation or
833 until state becomes inactive (e.g., `protocol.data_received()` callback
834 aborts the transport)
835
836 :raises: Whatever the corresponding `sock.recv()` raises except the
837 socket error with errno.EINTR
838 :raises: Whatever the `protocol.data_received()` callback raises
839 :raises _AsyncTransportBase.RxEndOfFile: upon shutdown of input stream
840
841 """
842 bytes_consumed = 0
843
844 while (self._state == self._STATE_ACTIVE and
845 bytes_consumed < self._MAX_CONSUME_BYTES):
846 data = self._sigint_safe_recv(self._sock, self._MAX_RECV_BYTES)
847 bytes_consumed += len(data)
848
849 # Empty data, should disconnect
850 if not data:
851 _LOGGER.error('Socket EOF; %s', self._sock)
852 raise self.RxEndOfFile()
853
854 # Pass the data to the protocol
855 try:
856 self._protocol.data_received(
857 data) # pyright: ignore[reportOptionalMemberAccess]
858 except Exception as error:
859 _LOGGER.exception(
860 'protocol.data_received() failed: error=%r; %s', error,
861 self._sock)
862 raise
863
864 def _produce(self) -> None:
865 """Utility method for use by subclasses to emit data from tx_buffers.
866 This method sends chunks from `tx_buffers` until all chunks are
867 exhausted or sending is interrupted by an exception. Maintains integrity
868 of `self.tx_buffers`.
869
870 :raises: whatever the corresponding `sock.send()` raises except the
871 socket error with errno.EINTR
872
873 """
874 while self._tx_buffers:
875 num_bytes_sent = self._sigint_safe_send(self._sock,
876 self._tx_buffers[0])
877
878 chunk = self._tx_buffers.popleft()
879 if num_bytes_sent < len(chunk):
880 _LOGGER.debug('Partial send, requeing remaining data; %s of %s',
881 num_bytes_sent, len(chunk))
882 self._tx_buffers.appendleft(chunk[num_bytes_sent:])
883
884 self._tx_buffered_byte_count -= num_bytes_sent
885 assert self._tx_buffered_byte_count >= 0, (
886 '_AsyncTransportBase._produce() tx buffer size underflow',
887 self._tx_buffered_byte_count, self._state)
888
889 @staticmethod
890 @_retry_on_sigint
891 def _sigint_safe_recv(sock, max_bytes: int) -> bytes:
892 """Receive data from socket, retrying on SIGINT.
893
894 :param sock: stream or SSL socket
895 :param max_bytes: maximum number of bytes to receive
896 :returns: received data or empty bytes uppon end of file
897 :rtype: bytes
898 :raises: whatever the corresponding `sock.recv()` raises except socket
899 error with errno.EINTR
900
901 """
902 return sock.recv(max_bytes)
903
904 @staticmethod
905 @_retry_on_sigint
906 def _sigint_safe_send(sock, data: bytes) -> int:
907 """Send data to socket, retrying on SIGINT.
908
909 :param sock: stream or SSL socket
910 :param data: data bytes to send
911 :returns: number of bytes actually sent
912 :rtype: int
913 :raises: whatever the corresponding `sock.send()` raises except socket
914 error with errno.EINTR
915
916 """
917 return sock.send(data)
918
919 @_log_exceptions
920 def _deactivate(self):
921 """Unregister the transport from I/O events
922
923 """
924 if self._state == self._STATE_ACTIVE:
925 _LOGGER.info('Deactivating transport: state=%s; %s', self._state,
926 self._sock)
927 self._nbio.remove_reader(
928 self._sock.fileno()
929 ) # pyright: ignore[reportOptionalMemberAccess, reportAttributeAccessIssue]
930 self._nbio.remove_writer(
931 self._sock.fileno()
932 ) # pyright: ignore[reportOptionalMemberAccess, reportAttributeAccessIssue]
933 self._tx_buffers.clear()
934
935 @_log_exceptions
936 def _close_and_finalize(self):
937 """Close the transport's socket and unlink the transport it from
938 references to other assets (protocol, etc.)
939
940 """
941 if self._state != self._STATE_COMPLETED:
942 _LOGGER.info('Closing transport socket and unlinking: state=%s; %s',
943 self._state, self._sock)
944 try:
945 self._sock.shutdown(
946 socket.SHUT_RDWR
947 ) # pyright: ignore[reportOptionalMemberAccess]
948 except pika.compat.SOCKET_ERROR:
949 pass
950 self._sock.close() # pyright: ignore[reportOptionalMemberAccess]
951 self._sock = None # type: ignore
952 self._protocol = None # type: ignore
953 self._nbio = None # type: ignore
954 self._state = self._STATE_COMPLETED
955
956 @_log_exceptions
957 def _initiate_abort(self, error: Optional[BaseException]) -> None:
958 """Initiate asynchronous abort of the transport that concludes with a
959 call to the protocol's `connection_lost()` method. No flushing of
960 output buffers will take place.
961
962 :param BaseException | None error: None if being canceled by user,
963 including via falsie return value from protocol.eof_received;
964 otherwise the exception corresponding to the the failed connection.
965 """
966 _LOGGER.info(
967 '_AsyncTransportBase._initate_abort(): Initiating abrupt '
968 'asynchronous transport shutdown: state=%s; error=%r; %s',
969 self._state, error, self._sock)
970
971 assert self._state != self._STATE_COMPLETED, (
972 '_AsyncTransportBase._initate_abort() expected '
973 'non-_STATE_COMPLETED', self._state)
974
975 if self._state == self._STATE_COMPLETED:
976 return
977
978 self._deactivate()
979
980 # Update state
981 if error is None:
982 # Being aborted by user
983
984 if self._state == self._STATE_ABORTED_BY_USER:
985 # Abort by user already pending
986 _LOGGER.debug('_AsyncTransportBase._initiate_abort(): '
987 'ignoring - user-abort already pending.')
988 return
989
990 # Notification priority is given to user-initiated abort over
991 # failed connection
992 self._state = self._STATE_ABORTED_BY_USER
993 else:
994 # Connection failed
995
996 if self._state != self._STATE_ACTIVE:
997 assert self._state == self._STATE_ABORTED_BY_USER, (
998 '_AsyncTransportBase._initate_abort() expected '
999 '_STATE_ABORTED_BY_USER', self._state)
1000 return
1001
1002 self._state = self._STATE_FAILED
1003
1004 # Schedule callback from I/O loop to avoid potential reentry into user
1005 # code
1006 self._nbio.add_callback_threadsafe( # pyright: ignore[reportAttributeAccessIssue, reportOptionalMemberAccess]
1007 functools.partial(self._connection_lost_notify_async, error))
1008
1009 @_log_exceptions
1010 def _connection_lost_notify_async(self,
1011 error: Optional[BaseException]) -> None:
1012 """Handle aborting of transport either due to socket error or user-
1013 initiated `abort()` call. Must be called from an I/O loop callback owned
1014 by us in order to avoid reentry into user code from user's API call into
1015 the transport.
1016
1017 :param BaseException | None error: None if being canceled by user;
1018 otherwise the exception corresponding to the the failed connection.
1019 """
1020 _LOGGER.debug('Concluding transport shutdown: state=%s; error=%r',
1021 self._state, error)
1022
1023 if self._state == self._STATE_COMPLETED:
1024 return
1025
1026 if error is not None and self._state != self._STATE_FAILED:
1027 # Priority is given to user-initiated abort notification
1028 assert self._state == self._STATE_ABORTED_BY_USER, (
1029 '_AsyncTransportBase._connection_lost_notify_async() '
1030 'expected _STATE_ABORTED_BY_USER', self._state)
1031 return
1032
1033 # Inform protocol
1034 try:
1035 self._protocol.connection_lost(
1036 error) # pyright: ignore[reportOptionalMemberAccess]
1037 except Exception as exc: # pylint: disable=W0703
1038 _LOGGER.exception('protocol.connection_lost(%r) failed: exc=%r; %s',
1039 error, exc, self._sock)
1040 # Re-raise, since we've exhausted our normal failure notification
1041 # mechanism (i.e., connection_lost())
1042 raise
1043 finally:
1044 self._close_and_finalize()
1045
1046
1047 class _AsyncPlaintextTransport(_AsyncTransportBase):
1048 """Implementation of `nbio_interface.AbstractStreamTransport` for a
1049 plaintext connection.
1050
1051 """
1052
1053 def __init__(self, sock: Union[socket.socket, ssl.SSLSocket],
1054 protocol: nbio_interface.AbstractStreamProtocol,
1055 nbio: Union[nbio_interface.AbstractIOServices,
1056 nbio_interface.AbstractFileDescriptorServices]):
1057 """
1058
1059 :param socket.socket sock: non-blocking connected socket
1060 :param pika.adapters.utils.nbio_interface.AbstractStreamProtocol protocol:
1061 corresponding protocol in this transport/protocol pairing; the
1062 protocol already had its `connection_made()` method called.
1063 :param AbstractIOServices | AbstractFileDescriptorServices nbio:
1064
1065 """
1066 super().__init__(sock, protocol, nbio)
1067
1068 # Request to be notified of incoming data; we'll watch for writability
1069 # only when our write buffer is non-empty
1070 self._nbio.set_reader(
1071 self._sock.fileno(), self._on_socket_readable
1072 ) # pyright: ignore[reportAttributeAccessIssue, reportOptionalMemberAccess]
1073
1074 def write(self, data: bytes) -> None:
1075 """Buffer the given data until it can be sent asynchronously.
1076
1077 :param bytes data:
1078 :raises ValueError: if called with empty data
1079
1080 """
1081 if self._state != self._STATE_ACTIVE:
1082 _LOGGER.debug(
1083 'Ignoring write() called during inactive state: '
1084 'state=%s; %s', self._state, self._sock)
1085 return
1086
1087 assert data, ('_AsyncPlaintextTransport.write(): empty data from user.',
1088 data, self._state)
1089
1090 # pika/pika#1286
1091 # NOTE: Modify code to write data to buffer before setting writer.
1092 # Otherwise a race condition can occur where ioloop executes writer
1093 # while buffer is still empty.
1094 tx_buffer_was_empty = self.get_write_buffer_size() == 0
1095
1096 self._buffer_tx_data(data)
1097
1098 if tx_buffer_was_empty:
1099 self._nbio.set_writer(
1100 self._sock.fileno(), self._on_socket_writable
1101 ) # pyright: ignore[reportAttributeAccessIssue, reportOptionalMemberAccess]
1102 _LOGGER.debug('Turned on writability watcher: %s', self._sock)
1103
1104 @_log_exceptions
1105 def _on_socket_readable(self) -> None:
1106 """Ingest data from socket and dispatch it to protocol until exception
1107 occurs (typically EAGAIN or EWOULDBLOCK), per-event data consumption
1108 limit is reached, transport becomes inactive, or failure.
1109
1110 """
1111 if self._state != self._STATE_ACTIVE:
1112 _LOGGER.debug(
1113 'Ignoring readability notification due to inactive '
1114 'state: state=%s; %s', self._state, self._sock)
1115 return
1116
1117 try:
1118 self._consume()
1119 except self.RxEndOfFile:
1120 try:
1121 keep_open = self._protocol.eof_received(
1122 ) # pyright: ignore[reportOptionalMemberAccess]
1123 except Exception as error: # pylint: disable=W0703
1124 _LOGGER.exception(
1125 'protocol.eof_received() failed: error=%r; %s', error,
1126 self._sock)
1127 self._initiate_abort(error)
1128 else:
1129 if keep_open:
1130 _LOGGER.info(
1131 'protocol.eof_received() elected to keep open: %s',
1132 self._sock)
1133 self._nbio.remove_reader(
1134 self._sock.fileno()
1135 ) # pyright: ignore[reportOptionalMemberAccess, reportAttributeAccessIssue]
1136 else:
1137 _LOGGER.info('protocol.eof_received() elected to close: %s',
1138 self._sock)
1139 self._initiate_abort(None)
1140 except (Exception, pika.compat.SOCKET_ERROR) as error: # pylint: disable=W0703
1141 if (isinstance(error, pika.compat.SOCKET_ERROR) and
1142 error.errno in _TRY_IO_AGAIN_SOCK_ERROR_CODES):
1143 _LOGGER.debug('Recv would block on %s', self._sock)
1144 else:
1145 _LOGGER.exception(
1146 '_AsyncBaseTransport._consume() failed, aborting '
1147 'connection: error=%r; sock=%s; Caller\'s stack:\n%s',
1148 error, self._sock,
1149 ''.join(traceback.format_exception(*sys.exc_info())))
1150 self._initiate_abort(error)
1151 else:
1152 if self._state != self._STATE_ACTIVE:
1153 # Most likely our protocol's `data_received()` aborted the
1154 # transport
1155 _LOGGER.debug(
1156 'Leaving Plaintext consumer due to inactive '
1157 'state: state=%s; %s', self._state, self._sock)
1158
1159 @_log_exceptions
1160 def _on_socket_writable(self) -> None:
1161 """Handle writable socket notification
1162
1163 """
1164 if self._state != self._STATE_ACTIVE:
1165 _LOGGER.debug(
1166 'Ignoring writability notification due to inactive '
1167 'state: state=%s; %s', self._state, self._sock)
1168 return
1169
1170 # We shouldn't be getting called with empty tx buffers
1171 assert self._tx_buffers, (
1172 '_AsyncPlaintextTransport._on_socket_writable() called, '
1173 'but _tx_buffers is empty.', self._state)
1174
1175 try:
1176 # Transmit buffered data to remote socket
1177 self._produce()
1178 except (Exception, pika.compat.SOCKET_ERROR) as error: # pylint: disable=W0703
1179 if (isinstance(error, pika.compat.SOCKET_ERROR) and
1180 error.errno in _TRY_IO_AGAIN_SOCK_ERROR_CODES):
1181 _LOGGER.debug('Send would block on %s', self._sock)
1182 else:
1183 _LOGGER.exception(
1184 '_AsyncBaseTransport._produce() failed, aborting '
1185 'connection: error=%r; sock=%s; Caller\'s stack:\n%s',
1186 error, self._sock,
1187 ''.join(traceback.format_exception(*sys.exc_info())))
1188 self._initiate_abort(error)
1189 else:
1190 if not self._tx_buffers:
1191 self._nbio.remove_writer(
1192 self._sock.fileno()
1193 ) # pyright: ignore[reportAttributeAccessIssue, reportOptionalMemberAccess]
1194 _LOGGER.debug('Turned off writability watcher: %s', self._sock)
1195
1196
1197 class _AsyncSSLTransport(_AsyncTransportBase):
1198 """Implementation of `.nbio_interface.AbstractStreamTransport` for an SSL
1199 connection.
1200
1201 """
1202
1203 def __init__(
1204 self, sock: ssl.SSLSocket,
1205 protocol: nbio_interface.AbstractStreamProtocol,
1206 nbio: nbio_interface.AbstractIOServices |
1207 nbio_interface.AbstractFileDescriptorServices
1208 ) -> None:
1209 """
1210
1211 :param ssl.SSLSocket sock: non-blocking connected socket
1212 :param pika.adapters.utils.nbio_interface.AbstractStreamProtocol protocol:
1213 corresponding protocol in this transport/protocol pairing; the
1214 protocol already had its `connection_made()` method called.
1215 :param AbstractIOServices | AbstractFileDescriptorServices nbio:
1216
1217 """
1218 super().__init__(sock, protocol, nbio)
1219
1220 self._ssl_readable_action = self._consume
1221 self._ssl_writable_action = None
1222
1223 # Bootstrap consumer; we'll take care of producer once data is buffered
1224 self._nbio.set_reader(
1225 self._sock.fileno(), self._on_socket_readable
1226 ) # pyright: ignore[reportAttributeAccessIssue, reportOptionalMemberAccess]
1227 # Try reading asap just in case read-ahead caused some
1228 self._nbio.add_callback_threadsafe(
1229 self._on_socket_readable
1230 ) # pyright: ignore[reportAttributeAccessIssue, reportOptionalMemberAccess]
1231
1232 def write(self, data: bytes) -> None:
1233 """Buffer the given data until it can be sent asynchronously.
1234
1235 :param bytes data:
1236 :raises ValueError: if called with empty data
1237
1238 """
1239 if self._state != self._STATE_ACTIVE:
1240 _LOGGER.debug(
1241 'Ignoring write() called during inactive state: '
1242 'state=%s; %s', self._state, self._sock)
1243 return
1244
1245 assert data, ('_AsyncSSLTransport.write(): empty data from user.', data,
1246 self._state)
1247
1248 # pika/pika#1286
1249 # NOTE: Modify code to write data to buffer before setting writer.
1250 # Otherwise a race condition can occur where ioloop executes writer
1251 # while buffer is still empty.
1252 tx_buffer_was_empty = self.get_write_buffer_size() == 0
1253
1254 self._buffer_tx_data(data)
1255
1256 if tx_buffer_was_empty and self._ssl_writable_action is None:
1257 self._ssl_writable_action = self._produce # type: ignore
1258 self._nbio.set_writer(
1259 self._sock.fileno(), self._on_socket_writable
1260 ) # pyright: ignore[reportAttributeAccessIssue, reportOptionalMemberAccess]
1261 _LOGGER.debug('Turned on writability watcher: %s', self._sock)
1262
1263 @_log_exceptions
1264 def _on_socket_readable(self) -> None:
1265 """Handle readable socket indication
1266
1267 """
1268 if self._state != self._STATE_ACTIVE:
1269 _LOGGER.debug(
1270 'Ignoring readability notification due to inactive '
1271 'state: state=%s; %s', self._state, self._sock)
1272 return
1273
1274 if self._ssl_readable_action: # type: ignore
1275 try:
1276 self._ssl_readable_action()
1277 except Exception as error: # pylint: disable=W0703
1278 self._initiate_abort(error)
1279 else:
1280 _LOGGER.debug(
1281 'SSL readable action was suppressed: '
1282 'ssl_writable_action=%r; %s', self._ssl_writable_action,
1283 self._sock)
1284
1285 @_log_exceptions
1286 def _on_socket_writable(self) -> None:
1287 """Handle writable socket notification
1288
1289 """
1290 if self._state != self._STATE_ACTIVE:
1291 _LOGGER.debug(
1292 'Ignoring writability notification due to inactive '
1293 'state: state=%s; %s', self._state, self._sock)
1294 return
1295
1296 if self._ssl_writable_action:
1297 try:
1298 self._ssl_writable_action()
1299 except Exception as error: # pylint: disable=W0703
1300 self._initiate_abort(error)
1301 else:
1302 _LOGGER.debug(
1303 'SSL writable action was suppressed: '
1304 'ssl_readable_action=%r; %s', self._ssl_readable_action,
1305 self._sock)
1306
1307 @_log_exceptions
1308 def _consume(self) -> None:
1309 """[override] Ingest data from socket and dispatch it to protocol until
1310 exception occurs (typically ssl.SSLError with
1311 SSL_ERROR_WANT_READ/WRITE), per-event data consumption limit is reached,
1312 transport becomes inactive, or failure.
1313
1314 Update consumer/producer registration.
1315
1316 :raises Exception: error that signals that connection needs to be
1317 aborted
1318 """
1319 next_consume_on_readable = True
1320
1321 try:
1322 super()._consume()
1323 except ssl.SSLError as error:
1324 if error.errno == ssl.SSL_ERROR_WANT_READ:
1325 _LOGGER.debug('SSL ingester wants read: %s', self._sock)
1326 elif error.errno == ssl.SSL_ERROR_WANT_WRITE:
1327 # Looks like SSL re-negotiation
1328 _LOGGER.debug('SSL ingester wants write: %s', self._sock)
1329 next_consume_on_readable = False
1330 else:
1331 _LOGGER.exception(
1332 '_AsyncBaseTransport._consume() failed, aborting '
1333 'connection: error=%r; sock=%s; Caller\'s stack:\n%s',
1334 error, self._sock,
1335 ''.join(traceback.format_exception(*sys.exc_info())))
1336 raise # let outer catch block abort the transport
1337 else:
1338 if self._state != self._STATE_ACTIVE:
1339 # Most likely our protocol's `data_received()` aborted the
1340 # transport
1341 _LOGGER.debug(
1342 'Leaving SSL consumer due to inactive '
1343 'state: state=%s; %s', self._state, self._sock)
1344 return
1345
1346 # Consumer exited without exception; there may still be more,
1347 # possibly unprocessed, data records in SSL input buffers that
1348 # can be read without waiting for socket to become readable.
1349
1350 # In case buffered input SSL data records still remain
1351 self._nbio.add_callback_threadsafe(
1352 self._on_socket_readable
1353 ) # pyright: ignore[reportAttributeAccessIssue, reportOptionalMemberAccess]
1354
1355 # Update consumer registration
1356 if next_consume_on_readable:
1357 if not self._ssl_readable_action: # type: ignore
1358 self._nbio.set_reader(
1359 self._sock.fileno(
1360 ), # pyright: ignore[reportAttributeAccessIssue, reportOptionalMemberAccess]
1361 self._on_socket_readable)
1362 self._ssl_readable_action = self._consume
1363
1364 # NOTE: can't use identity check, it fails for instance methods
1365 if self._ssl_writable_action == self._consume: # pylint: disable=W0143
1366 self._nbio.remove_writer(
1367 self._sock.fileno()
1368 ) # pyright: ignore[reportAttributeAccessIssue, reportOptionalMemberAccess]
1369 self._ssl_writable_action = None
1370 else:
1371 # WANT_WRITE
1372 if not self._ssl_writable_action:
1373 self._nbio.set_writer(
1374 self._sock.fileno(
1375 ), # pyright: ignore[reportAttributeAccessIssue, reportOptionalMemberAccess]
1376 self._on_socket_writable)
1377 self._ssl_writable_action = self._consume # type: ignore
1378
1379 if self._ssl_readable_action: # type: ignore
1380 self._nbio.remove_reader(
1381 self._sock.fileno()
1382 ) # pyright: ignore[reportAttributeAccessIssue, reportOptionalMemberAccess]
1383 self._ssl_readable_action = None # type: ignore
1384
1385 # Update producer registration
1386 if self._tx_buffers and not self._ssl_writable_action:
1387 self._ssl_writable_action = self._produce # type: ignore
1388 self._nbio.set_writer(
1389 self._sock.fileno(), self._on_socket_writable
1390 ) # pyright: ignore[reportAttributeAccessIssue, reportOptionalMemberAccess]
1391
1392 @_log_exceptions
1393 def _produce(self) -> None:
1394 """[override] Emit data from tx_buffers all chunks are exhausted or
1395 sending is interrupted by an exception (typically ssl.SSLError with
1396 SSL_ERROR_WANT_READ/WRITE).
1397
1398 Update consumer/producer registration.
1399
1400 :raises Exception: error that signals that connection needs to be
1401 aborted
1402
1403 """
1404 next_produce_on_writable = None # None means no need to produce
1405
1406 try:
1407 super()._produce()
1408 except ssl.SSLError as error:
1409 if error.errno == ssl.SSL_ERROR_WANT_READ:
1410 # Looks like SSL re-negotiation
1411 _LOGGER.debug('SSL emitter wants read: %s', self._sock)
1412 next_produce_on_writable = False
1413 elif error.errno == ssl.SSL_ERROR_WANT_WRITE:
1414 _LOGGER.debug('SSL emitter wants write: %s', self._sock)
1415 next_produce_on_writable = True
1416 else:
1417 _LOGGER.exception(
1418 '_AsyncBaseTransport._produce() failed, aborting '
1419 'connection: error=%r; sock=%s; Caller\'s stack:\n%s',
1420 error, self._sock,
1421 ''.join(traceback.format_exception(*sys.exc_info())))
1422 raise # let outer catch block abort the transport
1423 else:
1424 # No exception, so everything must have been written to the socket
1425 assert not self._tx_buffers, (
1426 '_AsyncSSLTransport._produce(): no exception from parent '
1427 'class, but data remains in _tx_buffers.',
1428 len(self._tx_buffers))
1429
1430 # Update producer registration
1431 if self._tx_buffers:
1432 assert next_produce_on_writable is not None, (
1433 '_AsyncSSLTransport._produce(): next_produce_on_writable is '
1434 'still None', self._state)
1435
1436 if next_produce_on_writable:
1437 if not self._ssl_writable_action:
1438 self._nbio.set_writer(
1439 self._sock.fileno(
1440 ), # pyright: ignore[reportAttributeAccessIssue, reportOptionalMemberAccess]
1441 self._on_socket_writable)
1442 self._ssl_writable_action = self._produce # type: ignore
1443
1444 # NOTE: can't use identity check, it fails for instance methods
1445 if self._ssl_readable_action == self._produce: # pylint: disable=W0143
1446 self._nbio.remove_reader(
1447 self._sock.fileno()
1448 ) # pyright: ignore[reportAttributeAccessIssue, reportOptionalMemberAccess]
1449 self._ssl_readable_action = None # type: ignore
1450 else:
1451 # WANT_READ
1452 if not self._ssl_readable_action: # type: ignore
1453 self._nbio.set_reader(
1454 self._sock.fileno(
1455 ), # pyright: ignore[reportAttributeAccessIssue, reportOptionalMemberAccess]
1456 self._on_socket_readable)
1457 self._ssl_readable_action = self._produce
1458
1459 if self._ssl_writable_action:
1460 self._nbio.remove_writer(
1461 self._sock.fileno()
1462 ) # pyright: ignore[reportAttributeAccessIssue, reportOptionalMemberAccess]
1463 self._ssl_writable_action = None
1464 else:
1465 # NOTE: can't use identity check, it fails for instance methods
1466 if self._ssl_readable_action == self._produce: # pylint: disable=W0143
1467 self._nbio.remove_reader(
1468 self._sock.fileno()
1469 ) # pyright: ignore[reportAttributeAccessIssue, reportOptionalMemberAccess]
1470 self._ssl_readable_action = None # type: ignore
1471 assert self._ssl_writable_action != self._produce, ( # pylint: disable=W0143
1472 '_AsyncSSLTransport._produce(): with empty tx_buffers, '
1473 'writable_action cannot be _produce when readable is '
1474 '_produce', self._state)
1475 else:
1476 # NOTE: can't use identity check, it fails for instance methods
1477 assert self._ssl_writable_action == self._produce, ( # pylint: disable=W0143
1478 '_AsyncSSLTransport._produce(): with empty tx_buffers, '
1479 'expected writable_action as _produce when readable_action '
1480 'is not _produce', 'writable_action:',
1481 self._ssl_writable_action, 'readable_action:',
1482 self._ssl_readable_action, 'state:', self._state)
1483 self._ssl_writable_action = None
1484 self._nbio.remove_writer(
1485 self._sock.fileno()
1486 ) # pyright: ignore[reportAttributeAccessIssue, reportOptionalMemberAccess]
1487
1488 # Update consumer registration
1489 if not self._ssl_readable_action: # type: ignore
1490 self._ssl_readable_action = self._consume
1491 self._nbio.set_reader(
1492 self._sock.fileno(), self._on_socket_readable
1493 ) # pyright: ignore[reportAttributeAccessIssue, reportOptionalMemberAccess]
1494 # In case input SSL data records have been buffered
1495 self._nbio.add_callback_threadsafe(
1496 self._on_socket_readable
1497 ) # pyright: ignore[reportOptionalMemberAccess, reportAttributeAccessIssue]
1498 elif self._sock.pending(): # type: ignore
1499 self._nbio.add_callback_threadsafe(
1500 self._on_socket_readable
1501 ) # pyright: ignore[reportOptionalMemberAccess, reportAttributeAccessIssue]