This commit is contained in:
2025-11-28 16:54:56 +09:00
parent 23176551b7
commit 8f18415f25
841 changed files with 67879 additions and 12265 deletions

View File

@@ -1,11 +1,10 @@
using System.Text;
using BrokerApiCore;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using ServerBase;
using ServerCore;
using BrokerApiCore;
namespace BrokerApiServer;
@@ -13,19 +12,8 @@ public static class AppBuilderExtensions
{
public static void initGlobalNlog()
{
// nlog 설정
var nlog_config_path = "./Config/nlog.config";
var full_path = Path.GetFullPath(nlog_config_path);
if (!File.Exists(full_path))
{
full_path = Path.GetFullPath(nlog_config_path, AppContext.BaseDirectory);
if (!File.Exists(full_path))
{
throw new ApplicationException($"nlog.config 파일을 찾을 수 없음 => {full_path}");
}
}
Log.NLogFileName = full_path;
Log.initLog(nameof(ServerType.BrokerApi), "Developer"); // nlog 설정
Log.getLogger().info("NLog Init");
}
public static ServerConfigMetaverseBroker initBrokerServerConfig()
@@ -42,35 +30,18 @@ public static class AppBuilderExtensions
throw new ApplicationException("ServerConfig.json 파일을 찾을 수 없음");
}
}
server_config.setConfigFilePath(full_path);
var result = server_config.tryLoadConfig().GetAwaiter().GetResult();
Guard.Against.resultFail(result);
return server_config;
}
public static void addBrokerServerLogic(this IServiceCollection services,
ServerConfigMetaverseBroker serverConfig)
{
var broker_logic = new BrokerServerLogic(serverConfig);
var result = broker_logic.onInit().GetAwaiter().GetResult();
if (result.isFail())
{
Log.getLogger().error($"BrokerServerLogic Init Failed => {result}");
throw new ApplicationException($"BrokerServerLogic Init Failed => {result}");
}
ServerLogicApp.setServerLogicApp(broker_logic);
services.AddSingleton<IServerLogic>(broker_logic);
}
public static void addCoreServices(this IServiceCollection services,
ServerConfigMetaverseBroker serverConfig)
{
services.AddSingleton(serverConfig);
var broker_logic = new BrokerServerLogic(serverConfig);
var result = broker_logic.onInit().GetAwaiter().GetResult();
services.AddSingleton<IServerLogic>(broker_logic);
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
@@ -80,7 +51,9 @@ public static class AppBuilderExtensions
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(serverConfig.MetaverseBroker?.JwtSecretKey ?? String.Empty))
IssuerSigningKey =
new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(serverConfig.MetaverseBroker?.JwtSecretKey ?? String.Empty))
};
});
@@ -90,7 +63,7 @@ public static class AppBuilderExtensions
// 메타데이터 관련 서비스 등록
services.AddSingleton<BrokerApiMetaLoader>();
services.AddScoped<BrokerMetaTableRef>( provider =>
services.AddScoped<BrokerMetaTableRef>(provider =>
{
var meta_loader = provider.GetRequiredService<BrokerApiMetaLoader>();
return new BrokerMetaTableRef(meta_loader.getMetaTable());
@@ -104,14 +77,8 @@ public static class AppBuilderExtensions
};
services.AddSingleton(jwt_option);
services.AddScoped<JwtGenerator>(provider =>
{
return new JwtGenerator(jwt_option);
});
services.AddScoped<JwtParser>(provider =>
{
return new JwtParser(jwt_option);
});
services.AddScoped<JwtGenerator>(provider => { return new JwtGenerator(jwt_option); });
services.AddScoped<JwtParser>(provider => { return new JwtParser(jwt_option); });
services.AddScoped<PlanetService>();
@@ -128,6 +95,8 @@ public static class AppBuilderExtensions
services.AddScoped<PlanetItemExchangeOrderAmountTotalLimitRepo>();
services.AddScoped<PlanetItemExchangeOrderAmountUserLimitRepo>();
services.AddSingleton<DynamoDbClient>();
services.AddDbContext<SsoAccountDbContext>(options =>
{
var connection_string = serverConfig.SsoAccountDb;
@@ -148,29 +117,19 @@ public static class AppBuilderExtensions
{
var connection_string = serverConfig.MetaverseBroker?.MetaverseBrokerDb;
options.UseMySql(connection_string, ServerVersion.AutoDetect(connection_string), my_sql_options =>
options.UseMySql(connection_string, ServerVersion.AutoDetect(connection_string), mySqlOptions =>
{
my_sql_options.EnableRetryOnFailure(
mySqlOptions.EnableRetryOnFailure(
maxRetryCount: 10,
maxRetryDelay: TimeSpan.FromSeconds(30),
errorNumbersToAdd: null
);
my_sql_options.CommandTimeout(60);
my_sql_options.MaxBatchSize(20);
mySqlOptions.CommandTimeout(60);
mySqlOptions.MaxBatchSize(20);
});
});
}
// todo: isLocal 삭제 예정
public static void addAppServices(this WebApplicationBuilder builder)
{
initGlobalNlog();
var server_config = initBrokerServerConfig();
builder.Services.addBrokerServerLogic(server_config);
builder.Services.addCoreServices(server_config);
builder.Services.addInfraServices(server_config);
}
public static void brokerServerLogicInit(this IApplicationBuilder app)
{
var server_logic = app.ApplicationServices.GetRequiredService<IServerLogic>() as BrokerServerLogic;
@@ -191,20 +150,29 @@ public static class AppBuilderExtensions
public static void validateRepoConnections(this IApplicationBuilder app)
{
var env = app.ApplicationServices.GetRequiredService<IWebHostEnvironment>();
// db 접속 유무 검사
using var scope = app.ApplicationServices.CreateScope();
var services = scope.ServiceProvider;
validateSsoAccountDb().Wait();
validateMetaverseBrokerDb().Wait();
migrateMetaverseBrokerDbForDevelopment().Wait();
try
{
validateSsoAccountDb().Wait();
validateMetaverseBrokerDb().Wait();
// 마이그레이션은 코드에서 호출하지 말고, 별도의 migration script를 통해서 수행한다.
migrateMetaverseBrokerDbForDevelopment().Wait();
}
catch (Exception ex)
{
Log.getLogger().error($"[Check Tunneling] Repo Connections Validation Failed => {ex.Message}");
throw new ApplicationException($"Repo Connections Validation Failed => {ex.Message}");
}
return;
async Task validateSsoAccountDb()
{
var context = services.GetRequiredService<SsoAccountDbContext>();
try
{
var context = services.GetRequiredService<SsoAccountDbContext>();
if (await context.Database.CanConnectAsync())
{
Log.getLogger().info($"Sso Account DB Connection OK => {context.Database.GetConnectionString()}");
@@ -217,17 +185,17 @@ public static class AppBuilderExtensions
{
Log.getLogger()
.error(
$"Sso Account DB Connection Failed => {ex.Message}, {context.Database.GetConnectionString()}");
$"Sso Account DB Connection Failed => {ex.Message}");
}
throw new ApplicationException($"Failed to connect Sso Account Db !!!");
// throw new ApplicationException($"Failed to connect Sso Account Db !!!");
}
async Task validateMetaverseBrokerDb()
{
var context = services.GetRequiredService<MetaverseBrokerDbContext>();
try
{
var context = services.GetRequiredService<MetaverseBrokerDbContext>();
if (await context.Database.CanConnectAsync())
{
Log.getLogger()
@@ -237,15 +205,16 @@ public static class AppBuilderExtensions
if (migrations.Any())
{
Log.getLogger().error($"{context.Database.ToString()} 마이그레션이 필요함 !!!");
migrations.Select( x => x.ToString()).ToList().ForEach(x => Log.getLogger().warn(x));
migrations.Select(x => x.ToString()).ToList().ForEach(x => Log.getLogger().warn(x));
}
return;
}
}
catch (Exception ex)
{
Log.getLogger()
.error($"Metaverse-Broker DB 접속 예외 발생 => {ex.Message}, {context.Database.GetConnectionString()}");
.error($"Metaverse-Broker DB 접속 예외 발생 => {ex.Message}");
}
throw new ApplicationException($"Failed to connect Broker Db !!!");
@@ -268,4 +237,80 @@ public static class AppBuilderExtensions
}
}
}
public static void addDynamoDb(this IServiceCollection services)
{
services.AddSingleton<DynamoDbClient>(x =>
{
var dynamo_db_client = new DynamoDbClient();
return dynamo_db_client;
// var result = new Result();
// var config = x.GetRequiredService<ServerConfig>();
//
// (var error_code, var table_names) =
// ServerConfigHelper.getDynamoDbTableNamesWithServiceType(config.ServiceType);
// if (error_code.isFail())
// {
// var err_msg =
// $"Failed to DynamoDbClient.getDynamoDbTableNameWithServiceType() !!! : {config.toBasicString()}";
// result.setFail(error_code, err_msg);
// Log.getLogger().error(err_msg);
// Guard.Against.resultFail(result);
// }
//
// var dynamo_db_client = new DynamoDbClient();
// var dynamodb_url = config.Dynamodb;
// var region = config.AWS.Region;
// var access_key = config.AWS.AccessKey;
// var secret_key = config.AWS.SecretKey;
// var use_local_db = config.AWS.LocalDynamoDB;
// if (result.isFail())
// {
// Log.getLogger().error($"Failed to connectToDb !!! ");
// Guard.Against.resultFail(result);
// }
//
// dynamo_db_client.connectToDb(table_names, use_local_db, dynamodb_url, access_key, secret_key, region);
// return dynamo_db_client;
});
}
public static void useDynamoDb(this IApplicationBuilder app)
{
var result = new Result();
var config = app.ApplicationServices.GetRequiredService<ServerConfig>();
(var error_code, var table_names) =
ServerConfigHelper.getDynamoDbTableNamesWithServiceType(config.ServiceType);
if (error_code.isFail())
{
var err_msg =
$"Failed to DynamoDbClient.getDynamoDbTableNameWithServiceType() !!! : {config.toBasicString()}";
result.setFail(error_code, err_msg);
Log.getLogger().error(err_msg);
Guard.Against.resultFail(result);
}
var dynamo_db_client = app.ApplicationServices.GetRequiredService<DynamoDbClient>();
var dynamodb_url = config.Dynamodb;
var region = config.AWS.Region;
var access_key = config.AWS.AccessKey;
var secret_key = config.AWS.SecretKey;
var use_local_db = config.AWS.LocalDynamoDB;
result = dynamo_db_client.connectToDb(table_names, use_local_db, dynamodb_url, access_key, secret_key, region);
if (result.isFail())
{
Log.getLogger().error($"Failed to connectToDb !!! ");
Guard.Against.resultFail(result);
}
var task = dynamo_db_client.createDBIfNotExists(false);
task.Wait();
if (false == task.Result)
{
var err_msg = $"Failed to create DB Table !!!";
result.setFail(ServerErrorCode.DynamoDbTableCreateFailed, err_msg);
Guard.Against.resultFail(result);
}
}
}