Skip to content

Commit

Permalink
feat: reuseport support
Browse files Browse the repository at this point in the history
  • Loading branch information
dpc committed Jun 3, 2024
1 parent b22cff6 commit 0ff1bd4
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
25 changes: 23 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ mod routes;
mod state;

use std::net::SocketAddr;
use std::str::FromStr as _;
use std::sync::Arc;
use std::time::Duration;

Expand All @@ -15,6 +16,7 @@ use axum::http::{HeaderName, Method};
use axum::Router;
use color_eyre::Result;
use db::Database;
use tokio::net::{TcpListener, TcpSocket};
use tokio::signal;
use tower_governor::governor::GovernorConfigBuilder;
use tower_governor::GovernorLayer;
Expand All @@ -29,14 +31,14 @@ use crate::state::AppState;

pub struct Server {
opts: opts::Opts,
listener: tokio::net::TcpListener,
listener: TcpListener,
state: Arc<AppState>,
}

impl Server {
pub async fn init(opts: opts::Opts) -> Result<Server> {
let assets = AssetCache::load_files(&opts.assets_dir).await;
let listener = tokio::net::TcpListener::bind(opts.listen.clone()).await?;
let listener = Self::get_listener(&opts).await?;
let db = Database::open(&opts.db).await?;
let state = Arc::new(AppState { db, assets });

Expand All @@ -51,6 +53,25 @@ impl Server {
})
}

pub async fn get_listener(opts: &opts::Opts) -> Result<TcpListener> {
let addr = SocketAddr::from_str(&opts.listen)?;

let socket = if addr.is_ipv4() {
TcpSocket::new_v4()?
} else {
TcpSocket::new_v6()?
};

if opts.reuseport {
#[cfg(unix)]
socket.set_reuseport(true)?;
}
socket.set_nodelay(true)?;

socket.bind(addr)?;
Ok(socket.listen(1024)?)
}

// TODO: move more stuff to init
pub async fn run(self) -> Result<()> {
let governor_conf = Box::new(
Expand Down
6 changes: 6 additions & 0 deletions src/opts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,11 @@ pub struct Opts {
#[arg(long, short, default_value = "[::1]:5050", env = "PERFITD_LISTEN")]
pub listen: String,

/// Reuse potentially already opened port (useful for systemd socket
/// activation)
#[arg(long, env = "PERFITD_REUSEPORT")]
pub reuseport: bool,

/// Database file path
#[arg(long, default_value = "perfitd.redb", env = "PERFITD_DB_PATH")]
pub db: PathBuf,
Expand Down Expand Up @@ -62,6 +67,7 @@ impl Default for Opts {
root_access_token: None,
rate_limit_replenish_millis: 500000,
rate_limit_burst: 60,
reuseport: false,
}
}
}
Expand Down

0 comments on commit 0ff1bd4

Please sign in to comment.