1
0
mirror of https://github.com/amir20/dozzle.git synced 2025-12-21 13:23:07 +01:00
Files
dozzle/internal/cache/expire.go
2024-05-13 15:32:51 -07:00

51 lines
874 B
Go

package cache
import (
"sync"
"time"
log "github.com/sirupsen/logrus"
)
type Cache[T any] struct {
f func() (T, error)
Timestamp time.Time
Duration time.Duration
Data T
mu sync.Mutex
}
func New[T any](f func() (T, error), duration time.Duration) *Cache[T] {
return &Cache[T]{
f: f,
Duration: duration,
}
}
func (c *Cache[T]) GetWithHit() (T, error, bool) {
c.mu.Lock()
defer c.mu.Unlock()
hit := true
if c.Timestamp.IsZero() || time.Since(c.Timestamp) > c.Duration {
hit = false
var err error
c.Data, err = c.f()
if err != nil {
return c.Data, err, hit
}
c.Timestamp = time.Now()
}
if hit {
log.Debugf("Cache hit for %T", c.Data)
} else {
log.Debugf("Cache miss for %T", c.Data)
}
return c.Data, nil, hit
}
func (c *Cache[T]) Get() (T, error) {
data, err, _ := c.GetWithHit()
return data, err
}