Files
systemrevivalserver/Program.cs
T
2026-01-30 14:03:22 -05:00

280 lines
9.8 KiB
C#

using System.Net;
using System.Net.Sockets;
using DataServer.Data;
using GameServer;
using GameServer.Dungeon;
using GameServices;
using GameServices.Admin.Pages;
using GameServices.Auth;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.DataProtection.KeyManagement;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Hosting;
using Server.Networking;
using Server.Networking.Handling;
using Server.Networking.Messages;
using Server.Redis;
using StackExchange.Redis;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
// ---- Razor Pages for Admin Panel ----
builder.Services.AddRazorPages()
.AddRazorPagesOptions(options =>
{
options.RootDirectory = "/Services/Admin/Pages";
});
// ---- Session for Admin Auth ----
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromHours(8);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
options.Cookie.Name = ".Divers.Admin.Session";
options.Cookie.Path = "/admin";
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.Cookie.SameSite = SameSiteMode.Lax;
});
builder.Services.AddAntiforgery(o =>
{
o.Cookie.Name = ".Divers.Admin.AntiForgery";
o.Cookie.Path = "/admin";
o.Cookie.SecurePolicy = CookieSecurePolicy.Always;
o.Cookie.SameSite = SameSiteMode.Lax;
});
// ---- MySQL conn string from env ----
string mysqlConnectionString = ConnectionStringFactory.BuildMySqlFromEnv();
// ---- Services (before Build) ----
builder.Services.AddSingleton<NetworkManager>();
builder.Services.AddDbContext<GameDbContext>(options =>
options.UseMySql(mysqlConnectionString, ServerVersion.AutoDetect(mysqlConnectionString)));
builder.Services.AddOptions<DatabaseOptions>()
.Configure(o =>
{
o.ConnectionString = mysqlConnectionString;
o.CommandTimeoutSeconds = int.TryParse(Environment.GetEnvironmentVariable("DB_COMMAND_TIMEOUT_S"), out var t) ? t : 30;
o.MaxRetryCount = int.TryParse(Environment.GetEnvironmentVariable("DB_MAX_RETRY"), out var r) ? r : 3;
o.RetryBaseDelayMs = int.TryParse(Environment.GetEnvironmentVariable("DB_RETRY_BASE_MS"), out var d) ? d : 100;
})
.Validate(o => !string.IsNullOrWhiteSpace(o.ConnectionString), "DB connection string required")
.ValidateOnStart();
// Redis + zone leases + WAL
//builder.Services.AddSingleton<IRedisManager, RedisManager>();
var redisCs = RedisManager.BuildRedisConnectionStringFromEnv()
?? throw new Exception("REDIS_CONNECTION_STRING required");
var redisMux = ConnectionMultiplexer.Connect(redisCs);
builder.Services.AddSingleton<IConnectionMultiplexer>(redisMux);
builder.Services.AddSingleton<IRedisManager, RedisManager>();
builder.Services.AddScoped<IAccountsRepository, AccountsRepository>();
builder.Services.AddScoped<ISessionAudit, SessionAudit>();
builder.Services.AddSingleton<IPasswordHasher, Pbkdf2PasswordHasher>();
builder.Services.AddScoped<IAuthService, AuthService>();
builder.Services.AddSingleton<ISessionRegistry, SessionRegistry>();
builder.Services.AddSingleton<IMessageSerializer, JsonSerializerAdapter>();
// Message handlers
builder.Services.AddSingleton<IClientMessageHandler, AuthHandler>();
builder.Services.AddSingleton<DungeonHandler>();
builder.Services.AddSingleton<IClientMessageHandler>(sp => sp.GetRequiredService<DungeonHandler>());
builder.Services.AddSingleton<LootService>();
builder.Services.AddSingleton<CraftingHandler>();
builder.Services.AddSingleton<MessageRouter>();
builder.Services.AddSingleton<IAdminAuthService, AdminAuthService>();
builder.Services.AddSingleton<ICdnBrowserService, MinioCdnBrowserService>();
builder.Services.AddSingleton<IServerBroadcastService, ServerBroadcastService>();
builder.Services.AddHttpClient(); // For CDN file hash computation
// Health checks
builder.Services.AddHealthChecks()
.AddCheck<DatabaseHealthCheck>("mysql", tags: new[] { "ready" });
var dpDb = redisMux.GetDatabase(2);
builder.Services.AddDataProtection()
.SetApplicationName("Void")
.PersistKeysToStackExchangeRedis(() => dpDb, "Void:DataProtectionKeys");
//var app = builder.Build();
//// DEBUG: Log registered handlers
//var router = app.Services.GetRequiredService<MessageRouter>();
//var handlers = app.Services.GetServices<IClientMessageHandler>();
//foreach (var h in handlers)
//{
// app.Logger.LogInformation("Registered handler: {Type} with opcodes: {OpCodes}",
// h.GetType().Name,
// string.Join(", ", h.SupportedOpCodes));
//}
var app = builder.Build();
var fwdOpts = new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
};
// In Kubernetes/ingress, these are often required because the proxy IPs are not “known”
fwdOpts.KnownNetworks.Clear();
fwdOpts.KnownProxies.Clear();
app.UseForwardedHeaders(fwdOpts);
app.Use(async (ctx, next) =>
{
ctx.Response.Headers["X-Pod"] = Environment.GetEnvironmentVariable("HOSTNAME") ?? "unknown";
await next();
});
var keyManager = app.Services.GetRequiredService<IKeyManager>();
var keys = keyManager.GetAllKeys();
app.Logger.LogInformation("DP keys present: {Count}", keys.Count);
foreach (var k in keys)
app.Logger.LogInformation("DP key: {Id} Created={Created} Expires={Expires} Revoked={Revoked}",
k.KeyId, k.CreationDate, k.ExpirationDate, k.IsRevoked);
var dungeonHandler = app.Services.GetRequiredService<DungeonHandler>();
await dungeonHandler.InitializeAsync();
var craftingHandler = app.Services.GetRequiredService<CraftingHandler>();
await craftingHandler.InitializeAsync();
// DEBUG: Directly try to resolve each service
app.Logger.LogInformation("=== DI Debug Start ===");
try
{
var serializer = app.Services.GetRequiredService<IMessageSerializer>();
app.Logger.LogInformation("IMessageSerializer resolved: {Type}", serializer.GetType().Name);
}
catch (Exception ex)
{
app.Logger.LogError(ex, "Failed to resolve IMessageSerializer");
}
//try
//{
// var matchMgr = app.Services.GetRequiredService<MatchManager>();
// app.Logger.LogInformation("MatchManager resolved OK");
//}
//catch (Exception ex)
//{
// app.Logger.LogError(ex, "Failed to resolve MatchManager");
//}
//try
//{
// var gameHandler = app.Services.GetRequiredService<GameHandler>();
// app.Logger.LogInformation("GameHandler resolved OK, opcodes: {Ops}", string.Join(",", gameHandler.SupportedOpCodes));
//}
//catch (Exception ex)
//{
// app.Logger.LogError(ex, "Failed to resolve GameHandler");
//}
var handlers = app.Services.GetServices<IClientMessageHandler>().ToList();
app.Logger.LogInformation("IClientMessageHandler count: {Count}", handlers.Count);
foreach (var h in handlers)
{
app.Logger.LogInformation(" Handler: {Type} with opcodes: {OpCodes}",
h.GetType().Name,
string.Join(", ", h.SupportedOpCodes));
}
var router = app.Services.GetRequiredService<MessageRouter>();
app.Logger.LogInformation("MessageRouter resolved OK");
app.Logger.LogInformation("=== DI Debug End ===");
// ---- Health endpoints ----
app.MapGet("/health/live", () => Results.Ok(new { status = "live" }));
app.MapGet("/health/ready", async (IRedisManager rm, HealthCheckService hc) =>
{
// Ping Redis and run registered health checks tagged "ready"
try
{
var pong = await rm.Db.PingAsync();
var report = await hc.CheckHealthAsync(r => r.Tags.Contains("ready"));
var ok = report.Status == HealthStatus.Healthy;
return ok
? Results.Ok(new { status = "ready", redisLatencyMs = pong.TotalMilliseconds })
: Results.StatusCode(503);
}
catch { return Results.StatusCode(503); }
});
// ---- Session middleware (must be before routing) ----
app.UseSession();
// ---- WebSockets endpoint ----
app.UseWebSockets(new WebSocketOptions { KeepAliveInterval = TimeSpan.FromSeconds(20) });
app.Map("/ws", async (HttpContext httpContext, NetworkManager networkManager) =>
{
if (!httpContext.WebSockets.IsWebSocketRequest)
{
httpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
return;
}
var ws = await httpContext.WebSockets.AcceptWebSocketAsync();
await networkManager.AcceptWebSocketAsync(httpContext, ws);
});
// ---- Start TCP listener ----
int tcpPort = int.TryParse(Environment.GetEnvironmentVariable("TCP_PORT"), out var parsed) ? parsed : 40000;
TcpListener? tcpListener = null;
try
{
tcpListener = new TcpListener(IPAddress.Any, tcpPort);
tcpListener.Start();
app.Logger.LogInformation("TCP listening on {Port}", tcpPort);
}
catch (Exception ex)
{
app.Logger.LogCritical(ex, "Failed to start TCP listener on port {Port}", tcpPort);
throw; // fail fast so k8s restarts the pod
}
var networkManager = app.Services.GetRequiredService<NetworkManager>();
_ = networkManager.AcceptTcpLoopAsync(tcpListener!, app.Lifetime.ApplicationStopping);
_ = networkManager.RunTickLoopAsync(app.Lifetime.ApplicationStopping);
// Graceful shutdown for TCP
app.Lifetime.ApplicationStopping.Register(() =>
{
try { tcpListener?.Stop(); } catch { }
});
// ---- (Optional) acquire a dev zone on startup ----
// var leases = app.Services.GetRequiredService<IZoneLeaseService>();
// _ = leases.TryAcquireAsync(zoneId: 1);
app.MapControllers();
app.MapRazorPages();
//Call two:
keyManager = app.Services.GetRequiredService<IKeyManager>();
keys = keyManager.GetAllKeys();
app.Logger.LogInformation("DP keys present: {Count}", keys.Count);
foreach (var k in keys)
app.Logger.LogInformation("DP key: {Id} Created={Created} Expires={Expires} Revoked={Revoked}",
k.KeyId, k.CreationDate, k.ExpirationDate, k.IsRevoked);
app.Logger.LogInformation("Admin panel available at /admin");
await app.RunAsync();