This repository has been archived by the owner on May 10, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
tinykv.go
349 lines (308 loc) · 7.26 KB
/
tinykv.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
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
package tinykv
import (
"fmt"
"sync"
"time"
)
//-----------------------------------------------------------------------------
type timeout struct {
expiresAt time.Time
expiresAfter time.Duration
isSliding bool
key string
}
func newTimeout(
key string,
expiresAfter time.Duration,
isSliding bool) *timeout {
return &timeout{
expiresAt: time.Now().Add(expiresAfter),
expiresAfter: expiresAfter,
isSliding: isSliding,
key: key,
}
}
func (to *timeout) slide() {
if to == nil {
return
}
if !to.isSliding {
return
}
if to.expiresAfter <= 0 {
return
}
to.expiresAt = time.Now().Add(to.expiresAfter)
}
func (to *timeout) expired() bool {
if to == nil {
return false
}
return time.Now().After(to.expiresAt)
}
//-----------------------------------------------------------------------------
// timeout heap
type th []*timeout
func (h th) Len() int { return len(h) }
func (h th) Less(i, j int) bool { return h[i].expiresAt.Before(h[j].expiresAt) }
func (h th) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *th) Push(x tohVal) { *h = append(*h, x) }
func (h *th) Pop() tohVal {
old := *h
n := len(old)
x := old[n-1]
*h = old[0 : n-1]
return x
}
//-----------------------------------------------------------------------------
type entry struct {
*timeout
value interface{}
}
//-----------------------------------------------------------------------------
// KV is a registry for values (like/is a concurrent map) with timeout and sliding timeout
type KV interface {
Delete(k string)
Get(k string) (v interface{}, ok bool)
Put(k string, v interface{}, options ...PutOption) error
Take(k string) (v interface{}, ok bool)
Stop()
}
//-----------------------------------------------------------------------------
type putOpt struct {
expiresAfter time.Duration
isSliding bool
cas func(interface{}, bool) bool
}
// PutOption extra options for put
type PutOption func(*putOpt)
// ExpiresAfter entry will expire after this time
func ExpiresAfter(expiresAfter time.Duration) PutOption {
return func(opt *putOpt) {
opt.expiresAfter = expiresAfter
}
}
// IsSliding sets if the entry would get expired in a sliding manner
func IsSliding(isSliding bool) PutOption {
return func(opt *putOpt) {
opt.isSliding = isSliding
}
}
// CAS for performing a compare and swap
func CAS(cas func(oldValue interface{}, found bool) bool) PutOption {
return func(opt *putOpt) {
opt.cas = cas
}
}
//-----------------------------------------------------------------------------
// store is a registry for values (like/is a concurrent map) with timeout and sliding timeout
type store struct {
onExpire func(k string, v interface{})
stop chan struct{}
stopOnce sync.Once
expirationInterval time.Duration
mx sync.Mutex
kv map[string]*entry
heap th
}
// New creates a new *store, onExpire is for notification (must be fast).
func New(expirationInterval time.Duration, onExpire ...func(k string, v interface{})) KV {
if expirationInterval <= 0 {
expirationInterval = time.Second * 20
}
res := &store{
stop: make(chan struct{}),
kv: make(map[string]*entry),
expirationInterval: expirationInterval,
heap: th{},
}
if len(onExpire) > 0 && onExpire[0] != nil {
res.onExpire = onExpire[0]
}
go res.expireLoop()
return res
}
// Stop stops the goroutine
func (kv *store) Stop() {
kv.stopOnce.Do(func() { close(kv.stop) })
}
// Delete deletes an entry
func (kv *store) Delete(k string) {
kv.mx.Lock()
defer kv.mx.Unlock()
delete(kv.kv, k)
}
// Get gets an entry from KV store
// and if a sliding timeout is set, it will be slided
func (kv *store) Get(k string) (interface{}, bool) {
kv.mx.Lock()
defer kv.mx.Unlock()
e, ok := kv.kv[k]
if !ok {
return nil, ok
}
e.slide()
if e.expired() {
go notifyExpirations(map[string]interface{}{k: e.value}, kv.onExpire)
delete(kv.kv, k)
return nil, false
}
return e.value, ok
}
// Put puts an entry inside kv store with provided options
func (kv *store) Put(k string, v interface{}, options ...PutOption) error {
opt := &putOpt{}
for _, v := range options {
v(opt)
}
e := &entry{
value: v,
}
kv.mx.Lock()
defer kv.mx.Unlock()
if opt.expiresAfter > 0 {
e.timeout = newTimeout(k, opt.expiresAfter, opt.isSliding)
timeheapPush(&kv.heap, e.timeout)
}
if opt.cas != nil {
return kv.cas(k, e, opt.cas)
}
kv.kv[k] = e
return nil
}
func (kv *store) cas(k string, e *entry, casFunc func(interface{}, bool) bool) error {
old, ok := kv.kv[k]
var oldValue interface{}
if ok && old != nil {
oldValue = old.value
}
if !casFunc(oldValue, ok) {
return ErrCASCond
}
if ok && old != nil {
if e.timeout != nil {
old.timeout = e.timeout
}
old.value = e.value
e = old
}
e.slide()
kv.kv[k] = e
return nil
}
// Take takes an entry out of kv store
func (kv *store) Take(k string) (interface{}, bool) {
kv.mx.Lock()
defer kv.mx.Unlock()
e, ok := kv.kv[k]
if ok {
delete(kv.kv, k)
return e.value, ok
}
return nil, ok
}
//-----------------------------------------------------------------------------
func (kv *store) expireLoop() {
interval := kv.expirationInterval
expireTime := time.NewTimer(interval)
for {
select {
case <-kv.stop:
return
case <-expireTime.C:
v := kv.expireFunc()
if v < 0 {
v = -1 * v
}
if v > 0 && v <= kv.expirationInterval {
interval = (2*interval + v) / 3 // good enough history
}
if interval <= 0 {
interval = time.Millisecond
}
expireTime.Reset(interval)
}
}
}
func (kv *store) expireFunc() time.Duration {
kv.mx.Lock()
defer kv.mx.Unlock()
var interval time.Duration
if len(kv.heap) == 0 {
return interval
}
expired := make(map[string]interface{})
c := -1
for {
if len(kv.heap) == 0 {
break
}
c++
if c >= len(kv.heap) {
break
}
last := kv.heap[0]
entry, ok := kv.kv[last.key]
if !ok {
timeheapPop(&kv.heap)
continue
}
if !last.expired() {
interval = last.expiresAt.Sub(time.Now())
if interval < 0 {
interval = last.expiresAfter
}
break
}
last = timeheapPop(&kv.heap)
if ok {
expired[last.key] = entry.value
}
}
REVAL:
for k := range expired {
newVal, ok := kv.kv[k]
if !ok ||
newVal.timeout == nil ||
!newVal.expired() {
delete(expired, k)
goto REVAL
}
delete(kv.kv, k)
}
go notifyExpirations(expired, kv.onExpire)
if interval == 0 && len(kv.heap) > 0 {
last := kv.heap[0]
interval = last.expiresAt.Sub(time.Now())
if interval < 0 {
interval = last.expiresAfter
}
}
return interval
}
func notifyExpirations(
expired map[string]interface{},
onExpire func(k string, v interface{})) {
if onExpire == nil {
return
}
for k, v := range expired {
k, v := k, v
try(func() error {
onExpire(k, v)
return nil
})
}
}
//-----------------------------------------------------------------------------
// errors
var (
ErrCASCond = errorf("CAS COND FAILED")
)
//-----------------------------------------------------------------------------
type sentinelErr string
func (v sentinelErr) Error() string { return string(v) }
func errorf(format string, a ...interface{}) error {
return sentinelErr(fmt.Sprintf(format, a...))
}
//-----------------------------------------------------------------------------