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
@@ -1,188 +1,123 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module ThrottleMachines
4
+ # `limit` calls per `period` (Integer nanoseconds) for one key, decided by
5
+ # `algorithm` over shared storage. A runtime object: its keywords have no
6
+ # core counterpart. Every answer in time is Integer nanoseconds.
4
7
  class Limiter
5
- attr_reader :key, :limit, :period, :algorithm, :storage
8
+ ALGORITHMS = %i[fixed_window gcra token_bucket].freeze
9
+
10
+ attr_reader :key, :limit, :period, :algorithm, :storage, :policy
6
11
 
7
12
  def initialize(key, limit:, period:, algorithm: :fixed_window, storage: nil)
8
13
  @key = key
9
- @limit = limit
10
- @period = period
14
+ @limit = positive(limit, 'limit')
15
+ @period = positive(period, 'period')
11
16
  @algorithm = algorithm
12
17
  @storage = storage || ThrottleMachines.storage
13
18
  validate_algorithm!
14
- validate_rate!
19
+ @policy = build_policy
20
+ freeze
15
21
  end
16
22
 
23
+ # Whether a call would be admitted now, consuming nothing.
17
24
  def allow?
18
- allowed = case @algorithm
19
- when :fixed_window
20
- # Don't increment here, just check
21
- count = @storage.get_counter(@key, @period)
22
- count < @limit
23
- when :gcra
24
- result = @storage.peek_gcra_limit(
25
- @key,
26
- @period.to_f / @limit, # emission_interval
27
- 0 # delay_tolerance (no burst)
28
- )
29
- result[:allowed]
30
- when :token_bucket
31
- result = @storage.peek_token_bucket(
32
- @key,
33
- @limit, # capacity
34
- @limit.to_f / @period # refill_rate
35
- )
36
- result[:allowed]
37
- else
38
- raise ArgumentError, "Unknown algorithm: #{@algorithm}"
39
- end
40
-
41
- # Instrument the check
25
+ allowed = peek.is_a?(Integer)
42
26
  Instrumentation.rate_limit_checked(self, allowed: allowed, remaining: nil)
43
-
44
27
  allowed
45
28
  end
46
29
 
30
+ # Admits one call or raises ThrottledError, then runs the block. An
31
+ # admission reports the count the check itself answered, which equals
32
+ # `remaining` at that instant (test/throttle_machines/remaining_parity_test.rb)
33
+ # and cannot race another caller; a refusal's `retry_after` costs a
34
+ # storage read, made only while instrumentation is active.
47
35
  def throttle!
48
- case @algorithm
49
- when :fixed_window
50
- # Increment and check atomically
51
- count = @storage.increment_counter(@key, @period)
52
- if count > @limit
53
- Instrumentation.rate_limit_throttled(self, retry_after: retry_after)
54
- raise ThrottledError, self
55
- end
56
- when :gcra
57
- result = @storage.check_gcra_limit(
58
- @key,
59
- @period.to_f / @limit, # emission_interval
60
- 0, # delay_tolerance (no burst)
61
- (@period * 2).to_i # ttl
62
- )
63
- unless result[:allowed]
64
- Instrumentation.rate_limit_throttled(self, retry_after: retry_after)
65
- raise ThrottledError, self
66
- end
67
- when :token_bucket
68
- result = @storage.check_token_bucket(
69
- @key,
70
- @limit, # capacity
71
- @limit.to_f / @period, # refill_rate
72
- (@period * 2).to_i # ttl
73
- )
74
- unless result[:allowed]
75
- Instrumentation.rate_limit_throttled(self, retry_after: retry_after)
76
- raise ThrottledError, self
77
- end
78
- else
79
- raise ArgumentError, "Unknown algorithm: #{@algorithm}"
80
- end
81
-
82
- # If we get here, the request was allowed
83
- # Calculate remaining after the operation
84
- remaining_count = begin
85
- remaining
86
- rescue StandardError
87
- nil
36
+ left = check
37
+ unless left.is_a?(Integer)
38
+ Instrumentation.rate_limit_throttled(self, retry_after: retry_after) if Instrumentation.active?
39
+ raise ThrottledError, self
88
40
  end
