diff --git a/utils/syncCache/cache.go b/utils/syncCache/cache.go index bdd544b..b0f29f8 100644 --- a/utils/syncCache/cache.go +++ b/utils/syncCache/cache.go @@ -62,20 +62,28 @@ func (sc *SyncCache[K, V]) Load(key K) (value V, loaded bool) { } func (sc *SyncCache[K, V]) LoadOrStore(key K, value V, expire time.Duration) (actual V, loaded bool) { - e, loaded := sc.cache.LoadOrStore(key, &entry[V]{ - expiration: time.Now().Add(expire), - value: value, - }) + e, loaded := sc.cache.LoadOrStore(key, NewEntry[V](value, expire)) if e.IsExpired() { - sc.cache.Store(key, &entry[V]{ - expiration: time.Now().Add(expire), - value: value, - }) + sc.cache.Store(key, NewEntry[V](value, expire)) return value, false } return e.value, loaded } +func (sc *SyncCache[K, V]) AddExpiration(key K, d time.Duration) { + e, ok := sc.cache.Load(key) + if ok { + e.AddExpiration(d) + } +} + +func (sc *SyncCache[K, V]) SetExpiration(key K, t time.Time) { + e, ok := sc.cache.Load(key) + if ok { + e.SetExpiration(t) + } +} + func (sc *SyncCache[K, V]) Delete(key K) { sc.LoadAndDelete(key) } diff --git a/utils/syncCache/item.go b/utils/syncCache/item.go index b74023e..2dd70a8 100644 --- a/utils/syncCache/item.go +++ b/utils/syncCache/item.go @@ -1,12 +1,30 @@ package synccache -import "time" +import ( + "sync/atomic" + "time" +) type entry[V any] struct { - expiration time.Time + expiration int64 value V } +func NewEntry[V any](value V, expire time.Duration) *entry[V] { + return &entry[V]{ + expiration: time.Now().Add(expire).UnixMilli(), + value: value, + } +} + func (e *entry[V]) IsExpired() bool { - return time.Now().After(e.expiration) + return time.Now().After(time.UnixMilli(atomic.LoadInt64(&e.expiration))) +} + +func (e *entry[V]) AddExpiration(d time.Duration) { + atomic.AddInt64(&e.expiration, int64(d)) +} + +func (e *entry[V]) SetExpiration(t time.Time) { + atomic.StoreInt64(&e.expiration, t.UnixMilli()) }