-
Notifications
You must be signed in to change notification settings - Fork 52
/
baskets_mem.go
292 lines (229 loc) · 6.06 KB
/
baskets_mem.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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
package main
import (
"fmt"
"log"
"net/http"
"strings"
"sync"
)
// DbTypeMemory defines name of in-memory database storage
const DbTypeMemory = "mem"
/// Basket interface ///
type memoryBasket struct {
sync.RWMutex
token string
config BasketConfig
requests []*RequestData
totalCount int
responses map[string]*ResponseConfig
}
func (basket *memoryBasket) applyLimit() {
// Keep requests up to specified capacity
if len(basket.requests) > basket.config.Capacity {
basket.requests = basket.requests[:basket.config.Capacity]
}
}
func (basket *memoryBasket) Config() BasketConfig {
return basket.config
}
func (basket *memoryBasket) Update(config BasketConfig) {
basket.Lock()
defer basket.Unlock()
basket.config = config
basket.applyLimit()
}
func (basket *memoryBasket) Authorize(token string) bool {
return token == basket.token
}
func (basket *memoryBasket) GetResponse(method string) *ResponseConfig {
basket.Lock()
defer basket.Unlock()
if response, exists := basket.responses[method]; exists {
return response
}
return nil
}
func (basket *memoryBasket) SetResponse(method string, response ResponseConfig) {
basket.Lock()
defer basket.Unlock()
basket.responses[method] = &response
}
func (basket *memoryBasket) Add(req *http.Request) *RequestData {
basket.Lock()
defer basket.Unlock()
data := ToRequestData(req)
// insert in front of collection
basket.requests = append([]*RequestData{data}, basket.requests...)
// keep total number of all collected requests
basket.totalCount++
// apply limits according to basket capacity
basket.applyLimit()
return data
}
func (basket *memoryBasket) Clear() {
basket.Lock()
defer basket.Unlock()
// reset collected requests and total counter
basket.requests = make([]*RequestData, 0, basket.config.Capacity)
// basket.totalCount = 0 // reset total stats
}
func (basket *memoryBasket) Size() int {
return len(basket.requests)
}
func (basket *memoryBasket) GetRequests(max int, skip int) RequestsPage {
basket.RLock()
defer basket.RUnlock()
size := basket.Size()
last := skip + max
requestsPage := RequestsPage{
Count: size,
TotalCount: basket.totalCount,
HasMore: last < size}
if skip < size {
if last > size {
last = size
}
requestsPage.Requests = basket.requests[skip:last]
}
return requestsPage
}
func (basket *memoryBasket) FindRequests(query string, in string, max int, skip int) RequestsQueryPage {
basket.RLock()
defer basket.RUnlock()
result := make([]*RequestData, 0, max)
skipped := 0
for index, request := range basket.requests {
// filter
if request.Matches(query, in) {
if skipped < skip {
skipped++
} else {
result = append(result, request)
}
}
// early exit
if len(result) == max {
return RequestsQueryPage{Requests: result, HasMore: index < len(basket.requests)-1}
}
}
// whole basket is scanned through
return RequestsQueryPage{Requests: result, HasMore: false}
}
/// BasketsDatabase interface ///
type memoryDatabase struct {
sync.RWMutex
baskets map[string]*memoryBasket
names []string
}
func (db *memoryDatabase) Create(name string, config BasketConfig) (BasketAuth, error) {
auth := BasketAuth{}
token, err := GenerateToken()
if err != nil {
return auth, fmt.Errorf("failed to generate token: %s", err)
}
db.Lock()
defer db.Unlock()
_, exists := db.baskets[name]
if exists {
return auth, fmt.Errorf("Basket with name '%s' already exists", name)
}
basket := new(memoryBasket)
basket.token = token
basket.config = config
basket.requests = make([]*RequestData, 0, config.Capacity)
basket.totalCount = 0
basket.responses = make(map[string]*ResponseConfig)
db.baskets[name] = basket
db.names = append(db.names, name)
// Uncomment if sorting is expected
// sort.Strings(db.names)
auth.Token = token
return auth, nil
}
func (db *memoryDatabase) Get(name string) Basket {
if basket, exists := db.baskets[name]; exists {
return basket
}
log.Printf("[warn] no basket found: %s", name)
return nil
}
func (db *memoryDatabase) Delete(name string) {
db.Lock()
defer db.Unlock()
delete(db.baskets, name)
for i, v := range db.names {
if v == name {
db.names = append(db.names[:i], db.names[i+1:]...)
break
}
}
}
func (db *memoryDatabase) Size() int {
return len(db.names)
}
func (db *memoryDatabase) GetNames(max int, skip int) BasketNamesPage {
db.RLock()
defer db.RUnlock()
size := len(db.names)
last := skip + max
namesPage := BasketNamesPage{
Count: size,
HasMore: last < size}
if skip < size {
if last > size {
last = size
}
namesPage.Names = db.names[skip:last]
}
return namesPage
}
func (db *memoryDatabase) FindNames(query string, max int, skip int) BasketNamesQueryPage {
db.RLock()
defer db.RUnlock()
result := make([]string, 0, max)
skipped := 0
for index, name := range db.names {
// filter
if strings.Contains(name, query) {
if skipped < skip {
skipped++
} else {
result = append(result, name)
}
}
// early exit
if len(result) == max {
return BasketNamesQueryPage{Names: result, HasMore: index < len(db.names)-1}
}
}
// whole database is scanned through
return BasketNamesQueryPage{Names: result, HasMore: false}
}
func (db *memoryDatabase) GetStats(max int) DatabaseStats {
db.RLock()
defer db.RUnlock()
stats := DatabaseStats{}
for _, name := range db.names {
if basket, exists := db.baskets[name]; exists {
var lastRequestDate int64
if basket.Size() > 0 {
lastRequestDate = basket.GetRequests(1, 0).Requests[0].Date
}
stats.Collect(&BasketInfo{
Name: name,
RequestsCount: basket.Size(),
RequestsTotalCount: basket.totalCount,
LastRequestDate: lastRequestDate}, max)
}
}
stats.UpdateAvarage()
return stats
}
func (db *memoryDatabase) Release() {
log.Print("[info] releasing in-memory database resources")
}
// NewMemoryDatabase creates an instance of in-memory Baskets Database
func NewMemoryDatabase() BasketsDatabase {
log.Print("[info] using in-memory database to store baskets")
return &memoryDatabase{baskets: make(map[string]*memoryBasket), names: make([]string, 0)}
}