55 lines
823 B
Go
55 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
|
||
|
}
|