24
24
from libp2p .custom_types import (
25
25
TProtocol ,
26
26
)
27
- from libp2p .network .stream .exceptions import (
28
- StreamClosed ,
29
- )
30
27
from libp2p .peer .id import (
31
28
ID ,
32
29
)
42
39
from libp2p .tools .async_service import (
43
40
Service ,
44
41
)
45
- from libp2p .utils import (
46
- encode_varint_prefixed ,
47
- )
48
42
49
43
from .exceptions import (
50
44
NoPubsubAttached ,
@@ -249,14 +243,8 @@ async def publish(self, msg_forwarder: ID, pubsub_msg: rpc_pb2.Message) -> None:
249
243
if peer_id not in self .pubsub .peers :
250
244
continue
251
245
stream = self .pubsub .peers [peer_id ]
252
- # FIXME: We should add a `WriteMsg` similar to write delimited messages.
253
- # Ref: https://github.com/libp2p/go-libp2p-pubsub/blob/master/comm.go#L107
254
246
# TODO: Go use `sendRPC`, which possibly piggybacks gossip/control messages.
255
- try :
256
- await stream .write (encode_varint_prefixed (rpc_msg .SerializeToString ()))
257
- except StreamClosed :
258
- logger .debug ("Fail to publish message to %s: stream closed" , peer_id )
259
- self .pubsub ._handle_dead_peer (peer_id )
247
+ await self .pubsub .write_msg (stream , rpc_msg )
260
248
for topic in pubsub_msg .topicIDs :
261
249
self .time_since_last_publish [topic ] = int (time .time ())
262
250
@@ -705,8 +693,6 @@ async def handle_iwant(
705
693
706
694
packet .publish .extend (msgs_to_forward )
707
695
708
- # 2) Serialize that packet
709
- rpc_msg : bytes = packet .SerializeToString ()
710
696
if self .pubsub is None :
711
697
raise NoPubsubAttached
712
698
@@ -720,14 +706,7 @@ async def handle_iwant(
720
706
peer_stream = self .pubsub .peers [sender_peer_id ]
721
707
722
708
# 4) And write the packet to the stream
723
- try :
724
- await peer_stream .write (encode_varint_prefixed (rpc_msg ))
725
- except StreamClosed :
726
- logger .debug (
727
- "Fail to responed to iwant request from %s: stream closed" ,
728
- sender_peer_id ,
729
- )
730
- self .pubsub ._handle_dead_peer (sender_peer_id )
709
+ await self .pubsub .write_msg (peer_stream , packet )
731
710
732
711
async def handle_graft (
733
712
self , graft_msg : rpc_pb2 .ControlGraft , sender_peer_id : ID
@@ -826,8 +805,6 @@ async def emit_control_message(
826
805
packet : rpc_pb2 .RPC = rpc_pb2 .RPC ()
827
806
packet .control .CopyFrom (control_msg )
828
807
829
- rpc_msg : bytes = packet .SerializeToString ()
830
-
831
808
# Get stream for peer from pubsub
832
809
if to_peer not in self .pubsub .peers :
833
810
logger .debug (
@@ -837,8 +814,4 @@ async def emit_control_message(
837
814
peer_stream = self .pubsub .peers [to_peer ]
838
815
839
816
# Write rpc to stream
840
- try :
841
- await peer_stream .write (encode_varint_prefixed (rpc_msg ))
842
- except StreamClosed :
843
- logger .debug ("Fail to emit control message to %s: stream closed" , to_peer )
844
- self .pubsub ._handle_dead_peer (to_peer )
817
+ await self .pubsub .write_msg (peer_stream , packet )
0 commit comments