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,15 @@
|
||||
# Build outputs
|
||||
bin/
|
||||
obj/
|
||||
|
||||
# User-specific files
|
||||
*.user
|
||||
*.suo
|
||||
.vs/
|
||||
|
||||
# Rider/JetBrains
|
||||
.idea/
|
||||
|
||||
# NuGet
|
||||
*.nupkg
|
||||
packages/
|
||||
@@ -0,0 +1,27 @@
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<!-- Target .NET 8 (LTS) in every project under this directory -->
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
|
||||
<!-- Nullable reference types: the compiler warns when a variable that can be null
|
||||
is used without a null check. Catches NullReferenceException at compile time. -->
|
||||
<Nullable>enable</Nullable>
|
||||
|
||||
<!-- Use the latest C# language version (C# 12 with .NET 8) -->
|
||||
<LangVersion>latest</LangVersion>
|
||||
|
||||
<!-- Treat all warnings as errors — keeps code quality high across all projects -->
|
||||
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
|
||||
|
||||
<!-- Implicit usings: automatically imports System, System.Linq,
|
||||
System.Collections.Generic, System.Threading.Tasks, etc.
|
||||
into every file so they don't need explicit using directives at the top. -->
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
|
||||
<!-- Library projects are not packaged as NuGet packages -->
|
||||
<IsPackable>false</IsPackable>
|
||||
|
||||
<!-- Ensure deterministic builds (same input always produces same output binary) -->
|
||||
<Deterministic>true</Deterministic>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,69 @@
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<!-- Central package management: all NuGet version numbers are declared here once.
|
||||
Individual .csproj files use <PackageReference Include="..." /> with no Version attribute.
|
||||
This prevents version drift — if you need to upgrade a package, change it here only. -->
|
||||
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- ── Dependency Injection ──────────────────────────────────────────── -->
|
||||
<!-- DI abstractions (IServiceCollection, IServiceProvider) for class library projects.
|
||||
Web SDK projects (Microsoft.NET.Sdk.Web) get this transitively from the framework.
|
||||
Pure class libraries need to reference it directly. -->
|
||||
<PackageVersion Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.0" />
|
||||
|
||||
<!-- ── gRPC ────────────────────────────────────────────────────────────── -->
|
||||
<!-- ASP.NET Core gRPC server + client + Protobuf code generation -->
|
||||
<PackageVersion Include="Grpc.AspNetCore" Version="2.62.0" />
|
||||
<!-- gRPC client factory — integrates with ASP.NET Core DI + HttpClientFactory -->
|
||||
<PackageVersion Include="Grpc.Net.ClientFactory" Version="2.62.0" />
|
||||
|
||||
<!-- ── NATS ───────────────────────────────────────────────────────────── -->
|
||||
<!-- Official NATS .NET client (NATS.Net is the modern unified package) -->
|
||||
<PackageVersion Include="NATS.Net" Version="2.3.0" />
|
||||
|
||||
<!-- ── Redis ─────────────────────────────────────────────────────────── -->
|
||||
<!-- StackExchange.Redis: battle-tested, high-performance Redis client for .NET -->
|
||||
<PackageVersion Include="StackExchange.Redis" Version="2.7.33" />
|
||||
|
||||
<!-- ── Entity Framework Core ─────────────────────────────────────────── -->
|
||||
<!-- EF Core ORM: maps C# classes to database tables, generates SQL queries -->
|
||||
<PackageVersion Include="Microsoft.EntityFrameworkCore" Version="8.0.0" />
|
||||
<!-- PostgreSQL driver for EF Core (Npgsql) -->
|
||||
<PackageVersion Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="8.0.0" />
|
||||
<!-- Design-time tools: enables 'dotnet ef migrations add' commands -->
|
||||
<PackageVersion Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.0" />
|
||||
|
||||
<!-- ── Logging ────────────────────────────────────────────────────────── -->
|
||||
<!-- Serilog: structured logging library (replaces Microsoft's default logger) -->
|
||||
<PackageVersion Include="Serilog.AspNetCore" Version="8.0.0" />
|
||||
<!-- Console sink: writes structured log events to stdout -->
|
||||
<PackageVersion Include="Serilog.Sinks.Console" Version="5.0.0" />
|
||||
<!-- Seq sink: sends logs to a Seq log server for querying and alerting -->
|
||||
<PackageVersion Include="Serilog.Sinks.Seq" Version="7.0.0" />
|
||||
|
||||
<!-- ── Serialization ─────────────────────────────────────────────────── -->
|
||||
<!-- MessagePack: binary serialization, faster + smaller than JSON.
|
||||
Registered as an alternative IMessageSerializer when performance matters. -->
|
||||
<PackageVersion Include="MessagePack" Version="2.5.140" />
|
||||
|
||||
<!-- ── Health Checks ─────────────────────────────────────────────────── -->
|
||||
<!-- Redis health check for Kubernetes liveness/readiness probes -->
|
||||
<PackageVersion Include="AspNetCore.HealthChecks.Redis" Version="8.0.1" />
|
||||
|
||||
<!-- ── Testing ───────────────────────────────────────────────────────── -->
|
||||
<!-- xUnit: the test framework (test discovery, runner, assertions) -->
|
||||
<PackageVersion Include="xunit" Version="2.6.6" />
|
||||
<!-- xUnit Visual Studio adapter: makes tests visible in VS Test Explorer -->
|
||||
<PackageVersion Include="xunit.runner.visualstudio" Version="2.5.7" />
|
||||
<!-- MSTest SDK dependency for xUnit runner -->
|
||||
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
|
||||
<!-- Moq: create mock implementations of interfaces for unit testing -->
|
||||
<PackageVersion Include="Moq" Version="4.20.70" />
|
||||
<!-- FluentAssertions: readable assertion syntax (result.Should().BeTrue()) -->
|
||||
<PackageVersion Include="FluentAssertions" Version="6.12.0" />
|
||||
<!-- In-process test server for integration tests -->
|
||||
<PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="8.0.0" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,13 @@
|
||||
<Solution>
|
||||
<Folder Name="/src/">
|
||||
<Project Path="src/SOR.Auth/SOR.Auth.csproj" />
|
||||
<Project Path="src/SOR.Gateway/SOR.Gateway.csproj" />
|
||||
<Project Path="src/SOR.Host/SOR.Host.csproj" />
|
||||
<Project Path="src/SOR.Networking.Abstractions/SOR.Networking.Abstractions.csproj" />
|
||||
<Project Path="src/SOR.Networking.Nats/SOR.Networking.Nats.csproj" />
|
||||
<Project Path="src/SOR.Networking.Redis/SOR.Networking.Redis.csproj" />
|
||||
<Project Path="src/SOR.Networking.WebSocket/SOR.Networking.WebSocket.csproj" />
|
||||
<Project Path="src/SOR.Shared.Proto/SOR.Shared.Proto.csproj" />
|
||||
<Project Path="src/SOR.Shared/SOR.Shared.csproj" />
|
||||
</Folder>
|
||||
</Solution>
|
||||
@@ -0,0 +1,98 @@
|
||||
namespace SOR.Auth.Handlers;
|
||||
|
||||
using Grpc.Core;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using SOR.Shared.Proto;
|
||||
|
||||
/// <summary>
|
||||
/// gRPC handler stub for the Auth service.
|
||||
///
|
||||
/// STATUS: Foundation stub only. All methods return placeholder responses.
|
||||
/// Real business logic (database, password hashing, session management)
|
||||
/// will be implemented when the Auth service is built out.
|
||||
///
|
||||
/// This stub is sufficient for the networking foundation phase:
|
||||
/// - The Gateway calls ValidateToken — this returns Valid=false for all tokens,
|
||||
/// meaning no connections will authenticate until the real implementation is in place.
|
||||
/// - The project compiles and the gRPC route is registered correctly.
|
||||
///
|
||||
/// When implementing for real:
|
||||
/// 1. Add IAuthService injection to the constructor
|
||||
/// 2. Replace each return statement with the actual service call
|
||||
/// 3. Map ServiceResult{T} to the Protobuf response message
|
||||
/// </summary>
|
||||
public sealed class AuthGrpcHandler : AuthService.AuthServiceBase
|
||||
{
|
||||
private readonly ILogger<AuthGrpcHandler> _logger;
|
||||
|
||||
public AuthGrpcHandler(ILogger<AuthGrpcHandler> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Validates a session token.
|
||||
/// STUB: always returns Valid=false until real implementation is added.
|
||||
/// </summary>
|
||||
public override Task<ValidateTokenResponse> ValidateToken(
|
||||
ValidateTokenRequest request,
|
||||
ServerCallContext context)
|
||||
{
|
||||
_logger.LogDebug("ValidateToken called (stub) for token length={Length}",
|
||||
request.SessionToken.Length);
|
||||
|
||||
// STUB: return invalid until real Auth business logic is implemented.
|
||||
return Task.FromResult(new ValidateTokenResponse
|
||||
{
|
||||
Valid = false,
|
||||
UserId = string.Empty,
|
||||
DisplayName = string.Empty
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Authenticates a user with email + password.
|
||||
/// STUB: always returns failure.
|
||||
/// </summary>
|
||||
public override Task<LoginResponse> Login(
|
||||
LoginRequest request,
|
||||
ServerCallContext context)
|
||||
{
|
||||
_logger.LogDebug("Login called (stub) for email={Email}", request.Email);
|
||||
|
||||
return Task.FromResult(new LoginResponse
|
||||
{
|
||||
Success = false,
|
||||
ErrorCode = "NOT_IMPLEMENTED"
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers a new user account.
|
||||
/// STUB: always returns failure.
|
||||
/// </summary>
|
||||
public override Task<RegisterResponse> Register(
|
||||
RegisterRequest request,
|
||||
ServerCallContext context)
|
||||
{
|
||||
_logger.LogDebug("Register called (stub)");
|
||||
|
||||
return Task.FromResult(new RegisterResponse
|
||||
{
|
||||
Success = false,
|
||||
ErrorCode = "NOT_IMPLEMENTED"
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Revokes a session token.
|
||||
/// STUB: no-op (returns success — revocation of non-existent tokens is idempotent).
|
||||
/// </summary>
|
||||
public override Task<LogoutResponse> Logout(
|
||||
LogoutRequest request,
|
||||
ServerCallContext context)
|
||||
{
|
||||
_logger.LogDebug("Logout called (stub)");
|
||||
return Task.FromResult(new LogoutResponse());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<AssemblyName>SOR.Auth</AssemblyName>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||
|
||||
<!-- Grpc.AspNetCore provides the server base classes (AuthService.AuthServiceBase)
|
||||
that the handler inherits from. -->
|
||||
<PackageReference Include="Grpc.AspNetCore" />
|
||||
|
||||
<ProjectReference Include="..\SOR.Shared\SOR.Shared.csproj" />
|
||||
<ProjectReference Include="..\SOR.Shared.Proto\SOR.Shared.Proto.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,35 @@
|
||||
namespace SOR.Auth;
|
||||
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
/// <summary>
|
||||
/// Registers Auth service dependencies in the DI container.
|
||||
///
|
||||
/// STATUS: Foundation stub only.
|
||||
/// Real registration (DbContext, repositories, IAuthService) will be added
|
||||
/// when Auth business logic is implemented.
|
||||
///
|
||||
/// Currently only registers the gRPC infrastructure so the handler can be
|
||||
/// mapped in SOR.Host.Program.cs via app.MapGrpcService{AuthGrpcHandler}().
|
||||
/// </summary>
|
||||
public static class ServiceRegistration
|
||||
{
|
||||
public static IServiceCollection AddAuthService(
|
||||
this IServiceCollection services,
|
||||
IConfiguration configuration)
|
||||
{
|
||||
// AddGrpc() registers the gRPC server infrastructure in ASP.NET Core.
|
||||
// Required before MapGrpcService{T} can be called in Program.cs.
|
||||
// Safe to call multiple times — ASP.NET Core deduplicates registrations.
|
||||
services.AddGrpc();
|
||||
|
||||
// TODO (when implementing Auth business logic):
|
||||
// services.Configure<AuthOptions>(configuration.GetSection("Auth"));
|
||||
// services.AddDbContext<AuthDbContext>(opts => opts.UseNpgsql(...));
|
||||
// services.AddScoped<IAuthRepository, AuthRepository>();
|
||||
// services.AddScoped<IAuthService, AuthService>();
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
namespace SOR.Gateway.Auth;
|
||||
|
||||
using Microsoft.Extensions.Logging;
|
||||
using SOR.Shared.Proto;
|
||||
|
||||
/// <summary>
|
||||
/// IGatewayAuthValidator implementation that calls the Auth gRPC service.
|
||||
///
|
||||
/// This is the only place in SOR.Gateway where the generated gRPC client type appears.
|
||||
/// All other Gateway code uses IGatewayAuthValidator (the interface).
|
||||
///
|
||||
/// The gRPC client (AuthService.AuthServiceClient) is injected via DI.
|
||||
/// It is registered in ServiceRegistration.cs using AddGrpcClient{T}(), which
|
||||
/// integrates gRPC client lifetime management with ASP.NET Core's HttpClientFactory.
|
||||
///
|
||||
/// Lifetime: Singleton (gRPC client factory handles connection pooling internally).
|
||||
/// </summary>
|
||||
public sealed class GatewayAuthValidator : IGatewayAuthValidator
|
||||
{
|
||||
// AuthService.AuthServiceClient is the generated client stub from auth.proto.
|
||||
// It wraps a gRPC channel and provides typed RPC methods (ValidateTokenAsync, etc.).
|
||||
private readonly AuthService.AuthServiceClient _grpcClient;
|
||||
private readonly ILogger<GatewayAuthValidator> _logger;
|
||||
|
||||
public GatewayAuthValidator(
|
||||
AuthService.AuthServiceClient grpcClient,
|
||||
ILogger<GatewayAuthValidator> logger)
|
||||
{
|
||||
_grpcClient = grpcClient;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public async Task<(bool Valid, string UserId, string DisplayName)> ValidateAsync(
|
||||
string sessionToken,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Call the Auth service's ValidateToken RPC.
|
||||
// This is a synchronous RPC (request → response) over gRPC.
|
||||
var response = await _grpcClient.ValidateTokenAsync(
|
||||
new ValidateTokenRequest { SessionToken = sessionToken },
|
||||
cancellationToken: cancellationToken);
|
||||
|
||||
if (!response.Valid)
|
||||
{
|
||||
_logger.LogDebug("Token validation failed: token is invalid or expired");
|
||||
return (false, string.Empty, string.Empty);
|
||||
}
|
||||
|
||||
return (true, response.UserId, response.DisplayName);
|
||||
}
|
||||
catch (Grpc.Core.RpcException ex)
|
||||
{
|
||||
// gRPC exception: Auth service is unreachable, overloaded, or returned an error.
|
||||
// Treat as invalid — never accept a connection that cannot be validated.
|
||||
_logger.LogWarning(ex,
|
||||
"Auth gRPC call failed during token validation: {Status}", ex.Status.StatusCode);
|
||||
return (false, string.Empty, string.Empty);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
namespace SOR.Gateway.Auth;
|
||||
|
||||
/// <summary>
|
||||
/// Validates session tokens during the Gateway auth handshake.
|
||||
///
|
||||
/// This interface wraps the generated Auth gRPC client stub so that:
|
||||
/// - Gateway code depends on this interface, not the gRPC type
|
||||
/// - The implementation can be swapped in tests (mock the interface)
|
||||
/// - The gRPC dependency is contained within GatewayAuthValidator.cs
|
||||
///
|
||||
/// If the Auth service call mechanism changes (e.g., gRPC → REST), only
|
||||
/// GatewayAuthValidator changes. Gateway.ConnectionLoop does not change.
|
||||
/// </summary>
|
||||
public interface IGatewayAuthValidator
|
||||
{
|
||||
/// <summary>
|
||||
/// Validates a session token by calling the Auth service.
|
||||
///
|
||||
/// Returns a tuple:
|
||||
/// - Valid: true if the token exists and has not expired or been revoked
|
||||
/// - UserId: the token owner's user ID (empty string if Valid = false)
|
||||
/// - DisplayName: the token owner's display name (empty string if Valid = false)
|
||||
///
|
||||
/// On Auth service unavailability (gRPC exception), returns Valid = false.
|
||||
/// This treats auth failures as invalid — better to reject than to let
|
||||
/// potentially invalid connections through.
|
||||
/// </summary>
|
||||
Task<(bool Valid, string UserId, string DisplayName)> ValidateAsync(
|
||||
string sessionToken,
|
||||
CancellationToken cancellationToken = default);
|
||||
}
|
||||
@@ -0,0 +1,365 @@
|
||||
namespace SOR.Gateway;
|
||||
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using StackExchange.Redis;
|
||||
using SOR.Gateway.Auth;
|
||||
using SOR.Gateway.Dispatch;
|
||||
using SOR.Gateway.Push;
|
||||
using SOR.Networking.Abstractions.Messaging;
|
||||
using SOR.Networking.Abstractions.Transport;
|
||||
using SOR.Shared.Networking;
|
||||
|
||||
/// <summary>
|
||||
/// Runs the full lifecycle of a single client connection.
|
||||
///
|
||||
/// This is the most important class in the Gateway. Every connected client
|
||||
/// has exactly one ConnectionLoop running as an independent Task.
|
||||
///
|
||||
/// Lifecycle phases:
|
||||
/// Phase 1: Auth handshake — wait for auth.hello, validate token
|
||||
/// Phase 2: Promote to authenticated — register in ConnectionManager
|
||||
/// Phase 3: Subscribe to Redis push channel
|
||||
/// Phase 4: Main message loop — receive → dispatch → optional reply
|
||||
/// Phase 5: Cleanup — always runs in finally (guaranteed cleanup)
|
||||
///
|
||||
/// Lifetime: Transient per connection. GatewayHostedService fires one Task per
|
||||
/// accepted IClientConnection. Each Task owns this class for its lifetime.
|
||||
/// </summary>
|
||||
public sealed class ConnectionLoop
|
||||
{
|
||||
private readonly ConnectionManager _connectionManager;
|
||||
private readonly IMessageDispatcher _dispatcher;
|
||||
private readonly IMessageSerializer _serializer;
|
||||
private readonly IGatewayAuthValidator _authValidator;
|
||||
private readonly IConnectionMultiplexer _redis;
|
||||
private readonly GatewayOptions _options;
|
||||
private readonly ILogger<ConnectionLoop> _logger;
|
||||
|
||||
public ConnectionLoop(
|
||||
ConnectionManager connectionManager,
|
||||
IMessageDispatcher dispatcher,
|
||||
IMessageSerializer serializer,
|
||||
IGatewayAuthValidator authValidator,
|
||||
IConnectionMultiplexer redis,
|
||||
IOptions<GatewayOptions> options,
|
||||
ILogger<ConnectionLoop> logger)
|
||||
{
|
||||
_connectionManager = connectionManager;
|
||||
_dispatcher = dispatcher;
|
||||
_serializer = serializer;
|
||||
_authValidator = authValidator;
|
||||
_redis = redis;
|
||||
_options = options.Value;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs the full connection lifecycle for a raw, unauthenticated IClientConnection.
|
||||
///
|
||||
/// This method is called by GatewayHostedService as a fire-and-forget Task.
|
||||
/// It handles its own exceptions — errors here must not propagate to the accept loop.
|
||||
///
|
||||
/// The 'appCancellationToken' is the application shutdown token. When cancelled,
|
||||
/// the connection closes gracefully.
|
||||
/// </summary>
|
||||
public async Task RunAsync(
|
||||
IClientConnection rawConnection,
|
||||
CancellationToken appCancellationToken)
|
||||
{
|
||||
// 'authConn' is null until the handshake completes.
|
||||
// Used in finally to decide whether to unregister from ConnectionManager.
|
||||
AuthenticatedConnection? authConn = null;
|
||||
RedisPushSubscriber? pushSubscriber = null;
|
||||
|
||||
try
|
||||
{
|
||||
// ── Phase 1: Auth Handshake ────────────────────────────────────────────
|
||||
|
||||
_logger.LogDebug(
|
||||
"Connection accepted: ConnectionId={ConnectionId} Remote={Remote}",
|
||||
rawConnection.ConnectionId, rawConnection.RemoteAddress);
|
||||
|
||||
// Create a combined cancellation token: cancel if either the app shuts down
|
||||
// OR the auth timeout expires. Whichever comes first.
|
||||
//
|
||||
// CancellationTokenSource.CreateLinkedTokenSource creates a new token that
|
||||
// is cancelled when ANY of the source tokens are cancelled.
|
||||
using var authTimeoutSts =
|
||||
new CancellationTokenSource(TimeSpan.FromMilliseconds(_options.AuthTimeoutMs));
|
||||
using var authLinked = CancellationTokenSource.CreateLinkedTokenSource(
|
||||
appCancellationToken, authTimeoutSts.Token);
|
||||
|
||||
// Wait for the first message. Must be auth.hello.
|
||||
// Returns null on clean close (client disconnected before sending anything).
|
||||
var rawMsg = await rawConnection.ReceiveAsync(authLinked.Token);
|
||||
|
||||
if (rawMsg is null)
|
||||
{
|
||||
_logger.LogDebug(
|
||||
"Connection closed before auth: ConnectionId={ConnectionId}",
|
||||
rawConnection.ConnectionId);
|
||||
return;
|
||||
}
|
||||
|
||||
// Parse the envelope (type, seq, inner payload bytes).
|
||||
// rawMsg.Payload contains the full wire bytes (envelope + payload).
|
||||
IClientMessage parsedMsg;
|
||||
try
|
||||
{
|
||||
parsedMsg = _serializer.Deserialize(rawMsg.Payload.Span);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex,
|
||||
"Failed to deserialize first message: ConnectionId={ConnectionId}",
|
||||
rawConnection.ConnectionId);
|
||||
await rawConnection.CloseAsync("invalid_message", appCancellationToken);
|
||||
return;
|
||||
}
|
||||
|
||||
// The first message MUST be auth.hello.
|
||||
if (!string.Equals(parsedMsg.Type, "auth.hello", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
_logger.LogWarning(
|
||||
"First message is not auth.hello: Type={Type} ConnectionId={ConnectionId}",
|
||||
parsedMsg.Type, rawConnection.ConnectionId);
|
||||
|
||||
await SendErrorAsync(rawConnection, parsedMsg.Seq,
|
||||
"AUTH_REQUIRED", "First message must be auth.hello.", appCancellationToken);
|
||||
await rawConnection.CloseAsync("auth_required", appCancellationToken);
|
||||
return;
|
||||
}
|
||||
|
||||
// Deserialize the auth.hello payload to get the session token.
|
||||
AuthHelloPayload helloPayload;
|
||||
try
|
||||
{
|
||||
helloPayload = _serializer.DeserializePayload<AuthHelloPayload>(parsedMsg.Payload);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex,
|
||||
"Failed to deserialize auth.hello payload: ConnectionId={ConnectionId}",
|
||||
rawConnection.ConnectionId);
|
||||
await SendErrorAsync(rawConnection, parsedMsg.Seq,
|
||||
"INVALID_PAYLOAD", "auth.hello payload is malformed.", appCancellationToken);
|
||||
await rawConnection.CloseAsync("invalid_payload", appCancellationToken);
|
||||
return;
|
||||
}
|
||||
|
||||
// ── Phase 2: Token Validation ──────────────────────────────────────────
|
||||
|
||||
var (isValid, userId, displayName) =
|
||||
await _authValidator.ValidateAsync(helloPayload.SessionToken, appCancellationToken);
|
||||
|
||||
if (!isValid)
|
||||
{
|
||||
_logger.LogInformation(
|
||||
"Auth failed: ConnectionId={ConnectionId} Remote={Remote}",
|
||||
rawConnection.ConnectionId, rawConnection.RemoteAddress);
|
||||
|
||||
await SendErrorAsync(rawConnection, parsedMsg.Seq,
|
||||
"AUTH_FAILED", "Invalid or expired session token.", appCancellationToken);
|
||||
await rawConnection.CloseAsync("auth_failed", appCancellationToken);
|
||||
return;
|
||||
}
|
||||
|
||||
// ── Phase 3: Promote to Authenticated Connection ───────────────────────
|
||||
|
||||
authConn = new AuthenticatedConnection(
|
||||
rawConnection, userId, displayName, helloPayload.SessionToken);
|
||||
|
||||
_connectionManager.Register(authConn);
|
||||
|
||||
_logger.LogInformation(
|
||||
"User authenticated: UserId={UserId} DisplayName={DisplayName} " +
|
||||
"ConnectionId={ConnectionId}",
|
||||
userId, displayName, rawConnection.ConnectionId);
|
||||
|
||||
// Send acknowledgement to client.
|
||||
await SendMessageAsync(
|
||||
rawConnection,
|
||||
ServerMessage.Reply("auth.hello.ack", parsedMsg.Seq, new
|
||||
{
|
||||
userId,
|
||||
displayName
|
||||
}),
|
||||
appCancellationToken);
|
||||
|
||||
// ── Phase 4: Subscribe to Redis Push Channel ───────────────────────────
|
||||
|
||||
// Create a logger for the push subscriber that includes the userId.
|
||||
// GetRequiredService<ILogger{RedisPushSubscriber}> would give a generic logger;
|
||||
// we use CreateLogger with a category name that includes the userId for filtering.
|
||||
var pushLogger = _logger as ILogger<RedisPushSubscriber>
|
||||
?? Microsoft.Extensions.Logging.Abstractions.NullLogger<RedisPushSubscriber>.Instance;
|
||||
|
||||
pushSubscriber = await RedisPushSubscriber.SubscribeAsync(
|
||||
_redis, authConn, pushLogger, appCancellationToken);
|
||||
|
||||
// ── Phase 5: Main Message Loop ─────────────────────────────────────────
|
||||
|
||||
while (rawConnection.IsConnected && !appCancellationToken.IsCancellationRequested)
|
||||
{
|
||||
// Wait for the next message from the client.
|
||||
// Returns null on clean close (client sent WebSocket close frame).
|
||||
IClientMessage? nextRaw;
|
||||
try
|
||||
{
|
||||
nextRaw = await rawConnection.ReceiveAsync(appCancellationToken);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// App is shutting down — exit the loop cleanly.
|
||||
break;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Network error (connection dropped unexpectedly).
|
||||
_logger.LogDebug(ex,
|
||||
"Receive error for user {UserId}: connection dropped",
|
||||
userId);
|
||||
break;
|
||||
}
|
||||
|
||||
if (nextRaw is null) break; // Clean close from client.
|
||||
|
||||
// Parse the message envelope.
|
||||
IClientMessage nextMsg;
|
||||
try
|
||||
{
|
||||
nextMsg = _serializer.Deserialize(nextRaw.Payload.Span);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex,
|
||||
"Failed to deserialize message from user {UserId}", userId);
|
||||
// Malformed message: send an error but keep the connection alive.
|
||||
await SendErrorAsync(rawConnection, 0,
|
||||
"INVALID_MESSAGE", "Message could not be parsed.", appCancellationToken);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check that a handler exists for this message type.
|
||||
if (!_dispatcher.HasHandler(nextMsg.Type))
|
||||
{
|
||||
_logger.LogDebug(
|
||||
"Unknown message type '{Type}' from user {UserId}",
|
||||
nextMsg.Type, userId);
|
||||
await SendErrorAsync(rawConnection, nextMsg.Seq,
|
||||
"UNKNOWN_TYPE",
|
||||
$"No handler registered for message type '{nextMsg.Type}'.",
|
||||
appCancellationToken);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Dispatch to the registered handler.
|
||||
IServerMessage? response;
|
||||
try
|
||||
{
|
||||
response = await _dispatcher.DispatchAsync(
|
||||
nextMsg, authConn, appCancellationToken);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Handler threw an unexpected exception.
|
||||
_logger.LogError(ex,
|
||||
"Handler for '{Type}' threw for user {UserId}",
|
||||
nextMsg.Type, userId);
|
||||
await SendErrorAsync(rawConnection, nextMsg.Seq,
|
||||
"INTERNAL_ERROR", "An internal error occurred.", appCancellationToken);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Send the handler's reply if one was returned.
|
||||
if (response is not null)
|
||||
{
|
||||
await SendMessageAsync(rawConnection, response, appCancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// Normal exit: auth timeout fired, or app shutdown, or client disconnected.
|
||||
// OperationCanceledException is not an error — it's the expected exit signal.
|
||||
_logger.LogDebug(
|
||||
"Connection loop cancelled: ConnectionId={ConnectionId}",
|
||||
rawConnection.ConnectionId);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Unexpected error in the connection loop itself (not in a handler).
|
||||
_logger.LogError(ex,
|
||||
"Unexpected error in connection loop: ConnectionId={ConnectionId}",
|
||||
rawConnection.ConnectionId);
|
||||
}
|
||||
finally
|
||||
{
|
||||
// ── Phase 6: Cleanup — ALWAYS runs, regardless of how the loop exited ──
|
||||
|
||||
// Unsubscribe from Redis push channel.
|
||||
if (pushSubscriber is not null)
|
||||
await pushSubscriber.DisposeAsync();
|
||||
|
||||
// Unregister from the connection map.
|
||||
if (authConn is not null)
|
||||
_connectionManager.Unregister(rawConnection.ConnectionId);
|
||||
|
||||
// Dispose the connection (closes WebSocket, signals middleware done TCS).
|
||||
await rawConnection.DisposeAsync();
|
||||
|
||||
_logger.LogDebug(
|
||||
"Connection loop ended: ConnectionId={ConnectionId}",
|
||||
rawConnection.ConnectionId);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Private helpers ────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Serializes and sends a message to the raw (pre-auth) or authenticated connection.
|
||||
/// Errors here are swallowed — if the send fails the connection is already gone.
|
||||
/// </summary>
|
||||
private async Task SendMessageAsync(
|
||||
IClientConnection connection,
|
||||
IServerMessage message,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var bytes = _serializer.Serialize(message);
|
||||
await connection.SendBytesAsync(bytes, cancellationToken);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogDebug(ex,
|
||||
"Failed to send message '{Type}' to ConnectionId={ConnectionId}",
|
||||
message.Type, connection.ConnectionId);
|
||||
}
|
||||
}
|
||||
|
||||
private Task SendErrorAsync(
|
||||
IClientConnection connection,
|
||||
int refSeq,
|
||||
string errorCode,
|
||||
string errorMessage,
|
||||
CancellationToken cancellationToken) =>
|
||||
SendMessageAsync(
|
||||
connection,
|
||||
ServerMessage.Error(refSeq, errorCode, errorMessage),
|
||||
cancellationToken);
|
||||
|
||||
// ── Inner type: auth.hello payload ────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Deserialization target for the auth.hello message payload.
|
||||
///
|
||||
/// Client sends:
|
||||
/// { "type": "auth.hello", "seq": 1, "payload": { "sessionToken": "abc123..." } }
|
||||
///
|
||||
/// 'record' with 'init' properties: immutable after deserialization.
|
||||
/// Properties must match JSON keys (camelCase by default via IMessageSerializer options).
|
||||
/// </summary>
|
||||
private sealed record AuthHelloPayload(string SessionToken);
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
namespace SOR.Gateway;
|
||||
|
||||
using System.Collections.Concurrent;
|
||||
using SOR.Networking.Abstractions.Transport;
|
||||
|
||||
/// <summary>
|
||||
/// In-process registry of all authenticated connections on this Gateway instance.
|
||||
///
|
||||
/// Maintains two indexes:
|
||||
/// - By connectionId: stable, unique per connection, available before auth
|
||||
/// - By userId: available after auth, used by push delivery to find the socket
|
||||
///
|
||||
/// Important: ConnectionManager only knows about connections on THIS Gateway instance.
|
||||
/// For cross-instance lookups (e.g., "is user X connected anywhere?"), use Redis.
|
||||
/// This is intentional — Gateway instances are independent; coordination goes through Redis.
|
||||
///
|
||||
/// Thread safety: ConcurrentDictionary handles concurrent Register/Unregister/lookup
|
||||
/// without additional locking.
|
||||
///
|
||||
/// Lifetime: Singleton.
|
||||
/// </summary>
|
||||
public sealed class ConnectionManager
|
||||
{
|
||||
// Primary index: connectionId → AuthenticatedConnection
|
||||
// A connectionId uniquely identifies one TCP socket / WebSocket upgrade.
|
||||
private readonly ConcurrentDictionary<string, AuthenticatedConnection> _byConnectionId = new();
|
||||
|
||||
// Secondary index: userId → connectionId
|
||||
// One active connection per userId on this instance.
|
||||
// If a user opens a second tab, the second connection replaces the first in this map
|
||||
// (both are still tracked in _byConnectionId; only the latest userId→connectionId
|
||||
// mapping is kept for push delivery lookups).
|
||||
private readonly ConcurrentDictionary<string, string> _userIdToConnectionId = new();
|
||||
|
||||
/// <summary>
|
||||
/// Registers an authenticated connection in both indexes.
|
||||
/// Called by ConnectionLoop.RunAsync() after the auth handshake succeeds.
|
||||
/// </summary>
|
||||
public void Register(AuthenticatedConnection connection)
|
||||
{
|
||||
var connId = connection.Connection.ConnectionId;
|
||||
|
||||
_byConnectionId[connId] = connection;
|
||||
|
||||
// If the user already has a connection (second tab opened), the new mapping
|
||||
// overwrites the old one. The old connection remains in _byConnectionId and
|
||||
// will clean itself up when its loop exits.
|
||||
_userIdToConnectionId[connection.UserId] = connId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes a connection from both indexes.
|
||||
/// Called by ConnectionLoop.RunAsync() in its finally block — always called
|
||||
/// regardless of how the loop exits (clean close, exception, timeout, etc.).
|
||||
/// </summary>
|
||||
public void Unregister(string connectionId)
|
||||
{
|
||||
if (_byConnectionId.TryRemove(connectionId, out var connection))
|
||||
{
|
||||
// Only remove the userId index if it still points to this connection.
|
||||
// If a newer connection from the same user replaced it, leave the index alone.
|
||||
_userIdToConnectionId.TryRemove(
|
||||
new KeyValuePair<string, string>(connection.UserId, connectionId));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks up a connection by its connection ID.
|
||||
/// Returns null if not registered (already disconnected).
|
||||
/// </summary>
|
||||
public AuthenticatedConnection? GetByConnectionId(string connectionId) =>
|
||||
_byConnectionId.GetValueOrDefault(connectionId);
|
||||
|
||||
/// <summary>
|
||||
/// Looks up the most recently registered connection for a given user.
|
||||
/// Returns null if the user is not connected on this Gateway instance.
|
||||
///
|
||||
/// Used by RedisPushSubscriber to find the WebSocket to deliver a pushed message to.
|
||||
/// </summary>
|
||||
public AuthenticatedConnection? GetByUserId(string userId)
|
||||
{
|
||||
if (!_userIdToConnectionId.TryGetValue(userId, out var connectionId))
|
||||
return null;
|
||||
|
||||
return _byConnectionId.GetValueOrDefault(connectionId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Total number of currently authenticated connections on this Gateway instance.
|
||||
/// Used for metrics and health reporting.
|
||||
/// </summary>
|
||||
public int ConnectedCount => _byConnectionId.Count;
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
namespace SOR.Gateway.Dispatch;
|
||||
|
||||
using Microsoft.Extensions.Logging;
|
||||
using SOR.Networking.Abstractions.Messaging;
|
||||
using SOR.Networking.Abstractions.Transport;
|
||||
|
||||
/// <summary>
|
||||
/// IMessageDispatcher implementation.
|
||||
///
|
||||
/// Collects all registered IMessageHandler implementations from the DI container
|
||||
/// at construction time and builds a frozen dispatch table keyed by message type.
|
||||
///
|
||||
/// Plugin pattern:
|
||||
/// Service modules register handlers with:
|
||||
/// services.AddTransient{IMessageHandler, ConcreteHandler}()
|
||||
/// This class collects them all via IEnumerable{IMessageHandler} injection.
|
||||
/// Adding a new handler to a service module never requires changing this class.
|
||||
///
|
||||
/// Startup validation:
|
||||
/// If two handlers register for the same message type, the constructor throws
|
||||
/// InvalidOperationException. This crashes startup rather than silently dropping
|
||||
/// one handler — duplicate registrations are always a bug.
|
||||
///
|
||||
/// Lifetime: Singleton. The dispatch table is immutable after construction.
|
||||
/// </summary>
|
||||
public sealed class MessageDispatcher : IMessageDispatcher
|
||||
{
|
||||
// IReadOnlyDictionary: immutable after construction.
|
||||
// StringComparer.OrdinalIgnoreCase: "Chat.Send" and "chat.send" route to the same handler.
|
||||
private readonly IReadOnlyDictionary<string, IMessageHandler> _handlers;
|
||||
private readonly ILogger<MessageDispatcher> _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Constructor. Called once at application startup by the DI container.
|
||||
///
|
||||
/// 'IEnumerable{IMessageHandler}' causes the DI container to inject ALL registered
|
||||
/// IMessageHandler implementations as a collection. This is the collection injection
|
||||
/// pattern — a standard .NET DI feature, no special configuration needed.
|
||||
/// </summary>
|
||||
public MessageDispatcher(
|
||||
IEnumerable<IMessageHandler> handlers,
|
||||
ILogger<MessageDispatcher> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
|
||||
// Build the dispatch table. Dictionary for O(1) type lookup per message.
|
||||
var table = new Dictionary<string, IMessageHandler>(
|
||||
StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
foreach (var handler in handlers)
|
||||
{
|
||||
// Fail fast on duplicates — this is always a configuration bug.
|
||||
if (!table.TryAdd(handler.MessageType, handler))
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"Duplicate IMessageHandler registered for type '{handler.MessageType}'. " +
|
||||
$"Existing: {table[handler.MessageType].GetType().Name}, " +
|
||||
$"Duplicate: {handler.GetType().Name}. " +
|
||||
"Each message type may have only one handler.");
|
||||
}
|
||||
|
||||
_logger.LogDebug("Registered handler for message type '{Type}': {Handler}",
|
||||
handler.MessageType, handler.GetType().Name);
|
||||
}
|
||||
|
||||
_handlers = table;
|
||||
|
||||
_logger.LogInformation(
|
||||
"MessageDispatcher initialized with {Count} handler(s): [{Types}]",
|
||||
_handlers.Count,
|
||||
string.Join(", ", _handlers.Keys));
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public bool HasHandler(string messageType) =>
|
||||
_handlers.ContainsKey(messageType);
|
||||
|
||||
/// <inheritdoc/>
|
||||
/// <remarks>
|
||||
/// Precondition: HasHandler(message.Type) == true.
|
||||
/// The Gateway connection loop checks HasHandler before calling DispatchAsync
|
||||
/// and sends an error response for unknown types without reaching this method.
|
||||
/// </remarks>
|
||||
public async Task<IServerMessage?> DispatchAsync(
|
||||
IClientMessage message,
|
||||
AuthenticatedConnection connection,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
// O(1) lookup — no lock needed (dictionary is read-only after construction).
|
||||
if (!_handlers.TryGetValue(message.Type, out var handler))
|
||||
{
|
||||
// Should not happen: caller checks HasHandler first.
|
||||
// Defensive check in case the method is called incorrectly.
|
||||
_logger.LogError(
|
||||
"DispatchAsync called for unregistered type '{Type}' — this is a bug",
|
||||
message.Type);
|
||||
return null;
|
||||
}
|
||||
|
||||
_logger.LogDebug(
|
||||
"Dispatching '{Type}' seq={Seq} for user {UserId}",
|
||||
message.Type, message.Seq, connection.UserId);
|
||||
|
||||
// Invoke the handler. Exceptions bubble up to the connection loop,
|
||||
// which logs them and sends a generic error response to the client.
|
||||
return await handler.HandleAsync(message, connection, cancellationToken);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
namespace SOR.Gateway;
|
||||
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using SOR.Networking.Abstractions.Transport;
|
||||
|
||||
/// <summary>
|
||||
/// Background service that runs the Gateway's connection accept loop.
|
||||
///
|
||||
/// IHostedService is the .NET interface for background services.
|
||||
/// The framework calls StartAsync() on application startup and StopAsync() on shutdown.
|
||||
///
|
||||
/// This service runs a tight loop: accept connection → fire ConnectionLoop as a Task.
|
||||
/// Each connection gets its own Task and runs fully independently.
|
||||
/// The accept loop itself never blocks waiting for an individual connection to finish.
|
||||
///
|
||||
/// Lifetime: Singleton (IHostedService instances are always Singleton in .NET DI).
|
||||
/// </summary>
|
||||
public sealed class GatewayHostedService : IHostedService
|
||||
{
|
||||
private readonly ITransport _transport;
|
||||
private readonly ConnectionLoop _connectionLoop;
|
||||
private readonly ILogger<GatewayHostedService> _logger;
|
||||
|
||||
// Track all active connection Tasks so we can wait for them on shutdown.
|
||||
// ConcurrentDictionary used as a thread-safe HashSet (value is bool placeholder).
|
||||
private readonly System.Collections.Concurrent.ConcurrentDictionary<Task, bool>
|
||||
_activeTasks = new();
|
||||
|
||||
// CancellationTokenSource that we control — cancelled in StopAsync to signal shutdown.
|
||||
private CancellationTokenSource _cts = new();
|
||||
|
||||
public GatewayHostedService(
|
||||
ITransport transport,
|
||||
ConnectionLoop connectionLoop,
|
||||
ILogger<GatewayHostedService> logger)
|
||||
{
|
||||
_transport = transport;
|
||||
_connectionLoop = connectionLoop;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called by the framework on application startup.
|
||||
/// Fires the accept loop as a background Task (does not block startup).
|
||||
/// </summary>
|
||||
public Task StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
_logger.LogInformation(
|
||||
"Gateway accept loop starting on transport '{Transport}'", _transport.Name);
|
||||
|
||||
// Fire the accept loop as a background Task.
|
||||
// '_ =' discards the returned Task — the loop manages itself.
|
||||
// We pass _cts.Token (our controlled token) rather than the startup token
|
||||
// because the startup token is only valid during the startup phase.
|
||||
_ = RunAcceptLoopAsync(_cts.Token);
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called by the framework on application shutdown.
|
||||
/// Cancels the accept loop and waits for all active connection Tasks to finish.
|
||||
/// </summary>
|
||||
public async Task StopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
_logger.LogInformation("Gateway shutting down. Waiting for {Count} connection(s) to close.",
|
||||
_activeTasks.Count);
|
||||
|
||||
// Signal cancellation to the accept loop and all active connection loops.
|
||||
await _cts.CancelAsync();
|
||||
|
||||
// Wait for all in-flight connection Tasks to complete,
|
||||
// but stop waiting after the shutdown timeout (cancellationToken from framework).
|
||||
//
|
||||
// Task.WhenAll runs all tasks concurrently and completes when all finish.
|
||||
// WaitAsync(cancellationToken) limits how long we wait.
|
||||
var allTasks = _activeTasks.Keys.ToArray();
|
||||
if (allTasks.Length > 0)
|
||||
{
|
||||
try
|
||||
{
|
||||
await Task.WhenAll(allTasks).WaitAsync(cancellationToken);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
_logger.LogWarning(
|
||||
"Shutdown timeout reached; {Count} connection(s) may not have closed cleanly.",
|
||||
_activeTasks.Count);
|
||||
}
|
||||
}
|
||||
|
||||
_logger.LogInformation("Gateway shut down.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The main accept loop. Runs until _cts is cancelled (application shutdown).
|
||||
/// Each accepted connection is handled in a separate Task.
|
||||
/// </summary>
|
||||
private async Task RunAcceptLoopAsync(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
while (!ct.IsCancellationRequested)
|
||||
{
|
||||
// Block until a new connection arrives.
|
||||
// Throws OperationCanceledException on shutdown — caught below.
|
||||
var connection = await _transport.AcceptAsync(ct);
|
||||
|
||||
_logger.LogDebug(
|
||||
"Accepted connection: ConnectionId={ConnectionId}",
|
||||
connection.ConnectionId);
|
||||
|
||||
// Fire the connection loop as an independent Task.
|
||||
// We do NOT await it — the accept loop continues immediately to accept the next.
|
||||
var task = _connectionLoop.RunAsync(connection, ct);
|
||||
|
||||
// Track the task so StopAsync can wait for all connections to close.
|
||||
_activeTasks.TryAdd(task, true);
|
||||
|
||||
// Remove the task from tracking when it completes (success or failure).
|
||||
// ContinueWith runs when the task finishes — this is the cleanup callback.
|
||||
// TaskContinuationOptions.ExecuteSynchronously: run the callback inline
|
||||
// on the completing thread to avoid scheduling overhead.
|
||||
_ = task.ContinueWith(
|
||||
t => _activeTasks.TryRemove(t, out _),
|
||||
TaskContinuationOptions.ExecuteSynchronously);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// Normal shutdown — the accept loop was cancelled.
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Unexpected error in the accept loop itself.
|
||||
// This would stop accepting new connections — log as Critical.
|
||||
_logger.LogCritical(ex,
|
||||
"Gateway accept loop crashed. No new connections will be accepted.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
namespace SOR.Gateway;
|
||||
|
||||
/// <summary>
|
||||
/// Configuration options for the Gateway service.
|
||||
/// Bound from the "Gateway" section of appsettings.json.
|
||||
///
|
||||
/// appsettings.json example:
|
||||
/// {
|
||||
/// "Gateway": {
|
||||
/// "AuthTimeoutMs": 10000,
|
||||
/// "MaxMessagesPerSecond": 20
|
||||
/// }
|
||||
/// }
|
||||
/// </summary>
|
||||
public sealed class GatewayOptions
|
||||
{
|
||||
/// <summary>
|
||||
/// How long the Gateway waits for an auth.hello message after a connection is accepted.
|
||||
/// If the client does not send auth.hello within this window, the connection is closed
|
||||
/// with an "auth_timeout" reason.
|
||||
/// Default: 10 seconds.
|
||||
/// </summary>
|
||||
public int AuthTimeoutMs { get; set; } = 10_000;
|
||||
|
||||
/// <summary>
|
||||
/// Maximum number of messages per second the Gateway will process per connection.
|
||||
/// Connections exceeding this rate receive a "rate_limit_exceeded" error and are
|
||||
/// disconnected. Protects against runaway clients flooding the server.
|
||||
///
|
||||
/// Note: rate limiting is tracked per connection, not per user.
|
||||
/// If a user opens multiple connections they get this budget per connection.
|
||||
///
|
||||
/// Set to 0 to disable rate limiting (not recommended for production).
|
||||
/// Default: 20 messages per second.
|
||||
///
|
||||
/// Implementation: tracked in ConnectionLoop but not enforced in this foundation phase.
|
||||
/// This option is defined now so configuration is in place before enforcement is added.
|
||||
/// </summary>
|
||||
public int MaxMessagesPerSecond { get; set; } = 20;
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
namespace SOR.Gateway.Push;
|
||||
|
||||
using Microsoft.Extensions.Logging;
|
||||
using StackExchange.Redis;
|
||||
using SOR.Networking.Abstractions.Transport;
|
||||
using SOR.Shared.Redis;
|
||||
|
||||
/// <summary>
|
||||
/// Subscribes to a Redis Pub/Sub channel for a specific user and forwards
|
||||
/// received bytes directly to their WebSocket connection.
|
||||
///
|
||||
/// This is the READ side of the push delivery pipeline (Gateway-internal):
|
||||
/// Redis channel "push:{userId}"
|
||||
/// → RedisPushSubscriber.OnMessageReceived callback
|
||||
/// → IClientConnection.SendBytesAsync (WebSocket send)
|
||||
///
|
||||
/// The WRITE side is IClientPush (SOR.Networking.Redis.RedisClientPush).
|
||||
/// Only the Gateway uses RedisPushSubscriber — it is not part of the public interfaces.
|
||||
///
|
||||
/// One instance per authenticated connection. Created by ConnectionLoop.RunAsync()
|
||||
/// after auth handshake. Disposed when the connection loop exits (user disconnected).
|
||||
///
|
||||
/// Factory method pattern: constructor is private; call SubscribeAsync() to create.
|
||||
/// </summary>
|
||||
public sealed class RedisPushSubscriber : IAsyncDisposable
|
||||
{
|
||||
private readonly ISubscriber _subscriber;
|
||||
private readonly RedisChannel _channel;
|
||||
private readonly AuthenticatedConnection _connection;
|
||||
private readonly ILogger<RedisPushSubscriber> _logger;
|
||||
|
||||
private RedisPushSubscriber(
|
||||
ISubscriber subscriber,
|
||||
RedisChannel channel,
|
||||
AuthenticatedConnection connection,
|
||||
ILogger<RedisPushSubscriber> logger)
|
||||
{
|
||||
_subscriber = subscriber;
|
||||
_channel = channel;
|
||||
_connection = connection;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates and starts a push subscriber for the given user connection.
|
||||
///
|
||||
/// Subscribes to "push:{userId}" on Redis. Any bytes published to this channel
|
||||
/// by IClientPush are immediately forwarded to the connection's WebSocket.
|
||||
///
|
||||
/// Returns the subscriber instance, which the caller holds until the connection
|
||||
/// ends. Disposing the subscriber unsubscribes from Redis.
|
||||
/// </summary>
|
||||
public static async Task<RedisPushSubscriber> SubscribeAsync(
|
||||
IConnectionMultiplexer redis,
|
||||
AuthenticatedConnection connection,
|
||||
ILogger<RedisPushSubscriber> logger,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var channelKey = RedisKeys.ClientPushChannel(connection.UserId);
|
||||
var channel = RedisChannel.Literal(channelKey);
|
||||
var subscriber = redis.GetSubscriber();
|
||||
|
||||
var instance = new RedisPushSubscriber(subscriber, channel, connection, logger);
|
||||
|
||||
// Subscribe to the channel. OnMessageReceived is called on a Redis
|
||||
// background thread each time a message is published to this channel.
|
||||
await subscriber.SubscribeAsync(channel, instance.OnMessageReceived);
|
||||
|
||||
logger.LogDebug(
|
||||
"Subscribed to Redis push channel '{Channel}' for user {UserId}",
|
||||
channelKey, connection.UserId);
|
||||
|
||||
return instance;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Callback invoked on a Redis background thread when a message arrives on the channel.
|
||||
///
|
||||
/// We fire-and-forget a Task to forward the bytes asynchronously.
|
||||
/// The send lock inside IClientConnection.SendBytesAsync serializes concurrent sends
|
||||
/// (in case a reply from a handler arrives at the same time as a push).
|
||||
///
|
||||
/// Errors are logged and swallowed — a failed push must not crash the subscriber.
|
||||
/// </summary>
|
||||
private void OnMessageReceived(RedisChannel channel, RedisValue value)
|
||||
{
|
||||
// Don't forward if the connection is already closing.
|
||||
if (!_connection.Connection.IsConnected) return;
|
||||
|
||||
// Fire-and-forget the async send.
|
||||
// '_ =' discards the Task intentionally. We catch exceptions inside.
|
||||
_ = ForwardAsync(value);
|
||||
}
|
||||
|
||||
private async Task ForwardAsync(RedisValue value)
|
||||
{
|
||||
try
|
||||
{
|
||||
// RedisValue is implicitly convertible to byte[].
|
||||
// ReadOnlyMemory<byte> wraps it without copying.
|
||||
byte[] bytes = (byte[])value!;
|
||||
|
||||
await _connection.Connection.SendBytesAsync(
|
||||
bytes,
|
||||
CancellationToken.None); // Don't use connection's token — push must complete
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex,
|
||||
"Failed to forward push to user {UserId}", _connection.UserId);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Unsubscribes from the Redis channel.
|
||||
/// Called by ConnectionLoop.RunAsync() in its finally block.
|
||||
/// </summary>
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await _subscriber.UnsubscribeAsync(_channel);
|
||||
|
||||
_logger.LogDebug(
|
||||
"Unsubscribed from Redis push channel for user {UserId}",
|
||||
_connection.UserId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<AssemblyName>SOR.Gateway</AssemblyName>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- ASP.NET Core for WebSocket middleware and DI -->
|
||||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||
|
||||
<!-- Redis for the push delivery read side (RedisPushSubscriber) -->
|
||||
<PackageReference Include="StackExchange.Redis" />
|
||||
|
||||
<!-- gRPC client factory for the Auth validator gRPC client -->
|
||||
<PackageReference Include="Grpc.Net.ClientFactory" />
|
||||
|
||||
<!-- IMPORTANT: SOR.Gateway only references Abstractions, NOT the concrete
|
||||
transport/bus/push implementations. This is what enables rip-and-replace:
|
||||
the concrete implementations are wired in SOR.Host, invisible to Gateway. -->
|
||||
<ProjectReference Include="..\SOR.Networking.Abstractions\SOR.Networking.Abstractions.csproj" />
|
||||
<ProjectReference Include="..\SOR.Shared\SOR.Shared.csproj" />
|
||||
|
||||
<!-- SOR.Shared.Proto for the generated Auth gRPC client stub -->
|
||||
<ProjectReference Include="..\SOR.Shared.Proto\SOR.Shared.Proto.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,75 @@
|
||||
namespace SOR.Gateway;
|
||||
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using SOR.Gateway.Auth;
|
||||
using SOR.Gateway.Dispatch;
|
||||
using SOR.Networking.Abstractions.Messaging;
|
||||
using SOR.Shared.Proto;
|
||||
|
||||
/// <summary>
|
||||
/// Registers all Gateway services in the DI container.
|
||||
/// Called from SOR.Host.Program.cs when "gateway" is in ENABLED_SERVICES.
|
||||
/// </summary>
|
||||
public static class ServiceRegistration
|
||||
{
|
||||
/// <summary>
|
||||
/// Registers:
|
||||
/// - GatewayOptions (from "Gateway" config section)
|
||||
/// - ConnectionManager (Singleton: in-process connection registry)
|
||||
/// - IMessageDispatcher → MessageDispatcher (Singleton: built from all IMessageHandlers)
|
||||
/// - IGatewayAuthValidator → GatewayAuthValidator (Singleton: wraps Auth gRPC client)
|
||||
/// - Auth gRPC client (via AddGrpcClient — uses HttpClientFactory for connection pooling)
|
||||
/// - ConnectionLoop (Transient: new instance per connection)
|
||||
/// - GatewayHostedService (Singleton: runs the accept loop)
|
||||
///
|
||||
/// Preconditions (must be registered before calling this):
|
||||
/// - ITransport (e.g., via AddWebSocketTransport)
|
||||
/// - IConnectionMultiplexer (StackExchange.Redis, registered in Host)
|
||||
/// - IMessageSerializer (via AddSharedServices)
|
||||
/// </summary>
|
||||
public static IServiceCollection AddGatewayService(
|
||||
this IServiceCollection services,
|
||||
IConfiguration configuration)
|
||||
{
|
||||
// Bind "Gateway" config section to GatewayOptions.
|
||||
services.Configure<GatewayOptions>(configuration.GetSection("Gateway"));
|
||||
|
||||
// Singleton: one ConnectionManager for this Gateway instance's lifetime.
|
||||
services.AddSingleton<ConnectionManager>();
|
||||
|
||||
// Singleton: MessageDispatcher collects all IMessageHandler registrations
|
||||
// via IEnumerable{IMessageHandler} injection. Built once at startup.
|
||||
services.AddSingleton<IMessageDispatcher, MessageDispatcher>();
|
||||
|
||||
// Register the Auth gRPC client using AddGrpcClient.
|
||||
// AddGrpcClient integrates with HttpClientFactory for:
|
||||
// - Connection pooling (one underlying HTTP/2 connection, multiplexed)
|
||||
// - Automatic retries (configurable via AddPolicyHandler)
|
||||
// - Proper lifetime management
|
||||
// The address comes from configuration: Services:Auth (e.g., "http://auth-service:5001")
|
||||
services.AddGrpcClient<AuthService.AuthServiceClient>(opts =>
|
||||
{
|
||||
opts.Address = new Uri(configuration["Services:Auth"]
|
||||
?? throw new InvalidOperationException(
|
||||
"Missing configuration: Services:Auth. " +
|
||||
"Set this to the Auth service gRPC address (e.g., http://localhost:5001)."));
|
||||
});
|
||||
|
||||
// Singleton: wraps the Auth gRPC client behind IGatewayAuthValidator.
|
||||
services.AddSingleton<IGatewayAuthValidator, GatewayAuthValidator>();
|
||||
|
||||
// Transient: a new ConnectionLoop is created for each connection.
|
||||
// This is safe because ConnectionLoop has no mutable shared state —
|
||||
// all its dependencies (ConnectionManager, IMessageDispatcher, etc.) are Singletons.
|
||||
// Using Transient ensures each connection gets a fresh instance with its own
|
||||
// logger context, even though the dependencies are shared.
|
||||
services.AddTransient<ConnectionLoop>();
|
||||
|
||||
// Singleton: IHostedService implementations are always Singleton.
|
||||
// Starts the accept loop on application startup.
|
||||
services.AddHostedService<GatewayHostedService>();
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
@@ -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" ]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
namespace SOR.Networking.Abstractions.EventBus;
|
||||
|
||||
/// <summary>
|
||||
/// Async publish/subscribe event bus.
|
||||
///
|
||||
/// Current implementation: NATS (SOR.Networking.Nats.NatsEventBus).
|
||||
/// To swap to RabbitMQ: create SOR.Networking.RabbitMq.RabbitMqEventBus,
|
||||
/// register it instead of NatsEventBus in SOR.Host. Service code does not change.
|
||||
///
|
||||
/// Usage pattern:
|
||||
/// - Publishers call PublishAsync on domain events (game ended, card purchased, etc.)
|
||||
/// - Subscribers (IHostedService) call SubscribeAsync and process via await foreach
|
||||
///
|
||||
/// The Gateway does NOT use IEventBus for client push delivery — that goes through
|
||||
/// IClientPush → Redis Pub/Sub → Gateway Redis subscriber → WebSocket.
|
||||
/// IEventBus is for inter-service async fan-out only.
|
||||
///
|
||||
/// Lifetime: Singleton.
|
||||
/// </summary>
|
||||
public interface IEventBus
|
||||
{
|
||||
/// <summary>
|
||||
/// Publishes an event to the named subject.
|
||||
///
|
||||
/// Fire-and-forget from the publisher's perspective — delivery to subscribers
|
||||
/// is handled by the broker. No reply is expected or waited for.
|
||||
///
|
||||
/// Subject naming convention: "sor.{service}.{event}"
|
||||
/// Examples: "sor.game.ended", "sor.bazaar.purchase.completed"
|
||||
/// All subject constants are defined in SOR.Shared.Nats.NatsSubjects.
|
||||
///
|
||||
/// T must be serializable by the underlying broker's serializer.
|
||||
/// The default NATS implementation uses System.Text.Json.
|
||||
/// </summary>
|
||||
Task PublishAsync<T>(
|
||||
string subject,
|
||||
T payload,
|
||||
CancellationToken cancellationToken = default)
|
||||
where T : notnull;
|
||||
|
||||
/// <summary>
|
||||
/// Subscribes to a subject and returns an async stream of received messages.
|
||||
///
|
||||
/// Callers consume this with 'await foreach':
|
||||
/// await foreach (var evt in _bus.SubscribeAsync{GameEndedEvent}(subject, ct))
|
||||
/// {
|
||||
/// await ProcessAsync(evt);
|
||||
/// }
|
||||
///
|
||||
/// The stream ends when cancellationToken is cancelled (application shutdown).
|
||||
/// Callers should catch OperationCanceledException as the normal exit signal.
|
||||
///
|
||||
/// Each subscriber receives its own copy of published messages (fan-out).
|
||||
/// Multiple instances of the same service subscribing to the same subject
|
||||
/// each receive a copy — use NATS JetStream with queue groups for
|
||||
/// competing-consumer (load-balanced) patterns when needed.
|
||||
/// </summary>
|
||||
IAsyncEnumerable<T> SubscribeAsync<T>(
|
||||
string subject,
|
||||
CancellationToken cancellationToken = default)
|
||||
where T : notnull;
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
namespace SOR.Networking.Abstractions.Messaging;
|
||||
|
||||
/// <summary>
|
||||
/// A single message received from a client, after the transport layer has
|
||||
/// read the raw bytes and the serializer has parsed the envelope.
|
||||
///
|
||||
/// Wire format (JSON):
|
||||
/// { "type": "chat.send", "seq": 7, "payload": { ... } }
|
||||
///
|
||||
/// The transport produces a RawClientMessage with just the raw bytes.
|
||||
/// IMessageSerializer.Deserialize() populates Type, Seq, and Payload from those bytes.
|
||||
/// The dispatcher then calls IMessageSerializer.DeserializePayload{T}(Payload)
|
||||
/// to get the handler-specific request object.
|
||||
/// </summary>
|
||||
public interface IClientMessage
|
||||
{
|
||||
/// <summary>
|
||||
/// Dot-namespaced message type string. Convention: "{service}.{action}".
|
||||
/// Examples: "auth.hello", "game.play_card", "chat.send", "collection.view_deck"
|
||||
///
|
||||
/// Used by IMessageDispatcher to look up the correct IMessageHandler.
|
||||
/// </summary>
|
||||
string Type { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Client-assigned sequence number. Monotonically increasing per connection.
|
||||
/// The server echoes this back in the 'ref' field of the response so the client
|
||||
/// can match async responses to the original requests.
|
||||
/// </summary>
|
||||
int Seq { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Serialized inner payload — the message-type-specific data.
|
||||
/// The envelope (type, seq) has already been extracted.
|
||||
/// Each IMessageHandler calls IMessageSerializer.DeserializePayload{T}(Payload)
|
||||
/// to convert this into its specific request type.
|
||||
///
|
||||
/// ReadOnlyMemory{byte} avoids copying: the bytes are owned by the transport
|
||||
/// receive buffer and valid for the lifetime of this message object.
|
||||
/// </summary>
|
||||
ReadOnlyMemory<byte> Payload { get; }
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
namespace SOR.Networking.Abstractions.Messaging;
|
||||
|
||||
using SOR.Networking.Abstractions.Transport;
|
||||
|
||||
/// <summary>
|
||||
/// Routes an incoming client message to the IMessageHandler registered for its type.
|
||||
///
|
||||
/// Built once at startup from all IMessageHandler registrations in the DI container.
|
||||
/// The dispatch table is frozen after construction — handlers cannot be added at runtime.
|
||||
///
|
||||
/// Lifetime: Singleton.
|
||||
/// </summary>
|
||||
public interface IMessageDispatcher
|
||||
{
|
||||
/// <summary>
|
||||
/// Returns true if a handler is registered for the given message type.
|
||||
/// Gateway uses this to reject messages with unknown types before attempting dispatch,
|
||||
/// providing a clear "UNKNOWN_TYPE" error response instead of a null return.
|
||||
/// </summary>
|
||||
bool HasHandler(string messageType);
|
||||
|
||||
/// <summary>
|
||||
/// Finds and invokes the handler registered for message.Type.
|
||||
///
|
||||
/// Returns the handler's response, or null if the handler returned null
|
||||
/// (fire-and-forget or deferred push). The Gateway connection loop sends
|
||||
/// the response if non-null.
|
||||
///
|
||||
/// Precondition: HasHandler(message.Type) is true. The caller checks this
|
||||
/// before calling DispatchAsync — an unknown type produces an error reply,
|
||||
/// not a dispatch call.
|
||||
///
|
||||
/// The connection parameter is forwarded to the handler unchanged.
|
||||
/// </summary>
|
||||
Task<IServerMessage?> DispatchAsync(
|
||||
IClientMessage message,
|
||||
AuthenticatedConnection connection,
|
||||
CancellationToken cancellationToken);
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
namespace SOR.Networking.Abstractions.Messaging;
|
||||
|
||||
using SOR.Networking.Abstractions.Transport;
|
||||
|
||||
/// <summary>
|
||||
/// Handles one specific message type received from a client.
|
||||
///
|
||||
/// Registration pattern (plugin-style):
|
||||
/// Each service module registers its handlers in DI:
|
||||
/// services.AddTransient{IMessageHandler, ChatSendHandler}()
|
||||
///
|
||||
/// MessageDispatcher collects all registered IMessageHandler implementations
|
||||
/// via IEnumerable{IMessageHandler} injection and builds a dispatch table.
|
||||
/// No Gateway code changes when a new service adds handlers.
|
||||
///
|
||||
/// Convention:
|
||||
/// - One handler class per message type.
|
||||
/// - File name matches: "{MessageType}.Replace('.', '_')}Handler.cs"
|
||||
/// - Example: "chat.send" → ChatSendHandler.cs
|
||||
///
|
||||
/// Lifetime: Transient. A new handler instance is created per message.
|
||||
/// This means handlers can safely use Scoped services (injected into the constructor
|
||||
/// via the DI scope created around each dispatch call in MessageDispatcher).
|
||||
/// </summary>
|
||||
public interface IMessageHandler
|
||||
{
|
||||
/// <summary>
|
||||
/// The message type this handler processes.
|
||||
/// Must be unique across all registered handlers in the process.
|
||||
/// Convention: "{service}.{action}" — all lowercase, dot-separated.
|
||||
/// Examples: "auth.hello", "game.play_card", "chat.send", "collection.view_deck"
|
||||
///
|
||||
/// MessageDispatcher throws InvalidOperationException at startup if two handlers
|
||||
/// share the same MessageType, making duplicate registrations a startup crash
|
||||
/// rather than a silent bug.
|
||||
/// </summary>
|
||||
string MessageType { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Handles the incoming message and returns an optional direct reply.
|
||||
///
|
||||
/// Return null when:
|
||||
/// - The handler is fire-and-forget (no client reply needed)
|
||||
/// - The reply will arrive later as a push event via IClientPush
|
||||
///
|
||||
/// Return a ServerMessage when:
|
||||
/// - A synchronous acknowledgement is appropriate ("auth.hello.ack", etc.)
|
||||
/// - An error response must be sent
|
||||
///
|
||||
/// The connection parameter carries the userId (connection.UserId) and
|
||||
/// a reference to the underlying IClientConnection for sending if needed.
|
||||
/// Prefer returning a non-null IServerMessage over calling SendBytesAsync
|
||||
/// directly — the Gateway connection loop handles the send uniformly.
|
||||
/// </summary>
|
||||
Task<IServerMessage?> HandleAsync(
|
||||
IClientMessage message,
|
||||
AuthenticatedConnection connection,
|
||||
CancellationToken cancellationToken);
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
namespace SOR.Networking.Abstractions.Messaging;
|
||||
|
||||
/// <summary>
|
||||
/// Serializes and deserializes message envelopes and payloads.
|
||||
///
|
||||
/// Two responsibilities:
|
||||
/// 1. Envelope codec: converts wire bytes ↔ IClientMessage / IServerMessage
|
||||
/// 2. Payload codec: converts payload bytes ↔ handler-specific request/response types
|
||||
///
|
||||
/// Default implementation: SystemTextJsonSerializer (System.Text.Json, camelCase)
|
||||
/// Swap-in: MessagePackSerializer — register it instead of the JSON implementation
|
||||
/// in SOR.Host. No other code changes anywhere.
|
||||
///
|
||||
/// Lifetime: Singleton. Implementations must be thread-safe.
|
||||
/// </summary>
|
||||
public interface IMessageSerializer
|
||||
{
|
||||
/// <summary>
|
||||
/// Parses a complete wire frame into its envelope fields (type, seq) plus
|
||||
/// the raw serialized payload bytes.
|
||||
///
|
||||
/// Called once per received message in the transport layer before dispatch.
|
||||
/// The returned IClientMessage's Payload contains only the inner payload bytes,
|
||||
/// not the full envelope — the envelope fields have been extracted.
|
||||
///
|
||||
/// Throws JsonException (or equivalent) on malformed input.
|
||||
/// </summary>
|
||||
IClientMessage Deserialize(ReadOnlySpan<byte> wireBytes);
|
||||
|
||||
/// <summary>
|
||||
/// Encodes an IServerMessage into wire bytes ready for transmission.
|
||||
///
|
||||
/// Called by the Gateway send path just before calling
|
||||
/// IClientConnection.SendBytesAsync().
|
||||
/// </summary>
|
||||
ReadOnlyMemory<byte> Serialize(IServerMessage message);
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes a raw payload into a handler-specific request type T.
|
||||
///
|
||||
/// Called by each IMessageHandler after receiving IClientMessage.Payload.
|
||||
/// The payload bytes were extracted from the original envelope by Deserialize().
|
||||
///
|
||||
/// Example:
|
||||
/// var req = _serializer.DeserializePayload{ChatSendRequest}(message.Payload);
|
||||
///
|
||||
/// Throws on type mismatch or malformed payload.
|
||||
/// </summary>
|
||||
T DeserializePayload<T>(ReadOnlyMemory<byte> payload) where T : notnull;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
namespace SOR.Networking.Abstractions.Messaging;
|
||||
|
||||
/// <summary>
|
||||
/// An outbound message to be sent to a client.
|
||||
///
|
||||
/// Produced by:
|
||||
/// - IMessageHandler.HandleAsync() — reply to a specific client request
|
||||
/// - IClientPush.PushAsync() — unsolicited server-initiated event
|
||||
///
|
||||
/// Wire format (JSON) for a reply:
|
||||
/// { "type": "chat.send.ack", "ref": 7, "payload": { ... } }
|
||||
///
|
||||
/// Wire format (JSON) for an unsolicited push (ref = 0):
|
||||
/// { "type": "game.state_update", "ref": 0, "payload": { ... } }
|
||||
///
|
||||
/// IMessageSerializer.Serialize() converts this into bytes for transmission.
|
||||
/// </summary>
|
||||
public interface IServerMessage
|
||||
{
|
||||
/// <summary>
|
||||
/// Dot-namespaced message type. Convention: "{service}.{action}" or
|
||||
/// "{service}.{action}.ack" for acknowledgement replies.
|
||||
/// Examples: "auth.hello.ack", "game.state_update", "error"
|
||||
/// </summary>
|
||||
string Type { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The client Seq number this message is a response to.
|
||||
/// Set to 0 for unsolicited push events (no corresponding client request).
|
||||
/// The client uses this to match async responses to pending requests.
|
||||
/// </summary>
|
||||
int Ref { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The payload object. Will be serialized by IMessageSerializer.Serialize().
|
||||
/// Can be any serializable C# object (anonymous types, records, DTOs).
|
||||
/// Null is valid for messages that carry no payload (e.g., a bare acknowledgement).
|
||||
/// </summary>
|
||||
object? Payload { get; }
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
namespace SOR.Networking.Abstractions.Push;
|
||||
|
||||
using SOR.Networking.Abstractions.Messaging;
|
||||
|
||||
/// <summary>
|
||||
/// Pushes a server-initiated message to a specific user's connected client.
|
||||
///
|
||||
/// This is the WRITE side of the push delivery pipeline:
|
||||
/// Caller → IClientPush → Redis Pub/Sub → Gateway subscriber → WebSocket → Client
|
||||
///
|
||||
/// Current implementation: RedisClientPush (SOR.Networking.Redis).
|
||||
/// To swap: create an alternative IClientPush implementation (e.g., direct in-process
|
||||
/// for single-instance deployments) and register it instead. No service code changes.
|
||||
///
|
||||
/// The GATEWAY also has a READ side (RedisPushSubscriber) that subscribes to
|
||||
/// the Redis channels for its connected users and forwards messages over WebSocket.
|
||||
/// The read side is internal to SOR.Gateway and not exposed through this interface.
|
||||
///
|
||||
/// Lifetime: Singleton.
|
||||
/// </summary>
|
||||
public interface IClientPush
|
||||
{
|
||||
/// <summary>
|
||||
/// Publishes a push message targeting the specified user.
|
||||
///
|
||||
/// Best-effort delivery: if no Gateway instance has the user connected,
|
||||
/// the message is dropped. This is intentional — push is not a reliable
|
||||
/// message queue. Use persistent storage + client sync for reliable delivery
|
||||
/// of important state (e.g., game state is stored in Redis and clients
|
||||
/// request it on reconnect; the push is just a notification to refresh).
|
||||
///
|
||||
/// Multiple Gateway instances may be subscribed to the same userId channel
|
||||
/// (e.g., if the user has two browser tabs open). All will receive and
|
||||
/// forward the message — the client is responsible for idempotent handling.
|
||||
/// </summary>
|
||||
Task PushAsync(
|
||||
string userId,
|
||||
IServerMessage message,
|
||||
CancellationToken cancellationToken = default);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<AssemblyName>SOR.Networking.Abstractions</AssemblyName>
|
||||
<!-- This project is purely interfaces and records.
|
||||
It has zero NuGet dependencies — only the .NET BCL (Base Class Library).
|
||||
Keeping it dependency-free means any project can reference it without
|
||||
pulling in heavy transitive packages. -->
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,40 @@
|
||||
namespace SOR.Networking.Abstractions.Transport;
|
||||
|
||||
/// <summary>
|
||||
/// An IClientConnection that has completed the auth handshake successfully.
|
||||
///
|
||||
/// Created by ConnectionLoop.RunAsync() after GatewayAuthValidator confirms the
|
||||
/// session token is valid. Immutable — properties are set once and never changed.
|
||||
///
|
||||
/// This is the context object passed to every IMessageHandler. Handlers use it to:
|
||||
/// - Know which user sent the message (UserId, DisplayName)
|
||||
/// - Send replies back to the correct client (Connection.SendBytesAsync)
|
||||
///
|
||||
/// 'record' in C# generates equality comparison (by value of all properties),
|
||||
/// a ToString() override, and a constructor automatically. The 'sealed' modifier
|
||||
/// means no class can inherit from it.
|
||||
/// </summary>
|
||||
public sealed record AuthenticatedConnection(
|
||||
/// <summary>The underlying transport connection for sending replies.</summary>
|
||||
IClientConnection Connection,
|
||||
|
||||
/// <summary>
|
||||
/// The authenticated user's unique identifier. A GUID stored as a string.
|
||||
/// This is the authoritative identity for all service calls made on behalf
|
||||
/// of this connection.
|
||||
/// </summary>
|
||||
string UserId,
|
||||
|
||||
/// <summary>
|
||||
/// The user's display name at the time of authentication.
|
||||
/// Cached here to avoid repeated lookups during the session.
|
||||
/// </summary>
|
||||
string DisplayName,
|
||||
|
||||
/// <summary>
|
||||
/// The session token used to authenticate this connection.
|
||||
/// Stored for revocation checks — if the token is invalidated mid-session,
|
||||
/// the connection can be closed.
|
||||
/// </summary>
|
||||
string SessionToken
|
||||
);
|
||||
@@ -0,0 +1,69 @@
|
||||
namespace SOR.Networking.Abstractions.Transport;
|
||||
|
||||
using SOR.Networking.Abstractions.Messaging;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a single connected client for the lifetime of their connection —
|
||||
/// from the moment the transport accepts them to the moment they disconnect.
|
||||
///
|
||||
/// IClientConnection is the raw, unauthenticated view of a connection.
|
||||
/// After the auth handshake succeeds, it is wrapped in an AuthenticatedConnection
|
||||
/// which adds the userId and display name.
|
||||
///
|
||||
/// Thread safety: ReceiveAsync and SendBytesAsync must NOT be called concurrently.
|
||||
/// The Gateway connection loop ensures only one receive and one send are in flight
|
||||
/// at a time per connection. The send lock in the implementation handles concurrent
|
||||
/// send attempts (e.g., push delivery arriving while a reply is being sent).
|
||||
///
|
||||
/// Lifetime: Scoped to one connection. Disposed by ConnectionLoop.RunAsync()
|
||||
/// in its finally block regardless of how the loop exits.
|
||||
/// </summary>
|
||||
public interface IClientConnection : IAsyncDisposable
|
||||
{
|
||||
/// <summary>
|
||||
/// Stable identifier for this connection. Assigned at accept time as a GUID.
|
||||
/// This is NOT the user ID — the connection exists before authentication.
|
||||
/// Used in logs and the ConnectionManager index.
|
||||
/// </summary>
|
||||
string ConnectionId { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Remote endpoint for logging (e.g., "203.0.113.42:55201").
|
||||
/// </summary>
|
||||
string RemoteAddress { get; }
|
||||
|
||||
/// <summary>
|
||||
/// True while the underlying transport channel is open and usable.
|
||||
/// May become false asynchronously when the client drops.
|
||||
/// </summary>
|
||||
bool IsConnected { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Reads and returns the next complete message from the client.
|
||||
/// Returns null on a clean close (client sent a close frame or disconnected gracefully).
|
||||
/// Throws on network error — the connection loop catches and breaks.
|
||||
///
|
||||
/// The returned IClientMessage contains raw bytes. The message type and seq are
|
||||
/// populated by IMessageSerializer.Deserialize() before dispatch.
|
||||
/// </summary>
|
||||
Task<IClientMessage?> ReceiveAsync(CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Sends pre-serialized bytes to the client.
|
||||
///
|
||||
/// Callers (Gateway send path and RedisPushSubscriber) pass bytes that have
|
||||
/// already been serialized by IMessageSerializer.Serialize(). This keeps
|
||||
/// the transport layer ignorant of the message format.
|
||||
///
|
||||
/// Implementations must serialize concurrent send calls — only one send may
|
||||
/// be in flight over the underlying transport at a time.
|
||||
/// </summary>
|
||||
ValueTask SendBytesAsync(ReadOnlyMemory<byte> bytes, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Initiates a graceful close. Implementations send a protocol-level close
|
||||
/// frame where supported (e.g., WebSocket close frame with status code).
|
||||
/// After this call IsConnected becomes false.
|
||||
/// </summary>
|
||||
Task CloseAsync(string reason, CancellationToken cancellationToken);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
namespace SOR.Networking.Abstractions.Transport;
|
||||
|
||||
/// <summary>
|
||||
/// Manages the server-side lifecycle of incoming connections for one transport protocol.
|
||||
///
|
||||
/// Current implementation: WebSocket (SOR.Networking.WebSocket.WebSocketTransport).
|
||||
/// To swap to raw TCP: create SOR.Networking.Tcp.TcpTransport implementing this interface,
|
||||
/// register it in SOR.Host instead of WebSocketTransport. Gateway code does not change.
|
||||
///
|
||||
/// Lifetime: Singleton. One ITransport instance exists for the process lifetime.
|
||||
/// </summary>
|
||||
public interface ITransport
|
||||
{
|
||||
/// <summary>
|
||||
/// Human-readable identifier for this transport. Used in logs and metrics.
|
||||
/// Examples: "websocket", "tcp", "quic"
|
||||
/// </summary>
|
||||
string Name { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Blocks until the next client connection is ready to hand off.
|
||||
/// Returns a raw, unauthenticated IClientConnection.
|
||||
///
|
||||
/// The connection is in "just accepted" state — the caller (GatewayHostedService)
|
||||
/// is responsible for running the auth handshake before trusting it.
|
||||
///
|
||||
/// Throws OperationCanceledException when the cancellation token is cancelled
|
||||
/// (i.e., on application shutdown). This is the normal exit signal.
|
||||
/// </summary>
|
||||
Task<IClientConnection> AcceptAsync(CancellationToken cancellationToken);
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
namespace SOR.Networking.Nats;
|
||||
|
||||
using System.Runtime.CompilerServices;
|
||||
using global::NATS.Client.Core;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using SOR.Networking.Abstractions.EventBus;
|
||||
|
||||
/// <summary>
|
||||
/// IEventBus implementation backed by NATS.Net.
|
||||
///
|
||||
/// This class is the only place in the codebase where NATS types appear.
|
||||
/// All calling code depends only on IEventBus (the abstraction).
|
||||
/// To replace NATS with RabbitMQ or another broker:
|
||||
/// 1. Create SOR.Networking.RabbitMq.RabbitMqEventBus implementing IEventBus
|
||||
/// 2. Register it in SOR.Host instead of NatsEventBus
|
||||
/// 3. No other code changes
|
||||
///
|
||||
/// NATS delivery guarantee: at-most-once (fire-and-forget) for core NATS.
|
||||
/// For at-least-once delivery, use NATS JetStream — add a separate
|
||||
/// JetStreamEventBus class when durable subscriber support is needed.
|
||||
///
|
||||
/// Lifetime: Singleton (INatsConnection is a Singleton from SOR.Host DI registration).
|
||||
/// </summary>
|
||||
public sealed class NatsEventBus : IEventBus
|
||||
{
|
||||
private readonly INatsConnection _nats;
|
||||
private readonly ILogger<NatsEventBus> _logger;
|
||||
|
||||
// INatsConnection is injected from DI — registered in SOR.Host.Program.cs
|
||||
// via builder.Services.AddNats(...). We don't create it here.
|
||||
public NatsEventBus(INatsConnection nats, ILogger<NatsEventBus> logger)
|
||||
{
|
||||
_nats = nats;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
/// <remarks>
|
||||
/// NATS.Net's PublishAsync{T} serializes T to JSON by default.
|
||||
/// The serialization format can be changed by configuring the INatsConnection
|
||||
/// serializer in SOR.Host — NatsEventBus does not need to change.
|
||||
/// </remarks>
|
||||
public async Task PublishAsync<T>(
|
||||
string subject,
|
||||
T payload,
|
||||
CancellationToken cancellationToken = default)
|
||||
where T : notnull
|
||||
{
|
||||
_logger.LogDebug("Publishing event to NATS subject {Subject}", subject);
|
||||
|
||||
await _nats.PublishAsync(subject, payload, cancellationToken: cancellationToken);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
/// <remarks>
|
||||
/// Returns an IAsyncEnumerable{T} that projects NATS message envelopes down to T.
|
||||
/// The 'yield return' pattern (async iterator) is used via the AsyncIterator
|
||||
/// helper method below because you cannot use 'await foreach' inside a method
|
||||
/// that also uses 'yield return' directly in older C# versions. In C# 12 with
|
||||
/// async iterators, this is supported directly.
|
||||
///
|
||||
/// Callers:
|
||||
/// await foreach (var evt in _bus.SubscribeAsync{GameEndedEvent}(subject, ct))
|
||||
/// await HandleAsync(evt);
|
||||
/// </remarks>
|
||||
public IAsyncEnumerable<T> SubscribeAsync<T>(
|
||||
string subject,
|
||||
CancellationToken cancellationToken = default)
|
||||
where T : notnull
|
||||
{
|
||||
_logger.LogDebug("Subscribing to NATS subject {Subject}", subject);
|
||||
return SubscribeAsyncIterator<T>(subject, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Async iterator that yields NATS messages as T.
|
||||
///
|
||||
/// 'async IAsyncEnumerable' with 'yield return' creates an async stream.
|
||||
/// Each 'yield return' produces one item; the caller gets control between items.
|
||||
/// The [EnumeratorCancellation] attribute forwards the caller's cancellation token
|
||||
/// into the iterator automatically when the caller cancels the 'await foreach'.
|
||||
/// </summary>
|
||||
private async IAsyncEnumerable<T> SubscribeAsyncIterator<T>(
|
||||
string subject,
|
||||
[EnumeratorCancellation] CancellationToken cancellationToken)
|
||||
where T : notnull
|
||||
{
|
||||
// SubscribeAsync returns IAsyncEnumerable{NatsMsg{T}}.
|
||||
// NatsMsg{T} is the NATS envelope containing the deserialized data plus metadata.
|
||||
await foreach (var msg in _nats
|
||||
.SubscribeAsync<T>(subject, cancellationToken: cancellationToken)
|
||||
.WithCancellation(cancellationToken))
|
||||
{
|
||||
// Skip null data (can occur for empty NATS messages or deserialization failures).
|
||||
if (msg.Data is null)
|
||||
{
|
||||
_logger.LogWarning(
|
||||
"Received null data on NATS subject {Subject} — skipping", subject);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Yield the deserialized value to the caller.
|
||||
// The caller processes it before we loop back to await the next message.
|
||||
yield return msg.Data;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<AssemblyName>SOR.Networking.Nats</AssemblyName>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- NATS.Net: the official, modern .NET NATS client.
|
||||
Provides INatsClient with async publish/subscribe support,
|
||||
built-in JSON serialization, and JetStream for durable messaging. -->
|
||||
<PackageReference Include="NATS.Net" />
|
||||
|
||||
<ProjectReference Include="..\SOR.Networking.Abstractions\SOR.Networking.Abstractions.csproj" />
|
||||
<ProjectReference Include="..\SOR.Shared\SOR.Shared.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,37 @@
|
||||
namespace SOR.Networking.Nats;
|
||||
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using SOR.Networking.Abstractions.EventBus;
|
||||
|
||||
/// <summary>
|
||||
/// Registers the NATS event bus in the DI container.
|
||||
///
|
||||
/// Note: The INatsConnection itself is registered in SOR.Host.Program.cs via
|
||||
/// builder.Services.AddNats(...) because it requires the NATS URL from config.
|
||||
/// This registration only wraps it behind IEventBus.
|
||||
///
|
||||
/// To swap NATS for another broker:
|
||||
/// In SOR.Host, replace AddNatsEventBus() with AddRabbitMqEventBus() (or equivalent).
|
||||
/// No service code changes.
|
||||
/// </summary>
|
||||
public static class ServiceRegistration
|
||||
{
|
||||
/// <summary>
|
||||
/// Registers IEventBus → NatsEventBus as a Singleton.
|
||||
///
|
||||
/// Precondition: INatsConnection must already be registered in the DI container
|
||||
/// (done in SOR.Host.Program.cs via builder.Services.AddNats(...)).
|
||||
/// </summary>
|
||||
public static IServiceCollection AddNatsEventBus(
|
||||
this IServiceCollection services,
|
||||
IConfiguration configuration)
|
||||
{
|
||||
// NatsEventBus depends on INatsConnection (Singleton from Host)
|
||||
// and ILogger{NatsEventBus} (provided by Serilog).
|
||||
// Both are already registered by the time this runs.
|
||||
services.AddSingleton<IEventBus, NatsEventBus>();
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
namespace SOR.Networking.Redis;
|
||||
|
||||
using Microsoft.Extensions.Logging;
|
||||
using StackExchange.Redis;
|
||||
using SOR.Networking.Abstractions.Messaging;
|
||||
using SOR.Networking.Abstractions.Push;
|
||||
using SOR.Shared.Redis;
|
||||
|
||||
/// <summary>
|
||||
/// IClientPush implementation using Redis Pub/Sub.
|
||||
///
|
||||
/// This is the WRITE side of the push delivery pipeline:
|
||||
/// Service calls PushAsync(userId, message)
|
||||
/// → Serializes message to bytes (via IMessageSerializer)
|
||||
/// → Publishes to Redis channel "push:{userId}"
|
||||
/// → Gateway (subscribed to that channel) receives the bytes
|
||||
/// → Gateway forwards bytes to the user's WebSocket
|
||||
///
|
||||
/// The Gateway's READ side (RedisPushSubscriber) handles the subscription.
|
||||
/// This class only handles publishing — it has no knowledge of Gateway internals.
|
||||
///
|
||||
/// Best-effort delivery: if no Gateway is subscribed to the userId channel
|
||||
/// (user disconnected), the message is dropped silently. This is correct behavior.
|
||||
/// Services must not assume push delivery is reliable — use persistent state and
|
||||
/// client-initiated sync for any data that must survive disconnections.
|
||||
///
|
||||
/// Lifetime: Singleton (IConnectionMultiplexer is a Singleton from SOR.Host).
|
||||
/// </summary>
|
||||
public sealed class RedisClientPush : IClientPush
|
||||
{
|
||||
private readonly IConnectionMultiplexer _redis;
|
||||
private readonly IMessageSerializer _serializer;
|
||||
private readonly ILogger<RedisClientPush> _logger;
|
||||
|
||||
public RedisClientPush(
|
||||
IConnectionMultiplexer redis,
|
||||
IMessageSerializer serializer,
|
||||
ILogger<RedisClientPush> logger)
|
||||
{
|
||||
_redis = redis;
|
||||
_serializer = serializer;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public async Task PushAsync(
|
||||
string userId,
|
||||
IServerMessage message,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
// Serialize the message to bytes.
|
||||
// The bytes are already in wire format (envelope + payload) — ready for
|
||||
// the Gateway to forward directly to the WebSocket without re-serializing.
|
||||
var bytes = _serializer.Serialize(message);
|
||||
|
||||
// Get the Redis channel key for this user.
|
||||
// RedisKey.Literal wraps the string to avoid StackExchange.Redis interpreting
|
||||
// pattern characters (* ? [) as wildcards.
|
||||
var channel = RedisChannel.Literal(RedisKeys.ClientPushChannel(userId));
|
||||
|
||||
_logger.LogDebug(
|
||||
"Pushing {MessageType} to user {UserId} via Redis Pub/Sub",
|
||||
message.Type, userId);
|
||||
|
||||
// ISubscriber.PublishAsync sends to the channel.
|
||||
// The return value is the number of subscribers that received the message.
|
||||
// We don't check it — zero subscribers (user disconnected) is not an error.
|
||||
var subscriber = _redis.GetSubscriber();
|
||||
await subscriber.PublishAsync(channel, bytes.ToArray());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<AssemblyName>SOR.Networking.Redis</AssemblyName>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- StackExchange.Redis: the standard high-performance Redis client for .NET.
|
||||
Provides IConnectionMultiplexer (the connection pool manager),
|
||||
IDatabase (for GET/SET/etc.), and ISubscriber (for Pub/Sub). -->
|
||||
<PackageReference Include="StackExchange.Redis" />
|
||||
|
||||
<ProjectReference Include="..\SOR.Networking.Abstractions\SOR.Networking.Abstractions.csproj" />
|
||||
<ProjectReference Include="..\SOR.Shared\SOR.Shared.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,30 @@
|
||||
namespace SOR.Networking.Redis;
|
||||
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using SOR.Networking.Abstractions.Push;
|
||||
|
||||
/// <summary>
|
||||
/// Registers the Redis client push service in the DI container.
|
||||
///
|
||||
/// Note: IConnectionMultiplexer and IMessageSerializer must already be registered
|
||||
/// before calling this (both are registered in SOR.Host.Program.cs).
|
||||
///
|
||||
/// To replace Redis Pub/Sub with another push delivery mechanism:
|
||||
/// Create an alternative IClientPush implementation and call its registration
|
||||
/// method instead of AddRedisClientPush(). No Gateway or service code changes.
|
||||
/// </summary>
|
||||
public static class ServiceRegistration
|
||||
{
|
||||
/// <summary>
|
||||
/// Registers IClientPush → RedisClientPush as a Singleton.
|
||||
///
|
||||
/// Preconditions (must be registered in DI before calling this):
|
||||
/// - IConnectionMultiplexer (StackExchange.Redis)
|
||||
/// - IMessageSerializer (from SOR.Shared.ServiceRegistration.AddSharedServices)
|
||||
/// </summary>
|
||||
public static IServiceCollection AddRedisClientPush(this IServiceCollection services)
|
||||
{
|
||||
services.AddSingleton<IClientPush, RedisClientPush>();
|
||||
return services;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<AssemblyName>SOR.Networking.WebSocket</AssemblyName>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- ASP.NET Core framework reference: gives access to IApplicationBuilder,
|
||||
HttpContext, WebSocket types, middleware APIs, etc.
|
||||
Note: AddWebSockets() from Microsoft.AspNetCore.WebSockets is called in
|
||||
SOR.Host.Program.cs (which uses Microsoft.NET.Sdk.Web), not here. -->
|
||||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||
|
||||
<ProjectReference Include="..\SOR.Networking.Abstractions\SOR.Networking.Abstractions.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,122 @@
|
||||
namespace SOR.Networking.WebSocket;
|
||||
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Options;
|
||||
using SOR.Networking.Abstractions.Transport;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods to register and wire the WebSocket transport.
|
||||
///
|
||||
/// Usage in SOR.Host.Program.cs:
|
||||
/// builder.Services.AddWebSocketTransport(builder.Configuration);
|
||||
/// ...
|
||||
/// app.UseWebSocketTransport(); // Must come BEFORE UseRouting()
|
||||
/// </summary>
|
||||
public static class ServiceRegistration
|
||||
{
|
||||
/// <summary>
|
||||
/// Registers the WebSocket transport in the DI container.
|
||||
///
|
||||
/// What this registers:
|
||||
/// - WebSocketTransportOptions from appsettings.json "WebSocket" section
|
||||
/// - WebSocketTransport as Singleton (the transport lives for the process lifetime)
|
||||
/// - ITransport → WebSocketTransport (the interface Gateway depends on)
|
||||
/// - ASP.NET Core's built-in WebSocket middleware (services.AddWebSockets)
|
||||
/// </summary>
|
||||
public static IServiceCollection AddWebSocketTransport(
|
||||
this IServiceCollection services,
|
||||
IConfiguration configuration)
|
||||
{
|
||||
// Bind the "WebSocket" config section to the typed options class.
|
||||
// IOptions{WebSocketTransportOptions} can then be injected anywhere.
|
||||
services.Configure<WebSocketTransportOptions>(
|
||||
configuration.GetSection("WebSocket"));
|
||||
|
||||
// Register the concrete transport as Singleton.
|
||||
// GatewayHostedService injects ITransport (the interface).
|
||||
// The middleware (UseWebSocketTransport) injects WebSocketTransport directly
|
||||
// to call EnqueueConnectionAsync — that's why we register it by concrete type too.
|
||||
services.AddSingleton<WebSocketTransport>();
|
||||
|
||||
// Register ITransport → resolve WebSocketTransport from the container.
|
||||
// This means: anywhere ITransport is injected, the container provides
|
||||
// the already-registered WebSocketTransport singleton.
|
||||
services.AddSingleton<ITransport>(
|
||||
sp => sp.GetRequiredService<WebSocketTransport>());
|
||||
|
||||
// NOTE: services.AddWebSockets() must be called separately in SOR.Host.Program.cs.
|
||||
// AddWebSockets is an ASP.NET Core extension that resolves correctly only from a
|
||||
// Microsoft.NET.Sdk.Web project. SOR.Host (the entry point) calls it before
|
||||
// calling AddWebSocketTransport(). See SOR.Host.Program.cs for details.
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Inserts the WebSocket upgrade middleware into the ASP.NET Core pipeline.
|
||||
///
|
||||
/// This middleware intercepts HTTP requests to the configured path ("/ws" by default),
|
||||
/// performs the WebSocket upgrade handshake, and hands the socket to WebSocketTransport.
|
||||
///
|
||||
/// IMPORTANT: Call this BEFORE app.UseRouting() so the WebSocket middleware
|
||||
/// intercepts upgrade requests before they reach the routing layer.
|
||||
///
|
||||
/// The middleware holds the request alive (via TaskCompletionSource) until
|
||||
/// the Gateway's ConnectionLoop signals the connection is done. This keeps
|
||||
/// the ASP.NET Core request pipeline entry point open for the duration of
|
||||
/// the WebSocket session.
|
||||
/// </summary>
|
||||
public static IApplicationBuilder UseWebSocketTransport(this IApplicationBuilder app)
|
||||
{
|
||||
// NOTE: app.UseWebSockets() is called in SOR.Host.Program.cs before this method.
|
||||
// It must be called from the Web SDK host project (SOR.Host) where the
|
||||
// Microsoft.AspNetCore.WebSockets assembly is fully available.
|
||||
|
||||
// Our custom middleware: intercept WebSocket upgrade requests.
|
||||
app.Use(async (context, next) =>
|
||||
{
|
||||
var options = context.RequestServices
|
||||
.GetRequiredService<IOptions<WebSocketTransportOptions>>().Value;
|
||||
|
||||
// Only intercept requests to the configured WebSocket path.
|
||||
// All other requests pass through to the next middleware (routing, gRPC, etc.).
|
||||
if (context.Request.Path != options.Path ||
|
||||
!context.WebSockets.IsWebSocketRequest)
|
||||
{
|
||||
await next(context);
|
||||
return;
|
||||
}
|
||||
|
||||
// Perform the WebSocket upgrade handshake.
|
||||
// AcceptWebSocketAsync sends the HTTP 101 Switching Protocols response.
|
||||
var socket = await context.WebSockets.AcceptWebSocketAsync();
|
||||
|
||||
// A TaskCompletionSource is a manually controlled Task completion signal.
|
||||
// The Gateway's ConnectionLoop calls connectionDone.SetResult() when it finishes
|
||||
// handling this connection. Until then, this middleware holds the request alive.
|
||||
var connectionDone = new TaskCompletionSource(
|
||||
TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
// Register a callback: when the request is aborted (client closes browser,
|
||||
// server shutdown, etc.), signal the done TCS so the middleware exits cleanly.
|
||||
context.RequestAborted.Register(() => connectionDone.TrySetResult());
|
||||
|
||||
var transport = context.RequestServices
|
||||
.GetRequiredService<WebSocketTransport>();
|
||||
|
||||
// Enqueue the connection for the Gateway's accept loop.
|
||||
// Pass connectionDone so the connection signals this middleware on dispose.
|
||||
await transport.EnqueueConnectionAsync(
|
||||
socket, context, connectionDone, context.RequestAborted);
|
||||
|
||||
// Wait here until the Gateway signals the connection is done.
|
||||
// This keeps the HTTP request alive for the full WebSocket session duration.
|
||||
await connectionDone.Task;
|
||||
});
|
||||
|
||||
return app;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
namespace SOR.Networking.WebSocket;
|
||||
|
||||
using System.Buffers;
|
||||
using System.Net.WebSockets;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using SOR.Networking.Abstractions.Messaging;
|
||||
using SOR.Networking.Abstractions.Transport;
|
||||
|
||||
/// <summary>
|
||||
/// IClientConnection implementation backed by a System.Net.WebSockets.WebSocket.
|
||||
///
|
||||
/// Key responsibilities:
|
||||
/// - Frame assembly: WebSocket messages can be split across multiple frames.
|
||||
/// ReceiveAsync loops until EndOfMessage = true, assembling into a MemoryStream.
|
||||
/// - Send serialization: only one send can be in flight at a time per WebSocket.
|
||||
/// SemaphoreSlim(1,1) acts as an async mutex on the send path.
|
||||
/// - Ping/pong heartbeat: a background task sends periodic ping frames so
|
||||
/// disconnected clients are detected within one PingIntervalMs cycle.
|
||||
///
|
||||
/// Thread safety:
|
||||
/// - ReceiveAsync: called only by the ConnectionLoop — no concurrent receive.
|
||||
/// - SendBytesAsync: may be called concurrently (push delivery + reply at same time).
|
||||
/// The _sendLock serializes concurrent sends.
|
||||
///
|
||||
/// Lifetime: created by WebSocketTransport per accepted connection.
|
||||
/// Disposed by ConnectionLoop.RunAsync() in its finally block.
|
||||
/// </summary>
|
||||
public sealed class WebSocketClientConnection : IClientConnection
|
||||
{
|
||||
private readonly System.Net.WebSockets.WebSocket _socket;
|
||||
private readonly WebSocketTransportOptions _options;
|
||||
private readonly ILogger _logger;
|
||||
|
||||
// SemaphoreSlim(1, 1) is a lightweight async-compatible mutex.
|
||||
// Unlike 'lock', it can be awaited without blocking the thread.
|
||||
private readonly SemaphoreSlim _sendLock = new(1, 1);
|
||||
|
||||
// CancellationTokenSource for the ping loop. Cancelled on dispose.
|
||||
private readonly CancellationTokenSource _pingSts = new();
|
||||
|
||||
// Signals the middleware that this connection's loop has finished,
|
||||
// so the middleware can release the HTTP request cleanly.
|
||||
private readonly TaskCompletionSource _connectionDone;
|
||||
|
||||
private bool _disposed;
|
||||
|
||||
public string ConnectionId { get; }
|
||||
public string RemoteAddress { get; }
|
||||
|
||||
public bool IsConnected =>
|
||||
!_disposed && _socket.State == WebSocketState.Open;
|
||||
|
||||
public WebSocketClientConnection(
|
||||
System.Net.WebSockets.WebSocket socket,
|
||||
string connectionId,
|
||||
string remoteAddress,
|
||||
WebSocketTransportOptions options,
|
||||
ILogger logger,
|
||||
TaskCompletionSource connectionDone)
|
||||
{
|
||||
_socket = socket;
|
||||
ConnectionId = connectionId;
|
||||
RemoteAddress = remoteAddress;
|
||||
_options = options;
|
||||
_logger = logger;
|
||||
_connectionDone = connectionDone;
|
||||
|
||||
// Start the ping loop in the background immediately.
|
||||
// '_ =' discards the Task intentionally — the loop runs fire-and-forget.
|
||||
// Exceptions inside are caught within the loop and logged.
|
||||
_ = RunPingLoopAsync(_pingSts.Token);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
/// <remarks>
|
||||
/// Assembles a complete WebSocket message from one or more frames.
|
||||
/// Returns null on clean close (WebSocketMessageType.Close received).
|
||||
/// Throws WebSocketException on unexpected disconnect — the caller handles it.
|
||||
///
|
||||
/// ArrayPool{byte}.Shared is used to rent receive buffers from a reusable pool
|
||||
/// rather than allocating a new byte[] per receive. Buffers are returned in finally.
|
||||
/// This is a common pattern for high-throughput .NET networking code.
|
||||
/// </remarks>
|
||||
public async Task<IClientMessage?> ReceiveAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
// Rent a buffer from the shared pool. The buffer may be larger than requested.
|
||||
// Always use ArrayPool.Return() in a finally block to avoid pool exhaustion.
|
||||
var buffer = ArrayPool<byte>.Shared.Rent(_options.MaxMessageSizeBytes);
|
||||
try
|
||||
{
|
||||
using var messageStream = new MemoryStream();
|
||||
WebSocketReceiveResult result;
|
||||
|
||||
do
|
||||
{
|
||||
// Receive one frame (may not be the complete message).
|
||||
result = await _socket.ReceiveAsync(
|
||||
new ArraySegment<byte>(buffer), cancellationToken);
|
||||
|
||||
switch (result.MessageType)
|
||||
{
|
||||
case WebSocketMessageType.Close:
|
||||
// Client sent a close frame — clean disconnect.
|
||||
_logger.LogDebug(
|
||||
"WebSocket close received: ConnectionId={ConnectionId} Status={Status}",
|
||||
ConnectionId, result.CloseStatus);
|
||||
return null;
|
||||
|
||||
case WebSocketMessageType.Text:
|
||||
case WebSocketMessageType.Binary:
|
||||
// Check if this frame would push us over the size limit.
|
||||
if (messageStream.Length + result.Count > _options.MaxMessageSizeBytes)
|
||||
{
|
||||
_logger.LogWarning(
|
||||
"Message too large: ConnectionId={ConnectionId} Limit={Limit}",
|
||||
ConnectionId, _options.MaxMessageSizeBytes);
|
||||
await CloseAsync("message_too_large", cancellationToken);
|
||||
return null;
|
||||
}
|
||||
// Append this frame's bytes to the message buffer.
|
||||
messageStream.Write(buffer, 0, result.Count);
|
||||
break;
|
||||
}
|
||||
|
||||
// EndOfMessage = true when all frames of this message have arrived.
|
||||
} while (!result.EndOfMessage);
|
||||
|
||||
// Return the assembled bytes as a RawClientMessage.
|
||||
// The serializer will parse the envelope (type, seq, payload) from these bytes.
|
||||
// We import RawClientMessage from SOR.Networking.Abstractions' concrete type
|
||||
// in SOR.Shared — but this project doesn't reference SOR.Shared.
|
||||
// Solution: return the bytes wrapped in a minimal internal implementation.
|
||||
return new ReceivedMessage(messageStream.ToArray());
|
||||
}
|
||||
finally
|
||||
{
|
||||
// Always return the rented buffer, even if an exception is thrown.
|
||||
ArrayPool<byte>.Shared.Return(buffer);
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public async ValueTask SendBytesAsync(ReadOnlyMemory<byte> bytes, CancellationToken cancellationToken)
|
||||
{
|
||||
// Acquire the send lock. If another send is in progress, this awaits until it completes.
|
||||
await _sendLock.WaitAsync(cancellationToken);
|
||||
try
|
||||
{
|
||||
if (_socket.State != WebSocketState.Open) return;
|
||||
|
||||
// Send as a binary frame. EndOfMessage = true (single-frame message).
|
||||
await _socket.SendAsync(bytes, WebSocketMessageType.Binary, true, cancellationToken);
|
||||
}
|
||||
finally
|
||||
{
|
||||
// Always release the lock, even if an exception occurs.
|
||||
_sendLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public async Task CloseAsync(string reason, CancellationToken cancellationToken)
|
||||
{
|
||||
if (_socket.State != WebSocketState.Open) return;
|
||||
|
||||
try
|
||||
{
|
||||
// Send a close frame with a normal closure status.
|
||||
// The client should respond with its own close frame, completing the handshake.
|
||||
await _socket.CloseAsync(
|
||||
WebSocketCloseStatus.NormalClosure,
|
||||
reason,
|
||||
cancellationToken);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// If the close handshake fails (client already gone), log and continue.
|
||||
_logger.LogDebug(ex,
|
||||
"Close handshake failed: ConnectionId={ConnectionId}", ConnectionId);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Ping/Pong Heartbeat ────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Sends periodic ping frames to detect stale connections.
|
||||
/// RFC 6455: the remote end must respond with a pong frame within a reasonable time.
|
||||
/// ASP.NET Core's WebSocket implementation handles pong responses automatically.
|
||||
/// If the connection drops between pings, the next send or receive will throw.
|
||||
/// </summary>
|
||||
private async Task RunPingLoopAsync(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
while (!ct.IsCancellationRequested)
|
||||
{
|
||||
await Task.Delay(_options.PingIntervalMs, ct);
|
||||
|
||||
if (_socket.State != WebSocketState.Open) return;
|
||||
|
||||
await _sendLock.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
// An empty binary frame acts as a ping in our protocol.
|
||||
// For full RFC 6455 ping/pong, WebSocketMessageType.Close is not applicable;
|
||||
// ASP.NET Core handles pong automatically at the Kestrel level.
|
||||
await _socket.SendAsync(
|
||||
ReadOnlyMemory<byte>.Empty,
|
||||
WebSocketMessageType.Binary,
|
||||
endOfMessage: true,
|
||||
ct);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_sendLock.Release();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// Normal exit on dispose or shutdown.
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Log ping failures but don't crash — the connection loop will detect
|
||||
// the disconnection on the next ReceiveAsync call.
|
||||
_logger.LogDebug(ex,
|
||||
"Ping loop error: ConnectionId={ConnectionId}", ConnectionId);
|
||||
}
|
||||
}
|
||||
|
||||
// ── IAsyncDisposable ──────────────────────────────────────────────────────
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
|
||||
// Stop the ping loop.
|
||||
await _pingSts.CancelAsync();
|
||||
_pingSts.Dispose();
|
||||
|
||||
// Dispose the send lock.
|
||||
_sendLock.Dispose();
|
||||
|
||||
// Dispose the underlying WebSocket.
|
||||
_socket.Dispose();
|
||||
|
||||
// Signal the middleware that this connection's work is complete.
|
||||
// TrySetResult is used (not SetResult) because RequestAborted may have
|
||||
// already set it if the server is shutting down.
|
||||
_connectionDone.TrySetResult();
|
||||
}
|
||||
|
||||
// ── Inner type: minimal IClientMessage for raw received bytes ─────────────
|
||||
|
||||
/// <summary>
|
||||
/// Lightweight IClientMessage carrying raw wire bytes.
|
||||
/// Type and Seq are populated after IMessageSerializer.Deserialize() is called.
|
||||
/// This inner class is private to SOR.Networking.WebSocket — external code
|
||||
/// only sees the IClientMessage interface.
|
||||
/// </summary>
|
||||
private sealed class ReceivedMessage : IClientMessage
|
||||
{
|
||||
// Before deserialization, Type and Seq are unknown.
|
||||
// They will be set by the serializer layer before dispatch.
|
||||
// We use a mutable design here because the serializer returns a new
|
||||
// RawClientMessage (from SOR.Shared) — this type is only an interim carrier
|
||||
// from ReceiveAsync up to the serializer call in ConnectionLoop.
|
||||
public string Type { get; init; } = string.Empty;
|
||||
public int Seq { get; init; }
|
||||
public ReadOnlyMemory<byte> Payload { get; }
|
||||
|
||||
public ReceivedMessage(byte[] rawBytes)
|
||||
{
|
||||
// The full wire bytes (envelope + payload) are stored as Payload.
|
||||
// The serializer will parse the envelope out of these bytes.
|
||||
Payload = rawBytes;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
namespace SOR.Networking.WebSocket;
|
||||
|
||||
using System.Net.WebSockets;
|
||||
using System.Threading.Channels;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using SOR.Networking.Abstractions.Transport;
|
||||
|
||||
/// <summary>
|
||||
/// ITransport implementation for WebSocket connections.
|
||||
///
|
||||
/// How the two sides connect:
|
||||
///
|
||||
/// ┌─────────────────────────────────────────────────────────────┐
|
||||
/// │ ASP.NET Core middleware (UseWebSocketTransport) │
|
||||
/// │ - Intercepts HTTP upgrade requests to the WS path │
|
||||
/// │ - Calls AcceptWebSocketAsync() │
|
||||
/// │ - Calls WebSocketTransport.EnqueueConnectionAsync() │
|
||||
/// └────────────────────────┬────────────────────────────────────┘
|
||||
/// │ Channel.Writer.WriteAsync()
|
||||
/// ▼
|
||||
/// ┌─────────────────────────────────────────────────────────────┐
|
||||
/// │ Channel{IClientConnection} (thread-safe handoff queue) │
|
||||
/// └────────────────────────┬────────────────────────────────────┘
|
||||
/// │ Channel.Reader.ReadAsync()
|
||||
/// ▼
|
||||
/// ┌─────────────────────────────────────────────────────────────┐
|
||||
/// │ GatewayHostedService │
|
||||
/// │ - Calls ITransport.AcceptAsync() (blocks on channel) │
|
||||
/// │ - Gets an IClientConnection and fires ConnectionLoop │
|
||||
/// └─────────────────────────────────────────────────────────────┘
|
||||
///
|
||||
/// The Channel is the key: it decouples the ASP.NET Core middleware thread
|
||||
/// from the Gateway accept loop without any shared mutable state.
|
||||
///
|
||||
/// Lifetime: Singleton.
|
||||
/// </summary>
|
||||
public sealed class WebSocketTransport : ITransport
|
||||
{
|
||||
public string Name => "websocket";
|
||||
|
||||
private readonly WebSocketTransportOptions _options;
|
||||
private readonly ILoggerFactory _loggerFactory;
|
||||
private readonly ILogger<WebSocketTransport> _logger;
|
||||
|
||||
// UnboundedChannel: never drops connections. If Gateway is slow to accept,
|
||||
// connections queue. SingleReader = true allows the channel to optimize
|
||||
// for a single consumer (the Gateway accept loop).
|
||||
private readonly Channel<IClientConnection> _pendingConnections =
|
||||
Channel.CreateUnbounded<IClientConnection>(
|
||||
new UnboundedChannelOptions
|
||||
{
|
||||
SingleReader = true, // Only GatewayHostedService reads
|
||||
SingleWriter = false, // Multiple middleware calls can write concurrently
|
||||
});
|
||||
|
||||
public WebSocketTransport(
|
||||
IOptions<WebSocketTransportOptions> options,
|
||||
ILoggerFactory loggerFactory,
|
||||
ILogger<WebSocketTransport> logger)
|
||||
{
|
||||
_options = options.Value;
|
||||
_loggerFactory = loggerFactory;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called by the ASP.NET Core middleware (ServiceRegistration.UseWebSocketTransport)
|
||||
/// when a WebSocket upgrade succeeds. Creates a WebSocketClientConnection and
|
||||
/// enqueues it for the Gateway's accept loop.
|
||||
///
|
||||
/// 'internal' means this method is visible within SOR.Networking.WebSocket but
|
||||
/// not to external assemblies. The middleware and transport live in the same assembly.
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// Called by the ASP.NET Core middleware (ServiceRegistration.UseWebSocketTransport)
|
||||
/// when a WebSocket upgrade succeeds. Creates a WebSocketClientConnection and
|
||||
/// enqueues it for the Gateway's accept loop.
|
||||
///
|
||||
/// The connectionDone TaskCompletionSource is stored on the connection and signalled
|
||||
/// when the connection is disposed (ConnectionLoop.RunAsync finally block).
|
||||
/// The middleware awaits connectionDone.Task to keep the HTTP request alive for the
|
||||
/// full WebSocket session, then lets the middleware method return to free resources.
|
||||
///
|
||||
/// 'internal': visible within SOR.Networking.WebSocket but not to external assemblies.
|
||||
/// </summary>
|
||||
internal async Task EnqueueConnectionAsync(
|
||||
System.Net.WebSockets.WebSocket socket,
|
||||
HttpContext httpContext,
|
||||
TaskCompletionSource connectionDone,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var connectionId = Guid.NewGuid().ToString("N");
|
||||
var remote = httpContext.Connection.RemoteIpAddress?.ToString()
|
||||
?? httpContext.Connection.RemotePort.ToString()
|
||||
?? "unknown";
|
||||
|
||||
_logger.LogDebug(
|
||||
"WebSocket upgrade accepted: ConnectionId={ConnectionId} Remote={Remote}",
|
||||
connectionId, remote);
|
||||
|
||||
var connLogger = _loggerFactory.CreateLogger(
|
||||
$"SOR.Networking.WebSocket.Connection.{connectionId[..8]}");
|
||||
|
||||
var connection = new WebSocketClientConnection(
|
||||
socket, connectionId, remote, _options, connLogger, connectionDone);
|
||||
|
||||
// WriteAsync never blocks for an UnboundedChannel.
|
||||
await _pendingConnections.Writer.WriteAsync(connection, cancellationToken);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
/// <remarks>
|
||||
/// Blocks until a connection is enqueued by the middleware, then dequeues and returns it.
|
||||
/// Throws OperationCanceledException on shutdown (cancellationToken cancelled).
|
||||
/// </remarks>
|
||||
public async Task<IClientConnection> AcceptAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
return await _pendingConnections.Reader.ReadAsync(cancellationToken);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
namespace SOR.Networking.WebSocket;
|
||||
|
||||
/// <summary>
|
||||
/// Configuration options for the WebSocket transport.
|
||||
/// Bound from the "WebSocket" section of appsettings.json via IOptions{WebSocketTransportOptions}.
|
||||
///
|
||||
/// appsettings.json example:
|
||||
/// {
|
||||
/// "WebSocket": {
|
||||
/// "Path": "/ws",
|
||||
/// "PingIntervalMs": 30000,
|
||||
/// "MaxMessageSizeBytes": 65536,
|
||||
/// "AuthTimeoutMs": 10000
|
||||
/// }
|
||||
/// }
|
||||
/// </summary>
|
||||
public sealed class WebSocketTransportOptions
|
||||
{
|
||||
/// <summary>
|
||||
/// The URL path the Gateway listens for WebSocket upgrade requests.
|
||||
/// All other paths are passed through to the normal ASP.NET Core routing pipeline.
|
||||
/// Default: "/ws"
|
||||
/// </summary>
|
||||
public string Path { get; set; } = "/ws";
|
||||
|
||||
/// <summary>
|
||||
/// How often to send a WebSocket ping frame to detect stale connections.
|
||||
/// RFC 6455 compliant clients respond automatically with a pong.
|
||||
/// If no pong is received within this interval the connection is considered dead.
|
||||
/// Default: 30 seconds (30,000 ms)
|
||||
/// </summary>
|
||||
public int PingIntervalMs { get; set; } = 30_000;
|
||||
|
||||
/// <summary>
|
||||
/// Maximum allowed size of a single WebSocket message in bytes.
|
||||
/// Multi-frame messages are assembled up to this limit.
|
||||
/// Messages exceeding this cause the connection to be closed with code 1009 (too large).
|
||||
/// Default: 64 KB (65,536 bytes) — sufficient for all current game message types.
|
||||
/// </summary>
|
||||
public int MaxMessageSizeBytes { get; set; } = 65_536;
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
// Protobuf language version 3 — the current standard.
|
||||
// proto3 differences from proto2: all fields optional by default,
|
||||
// no required fields, simpler default values.
|
||||
syntax = "proto3";
|
||||
|
||||
// The C# namespace for all generated types from this file.
|
||||
// Generated classes: AuthService.AuthServiceBase (server), AuthService.AuthServiceClient (client),
|
||||
// LoginRequest, LoginResponse, ValidateTokenRequest, ValidateTokenResponse, etc.
|
||||
option csharp_namespace = "SOR.Shared.Proto";
|
||||
|
||||
// Package prevents naming collisions with other .proto files.
|
||||
// Does not affect the C# namespace (that's controlled by csharp_namespace above).
|
||||
package sor.auth;
|
||||
|
||||
// ── Request / Response Messages ───────────────────────────────────────────────
|
||||
//
|
||||
// A 'message' is a structured data type. It compiles to a C# class with properties.
|
||||
// Each field has:
|
||||
// type — the data type (string, int32, bool, or another message)
|
||||
// name — the property name in the generated C# code
|
||||
// number — the field number used in binary encoding (NEVER change these;
|
||||
// changing a field number is a breaking change in binary format)
|
||||
|
||||
// ── Login ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
message LoginRequest {
|
||||
string email = 1;
|
||||
string password = 2;
|
||||
}
|
||||
|
||||
message LoginResponse {
|
||||
bool success = 1;
|
||||
|
||||
// Only populated on success. Empty string ("") on failure.
|
||||
string session_token = 2;
|
||||
|
||||
// Only populated on failure. Examples: "USER_NOT_FOUND", "INVALID_PASSWORD", "ACCOUNT_BANNED"
|
||||
string error_code = 3;
|
||||
}
|
||||
|
||||
// ── Token Validation ──────────────────────────────────────────────────────────
|
||||
|
||||
// Used by Gateway during the auth handshake to validate session tokens.
|
||||
// Also used by other services that need to verify caller identity.
|
||||
message ValidateTokenRequest {
|
||||
string session_token = 1;
|
||||
}
|
||||
|
||||
message ValidateTokenResponse {
|
||||
bool valid = 1;
|
||||
|
||||
// Only populated when valid = true.
|
||||
string user_id = 2;
|
||||
string display_name = 3;
|
||||
}
|
||||
|
||||
// ── Registration ──────────────────────────────────────────────────────────────
|
||||
|
||||
message RegisterRequest {
|
||||
string email = 1;
|
||||
string password = 2;
|
||||
string display_name = 3;
|
||||
}
|
||||
|
||||
message RegisterResponse {
|
||||
bool success = 1;
|
||||
string session_token = 2; // Set on success — user is automatically logged in
|
||||
string error_code = 3; // e.g., "EMAIL_TAKEN", "DISPLAY_NAME_TAKEN", "WEAK_PASSWORD"
|
||||
}
|
||||
|
||||
// ── Logout ────────────────────────────────────────────────────────────────────
|
||||
|
||||
message LogoutRequest {
|
||||
string session_token = 1;
|
||||
}
|
||||
|
||||
// Empty response — logout always succeeds (idempotent; revoking a non-existent token is fine)
|
||||
message LogoutResponse {}
|
||||
|
||||
// ── Service Definition ────────────────────────────────────────────────────────
|
||||
//
|
||||
// 'service' defines the RPC methods. The Protobuf compiler generates:
|
||||
// - AuthService.AuthServiceBase: abstract base class for the server handler to inherit
|
||||
// - AuthService.AuthServiceClient: client stub for other services to call Auth
|
||||
|
||||
service AuthService {
|
||||
// Primary login with email + password
|
||||
rpc Login(LoginRequest) returns (LoginResponse);
|
||||
|
||||
// Validate an opaque session token (called by Gateway on every connection)
|
||||
rpc ValidateToken(ValidateTokenRequest) returns (ValidateTokenResponse);
|
||||
|
||||
// Create a new account
|
||||
rpc Register(RegisterRequest) returns (RegisterResponse);
|
||||
|
||||
// Revoke a session token (called on explicit logout or ban)
|
||||
rpc Logout(LogoutRequest) returns (LogoutResponse);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<AssemblyName>SOR.Shared.Proto</AssemblyName>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- Grpc.AspNetCore includes:
|
||||
- Google.Protobuf: runtime library for reading/writing Protobuf messages
|
||||
- Grpc.Core.Api: gRPC abstractions (ServerCallContext, etc.)
|
||||
- Grpc.AspNetCore.Server: ASP.NET Core gRPC server integration
|
||||
- Grpc.Net.Client: gRPC client (for services calling other services) -->
|
||||
<PackageReference Include="Grpc.AspNetCore" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- Protobuf build targets: for each .proto file listed here, the build
|
||||
process runs 'protoc' (the Protobuf compiler) to generate C# code.
|
||||
GrpcServices="Both" generates:
|
||||
- Server base classes (e.g., AuthService.AuthServiceBase) for handler implementations
|
||||
- Client stubs (e.g., AuthService.AuthServiceClient) for inter-service calls
|
||||
The generated files appear in obj/ and are included automatically. -->
|
||||
<Protobuf Include="Protos/auth.proto" GrpcServices="Both" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,60 @@
|
||||
namespace SOR.Shared.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Standardized return type for business logic operations.
|
||||
///
|
||||
/// Expected failures (user not found, invalid input, duplicate name, etc.) are
|
||||
/// returned as ServiceResult.Fail(...) — no exception is thrown.
|
||||
/// Exceptions are reserved for truly unexpected failures (database unreachable, OOM).
|
||||
///
|
||||
/// Usage in a service:
|
||||
/// public async Task{ServiceResult{string}} LoginAsync(string email, string password)
|
||||
/// {
|
||||
/// var user = await _repo.FindByEmailAsync(email);
|
||||
/// if (user is null) return ServiceResult{string}.Fail("USER_NOT_FOUND", "...");
|
||||
/// ...
|
||||
/// return ServiceResult{string}.Ok(token);
|
||||
/// }
|
||||
///
|
||||
/// Usage in a handler:
|
||||
/// var result = await _authService.LoginAsync(email, password);
|
||||
/// if (!result.Success) return ServerMessage.Error(req.Seq, result.ErrorCode!, result.ErrorMessage!);
|
||||
/// return ServerMessage.Reply("auth.login.ack", req.Seq, new { Token = result.Value });
|
||||
///
|
||||
/// 'record' generates equality, ToString(), and a compact constructor automatically.
|
||||
/// The generic parameter T is the success value type.
|
||||
/// </summary>
|
||||
public sealed record ServiceResult<T>
|
||||
{
|
||||
/// <summary>True if the operation completed without an expected failure.</summary>
|
||||
public required bool Success { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// The operation's output value. Non-null when Success = true.
|
||||
/// The '?' after T makes this property nullable (can hold null).
|
||||
/// </summary>
|
||||
public T? Value { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Machine-readable error code. Non-null when Success = false.
|
||||
/// Convention: SCREAMING_SNAKE_CASE. Examples: "USER_NOT_FOUND", "INVALID_PASSWORD"
|
||||
/// Handlers map these to IServerMessage error responses sent to the client.
|
||||
/// </summary>
|
||||
public string? ErrorCode { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Human-readable error description. Non-null when Success = false.
|
||||
/// May be sent to the client in development; use generic messages in production.
|
||||
/// </summary>
|
||||
public string? ErrorMessage { get; init; }
|
||||
|
||||
// ── Factory methods ────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Returns a successful result containing the given value.</summary>
|
||||
public static ServiceResult<T> Ok(T value) =>
|
||||
new() { Success = true, Value = value };
|
||||
|
||||
/// <summary>Returns a failed result with the given error code and message.</summary>
|
||||
public static ServiceResult<T> Fail(string errorCode, string message) =>
|
||||
new() { Success = false, ErrorCode = errorCode, ErrorMessage = message };
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
namespace SOR.Shared.Nats;
|
||||
|
||||
/// <summary>
|
||||
/// All NATS subject names used for inter-service async pub/sub, in one place.
|
||||
///
|
||||
/// Same rationale as RedisKeys: centralizing prevents typos, collisions, and makes
|
||||
/// the full event catalog visible at a glance. A rename touches one file.
|
||||
///
|
||||
/// Naming convention: "sor.{service}.{event}" — all lowercase, dot-separated.
|
||||
/// This matches NATS subject hierarchy conventions and allows wildcard subscriptions
|
||||
/// like "sor.game.*" (all game events) or "sor.>" (all SOR events, for a logging service).
|
||||
///
|
||||
/// Subjects defined here are for NATS fan-out (IEventBus).
|
||||
/// Redis Pub/Sub keys (IClientPush) are in RedisKeys.
|
||||
/// </summary>
|
||||
public static class NatsSubjects
|
||||
{
|
||||
// ── Game ──────────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Published by Game service when a match ends.
|
||||
/// Consumers: Leaderboard (update MMR), Collection (grant rewards), Chat (notify channel)
|
||||
/// Payload: GameEndedEvent { GameId, WinnerId, LoserId, DurationSeconds, EndedAt }
|
||||
/// </summary>
|
||||
public const string GameEnded = "sor.game.ended";
|
||||
|
||||
/// <summary>
|
||||
/// Published by Game service when a match is about to start (all players connected).
|
||||
/// Consumers: Chat (create match channel)
|
||||
/// Payload: GameStartedEvent { GameId, PlayerIds[], StartedAt }
|
||||
/// </summary>
|
||||
public const string GameStarted = "sor.game.started";
|
||||
|
||||
// ── Bazaar / Economy ──────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Published by Bazaar service when a purchase completes successfully.
|
||||
/// Consumers: Collection (grant purchased cards/packs)
|
||||
/// Payload: PurchaseCompletedEvent { UserId, ItemId, ItemType, PricePaid, CurrencyType }
|
||||
/// </summary>
|
||||
public const string BazaarPurchaseCompleted = "sor.bazaar.purchase.completed";
|
||||
|
||||
// ── Collection ────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Published by Collection service when a card is added to a user's collection.
|
||||
/// Consumers: any service that tracks collection state
|
||||
/// Payload: CardGrantedEvent { UserId, CardId, Source, GrantedAt }
|
||||
/// </summary>
|
||||
public const string CollectionCardGranted = "sor.collection.card.granted";
|
||||
|
||||
// ── Leaderboard ───────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Published by Leaderboard service after MMR is updated for a match.
|
||||
/// Consumers: Gateway (push rating change notification to affected users)
|
||||
/// Payload: MatchRatedEvent { GameId, WinnerId, WinnerNewMmr, LoserId, LoserNewMmr }
|
||||
/// </summary>
|
||||
public const string LeaderboardMatchRated = "sor.leaderboard.match.rated";
|
||||
|
||||
// ── Admin ─────────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Published by Admin service when a player is banned.
|
||||
/// Consumers: Gateway (disconnect the player immediately), Auth (revoke all sessions)
|
||||
/// Payload: PlayerBannedEvent { UserId, BannedBy, Reason, ExpiresAt (null = permanent) }
|
||||
/// </summary>
|
||||
public const string AdminPlayerBanned = "sor.admin.player.banned";
|
||||
|
||||
/// <summary>
|
||||
/// Published by Admin service when a feature flag changes.
|
||||
/// Consumers: any service that caches feature flags in memory
|
||||
/// Payload: FeatureFlagChangedEvent { Flag, Enabled }
|
||||
/// </summary>
|
||||
public const string AdminFeatureFlagChanged = "sor.admin.featureflag.changed";
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
namespace SOR.Shared.Networking;
|
||||
|
||||
using SOR.Networking.Abstractions.Messaging;
|
||||
|
||||
/// <summary>
|
||||
/// Concrete implementation of IClientMessage.
|
||||
///
|
||||
/// Lifecycle:
|
||||
/// 1. The transport (WebSocketClientConnection.ReceiveAsync) produces raw bytes
|
||||
/// and creates a pre-parse RawClientMessage with only Payload set.
|
||||
/// 2. IMessageSerializer.Deserialize(wireBytes) parses the envelope and returns
|
||||
/// a fully populated RawClientMessage with Type, Seq, and inner Payload.
|
||||
/// 3. The dispatcher delivers it to the correct IMessageHandler.
|
||||
/// 4. The handler calls IMessageSerializer.DeserializePayload{T}(message.Payload)
|
||||
/// to convert the inner payload bytes into its specific request record.
|
||||
///
|
||||
/// Why separate pre-parse and post-parse?
|
||||
/// The transport reads bytes without knowing the serialization format.
|
||||
/// The serializer knows the format but not the transport.
|
||||
/// Keeping them separate respects the single-responsibility principle and
|
||||
/// makes swapping either independently possible.
|
||||
/// </summary>
|
||||
public sealed class RawClientMessage : IClientMessage
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public string Type { get; }
|
||||
|
||||
/// <inheritdoc/>
|
||||
public int Seq { get; }
|
||||
|
||||
/// <inheritdoc/>
|
||||
public ReadOnlyMemory<byte> Payload { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Post-parse constructor: created by IMessageSerializer.Deserialize()
|
||||
/// after the envelope fields have been extracted from wire bytes.
|
||||
/// Type, Seq, and the inner payload bytes are all known at this point.
|
||||
/// </summary>
|
||||
public RawClientMessage(string type, int seq, ReadOnlyMemory<byte> payload)
|
||||
{
|
||||
Type = type;
|
||||
Seq = seq;
|
||||
Payload = payload;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
namespace SOR.Shared.Networking;
|
||||
|
||||
using SOR.Networking.Abstractions.Messaging;
|
||||
|
||||
/// <summary>
|
||||
/// Standard concrete implementation of IServerMessage.
|
||||
///
|
||||
/// Handlers and services construct ServerMessage instances to send to clients.
|
||||
/// The static factory methods (Reply, Push, Error) cover the three common cases
|
||||
/// and provide a readable, self-documenting call site.
|
||||
///
|
||||
/// Examples:
|
||||
/// return ServerMessage.Reply("auth.hello.ack", req.Seq, new { UserId = "..." });
|
||||
/// return ServerMessage.Error(req.Seq, "DECK_TOO_LARGE", "Max 40 cards per deck.");
|
||||
/// await _push.PushAsync(userId, ServerMessage.Push("game.state_update", gameState));
|
||||
///
|
||||
/// 'sealed record' generates constructor, equality, ToString() automatically.
|
||||
/// The primary constructor syntax '(string Type, int Ref, object? Payload)'
|
||||
/// creates the three properties and a constructor in one line.
|
||||
/// </summary>
|
||||
public sealed record ServerMessage(string Type, int Ref, object? Payload) : IServerMessage
|
||||
{
|
||||
// ── Factory methods ────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Creates a direct reply to a client request.
|
||||
/// Sets Ref = refSeq so the client can match this response to its request.
|
||||
///
|
||||
/// Use when:
|
||||
/// - A client sent a message and expects an immediate acknowledgement
|
||||
/// - The operation completed synchronously within the handler
|
||||
/// </summary>
|
||||
public static ServerMessage Reply(string type, int refSeq, object? payload = null) =>
|
||||
new(type, refSeq, payload);
|
||||
|
||||
/// <summary>
|
||||
/// Creates an unsolicited server-initiated push event.
|
||||
/// Sets Ref = 0 (no corresponding client request).
|
||||
///
|
||||
/// Use when:
|
||||
/// - The server is pushing a state change the client did not request
|
||||
/// - Examples: opponent played a card, a game invite arrived, MMR updated
|
||||
/// </summary>
|
||||
public static ServerMessage Push(string type, object? payload = null) =>
|
||||
new(type, 0, payload);
|
||||
|
||||
/// <summary>
|
||||
/// Creates a structured error response.
|
||||
/// Sets Type = "error", Ref = refSeq, Payload = { errorCode, message }.
|
||||
///
|
||||
/// Use when:
|
||||
/// - A client request failed for an expected reason (validation, not found, banned)
|
||||
/// - The client needs a machine-readable errorCode to display the right UI state
|
||||
/// </summary>
|
||||
public static ServerMessage Error(int refSeq, string errorCode, string message) =>
|
||||
new("error", refSeq, new { errorCode, message });
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
namespace SOR.Shared.Redis;
|
||||
|
||||
/// <summary>
|
||||
/// All Redis key name patterns used across the entire server, in one place.
|
||||
///
|
||||
/// Why centralize here?
|
||||
/// - Prevents typos (a mistyped key silently produces cache misses or data loss)
|
||||
/// - Prevents key collisions between services
|
||||
/// - Makes the full set of Redis keys auditable at a glance
|
||||
/// - A rename touches one file, not a scattered grep
|
||||
///
|
||||
/// Naming convention: "{scope}:{identifier}"
|
||||
/// All keys are lowercase, colon-separated.
|
||||
///
|
||||
/// 'static class' means this class cannot be instantiated — it only contains static members.
|
||||
/// </summary>
|
||||
public static class RedisKeys
|
||||
{
|
||||
// ── Auth / Sessions ────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Opaque session token → serialized session data (userId, displayName, createdAt).
|
||||
/// TTL set to Auth:SessionTtlMinutes on creation; refreshed on each valid request.
|
||||
/// Example: "session:a1b2c3d4e5f6..."
|
||||
/// </summary>
|
||||
public static string Session(string token) => $"session:{token}";
|
||||
|
||||
/// <summary>
|
||||
/// Set of all active session tokens for a user.
|
||||
/// Used to enumerate and revoke all sessions when a user is banned or changes password.
|
||||
/// Example: "user_sessions:550e8400-e29b-41d4-a716-446655440000"
|
||||
/// </summary>
|
||||
public static string UserSessions(string userId) => $"user_sessions:{userId}";
|
||||
|
||||
// ── Gateway / Push Delivery ────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Redis Pub/Sub channel for pushing messages to a specific user's connected client.
|
||||
/// The Gateway subscribes to this channel for each authenticated connection.
|
||||
/// Other services publish to it via IClientPush.PushAsync().
|
||||
/// Example: "push:550e8400-e29b-41d4-a716-446655440000"
|
||||
/// </summary>
|
||||
public static string ClientPushChannel(string userId) => $"push:{userId}";
|
||||
|
||||
// ── Live Game State ────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Serialized active game state. Stored in Redis for fast reads; Game service
|
||||
/// is the only writer. Keyed by game ID (a GUID assigned at game creation).
|
||||
/// Example: "game:active:7c9e6679-7425-40de-944b-e07fc1f90ae7"
|
||||
/// </summary>
|
||||
public static string ActiveGame(string gameId) => $"game:active:{gameId}";
|
||||
|
||||
// ── Leaderboard ───────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Redis Sorted Set for the ranked leaderboard.
|
||||
/// Members: userId strings. Score: current MMR (Matchmaking Rating).
|
||||
/// ZADD / ZINCRBY / ZRANK operations run in O(log N) time.
|
||||
/// </summary>
|
||||
public static string LeaderboardRanked() => "leaderboard:ranked";
|
||||
|
||||
// ── Feature Flags ─────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Runtime feature flag value. "1" = enabled, "0" = disabled.
|
||||
/// Set by Admin service; read by any service via Redis GET.
|
||||
/// Example: "config:flag:ranked_queue_open"
|
||||
/// </summary>
|
||||
public static string FeatureFlag(string flag) => $"config:flag:{flag}";
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<AssemblyName>SOR.Shared</AssemblyName>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- DI abstractions: provides IServiceCollection used in ServiceRegistration.cs.
|
||||
Class library projects (Sdk="Microsoft.NET.Sdk") must reference this explicitly;
|
||||
Web SDK projects get it transitively from the ASP.NET Core framework reference. -->
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" />
|
||||
|
||||
<!-- SOR.Shared provides concrete implementations of Abstractions interfaces
|
||||
(ServerMessage, RawClientMessage, SystemTextJsonSerializer) so it
|
||||
must reference Abstractions. -->
|
||||
<ProjectReference Include="..\SOR.Networking.Abstractions\SOR.Networking.Abstractions.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<!-- System.Text.Json is included in the .NET 8 BCL — no package reference needed. -->
|
||||
<!-- StackExchange.Redis is NOT referenced here: RedisKeys only holds string constants. -->
|
||||
</Project>
|
||||
@@ -0,0 +1,114 @@
|
||||
namespace SOR.Shared.Serialization;
|
||||
|
||||
using System.Text.Json;
|
||||
using SOR.Networking.Abstractions.Messaging;
|
||||
using SOR.Shared.Networking;
|
||||
|
||||
/// <summary>
|
||||
/// IMessageSerializer implementation using System.Text.Json.
|
||||
///
|
||||
/// Wire format — Client to Server:
|
||||
/// { "type": "chat.send", "seq": 7, "payload": { "message": "Hello" } }
|
||||
///
|
||||
/// Wire format — Server to Client (reply, ref = client seq):
|
||||
/// { "type": "chat.send.ack", "ref": 7, "payload": { "messageId": "..." } }
|
||||
///
|
||||
/// Wire format — Server to Client (unsolicited push, ref = 0):
|
||||
/// { "type": "game.state_update", "ref": 0, "payload": { ... } }
|
||||
///
|
||||
/// To swap to MessagePack:
|
||||
/// 1. Create MessagePackSerializer implementing IMessageSerializer
|
||||
/// 2. In SOR.Shared.ServiceRegistration: replace AddSingleton{IMessageSerializer, SystemTextJsonSerializer}
|
||||
/// with AddSingleton{IMessageSerializer, MessagePackSerializer}
|
||||
/// 3. Update client to send/receive MessagePack frames instead of JSON
|
||||
/// 4. Nothing else changes — all handlers, all services, all tests are unaffected
|
||||
///
|
||||
/// Lifetime: Singleton. This class is thread-safe (no mutable state; JsonSerializerOptions
|
||||
/// is immutable after construction).
|
||||
/// </summary>
|
||||
public sealed class SystemTextJsonSerializer : IMessageSerializer
|
||||
{
|
||||
/// <summary>
|
||||
/// Shared options instance. Created once; reuse avoids repeated allocation.
|
||||
/// 'static readonly' = initialized once at class load time, shared across all instances.
|
||||
/// </summary>
|
||||
private static readonly JsonSerializerOptions Options = new()
|
||||
{
|
||||
// camelCase property names: C# 'SessionToken' → JSON 'sessionToken'
|
||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
||||
|
||||
// Case-insensitive property matching for deserialization:
|
||||
// JSON "SessionToken" and "sessionToken" both map to C# 'SessionToken'
|
||||
PropertyNameCaseInsensitive = true,
|
||||
|
||||
// Compact output — no indentation in production
|
||||
WriteIndented = false,
|
||||
};
|
||||
|
||||
/// <inheritdoc/>
|
||||
/// <remarks>
|
||||
/// Parses the JSON envelope and extracts the type, seq, and inner payload.
|
||||
/// The 'payload' JSON object is re-serialized to bytes so downstream code
|
||||
/// can deserialize it independently into the handler-specific type.
|
||||
/// </remarks>
|
||||
public IClientMessage Deserialize(ReadOnlySpan<byte> wireBytes)
|
||||
{
|
||||
// JsonDocument provides a DOM view of JSON bytes without full deserialization.
|
||||
// It is more efficient than JsonSerializer.Deserialize when we only need
|
||||
// a few fields and want to defer inner payload deserialization.
|
||||
// JsonDocument.Parse does not have a ReadOnlySpan{byte} overload in .NET 8.
|
||||
// .ToArray() copies the span into a byte[] — minimal overhead for the parse path.
|
||||
using var doc = JsonDocument.Parse(wireBytes.ToArray());
|
||||
var root = doc.RootElement;
|
||||
|
||||
// Extract envelope fields. GetString() returns null if the property is missing
|
||||
// or not a string — the ?? throw gives a clear error instead of a null ref later.
|
||||
var type = root.GetProperty("type").GetString()
|
||||
?? throw new JsonException("Client message missing required 'type' field.");
|
||||
|
||||
// TryGetProperty returns false (not an exception) if the field is absent.
|
||||
// Seq defaults to 0 if not provided — older clients or fire-and-forget messages.
|
||||
var seq = root.TryGetProperty("seq", out var seqEl) ? seqEl.GetInt32() : 0;
|
||||
|
||||
// Re-serialize the payload sub-object to bytes for handler deserialization.
|
||||
// If no payload field exists, use empty bytes (handler will receive default(T)).
|
||||
ReadOnlyMemory<byte> payloadBytes = ReadOnlyMemory<byte>.Empty;
|
||||
if (root.TryGetProperty("payload", out var payloadEl))
|
||||
{
|
||||
// SerializeToUtf8Bytes allocates a new byte[] — this is fine since it
|
||||
// happens once per message and the bytes are owned by RawClientMessage.
|
||||
payloadBytes = JsonSerializer.SerializeToUtf8Bytes(payloadEl, Options);
|
||||
}
|
||||
|
||||
return new RawClientMessage(type, seq, payloadBytes);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
/// <remarks>
|
||||
/// Serializes the full message envelope (type + ref + payload) to JSON bytes.
|
||||
/// </remarks>
|
||||
public ReadOnlyMemory<byte> Serialize(IServerMessage message)
|
||||
{
|
||||
// Anonymous type: a lightweight C# feature that creates a temporary class
|
||||
// with named properties without explicitly defining a class.
|
||||
// The '@' prefix on 'ref' is needed because 'ref' is a C# keyword.
|
||||
var envelope = new
|
||||
{
|
||||
type = message.Type,
|
||||
@ref = message.Ref,
|
||||
payload = message.Payload,
|
||||
};
|
||||
|
||||
return JsonSerializer.SerializeToUtf8Bytes(envelope, Options);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public T DeserializePayload<T>(ReadOnlyMemory<byte> payload) where T : notnull
|
||||
{
|
||||
// Span<byte> is a stack-allocated view of the memory — no copy.
|
||||
return JsonSerializer.Deserialize<T>(payload.Span, Options)
|
||||
?? throw new JsonException(
|
||||
$"Payload deserialized to null for type {typeof(T).Name}. " +
|
||||
"Ensure the payload JSON is not 'null'.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
namespace SOR.Shared;
|
||||
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using SOR.Networking.Abstractions.Messaging;
|
||||
using SOR.Shared.Serialization;
|
||||
|
||||
/// <summary>
|
||||
/// Registers SOR.Shared services into the DI container.
|
||||
/// Called once in SOR.Host.Program.cs before any other service registration.
|
||||
/// </summary>
|
||||
public static class ServiceRegistration
|
||||
{
|
||||
/// <summary>
|
||||
/// Registers all shared infrastructure services:
|
||||
/// - IMessageSerializer (SystemTextJsonSerializer by default)
|
||||
///
|
||||
/// To swap the serializer to MessagePack, replace this registration in Program.cs:
|
||||
/// builder.Services.AddSingleton{IMessageSerializer, MessagePackSerializer}()
|
||||
/// after calling AddSharedServices(), which will override the default.
|
||||
/// </summary>
|
||||
public static IServiceCollection AddSharedServices(this IServiceCollection services)
|
||||
{
|
||||
// Singleton: one serializer instance for the process lifetime.
|
||||
// SystemTextJsonSerializer has no mutable state — safe to share across threads.
|
||||
services.AddSingleton<IMessageSerializer, SystemTextJsonSerializer>();
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user