forked from keybase/client
/
payload_cache.go
62 lines (50 loc) · 1.16 KB
/
payload_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
package libkb
import (
"encoding/hex"
lru "github.com/hashicorp/golang-lru"
jsonw "github.com/keybase/go-jsonw"
)
type PayloadCache struct {
Contextified
cache *lru.Cache
}
func NewPayloadCache(g *GlobalContext, maxNumElements int) *PayloadCache {
c, err := lru.New(maxNumElements)
if err != nil {
g.Log.Warning("failed to create PayloadCache LRU: %s", err)
c = nil
}
return &PayloadCache{
Contextified: NewContextified(g),
cache: c,
}
}
func (p *PayloadCache) GetOrPrime(link *ChainLink) (*jsonw.Wrapper, error) {
// check if failed to create cache in NewPayloadCache
if p.cache == nil {
p.G().Log.Debug("PayloadCache no LRU, unmarshal for %x", link.unpacked.payloadHash)
payload, err := link.unpacked.Payload()
if err != nil {
return nil, err
}
return jsonw.Unmarshal(payload)
}
key := hex.EncodeToString(link.unpacked.payloadHash)
obj, ok := p.cache.Get(key)
if ok {
jw, ok := obj.(*jsonw.Wrapper)
if ok {
return jw, nil
}
}
payload, err := link.unpacked.Payload()
if err != nil {
return nil, err
}
jw, err := jsonw.Unmarshal(payload)
if err != nil {
return nil, err
}
p.cache.Add(key, jw)
return jw, nil
}