-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
ephemeral_purge_tracker.go
381 lines (337 loc) · 9.58 KB
/
ephemeral_purge_tracker.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
package chat
import (
"fmt"
"log"
"strings"
"sync"
"time"
lru "github.com/hashicorp/golang-lru"
"github.com/keybase/client/go/chat/globals"
"github.com/keybase/client/go/chat/storage"
"github.com/keybase/client/go/chat/types"
"github.com/keybase/client/go/chat/utils"
"github.com/keybase/client/go/libkb"
"github.com/keybase/client/go/protocol/chat1"
"github.com/keybase/client/go/protocol/gregor1"
"github.com/keybase/go-codec/codec"
"golang.org/x/net/context"
"golang.org/x/sync/errgroup"
)
const ephemeralTrackerDiskVersion = 1
const dbKeyPrefix = "et|uid:%s|convID:"
const memCacheLRUSize = 1000
type EphemeralTracker struct {
globals.Contextified
utils.DebugLabeler
sync.Mutex
lru *lru.Cache
started bool
stopCh chan struct{}
flushLoopCh chan struct{}
eg errgroup.Group
}
var _ types.EphemeralTracker = (*EphemeralTracker)(nil)
type ephemeralTrackerMemCache struct {
isDirty bool
info chat1.EphemeralPurgeInfo
}
type ephemeralTrackerEntry struct {
StorageVersion int `codec:"v"`
Info chat1.EphemeralPurgeInfo `codec:"i"`
}
func NewEphemeralTracker(g *globals.Context) *EphemeralTracker {
nlru, err := lru.New(memCacheLRUSize)
if err != nil {
// lru.New only panics if size <= 0
log.Panicf("Could not create lru cache: %v", err)
}
return &EphemeralTracker{Contextified: globals.NewContextified(g),
DebugLabeler: utils.NewDebugLabeler(g.ExternalG(), "EphemeralTracker", false),
lru: nlru,
flushLoopCh: make(chan struct{}, 10),
}
}
func (t *EphemeralTracker) Start(ctx context.Context, uid gregor1.UID) {
defer t.Trace(ctx, nil, "Start")()
t.Lock()
defer t.Unlock()
if t.started {
return
}
t.stopCh = make(chan struct{})
t.started = true
t.eg.Go(func() error { return t.flushLoop(uid, t.stopCh) })
}
func (t *EphemeralTracker) Stop(ctx context.Context) chan struct{} {
defer t.Trace(ctx, nil, "Stop")()
t.Lock()
defer t.Unlock()
ch := make(chan struct{})
if t.started {
close(t.stopCh)
t.started = false
go func() {
_ = t.eg.Wait()
close(ch)
}()
} else {
close(ch)
}
return ch
}
func (t *EphemeralTracker) flushLoop(uid gregor1.UID, stopCh chan struct{}) error {
ctx := context.Background()
for {
select {
case <-t.flushLoopCh:
if err := t.Flush(ctx, uid); err != nil {
t.Debug(ctx, "unable to flush: %v", err)
}
case <-t.G().Clock().After(30 * time.Second):
if err := t.Flush(ctx, uid); err != nil {
t.Debug(ctx, "unable to flush: %v", err)
}
case <-stopCh:
if err := t.Flush(ctx, uid); err != nil {
t.Debug(ctx, "unable to flush: %v", err)
}
return nil
}
}
}
func (t *EphemeralTracker) key(uid gregor1.UID, convID chat1.ConversationID) string {
return fmt.Sprintf(dbKeyPrefix, uid) + convID.String()
}
func (t *EphemeralTracker) dbKey(uid gregor1.UID, convID chat1.ConversationID) libkb.DbKey {
return libkb.DbKey{
Typ: libkb.DBChatEphemeralTracker,
Key: t.key(uid, convID),
}
}
func (t *EphemeralTracker) get(ctx context.Context, uid gregor1.UID, convID chat1.ConversationID) (*ephemeralTrackerMemCache, error) {
memKey := t.key(uid, convID)
data, found := t.lru.Get(memKey)
if found {
cache, ok := data.(ephemeralTrackerMemCache)
if ok {
return &cache, nil
}
}
dbKey := t.dbKey(uid, convID)
raw, found, err := t.G().LocalChatDb.GetRaw(dbKey)
if err != nil {
return nil, err
} else if !found {
return nil, nil
}
var dbRes ephemeralTrackerEntry
if err := decode(raw, &dbRes); err != nil {
return nil, err
}
switch dbRes.StorageVersion {
case ephemeralTrackerDiskVersion:
cache := ephemeralTrackerMemCache{info: dbRes.Info}
t.lru.Add(memKey, cache)
return &cache, nil
default:
// ignore other versions
return nil, nil
}
}
func (t *EphemeralTracker) put(ctx context.Context, uid gregor1.UID, convID chat1.ConversationID, info chat1.EphemeralPurgeInfo) (err error) {
t.lru.Add(t.key(uid, convID), ephemeralTrackerMemCache{
info: info,
isDirty: true,
})
return nil
}
func (t *EphemeralTracker) Flush(ctx context.Context, uid gregor1.UID) error {
t.Lock()
defer t.Unlock()
return t.flushLocked(ctx, uid)
}
func (t *EphemeralTracker) flushLocked(ctx context.Context, uid gregor1.UID) error {
for _, key := range t.lru.Keys() {
rawCache, found := t.lru.Get(key)
cache, ok := rawCache.(ephemeralTrackerMemCache)
if !found || !ok || !cache.isDirty {
continue
}
var entry ephemeralTrackerEntry
entry.StorageVersion = ephemeralTrackerDiskVersion
entry.Info = cache.info
data, err := encode(entry)
if err != nil {
return err
}
dbKey := t.dbKey(uid, cache.info.ConvID)
if err := t.G().LocalChatDb.PutRaw(dbKey, data); err != nil {
return err
}
cache.isDirty = false
t.lru.Add(key, cache)
}
return nil
}
func (t *EphemeralTracker) GetPurgeInfo(ctx context.Context,
uid gregor1.UID, convID chat1.ConversationID) (chat1.EphemeralPurgeInfo, error) {
defer t.Trace(ctx, nil, "GetPurgeInfo")()
t.Lock()
defer t.Unlock()
cache, err := t.get(ctx, uid, convID)
if err != nil {
return chat1.EphemeralPurgeInfo{}, err
} else if cache == nil {
return chat1.EphemeralPurgeInfo{}, storage.MissError{}
}
return cache.info, nil
}
func (t *EphemeralTracker) getAllKeysLocked(ctx context.Context, uid gregor1.UID) (keys []libkb.DbKey, err error) {
innerKeyPrefix := fmt.Sprintf(dbKeyPrefix, uid)
prefix := libkb.DbKey{
Typ: libkb.DBChatEphemeralTracker,
Key: innerKeyPrefix,
}.ToBytes()
leveldb, ok := t.G().LocalChatDb.GetEngine().(*libkb.LevelDb)
if !ok {
return nil, fmt.Errorf("could not get leveldb")
}
dbKeys, err := leveldb.KeysWithPrefixes(prefix)
if err != nil {
return nil, err
}
keys = make([]libkb.DbKey, 0, len(dbKeys))
for dbKey := range dbKeys {
if dbKey.Typ == libkb.DBChatEphemeralTracker && strings.HasPrefix(dbKey.Key, innerKeyPrefix) {
keys = append(keys, dbKey)
}
}
return keys, nil
}
func (t *EphemeralTracker) GetAllPurgeInfo(ctx context.Context, uid gregor1.UID) ([]chat1.EphemeralPurgeInfo, error) {
defer t.Trace(ctx, nil, "GetAllPurgeInfo")()
t.Lock()
defer t.Unlock()
if err := t.flushLocked(ctx, uid); err != nil {
return nil, err
}
dbKeys, err := t.getAllKeysLocked(ctx, uid)
if err != nil {
return nil, err
}
allPurgeInfo := make([]chat1.EphemeralPurgeInfo, 0, len(dbKeys))
innerKeyPrefix := fmt.Sprintf(dbKeyPrefix, uid)
for _, dbKey := range dbKeys {
convID, err := chat1.MakeConvID(dbKey.Key[len(innerKeyPrefix):])
if err != nil {
return nil, err
}
cache, err := t.get(ctx, uid, convID)
if err != nil {
return nil, err
} else if cache == nil {
continue
}
allPurgeInfo = append(allPurgeInfo, cache.info)
}
return allPurgeInfo, nil
}
func (t *EphemeralTracker) SetPurgeInfo(ctx context.Context,
convID chat1.ConversationID, uid gregor1.UID, purgeInfo *chat1.EphemeralPurgeInfo) (err error) {
t.Lock()
defer t.Unlock()
if purgeInfo == nil {
return nil
}
if err = t.put(ctx, uid, convID, *purgeInfo); err != nil {
return err
}
// Let our background monitor know about the new info.
return t.G().EphemeralPurger.Queue(ctx, *purgeInfo)
}
// When we are filtering new messages coming in/out of storage, we maybe update
// if they tell us about something older we should be purging.
func (t *EphemeralTracker) MaybeUpdatePurgeInfo(ctx context.Context,
convID chat1.ConversationID, uid gregor1.UID, purgeInfo *chat1.EphemeralPurgeInfo) (err error) {
t.Lock()
defer t.Unlock()
if purgeInfo == nil || purgeInfo.IsNil() {
return nil
}
cache, err := t.get(ctx, uid, convID)
if err != nil {
return err
}
if cache != nil { // Throw away our update info if what we already have is more restrictive.
if cache.info.IsActive {
purgeInfo.IsActive = true
}
if purgeInfo.MinUnexplodedID == 0 || cache.info.MinUnexplodedID < purgeInfo.MinUnexplodedID {
purgeInfo.MinUnexplodedID = cache.info.MinUnexplodedID
}
if purgeInfo.NextPurgeTime == 0 || (cache.info.NextPurgeTime != 0 && cache.info.NextPurgeTime < purgeInfo.NextPurgeTime) {
purgeInfo.NextPurgeTime = cache.info.NextPurgeTime
}
}
if cache != nil && purgeInfo.Eq(cache.info) {
return nil
}
if err = t.put(ctx, uid, convID, *purgeInfo); err != nil {
return nil
}
return t.G().EphemeralPurger.Queue(ctx, *purgeInfo)
}
func (t *EphemeralTracker) InactivatePurgeInfo(ctx context.Context,
convID chat1.ConversationID, uid gregor1.UID) (err error) {
t.Lock()
defer t.Unlock()
cache, err := t.get(ctx, uid, convID)
if err != nil {
return err
} else if cache == nil {
return nil
}
cache.info.IsActive = false
if err = t.put(ctx, uid, convID, cache.info); err != nil {
return err
}
// Let our background monitor know about the new info.
return t.G().EphemeralPurger.Queue(ctx, cache.info)
}
func (t *EphemeralTracker) clearMemory() {
t.lru.Purge()
}
func (t *EphemeralTracker) Clear(ctx context.Context, convID chat1.ConversationID, uid gregor1.UID) (err error) {
defer t.Trace(ctx, &err, "Clear")()
t.Lock()
defer t.Unlock()
t.lru.Remove(t.key(uid, convID))
dbKey := t.dbKey(uid, convID)
return t.G().LocalChatDb.Delete(dbKey)
}
func (t *EphemeralTracker) OnDbNuke(mctx libkb.MetaContext) error {
t.clearMemory()
return nil
}
func (t *EphemeralTracker) OnLogout(mctx libkb.MetaContext) error {
select {
case t.flushLoopCh <- struct{}{}:
default:
}
return nil
}
func decode(data []byte, res interface{}) error {
mh := codec.MsgpackHandle{WriteExt: true}
dec := codec.NewDecoderBytes(data, &mh)
err := dec.Decode(res)
return err
}
func encode(input interface{}) ([]byte, error) {
mh := codec.MsgpackHandle{WriteExt: true}
var data []byte
enc := codec.NewEncoderBytes(&data, &mh)
if err := enc.Encode(input); err != nil {
return nil, err
}
return data, nil
}