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`
13 # It's all the docstrings ... ! It's long for a good reason ^_^;
14 # pylint: disable=too-many-lines
17 from asyncio import StreamReader, StreamWriter
19 from functools import wraps
22 from ssl import SSLContext
36 from .error import QMPError
51 _TaskFN = Callable[[], Awaitable[None]] # aka ``async def func() -> None``
53 InternetAddrT = Tuple[str, int]
55 SocketAddrT = Union[UnixAddrT, InternetAddrT]
59 """Protocol session runstate."""
61 #: Fully quiesced and disconnected.
63 #: In the process of connecting or establishing a session.
65 #: Fully connected and active session.
67 #: In the process of disconnecting.
68 #: Runstate may be returned to `IDLE` by calling `disconnect()`.
72 class ConnectError(QMPError):
74 Raised when the initial connection process has failed.
76 This Exception always wraps a "root cause" exception that can be
77 interrogated for additional information.
79 :param error_message: Human-readable string describing the error.
80 :param exc: The root-cause exception.
82 def __init__(self, error_message: str, exc: Exception):
83 super().__init__(error_message)
84 #: Human-readable error string
85 self.error_message: str = error_message
86 #: Wrapped root cause exception
87 self.exc: Exception = exc
89 def __str__(self) -> str:
92 # If there's no error string, use the exception name.
93 cause = exception_summary(self.exc)
94 return f"{self.error_message}: {cause}"
97 class StateError(QMPError):
99 An API command (connect, execute, etc) was issued at an inappropriate time.
101 This error is raised when a command like
102 :py:meth:`~AsyncProtocol.connect()` is issued at an inappropriate
105 :param error_message: Human-readable string describing the state violation.
106 :param state: The actual `Runstate` seen at the time of the violation.
107 :param required: The `Runstate` required to process this command.
109 def __init__(self, error_message: str,
110 state: Runstate, required: Runstate):
111 super().__init__(error_message)
112 self.error_message = error_message
114 self.required = required
117 F = TypeVar('F', bound=Callable[..., Any]) # pylint: disable=invalid-name
121 def require(required_state: Runstate) -> Callable[[F], F]:
123 Decorator: protect a method so it can only be run in a certain `Runstate`.
125 :param required_state: The `Runstate` required to invoke this method.
126 :raise StateError: When the required `Runstate` is not met.
128 def _decorator(func: F) -> F:
129 # _decorator is the decorator that is built by calling the
130 # require() decorator factory; e.g.:
132 # @require(Runstate.IDLE) def foo(): ...
133 # will replace 'foo' with the result of '_decorator(foo)'.
136 def _wrapper(proto: 'AsyncProtocol[Any]',
137 *args: Any, **kwargs: Any) -> Any:
138 # _wrapper is the function that gets executed prior to the
141 name = type(proto).__name__
143 if proto.runstate != required_state:
144 if proto.runstate == Runstate.CONNECTING:
145 emsg = f"{name} is currently connecting."
146 elif proto.runstate == Runstate.DISCONNECTING:
147 emsg = (f"{name} is disconnecting."
148 " Call disconnect() to return to IDLE state.")
149 elif proto.runstate == Runstate.RUNNING:
150 emsg = f"{name} is already connected and running."
151 elif proto.runstate == Runstate.IDLE:
152 emsg = f"{name} is disconnected and idle."
155 raise StateError(emsg, proto.runstate, required_state)
156 # No StateError, so call the wrapped method.
157 return func(proto, *args, **kwargs)
159 # Return the decorated method;
160 # Transforming Func to Decorated[Func].
161 return cast(F, _wrapper)
163 # Return the decorator instance from the decorator factory. Phew!
167 class AsyncProtocol(Generic[T]):
169 AsyncProtocol implements a generic async message-based protocol.
171 This protocol assumes the basic unit of information transfer between
172 client and server is a "message", the details of which are left up
173 to the implementation. It assumes the sending and receiving of these
174 messages is full-duplex and not necessarily correlated; i.e. it
175 supports asynchronous inbound messages.
177 It is designed to be extended by a specific protocol which provides
178 the implementations for how to read and send messages. These must be
179 defined in `_do_recv()` and `_do_send()`, respectively.
181 Other callbacks have a default implementation, but are intended to be
182 either extended or overridden:
184 - `_establish_session`:
185 The base implementation starts the reader/writer tasks.
186 A protocol implementation can override this call, inserting
187 actions to be taken prior to starting the reader/writer tasks
188 before the super() call; actions needing to occur afterwards
189 can be written after the super() call.
191 Actions to be performed when a message is received.
193 Logging/Filtering hook for all outbound messages.
195 Logging/Filtering hook for all inbound messages.
196 This hook runs *before* `_on_message()`.
199 Name used for logging messages, if any. By default, messages
200 will log to 'qemu.aqmp.protocol', but each individual connection
201 can be given its own logger by giving it a name; messages will
202 then log to 'qemu.aqmp.protocol.${name}'.
204 # pylint: disable=too-many-instance-attributes
206 #: Logger object for debugging messages from this connection.
207 logger = logging.getLogger(__name__)
209 # Maximum allowable size of read buffer
212 # -------------------------
213 # Section: Public interface
214 # -------------------------
216 def __init__(self, name: Optional[str] = None) -> None:
217 #: The nickname for this connection, if any.
218 self.name: Optional[str] = name
219 if self.name is not None:
220 self.logger = self.logger.getChild(self.name)
223 self._reader: Optional[StreamReader] = None
224 self._writer: Optional[StreamWriter] = None
226 # Outbound Message queue
227 self._outgoing: asyncio.Queue[T]
229 # Special, long-running tasks:
230 self._reader_task: Optional[asyncio.Future[None]] = None
231 self._writer_task: Optional[asyncio.Future[None]] = None
233 # Aggregate of the above two tasks, used for Exception management.
234 self._bh_tasks: Optional[asyncio.Future[Tuple[None, None]]] = None
236 #: Disconnect task. The disconnect implementation runs in a task
237 #: so that asynchronous disconnects (initiated by the
238 #: reader/writer) are allowed to wait for the reader/writers to
240 self._dc_task: Optional[asyncio.Future[None]] = None
242 self._runstate = Runstate.IDLE
243 self._runstate_changed: Optional[asyncio.Event] = None
245 # Workaround for bind()
246 self._sock: Optional[socket.socket] = None
248 # Server state for start_server() and _incoming()
249 self._server: Optional[asyncio.AbstractServer] = None
250 self._accepted: Optional[asyncio.Event] = None
252 def __repr__(self) -> str:
253 cls_name = type(self).__name__
255 if self.name is not None:
256 tokens.append(f"name={self.name!r}")
257 tokens.append(f"runstate={self.runstate.name}")
258 return f"<{cls_name} {' '.join(tokens)}>"
260 @property # @upper_half
261 def runstate(self) -> Runstate:
262 """The current `Runstate` of the connection."""
263 return self._runstate
266 async def runstate_changed(self) -> Runstate:
268 Wait for the `runstate` to change, then return that runstate.
270 await self._runstate_event.wait()
274 @require(Runstate.IDLE)
275 async def start_server_and_accept(
276 self, address: SocketAddrT,
277 ssl: Optional[SSLContext] = None
280 Accept a connection and begin processing message queues.
282 If this call fails, `runstate` is guaranteed to be set back to `IDLE`.
285 Address to listen on; UNIX socket path or TCP address/port.
286 :param ssl: SSL context to use, if any.
288 :raise StateError: When the `Runstate` is not `IDLE`.
290 When a connection or session cannot be established.
292 This exception will wrap a more concrete one. In most cases,
293 the wrapped exception will be `OSError` or `EOFError`. If a
294 protocol-level failure occurs while establishing a new
295 session, the wrapped error may also be an `QMPError`.
297 await self._session_guard(
298 self._do_accept(address, ssl),
299 'Failed to establish connection')
300 await self._session_guard(
301 self._establish_session(),
302 'Failed to establish session')
303 assert self.runstate == Runstate.RUNNING
306 @require(Runstate.IDLE)
307 async def connect(self, address: SocketAddrT,
308 ssl: Optional[SSLContext] = None) -> None:
310 Connect to the server and begin processing message queues.
312 If this call fails, `runstate` is guaranteed to be set back to `IDLE`.
315 Address to connect to; UNIX socket path or TCP address/port.
316 :param ssl: SSL context to use, if any.
318 :raise StateError: When the `Runstate` is not `IDLE`.
320 When a connection or session cannot be established.
322 This exception will wrap a more concrete one. In most cases,
323 the wrapped exception will be `OSError` or `EOFError`. If a
324 protocol-level failure occurs while establishing a new
325 session, the wrapped error may also be an `QMPError`.
327 await self._session_guard(
328 self._do_connect(address, ssl),
329 'Failed to establish connection')
330 await self._session_guard(
331 self._establish_session(),
332 'Failed to establish session')
333 assert self.runstate == Runstate.RUNNING
336 async def disconnect(self) -> None:
338 Disconnect and wait for all tasks to fully stop.
340 If there was an exception that caused the reader/writers to
341 terminate prematurely, it will be raised here.
343 :raise Exception: When the reader or writer terminate unexpectedly.
345 self.logger.debug("disconnect() called.")
346 self._schedule_disconnect()
347 await self._wait_disconnect()
349 # --------------------------
350 # Section: Session machinery
351 # --------------------------
353 async def _session_guard(self, coro: Awaitable[None], emsg: str) -> None:
355 Async guard function used to roll back to `IDLE` on any error.
357 On any Exception, the state machine will be reset back to
358 `IDLE`. Most Exceptions will be wrapped with `ConnectError`, but
359 `BaseException` events will be left alone (This includes
360 asyncio.CancelledError, even prior to Python 3.8).
362 :param error_message:
363 Human-readable string describing what connection phase failed.
365 :raise BaseException:
366 When `BaseException` occurs in the guarded block.
368 When any other error is encountered in the guarded block.
370 # Note: After Python 3.6 support is removed, this should be an
371 # @asynccontextmanager instead of accepting a callback.
374 except BaseException as err:
375 self.logger.error("%s: %s", emsg, exception_summary(err))
376 self.logger.debug("%s:\n%s\n", emsg, pretty_traceback())
378 # Reset the runstate back to IDLE.
379 await self.disconnect()
381 # We don't expect any Exceptions from the disconnect function
382 # here, because we failed to connect in the first place.
383 # The disconnect() function is intended to perform
384 # only cannot-fail cleanup here, but you never know.
386 "Unexpected bottom half exception. "
387 "This is a bug in the QMP library. "
388 "Please report it to <qemu-devel@nongnu.org> and "
389 "CC: John Snow <jsnow@redhat.com>."
391 self.logger.critical("%s:\n%s\n", emsg, pretty_traceback())
394 # CancelledError is an Exception with special semantic meaning;
395 # We do NOT want to wrap it up under ConnectError.
396 # NB: CancelledError is not a BaseException before Python 3.8
397 if isinstance(err, asyncio.CancelledError):
400 # Any other kind of error can be treated as some kind of connection
401 # failure broadly. Inspect the 'exc' field to explore the root
402 # cause in greater detail.
403 if isinstance(err, Exception):
404 raise ConnectError(emsg, err) from err
406 # Raise BaseExceptions un-wrapped, they're more important.
410 def _runstate_event(self) -> asyncio.Event:
411 # asyncio.Event() objects should not be created prior to entrance into
412 # an event loop, so we can ensure we create it in the correct context.
413 # Create it on-demand *only* at the behest of an 'async def' method.
414 if not self._runstate_changed:
415 self._runstate_changed = asyncio.Event()
416 return self._runstate_changed
420 def _set_state(self, state: Runstate) -> None:
422 Change the `Runstate` of the protocol connection.
424 Signals the `runstate_changed` event.
426 if state == self._runstate:
429 self.logger.debug("Transitioning from '%s' to '%s'.",
430 str(self._runstate), str(state))
431 self._runstate = state
432 self._runstate_event.set()
433 self._runstate_event.clear()
435 @bottom_half # However, it does not run from the R/W tasks.
436 async def _stop_server(self) -> None:
438 Stop listening for / accepting new incoming connections.
440 if self._server is None:
444 self.logger.debug("Stopping server.")
446 await self._server.wait_closed()
447 self.logger.debug("Server stopped.")
451 @bottom_half # However, it does not run from the R/W tasks.
452 async def _incoming(self,
453 reader: asyncio.StreamReader,
454 writer: asyncio.StreamWriter) -> None:
456 Accept an incoming connection and signal the upper_half.
458 This method does the minimum necessary to accept a single
459 incoming connection. It signals back to the upper_half ASAP so
460 that any errors during session initialization can occur
461 naturally in the caller's stack.
463 :param reader: Incoming `asyncio.StreamReader`
464 :param writer: Incoming `asyncio.StreamWriter`
466 peer = writer.get_extra_info('peername', 'Unknown peer')
467 self.logger.debug("Incoming connection from %s", peer)
469 if self._reader or self._writer:
470 # Sadly, we can have more than one pending connection
471 # because of https://bugs.python.org/issue46715
472 # Close any extra connections we don't actually want.
473 self.logger.warning("Extraneous connection inadvertently accepted")
477 # A connection has been accepted; stop listening for new ones.
478 assert self._accepted is not None
479 await self._stop_server()
480 self._reader, self._writer = (reader, writer)
483 def _bind_hack(self, address: Union[str, Tuple[str, int]]) -> None:
485 Used to create a socket in advance of accept().
487 This is a workaround to ensure that we can guarantee timing of
488 precisely when a socket exists to avoid a connection attempt
489 bouncing off of nothing.
491 Python 3.7+ adds a feature to separate the server creation and
492 listening phases instead, and should be used instead of this
495 if isinstance(address, tuple):
496 family = socket.AF_INET
498 family = socket.AF_UNIX
500 sock = socket.socket(family, socket.SOCK_STREAM)
501 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
512 async def _do_accept(self, address: SocketAddrT,
513 ssl: Optional[SSLContext] = None) -> None:
515 Acting as the transport server, accept a single connection.
518 Address to listen on; UNIX socket path or TCP address/port.
519 :param ssl: SSL context to use, if any.
521 :raise OSError: For stream-related errors.
523 assert self.runstate == Runstate.IDLE
524 self._set_state(Runstate.CONNECTING)
526 self.logger.debug("Awaiting connection on %s ...", address)
527 self._accepted = asyncio.Event()
529 if isinstance(address, tuple):
530 coro = asyncio.start_server(
532 host=None if self._sock else address[0],
533 port=None if self._sock else address[1],
540 coro = asyncio.start_unix_server(
542 path=None if self._sock else address,
549 # Allow runstate watchers to witness 'CONNECTING' state; some
550 # failures in the streaming layer are synchronous and will not
552 await asyncio.sleep(0)
554 self._server = await coro # Starts listening
555 await self._accepted.wait() # Waits for the callback to finish
556 assert self._server is None
559 self.logger.debug("Connection accepted.")
562 async def _do_connect(self, address: SocketAddrT,
563 ssl: Optional[SSLContext] = None) -> None:
565 Acting as the transport client, initiate a connection to a server.
568 Address to connect to; UNIX socket path or TCP address/port.
569 :param ssl: SSL context to use, if any.
571 :raise OSError: For stream-related errors.
573 assert self.runstate == Runstate.IDLE
574 self._set_state(Runstate.CONNECTING)
576 # Allow runstate watchers to witness 'CONNECTING' state; some
577 # failures in the streaming layer are synchronous and will not
579 await asyncio.sleep(0)
581 self.logger.debug("Connecting to %s ...", address)
583 if isinstance(address, tuple):
584 connect = asyncio.open_connection(
591 connect = asyncio.open_unix_connection(
596 self._reader, self._writer = await connect
598 self.logger.debug("Connected.")
601 async def _establish_session(self) -> None:
603 Establish a new session.
605 Starts the readers/writer tasks; subclasses may perform their
606 own negotiations here. The Runstate will be RUNNING upon
607 successful conclusion.
609 assert self.runstate == Runstate.CONNECTING
611 self._outgoing = asyncio.Queue()
613 reader_coro = self._bh_loop_forever(self._bh_recv_message, 'Reader')
614 writer_coro = self._bh_loop_forever(self._bh_send_message, 'Writer')
616 self._reader_task = create_task(reader_coro)
617 self._writer_task = create_task(writer_coro)
619 self._bh_tasks = asyncio.gather(
624 self._set_state(Runstate.RUNNING)
625 await asyncio.sleep(0) # Allow runstate_event to process
629 def _schedule_disconnect(self) -> None:
631 Initiate a disconnect; idempotent.
633 This method is used both in the upper-half as a direct
634 consequence of `disconnect()`, and in the bottom-half in the
635 case of unhandled exceptions in the reader/writer tasks.
637 It can be invoked no matter what the `runstate` is.
639 if not self._dc_task:
640 self._set_state(Runstate.DISCONNECTING)
641 self.logger.debug("Scheduling disconnect.")
642 self._dc_task = create_task(self._bh_disconnect())
645 async def _wait_disconnect(self) -> None:
647 Waits for a previously scheduled disconnect to finish.
649 This method will gather any bottom half exceptions and re-raise
650 the one that occurred first; presuming it to be the root cause
651 of any subsequent Exceptions. It is intended to be used in the
652 upper half of the call chain.
655 Arbitrary exception re-raised on behalf of the reader/writer.
657 assert self.runstate == Runstate.DISCONNECTING
660 aws: List[Awaitable[object]] = [self._dc_task]
662 aws.insert(0, self._bh_tasks)
663 all_defined_tasks = asyncio.gather(*aws)
665 # Ensure disconnect is done; Exception (if any) is not raised here:
666 await asyncio.wait((self._dc_task,))
669 await all_defined_tasks # Raise Exceptions from the bottom half.
672 self._set_state(Runstate.IDLE)
675 def _cleanup(self) -> None:
677 Fully reset this object to a clean state and return to `IDLE`.
679 def _paranoid_task_erase(task: Optional['asyncio.Future[_U]']
680 ) -> Optional['asyncio.Future[_U]']:
681 # Help to erase a task, ENSURING it is fully quiesced first.
682 assert (task is None) or task.done()
683 return None if (task and task.done()) else task
685 assert self.runstate == Runstate.DISCONNECTING
686 self._dc_task = _paranoid_task_erase(self._dc_task)
687 self._reader_task = _paranoid_task_erase(self._reader_task)
688 self._writer_task = _paranoid_task_erase(self._writer_task)
689 self._bh_tasks = _paranoid_task_erase(self._bh_tasks)
694 # NB: _runstate_changed cannot be cleared because we still need it to
695 # send the final runstate changed event ...!
697 # ----------------------------
698 # Section: Bottom Half methods
699 # ----------------------------
702 async def _bh_disconnect(self) -> None:
704 Disconnect and cancel all outstanding tasks.
706 It is designed to be called from its task context,
707 :py:obj:`~AsyncProtocol._dc_task`. By running in its own task,
708 it is free to wait on any pending actions that may still need to
709 occur in either the reader or writer tasks.
711 assert self.runstate == Runstate.DISCONNECTING
713 def _done(task: Optional['asyncio.Future[Any]']) -> bool:
714 return task is not None and task.done()
716 # Are we already in an error pathway? If either of the tasks are
717 # already done, or if we have no tasks but a reader/writer; we
720 # NB: We can't use _bh_tasks to check for premature task
721 # completion, because it may not yet have had a chance to run
723 tasks = tuple(filter(None, (self._writer_task, self._reader_task)))
724 error_pathway = _done(self._reader_task) or _done(self._writer_task)
726 error_pathway |= bool(self._reader) or bool(self._writer)
729 # Try to flush the writer, if possible.
730 # This *may* cause an error and force us over into the error path.
731 if not error_pathway:
732 await self._bh_flush_writer()
733 except BaseException as err:
735 emsg = "Failed to flush the writer"
736 self.logger.error("%s: %s", emsg, exception_summary(err))
737 self.logger.debug("%s:\n%s\n", emsg, pretty_traceback())
740 # Cancel any still-running tasks (Won't raise):
741 if self._writer_task is not None and not self._writer_task.done():
742 self.logger.debug("Cancelling writer task.")
743 self._writer_task.cancel()
744 if self._reader_task is not None and not self._reader_task.done():
745 self.logger.debug("Cancelling reader task.")
746 self._reader_task.cancel()
748 # Close out the tasks entirely (Won't raise):
750 self.logger.debug("Waiting for tasks to complete ...")
751 await asyncio.wait(tasks)
753 # Lastly, close the stream itself. (*May raise*!):
754 await self._bh_close_stream(error_pathway)
755 self.logger.debug("Disconnected.")
758 async def _bh_flush_writer(self) -> None:
759 if not self._writer_task:
762 self.logger.debug("Draining the outbound queue ...")
763 await self._outgoing.join()
764 if self._writer is not None:
765 self.logger.debug("Flushing the StreamWriter ...")
766 await flush(self._writer)
769 async def _bh_close_stream(self, error_pathway: bool = False) -> None:
770 # NB: Closing the writer also implcitly closes the reader.
774 if not is_closing(self._writer):
775 self.logger.debug("Closing StreamWriter.")
778 self.logger.debug("Waiting for StreamWriter to close ...")
780 await wait_closed(self._writer)
781 except Exception: # pylint: disable=broad-except
782 # It's hard to tell if the Stream is already closed or
783 # not. Even if one of the tasks has failed, it may have
784 # failed for a higher-layered protocol reason. The
785 # stream could still be open and perfectly fine.
786 # I don't know how to discern its health here.
789 # We already know that *something* went wrong. Let's
790 # just trust that the Exception we already have is the
791 # better one to present to the user, even if we don't
792 # genuinely *know* the relationship between the two.
794 "Discarding Exception from wait_closed:\n%s\n",
798 # Oops, this is a brand-new error!
801 self.logger.debug("StreamWriter closed.")
804 async def _bh_loop_forever(self, async_fn: _TaskFN, name: str) -> None:
806 Run one of the bottom-half methods in a loop forever.
808 If the bottom half ever raises any exception, schedule a
809 disconnect that will terminate the entire loop.
811 :param async_fn: The bottom-half method to run in a loop.
812 :param name: The name of this task, used for logging.
817 except asyncio.CancelledError:
818 # We have been cancelled by _bh_disconnect, exit gracefully.
819 self.logger.debug("Task.%s: cancelled.", name)
821 except BaseException as err:
823 logging.INFO if isinstance(err, EOFError) else logging.ERROR,
825 name, exception_summary(err)
827 self.logger.debug("Task.%s: failure:\n%s\n",
828 name, pretty_traceback())
829 self._schedule_disconnect()
832 self.logger.debug("Task.%s: exiting.", name)
835 async def _bh_send_message(self) -> None:
837 Wait for an outgoing message, then send it.
839 Designed to be run in `_bh_loop_forever()`.
841 msg = await self._outgoing.get()
843 await self._send(msg)
845 self._outgoing.task_done()
848 async def _bh_recv_message(self) -> None:
850 Wait for an incoming message and call `_on_message` to route it.
852 Designed to be run in `_bh_loop_forever()`.
854 msg = await self._recv()
855 await self._on_message(msg)
857 # --------------------
858 # Section: Message I/O
859 # --------------------
863 def _cb_outbound(self, msg: T) -> T:
865 Callback: outbound message hook.
867 This is intended for subclasses to be able to add arbitrary
868 hooks to filter or manipulate outgoing messages. The base
869 implementation does nothing but log the message without any
870 manipulation of the message.
872 :param msg: raw outbound message
873 :return: final outbound message
875 self.logger.debug("--> %s", str(msg))
880 def _cb_inbound(self, msg: T) -> T:
882 Callback: inbound message hook.
884 This is intended for subclasses to be able to add arbitrary
885 hooks to filter or manipulate incoming messages. The base
886 implementation does nothing but log the message without any
887 manipulation of the message.
889 This method does not "handle" incoming messages; it is a filter.
890 The actual "endpoint" for incoming messages is `_on_message()`.
892 :param msg: raw inbound message
893 :return: processed inbound message
895 self.logger.debug("<-- %s", str(msg))
900 async def _readline(self) -> bytes:
902 Wait for a newline from the incoming reader.
904 This method is provided as a convenience for upper-layer
905 protocols, as many are line-based.
907 This method *may* return a sequence of bytes without a trailing
908 newline if EOF occurs, but *some* bytes were received. In this
909 case, the next call will raise `EOFError`. It is assumed that
910 the layer 5 protocol will decide if there is anything meaningful
911 to be done with a partial message.
913 :raise OSError: For stream-related errors.
915 If the reader stream is at EOF and there are no bytes to return.
916 :return: bytes, including the newline.
918 assert self._reader is not None
919 msg_bytes = await self._reader.readline()
922 if self._reader.at_eof():
929 async def _do_recv(self) -> T:
931 Abstract: Read from the stream and return a message.
933 Very low-level; intended to only be called by `_recv()`.
935 raise NotImplementedError
939 async def _recv(self) -> T:
941 Read an arbitrary protocol message.
944 This method is intended primarily for `_bh_recv_message()`
945 to use in an asynchronous task loop. Using it outside of
946 this loop will "steal" messages from the normal routing
947 mechanism. It is safe to use prior to `_establish_session()`,
948 but should not be used otherwise.
950 This method uses `_do_recv()` to retrieve the raw message, and
951 then transforms it using `_cb_inbound()`.
953 :return: A single (filtered, processed) protocol message.
955 message = await self._do_recv()
956 return self._cb_inbound(message)
960 def _do_send(self, msg: T) -> None:
962 Abstract: Write a message to the stream.
964 Very low-level; intended to only be called by `_send()`.
966 raise NotImplementedError
970 async def _send(self, msg: T) -> None:
972 Send an arbitrary protocol message.
974 This method will transform any outgoing messages according to
978 Like `_recv()`, this method is intended to be called by
979 the writer task loop that processes outgoing
980 messages. Calling it directly may circumvent logic
981 implemented by the caller meant to correlate outgoing and
984 :raise OSError: For problems with the underlying stream.
986 msg = self._cb_outbound(msg)
990 async def _on_message(self, msg: T) -> None:
992 Called to handle the receipt of a new message.
995 This is executed from within the reader loop, so be advised
996 that waiting on either the reader or writer task will lead
997 to deadlock. Additionally, any unhandled exceptions will
998 directly cause the loop to halt, so logic may be best-kept
999 to a minimum if at all possible.
1001 :param msg: The incoming message, already logged/filtered.
1003 # Nothing to do in the abstract case.