Module: CMDx::Limiters::LeakyBucket Private
Overview
This module is part of a private API. You should avoid using this module if possible, as it may be removed or be changed in the future.
Continuous leaky bucket backed by a single store key (store_key:lb).
Leaks one unit every per seconds; admits when level + cost <= max.
Instance Method Summary collapse
Instance Method Details
#call(quota) ⇒ RateLimit::Admission
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/cmdx/limiters/leaky_bucket.rb', line 15 def call(quota) state_key = "#{quota.store_key}:lb" now = Time.now.to_f level, last_at = parse_state(Stores.get(state_key), now) leaked = (now - last_at) / quota.per if leaked.positive? level -= leaked level = 0.0 if level.negative? end cost = quota.cost capacity = quota.max projected = level + cost admitted = projected <= capacity level = projected if admitted Stores.set(state_key, "#{level}:#{now}", ttl: bucket_ttl(quota)) retry_after = unless admitted overflow = projected - capacity overflow = 0 if overflow.negative? (overflow * quota.per).ceil end RateLimit::Admission.new( admitted:, count: nil, level:, retry_after:, limiter: :leaky_bucket ) end |