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
@@ -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 }
@@ -4,7 +4,21 @@ require 'digest/sha1'
4
4
 
5
5
  module ThrottleMachines
6
6
  module Storage
7
+ # Limiter state in Redis, decided atomically by Lua scripts that repeat
8
+ # the native core's arithmetic in Integer nanoseconds.
9
+ #
10
+ # `now` is the server's clock: each script reads Redis TIME (whole
11
+ # microseconds), so processes on any number of hosts share one store and
12
+ # one clock. A server whose clock steps back (NTP, a failover to another
13
+ # host) is the only clock the limits see.
14
+ #
15
+ # Lua numbers are doubles, exact up to 2**53. Stored instants count from
16
+ # a TIME second kept beside them and are rebased to the current second on
17
+ # every write, so they stay small: arithmetic is exact while policy spans
18
+ # are under 2**53 ns (about 104 days) and a key idles no longer than
19
+ # that, which its TTL (twice the limiter's period) bounds.
7
20
  class Redis < Base
21
+ NS_PER_MILLISECOND = 1_000_000
8
22
  # Load Lua scripts from files
9
23
  LUA_SCRIPTS_DIR = File.expand_path('redis', __dir__)
10
24
 
@@ -21,6 +35,7 @@ module ThrottleMachines
21
35
  TOKEN_BUCKET_SHA = Digest::SHA1.hexdigest(TOKEN_BUCKET_SCRIPT)
22
36
  PEEK_GCRA_SHA = Digest::SHA1.hexdigest(PEEK_GCRA_SCRIPT)
23
37
  PEEK_TOKEN_BUCKET_SHA = Digest::SHA1.hexdigest(PEEK_TOKEN_BUCKET_SCRIPT)
38
+ INCREMENT_COUNTER_SHA = Digest::SHA1.hexdigest(INCREMENT_COUNTER_SCRIPT)
24
39
 
25
40
  # Keys a single SCAN round trip asks for.
26
41
  SCAN_BATCH = 100
@@ -34,93 +49,61 @@ module ThrottleMachines
34
49
  validate_redis_connection!
35
50
  end
36
51
 
37
- # Rate limiting operations
38
52
  def increment_counter(key, window, amount = 1)
39
- window_key = prefixed("#{key}:#{window}")
40
-
41
- # Use Lua script for atomic increment with TTL
42
- with_redis do |redis|
43
- redis.eval(INCREMENT_COUNTER_SCRIPT, keys: [window_key], argv: [amount, window.to_i])
44
- end
53
+ run_script(INCREMENT_COUNTER_SCRIPT, INCREMENT_COUNTER_SHA,
54
+ keys: [window_key(key, window)], argv: [amount, milliseconds(window)])
45
55
  end
46
56
 
47
57
  def get_counter(key, window)
48
- window_key = prefixed("#{key}:#{window}")
49
- with_redis { |r| (r.get(window_key) || 0).to_i }
58
+ with_redis { |r| (r.get(window_key(key, window)) || 0).to_i }
50
59
  end
51
60
 
61
+ # Integer nanoseconds until the window's counter expires.
52
62
  def get_counter_ttl(key, window)
53
- window_key = prefixed("#{key}:#{window}")
54
- ttl = with_redis { |r| r.ttl(window_key) }
55
- [ttl, 0].max
63
+ ttl = with_redis { |r| r.pttl(window_key(key, window)) }
64
+ [ttl, 0].max * NS_PER_MILLISECOND
56
65
  end
57
66
 
58
67
  def reset_counter(key, window)
59
- window_key = prefixed("#{key}:#{window}")
60
- with_redis { |r| r.del(window_key) }
68
+ with_redis { |r| r.del(window_key(key, window)) }
61
69
  end
62
70
 
