Compare commits

..

4 Commits

16 changed files with 394 additions and 16 deletions

View File

@@ -5,6 +5,6 @@ members = [
"database-service",
"packet-service",
"world-service",
"utils",
"utils", "launcher", "api-service",
]
resolver = "2"

23
api-service/Cargo.toml Normal file
View File

@@ -0,0 +1,23 @@
[package]
name = "api-service"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.7.9"
hyper = { version = "1.5.1", features = ["server"] }
prost = "0.13.4"
serde = { version = "1.0.216", features = ["derive"] }
serde_json = "1.0.133"
tokio = { version = "1.42.0", features = ["full"] }
tonic = { version = "0.12.3", features = ["transport", "prost"] }
tower = "0.5.2"
log = "0.4.22"
tracing = "0.1.41"
tracing-subscriber = "0.3.19"
utils = { path = "../utils" }
dotenv = "0.15"
tower-http = { version = "0.6.2", features = ["cors"] }
[build-dependencies]
tonic-build = "0.12.3"

6
api-service/build.rs Normal file
View File

@@ -0,0 +1,6 @@
fn main() -> Result<(), Box<dyn std::error::Error>> {
tonic_build::configure()
.compile_well_known_types(true)
.compile_protos(&["../proto/auth.proto"], &["../proto"])?;
Ok(())
}

View File

@@ -0,0 +1,75 @@
use axum::extract::State;
use axum::{routing::post, Json, Router};
use serde::{Deserialize, Serialize};
use std::env;
use std::sync::Arc;
use axum::http::Method;
use tonic::transport::Channel;
use tower_http::cors::{Any, CorsLayer};
use auth::auth_service_client::AuthServiceClient;
use auth::LoginRequest;
use log::error;
use tokio::sync::Mutex;
pub mod auth {
tonic::include_proto!("auth");
}
#[derive(Serialize, Deserialize)]
struct RestLoginRequest {
username: String,
password: String,
}
#[derive(Serialize, Deserialize)]
struct RestLoginResponse {
token: String,
}
async fn login_handler(
State(grpc_client): State<Arc<Mutex<AuthServiceClient<Channel>>>>,
Json(payload): Json<RestLoginRequest>,
) -> Result<Json<RestLoginResponse>, axum::http::StatusCode> {
let request = tonic::Request::new(LoginRequest {
username: payload.username.clone(),
password: payload.password.clone(),
});
let mut client = grpc_client.lock().await; // Lock the mutex to get mutable access
match client.login(request).await {
Ok(response) => {
let token = response.into_inner().token;
Ok(Json(RestLoginResponse { token }))
}
Err(e) => {
error!("gRPC Login call failed: {}", e);
Err(axum::http::StatusCode::UNAUTHORIZED)
}
}
}
pub async fn serve_rest_api(
grpc_client: Arc<Mutex<AuthServiceClient<Channel>>>,
) -> Result<(), Box<dyn std::error::Error>> {
let cors = CorsLayer::new()
.allow_origin(Any) // Allow requests from any origin
.allow_methods([Method::GET, Method::POST]) // Allow specific methods
.allow_headers(Any); // Allow any headers
let app = Router::new()
.route("/api/login", post(login_handler))
.with_state(grpc_client)
.layer(cors);
let addr = env::var("LISTEN_ADDR").unwrap_or_else(|_| "127.0.0.1".to_string());
let port = env::var("API_SERVICE_PORT").unwrap_or_else(|_| "50050".to_string());
let listener = tokio::net::TcpListener::bind(format!("{}:{}", addr, port))
.await
.unwrap();
axum::serve(listener, app.into_make_service())
.await
.unwrap();
Ok(())
}

79
api-service/src/main.rs Normal file
View File

