This repository has been archived by the owner on Feb 12, 2019. It is now read-only.
/
favorites.go
382 lines (343 loc) · 9.15 KB
/
favorites.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
// Copyright 2016 Keybase Inc. All rights reserved.
// Use of this source code is governed by a BSD
// license that can be found in the LICENSE file.
package libkbfs
import (
"github.com/keybase/client/go/libkb"
"os"
"strings"
"sync"
"time"
"github.com/keybase/client/go/protocol/keybase1"
"github.com/keybase/kbfs/kbfssync"
"github.com/keybase/kbfs/tlf"
"golang.org/x/net/context"
)
const (
disableFavoritesEnvVar = "KEYBASE_DISABLE_FAVORITES"
favoritesCacheExpirationTime = time.Hour * 24 * 7 // one week
)
type favToAdd struct {
Favorite
// created, if set to true, indicates that this is the first time the TLF has
// ever existed. It is only used when adding the TLF to favorites
created bool
}
func (f favToAdd) ToKBFolder() keybase1.Folder {
return f.Favorite.ToKBFolder(f.created)
}
// favReq represents a request to access the logged-in user's
// favorites list. A single request can do one or more of the
// following: refresh the current cached list, add a favorite, remove
// a favorite, and get all the favorites. When the request is done,
// the resulting error (or nil) is sent over the done channel. The
// given ctx is used for all network operations.
type favReq struct {
// Request types
refresh bool
toAdd []favToAdd
toDel []Favorite
favs chan<- []Favorite
// Closed when the request is done.
done chan struct{}
// Set before done is closed
err error
// Context
ctx context.Context
}
// Favorites manages a user's favorite list.
type Favorites struct {
config Config
disabled bool
// Channels for interacting with the favorites cache
reqChan chan *favReq
wg kbfssync.RepeatedWaitGroup
// cache tracks the favorites for this user, that we know about.
// It may not be consistent with the server's view of the user's
// favorites list, if other devices have modified the list since
// the last refresh.
cache map[Favorite]bool
cacheExpireTime time.Time
inFlightLock sync.Mutex
inFlightAdds map[favToAdd]*favReq
muShutdown sync.RWMutex
shutdown bool
}
func newFavoritesWithChan(config Config, reqChan chan *favReq) *Favorites {
disableVal := strings.ToLower(os.Getenv(disableFavoritesEnvVar))
if len(disableVal) > 0 && disableVal != "0" && disableVal != "false" &&
disableVal != "no" {
config.MakeLogger("").CDebugf(nil,
"Disable favorites due to env var %s=%s",
disableFavoritesEnvVar, disableVal)
return &Favorites{
config: config,
disabled: true,
}
}
f := &Favorites{
config: config,
reqChan: reqChan,
inFlightAdds: make(map[favToAdd]*favReq),
}
go f.loop()
return f
}
// NewFavorites constructs a new Favorites instance.
func NewFavorites(config Config) *Favorites {
return newFavoritesWithChan(config, make(chan *favReq, 100))
}
func (f *Favorites) closeReq(req *favReq, err error) {
f.inFlightLock.Lock()
defer f.inFlightLock.Unlock()
req.err = err
close(req.done)
for _, fav := range req.toAdd {
delete(f.inFlightAdds, fav)
}
}
func (f *Favorites) handleReq(req *favReq) (err error) {
defer func() { f.closeReq(req, err) }()
kbpki := f.config.KBPKI()
// Fetch a new list if:
// * The user asked us to refresh
// * We haven't fetched it before
// * It's stale
if req.refresh || f.cache == nil || time.Now().After(f.cacheExpireTime) {
folders, err := kbpki.FavoriteList(req.ctx)
if err != nil {
if req.refresh {
// if we're supposed to refresh the cache and it's not
// working, try again in a few minutes.
in5Minutes := time.Now().Add(5 * time.Minute)
if in5Minutes.After(f.cacheExpireTime) {
f.cacheExpireTime = in5Minutes
}
}
return err
}
f.cache = make(map[Favorite]bool)
f.cacheExpireTime = libkb.ForceWallClock(time.Now()).Add(favoritesCacheExpirationTime)
for _, folder := range folders {
f.cache[*NewFavoriteFromFolder(folder)] = true
}
session, err := f.config.KBPKI().GetCurrentSession(req.ctx)
if err == nil {
// Add favorites for the current user, that cannot be deleted.
f.cache[Favorite{string(session.Name), tlf.Private}] = true
f.cache[Favorite{string(session.Name), tlf.Public}] = true
}
}
for _, fav := range req.toAdd {
if !fav.created && f.cache[fav.Favorite] {
continue
}
err := kbpki.FavoriteAdd(req.ctx, fav.ToKBFolder())
if err != nil {
f.config.MakeLogger("").CDebugf(req.ctx,
"Failure adding favorite %v: %v", fav, err)
return err
}
f.cache[fav.Favorite] = true
}
for _, fav := range req.toDel {
// Since our cache isn't necessarily up-to-date, always delete
// the favorite.
folder := fav.ToKBFolder(false)
err := kbpki.FavoriteDelete(req.ctx, folder)
if err != nil {
return err
}
delete(f.cache, fav)
}
if req.favs != nil {
favorites := make([]Favorite, 0, len(f.cache))
for fav := range f.cache {
favorites = append(favorites, fav)
}
req.favs <- favorites
}
return nil
}
func (f *Favorites) loop() {
for req := range f.reqChan {
f.handleReq(req)
f.wg.Done()
}
}
// Shutdown shuts down this Favorites instance.
func (f *Favorites) Shutdown() error {
if f.disabled {
return nil
}
f.muShutdown.Lock()
defer f.muShutdown.Unlock()
f.shutdown = true
close(f.reqChan)
return f.wg.Wait(context.Background())
}
func (f *Favorites) hasShutdown() bool {
f.muShutdown.RLock()
defer f.muShutdown.RUnlock()
return f.shutdown
}
func (f *Favorites) waitOnReq(ctx context.Context,
req *favReq) (retry bool, err error) {
select {
case <-ctx.Done():
return false, ctx.Err()
case <-req.done:
err = req.err
// If the request was canceled due to a context timeout that
// wasn't our own, try it again.
if err == context.Canceled || err == context.DeadlineExceeded {
select {
case <-ctx.Done():
return false, err
default:
return true, nil
}
}
return false, err
}
}
func (f *Favorites) sendReq(ctx context.Context, req *favReq) error {
f.wg.Add(1)
select {
case f.reqChan <- req:
case <-ctx.Done():
f.wg.Done()
err := ctx.Err()
f.closeReq(req, err)
return err
}
// With a direct sendReq call, we'll never have a shared request,
// so no need to check the retry status.
_, err := f.waitOnReq(ctx, req)
return err
}
func (f *Favorites) startOrJoinAddReq(
ctx context.Context, fav favToAdd) (req *favReq, doSend bool) {
f.inFlightLock.Lock()
defer f.inFlightLock.Unlock()
req, ok := f.inFlightAdds[fav]
if !ok {
req = &favReq{
ctx: ctx,
toAdd: []favToAdd{fav},
done: make(chan struct{}),
}
f.inFlightAdds[fav] = req
doSend = true
}
return req, doSend
}
// Add adds a favorite to your favorites list.
func (f *Favorites) Add(ctx context.Context, fav favToAdd) error {
if f.disabled {
return nil
}
if f.hasShutdown() {
return ShutdownHappenedError{}
}
doAdd := true
var err error
// Retry until we get an error that wasn't related to someone
// else's context being canceled.
for doAdd {
req, doSend := f.startOrJoinAddReq(ctx, fav)
if doSend {
return f.sendReq(ctx, req)
}
doAdd, err = f.waitOnReq(ctx, req)
}
return err
}
// AddAsync initiates a request to add this favorite to your favorites
// list, if one is not already in flight, but it doesn't wait for the
// result. (It could block while kicking off the request, if lots of
// different favorite operations are in flight.) The given context is
// used only for enqueuing the request on an internal queue, not for
// any resulting I/O.
func (f *Favorites) AddAsync(ctx context.Context, fav favToAdd) {
if f.disabled || f.hasShutdown() {
return
}
// Use a fresh context, since we want the request to succeed even
// if the original context is canceled.
req, doSend := f.startOrJoinAddReq(context.Background(), fav)
if doSend {
f.wg.Add(1)
select {
case f.reqChan <- req:
case <-ctx.Done():
f.wg.Done()
err := ctx.Err()
f.closeReq(req, err)
return
}
}
}
// Delete deletes a favorite from the favorites list. It is
// idempotent.
func (f *Favorites) Delete(ctx context.Context, fav Favorite) error {
if f.disabled {
return nil
}
if f.hasShutdown() {
return ShutdownHappenedError{}
}
return f.sendReq(ctx, &favReq{
ctx: ctx,
toDel: []Favorite{fav},
done: make(chan struct{}),
})
}
// RefreshCache refreshes the cached list of favorites.
func (f *Favorites) RefreshCache(ctx context.Context) {
if f.disabled || f.hasShutdown() {
return
}
// This request is non-blocking, so use a throw-away done channel
// and context.
req := &favReq{
refresh: true,
done: make(chan struct{}),
ctx: context.Background(),
}
f.wg.Add(1)
select {
case f.reqChan <- req:
case <-ctx.Done():
f.wg.Done()
return
}
}
// Get returns the logged-in user's list of favorites. It uses the cache.
func (f *Favorites) Get(ctx context.Context) ([]Favorite, error) {
if f.disabled {
session, err := f.config.KBPKI().GetCurrentSession(ctx)
if err == nil {
// Add favorites only for the current user.
return []Favorite{
{string(session.Name), tlf.Private},
{string(session.Name), tlf.Public},
}, nil
}
return nil, nil
}
if f.hasShutdown() {
return nil, ShutdownHappenedError{}
}
favChan := make(chan []Favorite, 1)
req := &favReq{
ctx: ctx,
favs: favChan,
done: make(chan struct{}),
}
err := f.sendReq(ctx, req)
if err != nil {
return nil, err
}
return <-favChan, nil
}