ntfy-alertmanager/cache.go
Thorben Günther d20d76d2b3
single mode: Cache alert fingerprints
If ntfy-alertmanager breaks alertmanager's grouping feature, it should
take care of caching alerts on its own.
2023-02-08 20:41:03 +01:00

54 lines
823 B
Go

package main
import (
"sync"
"time"
)
type fingerprint string
type cachedAlert struct {
expires time.Time
}
type cache struct {
mu sync.Mutex
alerts map[fingerprint]*cachedAlert
}
func (a *cachedAlert) expired() bool {
return a.expires.Before(time.Now())
}
func newCache() *cache {
c := new(cache)
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, d time.Duration) {
c.mu.Lock()
defer c.mu.Unlock()
alert := new(cachedAlert)
alert.expires = time.Now().Add(d)
c.alerts[f] = alert
}
func (c *cache) contains(f fingerprint) bool {
c.mu.Lock()
defer c.mu.Unlock()
_, ok := c.alerts[f]
return ok
}