2 Copyright 2016 The Kubernetes Authors.
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
8 http://www.apache.org/licenses/LICENSE-2.0
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.
23 "github.com/hashicorp/golang-lru"
26 // Clock defines an interface for obtaining the current time
27 type Clock interface {
31 // realClock implements the Clock interface by calling time.Now()
32 type realClock struct{}
34 func (realClock) Now() time.Time { return time.Now() }
36 // LRUExpireCache is a cache that ensures the mostly recently accessed keys are returned with
37 // a ttl beyond which keys are forcibly expired.
38 type LRUExpireCache struct {
39 // clock is used to obtain the current time
46 // NewLRUExpireCache creates an expiring cache with the given size
47 func NewLRUExpireCache(maxSize int) *LRUExpireCache {
48 return NewLRUExpireCacheWithClock(maxSize, realClock{})
51 // NewLRUExpireCacheWithClock creates an expiring cache with the given size, using the specified clock to obtain the current time.
52 func NewLRUExpireCacheWithClock(maxSize int, clock Clock) *LRUExpireCache {
53 cache, err := lru.New(maxSize)
55 // if called with an invalid size
58 return &LRUExpireCache{clock: clock, cache: cache}
61 type cacheEntry struct {
66 // Add adds the value to the cache at key with the specified maximum duration.
67 func (c *LRUExpireCache) Add(key interface{}, value interface{}, ttl time.Duration) {
70 c.cache.Add(key, &cacheEntry{value, c.clock.Now().Add(ttl)})
73 // Get returns the value at the specified key from the cache if it exists and is not
74 // expired, or returns false.
75 func (c *LRUExpireCache) Get(key interface{}) (interface{}, bool) {
78 e, ok := c.cache.Get(key)
82 if c.clock.Now().After(e.(*cacheEntry).expireTime) {
86 return e.(*cacheEntry).value, true
89 // Remove removes the specified key from the cache if it exists
90 func (c *LRUExpireCache) Remove(key interface{}) {
96 // Keys returns all the keys in the cache, even if they are expired. Subsequent calls to
97 // get may return not found. It returns all keys from oldest to newest.
98 func (c *LRUExpireCache) Keys() []interface{} {
100 defer c.lock.Unlock()
101 return c.cache.Keys()