2023-02-22 21:58:17 +00:00
|
|
|
package timecache
|
|
|
|
|
|
|
|
import (
|
2023-02-24 15:19:37 +00:00
|
|
|
"context"
|
2023-02-22 21:58:17 +00:00
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2023-02-24 15:19:37 +00:00
|
|
|
// LastSeenCache is a time cache that extends the expiry of a seen message when added
|
|
|
|
// or checked for presence with Has..
|
2023-02-22 21:58:17 +00:00
|
|
|
type LastSeenCache struct {
|
2023-02-24 15:19:37 +00:00
|
|
|
lk sync.Mutex
|
|
|
|
m map[string]time.Time
|
|
|
|
ttl time.Duration
|
|
|
|
|
|
|
|
done func()
|
2023-02-22 21:58:17 +00:00
|
|
|
}
|
|
|
|
|
2023-02-24 15:19:37 +00:00
|
|
|
var _ TimeCache = (*LastSeenCache)(nil)
|
|
|
|
|
|
|
|
func newLastSeenCache(ttl time.Duration) *LastSeenCache {
|
|
|
|
tc := &LastSeenCache{
|
|
|
|
m: make(map[string]time.Time),
|
|
|
|
ttl: ttl,
|
2023-02-22 21:58:17 +00:00
|
|
|
}
|
|
|
|
|
2023-02-24 15:19:37 +00:00
|
|
|
ctx, done := context.WithCancel(context.Background())
|
|
|
|
tc.done = done
|
|
|
|
go background(ctx, &tc.lk, tc.m)
|
2023-02-22 21:58:17 +00:00
|
|
|
|
2023-02-24 15:19:37 +00:00
|
|
|
return tc
|
|
|
|
}
|
2023-02-22 21:58:17 +00:00
|
|
|
|
2023-02-24 15:19:37 +00:00
|
|
|
func (tc *LastSeenCache) Done() {
|
|
|
|
tc.done()
|
2023-02-22 21:58:17 +00:00
|
|
|
}
|
|
|
|
|
2023-02-24 15:19:37 +00:00
|
|
|
func (tc *LastSeenCache) Add(s string) bool {
|
|
|
|
tc.lk.Lock()
|
|
|
|
defer tc.lk.Unlock()
|
2023-02-22 21:58:17 +00:00
|
|
|
|
2023-02-24 15:19:37 +00:00
|
|
|
_, ok := tc.m[s]
|
|
|
|
tc.m[s] = time.Now().Add(tc.ttl)
|
2023-02-22 21:58:17 +00:00
|
|
|
|
2023-02-24 15:19:37 +00:00
|
|
|
return !ok
|
2023-02-22 21:58:17 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (tc *LastSeenCache) Has(s string) bool {
|
2023-02-24 15:19:37 +00:00
|
|
|
tc.lk.Lock()
|
|
|
|
defer tc.lk.Unlock()
|
2023-02-22 21:58:17 +00:00
|
|
|
|
2023-02-24 15:19:37 +00:00
|
|
|
_, ok := tc.m[s]
|
|
|
|
if ok {
|
|
|
|
tc.m[s] = time.Now().Add(tc.ttl)
|
2023-02-22 21:58:17 +00:00
|
|
|
}
|
2023-02-24 15:19:37 +00:00
|
|
|
|
|
|
|
return ok
|
2023-02-22 21:58:17 +00:00
|
|
|
}
|