// SOR.Host — Multi-service runner // // This is the entry point for the entire SOR server. It reads the ENABLED_SERVICES // environment variable and starts exactly those service modules in a single process. // // This is also the ONLY file in the codebase where concrete networking implementations // (WebSocket, NATS, Redis) are wired to their abstractions. All other code depends on // interfaces only. To swap a transport or broker, change this file — nothing else. // // Examples: // ENABLED_SERVICES=all → run everything (development) // ENABLED_SERVICES=gateway,auth → run only Gateway + Auth (small VM) // ENABLED_SERVICES=gateway → run only Gateway (dedicated gateway pod) using SOR.Auth; using SOR.Bazaar; using SOR.Chat; using SOR.Collection; using SOR.Content; using SOR.Game; using SOR.Gateway; using SOR.Matchmaking; using SOR.Versioning; using SOR.Networking.Nats; using SOR.Networking.Redis; using SOR.Networking.WebSocket; using SOR.Shared; using Serilog; using StackExchange.Redis; using NATS.Client.Core; using NATS.Client.Hosting; using Microsoft.AspNetCore.WebSockets; using Microsoft.AspNetCore.Server.Kestrel.Core; using SOR.Auth.Handlers; // ── ENABLED_SERVICES ────────────────────────────────────────────────────────── // Read which services this instance should run. // Environment variable format: comma-separated service names. // Special value "all" runs every registered service (convenient for development). // // Example Kubernetes env: // - name: ENABLED_SERVICES // value: "gateway,auth" var rawServices = Environment.GetEnvironmentVariable("ENABLED_SERVICES") ?? "all"; var enabledServices = rawServices .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) .ToHashSet(StringComparer.OrdinalIgnoreCase); // Local function: returns true if the named service should start on this instance. bool IsEnabled(string name) => enabledServices.Contains("all") || enabledServices.Contains(name); // ── BUILDER ─────────────────────────────────────────────────────────────────── var builder = WebApplication.CreateBuilder(args); // Auth gRPC calls are internal-only and should not share the public WebSocket listener. // When auth is co-located with gateway and Services:Auth points at a loopback HTTP URL, // explicitly bind the public HTTP/WebSocket port and add a dedicated HTTP/2 loopback // listener for gRPC on the configured auth port. if (IsEnabled("auth") && Uri.TryCreate(builder.Configuration["Services:Auth"], UriKind.Absolute, out var authServiceUri) && string.Equals(authServiceUri.Scheme, Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase) && authServiceUri.IsLoopback) { builder.WebHost.ConfigureKestrel(options => { options.ListenAnyIP(8080, listenOptions => { listenOptions.Protocols = HttpProtocols.Http1; }); options.ListenLocalhost(authServiceUri.Port, listenOptions => { listenOptions.Protocols = HttpProtocols.Http2; }); }); } // ── Logging ─────────────────────────────────────────────────────────────────── // Replace .NET's default logger with Serilog. // Configuration comes from the "Serilog" section of appsettings.json. // ReadFrom.Configuration automatically picks up sinks, minimum levels, and enrichers. builder.Host.UseSerilog((context, config) => config.ReadFrom.Configuration(context.Configuration)); // ── Shared services ─────────────────────────────────────────────────────────── // Registers IMessageSerializer (SystemTextJsonSerializer by default). // To swap to MessagePack: after this call, add: // builder.Services.AddSingleton() // which overrides the default registration. builder.Services.AddSharedServices(); // ── Shared infrastructure (Singleton per process) ───────────────────────────── // Redis connection multiplexer: one connection pool for the entire process. // All services that need Redis inject IConnectionMultiplexer from DI. // GetConnectionString("Redis") reads from ConnectionStrings:Redis in appsettings.json // or the ConnectionStrings__Redis environment variable. builder.Services.AddSingleton( ConnectionMultiplexer.Connect( builder.Configuration.GetConnectionString("Redis") ?? throw new InvalidOperationException( "Missing configuration: ConnectionStrings:Redis. " + "Set this to your Redis connection string (e.g., 'localhost:6379')."))); // NATS client: one connection for the entire process. // AddNats is from NATS.Client.Hosting and registers NatsConnection as Singleton, // exposed as both NatsConnection and INatsConnection. // The 'opts with { Url = ... }' syntax uses a C# record 'with' expression to clone the // default options and set only the URL — all other defaults remain unchanged. builder.Services.AddNats(configureOpts: opts => opts with { Url = builder.Configuration["Nats:Url"] ?? throw new InvalidOperationException( "Missing configuration: Nats:Url. " + "Set this to your NATS server URL (e.g., 'nats://localhost:4222').") }); // ── Health checks ───────────────────────────────────────────────────────────── // Minimal health check for Kubernetes liveness/readiness probes. // Returns 200 OK at /health if the process is running. // TODO: add dependency health checks (Redis, NATS, Postgres) per service. builder.Services.AddHealthChecks(); // ── Networking transports ───────────────────────────────────────────────────── // These are the CONCRETE implementations of the networking abstractions. // This section is the "wiring" point. To swap a transport, change only here. // AddWebSockets must be called here (from the Web SDK host project) rather than // inside SOR.Networking.WebSocket.ServiceRegistration, because the AddWebSockets // extension method resolves correctly only from a Microsoft.NET.Sdk.Web project. // Without this call, context.WebSockets.IsWebSocketRequest is always false. if (IsEnabled("gateway")) builder.Services.AddWebSockets(opts => { // ASP.NET Core's built-in keep-alive interval (protocol-level ping/pong). // Our WebSocketClientConnection also sends application-level pings independently. opts.KeepAliveInterval = TimeSpan.FromSeconds(30); }); // WebSocket transport: ITransport → WebSocketTransport // Reads options from "WebSocket" config section. if (IsEnabled("gateway")) builder.Services.AddWebSocketTransport(builder.Configuration); // NATS event bus: IEventBus → NatsEventBus (wraps the INatsClient registered above) builder.Services.AddNatsEventBus(builder.Configuration); // Redis client push: IClientPush → RedisClientPush (write side of push delivery) // The Gateway's read side (RedisPushSubscriber) is internal to SOR.Gateway. builder.Services.AddRedisClientPush(); // ── Service modules ─────────────────────────────────────────────────────────── // Each service registers its own handlers, options, DbContext, repositories, etc. // Only services listed in ENABLED_SERVICES are started. if (IsEnabled("auth")) builder.Services.AddAuthService(builder.Configuration); if (IsEnabled("chat")) builder.Services.AddChatService(builder.Configuration); if (IsEnabled("collection")) builder.Services.AddCollectionService(builder.Configuration); if (IsEnabled("gateway")) builder.Services.AddGatewayService(builder.Configuration); if (IsEnabled("bazaar")) builder.Services.AddBazaarService(builder.Configuration); if (IsEnabled("content")) builder.Services.AddContentService(builder.Configuration); if (IsEnabled("versioning")) builder.Services.AddVersioningService(builder.Configuration); if (IsEnabled("matchmaking")) builder.Services.AddMatchmakingService(builder.Configuration); if (IsEnabled("game")) builder.Services.AddGameService(builder.Configuration); // TODO: Uncomment as each service is implemented: // if (IsEnabled("leaderboard")) builder.Services.AddLeaderboardService(builder.Configuration); // if (IsEnabled("admin")) builder.Services.AddAdminService(builder.Configuration); // ── BUILD ───────────────────────────────────────────────────────────────────── var app = builder.Build(); // ── Middleware pipeline ─────────────────────────────────────────────────────── // Middleware runs in the order it's added. Order matters. // WebSocket upgrade support: MUST come before UseRouting and UseWebSocketTransport. // This activates the protocol-level WebSocket upgrade handler in Kestrel. if (IsEnabled("gateway")) app.UseWebSockets(); // WebSocket upgrade interceptor: MUST come before UseRouting. // Intercepts HTTP upgrade requests to "/ws" and hands them to WebSocketTransport. if (IsEnabled("gateway")) app.UseWebSocketTransport(); // Routing: maps URL paths to gRPC service routes. app.UseRouting(); // ── Endpoints ───────────────────────────────────────────────────────────────── // gRPC service routes: map each handler to its Protobuf-defined URL. if (IsEnabled("auth")) app.MapGrpcService(); // Health check endpoint: Kubernetes probes GET /health to check liveness. app.MapHealthChecks("/health"); // ── RUN ─────────────────────────────────────────────────────────────────────── Log.Information("SOR Host starting. Services: {Services}", rawServices); // RunAsync blocks until the process receives a shutdown signal (SIGTERM, Ctrl+C). // On shutdown, ASP.NET Core calls StopAsync on all IHostedService implementations // (including GatewayHostedService) in reverse registration order. await app.RunAsync();