Skip to content

Commit

Permalink
fix(p2p): tcp fast fail to main queue
Browse files Browse the repository at this point in the history
  • Loading branch information
fumiama committed Aug 6, 2024
1 parent b71a054 commit 1c258fc
Showing 1 changed file with 15 additions and 9 deletions.
24 changes: 15 additions & 9 deletions gold/p2p/tcp/tcp.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,13 +100,14 @@ type subconn struct {

// Conn 伪装成无状态的有状态连接
type Conn struct {
addr *EndPoint
lstn *net.TCPListener
peers *ttl.Cache[string, *net.TCPConn]
recv chan *connrecv
cplk *sync.Mutex
sblk *sync.RWMutex
subs []*subconn
addr *EndPoint
lstn *net.TCPListener
peers *ttl.Cache[string, *net.TCPConn]
recv chan *connrecv
cplk *sync.Mutex
sblk *sync.RWMutex
subs []*subconn
suberr bool
}

func (conn *Conn) accept() {
Expand Down Expand Up @@ -440,8 +441,13 @@ func (conn *Conn) WriteToPeer(b []byte, ep p2p.EndPoint) (n int, err error) {
if len(b) >= 65536 {
return 0, errors.New("data size " + strconv.Itoa(len(b)) + " is too large")
}
if !conn.cplk.TryLock() {
return conn.writeToPeer(b, tcpep, true)
if !conn.suberr && !conn.cplk.TryLock() {
n, err = conn.writeToPeer(b, tcpep, true) // try sub write
if err == nil {
return
}
conn.suberr = true // fast fail
conn.cplk.Lock() // add to main queue
}
defer conn.cplk.Unlock()
return conn.writeToPeer(b, tcpep, false)
Expand Down

0 comments on commit 1c258fc

Please sign in to comment.