throttle_machines 0.4.3 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +231 -0
  3. data/Cargo.lock +307 -0
  4. data/Cargo.toml +31 -0
  5. data/README.md +89 -14
  6. data/ext/throttle_machines_native/core/CHANGELOG.md +77 -0
  7. data/ext/throttle_machines_native/core/Cargo.toml +25 -0
  8. data/ext/throttle_machines_native/core/README.md +100 -0
  9. data/ext/throttle_machines_native/core/src/fixed_window.rs +172 -0
  10. data/ext/throttle_machines_native/core/src/gate.rs +82 -0
  11. data/ext/throttle_machines_native/core/src/gcra.rs +219 -0
  12. data/ext/throttle_machines_native/core/src/keyed.rs +325 -0
  13. data/ext/throttle_machines_native/core/src/lib.rs +50 -0
  14. data/ext/throttle_machines_native/core/src/refusal.rs +30 -0
  15. data/ext/throttle_machines_native/core/src/token_bucket.rs +191 -0
  16. data/ext/throttle_machines_native/extconf.rb +2 -0
  17. data/ext/throttle_machines_native/ffi/CHANGELOG.md +59 -0
  18. data/ext/throttle_machines_native/ffi/Cargo.toml +22 -0
  19. data/ext/throttle_machines_native/ffi/extconf.rb +14 -0
  20. data/ext/throttle_machines_native/ffi/src/init.rs +63 -0
  21. data/ext/throttle_machines_native/ffi/src/lib.rs +255 -0
  22. data/ext/throttle_machines_native/ffi/src/values.rs +194 -0
  23. data/lib/throttle_machines/async_breaker.rb +5 -0
  24. data/lib/throttle_machines/async_support.rb +16 -21
  25. data/lib/throttle_machines/breakers.rb +46 -0
  26. data/lib/throttle_machines/control.rb +25 -46
  27. data/lib/throttle_machines/controller_helpers.rb +11 -10
  28. data/lib/throttle_machines/hedged_breaker.rb +4 -6
  29. data/lib/throttle_machines/hedged_request.rb +29 -42
  30. data/lib/throttle_machines/instrumentation.rb +10 -75
  31. data/lib/throttle_machines/limiter.rb +71 -136
  32. data/lib/throttle_machines/middleware.rb +6 -6
  33. data/lib/throttle_machines/rack_middleware/allow2_ban.rb +1 -8
  34. data/lib/throttle_machines/rack_middleware/ban_filter.rb +3 -2
  35. data/lib/throttle_machines/rack_middleware/configuration.rb +4 -2
  36. data/lib/throttle_machines/rack_middleware/fail2_ban.rb +5 -21
  37. data/lib/throttle_machines/rack_middleware/throttle.rb +2 -1
  38. data/lib/throttle_machines/rack_middleware.rb +3 -1
  39. data/lib/throttle_machines/storage/base.rb +49 -48
  40. data/lib/throttle_machines/storage/cache.rb +12 -6
  41. data/lib/throttle_machines/storage/memory.rb +68 -96
  42. data/lib/throttle_machines/storage/null.rb +18 -28
  43. data/lib/throttle_machines/storage/redis/gcra.lua +21 -20
  44. data/lib/throttle_machines/storage/redis/increment_counter.lua +4 -4
  45. data/lib/throttle_machines/storage/redis/peek_gcra.lua +16 -16
  46. data/lib/throttle_machines/storage/redis/peek_token_bucket.lua +22 -18
  47. data/lib/throttle_machines/storage/redis/token_bucket.lua +31 -19
  48. data/lib/throttle_machines/storage/redis.rb +63 -69
  49. data/lib/throttle_machines/throttled_error.rb +4 -1
  50. data/lib/throttle_machines/version.rb +1 -1
  51. data/lib/throttle_machines.rb +130 -87
  52. data/sig/throttle_machines.rbs +555 -0
  53. metadata +55 -71
  54. data/lib/throttle_machines/async_limiter.rb +0 -24
  55. data/lib/throttle_machines/dependency_error.rb +0 -6
  56. data/lib/throttle_machines/native_speedup.rb +0 -110
