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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +231 -0
- data/Cargo.lock +307 -0
- data/Cargo.toml +31 -0
- data/README.md +89 -14
- data/ext/throttle_machines_native/core/CHANGELOG.md +77 -0
- data/ext/throttle_machines_native/core/Cargo.toml +25 -0
- data/ext/throttle_machines_native/core/README.md +100 -0
- data/ext/throttle_machines_native/core/src/fixed_window.rs +172 -0
- data/ext/throttle_machines_native/core/src/gate.rs +82 -0
- data/ext/throttle_machines_native/core/src/gcra.rs +219 -0
- data/ext/throttle_machines_native/core/src/keyed.rs +325 -0
- data/ext/throttle_machines_native/core/src/lib.rs +50 -0
- data/ext/throttle_machines_native/core/src/refusal.rs +30 -0
- data/ext/throttle_machines_native/core/src/token_bucket.rs +191 -0
- data/ext/throttle_machines_native/extconf.rb +2 -0
- data/ext/throttle_machines_native/ffi/CHANGELOG.md +59 -0
- data/ext/throttle_machines_native/ffi/Cargo.toml +22 -0
- data/ext/throttle_machines_native/ffi/extconf.rb +14 -0
- data/ext/throttle_machines_native/ffi/src/init.rs +63 -0
- data/ext/throttle_machines_native/ffi/src/lib.rs +255 -0
- data/ext/throttle_machines_native/ffi/src/values.rs +194 -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/sig/throttle_machines.rbs +555 -0
- metadata +55 -71
- 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
data/README.md
CHANGED
|
@@ -45,6 +45,20 @@ bundle install
|
|
|
45
45
|
|
|
46
46
|
---
|
|
47
47
|
|
|
48
|
+
## 🕰️ Ship's Clock
|
|
49
|
+
|
|
50
|
+
Every instant and span is **Integer nanoseconds**: periods, windows, TTLs,
|
|
51
|
+
`retry_after`, deadlines. `ThrottleMachines.monotonic_time` reads
|
|
52
|
+
`Process.clock_gettime(Process::CLOCK_MONOTONIC, :nanosecond)`. No floats, no
|
|
53
|
+
seconds; HTTP `Retry-After` headers are the one place a wait becomes whole
|
|
54
|
+
seconds, rounded up.
|
|
55
|
+
|
|
56
|
+
```ruby
|
|
57
|
+
NS = ThrottleMachines::NS_PER_SECOND # 1_000_000_000
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
---
|
|
61
|
+
|
|
48
62
|
## 🎯 Quick Mission Brief
|
|
49
63
|
|
|
50
64
|
### Basic Throttling - The Photon Torpedo Approach
|
|
@@ -52,8 +66,8 @@ bundle install
|
|
|
52
66
|
```ruby
|
|
53
67
|
# Simple rate limiting - like controlling photon torpedo launches
|
|
54
68
|
torpedo_limiter = ThrottleMachines.limiter("photon_launcher",
|
|
55
|
-
limit: 10,
|
|
56
|
-
period: 60
|
|
69
|
+
limit: 10, # 10 torpedoes
|
|
70
|
+
period: 60 * NS # per minute
|
|
57
71
|
)
|
|
58
72
|
|
|
59
73
|
# Check and consume approach
|
|
@@ -69,7 +83,7 @@ begin
|
|
|
69
83
|
torpedo_limiter.throttle!
|
|
70
84
|
launch_torpedo!
|
|
71
85
|
rescue ThrottleMachines::ThrottledError => e
|
|
72
|
-
puts "Torpedo bay recharging... Retry after #{e.
|
|
86
|
+
puts "Torpedo bay recharging... Retry after #{e.retry_after} ns"
|
|
73
87
|
end
|
|
74
88
|
```
|
|
75
89
|
|
|
@@ -80,7 +94,7 @@ end
|
|
|
80
94
|
# Instead of sudden stops, it gracefully manages flow
|
|
81
95
|
diplomatic_limiter = ThrottleMachines.limiter("federation_embassy",
|
|
82
96
|
limit: 100,
|
|
83
|
-
period: 60,
|
|
97
|
+
period: 60 * NS,
|
|
84
98
|
algorithm: :gcra # Generic Cell Rate Algorithm
|
|
85
99
|
)
|
|
86
100
|
|
|
@@ -92,37 +106,87 @@ diplomatic_limiter = ThrottleMachines.limiter("federation_embassy",
|
|
|
92
106
|
```ruby
|
|
93
107
|
# Use the block form for automatic throttling
|
|
94
108
|
# This handles the throttle! and error handling for you
|
|
95
|
-
ThrottleMachines.limit("warp_drive", limit: 5, period: 60) do
|
|
109
|
+
ThrottleMachines.limit("warp_drive", limit: 5, period: 60 * NS) do
|
|
96
110
|
engage_warp_drive! # This will be throttled automatically
|
|
97
111
|
end
|
|
98
112
|
# Raises ThrottledError if limit exceeded
|
|
99
113
|
```
|
|
100
114
|
|
|
115
|
+
### The Reactor Core - Native Gates 🔩
|
|
116
|
+
|
|
117
|
+
Under every limiter sits a `no_std` Rust core. Its gates are yours to drive
|
|
118
|
+
directly, on a clock you supply. Policies are frozen `Data` values validated
|
|
119
|
+
by the core (`TypeError` for the wrong type, `RangeError` for a value it
|
|
120
|
+
refuses); a gate answers exactly how many more calls it would admit at that
|
|
121
|
+
instant, or a refusal Symbol, which changes nothing: `:throttled`, or for
|
|
122
|
+
GCRA `:overflow` when an admission would push its TAT past the largest
|
|
123
|
+
instant (`(2**64 * 10**9) - 1` nanoseconds; `retry_after` then answers that
|
|
124
|
+
instant: never). A `GcraPolicy` whose burst ceiling holds more than
|
|
125
|
+
`2**64 - 1` emission intervals is a `RangeError`. `now` is read over that
|
|
126
|
+
whole range, so every instant a gate returns (a GCRA `tat` can pass
|
|
127
|
+
`2**64 - 1`) reads back.
|
|
128
|
+
|
|
129
|
+
```ruby
|
|
130
|
+
policy = ThrottleMachines::GcraPolicy.per(1 * NS, 10, 3) # 10/s, bursts of 3
|
|
131
|
+
gate = ThrottleMachines::Gcra.new(policy)
|
|
132
|
+
now = ThrottleMachines.monotonic_time
|
|
133
|
+
|
|
134
|
+
gate.check(now) # => 2, then 1, then 0
|
|
135
|
+
gate.check(now) # => :throttled (after the burst)
|
|
136
|
+
gate.retry_after(now) # => 100_000_000
|
|
137
|
+
gate.peek(now) # non-consuming; gate.refund gives one back
|
|
138
|
+
|
|
139
|
+
bucket = ThrottleMachines::TokenBucket.new(ThrottleMachines::TokenBucketPolicy.new(5, 200_000_000))
|
|
140
|
+
window = ThrottleMachines::FixedWindow.new(ThrottleMachines::FixedWindowPolicy.new(60 * NS, 100))
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
State kept elsewhere resumes with `Gcra.restored(policy, tat)`,
|
|
144
|
+
`TokenBucket.restored(policy, tokens, refilled_at)` and
|
|
145
|
+
`FixedWindow.restored(policy, count, window_start)`.
|
|
146
|
+
|
|
147
|
+
### Retries and Breakers 🛡️
|
|
148
|
+
|
|
149
|
+
```ruby
|
|
150
|
+
backoff = ChronoMachines::Exponential.new(100_000_000, 2.0, 5 * NS, 1.0)
|
|
151
|
+
|
|
152
|
+
ThrottleMachines.control("hyperspace_relay") do
|
|
153
|
+
limit rate: 10, per: 1 * NS
|
|
154
|
+
break_on failures: 5, within: 60 * NS
|
|
155
|
+
retry_on_failure backoff, 3
|
|
156
|
+
end.call { relay.transmit! }
|
|
157
|
+
```
|
|
158
|
+
|
|
101
159
|
---
|
|
102
160
|
|
|
103
161
|
## Bounded in-memory storage
|
|
104
162
|
|
|
105
163
|
The memory backend tracks at most **65536 entries**, shared across fixed-window
|
|
106
|
-
counters, GCRA states, and token buckets
|
|
164
|
+
counters, GCRA states, and token buckets.
|
|
107
165
|
|
|
108
166
|
```ruby
|
|
109
167
|
ThrottleMachines.storage = ThrottleMachines::Storage::Memory.new(max_keys: 10_000)
|
|
110
168
|
```
|
|
111
169
|
|
|
112
170
|
When full, expired entries are reclaimed before admission. If no slot is
|
|
113
|
-
available, new identities are
|
|
171
|
+
available, new identities are refused with `:full`; active identities are never evicted
|
|
114
172
|
to make room and can continue under their existing limits. Peeks also fail
|
|
115
173
|
closed for untrackable identities. Capacity refusals use a one-second retry
|
|
116
174
|
hint, not a reservation. At saturation, on-demand expiry scans run at most
|
|
117
175
|
once per second, even with `auto_cleanup: false`.
|
|
118
176
|
|
|
119
|
-
`max_keys` must be a non-negative
|
|
177
|
+
`max_keys` must be a non-negative Integer; zero denies all identities. For
|
|
120
178
|
direct storage callers, an untrackable fixed-window counter reads/increments
|
|
121
|
-
as `
|
|
179
|
+
as `Storage::Base::UNTRACKED` (2**64) so it cannot pass a rate limit.
|
|
122
180
|
|
|
123
181
|
This bounds entry count, not bytes: also bound untrusted identity lengths.
|
|
124
182
|
Redis storage uses TTLs but has no application-level key cap; configure Redis
|
|
125
183
|
memory limits separately. Evicting active Redis keys can reset their limits.
|
|
184
|
+
Redis scripts read `now` from the server (`TIME`, whole microseconds, turned
|
|
185
|
+
into nanoseconds), so processes on any number of hosts can share one Redis
|
|
186
|
+
store; a step in the Redis host's clock is a step for every limit. Stored
|
|
187
|
+
instants count from a `TIME` second kept beside them and are rebased on each
|
|
188
|
+
write, which keeps the scripts' double arithmetic exact. GCRA state is a hash:
|
|
189
|
+
clear throttle keys written by a release that passed the caller's clock.
|
|
126
190
|
|
|
127
191
|
---
|
|
128
192
|
|
|
@@ -144,7 +208,7 @@ first requests.
|
|
|
144
208
|
|
|
145
209
|
It supports `:fixed_window` only; the cache API has no atomic read-modify-write
|
|
146
210
|
for GCRA or token buckets. A limiter built with an algorithm its storage lacks
|
|
147
|
-
raises `
|
|
211
|
+
raises `RangeError` on construction, for custom backends too.
|
|
148
212
|
|
|
149
213
|
When the store fails to count (an outage, `NullStore`), requests are admitted.
|
|
150
214
|
Pass `fail_closed: true` to throttle them instead. `clear` deletes only this
|
|
@@ -159,19 +223,19 @@ with `Limiter#reset!`.
|
|
|
159
223
|
Like the best spacecraft, ThrottleMachines follows the principle of **ultra-thin design**:
|
|
160
224
|
|
|
161
225
|
- **No bloat** - Every component serves a critical function
|
|
162
|
-
- **
|
|
163
|
-
- **
|
|
226
|
+
- **Rust reactor core** - `no_std`, allocation-free, no clock of its own
|
|
227
|
+
- **Exact time** - Integer nanoseconds end to end; no float drift at the boundaries
|
|
164
228
|
- **Modular systems** - Swap components like ship modules
|
|
165
229
|
|
|
166
230
|
---
|
|
167
231
|
|
|
168
232
|
## ⚡ Warp Factor Features
|
|
169
233
|
|
|
170
|
-
- **🚀 Multiple Algorithms** - GCRA, Token Bucket, Fixed Window
|
|
234
|
+
- **🚀 Multiple Algorithms** - GCRA, Token Bucket, Fixed Window
|
|
171
235
|
- **💫 Distributed Ready** - Redis backend for fleet coordination
|
|
172
236
|
- **🔄 Async Support** - Fiber-safe operations for quantum communications
|
|
173
237
|
- **🏃 Hedged Requests** - Multi-path navigation for reduced latency
|
|
174
|
-
- **🎯
|
|
238
|
+
- **🎯 Nanosecond Precision** - Navigate the cosmos with temporal accuracy
|
|
175
239
|
- **🔌 Pluggable Storage** - Memory crystals or Redis quantum storage
|
|
176
240
|
- **🌍 Rails Integration** - Seamless planetary docking procedures
|
|
177
241
|
- **📡 Rack Middleware** - Universal translator for all spacecraft
|
|
@@ -217,6 +281,17 @@ Found a breach in the hull? Encountered an unknown anomaly?
|
|
|
217
281
|
|
|
218
282
|
---
|
|
219
283
|
|
|
284
|
+
## 📡 Credits
|
|
285
|
+
|
|
286
|
+
**AMS Turner**, NCC-1986, *Turner*-class escort.
|
|
287
|
+
|
|
288
|
+
Named for Jonathan Turner's *New Directions in Communications* (1986), which
|
|
289
|
+
proposed the leaky bucket: let traffic drain at a fixed rate with a bounded
|
|
290
|
+
allowance for bursts. GCRA, the algorithm this gem's middleware and controller
|
|
291
|
+
helpers default to, is that leaky bucket kept as one theoretical arrival time.
|
|
292
|
+
|
|
293
|
+
---
|
|
294
|
+
|
|
220
295
|
## 🎖️ Mission Credentials
|
|
221
296
|
|
|
222
297
|
MIT License - See [LICENSE](LICENSE) for full transmission.
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## [0.6.0](https://github.com/seuros/throttle_machines/compare/throttle-machines-v0.5.0...throttle-machines-v0.6.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
|
+
|
|
15
|
+
### Bug Fixes
|
|
16
|
+
|
|
17
|
+
* keep test modules out of the packaged crate ([7f28c6e](https://github.com/seuros/throttle_machines/commit/7f28c6e2a72a9d4a30ec809be8f8a9c9462fa20e))
|
|
18
|
+
|
|
19
|
+
## [0.5.0](https://github.com/seuros/throttle_machines/compare/throttle-machines-v0.4.0...throttle-machines-v0.5.0) (2026-11-02)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
### Features
|
|
23
|
+
|
|
24
|
+
* refund a keyed admission ([d3c1aa0](https://github.com/seuros/throttle_machines/commit/d3c1aa0b95797e0574253b767e43c229ddb5de40))
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
### Bug Fixes
|
|
28
|
+
|
|
29
|
+
* sweep a keyed shard once an eighth of it could have recovered ([48b6ad9](https://github.com/seuros/throttle_machines/commit/48b6ad996b6ecdcf4b9b7c543d7970d0ffd8291a))
|
|
30
|
+
|
|
31
|
+
## [0.4.0](https://github.com/seuros/throttle_machines/compare/throttle-machines-v0.3.1...throttle-machines-v0.4.0) (2026-11-01)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
### Features
|
|
35
|
+
|
|
36
|
+
* bound the throttle wait by the caller's deadline ([37a7784](https://github.com/seuros/throttle_machines/commit/37a7784ca6b5eed976d5b61ca4b6d0a51502a407))
|
|
37
|
+
|
|
38
|
+
## [0.3.1](https://github.com/seuros/throttle_machines/compare/throttle-machines-v0.3.0...throttle-machines-v0.3.1) (2026-10-20)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
### Bug Fixes
|
|
42
|
+
|
|
43
|
+
* **core:** cap keyed GCRA storage under identity sprays ([fb8030a](https://github.com/seuros/throttle_machines/commit/fb8030a73b4dfe03497fd7550f8ee391cca41538))
|
|
44
|
+
|
|
45
|
+
## [0.3.0](https://github.com/seuros/throttle_machines/compare/throttle-machines-v0.2.1...throttle-machines-v0.3.0) (2026-10-14)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
### Features
|
|
49
|
+
|
|
50
|
+
* **core:** add KeyedGcra per-key store and GcraParams::from_rate ([b7fa7a5](https://github.com/seuros/throttle_machines/commit/b7fa7a59bcc3dfb276e4fb9be3a95e38c08fe84c))
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
### Bug Fixes
|
|
54
|
+
|
|
55
|
+
* **core:** admit a token due now despite float rounding ([c46bd54](https://github.com/seuros/throttle_machines/commit/c46bd54e2d913ecc25c3a9fe8098a8116c1747d6))
|
|
56
|
+
* **core:** admit on-schedule GCRA requests despite float rounding ([5aa090e](https://github.com/seuros/throttle_machines/commit/5aa090e1562325e5d9474f3ec35cf1d22d5ccafb))
|
|
57
|
+
|
|
58
|
+
## [0.2.1](https://github.com/seuros/throttle_machines/compare/throttle-machines-v0.2.0...throttle-machines-v0.2.1) (2026-10-10)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
### Performance Improvements
|
|
62
|
+
|
|
63
|
+
* **ffi:** build Decision/Outcome without a kwargs hash; adopt clippy pedantic and nursery ([23c263d](https://github.com/seuros/throttle_machines/commit/23c263da35829a9375397abaae807659ca96a1ac))
|
|
64
|
+
|
|
65
|
+
## [0.2.0](https://github.com/seuros/throttle_machines/compare/throttle-machines-v0.2.0...throttle-machines-v0.2.0) (2026-06-24)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
### Features
|
|
69
|
+
|
|
70
|
+
* add matryoshka pattern with Rust native extension ([97d41a6](https://github.com/seuros/throttle_machines/commit/97d41a6ddf71e042f437c44315c40e3d30c9efe1))
|
|
71
|
+
* add matryoshka pattern with Rust native extension ([3f614cb](https://github.com/seuros/throttle_machines/commit/3f614cbefe8b489f6627b35b635ed954e9e84d4d))
|
|
72
|
+
* add native circuit breaker on shared Gate contract ([dee0b57](https://github.com/seuros/throttle_machines/commit/dee0b57b20c7c887c2e7f7e7d7d2e6a5696be118))
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
### Bug Fixes
|
|
76
|
+
|
|
77
|
+
* ship pure ruby fallback gem ([3a54ac3](https://github.com/seuros/throttle_machines/commit/3a54ac3dffb073ece85a10c4c35ed3c426d658f6))
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
[package]
|
|
2
|
+
name = "throttle-machines"
|
|
3
|
+
version = "0.6.0"
|
|
4
|
+
edition.workspace = true
|
|
5
|
+
rust-version.workspace = true
|
|
6
|
+
license.workspace = true
|
|
7
|
+
authors = ["Abdelkader Boudih <terminale@gmail.com>"]
|
|
8
|
+
description = "Rate limiting (GCRA, token bucket, fixed window) on caller-supplied Duration clocks, no_std"
|
|
9
|
+
repository = "https://github.com/seuros/throttle_machines"
|
|
10
|
+
readme = "README.md"
|
|
11
|
+
keywords = ["rate-limiting", "throttling", "gcra", "token-bucket", "no-std"]
|
|
12
|
+
categories = ["no-std", "algorithms"]
|
|
13
|
+
exclude = ["src/**/tests.rs", "src/tests/", "tests/"]
|
|
14
|
+
|
|
15
|
+
[features]
|
|
16
|
+
default = []
|
|
17
|
+
# `KeyedGcra`: per-key GCRA state in a sharded, mutex-guarded `HashMap`. It
|
|
18
|
+
# allocates and locks, so it needs `std`; the gates themselves never do.
|
|
19
|
+
std = []
|
|
20
|
+
|
|
21
|
+
[dev-dependencies]
|
|
22
|
+
matryona-machines = { workspace = true, features = ["testing"] }
|
|
23
|
+
|
|
24
|
+
[lints]
|
|
25
|
+
workspace = true
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
# throttle-machines
|
|
2
|
+
|
|
3
|
+
Rate limiting on a clock you supply. `no_std`, allocation-free, no `unsafe`;
|
|
4
|
+
the crate reads no clock and does no I/O. `now` is a `core::time::Duration`
|
|
5
|
+
since an epoch you pick, and so is every span.
|
|
6
|
+
|
|
7
|
+
## Algorithms
|
|
8
|
+
|
|
9
|
+
Each limiter is a small `Copy` value, a validated policy plus the state it
|
|
10
|
+
has reached, behind the shared [`Gate`] contract:
|
|
11
|
+
|
|
12
|
+
- **GCRA** (`Gcra`, `GcraPolicy`): one call per emission interval, with a
|
|
13
|
+
delay tolerance for bursts. Smooth and exact.
|
|
14
|
+
- **Token bucket** (`TokenBucket`, `TokenBucketPolicy`): a burst of
|
|
15
|
+
`capacity`, one token earned every `refill_every`.
|
|
16
|
+
- **Fixed window** (`FixedWindow`, `FixedWindowPolicy`): `limit` calls per
|
|
17
|
+
window.
|
|
18
|
+
|
|
19
|
+
`check(now)` admits one call and answers exactly how many more the gate
|
|
20
|
+
would admit at the same instant, or a `Refusal`, which changes nothing:
|
|
21
|
+
`Throttled`, or for GCRA `Overflow` when the admission would push the TAT
|
|
22
|
+
past `Duration::MAX`. `peek(now)` answers the same without consuming,
|
|
23
|
+
`retry_after(now)` how long until the next admission (`Duration::MAX` when
|
|
24
|
+
no instant a `Duration` holds admits one), and `refund()` gives one
|
|
25
|
+
admission back. Nothing saturates into a count: a window or refill due past
|
|
26
|
+
`Duration::MAX` is never due.
|
|
27
|
+
|
|
28
|
+
Policies are built with `new`, which answers `None` for a value the limiter
|
|
29
|
+
cannot honour (a zero interval, refill or window; a GCRA burst ceiling,
|
|
30
|
+
`delay_tolerance + emission_interval`, past `Duration::MAX` or holding more
|
|
31
|
+
than `u64::MAX` intervals, which no `u64` count could answer), or with `per(period,
|
|
32
|
+
limit, ..)`, which spreads `limit` calls over `period`, rounding the interval
|
|
33
|
+
up to the nanosecond so the rate never exceeds the one asked for.
|
|
34
|
+
|
|
35
|
+
```rust
|
|
36
|
+
use core::num::NonZeroU64;
|
|
37
|
+
use core::time::Duration;
|
|
38
|
+
use throttle_machines::{Gate, Gcra, GcraPolicy, Refusal};
|
|
39
|
+
|
|
40
|
+
// 10 calls per second, bursts of 3.
|
|
41
|
+
let ten = NonZeroU64::new(10).unwrap();
|
|
42
|
+
let policy = GcraPolicy::per(Duration::from_secs(1), ten, NonZeroU64::new(3).unwrap()).unwrap();
|
|
43
|
+
let mut gcra = Gcra::new(policy);
|
|
44
|
+
|
|
45
|
+
let now = Duration::from_secs(60);
|
|
46
|
+
assert_eq!(gcra.check(now), Ok(2));
|
|
47
|
+
assert_eq!(gcra.check(now), Ok(1));
|
|
48
|
+
assert_eq!(gcra.check(now), Ok(0));
|
|
49
|
+
assert_eq!(gcra.check(now), Err(Refusal::Throttled));
|
|
50
|
+
assert_eq!(gcra.retry_after(now), Duration::from_millis(100));
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
A caller that keeps state elsewhere between calls (a database row, a cache
|
|
54
|
+
entry) reads it back with `tat()`, `tokens()`/`refilled_at()` or
|
|
55
|
+
`count()`/`window_start()` and resumes with `restored`.
|
|
56
|
+
|
|
57
|
+
## Per-key limiting
|
|
58
|
+
|
|
59
|
+
The `std` feature adds `KeyedGcra`, which holds a TAT per key in a sharded,
|
|
60
|
+
mutex-guarded map and evicts keys once they have fully recovered.
|
|
61
|
+
|
|
62
|
+
Each shard holds at most `max_keys_per_shard` keys (4096 by default, 65536
|
|
63
|
+
with the default 16 shards). A full shard first reclaims recovered keys, in
|
|
64
|
+
batches: it sweeps once an eighth of it could have recovered, and refuses
|
|
65
|
+
untracked keys with `Refusal::Full` until then without allocating. Tracked
|
|
66
|
+
keys keep their limits; free slots in other shards are not borrowed.
|
|
67
|
+
`evict_at` is a cleanup trigger after admissions, not the cap; `evict(now)`
|
|
68
|
+
reclaims every recovered key whenever it is called. `peek` never reclaims.
|
|
69
|
+
|
|
70
|
+
`refund(key, now)` gives back one admission `check` granted, for calls that
|
|
71
|
+
spend several limiters and must be admitted by all of them or none.
|
|
72
|
+
|
|
73
|
+
The cap bounds entry count, not key length: bound identities at ingress when
|
|
74
|
+
they are attacker-controlled.
|
|
75
|
+
|
|
76
|
+
```rust
|
|
77
|
+
# #[cfg(feature = "std")] {
|
|
78
|
+
use core::num::NonZeroU64;
|
|
79
|
+
use std::time::{Duration, Instant};
|
|
80
|
+
use throttle_machines::{GcraPolicy, KeyedGcra};
|
|
81
|
+
|
|
82
|
+
let ten = NonZeroU64::new(10).unwrap();
|
|
83
|
+
let policy = GcraPolicy::per(Duration::from_secs(1), ten, NonZeroU64::new(3).unwrap()).unwrap();
|
|
84
|
+
let limiter = KeyedGcra::<String>::new(policy);
|
|
85
|
+
|
|
86
|
+
let epoch = Instant::now();
|
|
87
|
+
assert_eq!(limiter.check("203.0.113.7", epoch.elapsed()), Ok(2));
|
|
88
|
+
# }
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
```toml
|
|
92
|
+
[dependencies]
|
|
93
|
+
throttle-machines = { version = ">=0.6", features = ["std"] }
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
## License
|
|
97
|
+
|
|
98
|
+
MIT
|
|
99
|
+
|
|
100
|
+
[`Gate`]: https://docs.rs/throttle-machines/latest/throttle_machines/trait.Gate.html
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
//! Fixed window: up to `limit` calls per window, the count starting again
|
|
2
|
+
//! when the window ends. Simple, but admits up to twice the limit across a
|
|
3
|
+
//! window boundary.
|
|
4
|
+
//!
|
|
5
|
+
//! A window whose end would pass `Duration::MAX` never ends: no instant a
|
|
6
|
+
//! `Duration` holds opens the next one, and `retry_after` answers
|
|
7
|
+
//! `Duration::MAX` (never) while it is spent.
|
|
8
|
+
|
|
9
|
+
use core::num::NonZeroU64;
|
|
10
|
+
use core::time::Duration;
|
|
11
|
+
|
|
12
|
+
use crate::{Gate, Refusal};
|
|
13
|
+
|
|
14
|
+
/// How a [`FixedWindow`] admits: `limit` calls per `window`.
|
|
15
|
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
16
|
+
pub struct FixedWindowPolicy {
|
|
17
|
+
window: Duration,
|
|
18
|
+
limit: NonZeroU64,
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
impl FixedWindowPolicy {
|
|
22
|
+
/// `None` for a zero `window`, which would never hold a call.
|
|
23
|
+
#[must_use]
|
|
24
|
+
pub const fn new(window: Duration, limit: NonZeroU64) -> Option<Self> {
|
|
25
|
+
if window.is_zero() {
|
|
26
|
+
return None;
|
|
27
|
+
}
|
|
28
|
+
Some(Self { window, limit })
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/// The length of a window.
|
|
32
|
+
#[must_use]
|
|
33
|
+
pub const fn window(&self) -> Duration {
|
|
34
|
+
self.window
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/// The most calls one window admits.
|
|
38
|
+
#[must_use]
|
|
39
|
+
pub const fn limit(&self) -> NonZeroU64 {
|
|
40
|
+
self.limit
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/// A fixed window counter: a [`FixedWindowPolicy`], the calls admitted in
|
|
45
|
+
/// the current window, and when it opened.
|
|
46
|
+
///
|
|
47
|
+
/// A window opens at the first call after the previous one ended; the first
|
|
48
|
+
/// window opens at the epoch.
|
|
49
|
+
///
|
|
50
|
+
/// ```
|
|
51
|
+
/// use core::num::NonZeroU64;
|
|
52
|
+
/// use core::time::Duration;
|
|
53
|
+
/// use throttle_machines::{FixedWindow, FixedWindowPolicy, Gate, Refusal};
|
|
54
|
+
///
|
|
55
|
+
/// let policy = FixedWindowPolicy::new(Duration::from_secs(60), NonZeroU64::new(1).unwrap()).unwrap();
|
|
56
|
+
/// let mut window = FixedWindow::new(policy);
|
|
57
|
+
/// assert_eq!(window.check(Duration::from_secs(1)), Ok(0));
|
|
58
|
+
/// assert_eq!(window.check(Duration::from_secs(2)), Err(Refusal::Throttled));
|
|
59
|
+
/// assert_eq!(window.retry_after(Duration::from_secs(2)), Duration::from_secs(58));
|
|
60
|
+
/// ```
|
|
61
|
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
62
|
+
pub struct FixedWindow {
|
|
63
|
+
policy: FixedWindowPolicy,
|
|
64
|
+
count: u64,
|
|
65
|
+
window_start: Duration,
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
impl FixedWindow {
|
|
69
|
+
/// A counter that has admitted nothing, in a window opened at the epoch.
|
|
70
|
+
#[must_use]
|
|
71
|
+
pub const fn new(policy: FixedWindowPolicy) -> Self {
|
|
72
|
+
Self {
|
|
73
|
+
policy,
|
|
74
|
+
count: 0,
|
|
75
|
+
window_start: Duration::ZERO,
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/// A counter resumed from [`count`](Self::count) and
|
|
80
|
+
/// [`window_start`](Self::window_start); `None` when `count` is above
|
|
81
|
+
/// the limit.
|
|
82
|
+
#[must_use]
|
|
83
|
+
pub const fn restored(
|
|
84
|
+
policy: FixedWindowPolicy,
|
|
85
|
+
count: u64,
|
|
86
|
+
window_start: Duration,
|
|
87
|
+
) -> Option<Self> {
|
|
88
|
+
if count > policy.limit.get() {
|
|
89
|
+
return None;
|
|
90
|
+
}
|
|
91
|
+
Some(Self {
|
|
92
|
+
policy,
|
|
93
|
+
count,
|
|
94
|
+
window_start,
|
|
95
|
+
})
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/// The policy this counter admits by.
|
|
99
|
+
#[must_use]
|
|
100
|
+
pub const fn policy(&self) -> FixedWindowPolicy {
|
|
101
|
+
self.policy
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/// Calls admitted in the window opened at
|
|
105
|
+
/// [`window_start`](Self::window_start).
|
|
106
|
+
#[must_use]
|
|
107
|
+
pub const fn count(&self) -> u64 {
|
|
108
|
+
self.count
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/// When the current window opened.
|
|
112
|
+
#[must_use]
|
|
113
|
+
pub const fn window_start(&self) -> Duration {
|
|
114
|
+
self.window_start
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/// When the current window ends; `None` when it never does.
|
|
118
|
+
const fn window_end(&self) -> Option<Duration> {
|
|
119
|
+
self.window_start.checked_add(self.policy.window)
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/// The count and window start as of `now`: a fresh window opened at
|
|
123
|
+
/// `now` once the current one has ended.
|
|
124
|
+
fn current(&self, now: Duration) -> (u64, Duration) {
|
|
125
|
+
if self.window_end().is_some_and(|end| now >= end) {
|
|
126
|
+
(0, now)
|
|
127
|
+
} else {
|
|
128
|
+
(self.count, self.window_start)
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const fn left(&self, admitted: u64) -> Result<u64, Refusal> {
|
|
133
|
+
match self.policy.limit.get().checked_sub(admitted) {
|
|
134
|
+
Some(0) | None => Err(Refusal::Throttled),
|
|
135
|
+
Some(left) => Ok(left),
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
impl Gate for FixedWindow {
|
|
141
|
+
fn check(&mut self, now: Duration) -> Result<u64, Refusal> {
|
|
142
|
+
let (count, window_start) = self.current(now);
|
|
143
|
+
// `left` answers at least one, so count < limit: neither step wraps.
|
|
144
|
+
let left = self.left(count)?;
|
|
145
|
+
self.count = count + 1;
|
|
146
|
+
self.window_start = window_start;
|
|
147
|
+
Ok(left - 1)
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
fn peek(&self, now: Duration) -> Result<u64, Refusal> {
|
|
151
|
+
self.left(self.current(now).0)
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
fn retry_after(&self, now: Duration) -> Duration {
|
|
155
|
+
let (count, window_start) = self.current(now);
|
|
156
|
+
if self.left(count).is_ok() {
|
|
157
|
+
return Duration::ZERO;
|
|
158
|
+
}
|
|
159
|
+
// Spent, so the window is still open at `now`: `now` is before its end.
|
|
160
|
+
window_start
|
|
161
|
+
.checked_add(self.policy.window)
|
|
162
|
+
.map_or(Duration::MAX, |end| end.saturating_sub(now))
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/// Takes one call off the current window's count.
|
|
166
|
+
fn refund(&mut self) {
|
|
167
|
+
self.count = self.count.saturating_sub(1);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
#[cfg(test)]
|
|
172
|
+
mod tests;
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
//! The contract every rate limiter honours.
|
|
2
|
+
|
|
3
|
+
use core::num::NonZeroU64;
|
|
4
|
+
use core::time::Duration;
|
|
5
|
+
|
|
6
|
+
use crate::Refusal;
|
|
7
|
+
|
|
8
|
+
/// An admission gate over a caller-supplied monotonic clock: `now` is a
|
|
9
|
+
/// [`Duration`] since an epoch the caller picks, the same for every call on
|
|
10
|
+
/// one gate.
|
|
11
|
+
///
|
|
12
|
+
/// A gate reads no clock and keeps no history beyond its own state. Calls at
|
|
13
|
+
/// an earlier `now` than an earlier call are answered, never refused for it:
|
|
14
|
+
/// each algorithm is at least as strict at an earlier instant as at a later
|
|
15
|
+
/// one, so a regressed clock can delay admissions but never grant extra ones.
|
|
16
|
+
pub trait Gate {
|
|
17
|
+
/// Admit one call at `now`. Honoured: how many more calls the gate would
|
|
18
|
+
/// admit at the same instant, exactly. A refusal changes nothing.
|
|
19
|
+
///
|
|
20
|
+
/// # Errors
|
|
21
|
+
///
|
|
22
|
+
/// [`Refusal::Throttled`] when the limit is spent at `now`;
|
|
23
|
+
/// [`Refusal::Overflow`] (GCRA only) when admitting would push the TAT
|
|
24
|
+
/// past `Duration::MAX`.
|
|
25
|
+
fn check(&mut self, now: Duration) -> Result<u64, Refusal>;
|
|
26
|
+
|
|
27
|
+
/// How many calls [`check`](Self::check) would admit back to back at
|
|
28
|
+
/// `now`, exactly, at least one, without consuming any.
|
|
29
|
+
///
|
|
30
|
+
/// # Errors
|
|
31
|
+
///
|
|
32
|
+
/// The refusal `check` would answer at `now`.
|
|
33
|
+
fn peek(&self, now: Duration) -> Result<u64, Refusal>;
|
|
34
|
+
|
|
35
|
+
/// How long after `now` the next call is admitted; zero when one is
|
|
36
|
+
/// admitted at `now`, and `Duration::MAX` when none is at any instant a
|
|
37
|
+
/// `Duration` can hold.
|
|
38
|
+
fn retry_after(&self, now: Duration) -> Duration;
|
|
39
|
+
|
|
40
|
+
/// Give back one admission `check` granted, for a call admitted only when
|
|
41
|
+
/// every gate it spends admits it. Refunding an admission never granted
|
|
42
|
+
/// grants capacity never earned, up to a fresh gate's.
|
|
43
|
+
fn refund(&mut self);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/// `span * count`, or `None` past `Duration::MAX`.
|
|
47
|
+
pub fn times(span: Duration, count: u128) -> Option<Duration> {
|
|
48
|
+
nanos(span.as_nanos().checked_mul(count)?)
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/// How many whole `span`s fit in `total`. `span` is never zero: the policies
|
|
52
|
+
/// that hold one refuse it.
|
|
53
|
+
pub fn fits(total: Duration, span: Duration) -> u128 {
|
|
54
|
+
total.as_nanos().checked_div(span.as_nanos()).unwrap_or(0)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/// `total / count`, rounded up, so a rate built from it never exceeds the
|
|
58
|
+
/// `count` per `total` asked for. `None` for a zero `total`.
|
|
59
|
+
pub fn share(total: Duration, count: NonZeroU64) -> Option<Duration> {
|
|
60
|
+
let share = total.as_nanos().div_ceil(u128::from(count.get()));
|
|
61
|
+
if share == 0 {
|
|
62
|
+
return None;
|
|
63
|
+
}
|
|
64
|
+
nanos(share)
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/// A count already bounded by a `u64` (a policy's capacity, the tokens
|
|
68
|
+
/// held), as the `u64` a gate answers.
|
|
69
|
+
pub fn count(value: u128) -> u64 {
|
|
70
|
+
u64::try_from(value).unwrap_or_else(|_| {
|
|
71
|
+
debug_assert!(false, "a count past the u64 bound its policy proved");
|
|
72
|
+
u64::MAX
|
|
73
|
+
})
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
fn nanos(value: u128) -> Option<Duration> {
|
|
77
|
+
const PER_SECOND: u128 = 1_000_000_000;
|
|
78
|
+
let seconds = u64::try_from(value / PER_SECOND).ok()?;
|
|
79
|
+
// The remainder is below a billion, so it fits.
|
|
80
|
+
let rest = u32::try_from(value % PER_SECOND).ok()?;
|
|
81
|
+
Some(Duration::new(seconds, rest))
|
|
82
|
+
}
|