mirror of
https://github.com/varun-r-mallya/py-libp2p.git
synced 2026-02-12 16:10:57 +00:00
Refine Mplex.close and SwarmConn.close
Ensure `close` cleans up things and cancel the service finally.
This commit is contained in:
@ -33,6 +33,7 @@ class IMuxedConn(ServiceAPI):
|
||||
async def close(self) -> None:
|
||||
"""close connection."""
|
||||
|
||||
@property
|
||||
@abstractmethod
|
||||
def is_closed(self) -> bool:
|
||||
"""
|
||||
|
||||
@ -91,7 +91,9 @@ class Mplex(IMuxedConn, Service):
|
||||
await self.secured_conn.close()
|
||||
# Blocked until `close` is finally set.
|
||||
await self.event_closed.wait()
|
||||
await self.manager.stop()
|
||||
|
||||
@property
|
||||
def is_closed(self) -> bool:
|
||||
"""
|
||||
check connection is fully closed.
|
||||
@ -213,10 +215,6 @@ class Mplex(IMuxedConn, Service):
|
||||
|
||||
return channel_id, flag, message
|
||||
|
||||
@property
|
||||
def _id(self) -> int:
|
||||
return 0 if self.is_initiator else 1
|
||||
|
||||
async def _handle_incoming_message(self) -> None:
|
||||
"""
|
||||
Read and handle a new incoming message.
|
||||
|
||||
@ -156,26 +156,22 @@ class MplexStream(IMuxedStream):
|
||||
if self.event_local_closed.is_set():
|
||||
return
|
||||
|
||||
print(f"!@# stream.close: {self.muxed_conn._id}: step=0")
|
||||
flag = (
|
||||
HeaderTags.CloseInitiator if self.is_initiator else HeaderTags.CloseReceiver
|
||||
)
|
||||
# TODO: Raise when `muxed_conn.send_message` fails and `Mplex` isn't shutdown.
|
||||
await self.muxed_conn.send_message(flag, None, self.stream_id)
|
||||
|
||||
print(f"!@# stream.close: {self.muxed_conn._id}: step=1")
|
||||
_is_remote_closed: bool
|
||||
async with self.close_lock:
|
||||
self.event_local_closed.set()
|
||||
_is_remote_closed = self.event_remote_closed.is_set()
|
||||
|
||||
print(f"!@# stream.close: {self.muxed_conn._id}: step=2")
|
||||
if _is_remote_closed:
|
||||
# Both sides are closed, we can safely remove the buffer from the dict.
|
||||
async with self.muxed_conn.streams_lock:
|
||||
if self.stream_id in self.muxed_conn.streams:
|
||||
del self.muxed_conn.streams[self.stream_id]
|
||||
print(f"!@# stream.close: {self.muxed_conn._id}: step=3")
|
||||
|
||||
async def reset(self) -> None:
|
||||
"""closes both ends of the stream tells this remote side to hang up."""
|
||||
|
||||
Reference in New Issue
Block a user