k8s.io/kubernetes@v1.29.3/pkg/kubelet/util/cache/object_cache.go (about) 1 /* 2 Copyright 2016 The Kubernetes Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package cache 18 19 import ( 20 "time" 21 22 expirationcache "k8s.io/client-go/tools/cache" 23 ) 24 25 // ObjectCache is a simple wrapper of expiration cache that 26 // 1. use string type key 27 // 2. has an updater to get value directly if it is expired 28 // 3. then update the cache 29 type ObjectCache struct { 30 cache expirationcache.Store 31 updater func() (interface{}, error) 32 } 33 34 // objectEntry is an object with string type key. 35 type objectEntry struct { 36 key string 37 obj interface{} 38 } 39 40 // NewObjectCache creates ObjectCache with an updater. 41 // updater returns an object to cache. 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 // stringKeyFunc is a string as cache key function 50 func stringKeyFunc(obj interface{}) (string, error) { 51 key := obj.(objectEntry).key 52 return key, nil 53 } 54 55 // Get gets cached objectEntry by using a unique string as the key. 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 // Add adds objectEntry by using a unique string as the key. 79 func (c *ObjectCache) Add(key string, obj interface{}) error { 80 return c.cache.Add(objectEntry{key: key, obj: obj}) 81 }