Add networking foundation — 9-project C# solution (compiles clean)
Implements the modular networking layer for SOR Server: - SOR.Networking.Abstractions: pure interfaces (ITransport, IClientConnection, IMessageSerializer, IMessageDispatcher, IMessageHandler, IEventBus, IClientPush) - SOR.Networking.WebSocket: ITransport + IClientConnection over System.Net.WebSockets - SOR.Networking.Nats: IEventBus over NATS.Net (INatsConnection) - SOR.Networking.Redis: IClientPush over Redis Pub/Sub - SOR.Shared: ServiceResult<T>, RedisKeys, NatsSubjects, ServerMessage, JSON serializer - SOR.Shared.Proto: auth.proto with gRPC AuthService contract - SOR.Gateway: accept loop, auth handshake, dispatcher, Redis push subscriber - SOR.Auth: stub gRPC handler (placeholder responses) - SOR.Host: multi-service runner via ENABLED_SERVICES env var; wires all DI All concrete implementations are wired exclusively in SOR.Host — every transport, broker, and push implementation can be swapped by changing only Program.cs. dotnet build SOR.slnx → 0 errors, 0 warnings Generated with [Claude Code](https://claude.ai/code) via [Happy](https://happy.engineering) Co-Authored-By: Claude <noreply@anthropic.com> Co-Authored-By: Happy <yesreply@happy.engineering>
This commit is contained in:
@@ -0,0 +1,177 @@
|
||||
// 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.Gateway;
|
||||
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 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);
|
||||
|
||||
// ── 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<IMessageSerializer, MessagePackSerializer>()
|
||||
// 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<IConnectionMultiplexer>(
|
||||
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("gateway")) builder.Services.AddGatewayService(builder.Configuration);
|
||||
|
||||
// TODO: Uncomment as each service is implemented:
|
||||
// if (IsEnabled("chat")) builder.Services.AddChatService(builder.Configuration);
|
||||
// if (IsEnabled("collection")) builder.Services.AddCollectionService(builder.Configuration);
|
||||
// if (IsEnabled("bazaar")) builder.Services.AddBazaarService(builder.Configuration);
|
||||
// if (IsEnabled("leaderboard")) builder.Services.AddLeaderboardService(builder.Configuration);
|
||||
// if (IsEnabled("content")) builder.Services.AddContentService(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<AuthGrpcHandler>();
|
||||
|
||||
// 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();
|
||||
@@ -0,0 +1,33 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
<PropertyGroup>
|
||||
<AssemblyName>SOR.Host</AssemblyName>
|
||||
|
||||
<!-- OutputType=Exe: this is the executable entry point for the entire server.
|
||||
All other projects are libraries (no OutputType means library by default).
|
||||
There is exactly one executable project in the solution. -->
|
||||
<OutputType>Exe</OutputType>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- Infrastructure clients — registered once in Host, shared by all services -->
|
||||
<PackageReference Include="StackExchange.Redis" />
|
||||
<PackageReference Include="NATS.Net" />
|
||||
|
||||
<!-- Serilog: structured logging provider -->
|
||||
<PackageReference Include="Serilog.AspNetCore" />
|
||||
<PackageReference Include="Serilog.Sinks.Console" />
|
||||
|
||||
<!-- All service modules and networking transports.
|
||||
SOR.Host is the ONLY project that references both the abstractions
|
||||
AND their concrete implementations. All other projects reference only
|
||||
Abstractions — the wiring happens here. -->
|
||||
<ProjectReference Include="..\SOR.Shared\SOR.Shared.csproj" />
|
||||
<ProjectReference Include="..\SOR.Shared.Proto\SOR.Shared.Proto.csproj" />
|
||||
<ProjectReference Include="..\SOR.Networking.Abstractions\SOR.Networking.Abstractions.csproj" />
|
||||
<ProjectReference Include="..\SOR.Networking.WebSocket\SOR.Networking.WebSocket.csproj" />
|
||||
<ProjectReference Include="..\SOR.Networking.Nats\SOR.Networking.Nats.csproj" />
|
||||
<ProjectReference Include="..\SOR.Networking.Redis\SOR.Networking.Redis.csproj" />
|
||||
<ProjectReference Include="..\SOR.Gateway\SOR.Gateway.csproj" />
|
||||
<ProjectReference Include="..\SOR.Auth\SOR.Auth.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"ConnectionStrings": {
|
||||
"Redis": "localhost:6379"
|
||||
},
|
||||
"Nats": {
|
||||
"Url": "nats://localhost:4222"
|
||||
},
|
||||
"WebSocket": {
|
||||
"Path": "/ws",
|
||||
"PingIntervalMs": 30000,
|
||||
"MaxMessageSizeBytes": 65536
|
||||
},
|
||||
"Gateway": {
|
||||
"AuthTimeoutMs": 10000,
|
||||
"MaxMessagesPerSecond": 20
|
||||
},
|
||||
"Services": {
|
||||
"Auth": "http://localhost:5001"
|
||||
},
|
||||
"Serilog": {
|
||||
"MinimumLevel": {
|
||||
"Default": "Information",
|
||||
"Override": {
|
||||
"Microsoft": "Warning",
|
||||
"Microsoft.AspNetCore": "Warning",
|
||||
"Grpc": "Warning",
|
||||
"System": "Warning"
|
||||
}
|
||||
},
|
||||
"WriteTo": [
|
||||
{
|
||||
"Name": "Console",
|
||||
"Args": {
|
||||
"outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {SourceContext}: {Message:lj}{NewLine}{Exception}"
|
||||
}
|
||||
}
|
||||
],
|
||||
"Enrich": [ "FromLogContext" ]
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user