ratelimit.go 4.3 KB

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