2019-09-15 16:58:08 +08:00
|
|
|
from libp2p.exceptions import ParseError
|
2019-09-05 23:24:17 +08:00
|
|
|
from libp2p.io.abc import ReadWriteCloser
|
2019-09-15 16:58:08 +08:00
|
|
|
from libp2p.io.exceptions import IOException
|
2019-08-17 00:19:37 +08:00
|
|
|
from libp2p.utils import encode_delim, read_delim
|
2019-08-07 18:02:30 +08:00
|
|
|
|
2019-09-15 16:58:08 +08:00
|
|
|
from .exceptions import MultiselectCommunicatorError
|
2018-11-29 02:51:50 +08:00
|
|
|
from .multiselect_communicator_interface import IMultiselectCommunicator
|
|
|
|
|
2019-01-10 02:38:56 +08:00
|
|
|
|
2019-09-05 23:24:17 +08:00
|
|
|
class MultiselectCommunicator(IMultiselectCommunicator):
|
|
|
|
read_writer: ReadWriteCloser
|
2019-08-15 23:31:26 +08:00
|
|
|
|
2019-09-05 23:24:17 +08:00
|
|
|
def __init__(self, read_writer: ReadWriteCloser) -> None:
|
|
|
|
self.read_writer = read_writer
|
2019-08-15 23:31:26 +08:00
|
|
|
|
|
|
|
async def write(self, msg_str: str) -> None:
|
2019-09-19 22:19:36 +08:00
|
|
|
"""
|
|
|
|
:raise MultiselectCommunicatorError: raised when failed to write to underlying reader
|
|
|
|
"""
|
2019-08-20 17:09:38 +08:00
|
|
|
msg_bytes = encode_delim(msg_str.encode())
|
2019-09-19 21:51:23 +08:00
|
|
|
try:
|
|
|
|
await self.read_writer.write(msg_bytes)
|
2019-09-23 16:01:22 +08:00
|
|
|
except IOException as error:
|
2019-09-19 21:51:23 +08:00
|
|
|
raise MultiselectCommunicatorError(
|
|
|
|
"fail to write to multiselect communicator"
|
2019-09-23 16:01:22 +08:00
|
|
|
) from error
|
2019-08-15 23:31:26 +08:00
|
|
|
|
|
|
|
async def read(self) -> str:
|
2019-09-19 22:19:36 +08:00
|
|
|
"""
|
|
|
|
:raise MultiselectCommunicatorError: raised when failed to read from underlying reader
|
|
|
|
"""
|
2019-09-15 16:58:08 +08:00
|
|
|
try:
|
|
|
|
data = await read_delim(self.read_writer)
|
|
|
|
# `IOException` includes `IncompleteReadError` and `StreamError`
|
2019-09-23 16:01:22 +08:00
|
|
|
except (ParseError, IOException) as error:
|
2019-09-15 16:58:08 +08:00
|
|
|
raise MultiselectCommunicatorError(
|
|
|
|
"fail to read from multiselect communicator"
|
2019-09-23 16:01:22 +08:00
|
|
|
) from error
|
2019-08-20 17:09:38 +08:00
|
|
|
return data.decode()
|