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
use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::hash::Hash;
use std::sync::Arc;

use crate::time::Clock;
use crate::time::SystemClock;

pub struct BackoffTracker<T> {
    field: HashMap<T, BackoffEntry>,
    clock: Arc<dyn Clock>,
    config: BackoffConfig,
}

impl<T> Default for BackoffTracker<T> {
    fn default() -> Self {
        Self::new(Arc::new(SystemClock::default()), BackoffConfig::default())
    }
}

impl<T> BackoffTracker<T> {
    pub fn new(clock: Arc<dyn Clock>, config: BackoffConfig) -> Self {
        Self {
            field: HashMap::new(),
            clock,
            config,
        }
    }
}

/// High level management of code execution using backoff tracking primitives.
impl<'t, T: Eq + Hash + 't> BackoffTracker<T> {
    /// Use this if you'd like to rate limit some code regardless of its outcome.
    ///
    /// Triggers an event on any execution. see `backoff_generic`.
    pub fn backoff<F: Fn() -> X, X>(&mut self, id: T, f: F) -> Option<X> {
        self.backoff_generic(id, f, false, |_| true)
    }

    /// Use this if you'd like to rate limit some code regardless of its
    /// outcome, but not if other events occur in between.
    ///
    /// Triggers an event on any execution. see `backoff_generic` and
    /// `singular_event`
    pub fn backoff_singular<F: Fn() -> X, X>(&mut self, id: T, f: F) -> Option<X> {
        self.backoff_generic(id, f, true, |_| true)
    }

    /// Use this if you'd like to rate limit some code when it fails.
    /// Triggers an event on Err. see `backoff_generic`.
    pub fn backoff_errors<F, O, E>(&mut self, id: T, f: F) -> Option<Result<O, E>>
    where
        F: Fn() -> Result<O, E>,
    {
        self.backoff_generic(id, f, false, Result::is_err)
    }

    /// Use this if you'd like to rate limit some code when it succeeds.
    /// Triggers an event on Ok. see `backoff_generic`.
    pub fn backoff_oks<F, O, E>(&mut self, id: T, f: F) -> Option<Result<O, E>>
    where
        F: Fn() -> Result<O, E>,
    {
        self.backoff_generic(id, f, false, Result::is_ok)
    }

    /// Generic function used by other `backoff_` functions.
    ///
    /// Run the code if ready. Trigger an event when the predicate is true
    /// Returns None if the execution was skipped due to not being ready.
    pub fn backoff_generic<F, X, P>(
        &mut self,
        id: T,
        f: F,
        singular: bool,
        predicate: P,
    ) -> Option<X>
    where
        F: Fn() -> X,
        P: Fn(&X) -> bool,
    {
        if self.is_ready(&id) {
            let result = f();
            if predicate(&result) {
                if singular && !self.field.contains_key(&id) {
                    self.field = HashMap::new();
                }
                self.event(id);
            }
            Some(result)
        } else {
            None
        }
    }
}

/// Primitives to track the backoff
impl<'t, T: Eq + Hash + 't> BackoffTracker<T> {
    pub fn event(&mut self, item: T) {
        let now = self.clock.current_timestamp();
        match self.field.entry(item) {
            Entry::Vacant(entry) => {
                entry.insert(BackoffEntry {
                    count: 1,
                    last: now,
                    delay: self.config.initial_delay(),
                });
            }
            Entry::Occupied(mut entry) => {
                let BackoffEntry { count, last, delay } = entry.get();
                if last + delay < now {
                    let delay = match self.config.strategy {
                        BackoffStrategy::Exponential(b) => {
                            std::cmp::min(delay * b, self.config.max_delay)
                        }
                        BackoffStrategy::Cliff(c) => {
                            if count > &c {
                                self.config.max_delay
                            } else {
                                self.config.min_delay
                            }
                        }
                    };
                    entry.insert(BackoffEntry {
                        count: count + 1,
                        last: now,
                        delay,
                    });
                }
            }
        }
    }

    /// Like `event`, but it clears all history of other events when a new event
    /// is received.
    ///
    /// Use this when you only need to backoff events that are consecutive
    /// duplicates, but don't need to backoff events if different events occur
    /// in between.
    pub fn singular_event(&mut self, item: T) {
        if !self.field.contains_key(&item) {
            self.field = HashMap::new();
        }
        self.event(item);
    }

    pub fn clear(&mut self, item: &T) {
        if self.field.contains_key(item) {
            self.field.remove(item);
        }
    }

    pub fn clear_many<'a>(&mut self, items: impl IntoIterator<Item = &'a T>)
    where
        't: 'a,
    {
        for item in items {
            self.field.remove(item);
        }
    }

    pub fn is_ready(&self, item: &T) -> bool {
        match self.field.get(item) {
            Some(x) => self.clock.current_timestamp() > x.last + x.delay,
            None => true,
        }
    }
}

/// Events must not be recorded here if they occurred...
/// - within a delay window
/// - before the last `clear`
struct BackoffEntry {
    /// Total quantity of registered events that occurred outside a delay window.
    count: u64,
    /// The time that the last event occurred outside a delay window.
    last: u64,
    /// The time window to wait since last_event before being "ready"
    delay: u64,
}

pub struct BackoffConfig {
    pub min_delay: u64,
    pub max_delay: u64,
    pub strategy: BackoffStrategy,
}

impl BackoffConfig {
    /// Simple rate limiter with a constant rate, doesn't backoff progressively.
    pub fn constant(period: u64) -> Self {
        Self {
            min_delay: period,
            max_delay: period,
            strategy: BackoffStrategy::Cliff(0),
        }
    }

    /// Once an event occurs, it will never be ready again unless cleared.
    pub fn once() -> Self {
        Self {
            min_delay: u64::MAX,
            max_delay: u64::MAX,
            strategy: BackoffStrategy::Cliff(0),
        }
    }

    pub fn initial_delay(&self) -> u64 {
        match self.strategy {
            BackoffStrategy::Cliff(0) => self.max_delay,
            _ => self.min_delay,
        }
    }
}

impl Default for BackoffConfig {
    fn default() -> Self {
        Self {
            min_delay: 30,
            max_delay: 3600,
            strategy: Default::default(),
        }
    }
}

pub enum BackoffStrategy {
    /// The wrapped integer is the base b of the exponential b^n where n is the
    /// number of events. Each event will trigger a delay b times as large as
    /// the prior delay.
    Exponential(u64),

    /// Cliff means you wait exactly the minimum delay for some number of
    /// events, then you suddenly switch to waiting the maximum interval for
    /// each event. The wrapped integer is the number of times to delay with the
    /// minimum interval before switching to the max interval.
    Cliff(u64),
}

impl Default for BackoffStrategy {
    fn default() -> Self {
        // 3 is the closest integer to Euler's constant, which makes it the
        // obvious choice as a standard base for an exponential. It also
        // subjectively feels to me like a generally satisfying rate of cooldown
        // in most cases, where 2 feels overly aggressive.
        BackoffStrategy::Exponential(3)
    }
}