Class: Jumbotron::Providers::Espn::Cooldown

Inherits:
Object
  • Object
show all
Defined in:
app/providers/jumbotron/providers/espn/cooldown.rb

Overview

Provider-wide ESPN availability cooldown. Backed by Rails-configured cache/store.

Constant Summary collapse

STATE_KEY =
"jumbotron:providers:espn:cooldown"
BASE_DELAY_SECONDS =
5
MAX_DELAY_SECONDS =
180

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(store: Rails.cache, clock: -> { Time.current }) ⇒ Cooldown

Returns a new instance of Cooldown.



12
13
14
15
# File 'app/providers/jumbotron/providers/espn/cooldown.rb', line 12

def initialize(store: Rails.cache, clock: -> { Time.current })
  @store = store
  @clock = clock
end

Class Method Details

.delay_for(failure_count) ⇒ Object



50
51
52
# File 'app/providers/jumbotron/providers/espn/cooldown.rb', line 50

def self.delay_for(failure_count)
  [BASE_DELAY_SECONDS * (2**(failure_count - 1)), MAX_DELAY_SECONDS].min
end

Instance Method Details

#cooling_down?(now: clock.call) ⇒ Boolean

rubocop:enable Naming/PredicateMethod

Returns:

  • (Boolean)


34
35
36
# File 'app/providers/jumbotron/providers/espn/cooldown.rb', line 34

def cooling_down?(now: clock.call)
  retry_after(now: now).positive?
end

#failure_countObject



46
47
48
# File 'app/providers/jumbotron/providers/espn/cooldown.rb', line 46

def failure_count
  read_state.fetch(:failure_count, 0)
end

#record_failure!(error, now: clock.call) ⇒ Object

rubocop:disable Naming/PredicateMethod -- bang mutators report whether state changed



18
19
20
21
22
23
24
25
26
# File 'app/providers/jumbotron/providers/espn/cooldown.rb', line 18

def record_failure!(error, now: clock.call)
  return false unless ProviderFailure.availability_failure?(error)

  state = read_state
  count = state.fetch(:failure_count, 0) + 1
  delay = delay_for(count)
  write_state(failure_count: count, cooldown_until: now + delay)
  true
end

#record_success!Object



28
29
30
31
# File 'app/providers/jumbotron/providers/espn/cooldown.rb', line 28

def record_success!
  store.delete(STATE_KEY)
  true
end

#retry_after(now: clock.call) ⇒ Object



38
39
40
41
42
43
44
# File 'app/providers/jumbotron/providers/espn/cooldown.rb', line 38

def retry_after(now: clock.call)
  until_time = read_state[:cooldown_until]
  return 0 if until_time.nil?

  remaining = (until_time - now).to_f
  remaining.positive? ? remaining.ceil : 0
end