feat(server): Add tcp-keepalive on in-coming server connections

This commit is contained in:
Σrebe - Romain GERARD 2024-05-01 15:07:45 +02:00
parent 421a5a230c
commit 69c372490a
No known key found for this signature in database
GPG key ID: 7A42B4B97E0332F4
2 changed files with 11 additions and 7 deletions

View file

@ -5,7 +5,7 @@ use crate::dns::DnsResolver;
use base64::Engine;
use bytes::BytesMut;
use log::warn;
use socket2::TcpKeepalive;
use socket2::{SockRef, TcpKeepalive};
use std::net::{SocketAddr, SocketAddrV4, SocketAddrV6};
use std::time::Duration;
@ -17,8 +17,7 @@ use tracing::log::info;
use tracing::{debug, instrument};
use url::{Host, Url};
fn configure_socket(socket: &mut TcpSocket, so_mark: &Option<u32>) -> Result<(), anyhow::Error> {
let socket = socket2::SockRef::from(&socket);
pub fn configure_socket(socket: SockRef, so_mark: &Option<u32>) -> Result<(), anyhow::Error> {
socket
.set_nodelay(true)
.with_context(|| format!("cannot set no_delay on socket: {:?}", io::Error::last_os_error()))?;
@ -71,12 +70,12 @@ pub async fn connect(
for addr in socket_addrs {
debug!("Connecting to {}", addr);
let mut socket = match &addr {
let socket = match &addr {
SocketAddr::V4(_) => TcpSocket::new_v4()?,
SocketAddr::V6(_) => TcpSocket::new_v6()?,
};
configure_socket(&mut socket, &so_mark)?;
configure_socket(socket2::SockRef::from(&socket), &so_mark)?;
match timeout(connect_timeout, socket.connect(addr)).await {
Ok(Ok(stream)) => {
cnx = Some(stream);

View file

@ -7,6 +7,7 @@ use http_body_util::{BodyStream, Either, StreamBody};
use std::cmp::min;
use std::fmt::Debug;
use std::future::Future;
use std::net::{IpAddr, SocketAddr};
use std::ops::Deref;
use std::pin::Pin;
@ -25,6 +26,7 @@ use hyper_util::rt::TokioExecutor;
use jsonwebtoken::TokenData;
use once_cell::sync::Lazy;
use parking_lot::Mutex;
use socket2::SockRef;
use crate::restrictions::config_reloader::RestrictionsRulesReloader;
use crate::restrictions::types::{
@ -727,8 +729,8 @@ pub async fn run_server(server_config: Arc<WsServerConfig>, restrictions: Restri
// Bind server and run forever to serve incoming connections.
let mut restrictions = RestrictionsRulesReloader::new(restrictions, server_config.restriction_config.clone())?;
let listener = TcpListener::bind(&server_config.bind).await?;
let mut await_config_reload = Box::pin(restrictions.reload_notifier());
let listener = TcpListener::bind(&server_config.bind).await?;
loop {
let cnx = select! {
@ -751,7 +753,10 @@ pub async fn run_server(server_config: Arc<WsServerConfig>, restrictions: Restri
continue;
}
};
let _ = stream.set_nodelay(true);
if let Err(err) = tcp::configure_socket(SockRef::from(&stream), &None) {
warn!("Error while configuring server socket {:?}", err);
}
let span = span!(
Level::INFO,