-
Notifications
You must be signed in to change notification settings - Fork 0
/
inmem.go
151 lines (122 loc) · 2.71 KB
/
inmem.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
package cache
import (
"context"
"fmt"
"math"
"sync"
"time"
)
var _ Cache[string, any] = &InMem[string, any]{}
type expiresAt int64
func (ea expiresAt) isExpired() bool {
i := int64(ea)
return time.Now().UnixNano() > i && i != int64(NoExpiration)
}
type item[V any] struct {
val V
expiresAt expiresAt
}
// InMem is a Cache implementation which interacts with an in-memory map
// It is concurrent safe
type InMem[K comparable, V any] struct {
items map[K]item[V]
cap int
ticker *time.Ticker
mu sync.RWMutex
}
// NewInMemory returns a InMem instance
func NewInMemory[K comparable, V any](cleanUpInterval time.Duration, cap int) *InMem[K, V] {
inmem := &InMem[K, V]{
items: map[K]item[V]{},
cap: cap,
ticker: time.NewTicker(cleanUpInterval),
}
go func() {
for range inmem.ticker.C {
inmem.mu.Lock()
inmem.cleanup()
inmem.mu.Unlock()
}
}()
return inmem
}
// Get retrieves an item from an in-memory map
func (i *InMem[K, V]) Get(ctx context.Context, key K) (V, error) {
i.mu.RLock()
defer i.mu.RUnlock()
select {
case <-ctx.Done():
return *new(V), fmt.Errorf("%w: %s", ErrNotGet, ctx.Err())
default:
}
item, ok := i.items[key]
if !ok {
return *new(V), ErrNotFound
}
if item.expiresAt.isExpired() {
return *new(V), ErrExpired
}
return item.val, nil
}
// Set stores an item to an in-memory map
func (i *InMem[K, V]) Set(ctx context.Context, key K, val V, ttl time.Duration) error {
i.mu.Lock()
defer i.mu.Unlock()
select {
case <-ctx.Done():
return fmt.Errorf("%w: %s", ErrNotSet, ctx.Err())
default:
}
exp := expiresAt(ttl)
if ttl != NoExpiration {
exp = expiresAt(time.Now().Add(ttl).UnixNano())
}
if len(i.items) == i.cap {
i.cleanup()
}
i.items[key] = item[V]{val: val, expiresAt: exp}
return nil
}
// Delete removes an item to an in-memory map
func (i *InMem[K, V]) Delete(ctx context.Context, key K) error {
i.mu.Lock()
defer i.mu.Unlock()
select {
case <-ctx.Done():
return fmt.Errorf("%w: %s", ErrNotDelete, ctx.Err())
default:
}
delete(i.items, key)
return nil
}
// Close stops the inner ticker
func (i *InMem[K, V]) Close() error {
i.mu.Lock()
defer i.mu.Unlock()
i.ticker.Stop()
return nil
}
// cleanup remove all the expired items.
// if no item is expired, it deletes the one closer to expire
func (i *InMem[K, V]) cleanup() {
ks := []K{}
minExp := math.MaxInt64
for k, item := range i.items {
switch {
case item.expiresAt.isExpired():
delete(i.items, k)
case minExp == int(item.expiresAt):
minExp = int(item.expiresAt)
ks = append(ks, k)
case minExp > int(item.expiresAt):
minExp = int(item.expiresAt)
ks = []K{k}
}
}
if len(i.items) < i.cap {
return
}
for _, k := range ks {
delete(i.items, k)
}
}