/
usercard_cache.go
66 lines (56 loc) · 1.61 KB
/
usercard_cache.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
package libkb
import (
"fmt"
"time"
"github.com/keybase/client/go/protocol/keybase1"
"stathat.com/c/ramcache"
)
// UserCardCache caches keybase1.UserCard objects in memory.
type UserCardCache struct {
cache *ramcache.Ramcache
}
// NewUserCardCache creates a UserCardCache. keybase1.UserCards will expire
// after maxAge.
func NewUserCardCache(maxAge time.Duration) *UserCardCache {
c := &UserCardCache{
cache: ramcache.New(),
}
c.cache.MaxAge = maxAge
c.cache.TTL = maxAge
return c
}
// Get looks for a keybase1.UserCard for uid. It returns nil, nil if not found.
// useSession is set if the card is being looked up with a session.
func (c *UserCardCache) Get(uid keybase1.UID, useSession bool) (*keybase1.UserCard, error) {
v, err := c.cache.Get(c.key(uid, useSession))
if err != nil {
if err == ramcache.ErrNotFound {
return nil, nil
}
return nil, err
}
card, ok := v.(keybase1.UserCard)
if !ok {
return nil, fmt.Errorf("invalid type in cache: %T", v)
}
return &card, nil
}
// Set stores card in the UserCardCache. usedSession is set based on
// whether user/card was looked up with a session or not.
func (c *UserCardCache) Set(card *keybase1.UserCard, usedSession bool) error {
return c.cache.Set(c.key(card.Uid, usedSession), *card)
}
// Shutdown stops any goroutines in the cache.
func (c *UserCardCache) Shutdown() {
c.cache.Shutdown()
}
func (c *UserCardCache) key(uid keybase1.UID, session bool) string {
suffix := "0"
if session {
suffix = "1"
}
return uid.String() + ":" + suffix
}
func (c *UserCardCache) Delete(uid keybase1.UID) error {
return c.cache.Delete(c.key(uid, true))
}