status-go/mailserver/limiter.go

89 lines
1.3 KiB
Go
Raw Permalink Normal View History

2018-05-21 11:30:37 +00:00
package mailserver
import (
"sync"
"time"
)
type rateLimiter struct {
sync.RWMutex
2018-05-21 11:30:37 +00:00
lifespan time.Duration // duration of the limit
db map[string]time.Time
period time.Duration
cancel chan struct{}
2018-05-21 11:30:37 +00:00
}
func newRateLimiter(duration time.Duration) *rateLimiter {
return &rateLimiter{
lifespan: duration,
db: make(map[string]time.Time),
period: time.Second,
2018-05-21 11:30:37 +00:00
}
}
func (l *rateLimiter) Start() {
cancel := make(chan struct{})
l.Lock()
l.cancel = cancel
l.Unlock()
go l.cleanUp(l.period, cancel)
}
2018-05-21 11:30:37 +00:00
func (l *rateLimiter) Stop() {
l.Lock()
defer l.Unlock()
if l.cancel == nil {
return
}
close(l.cancel)
l.cancel = nil
}
func (l *rateLimiter) Add(id string) {
l.Lock()
2018-05-21 11:30:37 +00:00
l.db[id] = time.Now()
l.Unlock()
2018-05-21 11:30:37 +00:00
}
func (l *rateLimiter) IsAllowed(id string) bool {
l.RLock()
defer l.RUnlock()
2018-05-21 11:30:37 +00:00
if lastRequestTime, ok := l.db[id]; ok {
return lastRequestTime.Add(l.lifespan).Before(time.Now())
2018-05-21 11:30:37 +00:00
}
return true
}
func (l *rateLimiter) cleanUp(period time.Duration, cancel <-chan struct{}) {
t := time.NewTicker(period)
defer t.Stop()
for {
select {
case <-t.C:
l.deleteExpired()
case <-cancel:
return
}
}
}
func (l *rateLimiter) deleteExpired() {
l.Lock()
defer l.Unlock()
2018-05-21 11:30:37 +00:00
now := time.Now()
for id, lastRequestTime := range l.db {
if lastRequestTime.Add(l.lifespan).Before(now) {
2018-05-21 11:30:37 +00:00
delete(l.db, id)
}
}
}