Add Redis, Wal, Services
This commit is contained in:
+61
-25
@@ -4,24 +4,26 @@ 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;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
//Test2
|
||||
// ---- Build connection string from env (K8s secrets env vars) ----
|
||||
|
||||
// ---- MySQL conn string from env ----
|
||||
string mysqlConnectionString = ConnectionStringFactory.BuildMySqlFromEnv();
|
||||
|
||||
// ---- Service registrations (MUST be before Build) ----
|
||||
// ---- Services (before Build) ----
|
||||
builder.Services.AddSingleton<MessageRouter>();
|
||||
builder.Services.AddSingleton<NetworkManager>();
|
||||
|
||||
// EF Core (single registration)
|
||||
builder.Services.AddDbContext<GameDbContext>(options =>
|
||||
options.UseMySql(mysqlConnectionString, ServerVersion.AutoDetect(mysqlConnectionString)));
|
||||
|
||||
// DatabaseOptions (used by DatabaseManager if you wired it)
|
||||
builder.Services.AddOptions<DatabaseOptions>()
|
||||
.Configure(o =>
|
||||
{
|
||||
@@ -33,22 +35,39 @@ builder.Services.AddOptions<DatabaseOptions>()
|
||||
.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>();
|
||||
|
||||
// Health checks (optional DB/Redis implementations)
|
||||
builder.Services.AddHealthChecks()
|
||||
.AddCheck<DatabaseHealthCheck>("mysql", tags: new[] { "ready" })
|
||||
//.AddCheck<RedisHealthCheck>("redis", tags: new[] { "ready" })
|
||||
;
|
||||
.AddCheck<DatabaseHealthCheck>("mysql", tags: new[] { "ready" });
|
||||
// .AddCheck<RedisHealthCheck>("redis", tags: new[] { "ready" });
|
||||
|
||||
// ---- Build the app AFTER all service registrations ----
|
||||
var app = builder.Build();
|
||||
|
||||
// ---- Health endpoints ----
|
||||
app.MapGet("/health/live", () => Results.Ok(new { status = "live" }));
|
||||
app.MapGet("/health/ready", () => Results.Ok(new { status = "ready" }));
|
||||
// ---- WebSockets endpoint ----
|
||||
app.UseWebSockets(new WebSocketOptions
|
||||
app.MapGet("/health/ready", async (IRedisManager rm, HealthCheckService hc) =>
|
||||
{
|
||||
KeepAliveInterval = TimeSpan.FromSeconds(20),
|
||||
ReceiveBufferSize = 64 * 1024
|
||||
// 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)
|
||||
@@ -56,21 +75,38 @@ app.Map("/ws", async (HttpContext httpContext, NetworkManager networkManager) =>
|
||||
httpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
|
||||
return;
|
||||
}
|
||||
|
||||
var acceptedWebSocket = await httpContext.WebSockets.AcceptWebSocketAsync();
|
||||
await networkManager.AcceptWebSocketAsync(httpContext, acceptedWebSocket);
|
||||
var ws = await httpContext.WebSockets.AcceptWebSocketAsync();
|
||||
await networkManager.AcceptWebSocketAsync(httpContext, ws);
|
||||
});
|
||||
// ---- Start TCP listener (after Build) ----
|
||||
|
||||
// ---- Start TCP listener ----
|
||||
int tcpPort = int.TryParse(Environment.GetEnvironmentVariable("TCP_PORT"), out var parsed) ? parsed : 40000;
|
||||
var tcpListener = new TcpListener(IPAddress.Any, tcpPort);
|
||||
tcpListener.Start();
|
||||
app.Logger.LogInformation("TCP listening on {Port}", tcpPort);
|
||||
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);
|
||||
|
||||
// ---- Tick loop ----
|
||||
_ = networkManager.AcceptTcpLoopAsync(tcpListener!, app.Lifetime.ApplicationStopping);
|
||||
_ = networkManager.RunTickLoopAsync(app.Lifetime.ApplicationStopping);
|
||||
|
||||
// ---- Run ----
|
||||
// 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();
|
||||
|
||||
Reference in New Issue
Block a user