Bundle: redb-route / redb.Route.Tcp (redb.Route.Tcp.txt), 12 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.Tcp/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.Tcp/Extensions/ServiceCollectionExtensions.cs
----
using Microsoft.Extensions.DependencyInjection;
using redb.Route.Extensions;
namespace redb.Route.Tcp;
///
/// Extension methods for registering the TCP component with dependency injection.
///
public static class ServiceCollectionExtensions
{
///
/// Registers the TCP component with the route context.
///
public static IServiceCollection AddRedbRouteTcp(this IServiceCollection services)
{
// IRouteContextConfigurator is applied by RouteHostedService at startup --
// the correct registration hook (a lazy marker singleton never fires).
services.AddRouteComponent();
return services;
}
}
Path: redb-route/redb.Route.Tcp/Fluent/TcpDsl.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.Tcp/Fluent/TcpDsl.cs
----
using System.Text;
namespace redb.Route.Tcp;
///
/// Fluent entry point for TCP endpoints.
///
/// // Consumer — listen for connections:
/// .From(TcpDsl.Listen("0.0.0.0:9000").TextLine().InOut())
///
/// // Producer — connect to remote host:
/// .To(TcpDsl.Connect("192.0.2.10:9000").TextLine().Reconnect())
///
///
public static class TcpDsl
{
/// Listen for incoming TCP connections (consumer).
public static TcpBuilder Listen(string hostPort) => new(hostPort);
/// Connect to a remote TCP endpoint (producer).
public static TcpBuilder Connect(string hostPort) => new(hostPort);
}
/// Fluent builder for TCP endpoint URIs. Scheme: tcp.
public sealed class TcpBuilder
{
private readonly string _hostPort;
// Framing
private bool _textLine;
private bool _lengthPrefixed;
private string? _delimiter;
private string? _encoding;
// Socket
private bool? _keepAlive;
private bool? _noDelay;
private int? _receiveBufferSize;
private int? _sendBufferSize;
// Producer
private int? _connectTimeout;
private bool _reconnect;
private int? _reconnectInterval;
private int? _maxReconnectAttempts;
// Consumer
private int? _backlog;
private int? _maxConnections;
private bool? _inOut;
// TLS
private bool _ssl;
private bool _trustAllCertificates;
private string? _clientCertPath;
private string? _clientCertPassword;
private string? _sslCertPath;
private string? _sslCertPassword;
private string? _connectionFactory;
private string? _sslTargetHost;
internal TcpBuilder(string hostPort)
{
ArgumentException.ThrowIfNullOrWhiteSpace(hostPort);
_hostPort = hostPort;
}
// ── Framing ─────────────────────────────────────────────────────
/// Use newline-delimited text framing.
public TcpBuilder TextLine() { _textLine = true; return this; }
/// Use length-prefixed binary framing.
public TcpBuilder LengthPrefixed() { _lengthPrefixed = true; return this; }
/// Custom delimiter for text-line framing.
public TcpBuilder Delimiter(string delimiter) { _delimiter = delimiter; return this; }
/// Character encoding. Default utf-8.
public TcpBuilder Encoding(string encoding) { _encoding = encoding; return this; }
// ── Socket ──────────────────────────────────────────────────────
/// Enable TCP keep-alive. Default true.
public TcpBuilder KeepAlive(bool value = true) { _keepAlive = value; return this; }
/// Set TCP_NODELAY. Default true.
public TcpBuilder NoDelay(bool value = true) { _noDelay = value; return this; }
/// Receive buffer size in bytes.
public TcpBuilder ReceiveBufferSize(int size) { _receiveBufferSize = size; return this; }
/// Send buffer size in bytes.
public TcpBuilder SendBufferSize(int size) { _sendBufferSize = size; return this; }
// ── Producer ────────────────────────────────────────────────────
/// Connection timeout in ms.
public TcpBuilder ConnectTimeout(int ms) { _connectTimeout = ms; return this; }
/// Enable auto-reconnect on disconnect.
public TcpBuilder Reconnect(int intervalMs = 5000, int maxAttempts = 0) { _reconnect = true; _reconnectInterval = intervalMs; _maxReconnectAttempts = maxAttempts; return this; }
// ── Consumer ────────────────────────────────────────────────────
/// TCP listen backlog. Default 128.
public TcpBuilder Backlog(int size) { _backlog = size; return this; }
/// Max concurrent connections. 0 = unlimited.
public TcpBuilder MaxConnections(int max) { _maxConnections = max; return this; }
/// Enable request-response pattern.
public TcpBuilder InOut(bool value = true) { _inOut = value; return this; }
// ── TLS ─────────────────────────────────────────────────────────
/// Enable SSL/TLS.
public TcpBuilder Ssl() { _ssl = true; return this; }
/// Path to SSL certificate.
public TcpBuilder SslCertPath(string path) { _sslCertPath = path; return this; }
/// SSL certificate password.
public TcpBuilder SslCertPassword(string password) { _sslCertPassword = password; return this; }
/// References a named from the route registry instead of putting the certificate password in the URI.
public TcpBuilder ConnectionFactory(string name) { _connectionFactory = name; return this; }
/// Target host name for SSL validation.
public TcpBuilder SslTargetHost(string host) { _sslTargetHost = host; 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 TcpBuilder TrustAllCertificates() { _trustAllCertificates = true; return this; }
/// Producer: PFX client certificate presented to a server that requires mTLS.
public TcpBuilder ClientCert(string path, string? password = null)
{ _clientCertPath = path; _clientCertPassword = password; return this; }
// ── Build ───────────────────────────────────────────────────────
public string Build()
{
var sb = new StringBuilder();
sb.Append("tcp:");
sb.Append(_hostPort);
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); }
AppendBool("textLine", _textLine);
AppendBool("lengthPrefixed", _lengthPrefixed);
AppendStr("delimiter", _delimiter);
AppendStr("encoding", _encoding);
AppendBoolN("keepAlive", _keepAlive);
AppendBoolN("noDelay", _noDelay);
AppendInt("receiveBufferSize", _receiveBufferSize);
AppendInt("sendBufferSize", _sendBufferSize);
AppendInt("connectTimeout", _connectTimeout);
AppendBool("reconnect", _reconnect);
AppendInt("reconnectInterval", _reconnectInterval);
AppendInt("maxReconnectAttempts", _maxReconnectAttempts);
AppendInt("backlog", _backlog);
AppendInt("maxConnections", _maxConnections);
AppendBoolN("inOut", _inOut);
AppendBool("ssl", _ssl);
AppendStr("sslCertPath", _sslCertPath);
AppendStr("sslCertPassword", _sslCertPassword);
AppendStr("connectionFactory", _connectionFactory);
AppendStr("sslTargetHost", _sslTargetHost);
AppendBool("trustAllCertificates", _trustAllCertificates);
AppendStr("clientCertPath", _clientCertPath);
AppendStr("clientCertPassword", _clientCertPassword);
return sb.ToString();
}
public static implicit operator string(TcpBuilder b) => b.Build();
public override string ToString() => Build();
}
Path: redb-route/redb.Route.Tcp/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.Tcp/README.md
----
# redb.Route.Tcp
> Documentation and articles:
TCP transport for redb.Route. Socket-based producer (client) and consumer (server) with text-line, length-prefixed, and raw framing modes, TLS, and InOut request-reply patterns.
[](https://www.nuget.org/packages/redb.Route.Tcp)
[](../../LICENSE)
## Installation
```bash
dotnet add package redb.Route.Tcp
```
No additional dependencies.
## Usage
### Fluent DSL
```csharp
using redb.Route.Tcp;
// TCP server (consumer)
From(TcpDsl.Listen("0.0.0.0:9000")
.TextLine()
.MaxConnections(100)
.Backlog(128))
.Log("Received: ${body}")
.To("direct://process");
// TCP client (producer)
From("direct://send")
.To(TcpDsl.Connect("server.local:9000")
.TextLine()
.ConnectTimeout(5000)
.Reconnect(intervalMs: 3000, maxAttempts: 5));
// Length-prefixed binary protocol
From(TcpDsl.Listen("0.0.0.0:9001")
.LengthPrefixed()
.InOut())
.Process(async (e, ct) =>
{
var request = (byte[])e.In.Body!;
e.In.Body = HandleRequest(request);
});
// TLS
From(TcpDsl.Listen("0.0.0.0:9443")
.TextLine()
.Ssl()
.SslCertPath("/certs/server.pfx")
.SslCertPassword("password"))
.To("direct://secure-handler");
```
A TLS **consumer** needs its certificate — from the endpoint or from a named
`TcpConnectionFactory`, which is where the password belongs. It is loaded once when the listener
starts: a missing file, a wrong password or no path at all fails the start with a message naming
the listener, instead of killing every accepted connection one by one.
A TLS **producer** needs no certificate of its own; `ssl=true` there means "speak TLS to the
server", with `sslTargetHost` for SNI when the name differs from the host you dial. To reach a
server behind a self-signed certificate (staging), say so out loud:
```csharp
.To(TcpDsl.Connect("staging:9443").Ssl().SslTargetHost("staging.internal").TrustAllCertificates())
```
It is never implied by anything else.
For a server that requires mTLS, the producer presents a client certificate — a different thing
from `sslCertPath`, which is the certificate a *consumer* serves:
```csharp
.To(TcpDsl.Connect("partner:9443").Ssl().ClientCert("/certs/client.pfx", "password"))
```
It is loaded once at start, so a reconnect does not re-read the PFX and a bad path or password is
a start-time error. The **consumer** does not request client certificates
(`AuthenticateAsServerAsync` with the server certificate alone), so mTLS here means "we present one
to someone else", not "we demand one".
### Bind address
The consumer's host may be an IP, `0.0.0.0` for every interface, `localhost`, or a resolvable
name; a name that resolves to nothing fails the start with a message naming it. Note that a
`TcpListener` binds exactly one address, so `localhost` here means the **IPv4 loopback** — a client
that dials `[::1]` explicitly needs `::1` in the URI.
## Fluent Builder API
| Category | Methods |
|----------|---------|
| **Server** | `TcpDsl.Listen(hostPort)`, `.Backlog()`, `.MaxConnections()`, `.InOut()` |
| **Client** | `TcpDsl.Connect(hostPort)`, `.ConnectTimeout()`, `.Reconnect(interval, max)` |
| **Framing** | `.TextLine()`, `.LengthPrefixed()`, `.Delimiter()`, `.Encoding()` |
| **Socket** | `.KeepAlive()`, `.NoDelay()`, `.ReceiveBufferSize()`, `.SendBufferSize()` |
| **TLS** | `.Ssl()`, `.SslCertPath()`, `.SslCertPassword()`, `.SslTargetHost()`, `.TrustAllCertificates()`, `.ClientCert()` |
## Framing Modes
| Mode | Description |
|------|-------------|
| `Raw` | No framing — raw byte stream |
| `TextLine` | Messages delimited by newline (`\n`) |
| `LengthPrefixed` | 4-byte big-endian length header + payload |
## URI Format
```
tcp://host:port?param=value&...
```
### URI Examples
```csharp
// Server — listen on all interfaces, text-line framing
From("tcp://0.0.0.0:9000?textLine=true&maxConnections=100")
// Client — connect with auto-reconnect
.To("tcp://server.local:9000?textLine=true&reconnect=true&reconnectInterval=3000&maxReconnectAttempts=5")
// Binary protocol with request-reply
From("tcp://0.0.0.0:9001?lengthPrefixed=true&inOut=true")
// TLS
From("tcp://0.0.0.0:9443?textLine=true&ssl=true&sslCertPath=/certs/server.pfx&sslCertPassword=secret")
```
### URI Parameters
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `textLine` | bool | `false` | Use newline-delimited framing |
| `lengthPrefixed` | bool | `false` | Use 4-byte length-prefixed framing |
| `delimiter` | string | `\n` | Line delimiter (TextLine mode) |
| `encoding` | string | `utf-8` | Character encoding |
| `keepAlive` | bool | `true` | TCP keep-alive |
| `noDelay` | bool | `true` | Disable Nagle's algorithm |
| `receiveBufferSize` | int | `0` | Socket receive buffer (bytes); 0 lets the system size and grow it. Also the Raw/TextLine read chunk (8192 when 0) |
| `sendBufferSize` | int | `0` | Socket send buffer (bytes); 0 lets the system size it |
| `connectTimeout` | int | `10000` | Client connect timeout (ms) |
| `reconnect` | bool | `false` | Auto-reconnect on connection loss |
| `reconnectInterval` | int | `5000` | Delay between reconnect attempts (ms) |
| `maxReconnectAttempts` | int | `0` | Max reconnect attempts (0 = unlimited) |
| `backlog` | int | `128` | Server listen backlog |
| `maxConnections` | int | `0` | Max concurrent connections (0 = unlimited) |
| `inOut` | bool | `false` | Request-reply mode (wait for / send response) |
| `ssl` | bool | `false` | Enable TLS |
| `sslCertPath` | string | — | Path to PFX certificate file |
| `sslCertPassword` | string | — | Certificate password |
| `sslTargetHost` | string | — | Expected server hostname (client TLS validation) |
## 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 TcpConnectionFactory
{
Ssl = true,
SslCertPath = "/secrets/client.pfx",
SslCertPassword = secrets.CertPassword,
});
// tcp://gateway.internal:7000?connectionFactory=prod
```
## Tracing
On the `redb.Route` activity source (`AddSource("redb.Route")`), with `network.transport` = `tcp` and
`redb.route.endpoint`:
- **Consumer.** One `Consumer` span, `tcp {host}:{port} receive`, per routed message, the InOut reply included. A framed
message carries no trace context, so the span is a root, never a child of the activity the listener inherited from
whoever started the routes; a connection that sends nothing opens none. A failed route marks it an error; our own stop
does not.
- **Producer.** One `Client` span per send, `tcp {host}:{port}`; an error when the send fails, unless our own token
cancelled it.
- `RouteEngineOptions.EnableTelemetry = false` opens neither span.
Path: redb-route/redb.Route.Tcp/TcpCodec.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.Tcp/TcpCodec.cs
----
using System.Buffers.Binary;
using System.IO;
using System.Text;
namespace redb.Route.Tcp;
///
/// Codec for reading and writing framed TCP messages.
/// Supports Raw, TextLine, and LengthPrefixed framing modes.
/// Thread-safe: stateless, all state is in the stream.
///
internal static class TcpCodec
{
///
/// Reads one framed message from the stream.
/// Returns null if the connection is closed (0 bytes read).
///
public static async Task ReadMessageAsync(
Stream stream, TcpFraming framing, string delimiter, int bufferSize, CancellationToken ct)
{
return framing switch
{
TcpFraming.TextLine => await ReadTextLineAsync(stream, delimiter, bufferSize, ct).ConfigureAwait(false),
TcpFraming.LengthPrefixed => await ReadLengthPrefixedAsync(stream, ct).ConfigureAwait(false),
_ => await ReadRawAsync(stream, bufferSize, ct).ConfigureAwait(false)
};
}
///
/// Writes one framed message to the stream.
///
public static async Task WriteMessageAsync(
Stream stream, byte[] data, TcpFraming framing, string delimiter, Encoding encoding, CancellationToken ct)
{
switch (framing)
{
case TcpFraming.TextLine:
await stream.WriteAsync(data, ct).ConfigureAwait(false);
var delimBytes = encoding.GetBytes(delimiter);
await stream.WriteAsync(delimBytes, ct).ConfigureAwait(false);
break;
case TcpFraming.LengthPrefixed:
var header = new byte[4];
BinaryPrimitives.WriteInt32BigEndian(header, data.Length);
await stream.WriteAsync(header, ct).ConfigureAwait(false);
await stream.WriteAsync(data, ct).ConfigureAwait(false);
break;
default: // Raw
await stream.WriteAsync(data, ct).ConfigureAwait(false);
break;
}
await stream.FlushAsync(ct).ConfigureAwait(false);
}
/// Reads bytes until the delimiter is encountered.
private static async Task ReadTextLineAsync(
Stream stream, string delimiter, int bufferSize, CancellationToken ct)
{
// We read byte-by-byte into a buffer, scanning for the delimiter.
// For high-throughput, a PipeReader would be better, but this is simple and correct.
var buffer = new MemoryStream(256);
var delimBytes = Encoding.UTF8.GetBytes(delimiter);
var matchPos = 0;
var singleByte = new byte[1];
while (true)
{
var read = await stream.ReadAsync(singleByte, ct).ConfigureAwait(false);
if (read == 0)
return buffer.Position > 0 ? buffer.ToArray() : null;
buffer.WriteByte(singleByte[0]);
if (singleByte[0] == delimBytes[matchPos])
{
matchPos++;
if (matchPos == delimBytes.Length)
{
// Remove delimiter from the result
var result = buffer.ToArray();
return result.AsSpan(0, result.Length - delimBytes.Length).ToArray();
}
}
else
{
matchPos = singleByte[0] == delimBytes[0] ? 1 : 0;
}
}
}
/// Reads a 4-byte big-endian length header, then exactly that many bytes.
private static async Task ReadLengthPrefixedAsync(Stream stream, CancellationToken ct)
{
var header = new byte[4];
var headerRead = await ReadExactAsync(stream, header, ct).ConfigureAwait(false);
if (!headerRead) return null;
var length = BinaryPrimitives.ReadInt32BigEndian(header);
if (length <= 0) return [];
var payload = new byte[length];
var payloadRead = await ReadExactAsync(stream, payload, ct).ConfigureAwait(false);
if (!payloadRead) return null;
return payload;
}
/// Reads a single chunk of available data (raw mode).
private static async Task ReadRawAsync(Stream stream, int bufferSize, CancellationToken ct)
{
var buffer = new byte[bufferSize];
var read = await stream.ReadAsync(buffer, ct).ConfigureAwait(false);
if (read == 0) return null;
return buffer.AsSpan(0, read).ToArray();
}
/// Reads exactly buffer.Length bytes or returns false on EOF.
private static async Task ReadExactAsync(Stream stream, byte[] buffer, CancellationToken ct)
{
var offset = 0;
while (offset < buffer.Length)
{
var read = await stream.ReadAsync(buffer.AsMemory(offset), ct).ConfigureAwait(false);
if (read == 0) return false;
offset += read;
}
return true;
}
}
Path: redb-route/redb.Route.Tcp/TcpComponent.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.Tcp/TcpComponent.cs
----
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Extensions;
using redb.Route.Core;
namespace redb.Route.Tcp;
///
/// TCP component. Scheme: "tcp".
/// Producer: TCP client — connects to remote host and sends data.
/// Consumer: TCP server — listens on a port, accepts connections, receives data.
/// URI format: tcp:host:port?textLine=true&delimiter=\n&inOut=true
///
public class TcpComponent : ComponentBase
{
///
public override string Scheme => "tcp";
///
public override IEndpoint CreateEndpoint(EndpointUri uri)
{
ArgumentNullException.ThrowIfNull(uri);
var options = new TcpEndpointOptions();
// Parse host:port from URI path
ParseHostPort(uri.Path, options);
options.BindFromUri(uri.RawParameters);
// Named ConnectionFactory keeps the TLS certificate password out of the route URI.
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);
}
options.Validate();
return new TcpEndpoint(uri, this, options);
}
///
/// Parses "host:port" from the URI path segment.
/// Path format: "/host:port" or "host:port".
///
internal static void ParseHostPort(string path, TcpEndpointOptions options)
{
var clean = path.TrimStart('/');
var colonIdx = clean.LastIndexOf(':');
if (colonIdx > 0 && int.TryParse(clean[(colonIdx + 1)..], out var port))
{
options.Host = clean[..colonIdx];
options.Port = port;
}
else
{
options.Host = clean;
}
}
}
///
/// TCP endpoint. Creates either a producer (TCP client) or consumer (TCP server).
///
public class TcpEndpoint : EndpointBase
{
/// Creates a TCP endpoint.
public TcpEndpoint(EndpointUri uri, TcpComponent component, TcpEndpointOptions options)
: base(uri, component, options)
{
}
/// The endpoint options for external access.
internal TcpEndpointOptions EndpointOptions => Options;
///
public override IProducer CreateProducer()
{
return new TcpProducer(this, Options);
}
///
public override IConsumer CreateConsumer(IProcessor processor)
{
ArgumentNullException.ThrowIfNull(processor);
return new TcpConsumer(this, processor, Options);
}
}
Path: redb-route/redb.Route.Tcp/TcpConnectionFactory.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.Tcp/TcpConnectionFactory.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
namespace redb.Route.Tcp;
///
/// Named connection factory for TCP. Register it in the route registry and reference it by name
/// from the endpoint URI (connectionFactory=my-tcp) 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.
///
///
public sealed class TcpConnectionFactory
{
/// 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; }
/// Expected TLS target host name (SNI / certificate validation).
public string? SslTargetHost { get; set; }
/// Producer only: accept any server certificate, including a self-signed one.
public bool TrustAllCertificates { get; set; }
/// Producer only: PFX client certificate for a server that requires mTLS.
public string? ClientCertPath { get; set; }
/// Password for .
[Sensitive]
public string? ClientCertPassword { 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(TcpEndpointOptions 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.SslTargetHost)))
options.SslTargetHost = SslTargetHost;
if (!supplied.ContainsKey(nameof(options.TrustAllCertificates)))
options.TrustAllCertificates = TrustAllCertificates;
if (!supplied.ContainsKey(nameof(options.ClientCertPath)))
options.ClientCertPath = ClientCertPath;
if (!supplied.ContainsKey(nameof(options.ClientCertPassword)))
options.ClientCertPassword = ClientCertPassword;
if (!supplied.ContainsKey(nameof(options.ConnectTimeout)))
options.ConnectTimeout = ConnectTimeout;
}
}
Path: redb-route/redb.Route.Tcp/TcpConsumer.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.Tcp/TcpConsumer.cs
----
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Telemetry;
namespace redb.Route.Tcp;
///
/// TCP consumer. Embedded TCP server that accepts connections, reads framed messages,
/// and dispatches them into the route processor pipeline.
/// Supports configurable framing (Raw, TextLine, LengthPrefixed), TLS,
/// max connections, and InOut exchange patterns for synchronous response.
///
public sealed class TcpConsumer : IConsumer
{
private readonly TcpEndpoint _endpoint;
public IEndpoint Endpoint => _endpoint;
private readonly IProcessor _processor;
private readonly TcpEndpointOptions _options;
private readonly Encoding _encoding;
private TcpListener? _listener;
private CancellationTokenSource? _cts;
private Task? _acceptLoopTask;
private long _processedCount;
private readonly ConcurrentDictionary _clients = new();
private readonly ConcurrentDictionary _clientTasks = new();
private readonly SemaphoreSlim? _connectionSemaphore;
private readonly InflightDrainGuard _drain = new();
private X509Certificate2? _serverCertificate;
private ILogger? _logger;
/// Creates a TCP consumer.
public TcpConsumer(TcpEndpoint endpoint, IProcessor processor, TcpEndpointOptions 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 clients.
public int ActiveConnections => _clients.Count;
/// The local endpoint the server is listening on. Available after Start().
public IPEndPoint? LocalEndPoint => _listener?.LocalEndpoint as IPEndPoint;
///
/// Turns the host of the endpoint URI into an address to bind. Plain IPAddress.Parse
/// threw a bare FormatException on any name — including localhost, which the
/// producer side of this very connector resolves without complaint, so the same URI worked as
/// a client and crashed as a server.
///
/// A binds one address, so localhost means the IPv4 loopback
/// here; a client that dials [::1] explicitly needs ::1 in the URI. (The shared
/// HTTP host binds both, because Kestrel opens two listeners for it.) This helper is
/// deliberately a local twin of the one in SharedHttpServerManager: a raw TCP transport
/// should not take a dependency on the HTTP hosting package for fifteen lines.
///
///
private static IPAddress ResolveBindAddress(string host)
{
if (IPAddress.TryParse(host, out var parsed))
return parsed;
if (string.Equals(host, "localhost", StringComparison.OrdinalIgnoreCase))
return IPAddress.Loopback;
if (string.IsNullOrWhiteSpace(host) || host == "*" || host == "+")
return IPAddress.Any;
try
{
var resolved = Dns.GetHostAddresses(host);
if (resolved.Length > 0)
return resolved[0];
}
catch (Exception ex) when (ex is SocketException or ArgumentException)
{
throw new ArgumentException(
$"Cannot bind a TCP listener to host '{host}': it is neither an IP address nor a resolvable name. " +
"Use an address the machine owns, 0.0.0.0 for every interface, or localhost.", ex);
}
throw new ArgumentException(
$"Cannot bind a TCP listener to host '{host}': the name resolved to no addresses.");
}
///
/// Loads the TLS certificate the server presents. The path arrives on the endpoint or through a
/// named , which applies it to the options before validation;
/// nothing means the listener must not open at all.
///
private X509Certificate2 LoadServerCertificate()
{
if (string.IsNullOrEmpty(_options.SslCertPath))
throw new InvalidOperationException(
$"TCP listener on {_options.Host}:{_options.Port} is configured with ssl=true but no server " +
"certificate. Set sslCertPath (and sslCertPassword), or use a named connectionFactory that " +
"carries them. Refusing to start, because every accepted connection would fail the handshake.");
try
{
return X509CertificateLoader.LoadPkcs12FromFile(_options.SslCertPath, _options.SslCertPassword);
}
catch (Exception ex) when (ex is CryptographicException or IOException or UnauthorizedAccessException)
{
// A bad path or a wrong password is a startup error too, not something to rediscover on
// every connection.
throw new InvalidOperationException(
$"TCP listener on {_options.Host}:{_options.Port} could not load its server certificate from " +
$"'{_options.SslCertPath}': {ex.Message}", ex);
}
}
///
public Task Start(CancellationToken ct = default)
{
// The certificate is resolved and loaded ONCE, before the socket opens. It used to be read
// from disk on every accepted connection through a null-forgiven SslCertPath!, so a missing
// certificate surfaced as an ArgumentNullException per connection — a type this consumer's
// catch list does not even cover — while the port sat there accepting.
_serverCertificate = _options.Ssl ? LoadServerCertificate() : null;
try
{
var ip = ResolveBindAddress(_options.Host);
_listener = new TcpListener(ip, _options.Port);
_listener.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
_listener.Start(_options.Backlog);
_cts = new CancellationTokenSource();
_drain.Start(ct);
_acceptLoopTask = AcceptLoopAsync(_cts.Token);
}
catch (Exception ex)
{
_logger?.LogError(ex, "TCP consumer Start failed on {Host}:{Port}", _options.Host, _options.Port);
_listener?.Stop(); _listener = null;
_cts?.Dispose(); _cts = null;
_drain.Dispose();
_serverCertificate?.Dispose(); _serverCertificate = null;
throw;
}
_logger ??= (_endpoint.Component as ComponentBase)?.Logger;
_logger?.LogInformation("TCP consumer started: {Host}:{Port}", _options.Host, _options.Port);
return Task.CompletedTask;
}
///
public async Task Stop(CancellationToken ct = default)
{
// Step 1: stop accepting new connections
_cts?.Cancel();
_listener?.Stop();
if (_acceptLoopTask is not null)
{
try { await _acceptLoopTask.ConfigureAwait(false); }
catch (OperationCanceledException) { }
}
// Step 2: drain in-flight message processing
await _drain.DrainAsync(ct, _logger, $"tcp:{_options.Host}:{_options.Port}").ConfigureAwait(false);
// Step 3: disconnect clients to unblock read loops
foreach (var (id, client) in _clients)
{
client.Dispose();
_clients.TryRemove(id, out _);
}
// Step 4: await all client handler tasks
if (!_clientTasks.IsEmpty)
{
try { await Task.WhenAll(_clientTasks.Values).ConfigureAwait(false); }
catch { /* errors already logged per-client */ }
}
// Step 5: cleanup
_listener = null;
_cts?.Dispose();
_cts = null;
_drain.Dispose();
// Loaded once at Start, so it is released once here — it used to be a per-connection
// X509Certificate2 that nobody disposed at all.
_serverCertificate?.Dispose();
_serverCertificate = null;
_logger ??= (_endpoint.Component as ComponentBase)?.Logger;
_logger?.LogInformation("TCP consumer stopped: {Host}:{Port}", _options.Host, _options.Port);
}
private async Task AcceptLoopAsync(CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
TcpClient client;
try
{
client = await _listener!.AcceptTcpClientAsync(ct).ConfigureAwait(false);
}
catch (OperationCanceledException) { break; }
catch (ObjectDisposedException) { break; }
catch (SocketException) when (ct.IsCancellationRequested) { break; }
ConfigureClient(client);
var connectionId = Guid.NewGuid().ToString("N");
_clients[connectionId] = client;
// Handle each client in a tracked task
var task = HandleClientAsync(client, connectionId, ct);
_clientTasks[connectionId] = task;
_ = task.ContinueWith(_ => _clientTasks.TryRemove(connectionId, out _), TaskContinuationOptions.ExecuteSynchronously);
}
}
private async Task HandleClientAsync(TcpClient client, string connectionId, CancellationToken ct)
{
if (_connectionSemaphore is not null)
await _connectionSemaphore.WaitAsync(ct).ConfigureAwait(false);
try
{
Stream stream = client.GetStream();
if (_serverCertificate is not null)
{
var sslStream = new SslStream(stream, leaveInnerStreamOpen: false);
await sslStream.AuthenticateAsServerAsync(_serverCertificate).ConfigureAwait(false);
stream = sslStream;
}
var remoteEp = client.Client.RemoteEndPoint?.ToString() ?? "unknown";
var localEp = client.Client.LocalEndPoint?.ToString() ?? "unknown";
while (!ct.IsCancellationRequested && client.Connected)
{
byte[]? data;
try
{
data = await TcpCodec.ReadMessageAsync(
stream, _options.Framing, _options.Delimiter, _options.ReadChunkSize, ct)
.ConfigureAwait(false);
}
catch (OperationCanceledException) { break; }
catch (IOException) { break; }
if (data is null) break; // Connection closed
var exchange = BuildExchange(data, connectionId, remoteEp, localEp);
// A framed message carries no trace context: its span is a root, never a child of the connection's activity.
using var span = RouteTelemetryExtensions.StartConsumerSpan