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
/// Config for rate limiting.
///
/// This object contains the configuration for the rate limits but does not actually hold any rate limiting state. It is often constructed once globally and used for many rate limits however it can also be constructed dynamically if desired.
#[derive(Clone,Debug)]
pub struct Config {
	rate: std::time::Duration,
	burst: u32,
}
/// A reason for denial.
#[derive(Debug,PartialEq)]
#[non_exhaustive]
pub enum Denied {
	/// The request can not be made at this time due to rate limiting rules.
	TooEarly(TooEarly),
	/// The request is larger than the max bucket size and will never be allowed with the current config.
	TooBig,
}

impl std::fmt::Display for Denied {
	fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
		match self {
			Denied::TooEarly(TooEarly{next}) => write!(f, "Try again after {:?}", next),
			Denied::TooBig => f.write_str("Request cost is larger than bucket size."),
		}
	}
}

impl std::error::Error for Denied {}

#[derive(Debug,PartialEq)]
pub struct TooEarly {
	next: std::time::SystemTime,
}

impl TooEarly {
	/// Return when the request will be allowed.
	///
	/// Returns the earliest time that the request can possibly succeed. If there are no other requests in the interim than retrying the same request will succeed at that time.
	pub fn available_at(&self) -> std::time::SystemTime {
		self.next
	}
}

impl Config {
	/// Create a new config.
	///
	/// rate: The amount of time that must elapse between each unit of request on average.
	/// burst: The maximum units that can be used instantaneously.
	///
	/// In other words this is configuring a token bucket where `rate` is the fill rate and `burst` is the maximum capacity.
	///
	/// The tokens are always replenished one-at-a-time. For example "10 tokens even 1min" isn't supported. Instead you would configure "1 token every 6 seconds" which is the same average rate but granted evenly throughout the minute.
	pub const fn new(rate: std::time::Duration, burst: u32) -> Self {
		Config{rate, burst}
	}
}

/// State for a single rate limit.
///
/// This tracks the state of a single rate limit. For example the rate limit for a particular IP.
///
/// This object is intentionally small and cheap so that it can be created for fine-grained tracking.
///
/// The `std::default::Default` implementation creates a "full" tracker. See `Tracker::full()`.
#[derive(Clone,Default,Debug)]
#[cfg_attr(feature="use_serde", derive(serde_derive::Deserialize,serde_derive::Serialize))]
pub struct Tracker {
	#[cfg_attr(feature="use_serde", serde(rename="l"))]
	last: Option<std::time::SystemTime>,
}

impl Tracker {
	/// Create a tracker that starts empty at the current time.
	///
	/// Equivalent to `Tracker::new_at(std::time::SystemTime::now())`.
	pub fn empty() -> Self {
		Self::new_at(std::time::SystemTime::now())
	}

	/// Create a tracker that is full.
	///
	/// This creates a tracker that has it's full burst capacity available.
	///
	/// Equivalent to `std::default::Default::default()`.
	pub fn full() -> Self {
		Self::default()
	}

	/// Create a tracker that starts at the provided time.
	///
	/// This means that the bucket will be empty at the indicated time and will fill starting from there. Note that this is **not** what you want for an limit that hasn't been used for a while and cleaned from the DB. For that case you want `Tracker::default()`.
	pub fn new_at(now: std::time::SystemTime) -> Self {
		Tracker{
			last: Some(now),
		}
	}

	/// Returns the tokens currently available.
	///
	/// Equivalent to `Tracker::capacity_at(std::time::SystemTime::now())`.
	pub fn capacity(&self,
		config: &Config,
	) -> u32 {
		self.capacity_at(config, std::time::SystemTime::now())
	}

	/// Returns the tokens currently available at the specified time.
	pub fn capacity_at(&self,
		config: &Config,
		now: std::time::SystemTime,
	) -> u32 {
		match self.last {
			Some(last) => {
				match now.duration_since(last) {
					Ok(elapsed) => {
						let periods = elapsed.as_nanos() / config.rate.as_nanos();
						let periods = u32::try_from(periods)
							.unwrap_or(u32::max_value());
						periods.min(config.burst)
					}
					Err(_) => 0,
				}
			}
			None => config.burst,
		}
	}

	/// Attempt to acquire `count` tokens from the rate limiter at the current time
	///
	/// Equivalent to `Tracker::acquire_at(config, count, std::time::SystemTime::now())`.
	pub fn acquire(&mut self,
		config: &Config,
		count: u32,
	) -> Result<(), Denied> {
		self.acquire_at(config, count, std::time::SystemTime::now())
	}

	/// Attempt to acquire `count` tokens from the rate limiter.
	///
	/// If the requested number of tokens are available the state is updated and `Ok(())` is returned. Otherwise an error describing the issue is returned.
	///
	/// Warning: To save memory a Tracker does not remember its Config. This means that you can switch the `config` argument between calls on the same Tracker. This is **not recommended** as it is not immediately obvious what the result will be but is completely supported. The only guarantee provided is that the new rate limit will take effect. If the Config is switched between calls the new rate limit will take effect immediately however the logical state of the Tracker may be surprising. For example a large "burst" config may be immediately filled or a new low "rate" may result in a previous "burst" capacity disappearing.
	pub fn acquire_at(&mut self,
		config: &Config,
		count: u32,
		now: std::time::SystemTime,
	) -> Result<(), Denied> {
		if count > config.burst {
			return Err(Denied::TooBig)
		}

		let required = config.rate * count;
		let max_last = now - (config.rate * config.burst) + required;

		if let Some(ref mut last) = self.last {
			let available_at = *last + required;
			if available_at > now {
				return Err(Denied::TooEarly(TooEarly{next: available_at}))
			}
			*last = available_at.max(max_last);
		} else {
			self.last = Some(max_last);
		}

		Ok(())
	}