63
- # GCRA operations (atomic via Lua)
64
- def check_gcra_limit(key, emission_interval, delay_tolerance, ttl)
65
- now = current_time
66
- result = run_script(GCRA_SCRIPT, GCRA_SHA,
67
- keys: [prefixed(key)],
68
- argv: [emission_interval, delay_tolerance, ttl, now])
71
+ def check_gcra(key, policy, ttl)
72
+ argv = [policy.emission_interval, policy.delay_tolerance, milliseconds(ttl)]
73
+ allowed, left = run_script(GCRA_SCRIPT, GCRA_SHA, keys: [prefixed(key)], argv: argv)
74
+ allowed == 1 ? Integer(left) : :throttled
75
+ end
69
76
 
70
- allowed = result[0] == 1
71
- tat = Float(result[1])
77
+ def peek_gcra(key, policy)
78
+ admitted(peek_gcra_reply(key, policy))
79
+ end
72
80
 
73
- {
74
- allowed: allowed,
75
- retry_after: allowed ? 0 : (tat - now - delay_tolerance),
76
- tat: tat
77
- }
81
+ def gcra_retry_after(key, policy)
82
+ Integer(peek_gcra_reply(key, policy)[2])
78
83
  end
79
84
 
80
85
  def reset_gcra(key)
81
86
  delete_state(key)
82
87
  end
83
88
 
84
- # Token bucket operations (atomic via Lua)
85
- def check_token_bucket(key, capacity, refill_rate, ttl)
86
- result = run_script(TOKEN_BUCKET_SCRIPT, TOKEN_BUCKET_SHA,
87
- keys: [prefixed(key)],
88
- argv: [capacity, refill_rate, ttl, current_time])
89
-
90
- token_bucket_result(result, refill_rate)
89
+ def check_token_bucket(key, policy, ttl)
90
+ argv = [policy.capacity, policy.refill_every, milliseconds(ttl)]
91
+ allowed, left = run_script(TOKEN_BUCKET_SCRIPT, TOKEN_BUCKET_SHA, keys: [prefixed(key)], argv: argv)
92
+ allowed == 1 ? Integer(left) : :throttled
91
93
  end
92
94
 
93
- def reset_token_bucket(key)
94
- delete_state(key)
95
+ def peek_token_bucket(key, policy)
96
+ admitted(peek_token_bucket_reply(key, policy))
95
97
  end
96
98
 
97
- # Peek methods for non-consuming checks
98
- def peek_gcra_limit(key, emission_interval, delay_tolerance)
99
- now = current_time
100
- result = run_script(PEEK_GCRA_SCRIPT, PEEK_GCRA_SHA,
101
- keys: [prefixed(key)],
102
- argv: [emission_interval, delay_tolerance, now])
103
-
104
- allowed = result[0] == 1
105
- tat = Float(result[1])
106
-
107
- {
108
- allowed: allowed,
109
- retry_after: allowed ? 0 : (tat - now - delay_tolerance),
110
- tat: tat
111
- }
99
+ def token_bucket_retry_after(key, policy)
100
+ Integer(peek_token_bucket_reply(key, policy)[2])
112
101
  end
113
102
 
114
- def peek_token_bucket(key, capacity, refill_rate)
115
- result = run_script(PEEK_TOKEN_BUCKET_SCRIPT, PEEK_TOKEN_BUCKET_SHA,
116
- keys: [prefixed(key)],
117
- argv: [capacity, refill_rate, current_time])
118
-
119
- token_bucket_result(result, refill_rate)
103
+ def reset_token_bucket(key)
104
+ delete_state(key)
120
105
  end
121
106
 
122
- # No circuit breaker operations: breaker state is owned by BreakerMachines
123
-
124
107
  # Utility operations
125
108
  def clear(pattern = nil)
126
109
  delete_matching(pattern ? prefixed(pattern) : "#{@prefix}#{GLOB_WILDCARD}")
@@ -158,17 +141,28 @@ module ThrottleMachines
158
141
  end
159
142
  end
160
143
 
