throttle_machines 0.4.3-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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +231 -0
- data/README.md +89 -14
- data/ext/throttle_machines_native/core/CHANGELOG.md +77 -0
- data/ext/throttle_machines_native/core/README.md +100 -0
- data/ext/throttle_machines_native/extconf.rb +2 -0
- data/ext/throttle_machines_native/ffi/CHANGELOG.md +59 -0
- data/lib/throttle_machines/async_breaker.rb +5 -0
- data/lib/throttle_machines/async_support.rb +16 -21
- data/lib/throttle_machines/breakers.rb +46 -0
- data/lib/throttle_machines/control.rb +25 -46
- data/lib/throttle_machines/controller_helpers.rb +11 -10
- data/lib/throttle_machines/hedged_breaker.rb +4 -6
- data/lib/throttle_machines/hedged_request.rb +29 -42
- data/lib/throttle_machines/instrumentation.rb +10 -75
- data/lib/throttle_machines/limiter.rb +71 -136
- data/lib/throttle_machines/middleware.rb +6 -6
- data/lib/throttle_machines/rack_middleware/allow2_ban.rb +1 -8
- data/lib/throttle_machines/rack_middleware/ban_filter.rb +3 -2
- data/lib/throttle_machines/rack_middleware/configuration.rb +4 -2
- data/lib/throttle_machines/rack_middleware/fail2_ban.rb +5 -21
- data/lib/throttle_machines/rack_middleware/throttle.rb +2 -1
- data/lib/throttle_machines/rack_middleware.rb +3 -1
- data/lib/throttle_machines/storage/base.rb +49 -48
- data/lib/throttle_machines/storage/cache.rb +12 -6
- data/lib/throttle_machines/storage/memory.rb +68 -96
- data/lib/throttle_machines/storage/null.rb +18 -28
- data/lib/throttle_machines/storage/redis/gcra.lua +21 -20
- data/lib/throttle_machines/storage/redis/increment_counter.lua +4 -4
- data/lib/throttle_machines/storage/redis/peek_gcra.lua +16 -16
- data/lib/throttle_machines/storage/redis/peek_token_bucket.lua +22 -18
- data/lib/throttle_machines/storage/redis/token_bucket.lua +31 -19
- data/lib/throttle_machines/storage/redis.rb +63 -69
- data/lib/throttle_machines/throttled_error.rb +4 -1
- data/lib/throttle_machines/version.rb +1 -1
- data/lib/throttle_machines.rb +130 -87
- data/lib/throttle_machines_native/throttle_machines_native.so +0 -0
- data/sig/throttle_machines.rbs +555 -0
- metadata +19 -57
- data/lib/throttle_machines/async_limiter.rb +0 -24
- data/lib/throttle_machines/dependency_error.rb +0 -6
- data/lib/throttle_machines/native_speedup.rb +0 -110
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## [0.5.0](https://github.com/seuros/throttle_machines/compare/throttle_machines_native-v0.4.2...throttle_machines_native-v0.5.0) (2026-11-16)
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
### ⚠ BREAKING CHANGES
|
|
7
|
+
|
|
8
|
+
* rebuild throttle on the fleet conventions with exact gate counts
|
|
9
|
+
|
|
10
|
+
### Features
|
|
11
|
+
|
|
12
|
+
* rebuild throttle on the fleet conventions with exact gate counts ([94d19f3](https://github.com/seuros/throttle_machines/commit/94d19f3abbcbe8c8b05563561e9a68d06ca8d079))
|
|
13
|
+
|
|
14
|
+
## [0.4.2](https://github.com/seuros/throttle_machines/compare/throttle_machines_native-v0.4.1...throttle_machines_native-v0.4.2) (2026-11-02)
|
|
15
|
+
|
|
16
|
+
## [0.4.1](https://github.com/seuros/throttle_machines/compare/throttle_machines_native-v0.4.0...throttle_machines_native-v0.4.1) (2026-11-01)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
### Bug Fixes
|
|
20
|
+
|
|
21
|
+
* enable the rb-sys compiled fallback so new Rubies can build ([9f1f1b6](https://github.com/seuros/throttle_machines/commit/9f1f1b6289d697ff2f3894820e7826a9ddbd1244))
|
|
22
|
+
|
|
23
|
+
## [0.4.0](https://github.com/seuros/throttle_machines/compare/throttle_machines_native-v0.3.2...throttle_machines_native-v0.4.0) (2026-11-01)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
### Features
|
|
27
|
+
|
|
28
|
+
* bound the throttle wait by the caller's deadline ([37a7784](https://github.com/seuros/throttle_machines/commit/37a7784ca6b5eed976d5b61ca4b6d0a51502a407))
|
|
29
|
+
|
|
30
|
+
## [0.3.2](https://github.com/seuros/throttle_machines/compare/throttle_machines_native-v0.3.1...throttle_machines_native-v0.3.2) (2026-10-20)
|
|
31
|
+
|
|
32
|
+
## [0.3.1](https://github.com/seuros/throttle_machines/compare/throttle_machines_native-v0.3.0...throttle_machines_native-v0.3.1) (2026-10-10)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
### Performance Improvements
|
|
36
|
+
|
|
37
|
+
* **ffi:** build Decision/Outcome without a kwargs hash; adopt clippy pedantic and nursery ([23c263d](https://github.com/seuros/throttle_machines/commit/23c263da35829a9375397abaae807659ca96a1ac))
|
|
38
|
+
|
|
39
|
+
## [0.3.0](https://github.com/seuros/throttle_machines/compare/throttle_machines_native-v0.2.0...throttle_machines_native-v0.3.0) (2026-10-06)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
### Features
|
|
43
|
+
|
|
44
|
+
* require Ruby 4.0, magnus 0.9, Ractor-safe ext with Data results ([448ecd6](https://github.com/seuros/throttle_machines/commit/448ecd6674c5be744cc92b44d368a46552d48161))
|
|
45
|
+
|
|
46
|
+
## [0.2.0](https://github.com/seuros/throttle_machines/compare/throttle_machines_native-v0.1.0...throttle_machines_native-v0.2.0) (2026-06-24)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
### Features
|
|
50
|
+
|
|
51
|
+
* add matryoshka pattern with Rust native extension ([97d41a6](https://github.com/seuros/throttle_machines/commit/97d41a6ddf71e042f437c44315c40e3d30c9efe1))
|
|
52
|
+
* add matryoshka pattern with Rust native extension ([3f614cb](https://github.com/seuros/throttle_machines/commit/3f614cbefe8b489f6627b35b635ed954e9e84d4d))
|
|
53
|
+
* add native circuit breaker on shared Gate contract ([dee0b57](https://github.com/seuros/throttle_machines/commit/dee0b57b20c7c887c2e7f7e7d7d2e6a5696be118))
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
### Bug Fixes
|
|
57
|
+
|
|
58
|
+
* ship pure ruby fallback gem ([3a54ac3](https://github.com/seuros/throttle_machines/commit/3a54ac3dffb073ece85a10c4c35ed3c426d658f6))
|
|
59
|
+
* upgrade magnus to 0.8.2 and refresh lock file ([01c6924](https://github.com/seuros/throttle_machines/commit/01c692477c05bd927501b595a4cfb162de968087))
|
|
@@ -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
|
-
#
|
|
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
|
|
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
|
-
|
|
34
|
-
raise if budget.clamp_sleep(
|
|
35
|
+
wait = e.retry_after
|
|
36
|
+
raise if budget.clamp_sleep(wait) < wait
|
|
35
37
|
|
|
36
|
-
sleep_for(
|
|
38
|
+
sleep_for(wait)
|
|
37
39
|
next
|
|
38
40
|
end
|
|
39
41
|
|
|
40
|
-
return block.call
|
|
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(
|
|
50
|
+
def sleep_for(nanoseconds)
|
|
51
|
+
seconds = Rational(nanoseconds, NS_PER_SECOND)
|
|
51
52
|
if (task = current_async_task)
|
|
52
|
-
task.sleep(
|
|
53
|
+
task.sleep(seconds)
|
|
53
54
|
else
|
|
54
|
-
sleep(
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
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
|
-
|
|
41
|
-
execution_chain = block
|
|
42
|
-
|
|
43
|
-
# Wrap with rate limiter (innermost, checked first)
|
|
36
|
+
chain = block
|
|
44
37
|
if @limiter
|
|
45
|
-
|
|
46
|
-
|
|
38
|
+
limited = chain
|
|
39
|
+
chain = proc { @limiter.throttle!(&limited) }
|
|
47
40
|
end
|
|
48
|
-
|
|
49
|
-
# Wrap with circuit breaker
|
|
50
41
|
if @breaker
|
|
51
|
-
|
|
52
|
-
|
|
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
|
-
|
|
58
|
-
|
|
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
|
-
|
|
69
|
-
|
|
70
|
-
|
|
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
|
-
|
|
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
|
-
|
|
86
|
-
|
|
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 #{
|
|
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 +
|
|
76
|
-
response.headers['Retry-After'] =
|
|
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:
|
|
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
|
|
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:
|
|
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:
|
|
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
|
|
43
|
-
raise ArgumentError, 'Block required' unless
|
|
43
|
+
def run
|
|
44
|
+
raise ArgumentError, 'Block required' unless block_given?
|
|
44
45
|
|
|
45
|
-
|
|
46
|
-
request_id = "#{object_id}-#{
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
88
|
-
|
|
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
|
-
|
|
94
|
-
|
|
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
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
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
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
3
|
module ThrottleMachines
|
|
4
|
-
#
|
|
4
|
+
# Events emitted through ActiveSupport::Notifications (or any backend
|
|
5
|
+
# answering `instrument`). Periods, waits and durations in payloads are
|
|
6
|
+
# Integer nanoseconds.
|
|
5
7
|
module Instrumentation
|
|
6
8
|
class << self
|
|
7
9
|
attr_writer :enabled, :backend
|
|
@@ -15,8 +17,14 @@ module ThrottleMachines
|
|
|
15
17
|
@backend ||= ActiveSupport::Notifications
|
|
16
18
|
end
|
|
17
19
|
|
|
20
|
+
# Whether events are published: callers whose payload costs a storage
|
|
21
|
+
# read ask first, so a silenced gem pays nothing for it.
|
|
22
|
+
def active?
|
|
23
|
+
enabled && !backend.nil?
|
|
24
|
+
end
|
|
25
|
+
|
|
18
26
|
def instrument(event_name, payload = {}, &block)
|
|
19
|
-
|
|
27
|
+
unless active?
|
|
20
28
|
return yield if block_given?
|
|
21
29
|
|
|
22
30
|
return
|
|
@@ -63,72 +71,6 @@ module ThrottleMachines
|
|
|
63
71
|
instrument('rate_limit.throttled', payload)
|
|
64
72
|
end
|
|
65
73
|
|
|
66
|
-
# Circuit breaker events
|
|
67
|
-
def circuit_opened(breaker, failure_count:)
|
|
68
|
-
payload = {
|
|
69
|
-
key: (breaker.respond_to?(:name) ? breaker.name : breaker.to_s),
|
|
70
|
-
failure_threshold: (breaker.respond_to?(:configuration) ? breaker.configuration[:failure_threshold] : nil),
|
|
71
|
-
timeout: (breaker.respond_to?(:configuration) ? breaker.configuration[:reset_timeout] : nil),
|
|
72
|
-
failure_count: failure_count
|
|
73
|
-
}
|
|
74
|
-
instrument('circuit_breaker.opened', payload)
|
|
75
|
-
end
|
|
76
|
-
|
|
77
|
-
def circuit_closed(breaker)
|
|
78
|
-
payload = {
|
|
79
|
-
key: (breaker.respond_to?(:name) ? breaker.name : breaker.to_s),
|
|
80
|
-
failure_threshold: (breaker.respond_to?(:configuration) ? breaker.configuration[:failure_threshold] : nil),
|
|
81
|
-
timeout: (breaker.respond_to?(:configuration) ? breaker.configuration[:reset_timeout] : nil)
|
|
82
|
-
}
|
|
83
|
-
instrument('circuit_breaker.closed', payload)
|
|
84
|
-
end
|
|
85
|
-
|
|
86
|
-
def circuit_half_opened(breaker)
|
|
87
|
-
payload = {
|
|
88
|
-
key: (breaker.respond_to?(:name) ? breaker.name : breaker.to_s),
|
|
89
|
-
failure_threshold: (breaker.respond_to?(:configuration) ? breaker.configuration[:failure_threshold] : nil),
|
|
90
|
-
timeout: (breaker.respond_to?(:configuration) ? breaker.configuration[:reset_timeout] : nil),
|
|
91
|
-
half_open_requests: (breaker.respond_to?(:configuration) ? breaker.configuration[:half_open_calls] : nil)
|
|
92
|
-
}
|
|
93
|
-
instrument('circuit_breaker.half_opened', payload)
|
|
94
|
-
end
|
|
95
|
-
|
|
96
|
-
def circuit_success(breaker)
|
|
97
|
-
payload = {
|
|
98
|
-
key: (breaker.respond_to?(:name) ? breaker.name : breaker.to_s),
|
|
99
|
-
state: (breaker.respond_to?(:to_h) ? breaker.to_h[:state] : nil)
|
|
100
|
-
}
|
|
101
|
-
instrument('circuit_breaker.success', payload)
|
|
102
|
-
end
|
|
103
|
-
|
|
104
|
-
def circuit_failure(breaker, error: nil)
|
|
105
|
-
payload = {
|
|
106
|
-
key: (breaker.respond_to?(:name) ? breaker.name : breaker.to_s),
|
|
107
|
-
state: (breaker.respond_to?(:to_h) ? breaker.to_h[:state] : nil),
|
|
108
|
-
error_class: error&.class&.name,
|
|
109
|
-
error_message: error&.message
|
|
110
|
-
}
|
|
111
|
-
instrument('circuit_breaker.failure', payload)
|
|
112
|
-
end
|
|
113
|
-
|
|
114
|
-
def circuit_rejected(breaker)
|
|
115
|
-
payload = {
|
|
116
|
-
key: (breaker.respond_to?(:name) ? breaker.name : breaker.to_s),
|
|
117
|
-
failure_threshold: (breaker.respond_to?(:configuration) ? breaker.configuration[:failure_threshold] : nil),
|
|
118
|
-
timeout: (breaker.respond_to?(:configuration) ? breaker.configuration[:reset_timeout] : nil)
|
|
119
|
-
}
|
|
120
|
-
instrument('circuit_breaker.rejected', payload)
|
|
121
|
-
end
|
|
122
|
-
|
|
123
|
-
# Cascade events
|
|
124
|
-
def cascade_triggered(primary_key, cascaded_key)
|
|
125
|
-
payload = {
|
|
126
|
-
primary_key: primary_key,
|
|
127
|
-
cascaded_key: cascaded_key
|
|
128
|
-
}
|
|
129
|
-
instrument('cascade.triggered', payload)
|
|
130
|
-
end
|
|
131
|
-
|
|
132
74
|
# Hedged request events
|
|
133
75
|
def hedged_request_started(request_id, attempts:)
|
|
134
76
|
payload = {
|
|
@@ -147,12 +89,5 @@ module ThrottleMachines
|
|
|
147
89
|
instrument('hedged_request.winner', payload)
|
|
148
90
|
end
|
|
149
91
|
end
|
|
150
|
-
|
|
151
|
-
# Null backend for when ActiveSupport::Notifications is not available
|
|
152
|
-
class NullBackend
|
|
153
|
-
def instrument(_name, _payload = {})
|
|
154
|
-
yield if block_given?
|
|
155
|
-
end
|
|
156
|
-
end
|
|
157
92
|
end
|
|
158
93
|
end
|