Class: ThrottleMachines::Control

Inherits:
Object
  • Object
show all
Defined in:
lib/throttle_machines/control.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key) ⇒ Control

Returns a new instance of Control.



7
8
9
10
# File 'lib/throttle_machines/control.rb', line 7

def initialize(key)
  @key = key
  @rules = {}
end

Instance Attribute Details

#breakerObject (readonly)

Returns the value of attribute breaker.



5
6
7
# File 'lib/throttle_machines/control.rb', line 5

def breaker
  @breaker
end

#keyObject (readonly)

Returns the value of attribute key.



5
6
7
# File 'lib/throttle_machines/control.rb', line 5

def key
  @key
end

#limiterObject (readonly)

Returns the value of attribute limiter.



5
6
7
# File 'lib/throttle_machines/control.rb', line 5

def limiter
  @limiter
end

#retrierObject (readonly)

Returns the value of attribute retrier.



5
6
7
# File 'lib/throttle_machines/control.rb', line 5

def retrier
  @retrier
end

Instance Method Details

#break_on(failures:, within:, timeout: nil) ⇒ Object



17
18
19
20
21
22
23
24
25
# File 'lib/throttle_machines/control.rb', line 17

def break_on(failures:, within:, timeout: nil)
  timeout ||= within
  @rules[:breaker] = {
    failure_threshold: failures,
    timeout: timeout,
    window: within
  }
  self
end

#call(&block) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/throttle_machines/control.rb', line 37

def call(&block)
  setup_components

  # Build execution chain: Retry -> Breaker -> Limiter -> User Code
  execution_chain = block

  # Wrap with rate limiter (innermost, checked first)
  if @limiter
    limiter_wrapped = execution_chain
    execution_chain = proc { @limiter.throttle!(&limiter_wrapped) }
  end

  # Wrap with circuit breaker
  if @breaker
    breaker_wrapped = execution_chain
    execution_chain = proc { @breaker.call(&breaker_wrapped) }
  end

  # Wrap with retry logic (outermost, handles all failures)
  if @retrier
    retry_wrapped = execution_chain
    execution_chain = proc { @retrier.call(&retry_wrapped) }
  end

  execution_chain.call
end

#limit(rate:, per:, algorithm: :gcra) ⇒ Object



12
13
14
15
# File 'lib/throttle_machines/control.rb', line 12

def limit(rate:, per:, algorithm: :gcra)
  @rules[:limit] = { rate: rate, period: per, algorithm: algorithm }
  self
end

#retry_on_failure(times:, backoff: :exponential, base_delay: 1, max_delay: 60) ⇒ Object



27
28
29
30
31
32
33
34
35
# File 'lib/throttle_machines/control.rb', line 27

def retry_on_failure(times:, backoff: :exponential, base_delay: 1, max_delay: 60)
  @rules[:retry] = {
    max_attempts: times,
    jitter: backoff,
    base_delay: base_delay,
    max_delay: max_delay
  }
  self
end