throttle_machines 0.4.2-aarch64-linux → 0.5.0-aarch64-linux

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 (42) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +231 -0
  3. data/README.md +89 -14
  4. data/ext/throttle_machines_native/core/CHANGELOG.md +77 -0
  5. data/ext/throttle_machines_native/core/README.md +100 -0
  6. data/ext/throttle_machines_native/extconf.rb +2 -0
  7. data/ext/throttle_machines_native/ffi/CHANGELOG.md +59 -0
  8. data/lib/throttle_machines/async_breaker.rb +5 -0
  9. data/lib/throttle_machines/async_support.rb +16 -21
  10. data/lib/throttle_machines/breakers.rb +46 -0
  11. data/lib/throttle_machines/control.rb +25 -46
  12. data/lib/throttle_machines/controller_helpers.rb +11 -10
  13. data/lib/throttle_machines/hedged_breaker.rb +4 -6
  14. data/lib/throttle_machines/hedged_request.rb +29 -42
  15. data/lib/throttle_machines/instrumentation.rb +10 -75
  16. data/lib/throttle_machines/limiter.rb +71 -136
  17. data/lib/throttle_machines/middleware.rb +6 -6
  18. data/lib/throttle_machines/rack_middleware/allow2_ban.rb +1 -8
  19. data/lib/throttle_machines/rack_middleware/ban_filter.rb +3 -2
  20. data/lib/throttle_machines/rack_middleware/configuration.rb +4 -2
  21. data/lib/throttle_machines/rack_middleware/fail2_ban.rb +5 -21
  22. data/lib/throttle_machines/rack_middleware/throttle.rb +2 -1
  23. data/lib/throttle_machines/rack_middleware.rb +3 -1
  24. data/lib/throttle_machines/storage/base.rb +49 -48
  25. data/lib/throttle_machines/storage/cache.rb +12 -6
  26. data/lib/throttle_machines/storage/memory.rb +68 -96
  27. data/lib/throttle_machines/storage/null.rb +18 -28
  28. data/lib/throttle_machines/storage/redis/gcra.lua +21 -20
  29. data/lib/throttle_machines/storage/redis/increment_counter.lua +4 -4
  30. data/lib/throttle_machines/storage/redis/peek_gcra.lua +16 -16
  31. data/lib/throttle_machines/storage/redis/peek_token_bucket.lua +22 -18
  32. data/lib/throttle_machines/storage/redis/token_bucket.lua +31 -19
  33. data/lib/throttle_machines/storage/redis.rb +63 -69
  34. data/lib/throttle_machines/throttled_error.rb +4 -1
  35. data/lib/throttle_machines/version.rb +1 -1
  36. data/lib/throttle_machines.rb +130 -87
  37. data/lib/throttle_machines_native/throttle_machines_native.so +0 -0
  38. data/sig/throttle_machines.rbs +555 -0
  39. metadata +19 -57
  40. data/lib/throttle_machines/async_limiter.rb +0 -24
  41. data/lib/throttle_machines/dependency_error.rb +0 -6
  42. data/lib/throttle_machines/native_speedup.rb +0 -110
@@ -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 }
@@ -1,24 +1,28 @@
1
+ -- Token bucket peek, the native core's arithmetic in Integer nanoseconds,
2
+ -- on the server's TIME (see token_bucket.lua for how instants are stored).
3
+ -- ARGV: capacity, refill_every.
4
+ -- Reply: {1, tokens available, 0} or {0, 0, nanoseconds until one is}.
1
5
  local key = KEYS[1]
2
6
  local capacity = tonumber(ARGV[1])
3
- local refill_rate = tonumber(ARGV[2])
4
- local now = tonumber(ARGV[3])
7
+ local refill = tonumber(ARGV[2])
5
8
 
6
- local bucket = redis.call('HMGET', key, 'tokens', 'last_refill')
7
- local tokens = tonumber(bucket[1]) or capacity
8
- local last_refill = tonumber(bucket[2]) or now
9
+ local time = redis.call('TIME')
10
+ local second = tonumber(time[1])
11
+ local bucket = redis.call('HMGET', key, 'tokens', 'refilled_at', 'epoch')
12
+ local now = (second - (tonumber(bucket[3]) or second)) * 1000000000 + tonumber(time[2]) * 1000
9
13
 
10
- -- Calculate tokens without modifying
11
- local elapsed = now - last_refill
12
- local tokens_to_add = elapsed * refill_rate
13
- tokens = math.min(tokens + tokens_to_add, capacity)
14
+ local tokens = math.min(tonumber(bucket[1]) or capacity, capacity)
15
+ local refilled_at = tonumber(bucket[2]) or 0
14
16
 
