Skip to content

Commit

Permalink
[OPTIMIZATION] rate limter
Browse files Browse the repository at this point in the history
  • Loading branch information
ismoilovdevml committed Oct 15, 2023
1 parent 38c7900 commit ad26fea
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 14 deletions.
39 changes: 38 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ clap = "2.33"
cookie = "0.14"
futures = "0.3"
futures-util = "0.3"
fnv = "1.0.7"
gethostname = "0.2"
http-auth-basic = "0.1"
hyper = { version = "0.14", features = ["client", "server", "http1", "http2", "stream"] }
Expand All @@ -27,6 +28,7 @@ linked-hash-map = "0.5"
lazy_static = "1.4"
log = "0.4"
log4rs = "1.0"
lru = "0.12.0"
notify = "4.0"
openssl-sys = { version = "0.9", features = ["vendored"] }
pin-project = "1.0"
Expand All @@ -42,6 +44,5 @@ tokio-util = { version = "0.6", features = ["full"] }
toml = { version = "0.5", features = ["preserve_order"] }
url = "2.2"
warp = "0.3.6"
fnv = "1.0.7"

[build-dependencies]
18 changes: 6 additions & 12 deletions src/middleware/rate_limiter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,26 +28,20 @@ impl RateLimiter {

let old_entries = connections
.iter()
// Due to temporal order in LinkedHashMap stopping early is possible
.take_while(|(_client_address, (_count, time))| now.duration_since(*time).as_secs() > self.window_sec)
.map(|(client_address, _)| *client_address)
.collect::<Vec<_>>();
for client_address in old_entries {
connections.remove(&client_address);
}

// Remove and reinsert to ensure temporal order in LinkedHashMap
let mut count = connections
.remove(client_address)
.map(|(count, _time)| count)
.unwrap_or(0);
// Prevent overflow
if count < u64::MAX {
count += 1;
}
connections.insert(*client_address, (count, now));
let count = connections
.entry(*client_address)
.or_insert((0, now));
count.0 += 1;
count.1 = now;

count <= self.limit
count.0 <= self.limit
}
}

Expand Down

0 comments on commit ad26fea

Please sign in to comment.