Skip to content

Commit

Permalink
Merge pull request #281 from JakubOnderka/speedup-rand
Browse files Browse the repository at this point in the history
Speedup: Use faster random generator for generating ping messages
  • Loading branch information
icewind1991 authored Jun 21, 2023
2 parents dcc4514 + 008e0d0 commit 9043222
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 2 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ reqwest = { version = "0.11.17", default-features = false, features = ["rustls-t
warp-real-ip = "0.2.0"
parse-display = "0.8.0"
percent-encoding = "2.2.0"
rand = "0.8.5"
rand = { version = "0.8.5", features = ["small_rng"] }
ahash = "0.8.3"
flexi_logger = { version = "=0.25.3", features = ["colors", "is-terminal"] }
tokio-stream = { version = "0.1.14", features = ["net"] }
Expand Down
7 changes: 6 additions & 1 deletion src/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use crate::{App, UserId};
use ahash::RandomState;
use dashmap::DashMap;
use futures::{future::select, pin_mut, SinkExt, StreamExt};
use rand::{Rng, SeedableRng};
use std::net::IpAddr;
use std::num::NonZeroUsize;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
Expand Down Expand Up @@ -107,6 +108,10 @@ pub async fn handle_user_socket(
let expect_pong = &expect_pong;

let transmit = async {
// Use faster random generator for generating ping messages, they dont need to be
// cryptographically secure. It is also OK to use same sequence for every connection.
let mut rng = rand::rngs::SmallRng::seed_from_u64(0);

let mut send_queue = SendQueue::default();

let mut reset = app.reset_rx();
Expand Down Expand Up @@ -136,7 +141,7 @@ pub async fn handle_user_socket(
}

if now.duration_since(last_send) > ping_interval {
let data = rand::random::<NonZeroUsize>().into();
let data = rng.gen::<NonZeroUsize>().into();
let last_ping = expect_pong.swap(data, Ordering::SeqCst);
if last_ping > 0 {
log::info!("{} didn't reply to ping, closing", user_id);
Expand Down

0 comments on commit 9043222

Please sign in to comment.