throttle_machines 0.4.2 → 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
@@ -0,0 +1,194 @@
1
+ //! The gem's policy `Data` classes, resolved once at init and pinned: read
2
+ //! from Ruby by exact class and re-validated through the core, and built
3
+ //! natively from what the core holds.
4
+
5
+ use std::num::NonZeroU64;
6
+
7
+ use magnus::{Error, IntoValue, RArray, RClass, RModule, RStruct, Ruby, Value, prelude::*};
8
+ use matryona_machines::ruby::{Class, duration, exact_fields, nanoseconds, positive};
9
+ use throttle_machines::{FixedWindowPolicy, GcraPolicy, TokenBucketPolicy};
10
+
11
+ /// Every `Data` class of the gem, as resolved at init.
12
+ pub struct Classes {
13
+ gcra: Class,
14
+ token_bucket: Class,
15
+ fixed_window: Class,
16
+ }
17
+
18
+ matryona_machines::registry! {
19
+ static CLASSES: Classes = "throttle_machines";
20
+ fn classes;
21
+ }
22
+
23
+ pub fn resolve(ruby: &Ruby, module: RModule) -> Result<(), Error> {
24
+ let class = |name| Class::resolve(ruby, module, name);
25
+ let classes = Classes {
26
+ gcra: class("GcraPolicy")?,
27
+ token_bucket: class("TokenBucketPolicy")?,
28
+ fixed_window: class("FixedWindowPolicy")?,
29
+ };
30
+ CLASSES.set(ruby, classes).map(drop)
31
+ }
32
+
33
+ fn range_error(ruby: &Ruby, message: &'static str) -> Error {
34
+ Error::new(ruby.exception_range_error(), message)
35
+ }
36
+
37
+ /// A frozen instance of `class` holding `members`, in order: all
38
+ /// `Data#initialize` does past the check, which the core's own values need
39
+ /// not repeat, so no Ruby code runs.
40
+ fn build<const N: usize>(class: RClass, members: [Value; N]) -> Result<Value, Error> {
41
+ let instance = RStruct::try_convert(class.obj_alloc()?)?;
42
+ for (index, member) in members.into_iter().enumerate() {
43
+ instance.aset(index, member)?;
44
+ }
45
+ instance.freeze();
46
+ Ok(instance.as_value())
47
+ }
48
+
49
+ const ZERO_INTERVAL: &str = "emission_interval must be positive";
50
+ const ZERO_REFILL: &str = "refill_every must be positive";
51
+ const ZERO_WINDOW: &str = "window must be positive";
52
+ const ZERO_PERIOD: &str = "period must be positive";
53
+ const BURST: &str = "the burst ceiling (delay_tolerance + emission_interval) must fit a Duration \
54
+ and hold at most 2**64-1 emission intervals";
55
+
56
+ fn gcra_policy(ruby: &Ruby, interval: Value, tolerance: Value) -> Result<GcraPolicy, Error> {
57
+ let interval = duration(interval, "emission_interval")?;
58
+ let tolerance = duration(tolerance, "delay_tolerance")?;
59
+ GcraPolicy::new(interval, tolerance).ok_or_else(|| {
60
+ range_error(
61
+ ruby,
62
+ if interval.is_zero() {
63
+ ZERO_INTERVAL
64
+ } else {
65
+ BURST
66
+ },
67
+ )
68
+ })
69
+ }
70
+
71
+ fn token_bucket_policy(
72
+ ruby: &Ruby,
73
+ capacity: Value,
74
+ refill_every: Value,
75
+ ) -> Result<TokenBucketPolicy, Error> {
76
+ let capacity = positive::<NonZeroU64>(capacity, "capacity")?;
77
+ let refill_every = duration(refill_every, "refill_every")?;
78
+ TokenBucketPolicy::new(capacity, refill_every).ok_or_else(|| range_error(ruby, ZERO_REFILL))
79
+ }
80
+
81
+ fn fixed_window_policy(
82
+ ruby: &Ruby,
83
+ window: Value,
84
+ limit: Value,
85
+ ) -> Result<FixedWindowPolicy, Error> {
86
+ let window = duration(window, "window")?;
87
+ let limit = positive::<NonZeroU64>(limit, "limit")?;
88
+ FixedWindowPolicy::new(window, limit).ok_or_else(|| range_error(ruby, ZERO_WINDOW))
89
+ }
90
+
91
+ /// `__gcra_policy`: what `GcraPolicy::new` accepts.
92
+ pub fn check_gcra(ruby: &Ruby, interval: Value, tolerance: Value) -> Result<(), Error> {
93
+ gcra_policy(ruby, interval, tolerance).map(drop)
94
+ }
95
+
96
+ /// `__token_bucket_policy`: what `TokenBucketPolicy::new` accepts.
97
+ pub fn check_token_bucket(ruby: &Ruby, capacity: Value, refill: Value) -> Result<(), Error> {
98
+ token_bucket_policy(ruby, capacity, refill).map(drop)
99
+ }
100
+
101
+ /// `__fixed_window_policy`: what `FixedWindowPolicy::new` accepts.
102
+ pub fn check_fixed_window(ruby: &Ruby, window: Value, limit: Value) -> Result<(), Error> {
103
+ fixed_window_policy(ruby, window, limit).map(drop)
104
+ }
105
+
106
+ /// `__gcra_per`: the two spans `GcraPolicy::per` answers, as an Array.
107
+ pub fn gcra_per(ruby: &Ruby, period: Value, limit: Value, burst: Value) -> Result<RArray, Error> {
108
+ let period = duration(period, "period")?;
109
+ let limit = positive::<NonZeroU64>(limit, "limit")?;
110
+ let burst = positive::<NonZeroU64>(burst, "burst")?;
111
+ let policy = GcraPolicy::per(period, limit, burst)
112
+ .ok_or_else(|| range_error(ruby, if period.is_zero() { ZERO_PERIOD } else { BURST }))?;
113
+ // `per` can answer a tolerance past what a policy span accepts back.
114
+ let tolerance = u64::try_from(policy.delay_tolerance().as_nanos())
115
+ .map_err(|_| range_error(ruby, "delay_tolerance must fit in 0..=2**64-1 nanoseconds"))?;
116
+ Ok(ruby.ary_new_from_values(&[
117
+ nanoseconds(ruby, policy.emission_interval()).as_value(),
118
+ tolerance.into_value_with(ruby),
119
+ ]))
120
+ }
121
+
122
+ /// `__token_bucket_per`: the capacity and refill span
123
+ /// `TokenBucketPolicy::per` answers, as an Array.
124
+ pub fn token_bucket_per(ruby: &Ruby, period: Value, limit: Value) -> Result<RArray, Error> {
125
+ let period = duration(period, "period")?;
126
+ let limit = positive::<NonZeroU64>(limit, "limit")?;
127
+ let policy =
128
+ TokenBucketPolicy::per(period, limit).ok_or_else(|| range_error(ruby, ZERO_PERIOD))?;
129
+ Ok(ruby.ary_new_from_values(&[
130
+ policy.capacity().get().into_value_with(ruby),
131
+ nanoseconds(ruby, policy.refill_every()).as_value(),
132
+ ]))
133
+ }
134
+
135
+ /// Exactly a `GcraPolicy`, its fields read from the struct and validated
136
+ /// again (`Marshal.load` skips `initialize`).
137
+ pub fn read_gcra(ruby: &Ruby, value: Value) -> Result<GcraPolicy, Error> {
138
+ let class = classes(ruby)?.gcra.get(ruby);
139
+ let [interval, tolerance] = exact_fields(
140
+ ruby,
141
+ value,
142
+ class,
143
+ "expected a ThrottleMachines::GcraPolicy",
144
+ )?;
145
+ gcra_policy(ruby, interval, tolerance)
146
+ }
147
+
148
+ /// Exactly a `TokenBucketPolicy`, as [`read_gcra`].
149
+ pub fn read_token_bucket(ruby: &Ruby, value: Value) -> Result<TokenBucketPolicy, Error> {
150
+ let class = classes(ruby)?.token_bucket.get(ruby);
151
+ let [capacity, refill] = exact_fields(
152
+ ruby,
153
+ value,
154
+ class,
155
+ "expected a ThrottleMachines::TokenBucketPolicy",
156
+ )?;
157
+ token_bucket_policy(ruby, capacity, refill)
158
+ }
159
+
160
+ /// Exactly a `FixedWindowPolicy`, as [`read_gcra`].
161
+ pub fn read_fixed_window(ruby: &Ruby, value: Value) -> Result<FixedWindowPolicy, Error> {
162
+ let class = classes(ruby)?.fixed_window.get(ruby);
163
+ let [window, limit] = exact_fields(
164
+ ruby,
165
+ value,
166
+ class,
167
+ "expected a ThrottleMachines::FixedWindowPolicy",
168
+ )?;
169
+ fixed_window_policy(ruby, window, limit)
170
+ }
171
+
172
+ pub fn gcra_value(ruby: &Ruby, policy: GcraPolicy) -> Result<Value, Error> {
173
+ let members = [
174
+ nanoseconds(ruby, policy.emission_interval()).as_value(),
175
+ nanoseconds(ruby, policy.delay_tolerance()).as_value(),
176
+ ];
177
+ build(classes(ruby)?.gcra.get(ruby), members)
178
+ }
179
+
180
+ pub fn token_bucket_value(ruby: &Ruby, policy: TokenBucketPolicy) -> Result<Value, Error> {
181
+ let members = [
182
+ policy.capacity().get().into_value_with(ruby),
183
+ nanoseconds(ruby, policy.refill_every()).as_value(),
184
+ ];
185
+ build(classes(ruby)?.token_bucket.get(ruby), members)
186
+ }
187
+
188
+ pub fn fixed_window_value(ruby: &Ruby, policy: FixedWindowPolicy) -> Result<Value, Error> {
189
+ let members = [
190
+ nanoseconds(ruby, policy.window()).as_value(),
191
+ policy.limit().get().into_value_with(ruby),
192
+ ];
193
+ build(classes(ruby)?.fixed_window.get(ruby), members)
194
+ }
@@ -1,6 +1,11 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module ThrottleMachines
4
+ # `AsyncBreaker.new(name, policy, **runtime)` builds a
5
+ # BreakerMachines::AsyncCircuit (fiber-safe by default; `call_async`,
6
+ # `fire_async`, `health_check_async`) once the `async` gem loads. Shape the
7
+ # policy with Breakers.policy(failures, window, cooldown), spans in Integer
8
+ # nanoseconds.
4
9
  class AsyncBreaker
