fix: fix bugs in cache order

This commit is contained in:
Stavros
2026-05-31 18:29:14 +03:00
parent ac9689dc9b
commit fe8463890a
+5 -5
View File
@@ -97,8 +97,10 @@ func (cs *CacheStore[T]) setCallback(key string, value T, ttl time.Duration) {
expiresAt: expiresAt, expiresAt: expiresAt,
} }
if !slices.Contains(cs.order, key) {
cs.order = append(cs.order, key) cs.order = append(cs.order, key)
} }
}
func (cs *CacheStore[T]) Set(key string, value T, ttl time.Duration) { func (cs *CacheStore[T]) Set(key string, value T, ttl time.Duration) {
cs.mu.Lock() cs.mu.Lock()
@@ -159,7 +161,7 @@ func (cs *CacheStore[T]) evictOne() bool {
for k, e := range cs.cache { for k, e := range cs.cache {
if e.expiresAt != nil && now.After(*e.expiresAt) { if e.expiresAt != nil && now.After(*e.expiresAt) {
delete(cs.cache, k) cs.deleteCallback(k)
return true return true
} }
if e.expiresAt != nil && (oldestExp == nil || e.expiresAt.Before(*oldestExp)) { if e.expiresAt != nil && (oldestExp == nil || e.expiresAt.Before(*oldestExp)) {
@@ -169,13 +171,11 @@ func (cs *CacheStore[T]) evictOne() bool {
// If we found an oldest key, evict it else we delete the first key in the order list // If we found an oldest key, evict it else we delete the first key in the order list
if oldestKey != "" { if oldestKey != "" {
delete(cs.cache, oldestKey) cs.deleteCallback(oldestKey)
return true return true
} else { } else {
if len(cs.order) > 0 { if len(cs.order) > 0 {
firstKey := cs.order[0] cs.deleteCallback(cs.order[0])
cs.order = cs.order[1:]
delete(cs.cache, firstKey)
return true return true
} }
} }