forked from darkweak/souin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
souin.go
254 lines (227 loc) · 6.59 KB
/
souin.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
package api
import (
"bytes"
"encoding/gob"
"encoding/json"
"fmt"
"net/http"
"regexp"
"strings"
"time"
"github.com/darkweak/souin/configurationtypes"
"github.com/darkweak/souin/pkg/storage"
"github.com/darkweak/souin/pkg/storage/types"
"github.com/darkweak/souin/pkg/surrogate/providers"
)
// SouinAPI object contains informations related to the endpoints
type SouinAPI struct {
basePath string
enabled bool
storers []types.Storer
surrogateStorage providers.SurrogateInterface
allowedMethods []string
}
type invalidationType string
const (
uriInvalidationType invalidationType = "uri"
uriPrefixInvalidationType invalidationType = "uri-prefix"
originInvalidationType invalidationType = "origin"
groupInvalidationType invalidationType = "group"
)
type invalidation struct {
Type invalidationType `json:"type"`
Selectors []string `json:"selectors"`
Groups []string `json:"groups"`
Purge bool `json:"purge"`
}
func initializeSouin(
configuration configurationtypes.AbstractConfigurationInterface,
storers []types.Storer,
surrogateStorage providers.SurrogateInterface,
) *SouinAPI {
basePath := configuration.GetAPI().Souin.BasePath
if basePath == "" {
basePath = "/souin"
}
allowedMethods := configuration.GetDefaultCache().GetAllowedHTTPVerbs()
if len(allowedMethods) == 0 {
allowedMethods = []string{http.MethodGet, http.MethodHead}
}
return &SouinAPI{
basePath,
configuration.GetAPI().Souin.Enable,
storers,
surrogateStorage,
allowedMethods,
}
}
// BulkDelete allow user to delete multiple items with regexp
func (s *SouinAPI) BulkDelete(key string, purge bool) {
key, _ = strings.CutPrefix(key, storage.MappingKeyPrefix)
for _, current := range s.storers {
if b := current.Get(storage.MappingKeyPrefix + key); len(b) > 0 {
var mapping types.StorageMapper
if e := gob.NewDecoder(bytes.NewBuffer(b)).Decode(&mapping); e == nil {
for k := range mapping.Mapping {
current.Delete(k)
}
}
if purge {
current.Delete(storage.MappingKeyPrefix + key)
} else {
newFreshTime := time.Now()
for k, v := range mapping.Mapping {
v.FreshTime = newFreshTime
mapping.Mapping[k] = v
}
}
}
}
s.Delete(key)
}
// Delete will delete a record into the provider cache system and will update the Souin API if enabled
func (s *SouinAPI) Delete(key string) {
for _, current := range s.storers {
current.Delete(key)
}
}
// GetAll will retrieve all stored keys in the provider
func (s *SouinAPI) GetAll() []string {
keys := []string{}
for _, current := range s.storers {
keys = append(keys, current.ListKeys()...)
}
return keys
}
// GetBasePath will return the basepath for this resource
func (s *SouinAPI) GetBasePath() string {
return s.basePath
}
// IsEnabled will return enabled status
func (s *SouinAPI) IsEnabled() bool {
return s.enabled
}
func (s *SouinAPI) listKeys(search string) []string {
res := []string{}
re, err := regexp.Compile(search)
if err != nil {
return res
}
for _, key := range s.GetAll() {
if re.MatchString(key) {
res = append(res, key)
}
}
return res
}
// HandleRequest will handle the request
func (s *SouinAPI) HandleRequest(w http.ResponseWriter, r *http.Request) {
res := []byte{}
compile := regexp.MustCompile(s.GetBasePath()+"/.+").FindString(r.RequestURI) != ""
switch r.Method {
case http.MethodGet:
if regexp.MustCompile(s.GetBasePath()+"/surrogate_keys").FindString(r.RequestURI) != "" {
res, _ = json.Marshal(s.surrogateStorage.List())
} else if compile {
search := regexp.MustCompile(s.GetBasePath()+"/(.+)").FindAllStringSubmatch(r.RequestURI, -1)[0][1]
res, _ = json.Marshal(s.listKeys(search))
if len(res) == 2 {
w.WriteHeader(http.StatusNotFound)
}
} else {
res, _ = json.Marshal(s.GetAll())
}
w.Header().Set("Content-Type", "application/json")
case http.MethodPost:
var invalidator invalidation
defer r.Body.Close()
err := json.NewDecoder(r.Body).Decode(&invalidator)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
keysToInvalidate := []string{}
switch invalidator.Type {
case groupInvalidationType:
keysToInvalidate, _ = s.surrogateStorage.Purge(http.Header{"Surrogate-Key": invalidator.Groups})
case uriPrefixInvalidationType, uriInvalidationType:
bodyKeys := []string{}
listedKeys := s.GetAll()
for _, k := range invalidator.Selectors {
if !strings.Contains(k, "//") {
rq, err := http.NewRequest(http.MethodGet, "//"+k, nil)
if err != nil {
continue
}
bodyKeys = append(bodyKeys, rq.Host+"-"+rq.URL.Path)
}
}
for _, allKey := range listedKeys {
for _, bk := range bodyKeys {
if invalidator.Type == uriInvalidationType {
if strings.Contains(allKey, bk) && strings.Contains(allKey, bk+"-") && strings.HasSuffix(allKey, bk) {
keysToInvalidate = append(keysToInvalidate, allKey)
break
}
} else {
if strings.Contains(allKey, bk) &&
(strings.Contains(allKey, bk+"-") || strings.Contains(allKey, bk+"?") || strings.Contains(allKey, bk+"/") || strings.HasSuffix(allKey, bk)) {
keysToInvalidate = append(keysToInvalidate, allKey)
break
}
}
}
}
case originInvalidationType:
bodyKeys := []string{}
listedKeys := s.GetAll()
for _, k := range invalidator.Selectors {
if !strings.Contains(k, "//") {
rq, err := http.NewRequest(http.MethodGet, "//"+k, nil)
if err != nil {
continue
}
bodyKeys = append(bodyKeys, rq.Host)
}
}
for _, allKey := range listedKeys {
for _, bk := range bodyKeys {
if strings.Contains(allKey, bk) {
keysToInvalidate = append(keysToInvalidate, allKey)
break
}
}
}
}
for _, k := range keysToInvalidate {
s.BulkDelete(k, invalidator.Purge)
}
w.WriteHeader(http.StatusOK)
case "PURGE":
if compile {
keysRg := regexp.MustCompile(s.GetBasePath() + "/(.+)")
flushRg := regexp.MustCompile(s.GetBasePath() + "/flush$")
if flushRg.FindString(r.RequestURI) != "" {
for _, current := range s.storers {
current.DeleteMany(".+")
}
e := s.surrogateStorage.Destruct()
if e != nil {
fmt.Printf("Error while purging the surrogate keys: %+v.", e)
}
fmt.Println("Successfully clear the cache and the surrogate keys storage.")
} else {
submatch := keysRg.FindAllStringSubmatch(r.RequestURI, -1)[0][1]
s.BulkDelete(submatch, true)
}
} else {
ck, _ := s.surrogateStorage.Purge(r.Header)
for _, k := range ck {
s.BulkDelete(k, true)
}
}
w.WriteHeader(http.StatusNoContent)
default:
}
_, _ = w.Write(res)
}