Class: ThrottleMachines::Storage::Redis

Inherits:
Base
  • Object
show all
Defined in:
lib/throttle_machines/storage/redis.rb

Constant Summary collapse

LUA_SCRIPTS_DIR =

Load Lua scripts from files

File.expand_path('redis', __dir__)
GCRA_SCRIPT =
File.read(File.join(LUA_SCRIPTS_DIR, 'gcra.lua'))
TOKEN_BUCKET_SCRIPT =
File.read(File.join(LUA_SCRIPTS_DIR, 'token_bucket.lua'))
PEEK_GCRA_SCRIPT =
File.read(File.join(LUA_SCRIPTS_DIR, 'peek_gcra.lua'))
PEEK_TOKEN_BUCKET_SCRIPT =
File.read(File.join(LUA_SCRIPTS_DIR, 'peek_token_bucket.lua'))
INCREMENT_COUNTER_SCRIPT =
File.read(File.join(LUA_SCRIPTS_DIR, 'increment_counter.lua'))

Instance Method Summary collapse

Methods inherited from Base

#with_timeout

Constructor Details

#initialize(options = {}) ⇒ Redis

Breaker scripts removed: breaker state is owned by BreakerMachines



16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/throttle_machines/storage/redis.rb', line 16

def initialize(options = {})
  super
  @redis = options[:redis] || options[:client] || options[:pool]
  @prefix = options[:prefix] || 'throttle:'

  # Cache scripts to avoid repeated script loads
  @gcra_sha = nil
  @token_bucket_sha = nil
  @peek_gcra_sha = nil
  @peek_token_bucket_sha = nil

  # Validate Redis connection
  validate_redis_connection!
end

Instance Method Details

#check_gcra_limit(key, emission_interval, delay_tolerance, ttl) ⇒ Object

GCRA operations (atomic via Lua)



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
# File 'lib/throttle_machines/storage/redis.rb', line 58

def check_gcra_limit(key, emission_interval, delay_tolerance, ttl)
  ensure_gcra_script_loaded!

  result = with_redis do |redis|
    redis.evalsha(
      @gcra_sha,
      keys: [prefixed(key)],
      argv: [emission_interval, delay_tolerance, ttl, current_time]
    )
  end

  allowed = result[0] == 1
  tat = result[1]
  now = current_time

  {
    allowed: allowed,
    retry_after: allowed ? 0 : (tat - now - delay_tolerance),
    tat: tat
  }
rescue ::Redis::CommandError => e
  raise unless e.message.include?('NOSCRIPT')

  @gcra_sha = nil
  retry
end

#check_token_bucket(key, capacity, refill_rate, ttl) ⇒ Object

Token bucket operations (atomic via Lua)



86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/throttle_machines/storage/redis.rb', line 86

def check_token_bucket(key, capacity, refill_rate, ttl)
  ensure_token_bucket_script_loaded!

  result = with_redis do |redis|
    redis.evalsha(
      @token_bucket_sha,
      keys: [prefixed(key)],
      argv: [capacity, refill_rate, ttl, current_time]
    )
  end

  allowed = result[0] == 1
  tokens = result[1]

  {
    allowed: allowed,
    retry_after: allowed ? 0 : (1 - tokens) / refill_rate,
    tokens_remaining: tokens.floor
  }
rescue ::Redis::CommandError => e
  raise unless e.message.include?('NOSCRIPT')

  @token_bucket_sha = nil
  retry
end

#clear(pattern = nil) ⇒ Object

Utility operations



169
170
171
172
173
174
175
176
177
178
179
180
181
# File 'lib/throttle_machines/storage/redis.rb', line 169

def clear(pattern = nil)
  # Use SCAN instead of KEYS to avoid blocking in production
  cursor = '0'
  scan_pattern = pattern ? prefixed(pattern) : "#{@prefix}*"

  with_redis do |redis|
    loop do
      cursor, keys = redis.scan(cursor, match: scan_pattern, count: 100)
      redis.del(*keys) unless keys.empty?
      break if cursor == '0'
    end
  end
end

#get_counter(key, window) ⇒ Object



41
42
43
44
# File 'lib/throttle_machines/storage/redis.rb', line 41

def get_counter(key, window)
  window_key = prefixed("#{key}:#{window}")
  with_redis { |r| (r.get(window_key) || 0).to_i }
end

#get_counter_ttl(key, window) ⇒ Object



46
47
48
49
50
# File 'lib/throttle_machines/storage/redis.rb', line 46

def get_counter_ttl(key, window)
  window_key = prefixed("#{key}:#{window}")
  ttl = with_redis { |r| r.ttl(window_key) }
  [ttl, 0].max
end

#healthy?Boolean

Returns:



183
184
185
186
187
# File 'lib/throttle_machines/storage/redis.rb', line 183

def healthy?
  with_redis { |r| r.ping == 'PONG' }
rescue StandardError
  false
end

#increment_counter(key, window, amount = 1) ⇒ Object

Rate limiting operations



32
33
34
35
36
37
38
39
# File 'lib/throttle_machines/storage/redis.rb', line 32

def increment_counter(key, window, amount = 1)
  window_key = prefixed("#{key}:#{window}")

  # Use Lua script for atomic increment with TTL
  with_redis do |redis|
    redis.eval(INCREMENT_COUNTER_SCRIPT, keys: [window_key], argv: [amount, window.to_i])
  end
end

#peek_gcra_limit(key, emission_interval, delay_tolerance) ⇒ Object

Peek methods for non-consuming checks



113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/throttle_machines/storage/redis.rb', line 113

def peek_gcra_limit(key, emission_interval, delay_tolerance)
  ensure_peek_gcra_script_loaded!

  result = with_redis do |redis|
    redis.evalsha(
      @peek_gcra_sha,
      keys: [prefixed(key)],
      argv: [emission_interval, delay_tolerance, current_time]
    )
  end

  allowed = result[0] == 1
  tat = result[1]
  now = current_time

  {
    allowed: allowed,
    retry_after: allowed ? 0 : (tat - now - delay_tolerance),
    tat: tat
  }
rescue ::Redis::CommandError => e
  raise unless e.message.include?('NOSCRIPT')

  @peek_gcra_sha = nil
  retry
end

#peek_token_bucket(key, capacity, refill_rate) ⇒ Object



140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/throttle_machines/storage/redis.rb', line 140

def peek_token_bucket(key, capacity, refill_rate)
  ensure_peek_token_bucket_script_loaded!

  result = with_redis do |redis|
    redis.evalsha(
      @peek_token_bucket_sha,
      keys: [prefixed(key)],
      argv: [capacity, refill_rate, current_time]
    )
  end

  allowed = result[0] == 1
  tokens_remaining = result[1]

  {
    allowed: allowed,
    retry_after: allowed ? 0 : (1 - tokens_remaining) / refill_rate,
    tokens_remaining: tokens_remaining.floor
  }
rescue ::Redis::CommandError => e
  raise unless e.message.include?('NOSCRIPT')

  @peek_token_bucket_sha = nil
  retry
end

#reset_counter(key, window) ⇒ Object



52
53
54
55
# File 'lib/throttle_machines/storage/redis.rb', line 52

def reset_counter(key, window)
  window_key = prefixed("#{key}:#{window}")
  with_redis { |r| r.del(window_key) }
end