trypema 2.1.0

High-performance rate limiting primitives in Rust, designed for concurrency safety, low overhead, and predictable latency.
Documentation
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
use super::*;

#[derive(Debug)]
struct AcceptingTransition {
    commit: AbsoluteHybridCommit,
    previous_accept_limit: u64,
    retry_after_ms: u128,
    remaining_after_waiting: u64,
    committed_total: u64,
}

#[derive(Debug)]
enum LocalAdmission {
    Allowed,
    Rejected(RateLimitDecision),
    Refresh,
    Exhausted(AcceptingTransition),
}

#[derive(Debug)]
pub(super) struct ResolvedRedisState {
    pub(super) key: RedisKey,
    pub(super) current_total: u64,
    pub(super) window_limit: Option<f64>,
    pub(super) oldest_bucket_ttl: Option<u64>,
    pub(super) oldest_bucket_count: Option<u64>,
    pub(super) state_revision: StateRevision,
}

impl AbsoluteHybridRateLimiter {
    fn evaluate_local_state(
        &self,
        key: &RedisKey,
        state: &AbsoluteRedisLimitingState,
        check_count: u64,
        increment: u64,
    ) -> Result<LocalAdmission, TrypemaError> {
        match state {
            AbsoluteRedisLimitingState::Undefined => Ok(LocalAdmission::Refresh),
            AbsoluteRedisLimitingState::Rejecting {
                time_instant,
                ttl_ms,
                count_after_release,
                ..
            } => {
                let elapsed_ms = mutex_lock(time_instant, "rejecting.time_instant")?
                    .elapsed()
                    .as_millis();
                let ttl_ms = *mutex_lock(ttl_ms, "rejecting.ttl_ms")? as u128;

                if elapsed_ms >= ttl_ms {
                    return Ok(LocalAdmission::Refresh);
                }

                let remaining_after_waiting =
                    *mutex_lock(count_after_release, "rejecting.count_after_release")?;

                Ok(LocalAdmission::Rejected(RateLimitDecision::Rejected {
                    window_size: self.window_size,
                    retry_after: duration_from_milliseconds(ttl_ms.saturating_sub(elapsed_ms)),
                    remaining_after_waiting,
                }))
            }
            AbsoluteRedisLimitingState::Accepting {
                window_limit,
                accept_limit,
                starting_count,
                count,
                time_instant,
                oldest_bucket_ttl,
                oldest_bucket_count,
                last_modified,
                state_revision,
            } => {
                let local_count = count.load(Ordering::Acquire);
                let accept_limit = *mutex_lock(accept_limit, "accepting.accept_limit")?;

                if check_count <= accept_limit.saturating_sub(local_count) {
                    *mutex_lock(last_modified, "accepting.last_modified")? = Instant::now();
                    count.fetch_add(increment, Ordering::AcqRel);

                    return Ok(LocalAdmission::Allowed);
                }

                let starting_count = *mutex_lock(starting_count, "accepting.starting_count")?;
                let committed_total = starting_count.saturating_add(local_count);
                let elapsed_ms = mutex_lock(time_instant, "accepting.time_instant")?
                    .elapsed()
                    .as_millis();
                let retry_after_ms =
                    match *mutex_lock(oldest_bucket_ttl, "accepting.oldest_bucket_ttl")? {
                        Some(oldest_bucket_ttl) => {
                            (oldest_bucket_ttl as u128).saturating_sub(elapsed_ms)
                        }
                        None => self.window_size.as_milliseconds(),
                    };
                let remaining_after_waiting =
                    (*mutex_lock(oldest_bucket_count, "accepting.oldest_bucket_count")?)
                        .unwrap_or(committed_total);

                if local_count < accept_limit {
                    return Ok(LocalAdmission::Rejected(RateLimitDecision::Rejected {
                        window_size: self.window_size,
                        retry_after: duration_from_milliseconds(retry_after_ms),
                        remaining_after_waiting,
                    }));
                }

                Ok(LocalAdmission::Exhausted(AcceptingTransition {
                    commit: AbsoluteHybridCommit {
                        key: key.clone(),
                        window_limit: *mutex_lock(window_limit, "accepting.window_limit")?,
                        count: local_count,
                        state_revision: *mutex_lock(state_revision, "accepting.state_revision")?,
                    },
                    previous_accept_limit: accept_limit,
                    retry_after_ms,
                    remaining_after_waiting,
                    committed_total,
                }))
            }
        }
    }