@@ -0,0 +1,79 @@
use crate::axum_gateway::auth::auth_service_client::AuthServiceClient;
use dotenv::dotenv;
use std::collections::HashMap;
use std::env;
use std::str::FromStr;
use std::sync::Arc;
use tokio::sync::Mutex;
use tokio::{select, signal};
use tracing::{info, Level};
use utils::consul_registration;
use utils::service_discovery::get_service_address;
mod axum_gateway;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
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("API_SERVICE_ADDR").unwrap_or_else(|_| "127.0.0.1".to_string());
let port = env::var("API_SERVICE_PORT").unwrap_or_else(|_| "50050".to_string());
let health_port = env::var("HEALTH_CHECK_PORT").unwrap_or_else(|_| "8079".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(|_| "api-service".to_string());
let service_address = addr.as_str();
let service_port = port.clone();
let health_check_url = format!("http://{}:{}/health", service_address, health_port);
// Register service with Consul
let service_id = consul_registration::generate_service_id();
let tags = vec!["version-1.0".to_string()];
let meta = HashMap::new();
consul_registration::register_service(
&consul_url,
service_id.as_str(),
service_name.as_str(),
service_address,
service_port.parse().unwrap_or(50050),
tags,
meta,
&health_check_url,
)
.await?;
// Start health-check endpoint
consul_registration::start_health_check(addr.as_str()).await?;
let auth_node = get_service_address(&consul_url, "auth-service").await?;
let auth_address = auth_node.get(0).unwrap();
let auth_service_address = format!(
"http://{}:{}",
auth_address.ServiceAddress, auth_address.ServicePort
);
// Connect to the gRPC auth-service
let grpc_client = AuthServiceClient::connect(auth_service_address.to_string()).await?;
let grpc_client = Arc::new(Mutex::new(grpc_client));
// Start the Axum REST API
info!("Starting REST API on 0.0.0.0:8079");
axum_gateway::serve_rest_api(grpc_client).await?;
select! {
_ = signal::ctrl_c() => {},
}
consul_registration::deregister_service(&consul_url, service_id.as_str())
.await
.expect("");
info!("service {} deregistered", service_name);
Ok(())
}

View File

