github.com/amazechain/amc@v0.1.3/internal/sync/deadlines.go (about) 1 package sync 2 3 import ( 4 "github.com/amazechain/amc/log" 5 "strings" 6 "time" 7 8 "github.com/libp2p/go-libp2p/core/network" 9 ) 10 11 var defaultReadDuration = ttfbTimeout 12 var defaultWriteDuration = respTimeout // RESP_TIMEOUT 13 14 // SetRPCStreamDeadlines sets read and write deadlines for libp2p-based connection streams. 15 func SetRPCStreamDeadlines(stream network.Stream) { 16 SetStreamReadDeadline(stream, defaultReadDuration) 17 SetStreamWriteDeadline(stream, defaultWriteDuration) 18 } 19 20 // SetStreamReadDeadline for reading from libp2p connection streams, deciding when to close 21 // a connection based on a particular duration. 22 // 23 // NOTE: libp2p uses the system clock time for determining the deadline so we use 24 // time.Now() instead of the synchronized roughtime.Now(). If the system 25 // time is corrupted (i.e. time does not advance), the node will experience 26 // issues being able to properly close streams, leading to unexpected failures and possible 27 // memory leaks. 28 func SetStreamReadDeadline(stream network.Stream, duration time.Duration) { 29 if err := stream.SetReadDeadline(time.Now().Add(duration)); err != nil && 30 !strings.Contains(err.Error(), "stream closed") { 31 log.Debug("Could not set stream deadline", "peer", stream.Conn().RemotePeer(), "protocol", stream.Protocol(), "direction", stream.Stat().Direction, "err", err) 32 } 33 } 34 35 // SetStreamWriteDeadline for writing to libp2p connection streams, deciding when to close 36 // a connection based on a particular duration. 37 // 38 // NOTE: libp2p uses the system clock time for determining the deadline so we use 39 // time.Now() instead of the synchronized roughtime.Now(). If the system 40 // time is corrupted (i.e. time does not advance), the node will experience 41 // issues being able to properly close streams, leading to unexpected failures and possible 42 // memory leaks. 43 func SetStreamWriteDeadline(stream network.Stream, duration time.Duration) { 44 if err := stream.SetWriteDeadline(time.Now().Add(duration)); err != nil { 45 log.Debug("Could not set stream deadline", "peer", stream.Conn().RemotePeer(), "protocol", stream.Protocol(), "direction", stream.Stat().Direction, "err", err) 46 } 47 }