-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtwo_level_cache.go
More file actions
295 lines (254 loc) · 8.18 KB
/
two_level_cache.go
File metadata and controls
295 lines (254 loc) · 8.18 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
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
293
294
295
/*
MIT License
Copyright (c) 2023 Frank Oh
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package echo_http_cache
import (
"sync"
"time"
)
// CacheTwoLevelStore implements two-level caching with L1 (memory) and L2 (Redis)
type CacheTwoLevelStore struct {
config TwoLevelConfig
metrics *CacheMetrics
asyncChan chan asyncOperation
wg sync.WaitGroup
stopChan chan struct{}
}
// asyncOperation represents an async cache operation
type asyncOperation struct {
operation string
key uint64
data []byte
expiration time.Time
}
// NewCacheTwoLevelStore creates a new two-level cache store with default config
func NewCacheTwoLevelStore(l1Store, l2Store CacheStore) CacheStore {
config := DefaultTwoLevelConfig
config.L1Store = l1Store
config.L2Store = l2Store
return NewCacheTwoLevelStoreWithConfig(config)
}
// NewCacheTwoLevelStoreWithConfig creates a new two-level cache store with custom config
func NewCacheTwoLevelStoreWithConfig(config TwoLevelConfig) CacheStore {
// Set defaults for missing values
if config.L1TTL == 0 {
config.L1TTL = DefaultTwoLevelConfig.L1TTL
}
if config.L2TTL == 0 {
config.L2TTL = DefaultTwoLevelConfig.L2TTL
}
if config.AsyncBuffer == 0 {
config.AsyncBuffer = DefaultTwoLevelConfig.AsyncBuffer
}
store := &CacheTwoLevelStore{
config: config,
metrics: &CacheMetrics{},
asyncChan: make(chan asyncOperation, config.AsyncBuffer),
stopChan: make(chan struct{}),
}
// Start async worker if using WriteBack strategy
if config.Strategy == WriteBack {
store.startAsyncWorker()
}
return store
}
// Get implements CacheStore interface
func (store *CacheTwoLevelStore) Get(key uint64) ([]byte, bool) {
// 1. Try L1 cache first (memory)
if data, found := store.config.L1Store.Get(key); found {
store.metrics.IncrementL1Hit()
return data, true
}
// 2. Try L2 cache (Redis)
if data, found := store.config.L2Store.Get(key); found {
store.metrics.IncrementL2Hit()
// Cache warming: promote L2 data to L1
if store.config.CacheWarming {
store.warmCache(key, data)
}
return data, true
}
// Cache miss
store.metrics.IncrementMiss()
return nil, false
}
// warmCache promotes L2 data to L1 cache with optimized logic
func (store *CacheTwoLevelStore) warmCache(key uint64, data []byte) {
if store.config.SyncMode == "async" {
// Async warming to avoid blocking the response
select {
case store.asyncChan <- asyncOperation{
operation: "warm",
key: key,
data: data,
}:
// Successfully queued for warming
default:
// Queue is full, skip warming to avoid blocking
}
} else {
// Sync warming
store.performWarming(key, data)
}
}
// performWarming executes the actual cache warming operation
func (store *CacheTwoLevelStore) performWarming(key uint64, data []byte) {
// Smart TTL calculation: use the shorter of L1TTL or remaining time
l1Expiration := time.Now().Add(store.config.L1TTL)
// For now, we use L1TTL. In a future version, we could get the actual
// expiration from L2 store if the interface supports it
store.config.L1Store.Set(key, data, l1Expiration)
}
// Set implements CacheStore interface
func (store *CacheTwoLevelStore) Set(key uint64, response []byte, expiration time.Time) {
switch store.config.Strategy {
case WriteThrough:
store.setWriteThrough(key, response, expiration)
case WriteBack:
store.setWriteBack(key, response, expiration)
case CacheAside:
store.setCacheAside(key, response, expiration)
}
}
// Release implements CacheStore interface
func (store *CacheTwoLevelStore) Release(key uint64) {
// Remove from both L1 and L2
store.config.L1Store.Release(key)
store.config.L2Store.Release(key)
}
// setWriteThrough implements write-through strategy
func (store *CacheTwoLevelStore) setWriteThrough(key uint64, response []byte, expiration time.Time) {
// Calculate L1 expiration (shorter TTL)
l1Expiration := time.Now().Add(store.config.L1TTL)
if l1Expiration.After(expiration) {
l1Expiration = expiration
}
// Calculate L2 expiration (longer TTL)
l2Expiration := time.Now().Add(store.config.L2TTL)
if l2Expiration.After(expiration) {
l2Expiration = expiration
}
// Write to both caches synchronously
store.config.L1Store.Set(key, response, l1Expiration)
store.config.L2Store.Set(key, response, l2Expiration)
}
// setWriteBack implements write-back strategy
func (store *CacheTwoLevelStore) setWriteBack(key uint64, response []byte, expiration time.Time) {
// Write to L1 immediately
l1Expiration := time.Now().Add(store.config.L1TTL)
if l1Expiration.After(expiration) {
l1Expiration = expiration
}
store.config.L1Store.Set(key, response, l1Expiration)
// Queue L2 write for async processing
l2Expiration := time.Now().Add(store.config.L2TTL)
if l2Expiration.After(expiration) {
l2Expiration = expiration
}
select {
case store.asyncChan <- asyncOperation{
operation: "set",
key: key,
data: response,
expiration: l2Expiration,
}:
default:
// Channel is full, fallback to synchronous write
store.config.L2Store.Set(key, response, l2Expiration)
}
}
// setCacheAside implements cache-aside strategy
func (store *CacheTwoLevelStore) setCacheAside(key uint64, response []byte, expiration time.Time) {
// Simple implementation: write to both (similar to write-through)
store.setWriteThrough(key, response, expiration)
}
// startAsyncWorker starts the async worker goroutine
func (store *CacheTwoLevelStore) startAsyncWorker() {
store.wg.Add(1)
go func() {
defer store.wg.Done()
for {
select {
case op := <-store.asyncChan:
switch op.operation {
case "set":
store.config.L2Store.Set(op.key, op.data, op.expiration)
case "release":
store.config.L2Store.Release(op.key)
case "warm":
store.performWarming(op.key, op.data)
}
case <-store.stopChan:
return
}
}
}()
}
// Stop gracefully stops the two-level cache store
func (store *CacheTwoLevelStore) Stop() {
if store.config.Strategy == WriteBack {
close(store.stopChan)
store.wg.Wait()
close(store.asyncChan)
}
}
// GetStats returns cache statistics
func (store *CacheTwoLevelStore) GetStats() CacheStats {
stats := store.metrics.GetStats()
// Add size information if available
if memorySizer, ok := store.config.L1Store.(interface{ Size() int }); ok {
stats.L1Size = memorySizer.Size()
}
if redisSizer, ok := store.config.L2Store.(interface{ Size() int }); ok {
stats.L2Size = redisSizer.Size()
}
return stats
}
// ClearL1 clears only L1 cache
func (store *CacheTwoLevelStore) ClearL1() error {
if clearer, ok := store.config.L1Store.(interface{ Clear() error }); ok {
return clearer.Clear()
}
return nil
}
// ClearL2 clears only L2 cache
func (store *CacheTwoLevelStore) ClearL2() error {
if clearer, ok := store.config.L2Store.(interface{ Clear() error }); ok {
return clearer.Clear()
}
return nil
}
// ClearAll clears both L1 and L2 caches
func (store *CacheTwoLevelStore) ClearAll() error {
var err1, err2 error
if clearer, ok := store.config.L1Store.(interface{ Clear() error }); ok {
err1 = clearer.Clear()
}
if clearer, ok := store.config.L2Store.(interface{ Clear() error }); ok {
err2 = clearer.Clear()
}
if err1 != nil {
return err1
}
return err2
}
// ResetStats resets cache statistics
func (store *CacheTwoLevelStore) ResetStats() {
store.metrics.Reset()
}