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.
Files changed (56) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +231 -0
  3. data/Cargo.lock +307 -0
  4. data/Cargo.toml +31 -0
  5. data/README.md +89 -14
  6. data/ext/throttle_machines_native/core/CHANGELOG.md +77 -0
  7. data/ext/throttle_machines_native/core/Cargo.toml +25 -0
  8. data/ext/throttle_machines_native/core/README.md +100 -0
  9. data/ext/throttle_machines_native/core/src/fixed_window.rs +172 -0
  10. data/ext/throttle_machines_native/core/src/gate.rs +82 -0
  11. data/ext/throttle_machines_native/core/src/gcra.rs +219 -0
  12. data/ext/throttle_machines_native/core/src/keyed.rs +325 -0
  13. data/ext/throttle_machines_native/core/src/lib.rs +50 -0
  14. data/ext/throttle_machines_native/core/src/refusal.rs +30 -0
  15. data/ext/throttle_machines_native/core/src/token_bucket.rs +191 -0
  16. data/ext/throttle_machines_native/extconf.rb +2 -0
  17. data/ext/throttle_machines_native/ffi/CHANGELOG.md +59 -0
  18. data/ext/throttle_machines_native/ffi/Cargo.toml +22 -0
  19. data/ext/throttle_machines_native/ffi/extconf.rb +14 -0
  20. data/ext/throttle_machines_native/ffi/src/init.rs +63 -0
  21. data/ext/throttle_machines_native/ffi/src/lib.rs +255 -0
  22. data/ext/throttle_machines_native/ffi/src/values.rs +194 -0
  23. data/lib/throttle_machines/async_breaker.rb +5 -0
  24. data/lib/throttle_machines/async_support.rb +16 -21
  25. data/lib/throttle_machines/breakers.rb +46 -0
  26. data/lib/throttle_machines/control.rb +25 -46
  27. data/lib/throttle_machines/controller_helpers.rb +11 -10
  28. data/lib/throttle_machines/hedged_breaker.rb +4 -6
  29. data/lib/throttle_machines/hedged_request.rb +29 -42
  30. data/lib/throttle_machines/instrumentation.rb +10 -75
  31. data/lib/throttle_machines/limiter.rb +71 -136
  32. data/lib/throttle_machines/middleware.rb +6 -6
  33. data/lib/throttle_machines/rack_middleware/allow2_ban.rb +1 -8
  34. data/lib/throttle_machines/rack_middleware/ban_filter.rb +3 -2
  35. data/lib/throttle_machines/rack_middleware/configuration.rb +4 -2
  36. data/lib/throttle_machines/rack_middleware/fail2_ban.rb +5 -21
  37. data/lib/throttle_machines/rack_middleware/throttle.rb +2 -1
  38. data/lib/throttle_machines/rack_middleware.rb +3 -1
  39. data/lib/throttle_machines/storage/base.rb +49 -48
  40. data/lib/throttle_machines/storage/cache.rb +12 -6
  41. data/lib/throttle_machines/storage/memory.rb +68 -96
  42. data/lib/throttle_machines/storage/null.rb +18 -28
  43. data/lib/throttle_machines/storage/redis/gcra.lua +21 -20
  44. data/lib/throttle_machines/storage/redis/increment_counter.lua +4 -4
  45. data/lib/throttle_machines/storage/redis/peek_gcra.lua +16 -16
  46. data/lib/throttle_machines/storage/redis/peek_token_bucket.lua +22 -18
  47. data/lib/throttle_machines/storage/redis/token_bucket.lua +31 -19
  48. data/lib/throttle_machines/storage/redis.rb +63 -69
  49. data/lib/throttle_machines/throttled_error.rb +4 -1
  50. data/lib/throttle_machines/version.rb +1 -1
  51. data/lib/throttle_machines.rb +130 -87
  52. data/sig/throttle_machines.rbs +555 -0
  53. metadata +55 -71
  54. data/lib/throttle_machines/async_limiter.rb +0 -24
  55. data/lib/throttle_machines/dependency_error.rb +0 -6
  56. data/lib/throttle_machines/native_speedup.rb +0 -110
@@ -2,15 +2,23 @@
2
2
 
3
3
  module ThrottleMachines