89
- Instrumentation.rate_limit_allowed(self, remaining: remaining_count)
90
41
 
42
+ Instrumentation.rate_limit_allowed(self, remaining: left) if Instrumentation.active?
91
43
  yield if block_given?
92
44
  end
93
45
 
94
46
  def reset!
95
47
  case @algorithm
96
- when :fixed_window
97
- @storage.reset_counter(@key, @period)
98
- when :gcra
99
- @storage.reset_gcra(@key)
100
- when :token_bucket
101
- @storage.reset_token_bucket(@key)
48
+ when :fixed_window then @storage.reset_counter(@key, @period)
49
+ when :gcra then @storage.reset_gcra(@key)
50
+ when :token_bucket then @storage.reset_token_bucket(@key)
102
51
  end
103
52
  end
104
53
 
54
+ # Calls still admitted now: the window's or bucket's count; for GCRA, the
55
+ # calls its burst admits back to back (one without a burst).
105
56
  def remaining
57
+ answer = peek
58
+ answer.is_a?(Integer) ? answer : 0
59
+ end
60
+
61
+ # Integer nanoseconds until a call is admitted; zero when one is now.
62
+ def retry_after
106
63
  case @algorithm
107
64
  when :fixed_window
108
- count = @storage.get_counter(@key, @period)
109
- [@limit - count, 0].max
110
- when :gcra
111
- # GCRA doesn't have a simple "remaining" count
112
- # Just return 1 or 0 based on current state
113
- result = @storage.peek_gcra_limit(
114
- @key,
115
- @period.to_f / @limit,
116
- 0
117
- )
118
- result[:allowed] ? 1 : 0
119
- when :token_bucket
120
- result = @storage.peek_token_bucket(
121
- @key,
122
- @limit,
123
- @limit.to_f / @period
124
- )
125
- result[:tokens_remaining].to_i
126
- else
127
- 0
65
+ @storage.get_counter(@key, @period) >= @limit ? @storage.get_counter_ttl(@key, @period) : 0
66
+ when :gcra then @storage.gcra_retry_after(@key, @policy)
67
+ when :token_bucket then @storage.token_bucket_retry_after(@key, @policy)
128
68
  end
129
69
  end
130
70
 
131
- def retry_after
71
+ def to_h
72
+ { key: @key, limit: @limit, period: @period, algorithm: @algorithm, remaining: remaining,
73
+ retry_after: retry_after }
74
+ end
75
+
76
+ private
77
+
78
+ # Integer calls left after this admission, or a refusal Symbol.
79
+ def check
80
+ case @algorithm
81
+ when :fixed_window
82
+ count = @storage.increment_counter(@key, @period)
83
+ count <= @limit ? @limit - count : :throttled
84
+ when :gcra then @storage.check_gcra(@key, @policy, @period * 2)
85
+ when :token_bucket then @storage.check_token_bucket(@key, @policy, @period * 2)
86
+ end
87
+ end
88
+
89
+ # Integer calls admitted now, at least one, or a refusal Symbol.
90
+ def peek
132
91
  case @algorithm
133
92
  when :fixed_window
134
93
  count = @storage.get_counter(@key, @period)
135
- if count >= @limit
136
- # Return the actual time remaining in the current window
137
- @storage.get_counter_ttl(@key, @period)
138
- else
139
- 0
140
- end
141
- when :gcra
142
- result = @storage.peek_gcra_limit(
143
- @key,
144
- @period.to_f / @limit,
145
- 0
146
- )
147
- result[:retry_after]
148
- when :token_bucket
149
- result = @storage.peek_token_bucket(
150
- @key,
151
- @limit,
152
- @limit.to_f / @period
153
- )
154
- result[:retry_after]
155
- else
156
- 0
94
+ count < @limit ? @limit - count : :throttled
95
+ when :gcra then @storage.peek_gcra(@key, @policy)
96
+ when :token_bucket then @storage.peek_token_bucket(@key, @policy)
157
97
  end