    fn restore_accepting_state(
        &self,
        commit: &AbsoluteHybridCommit,
        previous_accept_limit: u64,
    ) -> Result<(), TrypemaError> {
        if let Entry::Occupied(mut entry) = self.limiting_state.entry(commit.key.clone())
            && let AbsoluteRedisLimitingState::Accepting {
                accept_limit,
                count,
                ..
            } = entry.get_mut()
        {
            count.store(commit.count, Ordering::Release);
            *mutex_lock(accept_limit, "accepting.accept_limit")? = previous_accept_limit;
        }

        Ok(())
    }

    pub(super) async fn flush_local_pending_for_lifecycle(
        &self,
        key: &RedisKey,
    ) -> Result<bool, TrypemaError> {
        let Some(state) = self.limiting_state.get(key) else {
            return Ok(false);
        };
        let has_pending = matches!(state.deref(), AbsoluteRedisLimitingState::Accepting { count, .. }
            if count.load(Ordering::Acquire) > 0);
        drop(state);

        if !has_pending {
            return Ok(false);
        }

        let frozen = match self.limiting_state.entry(key.clone()) {
            Entry::Occupied(mut entry) => match entry.get_mut() {
                AbsoluteRedisLimitingState::Accepting {
                    window_limit,
                    accept_limit,
                    count,
                    state_revision,
                    ..
                } => {
                    let local_count = count.load(Ordering::Acquire);
                    if local_count == 0 {
                        return Ok(false);
                    }

                    let previous_accept_limit =
                        *mutex_lock(accept_limit, "accepting.accept_limit")?;
                    let commit = AbsoluteHybridCommit {
                        key: key.clone(),
                        window_limit: *mutex_lock(window_limit, "accepting.window_limit")?,
                        count: local_count,
                        state_revision: *mutex_lock(state_revision, "accepting.state_revision")?,
                    };
                    count.store(0, Ordering::Release);
                    *mutex_lock(accept_limit, "accepting.accept_limit")? = 0;
                    Some((commit, previous_accept_limit))
                }
                AbsoluteRedisLimitingState::Undefined
                | AbsoluteRedisLimitingState::Rejecting { .. } => None,
            },
            Entry::Vacant(_) => None,
        };

        let Some((commit, previous_accept_limit)) = frozen else {
            return Ok(false);
        };

        let _maintenance_guard = self.maintenance_lock.read().await;
        if let Err(err) = self
            .redis_proxy
            .batch_commit_state(std::slice::from_ref(&commit))
            .await
        {
            self.restore_accepting_state(&commit, previous_accept_limit)?;
            return Err(err);
        }

        Ok(true)
    }

