Files
ocis/proxy/pkg/cache/cache.go
T

78 lines
1.4 KiB
Go
Raw Normal View History

2020-05-04 14:08:19 +02:00
package cache
import (
"sync"
"time"
2020-05-04 14:08:19 +02:00
)
// Entry represents an entry on the cache. You can type assert on V.
type Entry struct {
V interface{}
expiration time.Time
2020-05-04 14:08:19 +02:00
}
// Cache is a barebones cache implementation.
type Cache struct {
entries map[string]*Entry
2020-05-04 14:08:19 +02:00
size int
m sync.Mutex
}
// NewCache returns a new instance of Cache.
func NewCache(o ...Option) Cache {
opts := newOptions(o...)
return Cache{
size: opts.size,
entries: map[string]*Entry{},
2020-05-04 14:08:19 +02:00
}
}
// Get gets a role-bundle by a given `roleID`.
func (c *Cache) Get(k string) *Entry {
2020-05-04 14:08:19 +02:00
c.m.Lock()
defer c.m.Unlock()
if _, ok := c.entries[k]; ok {
if c.expired(c.entries[k]) {
delete(c.entries, k)
return nil
}
return c.entries[k]
2020-05-04 14:08:19 +02:00
}
return nil
2020-05-04 14:08:19 +02:00
}
// Set sets a roleID / role-bundle.
func (c *Cache) Set(k string, val interface{}, expiration time.Time) {
2020-05-04 14:08:19 +02:00
c.m.Lock()
defer c.m.Unlock()
if !c.fits() {
c.evict()
2020-05-04 14:08:19 +02:00
}
c.entries[k] = &Entry{
val,
expiration,
2020-05-04 14:08:19 +02:00
}
}
// evict frees memory from the cache by removing entries that exceeded the cache TTL.
func (c *Cache) evict() {
for i := range c.entries {
if c.expired(c.entries[i]) {
delete(c.entries, i)
2020-05-05 17:22:23 +02:00
}
}
}
// expired checks if an entry is expired
func (c *Cache) expired(e *Entry) bool {
return e.expiration.Before(time.Now())
2020-05-04 14:08:19 +02:00
}
// fits returns whether the cache fits more entries.
2020-05-04 14:08:19 +02:00
func (c *Cache) fits() bool {
return c.size > len(c.entries)
2020-05-04 14:08:19 +02:00
}