tests: cache

This commit is contained in:
Felipe M 2025-03-23 23:37:26 +01:00
parent 92732f9682
commit 597feb7b54
Signed by: fmartingr
GPG key ID: CCFBC5637D4000A8
8 changed files with 822 additions and 32 deletions

37
cache/memory.go vendored
View file

@ -10,30 +10,44 @@ import (
var _ model.Cache = (*MemoryCache)(nil)
type MemoryCache struct {
data map[string]any
data map[string]model.CacheItem
dataMu sync.RWMutex
}
func (c *MemoryCache) Get(key string) (result any, err error) {
c.dataMu.RLock()
defer c.dataMu.RUnlock()
result, exists := c.data[key]
item, exists := c.data[key]
if !exists {
c.dataMu.RUnlock()
return result, model.ErrCacheKeyDontExist
}
return
// Check expiration while still holding the lock
if item.TTL != nil && item.TTL.Before(time.Now()) {
c.dataMu.RUnlock()
_ = c.Delete(key)
return result, model.ErrCacheKeyDontExist
}
value := item.Value
c.dataMu.RUnlock()
return value, nil
}
func (c *MemoryCache) GetWithExpiry(key string, expiration time.Duration) (any, error) {
// TODO: Implement expiration in memory cache.
return c.Get(key)
}
func (c *MemoryCache) Set(key string, value any, opts ...model.CacheOption) error {
item := model.CacheItem{
Key: key,
Value: value,
}
for _, opt := range opts {
opt(&item)
}
func (c *MemoryCache) Set(key string, value any) error {
c.dataMu.Lock()
c.data[key] = value
c.data[key] = item
c.dataMu.Unlock()
return nil
@ -48,6 +62,7 @@ func (c *MemoryCache) Delete(key string) error {
func NewMemoryCache() *MemoryCache {
return &MemoryCache{
data: make(map[string]any),
data: make(map[string]model.CacheItem),
dataMu: sync.RWMutex{},
}
}