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

cache relayAddrs for a short period of time #608

Merged
merged 1 commit into from
Apr 22, 2019
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
17 changes: 15 additions & 2 deletions p2p/host/relay/autorelay.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ type AutoRelay struct {
mx sync.Mutex
relays map[peer.ID]struct{}
status autonat.NATStatus

cachedAddrs []ma.Multiaddr
cachedAddrsExpiry time.Time
}

func NewAutoRelay(ctx context.Context, bhost *basic.BasicHost, discover discovery.Discoverer, router routing.PeerRouting) *AutoRelay {
Expand Down Expand Up @@ -108,6 +111,9 @@ func (ar *AutoRelay) background(ctx context.Context) {
}

if push {
ar.mx.Lock()
ar.cachedAddrs = nil
ar.mx.Unlock()
push = false
ar.host.PushIdentify()
}
Expand Down Expand Up @@ -250,16 +256,20 @@ func (ar *AutoRelay) selectRelays(ctx context.Context, pis []pstore.PeerInfo) []
// through which we can be dialed.
func (ar *AutoRelay) relayAddrs(addrs []ma.Multiaddr) []ma.Multiaddr {
ar.mx.Lock()
defer ar.mx.Unlock()

if ar.status != autonat.NATStatusPrivate {
ar.mx.Unlock()
return addrs
}

if ar.cachedAddrs != nil && time.Now().Before(ar.cachedAddrsExpiry) {
return ar.cachedAddrs
}

relays := make([]peer.ID, 0, len(ar.relays))
for p := range ar.relays {
relays = append(relays, p)
}
ar.mx.Unlock()

raddrs := make([]ma.Multiaddr, 0, 4*len(relays)+2)

Expand All @@ -285,6 +295,9 @@ func (ar *AutoRelay) relayAddrs(addrs []ma.Multiaddr) []ma.Multiaddr {
}
}

ar.cachedAddrs = raddrs
ar.cachedAddrsExpiry = time.Now().Add(30 * time.Second)

return raddrs
}

Expand Down