Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

examples: fix flaky multipro TestMain #2289

Merged
merged 2 commits into from
May 15, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
}