Class: ThrottleMachines::Limiter

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

Direct Known Subclasses

AsyncLimiter

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key, limit:, period:, algorithm: :fixed_window, storage: nil) ⇒ Limiter

Returns a new instance of Limiter.



7
8
9
10
11
12
13
# File 'lib/throttle_machines/limiter.rb', line 7

def initialize(key, limit:, period:, algorithm: :fixed_window, storage: nil)
  @key = key
  @limit = limit
  @period = period
  @algorithm = algorithm
  @storage = storage || ThrottleMachines.storage
end

Instance Attribute Details

#algorithmObject (readonly)

Returns the value of attribute algorithm.



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

def algorithm
  @algorithm
end

#keyObject (readonly)

Returns the value of attribute key.



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

def key
  @key
end

#limitObject (readonly)

Returns the value of attribute limit.



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

def limit
  @limit
end

#periodObject (readonly)

Returns the value of attribute period.



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

def period
  @period
end

#storageObject (readonly)

Returns the value of attribute storage.



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

def storage
  @storage
end

Instance Method Details

#allow?Boolean

Returns:

  • (Boolean)


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
# File 'lib/throttle_machines/limiter.rb', line 15

def allow?
  allowed = case @algorithm
            when :fixed_window
              # Don't increment here, just check
              count = @storage.get_counter(@key, @period)
              count < @limit
            when :gcra
              result = @storage.peek_gcra_limit(
                @key,
                @period.to_f / @limit,  # emission_interval
                0                       # delay_tolerance (no burst)
              )
              result[:allowed]
            when :token_bucket
              result = @storage.peek_token_bucket(
                @key,
                @limit,                 # capacity
                @limit.to_f / @period   # refill_rate
              )
              result[:allowed]
            else
              raise ArgumentError, "Unknown algorithm: #{@algorithm}"
            end

  # Instrument the check
  Instrumentation.rate_limit_checked(self, allowed: allowed, remaining: nil)

  allowed
end

#remainingObject



101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
# File 'lib/throttle_machines/limiter.rb', line 101

def remaining
  case @algorithm
  when :fixed_window
    count = @storage.get_counter(@key, @period)
    [@limit - count, 0].max
  when :gcra
    # GCRA doesn't have a simple "remaining" count
    # Just return 1 or 0 based on current state
    result = @storage.peek_gcra_limit(
      @key,
      @period.to_f / @limit,
      0
    )
    result[:allowed] ? 1 : 0
  when :token_bucket
    result = @storage.peek_token_bucket(
      @key,
      @limit,
      @limit.to_f / @period
    )
    result[:tokens_remaining].to_i
  else
    0
  end
end

#reset!Object



92
93
94
95
96
97
98
99
# File 'lib/throttle_machines/limiter.rb', line 92

def reset!
  case @algorithm
  when :fixed_window
    @storage.reset_counter(@key, @period)
  else
    @storage.clear("#{@key}*")
  end
end

#retry_afterObject



127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
# File 'lib/throttle_machines/limiter.rb', line 127

def retry_after
  case @algorithm
  when :fixed_window
    count = @storage.get_counter(@key, @period)
    if count >= @limit
      # Return the actual time remaining in the current window
      @storage.get_counter_ttl(@key, @period)
    else
      0
    end
  when :gcra
    result = @storage.peek_gcra_limit(
      @key,
      @period.to_f / @limit,
      0
    )
    result[:retry_after]
  when :token_bucket
    result = @storage.peek_token_bucket(
      @key,
      @limit,
      @limit.to_f / @period
    )
    result[:retry_after]
  else
    0
  end
end

#throttle!Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/throttle_machines/limiter.rb', line 45

def throttle!
  case @algorithm
  when :fixed_window
    # Increment and check atomically
    count = @storage.increment_counter(@key, @period)
    if count > @limit
      Instrumentation.rate_limit_throttled(self, retry_after: retry_after)
      raise ThrottledError, self
    end
  when :gcra
    result = @storage.check_gcra_limit(
      @key,
      @period.to_f / @limit,  # emission_interval
      0,                      # delay_tolerance (no burst)
      (@period * 2).to_i      # ttl
    )
    unless result[:allowed]
      Instrumentation.rate_limit_throttled(self, retry_after: retry_after)
      raise ThrottledError, self
    end
  when :token_bucket
    result = @storage.check_token_bucket(
      @key,
      @limit,                 # capacity
      @limit.to_f / @period,  # refill_rate
      (@period * 2).to_i      # ttl
    )
    unless result[:allowed]
      Instrumentation.rate_limit_throttled(self, retry_after: retry_after)
      raise ThrottledError, self
    end
  else
    raise ArgumentError, "Unknown algorithm: #{@algorithm}"
  end

  # If we get here, the request was allowed
  # Calculate remaining after the operation
  remaining_count = begin
    remaining
  rescue StandardError
    nil
  end
  Instrumentation.rate_limit_allowed(self, remaining: remaining_count)

  yield if block_given?
end

#to_hObject



156
157
158
159
160
161
162
163
164
165
# File 'lib/throttle_machines/limiter.rb', line 156

def to_h
  {
    key: @key,
    limit: @limit,
    period: @period,
    algorithm: @algorithm,
    remaining: remaining,
    retry_after: retry_after
  }
end