4
4
  module Storage
5
+ # Where limiters keep their state. Every instant and span is Integer
6
+ # nanoseconds. A GCRA or token bucket check answers the calls still
7
+ # admitted (an Integer) or a refusal Symbol, the core gate's own answer:
8
+ # :throttled, :overflow when a GCRA admission would push its TAT past the
9
+ # largest instant, or :full when the store cannot track another key.
5
10
  class Base
6
11
  ALGORITHM_OPERATIONS = {
7
12
  fixed_window: %i[increment_counter get_counter get_counter_ttl reset_counter],
8
- gcra: %i[check_gcra_limit peek_gcra_limit reset_gcra],
9
- token_bucket: %i[check_token_bucket peek_token_bucket reset_token_bucket]
13
+ gcra: %i[check_gcra peek_gcra gcra_retry_after reset_gcra],
14
+ token_bucket: %i[check_token_bucket peek_token_bucket token_bucket_retry_after reset_token_bucket]
10
15
  }.freeze
11
16
 
12
17
  HEALTH_KEY = 'throttle_machines:health'
13
18
 
19
+ # The count a counter the store cannot track answers: past any limit.
20
+ UNTRACKED = 2**64
21
+
14
22
  # What a backend puts between a limiter's key and the state it appends.
15
23
  KEY_SEPARATOR = ':'
16
24
 
@@ -28,75 +36,83 @@ module ThrottleMachines
28
36
  operations.all? { |operation| self.class.instance_method(operation).owner != Base }
29
37
  end
30
38
 
31
- # Rate limiting operations
39
+ # Counts `amount` more calls in the `window` the key is in; answers the
40
+ # window's count.
32
41
  def increment_counter(key, window, amount = 1)
33
- raise NotImplementedError, "#{self.class} does not implement #increment_counter"
42
+ unsupported(:increment_counter)
34
43
  end
35
44
 
36
45
  def get_counter(key, window)
37
- raise NotImplementedError, "#{self.class} does not implement #get_counter"
46
+ unsupported(:get_counter)
38
47
  end
39
48
 
49
+ # Integer nanoseconds until the key's window ends.
40
50
  def get_counter_ttl(key, window)
41
- raise NotImplementedError, "#{self.class} does not implement #get_counter_ttl"
51
+ unsupported(:get_counter_ttl)
42
52
  end
43
53
 
44
54
  def reset_counter(key, window)
45
- raise NotImplementedError, "#{self.class} does not implement #reset_counter"
55
+ unsupported(:reset_counter)
56
+ end
57
+
58
+ # Admits one call under a ThrottleMachines::GcraPolicy, keeping the
59
+ # state `ttl` past now.
60
+ def check_gcra(key, policy, ttl)
61
+ unsupported(:check_gcra)
46
62
  end
47
63
 
48
- # GCRA operations (atomic)
49
- def check_gcra_limit(key, emission_interval, delay_tolerance, ttl)
50
- raise NotImplementedError, "#{self.class} does not implement #check_gcra_limit"
64
+ def peek_gcra(key, policy)
65
+ unsupported(:peek_gcra)
51
66
  end
52
67
 
53
- def peek_gcra_limit(key, emission_interval, delay_tolerance)
54
- raise NotImplementedError, "#{self.class} does not implement #peek_gcra_limit"
68
+ def gcra_retry_after(key, policy)
69
+ unsupported(:gcra_retry_after)
55
70
  end
56
71
 
57
72
  def reset_gcra(key)
58
- raise NotImplementedError, "#{self.class} does not implement #reset_gcra"
73
+ unsupported(:reset_gcra)
59
74
  end
60
75
 
61
- # Token bucket operations (atomic)
62
- def check_token_bucket(key, capacity, refill_rate, ttl)
63
- raise NotImplementedError, "#{self.class} does not implement #check_token_bucket"
76
+ # Admits one call under a ThrottleMachines::TokenBucketPolicy.
77
+ def check_token_bucket(key, policy, ttl)
78
+ unsupported(:check_token_bucket)
64
79
  end
65
80
 
