github.com/meowstercatel/discordgo@v0.0.0-20250615204139-29b43d676735/ratelimit.go (about) 1 package discordgo 2 3 import ( 4 "math" 5 "net/http" 6 "strconv" 7 "strings" 8 "sync" 9 "sync/atomic" 10 "time" 11 ) 12 13 // customRateLimit holds information for defining a custom rate limit 14 type customRateLimit struct { 15 suffix string 16 requests int 17 reset time.Duration 18 } 19 20 // RateLimiter holds all ratelimit buckets 21 type RateLimiter struct { 22 sync.Mutex 23 global *int64 24 buckets map[string]*Bucket 25 globalRateLimit time.Duration 26 customRateLimits []*customRateLimit 27 } 28 29 // NewRatelimiter returns a new RateLimiter 30 func NewRatelimiter() *RateLimiter { 31 32 return &RateLimiter{ 33 buckets: make(map[string]*Bucket), 34 global: new(int64), 35 customRateLimits: []*customRateLimit{ 36 { 37 suffix: "//reactions//", 38 requests: 1, 39 reset: 200 * time.Millisecond, 40 }, 41 }, 42 } 43 } 44 45 // GetBucket retrieves or creates a bucket 46 func (r *RateLimiter) GetBucket(key string) *Bucket { 47 r.Lock() 48 defer r.Unlock() 49 50 if bucket, ok := r.buckets[key]; ok { 51 return bucket 52 } 53 54 b := &Bucket{ 55 Remaining: 1, 56 Key: key, 57 global: r.global, 58 } 59 60 // Check if there is a custom ratelimit set for this bucket ID. 61 for _, rl := range r.customRateLimits { 62 if strings.HasSuffix(b.Key, rl.suffix) { 63 b.customRateLimit = rl 64 break 65 } 66 } 67 68 r.buckets[key] = b 69 return b 70 } 71 72 // GetWaitTime returns the duration you should wait for a Bucket 73 func (r *RateLimiter) GetWaitTime(b *Bucket, minRemaining int) time.Duration { 74 // If we ran out of calls and the reset time is still ahead of us 75 // then we need to take it easy and relax a little 76 if b.Remaining < minRemaining && b.reset.After(time.Now()) { 77 return b.reset.Sub(time.Now()) 78 } 79 80 // Check for global ratelimits 81 sleepTo := time.Unix(0, atomic.LoadInt64(r.global)) 82 if now := time.Now(); now.Before(sleepTo) { 83 return sleepTo.Sub(now) 84 } 85 86 return 0 87 } 88 89 // LockBucket Locks until a request can be made 90 func (r *RateLimiter) LockBucket(bucketID string) *Bucket { 91 return r.LockBucketObject(r.GetBucket(bucketID)) 92 } 93 94 // LockBucketObject Locks an already resolved bucket until a request can be made 95 func (r *RateLimiter) LockBucketObject(b *Bucket) *Bucket { 96 b.Lock() 97 98 if wait := r.GetWaitTime(b, 1); wait > 0 { 99 time.Sleep(wait) 100 } 101 102 b.Remaining-- 103 return b 104 } 105 106 // Bucket represents a ratelimit bucket, each bucket gets ratelimited individually (-global ratelimits) 107 type Bucket struct { 108 sync.Mutex 109 Key string 110 Remaining int 111 limit int 112 reset time.Time 113 global *int64 114 115 lastReset time.Time 116 customRateLimit *customRateLimit 117 Userdata interface{} 118 } 119 120 // Release unlocks the bucket and reads the headers to update the buckets ratelimit info 121 // and locks up the whole thing in case if there's a global ratelimit. 122 func (b *Bucket) Release(headers http.Header) error { 123 defer b.Unlock() 124 125 // Check if the bucket uses a custom ratelimiter 126 if rl := b.customRateLimit; rl != nil { 127 if time.Now().Sub(b.lastReset) >= rl.reset { 128 b.Remaining = rl.requests - 1 129 b.lastReset = time.Now() 130 } 131 if b.Remaining < 1 { 132 b.reset = time.Now().Add(rl.reset) 133 } 134 return nil 135 } 136 137 if headers == nil { 138 return nil 139 } 140 141 remaining := headers.Get("X-RateLimit-Remaining") 142 reset := headers.Get("X-RateLimit-Reset") 143 global := headers.Get("X-RateLimit-Global") 144 resetAfter := headers.Get("X-RateLimit-Reset-After") 145 146 // Update global and per bucket reset time if the proper headers are available 147 // If global is set, then it will block all buckets until after Retry-After 148 // If Retry-After without global is provided it will use that for the new reset 149 // time since it's more accurate than X-RateLimit-Reset. 150 // If Retry-After after is not proided, it will update the reset time from X-RateLimit-Reset 151 if resetAfter != "" { 152 parsedAfter, err := strconv.ParseFloat(resetAfter, 64) 153 if err != nil { 154 return err 155 } 156 157 whole, frac := math.Modf(parsedAfter) 158 resetAt := time.Now().Add(time.Duration(whole) * time.Second).Add(time.Duration(frac*1000) * time.Millisecond) 159 160 // Lock either this single bucket or all buckets 161 if global != "" { 162 atomic.StoreInt64(b.global, resetAt.UnixNano()) 163 } else { 164 b.reset = resetAt 165 } 166 } else if reset != "" { 167 // Calculate the reset time by using the date header returned from discord 168 discordTime, err := http.ParseTime(headers.Get("Date")) 169 if err != nil { 170 return err 171 } 172 173 unix, err := strconv.ParseFloat(reset, 64) 174 if err != nil { 175 return err 176 } 177 178 // Calculate the time until reset and add it to the current local time 179 // some extra time is added because without it i still encountered 429's. 180 // The added amount is the lowest amount that gave no 429's 181 // in 1k requests 182 whole, frac := math.Modf(unix) 183 delta := time.Unix(int64(whole), 0).Add(time.Duration(frac*1000)*time.Millisecond).Sub(discordTime) + time.Millisecond*250 184 b.reset = time.Now().Add(delta) 185 } 186 187 // Udpate remaining if header is present 188 if remaining != "" { 189 parsedRemaining, err := strconv.ParseInt(remaining, 10, 32) 190 if err != nil { 191 return err 192 } 193 b.Remaining = int(parsedRemaining) 194 } 195 196 return nil 197 }