161
- # `result` is [allowed, tokens]: the balance after an admission, or the
162
- # fractional balance a refusal waits on. Matches Storage::Memory.
163
- def token_bucket_result(result, refill_rate)
164
- allowed = result[0] == 1
165
- tokens = Float(result[1])
144
+ # A peek reply is [allowed, calls admitted, nanoseconds to wait].
145
+ def admitted(reply)
146
+ reply[0] == 1 ? Integer(reply[1]) : :throttled
147
+ end
148
+
149
+ def peek_gcra_reply(key, policy)
150
+ argv = [policy.emission_interval, policy.delay_tolerance]
151
+ run_script(PEEK_GCRA_SCRIPT, PEEK_GCRA_SHA, keys: [prefixed(key)], argv: argv)
152
+ end
153
+
154
+ def peek_token_bucket_reply(key, policy)
155
+ argv = [policy.capacity, policy.refill_every]
156
+ run_script(PEEK_TOKEN_BUCKET_SCRIPT, PEEK_TOKEN_BUCKET_SHA, keys: [prefixed(key)], argv: argv)
157
+ end
158
+
159
+ def window_key(key, window)
160
+ prefixed("#{key}:#{window}")
161
+ end
166
162
 
167
- {
168
- allowed: allowed,
169
- retry_after: allowed ? 0 : (1 - tokens) / refill_rate,
170
- tokens_remaining: allowed ? tokens.floor : 0
171
- }
163
+ # Redis expiries are whole milliseconds; a span rounds up to at least one.
164
+ def milliseconds(nanoseconds)
165
+ [nanoseconds.ceildiv(NS_PER_MILLISECOND), 1].max
172
166
  end
173
167
 
174
168
  def prefixed(key)
@@ -9,6 +9,9 @@ module ThrottleMachines
9
9
  super("Rate limit exceeded for #{limiter.key}")
10
10
  end
11
11
 
12
- delegate :retry_after, to: :@limiter
12
+ # Integer nanoseconds until the limiter admits a call, asked now.
13
+ def retry_after
14
+ @limiter.retry_after
15
+ end
13
16
  end
14
17
  end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module ThrottleMachines
4
- VERSION = '0.4.3'
4
+ VERSION = '0.5.0'
5
5
  end
@@ -3,6 +3,7 @@
3
3
  require 'json'
4
4
  require 'timeout'
5
5
  require 'zeitwerk'
6
+ require 'active_support'
6
7
  require 'active_support/core_ext/class/attribute'
7
8
 
8
9
  # Ecosystem dependencies
@@ -10,57 +11,128 @@ require 'chrono_machines'
10
11
  require 'deadline_machines'
11
12
  require 'breaker_machines'
12
13
 
