Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Speedup: Use faster random generator for generating ping messages #281

Merged
merged 1 commit into from
Jun 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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