ntfy-alertmanager/cache.go

56 lines
874 B
Go

package main
import (
"sync"
"time"
)
type fingerprint string
type cachedAlert struct {
expires time.Time
}
type cache struct {
mu sync.Mutex
duration time.Duration
alerts map[fingerprint]*cachedAlert
}
func (a *cachedAlert) expired() bool {
return a.expires.Before(time.Now())
}
func newCache(d time.Duration) *cache {
c := new(cache)
c.duration = d
c.alerts = make(map[fingerprint]*cachedAlert)
return c
}
func (c *cache) cleanup() {
c.mu.Lock()
defer c.mu.Unlock()
for key, value := range c.alerts {
if value.expired() {
delete(c.alerts, key)
}
}
}
func (c *cache) set(f fingerprint) {
c.mu.Lock()
defer c.mu.Unlock()
alert := new(cachedAlert)
alert.expires = time.Now().Add(c.duration)
c.alerts[f] = alert
}
func (c *cache) contains(f fingerprint) bool {
c.mu.Lock()
defer c.mu.Unlock()
_, ok := c.alerts[f]
return ok
}