2018-05-21 11:30:37 +00:00
|
|
|
package mailserver
|
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2019-01-10 16:07:16 +00:00
|
|
|
type rateLimiter struct {
|
|
|
|
sync.RWMutex
|
2018-05-21 11:30:37 +00:00
|
|
|
|
2019-01-10 16:07:16 +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
|
|
|
}
|
|
|
|
|
2019-01-10 16:07:16 +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
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-01-10 16:07:16 +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
|
|
|
|
2019-01-10 16:07:16 +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()
|
2019-01-10 16:07:16 +00:00
|
|
|
l.Unlock()
|
2018-05-21 11:30:37 +00:00
|
|
|
}
|
|
|
|
|
2019-01-10 16:07:16 +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 {
|
2019-01-10 16:07:16 +00:00
|
|
|
return lastRequestTime.Add(l.lifespan).Before(time.Now())
|
2018-05-21 11:30:37 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2019-01-10 16:07:16 +00:00
|
|
|
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 {
|
2019-01-10 16:07:16 +00:00
|
|
|
if lastRequestTime.Add(l.lifespan).Before(now) {
|
2018-05-21 11:30:37 +00:00
|
|
|
delete(l.db, id)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|