    pub(super) async fn resolve_redis_state_and_commit(
        &self,
        read_state_result: AbsoluteHybridRedisProxyReadStateResult,
    ) -> Result<ResolvedRedisState, TrypemaError> {
        let AbsoluteHybridRedisProxyReadStateResult {
            key,
            current_total_count: redis_total,
            window_limit,
            oldest_bucket_ttl,
            oldest_bucket_count,
            state_revision,
        } = read_state_result;

        let mut current_total = redis_total;
        let mut window_limit = window_limit;

        let state = self.get_or_create_limiting_state(&key);

        match state.deref() {
            AbsoluteRedisLimitingState::Undefined => {
                drop(state);
            }
            AbsoluteRedisLimitingState::Rejecting {
                committed_count,
                committed_at,
                state_revision: local_state_revision,
                ..
            } => {
                let window_size_ms = self.window_size.as_milliseconds();

                if *mutex_lock(local_state_revision, "rejecting.state_revision")? == state_revision
                    && committed_at.elapsed().as_millis() < window_size_ms
                {
                    current_total = current_total.max(*committed_count);
                }

                drop(state);
            }
            AbsoluteRedisLimitingState::Accepting { .. } => {
                drop(state);
                let frozen = match self.limiting_state.entry(key.clone()) {
                    Entry::Occupied(mut entry) => match entry.get_mut() {
                        AbsoluteRedisLimitingState::Accepting {
                            window_limit: local_window_limit,
                            accept_limit,
                            count,
                            state_revision,
                            ..
                        } => {
                            let local_count = count.load(Ordering::Acquire);
                            let previous_accept_limit =
                                *mutex_lock(accept_limit, "accepting.accept_limit")?;
                            let local_window_limit =
                                *mutex_lock(local_window_limit, "accepting.window_limit")?;
                            let local_state_revision =
                                *mutex_lock(state_revision, "accepting.state_revision")?;

                            count.store(0, Ordering::Release);
                            *mutex_lock(accept_limit, "accepting.accept_limit")? = 0;

                            Some((
                                local_count,
                                previous_accept_limit,
                                local_window_limit,
                                local_state_revision,
                            ))
                        }
                        AbsoluteRedisLimitingState::Undefined
                        | AbsoluteRedisLimitingState::Rejecting { .. } => None,
                    },
                    Entry::Vacant(_) => None,
                };

                if let Some((
                    local_count,
                    previous_accept_limit,
                    local_window_limit,
                    local_state_revision,
                )) = frozen
                {
                    window_limit.get_or_insert(local_window_limit);
                    current_total = current_total.saturating_add(local_count);

                    if local_count > 0 {
                        let commit = AbsoluteHybridCommit {
                            key: key.clone(),
                            window_limit: local_window_limit,
                            count: local_count,
                            state_revision: local_state_revision,
                        };

                        let _maintenance_guard = self.maintenance_lock.read().await;
                        if let Err(err) = self
                            .redis_proxy
                            .batch_commit_state(std::slice::from_ref(&commit))
                            .await
                        {
                            self.restore_accepting_state(&commit, previous_accept_limit)?;
                            return Err(err);
                        }
                    }
                }
            }
        }

        Ok(ResolvedRedisState {
            key,
            current_total,
            window_limit,
            oldest_bucket_ttl,
            oldest_bucket_count,
            state_revision,
        })
    }

    fn reset_to_undefined(&self, key: &RedisKey) {
        let state = self.get_or_create_limiting_state(key);

        if matches!(state.deref(), AbsoluteRedisLimitingState::Undefined) {
            return;
        }

        drop(state);

        match self.limiting_state.entry(key.clone()) {
            Entry::Occupied(mut entry) => {
                *entry.get_mut() = AbsoluteRedisLimitingState::Undefined;
            }
            Entry::Vacant(entry) => {
                entry.insert(AbsoluteRedisLimitingState::Undefined);
            }
        }
    }

    fn store_rejecting_state(
        &self,
        state: &ResolvedRedisState,
        retry_after_ms: u64,
        remaining_after_waiting: u64,
    ) -> Result<(), TrypemaError> {
        let time_instant = Instant::now();
        let current = self.get_or_create_limiting_state(&state.key);

        if let AbsoluteRedisLimitingState::Rejecting {
            time_instant: current_time_instant,
            ttl_ms,
            count_after_release,
            state_revision: current_state_revision,
            ..
        } = current.deref()
        {
            // Refresh only the Redis-derived rejection interval. `committed_at`
            // must keep the time of the actual local commit; refreshing it here
            // would keep an expired committed count alive indefinitely.
            *mutex_lock(current_time_instant, "rejecting.time_instant")? = time_instant;
            *mutex_lock(ttl_ms, "rejecting.ttl_ms")? = retry_after_ms;
            *mutex_lock(count_after_release, "rejecting.count_after_release")? =
                remaining_after_waiting;
            *mutex_lock(current_state_revision, "rejecting.state_revision")? = state.state_revision;
            return Ok(());
        }

        drop(current);

        let rejecting = AbsoluteRedisLimitingState::Rejecting {
            time_instant: Mutex::new(time_instant),
            ttl_ms: Mutex::new(retry_after_ms),
            count_after_release: Mutex::new(remaining_after_waiting),
            committed_count: state.current_total,
            committed_at: time_instant,
            state_revision: Mutex::new(state.state_revision),
        };

        match self.limiting_state.entry(state.key.clone()) {
            Entry::Occupied(mut entry) => {
                *entry.get_mut() = rejecting;
            }
            Entry::Vacant(entry) => {
                entry.insert(rejecting);
            }
        }

        Ok(())
    }

