46 lines
803 B
Go
46 lines
803 B
Go
package platform
|
|
|
|
import (
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
type attempt struct {
|
|
count int
|
|
reset time.Time
|
|
}
|
|
|
|
type limiter struct {
|
|
mu sync.Mutex
|
|
entries map[string]attempt
|
|
limit int
|
|
window time.Duration
|
|
}
|
|
|
|
func newLimiter(limit int, window time.Duration) *limiter {
|
|
return &limiter{entries: map[string]attempt{}, limit: limit, window: window}
|
|
}
|
|
|
|
func (l *limiter) Allow(key string) bool {
|
|
now := time.Now()
|
|
l.mu.Lock()
|
|
defer l.mu.Unlock()
|
|
entry := l.entries[key]
|
|
if entry.reset.IsZero() || now.After(entry.reset) {
|
|
l.entries[key] = attempt{count: 1, reset: now.Add(l.window)}
|
|
return true
|
|
}
|
|
if entry.count >= l.limit {
|
|
return false
|
|
}
|
|
entry.count++
|
|
l.entries[key] = entry
|
|
return true
|
|
}
|
|
|
|
func (l *limiter) Reset(key string) {
|
|
l.mu.Lock()
|
|
defer l.mu.Unlock()
|
|
delete(l.entries, key)
|
|
}
|