Skip to content

Commit

Permalink
Improve rate limit error msg and deprecate codes (#41)
Browse files Browse the repository at this point in the history
  • Loading branch information
wanliqun authored May 22, 2024
1 parent 1bd8b03 commit c4dfe75
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 18 deletions.
21 changes: 4 additions & 17 deletions rate/fixed_window.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ func NewFixedWindow(interval time.Duration, max int) Limiter {
return &FixedWindow{
interval: interval,
max: int64(max),
startTime: toUnixMilli(time.Now().Truncate(interval)),
startTime: time.Now().Truncate(interval).UnixMilli(),
}
}

Expand All @@ -45,14 +45,14 @@ func (window *FixedWindow) LimitAt(now time.Time, n int) error {
atomic.AddInt64(&window.count, int64(-n))

startTime := atomic.LoadInt64(&window.startTime)
nextTime := fromUnixMilli(startTime).Add(window.interval)
nextTime := time.UnixMilli(startTime).Add(window.interval)
waitTime := nextTime.Sub(now)

return errRateLimited(int(window.max), waitTime)
}

func (window *FixedWindow) advance(now time.Time) {
truncated := toUnixMilli(now.Truncate(window.interval))
truncated := now.Truncate(window.interval).UnixMilli()

if startTime := atomic.LoadInt64(&window.startTime); startTime < truncated {
// reset
Expand All @@ -63,18 +63,5 @@ func (window *FixedWindow) advance(now time.Time) {

func (window *FixedWindow) Expired() bool {
startTime := atomic.LoadInt64(&window.startTime)
return time.Since(fromUnixMilli(startTime)) > window.interval
}

// TODO: deprecate the following time utility functions if the minimum version
// of Go required by the package is gte 1.7.

// toUnixMilli returns unix timestamp in milliseconds for specific time.
func toUnixMilli(t time.Time) int64 {
return t.UnixNano() / (1e6)
}

// fromUnixMilli returns time of specific unix timestamp in milliseconds.
func fromUnixMilli(msec int64) time.Time {
return time.Unix(msec/1e3, (msec%1e3)*1e6)
return time.Since(time.UnixMilli(startTime)) > window.interval
}
2 changes: 1 addition & 1 deletion rate/token_bucket.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ func (bucket *TokenBucket) LimitAt(now time.Time, n int) error {

if waitTime := rsv.Delay(); waitTime > 0 {
rsv.Cancel()
return errRateLimited(bucket.inner.Burst(), waitTime)
return errRateLimited(int(bucket.inner.Limit()), waitTime)
}

atomic.StoreInt64(&bucket.lastSeen, now.Unix())
Expand Down

0 comments on commit c4dfe75

Please sign in to comment.