From a12885fa6127db0aa3c29d33fc8ddeeb1fa1530c Mon Sep 17 00:00:00 2001 From: Bohdan Storozhuk Date: Mon, 31 Oct 2022 03:13:03 +0000 Subject: [PATCH] Make int64 based atomic ratelimiter default (#101) * Fix return timestamp discrepancy between regular atomic limiter and int64 based one * Make int64 based atomic limiter default Long story: this was added in #85, but reverted in #91 due to #90. #95 fixed the issue, so we're moving forward with the new implementation. --- limiter_atomic_int64.go | 10 ++++++++-- ratelimit.go | 2 +- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/limiter_atomic_int64.go b/limiter_atomic_int64.go index 38604ba..8f2e66c 100644 --- a/limiter_atomic_int64.go +++ b/limiter_atomic_int64.go @@ -82,6 +82,12 @@ func (t *atomicInt64Limiter) Take() time.Time { break } } - t.clock.Sleep(time.Duration(newTimeOfNextPermissionIssue - now)) - return time.Unix(0, newTimeOfNextPermissionIssue) + + sleepDuration := time.Duration(newTimeOfNextPermissionIssue - now) + if sleepDuration > 0 { + t.clock.Sleep(sleepDuration) + return time.Unix(0, newTimeOfNextPermissionIssue) + } + // return now if we don't sleep as atomicLimiter does + return time.Unix(0, now) } diff --git a/ratelimit.go b/ratelimit.go index 7370526..22b88ec 100644 --- a/ratelimit.go +++ b/ratelimit.go @@ -54,7 +54,7 @@ type config struct { // New returns a Limiter that will limit to the given RPS. func New(rate int, opts ...Option) Limiter { - return newAtomicBased(rate, opts...) + return newAtomicInt64Based(rate, opts...) } // buildConfig combines defaults with options.