feat: delete expired cache entries on init

This commit is contained in:
Jan De Dobbeleer 2022-08-07 10:25:57 +02:00 committed by Jan De Dobbeleer
parent f47c30d2df
commit 210629fd26
2 changed files with 12 additions and 17 deletions

View file

@ -17,6 +17,13 @@ type cacheObject struct {
TTL int `json:"ttl"` TTL int `json:"ttl"`
} }
func (c *cacheObject) expired() bool {
if c.TTL < 0 {
return false
}
return time.Now().Unix() >= (c.Timestamp + int64(c.TTL)*60)
}
type fileCache struct { type fileCache struct {
cache *concurrentMap cache *concurrentMap
cachePath string cachePath string
@ -38,6 +45,9 @@ func (fc *fileCache) Init(cachePath string) {
} }
for key, co := range list { for key, co := range list {
if co.expired() {
continue
}
fc.cache.set(key, co) fc.cache.set(key, co)
} }
} }
@ -60,19 +70,10 @@ func (fc *fileCache) Get(key string) (string, bool) {
if !found { if !found {
return "", false return "", false
} }
co, ok := val.(*cacheObject) if co, ok := val.(*cacheObject); ok {
if !ok {
return "", false
}
if co.TTL <= 0 {
return co.Value, true return co.Value, true
} }
expired := time.Now().Unix() >= (co.Timestamp + int64(co.TTL)*60)
if expired {
fc.cache.remove(key)
return "", false return "", false
}
return co.Value, true
} }
// sets the value for the given key with a TTL (minutes) // sets the value for the given key with a TTL (minutes)

View file

@ -25,12 +25,6 @@ func (c *concurrentMap) get(key string) (interface{}, bool) {
return "", false return "", false
} }
func (c *concurrentMap) remove(key string) {
lock.RLock()
defer lock.RUnlock()
delete(c.values, key)
}
func (c *concurrentMap) list() map[string]interface{} { func (c *concurrentMap) list() map[string]interface{} {
return c.values return c.values
} }