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; /// /// 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() /// public static class ServiceRegistration { /// /// 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) /// 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( 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(); // Register ITransport → resolve WebSocketTransport from the container. // This means: anywhere ITransport is injected, the container provides // the already-registered WebSocketTransport singleton. services.AddSingleton( sp => sp.GetRequiredService()); // 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; } /// /// 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. /// 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>().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(); // 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; } }