    fn store_accepting_state(
        &self,
        state: &ResolvedRedisState,
        window_limit: f64,
        increment: u64,
    ) -> Result<(), TrypemaError> {
        let time_instant = Instant::now();
        let accept_limit = (window_limit as u64).saturating_sub(state.current_total);
        let current = self.get_or_create_limiting_state(&state.key);

        if let AbsoluteRedisLimitingState::Accepting {
            window_limit: current_window_limit,
            accept_limit: current_accept_limit,
            starting_count,
            count,
            time_instant: current_time_instant,
            oldest_bucket_ttl,
            oldest_bucket_count,
            last_modified,
            state_revision,
        } = current.deref()
        {
            *mutex_lock(current_window_limit, "accepting.window_limit")? = window_limit;
            // Any pending local count was committed before this refresh. Keep it in the
            // inferred baseline instead of falling back to the pre-commit Redis total.
            *mutex_lock(starting_count, "accepting.starting_count")? = state.current_total;
            *mutex_lock(current_time_instant, "accepting.time_instant")? = time_instant;
            *mutex_lock(last_modified, "accepting.last_modified")? = time_instant;
            *mutex_lock(oldest_bucket_ttl, "accepting.oldest_bucket_ttl")? =
                state.oldest_bucket_ttl;
            *mutex_lock(oldest_bucket_count, "accepting.oldest_bucket_count")? =
                state.oldest_bucket_count;
            count.store(increment, Ordering::Release);
            *mutex_lock(current_accept_limit, "accepting.accept_limit")? = accept_limit;
            *mutex_lock(state_revision, "accepting.state_revision")? = state.state_revision;
            return Ok(());
        }

        drop(current);

        let accepting = AbsoluteRedisLimitingState::Accepting {
            window_limit: Mutex::new(window_limit),
            accept_limit: Mutex::new(accept_limit),
            starting_count: Mutex::new(state.current_total),
            count: AtomicU64::new(increment),
            time_instant: Mutex::new(time_instant),
            oldest_bucket_ttl: Mutex::new(state.oldest_bucket_ttl),
            oldest_bucket_count: Mutex::new(state.oldest_bucket_count),
            last_modified: Mutex::new(time_instant),
            state_revision: Mutex::new(state.state_revision),
        };

        match self.limiting_state.entry(state.key.clone()) {
            Entry::Occupied(mut entry) => {
                *entry.get_mut() = accepting;
            }
            Entry::Vacant(entry) => {
                entry.insert(accepting);
            }
        }

        Ok(())
    }

    async fn read_redis_and_reset_state(
        &self,
        key: &RedisKey,
        check_count: u64,
        increment: u64,
        rate_limit: Option<&RateLimit>,
    ) -> Result<RateLimitDecision, TrypemaError> {
        let read_state_result =
            self.redis_proxy.read_state(key).await.map_err(|err| {
                TrypemaError::CustomError(format!("Failed to read state: {err:?}"))
            })?;

        self.reset_single_state_from_read_result(
            read_state_result,
            check_count,
            increment,
            rate_limit,
        )
        .await
    }

    pub(super) async fn reset_single_state_from_read_result(
        &self,
        read_state_result: AbsoluteHybridRedisProxyReadStateResult,
        check_count: u64,
        increment: u64,
        rate_limit: Option<&RateLimit>,
    ) -> Result<RateLimitDecision, TrypemaError> {
        let state = self
            .resolve_redis_state_and_commit(read_state_result)
            .await?;

        let window_limit = match state.window_limit {
            Some(window_limit) => window_limit,
            None => {
                let Some(rate_limit) = rate_limit else {
                    self.reset_to_undefined(&state.key);

                    return Ok(RateLimitDecision::Allowed);
                };

                (self.window_size.as_seconds() as f64) * rate_limit.as_per_second()
            }
        };

        if state.current_total.saturating_add(check_count) > window_limit as u64 {
            let retry_after_ms = state.oldest_bucket_ttl.unwrap_or(0);
            let remaining_after_waiting = state.oldest_bucket_count.unwrap_or(0);

            self.store_rejecting_state(&state, retry_after_ms, remaining_after_waiting)?;

            return Ok(RateLimitDecision::Rejected {
                window_size: self.window_size,
                retry_after: duration_from_milliseconds(u128::from(retry_after_ms)),
                remaining_after_waiting,
            });
        }

        self.store_accepting_state(&state, window_limit, increment)?;

        Ok(RateLimitDecision::Allowed)
    }

