118 lines
4.4 KiB
C#
118 lines
4.4 KiB
C#
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.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<MessageRouter>();
|
|
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>();
|
|
builder.Services.AddSingleton<IZoneLeaseService, ZoneLeaseService>();
|
|
builder.Services.AddHostedService(sp => (ZoneLeaseService)sp.GetRequiredService<IZoneLeaseService>());
|
|
builder.Services.AddSingleton<IWalPublisher, WalPublisher>();
|
|
builder.Services.AddScoped<IAccountsRepository, AccountsRepository>();
|
|
builder.Services.AddSingleton<IPasswordHasher, Pbkdf2PasswordHasher>();
|
|
builder.Services.AddScoped<IAuthService, AuthService>();
|
|
builder.Services.AddSingleton<ISessionRegistry, SessionRegistry>();
|
|
|
|
// Health checks (optional DB/Redis implementations)
|
|
builder.Services.AddHealthChecks()
|
|
.AddCheck<DatabaseHealthCheck>("mysql", tags: new[] { "ready" });
|
|
// .AddCheck<RedisHealthCheck>("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>();
|
|
_ = 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);
|
|
|
|
await app.RunAsync();
|