Skip to content

Commit

Permalink
examples: fix flaky multipro TestMain (#2289)
Browse files Browse the repository at this point in the history
* examples: fix flaky multipro TestMain

* better to synchronise
  • Loading branch information
sukunrt authored May 15, 2023
1 parent 64be725 commit 301a197
Showing 1 changed file with 12 additions and 4 deletions.
16 changes: 12 additions & 4 deletions examples/multipro/ping.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"io"
"log"
"sync"

"github.com/libp2p/go-libp2p/core/host"
"github.com/libp2p/go-libp2p/core/network"
Expand All @@ -19,8 +20,9 @@ const pingResponse = "/ping/pingresp/0.0.1"

// PingProtocol type
type PingProtocol struct {
node *Node // local host
requests map[string]*p2p.PingRequest // used to access request data from response handlers
node *Node // local host
mu sync.Mutex
requests map[string]*p2p.PingRequest // used to access request data from response handlers. Protected by mu
done chan bool // only for demo purposes to stop main from terminating
}

Expand Down Expand Up @@ -111,14 +113,17 @@ func (p *PingProtocol) onPingResponse(s network.Stream) {
}

// locate request data and remove it if found
p.mu.Lock()
_, ok := p.requests[data.MessageData.Id]
if ok {
// remove request from map as we have processed it here
delete(p.requests, data.MessageData.Id)
} else {
log.Println("Failed to locate request data boject for response")
p.mu.Unlock()
return
}
p.mu.Unlock()

log.Printf("%s: Received ping response from %s. Message id:%s. Message: %s.", s.Conn().LocalPeer(), s.Conn().RemotePeer(), data.MessageData.Id, data.Message)
p.done <- true
Expand All @@ -141,13 +146,16 @@ func (p *PingProtocol) Ping(host host.Host) bool {
// add the signature to the message
req.MessageData.Sign = signature

// store ref request so response handler has access to it
p.mu.Lock()
p.requests[req.MessageData.Id] = req
p.mu.Unlock()

ok := p.node.sendProtoMessage(host.ID(), pingRequest, req)
if !ok {
return false
}

// store ref request so response handler has access to it
p.requests[req.MessageData.Id] = req
log.Printf("%s: Ping to: %s was sent. Message Id: %s, Message: %s", p.node.ID(), host.ID(), req.MessageData.Id, req.Message)
return true
}

0 comments on commit 301a197

Please sign in to comment.