Path: redb-route/redb.Route.WebSocket/WsComponent.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.WebSocket/WsComponent.cs
----
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Extensions;
using redb.Route.Core;
using redb.Route.Http;
namespace redb.Route.WebSocket;
///
/// WebSocket component. Scheme: "ws" (plain) or "wss" (TLS).
/// Producer: ClientWebSocket — connects to remote WebSocket server and sends frames.
/// Consumer: Kestrel-based WebSocket server — accepts connections and receives frames.
/// URI format: ws:host:port/path?messageType=Text&subProtocol=graphql-ws
///
public class WsComponent : ComponentBase
{
private readonly string _scheme;
private SharedHttpServerManager? _ownedServerManager;
///
/// Creates the ws component. A parameterless constructor of its own: the assembly scan
/// (context.AddComponents, the Tsak worker's module contexts) creates components through it and skips a type
/// whose only constructor has optional parameters.
///
public WsComponent() : this("ws")
{
}
/// Creates a WebSocket component with the given scheme.
public WsComponent(string scheme)
{
_scheme = scheme;
}
///
public override string Scheme => _scheme;
///
/// Shared Kestrel host. Set by AddRedbRouteWebSocket() so ws endpoints multiplex onto
/// the same listener as HTTP, gRPC, SOAP and AS2 (and inherit its trusted-proxy, CORS and TLS
/// handling). When the component is constructed by hand — tests, embedded scenarios — it owns
/// a private manager instead of failing, which keeps `new WsComponent()` usable on its own.
///
public SharedHttpServerManager? ServerManager { get; set; }
///
/// The manager actually used. Resolution order: explicitly assigned → the context's DI singleton
/// → a private instance. The DI step matters for module hosts that add the component by scanning
/// rather than through the extension method, so nothing ever assigns
/// while the one shared manager sits in the container (gRPC and AS2 resolve the same way).
///
internal SharedHttpServerManager EffectiveServerManager =>
ServerManager
?? Context.Resolve()
?? (_ownedServerManager ??= new SharedHttpServerManager());
///
/// Authenticates a handshake before the socket is upgraded. Supplied by the host through
/// AddRedbRouteWebSocket(o => o.Authenticate = ...); null means every connection is
/// accepted, which is the historical behaviour. The principal is put on every exchange the socket
/// produces (ExchangePrincipal); build its identity with an authentication type, because code
/// that reads it treats an identity that is not authenticated as anonymous.
///
public Func>? Authenticate { get; set; }
// Running consumers, so a server-mode producer can push into the clients of the consumer
// serving the same address. The key is host:port plus path, NOT the endpoint's normalized key:
// that one carries the sorted query parameters, and a producer always differs from its
// consumer by at least mode=Server.
private readonly System.Collections.Concurrent.ConcurrentDictionary _consumers =
new(StringComparer.OrdinalIgnoreCase);
internal static string ConsumerKey(string host, int port, string path) => $"{host}:{port}{path}";
internal void RegisterConsumer(WsConsumer consumer) =>
_consumers[ConsumerKey(consumer.EndpointOptions.Host, consumer.EndpointOptions.Port, consumer.ConsumerPath)] = consumer;
internal void UnregisterConsumer(WsConsumer consumer) =>
_consumers.TryRemove(ConsumerKey(consumer.EndpointOptions.Host, consumer.EndpointOptions.Port, consumer.ConsumerPath), out _);
internal WsConsumer? GetConsumer(string host, int port, string path) =>
_consumers.GetValueOrDefault(ConsumerKey(host, port, path));
///
public override async ValueTask DisposeAsync()
{
if (_ownedServerManager is not null)
{
await _ownedServerManager.DisposeAsync().ConfigureAwait(false);
_ownedServerManager = null;
}
await base.DisposeAsync().ConfigureAwait(false);
}
///
public override IEndpoint CreateEndpoint(EndpointUri uri)
{
ArgumentNullException.ThrowIfNull(uri);
var options = new WsEndpointOptions();
ParseHostPort(uri.Path, options);
options.BindFromUri(uri.RawParameters);
// Named ConnectionFactory keeps the TLS certificate password out of the route URI.
// Applied before the wss override so the scheme still wins on TLS.
if (!string.IsNullOrEmpty(options.ConnectionFactory))
{
// A set-but-unknown name fails loud -- never a silent fallback to URI params.
var factory = Context.GetRequiredFromRegistry(options.ConnectionFactory);
factory.ApplyTo(options, uri);
}
// wss implies SSL
if (_scheme == "wss")
options.Ssl = true;
options.Validate();
return new WsEndpoint(uri, this, options);
}
///
/// Parses "host:port/path" from the URI path segment.
/// Path format: "/host:port/route" or "host:port" or "/host:port".
///
internal static void ParseHostPort(string path, WsEndpointOptions options)
{
var clean = path.TrimStart('/');
// Find host:port — stop at the first slash after host:port
var slashIdx = clean.IndexOf('/');
var hostPort = slashIdx >= 0 ? clean[..slashIdx] : clean;
var colonIdx = hostPort.LastIndexOf(':');
if (colonIdx > 0 && int.TryParse(hostPort[(colonIdx + 1)..], out var port))
{
options.Host = hostPort[..colonIdx];
options.Port = port;
}
else
{
options.Host = hostPort;
}
}
///
/// Extracts the path portion after host:port (for consumer route matching).
/// "/0.0.0.0:9000/chat" → "/chat"
/// "/0.0.0.0:9000" → "/"
///
internal static string ExtractPath(string uriPath)
{
var clean = uriPath.TrimStart('/');
var slashIdx = clean.IndexOf('/');
return slashIdx >= 0 ? clean[slashIdx..] : "/";
}
}
///
/// WSS (WebSocket Secure) component. Uses the "wss" scheme and enables TLS.
///
public class WssComponent : WsComponent
{
/// Creates a WSS component.
public WssComponent() : base("wss") { }
}
///
/// WebSocket endpoint. Creates either a producer (ClientWebSocket) or consumer (Kestrel WS server).
///
public class WsEndpoint : EndpointBase
{
/// Creates a WebSocket endpoint.
public WsEndpoint(EndpointUri uri, WsComponent component, WsEndpointOptions options)
: base(uri, component, options)
{
}
/// The consumer route path (after host:port).
public string ConsumerPath => WsComponent.ExtractPath(Uri.Path);
/// The shared host this endpoint serves on.
internal SharedHttpServerManager ServerManager => ((WsComponent)Component).EffectiveServerManager;
///
/// Declares WebSocket support on the listener BEFORE any consumer starts it. The route context
/// starts every endpoint before it starts consumers, and only the consumer calls EnsureStarted,
/// so by the time the listener is built the middleware is guaranteed to be requested.
///
public override Task Start(CancellationToken ct = default)
{
ServerManager.EnableWebSockets(Options.Host, Options.Port,
Options.KeepAliveInterval > 0
? TimeSpan.FromMilliseconds(Options.KeepAliveInterval)
: null,
Options.Ssl, Options.SslCertPath, Options.SslCertPassword);
return Task.CompletedTask;
}
/// The endpoint options for external access.
internal WsEndpointOptions EndpointOptions => Options;
///
/// Builds the full WebSocket URL for the producer client.
/// "ws:echo.example.com:8080/feed" → "ws://echo.example.com:8080/feed"
///
public string BuildProducerUrl()
{
var scheme = Options.Ssl ? "wss" : "ws";
var path = Uri.Path.TrimStart('/');
return $"{scheme}://{path}";
}
///
public override IProducer CreateProducer()
{
return new WsProducer(this, Options);
}
///
public override IConsumer CreateConsumer(IProcessor processor)
{
ArgumentNullException.ThrowIfNull(processor);
return new WsConsumer(this, processor, Options);
}
}