5
10
  class << self
6
11
  def new(...)
@@ -1,19 +1,17 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- # Async/Fiber support for ThrottleMachines.
3
+ # Fiber-aware waiting for ThrottleMachines limiters.
4
4
  #
5
5
  # The async gem is optional. When an Async task is active, waits yield back to
6
- # the scheduler; otherwise the limiter falls back to normal sleep.
6
+ # the scheduler; otherwise the limiter sleeps the thread.
7
7
 
8
8
  module ThrottleMachines
9
- # Fiber-aware rate limiter helpers.
9
+ # Fiber-aware rate limiter helpers, included into Limiter.
10
10
  module AsyncSupport
11
11
  def allowed_async?
12
12
  allow?
13
13
  end
14
14
 
15
- alias allow_async? allowed_async?
16
-
17
15
  def check_async
18
16
  return false unless allowed_async?
19
17
 
@@ -21,6 +19,10 @@ module ThrottleMachines
21
19
  true
22
20
  end
23
21
 
22
+ # Admits one call, waiting for the limiter while it throttles: at most
23
+ # `max_wait` Integer nanoseconds (nil for no limit of its own), and never
24
+ # past the ambient deadline_machines budget. Raises ThrottledError when
25
+ # the next admission would come too late.
24
26
  def throttle_async(max_wait: nil, &block)
