Class: FaradayDynamicTimeout::Counter

Inherits:
Object
  • Object
show all
Defined in:
lib/faraday_dynamic_timeout/counter.rb

Instance Method Summary collapse

Constructor Details

#initialize(name:, redis:, ttl: 60.0) ⇒ Counter

Returns a new instance of Counter.



5
6
7
8
9
10
# File 'lib/faraday_dynamic_timeout/counter.rb', line 5

def initialize(name:, redis:, ttl: 60.0)
  @ttl = ttl.to_f
  @ttl = 60.0 if @ttl <= 0.0
  @redis = redis
  @key = "FaradayDynamicTimeout:#{name}"
end

Instance Method Details

#executeObject



12
13
14
15
16
17
18
19
# File 'lib/faraday_dynamic_timeout/counter.rb', line 12

def execute
  id = track!
  begin
    yield
  ensure
    release!(id)
  end
end

#release!(id) ⇒ Object



39
40
41
# File 'lib/faraday_dynamic_timeout/counter.rb', line 39

def release!(id)
  @redis.zrem(@key, id)
end

#track!(id = nil) ⇒ Object



30
31
32
33
34
35
36
37
# File 'lib/faraday_dynamic_timeout/counter.rb', line 30

def track!(id = nil)
  id ||= SecureRandom.hex
  @redis.multi do |transaction|
    transaction.zadd(@key, Time.now.to_f, id)
    transaction.pexpire(@key, (@ttl * 1000).round)
  end
  id
end

#valueObject



21
22
23
24
25
26
27
28
# File 'lib/faraday_dynamic_timeout/counter.rb', line 21

def value
  total_count, expired_count = @redis.multi do |transaction|
    transaction.zcard(@key)
    transaction.zremrangebyscore(@key, "-inf", Time.now.to_f - @ttl)
  end

  total_count - expired_count
end