Repository navigation
Expand file tree
/
Copy pathcache.go
More file actions
81 lines (72 loc) · 1.42 KB
/
Copy pathcache.go
File metadata and controls
81 lines (72 loc) · 1.42 KB
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
package pgkit
import (
"sync"
"time"
"golang.org/x/sync/singleflight"
)
type columnEntry struct {
cols []string
resolved time.Time
}
type columnCache struct {
mu sync.RWMutex
entries map[string]columnEntry
ttl time.Duration
max int
group singleflight.Group
now func() time.Time
}
func newColumnCache(ttl time.Duration, max int) *columnCache {
return &columnCache{
entries: make(map[string]columnEntry),
ttl: ttl,
max: max,
now: time.Now,
}
}
func (c *columnCache) get(key string) ([]string, bool) {
if c.ttl < 0 {
return nil, false
}
c.mu.RLock()
e, ok := c.entries[key]
c.mu.RUnlock()
if !ok {
return nil, false
}
if c.ttl > 0 && c.now().Sub(e.resolved) > c.ttl {
return nil, false
}
return e.cols, true
}
func (c *columnCache) put(key string, cols []string) {
if c.ttl < 0 {
return
}
c.mu.Lock()
defer c.mu.Unlock()
if c.max > 0 {
for len(c.entries) >= c.max {
c.evictOldestLocked()
}
}
c.entries[key] = columnEntry{cols: cols, resolved: c.now()}
}
func (c *columnCache) evictOldestLocked() {
var oldestKey string
var oldestTime time.Time
first := true
for k, e := range c.entries {
if first || e.resolved.Before(oldestTime) {
oldestKey, oldestTime, first = k, e.resolved, false
}
}
if !first {
delete(c.entries, oldestKey)
}
}
func (c *columnCache) invalidate() {
c.mu.Lock()
c.entries = make(map[string]columnEntry)
c.mu.Unlock()
}