This repository has been archived by the owner on Feb 17, 2022. It is now read-only.
/
storage.go
464 lines (413 loc) · 11.8 KB
/
storage.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
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
// Copyright 2018 Schibsted
package main
import (
"context"
"errors"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/schibsted/sebase/plog/internal/pkg/plogproto"
"github.com/schibsted/sebase/plog/pkg/plogd"
)
const (
interruptedKey = "@interrupted"
)
type smCode int
const (
smClose smCode = iota
smMsg
smLastRef
)
type storageMessage struct {
code smCode
key string
value interface{}
startTimestamp time.Time
}
// Storage represents the stored data for a single client program.
type Storage struct {
Prog string
State map[string]interface{}
storageSessions map[plogproto.CtxType]*storageSession
channelQueue chan progChannel
sendState chan string
cbState chan func(map[string]interface{})
}
func progCtx(prog string) context.Context {
return plogd.ContextWithProg(context.Background(), prog)
}
// DataStorage contains the full set of data stored.
type DataStorage struct {
lock sync.Mutex
ProgStore map[string]*Storage
ProgGroup sync.WaitGroup
Output plogd.OutputWriter
dumpEmpty bool
// For tests
testStatePing chan struct{}
}
/*
* For storing data, we build up a hierarchy of open sessions.
* There's a goroutine at each level which accepts input for that
* level and keeps a reference to the parent object.
* Once both the session and all sub objects are closed, the object
* is sent to the parent and the parent reference released.
*/
type storageSession struct {
channel chan storageMessage
refs uint32
confKey string
isState bool
}
var smPool = make(chan chan storageMessage, 256)
func newStorageSession(ck string, isState bool) *storageSession {
select {
case ch := <-smPool:
return &storageSession{ch, 1, ck, isState}
default:
return &storageSession{make(chan storageMessage, 256), 1, ck, isState}
}
}
func retainStorageSession(sess *storageSession) (*storageSession, uint32) {
refs := atomic.AddUint32(&sess.refs, 1)
return sess, refs
}
func releaseStorageSession(sess *storageSession) {
if atomic.AddUint32(&sess.refs, ^uint32(0)) == 0 {
sess.channel <- storageMessage{code: smClose}
}
}
func reclaimSessionChannel(ch chan storageMessage) {
select {
case smPool <- ch:
default:
}
}
func (sess *storageSession) Write(key string, value interface{}) error {
sess.channel <- storageMessage{smMsg, key, value, time.Time{}}
return nil
}
func (sess *storageSession) Close(proper, lastRef bool) {
if !proper {
sess.channel <- storageMessage{smMsg, interruptedKey, true, time.Time{}}
}
if lastRef {
sess.channel <- storageMessage{code: smLastRef}
}
releaseStorageSession(sess)
}
func (sess *storageSession) ConfKey() string {
return sess.confKey
}
/* dict session */
type dictSession struct {
storageSession
parentSession *storageSession
startTimestamp time.Time
key string
dict map[string]interface{}
}
func dictStoreHandler(sess *dictSession) {
for {
inMsg := <-sess.storageSession.channel
if inMsg.code == smClose {
break
}
if inMsg.code == smLastRef {
sess.parentSession.channel <- storageMessage{smMsg, sess.key, nil, sess.startTimestamp}
} else if sess.isState {
parentMessage := map[string]interface{}{inMsg.key: inMsg.value}
sess.parentSession.channel <- storageMessage{smMsg, sess.key, parentMessage, sess.startTimestamp}
} else {
sess.dict[inMsg.key] = inMsg.value
}
}
reclaimSessionChannel(sess.storageSession.channel)
if !sess.isState {
sess.parentSession.channel <- storageMessage{smMsg, sess.key, sess.dict, sess.startTimestamp}
}
releaseStorageSession(sess.parentSession)
}
// OpenDict creates a new dictionary storage session.
func (sess *storageSession) OpenDict(key string) (SessionOutput, error) {
ret := &dictSession{}
ret.storageSession = *newStorageSession(sess.confKey+"."+key, sess.isState)
ret.parentSession, _ = retainStorageSession(sess)
ret.startTimestamp = time.Now()
ret.key = key
ret.dict = make(map[string]interface{})
go dictStoreHandler(ret)
return ret, nil
}
/* list session */
type listSession struct {
storageSession
parentSession *storageSession
startTimestamp time.Time
key string
list []interface{}
dicts bool
}
func listStoreHandler(sess *listSession) {
for {
inMsg := <-sess.storageSession.channel
if inMsg.code == smClose {
break
}
if inMsg.code != smMsg {
continue
}
if sess.dicts {
sess.list = append(sess.list, map[string]interface{}{inMsg.key: inMsg.value})
} else if inMsg.key != interruptedKey {
sess.list = append(sess.list, inMsg.value)
}
}
reclaimSessionChannel(sess.storageSession.channel)
sess.parentSession.channel <- storageMessage{smMsg, sess.key, sess.list, sess.startTimestamp}
releaseStorageSession(sess.parentSession)
}
// OpenList creates a new list storage session.
func (sess *storageSession) OpenList(key string, dicts bool) (SessionOutput, error) {
ret := &listSession{}
ret.storageSession = *newStorageSession(sess.confKey+"."+key, sess.isState)
ret.parentSession, _ = retainStorageSession(sess)
ret.startTimestamp = time.Now()
ret.key = key
ret.dicts = dicts
ret.list = make([]interface{}, 0, 10)
go listStoreHandler(ret)
return ret, nil
}
/* root session */
func sendState(ctx context.Context, dataStore *DataStorage, prog, keyPath string, value interface{}) {
if value == nil {
return
}
ks := strings.Split(keyPath, ".")
for i := len(ks) - 1; i >= 0; i-- {
value = map[string]interface{}{ks[i]: value}
}
outMsg := plogd.LogMessage{time.Now(), prog, "state", value, nil, "", nil}
dataStore.Output.WriteMessage(ctx, outMsg)
}
func updateState(dataStore *DataStorage, progStore *Storage, node map[string]interface{}, stype plogproto.CtxType, key string, value interface{}, confKey string) {
if value == nil {
delete(node, key)
return
}
switch value := value.(type) {
case map[string]interface{}:
m, ismap := node[key].(map[string]interface{})
if !ismap {
m = make(map[string]interface{})
node[key] = m
}
for k, v := range value {
updateState(dataStore, progStore, m, stype, k, v, confKey+"."+k)
}
case int:
if stype == plogproto.CtxType_count {
if f, ok := node[key].(int); ok {
value += f
}
if value == 0 {
/* Recurse with a delete. */
updateState(dataStore, progStore, node, stype, key, nil, confKey)
return
}
}
node[key] = value
default:
node[key] = value
}
}
func dumpState(ctx context.Context, dataStore *DataStorage, progStore *Storage) {
if len(progStore.State) > 0 || dataStore.dumpEmpty {
outMsg := plogd.LogMessage{time.Now(), progStore.Prog, "state", progStore.State, nil, "", nil}
dataStore.Output.WriteMessage(ctx, outMsg)
}
}
func sendForKeyPath(ctx context.Context, dataStore *DataStorage, progStore *Storage, keyPath string) {
node := progStore.State
ismap := true
var v interface{}
for _, key := range strings.Split(keyPath, ".") {
if !ismap {
return
}
v = node[key]
node, ismap = v.(map[string]interface{})
}
sendState(ctx, dataStore, progStore.Prog, keyPath, v)
}
type progChannel struct {
key plogproto.CtxType
channel chan storageMessage
}
type muxMessage struct {
stype plogproto.CtxType
channel chan storageMessage
storageMessage
}
func progStoreMuxer(out chan<- muxMessage, ch progChannel) {
for {
msg := <-ch.channel
out <- muxMessage{ch.key, ch.channel, msg}
if msg.code == smClose {
break
}
}
}
func progStoreHandler(dataStore *DataStorage, progStore *Storage) {
muxCh := make(chan muxMessage)
chs := make(map[plogproto.CtxType]chan storageMessage)
ctx, cancel := context.WithCancel(progCtx(progStore.Prog))
defer dataStore.ProgGroup.Done()
defer cancel()
for {
dataStore.lock.Lock()
select {
case ch := <-progStore.channelQueue:
chs[ch.key] = ch.channel
go progStoreMuxer(muxCh, ch)
default:
if len(chs) == 0 {
delete(dataStore.ProgStore, progStore.Prog)
}
}
dataStore.lock.Unlock()
if len(chs) == 0 {
// Depleted even under lock.
break
}
for len(chs) > 0 {
select {
case ch := <-progStore.channelQueue:
chs[ch.key] = ch.channel
go progStoreMuxer(muxCh, ch)
case confKey := <-progStore.sendState:
if confKey == "" {
dumpState(ctx, dataStore, progStore)
} else {
sendForKeyPath(ctx, dataStore, progStore, confKey)
}
case cb := <-progStore.cbState:
cb(progStore.State)
case inMsg := <-muxCh:
if inMsg.code == smClose {
reclaimSessionChannel(inMsg.channel)
if chs[inMsg.stype] == inMsg.channel {
// Might've been replaced, only delete if latest.
delete(chs, inMsg.stype)
}
continue
}
if inMsg.code == smLastRef {
continue
}
if inMsg.stype != plogproto.CtxType_log {
updateState(dataStore, progStore, progStore.State, inMsg.stype, inMsg.key, inMsg.value, inMsg.key)
if dataStore.testStatePing != nil {
close(dataStore.testStatePing)
}
} else {
ts := &inMsg.startTimestamp
if ts.IsZero() {
ts = nil
}
outMsg := plogd.LogMessage{time.Now(), progStore.Prog, inMsg.key, inMsg.value, ts, "", nil}
dataStore.Output.WriteMessage(ctx, outMsg)
}
}
}
}
// Make sure there aren't any queued state callbacks before we disintegrate.
cbState:
for {
select {
case cb := <-progStore.cbState:
cb(progStore.State)
default:
break cbState
}
}
dumpState(ctx, dataStore, progStore)
}
func (store *DataStorage) findOutput(prog string, stype plogproto.CtxType) (SessionOutput, error) {
store.lock.Lock()
defer store.lock.Unlock()
if store.ProgStore == nil {
store.ProgStore = make(map[string]*Storage)
}
progStore := store.ProgStore[prog]
var ssess *storageSession
if progStore == nil {
progStore = new(Storage)
progStore.Prog = prog
progStore.State = make(map[string]interface{})
progStore.sendState = make(chan string, 256)
progStore.storageSessions = make(map[plogproto.CtxType]*storageSession)
progStore.channelQueue = make(chan progChannel, 5)
progStore.cbState = make(chan func(map[string]interface{}), 1)
store.ProgGroup.Add(1)
go progStoreHandler(store, progStore)
store.ProgStore[prog] = progStore
} else {
ssess = progStore.storageSessions[stype]
if ssess != nil {
_, refs := retainStorageSession(ssess)
// release might've dropped the refs to 0 temporarily and thus closed the
// channel. Reopen if so.
if refs == 1 {
ssess = nil
}
}
}
if ssess == nil {
ssess = newStorageSession(prog, stype != plogproto.CtxType_log)
select {
case progStore.channelQueue <- progChannel{stype, ssess.channel}:
break
default:
// This should be really really unlikely, but theoretically possible.
// When buffer size was 1 it did sometimes happen in unit tests.
// Easy solution is to abort.
releaseStorageSession(ssess)
return nil, ErrorTooManyConcurrentRequests
}
progStore.storageSessions[stype] = ssess
}
return ssess, nil
}
var (
// ErrorProgNotFound is used when the requested prog is not in use.
ErrorProgNotFound = errors.New("Program was not found")
// ErrorTooManyConcurrentRequests is used when buffers are full.
ErrorTooManyConcurrentRequests = errors.New("Too many concurrent requests")
)
// CallbackState returns true if prog exists and the callback was queued. The
// callback will be called. Returns false if the callback will not be called,
// err will be one of:
// ErrorProgNotFound, ErrorTooManyConcurrentRequests
func (store *DataStorage) CallbackState(prog string, cb func(map[string]interface{})) (bool, error) {
store.lock.Lock()
defer store.lock.Unlock()
progStore := store.ProgStore[prog]
if progStore == nil {
return false, ErrorProgNotFound
}
// Make sure to not hang here while we're holding the lock.
select {
case progStore.cbState <- cb:
return true, nil
default:
return false, ErrorTooManyConcurrentRequests
}
}
// Close waits for all sessions to close.
func (store *DataStorage) Close() error {
store.ProgGroup.Wait()
return nil
}