158
98
  end
159
99
 
160
- def to_h
161
- {
162
- key: @key,
163
- limit: @limit,
164
- period: @period,
165
- algorithm: @algorithm,
166
- remaining: remaining,
167
- retry_after: retry_after
168
- }
100
+ def build_policy
101
+ case @algorithm
102
+ when :fixed_window then FixedWindowPolicy.new(@period, @limit)
103
+ when :gcra then GcraPolicy.per(@period, @limit, 1)
104
+ when :token_bucket then TokenBucketPolicy.per(@period, @limit)
105
+ end
169
106
  end
170
107
 
171
- private
108
+ def positive(value, name)
109
+ raise TypeError, "#{name} must be an Integer, got #{value.inspect}" unless value.is_a?(Integer)
110
+ raise RangeError, "#{name} must be positive, got #{value}" unless value.positive?
172
111
 
173
- def validate_rate!
174
- raise ArgumentError, "limit must be positive, got #{@limit.inspect}" unless @limit.is_a?(Numeric) && @limit.positive?
175
- raise ArgumentError, "period must be positive, got #{@period.inspect}" unless @period.is_a?(Numeric) && @period.positive?
112
+ value
176
113
  end
177
114
 
178
115
  def validate_algorithm!
179
- unless Storage::Base::ALGORITHM_OPERATIONS.key?(@algorithm)
180
- raise ArgumentError, "Unknown algorithm: #{@algorithm.inspect}"
181
- end
116
+ raise RangeError, "Unknown algorithm: #{@algorithm.inspect}" unless ALGORITHMS.include?(@algorithm)
182
117
  return unless @storage.respond_to?(:supports?)
183
118
  return if @storage.supports?(@algorithm)
184
119
 
185
- raise ArgumentError, "#{@storage.class} does not support the #{@algorithm.inspect} algorithm"
120
+ raise RangeError, "#{@storage.class} does not support the #{@algorithm.inspect} algorithm"
186
121
  end
187
122
  end
188
123
  end
@@ -1,6 +1,8 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module ThrottleMachines
4
+ # Rack middleware applying limiters per path. `period:` is Integer
5
+ # nanoseconds; responses report waits in whole seconds, rounded up.
4
6
  class Middleware
5
7
  def initialize(app, &config_block)
6
8
  @app = app
@@ -70,18 +72,16 @@ module ThrottleMachines
70
72
  end
71
73
 
72
74
  def rate_limit_response(limiter)
75
+ wait = limiter.retry_after.ceildiv(NS_PER_SECOND)
73
76
  headers = {
74
77
  'Content-Type' => 'application/json',
75
78
  'X-RateLimit-Limit' => limiter.limit.to_s,
76
79
  'X-RateLimit-Remaining' => limiter.remaining.to_s,
77
- 'X-RateLimit-Reset' => (Time.now.to_i + limiter.retry_after).to_s,
78
- 'Retry-After' => limiter.retry_after.ceil.to_s
80
+ 'X-RateLimit-Reset' => (Time.now.to_i + wait).to_s,
81
+ 'Retry-After' => wait.to_s
79
82
  }
80
83
 
81
- body = JSON.generate({
82
- error: 'Rate limit exceeded',
83
- retry_after: limiter.retry_after
84
- })
84
+ body = JSON.generate({ error: 'Rate limit exceeded', retry_after: wait })
85
85
 
86
86
  [429, headers, [body]]
87
87
  end
@@ -24,14 +24,7 @@ module ThrottleMachines
24
24
  # Check if we've had enough successful requests
