-
Notifications
You must be signed in to change notification settings - Fork 0
/
listcache.go
379 lines (325 loc) · 8.7 KB
/
listcache.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
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
package resp2
import (
"bytes"
"context"
"fmt"
"sync"
"time"
"github.com/gomodule/redigo/redis"
lru "github.com/hashicorp/golang-lru"
logger "github.com/iwanbk/rimcu/logger"
"github.com/rs/xid"
"github.com/shamaton/msgpack"
)
// ListCache represents in memory cache of redis lists data type with RESP2 protocol
//
// the sync mechanism is using a kind of oplog
// update list:
// - update will always go to server.
// - send listNotif (cmd, key, arg)
// - after sending update command, the in mem cache will be marked as dirty
//
// read list:
// - read ops always go to in mem cache except it marked as dirty
//
// dirty in mem cache
// - in mem cache marked as dirty after it modified the respective key
// it will be marked as clean when it receives notification of the respective operation
// - when in dirty state, all ops of this key will be buffered
// - the buffer will be executed when it receives notification of the respective operation
type ListCache struct {
pool *redis.Pool
clientID []byte
cc *lru.Cache
opIDGen opIDGenerator
// lua scripts
luaRpush *redis.Script //rpush
luaLpop *redis.Script //rpush
logger logger.Logger
}
// ListCacheConfig defines configuration of ListCache type
type ListCacheConfig struct {
Logger logger.Logger
Size int
ClientID []byte
opIDGen opIDGenerator
}
// NewListCache creates new list cache with RESP2 protocol
func NewListCache(pool *redis.Pool, cfg ListCacheConfig) (*ListCache, error) {
if cfg.Size <= 0 {
cfg.Size = 1000
}
if cfg.ClientID == nil {
cfg.ClientID = xid.New().Bytes()
}
if cfg.Logger == nil {
cfg.Logger = logger.NewDefault()
}
if cfg.opIDGen == nil {
cfg.opIDGen = &defaultOpIDgen{}
}
cc, err := lru.New(cfg.Size)
if err != nil {
return nil, err
}
lc := &ListCache{
cc: cc,
pool: pool,
clientID: cfg.ClientID,
logger: cfg.Logger,
opIDGen: cfg.opIDGen,
luaRpush: redis.NewScript(1, scriptRpush),
luaLpop: redis.NewScript(1, scriptLpop),
}
rns := newResp2NotifSubcriber(pool, lc.handleNotifData, lc.handleNotifDisconnect,
listChannel, cfg.Logger)
return lc, rns.runSubscriber()
}
// Rpush insert all the specified values at the tail of the list stored at key
// TODO:
// - also do LTRIM
// - accept not only one values
func (lc *ListCache) Rpush(ctx context.Context, key, val string) error {
notif := newListNotif(lc.clientID, lc.opIDGen.Generate(), listRpushCmd, key, val)
_, err := redis.String(lc.execLua(ctx, lc.luaRpush, notif, key, val))
return err
}
// Get the whole list.
//
// It gets directly from memory if the key state is not dirty
// otherwise will get from the server
func (lc *ListCache) Get(ctx context.Context, key string) ([]string, error) {
cv, ok := lc.memGet(key)
if ok && !cv.IsDirty() {
return cv.list, nil
}
data, err := lc.getFromServer(ctx, key)
if err != nil {
return nil, err
}
if cv == nil {
cv = &listCacheVal{}
lc.memSet(key, cv)
}
// set cache
cv.SetList(data)
return data, nil
}
// Lpop removes and returns the first element of the list stored at key.
//
// Lpop currently executes the command directly to the server.
func (lc *ListCache) Lpop(ctx context.Context, key string) (string, bool, error) {
notif := newListNotif(lc.clientID, lc.opIDGen.Generate(), listLpopCmd, key, "")
val, err := redis.String(lc.execLua(ctx, lc.luaLpop, notif, key))
if err != nil {
return "", false, fmt.Errorf("lpop failed: %v", err)
}
return val, true, nil
}
func (lc *ListCache) execLua(ctx context.Context, scr *redis.Script, nt *listNotif, key string, args ...interface{}) (interface{}, error) {
notifMsg, err := nt.Encode()
if err != nil {
return nil, err
}
conn, err := lc.pool.GetContext(ctx)
if err != nil {
return nil, err
}
defer conn.Close()
cv, hasCache := lc.memGet(key)
if hasCache {
cv.SetDirty(nt.OpID)
}
scrArgs := append([]interface{}{key, notifMsg}, args...)
val, err := scr.Do(conn, scrArgs...)
if err != nil && hasCache {
cv.ClearDirty(nt.OpID)
}
return val, err
}
func (lc *ListCache) getFromServer(ctx context.Context, key string) ([]string, error) {
// get ALL list data from the server
conn, err := lc.pool.GetContext(ctx)
if err != nil {
return nil, err
}
defer conn.Close()
return redis.Strings(conn.Do("LRANGE", key, 0, -1))
}
func (lc *ListCache) memGet(key string) (*listCacheVal, bool) {
entry, ok := lc.cc.Get(key)
if !ok {
return nil, false
}
return entry.(*listCacheVal), true
}
func (lc *ListCache) memSet(key string, cv *listCacheVal) {
lc.cc.Add(key, cv)
}
func (lc *ListCache) name() string {
return string(lc.clientID)
}
// listNotif represents notification of the list write operation
type listNotif struct {
ClientID []byte
Cmd string
Key string
Arg string
OpID []byte
}
func newListNotif(clientID, opID []byte, cmd, key, arg string) *listNotif {
return &listNotif{
ClientID: clientID,
Cmd: cmd,
Key: key,
Arg: arg,
OpID: opID,
}
}
func (ln *listNotif) Encode() ([]byte, error) {
return msgpack.Encode(ln)
}
func decodeListNotif(b []byte) (*listNotif, error) {
var ln listNotif
return &ln, msgpack.Decode(b, &ln)
}
func (lc *ListCache) executeNotifs(cv *listCacheVal, notifs ...*listNotif) {
for _, nt := range notifs {
lc.logger.Debugf("rimcu:[%s]op=%v `%s` to key: %v", lc.name(), string(nt.OpID), nt.Cmd, nt.Key)
switch nt.Cmd {
case listRpushCmd:
cv.pushBack(nt.Arg)
case listLpopCmd:
cv.front()
default:
lc.logger.Errorf("rimcu:[%s]unknown list notif command: %v", lc.name(), nt.Cmd)
}
}
}
// handleNotif handle raw notification from the redis
func (lc *ListCache) handleNotifData(data []byte) {
// decode notification
nt, err := decodeListNotif(data)
if err != nil {
lc.logger.Errorf("failed to decode Notif:%w", err)
return
}
// if not in our memory, ignore
cv, ok := lc.memGet(nt.Key)
if !ok {
//lc.logger.Debugf("[rimcu]%s ignore list to key: %v : key not stored in local cache", string(lc.clientID), nt.Key)
return
}
cv.mtx.Lock()
defer cv.mtx.Unlock()
// if dirty, buffer it
if cv.isDirtyNoLock() {
if !cv.canClearDirty(nt, lc.clientID) {
lc.logger.Debugf("rimcu[%s]handleNotif: key `%s` is dirty, append notif", lc.name(), nt.Key)
cv.appendNotif(nt)
return
}
// finally got the dirty opID, need to execute the buffered notif
lc.executeNotifs(cv, cv.getNotifBuffer()...)
lc.executeNotifs(cv, nt)
lc.logger.Debugf("\trimcu[%s]handleNotif: clear dirty key `%s`", lc.name(), nt.Key)
cv.clearDirty()
return
}
lc.executeNotifs(cv, nt)
}
// check if the notification can clear dirty state of this list of the given client ID
//
// TODO: maybe check for the timestampt as well
func (lcv *listCacheVal) canClearDirty(nt *listNotif, clientID []byte) bool {
if !bytes.Equal(clientID, nt.ClientID) {
return false
}
return bytes.Equal(lcv.getDirtyID(), nt.OpID)
}
func (lc *ListCache) handleNotifDisconnect() {
lc.logger.Errorf("TODO handleNotifDisconnect")
}
// listCacheVal represents in memory backing of the ListCache
type listCacheVal struct {
mtx sync.RWMutex
list []string
dirtyTs int64
dirtyID []byte
notifBuffer []*listNotif
}
func (lcv *listCacheVal) SetList(data []string) {
lcv.mtx.Lock()
lcv.list = data
lcv.mtx.Unlock()
}
func (lcv *listCacheVal) SetDirty(opsID []byte) {
lcv.mtx.Lock()
defer lcv.mtx.Unlock()
lcv.dirtyTs = time.Now().Unix()
lcv.dirtyID = opsID
}
func (lcv *listCacheVal) ClearDirty(opID []byte) {
lcv.mtx.Lock()
defer lcv.mtx.Unlock()
if !bytes.Equal(opID, lcv.getDirtyID()) {
return
}
lcv.clearDirty()
}
func (lcv *listCacheVal) IsDirty() (isDirty bool) {
lcv.mtx.RLock()
isDirty = lcv.isDirtyNoLock()
lcv.mtx.RUnlock()
return
}
func (lcv *listCacheVal) isDirtyNoLock() (isDirty bool) {
return lcv.dirtyTs != 0
}
func (lcv *listCacheVal) getDirtyID() (dirtyID []byte) {
return lcv.dirtyID
}
func (lcv *listCacheVal) clearDirty() {
lcv.dirtyTs = 0
lcv.dirtyID = nil
}
func (lcv *listCacheVal) appendNotif(nt *listNotif) {
lcv.notifBuffer = append(lcv.notifBuffer, nt)
}
func (lcv *listCacheVal) GetList() (list []string) {
lcv.mtx.RLock()
list = lcv.list
lcv.mtx.RUnlock()
return
}
func (lcv *listCacheVal) getNotifBuffer() []*listNotif {
return lcv.notifBuffer
}
func (lcv *listCacheVal) front() (string, bool) {
if len(lcv.list) == 0 {
return "", false
}
var val string
val, lcv.list = lcv.list[0], lcv.list[1:]
return val, true
}
func (lcv *listCacheVal) pushBack(val string) {
lcv.list = append(lcv.list, val)
}
const (
listChannel = "rimcu:list"
listRpushCmd = "RPUSH"
listLpopCmd = "LPOP"
)
const (
scriptRpush = `
redis.call('RPUSH', KEYS[1], ARGV[2])
redis.call('publish', 'rimcu:list', ARGV[1])
return 'OK'
`
scriptLpop = `
local val = redis.call('LPOP', KEYS[1])
redis.call('publish', 'rimcu:list', ARGV[1])
return val
`
)