13
- # Set up Zeitwerk loader
14
+ # Rate limiting over a native Rust core.
15
+ #
16
+ # Every instant and span in this gem is Integer nanoseconds: `now` as read
17
+ # from `Process.clock_gettime(Process::CLOCK_MONOTONIC, :nanosecond)`, and
18
+ # every period, window, interval, TTL and retry_after. Arguments are in
19
+ # 0..2**64-1, except a native gate's instants (`now`, `tat`, `refilled_at`,
20
+ # `window_start`), which take the whole Duration range, so every instant a
21
+ # gate returns reads back.
22
+ #
23
+ # Every Data value below is held to what the core accepts, whether the gem
24
+ # built it or the caller did: TypeError for the wrong type, RangeError for a
25
+ # value outside the core's domain.
26
+ module ThrottleMachines
27
+ # One call per `emission_interval`, with up to `delay_tolerance` of calls
28
+ # ahead of schedule allowed as a burst. `emission_interval` is positive, and
29
+ # the burst ceiling (`delay_tolerance + emission_interval`) holds at most
30
+ # 2**64-1 intervals, so every count a gate answers is exact.
31
+ # `GcraPolicy.per(period, limit, burst)` spreads `limit` calls over
32
+ # `period`, `burst` of them back to back (1 for none), rounding the
33
+ # interval up to the nanosecond so the rate never exceeds the one asked for.
34
+ GcraPolicy = Data.define(:emission_interval, :delay_tolerance) do
35
+ def self.per(period, limit, burst)
36
+ new(*ThrottleMachines.__send__(:__gcra_per, period, limit, burst))
37
+ end
38
+
39
+ def initialize(emission_interval:, delay_tolerance:)
40
+ ThrottleMachines.__send__(:__gcra_policy, emission_interval, delay_tolerance)
41
+ super
42
+ end
43
+ end
44
+
45
+ # A burst of `capacity` calls (positive), one token earned every
46
+ # `refill_every` (positive). `TokenBucketPolicy.per(period, limit)` holds
47
+ # `limit` tokens and spreads their refill over `period`, rounded up.
48
+ TokenBucketPolicy = Data.define(:capacity, :refill_every) do
49
+ def self.per(period, limit)
50
+ new(*ThrottleMachines.__send__(:__token_bucket_per, period, limit))
51
+ end
52
+
53
+ def initialize(capacity:, refill_every:)
54
+ ThrottleMachines.__send__(:__token_bucket_policy, capacity, refill_every)
55
+ super
56
+ end
57
+ end
58
+
59
+ # `limit` calls (positive) per `window` (positive).
60
+ FixedWindowPolicy = Data.define(:window, :limit) do
61
+ def initialize(window:, limit:)
62
+ ThrottleMachines.__send__(:__fixed_window_policy, window, limit)
63
+ super
64
+ end
65
+ end
66
+ end
67
+
68
+ # Native is required: no algorithm fallback. It validates the Data values
69
+ # above and defines the gates over them (Gcra, TokenBucket, FixedWindow),
70
+ # so they must exist first.
71
+ require 'throttle_machines_native/throttle_machines_native'
72
+
73
+ module ThrottleMachines
74
+ private_class_method :__gcra_policy, :__token_bucket_policy, :__fixed_window_policy, :__gcra_per,
75
+ :__token_bucket_per
76
+
77
+ # The values are sealed. `initialize` is where each validates, and a
78
+ # subclass could override it, or `allocate` build an instance that never
79
+ # ran it: subclassing raises TypeError and `allocate` is gone. Sealing stops
80
+ # accidents, not reflection (`Marshal.load` skips `initialize`), so the
81
+ # native side is the authority: a policy it reads must be exactly its
82
+ # class, and its fields are checked again.
83
+ [GcraPolicy, TokenBucketPolicy, FixedWindowPolicy].each do |value|
84
+ value.singleton_class.undef_method(:allocate)
85
+ value.define_singleton_method(:inherited) { |_| raise TypeError, "#{value} cannot be subclassed" }
86
+ end
87
+ end
88
+
89
+ # The runtime layered on the gates: limiters over shared storage, Rack and
90
+ # Rails integration. Its keywords belong to it; the core has no counterpart.
14
91
  loader = Zeitwerk::Loader.for_gem
15
- loader.ignore("#{__dir__}/throttle_machines/engine.rb") unless defined?(Rails::Engine)
16
- loader.ignore("#{__dir__}/throttle_machines/native_speedup.rb")
92
+ # The engine is required below, not autoloaded: nothing references
93
+ # ThrottleMachines::Engine, and a Rails::Engine registers its initializers
94
+ # only when its class is defined.
95
+ loader.ignore("#{__dir__}/throttle_machines/engine.rb")
96
+ loader.ignore("#{__dir__}/throttle_machines/async_support.rb")
97
+ loader.ignore("#{__dir__}/throttle_machines_native")
17
98
  loader.setup
18
99
 
19
100
  module ThrottleMachines
101
+ NS_PER_SECOND = 1_000_000_000
102
+
20
103
  class Configuration
21
- attr_accessor :default_limit, :default_period, :default_storage, :clock,
22
- :default_algorithm, :instrumentation_enabled, :instrumentation_backend,
23
- :_storage_instance
104
+ attr_accessor :default_storage, :default_algorithm, :instrumentation_enabled,
105
+ :instrumentation_backend, :_storage_instance
106
+ attr_reader :fiber_safe
24
107
 
