rate_guard 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/CHANGELOG.md +44 -0
- data/LICENSE +21 -0
- data/README.md +237 -0
- data/lib/rate_guard/admission.rb +13 -0
- data/lib/rate_guard/algorithms/fixed_window_counter.rb +83 -0
- data/lib/rate_guard/algorithms/leaky_bucket_meter.rb +93 -0
- data/lib/rate_guard/algorithms/leaky_bucket_queue.rb +93 -0
- data/lib/rate_guard/algorithms/redis_sliding_window_counter.rb +137 -0
- data/lib/rate_guard/algorithms/sliding_window_counter.lua +60 -0
- data/lib/rate_guard/algorithms/sliding_window_counter.rb +148 -0
- data/lib/rate_guard/algorithms/sliding_window_log.rb +105 -0
- data/lib/rate_guard/algorithms/token_bucket.rb +93 -0
- data/lib/rate_guard/bypass.rb +39 -0
- data/lib/rate_guard/clock.rb +20 -0
- data/lib/rate_guard/configuration.rb +77 -0
- data/lib/rate_guard/errors.rb +9 -0
- data/lib/rate_guard/identifiers/api_key.rb +36 -0
- data/lib/rate_guard/identifiers/first_of.rb +28 -0
- data/lib/rate_guard/identifiers/global.rb +14 -0
- data/lib/rate_guard/identifiers/ip.rb +19 -0
- data/lib/rate_guard/identifiers/user.rb +34 -0
- data/lib/rate_guard/identifiers.rb +17 -0
- data/lib/rate_guard/json_log_formatter.rb +29 -0
- data/lib/rate_guard/metrics.rb +49 -0
- data/lib/rate_guard/middleware/client_ip.rb +40 -0
- data/lib/rate_guard/middleware.rb +147 -0
- data/lib/rate_guard/policy.rb +129 -0
- data/lib/rate_guard/policy_set.rb +59 -0
- data/lib/rate_guard/redis_error_reporter.rb +51 -0
- data/lib/rate_guard/registry.rb +109 -0
- data/lib/rate_guard/request.rb +7 -0
- data/lib/rate_guard/result.rb +17 -0
- data/lib/rate_guard/tiers.rb +25 -0
- data/lib/rate_guard/utils/numeric_utils.rb +22 -0
- data/lib/rate_guard/validators/configuration_validator.rb +28 -0
- data/lib/rate_guard/validators/cost_validator.rb +36 -0
- data/lib/rate_guard/version.rb +5 -0
- data/lib/rate_guard.rb +84 -0
- metadata +105 -0
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'digest'
|
|
4
|
+
require 'redis'
|
|
5
|
+
require_relative '../result'
|
|
6
|
+
|
|
7
|
+
module RateGuard
|
|
8
|
+
module Algorithms
|
|
9
|
+
# SlidingWindowCounter stored in Redis, shared by all servers.
|
|
10
|
+
# Each decision is one Lua script, which Redis runs atomically.
|
|
11
|
+
class RedisSlidingWindowCounter
|
|
12
|
+
SCRIPT = File.read(File.expand_path('sliding_window_counter.lua', __dir__)).freeze
|
|
13
|
+
SCRIPT_SHA = Digest::SHA1.hexdigest(SCRIPT).freeze
|
|
14
|
+
|
|
15
|
+
FAILURE_POLICIES = %i[allow reject].freeze
|
|
16
|
+
|
|
17
|
+
# Retry-after sent when failing closed.
|
|
18
|
+
FAIL_CLOSED_RETRY_AFTER = 1.0
|
|
19
|
+
|
|
20
|
+
EPSILON = 1e-9
|
|
21
|
+
|
|
22
|
+
attr_reader :limit, :window, :failure_policy
|
|
23
|
+
|
|
24
|
+
# redis - a Redis client
|
|
25
|
+
# failure_policy - :allow (fail open) or :reject (fail closed) if Redis is down
|
|
26
|
+
# on_error - optional callable, given the error
|
|
27
|
+
# clock - optional; defaults to the Redis server's clock
|
|
28
|
+
def initialize(redis:, limit:, window:, namespace: 'rate_guard', failure_policy: :allow,
|
|
29
|
+
on_error: nil, clock: nil)
|
|
30
|
+
raise ArgumentError, 'redis must respond to #evalsha and #eval' unless redis_client?(redis)
|
|
31
|
+
raise ArgumentError, 'limit must be a positive integer' unless limit.is_a?(Integer) && limit.positive?
|
|
32
|
+
raise ArgumentError, 'window must be a positive number' unless Utils::NumericUtils.positive_number?(window)
|
|
33
|
+
unless FAILURE_POLICIES.include?(failure_policy)
|
|
34
|
+
raise ArgumentError, "failure_policy must be one of #{FAILURE_POLICIES.inspect}"
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
@redis = redis
|
|
38
|
+
@limit = limit
|
|
39
|
+
@window = window
|
|
40
|
+
@prefix = "#{namespace}:w#{window.to_i == window ? window.to_i : window}"
|
|
41
|
+
@failure_policy = failure_policy
|
|
42
|
+
@on_error = on_error
|
|
43
|
+
@clock = clock
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
# Allows the request and spends `cost` if there is room.
|
|
47
|
+
# reserve: extra units that must stay free (for others); only cost is spent.
|
|
48
|
+
def acquire(key, cost: 1, reserve: 0)
|
|
49
|
+
Validators::CostValidator.validate!(
|
|
50
|
+
cost: cost,
|
|
51
|
+
maximum: @limit,
|
|
52
|
+
type: :integer,
|
|
53
|
+
reserve: reserve
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
reply = run_script(redis_key(key), [@limit, @window, cost, @clock ? @clock.now : '', reserve])
|
|
57
|
+
to_result(reply, cost + reserve)
|
|
58
|
+
rescue Redis::BaseConnectionError => e
|
|
59
|
+
@on_error&.call(e)
|
|
60
|
+
failure_result
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
# e.g. "rate_guard:w60:ip:203.0.113.7". The window is in the key,
|
|
64
|
+
# so changing it never reuses old counters.
|
|
65
|
+
def redis_key(key)
|
|
66
|
+
"#{@prefix}:#{key}"
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
private
|
|
70
|
+
|
|
71
|
+
# EVALSHA sends only the script's hash. If Redis lost the script
|
|
72
|
+
# (NOSCRIPT), EVAL sends it once and Redis caches it again.
|
|
73
|
+
def run_script(key, argv)
|
|
74
|
+
@redis.evalsha(SCRIPT_SHA, keys: [key], argv: argv)
|
|
75
|
+
rescue Redis::CommandError => e
|
|
76
|
+
raise unless e.message.start_with?('NOSCRIPT')
|
|
77
|
+
|
|
78
|
+
@redis.eval(SCRIPT, keys: [key], argv: argv)
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
# needed = cost + reserve
|
|
82
|
+
def to_result(reply, needed)
|
|
83
|
+
allowed, estimate, current, previous, index, now = reply
|
|
84
|
+
estimate = Float(estimate)
|
|
85
|
+
now = Float(now)
|
|
86
|
+
window_start = index * @window
|
|
87
|
+
reset_after = reset_after(window_start, current, previous, now)
|
|
88
|
+
|
|
89
|
+
if allowed == 1
|
|
90
|
+
Result.new(allowed: true, remaining: remaining(estimate), retry_after: 0.0, reset_after:)
|
|
91
|
+
else
|
|
92
|
+
retry_after = retry_after(window_start, current, previous, now, needed)
|
|
93
|
+
Result.new(allowed: false, remaining: remaining(estimate), retry_after:, reset_after:)
|
|
94
|
+
end
|
|
95
|
+
end
|
|
96
|
+
|
|
97
|
+
# Fail open: allow everything. Fail closed: reject everything.
|
|
98
|
+
def failure_result
|
|
99
|
+
if @failure_policy == :allow
|
|
100
|
+
Result.new(allowed: true, remaining: @limit, retry_after: 0.0)
|
|
101
|
+
else
|
|
102
|
+
Result.new(allowed: false, remaining: 0, retry_after: FAIL_CLOSED_RETRY_AFTER)
|
|
103
|
+
end
|
|
104
|
+
end
|
|
105
|
+
|
|
106
|
+
def remaining(estimated)
|
|
107
|
+
[(@limit - estimated + EPSILON).floor, 0].max
|
|
108
|
+
end
|
|
109
|
+
|
|
110
|
+
def retry_after(window_start, current, previous, now, cost)
|
|
111
|
+
room = @limit - current - cost
|
|
112
|
+
|
|
113
|
+
if room >= 0
|
|
114
|
+
progress = 1 - room.fdiv(previous)
|
|
115
|
+
window_start + (progress * @window) - now
|
|
116
|
+
else
|
|
117
|
+
progress = 1 - (@limit - cost).fdiv(current)
|
|
118
|
+
window_start + @window + (progress * @window) - now
|
|
119
|
+
end
|
|
120
|
+
end
|
|
121
|
+
|
|
122
|
+
def reset_after(window_start, current, previous, now)
|
|
123
|
+
if current.positive?
|
|
124
|
+
window_start + (2 * @window) - now
|
|
125
|
+
elsif previous.positive?
|
|
126
|
+
window_start + @window - now
|
|
127
|
+
else
|
|
128
|
+
0.0
|
|
129
|
+
end
|
|
130
|
+
end
|
|
131
|
+
|
|
132
|
+
def redis_client?(redis)
|
|
133
|
+
redis.respond_to?(:evalsha) && redis.respond_to?(:eval)
|
|
134
|
+
end
|
|
135
|
+
end
|
|
136
|
+
end
|
|
137
|
+
end
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
-- Sliding window counter, run atomically inside Redis.
|
|
2
|
+
--
|
|
3
|
+
-- KEYS[1] the key's hash: index, current, previous
|
|
4
|
+
-- ARGV[1] limit
|
|
5
|
+
-- ARGV[2] window in seconds
|
|
6
|
+
-- ARGV[3] cost
|
|
7
|
+
-- ARGV[4] now in seconds, or "" for the Redis clock
|
|
8
|
+
-- ARGV[5] reserve (0 if missing)
|
|
9
|
+
--
|
|
10
|
+
-- Returns { allowed (1/0), estimate, current, previous, index, now }
|
|
11
|
+
|
|
12
|
+
local key = KEYS[1]
|
|
13
|
+
local limit = tonumber(ARGV[1])
|
|
14
|
+
local window = tonumber(ARGV[2])
|
|
15
|
+
local cost = tonumber(ARGV[3])
|
|
16
|
+
local now = tonumber(ARGV[4])
|
|
17
|
+
local reserve = tonumber(ARGV[5]) or 0
|
|
18
|
+
|
|
19
|
+
if now == nil then
|
|
20
|
+
local time = redis.call('TIME')
|
|
21
|
+
now = tonumber(time[1]) + tonumber(time[2]) / 1000000
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
local index = math.floor(now / window)
|
|
25
|
+
local stored = redis.call('HMGET', key, 'index', 'current', 'previous')
|
|
26
|
+
local stored_index = tonumber(stored[1])
|
|
27
|
+
local current = tonumber(stored[2]) or 0
|
|
28
|
+
local previous = tonumber(stored[3]) or 0
|
|
29
|
+
|
|
30
|
+
-- Move to the window containing `now`. If time went back, stay.
|
|
31
|
+
if stored_index == nil then
|
|
32
|
+
stored_index = index
|
|
33
|
+
elseif index > stored_index then
|
|
34
|
+
if index == stored_index + 1 then
|
|
35
|
+
previous = current
|
|
36
|
+
else
|
|
37
|
+
previous = 0
|
|
38
|
+
end
|
|
39
|
+
current = 0
|
|
40
|
+
stored_index = index
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
local window_start = stored_index * window
|
|
44
|
+
local progress = (now - window_start) / window
|
|
45
|
+
if progress < 0 then progress = 0 elseif progress > 1 then progress = 1 end
|
|
46
|
+
|
|
47
|
+
local estimate = previous * (1 - progress) + current
|
|
48
|
+
local allowed = 0
|
|
49
|
+
if estimate + cost + reserve <= limit + 1e-9 then
|
|
50
|
+
allowed = 1
|
|
51
|
+
current = current + cost
|
|
52
|
+
estimate = estimate + cost
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
redis.call('HSET', key, 'index', stored_index, 'current', current, 'previous', previous)
|
|
56
|
+
-- Expire after two windows, when it no longer counts.
|
|
57
|
+
redis.call('PEXPIRE', key, math.max(1, math.ceil((window_start + 2 * window - now) * 1000)))
|
|
58
|
+
|
|
59
|
+
-- Redis turns Lua numbers into integers, so send decimals as strings.
|
|
60
|
+
return { allowed, tostring(estimate), current, previous, stored_index, tostring(now) }
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative '../clock'
|
|
4
|
+
require_relative '../result'
|
|
5
|
+
require_relative '../validators/configuration_validator'
|
|
6
|
+
require_relative '../validators/cost_validator'
|
|
7
|
+
|
|
8
|
+
module RateGuard
|
|
9
|
+
module Algorithms
|
|
10
|
+
# Estimates a sliding window from two fixed-window counters per key.
|
|
11
|
+
class SlidingWindowCounter
|
|
12
|
+
# Room for float rounding.
|
|
13
|
+
EPSILON = 1e-9
|
|
14
|
+
|
|
15
|
+
# index = window number: floor(time / window)
|
|
16
|
+
State = Struct.new(:index, :current, :previous)
|
|
17
|
+
|
|
18
|
+
attr_reader :limit, :window
|
|
19
|
+
|
|
20
|
+
def initialize(limit:, window:, clock: Clock::Wall)
|
|
21
|
+
Validators::ConfigurationValidator.validate!(
|
|
22
|
+
limit: [limit, :integer],
|
|
23
|
+
window: [window, :number]
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
@limit = limit
|
|
27
|
+
@window = window
|
|
28
|
+
@clock = clock
|
|
29
|
+
@states = {}
|
|
30
|
+
@mutex = Mutex.new
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
# Allows the request and spends `cost` if there is room.
|
|
34
|
+
# reserve: extra units that must stay free (for others); only cost is spent.
|
|
35
|
+
def acquire(key, cost: 1, reserve: 0)
|
|
36
|
+
Validators::CostValidator.validate!(
|
|
37
|
+
cost: cost,
|
|
38
|
+
maximum: @limit,
|
|
39
|
+
type: :integer,
|
|
40
|
+
reserve: reserve
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
@mutex.synchronize do
|
|
44
|
+
now = @clock.now
|
|
45
|
+
state = (@states[key] ||= State.new(window_index(now), 0, 0))
|
|
46
|
+
advance(state, now)
|
|
47
|
+
estimated = estimate_for(state, now)
|
|
48
|
+
|
|
49
|
+
if estimated + cost + reserve <= @limit + EPSILON
|
|
50
|
+
state.current += cost
|
|
51
|
+
Result.new(allowed: true, remaining: remaining(estimated + cost), retry_after: 0.0,
|
|
52
|
+
reset_after: reset_after(state, now))
|
|
53
|
+
else
|
|
54
|
+
Result.new(allowed: false, remaining: remaining(estimated),
|
|
55
|
+
retry_after: retry_after(state, now, cost + reserve), reset_after: reset_after(state, now))
|
|
56
|
+
end
|
|
57
|
+
end
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
# Estimated request count for a key right now.
|
|
61
|
+
def estimate(key)
|
|
62
|
+
@mutex.synchronize do
|
|
63
|
+
state = @states[key]
|
|
64
|
+
next 0.0 if state.nil?
|
|
65
|
+
|
|
66
|
+
now = @clock.now
|
|
67
|
+
advance(state, now)
|
|
68
|
+
estimate_for(state, now)
|
|
69
|
+
end
|
|
70
|
+
end
|
|
71
|
+
|
|
72
|
+
# Number of keys stored.
|
|
73
|
+
def tracked_keys
|
|
74
|
+
@mutex.synchronize { @states.size }
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
# Deletes keys whose counts have expired. Returns how many.
|
|
78
|
+
def prune
|
|
79
|
+
@mutex.synchronize do
|
|
80
|
+
now = @clock.now
|
|
81
|
+
before = @states.size
|
|
82
|
+
@states.delete_if do |_key, state|
|
|
83
|
+
advance(state, now)
|
|
84
|
+
state.current.zero? && state.previous.zero?
|
|
85
|
+
end
|
|
86
|
+
before - @states.size
|
|
87
|
+
end
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
private
|
|
91
|
+
|
|
92
|
+
def window_index(time)
|
|
93
|
+
(time / @window).floor
|
|
94
|
+
end
|
|
95
|
+
|
|
96
|
+
def window_start(state)
|
|
97
|
+
state.index * @window
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
# Move a key's counters to the current window (compares integers, not floats).
|
|
101
|
+
def advance(state, now)
|
|
102
|
+
index = window_index(now)
|
|
103
|
+
return if index <= state.index # same window, or the clock moved backwards
|
|
104
|
+
|
|
105
|
+
state.previous = index == state.index + 1 ? state.current : 0
|
|
106
|
+
state.current = 0
|
|
107
|
+
state.index = index
|
|
108
|
+
end
|
|
109
|
+
|
|
110
|
+
def estimate_for(state, now)
|
|
111
|
+
progress = ((now - window_start(state)) / @window).clamp(0.0, 1.0)
|
|
112
|
+
(state.previous * (1 - progress)) + state.current
|
|
113
|
+
end
|
|
114
|
+
|
|
115
|
+
def remaining(estimated)
|
|
116
|
+
[(@limit - estimated + EPSILON).floor, 0].max
|
|
117
|
+
end
|
|
118
|
+
|
|
119
|
+
# Seconds until `cost` more fits.
|
|
120
|
+
def retry_after(state, now, cost)
|
|
121
|
+
room = @limit - state.current - cost
|
|
122
|
+
|
|
123
|
+
if room >= 0
|
|
124
|
+
# Wait until the previous window's weight shrinks enough.
|
|
125
|
+
progress = 1 - room.fdiv(state.previous)
|
|
126
|
+
window_start(state) + (progress * @window) - now
|
|
127
|
+
else
|
|
128
|
+
# The current window alone is too full: wait into the next one.
|
|
129
|
+
progress = 1 - (@limit - cost).fdiv(state.current)
|
|
130
|
+
window_start(state) + @window + (progress * @window) - now
|
|
131
|
+
end
|
|
132
|
+
end
|
|
133
|
+
|
|
134
|
+
# Seconds until the estimate is zero.
|
|
135
|
+
def reset_after(state, now)
|
|
136
|
+
start = window_start(state)
|
|
137
|
+
|
|
138
|
+
if state.current.positive?
|
|
139
|
+
start + (2 * @window) - now
|
|
140
|
+
elsif state.previous.positive?
|
|
141
|
+
start + @window - now
|
|
142
|
+
else
|
|
143
|
+
0.0
|
|
144
|
+
end
|
|
145
|
+
end
|
|
146
|
+
end
|
|
147
|
+
end
|
|
148
|
+
end
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative '../clock'
|
|
4
|
+
require_relative '../result'
|
|
5
|
+
require_relative '../validators/configuration_validator'
|
|
6
|
+
require_relative '../validators/cost_validator'
|
|
7
|
+
|
|
8
|
+
module RateGuard
|
|
9
|
+
module Algorithms
|
|
10
|
+
# Stores each request's time and allows a new one only if the last
|
|
11
|
+
# `window` seconds have room. Exact, but keeps up to `limit` times per key.
|
|
12
|
+
class SlidingWindowLog
|
|
13
|
+
attr_reader :limit, :window
|
|
14
|
+
|
|
15
|
+
def initialize(limit:, window:, clock: Clock::Monotonic)
|
|
16
|
+
Validators::ConfigurationValidator.validate!(
|
|
17
|
+
limit: [limit, :integer],
|
|
18
|
+
window: [window, :number]
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
@limit = limit
|
|
22
|
+
@window = window
|
|
23
|
+
@clock = clock
|
|
24
|
+
@logs = {}
|
|
25
|
+
@mutex = Mutex.new
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
# Allows the request and spends `cost` if there is room.
|
|
29
|
+
# reserve: extra units that must stay free (for others); only cost is spent.
|
|
30
|
+
def acquire(key, cost: 1, reserve: 0)
|
|
31
|
+
Validators::CostValidator.validate!(
|
|
32
|
+
cost: cost,
|
|
33
|
+
maximum: @limit,
|
|
34
|
+
type: :integer,
|
|
35
|
+
reserve: reserve
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
@mutex.synchronize do
|
|
39
|
+
log = (@logs[key] ||= [])
|
|
40
|
+
now = current_time(log)
|
|
41
|
+
expire(log, now)
|
|
42
|
+
|
|
43
|
+
if log.size + cost + reserve <= @limit
|
|
44
|
+
log.concat(Array.new(cost, now))
|
|
45
|
+
Result.new(allowed: true, remaining: @limit - log.size, retry_after: 0.0,
|
|
46
|
+
reset_after: reset_after(log, now))
|
|
47
|
+
else
|
|
48
|
+
# It fits once enough of the oldest entries expire.
|
|
49
|
+
must_expire = log[log.size + cost + reserve - @limit - 1]
|
|
50
|
+
Result.new(allowed: false, remaining: @limit - log.size, retry_after: must_expire + @window - now,
|
|
51
|
+
reset_after: reset_after(log, now))
|
|
52
|
+
end
|
|
53
|
+
end
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
# Requests logged for a key in the last `window` seconds.
|
|
57
|
+
def count(key)
|
|
58
|
+
@mutex.synchronize do
|
|
59
|
+
log = @logs[key]
|
|
60
|
+
next 0 if log.nil?
|
|
61
|
+
|
|
62
|
+
expire(log, current_time(log))
|
|
63
|
+
log.size
|
|
64
|
+
end
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
# Number of keys with a log.
|
|
68
|
+
def tracked_keys
|
|
69
|
+
@mutex.synchronize { @logs.size }
|
|
70
|
+
end
|
|
71
|
+
|
|
72
|
+
# Deletes fully expired logs. Returns how many.
|
|
73
|
+
# Run it now and then, or keys that never return stay forever.
|
|
74
|
+
def prune
|
|
75
|
+
@mutex.synchronize do
|
|
76
|
+
before = @logs.size
|
|
77
|
+
@logs.delete_if do |_key, log|
|
|
78
|
+
expire(log, current_time(log))
|
|
79
|
+
log.empty?
|
|
80
|
+
end
|
|
81
|
+
before - @logs.size
|
|
82
|
+
end
|
|
83
|
+
end
|
|
84
|
+
|
|
85
|
+
private
|
|
86
|
+
|
|
87
|
+
# Appending keeps the log sorted. If the clock goes back, reuse the
|
|
88
|
+
# newest time so the order stays correct.
|
|
89
|
+
def current_time(log)
|
|
90
|
+
now = @clock.now
|
|
91
|
+
log.empty? ? now : [now, log.last].max
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
# Old entries are at the front; binary search finds where they end.
|
|
95
|
+
def expire(log, now)
|
|
96
|
+
first_live = log.bsearch_index { |time| time + @window > now } || log.size
|
|
97
|
+
log.shift(first_live)
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
def reset_after(log, now)
|
|
101
|
+
log.empty? ? 0.0 : log.last + @window - now
|
|
102
|
+
end
|
|
103
|
+
end
|
|
104
|
+
end
|
|
105
|
+
end
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative '../clock'
|
|
4
|
+
require_relative '../result'
|
|
5
|
+
require_relative '../validators/configuration_validator'
|
|
6
|
+
require_relative '../validators/cost_validator'
|
|
7
|
+
|
|
8
|
+
module RateGuard
|
|
9
|
+
module Algorithms
|
|
10
|
+
# Each key has up to `capacity` tokens, refilled at `refill_rate`
|
|
11
|
+
# per second. A request spends `cost` tokens or is rejected.
|
|
12
|
+
class TokenBucket
|
|
13
|
+
# Float math drifts (0.1 * 10 = 0.9999999999999999). Close enough counts.
|
|
14
|
+
EPSILON = 1e-9
|
|
15
|
+
|
|
16
|
+
State = Struct.new(:tokens, :updated_at)
|
|
17
|
+
|
|
18
|
+
attr_reader :capacity, :refill_rate
|
|
19
|
+
|
|
20
|
+
# The burst the bucket can take. All limiters answer #limit.
|
|
21
|
+
alias limit capacity
|
|
22
|
+
|
|
23
|
+
def initialize(capacity:, refill_rate:, clock: Clock::Monotonic)
|
|
24
|
+
Validators::ConfigurationValidator.validate!(
|
|
25
|
+
capacity: [capacity, :integer],
|
|
26
|
+
refill_rate: [refill_rate, :number]
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
@capacity = capacity
|
|
30
|
+
@refill_rate = refill_rate
|
|
31
|
+
@clock = clock
|
|
32
|
+
@buckets = {}
|
|
33
|
+
@mutex = Mutex.new
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
# Allows the request and spends `cost` if there is room.
|
|
37
|
+
# reserve: extra units that must stay free (for others); only cost is spent.
|
|
38
|
+
def acquire(key, cost: 1, reserve: 0)
|
|
39
|
+
Validators::CostValidator.validate!(
|
|
40
|
+
cost: cost,
|
|
41
|
+
maximum: @capacity,
|
|
42
|
+
maximum_name: 'capacity',
|
|
43
|
+
type: :number,
|
|
44
|
+
reserve: reserve
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
@mutex.synchronize do
|
|
48
|
+
state = refill(key)
|
|
49
|
+
|
|
50
|
+
if state.tokens + EPSILON >= cost + reserve
|
|
51
|
+
state.tokens = [state.tokens - cost, 0.0].max
|
|
52
|
+
Result.new(allowed: true, remaining: whole_tokens(state), retry_after: 0.0,
|
|
53
|
+
reset_after: until_full(state))
|
|
54
|
+
else
|
|
55
|
+
retry_after = (cost + reserve - state.tokens) / @refill_rate
|
|
56
|
+
Result.new(allowed: false, remaining: whole_tokens(state), retry_after: retry_after,
|
|
57
|
+
reset_after: until_full(state))
|
|
58
|
+
end
|
|
59
|
+
end
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
# Current tokens for a key, after refilling.
|
|
63
|
+
def tokens(key)
|
|
64
|
+
@mutex.synchronize { refill(key).tokens }
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
private
|
|
68
|
+
|
|
69
|
+
# Add the tokens earned since the last request, up to capacity.
|
|
70
|
+
def refill(key)
|
|
71
|
+
now = @clock.now
|
|
72
|
+
state = (@buckets[key] ||= State.new(@capacity.to_f, now))
|
|
73
|
+
|
|
74
|
+
elapsed = now - state.updated_at
|
|
75
|
+
if elapsed.positive?
|
|
76
|
+
state.tokens = [state.tokens + (elapsed * @refill_rate), @capacity].min.to_f
|
|
77
|
+
state.updated_at = now
|
|
78
|
+
end
|
|
79
|
+
|
|
80
|
+
state
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
def whole_tokens(state)
|
|
84
|
+
(state.tokens + EPSILON).floor
|
|
85
|
+
end
|
|
86
|
+
|
|
87
|
+
# Seconds until the bucket is full again.
|
|
88
|
+
def until_full(state)
|
|
89
|
+
(@capacity - state.tokens) / @refill_rate
|
|
90
|
+
end
|
|
91
|
+
end
|
|
92
|
+
end
|
|
93
|
+
end
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'digest'
|
|
4
|
+
require 'ipaddr'
|
|
5
|
+
require_relative 'middleware/client_ip'
|
|
6
|
+
|
|
7
|
+
module RateGuard
|
|
8
|
+
# Trusted clients that are never limited, by IP range or API key.
|
|
9
|
+
# The IP comes from ClientIp, so it can't be faked with a header.
|
|
10
|
+
# API keys are stored only as SHA-256 digests.
|
|
11
|
+
class Bypass
|
|
12
|
+
def initialize(ip_ranges: [], api_keys: [], client_ip: Middleware::ClientIp.new, header: 'X-API-Key')
|
|
13
|
+
@ranges = ip_ranges.map { |range| IPAddr.new(range) }.freeze
|
|
14
|
+
@key_digests = api_keys.map { |key| Digest::SHA256.hexdigest(key) }.to_set.freeze
|
|
15
|
+
@client_ip = client_ip
|
|
16
|
+
@env_key = "HTTP_#{header.upcase.tr('-', '_')}"
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
def call(env)
|
|
20
|
+
trusted_ip?(env) || trusted_key?(env)
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
private
|
|
24
|
+
|
|
25
|
+
def trusted_ip?(env)
|
|
26
|
+
return false if @ranges.empty?
|
|
27
|
+
|
|
28
|
+
address = IPAddr.new(@client_ip.call(env).to_s)
|
|
29
|
+
@ranges.any? { |range| range.family == address.family && range.include?(address) }
|
|
30
|
+
rescue IPAddr::Error
|
|
31
|
+
false
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
def trusted_key?(env)
|
|
35
|
+
api_key = env[@env_key].to_s.strip
|
|
36
|
+
!api_key.empty? && @key_digests.include?(Digest::SHA256.hexdigest(api_key))
|
|
37
|
+
end
|
|
38
|
+
end
|
|
39
|
+
end
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module RateGuard
|
|
4
|
+
module Clock
|
|
5
|
+
# Seconds since some fixed point. Never goes backwards: use it to measure time.
|
|
6
|
+
module Monotonic
|
|
7
|
+
def self.now
|
|
8
|
+
Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
9
|
+
end
|
|
10
|
+
end
|
|
11
|
+
|
|
12
|
+
# Seconds since 1970 (real time). Needed for calendar windows.
|
|
13
|
+
# It can jump when the system clock changes.
|
|
14
|
+
module Wall
|
|
15
|
+
def self.now
|
|
16
|
+
Process.clock_gettime(Process::CLOCK_REALTIME)
|
|
17
|
+
end
|
|
18
|
+
end
|
|
19
|
+
end
|
|
20
|
+
end
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative 'errors'
|
|
4
|
+
require_relative 'registry'
|
|
5
|
+
|
|
6
|
+
module RateGuard
|
|
7
|
+
# Settings for building a limiter: algorithm, limit per window, storage.
|
|
8
|
+
class Configuration
|
|
9
|
+
REDIS_FAILURE_POLICIES = %i[allow reject].freeze
|
|
10
|
+
|
|
11
|
+
attr_reader :algorithm, :redis_failure_policy
|
|
12
|
+
attr_accessor :limit, :window, :clock, :redis
|
|
13
|
+
|
|
14
|
+
# Called with the error when Redis fails, so failures are never silent.
|
|
15
|
+
attr_accessor :on_redis_error
|
|
16
|
+
|
|
17
|
+
# Prefix for Redis keys. Use a different one per policy.
|
|
18
|
+
attr_accessor :namespace
|
|
19
|
+
|
|
20
|
+
def initialize
|
|
21
|
+
@algorithm = :token_bucket
|
|
22
|
+
@limit = nil
|
|
23
|
+
@window = nil
|
|
24
|
+
@clock = nil
|
|
25
|
+
@redis = nil
|
|
26
|
+
@redis_failure_policy = :allow
|
|
27
|
+
@on_redis_error = nil
|
|
28
|
+
@namespace = 'rate_guard'
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
# Accepts a Symbol or a String (useful for ENV values).
|
|
32
|
+
def algorithm=(name)
|
|
33
|
+
@algorithm = symbolize(name)
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
# :allow (fail open) or :reject (fail closed) when Redis is down.
|
|
37
|
+
def redis_failure_policy=(policy)
|
|
38
|
+
@redis_failure_policy = symbolize(policy)
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
# Checks all settings and reports every problem in one error.
|
|
42
|
+
def validate!
|
|
43
|
+
problems = []
|
|
44
|
+
problems << algorithm_problem unless Registry.registered?(algorithm)
|
|
45
|
+
problems << "limit must be a positive integer (got #{limit.inspect})" unless positive_integer?(limit)
|
|
46
|
+
problems << "window must be a positive number of seconds (got #{window.inspect})" unless positive_number?(window)
|
|
47
|
+
problems << 'clock must respond to #now' unless clock.nil? || clock.respond_to?(:now)
|
|
48
|
+
problems << 'redis must be a Redis client (respond to #evalsha)' unless redis.nil? || redis.respond_to?(:evalsha)
|
|
49
|
+
problems << 'on_redis_error must respond to #call' unless on_redis_error.nil? || on_redis_error.respond_to?(:call)
|
|
50
|
+
problems << 'namespace must be a non-empty String' unless namespace.is_a?(String) && !namespace.empty?
|
|
51
|
+
unless REDIS_FAILURE_POLICIES.include?(redis_failure_policy)
|
|
52
|
+
problems << "redis_failure_policy must be :allow or :reject (got #{redis_failure_policy.inspect})"
|
|
53
|
+
end
|
|
54
|
+
raise ConfigurationError, "invalid rate limiter configuration: #{problems.join('; ')}" unless problems.empty?
|
|
55
|
+
|
|
56
|
+
self
|
|
57
|
+
end
|
|
58
|
+
|
|
59
|
+
private
|
|
60
|
+
|
|
61
|
+
def symbolize(value)
|
|
62
|
+
value.respond_to?(:to_sym) ? value.to_sym : value
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
def algorithm_problem
|
|
66
|
+
"algorithm #{algorithm.inspect} is not registered (available: #{Registry.names.map(&:inspect).join(', ')})"
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
def positive_integer?(value)
|
|
70
|
+
value.is_a?(Integer) && value.positive?
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
def positive_number?(value)
|
|
74
|
+
value.is_a?(Numeric) && value.real? && value.finite? && value.positive?
|
|
75
|
+
end
|
|
76
|
+
end
|
|
77
|
+
end
|