Subject: [PATCH] Replace github.com/juju/ratelimit with golang.org/x/time/rate juju/ratelimit is LGPL-3.0. It only backs the server-side fallback rate limit (LimitFallback); golang.org/x/time/rate (BSD-3-Clause) gives the same token bucket. RatelimitedConn.Bucket becomes RatelimitedConn.Limiter; Xray does not use the field. Reads larger than the burst wait in burst-sized steps. --- --- a/go.mod +++ b/go.mod @@ -4,11 +4,11 @@ require ( github.com/cloudflare/circl v1.6.3 - github.com/juju/ratelimit v1.0.2 github.com/pires/go-proxyproto v0.11.0 github.com/refraction-networking/utls v1.8.2 golang.org/x/crypto v0.48.0 golang.org/x/sys v0.41.0 + golang.org/x/time v0.14.0 ) require ( --- a/tls.go +++ b/tls.go @@ -43,6 +43,7 @@ "errors" "fmt" "io" + "math" "net" "os" "runtime" @@ -50,10 +51,10 @@ "sync" "time" - "github.com/juju/ratelimit" "github.com/pires/go-proxyproto" "golang.org/x/crypto/curve25519" "golang.org/x/crypto/hkdf" + "golang.org/x/time/rate" ) type CloseWriteConn interface { @@ -103,8 +104,8 @@ type RatelimitedConn struct { net.Conn - After int64 - Bucket *ratelimit.Bucket + After int64 + Limiter *rate.Limiter } func (c *RatelimitedConn) Read(b []byte) (int, error) { @@ -113,12 +114,23 @@ if c.After > 0 { c.After -= int64(n) } else { - c.Bucket.Wait(int64(n)) + waitTokens(c.Limiter, n) } } return n, err } +// waitTokens blocks until n tokens have been taken. rate.Limiter refuses a +// single request larger than its burst, so large reads wait in burst-sized steps. +func waitTokens(l *rate.Limiter, n int) { + burst := l.Burst() + for n > 0 { + k := min(n, burst) + _ = l.WaitN(context.Background(), k) + n -= k + } +} + func NewRatelimitedConn(conn net.Conn, limit *LimitFallback) net.Conn { if limit.BytesPerSec == 0 { return conn @@ -128,11 +140,12 @@ if burstBytesPerSec < limit.BytesPerSec { burstBytesPerSec = limit.BytesPerSec } + burst := int(min(burstBytesPerSec, uint64(math.MaxInt32))) return &RatelimitedConn{ - Conn: conn, - After: int64(limit.AfterBytes), - Bucket: ratelimit.NewBucketWithRate(float64(limit.BytesPerSec), int64(burstBytesPerSec)), + Conn: conn, + After: int64(limit.AfterBytes), + Limiter: rate.NewLimiter(rate.Limit(limit.BytesPerSec), burst), } }