-
Notifications
You must be signed in to change notification settings - Fork 18
/
dnscache.go
106 lines (83 loc) · 1.77 KB
/
dnscache.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
/*
Package dnscache contains a simple in-process cache for DNS lookups
*/
package dnscache
import (
"context"
"net"
"sync"
"time"
"github.com/vmihailenco/go-tinylfu"
)
const (
defaultCacheSize = 64
defaultTTL = 5 * time.Second
)
func defaultLookupFunc(ctx context.Context, r *net.Resolver, host string) ([]net.IP, error) {
addrs, err := r.LookupIPAddr(ctx, host)
if err != nil {
return nil, err
}
ips := make([]net.IP, len(addrs))
for i, ia := range addrs {
ips[i] = ia.IP
}
return ips, nil
}
type Resolver struct {
config Config
// mutable state
mu sync.Mutex
cache *tinylfu.T
}
type Config struct {
CacheSize int
TTL time.Duration
// Resolver optionally allows specifying a custom resolver
Resolver *net.Resolver
lookupFunc func(ctx context.Context, r *net.Resolver, host string) ([]net.IP, error)
}
func New(c Config) *Resolver {
if c.CacheSize == 0 {
c.CacheSize = defaultCacheSize
}
if c.TTL == 0 {
c.TTL = defaultTTL
}
if c.Resolver == nil {
c.Resolver = net.DefaultResolver
}
if c.lookupFunc == nil {
c.lookupFunc = defaultLookupFunc
}
return &Resolver{
config: c,
cache: tinylfu.New(c.CacheSize, 100000),
}
}
func (r *Resolver) Resolve(ctx context.Context, addr string) ([]net.IP, error) {
v, ok := r.cacheGet(addr)
if ok {
return v.([]net.IP), nil
}
ips, err := r.config.lookupFunc(ctx, r.config.Resolver, addr)
if err != nil {
return nil, err
}
r.cacheSet(&tinylfu.Item{
Key: addr,
Value: ips,
ExpireAt: time.Now().Add(r.config.TTL),
})
return ips, nil
}
func (r *Resolver) cacheSet(item *tinylfu.Item) {
r.mu.Lock()
defer r.mu.Unlock()
r.cache.Set(item)
}
func (r *Resolver) cacheGet(addr string) (interface{}, bool) {
r.mu.Lock()
defer r.mu.Unlock()
return r.cache.Get(addr)
}