class Vox::HTTP::Bucket
@!visibility private A bucket used for HTTP
rate limiting
Attributes
limit[R]
@!attribute [r] limit @return [Integer]
remaining[R]
@!attribute [r] remaining @return [Integer]
reset_time[R]
@!attribute [r] reset_time
@return [Time]
Public Class Methods
new(limit, remaining, reset_time)
click to toggle source
# File lib/vox/http/middleware/rate_limiter.rb, line 20 def initialize(limit, remaining, reset_time) update(limit, remaining, reset_time) @mutex = Mutex.new end
Public Instance Methods
lock_for(duration)
click to toggle source
Lock the mutex for a given duration. Used for cooldown periods
# File lib/vox/http/middleware/rate_limiter.rb, line 48 def lock_for(duration) @mutex.synchronize { sleep duration } end
lock_until_reset()
click to toggle source
Lock the mutex until the bucket resets
# File lib/vox/http/middleware/rate_limiter.rb, line 53 def lock_until_reset time_remaining = @reset_time - Time.now raise 'Cannot sleep for negative duration.' if time_remaining.negative? lock_for(time_remaining) unless locked? end
locked?()
click to toggle source
@return [true, false]
# File lib/vox/http/middleware/rate_limiter.rb, line 62 def locked? @mutex.locked? end
update(limit, remaining, reset_time)
click to toggle source
@param limit [Integer] @param remaining [Integer] @param reset_time
[Time]
# File lib/vox/http/middleware/rate_limiter.rb, line 29 def update(limit, remaining, reset_time) @limit = limit @remaining = remaining @reset_time = reset_time end
wait_until_available()
click to toggle source
Lock and unlock this mutex (prevents access during reset)
# File lib/vox/http/middleware/rate_limiter.rb, line 41 def wait_until_available return unless locked? @mutex.synchronize {} end
will_limit?()
click to toggle source
@return [true, false]
# File lib/vox/http/middleware/rate_limiter.rb, line 36 def will_limit? (@remaining - 1).negative? && Time.now <= @reset_time end