cache.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /*
  2. Copyright 2017 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package eventratelimit
  14. import (
  15. "github.com/hashicorp/golang-lru"
  16. "k8s.io/client-go/util/flowcontrol"
  17. )
  18. // cache is an interface for caching the limits of a particular type
  19. type cache interface {
  20. // get the rate limiter associated with the specified key
  21. get(key interface{}) flowcontrol.RateLimiter
  22. }
  23. // singleCache is a cache that only stores a single, constant item
  24. type singleCache struct {
  25. // the single rate limiter held by the cache
  26. rateLimiter flowcontrol.RateLimiter
  27. }
  28. func (c *singleCache) get(key interface{}) flowcontrol.RateLimiter {
  29. return c.rateLimiter
  30. }
  31. // lruCache is a least-recently-used cache
  32. type lruCache struct {
  33. // factory to use to create new rate limiters
  34. rateLimiterFactory func() flowcontrol.RateLimiter
  35. // the actual LRU cache
  36. cache *lru.Cache
  37. }
  38. func (c *lruCache) get(key interface{}) flowcontrol.RateLimiter {
  39. value, found := c.cache.Get(key)
  40. if !found {
  41. rateLimter := c.rateLimiterFactory()
  42. c.cache.Add(key, rateLimter)
  43. return rateLimter
  44. }
  45. return value.(flowcontrol.RateLimiter)
  46. }