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