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 start_server_and_accept(
269 self, address: SocketAddrT,
270 ssl: Optional[SSLContext] = None
273 Accept a connection and begin processing message queues.
275 If this call fails, `runstate` is guaranteed to be set back to `IDLE`.
278 Address to listen on; UNIX socket path or TCP address/port.
279 :param ssl: SSL context to use, if any.
281 :raise StateError: When the `Runstate` is not `IDLE`.
283 When a connection or session cannot be established.
285 This exception will wrap a more concrete one. In most cases,
286 the wrapped exception will be `OSError` or `EOFError`. If a
287 protocol-level failure occurs while establishing a new
288 session, the wrapped error may also be an `QMPError`.
290 await self._session_guard(
291 self._do_accept(address, ssl),
292 'Failed to establish connection')
293 await self._session_guard(
294 self._establish_session(),
295 'Failed to establish session')
296 assert self.runstate == Runstate.RUNNING
299 @require(Runstate.IDLE)
300 async def connect(self, address: SocketAddrT,
301 ssl: Optional[SSLContext] = None) -> None:
303 Connect to the server and begin processing message queues.
305 If this call fails, `runstate` is guaranteed to be set back to `IDLE`.
308 Address to connect to; UNIX socket path or TCP address/port.
309 :param ssl: SSL context to use, if any.
311 :raise StateError: When the `Runstate` is not `IDLE`.
313 When a connection or session cannot be established.
315 This exception will wrap a more concrete one. In most cases,
316 the wrapped exception will be `OSError` or `EOFError`. If a
317 protocol-level failure occurs while establishing a new
318 session, the wrapped error may also be an `QMPError`.
320 await self._session_guard(
321 self._do_connect(address, ssl),
322 'Failed to establish connection')
323 await self._session_guard(
324 self._establish_session(),
325 'Failed to establish session')
326 assert self.runstate == Runstate.RUNNING
329 async def disconnect(self) -> None:
331 Disconnect and wait for all tasks to fully stop.
333 If there was an exception that caused the reader/writers to
334 terminate prematurely, it will be raised here.
336 :raise Exception: When the reader or writer terminate unexpectedly.
338 self.logger.debug("disconnect() called.")
339 self._schedule_disconnect()
340 await self._wait_disconnect()
342 # --------------------------
343 # Section: Session machinery
344 # --------------------------
346 async def _session_guard(self, coro: Awaitable[None], emsg: str) -> None:
348 Async guard function used to roll back to `IDLE` on any error.
350 On any Exception, the state machine will be reset back to
351 `IDLE`. Most Exceptions will be wrapped with `ConnectError`, but
352 `BaseException` events will be left alone (This includes
353 asyncio.CancelledError, even prior to Python 3.8).
355 :param error_message:
356 Human-readable string describing what connection phase failed.
358 :raise BaseException:
359 When `BaseException` occurs in the guarded block.
361 When any other error is encountered in the guarded block.
363 # Note: After Python 3.6 support is removed, this should be an
364 # @asynccontextmanager instead of accepting a callback.
367 except BaseException as err:
368 self.logger.error("%s: %s", emsg, exception_summary(err))
369 self.logger.debug("%s:\n%s\n", emsg, pretty_traceback())
371 # Reset the runstate back to IDLE.
372 await self.disconnect()
374 # We don't expect any Exceptions from the disconnect function
375 # here, because we failed to connect in the first place.
376 # The disconnect() function is intended to perform
377 # only cannot-fail cleanup here, but you never know.
379 "Unexpected bottom half exception. "
380 "This is a bug in the QMP library. "
384 self.logger.critical("%s:\n%s\n", emsg, pretty_traceback())
387 # CancelledError is an Exception with special semantic meaning;
388 # We do NOT want to wrap it up under ConnectError.
389 # NB: CancelledError is not a BaseException before Python 3.8
390 if isinstance(err, asyncio.CancelledError):
393 # Any other kind of error can be treated as some kind of connection
394 # failure broadly. Inspect the 'exc' field to explore the root
395 # cause in greater detail.
396 if isinstance(err, Exception):
397 raise ConnectError(emsg, err) from err
399 # Raise BaseExceptions un-wrapped, they're more important.
403 def _runstate_event(self) -> asyncio.Event:
404 # asyncio.Event() objects should not be created prior to entrance into
405 # an event loop, so we can ensure we create it in the correct context.
406 # Create it on-demand *only* at the behest of an 'async def' method.
407 if not self._runstate_changed:
408 self._runstate_changed = asyncio.Event()
409 return self._runstate_changed
413 def _set_state(self, state: Runstate) -> None:
415 Change the `Runstate` of the protocol connection.
417 Signals the `runstate_changed` event.
419 if state == self._runstate:
422 self.logger.debug("Transitioning from '%s' to '%s'.",
423 str(self._runstate), str(state))
424 self._runstate = state
425 self._runstate_event.set()
426 self._runstate_event.clear()
428 def _bind_hack(self, address: Union[str, Tuple[str, int]]) -> None:
430 Used to create a socket in advance of accept().
432 This is a workaround to ensure that we can guarantee timing of
433 precisely when a socket exists to avoid a connection attempt
434 bouncing off of nothing.
436 Python 3.7+ adds a feature to separate the server creation and
437 listening phases instead, and should be used instead of this
440 if isinstance(address, tuple):
441 family = socket.AF_INET
443 family = socket.AF_UNIX
445 sock = socket.socket(family, socket.SOCK_STREAM)
446 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
457 async def _do_accept(self, address: SocketAddrT,
458 ssl: Optional[SSLContext] = None) -> None:
460 Acting as the transport server, accept a single connection.
463 Address to listen on; UNIX socket path or TCP address/port.
464 :param ssl: SSL context to use, if any.
466 :raise OSError: For stream-related errors.
468 assert self.runstate == Runstate.IDLE
469 self._set_state(Runstate.CONNECTING)
471 self.logger.debug("Awaiting connection on %s ...", address)
472 connected = asyncio.Event()
473 server: Optional[asyncio.AbstractServer] = None
475 async def _client_connected_cb(reader: asyncio.StreamReader,
476 writer: asyncio.StreamWriter) -> None:
477 """Used to accept a single incoming connection, see below."""
481 # A connection has been accepted; stop listening for new ones.
482 assert server is not None
484 await server.wait_closed()
487 # Register this client as being connected
488 self._reader, self._writer = (reader, writer)
490 # Signal back: We've accepted a client!
493 if isinstance(address, tuple):
494 coro = asyncio.start_server(
495 _client_connected_cb,
496 host=None if self._sock else address[0],
497 port=None if self._sock else address[1],
504 coro = asyncio.start_unix_server(
505 _client_connected_cb,
506 path=None if self._sock else address,
513 # Allow runstate watchers to witness 'CONNECTING' state; some
514 # failures in the streaming layer are synchronous and will not
516 await asyncio.sleep(0)
518 server = await coro # Starts listening
519 await connected.wait() # Waits for the callback to fire (and finish)
520 assert server is None
523 self.logger.debug("Connection accepted.")
526 async def _do_connect(self, address: SocketAddrT,
527 ssl: Optional[SSLContext] = None) -> None:
529 Acting as the transport client, initiate a connection to a server.
532 Address to connect to; UNIX socket path or TCP address/port.
533 :param ssl: SSL context to use, if any.
535 :raise OSError: For stream-related errors.
537 assert self.runstate == Runstate.IDLE
538 self._set_state(Runstate.CONNECTING)
540 # Allow runstate watchers to witness 'CONNECTING' state; some
541 # failures in the streaming layer are synchronous and will not
543 await asyncio.sleep(0)
545 self.logger.debug("Connecting to %s ...", address)
547 if isinstance(address, tuple):
548 connect = asyncio.open_connection(
555 connect = asyncio.open_unix_connection(
560 self._reader, self._writer = await connect
562 self.logger.debug("Connected.")
565 async def _establish_session(self) -> None:
567 Establish a new session.
569 Starts the readers/writer tasks; subclasses may perform their
570 own negotiations here. The Runstate will be RUNNING upon
571 successful conclusion.
573 assert self.runstate == Runstate.CONNECTING
575 self._outgoing = asyncio.Queue()
577 reader_coro = self._bh_loop_forever(self._bh_recv_message, 'Reader')
578 writer_coro = self._bh_loop_forever(self._bh_send_message, 'Writer')
580 self._reader_task = create_task(reader_coro)
581 self._writer_task = create_task(writer_coro)
583 self._bh_tasks = asyncio.gather(
588 self._set_state(Runstate.RUNNING)
589 await asyncio.sleep(0) # Allow runstate_event to process
593 def _schedule_disconnect(self) -> None:
595 Initiate a disconnect; idempotent.
597 This method is used both in the upper-half as a direct
598 consequence of `disconnect()`, and in the bottom-half in the
599 case of unhandled exceptions in the reader/writer tasks.
601 It can be invoked no matter what the `runstate` is.
603 if not self._dc_task:
604 self._set_state(Runstate.DISCONNECTING)
605 self.logger.debug("Scheduling disconnect.")
606 self._dc_task = create_task(self._bh_disconnect())
609 async def _wait_disconnect(self) -> None:
611 Waits for a previously scheduled disconnect to finish.
613 This method will gather any bottom half exceptions and re-raise
614 the one that occurred first; presuming it to be the root cause
615 of any subsequent Exceptions. It is intended to be used in the
616 upper half of the call chain.
619 Arbitrary exception re-raised on behalf of the reader/writer.
621 assert self.runstate == Runstate.DISCONNECTING
624 aws: List[Awaitable[object]] = [self._dc_task]
626 aws.insert(0, self._bh_tasks)
627 all_defined_tasks = asyncio.gather(*aws)
629 # Ensure disconnect is done; Exception (if any) is not raised here:
630 await asyncio.wait((self._dc_task,))
633 await all_defined_tasks # Raise Exceptions from the bottom half.
636 self._set_state(Runstate.IDLE)
639 def _cleanup(self) -> None:
641 Fully reset this object to a clean state and return to `IDLE`.
643 def _paranoid_task_erase(task: Optional['asyncio.Future[_U]']
644 ) -> Optional['asyncio.Future[_U]']:
645 # Help to erase a task, ENSURING it is fully quiesced first.
646 assert (task is None) or task.done()
647 return None if (task and task.done()) else task
649 assert self.runstate == Runstate.DISCONNECTING
650 self._dc_task = _paranoid_task_erase(self._dc_task)
651 self._reader_task = _paranoid_task_erase(self._reader_task)
652 self._writer_task = _paranoid_task_erase(self._writer_task)
653 self._bh_tasks = _paranoid_task_erase(self._bh_tasks)
658 # NB: _runstate_changed cannot be cleared because we still need it to
659 # send the final runstate changed event ...!
661 # ----------------------------
662 # Section: Bottom Half methods
663 # ----------------------------
666 async def _bh_disconnect(self) -> None:
668 Disconnect and cancel all outstanding tasks.
670 It is designed to be called from its task context,
671 :py:obj:`~AsyncProtocol._dc_task`. By running in its own task,
672 it is free to wait on any pending actions that may still need to
673 occur in either the reader or writer tasks.
675 assert self.runstate == Runstate.DISCONNECTING
677 def _done(task: Optional['asyncio.Future[Any]']) -> bool:
678 return task is not None and task.done()
680 # Are we already in an error pathway? If either of the tasks are
681 # already done, or if we have no tasks but a reader/writer; we
684 # NB: We can't use _bh_tasks to check for premature task
685 # completion, because it may not yet have had a chance to run
687 tasks = tuple(filter(None, (self._writer_task, self._reader_task)))
688 error_pathway = _done(self._reader_task) or _done(self._writer_task)
690 error_pathway |= bool(self._reader) or bool(self._writer)
693 # Try to flush the writer, if possible.
694 # This *may* cause an error and force us over into the error path.
695 if not error_pathway:
696 await self._bh_flush_writer()
697 except BaseException as err:
699 emsg = "Failed to flush the writer"
700 self.logger.error("%s: %s", emsg, exception_summary(err))
701 self.logger.debug("%s:\n%s\n", emsg, pretty_traceback())
704 # Cancel any still-running tasks (Won't raise):
705 if self._writer_task is not None and not self._writer_task.done():
706 self.logger.debug("Cancelling writer task.")
707 self._writer_task.cancel()
708 if self._reader_task is not None and not self._reader_task.done():
709 self.logger.debug("Cancelling reader task.")
710 self._reader_task.cancel()
712 # Close out the tasks entirely (Won't raise):
714 self.logger.debug("Waiting for tasks to complete ...")
715 await asyncio.wait(tasks)
717 # Lastly, close the stream itself. (*May raise*!):
718 await self._bh_close_stream(error_pathway)
719 self.logger.debug("Disconnected.")
722 async def _bh_flush_writer(self) -> None:
723 if not self._writer_task:
726 self.logger.debug("Draining the outbound queue ...")
727 await self._outgoing.join()
728 if self._writer is not None:
729 self.logger.debug("Flushing the StreamWriter ...")
730 await flush(self._writer)
733 async def _bh_close_stream(self, error_pathway: bool = False) -> None:
734 # NB: Closing the writer also implcitly closes the reader.
738 if not is_closing(self._writer):
739 self.logger.debug("Closing StreamWriter.")
742 self.logger.debug("Waiting for StreamWriter to close ...")
744 await wait_closed(self._writer)
745 except Exception: # pylint: disable=broad-except
746 # It's hard to tell if the Stream is already closed or
747 # not. Even if one of the tasks has failed, it may have
748 # failed for a higher-layered protocol reason. The
749 # stream could still be open and perfectly fine.
750 # I don't know how to discern its health here.
753 # We already know that *something* went wrong. Let's
754 # just trust that the Exception we already have is the
755 # better one to present to the user, even if we don't
756 # genuinely *know* the relationship between the two.
758 "Discarding Exception from wait_closed:\n%s\n",
762 # Oops, this is a brand-new error!
765 self.logger.debug("StreamWriter closed.")
768 async def _bh_loop_forever(self, async_fn: _TaskFN, name: str) -> None:
770 Run one of the bottom-half methods in a loop forever.
772 If the bottom half ever raises any exception, schedule a
773 disconnect that will terminate the entire loop.
775 :param async_fn: The bottom-half method to run in a loop.
776 :param name: The name of this task, used for logging.
781 except asyncio.CancelledError:
782 # We have been cancelled by _bh_disconnect, exit gracefully.
783 self.logger.debug("Task.%s: cancelled.", name)
785 except BaseException as err:
787 logging.INFO if isinstance(err, EOFError) else logging.ERROR,
789 name, exception_summary(err)
791 self.logger.debug("Task.%s: failure:\n%s\n",
792 name, pretty_traceback())
793 self._schedule_disconnect()
796 self.logger.debug("Task.%s: exiting.", name)
799 async def _bh_send_message(self) -> None:
801 Wait for an outgoing message, then send it.
803 Designed to be run in `_bh_loop_forever()`.
805 msg = await self._outgoing.get()
807 await self._send(msg)
809 self._outgoing.task_done()
812 async def _bh_recv_message(self) -> None:
814 Wait for an incoming message and call `_on_message` to route it.
816 Designed to be run in `_bh_loop_forever()`.
818 msg = await self._recv()
819 await self._on_message(msg)
821 # --------------------
822 # Section: Message I/O
823 # --------------------
827 def _cb_outbound(self, msg: T) -> T:
829 Callback: outbound message hook.
831 This is intended for subclasses to be able to add arbitrary
832 hooks to filter or manipulate outgoing messages. The base
833 implementation does nothing but log the message without any
834 manipulation of the message.
836 :param msg: raw outbound message
837 :return: final outbound message
839 self.logger.debug("--> %s", str(msg))
844 def _cb_inbound(self, msg: T) -> T:
846 Callback: inbound message hook.
848 This is intended for subclasses to be able to add arbitrary
849 hooks to filter or manipulate incoming messages. The base
850 implementation does nothing but log the message without any
851 manipulation of the message.
853 This method does not "handle" incoming messages; it is a filter.
854 The actual "endpoint" for incoming messages is `_on_message()`.
856 :param msg: raw inbound message
857 :return: processed inbound message
859 self.logger.debug("<-- %s", str(msg))
864 async def _readline(self) -> bytes:
866 Wait for a newline from the incoming reader.
868 This method is provided as a convenience for upper-layer
869 protocols, as many are line-based.
871 This method *may* return a sequence of bytes without a trailing
872 newline if EOF occurs, but *some* bytes were received. In this
873 case, the next call will raise `EOFError`. It is assumed that
874 the layer 5 protocol will decide if there is anything meaningful
875 to be done with a partial message.
877 :raise OSError: For stream-related errors.
879 If the reader stream is at EOF and there are no bytes to return.
880 :return: bytes, including the newline.
882 assert self._reader is not None
883 msg_bytes = await self._reader.readline()
886 if self._reader.at_eof():
893 async def _do_recv(self) -> T:
895 Abstract: Read from the stream and return a message.
897 Very low-level; intended to only be called by `_recv()`.
899 raise NotImplementedError
903 async def _recv(self) -> T:
905 Read an arbitrary protocol message.
908 This method is intended primarily for `_bh_recv_message()`
909 to use in an asynchronous task loop. Using it outside of
910 this loop will "steal" messages from the normal routing
911 mechanism. It is safe to use prior to `_establish_session()`,
912 but should not be used otherwise.
914 This method uses `_do_recv()` to retrieve the raw message, and
915 then transforms it using `_cb_inbound()`.
917 :return: A single (filtered, processed) protocol message.
919 message = await self._do_recv()
920 return self._cb_inbound(message)
924 def _do_send(self, msg: T) -> None:
926 Abstract: Write a message to the stream.
928 Very low-level; intended to only be called by `_send()`.
930 raise NotImplementedError
934 async def _send(self, msg: T) -> None:
936 Send an arbitrary protocol message.
938 This method will transform any outgoing messages according to
942 Like `_recv()`, this method is intended to be called by
943 the writer task loop that processes outgoing
944 messages. Calling it directly may circumvent logic
945 implemented by the caller meant to correlate outgoing and
948 :raise OSError: For problems with the underlying stream.
950 msg = self._cb_outbound(msg)
954 async def _on_message(self, msg: T) -> None:
956 Called to handle the receipt of a new message.
959 This is executed from within the reader loop, so be advised
960 that waiting on either the reader or writer task will lead
961 to deadlock. Additionally, any unhandled exceptions will
962 directly cause the loop to halt, so logic may be best-kept
963 to a minimum if at all possible.
965 :param msg: The incoming message, already logged/filtered.
967 # Nothing to do in the abstract case.