25
108
  def initialize
26
- @default_limit = 100
27
- @default_period = 60 # 1 minute
28
109
  @default_storage = :memory
29
110
  @default_algorithm = :fixed_window
30
- @clock = nil
31
111
  @instrumentation_enabled = true
32
112
  @instrumentation_backend = nil
33
113
  @fiber_safe = false
34
114
  @_storage_instance = nil
35
115
  end
36
116
 
37
- def fiber_safe
38
- @fiber_safe
39
- end
40
-
41
117
  def fiber_safe=(value)
42
118
  @fiber_safe = !!value
43
- ThrottleMachines.load_async_runtime! if @fiber_safe && ThrottleMachines.respond_to?(:load_async_runtime!)
119
+ ThrottleMachines.load_async_runtime! if @fiber_safe
44
120
  end
45
-
46
- alias async_enabled fiber_safe
47
- alias async_enabled= fiber_safe=
48
121
  end
49
122
 
50
123
  @config = Configuration.new
51
124
 
52
125
  class << self
53
- # Delegate monotonic time to BreakerMachines for consistency
54
- delegate :monotonic_time, to: :BreakerMachines
126
+ attr_reader :config
55
127
 
56
- def config
57
- @config
128
+ # The clock every limiter reads: Integer nanoseconds, monotonic.
129
+ def monotonic_time
130
+ Process.clock_gettime(Process::CLOCK_MONOTONIC, :nanosecond)
58
131
  end
59
132
 
60
133
  def configure
61
134
  yield(config) if block_given?
62
135
 
63
- # Apply instrumentation settings
64
136
  Instrumentation.enabled = config.instrumentation_enabled
65
137
  Instrumentation.backend = config.instrumentation_backend if config.instrumentation_backend
66
138
  load_async_runtime! if config.fiber_safe
@@ -79,9 +151,7 @@ module ThrottleMachines
79
151
  storage.reset_key(key)
80
152
  else
81
153
  storage.clear
82
- # Reset storage instance to force recreation with defaults
83
154
  config._storage_instance = nil
84
- # Re-apply instrumentation settings from the configuration
85
155
  Instrumentation.enabled = config.instrumentation_enabled
86
156
  Instrumentation.backend = config.instrumentation_backend
87
157
  end
@@ -93,39 +163,41 @@ module ThrottleMachines
93
163
  control
94
164
  end
95
165
 
96
- def limit(key, limit:, period:, algorithm: nil, &block)
97
- limiter = limiter(key, limit: limit, period: period, algorithm: algorithm)
98
- limiter.throttle!(&block)
166
+ def limit(key, limit:, period:, algorithm: nil, &)
167
+ limiter(key, limit: limit, period: period, algorithm: algorithm).throttle!(&)
99
168
  end
100
169
 
101
- def break_circuit(key, failures:, timeout:, &block)
102
- BreakerMachines::Registry.instance.get_or_create_dynamic_circuit(
103
- key, self, { failure_threshold: failures, reset_timeout: timeout }
104
- ).call(&block)
170
+ # Runs the block through the registry's shared circuit `key`: it opens
171
+ # on `failures` within `within` and stays open `timeout` (default
172
+ # `within`), both Integer nanoseconds, like Control#break_on.
173
+ def break_circuit(key, failures:, within:, timeout: within, &)
174
+ Breakers.dynamic(key, self, failures, within, timeout).call(&)
105
175
  end
106
176
 
107
- def retry_with(max_attempts: 3, backoff: :exponential, &block)
108
- # Delegate to chrono_machines
109
- policy_options = {
110
- max_attempts: max_attempts,
111
- backoff_strategy: backoff,
112
- jitter_factor: backoff == :exponential ? 1.0 : 0.0
113
- }
114
- ChronoMachines.retry(policy_options, &block)
177
+ # ChronoMachines.retry: a backoff shape (ChronoMachines::Exponential,
178
+ # Constant or Fibonacci), the attempt cap, and the executor's keywords.
179
+ def retry_with(strategy, max_attempts, **runtime, &)
180
+ ChronoMachines.retry(strategy, max_attempts, **runtime, &)
115
181
  end
