Bundle: redb-route / tests/redb.Route.Tests.Tcp (tests.redb.Route.Tests.Tcp.txt), 16 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/tests/redb.Route.Tests.Tcp/ServiceCollectionExtensionsTests.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/tests/redb.Route.Tests.Tcp/ServiceCollectionExtensionsTests.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Route.Core; using redb.Route.Extensions; using redb.Route.Abstractions; using redb.Route.Tcp; namespace redb.Route.Tests.Tcp; public class ServiceCollectionExtensionsTests { [Fact] public void AddRedbRouteTcp_RegistersTcpComponent() { var services = new ServiceCollection(); services.AddRedbRouteTcp(); var sp = services.BuildServiceProvider(); var component = sp.GetService(); component.Should().NotBeNull(); component!.Scheme.Should().Be("tcp"); } [Fact] public void AddRedbRouteTcp_ComponentIsSingleton() { var services = new ServiceCollection(); services.AddRedbRouteTcp(); var sp = services.BuildServiceProvider(); var first = sp.GetService(); var second = sp.GetService(); first.Should().BeSameAs(second); } [Fact] public async Task AddRedbRouteTcp_RegistersWithRouteContext() { var services = new ServiceCollection(); services.AddRedbRouteTcp(); await using var sp = services.BuildServiceProvider(); await using var context = new RouteContext(); // The hook RouteHostedService applies at startup foreach (var configurator in sp.GetServices()) configurator.Configure(context); context.HasComponent("tcp").Should().BeTrue(); } [Fact] public void AddRedbRouteTcp_ReturnsServiceCollection() { var services = new ServiceCollection(); var result = services.AddRedbRouteTcp(); result.Should().BeSameAs(services); } } Path: redb-route/tests/redb.Route.Tests.Tcp/TcpBuilderTests.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/tests/redb.Route.Tests.Tcp/TcpBuilderTests.cs ---- using redb.Route.Core; using redb.Route.Tcp; namespace redb.Route.Tests.Tcp; public class TcpBuilderTests { // ── Factory ───────────────────────────────────────────────────── [Fact] public void Listen_StartsWithTcpScheme() { var uri = TcpDsl.Listen("0.0.0.0:9000").Build(); uri.Should().StartWith("tcp:0.0.0.0:9000"); } [Fact] public void Connect_StartsWithTcpScheme() { var uri = TcpDsl.Connect("192.168.1.10:9000").Build(); uri.Should().StartWith("tcp:192.168.1.10:9000"); } [Fact] public void NullHostPort_Throws() { var act = () => TcpDsl.Listen(null!); act.Should().Throw(); } [Fact] public void EmptyHostPort_Throws() { var act = () => TcpDsl.Connect(""); act.Should().Throw(); } // ── Framing ───────────────────────────────────────────────────── [Fact] public void TextLine_SetsParam() { var uri = TcpDsl.Listen("0.0.0.0:9000").TextLine().Build(); uri.Should().Contain("textLine=true"); } [Fact] public void LengthPrefixed_SetsParam() { var uri = TcpDsl.Connect("h:9000").LengthPrefixed().Build(); uri.Should().Contain("lengthPrefixed=true"); } [Fact] public void Delimiter_SetsParam() { var uri = TcpDsl.Listen("h:9000").Delimiter("|").Build(); uri.Should().Contain("delimiter="); } [Fact] public void Encoding_SetsParam() { var uri = TcpDsl.Listen("h:9000").Encoding("utf-16").Build(); uri.Should().Contain("encoding=utf-16"); } // ── Socket ────────────────────────────────────────────────────── [Fact] public void KeepAlive_SetsParam() { var uri = TcpDsl.Connect("h:9000").KeepAlive().Build(); uri.Should().Contain("keepAlive=true"); } [Fact] public void NoDelay_SetsParam() { var uri = TcpDsl.Connect("h:9000").NoDelay().Build(); uri.Should().Contain("noDelay=true"); } [Fact] public void ReceiveBufferSize_SetsParam() { var uri = TcpDsl.Listen("h:9000").ReceiveBufferSize(65536).Build(); uri.Should().Contain("receiveBufferSize=65536"); } [Fact] public void SendBufferSize_SetsParam() { var uri = TcpDsl.Connect("h:9000").SendBufferSize(32768).Build(); uri.Should().Contain("sendBufferSize=32768"); } // ── Producer ──────────────────────────────────────────────────── [Fact] public void ConnectTimeout_SetsParam() { var uri = TcpDsl.Connect("h:9000").ConnectTimeout(5000).Build(); uri.Should().Contain("connectTimeout=5000"); } [Fact] public void Reconnect_SetsParams() { var uri = TcpDsl.Connect("h:9000").Reconnect(3000, 10).Build(); uri.Should().Contain("reconnect=true"); uri.Should().Contain("reconnectInterval=3000"); uri.Should().Contain("maxReconnectAttempts=10"); } // ── Consumer ──────────────────────────────────────────────────── [Fact] public void Backlog_SetsParam() { var uri = TcpDsl.Listen("0.0.0.0:9000").Backlog(256).Build(); uri.Should().Contain("backlog=256"); } [Fact] public void MaxConnections_SetsParam() { var uri = TcpDsl.Listen("0.0.0.0:9000").MaxConnections(100).Build(); uri.Should().Contain("maxConnections=100"); } [Fact] public void InOut_SetsParam() { var uri = TcpDsl.Listen("0.0.0.0:9000").InOut().Build(); uri.Should().Contain("inOut=true"); } // ── TLS ───────────────────────────────────────────────────────── [Fact] public void Ssl_SetsParam() { var uri = TcpDsl.Listen("0.0.0.0:9000").Ssl().Build(); uri.Should().Contain("ssl=true"); } [Fact] public void SslCertPath_SetsParam() { var uri = TcpDsl.Listen("0.0.0.0:9000").SslCertPath("/certs/cert.pfx").Build(); uri.Should().Contain("sslCertPath="); } [Fact] public void SslTargetHost_SetsParam() { var uri = TcpDsl.Connect("h:9000").SslTargetHost("api.example.com").Build(); uri.Should().Contain("sslTargetHost=api.example.com"); } // ── Conversion ────────────────────────────────────────────────── [Fact] public void ImplicitConversion_ReturnsUri() { string uri = TcpDsl.Listen("0.0.0.0:9000").TextLine().InOut(); uri.Should().StartWith("tcp:0.0.0.0:9000?"); } [Fact] public void ToString_ReturnsSameAsBuild() { var builder = TcpDsl.Connect("h:9000").TextLine().Reconnect(); builder.ToString().Should().Be(builder.Build()); } // ── Full chain ────────────────────────────────────────────────── [Fact] public void FullChain_Consumer_BuildsCorrectUri() { var uri = TcpDsl.Listen("0.0.0.0:9000") .TextLine() .KeepAlive() .NoDelay() .Backlog(256) .MaxConnections(100) .InOut() .Build(); uri.Should().StartWith("tcp:0.0.0.0:9000?"); uri.Should().Contain("textLine=true"); uri.Should().Contain("inOut=true"); } [Fact] public void FullChain_Producer_BuildsCorrectUri() { var uri = TcpDsl.Connect("192.168.1.10:9000") .TextLine() .ConnectTimeout(5000) .Reconnect(3000, 5) .Ssl() .SslTargetHost("api.example.com") .Build(); uri.Should().StartWith("tcp:192.168.1.10:9000?"); uri.Should().Contain("reconnect=true"); uri.Should().Contain("ssl=true"); } // ── Round-trip ────────────────────────────────────────────────── [Fact] public void RoundTrip_ParseAndReconstruct() { var original = TcpDsl.Listen("0.0.0.0:9000").TextLine().InOut().Build(); var parsed = EndpointUriParser.Parse(original); parsed.Scheme.Should().Be("tcp"); parsed.RawParameters["textLine"].Should().Be("true"); parsed.RawParameters["inOut"].Should().Be("true"); } } Path: redb-route/tests/redb.Route.Tests.Tcp/TcpCodecTests.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/tests/redb.Route.Tests.Tcp/TcpCodecTests.cs ---- using System.Buffers.Binary; using System.Net; using System.Net.Sockets; using System.Text; using redb.Route.Tcp; namespace redb.Route.Tests.Tcp; /// /// Unit tests for TcpCodec framing logic using in-memory streams. /// public class TcpCodecTests { // ── TextLine framing ── [Fact] public async Task TextLine_WriteAndRead_Roundtrip() { var ms = new MemoryStream(); var data = Encoding.UTF8.GetBytes("hello world"); await TcpCodec.WriteMessageAsync(ms, data, TcpFraming.TextLine, "\n", Encoding.UTF8, CancellationToken.None); ms.Position = 0; var result = await TcpCodec.ReadMessageAsync(ms, TcpFraming.TextLine, "\n", 8192, CancellationToken.None); result.Should().NotBeNull(); Encoding.UTF8.GetString(result!).Should().Be("hello world"); } [Fact] public async Task TextLine_CustomDelimiter_Roundtrip() { var ms = new MemoryStream(); var data = Encoding.UTF8.GetBytes("line1"); await TcpCodec.WriteMessageAsync(ms, data, TcpFraming.TextLine, "|", Encoding.UTF8, CancellationToken.None); ms.Position = 0; var result = await TcpCodec.ReadMessageAsync(ms, TcpFraming.TextLine, "|", 8192, CancellationToken.None); result.Should().NotBeNull(); Encoding.UTF8.GetString(result!).Should().Be("line1"); } [Fact] public async Task TextLine_MultipleMessages_ReadSequentially() { var ms = new MemoryStream(); await TcpCodec.WriteMessageAsync(ms, "msg1"u8.ToArray(), TcpFraming.TextLine, "\n", Encoding.UTF8, CancellationToken.None); await TcpCodec.WriteMessageAsync(ms, "msg2"u8.ToArray(), TcpFraming.TextLine, "\n", Encoding.UTF8, CancellationToken.None); ms.Position = 0; var r1 = await TcpCodec.ReadMessageAsync(ms, TcpFraming.TextLine, "\n", 8192, CancellationToken.None); var r2 = await TcpCodec.ReadMessageAsync(ms, TcpFraming.TextLine, "\n", 8192, CancellationToken.None); Encoding.UTF8.GetString(r1!).Should().Be("msg1"); Encoding.UTF8.GetString(r2!).Should().Be("msg2"); } [Fact] public async Task TextLine_EmptyStream_ReturnsNull() { var ms = new MemoryStream(); var result = await TcpCodec.ReadMessageAsync(ms, TcpFraming.TextLine, "\n", 8192, CancellationToken.None); result.Should().BeNull(); } [Fact] public async Task TextLine_CrLfDelimiter_Works() { var ms = new MemoryStream(); var data = Encoding.UTF8.GetBytes("hello"); await TcpCodec.WriteMessageAsync(ms, data, TcpFraming.TextLine, "\r\n", Encoding.UTF8, CancellationToken.None); ms.Position = 0; var result = await TcpCodec.ReadMessageAsync(ms, TcpFraming.TextLine, "\r\n", 8192, CancellationToken.None); Encoding.UTF8.GetString(result!).Should().Be("hello"); } // ── LengthPrefixed framing ── [Fact] public async Task LengthPrefixed_WriteAndRead_Roundtrip() { var ms = new MemoryStream(); var data = new byte[] { 1, 2, 3, 4, 5 }; await TcpCodec.WriteMessageAsync(ms, data, TcpFraming.LengthPrefixed, "\n", Encoding.UTF8, CancellationToken.None); ms.Position = 0; var result = await TcpCodec.ReadMessageAsync(ms, TcpFraming.LengthPrefixed, "\n", 8192, CancellationToken.None); result.Should().BeEquivalentTo(data); } [Fact] public async Task LengthPrefixed_VerifyHeader_BigEndian() { var ms = new MemoryStream(); var data = new byte[300]; new Random(42).NextBytes(data); await TcpCodec.WriteMessageAsync(ms, data, TcpFraming.LengthPrefixed, "\n", Encoding.UTF8, CancellationToken.None); ms.Position = 0; var header = new byte[4]; await ms.ReadExactlyAsync(header); var length = BinaryPrimitives.ReadInt32BigEndian(header); length.Should().Be(300); } [Fact] public async Task LengthPrefixed_EmptyPayload_Roundtrip() { var ms = new MemoryStream(); var data = Array.Empty(); await TcpCodec.WriteMessageAsync(ms, data, TcpFraming.LengthPrefixed, "\n", Encoding.UTF8, CancellationToken.None); ms.Position = 0; var result = await TcpCodec.ReadMessageAsync(ms, TcpFraming.LengthPrefixed, "\n", 8192, CancellationToken.None); result.Should().BeEmpty(); } [Fact] public async Task LengthPrefixed_MultipleMessages_ReadSequentially() { var ms = new MemoryStream(); var d1 = new byte[] { 10, 20, 30 }; var d2 = new byte[] { 40, 50 }; await TcpCodec.WriteMessageAsync(ms, d1, TcpFraming.LengthPrefixed, "\n", Encoding.UTF8, CancellationToken.None); await TcpCodec.WriteMessageAsync(ms, d2, TcpFraming.LengthPrefixed, "\n", Encoding.UTF8, CancellationToken.None); ms.Position = 0; var r1 = await TcpCodec.ReadMessageAsync(ms, TcpFraming.LengthPrefixed, "\n", 8192, CancellationToken.None); var r2 = await TcpCodec.ReadMessageAsync(ms, TcpFraming.LengthPrefixed, "\n", 8192, CancellationToken.None); r1.Should().BeEquivalentTo(d1); r2.Should().BeEquivalentTo(d2); } [Fact] public async Task LengthPrefixed_EmptyStream_ReturnsNull() { var ms = new MemoryStream(); var result = await TcpCodec.ReadMessageAsync(ms, TcpFraming.LengthPrefixed, "\n", 8192, CancellationToken.None); result.Should().BeNull(); } // ── Raw framing ── [Fact] public async Task Raw_WriteAndRead_Roundtrip() { var ms = new MemoryStream(); var data = new byte[] { 0xAA, 0xBB, 0xCC }; await TcpCodec.WriteMessageAsync(ms, data, TcpFraming.Raw, "\n", Encoding.UTF8, CancellationToken.None); ms.Position = 0; var result = await TcpCodec.ReadMessageAsync(ms, TcpFraming.Raw, "\n", 8192, CancellationToken.None); result.Should().BeEquivalentTo(data); } [Fact] public async Task Raw_EmptyStream_ReturnsNull() { var ms = new MemoryStream(); var result = await TcpCodec.ReadMessageAsync(ms, TcpFraming.Raw, "\n", 8192, CancellationToken.None); result.Should().BeNull(); } [Fact] public async Task Raw_LargePayload_ReadFully() { var data = new byte[4096]; new Random(42).NextBytes(data); var ms = new MemoryStream(data); var result = await TcpCodec.ReadMessageAsync(ms, TcpFraming.Raw, "\n", 8192, CancellationToken.None); result.Should().NotBeNull(); result!.Length.Should().BeGreaterThan(0); } } Path: redb-route/tests/redb.Route.Tests.Tcp/TcpComponentTests.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/tests/redb.Route.Tests.Tcp/TcpComponentTests.cs ---- using redb.Route.Abstractions; using redb.Route.Tcp; namespace redb.Route.Tests.Tcp; public class TcpComponentTests { [Fact] public void Scheme_ReturnsTcp() { var component = new TcpComponent(); component.Scheme.Should().Be("tcp"); } [Fact] public void CreateEndpoint_ValidUri_ReturnsTcpEndpoint() { var component = new TcpComponent(); var uri = new EndpointUri("tcp", "/localhost:9090", "tcp:localhost:9090", new Dictionary()); var endpoint = component.CreateEndpoint(uri); endpoint.Should().BeOfType(); endpoint.Uri.Should().BeSameAs(uri); endpoint.Component.Should().BeSameAs(component); } [Fact] public void CreateEndpoint_NullUri_Throws() { var component = new TcpComponent(); var act = () => component.CreateEndpoint(null!); act.Should().Throw(); } [Fact] public void CreateEndpoint_ParsesHostPort() { var component = new TcpComponent(); var uri = new EndpointUri("tcp", "/myhost:5555", "tcp:myhost:5555", new Dictionary()); var endpoint = (TcpEndpoint)component.CreateEndpoint(uri); endpoint.EndpointOptions.Host.Should().Be("myhost"); endpoint.EndpointOptions.Port.Should().Be(5555); } [Fact] public void CreateEndpoint_WithOptions_BindsCorrectly() { var component = new TcpComponent(); var parameters = new Dictionary { ["textLine"] = "true", ["delimiter"] = "|", ["keepAlive"] = "false", ["noDelay"] = "false", ["receiveBufferSize"] = "16384", ["sendBufferSize"] = "16384", ["connectTimeout"] = "5000" }; var uri = new EndpointUri("tcp", "/localhost:9090", "tcp:localhost:9090", parameters); var endpoint = (TcpEndpoint)component.CreateEndpoint(uri); endpoint.EndpointOptions.Framing.Should().Be(TcpFraming.TextLine); endpoint.EndpointOptions.Delimiter.Should().Be("|"); endpoint.EndpointOptions.KeepAlive.Should().BeFalse(); endpoint.EndpointOptions.NoDelay.Should().BeFalse(); endpoint.EndpointOptions.ReceiveBufferSize.Should().Be(16384); endpoint.EndpointOptions.SendBufferSize.Should().Be(16384); endpoint.EndpointOptions.ConnectTimeout.Should().Be(5000); } [Fact] public void CreateEndpoint_ConsumerOptions_BindsCorrectly() { var component = new TcpComponent(); var parameters = new Dictionary { ["backlog"] = "256", ["maxConnections"] = "100", ["inOut"] = "true" }; var uri = new EndpointUri("tcp", "/0.0.0.0:8080", "tcp:0.0.0.0:8080", parameters); var endpoint = (TcpEndpoint)component.CreateEndpoint(uri); endpoint.EndpointOptions.Backlog.Should().Be(256); endpoint.EndpointOptions.MaxConnections.Should().Be(100); endpoint.EndpointOptions.InOut.Should().BeTrue(); } [Fact] public void CreateEndpoint_LengthPrefixedFraming() { var component = new TcpComponent(); var parameters = new Dictionary { ["lengthPrefixed"] = "true" }; var uri = new EndpointUri("tcp", "/localhost:9090", "tcp:localhost:9090", parameters); var endpoint = (TcpEndpoint)component.CreateEndpoint(uri); endpoint.EndpointOptions.Framing.Should().Be(TcpFraming.LengthPrefixed); } [Fact] public void CreateEndpoint_FramingEnum_Direct() { var component = new TcpComponent(); var parameters = new Dictionary { ["framing"] = "TextLine" }; var uri = new EndpointUri("tcp", "/localhost:9090", "tcp:localhost:9090", parameters); var endpoint = (TcpEndpoint)component.CreateEndpoint(uri); endpoint.EndpointOptions.Framing.Should().Be(TcpFraming.TextLine); } [Fact] public void CreateEndpoint_ReconnectOptions() { var component = new TcpComponent(); var parameters = new Dictionary { ["reconnect"] = "true", ["reconnectInterval"] = "2000", ["maxReconnectAttempts"] = "5" }; var uri = new EndpointUri("tcp", "/localhost:9090", "tcp:localhost:9090", parameters); var endpoint = (TcpEndpoint)component.CreateEndpoint(uri); endpoint.EndpointOptions.Reconnect.Should().BeTrue(); endpoint.EndpointOptions.ReconnectInterval.Should().Be(2000); endpoint.EndpointOptions.MaxReconnectAttempts.Should().Be(5); } [Fact] public void CreateProducer_ReturnsTcpProducer() { var component = new TcpComponent(); var uri = new EndpointUri("tcp", "/localhost:9090", "tcp:localhost:9090", new Dictionary()); var endpoint = component.CreateEndpoint(uri); var producer = endpoint.CreateProducer(); producer.Should().BeOfType(); } [Fact] public void CreateConsumer_ReturnsTcpConsumer() { var component = new TcpComponent(); var uri = new EndpointUri("tcp", "/0.0.0.0:9090", "tcp:0.0.0.0:9090", new Dictionary()); var endpoint = component.CreateEndpoint(uri); var processor = Substitute.For(); var consumer = endpoint.CreateConsumer(processor); consumer.Should().BeOfType(); } [Fact] public void CreateConsumer_NullProcessor_Throws() { var component = new TcpComponent(); var uri = new EndpointUri("tcp", "/0.0.0.0:9090", "tcp:0.0.0.0:9090", new Dictionary()); var endpoint = component.CreateEndpoint(uri); var act = () => endpoint.CreateConsumer(null!); act.Should().Throw(); } [Theory] [InlineData("/localhost:9090", "localhost", 9090)] [InlineData("/0.0.0.0:8080", "0.0.0.0", 8080)] [InlineData("127.0.0.1:5555", "127.0.0.1", 5555)] [InlineData("/myserver:443", "myserver", 443)] public void ParseHostPort_VariousFormats(string path, string expectedHost, int expectedPort) { var options = new TcpEndpointOptions(); TcpComponent.ParseHostPort(path, options); options.Host.Should().Be(expectedHost); options.Port.Should().Be(expectedPort); } } Path: redb-route/tests/redb.Route.Tests.Tcp/TcpConnectionFactoryTests.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/tests/redb.Route.Tests.Tcp/TcpConnectionFactoryTests.cs ---- using redb.Route.Core; using redb.Route.Tcp; namespace redb.Route.Tests.Tcp; /// /// The TLS certificate password must be able to live in the registry instead of the endpoint URI, /// so it never reaches logs, telemetry, or the dashboard. /// public sealed class TcpConnectionFactoryTests { private const string Secret = "pfxP4ssw0rd"; private static TcpComponent Wire(string name, TcpConnectionFactory factory) { var context = new RouteContext(); var component = new TcpComponent(); context.AddComponent(component); context.AddToRegistry(name, factory); return component; } [Fact] public void Factory_SuppliesCertPassword_WhenUriCarriesNone() { var component = Wire("secure-tcp", new TcpConnectionFactory { Ssl = true, SslCertPath = "/etc/redb/certs/server.pfx", SslCertPassword = Secret, ConnectTimeout = 5_000 }); var uri = EndpointUriParser.Parse("tcp://0.0.0.0:9100?connectionFactory=secure-tcp"); var endpoint = component.CreateEndpoint(uri); endpoint.Should().NotBeNull(); uri.ToUriString().Should().NotContain(Secret); uri.ToString().Should().NotContain(Secret); } [Fact] public void ExplicitUriValue_WinsOverFactory() { var component = Wire("f", new TcpConnectionFactory { Ssl = true, ConnectTimeout = 5_000 }); var uri = EndpointUriParser.Parse( "tcp://0.0.0.0:9100?connectionFactory=f&connectTimeout=1234"); component.CreateEndpoint(uri).Should().NotBeNull(); uri.RawParameters["connectTimeout"].Should().Be("1234"); } [Fact] public void MissingFactory_FailsLoud() { var context = new RouteContext(); var component = new TcpComponent(); context.AddComponent(component); var uri = EndpointUriParser.Parse("tcp://0.0.0.0:9100?connectionFactory=absent"); var act = () => component.CreateEndpoint(uri); // A typo in connectionFactory must fail loud, not fall back silently act.Should().Throw() .Which.Message.Should().Contain("absent"); } } Path: redb-route/tests/redb.Route.Tests.Tcp/TcpConsumerTests.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/tests/redb.Route.Tests.Tcp/TcpConsumerTests.cs ---- using System.Net; using System.Net.Sockets; using System.Text; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Tcp; namespace redb.Route.Tests.Tcp; /// /// Tests for TcpConsumer. Starts a real TCP server (consumer) and sends data via TcpClient. /// Verifies message reception, framing, exchange creation, connection tracking, and InOut pattern. /// public class TcpConsumerTests : IAsyncLifetime { private TcpConsumer? _consumer; private int _port; // Captured exchanges from processor private IExchange? _lastExchange; private readonly List _capturedExchanges = []; // Configurable processor behaviour private Func? _processorAction; private static int GetFreePort() => global::redb.Route.Tests.Shared.TestPorts.Next(); public Task InitializeAsync() { _port = GetFreePort(); return Task.CompletedTask; } public async Task DisposeAsync() { if (_consumer is not null) await _consumer.Stop(); } private TcpConsumer CreateConsumer(TcpFraming framing = TcpFraming.TextLine, bool inOut = false, int maxConnections = 0, Dictionary? extra = null) { var parameters = new Dictionary(extra ?? []); parameters["framing"] = framing.ToString(); if (inOut) parameters["inOut"] = "true"; if (maxConnections > 0) parameters["maxConnections"] = maxConnections.ToString(); var component = new TcpComponent(); var uri = new EndpointUri("tcp", $"/127.0.0.1:{_port}", $"tcp:127.0.0.1:{_port}", parameters); var endpoint = (TcpEndpoint)component.CreateEndpoint(uri); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(async ci => { var ex = ci.Arg(); _lastExchange = ex; lock (_capturedExchanges) _capturedExchanges.Add(ex); if (_processorAction is not null) await _processorAction(ex); }); _consumer = new TcpConsumer(endpoint, processor, endpoint.EndpointOptions); return _consumer; } /// Sends a text line to the consumer and waits until it has been processed. private async Task SendTextLine(string text, string delimiter = "\n") { var before = _consumer!.ProcessedCount; var client = new TcpClient(); await client.ConnectAsync(IPAddress.Loopback, _port); var stream = client.GetStream(); var data = Encoding.UTF8.GetBytes(text + delimiter); await stream.WriteAsync(data); await stream.FlushAsync(); await TestWait.Until(() => _consumer!.ProcessedCount > before); return client; } /// Sends a length-prefixed message. private async Task SendLengthPrefixed(byte[] payload) { var before = _consumer!.ProcessedCount; var client = new TcpClient(); await client.ConnectAsync(IPAddress.Loopback, _port); var stream = client.GetStream(); var header = new byte[4]; System.Buffers.Binary.BinaryPrimitives.WriteInt32BigEndian(header, payload.Length); await stream.WriteAsync(header); await stream.WriteAsync(payload); await stream.FlushAsync(); await TestWait.Until(() => _consumer!.ProcessedCount > before); return client; } // ── Basic reception ── [Fact] public async Task Consumer_TextLine_ReceivesMessage() { var consumer = CreateConsumer(); await consumer.Start(); using var client = await SendTextLine("hello"); _lastExchange.Should().NotBeNull(); _lastExchange!.In.Body.Should().Be("hello"); } [Fact] public async Task Consumer_TextLine_BodyIsString() { var consumer = CreateConsumer(TcpFraming.TextLine); await consumer.Start(); using var client = await SendTextLine("typed"); _lastExchange!.In.Body.Should().BeOfType(); } [Fact] public async Task Consumer_LengthPrefixed_ReceivesMessage() { var consumer = CreateConsumer(TcpFraming.LengthPrefixed); await consumer.Start(); var payload = new byte[] { 10, 20, 30 }; using var client = await SendLengthPrefixed(payload); _lastExchange.Should().NotBeNull(); _lastExchange!.In.Body.Should().BeOfType(); ((byte[])_lastExchange.In.Body!).Should().BeEquivalentTo(payload); } [Fact] public async Task Consumer_MultipleMessages_AllProcessed() { var consumer = CreateConsumer(); await consumer.Start(); var client = new TcpClient(); await client.ConnectAsync(IPAddress.Loopback, _port); var stream = client.GetStream(); for (var i = 0; i < 5; i++) { var data = Encoding.UTF8.GetBytes($"msg-{i}\n"); await stream.WriteAsync(data); } await stream.FlushAsync(); await TestWait.Until(() => consumer.ProcessedCount >= 5); lock (_capturedExchanges) _capturedExchanges.Should().HaveCount(5); consumer.ProcessedCount.Should().Be(5); client.Dispose(); } // ── Headers ── [Fact] public async Task Consumer_SetsExchangeHeaders() { var consumer = CreateConsumer(); await consumer.Start(); using var client = await SendTextLine("test"); var headers = _lastExchange!.In.Headers; headers[TcpHeaders.RemoteAddress].Should().NotBeNull(); headers[TcpHeaders.LocalAddress].Should().NotBeNull(); headers[TcpHeaders.ConnectionId].Should().NotBeNull(); headers[TcpHeaders.Framing].Should().Be("TextLine"); headers[TcpHeaders.ByteCount].Should().Be("4"); // "test" = 4 bytes headers[TcpHeaders.Ssl].Should().Be("False"); } // ── ExchangePattern ── [Fact] public async Task Consumer_InOnly_PatternIsInOnly() { var consumer = CreateConsumer(inOut: false); await consumer.Start(); using var client = await SendTextLine("fire-and-forget"); _lastExchange!.Pattern.Should().Be(ExchangePattern.InOnly); } [Fact] public async Task Consumer_InOut_PatternIsInOut() { var consumer = CreateConsumer(inOut: true); await consumer.Start(); // For InOut, processor must provide Out message _processorAction = ex => { ex.Out = new Message("reply-body"); return Task.CompletedTask; }; // Send and receive response var client = new TcpClient(); await client.ConnectAsync(IPAddress.Loopback, _port); var stream = client.GetStream(); await stream.WriteAsync(Encoding.UTF8.GetBytes("request\n")); await stream.FlushAsync(); // Read response (TextLine framing: read until \n) var sb = new StringBuilder(); var buf = new byte[1024]; var deadline = DateTime.UtcNow.AddSeconds(3); while (DateTime.UtcNow < deadline) { if (stream.DataAvailable) { var n = await stream.ReadAsync(buf); sb.Append(Encoding.UTF8.GetString(buf, 0, n)); if (sb.ToString().Contains('\n')) break; } await Task.Delay(20); } sb.ToString().TrimEnd('\n').Should().Be("reply-body"); _lastExchange!.Pattern.Should().Be(ExchangePattern.InOut); client.Dispose(); } // ── InOut response ── [Fact] public async Task Consumer_InOut_LengthPrefixed_ReturnsResponse() { var consumer = CreateConsumer(TcpFraming.LengthPrefixed, inOut: true); await consumer.Start(); _processorAction = ex => { ex.Out = new Message(new byte[] { 99, 88, 77 }); return Task.CompletedTask; }; var client = new TcpClient(); await client.ConnectAsync(IPAddress.Loopback, _port); var stream = client.GetStream(); // Send length-prefixed message var payload = new byte[] { 1, 2, 3 }; var hdr = new byte[4]; System.Buffers.Binary.BinaryPrimitives.WriteInt32BigEndian(hdr, payload.Length); await stream.WriteAsync(hdr); await stream.WriteAsync(payload); await stream.FlushAsync(); // Read length-prefixed response var respHdr = new byte[4]; var deadline = DateTime.UtcNow.AddSeconds(3); var totalRead = 0; while (totalRead < 4 && DateTime.UtcNow < deadline) { var n = await stream.ReadAsync(respHdr.AsMemory(totalRead)); if (n == 0) break; totalRead += n; } var respLen = System.Buffers.Binary.BinaryPrimitives.ReadInt32BigEndian(respHdr); var respData = new byte[respLen]; totalRead = 0; while (totalRead < respLen && DateTime.UtcNow < deadline) { var n = await stream.ReadAsync(respData.AsMemory(totalRead)); if (n == 0) break; totalRead += n; } respData.Should().BeEquivalentTo(new byte[] { 99, 88, 77 }); client.Dispose(); } // ── Connection tracking ── [Fact] public async Task Consumer_ActiveConnections_TracksClients() { var consumer = CreateConsumer(); await consumer.Start(); var client1 = new TcpClient(); await client1.ConnectAsync(IPAddress.Loopback, _port); await TestWait.Until(() => consumer.ActiveConnections >= 1); consumer.ActiveConnections.Should().BeGreaterThanOrEqualTo(1); var client2 = new TcpClient(); await client2.ConnectAsync(IPAddress.Loopback, _port); await TestWait.Until(() => consumer.ActiveConnections >= 2); consumer.ActiveConnections.Should().BeGreaterThanOrEqualTo(2); client1.Dispose(); client2.Dispose(); } [Fact] public async Task Consumer_LocalEndPoint_IsSet() { var consumer = CreateConsumer(); await consumer.Start(); consumer.LocalEndPoint.Should().NotBeNull(); consumer.LocalEndPoint!.Port.Should().Be(_port); } // ── ProcessedCount ── [Fact] public async Task Consumer_ProcessedCount_Increments() { var consumer = CreateConsumer(); await consumer.Start(); consumer.ProcessedCount.Should().Be(0); using var client = await SendTextLine("one"); consumer.ProcessedCount.Should().Be(1); // Send another on same connection var stream = client.GetStream(); await stream.WriteAsync(Encoding.UTF8.GetBytes("two\n")); await stream.FlushAsync(); await TestWait.Until(() => consumer.ProcessedCount >= 2); consumer.ProcessedCount.Should().Be(2); } // ── Custom delimiter ── [Fact] public async Task Consumer_CustomDelimiter_Works() { var consumer = CreateConsumer(extra: new Dictionary { ["delimiter"] = "|" }); await consumer.Start(); var client = new TcpClient(); await client.ConnectAsync(IPAddress.Loopback, _port); var stream = client.GetStream(); await stream.WriteAsync(Encoding.UTF8.GetBytes("pipe-msg|")); await stream.FlushAsync(); await TestWait.Until(() => _lastExchange is not null); _lastExchange!.In.Body.Should().Be("pipe-msg"); client.Dispose(); } // ── Stop gracefully ── [Fact] public async Task Consumer_Stop_DisconnectsClients() { var consumer = CreateConsumer(); await consumer.Start(); var client = new TcpClient(); await client.ConnectAsync(IPAddress.Loopback, _port); await Task.Delay(50); await consumer.Stop(); _consumer = null; // Prevent double-stop in DisposeAsync consumer.ActiveConnections.Should().Be(0); client.Dispose(); } // ── Multiple concurrent clients ── [Fact] public async Task Consumer_ConcurrentClients_AllProcessed() { var consumer = CreateConsumer(); await consumer.Start(); var tasks = new List>(); for (var i = 0; i < 3; i++) { var idx = i; tasks.Add(Task.Run(async () => { var c = new TcpClient(); await c.ConnectAsync(IPAddress.Loopback, _port); var s = c.GetStream(); await s.WriteAsync(Encoding.UTF8.GetBytes($"client-{idx}\n")); await s.FlushAsync(); return c; })); } var clients = await Task.WhenAll(tasks); await TestWait.Until(() => { lock (_capturedExchanges) return _capturedExchanges.Count >= 3; }); lock (_capturedExchanges) _capturedExchanges.Should().HaveCount(3); foreach (var c in clients) c.Dispose(); } // ── ExchangeException on processor failure ── [Fact] public async Task Consumer_ProcessorThrows_SetsExceptionOnExchange() { var consumer = CreateConsumer(); await consumer.Start(); _processorAction = _ => throw new InvalidOperationException("boom"); using var client = await SendTextLine("error test"); // Even after exception, consumer should continue running _lastExchange.Should().NotBeNull(); _lastExchange!.Exception.Should().BeOfType(); consumer.ProcessedCount.Should().Be(1); } // ── Empty message ── [Fact] public async Task Consumer_EmptyTextLine_Processed() { var consumer = CreateConsumer(); await consumer.Start(); var client = new TcpClient(); await client.ConnectAsync(IPAddress.Loopback, _port); var stream = client.GetStream(); // empty line: just the delimiter await stream.WriteAsync(Encoding.UTF8.GetBytes("\n")); await stream.FlushAsync(); await TestWait.Until(() => _lastExchange is not null); _lastExchange.Should().NotBeNull(); _lastExchange!.In.Body.Should().Be(""); client.Dispose(); } } Path: redb-route/tests/redb.Route.Tests.Tcp/TcpDrainTests.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/tests/redb.Route.Tests.Tcp/TcpDrainTests.cs ---- using System.Net; using System.Net.Sockets; using NSubstitute; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Tcp; namespace redb.Route.Tests.Tcp; /// /// Integration test validating Fix #6: TCP drain waits for full exchange lifecycle /// (processing + InOut response + DisposeAsync) before allowing Stop to complete. /// [Trait("Category", "Integration")] public class TcpDrainTests : IAsyncLifetime { private int _port; private TcpConsumer? _consumer; private static int GetFreePort() => global::redb.Route.Tests.Shared.TestPorts.Next(); public Task InitializeAsync() { _port = GetFreePort(); return Task.CompletedTask; } public async Task DisposeAsync() { if (_consumer is not null) { try { await _consumer.Stop(); } catch { /* already stopped */ } } } [Fact] public async Task Drain_SlowProcessing_CompletesBeforeStopReturns() { var processedCount = 0; var processingStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(async ci => { processingStarted.TrySetResult(); await Task.Delay(400, ci.Arg()); Interlocked.Increment(ref processedCount); }); var component = new TcpComponent(); var parameters = new Dictionary { ["framing"] = TcpFraming.TextLine.ToString() }; var cUri = new EndpointUri("tcp", $"/127.0.0.1:{_port}", $"tcp:127.0.0.1:{_port}", parameters); var cEndpoint = (TcpEndpoint)component.CreateEndpoint(cUri); _consumer = new TcpConsumer(cEndpoint, processor, cEndpoint.EndpointOptions); await _consumer.Start(); var pUri = new EndpointUri("tcp", $"/127.0.0.1:{_port}", $"tcp:127.0.0.1:{_port}", parameters); var pEndpoint = (TcpEndpoint)component.CreateEndpoint(pUri); var producer = (TcpProducer)pEndpoint.CreateProducer(); await producer.Start(); // Send message — processing takes 400ms _ = producer.Process(new Exchange(new Message("drain-test"))); await processingStarted.Task; // Stop consumer immediately — drain should wait for processing to finish await _consumer.Stop(); _consumer = null; processedCount.Should().Be(1, "in-flight message must complete before Stop returns (drain waits for full lifecycle)"); await producer.Stop(); } [Fact] public async Task Drain_InOutMode_ResponseSentWithinDrainScope() { var processingStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(async ci => { processingStarted.TrySetResult(); var ex = ci.Arg(); await Task.Delay(200, ci.Arg()); ex.Out = new Message("PONG"); }); var component = new TcpComponent(); var parameters = new Dictionary { ["framing"] = TcpFraming.TextLine.ToString(), ["inOut"] = "true" }; var cUri = new EndpointUri("tcp", $"/127.0.0.1:{_port}", $"tcp:127.0.0.1:{_port}", parameters); var cEndpoint = (TcpEndpoint)component.CreateEndpoint(cUri); _consumer = new TcpConsumer(cEndpoint, processor, cEndpoint.EndpointOptions); await _consumer.Start(); var pUri = new EndpointUri("tcp", $"/127.0.0.1:{_port}", $"tcp:127.0.0.1:{_port}", parameters); var pEndpoint = (TcpEndpoint)component.CreateEndpoint(pUri); var producer = (TcpProducer)pEndpoint.CreateProducer(); await producer.Start(); // Send InOut request — response takes 200ms var exchange = new Exchange(new Message("PING")); var processTask = Task.Run(async () => await producer.Process(exchange)); await processingStarted.Task; // Start stop in background — drain-safe token keeps response write alive var stopTask = Task.Run(async () => { await _consumer!.Stop(); _consumer = null; }); // Both should complete — producer gets response, stop waits for drain await Task.WhenAll(processTask, stopTask); exchange.Out.Should().NotBeNull("InOut response should be received before drain completes"); exchange.Out!.Body.Should().Be("PONG"); await producer.Stop(); } } Path: redb-route/tests/redb.Route.Tests.Tcp/TcpEndpointOptionsTests.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/tests/redb.Route.Tests.Tcp/TcpEndpointOptionsTests.cs ---- using redb.Route.Tcp; namespace redb.Route.Tests.Tcp; public class TcpEndpointOptionsTests { [Fact] public void Defaults_AreCorrect() { var options = new TcpEndpointOptions(); options.Host.Should().Be("0.0.0.0"); options.Port.Should().Be(0); options.Framing.Should().Be(TcpFraming.Raw); options.TextLine.Should().BeFalse(); options.LengthPrefixed.Should().BeFalse(); options.Delimiter.Should().Be("\n"); options.Encoding.Should().Be("utf-8"); options.KeepAlive.Should().BeTrue(); options.NoDelay.Should().BeTrue(); options.ReceiveBufferSize.Should().Be(0); options.SendBufferSize.Should().Be(0); options.ConnectTimeout.Should().Be(10_000); options.Reconnect.Should().BeFalse(); options.ReconnectInterval.Should().Be(5_000); options.MaxReconnectAttempts.Should().Be(0); options.Backlog.Should().Be(128); options.MaxConnections.Should().Be(0); options.InOut.Should().BeFalse(); options.Ssl.Should().BeFalse(); } [Fact] public void Validate_ValidOptions_DoesNotThrow() { var options = new TcpEndpointOptions { Port = 9090 }; var act = () => options.Validate(); act.Should().NotThrow(); } [Fact] public void Validate_InvalidPort_Negative_Throws() { var options = new TcpEndpointOptions { Port = -1 }; var act = () => options.Validate(); act.Should().Throw().WithMessage("*Port*"); } [Fact] public void Validate_InvalidPort_TooHigh_Throws() { var options = new TcpEndpointOptions { Port = 70000 }; var act = () => options.Validate(); act.Should().Throw().WithMessage("*Port*"); } [Fact] public void Validate_InvalidReceiveBufferSize_Throws() { var options = new TcpEndpointOptions { ReceiveBufferSize = -1 }; var act = () => options.Validate(); act.Should().Throw().WithMessage("*ReceiveBufferSize*"); } /// /// A buffer size of 0 leaves the socket as the system made it. A fixed 8192 switched the Linux buffer tuning off, /// and on loopback a 64 KiB frame took about three seconds. /// [Fact] public void ZeroBufferSizes_LeaveTheSystemSizes_AndASetSizeReachesTheSocket() { using var untouched = new System.Net.Sockets.TcpClient(); var systemReceive = untouched.ReceiveBufferSize; var systemSend = untouched.SendBufferSize; using var byDefault = new System.Net.Sockets.TcpClient(); new TcpEndpointOptions().ApplyBufferSizes(byDefault); byDefault.ReceiveBufferSize.Should().Be(systemReceive); byDefault.SendBufferSize.Should().Be(systemSend); new TcpEndpointOptions().ReadChunkSize.Should().Be(TcpEndpointOptions.DefaultReadChunkSize); using var configured = new System.Net.Sockets.TcpClient(); var options = new TcpEndpointOptions { ReceiveBufferSize = 1 << 20, SendBufferSize = 1 << 20 }; options.ApplyBufferSizes(configured); configured.ReceiveBufferSize.Should().NotBe(systemReceive, "a size that was set is applied"); options.ReadChunkSize.Should().Be(1 << 20); } [Fact] public void Validate_InvalidSendBufferSize_Throws() { var options = new TcpEndpointOptions { SendBufferSize = -1 }; var act = () => options.Validate(); act.Should().Throw().WithMessage("*SendBufferSize*"); } [Fact] public void Validate_NegativeConnectTimeout_Throws() { var options = new TcpEndpointOptions { ConnectTimeout = -1 }; var act = () => options.Validate(); act.Should().Throw().WithMessage("*ConnectTimeout*"); } [Fact] public void Validate_InvalidReconnectInterval_Throws() { var options = new TcpEndpointOptions { ReconnectInterval = 0 }; var act = () => options.Validate(); act.Should().Throw().WithMessage("*ReconnectInterval*"); } [Fact] public void Validate_NegativeMaxReconnectAttempts_Throws() { var options = new TcpEndpointOptions { MaxReconnectAttempts = -1 }; var act = () => options.Validate(); act.Should().Throw().WithMessage("*MaxReconnectAttempts*"); } [Fact] public void Validate_InvalidBacklog_Throws() { var options = new TcpEndpointOptions { Backlog = 0 }; var act = () => options.Validate(); act.Should().Throw().WithMessage("*Backlog*"); } [Fact] public void Validate_NegativeMaxConnections_Throws() { var options = new TcpEndpointOptions { MaxConnections = -1 }; var act = () => options.Validate(); act.Should().Throw().WithMessage("*MaxConnections*"); } [Fact] public void Validate_TextLine_SetsFraming() { var options = new TcpEndpointOptions { TextLine = true }; options.Validate(); options.Framing.Should().Be(TcpFraming.TextLine); } [Fact] public void Validate_LengthPrefixed_SetsFraming() { var options = new TcpEndpointOptions { LengthPrefixed = true }; options.Validate(); options.Framing.Should().Be(TcpFraming.LengthPrefixed); } [Fact] public void Validate_BothTextLineAndLengthPrefixed_Throws() { var options = new TcpEndpointOptions { TextLine = true, LengthPrefixed = true }; var act = () => options.Validate(); act.Should().Throw().WithMessage("*TextLine*LengthPrefixed*"); } [Fact] public void Validate_BoundaryValues_AllValid() { var options = new TcpEndpointOptions { Port = 0, ReceiveBufferSize = 1, SendBufferSize = 1, ConnectTimeout = 0, ReconnectInterval = 1, MaxReconnectAttempts = 0, Backlog = 1, MaxConnections = 0 }; var act = () => options.Validate(); act.Should().NotThrow(); } [Fact] public void Validate_Port65535_Valid() { var options = new TcpEndpointOptions { Port = 65535 }; var act = () => options.Validate(); act.Should().NotThrow(); } } Path: redb-route/tests/redb.Route.Tests.Tcp/TcpIntegrationTests.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/tests/redb.Route.Tests.Tcp/TcpIntegrationTests.cs ---- using System.Net; using System.Net.Sockets; using System.Text; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Tcp; namespace redb.Route.Tests.Tcp; /// /// End-to-end integration tests: TcpProducer → TcpConsumer. /// Real TCP connections over loopback for all framing modes. /// public class TcpIntegrationTests : IAsyncLifetime { private int _port; private TcpConsumer? _consumer; private TcpProducer? _producer; // Captured exchanges from consumer processor private IExchange? _lastExchange; private readonly List _capturedExchanges = []; private Func? _processorAction; private static int GetFreePort() => global::redb.Route.Tests.Shared.TestPorts.Next(); public Task InitializeAsync() { _port = GetFreePort(); return Task.CompletedTask; } public async Task DisposeAsync() { if (_producer is not null) await _producer.Stop(); if (_consumer is not null) await _consumer.Stop(); } private (TcpConsumer consumer, TcpProducer producer) CreatePair( TcpFraming framing = TcpFraming.TextLine, bool inOut = false, Dictionary? extraConsumer = null, Dictionary? extraProducer = null) { // Consumer var cParams = new Dictionary(extraConsumer ?? []) { ["framing"] = framing.ToString() }; if (inOut) cParams["inOut"] = "true"; var component = new TcpComponent(); var cUri = new EndpointUri("tcp", $"/127.0.0.1:{_port}", $"tcp:127.0.0.1:{_port}", cParams); var cEndpoint = (TcpEndpoint)component.CreateEndpoint(cUri); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(async ci => { var ex = ci.Arg(); _lastExchange = ex; lock (_capturedExchanges) _capturedExchanges.Add(ex); if (_processorAction is not null) await _processorAction(ex); }); _consumer = new TcpConsumer(cEndpoint, processor, cEndpoint.EndpointOptions); // Producer var pParams = new Dictionary(extraProducer ?? []) { ["framing"] = framing.ToString() }; if (inOut) pParams["inOut"] = "true"; var pUri = new EndpointUri("tcp", $"/127.0.0.1:{_port}", $"tcp:127.0.0.1:{_port}", pParams); var pEndpoint = (TcpEndpoint)component.CreateEndpoint(pUri); _producer = (TcpProducer)pEndpoint.CreateProducer(); return (_consumer, _producer); } // ── TextLine ── [Fact] public async Task TextLine_ProducerToConsumer_StringDelivered() { var (consumer, producer) = CreatePair(TcpFraming.TextLine); await consumer.Start(); await producer.Start(); await producer.Process(new Exchange(new Message("integration hello"))); await TestWait.Until(() => _lastExchange is not null); _lastExchange.Should().NotBeNull(); _lastExchange!.In.Body.Should().Be("integration hello"); } [Fact] public async Task TextLine_MultipleMessages_AllDelivered() { var (consumer, producer) = CreatePair(TcpFraming.TextLine); await consumer.Start(); await producer.Start(); for (var i = 0; i < 10; i++) await producer.Process(new Exchange(new Message($"batch-{i}"))); await TestWait.Until(() => consumer.ProcessedCount >= 10); lock (_capturedExchanges) _capturedExchanges.Should().HaveCount(10); consumer.ProcessedCount.Should().Be(10); } [Fact] public async Task TextLine_CustomDelimiter_Works() { var (consumer, producer) = CreatePair( TcpFraming.TextLine, extraConsumer: new Dictionary { ["delimiter"] = "|" }, extraProducer: new Dictionary { ["delimiter"] = "|" }); await consumer.Start(); await producer.Start(); await producer.Process(new Exchange(new Message("pipe"))); await TestWait.Until(() => _lastExchange is not null); _lastExchange!.In.Body.Should().Be("pipe"); } // ── LengthPrefixed ── [Fact] public async Task LengthPrefixed_BinaryDelivered() { var (consumer, producer) = CreatePair(TcpFraming.LengthPrefixed); await consumer.Start(); await producer.Start(); var data = new byte[] { 0xAA, 0xBB, 0xCC, 0xDD }; await producer.Process(new Exchange(new Message(data))); await TestWait.Until(() => _lastExchange is not null); _lastExchange.Should().NotBeNull(); ((byte[])_lastExchange!.In.Body!).Should().BeEquivalentTo(data); } [Fact] public async Task LengthPrefixed_MultipleMessages_AllDelivered() { var (consumer, producer) = CreatePair(TcpFraming.LengthPrefixed); await consumer.Start(); await producer.Start(); for (var i = 0; i < 5; i++) await producer.Process(new Exchange(new Message(new byte[] { (byte)i }))); await TestWait.Until(() => { lock (_capturedExchanges) return _capturedExchanges.Count >= 5; }); lock (_capturedExchanges) _capturedExchanges.Should().HaveCount(5); } // ── InOut request-response ── [Fact] public async Task TextLine_InOut_RequestResponse() { _processorAction = ex => { // Echo back uppercased var input = (string)ex.In.Body!; ex.Out = new Message(input.ToUpperInvariant()); return Task.CompletedTask; }; var (consumer, producer) = CreatePair(TcpFraming.TextLine, inOut: true); await consumer.Start(); await producer.Start(); var exchange = new Exchange(new Message("hello")); await producer.Process(exchange); exchange.Out.Should().NotBeNull(); exchange.Out!.Body.Should().Be("HELLO"); } [Fact] public async Task LengthPrefixed_InOut_RequestResponse() { _processorAction = ex => { var input = (byte[])ex.In.Body!; var reversed = input.AsEnumerable().Reverse().ToArray(); ex.Out = new Message(reversed); return Task.CompletedTask; }; var (consumer, producer) = CreatePair(TcpFraming.LengthPrefixed, inOut: true); await consumer.Start(); await producer.Start(); var data = new byte[] { 1, 2, 3, 4, 5 }; var exchange = new Exchange(new Message(data)); await producer.Process(exchange); exchange.Out.Should().NotBeNull(); ((byte[])exchange.Out!.Body!).Should().BeEquivalentTo(new byte[] { 5, 4, 3, 2, 1 }); } // ── Headers propagation ── [Fact] public async Task Integration_ConsumerSetsAllHeaders() { var (consumer, producer) = CreatePair(); await consumer.Start(); await producer.Start(); await producer.Process(new Exchange(new Message("hdr test"))); await TestWait.Until(() => _lastExchange is not null); var h = _lastExchange!.In.Headers; h[TcpHeaders.RemoteAddress].Should().NotBeNull(); h[TcpHeaders.LocalAddress].Should().NotBeNull(); h[TcpHeaders.ConnectionId].Should().NotBeNull(); h[TcpHeaders.Framing].Should().Be("TextLine"); h[TcpHeaders.Ssl].Should().Be("False"); ((string)h[TcpHeaders.ByteCount]!).Should().NotBeNullOrEmpty(); } // ── Large payload ── [Fact] public async Task LengthPrefixed_LargePayload_Delivered() { var (consumer, producer) = CreatePair(TcpFraming.LengthPrefixed); await consumer.Start(); await producer.Start(); var largeData = new byte[64 * 1024]; Random.Shared.NextBytes(largeData); await producer.Process(new Exchange(new Message(largeData))); await TestWait.Until(() => _lastExchange is not null); _lastExchange.Should().NotBeNull(); ((byte[])_lastExchange!.In.Body!).Should().HaveCount(64 * 1024); ((byte[])_lastExchange.In.Body!).Should().BeEquivalentTo(largeData); } // ── NullBody ── [Fact] public async Task TextLine_NullBody_SendsEmptyLine() { var (consumer, producer) = CreatePair(TcpFraming.TextLine); await consumer.Start(); await producer.Start(); await producer.Process(new Exchange(new Message(null))); await TestWait.Until(() => _lastExchange is not null); _lastExchange.Should().NotBeNull(); _lastExchange!.In.Body.Should().Be(""); } // ── Stream body ── [Fact] public async Task TextLine_StreamBody_Delivered() { var (consumer, producer) = CreatePair(TcpFraming.TextLine); await consumer.Start(); await producer.Start(); var ms = new MemoryStream(Encoding.UTF8.GetBytes("from-stream")); await producer.Process(new Exchange(new Message(ms))); await TestWait.Until(() => _lastExchange is not null); _lastExchange!.In.Body.Should().Be("from-stream"); } } Path: redb-route/tests/redb.Route.Tests.Tcp/TcpProducerTests.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/tests/redb.Route.Tests.Tcp/TcpProducerTests.cs ---- using System.Net; using System.Net.Sockets; using System.Text; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Tcp; namespace redb.Route.Tests.Tcp; /// /// Tests for TcpProducer using a real embedded TCP test server. /// public class TcpProducerTests : IAsyncLifetime { private int _port; private TcpListener? _server; private CancellationTokenSource? _cts; // Captured by server private readonly List _receivedMessages = []; private string? _lastReceivedText; // Optional response for InOut private byte[]? _responseData; private TcpFraming _framing = TcpFraming.TextLine; private string _delimiter = "\n"; private static int GetFreePort() => global::redb.Route.Tests.Shared.TestPorts.Next(); public Task InitializeAsync() { _port = GetFreePort(); _cts = new CancellationTokenSource(); _server = new TcpListener(IPAddress.Loopback, _port); _server.Start(); _ = AcceptLoopAsync(_cts.Token); return Task.CompletedTask; } public Task DisposeAsync() { _cts?.Cancel(); _server?.Stop(); _cts?.Dispose(); return Task.CompletedTask; } private async Task AcceptLoopAsync(CancellationToken ct) { while (!ct.IsCancellationRequested) { TcpClient client; try { client = await _server!.AcceptTcpClientAsync(ct); } catch { break; } _ = HandleClientAsync(client, ct); } } private async Task HandleClientAsync(TcpClient client, CancellationToken ct) { try { var stream = client.GetStream(); while (!ct.IsCancellationRequested) { var data = await TcpCodec.ReadMessageAsync(stream, _framing, _delimiter, 8192, ct); if (data is null) break; lock (_receivedMessages) _receivedMessages.Add(data); _lastReceivedText = Encoding.UTF8.GetString(data); if (_responseData is not null) await TcpCodec.WriteMessageAsync(stream, _responseData, _framing, _delimiter, Encoding.UTF8, ct); } } catch { } finally { client.Dispose(); } } private TcpProducer CreateProducer(TcpFraming framing = TcpFraming.TextLine, bool inOut = false, Dictionary? extra = null) { _framing = framing; var parameters = new Dictionary(extra ?? []); parameters["framing"] = framing.ToString(); if (inOut) parameters["inOut"] = "true"; var component = new TcpComponent(); var uri = new EndpointUri("tcp", $"/127.0.0.1:{_port}", $"tcp:127.0.0.1:{_port}", parameters); var endpoint = (TcpEndpoint)component.CreateEndpoint(uri); return (TcpProducer)endpoint.CreateProducer(); } // ── Basic send ── [Fact] public async Task Producer_TextLine_SendsString() { var producer = CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("hello")); await producer.Process(exchange); await TestWait.Until(() => _lastReceivedText == "hello"); _lastReceivedText.Should().Be("hello"); await producer.Stop(); } [Fact] public async Task Producer_TextLine_SendsBytes() { var producer = CreateProducer(); await producer.Start(); var data = Encoding.UTF8.GetBytes("binary hello"); var exchange = new Exchange(new Message(data)); await producer.Process(exchange); await TestWait.Until(() => _lastReceivedText == "binary hello"); _lastReceivedText.Should().Be("binary hello"); await producer.Stop(); } [Fact] public async Task Producer_LengthPrefixed_SendsData() { _framing = TcpFraming.LengthPrefixed; var producer = CreateProducer(TcpFraming.LengthPrefixed); await producer.Start(); var data = new byte[] { 1, 2, 3, 4, 5 }; var exchange = new Exchange(new Message(data)); await producer.Process(exchange); await TestWait.Until(() => { lock (_receivedMessages) return _receivedMessages.Count >= 1; }); lock (_receivedMessages) _receivedMessages.Should().ContainSingle().Which.Should().BeEquivalentTo(data); await producer.Stop(); } [Fact] public async Task Producer_Raw_SendsData() { _framing = TcpFraming.Raw; var producer = CreateProducer(TcpFraming.Raw); await producer.Start(); var exchange = new Exchange(new Message("raw msg")); await producer.Process(exchange); await TestWait.Until(() => { lock (_receivedMessages) return _receivedMessages.Count > 0; }); lock (_receivedMessages) _receivedMessages.Should().HaveCountGreaterThan(0); await producer.Stop(); } // ── InOut (request-response) ── [Fact] public async Task Producer_InOut_ReceivesResponse() { _responseData = Encoding.UTF8.GetBytes("pong"); var producer = CreateProducer(inOut: true); await producer.Start(); var exchange = new Exchange(new Message("ping")); await producer.Process(exchange); exchange.Out.Should().NotBeNull(); exchange.Out!.Body.Should().Be("pong"); await producer.Stop(); } // ── Multiple messages ── [Fact] public async Task Producer_MultipleMessages_AllReceived() { var producer = CreateProducer(); await producer.Start(); for (var i = 0; i < 5; i++) { var exchange = new Exchange(new Message($"msg-{i}")); await producer.Process(exchange); } await TestWait.Until(() => { lock (_receivedMessages) return _receivedMessages.Count >= 5; }); lock (_receivedMessages) _receivedMessages.Should().HaveCount(5); await producer.Stop(); } // ── Headers ── [Fact] public async Task Producer_SetsExchangeHeaders() { var producer = CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("test")); await producer.Process(exchange); exchange.In.Headers[TcpHeaders.RemoteAddress].Should().NotBeNull(); exchange.In.Headers[TcpHeaders.LocalAddress].Should().NotBeNull(); exchange.In.Headers[TcpHeaders.Framing].Should().Be("TextLine"); exchange.In.Headers[TcpHeaders.Ssl].Should().Be("False"); await producer.Stop(); } // ── Lifecycle ── [Fact] public async Task Producer_ProcessBeforeStart_Throws() { var producer = CreateProducer(); var exchange = new Exchange(new Message("test")); var act = () => producer.Process(exchange); await act.Should().ThrowAsync(); } [Fact] public async Task Producer_StartStop_Lifecycle() { var producer = CreateProducer(); producer.IsStarted.Should().BeFalse(); await producer.Start(); producer.IsStarted.Should().BeTrue(); await producer.Stop(); producer.IsStarted.Should().BeFalse(); } [Fact] public async Task Producer_NullBody_SendsEmptyMessage() { var producer = CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message(null)); await producer.Process(exchange); await TestWait.Until(() => { lock (_receivedMessages) return _receivedMessages.Count >= 1; }); lock (_receivedMessages) _receivedMessages.Should().HaveCount(1); await producer.Stop(); } [Fact] public async Task Producer_StreamBody_Sends() { var producer = CreateProducer(); await producer.Start(); var stream = new MemoryStream(Encoding.UTF8.GetBytes("from stream")); var exchange = new Exchange(new Message(stream)); await producer.Process(exchange); await TestWait.Until(() => _lastReceivedText == "from stream"); _lastReceivedText.Should().Be("from stream"); await producer.Stop(); } [Fact] public async Task Producer_CustomDelimiter_Works() { _delimiter = "|"; var producer = CreateProducer(extra: new Dictionary { ["delimiter"] = "|" }); await producer.Start(); var exchange = new Exchange(new Message("pipe delimited")); await producer.Process(exchange); await TestWait.Until(() => _lastReceivedText == "pipe delimited"); _lastReceivedText.Should().Be("pipe delimited"); await producer.Stop(); } // ── Statistics ownership (audit follow-up) ── [Fact] public async Task HandBuiltProducer_RecordsOnlyWireBytes() { // Ownership audit: MessagesOut belongs to the core (ToProcessor for a routed .To(), // the ProducerTemplate for template sends). A self-recording producer double-counted // every routed send. The connector records only what the core cannot see: wire bytes. var component = new TcpComponent(); var uri = new EndpointUri("tcp", $"/127.0.0.1:{_port}", $"tcp:127.0.0.1:{_port}", new Dictionary { ["framing"] = "TextLine" }); var endpoint = (TcpEndpoint)component.CreateEndpoint(uri); var producer = (TcpProducer)endpoint.CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("hello"))); await Task.Delay(100); await producer.Stop(); endpoint.MessagesOut.Should().Be(0, "MessagesOut is written by the core, the own write doubled it in the route"); endpoint.BytesOut.Should().BeGreaterThan(0, "only the connector sees wire bytes"); } } Path: redb-route/tests/redb.Route.Tests.Tcp/TcpRestartTests.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/tests/redb.Route.Tests.Tcp/TcpRestartTests.cs ---- using System.Net; using System.Net.Sockets; using System.Text; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Tcp; namespace redb.Route.Tests.Tcp; /// /// A TCP consumer and producer keep working after Stop() and Start() of the same route context: the stop /// closes the listening socket, the start binds the port again on the cached endpoint, and the producer still connects. /// public sealed class TcpRestartTests { private static async Task AskAsync(int port, string text) { using var client = new TcpClient(); await client.ConnectAsync(IPAddress.Loopback, port); var stream = client.GetStream(); await stream.WriteAsync(Encoding.UTF8.GetBytes(text + "\n")); using var reader = new StreamReader(stream, Encoding.UTF8); return await reader.ReadLineAsync().WaitAsync(TimeSpan.FromSeconds(10)); } [Fact] public async Task Consumer_and_producer_work_after_the_context_is_stopped_and_started_again() { var port = global::redb.Route.Tests.Shared.TestPorts.Next(); await using var ctx = new RouteContext(); ctx.AddComponent(new TcpComponent()); ctx.AddRoutes(r => r.From($"tcp://127.0.0.1:{port}?framing=TextLine&inOut=true") .Process(e => e.Out = new Message("re:" + e.In.Body))); ctx.AddRoutes(r => r.From("direct://call").To($"tcp://127.0.0.1:{port}?framing=TextLine&inOut=true")); async Task CheckAsync(string body) { (await AskAsync(port, body)).Should().Be("re:" + body, "the TCP receiver replies after a restart"); var producer = ctx.GetEndpoint("direct://call").CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message(body + "-p")); await producer.Process(exchange); exchange.Exception.Should().BeNull("a TCP send after a restart arrives"); (exchange.HasOut ? exchange.Out! : exchange.In).Body?.ToString().Should().Be("re:" + body + "-p"); } await ctx.Start(); await CheckAsync("first"); await ctx.Stop(); await ctx.Start(); await CheckAsync("second"); } } Path: redb-route/tests/redb.Route.Tests.Tcp/TcpTelemetrySmokeTests.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/tests/redb.Route.Tests.Tcp/TcpTelemetrySmokeTests.cs ---- using System.Diagnostics; using System.Net; using System.Net.Sockets; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Tcp; using redb.Route.Telemetry; using redb.Route.Tests.Shared; namespace redb.Route.Tests.Tcp; /// /// Smoke test for the P1 transport span opened by . /// public sealed class TcpTelemetrySmokeTests : IAsyncLifetime { private int _port; private TcpListener? _server; private CancellationTokenSource? _cts; public Task InitializeAsync() { _port = GetFreePort(); _cts = new CancellationTokenSource(); _server = new TcpListener(IPAddress.Loopback, _port); _server.Start(); _ = AcceptLoop(_cts.Token); return Task.CompletedTask; } public Task DisposeAsync() { _cts?.Cancel(); _server?.Stop(); _cts?.Dispose(); return Task.CompletedTask; } private async Task AcceptLoop(CancellationToken ct) { try { while (!ct.IsCancellationRequested) { var client = await _server!.AcceptTcpClientAsync(ct); _ = HandleClient(client, ct); } } catch { } } private static async Task HandleClient(TcpClient client, CancellationToken ct) { try { var stream = client.GetStream(); while (!ct.IsCancellationRequested) { var data = await TcpCodec.ReadMessageAsync(stream, TcpFraming.TextLine, "\n", 8192, ct); if (data is null) break; } } catch { } finally { client.Dispose(); } } [Fact] public async Task TcpProducer_EmitsTransportSpanWithNetworkTags() { using var capture = new SpanCapture(); // this test's spans only var component = new TcpComponent(); var pars = new Dictionary { ["framing"] = "TextLine" }; var uri = new EndpointUri("tcp", $"/127.0.0.1:{_port}", $"tcp:127.0.0.1:{_port}", pars); var endpoint = (TcpEndpoint)component.CreateEndpoint(uri); var producer = (TcpProducer)endpoint.CreateProducer(); await producer.Start(); try { await producer.Process(new Exchange(new Message("ping"))); } finally { await producer.Stop(); } var activities = capture.Spans; activities.Should().NotBeEmpty(); // The capture keeps only this test's trace; the unique destination port picks the producer's span in it. var activity = activities.Single(a => Equals(a.GetTagItem("messaging.destination.name"), $"127.0.0.1:{_port}")); activity.Source.Name.Should().Be(RouteActivitySource.SourceName); activity.Kind.Should().Be(ActivityKind.Client); activity.GetTagItem("network.transport").Should().Be("tcp"); activity.GetTagItem("redb.route.endpoint").Should().NotBeNull(); activity.GetTagItem("messaging.destination.name").Should().Be($"127.0.0.1:{_port}"); } private static int GetFreePort() => global::redb.Route.Tests.Shared.TestPorts.Next(); } Path: redb-route/tests/redb.Route.Tests.Tcp/TcpTraceTests.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/tests/redb.Route.Tests.Tcp/TcpTraceTests.cs ---- using System.Diagnostics; using System.Net; using System.Net.Sockets; using System.Text; using redb.Route.Abstractions; using redb.Route.Configuration; using redb.Route.Core; using redb.Route.Tcp; using redb.Route.Telemetry; using redb.Route.Tests.Telemetry; namespace redb.Route.Tests.Tcp; /// /// A framed TCP message carries no trace context: the consumer opens a root span per routed message, never a child of the /// activity the listener inherited from whoever started it, and none while a connection sends nothing. A failed route /// marks it red. EnableTelemetry=false opens no span, on the consumer or the producer. /// public sealed class TcpTraceTests { private static readonly TimeSpan Wait = TimeSpan.FromSeconds(10); private readonly int _port = global::redb.Route.Tests.Shared.TestPorts.Next(); private string Uri => $"tcp://127.0.0.1:{_port}?framing=TextLine"; private RouteTelemetryProbe Spans(ActivityKind kind) => new(a => a.Kind == kind && RouteTelemetryProbe.Tag(a, RouteTelemetryProbe.EndpointTag)?.Contains($":{_port}", StringComparison.Ordinal) == true); private async Task StartConsumer(Action step, bool telemetry = true) { var ctx = new RouteContext(options: new RouteEngineOptions { EnableTelemetry = telemetry }); ctx.AddComponent(new TcpComponent()); ctx.AddRoutes(r => r.From(Uri).Process(step)); using (new Activity("host startup").SetIdFormat(ActivityIdFormat.W3C).Start()) await ctx.Start(); return ctx; } private async Task Send(params string[] lines) { var client = new TcpClient(); await client.ConnectAsync(IPAddress.Loopback, _port); foreach (var line in lines) await client.GetStream().WriteAsync(Encoding.UTF8.GetBytes(line + "\n")); await client.GetStream().FlushAsync(); return client; } private static async Task Until(Func done) { var deadline = DateTime.UtcNow + Wait; while (!done() && DateTime.UtcNow < deadline) await Task.Delay(50); } [Fact] public async Task Each_message_opens_a_root_span_even_under_an_ambient_activity() { using var probe = Spans(ActivityKind.Consumer); await using (await StartConsumer(_ => { })) { using var client = await Send("a", "b"); await Until(() => probe.Activities.Count >= 2); } probe.Activities.Should().HaveCount(2, "one span per routed message"); probe.Activities.Should().OnlyContain(a => a.ParentSpanId == default(ActivitySpanId), "a framed message carries no context, so its span starts a trace rather than joining the host's"); } [Fact] public async Task A_connection_that_sends_nothing_opens_no_span() { using var probe = Spans(ActivityKind.Consumer); await using (await StartConsumer(_ => { })) { using var client = await Send(); await Task.Delay(800); } probe.Activities.Should().BeEmpty(); } [Fact] public async Task A_failed_route_marks_the_span_red() { using var probe = Spans(ActivityKind.Consumer); await using (await StartConsumer(_ => throw new InvalidOperationException("route failed"))) { using var client = await Send("fail"); await Until(() => probe.Activities.Count >= 1); } probe.Activities.Should().ContainSingle().Which.Status.Should().Be(ActivityStatusCode.Error); } [Fact] public async Task Tracing_off_opens_no_span_on_either_side() { using var probe = new RouteTelemetryProbe(a => RouteTelemetryProbe.Tag(a, RouteTelemetryProbe.EndpointTag)?.Contains($":{_port}", StringComparison.Ordinal) == true); var routed = new TaskCompletionSource(); await using (var ctx = await StartConsumer(_ => routed.TrySetResult(), telemetry: false)) { using var template = new ProducerTemplate(ctx); template.Start(); await template.SendAsync(Uri, new Exchange(new Message("off"))); (await Task.WhenAny(routed.Task, Task.Delay(Wait))).Should().Be(routed.Task); } probe.Activities.Should().BeEmpty(); } } Path: redb-route/tests/redb.Route.Tests.Tcp/TcpTransportSecurityTests.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/tests/redb.Route.Tests.Tcp/TcpTransportSecurityTests.cs ---- using System.Net; using System.Net.Security; using System.Net.Sockets; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Tcp; namespace redb.Route.Tests.Tcp; /// /// The TCP server's TLS setup. It used to bind and accept happily with ssl=true and no /// certificate, then kill every accepted connection deep in the accept loop with an /// ArgumentNullException on SslCertPath! — a type not in its catch list. No plaintext /// ever flowed (the stream becomes an SslStream only after a successful handshake), but the failure /// belongs at the bind, with a message about the certificate, the way the shared HTTP host does it. /// The certificate is also loaded once at start now, not re-read from disk per connection. /// public sealed class TcpTransportSecurityTests : IAsyncLifetime { private readonly List _consumers = []; private readonly List _producers = []; private readonly List _tempFiles = []; public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { foreach (var p in _producers) await p.Stop(); foreach (var c in _consumers) await c.Stop(); foreach (var f in _tempFiles) if (File.Exists(f)) File.Delete(f); } private static int GetFreePort() => global::redb.Route.Tests.Shared.TestPorts.Next(); private TcpConsumer CreateConsumer(int port, Dictionary parameters, IProcessor? processor = null, string host = "127.0.0.1") { var component = new TcpComponent(); var uri = new EndpointUri("tcp", $"/{host}:{port}", $"tcp:{host}:{port}", parameters); var endpoint = (TcpEndpoint)component.CreateEndpoint(uri); var consumer = new TcpConsumer(endpoint, processor ?? Substitute.For(), endpoint.EndpointOptions); _consumers.Add(consumer); return consumer; } private TcpProducer CreateProducer(int port, Dictionary parameters, string host = "127.0.0.1") { var component = new TcpComponent(); var uri = new EndpointUri("tcp", $"/{host}:{port}", $"tcp:{host}:{port}", parameters); var endpoint = (TcpEndpoint)component.CreateEndpoint(uri); var producer = (TcpProducer)endpoint.CreateProducer(); _producers.Add(producer); return producer; } [Fact] public async Task TlsConsumer_WithoutCertificate_RefusesToStart() { var port = GetFreePort(); var consumer = CreateConsumer(port, new Dictionary { ["ssl"] = "true" }); var act = () => consumer.Start(); (await act.Should().ThrowAsync( "failing every connection with an ArgumentNullException is not the way to report a missing certificate")) .WithMessage("*certificate*"); } [Fact] public async Task TlsConsumer_WithoutCertificate_LeavesNoListeningPort() { var port = GetFreePort(); var consumer = CreateConsumer(port, new Dictionary { ["ssl"] = "true" }); var start = () => consumer.Start(); await start.Should().ThrowAsync(); using var client = new TcpClient(); var connect = () => client.ConnectAsync(IPAddress.Loopback, port); await connect.Should().ThrowAsync( "the listener accepted connections only to kill them at once - from outside the port looked alive"); } [Fact] public async Task TlsConsumer_WithCertificate_CompletesTheHandshakeAndReceives() { var port = GetFreePort(); var received = new TaskCompletionSource(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => { received.TrySetResult(ci.Arg().In.Body?.ToString() ?? ""); return Task.CompletedTask; }); var consumer = CreateConsumer(port, new Dictionary { ["ssl"] = "true", ["sslCertPath"] = WritePfx(), ["framing"] = "TextLine", }, processor); await consumer.Start(); using var client = new TcpClient(); await client.ConnectAsync(IPAddress.Loopback, port); await using var ssl = new SslStream(client.GetStream(), leaveInnerStreamOpen: false, (_, _, _, _) => true); await ssl.AuthenticateAsClientAsync("localhost"); var payload = Encoding.UTF8.GetBytes("over-tls\n"); await ssl.WriteAsync(payload); await ssl.FlushAsync(); (await received.Task.WaitAsync(TimeSpan.FromSeconds(10))).Should().Be("over-tls"); } [Fact] public async Task TlsConsumer_ServesManyConnections_FromOneLoadOfTheCertificate() { var port = GetFreePort(); var certPath = WritePfx(); var consumer = CreateConsumer(port, new Dictionary { ["ssl"] = "true", ["sslCertPath"] = certPath, ["framing"] = "TextLine", }); await consumer.Start(); // The PFX is gone from disk after the start. Every connection used to re-read it, so the // second client could never have completed a handshake. File.Delete(certPath); for (var i = 0; i < 2; i++) { using var client = new TcpClient(); await client.ConnectAsync(IPAddress.Loopback, port); await using var ssl = new SslStream(client.GetStream(), leaveInnerStreamOpen: false, (_, _, _, _) => true); var handshake = () => ssl.AuthenticateAsClientAsync("localhost"); await handshake.Should().NotThrowAsync( "the certificate is read once at start, not for every accepted connection"); } } // ── Bind address: the consumer parsed the host, the producer resolved it ── [Fact] public async Task Consumer_OnLocalhost_Starts() { var port = GetFreePort(); var consumer = CreateConsumer(port, new Dictionary { ["framing"] = "TextLine" }, host: "localhost"); await consumer.Start(); using var client = new TcpClient(); await client.ConnectAsync("localhost", port); client.Connected.Should().BeTrue( "IPAddress.Parse(\"localhost\") brought the consumer down with a FormatException, though the producer resolves the same name"); } [Fact] public async Task Consumer_OnUnresolvableHost_FailsWithANamedError() { var port = GetFreePort(); var consumer = CreateConsumer(port, [], host: "no-such-host.invalid"); var act = () => consumer.Start(); (await act.Should().ThrowAsync()).WithMessage("*no-such-host.invalid*"); } // ── Producer: reaching a server with a self-signed certificate ── [Fact] public async Task Producer_TrustAllCertificates_ReachesASelfSignedServer() { var port = GetFreePort(); var received = new TaskCompletionSource(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => { received.TrySetResult(ci.Arg().In.Body?.ToString() ?? ""); return Task.CompletedTask; }); var consumer = CreateConsumer(port, new Dictionary { ["ssl"] = "true", ["sslCertPath"] = WritePfx(), ["framing"] = "TextLine", }, processor); await consumer.Start(); var producer = CreateProducer(port, new Dictionary { ["ssl"] = "true", ["trustAllCertificates"] = "true", ["sslTargetHost"] = "localhost", ["framing"] = "TextLine", }); await producer.Start(); await producer.Process(new Exchange(new Message("self-signed"))); (await received.Task.WaitAsync(TimeSpan.FromSeconds(10))).Should().Be("self-signed", "the producer had no way at all to accept a self-signed certificate: staging is unreachable"); } [Fact] public async Task Producer_WithoutTrustAll_RefusesASelfSignedServer() { var port = GetFreePort(); var consumer = CreateConsumer(port, new Dictionary { ["ssl"] = "true", ["sslCertPath"] = WritePfx(), ["framing"] = "TextLine", }); await consumer.Start(); var producer = CreateProducer(port, new Dictionary { ["ssl"] = "true", ["sslTargetHost"] = "localhost", ["framing"] = "TextLine", }); var act = () => producer.Start(); // The specific type matters: ThrowAsync passed on ANY failure (a dead consumer, // a socket error) and could not tell "refused the certificate" from "never connected". await act.Should().ThrowAsync( "turning off the certificate check must be an explicit decision, not the default behaviour"); } // ── Producer mTLS: presenting a client certificate ── [Fact] public async Task Producer_PresentsClientCertificate_WhenTheServerAsksForOne() { var port = GetFreePort(); var serverCert = LoadPfx(WritePfx()); var clientCertPath = WritePfx("tcp-client"); // A raw mTLS server: this connector's own consumer does not request client certificates // (AuthenticateAsServerAsync(cert) alone), so the counterpart here is a plain SslStream. using var listener = new TcpListener(IPAddress.Loopback, port); listener.Start(); var presented = new TaskCompletionSource(); var accept = Task.Run(async () => { using var server = await listener.AcceptTcpClientAsync(); await using var ssl = new SslStream(server.GetStream(), leaveInnerStreamOpen: false, (_, _, _, _) => true); try { await ssl.AuthenticateAsServerAsync(serverCert, clientCertificateRequired: true, checkCertificateRevocation: false); presented.TrySetResult(ssl.RemoteCertificate?.Subject); } catch (Exception ex) { presented.TrySetException(ex); } }); var producer = CreateProducer(port, new Dictionary { ["ssl"] = "true", ["trustAllCertificates"] = "true", ["sslTargetHost"] = "localhost", ["clientCertPath"] = clientCertPath, ["framing"] = "TextLine", }); await producer.Start(); (await presented.Task.WaitAsync(TimeSpan.FromSeconds(10))) .Should().Contain("tcp-client", "the producer could not present a client certificate at all - an mTLS server was unreachable"); await accept; listener.Stop(); serverCert.Dispose(); } private static X509Certificate2 LoadPfx(string path) => X509CertificateLoader.LoadPkcs12FromFile(path, null); private string WritePfx(string cn = "localhost") { using var rsa = RSA.Create(2048); var request = new CertificateRequest($"CN={cn}", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); request.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, false)); var san = new SubjectAlternativeNameBuilder(); san.AddDnsName("localhost"); san.AddIpAddress(IPAddress.Loopback); request.CertificateExtensions.Add(san.Build()); using var cert = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1)); var path = Path.Combine(Path.GetTempPath(), $"redb-tcp-tls-{Guid.NewGuid():N}.pfx"); File.WriteAllBytes(path, cert.Export(X509ContentType.Pfx)); _tempFiles.Add(path); return path; } } Path: redb-route/tests/redb.Route.Tests.Tcp/TestWait.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/tests/redb.Route.Tests.Tcp/TestWait.cs ---- namespace redb.Route.Tests.Tcp; /// /// Waits for a condition instead of a fixed pause. A fixed pause is too short on a slow machine and makes the /// test fail at random; this wait ends as soon as the condition holds. /// internal static class TestWait { /// /// Polls every 20 ms until it returns true or elapses. /// At the timeout it simply returns, so the assertion that follows fails with its own message. /// public static async Task Until(Func done, int timeoutMs = 10_000) { var deadline = DateTime.UtcNow.AddMilliseconds(timeoutMs); while (!done() && DateTime.UtcNow < deadline) await Task.Delay(20); } } Path: redb-route/tests/redb.Route.Tests.Tcp/redb.Route.Tests.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/tests/redb.Route.Tests.Tcp/redb.Route.Tests.Tcp.csproj ----