add ServerConfig with env variables

This commit is contained in:
2025-06-16 18:03:42 +02:00
parent 0c619fbc94
commit 10837dac35
5 changed files with 138 additions and 4 deletions

10
src/config.rs Normal file
View File

@@ -0,0 +1,10 @@
use bon::Builder;
#[derive(Debug, Builder)]
pub struct ServerConfig {
#[builder(default = String::from("0.0.0.0"))]
pub host: String,
#[builder(default = 6171)]
pub port: u16,
pub max_connections: Option<usize>,
}

View File

@@ -1,8 +1,10 @@
use config::ServerConfig;
use errors::AppError;
use server::Server;
pub mod client;
pub mod commands;
pub mod config;
pub mod connection;
pub mod database;
pub mod errors;
@@ -13,7 +15,23 @@ pub type Result<T> = std::result::Result<T, AppError>;
#[tokio::main]
async fn main() -> Result<()> {
let mut server = Server::new("127.0.0.1:6171").await?;
let config = ServerConfig::builder()
.maybe_host(std::env::var("SERVER_HOST").ok())
.maybe_port(
std::env::var("SERVER_PORT")
.ok()
.map(|v| v.parse().ok())
.flatten(),
)
.maybe_max_connections(
std::env::var("MAX_CONNECTIONS")
.ok()
.map(|v| v.parse().ok())
.flatten(),
)
.build();
let mut server = Server::new(config).await?;
server.run().await?;

View File

@@ -4,6 +4,7 @@ use tokio::net::ToSocketAddrs;
use tokio::{net::TcpListener, sync::Semaphore};
use crate::Result;
use crate::config::ServerConfig;
use crate::connection::Connection;
use crate::database::Database;
use crate::handler::Handler;
@@ -16,14 +17,23 @@ pub struct Server {
}
impl Server {
const MAX_CONNECTIONS: usize = 256;
pub const MAX_CONNECTIONS: usize = 256;
pub async fn new<Addr: ToSocketAddrs>(addr: Addr) -> Result<Self> {
pub async fn new(config: ServerConfig) -> Result<Self> {
let addr = format!("{}:{}", config.host, config.port);
Self::_new(
addr,
config.max_connections.unwrap_or(Self::MAX_CONNECTIONS),
)
.await
}
async fn _new<Addr: ToSocketAddrs>(addr: Addr, max_connections: usize) -> Result<Self> {
let listener = TcpListener::bind(addr).await?;
Ok(Self {
db: Database::new(),
connection_limit: Arc::new(Semaphore::const_new(Self::MAX_CONNECTIONS)),
connection_limit: Arc::new(Semaphore::const_new(max_connections)),
listener,
})
}