25
27
  caller_budget = DeadlineMachines.current
26
28
 
@@ -30,16 +32,14 @@ module ThrottleMachines
30
32
  throttle!
31
33
  rescue ThrottledError => e
32
34
  caller_budget&.check!
33
- wait_time = [e.retry_after.to_f, 0.0].max
34
- raise if budget.clamp_sleep(wait_time) < wait_time
35
+ wait = e.retry_after
36
+ raise if budget.clamp_sleep(wait) < wait
35
37
 
36
- sleep_for(wait_time)
38
+ sleep_for(wait)
37
39
  next
38
40
  end
39
41
 
40
- return block.call if block
41
-
42
- return true
42
+ return block ? block.call : true
43
43
  end
44
44
  end
45
45
  end
@@ -47,22 +47,19 @@ module ThrottleMachines
47
47
  private
48
48
 
49
49
  # Use Async's fiber-aware sleep when in an async context.
50
- def sleep_for(duration)
50
+ def sleep_for(nanoseconds)
51
+ seconds = Rational(nanoseconds, NS_PER_SECOND)
51
52
  if (task = current_async_task)
52
- task.sleep(duration)
53
+ task.sleep(seconds)
53
54
  else
54
- sleep(duration)
55
+ sleep(seconds)
55
56
  end
