Class: RedisTokenBucket::Limiter
- Inherits:
-
Object
- Object
- RedisTokenBucket::Limiter
- Defined in:
- lib/redis_token_bucket/limiter.rb
Instance Method Summary collapse
-
#batch_charge(*charges) ⇒ Object
performs several bucket charge operations in batch.
-
#charge(bucket, amount, options = nil) ⇒ Object
charges ‘amount` tokens to the specified `bucket`.
-
#initialize(redis, clock = nil) ⇒ Limiter
constructor
A new instance of Limiter.
-
#read_level(bucket) ⇒ Object
returns the current level of tokens in the specified ‘bucket`.
-
#read_levels(*buckets) ⇒ Object
reports the current level of tokens for each of the specified ‘buckets`.
Constructor Details
#initialize(redis, clock = nil) ⇒ Limiter
Returns a new instance of Limiter.
3 4 5 6 |
# File 'lib/redis_token_bucket/limiter.rb', line 3 def initialize(redis, clock = nil) @redis = redis @clock = clock end |
Instance Method Details
#batch_charge(*charges) ⇒ Object
performs several bucket charge operations in batch.
each operation is passed in as an Array, containing the parameters for ‘batch`.
charging only happens if all buckets have sufficient tokens. the charges are done transactionally, so either all buckets are charged or none.
returns a tuple (= Array with two elements) containing ‘success:boolean` and `levels:Hash<String, Numeric>` where `levels` is a hash from bucket keys to bucket levels.
32 33 34 35 36 37 38 39 40 41 |
# File 'lib/redis_token_bucket/limiter.rb', line 32 def batch_charge(*charges) charges.each do |(bucket, amount, )| unless amount > 0 = "tried to charge #{amount}, needs to be Numeric and > 0" raise ArgumentError, end end run_script(charges) end |
#charge(bucket, amount, options = nil) ⇒ Object
charges ‘amount` tokens to the specified `bucket`.
charging only happens if the bucket has sufficient tokens. the level of “sufficient tokens” can be adjusted by passing in option
returns a tuple (= Array with two elements) containing ‘success:boolean` and `level:Numeric`
15 16 17 18 19 |
# File 'lib/redis_token_bucket/limiter.rb', line 15 def charge(bucket, amount, = nil) success, levels = batch_charge([bucket, amount, ]) return success, levels[bucket[:key]] end |
#read_level(bucket) ⇒ Object
returns the current level of tokens in the specified ‘bucket`.
44 45 46 |
# File 'lib/redis_token_bucket/limiter.rb', line 44 def read_level(bucket) read_levels(bucket)[bucket[:key]] end |
#read_levels(*buckets) ⇒ Object
reports the current level of tokens for each of the specified ‘buckets`. returns the levels as a Hash from bucket keys to bucket levels.
50 51 52 53 54 |
# File 'lib/redis_token_bucket/limiter.rb', line 50 def read_levels(*buckets) _, levels = run_script(buckets.map { |bucket| [bucket, 0] }) levels end |