Skip to content

Commit

Permalink
Program wide global rate limit
Browse files Browse the repository at this point in the history
  • Loading branch information
MineBartekSA committed May 13, 2021
1 parent e5dde7f commit 4089811
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 1 deletion.
2 changes: 1 addition & 1 deletion discord.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import (
)

// VERSION of DiscordGo, follows Semantic Versioning. (http://semver.org/)
const VERSION = "0.2.10-nlp"
const VERSION = "0.2.15-nlp"

// ErrMFA will be risen by New when the user has 2FA.
var ErrMFA = errors.New("account has 2FA enabled")
Expand Down
19 changes: 19 additions & 0 deletions ratelimit.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,25 @@ import (
"time"
)

var (
GlobalRateLimit = 50
GlobalRateLimitMutex = sync.Mutex{}
GlobalLimit = false
)

// Start a program wide rate limit
func StartGlobalLimit() {
GlobalLimit = true
go func (){
for {
GlobalRateLimitMutex.Lock()
GlobalRateLimit = 50
GlobalRateLimitMutex.Unlock()
time.Sleep(time.Second)
}
}()
}

// customRateLimit holds information for defining a custom rate limit
type customRateLimit struct {
suffix string
Expand Down
17 changes: 17 additions & 0 deletions ratelimit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,23 @@ import (
"time"
)

func TestGlobalRateLimit(t *testing.T) {
StartGlobalLimit()
b1, _ := New("")
b2, _ := New("")

_, _ = b1.User("633751371404804107")
_, _ = b2.User("485853402560200704")
if GlobalRateLimit == 50 {
t.Fatal("Global Rate Limit did not decrease!")
}

time.Sleep(time.Second)
if GlobalRateLimit != 50 {
t.Fatal("Global Rate Limit did not refresh!")
}
}

// This test takes ~2 seconds to run
func TestRatelimitReset(t *testing.T) {
rl := NewRatelimiter()
Expand Down
11 changes: 11 additions & 0 deletions restapi.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,17 @@ func (s *Session) RequestWithBucketID(method, urlStr string, data interface{}, b
// Sequence is the sequence number, if it fails with a 502 it will
// retry with sequence+1 until it either succeeds or sequence >= session.MaxRestRetries
func (s *Session) request(method, urlStr, contentType string, b []byte, bucketID string, sequence int) (response []byte, err error) {
if GlobalLimit {
if GlobalRateLimit == 0 {
log.Println("Global Rate Limit depleted! ("+s.Token[:10]+")") // Note: Temp
}
GlobalRateLimitMutex.Lock()
for GlobalRateLimit == 0 {
time.Sleep(time.Millisecond) // Wait for refresh
}
GlobalRateLimit -= 1
GlobalRateLimitMutex.Unlock()
}
if bucketID == "" {
bucketID = strings.SplitN(urlStr, "?", 2)[0]
}
Expand Down

0 comments on commit 4089811

Please sign in to comment.