rate_guard 0.1.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.
- checksums.yaml +7 -0
- data/CHANGELOG.md +44 -0
- data/LICENSE +21 -0
- data/README.md +237 -0
- data/lib/rate_guard/admission.rb +13 -0
- data/lib/rate_guard/algorithms/fixed_window_counter.rb +83 -0
- data/lib/rate_guard/algorithms/leaky_bucket_meter.rb +93 -0
- data/lib/rate_guard/algorithms/leaky_bucket_queue.rb +93 -0
- data/lib/rate_guard/algorithms/redis_sliding_window_counter.rb +137 -0
- data/lib/rate_guard/algorithms/sliding_window_counter.lua +60 -0
- data/lib/rate_guard/algorithms/sliding_window_counter.rb +148 -0
- data/lib/rate_guard/algorithms/sliding_window_log.rb +105 -0
- data/lib/rate_guard/algorithms/token_bucket.rb +93 -0
- data/lib/rate_guard/bypass.rb +39 -0
- data/lib/rate_guard/clock.rb +20 -0
- data/lib/rate_guard/configuration.rb +77 -0
- data/lib/rate_guard/errors.rb +9 -0
- data/lib/rate_guard/identifiers/api_key.rb +36 -0
- data/lib/rate_guard/identifiers/first_of.rb +28 -0
- data/lib/rate_guard/identifiers/global.rb +14 -0
- data/lib/rate_guard/identifiers/ip.rb +19 -0
- data/lib/rate_guard/identifiers/user.rb +34 -0
- data/lib/rate_guard/identifiers.rb +17 -0
- data/lib/rate_guard/json_log_formatter.rb +29 -0
- data/lib/rate_guard/metrics.rb +49 -0
- data/lib/rate_guard/middleware/client_ip.rb +40 -0
- data/lib/rate_guard/middleware.rb +147 -0
- data/lib/rate_guard/policy.rb +129 -0
- data/lib/rate_guard/policy_set.rb +59 -0
- data/lib/rate_guard/redis_error_reporter.rb +51 -0
- data/lib/rate_guard/registry.rb +109 -0
- data/lib/rate_guard/request.rb +7 -0
- data/lib/rate_guard/result.rb +17 -0
- data/lib/rate_guard/tiers.rb +25 -0
- data/lib/rate_guard/utils/numeric_utils.rb +22 -0
- data/lib/rate_guard/validators/configuration_validator.rb +28 -0
- data/lib/rate_guard/validators/cost_validator.rb +36 -0
- data/lib/rate_guard/version.rb +5 -0
- data/lib/rate_guard.rb +84 -0
- metadata +105 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: 5f5f40202df683f0723bbe2df02b8e49364b89c83edd41bc8a4a1f745929d187
|
|
4
|
+
data.tar.gz: 3df3ca88950e214e1485b7ef957b64928a0e1b58138a8ab6d956c2fb545ac207
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: d0d3cb2e2231493f4151062165d6d2a744b77abb44446463551c94a610e00293745e3d8b5c48e527f14a8d66e868a02371847bc6ee27f0dae49be7b6d0b8c0d5
|
|
7
|
+
data.tar.gz: a74ec2c6c3002beec549303908cb523e0fe686297d92d48f1d6d0fd17beb6aabc0eb57e4959551b4eb0a85c2c820f8df6e08ed60f043e97cc3111ba044f98081
|
data/CHANGELOG.md
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project are documented here. The format follows
|
|
4
|
+
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow
|
|
5
|
+
[Semantic Versioning](https://semver.org/).
|
|
6
|
+
|
|
7
|
+
## [Unreleased]
|
|
8
|
+
|
|
9
|
+
## [0.1.0] - 2026-11-24
|
|
10
|
+
|
|
11
|
+
First release.
|
|
12
|
+
|
|
13
|
+
### Added
|
|
14
|
+
|
|
15
|
+
- Algorithms behind one interface (`acquire(key, cost:, reserve:)` returning a
|
|
16
|
+
`Result`): token bucket, leaky bucket meter, fixed window, sliding window
|
|
17
|
+
log and sliding window counter; a leaky bucket queue (`enqueue`/`dequeue`)
|
|
18
|
+
for work that should wait instead of failing.
|
|
19
|
+
- A sliding window counter in Redis, atomic through a Lua script, shared by
|
|
20
|
+
every application server, with a fail-open or fail-closed policy and an
|
|
21
|
+
`on_redis_error` hook.
|
|
22
|
+
- `RateGuard.configure`, `RateGuard.limiter` (with per-limiter overrides),
|
|
23
|
+
`RateGuard.queue`, and a registry for adding algorithms by name.
|
|
24
|
+
- `RateGuard::Middleware` for Rack 3: per-route policies (`Policy`,
|
|
25
|
+
`PolicySet`), request cost, priority reserve, plan tiers (`Tiers`) and
|
|
26
|
+
trusted-client bypass (`Bypass`).
|
|
27
|
+
- Identifiers: client IP (`X-Forwarded-For` only behind trusted proxies), API
|
|
28
|
+
key (stored only as a digest, optionally verified), authenticated user,
|
|
29
|
+
first-of and global.
|
|
30
|
+
- `RateLimit-Limit`, `RateLimit-Remaining`, `RateLimit-Reset` and
|
|
31
|
+
`Retry-After` headers; a customizable rejection response.
|
|
32
|
+
- JSON log lines for rejections (`JsonLogFormatter`), a throttled Redis error
|
|
33
|
+
reporter, and a metrics interface (`Metrics::Null`, `Metrics::InMemory`).
|
|
34
|
+
- Benchmarks comparing speed, memory and contention for every algorithm.
|
|
35
|
+
|
|
36
|
+
### Changed
|
|
37
|
+
|
|
38
|
+
- Renamed from `rate_limiter` to `rate_guard`, because `rate_limiter` is an
|
|
39
|
+
existing gem on RubyGems: `require 'rate_guard'` and `RateGuard` replace
|
|
40
|
+
`require 'rate_limiter'` and `RateLimiter`. Rack env keys, metric names and
|
|
41
|
+
the default Redis namespace now start with `rate_guard`.
|
|
42
|
+
|
|
43
|
+
[Unreleased]: https://github.com/Null-logic-0/ruby-rate-limiter/compare/v0.1.0...HEAD
|
|
44
|
+
[0.1.0]: https://github.com/Null-logic-0/ruby-rate-limiter/releases/tag/v0.1.0
|
data/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Luka Tchelidze
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
data/README.md
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
# rate_guard
|
|
2
|
+
|
|
3
|
+
Rate limiting for Ruby and Rack apps.
|
|
4
|
+
|
|
5
|
+
- 6 algorithms: token bucket, leaky bucket (meter and queue), fixed window, sliding window log, sliding window counter
|
|
6
|
+
- Rack middleware with rules per route, client, and plan
|
|
7
|
+
- Standard `RateLimit-*` and `Retry-After` headers
|
|
8
|
+
- Optional Redis, so many servers share one limit
|
|
9
|
+
- Thread-safe
|
|
10
|
+
|
|
11
|
+
Needs Ruby 4.0 or newer.
|
|
12
|
+
|
|
13
|
+
## Install
|
|
14
|
+
|
|
15
|
+
<!-- readme: gemfile -->
|
|
16
|
+
```ruby
|
|
17
|
+
gem 'rate_guard', '~> 0.1'
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Add these too if you need them:
|
|
21
|
+
|
|
22
|
+
<!-- readme: gemfile -->
|
|
23
|
+
```ruby
|
|
24
|
+
gem 'redis', '~> 6.1' # to share limits between servers
|
|
25
|
+
gem 'logger', '~> 1.7' # for JSON logs
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## Plain Ruby
|
|
29
|
+
|
|
30
|
+
```ruby
|
|
31
|
+
require 'rate_guard'
|
|
32
|
+
|
|
33
|
+
RateGuard.configure do |config|
|
|
34
|
+
config.algorithm = :token_bucket
|
|
35
|
+
config.limit = 3 # 3 requests...
|
|
36
|
+
config.window = 60 # ...per 60 seconds
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
limiter = RateGuard.limiter
|
|
40
|
+
|
|
41
|
+
4.times do |n|
|
|
42
|
+
result = limiter.acquire('user:42')
|
|
43
|
+
if result.allowed?
|
|
44
|
+
puts "request #{n + 1}: allowed, #{result.remaining} left"
|
|
45
|
+
else
|
|
46
|
+
puts "request #{n + 1}: rejected, retry in #{result.retry_after.ceil}s"
|
|
47
|
+
end
|
|
48
|
+
end
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
```text
|
|
52
|
+
request 1: allowed, 2 left
|
|
53
|
+
request 2: allowed, 1 left
|
|
54
|
+
request 3: allowed, 0 left
|
|
55
|
+
request 4: rejected, retry in 20s
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Each key (here `'user:42'`) has its own counter.
|
|
59
|
+
|
|
60
|
+
## Rack
|
|
61
|
+
|
|
62
|
+
Limit one path per client IP:
|
|
63
|
+
|
|
64
|
+
<!-- readme: file config.ru -->
|
|
65
|
+
```ruby
|
|
66
|
+
# config.ru
|
|
67
|
+
require 'rate_guard'
|
|
68
|
+
require 'rate_guard/middleware'
|
|
69
|
+
|
|
70
|
+
RateGuard.configure do |config|
|
|
71
|
+
config.algorithm = :sliding_window_log
|
|
72
|
+
config.limit = 2
|
|
73
|
+
config.window = 60
|
|
74
|
+
end
|
|
75
|
+
|
|
76
|
+
use RateGuard::Middleware, limiter: RateGuard.limiter, paths: ['/hello']
|
|
77
|
+
run ->(_env) { [200, { 'content-type' => 'text/plain' }, ["Hello\n"]] }
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
The third request to `/hello` within a minute gets `429 Too Many Requests`. Other paths are not limited.
|
|
81
|
+
|
|
82
|
+
## Several rules
|
|
83
|
+
|
|
84
|
+
A `PolicySet` holds several rules. A request must pass all rules that match it.
|
|
85
|
+
|
|
86
|
+
```ruby
|
|
87
|
+
require 'rack'
|
|
88
|
+
require 'rate_guard'
|
|
89
|
+
require 'rate_guard/middleware'
|
|
90
|
+
|
|
91
|
+
RateGuard.configure do |config|
|
|
92
|
+
config.algorithm = :sliding_window_log
|
|
93
|
+
config.limit = 100
|
|
94
|
+
config.window = 60
|
|
95
|
+
end
|
|
96
|
+
|
|
97
|
+
policies = RateGuard::PolicySet.new(
|
|
98
|
+
[
|
|
99
|
+
# 3 login attempts per minute, per IP
|
|
100
|
+
RateGuard::Policy.new(name: 'login', methods: %w[POST], paths: %w[/login],
|
|
101
|
+
limiter: RateGuard.limiter(limit: 3)),
|
|
102
|
+
# 1000 requests per minute for everyone together
|
|
103
|
+
RateGuard::Policy.new(name: 'global', identifier: RateGuard::Identifiers::Global.new,
|
|
104
|
+
limiter: RateGuard.limiter(limit: 1000))
|
|
105
|
+
]
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
app = Rack::Builder.app do
|
|
109
|
+
use RateGuard::Middleware, policies: policies
|
|
110
|
+
run ->(_env) { [200, {}, ['ok']] }
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
client = Rack::MockRequest.new(app)
|
|
114
|
+
4.times do
|
|
115
|
+
response = client.post('/login', 'REMOTE_ADDR' => '203.0.113.7')
|
|
116
|
+
puts "#{response.status} remaining=#{response.headers['ratelimit-remaining']}"
|
|
117
|
+
end
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
```text
|
|
121
|
+
200 remaining=2
|
|
122
|
+
200 remaining=1
|
|
123
|
+
200 remaining=0
|
|
124
|
+
429 remaining=0
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
Each `Policy` can set:
|
|
128
|
+
|
|
129
|
+
| Option | What it does |
|
|
130
|
+
| --- | --- |
|
|
131
|
+
| `name:` | A unique name, used in logs |
|
|
132
|
+
| `limiter:` | The limiter that decides |
|
|
133
|
+
| `methods:`, `paths:` | Which requests it covers (`nil` means all) |
|
|
134
|
+
| `identifier:` | Who requests count against (default: client IP) |
|
|
135
|
+
| `cost:` | How much one request costs (default: 1) |
|
|
136
|
+
|
|
137
|
+
Identifiers: `Identifiers::Ip`, `Identifiers::ApiKey`, `Identifiers::User`, `Identifiers::Global`, and `Identifiers::FirstOf` to try several in order. API keys are stored only as hashes, never as plain text.
|
|
138
|
+
|
|
139
|
+
## Algorithms
|
|
140
|
+
|
|
141
|
+
| Name | Good for |
|
|
142
|
+
| --- | --- |
|
|
143
|
+
| `:token_bucket` | Allowing short bursts |
|
|
144
|
+
| `:leaky_bucket_meter` | Smooth, steady traffic |
|
|
145
|
+
| `:fixed_window` | Lowest memory use (allows bursts at window edges) |
|
|
146
|
+
| `:sliding_window_log` | Exact limits (uses more memory) |
|
|
147
|
+
| `:sliding_window_counter` | Nearly exact, low memory, works with Redis |
|
|
148
|
+
| `:leaky_bucket_queue` | Making work wait instead of rejecting it |
|
|
149
|
+
|
|
150
|
+
## Redis
|
|
151
|
+
|
|
152
|
+
With Redis, all your servers share one count:
|
|
153
|
+
|
|
154
|
+
<!-- readme: redis -->
|
|
155
|
+
```ruby
|
|
156
|
+
require 'redis'
|
|
157
|
+
require 'rate_guard'
|
|
158
|
+
|
|
159
|
+
redis = Redis.new(url: ENV.fetch('REDIS_URL', 'redis://127.0.0.1:6379'))
|
|
160
|
+
redis.scan_each(match: 'rate_guard:readme:*') { |key| redis.del(key) } # start fresh
|
|
161
|
+
|
|
162
|
+
RateGuard.configure do |config|
|
|
163
|
+
config.algorithm = :sliding_window_counter
|
|
164
|
+
config.limit = 3
|
|
165
|
+
config.window = 60
|
|
166
|
+
config.redis = redis
|
|
167
|
+
config.namespace = 'rate_guard:readme'
|
|
168
|
+
end
|
|
169
|
+
|
|
170
|
+
server_a = RateGuard.limiter
|
|
171
|
+
server_b = RateGuard.limiter
|
|
172
|
+
|
|
173
|
+
[server_a, server_b, server_a, server_b].each_with_index do |server, n|
|
|
174
|
+
puts "request #{n + 1}: #{server.acquire('user:42').allowed? ? 'allowed' : 'rejected'}"
|
|
175
|
+
end
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
```text
|
|
179
|
+
request 1: allowed
|
|
180
|
+
request 2: allowed
|
|
181
|
+
request 3: allowed
|
|
182
|
+
request 4: rejected
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
If Redis goes down, `config.redis_failure_policy` decides what happens:
|
|
186
|
+
`:allow` lets all requests through (the default), `:reject` blocks them.
|
|
187
|
+
|
|
188
|
+
## Logs
|
|
189
|
+
|
|
190
|
+
Rejected requests can be logged as JSON (`…` marks values that change each time):
|
|
191
|
+
|
|
192
|
+
```ruby
|
|
193
|
+
require 'rack'
|
|
194
|
+
require 'rate_guard'
|
|
195
|
+
require 'rate_guard/middleware'
|
|
196
|
+
|
|
197
|
+
logger = RateGuard::JsonLogFormatter.logger($stdout)
|
|
198
|
+
limiter = RateGuard::Algorithms::SlidingWindowLog.new(limit: 1, window: 60)
|
|
199
|
+
|
|
200
|
+
app = Rack::Builder.app do
|
|
201
|
+
use RateGuard::Middleware, limiter: limiter, paths: ['/search'], logger: logger
|
|
202
|
+
run ->(_env) { [200, {}, ['ok']] }
|
|
203
|
+
end
|
|
204
|
+
|
|
205
|
+
client = Rack::MockRequest.new(app)
|
|
206
|
+
2.times { client.get('/search', 'REMOTE_ADDR' => '203.0.113.7') }
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
```text
|
|
210
|
+
{"time":"…","level":"warn","event":"rate_limited","policy":"default","key":"ip:203.0.113.7","path":"/search","method":"GET","limit":1,"remaining":0,"retry_after":…,"algorithm":"sliding_window_log"}
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
## Settings
|
|
214
|
+
|
|
215
|
+
| Setting | Meaning |
|
|
216
|
+
| --- | --- |
|
|
217
|
+
| `algorithm` | Which algorithm (default `:token_bucket`) |
|
|
218
|
+
| `limit` | Requests allowed per window |
|
|
219
|
+
| `window` | Window length in seconds |
|
|
220
|
+
| `redis` | A Redis client, to share limits |
|
|
221
|
+
| `redis_failure_policy` | `:allow` or `:reject` when Redis is down |
|
|
222
|
+
| `namespace` | Prefix for Redis keys |
|
|
223
|
+
|
|
224
|
+
`RateGuard.limiter(limit: 5)` builds a limiter with some settings changed.
|
|
225
|
+
|
|
226
|
+
## Development
|
|
227
|
+
|
|
228
|
+
```sh
|
|
229
|
+
bundle install
|
|
230
|
+
bundle exec rspec # tests (Redis tests are skipped without Redis)
|
|
231
|
+
bundle exec rake benchmark # speed and memory of each algorithm
|
|
232
|
+
docker compose up --build # demo API with two servers and Redis
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
## License
|
|
236
|
+
|
|
237
|
+
MIT
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module RateGuard
|
|
4
|
+
# Result of adding an item to a queue limiter.
|
|
5
|
+
|
|
6
|
+
# accepted - true if the item was queued
|
|
7
|
+
# position - place in the queue, from 1 (nil if rejected)
|
|
8
|
+
# wait - seconds until the item is released (nil if rejected)
|
|
9
|
+
# retry_after - seconds until the queue has room (0.0 if accepted)
|
|
10
|
+
Admission = Data.define(:accepted, :position, :wait, :retry_after) do
|
|
11
|
+
def accepted? = accepted
|
|
12
|
+
end
|
|
13
|
+
end
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative '../clock'
|
|
4
|
+
require_relative '../result'
|
|
5
|
+
require_relative '../validators/configuration_validator'
|
|
6
|
+
require_relative '../validators/cost_validator'
|
|
7
|
+
|
|
8
|
+
module RateGuard
|
|
9
|
+
module Algorithms
|
|
10
|
+
# Counts requests per clock-aligned window (e.g. 17:47:00-17:47:59).
|
|
11
|
+
# At `limit`, requests are rejected until the next window.
|
|
12
|
+
class FixedWindowCounter
|
|
13
|
+
attr_reader :limit, :window
|
|
14
|
+
|
|
15
|
+
def initialize(limit:, window:, clock: Clock::Wall)
|
|
16
|
+
Validators::ConfigurationValidator.validate!(
|
|
17
|
+
limit: [limit, :integer],
|
|
18
|
+
window: [window, :number]
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
@limit = limit
|
|
22
|
+
@window = window
|
|
23
|
+
@clock = clock
|
|
24
|
+
@window_start = nil
|
|
25
|
+
@counts = Hash.new(0)
|
|
26
|
+
@mutex = Mutex.new
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
# Allows the request and spends `cost` if there is room.
|
|
30
|
+
# reserve: extra units that must stay free (for others); only cost is spent.
|
|
31
|
+
def acquire(key, cost: 1, reserve: 0)
|
|
32
|
+
Validators::CostValidator.validate!(
|
|
33
|
+
cost: cost,
|
|
34
|
+
maximum: @limit,
|
|
35
|
+
type: :integer,
|
|
36
|
+
reserve: reserve
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
@mutex.synchronize do
|
|
40
|
+
now = @clock.now
|
|
41
|
+
roll_window(now)
|
|
42
|
+
used = @counts[key]
|
|
43
|
+
reset_after = @window_start + @window - now
|
|
44
|
+
|
|
45
|
+
if used + cost + reserve <= @limit
|
|
46
|
+
@counts[key] = used + cost
|
|
47
|
+
Result.new(allowed: true, remaining: @limit - used - cost, retry_after: 0.0, reset_after:)
|
|
48
|
+
else
|
|
49
|
+
Result.new(allowed: false, remaining: @limit - used, retry_after: reset_after, reset_after:)
|
|
50
|
+
end
|
|
51
|
+
end
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
# Requests counted for a key in the current window.
|
|
55
|
+
def count(key)
|
|
56
|
+
@mutex.synchronize do
|
|
57
|
+
roll_window(@clock.now)
|
|
58
|
+
@counts[key]
|
|
59
|
+
end
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
# Number of keys counted in the current window.
|
|
63
|
+
def tracked_keys
|
|
64
|
+
@mutex.synchronize do
|
|
65
|
+
roll_window(@clock.now)
|
|
66
|
+
@counts.size
|
|
67
|
+
end
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
private
|
|
71
|
+
|
|
72
|
+
# A new window makes all stored counts old, so drop them together.
|
|
73
|
+
# If the clock goes back, keep the current window.
|
|
74
|
+
def roll_window(now)
|
|
75
|
+
start = (now / @window).floor * @window
|
|
76
|
+
return if @window_start && start <= @window_start
|
|
77
|
+
|
|
78
|
+
@window_start = start
|
|
79
|
+
@counts.clear
|
|
80
|
+
end
|
|
81
|
+
end
|
|
82
|
+
end
|
|
83
|
+
end
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative '../clock'
|
|
4
|
+
require_relative '../result'
|
|
5
|
+
require_relative '../validators/configuration_validator'
|
|
6
|
+
require_relative '../validators/cost_validator'
|
|
7
|
+
|
|
8
|
+
module RateGuard
|
|
9
|
+
module Algorithms
|
|
10
|
+
# Each key has a bucket of `capacity`. Requests pour in `cost`;
|
|
11
|
+
# it drains at `leak_rate` per second. Overflow is rejected.
|
|
12
|
+
class LeakyBucketMeter
|
|
13
|
+
EPSILON = 1e-9
|
|
14
|
+
|
|
15
|
+
State = Struct.new(:level, :updated_at)
|
|
16
|
+
|
|
17
|
+
attr_reader :capacity, :leak_rate
|
|
18
|
+
|
|
19
|
+
# The burst the bucket can take. All limiters answer #limit.
|
|
20
|
+
alias limit capacity
|
|
21
|
+
|
|
22
|
+
def initialize(capacity:, leak_rate:, clock: Clock::Monotonic)
|
|
23
|
+
Validators::ConfigurationValidator.validate!(
|
|
24
|
+
capacity: [capacity, :integer],
|
|
25
|
+
leak_rate: [leak_rate, :number]
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
@capacity = capacity
|
|
29
|
+
@leak_rate = leak_rate
|
|
30
|
+
@clock = clock
|
|
31
|
+
@buckets = {}
|
|
32
|
+
@mutex = Mutex.new
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
# Allows the request and spends `cost` if there is room.
|
|
36
|
+
# reserve: extra units that must stay free (for others); only cost is spent.
|
|
37
|
+
def acquire(key, cost: 1, reserve: 0)
|
|
38
|
+
Validators::CostValidator.validate!(
|
|
39
|
+
cost: cost,
|
|
40
|
+
maximum: @capacity,
|
|
41
|
+
maximum_name: 'capacity',
|
|
42
|
+
type: :number,
|
|
43
|
+
reserve: reserve
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
@mutex.synchronize do
|
|
47
|
+
state = leak(key)
|
|
48
|
+
|
|
49
|
+
if state.level + cost + reserve <= @capacity + EPSILON
|
|
50
|
+
state.level = [state.level + cost, @capacity].min.to_f
|
|
51
|
+
Result.new(allowed: true, remaining: headroom(state), retry_after: 0.0,
|
|
52
|
+
reset_after: until_empty(state))
|
|
53
|
+
else
|
|
54
|
+
retry_after = (state.level + cost + reserve - @capacity) / @leak_rate
|
|
55
|
+
Result.new(allowed: false, remaining: headroom(state), retry_after: retry_after,
|
|
56
|
+
reset_after: until_empty(state))
|
|
57
|
+
end
|
|
58
|
+
end
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
# Current level for a key, after draining.
|
|
62
|
+
def level(key)
|
|
63
|
+
@mutex.synchronize { leak(key).level }
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
private
|
|
67
|
+
|
|
68
|
+
# Drain everything that leaked since the last request.
|
|
69
|
+
def leak(key)
|
|
70
|
+
now = @clock.now
|
|
71
|
+
state = (@buckets[key] ||= State.new(0.0, now))
|
|
72
|
+
|
|
73
|
+
elapsed = now - state.updated_at
|
|
74
|
+
if elapsed.positive?
|
|
75
|
+
state.level = [state.level - (elapsed * @leak_rate), 0.0].max
|
|
76
|
+
state.updated_at = now
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
state
|
|
80
|
+
end
|
|
81
|
+
|
|
82
|
+
# Requests that still fit.
|
|
83
|
+
def headroom(state)
|
|
84
|
+
(@capacity - state.level + EPSILON).floor
|
|
85
|
+
end
|
|
86
|
+
|
|
87
|
+
# Seconds until the bucket is empty again.
|
|
88
|
+
def until_empty(state)
|
|
89
|
+
state.level / @leak_rate
|
|
90
|
+
end
|
|
91
|
+
end
|
|
92
|
+
end
|
|
93
|
+
end
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative '../clock'
|
|
4
|
+
require_relative '../admission'
|
|
5
|
+
require_relative '../validators/configuration_validator'
|
|
6
|
+
|
|
7
|
+
module RateGuard
|
|
8
|
+
module Algorithms
|
|
9
|
+
# Each key has a queue of up to `capacity` items, released at
|
|
10
|
+
# `leak_rate` per second. A full queue rejects new items.
|
|
11
|
+
class LeakyBucketQueue
|
|
12
|
+
EPSILON = 1e-9
|
|
13
|
+
|
|
14
|
+
State = Struct.new(:items, :last_released_at)
|
|
15
|
+
|
|
16
|
+
attr_reader :capacity, :leak_rate
|
|
17
|
+
|
|
18
|
+
def initialize(capacity:, leak_rate:, clock: Clock::Monotonic)
|
|
19
|
+
Validators::ConfigurationValidator.validate!(
|
|
20
|
+
capacity: [capacity, :integer],
|
|
21
|
+
leak_rate: [leak_rate, :number]
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
@capacity = capacity
|
|
25
|
+
@leak_rate = leak_rate
|
|
26
|
+
@interval = 1.0 / leak_rate
|
|
27
|
+
@clock = clock
|
|
28
|
+
@queues = {}
|
|
29
|
+
@mutex = Mutex.new
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
# Adds an item to the key's queue.
|
|
33
|
+
def enqueue(key, item)
|
|
34
|
+
raise ArgumentError, 'item must not be nil' if item.nil?
|
|
35
|
+
|
|
36
|
+
@mutex.synchronize do
|
|
37
|
+
state = state_for(key)
|
|
38
|
+
now = @clock.now
|
|
39
|
+
until_next_slot = next_slot(state, now) - now
|
|
40
|
+
waiting = state.items.size
|
|
41
|
+
|
|
42
|
+
if waiting >= @capacity
|
|
43
|
+
Admission.new(accepted: false, position: nil, wait: nil, retry_after: until_next_slot)
|
|
44
|
+
else
|
|
45
|
+
state.items.push(item)
|
|
46
|
+
Admission.new(accepted: true, position: waiting + 1,
|
|
47
|
+
wait: until_next_slot + (waiting * @interval), retry_after: 0.0)
|
|
48
|
+
end
|
|
49
|
+
end
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
# Returns the next item if its turn has come, else nil.
|
|
53
|
+
def dequeue(key)
|
|
54
|
+
@mutex.synchronize do
|
|
55
|
+
state = state_for(key)
|
|
56
|
+
now = @clock.now
|
|
57
|
+
next if state.items.empty? || now + EPSILON < next_slot(state, now)
|
|
58
|
+
|
|
59
|
+
state.last_released_at = now
|
|
60
|
+
state.items.shift
|
|
61
|
+
end
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
# Seconds until #dequeue returns an item; nil if the queue is empty.
|
|
65
|
+
def next_release_in(key)
|
|
66
|
+
@mutex.synchronize do
|
|
67
|
+
state = state_for(key)
|
|
68
|
+
next if state.items.empty?
|
|
69
|
+
|
|
70
|
+
now = @clock.now
|
|
71
|
+
next_slot(state, now) - now
|
|
72
|
+
end
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
def size(key)
|
|
76
|
+
@mutex.synchronize { state_for(key).items.size }
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
private
|
|
80
|
+
|
|
81
|
+
def state_for(key)
|
|
82
|
+
@queues[key] ||= State.new([], nil)
|
|
83
|
+
end
|
|
84
|
+
|
|
85
|
+
# When the next item may leave. Idle time doesn't save up turns.
|
|
86
|
+
def next_slot(state, now)
|
|
87
|
+
return now if state.last_released_at.nil?
|
|
88
|
+
|
|
89
|
+
[now, state.last_released_at + @interval].max
|
|
90
|
+
end
|
|
91
|
+
end
|
|
92
|
+
end
|
|
93
|
+
end
|