| 1 |
package util |
| 2 |
|
| 3 |
import ( |
| 4 |
"sync" |
| 5 |
"time" |
| 6 |
) |
| 7 |
|
| 8 |
// LookupCache is a single-value cache with a time-to-live (TTL). The cache has a lookup function |
| 9 |
// to retrieve the value and stores it until TTL is reached. |
| 10 |
// |
| 11 |
// Example: |
| 12 |
// |
| 13 |
// lookup := func() (string, error) { |
| 14 |
// r, _ := http.Get("...") |
| 15 |
// s, _ := io.ReadAll(r.Body) |
| 16 |
// return string(s), nil |
| 17 |
// } |
| 18 |
// c := NewLookupCache[string](lookup, time.Hour) |
| 19 |
// fmt.Println(c.Get()) // Fetches the string via HTTP |
| 20 |
// fmt.Println(c.Get()) // Uses cached value |
| 21 |
type LookupCache[T any] struct { |
| 22 |
value *T |
| 23 |
lookup func() (T, error) |
| 24 |
ttl time.Duration |
| 25 |
updated time.Time |
| 26 |
mu sync.Mutex |
| 27 |
} |
| 28 |
|
| 29 |
// LookupFunc is a function that is called by the LookupCache if the underlying |
| 30 |
// value is out-of-date. It returns the new value, or an error. |
| 31 |
type LookupFunc[T any] func() (T, error) |
| 32 |
|
| 33 |
// NewLookupCache creates a new LookupCache with a given time-to-live (TTL) |
| 34 |
func NewLookupCache[T any](lookup LookupFunc[T], ttl time.Duration) *LookupCache[T] { |
| 35 |
return &LookupCache[T]{ |
| 36 |
value: nil, |
| 37 |
lookup: lookup, |
| 38 |
ttl: ttl, |
| 39 |
} |
| 40 |
} |
| 41 |
|
| 42 |
// Value returns the cached value, or retrieves it via the lookup function |
| 43 |
func (c *LookupCache[T]) Value() (T, error) { |
| 44 |
c.mu.Lock() |
| 45 |
defer c.mu.Unlock() |
| 46 |
if c.value == nil || (c.ttl > 0 && time.Since(c.updated) > c.ttl) { |
| 47 |
value, err := c.lookup() |
| 48 |
if err != nil { |
| 49 |
var t T |
| 50 |
return t, err |
| 51 |
} |
| 52 |
c.value = &value |
| 53 |
c.updated = time.Now() |
| 54 |
} |
| 55 |
return *c.value, nil |
| 56 |
} |