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