1
0
Fork 0
mirror of https://github.com/diamondburned/arikawa.git synced 2024-12-11 07:54:58 +00:00
arikawa/utils/ws/throttler.go
diamondburned 5811606559
gateway: Fix Send rate limiting
Prior to this commit, gateways can send 120 events before being
throttled at a terribly slow rate of 1 send per minute.

This commit permits gateways to send 5 events before being throttled at
a rate of slightly less than 120 events per minute.
2022-12-07 00:25:55 -08:00

40 lines
1.1 KiB
Go

package ws
import (
"time"
"golang.org/x/time/rate"
)
// SendBurst determines the number of gateway commands that can be sent all at
// once before being throttled. The higher the burst, the slower the rate
// limiter recovers.
var SendBurst = 5
// NewSendLimiter returns a rate limiter for throttling gateway commands.
func NewSendLimiter() *rate.Limiter {
const perMinute = 120
return rate.NewLimiter(
// Permit r = minute / (120 - b) commands per second.
rate.Every(time.Minute/(perMinute-time.Duration(SendBurst))),
SendBurst,
)
}
// NewDialLimiter returns a rate limiter for throttling new gateway connections.
func NewDialLimiter() *rate.Limiter {
return rate.NewLimiter(rate.Every(5*time.Second), 1)
}
// NewIdentityLimiter returns a rate limiter for throttling gateway Identify
// commands.
func NewIdentityLimiter() *rate.Limiter {
return NewDialLimiter() // same
}
// NewGlobalIdentityLimiter returns a rate limiter for throttling global
// gateway Identify commands.
func NewGlobalIdentityLimiter() *rate.Limiter {
return rate.NewLimiter(rate.Every(24*time.Hour), 1000)
}