-
Notifications
You must be signed in to change notification settings - Fork 0
/
quota.go
78 lines (64 loc) · 1.55 KB
/
quota.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package rate
import (
"sync"
"time"
)
// Quota tracks the remaining number of requests that can be made within a time
// period.
type Quota struct {
limit *Limited
used uint64
expiresAt time.Time
mu sync.RWMutex
}
func (q *Quota) reset(l *Limited) {
q.mu.Lock()
defer q.mu.Unlock()
q.used = 0
q.expiresAt = time.Now().Add(l.Period)
q.limit = l
}
// Expired checks if the quota has expired.
func (q *Quota) Expired() bool {
q.mu.RLock()
defer q.mu.RUnlock()
return time.Now().After(q.expiresAt)
}
// Remaining is the number of requests that can be made prior to the quota
// expiring. If this returns zero, the request should not be allowed.
func (q *Quota) Remaining() uint64 {
q.mu.RLock()
defer q.mu.RUnlock()
used := q.used
if used > q.limit.MaxRequests {
return 0
}
return q.limit.MaxRequests - used
}
// MaxRequests returns the maximum number of requests that can be made for
// this Quota.
func (q *Quota) MaxRequests() uint64 {
q.mu.RLock()
defer q.mu.RUnlock()
return q.limit.MaxRequests
}
// ResetsIn returns the amount of time before the quota will expire.
func (q *Quota) ResetsIn() time.Duration {
q.mu.RLock()
defer q.mu.RUnlock()
return q.expiresAt.Sub(time.Now())
}
// Expiration returns the time that the quota will expire.
func (q *Quota) Expiration() time.Time {
q.mu.RLock()
defer q.mu.RUnlock()
return q.expiresAt
}
// Consume reduces the quota's remaining requests by one.
func (q *Quota) Consume() {
q.mu.Lock()
defer q.mu.Unlock()
q.used++
}