2 Generic Asynchronous Message-based Protocol Support
4 This module provides a generic framework for sending and receiving
5 messages over an asyncio stream. `AsyncProtocol` is an abstract class
6 that implements the core mechanisms of a simple send/receive protocol,
7 and is designed to be extended.
9 In this package, it is used as the implementation for the `QMPClient`
14 from asyncio import StreamReader, StreamWriter
16 from functools import wraps
19 from ssl import SSLContext
33 from .error import QMPError
48 _TaskFN = Callable[[], Awaitable[None]] # aka ``async def func() -> None``
50 InternetAddrT = Tuple[str, int]
52 SocketAddrT = Union[UnixAddrT, InternetAddrT]
56 """Protocol session runstate."""
58 #: Fully quiesced and disconnected.
60 #: In the process of connecting or establishing a session.
62 #: Fully connected and active session.
64 #: In the process of disconnecting.
65 #: Runstate may be returned to `IDLE` by calling `disconnect()`.
69 class ConnectError(QMPError):
71 Raised when the initial connection process has failed.
73 This Exception always wraps a "root cause" exception that can be
74 interrogated for additional information.
76 :param error_message: Human-readable string describing the error.
77 :param exc: The root-cause exception.
79 def __init__(self, error_message: str, exc: Exception):
80 super().__init__(error_message)
81 #: Human-readable error string
82 self.error_message: str = error_message
83 #: Wrapped root cause exception
84 self.exc: Exception = exc
86 def __str__(self) -> str:
89 # If there's no error string, use the exception name.
90 cause = exception_summary(self.exc)
91 return f"{self.error_message}: {cause}"
94 class StateError(QMPError):
96 An API command (connect, execute, etc) was issued at an inappropriate time.
98 This error is raised when a command like
99 :py:meth:`~AsyncProtocol.connect()` is issued at an inappropriate
102 :param error_message: Human-readable string describing the state violation.
103 :param state: The actual `Runstate` seen at the time of the violation.
104 :param required: The `Runstate` required to process this command.
106 def __init__(self, error_message: str,
107 state: Runstate, required: Runstate):
108 super().__init__(error_message)
109 self.error_message = error_message
111 self.required = required
114 F = TypeVar('F', bound=Callable[..., Any]) # pylint: disable=invalid-name
118 def require(required_state: Runstate) -> Callable[[F], F]:
120 Decorator: protect a method so it can only be run in a certain `Runstate`.
122 :param required_state: The `Runstate` required to invoke this method.
123 :raise StateError: When the required `Runstate` is not met.
125 def _decorator(func: F) -> F:
126 # _decorator is the decorator that is built by calling the
127 # require() decorator factory; e.g.:
129 # @require(Runstate.IDLE) def foo(): ...
130 # will replace 'foo' with the result of '_decorator(foo)'.
133 def _wrapper(proto: 'AsyncProtocol[Any]',
134 *args: Any, **kwargs: Any) -> Any:
135 # _wrapper is the function that gets executed prior to the
138 name = type(proto).__name__
140 if proto.runstate != required_state:
141 if proto.runstate == Runstate.CONNECTING:
142 emsg = f"{name} is currently connecting."
143 elif proto.runstate == Runstate.DISCONNECTING:
144 emsg = (f"{name} is disconnecting."
145 " Call disconnect() to return to IDLE state.")
146 elif proto.runstate == Runstate.RUNNING:
147 emsg = f"{name} is already connected and running."
148 elif proto.runstate == Runstate.IDLE:
149 emsg = f"{name} is disconnected and idle."
152 raise StateError(emsg, proto.runstate, required_state)
153 # No StateError, so call the wrapped method.
154 return func(proto, *args, **kwargs)
156 # Return the decorated method;
157 # Transforming Func to Decorated[Func].
158 return cast(F, _wrapper)
160 # Return the decorator instance from the decorator factory. Phew!
164 class AsyncProtocol(Generic[T]):
166 AsyncProtocol implements a generic async message-based protocol.
168 This protocol assumes the basic unit of information transfer between
169 client and server is a "message", the details of which are left up
170 to the implementation. It assumes the sending and receiving of these
171 messages is full-duplex and not necessarily correlated; i.e. it
172 supports asynchronous inbound messages.
174 It is designed to be extended by a specific protocol which provides
175 the implementations for how to read and send messages. These must be
176 defined in `_do_recv()` and `_do_send()`, respectively.
178 Other callbacks have a default implementation, but are intended to be
179 either extended or overridden:
181 - `_establish_session`:
182 The base implementation starts the reader/writer tasks.
183 A protocol implementation can override this call, inserting
184 actions to be taken prior to starting the reader/writer tasks
185 before the super() call; actions needing to occur afterwards
186 can be written after the super() call.
188 Actions to be performed when a message is received.
190 Logging/Filtering hook for all outbound messages.
192 Logging/Filtering hook for all inbound messages.
193 This hook runs *before* `_on_message()`.
196 Name used for logging messages, if any. By default, messages
197 will log to 'qemu.aqmp.protocol', but each individual connection
198 can be given its own logger by giving it a name; messages will
199 then log to 'qemu.aqmp.protocol.${name}'.
201 # pylint: disable=too-many-instance-attributes
203 #: Logger object for debugging messages from this connection.
204 logger = logging.getLogger(__name__)
206 # Maximum allowable size of read buffer
209 # -------------------------
210 # Section: Public interface
211 # -------------------------
213 def __init__(self, name: Optional[str] = None) -> None:
214 #: The nickname for this connection, if any.
215 self.name: Optional[str] = name
216 if self.name is not None:
217 self.logger = self.logger.getChild(self.name)
220 self._reader: Optional[StreamReader] = None
221 self._writer: Optional[StreamWriter] = None
223 # Outbound Message queue
224 self._outgoing: asyncio.Queue[T]
226 # Special, long-running tasks:
227 self._reader_task: Optional[asyncio.Future[None]] = None
228 self._writer_task: Optional[asyncio.Future[None]] = None
230 # Aggregate of the above two tasks, used for Exception management.
231 self._bh_tasks: Optional[asyncio.Future[Tuple[None, None]]] = None
233 #: Disconnect task. The disconnect implementation runs in a task
234 #: so that asynchronous disconnects (initiated by the
235 #: reader/writer) are allowed to wait for the reader/writers to
237 self._dc_task: Optional[asyncio.Future[None]] = None
239 self._runstate = Runstate.IDLE
240 self._runstate_changed: Optional[asyncio.Event] = None
242 # Workaround for bind()
243 self._sock: Optional[socket.socket] = None
245 def __repr__(self) -> str:
246 cls_name = type(self).__name__
248 if self.name is not None:
249 tokens.append(f"name={self.name!r}")
250 tokens.append(f"runstate={self.runstate.name}")
251 return f"<{cls_name} {' '.join(tokens)}>"
253 @property # @upper_half
254 def runstate(self) -> Runstate:
255 """The current `Runstate` of the connection."""
256 return self._runstate
259 async def runstate_changed(self) -> Runstate:
261 Wait for the `runstate` to change, then return that runstate.
263 await self._runstate_event.wait()
267 @require(Runstate.IDLE)
268 async def accept(self, address: SocketAddrT,
269 ssl: Optional[SSLContext] = None) -> None:
271 Accept a connection and begin processing message queues.
273 If this call fails, `runstate` is guaranteed to be set back to `IDLE`.
276 Address to listen to; UNIX socket path or TCP address/port.
277 :param ssl: SSL context to use, if any.
279 :raise StateError: When the `Runstate` is not `IDLE`.
280 :raise ConnectError: If a connection could not be accepted.
282 await self._new_session(address, ssl, accept=True)
285 @require(Runstate.IDLE)
286 async def connect(self, address: SocketAddrT,
287 ssl: Optional[SSLContext] = None) -> None:
289 Connect to the server and begin processing message queues.
291 If this call fails, `runstate` is guaranteed to be set back to `IDLE`.
294 Address to connect to; UNIX socket path or TCP address/port.
295 :param ssl: SSL context to use, if any.
297 :raise StateError: When the `Runstate` is not `IDLE`.
298 :raise ConnectError: If a connection cannot be made to the server.
300 await self._new_session(address, ssl)
303 async def disconnect(self) -> None:
305 Disconnect and wait for all tasks to fully stop.
307 If there was an exception that caused the reader/writers to
308 terminate prematurely, it will be raised here.
310 :raise Exception: When the reader or writer terminate unexpectedly.
312 self.logger.debug("disconnect() called.")
313 self._schedule_disconnect()
314 await self._wait_disconnect()
316 # --------------------------
317 # Section: Session machinery
318 # --------------------------
320 async def _session_guard(self, coro: Awaitable[None], emsg: str) -> None:
322 Async guard function used to roll back to `IDLE` on any error.
324 On any Exception, the state machine will be reset back to
325 `IDLE`. Most Exceptions will be wrapped with `ConnectError`, but
326 `BaseException` events will be left alone (This includes
327 asyncio.CancelledError, even prior to Python 3.8).
329 :param error_message:
330 Human-readable string describing what connection phase failed.
332 :raise BaseException:
333 When `BaseException` occurs in the guarded block.
335 When any other error is encountered in the guarded block.
337 # Note: After Python 3.6 support is removed, this should be an
338 # @asynccontextmanager instead of accepting a callback.
341 except BaseException as err:
342 self.logger.error("%s: %s", emsg, exception_summary(err))
343 self.logger.debug("%s:\n%s\n", emsg, pretty_traceback())
345 # Reset the runstate back to IDLE.
346 await self.disconnect()
348 # We don't expect any Exceptions from the disconnect function
349 # here, because we failed to connect in the first place.
350 # The disconnect() function is intended to perform
351 # only cannot-fail cleanup here, but you never know.
353 "Unexpected bottom half exception. "
354 "This is a bug in the QMP library. "
358 self.logger.critical("%s:\n%s\n", emsg, pretty_traceback())
361 # CancelledError is an Exception with special semantic meaning;
362 # We do NOT want to wrap it up under ConnectError.
363 # NB: CancelledError is not a BaseException before Python 3.8
364 if isinstance(err, asyncio.CancelledError):
367 # Any other kind of error can be treated as some kind of connection
368 # failure broadly. Inspect the 'exc' field to explore the root
369 # cause in greater detail.
370 if isinstance(err, Exception):
371 raise ConnectError(emsg, err) from err
373 # Raise BaseExceptions un-wrapped, they're more important.
377 def _runstate_event(self) -> asyncio.Event:
378 # asyncio.Event() objects should not be created prior to entrance into
379 # an event loop, so we can ensure we create it in the correct context.
380 # Create it on-demand *only* at the behest of an 'async def' method.
381 if not self._runstate_changed:
382 self._runstate_changed = asyncio.Event()
383 return self._runstate_changed
387 def _set_state(self, state: Runstate) -> None:
389 Change the `Runstate` of the protocol connection.
391 Signals the `runstate_changed` event.
393 if state == self._runstate:
396 self.logger.debug("Transitioning from '%s' to '%s'.",
397 str(self._runstate), str(state))
398 self._runstate = state
399 self._runstate_event.set()
400 self._runstate_event.clear()
403 async def _new_session(self,
404 address: SocketAddrT,
405 ssl: Optional[SSLContext] = None,
406 accept: bool = False) -> None:
408 Establish a new connection and initialize the session.
410 Connect or accept a new connection, then begin the protocol
411 session machinery. If this call fails, `runstate` is guaranteed
412 to be set back to `IDLE`.
415 Address to connect to/listen on;
416 UNIX socket path or TCP address/port.
417 :param ssl: SSL context to use, if any.
418 :param accept: Accept a connection instead of connecting when `True`.
421 When a connection or session cannot be established.
423 This exception will wrap a more concrete one. In most cases,
424 the wrapped exception will be `OSError` or `EOFError`. If a
425 protocol-level failure occurs while establishing a new
426 session, the wrapped error may also be an `QMPError`.
428 assert self.runstate == Runstate.IDLE
430 await self._session_guard(
431 self._establish_connection(address, ssl, accept),
432 'Failed to establish connection')
434 await self._session_guard(
435 self._establish_session(),
436 'Failed to establish session')
438 assert self.runstate == Runstate.RUNNING
441 async def _establish_connection(
443 address: SocketAddrT,
444 ssl: Optional[SSLContext] = None,
448 Establish a new connection.
451 Address to connect to/listen on;
452 UNIX socket path or TCP address/port.
453 :param ssl: SSL context to use, if any.
454 :param accept: Accept a connection instead of connecting when `True`.
456 assert self.runstate == Runstate.IDLE
457 self._set_state(Runstate.CONNECTING)
459 # Allow runstate watchers to witness 'CONNECTING' state; some
460 # failures in the streaming layer are synchronous and will not
462 await asyncio.sleep(0)
465 await self._do_accept(address, ssl)
467 await self._do_connect(address, ssl)
469 def _bind_hack(self, address: Union[str, Tuple[str, int]]) -> None:
471 Used to create a socket in advance of accept().
473 This is a workaround to ensure that we can guarantee timing of
474 precisely when a socket exists to avoid a connection attempt
475 bouncing off of nothing.
477 Python 3.7+ adds a feature to separate the server creation and
478 listening phases instead, and should be used instead of this
481 if isinstance(address, tuple):
482 family = socket.AF_INET
484 family = socket.AF_UNIX
486 sock = socket.socket(family, socket.SOCK_STREAM)
487 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
498 async def _do_accept(self, address: SocketAddrT,
499 ssl: Optional[SSLContext] = None) -> None:
501 Acting as the transport server, accept a single connection.
504 Address to listen on; UNIX socket path or TCP address/port.
505 :param ssl: SSL context to use, if any.
507 :raise OSError: For stream-related errors.
509 self.logger.debug("Awaiting connection on %s ...", address)
510 connected = asyncio.Event()
511 server: Optional[asyncio.AbstractServer] = None
513 async def _client_connected_cb(reader: asyncio.StreamReader,
514 writer: asyncio.StreamWriter) -> None:
515 """Used to accept a single incoming connection, see below."""
519 # A connection has been accepted; stop listening for new ones.
520 assert server is not None
522 await server.wait_closed()
525 # Register this client as being connected
526 self._reader, self._writer = (reader, writer)
528 # Signal back: We've accepted a client!
531 if isinstance(address, tuple):
532 coro = asyncio.start_server(
533 _client_connected_cb,
534 host=None if self._sock else address[0],
535 port=None if self._sock else address[1],
542 coro = asyncio.start_unix_server(
543 _client_connected_cb,
544 path=None if self._sock else address,
551 server = await coro # Starts listening
552 await connected.wait() # Waits for the callback to fire (and finish)
553 assert server is None
556 self.logger.debug("Connection accepted.")
559 async def _do_connect(self, address: SocketAddrT,
560 ssl: Optional[SSLContext] = None) -> None:
562 Acting as the transport client, initiate a connection to a server.
565 Address to connect to; UNIX socket path or TCP address/port.
566 :param ssl: SSL context to use, if any.
568 :raise OSError: For stream-related errors.
570 self.logger.debug("Connecting to %s ...", address)
572 if isinstance(address, tuple):
573 connect = asyncio.open_connection(
580 connect = asyncio.open_unix_connection(
585 self._reader, self._writer = await connect
587 self.logger.debug("Connected.")
590 async def _establish_session(self) -> None:
592 Establish a new session.
594 Starts the readers/writer tasks; subclasses may perform their
595 own negotiations here. The Runstate will be RUNNING upon
596 successful conclusion.
598 assert self.runstate == Runstate.CONNECTING
600 self._outgoing = asyncio.Queue()
602 reader_coro = self._bh_loop_forever(self._bh_recv_message, 'Reader')
603 writer_coro = self._bh_loop_forever(self._bh_send_message, 'Writer')
605 self._reader_task = create_task(reader_coro)
606 self._writer_task = create_task(writer_coro)
608 self._bh_tasks = asyncio.gather(
613 self._set_state(Runstate.RUNNING)
614 await asyncio.sleep(0) # Allow runstate_event to process
618 def _schedule_disconnect(self) -> None:
620 Initiate a disconnect; idempotent.
622 This method is used both in the upper-half as a direct
623 consequence of `disconnect()`, and in the bottom-half in the
624 case of unhandled exceptions in the reader/writer tasks.
626 It can be invoked no matter what the `runstate` is.
628 if not self._dc_task:
629 self._set_state(Runstate.DISCONNECTING)
630 self.logger.debug("Scheduling disconnect.")
631 self._dc_task = create_task(self._bh_disconnect())
634 async def _wait_disconnect(self) -> None:
636 Waits for a previously scheduled disconnect to finish.
638 This method will gather any bottom half exceptions and re-raise
639 the one that occurred first; presuming it to be the root cause
640 of any subsequent Exceptions. It is intended to be used in the
641 upper half of the call chain.
644 Arbitrary exception re-raised on behalf of the reader/writer.
646 assert self.runstate == Runstate.DISCONNECTING
649 aws: List[Awaitable[object]] = [self._dc_task]
651 aws.insert(0, self._bh_tasks)
652 all_defined_tasks = asyncio.gather(*aws)
654 # Ensure disconnect is done; Exception (if any) is not raised here:
655 await asyncio.wait((self._dc_task,))
658 await all_defined_tasks # Raise Exceptions from the bottom half.
661 self._set_state(Runstate.IDLE)
664 def _cleanup(self) -> None:
666 Fully reset this object to a clean state and return to `IDLE`.
668 def _paranoid_task_erase(task: Optional['asyncio.Future[_U]']
669 ) -> Optional['asyncio.Future[_U]']:
670 # Help to erase a task, ENSURING it is fully quiesced first.
671 assert (task is None) or task.done()
672 return None if (task and task.done()) else task
674 assert self.runstate == Runstate.DISCONNECTING
675 self._dc_task = _paranoid_task_erase(self._dc_task)
676 self._reader_task = _paranoid_task_erase(self._reader_task)
677 self._writer_task = _paranoid_task_erase(self._writer_task)
678 self._bh_tasks = _paranoid_task_erase(self._bh_tasks)
683 # NB: _runstate_changed cannot be cleared because we still need it to
684 # send the final runstate changed event ...!
686 # ----------------------------
687 # Section: Bottom Half methods
688 # ----------------------------
691 async def _bh_disconnect(self) -> None:
693 Disconnect and cancel all outstanding tasks.
695 It is designed to be called from its task context,
696 :py:obj:`~AsyncProtocol._dc_task`. By running in its own task,
697 it is free to wait on any pending actions that may still need to
698 occur in either the reader or writer tasks.
700 assert self.runstate == Runstate.DISCONNECTING
702 def _done(task: Optional['asyncio.Future[Any]']) -> bool:
703 return task is not None and task.done()
705 # Are we already in an error pathway? If either of the tasks are
706 # already done, or if we have no tasks but a reader/writer; we
709 # NB: We can't use _bh_tasks to check for premature task
710 # completion, because it may not yet have had a chance to run
712 tasks = tuple(filter(None, (self._writer_task, self._reader_task)))
713 error_pathway = _done(self._reader_task) or _done(self._writer_task)
715 error_pathway |= bool(self._reader) or bool(self._writer)
718 # Try to flush the writer, if possible.
719 # This *may* cause an error and force us over into the error path.
720 if not error_pathway:
721 await self._bh_flush_writer()
722 except BaseException as err:
724 emsg = "Failed to flush the writer"
725 self.logger.error("%s: %s", emsg, exception_summary(err))
726 self.logger.debug("%s:\n%s\n", emsg, pretty_traceback())
729 # Cancel any still-running tasks (Won't raise):
730 if self._writer_task is not None and not self._writer_task.done():
731 self.logger.debug("Cancelling writer task.")
732 self._writer_task.cancel()
733 if self._reader_task is not None and not self._reader_task.done():
734 self.logger.debug("Cancelling reader task.")
735 self._reader_task.cancel()
737 # Close out the tasks entirely (Won't raise):
739 self.logger.debug("Waiting for tasks to complete ...")
740 await asyncio.wait(tasks)
742 # Lastly, close the stream itself. (*May raise*!):
743 await self._bh_close_stream(error_pathway)
744 self.logger.debug("Disconnected.")
747 async def _bh_flush_writer(self) -> None:
748 if not self._writer_task:
751 self.logger.debug("Draining the outbound queue ...")
752 await self._outgoing.join()
753 if self._writer is not None:
754 self.logger.debug("Flushing the StreamWriter ...")
755 await flush(self._writer)
758 async def _bh_close_stream(self, error_pathway: bool = False) -> None:
759 # NB: Closing the writer also implcitly closes the reader.
763 if not is_closing(self._writer):
764 self.logger.debug("Closing StreamWriter.")
767 self.logger.debug("Waiting for StreamWriter to close ...")
769 await wait_closed(self._writer)
770 except Exception: # pylint: disable=broad-except
771 # It's hard to tell if the Stream is already closed or
772 # not. Even if one of the tasks has failed, it may have
773 # failed for a higher-layered protocol reason. The
774 # stream could still be open and perfectly fine.
775 # I don't know how to discern its health here.
778 # We already know that *something* went wrong. Let's
779 # just trust that the Exception we already have is the
780 # better one to present to the user, even if we don't
781 # genuinely *know* the relationship between the two.
783 "Discarding Exception from wait_closed:\n%s\n",
787 # Oops, this is a brand-new error!
790 self.logger.debug("StreamWriter closed.")
793 async def _bh_loop_forever(self, async_fn: _TaskFN, name: str) -> None:
795 Run one of the bottom-half methods in a loop forever.
797 If the bottom half ever raises any exception, schedule a
798 disconnect that will terminate the entire loop.
800 :param async_fn: The bottom-half method to run in a loop.
801 :param name: The name of this task, used for logging.
806 except asyncio.CancelledError:
807 # We have been cancelled by _bh_disconnect, exit gracefully.
808 self.logger.debug("Task.%s: cancelled.", name)
810 except BaseException as err:
812 logging.INFO if isinstance(err, EOFError) else logging.ERROR,
814 name, exception_summary(err)
816 self.logger.debug("Task.%s: failure:\n%s\n",
817 name, pretty_traceback())
818 self._schedule_disconnect()
821 self.logger.debug("Task.%s: exiting.", name)
824 async def _bh_send_message(self) -> None:
826 Wait for an outgoing message, then send it.
828 Designed to be run in `_bh_loop_forever()`.
830 msg = await self._outgoing.get()
832 await self._send(msg)
834 self._outgoing.task_done()
837 async def _bh_recv_message(self) -> None:
839 Wait for an incoming message and call `_on_message` to route it.
841 Designed to be run in `_bh_loop_forever()`.
843 msg = await self._recv()
844 await self._on_message(msg)
846 # --------------------
847 # Section: Message I/O
848 # --------------------
852 def _cb_outbound(self, msg: T) -> T:
854 Callback: outbound message hook.
856 This is intended for subclasses to be able to add arbitrary
857 hooks to filter or manipulate outgoing messages. The base
858 implementation does nothing but log the message without any
859 manipulation of the message.
861 :param msg: raw outbound message
862 :return: final outbound message
864 self.logger.debug("--> %s", str(msg))
869 def _cb_inbound(self, msg: T) -> T:
871 Callback: inbound message hook.
873 This is intended for subclasses to be able to add arbitrary
874 hooks to filter or manipulate incoming messages. The base
875 implementation does nothing but log the message without any
876 manipulation of the message.
878 This method does not "handle" incoming messages; it is a filter.
879 The actual "endpoint" for incoming messages is `_on_message()`.
881 :param msg: raw inbound message
882 :return: processed inbound message
884 self.logger.debug("<-- %s", str(msg))
889 async def _readline(self) -> bytes:
891 Wait for a newline from the incoming reader.
893 This method is provided as a convenience for upper-layer
894 protocols, as many are line-based.
896 This method *may* return a sequence of bytes without a trailing
897 newline if EOF occurs, but *some* bytes were received. In this
898 case, the next call will raise `EOFError`. It is assumed that
899 the layer 5 protocol will decide if there is anything meaningful
900 to be done with a partial message.
902 :raise OSError: For stream-related errors.
904 If the reader stream is at EOF and there are no bytes to return.
905 :return: bytes, including the newline.
907 assert self._reader is not None
908 msg_bytes = await self._reader.readline()
911 if self._reader.at_eof():
918 async def _do_recv(self) -> T:
920 Abstract: Read from the stream and return a message.
922 Very low-level; intended to only be called by `_recv()`.
924 raise NotImplementedError
928 async def _recv(self) -> T:
930 Read an arbitrary protocol message.
933 This method is intended primarily for `_bh_recv_message()`
934 to use in an asynchronous task loop. Using it outside of
935 this loop will "steal" messages from the normal routing
936 mechanism. It is safe to use prior to `_establish_session()`,
937 but should not be used otherwise.
939 This method uses `_do_recv()` to retrieve the raw message, and
940 then transforms it using `_cb_inbound()`.
942 :return: A single (filtered, processed) protocol message.
944 message = await self._do_recv()
945 return self._cb_inbound(message)
949 def _do_send(self, msg: T) -> None:
951 Abstract: Write a message to the stream.
953 Very low-level; intended to only be called by `_send()`.
955 raise NotImplementedError
959 async def _send(self, msg: T) -> None:
961 Send an arbitrary protocol message.
963 This method will transform any outgoing messages according to
967 Like `_recv()`, this method is intended to be called by
968 the writer task loop that processes outgoing
969 messages. Calling it directly may circumvent logic
970 implemented by the caller meant to correlate outgoing and
973 :raise OSError: For problems with the underlying stream.
975 msg = self._cb_outbound(msg)
979 async def _on_message(self, msg: T) -> None:
981 Called to handle the receipt of a new message.
984 This is executed from within the reader loop, so be advised
985 that waiting on either the reader or writer task will lead
986 to deadlock. Additionally, any unhandled exceptions will
987 directly cause the loop to halt, so logic may be best-kept
988 to a minimum if at all possible.
990 :param msg: The incoming message, already logged/filtered.
992 # Nothing to do in the abstract case.