25
25
  if success_limiter.remaining.zero?
26
26
  # Reset the fail2ban breaker (use BreakerMachines circuit)
27
- breaker = BreakerMachines::Registry.instance.get_or_create_dynamic_circuit(
28
- fail_key,
29
- self,
30
- failure_threshold: @maxretry,
31
- failure_window: @findtime,
32
- reset_timeout: @bantime
33
- )
34
- breaker.hard_reset
27
+ Breakers.dynamic(fail_key, self, @maxretry, @findtime, @bantime).reset
35
28
 
36
29
  # Reset our own counter
37
30
  ThrottleMachines.storage.reset_counter(success_key, @findtime)
@@ -14,9 +14,10 @@ module ThrottleMachines
14
14
  @name = name
15
15
  @block = block
16
16
 
17
+ # `findtime` and `bantime` are Integer nanoseconds.
17
18
  @maxretry = options[:maxretry] || 5
18
- @findtime = options[:findtime] || 60
19
- @bantime = options[:bantime] || 300
19
+ @findtime = options[:findtime] || (60 * NS_PER_SECOND)
20
+ @bantime = options[:bantime] || (300 * NS_PER_SECOND)
20
21
  end
21
22
 
22
23
  private
@@ -7,14 +7,16 @@ module ThrottleMachines
7
7
  class Configuration
8
8
  DEFAULT_BLOCKLISTED_RESPONDER = ->(_req) { [403, { 'content-type' => 'text/plain' }, ["Forbidden\n"]] }
9
9
 
10
+ # `retry_after` in the match data is Integer nanoseconds; the header is
11
+ # whole seconds, rounded up.
10
12
  DEFAULT_THROTTLED_RESPONDER = lambda do |req|
11
13
  match_data = req.env['rack.attack.match_data']
12
- retry_after = match_data[:retry_after] || 60
14
+ retry_after = (match_data[:retry_after] || (60 * NS_PER_SECOND)).ceildiv(NS_PER_SECOND)
13
15
 
14
16
  [429, { 'content-type' => 'text/plain', 'retry-after' => retry_after.to_s }, ["Retry later\n"]]
15
17
  end
16
18
 
17
- attr_reader :throttles, :tracks, :safelists, :blocklists
19
+ attr_reader :throttles, :tracks, :safelists, :blocklists, :fail2bans, :allow2bans
18
20
  attr_accessor :throttled_responder, :blocklisted_responder
19
21
 
20
22
  def initialize
@@ -10,24 +10,14 @@ module ThrottleMachines
10
10
  key = "fail2ban:#{@name}:#{discriminator}"
11
11
 
12
12
  # Use a globally managed BreakerMachines circuit as the ban mechanism
13
- breaker = BreakerMachines::Registry.instance.get_or_create_dynamic_circuit(
14
- key,
15
- self,
16
- failure_threshold: @maxretry,
17
- failure_window: @findtime,
18
- reset_timeout: @bantime
19
- )
13
+ breaker = Breakers.dynamic(key, self, @maxretry, @findtime, @bantime)
20
14
 
21
15
  # Check if circuit is open (banned)
22
16
  if breaker.open?
23
17
  stats = breaker.stats
24
- now = BreakerMachines.monotonic_time
25
- time_until_unban = if stats.opened_at
26
- remaining = @bantime - (now - stats.opened_at)
27
- remaining.positive? ? remaining : 0
28
- else
29
- @bantime
30
- end
18
+ # Integer nanoseconds, like findtime and bantime.
19
+ banned_for = Breakers.since(breaker)
20
+ time_until_unban = banned_for ? [@bantime - banned_for, 0].max : @bantime
31
21
 
32
22
  request.env['rack.attack.matched'] = @name
33
23
  request.env['rack.attack.match_type'] = :fail2ban