56
57
  end
57
58
 
58
59
  def current_async_task
59
60
  return nil unless defined?(::Async::Task)
60
61
 
61
- if ::Async::Task.respond_to?(:current?)
62
- ::Async::Task.current?
63
- else
64
- ::Async::Task.current
65
- end
62
+ ::Async::Task.current?
66
63
  rescue StandardError
67
64
  nil
68
65
  end
@@ -70,5 +67,3 @@ module ThrottleMachines
70
67
  end
71
68
 
72
69
  ThrottleMachines::Limiter.include(ThrottleMachines::AsyncSupport)
73
-
74
- warn "[ThrottleMachines] Async support loaded" if ENV['DEBUG_MATRYOSHKA']
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ThrottleMachines
4
+ # The one seam between this gem and BreakerMachines circuits. Both speak
5
+ # Integer nanoseconds; this module only shapes the core's Policy and reads
6
+ # spans back off a circuit's own clock.
7
+ module Breakers
8
+ # The `exceptions:` a circuit guarding a limiter counts: any
9
+ # StandardError but ThrottledError. Being throttled says nothing about
10
+ # the guarded service, so it passes through uncounted.
11
+ module Failure
12
+ def self.===(error) = error.is_a?(StandardError) && !error.is_a?(ThrottledError)
13
+ end
14
+
15
+ module_function
16
+
17
+ # The Policy every ThrottleMachines circuit runs: open on `failures`
18
+ # within `window`, stay open exactly `cooldown` (no jitter), then close
19
+ # on one successful probe. `window` and `cooldown` are Integer
20
+ # nanoseconds.
21
+ def policy(failures, window, cooldown)
22
+ BreakerMachines::Policy.new(
23
+ BreakerMachines::Threshold.new(failures, nil, 0),
24
+ window,
25
+ BreakerMachines::Recovery.new(cooldown, 0.0, 1, 1),
26
+ nil
27
+ )
28
+ end
29
+
30
+ # The registry's shared circuit `name`, created on first use with
31
+ # `policy(failures, window, cooldown)` and owned by `owner`.
32
+ def dynamic(name, owner, failures, window, cooldown, **runtime)
33
+ BreakerMachines::Registry.instance.get_or_create_dynamic_circuit(
34
+ name, owner, policy(failures, window, cooldown), **runtime
35
+ )
36
+ end
37
+
38
+ # Integer nanoseconds since `circuit` opened, on the circuit's clock (a
39
+ # wall clock when it shares state through a storage), or nil when it is
40
+ # not open.
41
+ def since(circuit)
42
+ opened_at = circuit.stats.opened_at
43
+ opened_at && (circuit.now - opened_at)
44
+ end
45
+ end
46
+ end
@@ -1,6 +1,9 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module ThrottleMachines
4
+ # Composes a rate limit, a circuit breaker and a retry around a block:
5
+ # retry outermost, then the breaker, then the limiter. Spans are Integer
6
+ # nanoseconds.
4
7
  class Control
5
8
  attr_reader :key, :limiter, :breaker, :retrier
6
9
 
@@ -15,82 +18,58 @@ module ThrottleMachines
15
18
  end
16
19
 
17
20
  def break_on(failures:, within:, timeout: nil)
18
- timeout ||= within
19
- @rules[:breaker] = {
20
- failure_threshold: failures,
21
- timeout: timeout,
22
- window: within
23
- }
21
+ @rules[:breaker] = { failure_threshold: failures, timeout: timeout || within, window: within }
24
22
  self
25
23
  end
26
24
 