66
- def peek_token_bucket(key, capacity, refill_rate)
67
- raise NotImplementedError, "#{self.class} does not implement #peek_token_bucket"
81
+ def peek_token_bucket(key, policy)
82
+ unsupported(:peek_token_bucket)
83
+ end
84
+
85
+ def token_bucket_retry_after(key, policy)
86
+ unsupported(:token_bucket_retry_after)
68
87
  end
69
88
 
70
89
  def reset_token_bucket(key)
71
- raise NotImplementedError, "#{self.class} does not implement #reset_token_bucket"
90
+ unsupported(:reset_token_bucket)
72
91
  end
73
92
 
74
- # Utility operations
75
93
  def clear(pattern = nil)
76
- raise NotImplementedError, "#{self.class} does not implement #clear"
94
+ unsupported(:clear)
77
95
  end
78
96
 
79
97
  # Deletes every entry this key owns, whatever algorithm wrote it.
80
98
  def reset_key(key)
81
- raise NotImplementedError, "#{self.class} does not implement #reset_key"
99
+ unsupported(:reset_key)
82
100
  end
83
101
 
84
102
  def healthy?
85
- get_counter(HEALTH_KEY, 1)
103
+ get_counter(HEALTH_KEY, NS_PER_SECOND)
86
104
  true
87
105
  rescue StandardError
88
106
  false
89
107
  end
90
108
 
91
- def with_timeout(timeout, &block)
109
+ # Runs the block for at most `timeout` nanoseconds, less when the
110
+ # ambient deadline_machines budget is shorter.
111
+ def with_timeout(timeout, &)
92
112
  DeadlineMachines.check!
93
- Timeout.timeout(DeadlineMachines.clamp_sleep(timeout), &block)
113
+ Timeout.timeout(Rational(DeadlineMachines.clamp_sleep(timeout), NS_PER_SECOND), &)
94
114
  end
95
115
 
96
- # Rounding slack for time comparisons, in units of the clock's precision.
97
- # Matches the native core.
98
- SLACK_ULPS = 64
99
-
100
116
  protected
101
117
 
102
118
  def owned_by?(stored_key, key)
@@ -111,29 +127,14 @@ module ThrottleMachines
111
127
  Regexp.new("\\A#{Regexp.escape(glob).gsub(Regexp.escape(GLOB_WILDCARD), '.*')}\\z")
112
128
  end
113
129
 
114
- # Times are running sums and differences of float seconds, so an
115
- # on-schedule arrival can miss an exact boundary by a few ulps. The slack
116
- # scales with the clock's magnitude.
117
- def rounding_slack(time)
118
- Float::EPSILON * SLACK_ULPS * [time.abs, 1.0].max
119
- end
120
-
121
- def gcra_allowed?(tat, now, delay_tolerance)
122
- tat - now <= delay_tolerance + rounding_slack(tat)
123
- end
124
-
125
- # Whether a token is available, allowing for rounding in the refill.
126
- def token_available?(tokens, now, refill_rate)
127
- tokens >= 1 - (rounding_slack(now) * refill_rate)
128
- end
129
-
130
130
  def current_time
131
- # Use monotonic time for consistency with BreakerMachines
132
131
  ThrottleMachines.monotonic_time
133
132
  end
134
133
 
135
- def monotonic_time
136
- ThrottleMachines.monotonic_time
134
+ private
135
+
136
+ def unsupported(operation)
137
+ raise NotImplementedError, "#{self.class} does not implement ##{operation}"
137
138
  end
138
139
  end
139
140
  end
@@ -2,6 +2,8 @@
2
2
 
3
3
  module ThrottleMachines
4
4
  module Storage
5
+ # Fixed windows in an ActiveSupport cache, aligned to the wall-clock
6
+ # epoch so every process sharing the cache counts the same window.
5
7
  class Cache < Base
6
8
  # The wildcard a caller's pattern keeps; everything else is a literal.
7
9
  PATTERN_SPECIALS = /[?\[\]\\]/
@@ -16,14 +18,16 @@ module ThrottleMachines
16
18
  end
17
19
 
18
20
  def increment_counter(key, window, amount = 1)
19
- count = @cache.increment(window_key(key, window), amount, expires_in: window.to_f.ceil + 1)
20
- count || (@fail_closed ? Float::INFINITY : 0)
21
+ expires_in = window.ceildiv(NS_PER_SECOND) + 1
22
+ count = @cache.increment(window_key(key, window), amount, expires_in: expires_in)
23
+ count || (@fail_closed ? UNTRACKED : 0)
21
24
  end
