Files
sor/Server/src/SOR.Networking.WebSocket/ServiceRegistration.cs
T
d21adbc8d0 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>
2026-02-24 21:01:38 -05:00

123 lines
5.7 KiB
C#

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;
}
}