116
182
 
117
183
  def limiter(key, limit:, period:, algorithm: nil)
118
- Limiter.new(
119
- key,
120
- limit: limit,
121
- period: period,
122
- algorithm: algorithm || config.default_algorithm,
123
- storage: storage
124
- )
184
+ Limiter.new(key, limit: limit, period: period, algorithm: algorithm || config.default_algorithm,
185
+ storage: storage)
125
186
  end
126
187
 
127
188
  def async_breaker(...)
128
- ThrottleMachines::AsyncBreaker.new(...)
189
+ AsyncBreaker.new(...)
190
+ end
191
+
192
+ # Runs the block through a HedgedRequest built with these keywords, then
193
+ # shuts its executor down.
194
+ def hedged_request(**, &)
195
+ hedged = HedgedRequest.new(**)
196
+ begin
197
+ hedged.run(&)
198
+ ensure
199
+ hedged.shutdown
200
+ end
129
201
  end
130
202
 
131
203
  def load_async_runtime!
@@ -142,60 +214,31 @@ module ThrottleMachines
142
214
 
143
215
  def create_storage(storage)
144
216
  case storage
145
- when Symbol
146
- create_storage_from_symbol(storage)
147
- when Class
148
- storage.new
149
- when Storage::Base
150
- storage
151
- else
152
- raise ArgumentError, "Invalid storage: #{storage.inspect}"
217
+ when Symbol then create_storage_from_symbol(storage)
218
+ when Class then storage.new
219
+ when Storage::Base then storage
220
+ else raise TypeError, "Invalid storage: #{storage.inspect}"
153
221
  end
154
222
  end
155
223
 
156
224
  def create_storage_from_symbol(symbol)
157
225
  case symbol
158
- when :memory
159
- Storage::Memory.new
160
- when :cache
161
- Storage::Cache.new
226
+ when :memory then Storage::Memory.new
227
+ when :cache then Storage::Cache.new
228
+ when :null then Storage::Null.new
162
229
  when :redis
163
- raise ArgumentError, 'Redis storage requires redis gem' unless defined?(Redis)
164
-
165
230
  raise ArgumentError, 'Redis storage requires a Redis client instance. ' \
166
- 'Configure with: config.storage = Storage::Redis.new(redis: Redis.new)'
167
-
168
- when :null
169
- Storage::Null.new
170
- else
171
- raise ArgumentError, "Unknown storage type: #{symbol}"
231
+ 'Configure with: ThrottleMachines.storage = Storage::Redis.new(redis: Redis.new)'
232
+ else raise RangeError, "Unknown storage type: #{symbol}"
172
233
  end
173
234
  end
174
235
  end
175
236
 
176
- # Auto-configure with defaults
177
237
  configure
178
238
 
179
239
  CircuitOpenError = BreakerMachines::CircuitOpenError
180
240
  RetryExhaustedError = ChronoMachines::MaxRetriesExceededError
181
-
182
- # Back-compat wrapper: use BreakerMachines as the circuit implementation
183
- Breaker = BreakerMachines::Circuit
184
241
  end
185
242
 
186
- # Optional speedups (order matters: most specific first)
187
- # These are loaded after Zeitwerk setup to allow graceful fallback.
188
-
189
- # Native Rust extension for performance-critical algorithms
190
- begin
191
- require_relative "throttle_machines/native_speedup"
192
- rescue LoadError
193
- # Native extension not available, pure Ruby will be used
194
- end
195
-
196
- # Async/Fiber support when Async gem is loaded
197
- begin
198
- require_relative "throttle_machines/async_support"
199
- rescue LoadError
200
- # Async gem not available
201
- end
243
+ require_relative 'throttle_machines/async_support'
244
+ require_relative 'throttle_machines/engine' if defined?(Rails::Engine)