forked from andersfylling/disgord
/
bucket.go
249 lines (213 loc) · 6.37 KB
/
bucket.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
package httd
import (
"context"
"errors"
"net/http"
"strconv"
"sync"
"time"
"github.com/Vedza/disgord/internal/util"
)
func newLeakyBucket(global *ltBucket) (b *ltBucket) {
b = <Bucket{
remaining: -1,
resetTime: time.Now(),
global: global,
}
return b
}
type bucketTransaction = func() (resp *http.Response, body []byte, err error)
// ltBucket combines leaky and token buckets to allow time aware of the REST requests while they're in queue.
type ltBucket struct {
mu sync.RWMutex
atomicLock util.AtomicLock
hash string // discord designated hash
queue util.TicketQueue // Ticket => Token
remaining int // remaining requests
resetTime time.Time // affected by time diff
discordResetTime time.Time // unaffected by time diff
updatedAt time.Time // use date from discord header
// this bucket is global if this.global is nil or this == this.global
global *ltBucket
usingGlobal bool
}
var _ RESTBucket = (*ltBucket)(nil)
func (b *ltBucket) AcquireLock() (locked bool) {
if locked = b.atomicLock.AcquireLock(); !locked {
return false
}
if _, err := b.SelectiveGlobalLock(); err != nil {
b.atomicLock.Unlock()
return false
}
return true
}
func (b *ltBucket) SelectiveGlobalLock() (locked bool, err error) {
if b != b.global {
// peek global ltBucket
b.global.mu.RLock()
globalLock := b.global.active()
b.global.mu.RUnlock()
// TODO: can this cause http 429?
if globalLock {
// so check if the globalLock has changed since the read
if locked = b.global.atomicLock.AcquireLock(); !locked {
return false, errors.New("unable to acquire needed global lock")
}
b.global.mu.RLock()
if !b.global.active() {
b.global.atomicLock.Unlock()
locked = true
} else {
b.usingGlobal = true
}
b.global.mu.RUnlock()
}
}
return locked, nil
}
func (b *ltBucket) Transaction(ctx context.Context, do bucketTransaction) (resp *http.Response, body []byte, err error) {
// wait until you are next in line and you can acquire a lock
// this is to support timeout/cancellation for stacked requests
// TODO: on success, every request with same endpoint or a valid subset can be fulfilled locally
// reqA = /guilds/1/members?limit=100
// reqB = /guilds/1/members?limit=10
// reqB is a subset of A, and therefore reqA can create a response for reqB locally (must be deep copy - djp)
token := b.queue.NewTicket()
for {
select {
case <-ctx.Done():
b.queue.Delete(token)
return nil, nil, errors.New("time out")
case <-time.After(10 * time.Millisecond):
// TODO-perf: this wastes a lot of CPU usage
}
if !b.queue.Next(token, b.AcquireLock) {
continue
}
break
}
defer b.atomicLock.Unlock()
if b.usingGlobal {
defer b.global.atomicLock.Unlock()
defer func() {
b.usingGlobal = false
}()
}
// set active ltBucket
var bucket *ltBucket
if b.usingGlobal {
bucket = b.global
} else {
bucket = b
}
// check if rate limited and try to wait it out
var wait time.Duration
now := time.Now()
if bucket.resetTime.After(now) && bucket.remaining == 0 {
wait = bucket.resetTime.Sub(now)
}
if deadline, ok := ctx.Deadline(); ok && deadline.Before(time.Now().Add(wait)) {
return nil, nil, errors.New("time out, bucket resets in " + wait.String())
}
select {
case <-ctx.Done():
return nil, nil, errors.New("time out")
case <-time.After(wait):
}
// send request
resp, body, err = do()
if err != nil {
return nil, nil, err
}
// update ltBucket info
// reduce remaining if needed
if !b.updateAfterRequest(resp.Header, resp.StatusCode) && bucket.remaining > 0 {
bucket.remaining--
}
return resp, body, nil
}
// updateAfterRequests updates the bucket with the latest rate limit info from http responses.
//
// Note! you must call NormalizeDiscordHeader before using this.
func (b *ltBucket) updateAfterRequest(header http.Header, statusCode int) (adjustedRemaining bool) {
if normalized := header.Get(DisgordNormalizedHeader); normalized == "" {
panic("headers were not normalized to use milliseconds")
}
// to synchronize the timestamp between the bot and the discord server
// we assume the current time is equal the header date
discordTime, err := HeaderToTime(header)
if err != nil {
discordTime = time.Now()
}
localTime := time.Now()
diff := localTime.Sub(discordTime)
var isGlobal bool
bucketHash := header.Get(XRateLimitBucket)
if _, ok := header[XRateLimitBucket]; ok && bucketHash == "" {
isGlobal = true
}
isGlobal = isGlobal || header.Get(XRateLimitGlobal) == "true"
// if this is not a 429 error we can determine if the local ltBucket is a global one or not
if statusCode != http.StatusTooManyRequests && b.hash == "" {
if isGlobal {
b.hash = GlobalHash
} else if bucketHash != "" {
b.hash = bucketHash
}
}
var reset time.Time
var discordReset time.Time
var remaining int = -1
if resetStr := header.Get(XRateLimitReset); resetStr != "" {
epoch, _ := strconv.ParseInt(resetStr, 10, 64)
epoch *= int64(time.Millisecond) // ms => nano
reset = time.Unix(0, epoch+diff.Nanoseconds())
discordReset = time.Unix(0, epoch)
}
if remainingStr := header.Get(XRateLimitRemaining); remainingStr != "" {
remainingInt64, _ := strconv.ParseInt(remainingStr, 10, 64)
if remainingInt64 >= 0 {
remaining = int(remainingInt64)
}
}
// update ltBucket reference to whatever the header regards
var bucket *ltBucket
if isGlobal {
if b.global == b {
bucket = b
} else {
bucket = b.global
}
bucket.mu.Lock()
defer bucket.mu.Unlock()
} else {
bucket = b // no need to lock normal buckets
if !(b.global == nil || b == b.global) && bucketHash != "" {
b.hash = bucketHash
}
}
if discordReset.Before(time.Unix(0, int64(time.Hour))) {
return false
}
// TODO: this can be simpler
// use discord reset time, as the local reset can be different in ms or s per request.
if discordReset.After(bucket.discordResetTime) {
bucket.resetTime = reset
bucket.discordResetTime = discordReset
bucket.remaining = remaining
bucket.updatedAt = discordTime
adjustedRemaining = true
} else if bucket.discordResetTime == discordReset {
if bucket.remaining == -1 || bucket.remaining > remaining {
bucket.remaining = remaining
bucket.updatedAt = discordTime
bucket.discordResetTime = discordReset
adjustedRemaining = true
}
}
return adjustedRemaining
}
func (b *ltBucket) active() bool {
return b.remaining >= 0 && !time.Now().After(b.resetTime)
}