-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathcache_adapter_memory.go
More file actions
92 lines (77 loc) · 1.71 KB
/
cache_adapter_memory.go
File metadata and controls
92 lines (77 loc) · 1.71 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
package limen
import (
"context"
"sync"
"time"
)
type memoryEntry struct {
value []byte
expiresAt time.Time // zero value means no expiry
}
func (e *memoryEntry) isExpired() bool {
return !e.expiresAt.IsZero() && time.Now().After(e.expiresAt)
}
// MemoryCacheStore is the default in-process CacheAdapter implementation.
// It uses sync.RWMutex-protected maps with lazy expiry on read.
type MemoryCacheStore struct {
mu sync.RWMutex
data map[string]*memoryEntry
}
func NewMemoryCacheStore() *MemoryCacheStore {
return &MemoryCacheStore{
data: make(map[string]*memoryEntry),
}
}
func (m *MemoryCacheStore) Get(_ context.Context, key string) ([]byte, error) {
m.mu.RLock()
entry, ok := m.data[key]
m.mu.RUnlock()
if !ok {
return nil, ErrRecordNotFound
}
if entry.isExpired() {
m.mu.Lock()
delete(m.data, key)
m.mu.Unlock()
return nil, ErrRecordNotFound
}
cp := make([]byte, len(entry.value))
copy(cp, entry.value)
return cp, nil
}
func (m *MemoryCacheStore) Set(_ context.Context, key string, value []byte, ttl time.Duration) error {
m.mu.Lock()
defer m.mu.Unlock()
var expiresAt time.Time
if ttl > 0 {
expiresAt = time.Now().Add(ttl)
}
cp := make([]byte, len(value))
copy(cp, value)
m.data[key] = &memoryEntry{
value: cp,
expiresAt: expiresAt,
}
return nil
}
func (m *MemoryCacheStore) Has(_ context.Context, key string) (bool, error) {
m.mu.RLock()
entry, ok := m.data[key]
m.mu.RUnlock()
if !ok {
return false, nil
}
if entry.isExpired() {
m.mu.Lock()
delete(m.data, key)
m.mu.Unlock()
return false, nil
}
return true, nil
}
func (m *MemoryCacheStore) Delete(_ context.Context, key string) error {
m.mu.Lock()
delete(m.data, key)
m.mu.Unlock()
return nil
}