Bundle: redb-route / redb.Route.WebSocket (redb.Route.WebSocket.txt), 11 files
Snapshot: 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
Index: https://redbase.app/src/dev-2026-12-06/redb-route/_index.txt
====
Path: redb-route/redb.Route.WebSocket/Extensions/ServiceCollectionExtensions.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/Extensions/ServiceCollectionExtensions.cs
----
using System.Security.Claims;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using redb.Route.Extensions;
using redb.Route.Http;
namespace redb.Route.WebSocket;
///
/// Extension methods for registering the WebSocket component with dependency injection.
///
public static class ServiceCollectionExtensions
{
///
/// Registers the WS and WSS components with the route context.
///
public static IServiceCollection AddRedbRouteWebSocket(this IServiceCollection services)
=> AddRedbRouteWebSocket(services, null);
///
/// Registers the WS and WSS components and lets the host authenticate incoming connections.
///
/// services.AddRedbRouteWebSocket(o =>
/// o.Authenticate = async ctx => await myJwtValidator.ValidateAsync(
/// ctx.Request.Query["access_token"]));
///
///
public static IServiceCollection AddRedbRouteWebSocket(
this IServiceCollection services,
Action? configure)
{
var registration = new WsRegistrationOptions();
configure?.Invoke(registration);
// ws endpoints multiplex onto the same Kestrel as HTTP/gRPC/SOAP/AS2 (idempotent call).
services.AddRedbRouteHttpHosting();
services.AddSingleton();
services.AddSingleton();
// IRouteContextConfigurator is applied by RouteHostedService at startup --
// the correct registration hook (a lazy marker singleton never fires).
services.AddRouteContextConfigurator((sp, context) =>
{
var serverManager = sp.GetRequiredService();
var ws = sp.GetRequiredService();
ws.ServerManager = serverManager;
ws.Authenticate = registration.Authenticate;
context.AddComponent(ws);
var wss = sp.GetRequiredService();
wss.ServerManager = serverManager;
wss.Authenticate = registration.Authenticate;
context.AddComponent(wss);
});
return services;
}
}
///
/// Host-supplied configuration for WebSocket consumers. The route host is a generic host, not an
/// ASP.NET application, so authentication arrives as a delegate the host writes rather than
/// through an authentication stack the connector would have to depend on.
///
public sealed class WsRegistrationOptions
{
///
/// Authenticates a WebSocket handshake. Returns the principal to attach to the request (its
/// NameIdentifier claim reaches the route as the redbWs.UserId header), or null
/// to reject the upgrade with 401.
///
/// Browsers cannot set headers on a WebSocket handshake, so a token normally arrives in the
/// access_token query parameter: read it from there and from the Authorization header.
///
///
/// The principal is also put on every exchange the socket produces (ExchangePrincipal). Build its
/// identity with an authentication type (new ClaimsIdentity(claims, "Bearer")): code that reads
/// the principal treats an identity that is not authenticated as anonymous.
///
///
public Func>? Authenticate { get; set; }
}
Path: redb-route/redb.Route.WebSocket/Fluent/Ws.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/Fluent/Ws.cs
----
using System.Text;
namespace redb.Route.WebSocket;
///
/// Fluent entry point for WebSocket endpoints.
///
/// // Consumer — listen for WS connections:
/// .From(Ws.Listen("0.0.0.0:8080/chat").SubProtocol("json").InOut())
///
/// // Producer — connect to remote WS:
/// .To(Ws.Connect("api.example.com:443/stream").Ssl().Binary())
///
/// // Secure WebSocket (wss):
/// .To(Ws.Connect("api.example.com/stream").Ssl())
///
///
public static class Ws
{
/// Listen for WebSocket connections (consumer).
/// Bind address, e.g. 0.0.0.0:8080/chat.
public static WsBuilder Listen(string hostPortPath) => new(hostPortPath);
/// Connect to a remote WebSocket (producer).
/// Target address, e.g. api.example.com:443/stream.
public static WsBuilder Connect(string hostPortPath) => new(hostPortPath);
///
/// Push into the clients of the local consumer serving this address, so a route can send
/// unsolicited frames (quotes, notifications, progress) instead of only answering incoming
/// ones. Set the redbWs.TargetConnection header to reach one client instead of all.
///
/// The address of the running consumer, e.g. 0.0.0.0:8080/stream.
public static WsBuilder Broadcast(string hostPortPath) => new WsBuilder(hostPortPath).ServerMode();
}
/// Fluent builder for WebSocket endpoint URIs. Scheme: ws (or wss with SSL).
public sealed class WsBuilder
{
private readonly string _hostPortPath;
// Framing
private string? _messageType;
private string? _encoding;
private string? _subProtocol;
// Socket
private int? _receiveBufferSize;
private int? _sendBufferSize;
private int? _keepAliveInterval;
// Producer
private int? _connectTimeout;
private bool _reconnect;
private int? _reconnectInterval;
private int? _maxReconnectAttempts;
private int? _reconnectTimeout;
private string? _mode;
// Consumer
private int? _maxConnections;
private bool? _inOut;
// TLS
private bool _ssl;
private string? _sslCertPath;
private string? _sslCertPassword;
private bool _trustAllCertificates;
internal WsBuilder(string hostPortPath)
{
ArgumentException.ThrowIfNullOrWhiteSpace(hostPortPath);
_hostPortPath = hostPortPath;
}
// ── Framing ─────────────────────────────────────────────────────
/// Send/receive binary messages instead of text.
public WsBuilder Binary() { _messageType = "Binary"; return this; }
/// Character encoding. Default utf-8.
public WsBuilder Encoding(string encoding) { _encoding = encoding; return this; }
/// WebSocket sub-protocol (e.g. graphql-ws, json).
public WsBuilder SubProtocol(string protocol) { _subProtocol = protocol; return this; }
// ── Socket ──────────────────────────────────────────────────────
/// Receive buffer size in bytes.
public WsBuilder ReceiveBufferSize(int size) { _receiveBufferSize = size; return this; }
/// Send buffer size in bytes.
public WsBuilder SendBufferSize(int size) { _sendBufferSize = size; return this; }
/// Keep-alive interval in ms. Default 30000.
public WsBuilder KeepAliveInterval(int ms) { _keepAliveInterval = ms; return this; }
// ── Producer ────────────────────────────────────────────────────
/// Connection timeout in ms.
public WsBuilder ConnectTimeout(int ms) { _connectTimeout = ms; return this; }
/// Enable auto-reconnect.
public WsBuilder Reconnect(int intervalMs = 5000, int maxAttempts = 0) { _reconnect = true; _reconnectInterval = intervalMs; _maxReconnectAttempts = maxAttempts; return this; }
///
/// Overall time budget for reconnecting, in ms. Without it (and without a max attempt count)
/// a send against a server that stays down never returns, so dead-letter never fires.
///
public WsBuilder ReconnectTimeout(int ms) { _reconnectTimeout = ms; return this; }
/// Push into the clients of the local consumer instead of connecting out.
public WsBuilder ServerMode() { _mode = "Server"; return this; }
// ── Consumer ────────────────────────────────────────────────────
/// Max concurrent connections. 0 = unlimited.
public WsBuilder MaxConnections(int max) { _maxConnections = max; return this; }
/// Enable request-response pattern.
public WsBuilder InOut(bool value = true) { _inOut = value; return this; }
// ── TLS ─────────────────────────────────────────────────────────
/// Enable SSL/TLS (wss).
public WsBuilder Ssl() { _ssl = true; return this; }
/// Path to SSL certificate.
public WsBuilder SslCertPath(string path) { _sslCertPath = path; return this; }
/// SSL certificate password.
public WsBuilder SslCertPassword(string password) { _sslCertPassword = password; return this; }
///
/// Producer: accept any server certificate, including a self-signed one. Explicit on purpose --
/// turning certificate validation off should never be a side effect of another option.
///
public WsBuilder TrustAllCertificates() { _trustAllCertificates = true; return this; }
// ── Build ───────────────────────────────────────────────────────
public string Build()
{
var scheme = _ssl ? "wss" : "ws";
var sb = new StringBuilder();
sb.Append(scheme);
sb.Append(':');
sb.Append(_hostPortPath);
var sep = '?';
void Append(string key, string v) { sb.Append(sep); sb.Append(key); sb.Append('='); sb.Append(Uri.EscapeDataString(v)); sep = '&'; }
void AppendInt(string key, int? v) { if (v.HasValue) Append(key, v.Value.ToString()); }
void AppendBool(string key, bool v) { if (v) Append(key, "true"); }
void AppendBoolN(string key, bool? v) { if (v.HasValue) Append(key, v.Value.ToString().ToLowerInvariant()); }
void AppendStr(string key, string? v) { if (v != null) Append(key, v); }
AppendStr("messageType", _messageType);
AppendStr("encoding", _encoding);
AppendStr("subProtocol", _subProtocol);
AppendInt("receiveBufferSize", _receiveBufferSize);
AppendInt("sendBufferSize", _sendBufferSize);
AppendInt("keepAliveInterval", _keepAliveInterval);
AppendInt("connectTimeout", _connectTimeout);
AppendBool("reconnect", _reconnect);
AppendInt("reconnectInterval", _reconnectInterval);
AppendInt("maxReconnectAttempts", _maxReconnectAttempts);
AppendInt("reconnectTimeout", _reconnectTimeout);
AppendStr("mode", _mode);
AppendInt("maxConnections", _maxConnections);
AppendBoolN("inOut", _inOut);
AppendBool("ssl", _ssl);
AppendStr("sslCertPath", _sslCertPath);
AppendStr("sslCertPassword", _sslCertPassword);
AppendBool("trustAllCertificates", _trustAllCertificates);
return sb.ToString();
}
public static implicit operator string(WsBuilder b) => b.Build();
public override string ToString() => Build();
}
Path: redb-route/redb.Route.WebSocket/README.md
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/README.md
----
# redb.Route.WebSocket
> Documentation and articles:
WebSocket transport for redb.Route. ClientWebSocket producer and Kestrel-based WebSocket server consumer with text/binary frames, ping/pong, reconnect, and subprotocol support.
[](https://www.nuget.org/packages/redb.Route.WebSocket)
[](../../LICENSE)
## Installation
```bash
dotnet add package redb.Route.WebSocket
```
## Usage
### Fluent DSL
```csharp
using redb.Route.WebSocket;
// WebSocket server (consumer)
From(Ws.Listen("0.0.0.0:8080/ws")
.MaxConnections(500)
.InOut())
.Process(async (e, ct) =>
{
var msg = (string)e.In.Body!;
e.In.Body = $"Echo: {msg}";
});
// WebSocket client (producer)
From("direct://push")
.To(Ws.Connect("wss://stream.example.com/feed")
.SubProtocol("json")
.ConnectTimeout(5000)
.Reconnect(intervalMs: 3000, maxAttempts: 10));
// Binary mode
From(Ws.Listen("0.0.0.0:8080/binary")
.Binary()
.ReceiveBufferSize(65536))
.To("direct://binary-handler");
// TLS
From(Ws.Listen("0.0.0.0:8443/secure")
.Ssl()
.SslCertPath("/certs/server.pfx")
.SslCertPassword("password"))
.To("direct://secure-handler");
```
## Fluent Builder API
| Category | Methods |
|----------|---------|
| **Server** | `Ws.Listen(hostPortPath)`, `.MaxConnections()`, `.InOut()` |
| **Client** | `Ws.Connect(hostPortPath)`, `.ConnectTimeout()`, `.Reconnect(interval, max)` |
| **Framing** | `.Binary()`, `.Encoding()`, `.SubProtocol()` |
| **Socket** | `.ReceiveBufferSize()`, `.SendBufferSize()`, `.KeepAliveInterval()` |
| **TLS** | `.Ssl()`, `.SslCertPath()`, `.SslCertPassword()`, `.TrustAllCertificates()` |
## One port for REST and WebSocket
The consumer serves on the **shared Kestrel host** (`redb.Route.Http.Hosting`), the same listener
HTTP, gRPC, SOAP and AS2 routes use, so the typical production layout works:
```csharp
From("http://0.0.0.0:8080/api/orders") // REST
From("ws://0.0.0.0:8080/stream") // live updates, same port, same proxy
```
## Pushing to connected clients
A route can send frames to its own clients instead of only answering them
(`mode=Server` / `Ws.Broadcast`):
```csharp
// broadcast to everyone on /stream
From("timer://ticks?period=1000")
.To(Ws.Broadcast("0.0.0.0:8080/stream"));
// answer one client later, by the id the incoming exchange carried
From(Ws.Listen("0.0.0.0:8080/stream"))
.To("direct://slow-work");
From("direct://slow-work-done")
.SetHeader(WsHeaders.TargetConnection, Expr("${header.redbWs.ConnectionId}"))
.To(Ws.Broadcast("0.0.0.0:8080/stream"));
```
The consumer serving that address has to be running; a server-mode producer that finds none
refuses to start rather than pushing into nothing.
## Authenticating the handshake
The route host is a generic host, not an ASP.NET application, so the host supplies a delegate:
```csharp
services.AddRedbRouteWebSocket(o => o.Authenticate = async ctx =>
await myJwtValidator.ValidateAsync(ctx.Request.Query["access_token"]));
```
Null rejects the upgrade with 401. The principal's `NameIdentifier` reaches the route as the
`redbWs.UserId` header, and the principal itself is on every exchange the socket produces
(`ExchangePrincipal.Get(exchange)`). Build the identity with an authentication type
(`new ClaimsIdentity(claims, "Bearer")`): code that reads the principal treats an identity that is not
authenticated as anonymous.
Without this delegate, a caller identified by the shared host
(`AddRedbRouteHttpHosting(o => o.ResolvePrincipal = ...)`) is used in the same way, but an anonymous
handshake is not rejected. When the delegate is set, it takes precedence.
## Schemes
Both `ws` and `wss` schemes are supported for plain and TLS connections. `wss://` on a consumer
**requires** `sslCertPath`: without it the listener would be a plain socket while the log said
`wss://`, so it refuses to start. On a producer, reaching a server with a self-signed certificate
(staging) needs an explicit `trustAllCertificates=true`.
## Behaviour worth knowing
- **`maxConnections` queues, it does not refuse.** A client arriving over the limit waits for a
slot instead of being rejected, and gives up when it disconnects.
- **`inOut` has no correlation id.** WebSocket is duplex, so the first frame that arrives after a
send is taken as its answer; an unrelated server push landing at that moment would be taken
instead. The send lock is held while waiting, which also serialises senders.
- **`reconnect=true` retries forever by default** (`maxReconnectAttempts=0`). Against a server
that stays down that means an exchange never returns and dead-letter never fires — set
`reconnectTimeout` (ms) to cap the attempts by time and let the send fail.
## Part of
[redb.Route](../README.md) — ESB & EIP Framework for .NET
## Named connection factory
Keep credentials out of the route URI: register a factory in the context registry and
reference it by name. A set-but-unknown name fails loud at startup — a typo can never
silently fall back to inline URI parameters.
```csharp
context.AddToRegistry("prod", new WsConnectionFactory
{
Ssl = true,
SslCertPath = "/secrets/client.pfx",
});
// wss://feed.internal/ticks?connectionFactory=prod
```
## Tracing
On the `redb.Route` activity source (`AddSource("redb.Route")`), with `messaging.system` = `websocket` and
`redb.route.endpoint`:
- **Consumer.** One `Consumer` span, `ws {path} receive`, per routed message, the InOut reply included. A frame carries
no headers, so the span is a root; when the client sent `traceparent` with its upgrade request, every span of that
connection links that context. The connection itself, which may live for hours, is never the parent, and a
connection that sends nothing opens no span. A failed route marks the span an error; our own stop does not.
- **Producer.** One `Producer` span per send, `ws send {mode}`; an error when the send fails, unless our own token
cancelled it. No trace context is written to the frame.
- `RouteEngineOptions.EnableTelemetry = false` opens neither span.
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);
}
}
Path: redb-route/redb.Route.WebSocket/WsConnectionFactory.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/WsConnectionFactory.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
namespace redb.Route.WebSocket;
///
/// Named connection factory for WebSocket. Register it in the route registry and reference it by
/// name from the endpoint URI (connectionFactory=my-ws) so the TLS certificate password
/// never has to appear in the URI, and therefore can never reach logs, telemetry, or the dashboard.
///
/// The listen/target address stays in the endpoint path — a factory carries TLS material and
/// timeouts only and can never silently redirect a route. Note the wss scheme still forces
/// TLS on regardless of what the factory says.
///
///
public sealed class WsConnectionFactory
{
/// Serve/connect over TLS.
public bool Ssl { get; set; }
/// Path to the PFX certificate.
public string? SslCertPath { get; set; }
/// Password for the PFX certificate.
[Sensitive]
public string? SslCertPassword { get; set; }
/// Connect timeout in milliseconds.
public int ConnectTimeout { get; set; } = 10_000;
///
/// Copies this factory's TLS and timeout settings onto the endpoint options, but only for
/// parameters the endpoint URI did not set explicitly — an inline URI value always wins.
///
internal void ApplyTo(WsEndpointOptions options, EndpointUri uri)
{
var supplied = uri.RawParameters;
if (!supplied.ContainsKey(nameof(options.Ssl))) options.Ssl = Ssl;
if (!supplied.ContainsKey(nameof(options.SslCertPath))) options.SslCertPath = SslCertPath;
if (!supplied.ContainsKey(nameof(options.SslCertPassword)))
options.SslCertPassword = SslCertPassword;
if (!supplied.ContainsKey(nameof(options.ConnectTimeout)))
options.ConnectTimeout = ConnectTimeout;
}
}
Path: redb-route/redb.Route.WebSocket/WsConsumer.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/WsConsumer.cs
----
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Net;
using System.Net.WebSockets;
using System.Text;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Http;
using redb.Route.Telemetry;
namespace redb.Route.WebSocket;
///
/// WebSocket consumer. Embedded Kestrel-based WebSocket server that accepts connections,
/// receives message frames, and dispatches them into the route processor pipeline.
/// Supports text and binary frames, subprotocol negotiation, MaxConnections throttling,
/// and InOut exchange pattern for sending response frames back.
///
public sealed class WsConsumer : IConsumer
{
private readonly WsEndpoint _endpoint;
public IEndpoint Endpoint => _endpoint;
private readonly IProcessor _processor;
private readonly WsEndpointOptions _options;
private readonly Encoding _encoding;
private SharedHttpServerManager? _serverManager;
private RouteRegistration? _registration;
private long _processedCount;
private readonly ConcurrentDictionary _clients = new();
private readonly SemaphoreSlim? _connectionSemaphore;
private CancellationTokenSource? _cts;
private readonly InflightDrainGuard _drain = new();
private ILogger? _logger;
/// Creates a WebSocket consumer.
public WsConsumer(WsEndpoint endpoint, IProcessor processor, WsEndpointOptions options)
{
_endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint));
_processor = processor ?? throw new ArgumentNullException(nameof(processor));
_options = options ?? throw new ArgumentNullException(nameof(options));
_encoding = Encoding.GetEncoding(options.Encoding);
_logger = (endpoint.Component as ComponentBase)?.Logger;
if (options.MaxConnections > 0)
_connectionSemaphore = new SemaphoreSlim(options.MaxConnections, options.MaxConnections);
}
/// Number of messages successfully processed.
public long ProcessedCount => Interlocked.Read(ref _processedCount);
/// Number of currently connected WebSocket clients.
public int ActiveConnections => _clients.Count;
/// Ids of the currently connected clients, addressable by a server-mode producer.
public IReadOnlyCollection ConnectionIds => _clients.Keys.ToArray();
/// The endpoint options, for the component's consumer registry.
internal WsEndpointOptions EndpointOptions => _options;
/// The path this consumer serves, for the component's consumer registry.
internal string ConsumerPath => _endpoint.ConsumerPath;
///
/// Pushes a frame into connected clients: one of them when is
/// given, all of them otherwise. Returns how many sockets it reached.
///
internal async Task SendToClients(byte[] data, WebSocketMessageType type,
string? connectionId, CancellationToken ct)
{
var targets = connectionId is null
? _clients.ToArray()
: _clients.TryGetValue(connectionId, out var one)
? [new KeyValuePair(connectionId, one)]
: Array.Empty>();
if (connectionId is not null && targets.Length == 0)
throw new InvalidOperationException(
$"No WebSocket client with connection id '{connectionId}' on {_endpoint.ConsumerPath}. " +
"The client may have disconnected since the exchange that carried the id.");
var sent = 0;
foreach (var (id, socket) in targets)
{
if (socket.State != WebSocketState.Open) continue;
try
{
await socket.SendAsync(data, type, endOfMessage: true, ct).ConfigureAwait(false);
sent++;
}
catch (Exception ex) when (ex is WebSocketException or ObjectDisposedException)
{
// One dead socket must not fail a broadcast to everyone else; it is dropped from
// the registry and its handler's finally will finish the cleanup.
_logger?.LogDebug(ex, "WebSocket push skipped a closed client: {ConnectionId}", id);
_clients.TryRemove(id, out _);
}
}
return sent;
}
/// The base URL the server is listening on. Available after Start().
public string? BaseUrl { get; private set; }
///
public async Task Start(CancellationToken ct = default)
{
// wss:// without a certificate anywhere refuses to bind — enforced once, by the shared
// host, which is the only place that sees the endpoint, the connection factory and the
// host default together.
_cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
_drain.Start(ct);
try
{
// One Kestrel per host:port, shared with HTTP, gRPC, SOAP and AS2:
// the endpoint asked for WebSocket support during its own Start, which runs before
// any consumer, so the listener is built with the upgrade middleware in place.
_serverManager = _endpoint.ServerManager;
// Idempotent: the endpoint already asked for this during its own Start when the route
// context owns the lifecycle. Repeating it here keeps a hand-built consumer (tests,
// embedded use) working, and still fails loud if the listener came up without upgrades.
_serverManager.EnableWebSockets(_options.Host, _options.Port,
_options.KeepAliveInterval > 0
? TimeSpan.FromMilliseconds(_options.KeepAliveInterval)
: null,
_options.Ssl, _options.SslCertPath, _options.SslCertPassword);
_registration = _serverManager.RegisterRoute(
_options.Host, _options.Port, _endpoint.ConsumerPath, methods: null, HandleRequest,
_options.Ssl, _options.SslCertPath, _options.SslCertPassword);
// Visible to a server-mode producer only once the listener is up, so a push can never
// find a consumer that is not actually serving.
if (_endpoint.Component is WsComponent comp)
comp.RegisterConsumer(this);
await _serverManager.EnsureStarted(_options.Host, _options.Port, ct).ConfigureAwait(false);
BaseUrl = _serverManager.GetBaseUrl(_options.Host, _options.Port) ?? BuildBaseUrl();
}
catch (Exception ex)
{
_logger?.LogError(ex, "WebSocket consumer Start failed on {Host}:{Port}", _options.Host, _options.Port);
if (_endpoint.Component is WsComponent failed)
failed.UnregisterConsumer(this);
if (_registration is not null)
{
_serverManager?.UnregisterRoute(_registration);
_registration = null;
}
_cts?.Dispose(); _cts = null;
_drain.Dispose();
throw;
}
_logger ??= (_endpoint.Component as ComponentBase)?.Logger;
_logger?.LogInformation("WebSocket consumer started: {Url}{Path}", BaseUrl, _endpoint.ConsumerPath);
}
///
public async Task Stop(CancellationToken ct = default)
{
// A server-mode producer must stop finding us before the sockets start closing.
if (_endpoint.Component is WsComponent comp)
comp.UnregisterConsumer(this);
// Signal cancellation to all handlers: the receive loops exit and stop taking new frames.
_cts?.Cancel();
// Drain in-flight message processing before the listener goes away.
await _drain.DrainAsync(ct, _logger, "WebSocket").ConfigureAwait(false);
// Give up our route; the listener itself stops only when the last route on it is gone,
// because HTTP/gRPC/SOAP consumers may still be serving the same port.
if (_registration is not null && _serverManager is not null)
{
_serverManager.UnregisterRoute(_registration);
_registration = null;
await _serverManager.StopIfEmpty(_options.Host, _options.Port, ct).ConfigureAwait(false);
}
// Close any sockets still open (their handlers already left the receive loop).
foreach (var (id, ws) in _clients)
{
ws.Dispose();
_clients.TryRemove(id, out _);
}
_cts?.Dispose();
_cts = null;
_connectionSemaphore?.Dispose();
_drain.Dispose();
_logger ??= (_endpoint.Component as ComponentBase)?.Logger;
_logger?.LogInformation("WebSocket consumer stopped");
}
private async Task HandleRequest(HttpContext httpContext)
{
if (!httpContext.WebSockets.IsWebSocketRequest)
{
httpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
await httpContext.Response.WriteAsync("WebSocket connections only.").ConfigureAwait(false);
return;
}
// Host-supplied authentication, before the upgrade: a rejected handshake never becomes a
// socket, and an accepted one carries its principal into every exchange it produces. The
// component's own delegate decides on its paths; without one, the caller is whoever the
// shared host's resolver (HttpHostingOptions.ResolvePrincipal) identified, if anyone.
System.Security.Claims.ClaimsPrincipal? principal;
if ((_endpoint.Component as WsComponent)?.Authenticate is { } authenticate)
{
principal = await authenticate(httpContext).ConfigureAwait(false);
if (principal is null)
{
httpContext.Response.StatusCode = StatusCodes.Status401Unauthorized;
return;
}
httpContext.User = principal;
}
else
{
principal = SharedHttpServerManager.GetResolvedPrincipal(httpContext);
}
var userId = principal?.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value
?? principal?.Identity?.Name;
// Throttle connections
if (_connectionSemaphore is not null)
await _connectionSemaphore.WaitAsync(httpContext.RequestAborted).ConfigureAwait(false);
// The upgrade request is the only place a client can put trace headers; every message span links it.
var handshake = RouteTelemetryExtensions.ExtractTraceContext(httpContext.Request.Headers,
static (headers, name) => headers.TryGetValue(name, out var values) ? values.ToString() : null);
var connectionId = Guid.NewGuid().ToString("N");
System.Net.WebSockets.WebSocket ws;
try
{
ws = _options.SubProtocol is not null
? await httpContext.WebSockets.AcceptWebSocketAsync(_options.SubProtocol).ConfigureAwait(false)
: await httpContext.WebSockets.AcceptWebSocketAsync().ConfigureAwait(false);
}
catch
{
_connectionSemaphore?.Release();
return;
}
_clients[connectionId] = ws;
var remoteEp = httpContext.Connection.RemoteIpAddress is not null
? $"{httpContext.Connection.RemoteIpAddress}:{httpContext.Connection.RemotePort}"
: "unknown";
var localEp = httpContext.Connection.LocalIpAddress is not null
? $"{httpContext.Connection.LocalIpAddress}:{httpContext.Connection.LocalPort}"
: "unknown";
try
{
using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(httpContext.RequestAborted, _cts?.Token ?? CancellationToken.None);
await HandleWebSocket(ws, connectionId, remoteEp, localEp, principal, userId, handshake, linkedCts.Token)
.ConfigureAwait(false);
}
finally
{
_connectionSemaphore?.Release();
ws.Dispose();
_clients.TryRemove(connectionId, out _);
}
}
private async Task HandleWebSocket(System.Net.WebSockets.WebSocket ws, string connectionId,
string remoteEp, string localEp, System.Security.Claims.ClaimsPrincipal? principal, string? userId,
ActivityContext handshake, CancellationToken ct)
{
IEnumerable? links = handshake == default ? null : [new ActivityLink(handshake)];
var buffer = new byte[_options.ReceiveBufferSize];
while (ws.State == WebSocketState.Open && !ct.IsCancellationRequested)
{
byte[] data;
WebSocketMessageType msgType;
try
{
using var ms = new MemoryStream();
WebSocketReceiveResult result;
do
{
result = await ws.ReceiveAsync(buffer, ct).ConfigureAwait(false);
if (result.MessageType == WebSocketMessageType.Close)
return;
ms.Write(buffer, 0, result.Count);
}
while (!result.EndOfMessage);
data = ms.ToArray();
msgType = result.MessageType;
}
catch (OperationCanceledException) { return; }
catch (WebSocketException) { return; }
// Pipeline statistics (MessagesIn/BytesIn/Errors) belong to the core: the routed
// processor chain is wrapped in StatisticsProcessor, and recording here as well
// double-counted every frame (the statistics-ownership audit).
var exchange = BuildExchange(data, msgType, connectionId, remoteEp, localEp, principal, userId);
// A frame carries no headers: its span is a root linked to the upgrade request, never a child of the
// connection's activity, which may live for hours.
using var span = RouteTelemetryExtensions.StartConsumerSpan