22
25
 
23
26
  def get_counter(key, window)
24
27
  @cache.read(window_key(key, window), raw: true).to_i
25
28
  end
26
29
 
30
+ # Integer nanoseconds until the current window ends.
27
31
  def get_counter_ttl(_key, window)
28
32
  window = positive_window(window)
29
33
  window - (wall_time % window)
@@ -53,12 +57,12 @@ module ThrottleMachines
53
57
 
54
58
  def window_key(key, window)
55
59
  window = positive_window(window)
56
- "#{@prefix}:#{key}:#{window}:#{(wall_time / window).floor}"
60
+ "#{@prefix}:#{key}:#{window}:#{wall_time / window}"
57
61
  end
58
62
 
59
63
  def positive_window(window)
60
- window = window.to_f
61
- raise ArgumentError, "window must be positive, got #{window}" unless window.positive?
64
+ raise TypeError, "window must be an Integer, got #{window.inspect}" unless window.is_a?(Integer)
65
+ raise RangeError, "window must be positive, got #{window}" unless window.positive?
62
66
 
63
67
  window
64
68
  end
@@ -83,8 +87,10 @@ module ThrottleMachines
83
87
  Regexp.new("^#{Regexp.escape(literal)}")
84
88
  end
85
89
 
90
+ # Integer nanoseconds since the Unix epoch.
86
91
  def wall_time
87
- Time.now.to_f
92
+ now = Time.now
93
+ (now.to_i * NS_PER_SECOND) + now.nsec
88
94
  end
89
95
  end
90
96
  end
@@ -6,15 +6,18 @@ module ThrottleMachines
6
6
  module Storage
7
7
  class Memory < Base
8
8
  DEFAULT_MAX_KEYS = 65_536
9
- CAPACITY_RETRY_AFTER = 1.0
10
- DEFAULT_CLEANUP_INTERVAL = 60
9
+ # Integer nanoseconds a key refused as :full is told to wait.
10
+ CAPACITY_RETRY_AFTER = NS_PER_SECOND
11
+ # Integer nanoseconds between background sweeps of expired entries.
12
+ DEFAULT_CLEANUP_INTERVAL = 60 * NS_PER_SECOND
11
13
  DEFAULT_LOCK_POOL_SIZE = 32
12
14
  SHUTDOWN_GRACE = 1.0
13
15
 
14
16
  def initialize(options = {})
15
17
  super
16
18
  max_keys = options.fetch(:max_keys, DEFAULT_MAX_KEYS)
17
- raise ArgumentError, 'max_keys must be a non-negative integer' unless max_keys.is_a?(Integer) && max_keys >= 0
19
+ raise TypeError, "max_keys must be an Integer, got #{max_keys.inspect}" unless max_keys.is_a?(Integer)
20
+ raise RangeError, "max_keys must not be negative, got #{max_keys}" if max_keys.negative?
18
21
 
