knative.dev/pkg@v0.0.0-20260602142205-ac97e43f6622/apis/duck/cached.go (about) 1 /* 2 Copyright 2018 The Knative 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 duck 18 19 import ( 20 "context" 21 "sync" 22 23 "k8s.io/apimachinery/pkg/runtime/schema" 24 "k8s.io/client-go/tools/cache" 25 ) 26 27 // CachedInformerFactory implements InformerFactory by delegating to another 28 // InformerFactory, but memoizing the results. 29 type CachedInformerFactory struct { 30 Delegate InformerFactory 31 32 m sync.Mutex 33 cache map[schema.GroupVersionResource]*informerCache 34 } 35 36 // Check that CachedInformerFactory implements InformerFactory. 37 var _ InformerFactory = (*CachedInformerFactory)(nil) 38 39 // Get implements InformerFactory. 40 func (cif *CachedInformerFactory) Get(ctx context.Context, gvr schema.GroupVersionResource) (cache.SharedIndexInformer, cache.GenericLister, error) { 41 cif.m.Lock() 42 43 if cif.cache == nil { 44 cif.cache = make(map[schema.GroupVersionResource]*informerCache) 45 } 46 47 ic, ok := cif.cache[gvr] 48 if !ok { 49 ic = &informerCache{} 50 ic.init = func() { 51 ic.Lock() 52 defer ic.Unlock() 53 54 // double-checked lock to ensure we call the Delegate 55 // only once even if multiple goroutines end up inside 56 // init() simultaneously 57 if ic.hasInformer() { 58 return 59 } 60 61 ic.inf, ic.lister, ic.err = cif.Delegate.Get(ctx, gvr) 62 } 63 cif.cache[gvr] = ic 64 } 65 66 // If this were done via "defer", then TestDifferentGVRs will fail. 67 cif.m.Unlock() 68 69 // The call to the delegate could be slow because it syncs informers, so do 70 // this outside of the main lock. 71 return ic.Get() 72 } 73 74 type informerCache struct { 75 sync.RWMutex 76 77 init func() 78 79 inf cache.SharedIndexInformer 80 lister cache.GenericLister 81 err error 82 } 83 84 // Get returns the cached informer. If it does not yet exist, we first try to 85 // acquire one by executing the cache's init function. 86 func (ic *informerCache) Get() (cache.SharedIndexInformer, cache.GenericLister, error) { 87 if !ic.initialized() { 88 ic.init() 89 } 90 return ic.inf, ic.lister, ic.err 91 } 92 93 func (ic *informerCache) initialized() bool { 94 ic.RLock() 95 defer ic.RUnlock() 96 return ic.hasInformer() 97 } 98 99 func (ic *informerCache) hasInformer() bool { 100 return ic.inf != nil && ic.lister != nil 101 }