py-libp2p/libp2p/stream_muxer/mplex/mplex.py

222 lines
7.7 KiB
Python
Raw Normal View History

import asyncio
from typing import Dict, Optional, Tuple
2019-08-02 18:28:04 +08:00
2019-08-05 10:35:56 +08:00
from libp2p.network.typing import GenericProtocolHandlerFn
from libp2p.peer.id import ID
2019-08-05 11:22:44 +08:00
from libp2p.security.secure_conn_interface import ISecureConn
from libp2p.stream_muxer.abc import IMuxedConn, IMuxedStream
from libp2p.typing import TProtocol
from libp2p.utils import (
decode_uvarint_from_stream,
encode_uvarint,
read_varint_prefixed_bytes,
)
2019-01-10 02:38:56 +08:00
2019-08-02 17:14:43 +08:00
from .constants import HeaderTags
2019-08-28 21:43:34 +08:00
from .datastructures import StreamID
from .exceptions import StreamNotFound
2019-08-03 13:36:19 +08:00
from .mplex_stream import MplexStream
2018-11-01 05:31:00 +08:00
MPLEX_PROTOCOL_ID = TProtocol("/mplex/6.7.0")
2019-08-02 17:53:51 +08:00
2018-11-21 09:28:41 +08:00
class Mplex(IMuxedConn):
2018-11-01 05:31:00 +08:00
"""
reference: https://github.com/libp2p/go-mplex/blob/master/multiplex.go
"""
secured_conn: ISecureConn
peer_id: ID
# TODO: `dataIn` in go implementation. Should be size of 8.
# TODO: Also, `dataIn` is closed indicating EOF in Go. We don't have similar strategies
# to let the `MplexStream`s know that EOF arrived (#235).
2019-08-28 21:43:34 +08:00
buffers: Dict[StreamID, "asyncio.Queue[bytes]"]
stream_queue: "asyncio.Queue[StreamID]"
next_channel_id: int
2019-08-02 17:53:51 +08:00
# TODO: `generic_protocol_handler` should be refactored out of mplex conn.
2019-08-02 17:53:51 +08:00
def __init__(
self,
secured_conn: ISecureConn,
generic_protocol_handler: GenericProtocolHandlerFn,
peer_id: ID,
2019-08-02 17:53:51 +08:00
) -> None:
2018-11-01 05:31:00 +08:00
"""
create a new muxed connection
:param secured_conn: an instance of ``ISecureConn``
:param generic_protocol_handler: generic protocol handler
for new muxed streams
[WIP] PubSub and FloodSub development (#133) * Add notifee interface * Add notify function to network interface * Implement notify feature * Add tests for notify * Make notifee functions all async * Fix linting issue * Fix linting issue * Scaffold pubsub router interface * Scaffold pubsub directory * Store peer_id in muxed connection * Implement pubsub notifee * Remove outdated files * Implement pubsub first attempt * Prepare pubsub for floodsub * Add mplex conn to net stream and add conn in notify tests * Implement floodsub * Use NetStream in generic protocol handler * Debugging async issues * Modify test to perform proper assert. Test passes * Remove callbacks. Reduce sleep time * Add simple three node test * Clean up code. Add message classes * Add test for two topics * Add conn to net stream and conn tests * Refactor test setup to remove duplicate code * Fix linting issues * Fix linting issue * Fix linting issue * Fix outstanding unrelated lint issue in multiselect_client * Add connect function * Remove debug prints * Remove debug prints from floodsub * Use MessageTalk in place of direct message breakdown * Remove extra prints * Remove outdated function * Add message to queues for all topics in message * Debugging * Add message self delivery * Increase read timeout to 5 to get pubsub tests passing * Refactor testing helper func. Add tests * Add tests and increase timeout to get tests passing * Add dummy account demo scaffolding * Attempt to use threads. Test fails * Implement basic dummy node tests using threads * Add generic testing function * Add simple seven node tree test * Add more complex seven node tree tests * Add five node ring tests * Remove unnecessary get_message_type func * Add documentation to classes * Add message id to messages * Add documentation to test helper func * Add docs to dummy account node helper func * Add more docs to dummy account node test helper func * fixed linting errors in floodsub * small notify bugfix * move pubsub into libp2p * fixed pubsub linting * fixing pubsub test failures * linting
2019-03-24 01:52:02 +08:00
:param peer_id: peer_id of peer the connection is to
2018-11-01 05:31:00 +08:00
"""
self.secured_conn = secured_conn
2018-11-26 00:05:56 +08:00
2019-08-28 21:43:34 +08:00
self.next_channel_id = 0
# Store generic protocol handler
self.generic_protocol_handler = generic_protocol_handler
[WIP] PubSub and FloodSub development (#133) * Add notifee interface * Add notify function to network interface * Implement notify feature * Add tests for notify * Make notifee functions all async * Fix linting issue * Fix linting issue * Scaffold pubsub router interface * Scaffold pubsub directory * Store peer_id in muxed connection * Implement pubsub notifee * Remove outdated files * Implement pubsub first attempt * Prepare pubsub for floodsub * Add mplex conn to net stream and add conn in notify tests * Implement floodsub * Use NetStream in generic protocol handler * Debugging async issues * Modify test to perform proper assert. Test passes * Remove callbacks. Reduce sleep time * Add simple three node test * Clean up code. Add message classes * Add test for two topics * Add conn to net stream and conn tests * Refactor test setup to remove duplicate code * Fix linting issues * Fix linting issue * Fix linting issue * Fix outstanding unrelated lint issue in multiselect_client * Add connect function * Remove debug prints * Remove debug prints from floodsub * Use MessageTalk in place of direct message breakdown * Remove extra prints * Remove outdated function * Add message to queues for all topics in message * Debugging * Add message self delivery * Increase read timeout to 5 to get pubsub tests passing * Refactor testing helper func. Add tests * Add tests and increase timeout to get tests passing * Add dummy account demo scaffolding * Attempt to use threads. Test fails * Implement basic dummy node tests using threads * Add generic testing function * Add simple seven node tree test * Add more complex seven node tree tests * Add five node ring tests * Remove unnecessary get_message_type func * Add documentation to classes * Add message id to messages * Add documentation to test helper func * Add docs to dummy account node helper func * Add more docs to dummy account node test helper func * fixed linting errors in floodsub * small notify bugfix * move pubsub into libp2p * fixed pubsub linting * fixing pubsub test failures * linting
2019-03-24 01:52:02 +08:00
# Set peer_id
self.peer_id = peer_id
2018-11-26 00:05:56 +08:00
# Mapping from stream ID -> buffer of messages for that stream
self.buffers = {}
2018-11-26 00:05:56 +08:00
2018-11-13 00:00:43 +08:00
self.stream_queue = asyncio.Queue()
# Kick off reading
asyncio.ensure_future(self.handle_incoming())
2018-11-01 05:31:00 +08:00
@property
def initiator(self) -> bool:
return self.secured_conn.initiator
async def close(self) -> None:
2018-11-01 05:31:00 +08:00
"""
close the stream muxer and underlying secured connection
2018-11-01 05:31:00 +08:00
"""
await self.secured_conn.close()
2018-11-01 05:31:00 +08:00
2019-08-02 17:53:51 +08:00
def is_closed(self) -> bool:
2018-11-01 05:31:00 +08:00
"""
check connection is fully closed
:return: true if successful
"""
2019-08-02 17:53:51 +08:00
raise NotImplementedError()
2018-11-01 05:31:00 +08:00
2019-08-28 21:43:34 +08:00
async def read_buffer(self, stream_id: StreamID) -> bytes:
"""
Read a message from buffer of the stream specified by `stream_id`,
check secured connection for new messages.
2019-08-16 10:21:51 +08:00
`StreamNotFound` is raised when stream `stream_id` is not found in `Mplex`.
:param stream_id: stream id of stream to read from
:return: message read
"""
if stream_id not in self.buffers:
raise StreamNotFound(f"stream {stream_id} is not found")
return await self.buffers[stream_id].get()
2018-11-13 00:00:43 +08:00
2019-08-28 21:43:34 +08:00
async def read_buffer_nonblocking(self, stream_id: StreamID) -> Optional[bytes]:
"""
Read a message from buffer of the stream specified by `stream_id`, non-blockingly.
2019-08-16 10:21:51 +08:00
`StreamNotFound` is raised when stream `stream_id` is not found in `Mplex`.
"""
if stream_id not in self.buffers:
raise StreamNotFound(f"stream {stream_id} is not found")
if self.buffers[stream_id].empty():
return None
return await self.buffers[stream_id].get()
2019-08-28 21:43:34 +08:00
def _get_next_channel_id(self) -> int:
"""
Get next available stream id
:return: next available stream id for the connection
"""
2019-08-28 21:43:34 +08:00
next_id = self.next_channel_id
self.next_channel_id += 1
return next_id
async def open_stream(self) -> IMuxedStream:
2018-11-01 05:31:00 +08:00
"""
creates a new muxed_stream
:return: a new ``MplexStream``
2018-11-01 05:31:00 +08:00
"""
2019-08-28 21:43:34 +08:00
channel_id = self._get_next_channel_id()
stream_id = StreamID(channel_id=channel_id, is_initiator=True)
name = str(channel_id)
stream = MplexStream(name, stream_id, self)
self.buffers[stream_id] = asyncio.Queue()
2019-08-28 21:43:34 +08:00
# Default stream name is the `channel_id`
await self.send_message(HeaderTags.NewStream, name.encode(), stream_id)
return stream
async def accept_stream(self, name: str) -> None:
2018-11-01 05:31:00 +08:00
"""
accepts a muxed stream opened by the other end
"""
2018-11-13 00:00:43 +08:00
stream_id = await self.stream_queue.get()
2019-08-28 21:43:34 +08:00
stream = MplexStream(name, stream_id, self)
asyncio.ensure_future(self.generic_protocol_handler(stream))
2019-08-28 21:43:34 +08:00
async def send_message(
self, flag: HeaderTags, data: bytes, stream_id: StreamID
) -> int:
"""
sends a message over the connection
:param header: header to use
:param data: data to send in the message
2018-11-12 06:38:11 +08:00
:param stream_id: stream the message is in
"""
2018-11-12 06:38:11 +08:00
# << by 3, then or with flag
2019-08-28 21:43:34 +08:00
header = (stream_id.channel_id << 3) | flag.value
2018-11-12 06:38:11 +08:00
header = encode_uvarint(header)
2018-11-19 00:22:17 +08:00
if data is None:
data_length = encode_uvarint(0)
_bytes = header + data_length
else:
data_length = encode_uvarint(len(data))
_bytes = header + data_length + data
2018-11-13 00:00:43 +08:00
return await self.write_to_stream(_bytes)
2018-11-12 06:38:11 +08:00
2019-08-02 17:53:51 +08:00
async def write_to_stream(self, _bytes: bytearray) -> int:
"""
writes a byte array to a secured connection
:param _bytes: byte array to write
:return: length written
"""
await self.secured_conn.write(_bytes)
2018-11-12 06:48:31 +08:00
return len(_bytes)
2019-08-02 17:53:51 +08:00
async def handle_incoming(self) -> None:
"""
Read a message off of the secured connection and add it to the corresponding message buffer
"""
# TODO Deal with other types of messages using flag (currently _)
2018-11-13 00:00:43 +08:00
while True:
2019-08-28 21:43:34 +08:00
channel_id, flag, message = await self.read_message()
2018-11-13 00:00:43 +08:00
2019-08-28 21:43:34 +08:00
if channel_id is not None and flag is not None and message is not None:
stream_id = StreamID(channel_id=channel_id, is_initiator=bool(flag & 1))
if stream_id not in self.buffers:
self.buffers[stream_id] = asyncio.Queue()
await self.stream_queue.put(stream_id)
2018-11-13 00:00:43 +08:00
# TODO: Handle more tags, and refactor `HeaderTags`
2019-08-02 17:14:43 +08:00
if flag == HeaderTags.NewStream.value:
# new stream detected on connection
await self.accept_stream(message.decode())
elif flag in (
HeaderTags.MessageInitiator.value,
HeaderTags.MessageReceiver.value,
):
await self.buffers[stream_id].put(message)
# Force context switch
await asyncio.sleep(0)
2019-08-02 17:53:51 +08:00
async def read_message(self) -> Tuple[int, int, bytes]:
"""
Read a single message off of the secured connection
:return: stream_id, flag, message contents
"""
# FIXME: No timeout is used in Go implementation.
# Timeout is set to a relatively small value to alleviate wait time to exit
# loop in handle_incoming
header = await decode_uvarint_from_stream(self.secured_conn)
# TODO: Handle the case of EOF and other exceptions?
try:
message = await asyncio.wait_for(
read_varint_prefixed_bytes(self.secured_conn), timeout=5
)
except asyncio.TimeoutError:
# TODO: Investigate what we should do if time is out.
return None, None, None
flag = header & 0x07
2019-08-28 21:43:34 +08:00
channel_id = header >> 3
2019-08-28 21:43:34 +08:00
return channel_id, flag, message