forked from keybase/client
/
ratelimit.go
49 lines (42 loc) · 1.15 KB
/
ratelimit.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// Copyright 2015 Keybase, Inc. All rights reserved. Use of
// this source code is governed by the included BSD license.
package libkb
import (
"sync"
"time"
)
type RateLimitCategory string
const (
CheckTrackingRateLimit RateLimitCategory = "CheckTrackingRateLimit"
TestEventRateLimit = "TestEventRateLimit"
)
type RateLimits struct {
Contextified
sync.Mutex
lastActionTimes map[RateLimitCategory]time.Time
}
func NewRateLimits(g *GlobalContext) *RateLimits {
return &RateLimits{
lastActionTimes: make(map[RateLimitCategory]time.Time),
Contextified: NewContextified(g),
}
}
func (r *RateLimits) GetPermission(category RateLimitCategory, interval time.Duration) bool {
r.Lock()
defer r.Unlock()
now := time.Now()
last, exists := r.lastActionTimes[category]
if !exists {
r.G().Log.Debug("Rate limit %s checked for the first time.", category)
r.lastActionTimes[category] = now
return true
}
timeSince := now.Sub(last)
if timeSince >= interval {
r.G().Log.Debug("Rate limit %s passed.", category)
r.lastActionTimes[category] = now
return true
}
r.G().Log.Debug("Rate limit %s too recent.", category)
return false
}