/
ephemeral_purger.go
325 lines (277 loc) · 8.39 KB
/
ephemeral_purger.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
package chat
import (
"container/heap"
"context"
"fmt"
"sync"
"time"
"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/protocol/chat1"
"github.com/keybase/client/go/protocol/gregor1"
"github.com/keybase/clockwork"
)
// An queueItem is something we manage in a priority queue.
type queueItem struct {
purgeInfo chat1.EphemeralPurgeInfo
// The index is needed by `update` and is maintained by the heap.Interface methods.
index int // The index of the queueItem in the heap.
}
// A priorityQueue implements heap.Interface and holds queueItems.
// We also keep a map of queueItems for easy item updates
type priorityQueue struct {
sync.RWMutex
queue []*queueItem
// convID -> *queueItem
itemMap map[string]*queueItem
}
func newPriorityQueue() *priorityQueue {
return &priorityQueue{
queue: []*queueItem{},
itemMap: make(map[string]*queueItem),
}
}
func (pq *priorityQueue) Len() int {
pq.RLock()
defer pq.RUnlock()
return len(pq.queue)
}
func (pq *priorityQueue) Less(i, j int) bool {
pq.RLock()
defer pq.RUnlock()
return pq.queue[i].purgeInfo.NextPurgeTime < pq.queue[j].purgeInfo.NextPurgeTime
}
func (pq *priorityQueue) Swap(i, j int) {
pq.Lock()
defer pq.Unlock()
pq.queue[i], pq.queue[j] = pq.queue[j], pq.queue[i]
pq.queue[i].index = i
pq.queue[j].index = j
}
// Note this method should not be used directly since we only want each
// conversation to appear once in the heap. Use
// `BackgroundEphemeralPurger.update` instead since it handles this as
// intended.
func (pq *priorityQueue) Push(x interface{}) {
pq.Lock()
defer pq.Unlock()
item := x.(*queueItem)
item.index = len(pq.queue)
pq.queue = append(pq.queue, item)
pq.itemMap[item.purgeInfo.ConvID.String()] = item
}
func (pq *priorityQueue) Pop() interface{} {
pq.Lock()
defer pq.Unlock()
n := len(pq.queue)
item := pq.queue[n-1]
item.index = -1 // for safety
pq.queue = pq.queue[:n-1]
delete(pq.itemMap, item.purgeInfo.ConvID.String())
return item
}
func (pq *priorityQueue) Peek() *queueItem {
pq.RLock()
defer pq.RUnlock()
if len(pq.queue) == 0 {
return nil
}
return pq.queue[0]
}
type BackgroundEphemeralPurger struct {
globals.Contextified
utils.DebugLabeler
// used to prevent concurrent calls to Start/Stop
lock sync.Mutex
// used to prevent concurrent modifications to `pq`
queueLock sync.Mutex
uid gregor1.UID
looping bool
pq *priorityQueue
stopCh chan chan struct{}
storage *storage.Storage
delay time.Duration
clock clockwork.Clock
purgeTimer *time.Timer
}
var _ types.EphemeralPurger = (*BackgroundEphemeralPurger)(nil)
func NewBackgroundEphemeralPurger(g *globals.Context, storage *storage.Storage) *BackgroundEphemeralPurger {
return &BackgroundEphemeralPurger{
Contextified: globals.NewContextified(g),
DebugLabeler: utils.NewDebugLabeler(g.GetLog(), "BackgroundEphemeralPurger", false),
storage: storage,
stopCh: make(chan chan struct{}),
delay: 500 * time.Millisecond,
clock: clockwork.NewRealClock(),
}
}
func (b *BackgroundEphemeralPurger) SetClock(clock clockwork.Clock) {
b.clock = clock
}
func (b *BackgroundEphemeralPurger) Start(ctx context.Context, uid gregor1.UID) {
b.Debug(ctx, "Start")
b.lock.Lock()
defer b.lock.Unlock()
b.cleanupTimers()
if b.looping {
b.stopCh <- make(chan struct{})
// We may get a call to Start/Stop before `loop()` can grab the lock
// reset this to false so we just reset it here.
b.looping = false
}
b.uid = uid
b.initQueue(ctx)
// Immediately fire to queue any purges we picked up during initQueue
b.purgeTimer = time.NewTimer(0)
go b.loop()
}
func (b *BackgroundEphemeralPurger) Stop(ctx context.Context) chan struct{} {
b.Debug(ctx, "Stop")
b.lock.Lock()
defer b.lock.Unlock()
b.cleanupTimers()
ch := make(chan struct{})
if b.looping {
b.stopCh <- ch
// We may get a call to Start/Stop before `loop()` can grab the lock
// reset this to false so we just reset it here.
b.looping = false
} else {
close(ch)
}
return ch
}
func (b *BackgroundEphemeralPurger) cleanupTimers() {
if b.purgeTimer != nil {
b.purgeTimer.Stop()
}
}
func (b *BackgroundEphemeralPurger) Queue(ctx context.Context, purgeInfo chat1.EphemeralPurgeInfo) error {
b.queueLock.Lock()
defer b.queueLock.Unlock()
if b.pq == nil {
return fmt.Errorf("Must call Start() before adding to the Queue")
}
// We only keep active items in the queue.
if !purgeInfo.IsActive {
return nil
}
// If we are starting the queue or get an earlier expiration time, reset or start the timer
head := b.pq.Peek()
if head == nil || purgeInfo.NextPurgeTime < head.purgeInfo.NextPurgeTime {
b.resetTimer(ctx, purgeInfo)
}
b.updateQueue(purgeInfo)
b.Debug(ctx, "Queue purgeInfo: %v, head: %+v, looping: %v, len(queue): %v",
purgeInfo, head, b.looping, len(b.pq.queue))
// Sanity check to force our timer to fire if it hasn't for some reason.
head = b.pq.Peek()
if head.purgeInfo.NextPurgeTime.Time().Before(b.clock.Now()) {
b.Debug(ctx, "Queue resetting timer, head is in the past.")
b.resetTimer(ctx, head.purgeInfo)
}
return nil
}
// Read all purgeInfo from disk and startup our queue.
func (b *BackgroundEphemeralPurger) initQueue(ctx context.Context) {
b.queueLock.Lock()
defer b.queueLock.Unlock()
// Create a new queue
b.pq = newPriorityQueue()
heap.Init(b.pq)
allPurgeInfo, err := b.storage.GetAllPurgeInfo(ctx, b.uid)
if err != nil {
b.Debug(ctx, "unable to get purgeInfo: %v", allPurgeInfo)
}
for _, purgeInfo := range allPurgeInfo {
if purgeInfo.IsActive {
b.updateQueue(purgeInfo)
}
}
}
func (b *BackgroundEphemeralPurger) updateQueue(purgeInfo chat1.EphemeralPurgeInfo) {
item, ok := b.pq.itemMap[purgeInfo.ConvID.String()]
if ok {
item.purgeInfo = purgeInfo
heap.Fix(b.pq, item.index)
} else {
heap.Push(b.pq, &queueItem{purgeInfo: purgeInfo})
}
}
// This runs when we are waiting to run a job but will shut itself down if we
// have no work.
func (b *BackgroundEphemeralPurger) loop() {
bgctx := context.Background()
b.lock.Lock()
b.looping = true
b.lock.Unlock()
for {
select {
case <-b.purgeTimer.C:
b.queueLock.Lock()
b.queuePurges(bgctx)
b.queueLock.Unlock()
case ch := <-b.stopCh: // caller will reset looping=false
b.Debug(bgctx, "loop: shutting down for %s", b.uid)
close(ch)
return
}
}
}
// Send any conversations that need an ephemeral message purged to the
// convLoader. We reset our timer with the next minimum time (if any) returning
// if the work loop should stop or not.
func (b *BackgroundEphemeralPurger) queuePurges(ctx context.Context) bool {
b.Debug(ctx, "queuePurges")
i := 0
// Peek into the queue for any expired convs
for _, item := range b.pq.queue {
purgeInfo := item.purgeInfo
now := b.clock.Now()
nextPurgeTime := purgeInfo.NextPurgeTime.Time()
if nextPurgeTime.Before(now) || nextPurgeTime.Equal(now) {
job := types.NewConvLoaderJob(purgeInfo.ConvID, &chat1.Pagination{},
types.ConvLoaderPriorityHigh, newConvLoaderEphemeralPurgeHook(b.G(), b.uid, &purgeInfo))
if err := b.G().ConvLoader.Queue(ctx, job); err != nil {
b.Debug(ctx, "convLoader Queue error %s", err)
}
// Don't spam out to the convloader
if i > 0 {
b.clock.Sleep(b.delay)
}
i++
} else {
break
}
}
// Maintain the queue and pop off any items we just sent off for purging
for i > 0 {
heap.Pop(b.pq)
i--
}
nextItem := b.pq.Peek()
if nextItem == nil {
if b.purgeTimer != nil {
b.purgeTimer.Stop()
}
return true
}
// Reset our time for the next min item of the queue.
b.resetTimer(ctx, nextItem.purgeInfo)
return false
}
func (b *BackgroundEphemeralPurger) resetTimer(ctx context.Context, purgeInfo chat1.EphemeralPurgeInfo) {
duration := purgeInfo.NextPurgeTime.Time().Sub(b.clock.Now())
b.Debug(ctx, "resetTimer nextPurgeTime: %v, now: %v, duration: %v", purgeInfo.NextPurgeTime.Time(), b.clock.Now(), duration)
b.purgeTimer.Stop()
b.purgeTimer.Reset(duration)
}
func newConvLoaderEphemeralPurgeHook(g *globals.Context, uid gregor1.UID, purgeInfo *chat1.EphemeralPurgeInfo) func(ctx context.Context, tv chat1.ThreadView, job types.ConvLoaderJob) {
return func(ctx context.Context, tv chat1.ThreadView, job types.ConvLoaderJob) {
if _, _, err := g.ConvSource.EphemeralPurge(ctx, job.ConvID, uid, purgeInfo); err != nil {
g.GetLog().CDebugf(ctx, "ephemeralPurge: %s", err)
}
}
}