ntfy-alertmanager/cache.go
Thorben Günther 7a6b7c9cdb
cache: Take alert status (firing, resolved) into account
Otherwise a resolved alert would not trigger a notification, since its
fingerprint - which is a generated hash from the labels - remains the
same.
2023-02-08 20:41:05 +01:00

63 lines
994 B
Go

package main
import (
"sync"
"time"
)
type fingerprint string
type status string
type cachedAlert struct {
expires time.Time
status status
}
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, s status) {
c.mu.Lock()
defer c.mu.Unlock()
alert := new(cachedAlert)
alert.expires = time.Now().Add(c.duration)
alert.status = s
c.alerts[f] = alert
}
func (c *cache) contains(f fingerprint, s status) bool {
c.mu.Lock()
defer c.mu.Unlock()
alert, ok := c.alerts[f]
if ok {
return alert.status == s
}
return false
}