-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgoop-cache.go
More file actions
471 lines (393 loc) · 10.3 KB
/
goop-cache.go
File metadata and controls
471 lines (393 loc) · 10.3 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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
package goop
import (
"crypto/md5"
"encoding/hex"
"encoding/json"
"os"
"path/filepath"
"sync"
"time"
)
// CacheEntry represents a cached response
type CacheEntry struct {
Key string `json:"key"`
Content string `json:"content"`
Headers string `json:"headers"`
Timestamp time.Time `json:"timestamp"`
TTL time.Duration `json:"ttl"`
Size int64 `json:"size"`
}
// IsExpired checks if the cache entry has expired
func (c *CacheEntry) IsExpired() bool {
return time.Since(c.Timestamp) > c.TTL
}
// CacheConfig defines caching behavior
type CacheConfig struct {
Enabled bool `json:"enabled"`
MemoryLimit int64 `json:"memory_limit"` // bytes
DiskLimit int64 `json:"disk_limit"` // bytes
DefaultTTL time.Duration `json:"default_ttl"`
CacheDir string `json:"cache_dir"`
Compression bool `json:"compression"`
}
// DefaultCacheConfig returns sensible default caching settings
var DefaultCacheConfig = CacheConfig{
Enabled: true,
MemoryLimit: 100 * 1024 * 1024, // 100MB
DiskLimit: 500 * 1024 * 1024, // 500MB
DefaultTTL: 1 * time.Hour,
CacheDir: ".goop_cache",
Compression: true,
}
// FastCacheConfig optimized for speed
var FastCacheConfig = CacheConfig{
Enabled: true,
MemoryLimit: 200 * 1024 * 1024, // 200MB
DiskLimit: 1024 * 1024 * 1024, // 1GB
DefaultTTL: 30 * time.Minute,
CacheDir: ".goop_cache_fast",
Compression: false,
}
// CacheStats provides cache performance metrics
type CacheStats struct {
MemoryHits int64 `json:"memory_hits"`
MemoryMisses int64 `json:"memory_misses"`
DiskHits int64 `json:"disk_hits"`
DiskMisses int64 `json:"disk_misses"`
MemorySize int64 `json:"memory_size"`
DiskSize int64 `json:"disk_size"`
TotalEntries int64 `json:"total_entries"`
}
// Cache interface defines cache operations
type Cache interface {
Get(key string) (*CacheEntry, bool)
Set(key string, entry *CacheEntry) error
Delete(key string) error
Clear() error
Stats() CacheStats
}
// MemoryCache provides in-memory caching
type MemoryCache struct {
config CacheConfig
cache map[string]*CacheEntry
mutex sync.RWMutex
stats CacheStats
}
// NewMemoryCache creates a new memory cache
func NewMemoryCache(config CacheConfig) *MemoryCache {
return &MemoryCache{
config: config,
cache: make(map[string]*CacheEntry),
stats: CacheStats{},
}
}
// Get retrieves an entry from memory cache
func (m *MemoryCache) Get(key string) (*CacheEntry, bool) {
m.mutex.RLock()
defer m.mutex.RUnlock()
entry, exists := m.cache[key]
if !exists {
m.stats.MemoryMisses++
return nil, false
}
if entry.IsExpired() {
delete(m.cache, key)
m.stats.MemoryMisses++
return nil, false
}
m.stats.MemoryHits++
return entry, true
}
// Set stores an entry in memory cache
func (m *MemoryCache) Set(key string, entry *CacheEntry) error {
m.mutex.Lock()
defer m.mutex.Unlock()
// Check memory limit
if m.getCurrentMemorySize()+entry.Size > m.config.MemoryLimit {
m.evictOldest()
}
m.cache[key] = entry
m.stats.MemorySize += entry.Size
m.stats.TotalEntries = int64(len(m.cache))
return nil
}
// Delete removes an entry from memory cache
func (m *MemoryCache) Delete(key string) error {
m.mutex.Lock()
defer m.mutex.Unlock()
if entry, exists := m.cache[key]; exists {
delete(m.cache, key)
m.stats.MemorySize -= entry.Size
m.stats.TotalEntries = int64(len(m.cache))
}
return nil
}
// Clear empties the memory cache
func (m *MemoryCache) Clear() error {
m.mutex.Lock()
defer m.mutex.Unlock()
m.cache = make(map[string]*CacheEntry)
m.stats.MemorySize = 0
m.stats.TotalEntries = 0
return nil
}
// Stats returns cache statistics
func (m *MemoryCache) Stats() CacheStats {
m.mutex.RLock()
defer m.mutex.RUnlock()
return m.stats
}
// getCurrentMemorySize calculates current memory usage
func (m *MemoryCache) getCurrentMemorySize() int64 {
var size int64
for _, entry := range m.cache {
size += entry.Size
}
return size
}
// evictOldest removes the oldest entry
func (m *MemoryCache) evictOldest() {
var oldestKey string
var oldestTime time.Time
for key, entry := range m.cache {
if oldestKey == "" || entry.Timestamp.Before(oldestTime) {
oldestKey = key
oldestTime = entry.Timestamp
}
}
if oldestKey != "" {
if entry, exists := m.cache[oldestKey]; exists {
delete(m.cache, oldestKey)
m.stats.MemorySize -= entry.Size
}
}
}
// DiskCache provides persistent disk-based caching
type DiskCache struct {
config CacheConfig
mutex sync.RWMutex
stats CacheStats
}
// NewDiskCache creates a new disk cache
func NewDiskCache(config CacheConfig) *DiskCache {
// Ensure cache directory exists
os.MkdirAll(config.CacheDir, 0755)
return &DiskCache{
config: config,
stats: CacheStats{},
}
}
// Get retrieves an entry from disk cache
func (d *DiskCache) Get(key string) (*CacheEntry, bool) {
d.mutex.RLock()
defer d.mutex.RUnlock()
filename := filepath.Join(d.config.CacheDir, key+".json")
data, err := os.ReadFile(filename)
if err != nil {
d.stats.DiskMisses++
return nil, false
}
var entry CacheEntry
if err := json.Unmarshal(data, &entry); err != nil {
d.stats.DiskMisses++
return nil, false
}
if entry.IsExpired() {
os.Remove(filename)
d.stats.DiskMisses++
return nil, false
}
d.stats.DiskHits++
return &entry, true
}
// Set stores an entry in disk cache
func (d *DiskCache) Set(key string, entry *CacheEntry) error {
d.mutex.Lock()
defer d.mutex.Unlock()
// Check disk limit
if d.getCurrentDiskSize()+entry.Size > d.config.DiskLimit {
d.evictOldestDisk()
}
filename := filepath.Join(d.config.CacheDir, key+".json")
data, err := json.Marshal(entry)
if err != nil {
return err
}
if err := os.WriteFile(filename, data, 0644); err != nil {
return err
}
d.stats.DiskSize += entry.Size
return nil
}
// Delete removes an entry from disk cache
func (d *DiskCache) Delete(key string) error {
d.mutex.Lock()
defer d.mutex.Unlock()
filename := filepath.Join(d.config.CacheDir, key+".json")
// Get file size before deletion
if info, err := os.Stat(filename); err == nil {
d.stats.DiskSize -= info.Size()
}
return os.Remove(filename)
}
// Clear empties the disk cache
func (d *DiskCache) Clear() error {
d.mutex.Lock()
defer d.mutex.Unlock()
err := os.RemoveAll(d.config.CacheDir)
if err != nil {
return err
}
os.MkdirAll(d.config.CacheDir, 0755)
d.stats.DiskSize = 0
return nil
}
// Stats returns cache statistics
func (d *DiskCache) Stats() CacheStats {
d.mutex.RLock()
defer d.mutex.RUnlock()
return d.stats
}
// getCurrentDiskSize calculates current disk usage
func (d *DiskCache) getCurrentDiskSize() int64 {
var size int64
filepath.Walk(d.config.CacheDir, func(path string, info os.FileInfo, err error) error {
if err == nil && !info.IsDir() {
size += info.Size()
}
return nil
})
return size
}
// evictOldestDisk removes the oldest file from disk
func (d *DiskCache) evictOldestDisk() {
var oldestFile string
var oldestTime time.Time
filepath.Walk(d.config.CacheDir, func(path string, info os.FileInfo, err error) error {
if err != nil || info.IsDir() {
return nil
}
if oldestFile == "" || info.ModTime().Before(oldestTime) {
oldestFile = path
oldestTime = info.ModTime()
}
return nil
})
if oldestFile != "" {
if info, err := os.Stat(oldestFile); err == nil {
os.Remove(oldestFile)
d.stats.DiskSize -= info.Size()
}
}
}
// HybridCache combines memory and disk caching
type HybridCache struct {
memoryCache *MemoryCache
diskCache *DiskCache
config CacheConfig
mutex sync.RWMutex
}
// NewHybridCache creates a new hybrid cache
func NewHybridCache(config CacheConfig) *HybridCache {
return &HybridCache{
memoryCache: NewMemoryCache(config),
diskCache: NewDiskCache(config),
config: config,
}
}
// Get retrieves an entry from hybrid cache (memory first, then disk)
func (h *HybridCache) Get(key string) (*CacheEntry, bool) {
// Try memory cache first
if entry, found := h.memoryCache.Get(key); found {
return entry, true
}
// Try disk cache
if entry, found := h.diskCache.Get(key); found {
// Promote to memory cache
h.memoryCache.Set(key, entry)
return entry, true
}
return nil, false
}
// Set stores an entry in both memory and disk cache
func (h *HybridCache) Set(key string, entry *CacheEntry) error {
// Store in both caches
if err := h.memoryCache.Set(key, entry); err != nil {
return err
}
return h.diskCache.Set(key, entry)
}
// Delete removes an entry from both caches
func (h *HybridCache) Delete(key string) error {
h.memoryCache.Delete(key)
return h.diskCache.Delete(key)
}
// Clear empties both caches
func (h *HybridCache) Clear() error {
h.memoryCache.Clear()
return h.diskCache.Clear()
}
// Stats returns combined cache statistics
func (h *HybridCache) Stats() CacheStats {
memStats := h.memoryCache.Stats()
diskStats := h.diskCache.Stats()
return CacheStats{
MemoryHits: memStats.MemoryHits,
MemoryMisses: memStats.MemoryMisses,
DiskHits: diskStats.DiskHits,
DiskMisses: diskStats.DiskMisses,
MemorySize: memStats.MemorySize,
DiskSize: diskStats.DiskSize,
TotalEntries: memStats.TotalEntries,
}
}
// Global cache instance
var globalCache Cache
var cacheConfig CacheConfig
var cacheMutex sync.RWMutex
// SetCacheConfig configures the global cache
func SetCacheConfig(config CacheConfig) {
cacheMutex.Lock()
defer cacheMutex.Unlock()
cacheConfig = config
if config.Enabled {
globalCache = NewHybridCache(config)
} else {
globalCache = nil
}
}
// GetCacheConfig returns current cache configuration
func GetCacheConfig() CacheConfig {
cacheMutex.RLock()
defer cacheMutex.RUnlock()
return cacheConfig
}
// GetCacheStats returns cache performance statistics
func GetCacheStats() CacheStats {
cacheMutex.RLock()
defer cacheMutex.RUnlock()
if globalCache == nil {
return CacheStats{}
}
return globalCache.Stats()
}
// ClearCache empties all caches
func ClearCache() error {
cacheMutex.Lock()
defer cacheMutex.Unlock()
if globalCache == nil {
return nil
}
return globalCache.Clear()
}
// generateCacheKey creates a unique cache key
func generateCacheKey(url string, method string, headers map[string]string) string {
h := md5.New()
h.Write([]byte(url))
h.Write([]byte(method))
// Add headers to key for cache differentiation
for k, v := range headers {
h.Write([]byte(k + ":" + v))
}
return hex.EncodeToString(h.Sum(nil))
}