15
- -- `elapsed` carries the clock's rounding; a token due exactly now may come
16
- -- out a hair short of 1. The slack scales with the clock, as in the native core.
17
- local slack = 2.220446049250313e-16 * 64 * math.max(math.abs(now), 1) * refill_rate
18
- local allow = tokens >= 1 - slack
19
- -- Admitted: tokens left after this request. Refused: the fractional balance,
20
- -- which retry_after is computed from.
21
- local tokens_after = allow and math.max(tokens - 1, 0) or tokens
17
+ local earned = math.floor(math.max(now - refilled_at, 0) / refill)
18
+ if tokens + earned >= capacity then
19
+ return { 1, capacity, 0 }
20
+ end
22
21
 
23
- -- Redis truncates Lua numbers in replies to integers; send the count as text.
24
- return { allow and 1 or 0, string.format('%.17g', tokens_after) }
22
+ tokens = tokens + earned
23
+ if tokens >= 1 then
24
+ return { 1, tokens, 0 }
25
+ end
26
+
27
+ refilled_at = refilled_at + earned * refill
28
+ return { 0, 0, string.format('%.0f', math.max(refilled_at + refill - now, 0)) }
@@ -1,27 +1,39 @@
1
+ -- Token bucket admission, the native core's arithmetic in Integer
2
+ -- nanoseconds. `now` is the server's TIME, one clock for every client. The
3
+ -- refill instant is stored relative to `epoch`, a TIME second, and rebased
4
+ -- to the current second on every write, so every number stays small enough
5
+ -- to be exact in Lua's doubles.
6
+ -- ARGV: capacity, refill_every, ttl (ms).
7
+ -- Reply: {1, tokens left} or {0, 0} (throttled, nothing stored).
1
8
  local key = KEYS[1]
2
9
  local capacity = tonumber(ARGV[1])
3
- local refill_rate = tonumber(ARGV[2])
10
+ local refill = tonumber(ARGV[2])
4
11
  local ttl = tonumber(ARGV[3])
5
- local now = tonumber(ARGV[4])
6
12
 
7
- local bucket = redis.call('HMGET', key, 'tokens', 'last_refill')
8
- local tokens = tonumber(bucket[1]) or capacity
9
- local last_refill = tonumber(bucket[2]) or now
13
+ local time = redis.call('TIME')
14
+ local second = tonumber(time[1])
15
+ local bucket = redis.call('HMGET', key, 'tokens', 'refilled_at', 'epoch')
16
+ local shift = (second - (tonumber(bucket[3]) or second)) * 1000000000
17
+ local now = shift + tonumber(time[2]) * 1000
10
18
 
11
- -- Refill tokens
12
- local elapsed = now - last_refill
13
- local tokens_to_add = elapsed * refill_rate
14
- tokens = math.min(tokens + tokens_to_add, capacity)
19
+ local tokens = math.min(tonumber(bucket[1]) or capacity, capacity)
20
+ local refilled_at = tonumber(bucket[2]) or 0
15
21
 
16
- -- `elapsed` carries the clock's rounding; a token due exactly now may come
17
- -- out a hair short of 1. The slack scales with the clock, as in the native core.
18
- local slack = 2.220446049250313e-16 * 64 * math.max(math.abs(now), 1) * refill_rate
19
- local allow = tokens >= 1 - slack
20
- if allow then
21
- tokens = math.max(tokens - 1, 0)
22
- redis.call('HMSET', key, 'tokens', tokens, 'last_refill', now)
23
- redis.call('EXPIRE', key, ttl)
22
+ -- A partial span toward the next token is kept; nothing is banked past capacity.
23
+ local earned = math.floor(math.max(now - refilled_at, 0) / refill)
24
+ if tokens + earned >= capacity then
25
+ tokens = capacity
26
+ refilled_at = math.max(refilled_at, now)
27
+ else
28
+ tokens = tokens + earned
29
+ refilled_at = refilled_at + earned * refill
24
30
  end
25
31
 
26
- -- Redis truncates Lua numbers in replies to integers; send the count as text.
27
- return { allow and 1 or 0, string.format('%.17g', tokens) }
32
+ if tokens < 1 then
33
+ return { 0, 0 }
34
+ end
35
+
36
+ tokens = tokens - 1
37
+ redis.call('HSET', key, 'tokens', tokens, 'refilled_at', string.format('%.0f', refilled_at - shift), 'epoch', second)
38
+ redis.call('PEXPIRE', key, ttl)
39
+ return { 1, tokens }