@@ -57,13 +47,7 @@ module ThrottleMachines
57
47
  # Use the breaker to record a failure if block returns true
58
48
  return unless yield
59
49
 
60
- breaker = BreakerMachines::Registry.instance.get_or_create_dynamic_circuit(
61
- key,
62
- self,
63
- failure_threshold: @maxretry,
64
- failure_window: @findtime,
65
- reset_timeout: @bantime
66
- )
50
+ breaker = Breakers.dynamic(key, self, @maxretry, @findtime, @bantime)
67
51
 
68
52
  # Record failure by trying to call through the breaker
69
53
  # and letting it fail
@@ -13,7 +13,8 @@ module ThrottleMachines
13
13
  raise ArgumentError, 'Must pass :period option' unless options[:period]
14
14
 
15
15
  @limit = options[:limit]
16
- @period = options[:period].to_i
16
+ # Integer nanoseconds, or a callable answering them per request.
17
+ @period = options[:period]
17
18
  @algorithm = options[:algorithm] || :fixed_window
18
19
  end
19
20
 
@@ -28,7 +28,9 @@ module ThrottleMachines
28
28
  :throttles,
29
29
  :tracks,
30
30
  :safelists,
31
- :blocklists
31
+ :blocklists,
32
+ :fail2bans,
33
+ :allow2bans
32
34
 
33
35
  def configure(&block)
34
36
  @configuration ||= Configuration.new
@@ -2,15 +2,23 @@
2
2
 
3
3
  module ThrottleMachines
4
4
  module Storage
5
+ # Where limiters keep their state. Every instant and span is Integer
6
+ # nanoseconds. A GCRA or token bucket check answers the calls still
7
+ # admitted (an Integer) or a refusal Symbol, the core gate's own answer:
8
+ # :throttled, :overflow when a GCRA admission would push its TAT past the
9
+ # largest instant, or :full when the store cannot track another key.
5
10
  class Base
6
11
  ALGORITHM_OPERATIONS = {
7
12
  fixed_window: %i[increment_counter get_counter get_counter_ttl reset_counter],
8
- gcra: %i[check_gcra_limit peek_gcra_limit reset_gcra],
9
- token_bucket: %i[check_token_bucket peek_token_bucket reset_token_bucket]
13
+ gcra: %i[check_gcra peek_gcra gcra_retry_after reset_gcra],
14
+ token_bucket: %i[check_token_bucket peek_token_bucket token_bucket_retry_after reset_token_bucket]
10
15
  }.freeze
11
16
 
12
17
  HEALTH_KEY = 'throttle_machines:health'
13
18
 
19
+ # The count a counter the store cannot track answers: past any limit.
20
+ UNTRACKED = 2**64
21
+
14
22
  # What a backend puts between a limiter's key and the state it appends.
15
23
  KEY_SEPARATOR = ':'
16
24
 
@@ -28,75 +36,83 @@ module ThrottleMachines
28
36
  operations.all? { |operation| self.class.instance_method(operation).owner != Base }
29
37
  end
30
38
 
31
- # Rate limiting operations
39
+ # Counts `amount` more calls in the `window` the key is in; answers the
40
+ # window's count.
32
41
  def increment_counter(key, window, amount = 1)
33
- raise NotImplementedError, "#{self.class} does not implement #increment_counter"
42
+ unsupported(:increment_counter)
34
43
  end
35
44
 
36
45
  def get_counter(key, window)
37
- raise NotImplementedError, "#{self.class} does not implement #get_counter"
46
+ unsupported(:get_counter)
38
47
  end
39
48
 
49
+ # Integer nanoseconds until the key's window ends.
40
50
  def get_counter_ttl(key, window)
41
- raise NotImplementedError, "#{self.class} does not implement #get_counter_ttl"
51
+ unsupported(:get_counter_ttl)
42
52
  end
43
53
 
44
54
  def reset_counter(key, window)