    pub(super) async fn send_commit(
        &self,
        commit: AbsoluteHybridCommit,
    ) -> Result<(), TrypemaError> {
        self.commiter_sender
            .send(commit.into())
            .await
            .map_err(|err| TrypemaError::CustomError(format!("Failed to send commit: {err:?}")))?;

        Ok(())
    } // end method send_commit

    pub(super) async fn is_allowed_with_count_increment(
        &self,
        key: &RedisKey,
        check_count: u64,
        increment: u64,
        rate_limit: Option<&RateLimit>,
    ) -> Result<RateLimitDecision, TrypemaError> {
        let state = self.get_or_create_limiting_state(key);

        match self.evaluate_local_state(key, state.deref(), check_count, increment)? {
            LocalAdmission::Allowed => return Ok(RateLimitDecision::Allowed),
            LocalAdmission::Rejected(decision) => return Ok(decision),
            LocalAdmission::Refresh | LocalAdmission::Exhausted(_) => {}
        }

        drop(state);

        self.coordinate_local_transition(key, check_count, increment, rate_limit)
            .await
    } // end method is_allowed_with_count_increment

    async fn coordinate_local_transition(
        &self,
        key: &RedisKey,
        check_count: u64,
        increment: u64,
        rate_limit: Option<&RateLimit>,
    ) -> Result<RateLimitDecision, TrypemaError> {
        let reset_lock = self.get_or_create_reset_lock(key);
        let _reset_guard = reset_lock.lock().await;

        let state = self.get_or_create_limiting_state(key);

        match self.evaluate_local_state(key, state.deref(), check_count, increment)? {
            LocalAdmission::Allowed => return Ok(RateLimitDecision::Allowed),
            LocalAdmission::Rejected(decision) => return Ok(decision),
            LocalAdmission::Refresh => {
                drop(state);
                return self
                    .read_redis_and_reset_state(key, check_count, increment, rate_limit)
                    .await;
            }
            LocalAdmission::Exhausted(_) => drop(state),
        }

        let transition = match self.limiting_state.entry(key.clone()) {
            Entry::Occupied(mut entry) => {
                let admission =
                    self.evaluate_local_state(key, entry.get(), check_count, increment)?;
                match admission {
                    LocalAdmission::Allowed => return Ok(RateLimitDecision::Allowed),
                    LocalAdmission::Rejected(decision) => return Ok(decision),
                    LocalAdmission::Refresh => None,
                    LocalAdmission::Exhausted(transition) => {
                        let AbsoluteRedisLimitingState::Accepting {
                            accept_limit,
                            count,
                            ..
                        } = entry.get_mut()
                        else {
                            return Err(TrypemaError::CustomError(
                                "absolute hybrid state changed during exclusive revalidation"
                                    .to_string(),
                            ));
                        };

                        count.store(0, Ordering::Release);
                        *mutex_lock(accept_limit, "accepting.accept_limit")? = 0;
                        Some(transition)
                    }
                }
            }
            Entry::Vacant(_) => None,
        };

        let Some(transition) = transition else {
            return self
                .read_redis_and_reset_state(key, check_count, increment, rate_limit)
                .await;
        };

        let _maintenance_guard = self.maintenance_lock.read().await;
        if let Err(err) = self
            .redis_proxy
            .batch_commit_state(std::slice::from_ref(&transition.commit))
            .await
        {
            self.restore_accepting_state(&transition.commit, transition.previous_accept_limit)?;
            return Err(err);
        }

        let state = ResolvedRedisState {
            key: key.clone(),
            current_total: transition.committed_total,
            window_limit: Some(transition.commit.window_limit),
            oldest_bucket_ttl: Some(transition.retry_after_ms as u64),
            oldest_bucket_count: Some(transition.remaining_after_waiting),
            state_revision: transition.commit.state_revision,
        };

        self.store_rejecting_state(
            &state,
            transition.retry_after_ms as u64,
            transition.remaining_after_waiting,
        )?;

        Ok(RateLimitDecision::Rejected {
            window_size: self.window_size,
            retry_after: duration_from_milliseconds(transition.retry_after_ms),
            remaining_after_waiting: transition.remaining_after_waiting,
        })
    }
}