/
cache.go
167 lines (144 loc) · 3.73 KB
/
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
package garnish
import (
"strconv"
"strings"
"sync"
"time"
)
var (
PurgeHitResponse = Empty(200)
PurgeMissResponse = Empty(204)
NotModifiedResponse = Empty(304)
hitHeaderValue = []string{"hit"}
zero time.Time
)
type Serializer interface {
Write(b []byte)
WriteInt(i int)
WriteByte(b byte)
WriteString(s string)
}
type Deserializer interface {
ReadInt() int
ReadByte() byte
ReadBytes() []byte
CloneBytes() []byte
ReadString() string
}
type CacheStorage interface {
Get(primary, secondary string) CachedResponse
Set(primary string, secondary string, response CachedResponse)
Delete(primary, secondary string) bool
DeleteAll(primary string) bool
Save(path string, count int, cutoff time.Duration) error
Load(path string) error
SetSize(size int)
GetSize() int
Stop()
}
type CachedResponse interface {
Response
Size() int
Expire(at time.Time)
Expires() time.Time
Serialize(serializer Serializer) error
Deserialize(deserializer Deserializer) error
}
// A function that generates cache keys from a request
type CacheKeyLookup func(req *Request) (string, string)
// A function that purges the cache
// Returning a nil response means that the request will be forward onwards
type PurgeHandler func(req *Request, lookup CacheKeyLookup, cache CacheStorage) Response
func DefaultCacheKeyLookup(req *Request) (string, string) {
return req.URL.Path, req.URL.RawQuery
}
type Cache struct {
sync.Mutex
downloads map[string]time.Time
Storage CacheStorage
Saint bool
GraceTTL time.Duration
PurgeHandler PurgeHandler
}
func NewCache() *Cache {
return &Cache{
downloads: make(map[string]time.Time),
}
}
func (c *Cache) Set(primary string, secondary string, config *RouteCache, res Response) {
ttl := c.ttl(config, res)
if ttl == 0 {
return
}
cacheable := res.ToCacheable(time.Now().Add(ttl))
c.Storage.Set(primary, secondary, cacheable)
}
func (c *Cache) ttl(config *RouteCache, res Response) time.Duration {
status := res.Status()
if status >= 200 && status <= 400 && config.TTL > 0 {
return config.TTL
}
cc := res.Header()["Cache-Control"]
if len(cc) == 0 {
return 0
}
for _, value := range cc {
if strings.Contains(value, "private") {
break
}
if index := strings.Index(value, "max-age="); index > -1 {
if seconds, err := strconv.Atoi(value[index+8:]); err == nil {
return time.Second * time.Duration(seconds)
} else {
Log.Warnf("invalid cache control header %q", value)
break
}
}
}
return 0
}
// A clone is critical since the original request is likely to be closed
// before we're finishing with Grace and we might end up with a request
// that contains data from multiple sources.
func (c *Cache) Grace(primary string, secondary string, req *Request, next Handler) {
key := primary + secondary
if c.reserveDownload(key) == false {
return
}
go c.grace(key, primary, secondary, req.Clone(), next)
}
func (c *Cache) grace(key string, primary string, secondary string, req *Request, next Handler) {
defer func() {
req.Close()
c.Lock()
delete(c.downloads, key)
c.Unlock()
}()
res := next(req)
if res == nil {
Log.Errorf("grace nil response for %q", req.URL)
return
}
defer res.Close()
if res.Status() >= 500 {
Log.Errorf("grace error for %q", req.URL)
} else {
c.Set(primary, secondary, req.Route.Cache, res)
}
}
func (c *Cache) reserveDownload(key string) bool {
now := time.Now()
c.Lock()
defer c.Unlock()
if expires, exists := c.downloads[key]; exists && expires.After(now) {
return false
}
c.downloads[key] = now.Add(time.Second * 30)
return true
}
func (c *Cache) Save(path string, count int, cutoff time.Duration) error {
return c.Storage.Save(path, count, cutoff)
}
func (c *Cache) Load(path string) error {
return c.Storage.Load(path)
}