Files
nmon/internal/app/ttlcache.go
jleung ad220eae58 Interface-down alerts are opt-in: per port (bell toggle, bulk) and via groups
interfaces.alert_down / groups.alert_down (migration 9); interface_down rule OptIn; non-opted ports' open alerts close silently as retired.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Lx9FNLG2CqeBbVGGd9bFsP
2026-10-23 05:04:41 +00:00

62 lines
1.4 KiB
Go

package app
import (
"sync"
"time"
"github.com/v10networks/nmon/internal/clock"
)
// maxCached bounds a ttlCache; it is emptied when it grows past it, so a large
// inventory costs a burst of lookups instead of unbounded memory.
const maxCached = 200_000
// ttlCache remembers lookups the alert callbacks repeat for every series on every
// evaluation. A failed load is returned and not remembered.
type ttlCache[K comparable, V any] struct {
clk clock.Clock
ttl time.Duration
mu sync.Mutex
m map[K]ttlEntry[V]
}
type ttlEntry[V any] struct {
v V
expires time.Time
}
func newTTLCache[K comparable, V any](clk clock.Clock, ttl time.Duration) *ttlCache[K, V] {
return &ttlCache[K, V]{clk: clk, ttl: ttl, m: map[K]ttlEntry[V]{}}
}
// get returns the cached value for k, loading it when absent or expired.
func (c *ttlCache[K, V]) get(k K, load func() (V, error)) (V, error) {
now := c.clk.Now()
c.mu.Lock()
e, ok := c.m[k]
c.mu.Unlock()
if ok && now.Before(e.expires) {
return e.v, nil
}
v, err := load()
if err != nil {
var zero V
return zero, err
}
c.mu.Lock()
if len(c.m) >= maxCached {
c.m = map[K]ttlEntry[V]{}
}
c.m[k] = ttlEntry[V]{v: v, expires: now.Add(c.ttl)}
c.mu.Unlock()
return v, nil
}
// invalidate forgets every cached value, so the next get loads afresh.
func (c *ttlCache[K, V]) invalidate() {
c.mu.Lock()
c.m = map[K]ttlEntry[V]{}
c.mu.Unlock()
}