throttle_machines 0.4.3 → 0.5.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 +4 -4
- data/CHANGELOG.md +231 -0
- data/Cargo.lock +307 -0
- data/Cargo.toml +31 -0
- data/README.md +89 -14
- data/ext/throttle_machines_native/core/CHANGELOG.md +77 -0
- data/ext/throttle_machines_native/core/Cargo.toml +25 -0
- data/ext/throttle_machines_native/core/README.md +100 -0
- data/ext/throttle_machines_native/core/src/fixed_window.rs +172 -0
- data/ext/throttle_machines_native/core/src/gate.rs +82 -0
- data/ext/throttle_machines_native/core/src/gcra.rs +219 -0
- data/ext/throttle_machines_native/core/src/keyed.rs +325 -0
- data/ext/throttle_machines_native/core/src/lib.rs +50 -0
- data/ext/throttle_machines_native/core/src/refusal.rs +30 -0
- data/ext/throttle_machines_native/core/src/token_bucket.rs +191 -0
- data/ext/throttle_machines_native/extconf.rb +2 -0
- data/ext/throttle_machines_native/ffi/CHANGELOG.md +59 -0
- data/ext/throttle_machines_native/ffi/Cargo.toml +22 -0
- data/ext/throttle_machines_native/ffi/extconf.rb +14 -0
- data/ext/throttle_machines_native/ffi/src/init.rs +63 -0
- data/ext/throttle_machines_native/ffi/src/lib.rs +255 -0
- data/ext/throttle_machines_native/ffi/src/values.rs +194 -0
- data/lib/throttle_machines/async_breaker.rb +5 -0
- data/lib/throttle_machines/async_support.rb +16 -21
- data/lib/throttle_machines/breakers.rb +46 -0
- data/lib/throttle_machines/control.rb +25 -46
- data/lib/throttle_machines/controller_helpers.rb +11 -10
- data/lib/throttle_machines/hedged_breaker.rb +4 -6
- data/lib/throttle_machines/hedged_request.rb +29 -42
- data/lib/throttle_machines/instrumentation.rb +10 -75
- data/lib/throttle_machines/limiter.rb +71 -136
- data/lib/throttle_machines/middleware.rb +6 -6
- data/lib/throttle_machines/rack_middleware/allow2_ban.rb +1 -8
- data/lib/throttle_machines/rack_middleware/ban_filter.rb +3 -2
- data/lib/throttle_machines/rack_middleware/configuration.rb +4 -2
- data/lib/throttle_machines/rack_middleware/fail2_ban.rb +5 -21
- data/lib/throttle_machines/rack_middleware/throttle.rb +2 -1
- data/lib/throttle_machines/rack_middleware.rb +3 -1
- data/lib/throttle_machines/storage/base.rb +49 -48
- data/lib/throttle_machines/storage/cache.rb +12 -6
- data/lib/throttle_machines/storage/memory.rb +68 -96
- data/lib/throttle_machines/storage/null.rb +18 -28
- data/lib/throttle_machines/storage/redis/gcra.lua +21 -20
- data/lib/throttle_machines/storage/redis/increment_counter.lua +4 -4
- data/lib/throttle_machines/storage/redis/peek_gcra.lua +16 -16
- data/lib/throttle_machines/storage/redis/peek_token_bucket.lua +22 -18
- data/lib/throttle_machines/storage/redis/token_bucket.lua +31 -19
- data/lib/throttle_machines/storage/redis.rb +63 -69
- data/lib/throttle_machines/throttled_error.rb +4 -1
- data/lib/throttle_machines/version.rb +1 -1
- data/lib/throttle_machines.rb +130 -87
- data/sig/throttle_machines.rbs +555 -0
- metadata +55 -71
- data/lib/throttle_machines/async_limiter.rb +0 -24
- data/lib/throttle_machines/dependency_error.rb +0 -6
- data/lib/throttle_machines/native_speedup.rb +0 -110
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
3
|
module ThrottleMachines
|
|
4
|
-
#
|
|
4
|
+
# Events emitted through ActiveSupport::Notifications (or any backend
|
|
5
|
+
# answering `instrument`). Periods, waits and durations in payloads are
|
|
6
|
+
# Integer nanoseconds.
|
|
5
7
|
module Instrumentation
|
|
6
8
|
class << self
|
|
7
9
|
attr_writer :enabled, :backend
|
|
@@ -15,8 +17,14 @@ module ThrottleMachines
|
|
|
15
17
|
@backend ||= ActiveSupport::Notifications
|
|
16
18
|
end
|
|
17
19
|
|
|
20
|
+
# Whether events are published: callers whose payload costs a storage
|
|
21
|
+
# read ask first, so a silenced gem pays nothing for it.
|
|
22
|
+
def active?
|
|
23
|
+
enabled && !backend.nil?
|
|
24
|
+
end
|
|
25
|
+
|
|
18
26
|
def instrument(event_name, payload = {}, &block)
|
|
19
|
-
|
|
27
|
+
unless active?
|
|
20
28
|
return yield if block_given?
|
|
21
29
|
|
|
22
30
|
return
|
|
@@ -63,72 +71,6 @@ module ThrottleMachines
|
|
|
63
71
|
instrument('rate_limit.throttled', payload)
|
|
64
72
|
end
|
|
65
73
|
|
|
66
|
-
# Circuit breaker events
|
|
67
|
-
def circuit_opened(breaker, failure_count:)
|
|
68
|
-
payload = {
|
|
69
|
-
key: (breaker.respond_to?(:name) ? breaker.name : breaker.to_s),
|
|
70
|
-
failure_threshold: (breaker.respond_to?(:configuration) ? breaker.configuration[:failure_threshold] : nil),
|
|
71
|
-
timeout: (breaker.respond_to?(:configuration) ? breaker.configuration[:reset_timeout] : nil),
|
|
72
|
-
failure_count: failure_count
|
|
73
|
-
}
|
|
74
|
-
instrument('circuit_breaker.opened', payload)
|
|
75
|
-
end
|
|
76
|
-
|
|
77
|
-
def circuit_closed(breaker)
|
|
78
|
-
payload = {
|
|
79
|
-
key: (breaker.respond_to?(:name) ? breaker.name : breaker.to_s),
|
|
80
|
-
failure_threshold: (breaker.respond_to?(:configuration) ? breaker.configuration[:failure_threshold] : nil),
|
|
81
|
-
timeout: (breaker.respond_to?(:configuration) ? breaker.configuration[:reset_timeout] : nil)
|
|
82
|
-
}
|
|
83
|
-
instrument('circuit_breaker.closed', payload)
|
|
84
|
-
end
|
|
85
|
-
|
|
86
|
-
def circuit_half_opened(breaker)
|
|
87
|
-
payload = {
|
|
88
|
-
key: (breaker.respond_to?(:name) ? breaker.name : breaker.to_s),
|
|
89
|
-
failure_threshold: (breaker.respond_to?(:configuration) ? breaker.configuration[:failure_threshold] : nil),
|
|
90
|
-
timeout: (breaker.respond_to?(:configuration) ? breaker.configuration[:reset_timeout] : nil),
|
|
91
|
-
half_open_requests: (breaker.respond_to?(:configuration) ? breaker.configuration[:half_open_calls] : nil)
|
|
92
|
-
}
|
|
93
|
-
instrument('circuit_breaker.half_opened', payload)
|
|
94
|
-
end
|
|
95
|
-
|
|
96
|
-
def circuit_success(breaker)
|
|
97
|
-
payload = {
|
|
98
|
-
key: (breaker.respond_to?(:name) ? breaker.name : breaker.to_s),
|
|
99
|
-
state: (breaker.respond_to?(:to_h) ? breaker.to_h[:state] : nil)
|
|
100
|
-
}
|
|
101
|
-
instrument('circuit_breaker.success', payload)
|
|
102
|
-
end
|
|
103
|
-
|
|
104
|
-
def circuit_failure(breaker, error: nil)
|
|
105
|
-
payload = {
|
|
106
|
-
key: (breaker.respond_to?(:name) ? breaker.name : breaker.to_s),
|
|
107
|
-
state: (breaker.respond_to?(:to_h) ? breaker.to_h[:state] : nil),
|
|
108
|
-
error_class: error&.class&.name,
|
|
109
|
-
error_message: error&.message
|
|
110
|
-
}
|
|
111
|
-
instrument('circuit_breaker.failure', payload)
|
|
112
|
-
end
|
|
113
|
-
|
|
114
|
-
def circuit_rejected(breaker)
|
|
115
|
-
payload = {
|
|
116
|
-
key: (breaker.respond_to?(:name) ? breaker.name : breaker.to_s),
|
|
117
|
-
failure_threshold: (breaker.respond_to?(:configuration) ? breaker.configuration[:failure_threshold] : nil),
|
|
118
|
-
timeout: (breaker.respond_to?(:configuration) ? breaker.configuration[:reset_timeout] : nil)
|
|
119
|
-
}
|
|
120
|
-
instrument('circuit_breaker.rejected', payload)
|
|
121
|
-
end
|
|
122
|
-
|
|
123
|
-
# Cascade events
|
|
124
|
-
def cascade_triggered(primary_key, cascaded_key)
|
|
125
|
-
payload = {
|
|
126
|
-
primary_key: primary_key,
|
|
127
|
-
cascaded_key: cascaded_key
|
|
128
|
-
}
|
|
129
|
-
instrument('cascade.triggered', payload)
|
|
130
|
-
end
|
|
131
|
-
|
|
132
74
|
# Hedged request events
|
|
133
75
|
def hedged_request_started(request_id, attempts:)
|
|
134
76
|
payload = {
|
|
@@ -147,12 +89,5 @@ module ThrottleMachines
|
|
|
147
89
|
instrument('hedged_request.winner', payload)
|
|
148
90
|
end
|
|
149
91
|
end
|
|
150
|
-
|
|
151
|
-
# Null backend for when ActiveSupport::Notifications is not available
|
|
152
|
-
class NullBackend
|
|
153
|
-
def instrument(_name, _payload = {})
|
|
154
|
-
yield if block_given?
|
|
155
|
-
end
|
|
156
|
-
end
|
|
157
92
|
end
|
|
158
93
|
end
|
|
@@ -1,188 +1,123 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
3
|
module ThrottleMachines
|
|
4
|
+
# `limit` calls per `period` (Integer nanoseconds) for one key, decided by
|
|
5
|
+
# `algorithm` over shared storage. A runtime object: its keywords have no
|
|
6
|
+
# core counterpart. Every answer in time is Integer nanoseconds.
|
|
4
7
|
class Limiter
|
|
5
|
-
|
|
8
|
+
ALGORITHMS = %i[fixed_window gcra token_bucket].freeze
|
|
9
|
+
|
|
10
|
+
attr_reader :key, :limit, :period, :algorithm, :storage, :policy
|
|
6
11
|
|
|
7
12
|
def initialize(key, limit:, period:, algorithm: :fixed_window, storage: nil)
|
|
8
13
|
@key = key
|
|
9
|
-
@limit = limit
|
|
10
|
-
@period = period
|
|
14
|
+
@limit = positive(limit, 'limit')
|
|
15
|
+
@period = positive(period, 'period')
|
|
11
16
|
@algorithm = algorithm
|
|
12
17
|
@storage = storage || ThrottleMachines.storage
|
|
13
18
|
validate_algorithm!
|
|
14
|
-
|
|
19
|
+
@policy = build_policy
|
|
20
|
+
freeze
|
|
15
21
|
end
|
|
16
22
|
|
|
23
|
+
# Whether a call would be admitted now, consuming nothing.
|
|
17
24
|
def allow?
|
|
18
|
-
allowed =
|
|
19
|
-
when :fixed_window
|
|
20
|
-
# Don't increment here, just check
|
|
21
|
-
count = @storage.get_counter(@key, @period)
|
|
22
|
-
count < @limit
|
|
23
|
-
when :gcra
|
|
24
|
-
result = @storage.peek_gcra_limit(
|
|
25
|
-
@key,
|
|
26
|
-
@period.to_f / @limit, # emission_interval
|
|
27
|
-
0 # delay_tolerance (no burst)
|
|
28
|
-
)
|
|
29
|
-
result[:allowed]
|
|
30
|
-
when :token_bucket
|
|
31
|
-
result = @storage.peek_token_bucket(
|
|
32
|
-
@key,
|
|
33
|
-
@limit, # capacity
|
|
34
|
-
@limit.to_f / @period # refill_rate
|
|
35
|
-
)
|
|
36
|
-
result[:allowed]
|
|
37
|
-
else
|
|
38
|
-
raise ArgumentError, "Unknown algorithm: #{@algorithm}"
|
|
39
|
-
end
|
|
40
|
-
|
|
41
|
-
# Instrument the check
|
|
25
|
+
allowed = peek.is_a?(Integer)
|
|
42
26
|
Instrumentation.rate_limit_checked(self, allowed: allowed, remaining: nil)
|
|
43
|
-
|
|
44
27
|
allowed
|
|
45
28
|
end
|
|
46
29
|
|
|
30
|
+
# Admits one call or raises ThrottledError, then runs the block. An
|
|
31
|
+
# admission reports the count the check itself answered, which equals
|
|
32
|
+
# `remaining` at that instant (test/throttle_machines/remaining_parity_test.rb)
|
|
33
|
+
# and cannot race another caller; a refusal's `retry_after` costs a
|
|
34
|
+
# storage read, made only while instrumentation is active.
|
|
47
35
|
def throttle!
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
if count > @limit
|
|
53
|
-
Instrumentation.rate_limit_throttled(self, retry_after: retry_after)
|
|
54
|
-
raise ThrottledError, self
|
|
55
|
-
end
|
|
56
|
-
when :gcra
|
|
57
|
-
result = @storage.check_gcra_limit(
|
|
58
|
-
@key,
|
|
59
|
-
@period.to_f / @limit, # emission_interval
|
|
60
|
-
0, # delay_tolerance (no burst)
|
|
61
|
-
(@period * 2).to_i # ttl
|
|
62
|
-
)
|
|
63
|
-
unless result[:allowed]
|
|
64
|
-
Instrumentation.rate_limit_throttled(self, retry_after: retry_after)
|
|
65
|
-
raise ThrottledError, self
|
|
66
|
-
end
|
|
67
|
-
when :token_bucket
|
|
68
|
-
result = @storage.check_token_bucket(
|
|
69
|
-
@key,
|
|
70
|
-
@limit, # capacity
|
|
71
|
-
@limit.to_f / @period, # refill_rate
|
|
72
|
-
(@period * 2).to_i # ttl
|
|
73
|
-
)
|
|
74
|
-
unless result[:allowed]
|
|
75
|
-
Instrumentation.rate_limit_throttled(self, retry_after: retry_after)
|
|
76
|
-
raise ThrottledError, self
|
|
77
|
-
end
|
|
78
|
-
else
|
|
79
|
-
raise ArgumentError, "Unknown algorithm: #{@algorithm}"
|
|
80
|
-
end
|
|
81
|
-
|
|
82
|
-
# If we get here, the request was allowed
|
|
83
|
-
# Calculate remaining after the operation
|
|
84
|
-
remaining_count = begin
|
|
85
|
-
remaining
|
|
86
|
-
rescue StandardError
|
|
87
|
-
nil
|
|
36
|
+
left = check
|
|
37
|
+
unless left.is_a?(Integer)
|
|
38
|
+
Instrumentation.rate_limit_throttled(self, retry_after: retry_after) if Instrumentation.active?
|
|
39
|
+
raise ThrottledError, self
|
|
88
40
|
end
|
|
89
|
-
Instrumentation.rate_limit_allowed(self, remaining: remaining_count)
|
|
90
41
|
|
|
42
|
+
Instrumentation.rate_limit_allowed(self, remaining: left) if Instrumentation.active?
|
|
91
43
|
yield if block_given?
|
|
92
44
|
end
|
|
93
45
|
|
|
94
46
|
def reset!
|
|
95
47
|
case @algorithm
|
|
96
|
-
when :fixed_window
|
|
97
|
-
|
|
98
|
-
when :
|
|
99
|
-
@storage.reset_gcra(@key)
|
|
100
|
-
when :token_bucket
|
|
101
|
-
@storage.reset_token_bucket(@key)
|
|
48
|
+
when :fixed_window then @storage.reset_counter(@key, @period)
|
|
49
|
+
when :gcra then @storage.reset_gcra(@key)
|
|
50
|
+
when :token_bucket then @storage.reset_token_bucket(@key)
|
|
102
51
|
end
|
|
103
52
|
end
|
|
104
53
|
|
|
54
|
+
# Calls still admitted now: the window's or bucket's count; for GCRA, the
|
|
55
|
+
# calls its burst admits back to back (one without a burst).
|
|
105
56
|
def remaining
|
|
57
|
+
answer = peek
|
|
58
|
+
answer.is_a?(Integer) ? answer : 0
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
# Integer nanoseconds until a call is admitted; zero when one is now.
|
|
62
|
+
def retry_after
|
|
106
63
|
case @algorithm
|
|
107
64
|
when :fixed_window
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
when :
|
|
111
|
-
# GCRA doesn't have a simple "remaining" count
|
|
112
|
-
# Just return 1 or 0 based on current state
|
|
113
|
-
result = @storage.peek_gcra_limit(
|
|
114
|
-
@key,
|
|
115
|
-
@period.to_f / @limit,
|
|
116
|
-
0
|
|
117
|
-
)
|
|
118
|
-
result[:allowed] ? 1 : 0
|
|
119
|
-
when :token_bucket
|
|
120
|
-
result = @storage.peek_token_bucket(
|
|
121
|
-
@key,
|
|
122
|
-
@limit,
|
|
123
|
-
@limit.to_f / @period
|
|
124
|
-
)
|
|
125
|
-
result[:tokens_remaining].to_i
|
|
126
|
-
else
|
|
127
|
-
0
|
|
65
|
+
@storage.get_counter(@key, @period) >= @limit ? @storage.get_counter_ttl(@key, @period) : 0
|
|
66
|
+
when :gcra then @storage.gcra_retry_after(@key, @policy)
|
|
67
|
+
when :token_bucket then @storage.token_bucket_retry_after(@key, @policy)
|
|
128
68
|
end
|
|
129
69
|
end
|
|
130
70
|
|
|
131
|
-
def
|
|
71
|
+
def to_h
|
|
72
|
+
{ key: @key, limit: @limit, period: @period, algorithm: @algorithm, remaining: remaining,
|
|
73
|
+
retry_after: retry_after }
|
|
74
|
+
end
|
|
75
|
+
|
|
76
|
+
private
|
|
77
|
+
|
|
78
|
+
# Integer calls left after this admission, or a refusal Symbol.
|
|
79
|
+
def check
|
|
80
|
+
case @algorithm
|
|
81
|
+
when :fixed_window
|
|
82
|
+
count = @storage.increment_counter(@key, @period)
|
|
83
|
+
count <= @limit ? @limit - count : :throttled
|
|
84
|
+
when :gcra then @storage.check_gcra(@key, @policy, @period * 2)
|
|
85
|
+
when :token_bucket then @storage.check_token_bucket(@key, @policy, @period * 2)
|
|
86
|
+
end
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
# Integer calls admitted now, at least one, or a refusal Symbol.
|
|
90
|
+
def peek
|
|
132
91
|
case @algorithm
|
|
133
92
|
when :fixed_window
|
|
134
93
|
count = @storage.get_counter(@key, @period)
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
else
|
|
139
|
-
0
|
|
140
|
-
end
|
|
141
|
-
when :gcra
|
|
142
|
-
result = @storage.peek_gcra_limit(
|
|
143
|
-
@key,
|
|
144
|
-
@period.to_f / @limit,
|
|
145
|
-
0
|
|
146
|
-
)
|
|
147
|
-
result[:retry_after]
|
|
148
|
-
when :token_bucket
|
|
149
|
-
result = @storage.peek_token_bucket(
|
|
150
|
-
@key,
|
|
151
|
-
@limit,
|
|
152
|
-
@limit.to_f / @period
|
|
153
|
-
)
|
|
154
|
-
result[:retry_after]
|
|
155
|
-
else
|
|
156
|
-
0
|
|
94
|
+
count < @limit ? @limit - count : :throttled
|
|
95
|
+
when :gcra then @storage.peek_gcra(@key, @policy)
|
|
96
|
+
when :token_bucket then @storage.peek_token_bucket(@key, @policy)
|
|
157
97
|
end
|
|
158
98
|
end
|
|
159
99
|
|
|
160
|
-
def
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
remaining: remaining,
|
|
167
|
-
retry_after: retry_after
|
|
168
|
-
}
|
|
100
|
+
def build_policy
|
|
101
|
+
case @algorithm
|
|
102
|
+
when :fixed_window then FixedWindowPolicy.new(@period, @limit)
|
|
103
|
+
when :gcra then GcraPolicy.per(@period, @limit, 1)
|
|
104
|
+
when :token_bucket then TokenBucketPolicy.per(@period, @limit)
|
|
105
|
+
end
|
|
169
106
|
end
|
|
170
107
|
|
|
171
|
-
|
|
108
|
+
def positive(value, name)
|
|
109
|
+
raise TypeError, "#{name} must be an Integer, got #{value.inspect}" unless value.is_a?(Integer)
|
|
110
|
+
raise RangeError, "#{name} must be positive, got #{value}" unless value.positive?
|
|
172
111
|
|
|
173
|
-
|
|
174
|
-
raise ArgumentError, "limit must be positive, got #{@limit.inspect}" unless @limit.is_a?(Numeric) && @limit.positive?
|
|
175
|
-
raise ArgumentError, "period must be positive, got #{@period.inspect}" unless @period.is_a?(Numeric) && @period.positive?
|
|
112
|
+
value
|
|
176
113
|
end
|
|
177
114
|
|
|
178
115
|
def validate_algorithm!
|
|
179
|
-
unless
|
|
180
|
-
raise ArgumentError, "Unknown algorithm: #{@algorithm.inspect}"
|
|
181
|
-
end
|
|
116
|
+
raise RangeError, "Unknown algorithm: #{@algorithm.inspect}" unless ALGORITHMS.include?(@algorithm)
|
|
182
117
|
return unless @storage.respond_to?(:supports?)
|
|
183
118
|
return if @storage.supports?(@algorithm)
|
|
184
119
|
|
|
185
|
-
raise
|
|
120
|
+
raise RangeError, "#{@storage.class} does not support the #{@algorithm.inspect} algorithm"
|
|
186
121
|
end
|
|
187
122
|
end
|
|
188
123
|
end
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
3
|
module ThrottleMachines
|
|
4
|
+
# Rack middleware applying limiters per path. `period:` is Integer
|
|
5
|
+
# nanoseconds; responses report waits in whole seconds, rounded up.
|
|
4
6
|
class Middleware
|
|
5
7
|
def initialize(app, &config_block)
|
|
6
8
|
@app = app
|
|
@@ -70,18 +72,16 @@ module ThrottleMachines
|
|
|
70
72
|
end
|
|
71
73
|
|
|
72
74
|
def rate_limit_response(limiter)
|
|
75
|
+
wait = limiter.retry_after.ceildiv(NS_PER_SECOND)
|
|
73
76
|
headers = {
|
|
74
77
|
'Content-Type' => 'application/json',
|
|
75
78
|
'X-RateLimit-Limit' => limiter.limit.to_s,
|
|
76
79
|
'X-RateLimit-Remaining' => limiter.remaining.to_s,
|
|
77
|
-
'X-RateLimit-Reset' => (Time.now.to_i +
|
|
78
|
-
'Retry-After' =>
|
|
80
|
+
'X-RateLimit-Reset' => (Time.now.to_i + wait).to_s,
|
|
81
|
+
'Retry-After' => wait.to_s
|
|
79
82
|
}
|
|
80
83
|
|
|
81
|
-
body = JSON.generate({
|
|
82
|
-
error: 'Rate limit exceeded',
|
|
83
|
-
retry_after: limiter.retry_after
|
|
84
|
-
})
|
|
84
|
+
body = JSON.generate({ error: 'Rate limit exceeded', retry_after: wait })
|
|
85
85
|
|
|
86
86
|
[429, headers, [body]]
|
|
87
87
|
end
|
|
@@ -24,14 +24,7 @@ module ThrottleMachines
|
|
|
24
24
|
# Check if we've had enough successful requests
|
|
25
25
|
if success_limiter.remaining.zero?
|
|
26
26
|
# Reset the fail2ban breaker (use BreakerMachines circuit)
|
|
27
|
-
|
|
28
|
-
fail_key,
|
|
29
|
-
self,
|
|
30
|
-
failure_threshold: @maxretry,
|
|
31
|
-
failure_window: @findtime,
|
|
32
|
-
reset_timeout: @bantime
|
|
33
|
-
)
|
|
34
|
-
breaker.hard_reset
|
|
27
|
+
Breakers.dynamic(fail_key, self, @maxretry, @findtime, @bantime).reset
|
|
35
28
|
|
|
36
29
|
# Reset our own counter
|
|
37
30
|
ThrottleMachines.storage.reset_counter(success_key, @findtime)
|
|
@@ -14,9 +14,10 @@ module ThrottleMachines
|
|
|
14
14
|
@name = name
|
|
15
15
|
@block = block
|
|
16
16
|
|
|
17
|
+
# `findtime` and `bantime` are Integer nanoseconds.
|
|
17
18
|
@maxretry = options[:maxretry] || 5
|
|
18
|
-
@findtime = options[:findtime] || 60
|
|
19
|
-
@bantime = options[:bantime] || 300
|
|
19
|
+
@findtime = options[:findtime] || (60 * NS_PER_SECOND)
|
|
20
|
+
@bantime = options[:bantime] || (300 * NS_PER_SECOND)
|
|
20
21
|
end
|
|
21
22
|
|
|
22
23
|
private
|
|
@@ -7,14 +7,16 @@ module ThrottleMachines
|
|
|
7
7
|
class Configuration
|
|
8
8
|
DEFAULT_BLOCKLISTED_RESPONDER = ->(_req) { [403, { 'content-type' => 'text/plain' }, ["Forbidden\n"]] }
|
|
9
9
|
|
|
10
|
+
# `retry_after` in the match data is Integer nanoseconds; the header is
|
|
11
|
+
# whole seconds, rounded up.
|
|
10
12
|
DEFAULT_THROTTLED_RESPONDER = lambda do |req|
|
|
11
13
|
match_data = req.env['rack.attack.match_data']
|
|
12
|
-
retry_after = match_data[:retry_after] || 60
|
|
14
|
+
retry_after = (match_data[:retry_after] || (60 * NS_PER_SECOND)).ceildiv(NS_PER_SECOND)
|
|
13
15
|
|
|
14
16
|
[429, { 'content-type' => 'text/plain', 'retry-after' => retry_after.to_s }, ["Retry later\n"]]
|
|
15
17
|
end
|
|
16
18
|
|
|
17
|
-
attr_reader :throttles, :tracks, :safelists, :blocklists
|
|
19
|
+
attr_reader :throttles, :tracks, :safelists, :blocklists, :fail2bans, :allow2bans
|
|
18
20
|
attr_accessor :throttled_responder, :blocklisted_responder
|
|
19
21
|
|
|
20
22
|
def initialize
|
|
@@ -10,24 +10,14 @@ module ThrottleMachines
|
|
|
10
10
|
key = "fail2ban:#{@name}:#{discriminator}"
|
|
11
11
|
|
|
12
12
|
# Use a globally managed BreakerMachines circuit as the ban mechanism
|
|
13
|
-
breaker =
|
|
14
|
-
key,
|
|
15
|
-
self,
|
|
16
|
-
failure_threshold: @maxretry,
|
|
17
|
-
failure_window: @findtime,
|
|
18
|
-
reset_timeout: @bantime
|
|
19
|
-
)
|
|
13
|
+
breaker = Breakers.dynamic(key, self, @maxretry, @findtime, @bantime)
|
|
20
14
|
|
|
21
15
|
# Check if circuit is open (banned)
|
|
22
16
|
if breaker.open?
|
|
23
17
|
stats = breaker.stats
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
remaining.positive? ? remaining : 0
|
|
28
|
-
else
|
|
29
|
-
@bantime
|
|
30
|
-
end
|
|
18
|
+
# Integer nanoseconds, like findtime and bantime.
|
|
19
|
+
banned_for = Breakers.since(breaker)
|
|
20
|
+
time_until_unban = banned_for ? [@bantime - banned_for, 0].max : @bantime
|
|
31
21
|
|
|
32
22
|
request.env['rack.attack.matched'] = @name
|
|
33
23
|
request.env['rack.attack.match_type'] = :fail2ban
|
|
@@ -57,13 +47,7 @@ module ThrottleMachines
|
|
|
57
47
|
# Use the breaker to record a failure if block returns true
|
|
58
48
|
return unless yield
|
|
59
49
|
|
|
60
|
-
breaker =
|
|
61
|
-
key,
|
|
62
|
-
self,
|
|
63
|
-
failure_threshold: @maxretry,
|
|
64
|
-
failure_window: @findtime,
|
|
65
|
-
reset_timeout: @bantime
|
|
66
|
-
)
|
|
50
|
+
breaker = Breakers.dynamic(key, self, @maxretry, @findtime, @bantime)
|
|
67
51
|
|
|
68
52
|
# Record failure by trying to call through the breaker
|
|
69
53
|
# and letting it fail
|
|
@@ -13,7 +13,8 @@ module ThrottleMachines
|
|
|
13
13
|
raise ArgumentError, 'Must pass :period option' unless options[:period]
|
|
14
14
|
|
|
15
15
|
@limit = options[:limit]
|
|
16
|
-
|
|
16
|
+
# Integer nanoseconds, or a callable answering them per request.
|
|
17
|
+
@period = options[:period]
|
|
17
18
|
@algorithm = options[:algorithm] || :fixed_window
|
|
18
19
|
end
|
|
19
20
|
|