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. [![NuGet](https://img.shields.io/nuget/v/redb.Route.Tcp?label=NuGet&color=blue)](https://www.nuget.org/packages/redb.Route.Tcp) [![License: Apache 2.0](https://img.shields.io/badge/license-Apache%202.0-blue)](../../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( (_endpoint.Component as ComponentBase)?.Context, $"tcp {_options.Host}:{_options.Port} receive", ActivityKind.Consumer, "network.transport", "tcp", _endpoint.Uri.NormalizedKey, null, static (_, _) => null, operation: "receive"); _drain.Increment(); try { try { await _processor.Process(exchange, _drain.ProcessingToken).ConfigureAwait(false); } catch (Exception ex) { _logger?.LogError(ex, "TCP message processing failed: remote={RemoteEndpoint}", remoteEp); 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: write response back (use drain-safe token so response completes during drain) if (_options.InOut && exchange.Exception is null) { var responseData = ResolveResponseBody(exchange); if (responseData is not null) { await TcpCodec.WriteMessageAsync( stream, responseData, _options.Framing, _options.Delimiter, _encoding, _drain.ProcessingToken) .ConfigureAwait(false); } } Interlocked.Increment(ref _processedCount); await exchange.DisposeAsync().ConfigureAwait(false); } finally { _drain.Decrement(); } } } catch (OperationCanceledException) { } catch (IOException) { } catch (SocketException) { } finally { _connectionSemaphore?.Release(); client.Dispose(); _clients.TryRemove(connectionId, out _); } } private IExchange BuildExchange(byte[] data, string connectionId, string remoteEp, string localEp) { // For TextLine, decode to string; otherwise keep as byte[] object body = _options.Framing == TcpFraming.TextLine ? _encoding.GetString(data) : data; var message = new Message(body); message.Headers[TcpHeaders.RemoteAddress] = remoteEp; message.Headers[TcpHeaders.LocalAddress] = localEp; message.Headers[TcpHeaders.ConnectionId] = connectionId; message.Headers[TcpHeaders.Framing] = _options.Framing.ToString(); message.Headers[TcpHeaders.ByteCount] = data.Length.ToString(); message.Headers[TcpHeaders.Ssl] = _options.Ssl.ToString(); var exchange = Exchange.Create(message, _endpoint.ScopeFactory); exchange.Pattern = _options.InOut ? ExchangePattern.InOut : ExchangePattern.InOnly; return exchange; } private byte[]? ResolveResponseBody(IExchange exchange) { var outBody = exchange.Out?.Body; if (outBody is null) return null; return outBody switch { byte[] bytes => bytes, string str => _encoding.GetBytes(str), _ => _encoding.GetBytes(outBody.ToString()!) }; } private void ConfigureClient(TcpClient client) { client.NoDelay = _options.NoDelay; _options.ApplyBufferSizes(client); client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, _options.KeepAlive); } } Path: redb-route/redb.Route.Tcp/TcpEndpointOptions.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/TcpEndpointOptions.cs ---- using redb.Route.Core; namespace redb.Route.Tcp; /// /// Options for the TCP endpoint. Shared by both producer and consumer. /// Use URI parameters to configure: tcp:host:port?textLine=true&delimiter=\n /// public class TcpEndpointOptions : EndpointOptions { // ── Connection ────────────────────────────────────── /// Remote host (producer) or bind host (consumer). Parsed from URI path. public string Host { get; set; } = "0.0.0.0"; /// Remote port (producer) or bind port (consumer). Parsed from URI path. public int Port { get; set; } // ── Framing ───────────────────────────────────────── /// Message framing mode. Default: Raw. public TcpFraming Framing { get; set; } = TcpFraming.Raw; /// /// Shortcut: set to true to use TextLine framing. /// Equivalent to Framing=TextLine. Default: false. /// public bool TextLine { get; set; } /// /// Shortcut: set to true to use LengthPrefixed framing. /// Equivalent to Framing=LengthPrefixed. Default: false. /// public bool LengthPrefixed { get; set; } /// /// Delimiter for TextLine framing. Default: "\n". /// Supports common escape sequences: \n, \r\n, \r. /// public string Delimiter { get; set; } = "\n"; /// Text encoding name for TextLine framing and string body conversion. Default: utf-8. public string Encoding { get; set; } = "utf-8"; // ── Socket options ────────────────────────────────── /// TCP keep-alive. Default: true. public bool KeepAlive { get; set; } = true; /// Disable Nagle's algorithm for low-latency. Default: true. public bool NoDelay { get; set; } = true; /// /// Socket receive buffer (SO_RCVBUF) in bytes. Default 0: the system sizes the buffer and grows it with the /// traffic. A fixed size switches that tuning off on Linux; 8192 there, on loopback, let a 64 KiB frame through /// in about three seconds, because the window stayed below one segment. The Raw and TextLine reads use the same /// value as their chunk size, or when it is 0. /// public int ReceiveBufferSize { get; set; } /// Socket send buffer (SO_SNDBUF) in bytes. Default 0: the system sizes the buffer. public int SendBufferSize { get; set; } /// The chunk size of a Raw or TextLine read when is 0. public const int DefaultReadChunkSize = 8192; /// The chunk size the Raw and TextLine reads use. internal int ReadChunkSize => ReceiveBufferSize > 0 ? ReceiveBufferSize : DefaultReadChunkSize; /// Applies the buffer sizes that were set; a 0 leaves the system's own size in place. internal void ApplyBufferSizes(System.Net.Sockets.TcpClient client) { if (ReceiveBufferSize > 0) client.ReceiveBufferSize = ReceiveBufferSize; if (SendBufferSize > 0) client.SendBufferSize = SendBufferSize; } // ── 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; } // ── Consumer (server) ─────────────────────────────── /// Listen backlog for the TCP server. Default: 128. public int Backlog { get; set; } = 128; /// Maximum concurrent client connections. 0 = unlimited. Default: 0. public int MaxConnections { get; set; } /// /// If true, the consumer returns the exchange Out body as the TCP response (InOut pattern). /// If false, processes the message without responding (InOnly). Default: false. /// public bool InOut { get; set; } // ── TLS ───────────────────────────────────────────── /// Enable TLS encryption. Default: false. public bool Ssl { get; set; } /// Path to PFX certificate file for TLS (consumer). Required when ssl=true for consumer. public string? SslCertPath { get; set; } /// Password for the PFX certificate. [Sensitive] public string? SslCertPassword { 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(TcpConnectionFactory))] public string? ConnectionFactory { get; set; } /// /// Target host name for TLS server certificate validation (producer). /// If not set, uses the Host value. /// public string? SslTargetHost { get; set; } /// /// Producer only: accept any server certificate, including a self-signed one. Off by default /// and never implied by another option — a staging server behind a self-signed certificate is /// a real need, but switching validation off has to be a decision someone wrote down. /// public bool TrustAllCertificates { get; set; } /// /// Producer only: PFX client certificate presented to a server that requires mTLS. Distinct /// from , which is the certificate a consumer serves; naming follows /// the gRPC connector's clientCertPath. /// public string? ClientCertPath { get; set; } /// Password for . [Sensitive] public string? ClientCertPassword { 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 (0: the system's own size)."); if (SendBufferSize < 0) throw new ArgumentException("SendBufferSize must be >= 0 (0: the system's own size)."); 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 (Backlog <= 0) throw new ArgumentException("Backlog must be > 0."); if (MaxConnections < 0) throw new ArgumentException("MaxConnections must be >= 0."); // Resolve framing shortcuts if (TextLine) Framing = TcpFraming.TextLine; if (LengthPrefixed) Framing = TcpFraming.LengthPrefixed; if (TextLine && LengthPrefixed) throw new ArgumentException("Cannot enable both TextLine and LengthPrefixed framing."); } } Path: redb-route/redb.Route.Tcp/TcpEnums.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/TcpEnums.cs ---- namespace redb.Route.Tcp; /// /// Message framing mode for TCP communication. /// Determines how messages are delimited on the wire. /// public enum TcpFraming { /// Raw mode: entire read buffer is one message. No framing applied. Raw, /// Text-line mode: messages delimited by a configurable delimiter (default: newline). TextLine, /// Length-prefixed mode: 4-byte big-endian length header followed by payload bytes. LengthPrefixed } Path: redb-route/redb.Route.Tcp/TcpHeaders.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/TcpHeaders.cs ---- namespace redb.Route.Tcp; /// /// Well-known header keys for TCP exchanges. /// public static class TcpHeaders { /// Common prefix for all TCP component headers. public const string Prefix = "redbTcp."; /// Remote endpoint address (IP:port) of the connected peer. public const string RemoteAddress = "redbTcp.RemoteAddress"; /// Local endpoint address (IP:port) of the local socket. public const string LocalAddress = "redbTcp.LocalAddress"; /// Connection ID (unique per accepted client connection on consumer). public const string ConnectionId = "redbTcp.ConnectionId"; /// The framing mode used for this exchange. public const string Framing = "redbTcp.Framing"; /// Whether TLS is active on this connection. public const string Ssl = "redbTcp.Ssl"; /// Number of bytes in the raw message before decoding. public const string ByteCount = "redbTcp.ByteCount"; } Path: redb-route/redb.Route.Tcp/TcpProducer.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/TcpProducer.cs ---- 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 producer. Connects to a remote TCP server and sends exchange body data. /// Supports Raw, TextLine, and LengthPrefixed framing. /// In InOut mode, waits for a response and populates the exchange Out message. /// public sealed class TcpProducer : ConnectableProducer { private readonly TcpEndpoint _endpoint; private readonly TcpEndpointOptions _options; private readonly Encoding _encoding; private TcpClient? _client; private Stream? _stream; private X509Certificate2? _clientCertificate; private readonly SemaphoreSlim _sendLock = new(1, 1); /// Creates a TCP producer. public TcpProducer(TcpEndpoint endpoint, TcpEndpointOptions 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; /// protected override string ProducerName => $"tcp:{_options.Host}:{_options.Port}"; /// protected override async Task ConnectAsync(CancellationToken ct) { // Loaded once here rather than per connection, so a reconnect loop does not re-read the // PFX from disk and a bad path or password is a start-time error. _clientCertificate ??= LoadClientCertificate(); await ConnectTcpAsync(ct).ConfigureAwait(false); } /// protected override async Task DisconnectAsync(CancellationToken ct) { if (_stream is not null) { await _stream.DisposeAsync().ConfigureAwait(false); _stream = null; } _client?.Dispose(); _client = null; _clientCertificate?.Dispose(); _clientCertificate = null; } /// /// Loads the client certificate presented to a server that requires mTLS, if one is configured. /// private X509Certificate2? LoadClientCertificate() { if (string.IsNullOrEmpty(_options.ClientCertPath)) return null; try { return X509CertificateLoader.LoadPkcs12FromFile(_options.ClientCertPath, _options.ClientCertPassword); } catch (Exception ex) when (ex is CryptographicException or IOException or UnauthorizedAccessException) { throw new InvalidOperationException( $"TCP producer for {_options.Host}:{_options.Port} could not load its client certificate from " + $"'{_options.ClientCertPath}': {ex.Message}", ex); } } /// public override async Task Process(IExchange exchange, CancellationToken ct = default) { EnsureStarted(); using var activity = RouteTelemetryExtensions.StartTransportSpan( (_endpoint.Component as ComponentBase)?.Context, $"tcp {_options.Host}:{_options.Port}", ActivityKind.Client, "network.transport", "tcp", _endpoint.Uri.NormalizedKey, destination: $"{_options.Host}:{_options.Port}"); try { await SendMessageAsync(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; } } private async Task SendMessageAsync(IExchange exchange, CancellationToken ct) { // Reconnect if needed if (_client is not { Connected: true }) { if (_options.Reconnect) await ReconnectAsync(ct).ConfigureAwait(false); else throw new InvalidOperationException("TCP connection lost and reconnect is disabled."); } var data = ResolveBody(exchange); await _sendLock.WaitAsync(ct).ConfigureAwait(false); try { // Transparent retry on stale pooled connection. // Socket.Connected reflects state of the *last* I/O, so a connection torn // down between Process() calls (server timeout, KeepAlive probe, firewall RST) // is only detected when the next Write throws IOException/SocketException. // Same pattern as HttpClient connection pool revalidation and SqlConnection // pool validation: treat the first failure on a cached connection as expected, // reconnect once silently, retry. If the second attempt also fails, bubble up. try { await SendAndOptionallyReadAsync(exchange, data, ct).ConfigureAwait(false); } catch (Exception ex) when (_options.Reconnect && IsStaleConnectionError(ex)) { Logger?.LogDebug(ex, "TCP stale pooled connection to {Host}:{Port} detected; reconnecting and retrying once", _options.Host, _options.Port); await ReconnectAsync(ct).ConfigureAwait(false); await SendAndOptionallyReadAsync(exchange, data, ct).ConfigureAwait(false); } } finally { _sendLock.Release(); } SetExchangeHeaders(exchange); } private async Task SendAndOptionallyReadAsync(IExchange exchange, byte[] data, CancellationToken ct) { await TcpCodec.WriteMessageAsync(_stream!, data, _options.Framing, _options.Delimiter, _encoding, ct) .ConfigureAwait(false); // Ownership audit: MessagesOut is the core's (ToProcessor / the template); the // connector records only the wire bytes the core cannot see. _endpoint.RecordBytesOut(data.Length); // InOut: read response if (_options.InOut) { var response = await TcpCodec.ReadMessageAsync( _stream!, _options.Framing, _options.Delimiter, _options.ReadChunkSize, ct) .ConfigureAwait(false); if (response is not null) { _endpoint.RecordBytesIn(response.Length); var outMsg = new Message(_options.Framing == TcpFraming.TextLine ? _encoding.GetString(response) : (object)response); outMsg.Headers[TcpHeaders.ByteCount] = response.Length.ToString(); exchange.Out = outMsg; } } } private static bool IsStaleConnectionError(Exception ex) { // Unwrap IOException → SocketException; recognise the classic stale-pool codes. var socketEx = ex as SocketException ?? ex.InnerException as SocketException; if (socketEx is not null) { return socketEx.SocketErrorCode is SocketError.ConnectionAborted // 10053 WSAECONNABORTED or SocketError.ConnectionReset // 10054 WSAECONNRESET or SocketError.NotConnected // 10057 WSAENOTCONN or SocketError.Shutdown // 10058 WSAESHUTDOWN or SocketError.HostUnreachable or SocketError.NetworkReset or SocketError.TimedOut; } return ex is IOException or ObjectDisposedException; } private byte[] ResolveBody(IExchange exchange) { var body = exchange.In.Body; return body switch { byte[] bytes => bytes, Stream s => ReadStream(s), string str => _encoding.GetBytes(str), null => [], _ => _encoding.GetBytes(BodyText.Of(body)) }; } 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 void SetExchangeHeaders(IExchange exchange) { if (_client?.Client.RemoteEndPoint is IPEndPoint remote) exchange.In.Headers[TcpHeaders.RemoteAddress] = remote.ToString(); if (_client?.Client.LocalEndPoint is IPEndPoint local) exchange.In.Headers[TcpHeaders.LocalAddress] = local.ToString(); exchange.In.Headers[TcpHeaders.Framing] = _options.Framing.ToString(); exchange.In.Headers[TcpHeaders.Ssl] = _options.Ssl.ToString(); } private async Task ConnectTcpAsync(CancellationToken ct) { _client = new TcpClient { NoDelay = _options.NoDelay, }; _options.ApplyBufferSizes(_client); _client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, _options.KeepAlive); using var cts = _options.ConnectTimeout > 0 ? CancellationTokenSource.CreateLinkedTokenSource(ct) : null; cts?.CancelAfter(_options.ConnectTimeout); await _client.ConnectAsync(_options.Host, _options.Port, cts?.Token ?? ct).ConfigureAwait(false); Stream netStream = _client.GetStream(); if (_options.Ssl) { // Explicit, never implied: without trustAllCertificates the default chain validation // applies, which is what makes a self-signed staging server unreachable by design. var sslStream = _options.TrustAllCertificates ? new SslStream(netStream, leaveInnerStreamOpen: false, (_, _, _, _) => true) : new SslStream(netStream, leaveInnerStreamOpen: false); var authOptions = new SslClientAuthenticationOptions { TargetHost = _options.SslTargetHost ?? _options.Host, }; // Loaded once in Start, so a reconnect does not re-read the PFX from disk. if (_clientCertificate is not null) authOptions.ClientCertificates = [_clientCertificate]; await sslStream.AuthenticateAsClientAsync(authOptions, ct).ConfigureAwait(false); netStream = sslStream; } _stream = netStream; } private async Task ReconnectAsync(CancellationToken ct) { var attempts = 0; while (true) { attempts++; try { if (_stream is not null) await _stream.DisposeAsync().ConfigureAwait(false); _client?.Dispose(); await ConnectTcpAsync(ct).ConfigureAwait(false); return; } catch when (_options.MaxReconnectAttempts > 0 && attempts >= _options.MaxReconnectAttempts) { Logger?.LogError("TCP reconnect to {Host}:{Port} exhausted {Max} attempts", _options.Host, _options.Port, _options.MaxReconnectAttempts); throw; } catch (Exception ex) { Logger?.LogWarning(ex, "TCP 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.Tcp/redb.Route.Tcp.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.Tcp/redb.Route.Tcp.csproj ---- redb.Route.Tcp TCP transport for redb.Route ESB framework. Provides socket-based producer (client) and consumer (server) with text-line, length-prefixed, and raw framing modes, TLS, and InOut patterns. esb;messaging;tcp;socket;netty;server;client;redb README.md