	/// Attempts to minimize the state at the current time.
	///
	/// Equivalent to `Tracker::simplify_at(config, std::time::SystemTime::now())`.
	pub fn simplify(&mut self,
		config: &Config,
	) -> bool {
		self.simplify_at(config, std::time::SystemTime::now())
	}

	/// Attempts to minimize the state.
	///
	/// If a rate limit hasn't been used in a long time the bucket will be full and the state can be simplified.
	///
	/// Returns `true` if the state is "simple" and equivalent to `Tracker::default()`. If this occurs you don't need to store the state and can use the default state if needed again.
	pub fn simplify_at(&mut self,
		config: &Config,
		now: std::time::SystemTime,
	) -> bool {
		if let Some(last) = self.last {
			if let Ok(elapsed) = now.duration_since(last) {
				let periods = elapsed.as_nanos() / config.rate.as_nanos();
				if periods >= config.burst as u128 {
					self.last = None;
				}
			}
		}

		self.last.is_none()
	}
}

#[test]
fn test_rate_limit_fresh() {
	let cfg = Config::new(std::time::Duration::from_secs(1), 10);

	assert!(Tracker::default().simplify_at(&cfg, std::time::UNIX_EPOCH));

	assert_eq!(
		Tracker::default().acquire(&cfg, 11),
		Err(Denied::TooBig));

	let mut t = Tracker::default();
	assert_eq!(t.capacity_at(&cfg, std::time::UNIX_EPOCH), 10);
	assert_eq!(t.acquire_at(&cfg, 1, std::time::UNIX_EPOCH), Ok(()));
	assert_eq!(t.capacity_at(&cfg, std::time::UNIX_EPOCH), 9);

	let mut t = Tracker::default();
	assert_eq!(t.capacity_at(&cfg, std::time::UNIX_EPOCH), 10);
	assert_eq!(t.acquire_at(&cfg, 8, std::time::UNIX_EPOCH), Ok(()));
	assert_eq!(t.capacity_at(&cfg, std::time::UNIX_EPOCH), 2);
}

#[test]
fn test_rate_limit_active_capacity() {
	let cfg = Config::new(std::time::Duration::from_secs(1), 10);
	let mut t = Tracker::default();
	assert_eq!(t.acquire_at(&cfg, 4, std::time::UNIX_EPOCH), Ok(()));
	assert!(!t.simplify_at(&cfg, std::time::UNIX_EPOCH));

	assert_eq!(t.capacity_at(&cfg, std::time::UNIX_EPOCH), 6);
	assert_eq!(t.capacity_at(&cfg, std::time::UNIX_EPOCH + std::time::Duration::from_secs(1)), 7);
	assert_eq!(t.capacity_at(&cfg, std::time::UNIX_EPOCH + std::time::Duration::from_secs(2)), 8);
	assert_eq!(t.capacity_at(&cfg, std::time::UNIX_EPOCH + std::time::Duration::from_secs(3)), 9);
	assert_eq!(t.capacity_at(&cfg, std::time::UNIX_EPOCH + std::time::Duration::from_secs(4)), 10);
	assert_eq!(t.capacity_at(&cfg, std::time::UNIX_EPOCH + std::time::Duration::from_secs(5)), 10);
	assert_eq!(t.capacity_at(&cfg, std::time::UNIX_EPOCH + std::time::Duration::from_secs(50)), 10);
}

#[test]
fn test_rate_limit_active_acquire() {
	let cfg = Config::new(std::time::Duration::from_secs(1), 10);
	let mut base = Tracker::default();
	assert_eq!(base.acquire_at(&cfg, 4, std::time::UNIX_EPOCH), Ok(()));
	assert_eq!(base.capacity_at(&cfg, std::time::UNIX_EPOCH), 6);
	let base = base;

	let mut t = base.clone();
	assert_eq!(
		t.acquire_at(&cfg, 2, std::time::UNIX_EPOCH),
		Ok(()));
	assert_eq!(t.capacity_at(&cfg, std::time::UNIX_EPOCH), 4);

	let mut t = base.clone();
	assert_eq!(
		t.acquire_at(&cfg, 6, std::time::UNIX_EPOCH),
		Ok(()));
	assert_eq!(t.capacity_at(&cfg, std::time::UNIX_EPOCH), 0);

	let mut t = base.clone();
	assert_eq!(
		t.acquire_at(&cfg, 7, std::time::UNIX_EPOCH),
		Err(Denied::TooEarly(TooEarly{
			next: std::time::UNIX_EPOCH + std::time::Duration::from_secs(1),
		})));
	assert_eq!(
		t.acquire_at(&cfg, 7, std::time::UNIX_EPOCH + std::time::Duration::from_secs(1)),
		Ok(()));

	let mut t = base.clone();
	assert_eq!(
		t.acquire_at(&cfg, 10, std::time::UNIX_EPOCH),
		Err(Denied::TooEarly(TooEarly{
			next: std::time::UNIX_EPOCH + std::time::Duration::from_secs(4),
		})));
	assert_eq!(
		t.acquire_at(&cfg, 10, std::time::UNIX_EPOCH + std::time::Duration::from_secs(4)),
		Ok(()));
}