Files
Snip/backend/internal/adapter/memory/cache.go
T
2026-06-15 21:25:57 +07:00

49 lines
952 B
Go

package memory
import (
"context"
"sync"
"time"
"github.com/snip/backend/internal/port"
)
type cacheEntry struct {
res port.Resolution
expires time.Time
}
// Cache is a TTL map standing in for Redis.
type Cache struct {
mu sync.RWMutex
m map[string]cacheEntry
}
func NewCache() *Cache {
return &Cache{m: make(map[string]cacheEntry)}
}
func (c *Cache) GetResolution(_ context.Context, code string) (port.Resolution, bool, error) {
c.mu.RLock()
e, ok := c.m[code]
c.mu.RUnlock()
if !ok || time.Now().After(e.expires) {
return port.Resolution{}, false, nil
}
return e.res, true, nil
}
func (c *Cache) SetResolution(_ context.Context, code string, r port.Resolution, ttl time.Duration) error {
c.mu.Lock()
c.m[code] = cacheEntry{res: r, expires: time.Now().Add(ttl)}
c.mu.Unlock()
return nil
}
func (c *Cache) Invalidate(_ context.Context, code string) error {
c.mu.Lock()
delete(c.m, code)
c.mu.Unlock()
return nil
}