use crate::auth_client::AuthClient; use crate::bufferpool::BufferPool; use crate::character_client::CharacterClient; use crate::connection_service::ConnectionService; use crate::metrics::{ACTIVE_CONNECTIONS, PACKETS_RECEIVED}; use crate::packet::Packet; use crate::router::PacketRouter; use dotenv::dotenv; use prometheus::{self, Encoder, TextEncoder}; use prometheus_exporter; use std::collections::HashMap; use std::env; use std::error::Error; use std::net::ToSocketAddrs; use std::str::FromStr; use std::sync::Arc; use tokio::io::AsyncReadExt; use tokio::net::{TcpListener, TcpStream}; use tokio::sync::{Mutex, Semaphore}; use tokio::{select, signal}; use tracing::Level; use tracing::{debug, error, info, warn}; use utils::consul_registration; use utils::service_discovery::get_service_address; use warp::Filter; mod auth_client; mod bufferpool; mod character_client; mod connection_service; mod connection_state; mod dataconsts; mod enums; mod handlers; mod metrics; mod packet; mod packet_type; mod packets; mod router; mod types; pub mod common { tonic::include_proto!("common"); } pub mod auth { tonic::include_proto!("auth"); // Path matches the package name in auth.proto } pub mod character_common { tonic::include_proto!("character_common"); // Path matches the package name in auth.proto } pub mod character { tonic::include_proto!("character"); // Path matches the package name in auth.proto } const BUFFER_POOL_SIZE: usize = 1000; const MAX_CONCURRENT_CONNECTIONS: usize = 100; #[tokio::main] async fn main() -> Result<(), Box> { dotenv().ok(); tracing_subscriber::fmt() .with_max_level( Level::from_str(&env::var("LOG_LEVEL").unwrap_or_else(|_| "info".to_string())) .unwrap_or_else(|_| Level::INFO), ) .init(); // Set the gRPC server address let addr = env::var("LISTEN_ADDR").unwrap_or_else(|_| "0.0.0.0".to_string()); let port = env::var("PACKET_SERVICE_PORT").unwrap_or_else(|_| "4000".to_string()); let metrics_port = env::var("PACKET_METRICS_PORT").unwrap_or_else(|_| "4001".to_string()); let health_port = env::var("HEALTH_CHECK_PORT").unwrap_or_else(|_| "8082".to_string()); let consul_url = env::var("CONSUL_URL").unwrap_or_else(|_| "http://127.0.0.1:8500".to_string()); let service_name = env::var("SERVICE_NAME").unwrap_or_else(|_| "packet-service".to_string()); let service_address = env::var("PACKET_SERVICE_ADDR").unwrap_or_else(|_| "127.0.0.1".to_string()); let service_port = port.clone(); let health_check_url = format!("http://{}:{}/health", service_address, health_port); let auth_node = get_service_address(&consul_url, "auth-service").await?; let character_node = get_service_address(&consul_url, "character-service").await?; // Register service with Consul let service_id = consul_registration::get_or_generate_service_id(env!("CARGO_PKG_NAME")); let version = env!("CARGO_PKG_VERSION").to_string(); let tags = vec![version, "tcp".to_string()]; let mut meta = HashMap::new(); consul_registration::register_service( &consul_url, service_id.as_str(), service_name.as_str(), service_address.as_str(), service_port.parse().unwrap_or(50052), tags, meta, Some("http"), Some(&health_check_url), ) .await?; // Start health-check endpoint consul_registration::start_health_check(addr.as_str()).await?; let auth_address = auth_node.get(0).unwrap(); let auth_url = format!( "http://{}:{}", auth_address.ServiceAddress, auth_address.ServicePort ); let auth_client = Arc::new(Mutex::new(AuthClient::connect(&auth_url).await?)); let character_address = character_node.get(0).unwrap(); let character_url = format!( "http://{}:{}", character_address.ServiceAddress, character_address.ServicePort ); let character_client = Arc::new(Mutex::new(CharacterClient::connect(&character_url).await?)); let full_addr = format!("{}:{}", &addr, port); tokio::spawn(async move { let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_CONNECTIONS)); let listener = TcpListener::bind(full_addr.clone()).await.unwrap(); let buffer_pool = BufferPool::new(BUFFER_POOL_SIZE); let connection_service = Arc::new(ConnectionService::new()); let packet_router = PacketRouter { auth_client, character_client, connection_service, }; info!("Packet service listening on {}", full_addr); loop { let (mut socket, addr) = listener.accept().await.unwrap(); let packet_router = packet_router.clone(); info!("New connection from {}", addr); let pool = buffer_pool.clone(); let permit = semaphore.clone().acquire_owned().await.unwrap(); // Spawn a new task for each connection tokio::spawn(async move { let _permit = permit; let connection_id = packet_router.connection_service.add_connection(); if let Err(e) = packet_router .handle_connection(&mut socket, pool, connection_id.clone()) .await { error!("Error handling connection: {}", e); } packet_router .connection_service .remove_connection(&connection_id); }); } }); let binding = format!("{}:{}", &addr, metrics_port); prometheus_exporter::start(binding.parse().unwrap()).unwrap(); utils::signal_handler::wait_for_signal().await; consul_registration::deregister_service(&consul_url, service_id.as_str()) .await .expect(""); info!("service {} deregistered", service_name); Ok(()) }