19
22
  @state = State.new(
20
23
  max_keys: max_keys,
@@ -26,7 +29,7 @@ module ThrottleMachines
26
29
  @token_buckets = @state.token_buckets
27
30
 
28
31
  @capacity_cleanup_lock = Mutex.new
29
- @next_capacity_cleanup_at = -Float::INFINITY
32
+ @next_capacity_cleanup_at = nil
30
33
  @cleanup_thread = nil
31
34
 
32
35
  return if options[:auto_cleanup] == false
@@ -59,7 +62,7 @@ module ThrottleMachines
59
62
  stored = store_entry(@counters, window_key, { count: new_count, expires_at: counter[:expires_at] })
60
63
  end
61
64
  # An untrackable counter must never look like an admitted request.
62
- stored ? new_count : Float::INFINITY
65
+ stored ? new_count : UNTRACKED
63
66
  end
64
67
  end
65
68
 
@@ -69,7 +72,7 @@ module ThrottleMachines
69
72
 
70
73
  with_read_lock(window_key) do
71
74
  counter = @counters[window_key]
72
- return capacity_available?(@counters, window_key) ? 0 : Float::INFINITY unless counter
75
+ return capacity_available?(@counters, window_key) ? 0 : UNTRACKED unless counter
73
76
  return 0 if counter[:expires_at] <= current_time
74
77
 
75
78
  counter[:count]
@@ -93,47 +96,38 @@ module ThrottleMachines
93
96
  with_write_lock(window_key) { delete_entry(@counters, window_key) }
94
97
  end
95
98
 
96
- # GCRA operations (atomic simulation)
97
- def check_gcra_limit(key, emission_interval, delay_tolerance, ttl)
99
+ # GCRA and token bucket state is the core gate's own, kept per key as
100
+ # the values `restored` takes, so a limiter whose policy changes
101
+ # resumes from where the key's state left off. A refusal stores
102
+ # nothing.
103
+ def check_gcra(key, policy, ttl)
98
104
  reclaim_capacity
99
105
  with_write_lock(key) do
100
106
  now = current_time
101
- state = @gcra_states[key] || { tat: 0.0 }
107
+ entry = @gcra_states[key]
108
+ return :full unless entry || capacity_available?(@gcra_states, key)
102
109
 
103
- tat = [state[:tat], now].max
104
- allow = gcra_allowed?(tat, now, delay_tolerance)
110
+ gate = entry ? Gcra.restored(policy, entry[:tat]) : Gcra.new(policy)
111
+ answer = gate.check(now)
112
+ return answer unless answer.is_a?(Integer)
113
+ return :full unless store_entry(@gcra_states, key, { tat: gate.tat, expires_at: now + ttl })
105
114
 
106
- if allow
107
- new_tat = tat + emission_interval
108
- unless store_entry(@gcra_states, key, { tat: new_tat, expires_at: now + ttl })
109
- return capacity_gcra_refusal(now, delay_tolerance)
110
- end
111
- end
112
-
113
- {
114
- allowed: allow,
115
- retry_after: allow ? 0.0 : (tat - now - delay_tolerance),
116
- tat: tat
117
- }
115
+ answer
118
116
  end
119
117
  end
120
118
 
121
- def peek_gcra_limit(key, _emission_interval, delay_tolerance)
119
+ def peek_gcra(key, policy)
122
120
  reclaim_capacity
123
121
  with_read_lock(key) do
124
- now = current_time
125
- return capacity_gcra_refusal(now, delay_tolerance) unless capacity_available?(@gcra_states, key)
126
-
127
- state = @gcra_states[key] || { tat: 0.0 }
128
-
129
- tat = [state[:tat], now].max
130
- allow = gcra_allowed?(tat, now, delay_tolerance)
122
+ gate = gcra_gate(key, policy)
123
+ gate ? gate.peek(current_time) : :full
124
+ end
125
+ end
131
126
 
132
- {
133
- allowed: allow,
134
- retry_after: allow ? 0.0 : (tat - now - delay_tolerance),
135
- tat: tat
136
- }
127
+ def gcra_retry_after(key, policy)
128
+ with_read_lock(key) do
129
+ gate = gcra_gate(key, policy)
130
+ gate ? gate.retry_after(current_time) : CAPACITY_RETRY_AFTER
137
131
  end
138
132
  end
139
133
 
@@ -141,71 +135,36 @@ module ThrottleMachines
141
135
  with_write_lock(key) { delete_entry(@gcra_states, key) }
142
136
  end
143
137
 
144
- # Token bucket operations (atomic simulation)
145
- def check_token_bucket(key, capacity, refill_rate, ttl)
138
+ def check_token_bucket(key, policy, ttl)
146
139
  reclaim_capacity
147
140
  with_write_lock(key) do
148
141
  now = current_time
149
- bucket = @token_buckets[key] || { tokens: capacity, last_refill: now }
150
-
151
- # Refill tokens
152
- elapsed = now - bucket[:last_refill]
153
- tokens_to_add = elapsed * refill_rate
154
- bucket[:tokens] = [bucket[:tokens] + tokens_to_add, capacity].min
155
- bucket[:last_refill] = now
156
-
157
- # Check if we can consume a token
158
- if token_available?(bucket[:tokens], now, refill_rate)
159
- bucket[:tokens] = [bucket[:tokens] - 1, 0.0].max
160
- unless store_entry(@token_buckets, key, bucket.merge(expires_at: now + ttl))
161
- return capacity_token_bucket_refusal
162
- end
142
+ entry = @token_buckets[key]
143
+ return :full unless entry || capacity_available?(@token_buckets, key)
163
144
 
164
- {
165
- allowed: true,
166
- retry_after: 0.0,
167
- tokens_remaining: bucket[:tokens].floor
168
- }
169
- else
170
- retry_after = (1 - bucket[:tokens]) / refill_rate
145
+ gate = entry ? restored_bucket(policy, entry) : TokenBucket.new(policy)
146
+ answer = gate.check(now)
147
+ return answer unless answer.is_a?(Integer)
171
148
 
172
- {
173
- allowed: false,
174
- retry_after: retry_after,
175
- tokens_remaining: 0
176
- }
177
- end
149
+ state = { tokens: gate.tokens, refilled_at: gate.refilled_at, expires_at: now + ttl }
150
+ return :full unless store_entry(@token_buckets, key, state)
151
+
152
+ answer
178
153
  end
179
154
  end
180
155
 
181
- def peek_token_bucket(key, capacity, refill_rate)
156
+ def peek_token_bucket(key, policy)
182
157
  reclaim_capacity
183
158
  with_read_lock(key) do
184
- now = current_time
185
- return capacity_token_bucket_refusal unless capacity_available?(@token_buckets, key)
186
-
187
- bucket = @token_buckets[key] || { tokens: capacity, last_refill: now }
188
-
189
- # Calculate tokens without modifying state
190
- elapsed = now - bucket[:last_refill]
191
- tokens_to_add = elapsed * refill_rate
192
- current_tokens = [bucket[:tokens] + tokens_to_add, capacity].min
193
-
194
- if token_available?(current_tokens, now, refill_rate)
195
- {
196
- allowed: true,
197
- retry_after: 0.0,
198
- tokens_remaining: [current_tokens - 1, 0].max.floor
199
- }
200
- else
201
- retry_after = (1 - current_tokens) / refill_rate
159
+ gate = bucket_gate(key, policy)
160
+ gate ? gate.peek(current_time) : :full
161
+ end
162
+ end
202
163
 
203
- {
204
- allowed: false,
205
- retry_after: retry_after,
206
- tokens_remaining: 0
207
- }
208
- end
164
+ def token_bucket_retry_after(key, policy)
165
+ with_read_lock(key) do
166
+ gate = bucket_gate(key, policy)
167
+ gate ? gate.retry_after(current_time) : CAPACITY_RETRY_AFTER
209
168
  end
210
169
  end
211
170
 
@@ -263,12 +222,25 @@ module ThrottleMachines
263
222
  @state.capacity_available?(store, key)
264
223
  end
265
224
 
266
- def capacity_gcra_refusal(now, delay_tolerance)
267
- { allowed: false, retry_after: CAPACITY_RETRY_AFTER, tat: now + delay_tolerance + CAPACITY_RETRY_AFTER }
225
+ # The key's gate, or nil when it is untracked and the store is full.
226
+ def gcra_gate(key, policy)
227
+ entry = @gcra_states[key]
228
+ return Gcra.restored(policy, entry[:tat]) if entry
229
+
230
+ Gcra.new(policy) if capacity_available?(@gcra_states, key)
231
+ end
232
+
233
+ def bucket_gate(key, policy)
234
+ entry = @token_buckets[key]
235
+ return restored_bucket(policy, entry) if entry
236
+
237
+ TokenBucket.new(policy) if capacity_available?(@token_buckets, key)
268
238
  end
269
239
 
270
- def capacity_token_bucket_refusal
271
- { allowed: false, retry_after: CAPACITY_RETRY_AFTER, tokens_remaining: 0 }
240
+ # A capacity lowered since the key was stored keeps at most a full
241
+ # bucket.
242
+ def restored_bucket(policy, entry)
243
+ TokenBucket.restored(policy, [entry[:tokens], policy.capacity].min, entry[:refilled_at])
272
244
  end
273
245
 
274
246
  # Run before taking any striped lock. At saturation, attempt expiry
@@ -280,7 +252,7 @@ module ThrottleMachines
280
252
 
281
253
  begin
282
254
  now = current_time
283
- return if now < @next_capacity_cleanup_at
255
+ return if @next_capacity_cleanup_at && now < @next_capacity_cleanup_at
284
256
 
285
257
  @next_capacity_cleanup_at = now + CAPACITY_RETRY_AFTER
286
258
  clean_expired_entries
@@ -325,7 +297,7 @@ module ThrottleMachines
325
297
  loop do
326
298
  break if @shutdown
327
299
 
328
- sleep @cleanup_interval
300
+ sleep Rational(@cleanup_interval, NS_PER_SECOND)
329
301
  break if @shutdown
330
302
 
331
303
  clean_expired_entries
@@ -2,8 +2,9 @@
2
2
 
3
3
  module ThrottleMachines
4
4
  module Storage
5
+ # Admits everything and keeps nothing: every check answers the policy's
6
+ # full allowance, every wait is zero.
5
7
  class Null < Base
6
- # Rate limiting operations
7
8
  def increment_counter(_key, _window, _amount = 1)
8
9
  0
9
10
  end
@@ -20,49 +21,38 @@ module ThrottleMachines
20
21
  true
21
22
  end
22
23
 
23
- # GCRA operations
24
- def check_gcra_limit(_key, _emission_interval, _delay_tolerance, _ttl)
25
- {
26
- allowed: true,
27
- retry_after: 0,
28
- tat: 0
29
- }
24
+ def check_gcra(_key, policy, _ttl)
25
+ Gcra.new(policy).peek(0) - 1
30
26
  end
31
27
 
32
- def peek_gcra_limit(_key, _emission_interval, _delay_tolerance)
33
- {
34
- allowed: true,
35
- retry_after: 0,
36
- tat: 0
37
- }
28
+ def peek_gcra(_key, policy)
29
+ Gcra.new(policy).peek(0)
30
+ end
31
+
32
+ def gcra_retry_after(_key, _policy)
33
+ 0
38
34
  end
39
35
 
40
36
  def reset_gcra(_key)
41
37
  true
42
38
  end
43
39
 
44
- # Token bucket operations
45
- def check_token_bucket(_key, capacity, _refill_rate, _ttl)
46
- {
47
- allowed: true,
48
- retry_after: 0,
49
- tokens_remaining: capacity
50
- }
40
+ def check_token_bucket(_key, policy, _ttl)
41
+ policy.capacity - 1
51
42
  end
52
43
 
53
- def peek_token_bucket(_key, capacity, _refill_rate)
54
- {
55
- allowed: true,
56
- retry_after: 0,
57
- tokens_remaining: capacity
58
- }
44
+ def peek_token_bucket(_key, policy)
45
+ policy.capacity
46
+ end
47
+
48
+ def token_bucket_retry_after(_key, _policy)
49
+ 0
59
50
  end
60
51
 
61
52
  def reset_token_bucket(_key)
62
53
  true
63
54
  end
64
55
 
65
- # Utility operations
66
56
  def clear(_pattern = nil)
67
57
  true
68
58
  end
@@ -1,26 +1,27 @@
1
+ -- GCRA admission, the native core's arithmetic in Integer nanoseconds.
2
+ -- `now` is the server's TIME, one clock for every client. The theoretical
3
+ -- arrival time is stored relative to `epoch`, a TIME second, and rebased to
4
+ -- the current second on every write, so every number stays small enough to
5
+ -- be exact in Lua's doubles.
6
+ -- ARGV: emission_interval, delay_tolerance, ttl (ms).
7
+ -- Reply: {1, calls still admitted} or {0, 0} (throttled, nothing stored).
1
8
  local key = KEYS[1]
2
- local emission_interval = tonumber(ARGV[1])
3
- local delay_tolerance = tonumber(ARGV[2])
9
+ local interval = tonumber(ARGV[1])
10
+ local tolerance = tonumber(ARGV[2])
4
11
  local ttl = tonumber(ARGV[3])
5
- local now = tonumber(ARGV[4])
6
12
 
7
- local tat = redis.call('GET', key)
8
- if not tat then
9
- tat = 0
10
- else
11
- tat = tonumber(tat)
12
- end
13
-
14
- tat = math.max(tat, now)
15
- -- The TAT is a running sum of emission intervals, so an on-schedule arrival
16
- -- can overshoot the tolerance by a few ulps; the slack scales with the clock.
17
- local slack = 2.220446049250313e-16 * 64 * math.max(math.abs(tat), 1)
18
- local allow = (tat - now) <= delay_tolerance + slack
13
+ local time = redis.call('TIME')
14
+ local second = tonumber(time[1])
15
+ local state = redis.call('HMGET', key, 'tat', 'epoch')
16
+ local shift = (second - (tonumber(state[2]) or second)) * 1000000000
17
+ local now = shift + tonumber(time[2]) * 1000
19
18
 
20
- if allow then
21
- local new_tat = tat + emission_interval
22
- redis.call('SET', key, new_tat, 'EX', ttl)
19
+ local tat = tonumber(state[1]) or 0
20
+ local ahead = math.max(tat - now, 0)
21
+ if ahead > tolerance then
22
+ return { 0, 0 }
23
23
  end
24
24
 
25
- -- Redis truncates Lua numbers in replies to integers; send the TAT as text.
26
- return { allow and 1 or 0, string.format('%.17g', tat) }
25
+ redis.call('HSET', key, 'tat', string.format('%.0f', math.max(tat, now) + interval - shift), 'epoch', second)
26
+ redis.call('PEXPIRE', key, ttl)
27
+ return { 1, math.floor((tolerance - ahead) / interval) }
@@ -1,9 +1,9 @@
1
+ -- ARGV: amount, window (ms).
1
2
  local count = redis.call('INCRBY', KEYS[1], ARGV[1])
2
- local ttl = redis.call('TTL', KEYS[1])
3
3
 
4
- -- Set expiry if key is new (ttl == -2) or has no TTL (ttl == -1)
5
- if ttl <= 0 then
6
- redis.call('EXPIRE', KEYS[1], ARGV[2])
4
+ -- Set expiry if the key is new or has none.
5
+ if redis.call('PTTL', KEYS[1]) < 0 then
6
+ redis.call('PEXPIRE', KEYS[1], ARGV[2])
7
7
  end
8
8
 
9
9
  return count
@@ -1,20 +1,20 @@
1
+ -- GCRA peek, the native core's arithmetic in Integer nanoseconds, on the
2
+ -- server's TIME (see gcra.lua for how instants are stored).
3
+ -- ARGV: emission_interval, delay_tolerance.
4
+ -- Reply: {1, calls admitted now, 0} or {0, 0, nanoseconds until admitted}.
1
5
  local key = KEYS[1]
2
- local emission_interval = tonumber(ARGV[1])
3
- local delay_tolerance = tonumber(ARGV[2])
4
- local now = tonumber(ARGV[3])
6
+ local interval = tonumber(ARGV[1])
7
+ local tolerance = tonumber(ARGV[2])
5
8
 
6
- local tat = redis.call('GET', key)
7
- if not tat then
8
- tat = 0
9
- else
10
- tat = tonumber(tat)
11
- end
9
+ local time = redis.call('TIME')
10
+ local second = tonumber(time[1])
11
+ local state = redis.call('HMGET', key, 'tat', 'epoch')
12
+ local now = (second - (tonumber(state[2]) or second)) * 1000000000 + tonumber(time[2]) * 1000
12
13
 
13
- tat = math.max(tat, now)
14
- -- The TAT is a running sum of emission intervals, so an on-schedule arrival
15
- -- can overshoot the tolerance by a few ulps; the slack scales with the clock.
16
- local slack = 2.220446049250313e-16 * 64 * math.max(math.abs(tat), 1)
17
- local allow = (tat - now) <= delay_tolerance + slack
14
+ local tat = tonumber(state[1]) or 0
15
+ local ahead = math.max(tat - now, 0)
16
+ if ahead > tolerance then
17
+ return { 0, 0, string.format('%.0f', ahead - tolerance) }
18
+ end
18
19
 
19
- -- Redis truncates Lua numbers in replies to integers; send the TAT as text.
20
- return { allow and 1 or 0, string.format('%.17g', tat) }
20
+ return { 1, math.floor((tolerance + interval - ahead) / interval), 0 }