27
- def retry_on_failure(times:, backoff: :exponential, base_delay: 1, max_delay: 60)
28
- @rules[:retry] = {
29
- max_attempts: times,
30
- backoff: backoff,
31
- base_delay: base_delay,
32
- max_delay: max_delay
33
- }
25
+ # Retries through ChronoMachines: a backoff shape (Exponential, Constant
26
+ # or Fibonacci, spans in Integer nanoseconds) and the attempt cap, as
27
+ # ChronoMachines::Executor takes them, then its runtime keywords.
28
+ def retry_on_failure(strategy, max_attempts, **runtime)
29
+ @rules[:retry] = [strategy, max_attempts, runtime]
34
30
  self
35
31
  end
36
32
 
37
33
  def call(&block)
38
34
  setup_components
39
35
 
40
- # Build execution chain: Retry -> Breaker -> Limiter -> User Code
41
- execution_chain = block
42
-
43
- # Wrap with rate limiter (innermost, checked first)
36
+ chain = block
44
37
  if @limiter
45
- limiter_wrapped = execution_chain
46
- execution_chain = proc { @limiter.throttle!(&limiter_wrapped) }
38
+ limited = chain
39
+ chain = proc { @limiter.throttle!(&limited) }
47
40
  end
48
-
49
- # Wrap with circuit breaker
50
41
  if @breaker
51
- breaker_wrapped = execution_chain
52
- execution_chain = proc { @breaker.call(&breaker_wrapped) }
42
+ guarded = chain
43
+ chain = proc { @breaker.call(&guarded) }
53
44
  end
54
-
55
- # Wrap with retry logic (outermost, handles all failures)
56
45
  if @retrier
57
- retry_wrapped = execution_chain
58
- execution_chain = proc { @retrier.call(&retry_wrapped) }
46
+ retried = chain
47
+ chain = proc { @retrier.call(&retried) }
59
48
  end
60
-
61
- execution_chain.call
49
+ chain.call
62
50
  end
63
51
 
64
52
  private
65
53
 
66
54
  def setup_components
67
55
  if @rules[:limit] && !@limiter
68
- @limiter = ThrottleMachines.limiter(@key,
69
- limit: @rules[:limit][:rate],
70
- period: @rules[:limit][:period],
71
- algorithm: @rules[:limit][:algorithm])
56
+ rule = @rules[:limit]
57
+ @limiter = ThrottleMachines.limiter(@key, limit: rule[:rate], period: rule[:period],
58
+ algorithm: rule[:algorithm])
72
59
  end
73
60
 
74
61
  if @rules[:breaker] && !@breaker
62
+ rule = @rules[:breaker]
75
63
  @breaker = BreakerMachines::Circuit.new(
76
- @key,
77
- failure_threshold: @rules[:breaker][:failure_threshold],
78
- failure_window: @rules[:breaker][:window],
79
- reset_timeout: @rules[:breaker][:timeout]
64
+ @key, Breakers.policy(rule[:failure_threshold], rule[:window], rule[:timeout]),
65
+ exceptions: [Breakers::Failure]
80
66
  )
81
67
  end
82
68
 
83
69
  return unless @rules[:retry] && !@retrier
84
70
 
85
- # Use ChronoMachines for retry functionality
86
- policy_options = {
87
- max_attempts: @rules[:retry][:max_attempts],
88
- base_delay: @rules[:retry][:base_delay],
89
- max_delay: @rules[:retry][:max_delay],
90
- backoff_strategy: @rules[:retry][:backoff],
91
- jitter_factor: @rules[:retry][:backoff] == :exponential ? 1.0 : 0.0
92
- }
93
- @retrier = ChronoMachines::Executor.new(policy_options)
71
+ strategy, max_attempts, runtime = @rules[:retry]
72
+ @retrier = ChronoMachines::Executor.new(strategy, max_attempts, **runtime)
94
73
  end
95
74
  end
96
75
  end
@@ -1,6 +1,8 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module ThrottleMachines
4
+ # Rails controller helpers. `period:` is Integer nanoseconds; responses
5
+ # report waits in whole seconds, rounded up.
4
6
  module ControllerHelpers
5
7
  extend ActiveSupport::Concern
6
8
 