@@ -0,0 +1,191 @@
1
+ //! Token bucket: up to `capacity` calls back to back, refilled one token
2
+ //! every `refill_every`.
3
+ //!
4
+ //! A token due past `Duration::MAX` is never earned: `retry_after` answers
5
+ //! `Duration::MAX` (never) for an empty bucket whose next token falls there.
6
+
7
+ use core::num::NonZeroU64;
8
+ use core::time::Duration;
9
+
10
+ use crate::gate::{count, fits, share, times};
11
+ use crate::{Gate, Refusal};
12
+
13
+ /// How a [`TokenBucket`] admits: a burst of `capacity`, one more call per
14
+ /// `refill_every`.
15
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
16
+ pub struct TokenBucketPolicy {
17
+ capacity: NonZeroU64,
18
+ refill_every: Duration,
19
+ }
20
+
21
+ impl TokenBucketPolicy {
22
+ /// `None` for a zero `refill_every`, which would refill without bound.
23
+ #[must_use]
24
+ pub const fn new(capacity: NonZeroU64, refill_every: Duration) -> Option<Self> {
25
+ if refill_every.is_zero() {
26
+ return None;
27
+ }
28
+ Some(Self {
29
+ capacity,
30
+ refill_every,
31
+ })
32
+ }
33
+
34
+ /// `limit` calls per `period`, all of them available as a burst. The
35
+ /// refill span is `period / limit` rounded up to the nanosecond; `None`
36
+ /// for a zero `period`.
37
+ ///
38
+ /// ```
39
+ /// use core::num::NonZeroU64;
40
+ /// use core::time::Duration;
41
+ /// use throttle_machines::TokenBucketPolicy;
42
+ ///
43
+ /// let policy = TokenBucketPolicy::per(Duration::from_secs(60), NonZeroU64::new(3).unwrap()).unwrap();
44
+ /// assert_eq!(policy.capacity().get(), 3);
45
+ /// assert_eq!(policy.refill_every(), Duration::from_secs(20));
46
+ /// ```
47
+ #[must_use]
48
+ pub fn per(period: Duration, limit: NonZeroU64) -> Option<Self> {
49
+ Self::new(limit, share(period, limit)?)
50
+ }
51
+
52
+ /// The most tokens the bucket holds.
53
+ #[must_use]
54
+ pub const fn capacity(&self) -> NonZeroU64 {
55
+ self.capacity
56
+ }
57
+
58
+ /// The span that earns one token.
59
+ #[must_use]
60
+ pub const fn refill_every(&self) -> Duration {
61
+ self.refill_every
62
+ }
63
+ }
64
+
65
+ /// A token bucket: a [`TokenBucketPolicy`], the tokens held, and the instant
66
+ /// refill credit was counted up to.
67
+ ///
68
+ /// ```
69
+ /// use core::num::NonZeroU64;
70
+ /// use core::time::Duration;
71
+ /// use throttle_machines::{Gate, Refusal, TokenBucket, TokenBucketPolicy};
72
+ ///
73
+ /// let policy = TokenBucketPolicy::new(NonZeroU64::new(2).unwrap(), Duration::from_secs(1)).unwrap();
74
+ /// let mut bucket = TokenBucket::new(policy);
75
+ /// let now = Duration::from_secs(5);
76
+ /// assert_eq!(bucket.check(now), Ok(1));
77
+ /// assert_eq!(bucket.check(now), Ok(0));
78
+ /// assert_eq!(bucket.check(now), Err(Refusal::Throttled));
79
+ /// assert_eq!(bucket.check(now + Duration::from_secs(1)), Ok(0));
80
+ /// ```
81
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
82
+ pub struct TokenBucket {
83
+ policy: TokenBucketPolicy,
84
+ tokens: u64,
85
+ refilled_at: Duration,
86
+ }
87
+
88
+ impl TokenBucket {
89
+ /// A full bucket.
90
+ #[must_use]
91
+ pub const fn new(policy: TokenBucketPolicy) -> Self {
92
+ Self {
93
+ policy,
94
+ tokens: policy.capacity.get(),
95
+ refilled_at: Duration::ZERO,
96
+ }
97
+ }
98
+
99
+ /// A bucket resumed from [`tokens`](Self::tokens) and
100
+ /// [`refilled_at`](Self::refilled_at); `None` when `tokens` is above the
101
+ /// capacity.
102
+ #[must_use]
103
+ pub const fn restored(
104
+ policy: TokenBucketPolicy,
105
+ tokens: u64,
106
+ refilled_at: Duration,
107
+ ) -> Option<Self> {
108
+ if tokens > policy.capacity.get() {
109
+ return None;
110
+ }
111
+ Some(Self {
112
+ policy,
113
+ tokens,
114
+ refilled_at,
115
+ })
116
+ }
117
+
118
+ /// The policy this bucket admits by.
119
+ #[must_use]
120
+ pub const fn policy(&self) -> TokenBucketPolicy {
121
+ self.policy
122
+ }
123
+
124
+ /// Tokens held as of [`refilled_at`](Self::refilled_at).
125
+ #[must_use]
126
+ pub const fn tokens(&self) -> u64 {
127
+ self.tokens
128
+ }
129
+
130
+ /// The instant refill credit is counted from. A full bucket earns
131
+ /// nothing, so its count starts again when a token is spent.
132
+ #[must_use]
133
+ pub const fn refilled_at(&self) -> Duration {
134
+ self.refilled_at
135
+ }
136
+
137
+ /// Tokens and the refill instant as of `now`. A partial span earned
138
+ /// toward the next token is kept; nothing is banked past capacity.
139
+ fn refilled(&self, now: Duration) -> (u64, Duration) {
140
+ let capacity = self.policy.capacity.get();
141
+ let earned = fits(
142
+ now.saturating_sub(self.refilled_at),
143
+ self.policy.refill_every,
144
+ );
145
+ let tokens = u128::from(self.tokens).saturating_add(earned);
146
+ if tokens >= u128::from(capacity) {
147
+ return (capacity, self.refilled_at.max(now));
148
+ }
149
+ // Below capacity, so `earned` spans fit inside `now - refilled_at`.
150
+ let spent = times(self.policy.refill_every, earned).unwrap_or(Duration::ZERO);
151
+ (count(tokens), self.refilled_at.saturating_add(spent))
152
+ }
153
+ }
154
+
155
+ impl Gate for TokenBucket {
156
+ fn check(&mut self, now: Duration) -> Result<u64, Refusal> {
157
+ let (tokens, refilled_at) = self.refilled(now);
158
+ let left = tokens.checked_sub(1).ok_or(Refusal::Throttled)?;
159
+ self.tokens = left;
160
+ self.refilled_at = refilled_at;
161
+ Ok(left)
162
+ }
163
+
164
+ fn peek(&self, now: Duration) -> Result<u64, Refusal> {
165
+ match self.refilled(now) {
166
+ (0, _) => Err(Refusal::Throttled),
167
+ (tokens, _) => Ok(tokens),
168
+ }
169
+ }
170
+
171
+ fn retry_after(&self, now: Duration) -> Duration {
172
+ match self.refilled(now) {
173
+ // Empty, so the next token is due after `now`.
174
+ (0, refilled_at) => refilled_at
175
+ .checked_add(self.policy.refill_every)
176
+ .map_or(Duration::MAX, |due| due.saturating_sub(now)),
177
+ _ => Duration::ZERO,
178
+ }
179
+ }
180
+
181
+ /// Puts one token back, never past capacity.
182
+ fn refund(&mut self) {
183
+ self.tokens = self
184
+ .tokens
185
+ .saturating_add(1)
186
+ .min(self.policy.capacity.get());
187
+ }
188
+ }
189
+
190
+ #[cfg(test)]
191
+ mod tests;
@@ -0,0 +1,2 @@
1
+ # frozen_string_literal: true
2
+ require_relative 'ffi/extconf'
@@ -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))
@@ -0,0 +1,22 @@
1
+ [package]
2
+ name = "throttle_machines_native"
3
+ version = "0.5.0"
4
+ edition.workspace = true
5
+ rust-version.workspace = true
6
+ license.workspace = true
7
+ authors = ["Abdelkader Boudih <terminale@gmail.com>"]
8
+ publish = false
9
+
10
+ [lib]
11
+ crate-type = ["cdylib"]
12
+ test = false
13
+ doctest = false
14
+
15
+ [dependencies]
16
+ throttle-machines.workspace = true
17
+ magnus.workspace = true
18
+ rb-sys.workspace = true
19
+ matryona-machines = { workspace = true, features = ["ruby"] }
20
+
21
+ [lints]
22
+ workspace = true
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+ require 'mkmf'
3
+ require 'pathname'
4
+ require 'rb_sys/mkmf'
5
+
6
+ create_rust_makefile('throttle_machines_native/throttle_machines_native') do |e|
7
+ e.ext_dir = Pathname(__dir__).relative_path_from(Pathname(Dir.pwd)).to_s
8
+ e.profile = ENV.fetch('RB_SYS_CARGO_PROFILE', :release).to_sym
9
+ end
10
+ makefile = File.join(Dir.pwd, 'Makefile')
11
+ File.write(makefile, File.read(makefile).gsub(
12
+ /^RB_SYS_CARGO_MANIFEST_DIR \?=.*$/,
13
+ "RB_SYS_CARGO_MANIFEST_DIR ?= #{File.expand_path(__dir__)}"
14
+ ))
@@ -0,0 +1,63 @@
1
+ //! Private native entry point.
2
+ use magnus::{Error, Ruby, function, method, prelude::*};
3
+ use matryona_machines::ruby::Class;
4
+
5
+ use crate::{FixedWindow, Gcra, TokenBucket, values};
6
+
7
+ #[magnus::init]
8
+ fn init(ruby: &Ruby) -> Result<(), Error> {
9
+ let module = ruby.define_module("ThrottleMachines")?;
10
+ values::resolve(ruby, module)?;
11
+ // Validation hooks for the Data values; lib/ makes them private.
12
+ module.define_singleton_method("__gcra_policy", function!(values::check_gcra, 2))?;
13
+ module.define_singleton_method(
14
+ "__token_bucket_policy",
15
+ function!(values::check_token_bucket, 2),
16
+ )?;
17
+ module.define_singleton_method(
18
+ "__fixed_window_policy",
19
+ function!(values::check_fixed_window, 2),
20
+ )?;
21
+ module.define_singleton_method("__gcra_per", function!(values::gcra_per, 3))?;
22
+ module.define_singleton_method("__token_bucket_per", function!(values::token_bucket_per, 2))?;
23
+
24
+ let gcra = module.define_class("Gcra", ruby.class_object())?;
25
+ gcra.undef_default_alloc_func();
26
+ gcra.define_singleton_method("new", function!(Gcra::new, 1))?;
27
+ gcra.define_singleton_method("restored", function!(Gcra::restored, 2))?;
28
+ gcra.define_method("check", method!(Gcra::check, 1))?;
29
+ gcra.define_method("peek", method!(Gcra::peek, 1))?;
30
+ gcra.define_method("retry_after", method!(Gcra::retry_after, 1))?;
31
+ gcra.define_method("refund", method!(Gcra::refund, 0))?;
32
+ gcra.define_method("policy", method!(Gcra::policy, 0))?;
33
+ gcra.define_method("tat", method!(Gcra::tat, 0))?;
34
+ // Each `new` answers a wrapped gate: its class is fixed now, so building
35
+ // one never looks it up by name.
36
+ Class::pin_wrapped::<Gcra>(ruby, gcra)?;
37
+
38
+ let bucket = module.define_class("TokenBucket", ruby.class_object())?;
39
+ bucket.undef_default_alloc_func();
40
+ bucket.define_singleton_method("new", function!(TokenBucket::new, 1))?;
41
+ bucket.define_singleton_method("restored", function!(TokenBucket::restored, 3))?;
42
+ bucket.define_method("check", method!(TokenBucket::check, 1))?;
43
+ bucket.define_method("peek", method!(TokenBucket::peek, 1))?;
44
+ bucket.define_method("retry_after", method!(TokenBucket::retry_after, 1))?;
45
+ bucket.define_method("refund", method!(TokenBucket::refund, 0))?;
46
+ bucket.define_method("policy", method!(TokenBucket::policy, 0))?;
47
+ bucket.define_method("tokens", method!(TokenBucket::tokens, 0))?;
48
+ bucket.define_method("refilled_at", method!(TokenBucket::refilled_at, 0))?;
49
+ Class::pin_wrapped::<TokenBucket>(ruby, bucket)?;
50
+
51
+ let window = module.define_class("FixedWindow", ruby.class_object())?;
52
+ window.undef_default_alloc_func();
53
+ window.define_singleton_method("new", function!(FixedWindow::new, 1))?;
54
+ window.define_singleton_method("restored", function!(FixedWindow::restored, 3))?;
55
+ window.define_method("check", method!(FixedWindow::check, 1))?;
56
+ window.define_method("peek", method!(FixedWindow::peek, 1))?;
57
+ window.define_method("retry_after", method!(FixedWindow::retry_after, 1))?;
58
+ window.define_method("refund", method!(FixedWindow::refund, 0))?;
59
+ window.define_method("policy", method!(FixedWindow::policy, 0))?;
60
+ window.define_method("count", method!(FixedWindow::count, 0))?;
61
+ window.define_method("window_start", method!(FixedWindow::window_start, 0))?;
62
+ Class::pin_wrapped::<FixedWindow>(ruby, window).map(drop)
63
+ }
@@ -0,0 +1,255 @@
1
+ //! Thin binding to the throttle-machines gates.
2
+ //!
3
+ //! Each gate is a wrapped core value; its answers are only Integers, Symbols
4
+ //! and `nil`, so mutating calls change it in place, frozen checked first.
5
+ //!
6
+ //! Every `now` is read over the whole `Duration` range (matryona's
7
+ //! `instant`), so any instant a gate returns (a GCRA `tat` is `now` plus an
8
+ //! interval, past 2**64-1 nanoseconds) reads back.
9
+ mod init;
10
+ mod values;
11
+
12
+ use std::cell::RefCell;
13
+ use std::time::Duration;
14
+
15
+ use magnus::{Error, Integer, IntoValue, Ruby, Value, typed_data::Obj, value::ReprValue};
16
+ use matryona_machines::ruby::{Symbols, instant, integer, nanoseconds};
17
+ use throttle_machines::{
18
+ FixedWindow as FixedWindowCore, Gate, Gcra as GcraCore, Refusal, TokenBucket as TokenBucketCore,
19
+ };
20
+
21
+ matryona_machines::symbols! {
22
+ /// A refusal as its Symbol: the snake case of the core variant. The
23
+ /// gates never answer `:full`; only the core's `KeyedGcra` does. Only
24
+ /// GCRA answers `:overflow`.
25
+ Refusals for Refusal as "refusal" {
26
+ Throttled => "throttled",
27
+ Full => "full",
28
+ Overflow => "overflow",
29
+ }
30
+ }
31
+
32
+ /// An honoured count as an Integer, a refusal as its Symbol.
33
+ fn answer(ruby: &Ruby, decided: Result<u64, Refusal>) -> Value {
34
+ match decided {
35
+ Ok(count) => count.into_value_with(ruby),
36
+ Err(refused) => Refusals::symbol(ruby, refused).as_value(),
37
+ }
38
+ }
39
+
40
+ fn now_of(now: Value) -> Result<Duration, Error> {
41
+ instant(now, "now")
42
+ }
43
+
44
+ fn check<G: Gate>(
45
+ ruby: &Ruby,
46
+ this: impl ReprValue,
47
+ cell: &RefCell<G>,
48
+ now: Value,
49
+ ) -> Result<Value, Error> {
50
+ this.check_frozen()?;
51
+ let now = now_of(now)?;
52
+ let decided = cell.borrow_mut().check(now);
53
+ Ok(answer(ruby, decided))
54
+ }
55
+
56
+ fn peek<G: Gate>(ruby: &Ruby, cell: &RefCell<G>, now: Value) -> Result<Value, Error> {
57
+ let now = now_of(now)?;
58
+ let decided = cell.borrow().peek(now);
59
+ Ok(answer(ruby, decided))
60
+ }
61
+
62
+ fn retry_after<G: Gate>(ruby: &Ruby, cell: &RefCell<G>, now: Value) -> Result<Integer, Error> {
63
+ let now = now_of(now)?;
64
+ let wait = cell.borrow().retry_after(now);
65
+ Ok(nanoseconds(ruby, wait))
66
+ }
67
+
68
+ fn refund<G: Gate>(this: impl ReprValue, cell: &RefCell<G>) -> Result<(), Error> {
69
+ this.check_frozen()?;
70
+ cell.borrow_mut().refund();
71
+ Ok(())
72
+ }
73
+
74
+ #[magnus::wrap(class = "ThrottleMachines::Gcra", free_immediately, size)]
75
+ struct Gcra {
76
+ core: RefCell<GcraCore>,
77
+ }
78
+
79
+ impl Gcra {
80
+ fn new(ruby: &Ruby, policy: Value) -> Result<Self, Error> {
81
+ let policy = values::read_gcra(ruby, policy)?;
82
+ Ok(Self::from(GcraCore::new(policy)))
83
+ }
84
+
85
+ fn restored(ruby: &Ruby, policy: Value, tat: Value) -> Result<Self, Error> {
86
+ let policy = values::read_gcra(ruby, policy)?;
87
+ let tat = instant(tat, "tat")?;
88
+ Ok(Self::from(GcraCore::restored(policy, tat)))
89
+ }
90
+
91
+ const fn from(core: GcraCore) -> Self {
92
+ Self {
93
+ core: RefCell::new(core),
94
+ }
95
+ }
96
+
97
+ fn check(ruby: &Ruby, this: Obj<Self>, now: Value) -> Result<Value, Error> {
98
+ check(ruby, this, &this.core, now)
99
+ }
100
+
101
+ fn peek(ruby: &Ruby, this: &Self, now: Value) -> Result<Value, Error> {
102
+ peek(ruby, &this.core, now)
103
+ }
104
+
105
+ fn retry_after(ruby: &Ruby, this: &Self, now: Value) -> Result<Integer, Error> {
106
+ retry_after(ruby, &this.core, now)
107
+ }
108
+
109
+ fn refund(this: Obj<Self>) -> Result<(), Error> {
110
+ refund(this, &this.core)
111
+ }
112
+
113
+ fn policy(ruby: &Ruby, this: &Self) -> Result<Value, Error> {
114
+ let policy = this.core.borrow().policy();
115
+ values::gcra_value(ruby, policy)
116
+ }
117
+
118
+ fn tat(ruby: &Ruby, this: &Self) -> Integer {
119
+ nanoseconds(ruby, this.core.borrow().tat())
120
+ }
121
+ }
122
+
123
+ #[magnus::wrap(class = "ThrottleMachines::TokenBucket", free_immediately, size)]
124
+ struct TokenBucket {
125
+ core: RefCell<TokenBucketCore>,
126
+ }
127
+
128
+ impl TokenBucket {
129
+ fn new(ruby: &Ruby, policy: Value) -> Result<Self, Error> {
130
+ let policy = values::read_token_bucket(ruby, policy)?;
131
+ Ok(Self::from(TokenBucketCore::new(policy)))
132
+ }
133
+
134
+ /// Raises `RangeError` for more tokens than the capacity.
135
+ fn restored(
136
+ ruby: &Ruby,
137
+ policy: Value,
138
+ tokens: Value,
139
+ refilled_at: Value,
140
+ ) -> Result<Self, Error> {
141
+ let policy = values::read_token_bucket(ruby, policy)?;
142
+ let tokens = integer::<u64>(tokens, "tokens")?;
143
+ let refilled_at = instant(refilled_at, "refilled_at")?;
144
+ TokenBucketCore::restored(policy, tokens, refilled_at)
145
+ .map(Self::from)
146
+ .ok_or_else(|| {
147
+ Error::new(
148
+ ruby.exception_range_error(),
149
+ "tokens must not exceed the capacity",
150
+ )
151
+ })
152
+ }
153
+
154
+ const fn from(core: TokenBucketCore) -> Self {
155
+ Self {
156
+ core: RefCell::new(core),
157
+ }
158
+ }
159
+
160
+ fn check(ruby: &Ruby, this: Obj<Self>, now: Value) -> Result<Value, Error> {
161
+ check(ruby, this, &this.core, now)
162
+ }
163
+
164
+ fn peek(ruby: &Ruby, this: &Self, now: Value) -> Result<Value, Error> {
165
+ peek(ruby, &this.core, now)
166
+ }
167
+
168
+ fn retry_after(ruby: &Ruby, this: &Self, now: Value) -> Result<Integer, Error> {
169
+ retry_after(ruby, &this.core, now)
170
+ }
171
+
172
+ fn refund(this: Obj<Self>) -> Result<(), Error> {
173
+ refund(this, &this.core)
174
+ }
175
+
176
+ fn policy(ruby: &Ruby, this: &Self) -> Result<Value, Error> {
177
+ let policy = this.core.borrow().policy();
178
+ values::token_bucket_value(ruby, policy)
179
+ }
180
+
181
+ fn tokens(&self) -> u64 {
182
+ self.core.borrow().tokens()
183
+ }
184
+
185
+ fn refilled_at(ruby: &Ruby, this: &Self) -> Integer {
186
+ nanoseconds(ruby, this.core.borrow().refilled_at())
187
+ }
188
+ }
189
+
190
+ #[magnus::wrap(class = "ThrottleMachines::FixedWindow", free_immediately, size)]
191
+ struct FixedWindow {
192
+ core: RefCell<FixedWindowCore>,
193
+ }
194
+
195
+ impl FixedWindow {
196
+ fn new(ruby: &Ruby, policy: Value) -> Result<Self, Error> {
197
+ let policy = values::read_fixed_window(ruby, policy)?;
198
+ Ok(Self::from(FixedWindowCore::new(policy)))
199
+ }
200
+
201
+ /// Raises `RangeError` for a count past the limit.
202
+ fn restored(
203
+ ruby: &Ruby,
204
+ policy: Value,
205
+ count: Value,
206
+ window_start: Value,
207
+ ) -> Result<Self, Error> {
208
+ let policy = values::read_fixed_window(ruby, policy)?;
209
+ let count = integer::<u64>(count, "count")?;
210
+ let window_start = instant(window_start, "window_start")?;
211
+ FixedWindowCore::restored(policy, count, window_start)
212
+ .map(Self::from)
213
+ .ok_or_else(|| {
214
+ Error::new(
215
+ ruby.exception_range_error(),
216
+ "count must not exceed the limit",
217
+ )
218
+ })
219
+ }
220
+
221
+ const fn from(core: FixedWindowCore) -> Self {
222
+ Self {
223
+ core: RefCell::new(core),
224
+ }
225
+ }
226
+
227
+ fn check(ruby: &Ruby, this: Obj<Self>, now: Value) -> Result<Value, Error> {
228
+ check(ruby, this, &this.core, now)
229
+ }
230
+
231
+ fn peek(ruby: &Ruby, this: &Self, now: Value) -> Result<Value, Error> {
232
+ peek(ruby, &this.core, now)
233
+ }
234
+
235
+ fn retry_after(ruby: &Ruby, this: &Self, now: Value) -> Result<Integer, Error> {
236
+ retry_after(ruby, &this.core, now)
237
+ }
238
+
239
+ fn refund(this: Obj<Self>) -> Result<(), Error> {
240
+ refund(this, &this.core)
241
+ }
242
+
243
+ fn policy(ruby: &Ruby, this: &Self) -> Result<Value, Error> {
244
+ let policy = this.core.borrow().policy();
245
+ values::fixed_window_value(ruby, policy)
246
+ }
247
+
248
+ fn count(&self) -> u64 {
249
+ self.core.borrow().count()
250
+ }
251
+
252
+ fn window_start(ruby: &Ruby, this: &Self) -> Integer {
253
+ nanoseconds(ruby, this.core.borrow().window_start())
254
+ }
255
+ }