Skip to content

Commit

Permalink
feat: cache router info
Browse files Browse the repository at this point in the history
Unfortunately, constructing a router is _not_ cheap. Cache it so we don't have
to re-compute it every time we get a query.
  • Loading branch information
Stebalien committed Apr 8, 2020
1 parent c7a9b73 commit 9461bab
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
38 changes: 37 additions & 1 deletion dht_filters.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,13 @@ package dht
import (
"bytes"
"net"
"sync"
"time"

"github.com/libp2p/go-libp2p-core/network"
"github.com/libp2p/go-libp2p-core/peer"

"github.com/google/gopacket/routing"
netroute "github.com/libp2p/go-netroute"

ma "github.com/multiformats/go-multiaddr"
Expand Down Expand Up @@ -64,10 +68,42 @@ func PrivateQueryFilter(dht *IpfsDHT, ai peer.AddrInfo) bool {

var _ QueryFilterFunc = PrivateQueryFilter

// We call this very frequently but routes can technically change at runtime.
// Cache it for two minutes.
const routerCacheTime = 2 * time.Minute

var routerCache struct {
sync.RWMutex
router routing.Router
expires time.Time
}

func getCachedRouter() routing.Router {
routerCache.RLock()
router := routerCache.router
expires := routerCache.expires
routerCache.RUnlock()

if time.Now().Before(expires) {
return router
}

routerCache.Lock()
defer routerCache.Unlock()

now := time.Now()
if now.Before(routerCache.expires) {
return router
}
routerCache.router, _ = netroute.New()
routerCache.expires = now.Add(routerCacheTime)
return router
}

// PrivateRoutingTableFilter allows a peer to be added to the routing table if the connections to that peer indicate
// that it is on a private network
func PrivateRoutingTableFilter(dht *IpfsDHT, conns []network.Conn) bool {
router, _ := netroute.New()
router := getCachedRouter()
myAdvertisedIPs := make([]net.IP, 0)
for _, a := range dht.Host().Addrs() {
if manet.IsPublicAddr(a) && !isRelayAddr(a) {
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ go 1.14

require (
github.com/gogo/protobuf v1.3.1
github.com/google/gopacket v1.1.17
github.com/google/uuid v1.1.1
github.com/hashicorp/go-multierror v1.1.0
github.com/hashicorp/golang-lru v0.5.4
Expand All @@ -24,7 +25,6 @@ require (
github.com/libp2p/go-libp2p-testing v0.1.1
github.com/libp2p/go-msgio v0.0.4
github.com/libp2p/go-netroute v0.1.2
github.com/mr-tron/base58 v1.1.3
github.com/multiformats/go-base32 v0.0.3
github.com/multiformats/go-multiaddr v0.2.1
github.com/multiformats/go-multiaddr-dns v0.2.0
Expand Down

0 comments on commit 9461bab

Please sign in to comment.