using System.Net; using System.Net.Sockets; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Hosting; using Server.Data; using Server.Networking; using Server.Networking.Handling; using Server.Networking.Messages; using Server.Persistence; using Server.Redis; using Server.Services; using Server.Services.Auth; var builder = WebApplication.CreateBuilder(args); // ---- MySQL conn string from env ---- string mysqlConnectionString = ConnectionStringFactory.BuildMySqlFromEnv(); // ---- Services (before Build) ---- builder.Services.AddSingleton(); 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(); builder.Services.AddSingleton(); builder.Services.AddHostedService(sp => (ZoneLeaseService)sp.GetRequiredService()); builder.Services.AddSingleton(); builder.Services.AddScoped(); builder.Services.AddSingleton(); builder.Services.AddScoped(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); // if not already builder.Services.AddSingleton(); // add more handlers similarly builder.Services.AddSingleton(); // Health checks (optional DB/Redis implementations) builder.Services.AddHealthChecks() .AddCheck("mysql", tags: new[] { "ready" }); // .AddCheck("redis", tags: new[] { "ready" }); var app = builder.Build(); // ---- 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); } }); // ---- 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); await app.RunAsync();