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
use std::{collections::HashSet, sync::Arc};

use governor::{clock::DefaultClock, state::keyed::DefaultKeyedStateStore, RateLimiter};
pub use governor::{Jitter, Quota};
#[allow(unused_imports)]
pub use nonzero_ext::nonzero;

use crate::{
    core::{Handler, PredicateResult},
    ratelimit::{
        jitter::NoJitter,
        key::Key,
        method::{MethodDiscard, MethodWait},
    },
};

#[cfg(test)]
mod tests;

/// A predicate with keyed rate limiter.
///
/// Each update will have it's own rate limit under key `K`.
#[derive(Clone)]
pub struct KeyedRateLimitPredicate<K, J, M>
where
    K: Key,
{
    limiter: Arc<RateLimiter<K, DefaultKeyedStateStore<K>, DefaultClock>>,
    jitter: J,
    _method: M,
    keys: HashSet<K>,
}

impl<K, J, M> KeyedRateLimitPredicate<K, J, M>
where
    K: Key,
{
    fn new(quota: Quota, jitter: J, method: M) -> Self {
        Self {
            limiter: Arc::new(RateLimiter::dashmap(quota)),
            jitter,
            _method: method,
            keys: Default::default(),
        }
    }

    /// Use this method when you need to run a predicate only for a specific key.
    ///
    /// If this method is not called, predicate will run for all updates.
    ///
    /// # Arguments
    ///
    /// * `key` - A key to filter by.
    pub fn with_key<T: Into<K>>(mut self, key: T) -> Self {
        self.keys.insert(key.into());
        self
    }

    fn has_key(&self, key: &K) -> bool {
        if self.keys.is_empty() {
            true
        } else {
            self.keys.contains(key)
        }
    }
}

impl<K> KeyedRateLimitPredicate<K, NoJitter, MethodDiscard>
where
    K: Key,
{
    /// Creates a new `KeyedRateLimitPredicate` with the discard method.
    ///
    /// Predicate will stop update propagation when the rate limit is reached.
    ///
    /// # Arguments
    ///
    /// * `quota` - A rate limiting quota.
    pub fn discard(quota: Quota) -> Self {
        Self::new(quota, NoJitter, MethodDiscard)
    }
}

impl<K> KeyedRateLimitPredicate<K, NoJitter, MethodWait>
where
    K: Key,
{
    /// Creates a new `KeyedRateLimitPredicate` with wait method.
    ///
    /// Predicate will pause update propagation when the rate limit is reached.
    ///
    /// # Arguments
    ///
    /// * `quota` - A rate limiting quota.
    pub fn wait(quota: Quota) -> Self {
        Self::new(quota, NoJitter, MethodWait)
    }
}

impl<K> KeyedRateLimitPredicate<K, Jitter, MethodWait>
where
    K: Key,
{
    /// Creates a new `KeyedRateLimitPredicate` with wait method and jitter.
    ///
    /// Predicate will pause update propagation when the rate limit is reached.
    ///
    /// # Arguments
    ///
    /// * `quota` - A rate limiting quota.
    /// * `jitter` - An interval specification for deviating from the nominal wait time.
    pub fn wait_with_jitter(quota: Quota, jitter: Jitter) -> Self {
        Self::new(quota, jitter, MethodWait)
    }
}

impl<K> Handler<K> for KeyedRateLimitPredicate<K, NoJitter, MethodDiscard>
where
    K: Key + Sync,
{
    type Output = PredicateResult;

    async fn handle(&self, input: K) -> Self::Output {
        if self.has_key(&input) {
            match self.limiter.check_key(&input) {
                Ok(_) => PredicateResult::True,
                Err(_) => {
                    log::info!("KeyedRateLimitPredicate: update discarded");
                    PredicateResult::False
                }
            }
        } else {
            PredicateResult::True
        }
    }
}

impl<K> Handler<K> for KeyedRateLimitPredicate<K, NoJitter, MethodWait>
where
    K: Key + Sync + 'static,
{
    type Output = PredicateResult;

    async fn handle(&self, input: K) -> Self::Output {
        if self.has_key(&input) {
            self.limiter.until_key_ready(&input).await;
            PredicateResult::True
        } else {
            PredicateResult::True
        }
    }
}

impl<K> Handler<K> for KeyedRateLimitPredicate<K, Jitter, MethodWait>
where
    K: Key + Sync + 'static,
{
    type Output = PredicateResult;

    async fn handle(&self, input: K) -> Self::Output {
        if self.has_key(&input) {
            self.limiter.until_key_ready_with_jitter(&input, self.jitter).await;
            PredicateResult::True
        } else {
            PredicateResult::True
        }
    }
}