@@ -15,10 +17,10 @@ module ThrottleMachines
15
17
  key ||= default_throttle_key
16
18
 
17
19
  limiter = ThrottleMachines.limiter(key, limit: limit, period: period, algorithm: algorithm)
18
-
19
- render_rate_limited(limiter) unless limiter.allow?
20
-
20
+ limiter.throttle!
21
21
  set_rate_limit_headers(limiter)
22
+ rescue ThrottledError
23
+ render_rate_limited(limiter)
22
24
  end
23
25
 
24
26
  def with_throttle(key = nil, limit:, period:, &block)
@@ -53,27 +55,26 @@ module ThrottleMachines
53
55
 
54
56
  def render_rate_limited(limiter)
55
57
  set_rate_limit_headers(limiter)
58
+ wait = limiter.retry_after.ceildiv(NS_PER_SECOND)
56
59
 
57
60
  respond_to do |format|
58
61
  format.json do
59
- render json: {
60
- error: 'Rate limit exceeded',
61
- retry_after: limiter.retry_after
62
- }, status: :too_many_requests
62
+ render json: { error: 'Rate limit exceeded', retry_after: wait }, status: :too_many_requests
63
63
  end
64
64
 
65
65
  format.html do
66
- render plain: "Rate limit exceeded. Please try again in #{limiter.retry_after} seconds.",
66
+ render plain: "Rate limit exceeded. Please try again in #{wait} seconds.",
67
67
  status: :too_many_requests
68
68
  end
69
69
  end
70
70
  end
71
71
 
72
72
  def set_rate_limit_headers(limiter)
73
+ wait = limiter.retry_after.ceildiv(NS_PER_SECOND)
73
74
  response.headers['X-RateLimit-Limit'] = limiter.limit.to_s
74
75
  response.headers['X-RateLimit-Remaining'] = limiter.remaining.to_s
75
- response.headers['X-RateLimit-Reset'] = (Time.now.to_i + limiter.retry_after).to_s
76
- response.headers['Retry-After'] = limiter.retry_after.ceil.to_s
76
+ response.headers['X-RateLimit-Reset'] = (Time.now.to_i + wait).to_s
77
+ response.headers['Retry-After'] = wait.to_s
77
78
  end
78
79
  end
79
80
  end
@@ -1,14 +1,12 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module ThrottleMachines
4
- # Hedged request with circuit breaker integration
4
+ # Hedged request with circuit breaker integration. `delay` is Integer
5
+ # nanoseconds between attempts.
5
6
  class HedgedBreaker
6
- def initialize(breakers, delay: 0.05)
7
+ def initialize(breakers, delay: 50_000_000)
7
8
  @breakers = Array(breakers)
8
- @hedged = HedgedRequest.new(
9
- delay: delay,
10
- max_attempts: @breakers.size
11
- )
9
+ @hedged = HedgedRequest.new(delay: delay, max_attempts: @breakers.size)
12
10
  end
13
11
 
14
12
  def run(&block)
@@ -8,11 +8,12 @@ module ThrottleMachines
8
8
  # Like sending scout ships on multiple routes to find the fastest path.
9
9
  # The first ship to reach the destination wins, others are recalled.
10
10
  #
11
- # Reduces latency by racing multiple backends/attempts with staggered delays.
11
+ # Reduces latency by racing attempts started `delay` apart. `delay` and
12
+ # `timeout` are Integer nanoseconds (`timeout` nil for none).
12
13
  #
13
14
  # Example:
14
15
  # hedged = ThrottleMachines::HedgedRequest.new(
15
- # delay: 0.05, # 50ms between attempts
16
+ # delay: 50_000_000, # 50 ms between attempts
16
17
  # max_attempts: 3
17
18
  # )
18
19
  #
@@ -26,10 +27,10 @@ module ThrottleMachines
26
27
  class HedgedRequest
27
28
  attr_reader :delay, :max_attempts, :timeout
28
29
 
29
- def initialize(delay: 0.05, max_attempts: 2, timeout: nil)
30
- @delay = delay
30
+ def initialize(delay: 50_000_000, max_attempts: 2, timeout: nil)
31
+ @delay = span(delay, 'delay')
31
32
  @max_attempts = max_attempts
