2022-04-29 13:02:25 -07:00
|
|
|
package cache
|
|
|
|
|
|
|
|
import (
|
|
|
|
"time"
|
|
|
|
|
2024-04-23 07:15:38 -07:00
|
|
|
"git.jamestombleson.com/jtom38/newsbot-api/internal/domain"
|
2022-04-29 13:02:25 -07:00
|
|
|
)
|
|
|
|
|
|
|
|
// When a record becomes tainted, it needs to be renewed or it will be dropped from the cache.
|
|
|
|
// If a record is tainted and used again, the taint will be removed and a new Expires value will be set.
|
|
|
|
// If its not renewed, it will be dropped.
|
2022-12-04 08:49:17 -08:00
|
|
|
type CacheAgeMonitor struct{}
|
2022-04-29 13:02:25 -07:00
|
|
|
|
|
|
|
func NewCacheAgeMonitor() CacheAgeMonitor {
|
|
|
|
return CacheAgeMonitor{}
|
|
|
|
}
|
|
|
|
|
|
|
|
// This is an automated job that will review all the objects for age and taint them if needed.
|
|
|
|
func (cam CacheAgeMonitor) CheckExpiredEntries() {
|
|
|
|
now := time.Now()
|
|
|
|
for index, item := range cacheStorage {
|
|
|
|
if now.After(item.Expires) {
|
2022-12-04 08:49:17 -08:00
|
|
|
|
2022-04-29 13:02:25 -07:00
|
|
|
// the timer expired, and its not tainted, taint it
|
|
|
|
if !item.IsTainted {
|
2022-12-04 08:49:17 -08:00
|
|
|
item.IsTainted = true
|
2022-04-29 13:02:25 -07:00
|
|
|
item.Expires = now.Add(1 * time.Hour)
|
|
|
|
}
|
|
|
|
|
|
|
|
// if its tainted and the timer didnt get renewed, delete
|
|
|
|
if item.IsTainted {
|
|
|
|
cacheStorage = cam.removeEntry(index)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// This creates a new slice and skips over the item that needs to be dropped
|
2024-04-23 07:15:38 -07:00
|
|
|
func (cam CacheAgeMonitor) removeEntry(index int) []*domain.CacheItem {
|
|
|
|
var temp []*domain.CacheItem
|
2022-04-29 13:02:25 -07:00
|
|
|
for i, item := range cacheStorage {
|
2022-12-04 08:49:17 -08:00
|
|
|
if i != index {
|
|
|
|
temp = append(temp, item)
|
|
|
|
}
|
2022-04-29 13:02:25 -07:00
|
|
|
}
|
|
|
|
return temp
|
|
|
|
}
|