Class: Rookout::Augs::AugRateLimiter
- Inherits:
-
Object
- Object
- Rookout::Augs::AugRateLimiter
- Defined in:
- lib/rookout/augs/aug_rate_limiter.rb
Instance Method Summary collapse
- #after_run(start_time) ⇒ Object
- #before_run(start_time) ⇒ Object
-
#initialize(quota, window_size, active_limit) ⇒ AugRateLimiter
constructor
A new instance of AugRateLimiter.
Constructor Details
#initialize(quota, window_size, active_limit) ⇒ AugRateLimiter
Returns a new instance of AugRateLimiter.
7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
# File 'lib/rookout/augs/aug_rate_limiter.rb', line 7 def initialize quota, window_size, active_limit @quota = quota @has_quota = !@quota.nil? && (@quota > 0) @window_size = window_size if active_limit > 0 @active_weight = quota / active_limit else @active_weight = 0 end @mutex = Mutex.new @active_count = 0 @windows = {} end |
Instance Method Details
#after_run(start_time) ⇒ Object
47 48 49 50 51 52 53 54 55 56 57 |
# File 'lib/rookout/augs/aug_rate_limiter.rb', line 47 def after_run start_time if @has_quota now_ns = Utils.time_to_nanoseconds start_time current_window_key, = now_ns time_used = Utils.time_to_nanoseconds(Time.now) - now_ns time_recorded = time_used > Config.min_rate_limit_value_ns ? time_used : Config.min_rate_limit_value_ns @mutex.synchronize { record_usage current_window_key, time_recorded } end # Reduce active count @mutex.synchronize { @active_count -= 1 } end |
#before_run(start_time) ⇒ Object
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/rookout/augs/aug_rate_limiter.rb', line 22 def before_run start_time # If no quota, we can safely exit unless @has_quota return true end now_ns = Utils.time_to_nanoseconds start_time current_window_key, prev_window_key = now_ns @mutex.synchronize do # Clean old windows cleanup now_ns usage = current_usage now_ns, current_window_key, prev_window_key @active_count += 1 # If exceeding quota if usage > @quota warning = Processor::RookError.new Exceptions::RookRuleRateLimited.create UserWarnings.notify_warning warning return false end return true end end |