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.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(); builder.Services.AddDbContext(options => options.UseMySql(mysqlConnectionString, ServerVersion.AutoDetect(mysqlConnectionString))); builder.Services.AddOptions() .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(); var redisCs = RedisManager.BuildRedisConnectionStringFromEnv() ?? throw new Exception("REDIS_CONNECTION_STRING required"); var redisMux = ConnectionMultiplexer.Connect(redisCs); builder.Services.AddSingleton(redisMux); builder.Services.AddSingleton(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddSingleton(); builder.Services.AddScoped(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); // Message handlers builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(sp => sp.GetRequiredService()); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddHttpClient(); // For CDN file hash computation // Health checks builder.Services.AddHealthChecks() .AddCheck("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(); //var handlers = app.Services.GetServices(); //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(); app.Use(async (ctx, next) => { ctx.Response.Headers["X-Pod"] = Environment.GetEnvironmentVariable("HOSTNAME") ?? "unknown"; await next(); }); var keyManager = app.Services.GetRequiredService(); 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(); await dungeonHandler.InitializeAsync(); var craftingHandler = app.Services.GetRequiredService(); await craftingHandler.InitializeAsync(); // DEBUG: Directly try to resolve each service app.Logger.LogInformation("=== DI Debug Start ==="); try { var serializer = app.Services.GetRequiredService(); 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(); // app.Logger.LogInformation("MatchManager resolved OK"); //} //catch (Exception ex) //{ // app.Logger.LogError(ex, "Failed to resolve MatchManager"); //} //try //{ // var gameHandler = app.Services.GetRequiredService(); // 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().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(); 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.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(); // _ = leases.TryAcquireAsync(zoneId: 1); app.MapControllers(); app.MapRazorPages(); //Call two: keyManager = app.Services.GetRequiredService(); 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();