token_bucket/fixed_window/impl.rs
1use super::*;
2
3/// Configuration constructors and accessors for `FixedWindowConfig`.
4impl FixedWindowConfig {
5 /// Creates a `FixedWindowConfig` allowing `limit` units per `window_ns` nanoseconds.
6 ///
7 /// # Arguments
8 ///
9 /// - `u64` - Maximum units permitted per window (`1..=u32::MAX`).
10 /// - `u64` - Window duration in nanoseconds (`>= 1`).
11 ///
12 /// # Returns
13 ///
14 /// - `Result<Self, RateLimitError>` - Validated configuration or an error.
15 #[inline(always)]
16 pub fn from_nanos(limit: u64, window_ns: u64) -> Result<Self, RateLimitError> {
17 if limit == 0 || limit > MAX_FIXED_WINDOW_LIMIT {
18 return Err(RateLimitError::InvalidLimit);
19 }
20 if window_ns == 0 {
21 return Err(RateLimitError::ZeroPeriod);
22 }
23 let window_div: FastDivU64 = FastDivU64::new(window_ns);
24 let count_bits: u32 = (PACKED_STATE_BITS - limit.leading_zeros()).max(1);
25 let count_mask: u64 = (1u64 << count_bits) - 1;
26 let window_bits: u32 = PACKED_STATE_BITS - count_bits;
27 let window_mask: u64 = (1u64 << window_bits) - 1;
28 let window_half: u64 = 1u64 << (window_bits - 1);
29 Ok(Self {
30 limit,
31 window_ns,
32 window_div,
33 count_bits,
34 count_mask,
35 window_mask,
36 window_half,
37 })
38 }
39
40 /// Creates a `FixedWindowConfig` allowing `limit` units per `window` duration.
41 ///
42 /// # Arguments
43 ///
44 /// - `u64` - Maximum units permitted per window (`1..=u32::MAX`).
45 /// - `Duration` - Fixed window duration (`>= 1ns`).
46 ///
47 /// # Returns
48 ///
49 /// - `Result<Self, RateLimitError>` - Validated configuration or an error.
50 #[inline(always)]
51 pub fn new(limit: u64, window: Duration) -> Result<Self, RateLimitError> {
52 let nanos: u128 = window.as_nanos();
53 if nanos == 0 {
54 return Err(RateLimitError::ZeroPeriod);
55 }
56 if nanos > u64::MAX as u128 {
57 return Err(RateLimitError::Overflow);
58 }
59 Self::from_nanos(limit, nanos as u64)
60 }
61
62 /// Returns the configured per-window request limit.
63 ///
64 /// # Arguments
65 ///
66 /// - `&Self` - The fixed-window configuration.
67 ///
68 /// # Returns
69 ///
70 /// - `u64` - Maximum requests per window.
71 #[inline(always)]
72 pub fn get_limit(&self) -> u64 {
73 self.limit
74 }
75
76 /// Returns the configured window duration in nanoseconds.
77 ///
78 /// # Arguments
79 ///
80 /// - `&Self` - The fixed-window configuration.
81 ///
82 /// # Returns
83 ///
84 /// - `u64` - Window length in nanoseconds.
85 #[inline(always)]
86 pub fn get_window_ns(&self) -> u64 {
87 self.window_ns
88 }
89
90 /// Returns the precomputed reciprocal divider for `window_ns`.
91 ///
92 /// # Returns
93 ///
94 /// - `&FastDivU64` - Reciprocal divider reference.
95 #[inline(always)]
96 pub(crate) fn get_window_div(&self) -> &FastDivU64 {
97 &self.window_div
98 }
99
100 /// Computes exact `now_ns / window_ns` without hardware division.
101 ///
102 /// # Arguments
103 ///
104 /// - `u64` - Monotonic timestamp in nanoseconds.
105 ///
106 /// # Returns
107 ///
108 /// - `u64` - Window index.
109 #[inline(always)]
110 pub(crate) fn div_window(&self, now_ns: u64) -> u64 {
111 self.get_window_div().div(now_ns)
112 }
113
114 /// Returns the bit width reserved for the packed counter.
115 ///
116 /// # Arguments
117 ///
118 /// - `&Self` - The fixed-window configuration.
119 ///
120 /// # Returns
121 ///
122 /// - `u32` - Counter bit width.
123 #[inline(always)]
124 pub(crate) fn get_count_bits(&self) -> u32 {
125 self.count_bits
126 }
127
128 /// Returns the bitmask for extracting the packed counter.
129 ///
130 /// # Arguments
131 ///
132 /// - `&Self` - The fixed-window configuration.
133 ///
134 /// # Returns
135 ///
136 /// - `u64` - Counter mask.
137 #[inline(always)]
138 pub(crate) fn get_count_mask(&self) -> u64 {
139 self.count_mask
140 }
141
142 /// Returns the bitmask for wrapping window indices.
143 ///
144 /// # Arguments
145 ///
146 /// - `&Self` - The fixed-window configuration.
147 ///
148 /// # Returns
149 ///
150 /// - `u64` - Window index mask.
151 #[inline(always)]
152 pub(crate) fn get_window_mask(&self) -> u64 {
153 self.window_mask
154 }
155
156 /// Returns the half-ring threshold for modular window ordering.
157 ///
158 /// # Arguments
159 ///
160 /// - `&Self` - The fixed-window configuration.
161 ///
162 /// # Returns
163 ///
164 /// - `u64` - Half-ring threshold.
165 #[inline(always)]
166 pub(crate) fn get_window_half(&self) -> u64 {
167 self.window_half
168 }
169}
170
171/// Default empty `FixedWindowCell` initialized at window `0`, count `0`.
172impl Default for FixedWindowCell {
173 /// Creates a `FixedWindowCell` at window `0` with zero usage.
174 #[inline(always)]
175 fn default() -> Self {
176 Self::new()
177 }
178}
179
180/// Lock-free atomic fixed-window operations on `FixedWindowCell`.
181impl FixedWindowCell {
182 /// Creates an empty `FixedWindowCell` initialized at window `0`, count `0`.
183 #[inline(always)]
184 pub fn new() -> Self {
185 Self {
186 packed: AtomicU64::new(0),
187 }
188 }
189
190 /// Returns a reference to the packed atomic word.
191 ///
192 /// # Arguments
193 ///
194 /// - `&Self` - The fixed-window cell.
195 ///
196 /// # Returns
197 ///
198 /// - `&AtomicU64` - Reference to the packed state word.
199 #[inline(always)]
200 pub(crate) fn get_packed(&self) -> &AtomicU64 {
201 &self.packed
202 }
203
204 /// Resets the cell back to window `0` with count `0`.
205 ///
206 /// # Arguments
207 ///
208 /// - `&Self` - The fixed-window cell.
209 #[inline(always)]
210 pub fn reset(&self) {
211 self.get_packed().store(0, Ordering::Release);
212 }
213
214 /// Returns whether the cell has no active usage in the current window at `now_ns`.
215 ///
216 /// # Arguments
217 ///
218 /// - `&Self` - The fixed-window cell.
219 /// - `&FixedWindowConfig` - Fixed-window configuration.
220 /// - `u64` - Current monotonic timestamp in nanoseconds.
221 ///
222 /// # Returns
223 ///
224 /// - `bool` - `true` when the cell belongs to a prior window or has count `0`.
225 #[inline(always)]
226 pub fn is_idle_at_ns(&self, config: &FixedWindowConfig, now_ns: u64) -> bool {
227 Self::is_idle_atomic(self.get_packed(), config, now_ns)
228 }
229
230 /// Inspects current fixed-window availability at `now_ns` without mutating state.
231 ///
232 /// # Arguments
233 ///
234 /// - `&Self` - The fixed-window cell.
235 /// - `&FixedWindowConfig` - Fixed-window configuration.
236 /// - `u64` - Current monotonic timestamp in nanoseconds.
237 ///
238 /// # Returns
239 ///
240 /// - `RateLimitDecision` - Non-mutating availability snapshot.
241 #[inline(always)]
242 pub fn peek_at_ns(&self, config: &FixedWindowConfig, now_ns: u64) -> RateLimitDecision {
243 Self::peek_atomic(self.get_packed(), config, now_ns)
244 }
245
246 /// Atomically checks and consumes `cost` units at monotonic timestamp `now_ns`.
247 ///
248 /// # Arguments
249 ///
250 /// - `&Self` - The fixed-window cell.
251 /// - `&FixedWindowConfig` - Fixed-window configuration.
252 /// - `u64` - Current monotonic timestamp in nanoseconds.
253 /// - `u64` - Request cost in units.
254 ///
255 /// # Returns
256 ///
257 /// - `RateLimitDecision` - Admission decision and nanosecond timings.
258 #[inline(always)]
259 pub fn check_n_at_ns(
260 &self,
261 config: &FixedWindowConfig,
262 now_ns: u64,
263 cost: u64,
264 ) -> RateLimitDecision {
265 Self::check_n_atomic(self.get_packed(), config, now_ns, cost)
266 }
267
268 /// Checks whether a raw packed atomic fixed-window word is idle at `now_ns`.
269 ///
270 /// # Arguments
271 ///
272 /// - `&AtomicU64` - Atomic packed state word.
273 /// - `&FixedWindowConfig` - Fixed-window configuration.
274 /// - `u64` - Current monotonic timestamp in nanoseconds.
275 ///
276 /// # Returns
277 ///
278 /// - `bool` - `true` when count is zero or belongs to a prior window.
279 #[inline(always)]
280 pub(crate) fn is_idle_atomic(
281 atomic: &AtomicU64,
282 config: &FixedWindowConfig,
283 now_ns: u64,
284 ) -> bool {
285 let state: u64 = atomic.load(Ordering::Relaxed);
286 let stored_count: u64 = state & config.get_count_mask();
287 if stored_count == 0 {
288 return true;
289 }
290 let stored_win: u64 = state >> config.get_count_bits();
291 let cur_win: u64 = config.div_window(now_ns) & config.get_window_mask();
292 let forward_diff: u64 = cur_win.wrapping_sub(stored_win) & config.get_window_mask();
293 forward_diff > 0 && forward_diff < config.get_window_half()
294 }
295
296 /// Non-mutating fixed-window availability check against a raw atomic word.
297 ///
298 /// # Arguments
299 ///
300 /// - `&AtomicU64` - Atomic packed state word.
301 /// - `&FixedWindowConfig` - Fixed-window configuration.
302 /// - `u64` - Current monotonic timestamp in nanoseconds.
303 ///
304 /// # Returns
305 ///
306 /// - `RateLimitDecision` - Availability snapshot.
307 #[inline(always)]
308 pub(crate) fn peek_atomic(
309 atomic: &AtomicU64,
310 config: &FixedWindowConfig,
311 now_ns: u64,
312 ) -> RateLimitDecision {
313 let state: u64 = atomic.load(Ordering::Relaxed);
314 let cur_win_full: u64 = config.div_window(now_ns);
315 let base_rem_ns: u64 =
316 config.get_window_ns() - (now_ns - cur_win_full.wrapping_mul(config.get_window_ns()));
317 let (ahead_diff, used): (u64, u64) =
318 Self::resolve_window_at(config, state, cur_win_full & config.get_window_mask());
319 let reset_after_ns: u64 = if ahead_diff == 0 {
320 base_rem_ns
321 } else {
322 base_rem_ns.saturating_add(ahead_diff.saturating_mul(config.get_window_ns()))
323 };
324 let limit: u64 = config.get_limit();
325 let remaining: u64 = limit.saturating_sub(used);
326 let allowed: bool = remaining >= 1;
327 let retry_after_ns: u64 = if allowed { 0 } else { reset_after_ns };
328 RateLimitDecision::new(allowed, remaining, reset_after_ns, retry_after_ns, limit)
329 }
330
331 /// Lock-free fixed-window check and consumption against a raw atomic word.
332 ///
333 /// # Arguments
334 ///
335 /// - `&AtomicU64` - Atomic packed state word.
336 /// - `&FixedWindowConfig` - Fixed-window configuration.
337 /// - `u64` - Current monotonic timestamp in nanoseconds.
338 /// - `u64` - Request cost in units.
339 ///
340 /// # Returns
341 ///
342 /// - `RateLimitDecision` - Admission decision and nanosecond timings.
343 #[inline(always)]
344 pub(crate) fn check_n_atomic(
345 atomic: &AtomicU64,
346 config: &FixedWindowConfig,
347 now_ns: u64,
348 cost: u64,
349 ) -> RateLimitDecision {
350 let limit: u64 = config.get_limit();
351 let count_bits: u32 = config.get_count_bits();
352 let window_mask: u64 = config.get_window_mask();
353 let window_ns: u64 = config.get_window_ns();
354 let cur_win_full: u64 = config.div_window(now_ns);
355 let cur_win_low: u64 = cur_win_full & window_mask;
356 let base_rem_ns: u64 = window_ns - (now_ns - cur_win_full.wrapping_mul(window_ns));
357 if cost == 0 {
358 let state: u64 = atomic.load(Ordering::Relaxed);
359 let (ahead_diff, used): (u64, u64) =
360 Self::resolve_window_at(config, state, cur_win_low);
361 let reset_after_ns: u64 = if ahead_diff == 0 {
362 base_rem_ns
363 } else {
364 base_rem_ns.saturating_add(ahead_diff.saturating_mul(window_ns))
365 };
366 return RateLimitDecision::new(
367 true,
368 limit.saturating_sub(used),
369 reset_after_ns,
370 0,
371 limit,
372 );
373 }
374 if cost > limit {
375 let state: u64 = atomic.load(Ordering::Relaxed);
376 let (ahead_diff, used): (u64, u64) =
377 Self::resolve_window_at(config, state, cur_win_low);
378 let reset_after_ns: u64 = if ahead_diff == 0 {
379 base_rem_ns
380 } else {
381 base_rem_ns.saturating_add(ahead_diff.saturating_mul(window_ns))
382 };
383 return RateLimitDecision::new(
384 false,
385 limit.saturating_sub(used),
386 reset_after_ns,
387 u64::MAX,
388 limit,
389 );
390 }
391 let count_mask: u64 = config.get_count_mask();
392 let mut current: u64 = atomic.load(Ordering::Relaxed);
393 loop {
394 if (current >> count_bits) == cur_win_low {
395 let used: u64 = current & count_mask;
396 let next_used: u64 = used + cost;
397 if next_used > limit {
398 return RateLimitDecision::new(
399 false,
400 limit.saturating_sub(used),
401 base_rem_ns,
402 base_rem_ns,
403 limit,
404 );
405 }
406 match atomic.compare_exchange_weak(
407 current,
408 current + cost,
409 Ordering::Relaxed,
410 Ordering::Relaxed,
411 ) {
412 Ok(_) => {
413 return RateLimitDecision::new(
414 true,
415 limit - next_used,
416 base_rem_ns,
417 0,
418 limit,
419 );
420 }
421 Err(observed) => {
422 current = observed;
423 continue;
424 }
425 }
426 }
427 let (ahead_diff, used): (u64, u64) =
428 Self::resolve_window_at(config, current, cur_win_low);
429 let next_used: u64 = used.saturating_add(cost);
430 if next_used > limit {
431 let reset_after_ns: u64 = if ahead_diff == 0 {
432 base_rem_ns
433 } else {
434 base_rem_ns.saturating_add(ahead_diff.saturating_mul(window_ns))
435 };
436 let remaining: u64 = limit.saturating_sub(used);
437 return RateLimitDecision::new(
438 false,
439 remaining,
440 reset_after_ns,
441 reset_after_ns,
442 limit,
443 );
444 }
445 let next_win_low: u64 = cur_win_low.wrapping_add(ahead_diff) & window_mask;
446 let next_packed: u64 = (next_win_low << count_bits) | next_used;
447 match atomic.compare_exchange_weak(
448 current,
449 next_packed,
450 Ordering::Relaxed,
451 Ordering::Relaxed,
452 ) {
453 Ok(_) => {
454 let reset_after_ns: u64 = if ahead_diff == 0 {
455 base_rem_ns
456 } else {
457 base_rem_ns.saturating_add(ahead_diff.saturating_mul(window_ns))
458 };
459 let remaining: u64 = limit - next_used;
460 return RateLimitDecision::new(true, remaining, reset_after_ns, 0, limit);
461 }
462 Err(observed) => {
463 current = observed;
464 }
465 }
466 }
467 }
468
469 /// Resolves `(ahead_diff, effective_used)` against precomputed `cur_win_low`.
470 ///
471 /// # Arguments
472 ///
473 /// - `&FixedWindowConfig` - Fixed-window configuration.
474 /// - `u64` - Loaded packed state word.
475 /// - `u64` - Masked current window index (`cur_win_full & window_mask`).
476 ///
477 /// # Returns
478 ///
479 /// - `(u64, u64)` - Tuple of `(ahead_windows, effective_used_count)`.
480 #[inline(always)]
481 pub(crate) fn resolve_window_at(
482 config: &FixedWindowConfig,
483 packed: u64,
484 cur_win_low: u64,
485 ) -> (u64, u64) {
486 let stored_win_low: u64 = packed >> config.get_count_bits();
487 let stored_count: u64 = packed & config.get_count_mask();
488 if stored_win_low == cur_win_low {
489 return (0, stored_count);
490 }
491 let forward_diff: u64 = cur_win_low.wrapping_sub(stored_win_low) & config.get_window_mask();
492 if forward_diff < config.get_window_half() {
493 (0, 0)
494 } else {
495 let ahead_diff: u64 =
496 stored_win_low.wrapping_sub(cur_win_low) & config.get_window_mask();
497 (ahead_diff, stored_count)
498 }
499 }
500
501 /// Computes remaining nanoseconds until the end of the window containing `now_ns`.
502 ///
503 /// # Arguments
504 ///
505 /// - `&FixedWindowConfig` - Fixed-window configuration.
506 /// - `u64` - Monotonic timestamp in nanoseconds.
507 ///
508 /// # Returns
509 ///
510 /// - `u64` - Nanoseconds until the next fixed window starts.
511 #[inline(always)]
512 pub(crate) fn current_window_remaining_ns(config: &FixedWindowConfig, now_ns: u64) -> u64 {
513 let window_ns: u64 = config.get_window_ns();
514 let cur_win: u64 = config.div_window(now_ns);
515 window_ns - (now_ns - cur_win.wrapping_mul(window_ns))
516 }
517}
518
519/// Core lock-free operations for `FixedWindowLimiter`.
520impl FixedWindowLimiter {
521 /// Creates a new `FixedWindowLimiter` from a validated `FixedWindowConfig`.
522 ///
523 /// # Arguments
524 ///
525 /// - `FixedWindowConfig` - Validated fixed-window configuration.
526 #[inline(always)]
527 pub fn new(config: FixedWindowConfig) -> Self {
528 Self {
529 config,
530 clock: MonotonicClock::new(),
531 cell: FixedWindowCell::new(),
532 }
533 }
534
535 /// Creates a new `FixedWindowLimiter` anchored at a caller-supplied `MonotonicClock`.
536 ///
537 /// # Arguments
538 ///
539 /// - `FixedWindowConfig` - Validated fixed-window configuration.
540 /// - `MonotonicClock` - Monotonic clock origin.
541 #[inline(always)]
542 pub fn with_clock(config: FixedWindowConfig, clock: MonotonicClock) -> Self {
543 Self {
544 config,
545 clock,
546 cell: FixedWindowCell::new(),
547 }
548 }
549
550 /// Returns the fixed-window configuration.
551 ///
552 /// # Arguments
553 ///
554 /// - `&Self` - The limiter instance.
555 ///
556 /// # Returns
557 ///
558 /// - `&FixedWindowConfig` - Reference to the configuration.
559 #[inline(always)]
560 pub fn get_config(&self) -> &FixedWindowConfig {
561 &self.config
562 }
563
564 /// Returns the embedded monotonic clock.
565 ///
566 /// # Arguments
567 ///
568 /// - `&Self` - The limiter instance.
569 ///
570 /// # Returns
571 ///
572 /// - `&MonotonicClock` - Reference to the clock.
573 #[inline(always)]
574 pub fn get_clock(&self) -> &MonotonicClock {
575 &self.clock
576 }
577
578 /// Returns a reference to the underlying atomic fixed-window cell.
579 ///
580 /// # Arguments
581 ///
582 /// - `&Self` - The limiter instance.
583 ///
584 /// # Returns
585 ///
586 /// - `&FixedWindowCell` - Reference to the atomic cell.
587 #[inline(always)]
588 pub(crate) fn get_cell(&self) -> &FixedWindowCell {
589 &self.cell
590 }
591
592 /// Checks and consumes 1 unit using the embedded monotonic clock.
593 ///
594 /// # Arguments
595 ///
596 /// - `&Self` - The limiter instance.
597 ///
598 /// # Returns
599 ///
600 /// - `RateLimitDecision` - Admission decision and nanosecond timings.
601 #[inline(always)]
602 pub fn check(&self) -> RateLimitDecision {
603 self.check_n_at_ns(self.get_clock().now_ns(), 1)
604 }
605
606 /// Checks and consumes `cost` units using the embedded monotonic clock.
607 ///
608 /// # Arguments
609 ///
610 /// - `&Self` - The limiter instance.
611 /// - `u64` - Number of quota units to consume.
612 ///
613 /// # Returns
614 ///
615 /// - `RateLimitDecision` - Admission decision and nanosecond timings.
616 #[inline(always)]
617 pub fn check_n(&self, cost: u64) -> RateLimitDecision {
618 self.check_n_at_ns(self.get_clock().now_ns(), cost)
619 }
620
621 /// Checks and consumes 1 unit at an explicit monotonic timestamp in nanoseconds.
622 ///
623 /// # Arguments
624 ///
625 /// - `&Self` - The limiter instance.
626 /// - `u64` - Monotonic timestamp in nanoseconds.
627 ///
628 /// # Returns
629 ///
630 /// - `RateLimitDecision` - Admission decision and nanosecond timings.
631 #[inline(always)]
632 pub fn check_at_ns(&self, now_ns: u64) -> RateLimitDecision {
633 self.get_cell().check_n_at_ns(self.get_config(), now_ns, 1)
634 }
635
636 /// Checks and consumes `cost` units at an explicit monotonic timestamp in nanoseconds.
637 ///
638 /// # Arguments
639 ///
640 /// - `&Self` - The limiter instance.
641 /// - `u64` - Monotonic timestamp in nanoseconds.
642 /// - `u64` - Number of quota units to consume.
643 ///
644 /// # Returns
645 ///
646 /// - `RateLimitDecision` - Admission decision and nanosecond timings.
647 #[inline(always)]
648 pub fn check_n_at_ns(&self, now_ns: u64, cost: u64) -> RateLimitDecision {
649 self.get_cell()
650 .check_n_at_ns(self.get_config(), now_ns, cost)
651 }
652
653 /// Inspects current availability without consuming quota.
654 ///
655 /// # Arguments
656 ///
657 /// - `&Self` - The limiter instance.
658 ///
659 /// # Returns
660 ///
661 /// - `RateLimitDecision` - Non-mutating availability snapshot.
662 #[inline(always)]
663 pub fn peek(&self) -> RateLimitDecision {
664 self.peek_at_ns(self.get_clock().now_ns())
665 }
666
667 /// Inspects availability at an explicit monotonic timestamp without consuming quota.
668 ///
669 /// # Arguments
670 ///
671 /// - `&Self` - The limiter instance.
672 /// - `u64` - Monotonic timestamp in nanoseconds.
673 ///
674 /// # Returns
675 ///
676 /// - `RateLimitDecision` - Non-mutating availability snapshot.
677 #[inline(always)]
678 pub fn peek_at_ns(&self, now_ns: u64) -> RateLimitDecision {
679 self.get_cell().peek_at_ns(self.get_config(), now_ns)
680 }
681
682 /// Resets the limiter counter back to zero.
683 ///
684 /// # Arguments
685 ///
686 /// - `&Self` - The limiter instance.
687 #[inline(always)]
688 pub fn reset(&self) {
689 self.get_cell().reset();
690 }
691}