@@ -25,13 +25,13 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
.init();
// Set the gRPC server address
let addr = env::var("AUTH_SERVICE_ADDR").unwrap_or_else(|_| "127.0.0.1".to_string());
let addr = env::var("LISTEN_ADDR").unwrap_or_else(|_| "127.0.0.1".to_string());
let port = env::var("AUTH_SERVICE_PORT").unwrap_or_else(|_| "50051".to_string());
let health_port = env::var("HEALTH_CHECK_PORT").unwrap_or_else(|_| "8081".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(|_| "auth-service".to_string());
let service_address = addr.as_str();
let service_address = env::var("AUTH_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 health_check_endpoint_addr = format!("{}:{}", service_address, health_port);
@@ -45,7 +45,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
&consul_url,
service_id.as_str(),
service_name.as_str(),
service_address,
service_address.as_str(),
service_port.parse().unwrap_or(50052),
tags,
meta,

View File

@@ -0,0 +1,16 @@
fn main() {
// gRPC Server code
tonic_build::configure()
.build_server(true) // Generate gRPC server code
.compile_well_known_types(true)
.type_attribute(".", "#[derive(serde::Serialize, serde::Deserialize)]")
.compile_protos(&["../proto/character.proto"], &["../proto"])
.unwrap_or_else(|e| panic!("Failed to compile protos {:?}", e));
// gRPC Client code
tonic_build::configure()
.build_server(false) // Generate gRPC client code
.compile_well_known_types(true)
.compile_protos(&["../proto/database.proto", "../proto/auth.proto"], &["../proto"])
.unwrap_or_else(|e| panic!("Failed to compile protos {:?}", e));
}

View File

@@ -15,13 +15,13 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
.init();
// Set the gRPC server address
let addr = env::var("CHARACTER_SERVICE_ADDR").unwrap_or_else(|_| "127.0.0.1".to_string());
let addr = env::var("LISTEN_ADDR").unwrap_or_else(|_| "127.0.0.1".to_string());
let port = env::var("CHARACTER_SERVICE_PORT").unwrap_or_else(|_| "50053".to_string());
let health_port = env::var("HEALTH_CHECK_PORT").unwrap_or_else(|_| "8083".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(|_| "character-service".to_string());
let service_address = addr.as_str();
let service_address = env::var("CHARACTER_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 health_check_endpoint_addr = format!("{}:{}", service_address, health_port);
@@ -36,7 +36,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
&consul_url,
service_id.as_str(),
service_name.as_str(),
service_address,
service_address.as_str(),
service_port.parse().unwrap_or(50052),
tags,
meta,

View File

@@ -23,7 +23,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
.with_max_level(Level::from_str(&env::var("LOG_LEVEL").unwrap_or_else(|_| "info".to_string())).unwrap_or_else(|_| Level::INFO))
.init();
let addr = env::var("DATABASE_SERVICE_ADDR").unwrap_or_else(|_| "127.0.0.1".to_string());
let addr = env::var("LISTEN_ADDR").unwrap_or_else(|_| "127.0.0.1".to_string());
let port = env::var("DATABASE_SERVICE_PORT").unwrap_or_else(|_| "50052".to_string());
let health_port = env::var("HEALTH_CHECK_PORT").unwrap_or_else(|_| "8080".to_string());
@@ -32,7 +32,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
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(|_| "database-service".to_string());
let service_address = addr.as_str();
let service_address = env::var("DATABASE_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 health_check_endpoint_addr = format!("{}:{}", service_address, health_port);
@@ -45,7 +45,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
&consul_url,
service_id.as_str(),
service_name.as_str(),
service_address,
service_address.as_str(),
service_port.parse().unwrap_or(50052),
tags,
meta,

10
launcher/Cargo.toml Normal file
View File

@@ -0,0 +1,10 @@
[package]
name = "launcher"
version = "0.1.0"
edition = "2021"
[dependencies]
shell-escape = "0.1.5"
tracing = "0.1.41"
tracing-subscriber = "0.3.19"
url = "2.5.4"

120
launcher/src/main.rs Normal file
View File

@@ -0,0 +1,120 @@
use std::path::Path;
use std::process::{exit, Command, Stdio};
use std::str::FromStr;
use std::{env, io};
use tracing::{error, info, Level};
use url::Url;
fn wait_for_keypress() {
// Wait for a keypress
info!("Press Enter to close the launcher...");
let _ = io::stdin().read_line(&mut String::new());
}
fn format_shell_command(command: &Command) -> String {
let executable = command.get_program().to_string_lossy();
let args: Vec<String> = command
.get_args()
.map(|arg| shell_escape::escape(arg.to_string_lossy()).into_owned())
.collect();
format!("{} {}", executable, args.join(" "))
}
fn main() {
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();
// Get the full command-line arguments (the URL is passed as the first argument after the executable)
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
error!("Usage: osirose-launcher <url>");
wait_for_keypress();
return;
}
let url = &args[1];
let working_directory =
env::var("GAME_CLIENT_PATH").unwrap_or_else(|_| "D:/rose_osirose-new-x64".to_string());
// Parse the URL
match Url::parse(url) {
Ok(parsed_url) => {
// Extract the "otp" parameter
let otp = parsed_url
.query_pairs()
.find(|(key, _)| key == "otp")
.map(|(_, value)| value.to_string());
let ip = parsed_url
.query_pairs()
.find(|(key, _)| key == "ip")
.map(|(_, value)| value.to_string());
let username = parsed_url
.query_pairs()
.find(|(key, _)| key == "username")
.map(|(_, value)| value.to_string());
let port = parsed_url
.query_pairs()
.find(|(key, _)| key == "port")
.map(|(_, value)| value.to_string())
.unwrap_or("4000".to_string());
// Ensure required parameters are present
if otp.is_none() || ip.is_none() || username.is_none() {
error!("Missing required parameters: otp, ip, or username");
wait_for_keypress();
return;
}
// Unwrap the parameters
let otp = otp.unwrap();
let ip = ip.unwrap();
let username = username.unwrap();
info!("Launching game with:");
info!(" OTP: {}", otp);
info!(" IP: {}", ip);
info!(" Username: {}", username);
// Change the working directory
if let Err(e) = env::set_current_dir(Path::new(&working_directory)) {
eprintln!("Failed to set working directory: {}", e);
wait_for_keypress();
exit(1);
}
// Construct the game client command
let game_executable = "./TRose.exe";
let mut command = Command::new(game_executable);
command
.arg("@TRIGGER_SOFT@")
.arg("_direct")
.arg("_server")
.arg(ip)
.arg("_port")
.arg(port)
.arg("_userid")
.arg(username)
.arg("_otp")
.arg(otp)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null());
info!("Executing: {:?}", format_shell_command(&command));
// Check if the game launched successfully
match command.spawn() {
Ok(_) => info!("Game launched successfully!"),
Err(e) => error!("Failed to launch the game: {}", e),
}
}
Err(e) => error!("Failed to parse URL: {}", e),
}
info!("Launcher is closing...");
}

View File

@@ -72,13 +72,13 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
.init();
// Set the gRPC server address
let addr = env::var("PACKET_SERVICE_ADDR").unwrap_or_else(|_| "127.0.0.1".to_string());
let addr = env::var("LISTEN_ADDR").unwrap_or_else(|_| "127.0.0.1".to_string());
let port = env::var("PACKET_SERVICE_PORT").unwrap_or_else(|_| "4000".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 = addr.as_str();
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 health_check_endpoint_addr = format!("{}:{}", service_address, health_port);
@@ -92,7 +92,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
&consul_url,
service_id.as_str(),
service_name.as_str(),
service_address,
service_address.as_str(),
service_port.parse().unwrap_or(50052),
tags,
meta,

16
proto/character.proto Normal file
View File

@@ -0,0 +1,16 @@
syntax = "proto3";
package character;
service CharacterService {
rpc GetCharacterList(CharacterListRequest) returns (CharacterListResponse);
}
message CharacterListRequest {
string token = 1;
string user_id = 2;
}
message CharacterListResponse {
int32 count = 1;
}

17
proto/world.proto Normal file
View File

@@ -0,0 +1,17 @@
syntax = "proto3";
package character;
service CharacterService {
rpc GetCharacter(CharacterRequest) returns (CharacterResponse);
}
message CharacterRequest {
string token = 1;
string user_id = 2;
string char_id = 3;
}
message CharacterResponse {
int32 count = 1;
}

16
world-service/build.rs Normal file
View File

@@ -0,0 +1,16 @@
fn main() {
// gRPC Server code
tonic_build::configure()
.build_server(true) // Generate gRPC server code
.compile_well_known_types(true)
.type_attribute(".", "#[derive(serde::Serialize, serde::Deserialize)]")
.compile_protos(&["../proto/world.proto"], &["../proto"])
.unwrap_or_else(|e| panic!("Failed to compile protos {:?}", e));
// gRPC Client code
tonic_build::configure()
.build_server(false) // Generate gRPC client code
.compile_well_known_types(true)
.compile_protos(&["../proto/database.proto", "../proto/auth.proto"], &["../proto"])
.unwrap_or_else(|e| panic!("Failed to compile protos {:?}", e));
}

View File

@@ -15,13 +15,13 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
.init();
// Set the gRPC server address
let addr = env::var("WORLD_SERVICE_ADDR").unwrap_or_else(|_| "127.0.0.1".to_string());
let addr = env::var("LISTEN_ADDR").unwrap_or_else(|_| "127.0.0.1".to_string());
let port = env::var("WORLD_SERVICE_PORT").unwrap_or_else(|_| "50054".to_string());
let health_port = env::var("HEALTH_CHECK_PORT").unwrap_or_else(|_| "8084".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(|_| "world-service".to_string());
let service_address = addr.as_str();
let service_address = env::var("WORLD_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 health_check_endpoint_addr = format!("{}:{}", service_address, health_port);
@@ -36,7 +36,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
&consul_url,
service_id.as_str(),
service_name.as_str(),
service_address,
service_address.as_str(),
service_port.parse().unwrap_or(50054),
tags,
meta,