32
- @timeout = timeout
33
+ @timeout = timeout.nil? ? nil : span(timeout, 'timeout')
33
34
  @executor = Concurrent::ThreadPoolExecutor.new(
34
35
  min_threads: 1,
35
36
  max_threads: max_attempts,
@@ -39,33 +40,25 @@ module ThrottleMachines
39
40
  end
40
41
 
41
42
  # Run hedged request with automatic cancellation of slower attempts
42
- def run(&block)
43
- raise ArgumentError, 'Block required' unless block
43
+ def run
44
+ raise ArgumentError, 'Block required' unless block_given?
44
45
 
45
- # Generate a unique request ID for tracking
46
- request_id = "#{object_id}-#{Time.now.to_f}"
47
-
48
- # Instrument the start of the hedged request
46
+ start_time = ThrottleMachines.monotonic_time
47
+ request_id = "#{object_id}-#{start_time}"
49
48
  Instrumentation.hedged_request_started(request_id, attempts: @max_attempts)
50
49
 
51
- # Use Concurrent::Promises for better async handling
52
- futures = []
53
50
  first_result = Concurrent::Promises.resolvable_future
54
- start_time = Time.now.to_f
55
51
 
56
52
  @max_attempts.times do |attempt|
57
- # Schedule with delay
58
53
  future = if attempt.zero?
59
54
  Concurrent::Promises.future_on(@executor) { yield(attempt) }
60
55
  else
61
- Concurrent::Promises.schedule_on(@executor, @delay * attempt) { yield(attempt) }
56
+ Concurrent::Promises.schedule_on(@executor, seconds(@delay * attempt)) { yield(attempt) }
62
57
  end
63
58
 
64
- # Race to resolve first_result
65
59
  future.then do |result|
66
60
  if !first_result.resolved? && first_result.fulfill(result)
67
- # This attempt won the race
68
- duration = Time.now.to_f - start_time
61
+ duration = ThrottleMachines.monotonic_time - start_time
69
62
  Instrumentation.hedged_request_winner(request_id, attempt: attempt, duration: duration)
70
63
  end
71
64
  result
@@ -73,42 +66,36 @@ module ThrottleMachines
73
66
  # Only reject if this was the last attempt and nothing succeeded
74
67
  first_result.reject(error) if attempt == @max_attempts - 1 && !first_result.resolved?
75
68
  end
76
-
77
- futures << future
78
69
  end
79
70
 
80
- # Wait with optional timeout
81
- if @timeout
82
- # Use any_resolved_future with timeout
83
- timeout_future = Concurrent::Promises.schedule(@timeout) do
84
- raise TimeoutError, "Hedged request timed out after #{@timeout}s"
85
- end
71
+ return first_result.value! unless @timeout
86
72
 
87
- Concurrent::Promises.any_resolved_future(first_result, timeout_future).value!
88
- else
89
- first_result.value!
73
+ timeout_future = Concurrent::Promises.schedule(seconds(@timeout)) do
74
+ raise Timeout::Error, "Hedged request timed out after #{@timeout} ns"
90
75
  end
76
+ Concurrent::Promises.any_resolved_future(first_result, timeout_future).value!
91
77
  end
92
78
 
93
- # Run async version
94
- def run_async(&block)
95
- Concurrent::Promises.future { run(&block) }
79
+ def run_async(&)
80
+ Concurrent::Promises.future { run(&) }
96
81
  end
97
82
 
98
- # Shutdown the executor
99
83
  def shutdown
100
84
  @executor.shutdown
101
85
  @executor.wait_for_termination(5)
102
86
  end
103
- end
104
87
 
105
- # Convenience method
106
- def self.hedged_request(**, &)
107
- hedged = HedgedRequest.new(**)
108
- begin
109
- hedged.run(&)
110
- ensure
111
- hedged.shutdown
88
+ private
89
+
90
+ def span(value, name)
91
+ raise TypeError, "#{name} must be an Integer, got #{value.inspect}" unless value.is_a?(Integer)
92
+ raise RangeError, "#{name} must not be negative, got #{value}" if value.negative?
93
+
94
+ value
95
+ end
96
+
97
+ def seconds(nanoseconds)
98
+ Rational(nanoseconds, NS_PER_SECOND)
112
99
  end
113
100
  end
114
101
  end