-
Notifications
You must be signed in to change notification settings - Fork 49
/
common.go
271 lines (225 loc) · 7.31 KB
/
common.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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
package providers
import (
"fmt"
"net/http"
"net/url"
"regexp"
"strings"
"sync"
"time"
"github.com/darkweak/souin/configurationtypes"
"github.com/darkweak/souin/pkg/storage"
"github.com/darkweak/souin/pkg/storage/types"
"go.uber.org/zap"
)
const (
cdnCacheControl = "CDN-Cache-Control"
cacheGroupKey = "Cache-Groups"
surrogateKey = "Surrogate-Key"
surrogateControl = "Surrogate-Control"
cacheControl = "Cache-Control"
noStoreDirective = "no-store"
souinStorageSeparator = ","
souinCacheControl = "Souin-Cache-Control"
fastlyCacheControl = "Fastly-Cache-Control"
edgeCacheTag = "Edge-Cache-Tag"
cacheTags = "Cache-Tags"
cacheTag = "Cache-Tag"
surrogatePrefix = "SURROGATE_"
)
var storageToInfiniteTTLMap = map[string]time.Duration{
"BADGER": 365 * 24 * time.Hour,
"ETCD": 365 * 24 * time.Hour,
"NUTS": 0,
"OLRIC": 365 * 24 * time.Hour,
"REDIS": 0,
}
func (s *baseStorage) ParseHeaders(value string) []string {
return regexp.MustCompile(s.parent.getHeaderSeparator()+" *").Split(value, -1)
}
func getCandidateHeader(header http.Header, getCandidates func() []string) (string, string) {
candidates := getCandidates()
for _, candidate := range candidates {
if h := header.Get(candidate); h != "" {
return candidate, h
}
}
return candidates[len(candidates)-1], ""
}
func isSafeHTTPMethod(method string) bool {
switch method {
case http.MethodGet, http.MethodHead, http.MethodOptions, http.MethodTrace:
return true
}
return false
}
func uniqueTag(values []string) []string {
tmp := make(map[string]bool)
list := []string{}
for _, item := range values {
if item == "" {
continue
}
if _, found := tmp[item]; !found {
tmp[item] = true
i, _ := url.QueryUnescape(item)
list = append(list, i)
}
}
return list
}
type keysRegexpInner struct {
Headers map[string]*regexp.Regexp
Url *regexp.Regexp
}
type baseStorage struct {
parent SurrogateInterface
Storage types.Storer
Keys map[string]configurationtypes.SurrogateKeys
keysRegexp map[string]keysRegexpInner
dynamic bool
keepStale bool
logger *zap.Logger
mu *sync.Mutex
duration time.Duration
}
func (s *baseStorage) init(config configurationtypes.AbstractConfigurationInterface) {
if configuration, ok := config.GetSurrogateKeys()["_configuration"]; ok {
instanciator, err := storage.NewStorageFromName(configuration.SurrogateConfiguration.Storer)
if err != nil {
instanciator, _ = storage.NewStorageFromName("nuts")
}
storer, err := instanciator(config)
if err != nil {
panic(fmt.Sprintf("Impossible to instanciate the storer for the surrogate-keys: %v", err))
}
s.Storage = storer
} else {
instanciator, _ := storage.NewStorageFromName("nuts")
storer, err := instanciator(config)
if err != nil {
panic(fmt.Sprintf("Impossible to instanciate the storer for the surrogate-keys: %v", err))
}
s.Storage = storer
}
s.Keys = config.GetSurrogateKeys()
s.keepStale = config.GetDefaultCache().GetCDN().Strategy != "hard"
keysRegexp := make(map[string]keysRegexpInner, len(s.Keys))
baseRegexp := regexp.MustCompile(".+")
for key, regexps := range s.Keys {
headers := make(map[string]*regexp.Regexp, len(regexps.Headers))
for hk, hv := range regexps.Headers {
headers[hk] = baseRegexp
if hv != "" {
headers[hk] = regexp.MustCompile(hv)
}
}
innerKey := keysRegexpInner{Headers: headers, Url: baseRegexp}
if regexps.URL != "" {
innerKey.Url = regexp.MustCompile(regexps.URL)
}
keysRegexp[key] = innerKey
}
s.dynamic = config.GetDefaultCache().GetCDN().Dynamic
s.logger = config.GetLogger()
s.keysRegexp = keysRegexp
s.mu = &sync.Mutex{}
s.duration = storageToInfiniteTTLMap[s.Storage.Name()]
}
func (s *baseStorage) storeTag(tag string, cacheKey string, re *regexp.Regexp) {
defer s.mu.Unlock()
s.mu.Lock()
currentValue := string(s.Storage.Get(surrogatePrefix + tag))
if !re.MatchString(currentValue) {
s.logger.Sugar().Debugf("Store the tag %s", tag)
_ = s.Storage.Set(surrogatePrefix+tag, []byte(currentValue+souinStorageSeparator+cacheKey), configurationtypes.URL{}, s.duration)
}
}
func (*baseStorage) candidateStore(tag string) bool {
return !strings.Contains(tag, noStoreDirective)
}
func (*baseStorage) getOrderedSurrogateKeyHeadersCandidate() []string {
return []string{
surrogateKey,
edgeCacheTag,
cacheTags,
}
}
func (*baseStorage) getOrderedSurrogateControlHeadersCandidate() []string {
return []string{
souinCacheControl,
surrogateControl,
cdnCacheControl,
cacheControl,
}
}
func (s *baseStorage) GetSurrogateControl(header http.Header) (string, string) {
return getCandidateHeader(header, s.parent.getOrderedSurrogateControlHeadersCandidate)
}
func (s *baseStorage) GetSurrogateControlName() string {
return s.parent.getOrderedSurrogateControlHeadersCandidate()[0]
}
func (s *baseStorage) getSurrogateKey(header http.Header) string {
_, v := getCandidateHeader(header, s.parent.getOrderedSurrogateKeyHeadersCandidate)
return v
}
func (s *baseStorage) purgeTag(tag string) []string {
toInvalidate := string(s.Storage.Get(surrogatePrefix + tag))
s.logger.Sugar().Debugf("Purge the tag %s", tag)
if !s.keepStale {
s.Storage.Delete(surrogatePrefix + tag)
}
return strings.Split(toInvalidate, souinStorageSeparator)
}
// Store will take the lead to store the cache key for each provided Surrogate-key
func (s *baseStorage) Store(response *http.Response, cacheKey string) error {
h := response.Header
cacheKey = url.QueryEscape(cacheKey)
urlRegexp := regexp.MustCompile("(^|" + regexp.QuoteMeta(souinStorageSeparator) + ")" + regexp.QuoteMeta(cacheKey) + "(" + regexp.QuoteMeta(souinStorageSeparator) + "|$)")
keys := s.ParseHeaders(s.parent.getSurrogateKey(h))
for _, key := range keys {
_, v := s.parent.GetSurrogateControl(h)
if controls := s.ParseHeaders(v); len(controls) != 0 {
if len(controls) == 1 && controls[0] == "" {
s.storeTag(key, cacheKey, urlRegexp)
continue
}
for _, control := range controls {
if s.parent.candidateStore(control) {
s.storeTag(key, cacheKey, urlRegexp)
}
}
} else {
s.storeTag(key, cacheKey, urlRegexp)
}
}
return nil
}
// Purge take the request headers as parameter, retrieve the associated cache keys for the Surrogate-Key given.
// It returns an array which one contains the cache keys to invalidate.
func (s *baseStorage) Purge(header http.Header) (cacheKeys []string, surrogateKeys []string) {
surrogates := s.ParseHeaders(s.parent.getSurrogateKey(header))
toInvalidate := []string{}
for _, su := range surrogates {
toInvalidate = append(toInvalidate, s.purgeTag(su)...)
}
s.logger.Sugar().Debugf("Purge the following tags: %+v", toInvalidate)
return uniqueTag(toInvalidate), surrogates
}
// Invalidate the grouped responses from the Cache-Group-Invalidation HTTP response header
func (s *baseStorage) Invalidate(method string, headers http.Header) {
if !isSafeHTTPMethod(method) {
for _, group := range headers["Cache-Group-Invalidation"] {
s.purgeTag(group)
}
}
}
// List returns the stored keys associated to resources
func (s *baseStorage) List() map[string]string {
return s.Storage.MapKeys(surrogatePrefix)
}
// Destruct method will shutdown properly the provider
func (s *baseStorage) Destruct() error {
s.Storage.DeleteMany(surrogatePrefix + ".*")
return nil
}