45
- raise NotImplementedError, "#{self.class} does not implement #reset_counter"
55
+ unsupported(:reset_counter)
56
+ end
57
+
58
+ # Admits one call under a ThrottleMachines::GcraPolicy, keeping the
59
+ # state `ttl` past now.
60
+ def check_gcra(key, policy, ttl)
61
+ unsupported(:check_gcra)
46
62
  end
47
63
 
48
- # GCRA operations (atomic)
49
- def check_gcra_limit(key, emission_interval, delay_tolerance, ttl)
50
- raise NotImplementedError, "#{self.class} does not implement #check_gcra_limit"
64
+ def peek_gcra(key, policy)
65
+ unsupported(:peek_gcra)
51
66
  end
52
67
 
53
- def peek_gcra_limit(key, emission_interval, delay_tolerance)
54
- raise NotImplementedError, "#{self.class} does not implement #peek_gcra_limit"
68
+ def gcra_retry_after(key, policy)
69
+ unsupported(:gcra_retry_after)
55
70
  end
56
71
 
57
72
  def reset_gcra(key)
58
- raise NotImplementedError, "#{self.class} does not implement #reset_gcra"
73
+ unsupported(:reset_gcra)
59
74
  end
60
75
 
61
- # Token bucket operations (atomic)
62
- def check_token_bucket(key, capacity, refill_rate, ttl)
63
- raise NotImplementedError, "#{self.class} does not implement #check_token_bucket"
76
+ # Admits one call under a ThrottleMachines::TokenBucketPolicy.
77
+ def check_token_bucket(key, policy, ttl)
78
+ unsupported(:check_token_bucket)
64
79
  end
65
80
 
66
- def peek_token_bucket(key, capacity, refill_rate)
67
- raise NotImplementedError, "#{self.class} does not implement #peek_token_bucket"
81
+ def peek_token_bucket(key, policy)
82
+ unsupported(:peek_token_bucket)
83
+ end
84
+
85
+ def token_bucket_retry_after(key, policy)
86
+ unsupported(:token_bucket_retry_after)
68
87
  end
69
88
 
70
89
  def reset_token_bucket(key)
71
- raise NotImplementedError, "#{self.class} does not implement #reset_token_bucket"
90
+ unsupported(:reset_token_bucket)
72
91
  end
73
92
 
74
- # Utility operations
75
93
  def clear(pattern = nil)
76
- raise NotImplementedError, "#{self.class} does not implement #clear"
94
+ unsupported(:clear)
77
95
  end
78
96
 
79
97
  # Deletes every entry this key owns, whatever algorithm wrote it.
80
98
  def reset_key(key)
81
- raise NotImplementedError, "#{self.class} does not implement #reset_key"
99
+ unsupported(:reset_key)
82
100
  end
83
101
 
84
102
  def healthy?
85
- get_counter(HEALTH_KEY, 1)
103
+ get_counter(HEALTH_KEY, NS_PER_SECOND)
86
104
  true
87
105
  rescue StandardError
88
106
  false
89
107
  end
90
108
 
91
- def with_timeout(timeout, &block)
109
+ # Runs the block for at most `timeout` nanoseconds, less when the
110
+ # ambient deadline_machines budget is shorter.
111
+ def with_timeout(timeout, &)
92
112
  DeadlineMachines.check!
93
- Timeout.timeout(DeadlineMachines.clamp_sleep(timeout), &block)
113
+ Timeout.timeout(Rational(DeadlineMachines.clamp_sleep(timeout), NS_PER_SECOND), &)
94
114
  end
95
115
 
96
- # Rounding slack for time comparisons, in units of the clock's precision.
97
- # Matches the native core.
98
- SLACK_ULPS = 64
99
-
100
116
  protected
101
117
 
102
118
  def owned_by?(stored_key, key)
