1 /* 2 Copyright 2017 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 eventratelimit 18 19 import ( 20 "k8s.io/client-go/util/flowcontrol" 21 "k8s.io/utils/lru" 22 ) 23 24 // cache is an interface for caching the limits of a particular type 25 type cache interface { 26 // get the rate limiter associated with the specified key 27 get(key interface{}) flowcontrol.RateLimiter 28 } 29 30 // singleCache is a cache that only stores a single, constant item 31 type singleCache struct { 32 // the single rate limiter held by the cache 33 rateLimiter flowcontrol.RateLimiter 34 } 35 36 func (c *singleCache) get(key interface{}) flowcontrol.RateLimiter { 37 return c.rateLimiter 38 } 39 40 // lruCache is a least-recently-used cache 41 type lruCache struct { 42 // factory to use to create new rate limiters 43 rateLimiterFactory func() flowcontrol.RateLimiter 44 // the actual LRU cache 45 cache *lru.Cache 46 } 47 48 func (c *lruCache) get(key interface{}) flowcontrol.RateLimiter { 49 value, found := c.cache.Get(key) 50 if !found { 51 rateLimter := c.rateLimiterFactory() 52 c.cache.Add(key, rateLimter) 53 return rateLimter 54 } 55 return value.(flowcontrol.RateLimiter) 56 } 57