1
package authcache
2

3
import (
4
	"time"
5

6
	"github.com/miekg/dns"
7
	"github.com/semihalev/sdns/cache"
8
)
9

10
// NS represents a cache entry
11
type NS struct {
12
	Servers *AuthServers
13
	DSRR    []dns.RR
14
	TTL     time.Duration
15

16
	ut time.Time
17
}
18

19
// NSCache type
20
type NSCache struct {
21
	cache *cache.Cache
22

23
	now func() time.Time
24
}
25

26
// NewNSCache return new cache
27
func NewNSCache() *NSCache {
28
	n := &NSCache{
29 1
		cache: cache.New(defaultCap),
30 1
		now:   time.Now,
31
	}
32

33 1
	return n
34
}
35

36
// Get returns the entry for a key or an error
37
func (n *NSCache) Get(key uint64) (*NS, error) {
38 1
	el, ok := n.cache.Get(key)
39

40 1
	if !ok {
41 1
		return nil, cache.ErrCacheNotFound
42
	}
43

44 1
	ns := el.(*NS)
45

46 1
	elapsed := n.now().UTC().Sub(ns.ut)
47

48 1
	if elapsed >= ns.TTL {
49 1
		return nil, cache.ErrCacheExpired
50
	}
51

52 1
	return ns, nil
53
}
54

55
// Set sets a keys value to a NS
56
func (n *NSCache) Set(key uint64, dsRR []dns.RR, servers *AuthServers, ttl time.Duration) {
57 1
	if ttl > maximumTTL {
58 0
		ttl = maximumTTL
59 1
	} else if ttl < minimumTTL {
60 0
		ttl = minimumTTL
61
	}
62

63
	n.cache.Add(key, &NS{
64 1
		Servers: servers,
65 1
		DSRR:    dsRR,
66 1
		TTL:     ttl,
67 1
		ut:      n.now().UTC().Round(time.Second),
68 1
	})
69
}
70

71
// Remove remove a cache
72
func (n *NSCache) Remove(key uint64) {
73 1
	n.cache.Remove(key)
74
}
75

76
const (
77
	maximumTTL = 12 * time.Hour
78
	minimumTTL = 1 * time.Hour
79
	defaultCap = 1024 * 256
80
)

Read our documentation on viewing source code .

Loading