Files
caliverse_server/BrokerApiServer/Extensions/AppBuilderExtensions.cs
2025-05-01 07:23:28 +09:00

272 lines
8.4 KiB
C#

using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using ServerBase;
using ServerCore;
using BrokerApiCore;
namespace BrokerApiServer;
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;
}
public static ServerConfigMetaverseBroker initBrokerServerConfig()
{
// 서버 설정
var server_config = new ServerConfigMetaverseBroker();
var server_config_path = "./Config/ServerConfig.json";
var full_path = Path.GetFullPath(server_config_path);
if (!File.Exists(full_path))
{
full_path = Path.GetFullPath(server_config_path, AppContext.BaseDirectory);
if (!File.Exists(full_path))
{
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 =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(serverConfig.MetaverseBroker?.JwtSecretKey ?? String.Empty))
};
});
services.AddScoped<UserAuthService>();
services.addExchangeServices();
// 메타데이터 관련 서비스 등록
services.AddSingleton<BrokerApiMetaLoader>();
services.AddScoped<BrokerMetaTableRef>( provider =>
{
var meta_loader = provider.GetRequiredService<BrokerApiMetaLoader>();
return new BrokerMetaTableRef(meta_loader.getMetaTable());
});
services.AddHostedService<MetaDataReloadScheduler>();
var jwt_option = new JwtOption
{
Secret = serverConfig.MetaverseBroker?.JwtSecretKey ?? String.Empty,
TokenValidityInMinutes = serverConfig.MetaverseBroker?.ExpireMinutes ?? 1
};
services.AddSingleton(jwt_option);
services.AddScoped<JwtGenerator>(provider =>
{
return new JwtGenerator(jwt_option);
});
services.AddScoped<JwtParser>(provider =>
{
return new JwtParser(jwt_option);
});
services.AddScoped<PlanetService>();
// 미들웨어 설정
services.AddScoped<ResultLoggingMiddleware>();
}
public static void addInfraServices(this IServiceCollection services, ServerConfigMetaverseBroker serverConfig)
{
// 코어 리파지토리 서비스 설정
services.AddScoped<SsoAccountRepo>();
services.AddScoped<PlanetInfoRepo>();
services.AddScoped<PlanetItemExchangeOrderRepo>();
services.AddScoped<PlanetItemExchangeOrderAmountTotalLimitRepo>();
services.AddScoped<PlanetItemExchangeOrderAmountUserLimitRepo>();
services.AddDbContext<SsoAccountDbContext>(options =>
{
var connection_string = serverConfig.SsoAccountDb;
options.UseMySql(connection_string, ServerVersion.AutoDetect(connection_string), mySqlOptions =>
{
mySqlOptions.EnableRetryOnFailure(
maxRetryCount: 10,
maxRetryDelay: TimeSpan.FromSeconds(30),
errorNumbersToAdd: null
);
mySqlOptions.CommandTimeout(60);
mySqlOptions.MaxBatchSize(20);
});
});
services.AddDbContext<MetaverseBrokerDbContext>(options =>
{
var connection_string = serverConfig.MetaverseBroker?.MetaverseBrokerDb;
options.UseMySql(connection_string, ServerVersion.AutoDetect(connection_string), my_sql_options =>
{
my_sql_options.EnableRetryOnFailure(
maxRetryCount: 10,
maxRetryDelay: TimeSpan.FromSeconds(30),
errorNumbersToAdd: null
);
my_sql_options.CommandTimeout(60);
my_sql_options.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;
NullReferenceCheckHelper.throwIfNull(server_logic, () => $"BrokerServerLogic is null");
server_logic.onInit().Wait();
}
public static void metadataMangerInit(this IApplicationBuilder app, string? dataPath = null)
{
var meta_loader = app.ApplicationServices.GetRequiredService<BrokerApiMetaLoader>();
var result = meta_loader.load(dataPath);
if (result.isFail())
{
Log.getLogger().error($"MetaDataManager Init Failed => {result}");
throw new ApplicationException($"MetaDataManager Init Failed => {result}");
}
}
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();
return;
async Task validateSsoAccountDb()
{
var context = services.GetRequiredService<SsoAccountDbContext>();
try
{
if (await context.Database.CanConnectAsync())
{
Log.getLogger().info($"Sso Account DB Connection OK => {context.Database.GetConnectionString()}");
return;
}
Log.getLogger().error($"Sso Account DB Connection Failed => {context.Database.GetConnectionString()}");
}
catch (Exception ex)
{
Log.getLogger()
.error(
$"Sso Account DB Connection Failed => {ex.Message}, {context.Database.GetConnectionString()}");
}
throw new ApplicationException($"Failed to connect Sso Account Db !!!");
}
async Task validateMetaverseBrokerDb()
{
var context = services.GetRequiredService<MetaverseBrokerDbContext>();
try
{
if (await context.Database.CanConnectAsync())
{
Log.getLogger()
.info($"Metaverse-Broker DB Connection OK => {context.Database.GetConnectionString()}");
var pending_migrations = await context.Database.GetPendingMigrationsAsync();
var migrations = pending_migrations as string[] ?? pending_migrations.ToArray();
if (migrations.Any())
{
Log.getLogger().error($"{context.Database.ToString()} 마이그레션이 필요함 !!!");
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()}");
}
throw new ApplicationException($"Failed to connect Broker Db !!!");
}
async Task migrateMetaverseBrokerDbForDevelopment()
{
// if (!env.IsDevelopment())
// {
// return;
// }
var context = services.GetRequiredService<MetaverseBrokerDbContext>();
try
{
await context.Database.MigrateAsync();
}
catch (Exception ex)
{
Log.getLogger().error($"Metaverse-Broker DB Migrate 실패 => {ex.Message}");
}
}
}
}