@@ -111,29 +127,14 @@ module ThrottleMachines
111
127
  Regexp.new("\\A#{Regexp.escape(glob).gsub(Regexp.escape(GLOB_WILDCARD), '.*')}\\z")
112
128
  end
113
129
 
114
- # Times are running sums and differences of float seconds, so an
115
- # on-schedule arrival can miss an exact boundary by a few ulps. The slack
116
- # scales with the clock's magnitude.
117
- def rounding_slack(time)
118
- Float::EPSILON * SLACK_ULPS * [time.abs, 1.0].max
119
- end
120
-
121
- def gcra_allowed?(tat, now, delay_tolerance)
122
- tat - now <= delay_tolerance + rounding_slack(tat)
123
- end
124
-
125
- # Whether a token is available, allowing for rounding in the refill.
126
- def token_available?(tokens, now, refill_rate)
127
- tokens >= 1 - (rounding_slack(now) * refill_rate)
128
- end
129
-
130
130
  def current_time
131
- # Use monotonic time for consistency with BreakerMachines
132
131
  ThrottleMachines.monotonic_time
133
132
  end
134
133
 
135
- def monotonic_time
136
- ThrottleMachines.monotonic_time
134
+ private
135
+
136
+ def unsupported(operation)
137
+ raise NotImplementedError, "#{self.class} does not implement ##{operation}"
137
138
  end
138
139
  end
139
140
  end
@@ -2,6 +2,8 @@
2
2
 
3
3
  module ThrottleMachines
4
4
  module Storage
5
+ # Fixed windows in an ActiveSupport cache, aligned to the wall-clock
6
+ # epoch so every process sharing the cache counts the same window.
5
7
  class Cache < Base
6
8
  # The wildcard a caller's pattern keeps; everything else is a literal.
7
9
  PATTERN_SPECIALS = /[?\[\]\\]/
@@ -16,14 +18,16 @@ module ThrottleMachines
16
18
  end
17
19
 
18
20
  def increment_counter(key, window, amount = 1)
19
- count = @cache.increment(window_key(key, window), amount, expires_in: window.to_f.ceil + 1)
20
- count || (@fail_closed ? Float::INFINITY : 0)
21
+ expires_in = window.ceildiv(NS_PER_SECOND) + 1
22
+ count = @cache.increment(window_key(key, window), amount, expires_in: expires_in)
23
+ count || (@fail_closed ? UNTRACKED : 0)
21
24
  end
22
25
 
23
26
  def get_counter(key, window)
24
27
  @cache.read(window_key(key, window), raw: true).to_i
25
28
  end
26
29
 
30
+ # Integer nanoseconds until the current window ends.
27
31
  def get_counter_ttl(_key, window)
28
32
  window = positive_window(window)
29
33
  window - (wall_time % window)
@@ -53,12 +57,12 @@ module ThrottleMachines
53
57
 
54
58
  def window_key(key, window)
55
59
  window = positive_window(window)
56
- "#{@prefix}:#{key}:#{window}:#{(wall_time / window).floor}"
60
+ "#{@prefix}:#{key}:#{window}:#{wall_time / window}"
57
61
  end
58
62
 
59
63
  def positive_window(window)
60
- window = window.to_f
61
- raise ArgumentError, "window must be positive, got #{window}" unless window.positive?
64
+ raise TypeError, "window must be an Integer, got #{window.inspect}" unless window.is_a?(Integer)
65
+ raise RangeError, "window must be positive, got #{window}" unless window.positive?
62
66
 
63
67
  window
64
68
  end
@@ -83,8 +87,10 @@ module ThrottleMachines
83
87
  Regexp.new("^#{Regexp.escape(literal)}")
84
88
  end
85
89
 
90
+ # Integer nanoseconds since the Unix epoch.
86
91
  def wall_time
87
- Time.now.to_f
92
+ now = Time.now
93
+ (now.to_i * NS_PER_SECOND) + now.nsec
88
94
  end
89
95
  end
90
96
  end