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. [![NuGet](https://img.shields.io/nuget/v/redb.Route.WebSocket?label=NuGet&color=blue)](https://www.nuget.org/packages/redb.Route.WebSocket) [![License: Apache 2.0](https://img.shields.io/badge/license-Apache%202.0-blue)](../../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( (_endpoint.Component as ComponentBase)?.Context, $"ws {_endpoint.ConsumerPath} receive", ActivityKind.Consumer, "messaging.system", "websocket", _endpoint.Uri.NormalizedKey, null, static (_, _) => null, destination: _endpoint.ConsumerPath, operation: "receive", links: links); _drain.Increment(); try { try { await _processor.Process(exchange, _drain.ProcessingToken).ConfigureAwait(false); } catch (Exception ex) { _logger?.LogError(ex, "WebSocket message processing failed: remote={RemoteEndpoint}, type={MessageType}", remoteEp, msgType); exchange.Exception = ex; } // Our own stop is not a failure; any other cancellation, a timeout inside the route, is. if (exchange.Exception is { } failure && !exchange.ExceptionHandled && (failure is not OperationCanceledException || !_drain.ProcessingToken.IsCancellationRequested)) span.Activity.RecordFailure(failure); // InOut: send response frame (use drain-safe token so response completes during drain) if (_options.InOut && exchange.Exception is null && exchange.HasOut && exchange.Out!.Body is not null) { if (exchange.Out.Body is IAsyncEnumerable asyncStrings) { await foreach (var chunk in asyncStrings.WithCancellation(_drain.ProcessingToken).ConfigureAwait(false)) { if (string.IsNullOrEmpty(chunk)) continue; var bytes = _encoding.GetBytes(chunk); await ws.SendAsync(bytes, WebSocketMessageType.Text, endOfMessage: true, _drain.ProcessingToken).ConfigureAwait(false); } } else { var (responseData, responseType) = ResolveResponseBody(exchange); await ws.SendAsync(responseData, responseType, endOfMessage: true, _drain.ProcessingToken).ConfigureAwait(false); } } Interlocked.Increment(ref _processedCount); await exchange.DisposeAsync().ConfigureAwait(false); } finally { _drain.Decrement(); } } } private IExchange BuildExchange(byte[] data, WebSocketMessageType msgType, string connectionId, string remoteEp, string localEp, System.Security.Claims.ClaimsPrincipal? principal, string? userId) { object body = msgType == WebSocketMessageType.Text ? _encoding.GetString(data) : data; var message = new Message(body); message.Headers[WsHeaders.RemoteAddress] = remoteEp; message.Headers[WsHeaders.LocalAddress] = localEp; message.Headers[WsHeaders.ConnectionId] = connectionId; message.Headers[WsHeaders.MessageType] = msgType == WebSocketMessageType.Text ? "Text" : "Binary"; message.Headers[WsHeaders.ByteCount] = data.Length.ToString(); message.Headers[WsHeaders.Ssl] = _options.Ssl.ToString(); message.Headers[WsHeaders.Path] = _endpoint.ConsumerPath; if (_options.SubProtocol is not null) message.Headers[WsHeaders.SubProtocol] = _options.SubProtocol; if (userId is not null) message.Headers[WsHeaders.UserId] = userId; var exchange = Exchange.Create(message, _endpoint.ScopeFactory); exchange.Pattern = _options.InOut ? ExchangePattern.InOut : ExchangePattern.InOnly; ExchangePrincipal.Set(exchange, principal); return exchange; } private (byte[] data, WebSocketMessageType type) ResolveResponseBody(IExchange exchange) { var outBody = exchange.Out!.Body!; return outBody switch { byte[] bytes => (bytes, WebSocketMessageType.Binary), string str => (_encoding.GetBytes(str), WebSocketMessageType.Text), _ => (_encoding.GetBytes(outBody.ToString()!), WebSocketMessageType.Text) }; } private string BuildBaseUrl() { var scheme = _options.Ssl ? "wss" : "ws"; var host = _options.Host == "0.0.0.0" ? "127.0.0.1" : _options.Host; return $"{scheme}://{host}:{_options.Port}"; } } Path: redb-route/redb.Route.WebSocket/WsEndpointOptions.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/WsEndpointOptions.cs ---- using redb.Route.Core; namespace redb.Route.WebSocket; /// /// Options for the WebSocket endpoint. Shared by both producer and consumer. /// URI format: ws:host:port/path?messageType=Text&subProtocol=graphql-ws /// public class WsEndpointOptions : EndpointOptions { // ── Connection ────────────────────────────────────── /// Host to connect or bind. Parsed from URI path. public string Host { get; set; } = "0.0.0.0"; /// Port number. Parsed from URI path. public int Port { get; set; } = 8080; // ── Framing ───────────────────────────────────────── /// Default message type for outgoing frames. Default: Text. public WsMessageType MessageType { get; set; } = WsMessageType.Text; /// Text encoding name. Default: utf-8. public string Encoding { get; set; } = "utf-8"; // ── Protocol ──────────────────────────────────────── /// /// WebSocket subprotocol to negotiate (e.g. "graphql-ws", "mqtt"). /// Default: null (no subprotocol). /// public string? SubProtocol { get; set; } // ── Socket ────────────────────────────────────────── /// Receive buffer size in bytes. Default: 8192. public int ReceiveBufferSize { get; set; } = 8192; /// Send buffer size in bytes (ClientWebSocket only). Default: 8192. public int SendBufferSize { get; set; } = 8192; /// Keep-alive ping interval in milliseconds. 0 = disabled. Default: 30000 (30s). public int KeepAliveInterval { get; set; } = 30_000; // ── Producer (client) ─────────────────────────────── /// Connect timeout in milliseconds. Default: 10000 (10s). 0 = infinite. public int ConnectTimeout { get; set; } = 10_000; /// Auto-reconnect on disconnect. Default: false. public bool Reconnect { get; set; } /// Interval between reconnect attempts in milliseconds. Default: 5000. public int ReconnectInterval { get; set; } = 5_000; /// Maximum reconnect attempts. 0 = unlimited. Default: 0. public int MaxReconnectAttempts { get; set; } /// /// Overall time budget for reconnecting, in milliseconds. 0 = no budget (default, the /// historical behaviour). With reconnect=true, maxReconnectAttempts=0 and a /// server that stays down, an exchange would otherwise never come back and dead-letter would /// never fire; set this to make the send fail instead of hanging. /// public int ReconnectTimeout { get; set; } /// /// Producer mode. Client (default) connects to a remote server with /// . Server pushes into the clients /// of the consumer running on the same URI, so a route can send unsolicited frames /// (quotes, notifications, progress) instead of only answering incoming ones. /// public WsMode Mode { get; set; } = WsMode.Client; // ── Consumer (server) ─────────────────────────────── /// Maximum concurrent WebSocket connections. 0 = unlimited. Default: 0. public int MaxConnections { get; set; } /// /// If true, the consumer returns the exchange Out body as a WebSocket response frame (InOut pattern). /// Default: false. /// public bool InOut { get; set; } // ── TLS ───────────────────────────────────────────── /// Enable TLS (wss). Default: false. public bool Ssl { get; set; } /// Path to PFX certificate file for TLS (consumer/server). Required when ssl=true for consumer. public string? SslCertPath { get; set; } /// Password for the PFX certificate. [Sensitive] public string? SslCertPassword { get; set; } /// /// Producer only: accept any server certificate on a wss:// connection, including a /// self-signed one. Off by default and never implied by another option — turning certificate /// validation off has to be an explicit decision, and it belongs to staging, not production. /// public bool TrustAllCertificates { get; set; } /// /// Named from the route registry. Lets the TLS certificate /// password live in the registry instead of the endpoint URI, so it never reaches logs /// or dashboards. /// [RegistryReference(typeof(WsConnectionFactory))] public string? ConnectionFactory { get; set; } /// public override void Validate() { if (Port is < 0 or > 65535) throw new ArgumentException("Port must be between 0 and 65535."); if (ReceiveBufferSize <= 0) throw new ArgumentException("ReceiveBufferSize must be > 0."); if (SendBufferSize <= 0) throw new ArgumentException("SendBufferSize must be > 0."); if (KeepAliveInterval < 0) throw new ArgumentException("KeepAliveInterval must be >= 0."); if (ConnectTimeout < 0) throw new ArgumentException("ConnectTimeout must be >= 0."); if (ReconnectInterval <= 0) throw new ArgumentException("ReconnectInterval must be > 0."); if (MaxReconnectAttempts < 0) throw new ArgumentException("MaxReconnectAttempts must be >= 0."); if (ReconnectTimeout < 0) throw new ArgumentException("ReconnectTimeout must be >= 0."); if (MaxConnections < 0) throw new ArgumentException("MaxConnections must be >= 0."); // Without this the mistake surfaces as a bare framework ArgumentException from the // consumer's constructor, with no hint which option or which endpoint is at fault. try { System.Text.Encoding.GetEncoding(Encoding); } catch (ArgumentException ex) { throw new ArgumentException( $"Unknown encoding '{Encoding}'. Use a name System.Text.Encoding knows, such as utf-8.", ex); } } } /// Producer mode for the WebSocket component. public enum WsMode { /// Connect to a remote WebSocket server and send frames on it. Client, /// Push frames into the clients of the local consumer serving the same URI. Server, } Path: redb-route/redb.Route.WebSocket/WsEnums.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/WsEnums.cs ---- namespace redb.Route.WebSocket; /// /// WebSocket message type. Maps to . /// public enum WsMessageType { /// UTF-8 text frame. Text, /// Binary frame. Binary } Path: redb-route/redb.Route.WebSocket/WsHeaders.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/WsHeaders.cs ---- namespace redb.Route.WebSocket; /// /// Well-known header constants used by the WebSocket component. /// public static class WsHeaders { /// Common prefix for all WebSocket component headers. public const string Prefix = "redbWs."; /// Remote endpoint address (IP:port). public const string RemoteAddress = "redbWs.RemoteAddress"; /// Local endpoint address (IP:port). public const string LocalAddress = "redbWs.LocalAddress"; /// Unique connection identifier. public const string ConnectionId = "redbWs.ConnectionId"; /// Message type: "Text" or "Binary". public const string MessageType = "redbWs.MessageType"; /// Message byte count. public const string ByteCount = "redbWs.ByteCount"; /// WebSocket subprotocol negotiated. public const string SubProtocol = "redbWs.SubProtocol"; /// Whether TLS/WSS is used: "True"/"False". public const string Ssl = "redbWs.Ssl"; /// Request path the WebSocket was accepted on. public const string Path = "redbWs.Path"; /// /// Identity of the connected client, when the host supplied an authentication delegate: /// the principal's NameIdentifier claim. /// public const string UserId = "redbWs.UserId"; /// /// Server-mode producer: the connection id to push this frame to. Absent means every /// connected client. The id is the one the consumer put into /// on the incoming exchange. /// public const string TargetConnection = "redbWs.TargetConnection"; } Path: redb-route/redb.Route.WebSocket/WsProducer.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/WsProducer.cs ---- using System.Diagnostics; using System.Net.WebSockets; using System.Text; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Telemetry; namespace redb.Route.WebSocket; /// /// WebSocket producer. Connects to a remote WebSocket server using /// and sends exchange body as text or binary frames. /// In InOut mode, waits for a response frame and populates the exchange Out message. /// public sealed class WsProducer : ConnectableProducer { private readonly WsEndpoint _endpoint; private readonly WsEndpointOptions _options; private readonly Encoding _encoding; private ClientWebSocket? _ws; private WsConsumer? _localConsumer; private readonly SemaphoreSlim _sendLock = new(1, 1); /// Creates a WebSocket producer. public WsProducer(WsEndpoint endpoint, WsEndpointOptions options) { _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); _options = options ?? throw new ArgumentNullException(nameof(options)); _encoding = Encoding.GetEncoding(options.Encoding); } /// protected override IEndpoint ProducerEndpoint => _endpoint; /// // The name goes into the "producer started" log line, so a ws://user:pass@host URI must not // carry its password through it. protected override string ProducerName => $"ws:{_options.Mode}:{EndpointUri.Sanitize(_endpoint.BuildProducerUrl())}"; /// The logged producer name, so a test can pin the masking. internal string DiagnosticName => ProducerName; /// protected override async Task ConnectAsync(CancellationToken ct) { if (_options.Mode == WsMode.Server) { // Push into the clients of the consumer on the same URI. It has to be running: // silently pushing into nothing would be worse than a refusal to start. _localConsumer = (_endpoint.Component as WsComponent)?.GetConsumer( _options.Host, _options.Port, _endpoint.ConsumerPath) ?? throw new InvalidOperationException( $"Server-mode producer needs a running WebSocket consumer on {_endpoint.Uri.ToMaskedUriString()}. " + "Start From(\"ws:...\") on the same URI before sending to \"ws:...?mode=Server\"."); return; } await ConnectWsAsync(ct).ConfigureAwait(false); } /// protected override async Task DisconnectAsync(CancellationToken ct) { _localConsumer = null; if (_ws is { State: WebSocketState.Open or WebSocketState.CloseReceived }) { try { using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(2)); await _ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "Stopping", cts.Token).ConfigureAwait(false); } catch (Exception ex) { Logger?.LogDebug(ex, "WebSocket: error closing during stop"); } } _ws?.Dispose(); _ws = null; } /// public override async Task Process(IExchange exchange, CancellationToken ct = default) { EnsureStarted(); using var activity = RouteTelemetryExtensions.StartTransportSpan( (_endpoint.Component as ComponentBase)?.Context, $"ws send {_options.Mode}", ActivityKind.Producer, "messaging.system", "websocket", _endpoint.Uri.NormalizedKey, destination: _endpoint.ConsumerPath, operation: "send"); // No RecordError here: the exception flies on into the core (ToProcessor / the template), which // records it against this endpoint - recording here as well double-counted it (the // statistics-ownership audit). The span is marked, then the exception is rethrown. try { if (_options.Mode == WsMode.Server) await ProcessServerMode(exchange, ct).ConfigureAwait(false); else await ProcessClientMode(exchange, ct).ConfigureAwait(false); } catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested) { // Only our own token cancelling the send is a stop; any other failure marks the span. activity.RecordFailure(ex); throw; } SetExchangeHeaders(exchange); } /// Pushes the body into the clients of the local consumer (mode=Server). private async Task ProcessServerMode(IExchange exchange, CancellationToken ct) { var (data, msgType) = ResolveBody(exchange); var target = exchange.In.Headers.TryGetValue(WsHeaders.TargetConnection, out var raw) && raw is string id && !string.IsNullOrEmpty(id) ? id : null; var sent = await _localConsumer!.SendToClients(data, msgType, target, ct).ConfigureAwait(false); // MessagesOut is the core's (ToProcessor counts the exchange once); the connector owns // only the wire bytes - one exchange can reach many sockets, so bytes follow the frames. for (var i = 0; i < sent; i++) _endpoint.RecordBytesOut(data.Length); } private async Task ProcessClientMode(IExchange exchange, CancellationToken ct) { // Reconnect if needed if (_ws is null or { State: not WebSocketState.Open }) { if (_options.Reconnect) await ReconnectAsync(ct).ConfigureAwait(false); else throw new InvalidOperationException("WebSocket connection lost and reconnect is disabled."); } var (data, msgType) = ResolveBody(exchange); await _sendLock.WaitAsync(ct).ConfigureAwait(false); try { await _ws!.SendAsync(data, msgType, endOfMessage: true, ct).ConfigureAwait(false); _endpoint.RecordBytesOut(data.Length); // wire bytes only: MessagesOut belongs to the core // InOut: read response frame if (_options.InOut) { var (responseData, responseType) = await ReceiveMessageAsync(ct).ConfigureAwait(false); if (responseData is not null) { _endpoint.RecordBytesIn(responseData.Length); object body = responseType == WebSocketMessageType.Text ? _encoding.GetString(responseData) : responseData; var outMsg = new Message(body); outMsg.Headers[WsHeaders.MessageType] = responseType == WebSocketMessageType.Text ? "Text" : "Binary"; outMsg.Headers[WsHeaders.ByteCount] = responseData.Length.ToString(); exchange.Out = outMsg; } } } finally { _sendLock.Release(); } } private (byte[] data, WebSocketMessageType type) ResolveBody(IExchange exchange) { var body = exchange.In.Body; var wsType = _options.MessageType == WsMessageType.Binary ? WebSocketMessageType.Binary : WebSocketMessageType.Text; byte[] data = body switch { byte[] bytes => bytes, Stream s => ReadStream(s), string str => _encoding.GetBytes(str), null => [], _ => _encoding.GetBytes(BodyText.Of(body)) }; return (data, wsType); } private static byte[] ReadStream(Stream s) { if (s is MemoryStream ms) return ms.ToArray(); using var temp = new MemoryStream(); s.CopyTo(temp); return temp.ToArray(); } private async Task<(byte[]? data, WebSocketMessageType type)> ReceiveMessageAsync(CancellationToken ct) { var buffer = new byte[_options.ReceiveBufferSize]; using var ms = new MemoryStream(); WebSocketReceiveResult result; do { result = await _ws!.ReceiveAsync(buffer, ct).ConfigureAwait(false); if (result.MessageType == WebSocketMessageType.Close) return (null, WebSocketMessageType.Close); ms.Write(buffer, 0, result.Count); } while (!result.EndOfMessage); return (ms.ToArray(), result.MessageType); } private void SetExchangeHeaders(IExchange exchange) { exchange.In.Headers[WsHeaders.MessageType] = _options.MessageType.ToString(); exchange.In.Headers[WsHeaders.Ssl] = _options.Ssl.ToString(); if (_ws?.SubProtocol is not null) exchange.In.Headers[WsHeaders.SubProtocol] = _ws.SubProtocol; } private async Task ConnectWsAsync(CancellationToken ct) { _ws = new ClientWebSocket(); if (_options.KeepAliveInterval > 0) _ws.Options.KeepAliveInterval = TimeSpan.FromMilliseconds(_options.KeepAliveInterval); _ws.Options.SetBuffer(_options.ReceiveBufferSize, _options.SendBufferSize); if (_options.SubProtocol is not null) _ws.Options.AddSubProtocol(_options.SubProtocol); // Explicit, never implied: a self-signed staging server is reachable only when the route // says so out loud. if (_options.TrustAllCertificates) _ws.Options.RemoteCertificateValidationCallback = (_, _, _, _) => true; var uri = new Uri(_endpoint.BuildProducerUrl()); using var cts = _options.ConnectTimeout > 0 ? CancellationTokenSource.CreateLinkedTokenSource(ct) : null; cts?.CancelAfter(_options.ConnectTimeout); await _ws.ConnectAsync(uri, cts?.Token ?? ct).ConfigureAwait(false); } private async Task ReconnectAsync(CancellationToken ct) { var attempts = 0; var budget = _options.ReconnectTimeout > 0 ? Stopwatch.StartNew() : null; while (true) { attempts++; try { _ws?.Dispose(); await ConnectWsAsync(ct).ConfigureAwait(false); return; } catch when (_options.MaxReconnectAttempts > 0 && attempts >= _options.MaxReconnectAttempts) { Logger?.LogError("WebSocket reconnect to {Host}:{Port} exhausted {Max} attempts", _options.Host, _options.Port, _options.MaxReconnectAttempts); throw; } catch when (budget is not null && budget.ElapsedMilliseconds >= _options.ReconnectTimeout) { // Without a budget an exchange against a server that stays down never returns: // it does not fail, so dead-letter never fires and the route simply hangs. Logger?.LogError("WebSocket reconnect to {Host}:{Port} exhausted its {Timeout} ms budget after {Attempts} attempts", _options.Host, _options.Port, _options.ReconnectTimeout, attempts); throw; } catch (Exception ex) { Logger?.LogWarning(ex, "WebSocket reconnect to {Host}:{Port} failed, attempt {Attempt}", _options.Host, _options.Port, attempts); await Task.Delay(_options.ReconnectInterval, ct).ConfigureAwait(false); } } } } Path: redb-route/redb.Route.WebSocket/redb.Route.WebSocket.csproj 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/redb.Route.WebSocket.csproj ---- redb.Route.WebSocket WebSocket transport for redb.Route ESB framework. Provides ClientWebSocket producer and Kestrel-based WebSocket server consumer with text/binary frames, ping/pong, reconnect, and subprotocol support. esb;messaging;websocket;ws;wss;realtime;kestrel;redb README.md