...
1
16
17 package cache
18
19 import (
20 "time"
21
22 expirationcache "k8s.io/client-go/tools/cache"
23 )
24
25
26
27
28
29 type ObjectCache struct {
30 cache expirationcache.Store
31 updater func() (interface{}, error)
32 }
33
34
35 type objectEntry struct {
36 key string
37 obj interface{}
38 }
39
40
41
42 func NewObjectCache(f func() (interface{}, error), ttl time.Duration) *ObjectCache {
43 return &ObjectCache{
44 updater: f,
45 cache: expirationcache.NewTTLStore(stringKeyFunc, ttl),
46 }
47 }
48
49
50 func stringKeyFunc(obj interface{}) (string, error) {
51 key := obj.(objectEntry).key
52 return key, nil
53 }
54
55
56 func (c *ObjectCache) Get(key string) (interface{}, error) {
57 value, ok, err := c.cache.Get(objectEntry{key: key})
58 if err != nil {
59 return nil, err
60 }
61 if !ok {
62 obj, err := c.updater()
63 if err != nil {
64 return nil, err
65 }
66 err = c.cache.Add(objectEntry{
67 key: key,
68 obj: obj,
69 })
70 if err != nil {
71 return nil, err
72 }
73 return obj, nil
74 }
75 return value.(objectEntry).obj, nil
76 }
77
78
79 func (c *ObjectCache) Add(key string, obj interface{}) error {
80 return c.cache.Add(objectEntry{key: key, obj: obj})
81 }
82
View as plain text