/
error_cache.go
125 lines (99 loc) · 2.26 KB
/
error_cache.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package main
import (
"strings"
"sync"
"time"
"github.com/semihalev/log"
)
// ErrorCache type
type ErrorCache struct {
mu sync.RWMutex
TTL uint32
Backend map[string]time.Time
Maxcount int
}
// NewErrorCache return new cache
func NewErrorCache(maxcount int, ttl uint32) *ErrorCache {
c := &ErrorCache{
Backend: make(map[string]time.Time, maxcount),
Maxcount: maxcount,
TTL: ttl,
}
go c.run()
return c
}
// Get returns the entry for a key or an error
func (c *ErrorCache) Get(key string) error {
key = strings.ToLower(key)
c.mu.RLock()
t, ok := c.Backend[key]
c.mu.RUnlock()
if !ok {
log.Debug("Error cache miss", "key", key)
return KeyNotFound{key}
}
//Truncate time to the second, so that subsecond queries won't keep moving
//forward the last update time without touching the TTL
now := WallClock.Now().Truncate(time.Second)
elapsed := uint32(now.Sub(t).Seconds())
if elapsed > c.TTL {
log.Debug("Error cache expired", "key", key)
c.Remove(key)
return KeyExpired{key}
}
return nil
}
// Set sets a keys value to a error cache
func (c *ErrorCache) Set(key string) error {
key = strings.ToLower(key)
if c.Full() && !c.Exists(key) {
return CacheIsFull{}
}
c.mu.Lock()
c.Backend[key] = WallClock.Now().Truncate(time.Second)
c.mu.Unlock()
return nil
}
// Remove removes an entry from the cache
func (c *ErrorCache) Remove(key string) {
key = strings.ToLower(key)
c.mu.Lock()
delete(c.Backend, key)
c.mu.Unlock()
}
// Exists returns whether or not a key exists in the cache
func (c *ErrorCache) Exists(key string) bool {
key = strings.ToLower(key)
c.mu.RLock()
_, ok := c.Backend[key]
c.mu.RUnlock()
return ok
}
// Length returns the caches length
func (c *ErrorCache) Length() int {
c.mu.RLock()
defer c.mu.RUnlock()
return len(c.Backend)
}
// Full returns whether or not the cache is full
func (c *ErrorCache) Full() bool {
if c.Maxcount == 0 {
return false
}
return c.Length() >= c.Maxcount
}
func (c *ErrorCache) run() {
ticker := time.NewTicker(time.Hour)
for range ticker.C {
c.mu.Lock()
for key, t := range c.Backend {
now := WallClock.Now().Truncate(time.Second)
elapsed := uint32(now.Sub(t).Seconds())
if elapsed > c.TTL {
delete(c.Backend, key)
break
}
}
c.mu.Unlock()
}
}