Skip to content

Commit 9461bab

Browse files
committed
feat: cache router info
Unfortunately, constructing a router is _not_ cheap. Cache it so we don't have to re-compute it every time we get a query.
1 parent c7a9b73 commit 9461bab

File tree

2 files changed

+38
-2
lines changed

2 files changed

+38
-2
lines changed

dht_filters.go

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,13 @@ package dht
33
import (
44
"bytes"
55
"net"
6+
"sync"
7+
"time"
68

79
"github.com/libp2p/go-libp2p-core/network"
810
"github.com/libp2p/go-libp2p-core/peer"
11+
12+
"github.com/google/gopacket/routing"
913
netroute "github.com/libp2p/go-netroute"
1014

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

6569
var _ QueryFilterFunc = PrivateQueryFilter
6670

71+
// We call this very frequently but routes can technically change at runtime.
72+
// Cache it for two minutes.
73+
const routerCacheTime = 2 * time.Minute
74+
75+
var routerCache struct {
76+
sync.RWMutex
77+
router routing.Router
78+
expires time.Time
79+
}
80+
81+
func getCachedRouter() routing.Router {
82+
routerCache.RLock()
83+
router := routerCache.router
84+
expires := routerCache.expires
85+
routerCache.RUnlock()
86+
87+
if time.Now().Before(expires) {
88+
return router
89+
}
90+
91+
routerCache.Lock()
92+
defer routerCache.Unlock()
93+
94+
now := time.Now()
95+
if now.Before(routerCache.expires) {
96+
return router
97+
}
98+
routerCache.router, _ = netroute.New()
99+
routerCache.expires = now.Add(routerCacheTime)
100+
return router
101+
}
102+
67103
// PrivateRoutingTableFilter allows a peer to be added to the routing table if the connections to that peer indicate
68104
// that it is on a private network
69105
func PrivateRoutingTableFilter(dht *IpfsDHT, conns []network.Conn) bool {
70-
router, _ := netroute.New()
106+
router := getCachedRouter()
71107
myAdvertisedIPs := make([]net.IP, 0)
72108
for _, a := range dht.Host().Addrs() {
73109
if manet.IsPublicAddr(a) && !isRelayAddr(a) {

go.mod

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ go 1.14
44

55
require (
66
github.com/gogo/protobuf v1.3.1
7+
github.com/google/gopacket v1.1.17
78
github.com/google/uuid v1.1.1
89
github.com/hashicorp/go-multierror v1.1.0
910
github.com/hashicorp/golang-lru v0.5.4
@@ -24,7 +25,6 @@ require (
2425
github.com/libp2p/go-libp2p-testing v0.1.1
2526
github.com/libp2p/go-msgio v0.0.4
2627
github.com/libp2p/go-netroute v0.1.2
27-
github.com/mr-tron/base58 v1.1.3
2828
github.com/multiformats/go-base32 v0.0.3
2929
github.com/multiformats/go-multiaddr v0.2.1
3030
github.com/multiformats/go-multiaddr-dns v0.2.0

0 commit comments

Comments
 (0)