Bundle: redb-route / tests/redb.Route.Tests.WebSocket (tests.redb.Route.Tests.WebSocket.txt), 20 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.WebSocket/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.WebSocket/ServiceCollectionExtensionsTests.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Route.Core; using redb.Route.Extensions; using redb.Route.Abstractions; using redb.Route.WebSocket; namespace redb.Route.Tests.WebSocket; public class ServiceCollectionExtensionsTests { [Fact] public void AddRedbRouteWebSocket_RegistersWsComponent() { var services = new ServiceCollection(); services.AddRedbRouteWebSocket(); var sp = services.BuildServiceProvider(); var component = sp.GetService(); component.Should().NotBeNull(); component!.Scheme.Should().Be("ws"); } [Fact] public void AddRedbRouteWebSocket_RegistersWssComponent() { var services = new ServiceCollection(); services.AddRedbRouteWebSocket(); var sp = services.BuildServiceProvider(); var component = sp.GetService(); component.Should().NotBeNull(); component!.Scheme.Should().Be("wss"); } [Fact] public void AddRedbRouteWebSocket_ComponentsAreSingleton() { var services = new ServiceCollection(); services.AddRedbRouteWebSocket(); var sp = services.BuildServiceProvider(); var first = sp.GetService(); var second = sp.GetService(); first.Should().BeSameAs(second); } [Fact] public async Task AddRedbRouteWebSocket_RegistersWithRouteContext() { var services = new ServiceCollection(); services.AddRedbRouteWebSocket(); await using var sp = services.BuildServiceProvider(); await using var context = new RouteContext(); foreach (var configurator in sp.GetServices()) configurator.Configure(context); context.HasComponent("ws").Should().BeTrue(); context.HasComponent("wss").Should().BeTrue(); } [Fact] public void AddRedbRouteWebSocket_ReturnsServiceCollection() { var services = new ServiceCollection(); var result = services.AddRedbRouteWebSocket(); result.Should().BeSameAs(services); } } Path: redb-route/tests/redb.Route.Tests.WebSocket/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.WebSocket/TestWait.cs ---- namespace redb.Route.Tests.WebSocket; /// /// 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.WebSocket/WsAuditFixesTests.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.WebSocket/WsAuditFixesTests.cs ---- using System.Diagnostics; using System.Net; using System.Net.Sockets; using System.Net.WebSockets; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text; using Microsoft.AspNetCore.Http; using OpenTelemetry; using OpenTelemetry.Trace; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Telemetry; using redb.Route.WebSocket; namespace redb.Route.Tests.WebSocket; /// /// The findings of the WebSocket audit, one test each. /// Every test here was red before its fix. /// public sealed class WsAuditFixesTests : 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 static WsEndpoint Endpoint(WsComponent component, string path, Dictionary? pars = null) { var raw = $"{component.Scheme}:{path}"; var uri = new EndpointUri(component.Scheme, "/" + path, raw, pars ?? []); return (WsEndpoint)component.CreateEndpoint(uri); } private WsConsumer StartConsumer(WsEndpoint endpoint, IProcessor processor) { var consumer = (WsConsumer)endpoint.CreateConsumer(processor); _consumers.Add(consumer); return consumer; } // ── WS-2. wss:// without a certificate used to open a PLAINTEXT socket ── [Fact] public async Task WssConsumer_WithoutCertificate_FailsLoud() { var port = GetFreePort(); var component = new WssComponent(); var endpoint = Endpoint(component, $"127.0.0.1:{port}/secure"); var consumer = StartConsumer(endpoint, Substitute.For()); var act = () => consumer.Start(); (await act.Should().ThrowAsync( "wss without a certificate opened a plain socket and reported wss:// in the log")) .WithMessage("*sslCertPath*"); } // ── The handshake is authenticated by a host-supplied delegate ─────────── [Fact] public async Task Authenticate_RejectsHandshakeWithoutToken() { var port = GetFreePort(); var component = new WsComponent { Authenticate = TokenAuth("good") }; var endpoint = Endpoint(component, $"127.0.0.1:{port}/secure"); var consumer = StartConsumer(endpoint, Substitute.For()); await consumer.Start(); using var client = new ClientWebSocket(); var act = () => client.ConnectAsync(new Uri($"ws://127.0.0.1:{port}/secure"), CancellationToken.None); await act.Should().ThrowAsync("an upgrade without a token must be refused"); consumer.ActiveConnections.Should().Be(0); } [Fact] public async Task Authenticate_PutsUserIdOnTheExchange() { var port = GetFreePort(); var component = new WsComponent { Authenticate = TokenAuth("good") }; var endpoint = Endpoint(component, $"127.0.0.1:{port}/secure"); var captured = new CapturingProcessor(); var consumer = StartConsumer(endpoint, captured); await consumer.Start(); using var client = new ClientWebSocket(); await client.ConnectAsync(new Uri($"ws://127.0.0.1:{port}/secure?access_token=good"), CancellationToken.None); await client.SendAsync(Encoding.UTF8.GetBytes("hi"), WebSocketMessageType.Text, true, CancellationToken.None); var deadline = DateTime.UtcNow.AddSeconds(5); while (captured.LastExchange is null && DateTime.UtcNow < deadline) await Task.Delay(20); captured.LastExchange.Should().NotBeNull(); captured.LastExchange!.In.GetHeader(WsHeaders.UserId).Should().Be("user-42"); } // ── WS-5. localhost in a consumer URI used to be a FormatException ── [Fact] public async Task Consumer_OnLocalhost_Starts() { var port = GetFreePort(); var component = new WsComponent(); var endpoint = Endpoint(component, $"localhost:{port}/chat"); var consumer = StartConsumer(endpoint, Substitute.For()); await consumer.Start(); using var client = new ClientWebSocket(); await client.ConnectAsync(new Uri($"ws://localhost:{port}/chat"), CancellationToken.None); client.State.Should().Be(WebSocketState.Open, "IPAddress.Parse(\"localhost\") threw FormatException instead of starting the listener"); } // ── WS-4. The server could not push to its own clients ── [Fact] public async Task ServerModeProducer_BroadcastsToAllClients() { var port = GetFreePort(); var component = new WsComponent(); var endpoint = Endpoint(component, $"127.0.0.1:{port}/feed"); var consumer = StartConsumer(endpoint, Substitute.For()); await consumer.Start(); using var first = new ClientWebSocket(); using var second = new ClientWebSocket(); await first.ConnectAsync(new Uri($"ws://127.0.0.1:{port}/feed"), CancellationToken.None); await second.ConnectAsync(new Uri($"ws://127.0.0.1:{port}/feed"), CancellationToken.None); await WaitForConnections(consumer, 2); var pushEndpoint = Endpoint(component, $"127.0.0.1:{port}/feed", new Dictionary { ["mode"] = "Server" }); var producer = pushEndpoint.CreateProducer(); _producers.Add(producer); await producer.Start(); await producer.Process(new Exchange(new Message("quote:42"))); (await ReceiveText(first)).Should().Be("quote:42"); (await ReceiveText(second)).Should().Be("quote:42", "a route must be able to push to its ws clients on its own, not only reply"); } [Fact] public async Task ServerModeProducer_SendsToOneConnection() { var port = GetFreePort(); var component = new WsComponent(); var endpoint = Endpoint(component, $"127.0.0.1:{port}/feed"); var consumer = StartConsumer(endpoint, Substitute.For()); await consumer.Start(); using var target = new ClientWebSocket(); using var other = new ClientWebSocket(); await target.ConnectAsync(new Uri($"ws://127.0.0.1:{port}/feed"), CancellationToken.None); await WaitForConnections(consumer, 1); var targetId = consumer.ConnectionIds.Single(); await other.ConnectAsync(new Uri($"ws://127.0.0.1:{port}/feed"), CancellationToken.None); await WaitForConnections(consumer, 2); var pushEndpoint = Endpoint(component, $"127.0.0.1:{port}/feed", new Dictionary { ["mode"] = "Server" }); var producer = pushEndpoint.CreateProducer(); _producers.Add(producer); await producer.Start(); var exchange = new Exchange(new Message("private")); exchange.In.Headers[WsHeaders.TargetConnection] = targetId; await producer.Process(exchange); (await ReceiveText(target)).Should().Be("private"); var stray = ReceiveText(other); var raced = await Task.WhenAny(stray, Task.Delay(300)); raced.Should().NotBeSameAs(stray, "an addressed push must not go to the other clients"); } [Fact] public async Task ServerModeProducer_WithoutConsumer_FailsLoud() { var port = GetFreePort(); var component = new WsComponent(); var pushEndpoint = Endpoint(component, $"127.0.0.1:{port}/nobody", new Dictionary { ["mode"] = "Server" }); var producer = pushEndpoint.CreateProducer(); _producers.Add(producer); var act = () => producer.Start(); (await act.Should().ThrowAsync()) .WithMessage("*consumer*"); } // ── WS-6. wss:// producer could not talk to a self-signed staging server ── [Fact] public async Task Producer_TrustAllCertificates_ConnectsToSelfSignedServer() { var port = GetFreePort(); var certPath = WriteSelfSignedPfx("localhost"); var serverComponent = new WssComponent(); var serverEndpoint = Endpoint(serverComponent, $"127.0.0.1:{port}/secure", new Dictionary { ["sslCertPath"] = certPath, ["inOut"] = "true", }); var consumer = StartConsumer(serverEndpoint, new EchoProcessor()); await consumer.Start(); var clientComponent = new WssComponent(); var clientEndpoint = Endpoint(clientComponent, $"localhost:{port}/secure", new Dictionary { ["trustAllCertificates"] = "true", ["inOut"] = "true", }); var producer = clientEndpoint.CreateProducer(); _producers.Add(producer); await producer.Start(); var exchange = new Exchange(new Message("tls")); await producer.Process(exchange); exchange.Out!.Body.Should().Be("echo:tls", "ClientWebSocket had no certificate check setting at all: staging was unreachable"); } // ── WS-7. reconnect=true against a dead server never returned ── [Fact] public async Task Producer_ReconnectTimeout_FailsInsteadOfHangingForever() { var port = GetFreePort(); var component = new WsComponent(); var serverEndpoint = Endpoint(component, $"127.0.0.1:{port}/dead"); var consumer = StartConsumer(serverEndpoint, Substitute.For()); await consumer.Start(); var clientEndpoint = Endpoint(component, $"127.0.0.1:{port}/dead", new Dictionary { ["reconnect"] = "true", ["reconnectInterval"] = "50", ["reconnectTimeout"] = "300", ["connectTimeout"] = "200", }); var producer = clientEndpoint.CreateProducer(); _producers.Add(producer); await producer.Start(); await producer.Process(new Exchange(new Message("while it is up"))); await consumer.Stop(); // the listener goes away under the producer var started = Stopwatch.StartNew(); var act = async () => { // The first send after the shutdown may still succeed into a socket that has not yet // noticed the close; the one after it enters the reconnect loop, where the hang was. for (var i = 0; i < 10; i++) await producer.Process(new Exchange(new Message("after it is gone"))); }; await act.Should().ThrowAsync( "with reconnect=true and maxReconnectAttempts=0 the exchange never returned: " + "no error surfaced, the dead letter did not fire, the route just hung"); started.Stop(); started.Elapsed.Should().BeLessThan(TimeSpan.FromSeconds(15), "reconnectTimeout is a ceiling, not a wish"); } // ── WS-8. the producer name leaked the URI password into the log ── [Fact] public void ProducerName_MasksPassword() { var component = new WsComponent(); var endpoint = Endpoint(component, "user:s3cr3t@example.com:9000/feed"); var producer = (WsProducer)endpoint.CreateProducer(); producer.DiagnosticName.Should().NotContain("s3cr3t", "the producer name goes to the log in the line \"producer started\""); } // ── WS-12. the producer span had no destination ── [Fact] public async Task ProducerSpan_CarriesDestination() { var port = GetFreePort(); var component = new WsComponent(); var endpoint = Endpoint(component, $"127.0.0.1:{port}/feed"); var consumer = StartConsumer(endpoint, Substitute.For()); await consumer.Start(); var activities = new List(); using var tracer = Sdk.CreateTracerProviderBuilder() .AddSource(RouteActivitySource.SourceName) .AddInMemoryExporter(activities) .Build()!; var producer = endpoint.CreateProducer(); _producers.Add(producer); await producer.Start(); await producer.Process(new Exchange(new Message("x"))); tracer.ForceFlush(1000); // The listener is process-wide (see WsTelemetrySmokeTests): select this producer's span by kind // and by its own port, not by position. var span = activities.Should().ContainSingle(a => a.Kind == ActivityKind.Producer && ((a.GetTagItem("redb.route.endpoint") as string) ?? string.Empty).Contains($":{port}/")).Subject; span.GetTagItem("messaging.destination.name").Should().Be("/feed", "SignalR had a destination, WebSocket did not, though the address is known"); } // ── WS-1. producer statistics were never recorded ── [Fact] public async Task Producer_RecordsEndpointStatistics() { var port = GetFreePort(); var component = new WsComponent(); var endpoint = Endpoint(component, $"127.0.0.1:{port}/stats"); var consumer = StartConsumer(endpoint, Substitute.For()); await consumer.Start(); var producer = endpoint.CreateProducer(); _producers.Add(producer); await producer.Start(); await producer.Process(new Exchange(new Message("hello"))); // Ownership audit: MessagesOut belongs to the core (ToProcessor / the template), so a // hand-built producer records only what the core cannot see - the wire bytes. The routed // counterpart lives in WsStatisticsOwnershipTests. var stats = (IEndpointStatistics)endpoint; stats.BytesOut.Should().Be(5, "wire bytes stay with the connector"); stats.MessagesOut.Should().Be(0, "MessagesOut is written by the core, the own write doubled it in the route"); } // ── The DSL exposes what the options gained ── [Fact] public void Dsl_BroadcastAndNewOptions() { Ws.Broadcast("0.0.0.0:8080/stream").Build() .Should().Be("ws:0.0.0.0:8080/stream?mode=Server"); Ws.Connect("staging:8443/feed").Ssl().TrustAllCertificates().Build() .Should().Be("wss:staging:8443/feed?ssl=true&trustAllCertificates=true"); Ws.Connect("host:8080/feed").Reconnect(intervalMs: 1000).ReconnectTimeout(30_000).Build() .Should().Contain("reconnectTimeout=30000"); } // ── Minor: a bad encoding name threw a bare framework ArgumentException ─── [Fact] public void UnknownEncoding_IsRejectedByValidate() { var component = new WsComponent(); var act = () => Endpoint(component, "127.0.0.1:9000/x", new Dictionary { ["encoding"] = "utf-9" }); act.Should().Throw().WithMessage("*utf-9*"); } // ── Helpers ── private static async Task WaitForConnections(WsConsumer consumer, int expected) { var deadline = DateTime.UtcNow.AddSeconds(5); while (consumer.ActiveConnections < expected && DateTime.UtcNow < deadline) await Task.Delay(20); consumer.ActiveConnections.Should().BeGreaterThanOrEqualTo(expected); } private static async Task ReceiveText(ClientWebSocket client) { var buffer = new byte[8192]; var result = await client.ReceiveAsync(buffer, CancellationToken.None); return Encoding.UTF8.GetString(buffer, 0, result.Count); } private string WriteSelfSignedPfx(string cn) { 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-ws-{Guid.NewGuid():N}.pfx"); File.WriteAllBytes(path, cert.Export(X509ContentType.Pfx)); _tempFiles.Add(path); return path; } /// /// What a host is expected to write: browsers cannot set headers on a WebSocket handshake, so /// the token comes in the query string, and a non-browser client may still use the header. /// private static Func> TokenAuth(string expected) => ctx => { var header = ctx.Request.Headers.Authorization.ToString(); var token = header.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase) ? header["Bearer ".Length..] : ctx.Request.Query["access_token"].ToString(); return Task.FromResult(token == expected ? new System.Security.Claims.ClaimsPrincipal(new System.Security.Claims.ClaimsIdentity( [new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.NameIdentifier, "user-42")], "test")) : null); }; private sealed class EchoProcessor : IProcessor { public Task Process(IExchange exchange, CancellationToken ct = default) { exchange.Out = new Message("echo:" + exchange.In.Body); return Task.CompletedTask; } } private sealed class CapturingProcessor : IProcessor { public IExchange? LastExchange { get; private set; } public Task Process(IExchange exchange, CancellationToken ct = default) { LastExchange = exchange.Snapshot(); return Task.CompletedTask; } } } Path: redb-route/tests/redb.Route.Tests.WebSocket/WsBuilderTests.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.WebSocket/WsBuilderTests.cs ---- using redb.Route.Core; using redb.Route.WebSocket; namespace redb.Route.Tests.WebSocket; public class WsBuilderTests { // ── Factory ───────────────────────────────────────────────────── [Fact] public void Listen_StartsWithWsScheme() { var uri = Ws.Listen("0.0.0.0:8080/chat").Build(); uri.Should().StartWith("ws:0.0.0.0:8080/chat"); } [Fact] public void Connect_StartsWithWsScheme() { var uri = Ws.Connect("api.example.com:443/stream").Build(); uri.Should().StartWith("ws:api.example.com:443/stream"); } [Fact] public void NullHostPort_Throws() { var act = () => Ws.Listen(null!); act.Should().Throw(); } [Fact] public void EmptyHostPort_Throws() { var act = () => Ws.Connect(""); act.Should().Throw(); } // ── Framing ───────────────────────────────────────────────────── [Fact] public void Binary_SetsParam() { var uri = Ws.Connect("h:8080/ws").Binary().Build(); uri.Should().Contain("messageType=Binary"); } [Fact] public void Encoding_SetsParam() { var uri = Ws.Connect("h:8080/ws").Encoding("utf-16").Build(); uri.Should().Contain("encoding=utf-16"); } [Fact] public void SubProtocol_SetsParam() { var uri = Ws.Listen("0.0.0.0:8080/ws").SubProtocol("graphql-ws").Build(); uri.Should().Contain("subProtocol=graphql-ws"); } // ── Socket ────────────────────────────────────────────────────── [Fact] public void ReceiveBufferSize_SetsParam() { var uri = Ws.Listen("h:8080/ws").ReceiveBufferSize(65536).Build(); uri.Should().Contain("receiveBufferSize=65536"); } [Fact] public void SendBufferSize_SetsParam() { var uri = Ws.Connect("h:8080/ws").SendBufferSize(32768).Build(); uri.Should().Contain("sendBufferSize=32768"); } [Fact] public void KeepAliveInterval_SetsParam() { var uri = Ws.Connect("h:8080/ws").KeepAliveInterval(15000).Build(); uri.Should().Contain("keepAliveInterval=15000"); } // ── Producer ──────────────────────────────────────────────────── [Fact] public void ConnectTimeout_SetsParam() { var uri = Ws.Connect("h:8080/ws").ConnectTimeout(5000).Build(); uri.Should().Contain("connectTimeout=5000"); } [Fact] public void Reconnect_SetsParams() { var uri = Ws.Connect("h:8080/ws").Reconnect(3000, 10).Build(); uri.Should().Contain("reconnect=true"); uri.Should().Contain("reconnectInterval=3000"); uri.Should().Contain("maxReconnectAttempts=10"); } // ── Consumer ──────────────────────────────────────────────────── [Fact] public void MaxConnections_SetsParam() { var uri = Ws.Listen("0.0.0.0:8080/ws").MaxConnections(100).Build(); uri.Should().Contain("maxConnections=100"); } [Fact] public void InOut_SetsParam() { var uri = Ws.Listen("0.0.0.0:8080/ws").InOut().Build(); uri.Should().Contain("inOut=true"); } // ── TLS ───────────────────────────────────────────────────────── [Fact] public void Ssl_ChangesSchemeToWss() { var uri = Ws.Connect("api.example.com/stream").Ssl().Build(); uri.Should().StartWith("wss:api.example.com/stream"); } [Fact] public void Ssl_SetsParamTrue() { var uri = Ws.Connect("h:443/ws").Ssl().Build(); uri.Should().Contain("ssl=true"); } [Fact] public void SslCertPath_SetsParam() { var uri = Ws.Listen("0.0.0.0:443/ws").SslCertPath("/certs/cert.pfx").Build(); uri.Should().Contain("sslCertPath="); } // ── Conversion ────────────────────────────────────────────────── [Fact] public void ImplicitConversion_ReturnsUri() { string uri = Ws.Listen("0.0.0.0:8080/chat").SubProtocol("json").InOut(); uri.Should().StartWith("ws:0.0.0.0:8080/chat?"); } [Fact] public void ToString_ReturnsSameAsBuild() { var builder = Ws.Connect("h:8080/ws").Binary().Reconnect(); builder.ToString().Should().Be(builder.Build()); } // ── Full chain ────────────────────────────────────────────────── [Fact] public void FullChain_Consumer_BuildsCorrectUri() { var uri = Ws.Listen("0.0.0.0:8080/chat") .SubProtocol("json") .ReceiveBufferSize(65536) .MaxConnections(200) .InOut() .Build(); uri.Should().StartWith("ws:0.0.0.0:8080/chat?"); uri.Should().Contain("subProtocol=json"); uri.Should().Contain("inOut=true"); } [Fact] public void FullChain_Producer_BuildsCorrectUri() { var uri = Ws.Connect("api.example.com:443/stream") .Ssl() .Binary() .ConnectTimeout(5000) .Reconnect(3000, 5) .Build(); uri.Should().StartWith("wss:api.example.com:443/stream?"); uri.Should().Contain("messageType=Binary"); uri.Should().Contain("reconnect=true"); } // ── Round-trip ────────────────────────────────────────────────── [Fact] public void RoundTrip_ParseAndReconstruct() { var original = Ws.Listen("0.0.0.0:8080/chat").SubProtocol("json").Build(); var parsed = EndpointUriParser.Parse(original); parsed.Scheme.Should().Be("ws"); parsed.RawParameters["subProtocol"].Should().Be("json"); } [Fact] public void RoundTrip_Wss_ParseAndReconstruct() { var original = Ws.Connect("h:443/stream").Ssl().Build(); var parsed = EndpointUriParser.Parse(original); parsed.Scheme.Should().Be("wss"); } } Path: redb-route/tests/redb.Route.Tests.WebSocket/WsComponentSharedHostFromDiTests.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.WebSocket/WsComponentSharedHostFromDiTests.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Route.Core; using redb.Route.Http; using redb.Route.WebSocket; namespace redb.Route.Tests.WebSocket; /// /// Where the component looks for the shared Kestrel host: explicitly assigned, then the context's DI /// container, then its own. The middle step is what a module host needs — it adds components by /// scanning (so ServerManager is never assigned) while the one shared manager sits in DI. /// Requested by the Tsak agent 2026-09-24; gRPC and AS2 already resolved in this order. /// public class WsComponentSharedHostFromDiTests { private static IServiceProvider ProviderWith(SharedHttpServerManager manager) => new ServiceCollection().AddSingleton(manager).BuildServiceProvider(); [Fact] public void The_manager_in_the_contexts_container_is_used_when_none_was_assigned() { var shared = new SharedHttpServerManager(); var component = new WsComponent(); using var context = new RouteContext(); context.SetServiceProvider(ProviderWith(shared)); context.AddComponent(component); component.EffectiveServerManager.Should().BeSameAs(shared); } [Fact] public void An_assigned_manager_wins_over_the_container() { var assigned = new SharedHttpServerManager(); var component = new WsComponent { ServerManager = assigned }; using var context = new RouteContext(); context.SetServiceProvider(ProviderWith(new SharedHttpServerManager())); context.AddComponent(component); component.EffectiveServerManager.Should().BeSameAs(assigned); } [Fact] public void A_manager_set_as_a_context_service_is_found_too() { var shared = new SharedHttpServerManager(); var component = new WsComponent(); using var context = new RouteContext(); context.AddService(typeof(SharedHttpServerManager), shared); context.AddComponent(component); // Both places a host can leave it are read in one order, the context services first: // a host without a DI container has AddService and nothing else. component.EffectiveServerManager.Should().BeSameAs(shared); } [Fact] public void Without_either_the_component_still_owns_one() { var component = new WsComponent(); using var context = new RouteContext(); context.AddComponent(component); component.EffectiveServerManager.Should().NotBeNull(); } } Path: redb-route/tests/redb.Route.Tests.WebSocket/WsComponentTests.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.WebSocket/WsComponentTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.WebSocket; namespace redb.Route.Tests.WebSocket; public class WsComponentTests { [Fact] public void Scheme_IsWs() { var component = new WsComponent(); component.Scheme.Should().Be("ws"); } [Fact] public async Task AssemblyScan_RegistersWs_AndWss() { // The Tsak worker builds a module's components by this scan, through parameterless constructors. await using var context = new RouteContext(); redb.Route.Extensions.RouteContextExtensions.AddComponents(context, typeof(WsComponent).Assembly); context.GetComponent("ws").Should().NotBeNull().And.NotBeOfType(); context.GetComponent("wss").Should().NotBeNull(); } [Fact] public void WssComponent_Scheme_IsWss() { var component = new WssComponent(); component.Scheme.Should().Be("wss"); } [Fact] public void CreateEndpoint_ValidUri_ReturnsWsEndpoint() { var component = new WsComponent(); var uri = new EndpointUri("ws", "/127.0.0.1:9000/chat", "ws:127.0.0.1:9000/chat", new Dictionary()); var endpoint = component.CreateEndpoint(uri); endpoint.Should().BeOfType(); } [Fact] public void CreateEndpoint_NullUri_Throws() { var component = new WsComponent(); var act = () => component.CreateEndpoint(null!); act.Should().Throw(); } [Theory] [InlineData("/127.0.0.1:9000/chat", "127.0.0.1", 9000)] [InlineData("localhost:8080", "localhost", 8080)] [InlineData("/0.0.0.0:5555/feed", "0.0.0.0", 5555)] [InlineData("/myhost:443", "myhost", 443)] public void ParseHostPort_ExtractsCorrectly(string path, string expectedHost, int expectedPort) { var options = new WsEndpointOptions(); WsComponent.ParseHostPort(path, options); options.Host.Should().Be(expectedHost); options.Port.Should().Be(expectedPort); } [Theory] [InlineData("/127.0.0.1:9000/chat", "/chat")] [InlineData("/0.0.0.0:5000", "/")] [InlineData("/host:8080/a/b/c", "/a/b/c")] public void ExtractPath_CorrectPath(string uriPath, string expected) { WsComponent.ExtractPath(uriPath).Should().Be(expected); } [Fact] public void CreateEndpoint_BindsMessageType() { var component = new WsComponent(); var uri = new EndpointUri("ws", "/127.0.0.1:9000", "ws:127.0.0.1:9000", new Dictionary { ["messageType"] = "Binary" }); var endpoint = (WsEndpoint)component.CreateEndpoint(uri); endpoint.EndpointOptions.MessageType.Should().Be(WsMessageType.Binary); } [Fact] public void CreateEndpoint_BindsSubProtocol() { var component = new WsComponent(); var uri = new EndpointUri("ws", "/127.0.0.1:9000", "ws:127.0.0.1:9000", new Dictionary { ["subProtocol"] = "graphql-ws" }); var endpoint = (WsEndpoint)component.CreateEndpoint(uri); endpoint.EndpointOptions.SubProtocol.Should().Be("graphql-ws"); } [Fact] public void CreateEndpoint_BindsKeepAliveInterval() { var component = new WsComponent(); var uri = new EndpointUri("ws", "/127.0.0.1:9000", "ws:127.0.0.1:9000", new Dictionary { ["keepAliveInterval"] = "5000" }); var endpoint = (WsEndpoint)component.CreateEndpoint(uri); endpoint.EndpointOptions.KeepAliveInterval.Should().Be(5000); } [Fact] public void CreateEndpoint_BindsReconnectOptions() { var component = new WsComponent(); var uri = new EndpointUri("ws", "/127.0.0.1:9000", "ws:127.0.0.1:9000", new Dictionary { ["reconnect"] = "true", ["reconnectInterval"] = "3000", ["maxReconnectAttempts"] = "5" }); var endpoint = (WsEndpoint)component.CreateEndpoint(uri); endpoint.EndpointOptions.Reconnect.Should().BeTrue(); endpoint.EndpointOptions.ReconnectInterval.Should().Be(3000); endpoint.EndpointOptions.MaxReconnectAttempts.Should().Be(5); } [Fact] public void CreateEndpoint_BindsConsumerOptions() { var component = new WsComponent(); var uri = new EndpointUri("ws", "/127.0.0.1:9000", "ws:127.0.0.1:9000", new Dictionary { ["maxConnections"] = "50", ["inOut"] = "true" }); var endpoint = (WsEndpoint)component.CreateEndpoint(uri); endpoint.EndpointOptions.MaxConnections.Should().Be(50); endpoint.EndpointOptions.InOut.Should().BeTrue(); } [Fact] public void WssComponent_CreateEndpoint_SetsSslTrue() { var component = new WssComponent(); var uri = new EndpointUri("wss", "/127.0.0.1:443", "wss:127.0.0.1:443", new Dictionary()); var endpoint = (WsEndpoint)component.CreateEndpoint(uri); endpoint.EndpointOptions.Ssl.Should().BeTrue(); } [Fact] public void ConsumerPath_Extracted() { var component = new WsComponent(); var uri = new EndpointUri("ws", "/127.0.0.1:9000/chat", "ws:127.0.0.1:9000/chat", new Dictionary()); var endpoint = (WsEndpoint)component.CreateEndpoint(uri); endpoint.ConsumerPath.Should().Be("/chat"); } [Fact] public void BuildProducerUrl_CorrectFormat() { var component = new WsComponent(); var uri = new EndpointUri("ws", "/echo.example.com:8080/feed", "ws:echo.example.com:8080/feed", new Dictionary()); var endpoint = (WsEndpoint)component.CreateEndpoint(uri); endpoint.BuildProducerUrl().Should().Be("ws://echo.example.com:8080/feed"); } [Fact] public void BuildProducerUrl_Wss_CorrectScheme() { var component = new WssComponent(); var uri = new EndpointUri("wss", "/secure.example.com:443/ws", "wss:secure.example.com:443/ws", new Dictionary()); var endpoint = (WsEndpoint)component.CreateEndpoint(uri); endpoint.BuildProducerUrl().Should().Be("wss://secure.example.com:443/ws"); } [Fact] public void CreateProducer_ReturnsWsProducer() { var component = new WsComponent(); var uri = new EndpointUri("ws", "/127.0.0.1:9000", "ws:127.0.0.1:9000", new Dictionary()); var endpoint = (WsEndpoint)component.CreateEndpoint(uri); endpoint.CreateProducer().Should().BeOfType(); } [Fact] public void CreateConsumer_ReturnsWsConsumer() { var component = new WsComponent(); var uri = new EndpointUri("ws", "/127.0.0.1:9000", "ws:127.0.0.1:9000", new Dictionary()); var endpoint = (WsEndpoint)component.CreateEndpoint(uri); var processor = Substitute.For(); endpoint.CreateConsumer(processor).Should().BeOfType(); } [Fact] public void CreateConsumer_NullProcessor_Throws() { var component = new WsComponent(); var uri = new EndpointUri("ws", "/127.0.0.1:9000", "ws:127.0.0.1:9000", new Dictionary()); var endpoint = (WsEndpoint)component.CreateEndpoint(uri); var act = () => endpoint.CreateConsumer(null!); act.Should().Throw(); } } Path: redb-route/tests/redb.Route.Tests.WebSocket/WsConnectionFactoryTests.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.WebSocket/WsConnectionFactoryTests.cs ---- using redb.Route.Core; using redb.Route.WebSocket; namespace redb.Route.Tests.WebSocket; /// /// 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 WsConnectionFactoryTests { private const string Secret = "pfxP4ssw0rd"; private static WsComponent Wire(string name, WsConnectionFactory factory, string scheme = "ws") { var context = new RouteContext(); var component = new WsComponent(scheme); context.AddComponent(component); context.AddToRegistry(name, factory); return component; } [Fact] public void Factory_SuppliesCertPassword_WhenUriCarriesNone() { var component = Wire("secure-ws", new WsConnectionFactory { Ssl = true, SslCertPath = "/etc/redb/certs/server.pfx", SslCertPassword = Secret }); var uri = EndpointUriParser.Parse("ws://0.0.0.0:9000/feed?connectionFactory=secure-ws"); var endpoint = component.CreateEndpoint(uri); endpoint.Should().NotBeNull(); uri.ToUriString().Should().NotContain(Secret); uri.ToString().Should().NotContain(Secret); } [Fact] public void WssScheme_StillForcesTls_RegardlessOfFactory() { // The factory says Ssl=false, but the wss scheme must still win. var component = Wire("plain", new WsConnectionFactory { Ssl = false }, "wss"); var uri = EndpointUriParser.Parse("wss://0.0.0.0:9443/feed?connectionFactory=plain"); var endpoint = (WsEndpoint)component.CreateEndpoint(uri); endpoint.EndpointOptions.Ssl.Should().BeTrue(); } [Fact] public void MissingFactory_FailsLoud() { var context = new RouteContext(); var component = new WsComponent(); context.AddComponent(component); var uri = EndpointUriParser.Parse("ws://0.0.0.0:9000/feed?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.WebSocket/WsConsumerTests.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.WebSocket/WsConsumerTests.cs ---- using System.Net; using System.Net.Sockets; using System.Net.WebSockets; using System.Text; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.WebSocket; namespace redb.Route.Tests.WebSocket; /// /// Tests for WsConsumer. Starts a real embedded WsConsumer (Kestrel-based WS server) /// and connects to it with System.Net.WebSockets.ClientWebSocket. /// public class WsConsumerTests : IAsyncLifetime { private WsConsumer? _consumer; private int _port; 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 (_consumer is not null) await _consumer.Stop(); } private WsConsumer CreateConsumer(bool inOut = false, int maxConnections = 0, WsMessageType messageType = WsMessageType.Text, string path = "/ws", string? subProtocol = null) { var parameters = new Dictionary { ["messageType"] = messageType.ToString() }; if (inOut) parameters["inOut"] = "true"; if (maxConnections > 0) parameters["maxConnections"] = maxConnections.ToString(); if (subProtocol is not null) parameters["subProtocol"] = subProtocol; var component = new WsComponent(); var uri = new EndpointUri("ws", $"/127.0.0.1:{_port}{path}", $"ws:127.0.0.1:{_port}{path}", parameters); var endpoint = (WsEndpoint)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 WsConsumer(endpoint, processor, endpoint.EndpointOptions); return _consumer; } private async Task ConnectClient(string path = "/ws", string? subProtocol = null) { var ws = new ClientWebSocket(); if (subProtocol is not null) ws.Options.AddSubProtocol(subProtocol); await ws.ConnectAsync(new Uri($"ws://127.0.0.1:{_port}{path}"), CancellationToken.None); return ws; } private static async Task SendText(ClientWebSocket ws, string text) { var data = Encoding.UTF8.GetBytes(text); await ws.SendAsync(data, WebSocketMessageType.Text, endOfMessage: true, CancellationToken.None); } private static async Task SendBinary(ClientWebSocket ws, byte[] data) { await ws.SendAsync(data, WebSocketMessageType.Binary, endOfMessage: true, CancellationToken.None); } private static async Task ReceiveText(ClientWebSocket ws) { using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); var buffer = new byte[4096]; using var ms = new MemoryStream(); WebSocketReceiveResult result; do { result = await ws.ReceiveAsync(buffer, cts.Token); ms.Write(buffer, 0, result.Count); } while (!result.EndOfMessage); return Encoding.UTF8.GetString(ms.ToArray()); } private static async Task ReceiveBinary(ClientWebSocket ws) { using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); var buffer = new byte[4096]; using var ms = new MemoryStream(); WebSocketReceiveResult result; do { result = await ws.ReceiveAsync(buffer, cts.Token); ms.Write(buffer, 0, result.Count); } while (!result.EndOfMessage); return ms.ToArray(); } // ── Basic reception ── [Fact] public async Task Consumer_Text_ReceivesMessage() { var consumer = CreateConsumer(); await consumer.Start(); using var ws = await ConnectClient(); await SendText(ws, "hello ws"); await TestWait.Until(() => _lastExchange is not null); _lastExchange.Should().NotBeNull(); _lastExchange!.In.Body.Should().Be("hello ws"); } [Fact] public async Task Consumer_Text_BodyIsString() { var consumer = CreateConsumer(); await consumer.Start(); using var ws = await ConnectClient(); await SendText(ws, "typed"); await TestWait.Until(() => _lastExchange is not null); _lastExchange!.In.Body.Should().BeOfType(); } [Fact] public async Task Consumer_Binary_ReceivesMessage() { var consumer = CreateConsumer(messageType: WsMessageType.Binary); await consumer.Start(); using var ws = await ConnectClient(); var payload = new byte[] { 10, 20, 30 }; await SendBinary(ws, payload); await TestWait.Until(() => _lastExchange is not null); _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(); using var ws = await ConnectClient(); for (var i = 0; i < 5; i++) await SendText(ws, $"msg-{i}"); await TestWait.Until(() => consumer.ProcessedCount >= 5); lock (_capturedExchanges) _capturedExchanges.Should().HaveCount(5); consumer.ProcessedCount.Should().Be(5); } // ── Headers ── [Fact] public async Task Consumer_SetsExchangeHeaders() { var consumer = CreateConsumer(); await consumer.Start(); using var ws = await ConnectClient(); await SendText(ws, "header test"); await TestWait.Until(() => _lastExchange is not null); var h = _lastExchange!.In.Headers; h[WsHeaders.RemoteAddress].Should().NotBeNull(); h[WsHeaders.LocalAddress].Should().NotBeNull(); h[WsHeaders.ConnectionId].Should().NotBeNull(); h[WsHeaders.MessageType].Should().Be("Text"); h[WsHeaders.ByteCount].Should().NotBeNull(); h[WsHeaders.Ssl].Should().Be("False"); h[WsHeaders.Path].Should().Be("/ws"); } // ── ExchangePattern ── [Fact] public async Task Consumer_InOnly_PatternIsInOnly() { var consumer = CreateConsumer(inOut: false); await consumer.Start(); using var ws = await ConnectClient(); await SendText(ws, "fire-and-forget"); await TestWait.Until(() => _lastExchange is not null); _lastExchange!.Pattern.Should().Be(ExchangePattern.InOnly); } [Fact] public async Task Consumer_InOut_PatternIsInOut() { _processorAction = ex => { ex.Out = new Message("reply"); return Task.CompletedTask; }; var consumer = CreateConsumer(inOut: true); await consumer.Start(); using var ws = await ConnectClient(); await SendText(ws, "request"); var response = await ReceiveText(ws); response.Should().Be("reply"); _lastExchange!.Pattern.Should().Be(ExchangePattern.InOut); } // ── InOut response ── [Fact] public async Task Consumer_InOut_Binary_ReturnsResponse() { _processorAction = ex => { ex.Out = new Message(new byte[] { 99, 88, 77 }); return Task.CompletedTask; }; var consumer = CreateConsumer(inOut: true, messageType: WsMessageType.Binary); await consumer.Start(); using var ws = await ConnectClient(); await SendBinary(ws, new byte[] { 1, 2, 3 }); var response = await ReceiveBinary(ws); response.Should().BeEquivalentTo(new byte[] { 99, 88, 77 }); } // ── Connection tracking ── [Fact] public async Task Consumer_ActiveConnections_TracksClients() { var consumer = CreateConsumer(); await consumer.Start(); using var ws1 = await ConnectClient(); await TestWait.Until(() => consumer.ActiveConnections >= 1); consumer.ActiveConnections.Should().BeGreaterThanOrEqualTo(1); using var ws2 = await ConnectClient(); await TestWait.Until(() => consumer.ActiveConnections >= 2); consumer.ActiveConnections.Should().BeGreaterThanOrEqualTo(2); } // ── ProcessedCount ── [Fact] public async Task Consumer_ProcessedCount_Increments() { var consumer = CreateConsumer(); await consumer.Start(); consumer.ProcessedCount.Should().Be(0); using var ws = await ConnectClient(); await SendText(ws, "one"); await TestWait.Until(() => consumer.ProcessedCount >= 1); consumer.ProcessedCount.Should().Be(1); await SendText(ws, "two"); await TestWait.Until(() => consumer.ProcessedCount >= 2); consumer.ProcessedCount.Should().Be(2); } // ── Non-WebSocket request rejected ── [Fact] public async Task Consumer_NonWsRequest_Returns400() { var consumer = CreateConsumer(); await consumer.Start(); using var httpClient = new HttpClient(); var response = await httpClient.GetAsync($"http://127.0.0.1:{_port}/ws"); response.StatusCode.Should().Be(System.Net.HttpStatusCode.BadRequest); } // ── Stop gracefully ── [Fact] public async Task Consumer_Stop_DisconnectsClients() { var consumer = CreateConsumer(); await consumer.Start(); using var ws = await ConnectClient(); await Task.Delay(50); await consumer.Stop(); _consumer = null; // prevent double-stop consumer.ActiveConnections.Should().Be(0); } // ── Multiple concurrent clients ── [Fact] public async Task Consumer_ConcurrentClients_AllProcessed() { var consumer = CreateConsumer(); await consumer.Start(); var clients = new List(); for (var i = 0; i < 3; i++) { var ws = await ConnectClient(); await SendText(ws, $"client-{i}"); clients.Add(ws); } await TestWait.Until(() => { lock (_capturedExchanges) return _capturedExchanges.Count >= 3; }); lock (_capturedExchanges) _capturedExchanges.Should().HaveCount(3); foreach (var c in clients) c.Dispose(); } // ── Processor exception ── [Fact] public async Task Consumer_ProcessorThrows_SetsExceptionOnExchange() { _processorAction = _ => throw new InvalidOperationException("boom"); var consumer = CreateConsumer(); await consumer.Start(); using var ws = await ConnectClient(); await SendText(ws, "error test"); await TestWait.Until(() => consumer.ProcessedCount >= 1); _lastExchange.Should().NotBeNull(); _lastExchange!.Exception.Should().BeOfType(); consumer.ProcessedCount.Should().Be(1); } // ── BaseUrl ── [Fact] public async Task Consumer_BaseUrl_IsSet() { var consumer = CreateConsumer(); await consumer.Start(); consumer.BaseUrl.Should().NotBeNull(); consumer.BaseUrl.Should().Contain(_port.ToString()); } // ── Empty message ── [Fact] public async Task Consumer_EmptyTextMessage_Processed() { var consumer = CreateConsumer(); await consumer.Start(); using var ws = await ConnectClient(); await SendText(ws, ""); await TestWait.Until(() => _lastExchange is not null); _lastExchange.Should().NotBeNull(); _lastExchange!.In.Body.Should().Be(""); } } Path: redb-route/tests/redb.Route.Tests.WebSocket/WsDrainTests.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.WebSocket/WsDrainTests.cs ---- using System.Net; using System.Net.Sockets; using NSubstitute; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.WebSocket; namespace redb.Route.Tests.WebSocket; /// /// Integration tests validating Fix #3: WsConsumer now has InflightDrainGuard. /// Stop() drains in-flight messages before tearing down the Kestrel server. /// [Trait("Category", "Integration")] public class WsDrainTests : IAsyncLifetime { private int _port; private WsConsumer? _consumer; private WsProducer? _producer; 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) { try { await _producer.Stop(); } catch { /* already stopped */ } } 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 WsComponent(); var parameters = new Dictionary(); var cUri = new EndpointUri("ws", $"/127.0.0.1:{_port}/ws", $"ws:127.0.0.1:{_port}/ws", parameters); var cEndpoint = (WsEndpoint)component.CreateEndpoint(cUri); _consumer = new WsConsumer(cEndpoint, processor, cEndpoint.EndpointOptions); await _consumer.Start(); var pUri = new EndpointUri("ws", $"/127.0.0.1:{_port}/ws", $"ws:127.0.0.1:{_port}/ws", parameters); var pEndpoint = (WsEndpoint)component.CreateEndpoint(pUri); _producer = (WsProducer)pEndpoint.CreateProducer(); await _producer.Start(); // Send message — processing takes 400ms _ = _producer.Process(new Exchange(new Message("drain-test"))); await processingStarted.Task; // Stop consumer — InflightDrainGuard should wait for processing to finish await _consumer.Stop(); _consumer = null; processedCount.Should().Be(1, "in-flight message must complete before Stop returns (InflightDrainGuard)"); } [Fact] public async Task Drain_MultipleMessages_AllCompleteBeforeStop() { var processedCount = 0; var allStarted = new CountdownEvent(3); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(async ci => { allStarted.Signal(); await Task.Delay(300, ci.Arg()); Interlocked.Increment(ref processedCount); }); var component = new WsComponent(); var parameters = new Dictionary(); var cUri = new EndpointUri("ws", $"/127.0.0.1:{_port}/ws", $"ws:127.0.0.1:{_port}/ws", parameters); var cEndpoint = (WsEndpoint)component.CreateEndpoint(cUri); _consumer = new WsConsumer(cEndpoint, processor, cEndpoint.EndpointOptions); await _consumer.Start(); // Send 3 messages from separate producers (each opens its own WS connection) var producers = new List(); for (int i = 0; i < 3; i++) { var pUri = new EndpointUri("ws", $"/127.0.0.1:{_port}/ws", $"ws:127.0.0.1:{_port}/ws", parameters); var pEndpoint = (WsEndpoint)component.CreateEndpoint(pUri); var p = (WsProducer)pEndpoint.CreateProducer(); await p.Start(); producers.Add(p); _ = p.Process(new Exchange(new Message($"msg-{i}"))); } allStarted.Wait(TimeSpan.FromSeconds(10)); // Stop consumer — should drain all 3 in-flight messages await _consumer.Stop(); _consumer = null; processedCount.Should().Be(3, "all in-flight messages must complete before Stop returns"); foreach (var p in producers) await p.Stop(); } } Path: redb-route/tests/redb.Route.Tests.WebSocket/WsEndpointOptionsTests.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.WebSocket/WsEndpointOptionsTests.cs ---- using redb.Route.WebSocket; namespace redb.Route.Tests.WebSocket; public class WsEndpointOptionsTests { [Fact] public void Defaults_AreCorrect() { var opts = new WsEndpointOptions(); opts.Host.Should().Be("0.0.0.0"); opts.Port.Should().Be(8080); opts.MessageType.Should().Be(WsMessageType.Text); opts.Encoding.Should().Be("utf-8"); opts.SubProtocol.Should().BeNull(); opts.ReceiveBufferSize.Should().Be(8192); opts.SendBufferSize.Should().Be(8192); opts.KeepAliveInterval.Should().Be(30_000); opts.ConnectTimeout.Should().Be(10_000); opts.Reconnect.Should().BeFalse(); opts.ReconnectInterval.Should().Be(5_000); opts.MaxReconnectAttempts.Should().Be(0); opts.MaxConnections.Should().Be(0); opts.InOut.Should().BeFalse(); opts.Ssl.Should().BeFalse(); opts.SslCertPath.Should().BeNull(); opts.SslCertPassword.Should().BeNull(); } [Fact] public void Validate_ValidOptions_NoException() { var opts = new WsEndpointOptions { Port = 9000 }; var act = () => opts.Validate(); act.Should().NotThrow(); } [Theory] [InlineData(-1)] [InlineData(70000)] public void Validate_InvalidPort_Throws(int port) { var opts = new WsEndpointOptions { Port = port }; var act = () => opts.Validate(); act.Should().Throw().WithMessage("*Port*"); } [Fact] public void Validate_InvalidReceiveBufferSize_Throws() { var opts = new WsEndpointOptions { ReceiveBufferSize = 0 }; var act = () => opts.Validate(); act.Should().Throw().WithMessage("*ReceiveBufferSize*"); } [Fact] public void Validate_InvalidSendBufferSize_Throws() { var opts = new WsEndpointOptions { SendBufferSize = -1 }; var act = () => opts.Validate(); act.Should().Throw().WithMessage("*SendBufferSize*"); } [Fact] public void Validate_NegativeKeepAliveInterval_Throws() { var opts = new WsEndpointOptions { KeepAliveInterval = -1 }; var act = () => opts.Validate(); act.Should().Throw().WithMessage("*KeepAliveInterval*"); } [Fact] public void Validate_NegativeConnectTimeout_Throws() { var opts = new WsEndpointOptions { ConnectTimeout = -1 }; var act = () => opts.Validate(); act.Should().Throw().WithMessage("*ConnectTimeout*"); } [Fact] public void Validate_InvalidReconnectInterval_Throws() { var opts = new WsEndpointOptions { ReconnectInterval = 0 }; var act = () => opts.Validate(); act.Should().Throw().WithMessage("*ReconnectInterval*"); } [Fact] public void Validate_NegativeMaxReconnectAttempts_Throws() { var opts = new WsEndpointOptions { MaxReconnectAttempts = -1 }; var act = () => opts.Validate(); act.Should().Throw().WithMessage("*MaxReconnectAttempts*"); } [Fact] public void Validate_NegativeMaxConnections_Throws() { var opts = new WsEndpointOptions { MaxConnections = -1 }; var act = () => opts.Validate(); act.Should().Throw().WithMessage("*MaxConnections*"); } [Fact] public void Validate_ZeroKeepAlive_Valid() { var opts = new WsEndpointOptions { KeepAliveInterval = 0 }; var act = () => opts.Validate(); act.Should().NotThrow(); } [Fact] public void Validate_ZeroConnectTimeout_Valid() { var opts = new WsEndpointOptions { ConnectTimeout = 0 }; var act = () => opts.Validate(); act.Should().NotThrow(); } [Fact] public void Validate_Port65535_Valid() { var opts = new WsEndpointOptions { Port = 65535 }; var act = () => opts.Validate(); act.Should().NotThrow(); } [Fact] public void MessageType_Binary_Accepted() { var opts = new WsEndpointOptions { MessageType = WsMessageType.Binary }; opts.MessageType.Should().Be(WsMessageType.Binary); } } Path: redb-route/tests/redb.Route.Tests.WebSocket/WsIntegrationTests.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.WebSocket/WsIntegrationTests.cs ---- using System.Net; using System.Net.Sockets; using System.Text; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.WebSocket; namespace redb.Route.Tests.WebSocket; /// /// End-to-end integration tests: WsProducer → WsConsumer. /// Real WebSocket connections over loopback for text and binary message types. /// public class WsIntegrationTests : IAsyncLifetime { private int _port; private WsConsumer? _consumer; private WsProducer? _producer; 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 async Task<(WsConsumer consumer, WsProducer producer)> CreatePair( WsMessageType messageType = WsMessageType.Text, bool inOut = false) { var parameters = new Dictionary { ["messageType"] = messageType.ToString() }; if (inOut) parameters["inOut"] = "true"; var component = new WsComponent(); // Consumer var cUri = new EndpointUri("ws", $"/127.0.0.1:{_port}/ws", $"ws:127.0.0.1:{_port}/ws", parameters); var cEndpoint = (WsEndpoint)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 WsConsumer(cEndpoint, processor, cEndpoint.EndpointOptions); await _consumer.Start(); // Producer var pUri = new EndpointUri("ws", $"/127.0.0.1:{_port}/ws", $"ws:127.0.0.1:{_port}/ws", parameters); var pEndpoint = (WsEndpoint)component.CreateEndpoint(pUri); _producer = (WsProducer)pEndpoint.CreateProducer(); await _producer.Start(); return (_consumer, _producer); } // ── Text ── [Fact] public async Task Text_ProducerToConsumer_StringDelivered() { var (consumer, producer) = await CreatePair(WsMessageType.Text); 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 Text_MultipleMessages_AllDelivered() { var (consumer, producer) = await CreatePair(WsMessageType.Text); 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); } // ── Binary ── [Fact] public async Task Binary_ProducerToConsumer_Delivered() { var (consumer, producer) = await CreatePair(WsMessageType.Binary); var data = new byte[] { 0xAA, 0xBB, 0xCC }; 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 Binary_MultipleMessages_AllDelivered() { var (consumer, producer) = await CreatePair(WsMessageType.Binary); 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 ── [Fact] public async Task Text_InOut_RequestResponse() { _processorAction = ex => { var input = (string)ex.In.Body!; ex.Out = new Message(input.ToUpperInvariant()); return Task.CompletedTask; }; var (consumer, producer) = await CreatePair(WsMessageType.Text, inOut: true); var exchange = new Exchange(new Message("echo me")); await producer.Process(exchange); exchange.Out.Should().NotBeNull(); exchange.Out!.Body.Should().Be("ECHO ME"); } [Fact] public async Task Binary_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) = await CreatePair(WsMessageType.Binary, inOut: true); 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 ── [Fact] public async Task Integration_ConsumerSetsAllHeaders() { var (consumer, producer) = await CreatePair(); await producer.Process(new Exchange(new Message("hdr test"))); await TestWait.Until(() => _lastExchange is not null); var h = _lastExchange!.In.Headers; h[WsHeaders.RemoteAddress].Should().NotBeNull(); h[WsHeaders.LocalAddress].Should().NotBeNull(); h[WsHeaders.ConnectionId].Should().NotBeNull(); h[WsHeaders.MessageType].Should().Be("Text"); h[WsHeaders.Ssl].Should().Be("False"); ((string)h[WsHeaders.ByteCount]!).Should().NotBeNullOrEmpty(); h[WsHeaders.Path].Should().Be("/ws"); } // ── Large payload ── [Fact] public async Task Binary_LargePayload_Delivered() { var (consumer, producer) = await CreatePair(WsMessageType.Binary); 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); } // ── Null body ── [Fact] public async Task Text_NullBody_SendsEmptyFrame() { var (consumer, producer) = await CreatePair(WsMessageType.Text); 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 Text_StreamBody_Delivered() { var (consumer, producer) = await CreatePair(WsMessageType.Text); 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.WebSocket/WsPrincipalTests.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.WebSocket/WsPrincipalTests.cs ---- using System.Net; using System.Net.Sockets; using System.Net.WebSockets; using System.Security.Claims; using System.Text; using Microsoft.AspNetCore.Http; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Http; using redb.Route.WebSocket; namespace redb.Route.Tests.WebSocket; /// /// The caller's identity on WebSocket exchanges. The shared host's resolver identifies the handshake and /// the consumer puts the principal on every exchange the socket produces; the component's own /// , when set, decides instead. /// public sealed class WsPrincipalTests : IAsyncLifetime { private readonly List _consumers = []; private readonly List _managers = []; public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { foreach (var c in _consumers) await c.Stop(); foreach (var m in _managers) await m.DisposeAsync(); } private static int GetFreePort() => global::redb.Route.Tests.Shared.TestPorts.Next(); private static ClaimsPrincipal User(string id) => new(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, id)], "test")); private static Func> TokenIdentifies(string id) => ctx => Task.FromResult(ctx.Request.Query["access_token"].ToString() == "good" ? User(id) : null); private SharedHttpServerManager Manager(Func> resolve) { var manager = new SharedHttpServerManager(new HttpHostingOptions { ResolvePrincipal = resolve }); _managers.Add(manager); return manager; } private async Task SendOneFrameAsync(WsComponent component, int port) { var uri = new EndpointUri(component.Scheme, $"/127.0.0.1:{port}/who", $"{component.Scheme}:127.0.0.1:{port}/who", new Dictionary()); var endpoint = (WsEndpoint)component.CreateEndpoint(uri); var captured = new CapturingProcessor(); var consumer = (WsConsumer)endpoint.CreateConsumer(captured); _consumers.Add(consumer); await consumer.Start(); using var client = new ClientWebSocket(); await client.ConnectAsync(new Uri($"ws://127.0.0.1:{port}/who?access_token=good"), CancellationToken.None); await client.SendAsync(Encoding.UTF8.GetBytes("hi"), WebSocketMessageType.Text, true, CancellationToken.None); var deadline = DateTime.UtcNow.AddSeconds(5); while (captured.LastExchange is null && DateTime.UtcNow < deadline) await Task.Delay(20); captured.LastExchange.Should().NotBeNull(); return captured.LastExchange!; } [Fact] public async Task HostResolver_PrincipalAndUserIdReachTheExchange() { var port = GetFreePort(); var component = new WsComponent { ServerManager = Manager(TokenIdentifies("host-user")) }; var exchange = await SendOneFrameAsync(component, port); ExchangePrincipal.Get(exchange)!.FindFirst(ClaimTypes.NameIdentifier)!.Value.Should().Be("host-user"); exchange.In.GetHeader(WsHeaders.UserId).Should().Be("host-user", "the header is derived from the same principal, whoever produced it"); } [Fact] public async Task ComponentAuthenticate_TakesPrecedenceOverTheHostResolver() { var port = GetFreePort(); var component = new WsComponent { ServerManager = Manager(_ => Task.FromResult(User("host-user"))), Authenticate = TokenIdentifies("ws-user"), }; var exchange = await SendOneFrameAsync(component, port); ExchangePrincipal.Get(exchange)!.FindFirst(ClaimTypes.NameIdentifier)!.Value.Should().Be("ws-user", "the transport's own hook is the more specific decision on its path"); } private sealed class CapturingProcessor : IProcessor { public IExchange? LastExchange { get; private set; } public Task Process(IExchange exchange, CancellationToken ct = default) { LastExchange = exchange.Snapshot(); return Task.CompletedTask; } } } Path: redb-route/tests/redb.Route.Tests.WebSocket/WsProducerTests.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.WebSocket/WsProducerTests.cs ---- using System.Net; using System.Net.Sockets; using System.Net.WebSockets; using System.Text; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.WebSocket; namespace redb.Route.Tests.WebSocket; /// /// Tests for WsProducer. Starts a real embedded WsConsumer server /// and connects to it with the WsProducer client. /// public class WsProducerTests : IAsyncLifetime { private int _port; private WsConsumer? _serverConsumer; private IExchange? _lastExchange; 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 (_serverConsumer is not null) await _serverConsumer.Stop(); } private async Task StartServer(bool inOut = false, WsMessageType messageType = WsMessageType.Text, string? subProtocol = null) { var parameters = new Dictionary { ["messageType"] = messageType.ToString() }; if (inOut) parameters["inOut"] = "true"; if (subProtocol is not null) parameters["subProtocol"] = subProtocol; var component = new WsComponent(); var uri = new EndpointUri("ws", $"/127.0.0.1:{_port}/ws", $"ws:127.0.0.1:{_port}/ws", parameters); var endpoint = (WsEndpoint)component.CreateEndpoint(uri); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(async ci => { var ex = ci.Arg(); _lastExchange = ex; if (_processorAction is not null) await _processorAction(ex); }); _serverConsumer = new WsConsumer(endpoint, processor, endpoint.EndpointOptions); await _serverConsumer.Start(); return _serverConsumer; } private WsProducer CreateProducer(WsMessageType messageType = WsMessageType.Text, bool inOut = false, string? subProtocol = null, Dictionary? extra = null) { var parameters = new Dictionary(extra ?? []) { ["messageType"] = messageType.ToString() }; if (inOut) parameters["inOut"] = "true"; if (subProtocol is not null) parameters["subProtocol"] = subProtocol; var component = new WsComponent(); var uri = new EndpointUri("ws", $"/127.0.0.1:{_port}/ws", $"ws:127.0.0.1:{_port}/ws", parameters); var endpoint = (WsEndpoint)component.CreateEndpoint(uri); return (WsProducer)endpoint.CreateProducer(); } // ── Basic send ── [Fact] public async Task Producer_Text_SendsString() { await StartServer(); var producer = CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("hello ws"))); await TestWait.Until(() => _lastExchange is not null); _lastExchange.Should().NotBeNull(); _lastExchange!.In.Body.Should().Be("hello ws"); await producer.Stop(); } [Fact] public async Task Producer_Binary_SendsBytes() { await StartServer(messageType: WsMessageType.Binary); var producer = CreateProducer(WsMessageType.Binary); await producer.Start(); var data = new byte[] { 1, 2, 3, 4, 5 }; await producer.Process(new Exchange(new Message(data))); await TestWait.Until(() => _lastExchange is not null); _lastExchange.Should().NotBeNull(); _lastExchange!.In.Body.Should().BeOfType(); ((byte[])_lastExchange.In.Body!).Should().BeEquivalentTo(data); await producer.Stop(); } // ── InOut ── [Fact] public async Task Producer_InOut_ReceivesResponse() { _processorAction = ex => { ex.Out = new Message("pong"); return Task.CompletedTask; }; await StartServer(inOut: true); 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() { await StartServer(); var producer = CreateProducer(); await producer.Start(); for (var i = 0; i < 5; i++) await producer.Process(new Exchange(new Message($"msg-{i}"))); await TestWait.Until(() => _serverConsumer!.ProcessedCount >= 5); _serverConsumer!.ProcessedCount.Should().Be(5); await producer.Stop(); } // ── Headers ── [Fact] public async Task Producer_SetsExchangeHeaders() { await StartServer(); var producer = CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("test")); await producer.Process(exchange); exchange.In.Headers[WsHeaders.MessageType].Should().Be("Text"); exchange.In.Headers[WsHeaders.Ssl].Should().Be("False"); await producer.Stop(); } // ── Lifecycle ── [Fact] public async Task Producer_ProcessBeforeStart_Throws() { var producer = CreateProducer(); var act = () => producer.Process(new Exchange(new Message("test"))); await act.Should().ThrowAsync(); } [Fact] public async Task Producer_StartStop_Lifecycle() { await StartServer(); 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_Sends() { await StartServer(); var producer = CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message(null))); await TestWait.Until(() => _lastExchange is not null); _lastExchange.Should().NotBeNull(); await producer.Stop(); } [Fact] public async Task Producer_StreamBody_Sends() { await StartServer(); var producer = CreateProducer(); await producer.Start(); var ms = new MemoryStream(Encoding.UTF8.GetBytes("stream body")); await producer.Process(new Exchange(new Message(ms))); await TestWait.Until(() => _lastExchange is not null); _lastExchange!.In.Body.Should().Be("stream body"); await producer.Stop(); } } Path: redb-route/tests/redb.Route.Tests.WebSocket/WsRestartTests.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.WebSocket/WsRestartTests.cs ---- using System.Net.WebSockets; using System.Text; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Http; using redb.Route.WebSocket; namespace redb.Route.Tests.WebSocket; /// /// A WebSocket consumer keeps serving after Stop() and Start() of the same route context: the stop /// closes the listener's path, the start opens it again on the cached endpoint. /// public sealed class WsRestartTests : IAsyncLifetime { private readonly SharedHttpServerManager _manager = new(); private readonly RouteContext _ctx = new(); public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { await _ctx.DisposeAsync(); await _manager.DisposeAsync(); } private static async Task EchoAsync(int port, string text) { using var client = new ClientWebSocket(); await client.ConnectAsync(new Uri($"ws://127.0.0.1:{port}/chat"), CancellationToken.None); await client.SendAsync(Encoding.UTF8.GetBytes(text), WebSocketMessageType.Text, true, CancellationToken.None); var buffer = new byte[64]; var result = await client.ReceiveAsync(buffer, CancellationToken.None); return Encoding.UTF8.GetString(buffer, 0, result.Count); } [Fact] public async Task Consumer_serves_after_the_context_is_stopped_and_started_again() { var port = global::redb.Route.Tests.Shared.TestPorts.Next(); _ctx.AddComponent(new WsComponent { ServerManager = _manager }); _ctx.AddRoutes(r => r.From($"ws://127.0.0.1:{port}/chat?inOut=true").Process(e => e.Out = new Message("echo:" + e.In.Body))); await _ctx.Start(); (await EchoAsync(port, "first")).Should().Be("echo:first"); await _ctx.Stop(); await _ctx.Start(); (await EchoAsync(port, "second")).Should().Be("echo:second", "the WebSocket receiver replies after a restart"); } } Path: redb-route/tests/redb.Route.Tests.WebSocket/WsSharedHostTests.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.WebSocket/WsSharedHostTests.cs ---- using System.Net; using System.Net.Sockets; using System.Net.WebSockets; using System.Text; using Microsoft.AspNetCore.Http; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Http; using redb.Route.WebSocket; namespace redb.Route.Tests.WebSocket; /// /// The WebSocket consumer serves on the SHARED Kestrel, so a ws route and a plain /// HTTP route can live on one port — the thing that was impossible while every consumer built /// its own server (REST and WebSocket behind one reverse proxy on one port). /// public sealed class WsSharedHostTests : IAsyncLifetime { private readonly SharedHttpServerManager _manager = new(); private readonly HttpClient _http = new(); private WsConsumer? _consumer; public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { if (_consumer is not null) await _consumer.Stop(); _http.Dispose(); await _manager.DisposeAsync(); } private static int GetFreePort() => global::redb.Route.Tests.Shared.TestPorts.Next(); private WsEndpoint CreateEndpoint(int port, string path, string? extraParams = null) { var component = new WsComponent { ServerManager = _manager }; var uri = EndpointUriParser.Parse( $"ws://127.0.0.1:{port}{path}" + (extraParams is null ? "" : $"?{extraParams}")); return (WsEndpoint)component.CreateEndpoint(uri); } [Fact] public async Task WebSocketAndHttp_ShareOnePort() { var port = GetFreePort(); // A plain HTTP route registered by "another connector" on the same listener. _manager.RegisterRoute("127.0.0.1", port, "/api/health", "GET", ctx => ctx.Response.WriteAsync("healthy")); var endpoint = CreateEndpoint(port, "/chat", "inOut=true"); await endpoint.Start(); _consumer = (WsConsumer)endpoint.CreateConsumer(new EchoProcessor()); await _consumer.Start(); _manager.ServerCount.Should().Be(1, "ws and http must share ONE Kestrel"); // HTTP still works… (await _http.GetStringAsync($"http://127.0.0.1:{port}/api/health")).Should().Be("healthy"); // …and the WebSocket upgrade on the same port works too. using var client = new ClientWebSocket(); await client.ConnectAsync(new Uri($"ws://127.0.0.1:{port}/chat"), CancellationToken.None); await client.SendAsync(Encoding.UTF8.GetBytes("hello"), WebSocketMessageType.Text, true, CancellationToken.None); var buffer = new byte[64]; var result = await client.ReceiveAsync(buffer, CancellationToken.None); Encoding.UTF8.GetString(buffer, 0, result.Count).Should().Be("echo:hello"); } [Fact] public async Task NonWebSocketRequestToWsPath_Gets400() { var port = GetFreePort(); var endpoint = CreateEndpoint(port, "/chat"); await endpoint.Start(); _consumer = (WsConsumer)endpoint.CreateConsumer(new EchoProcessor()); await _consumer.Start(); var response = await _http.GetAsync($"http://127.0.0.1:{port}/chat"); response.StatusCode.Should().Be(HttpStatusCode.BadRequest); } [Fact] public async Task ConsumerStop_LeavesListenerAliveForOtherRoutes() { var port = GetFreePort(); _manager.RegisterRoute("127.0.0.1", port, "/api/health", "GET", ctx => ctx.Response.WriteAsync("healthy")); var endpoint = CreateEndpoint(port, "/chat"); await endpoint.Start(); var consumer = (WsConsumer)endpoint.CreateConsumer(new EchoProcessor()); await consumer.Start(); await consumer.Stop(); // The HTTP route on the same listener must survive the ws consumer going away. (await _http.GetStringAsync($"http://127.0.0.1:{port}/api/health")).Should().Be("healthy"); } [Fact] public async Task ConsumerRecordsEndpointStatistics() { var port = GetFreePort(); var endpoint = CreateEndpoint(port, "/stats"); await endpoint.Start(); _consumer = (WsConsumer)endpoint.CreateConsumer(new EchoProcessor()); await _consumer.Start(); using var client = new ClientWebSocket(); await client.ConnectAsync(new Uri($"ws://127.0.0.1:{port}/stats"), CancellationToken.None); await client.SendAsync(Encoding.UTF8.GetBytes("12345"), WebSocketMessageType.Text, true, CancellationToken.None); // Ownership audit: pipeline statistics (MessagesIn/BytesIn) are recorded by the core's // StatisticsProcessor around a ROUTED consumer - self-recording here double-counted them. // A hand-built consumer therefore stays at zero; the routed contract is pinned by // WsStatisticsOwnershipTests.RoutedConsumer_CountsEachFrameOnce. await Task.Delay(500); var stats = (IEndpointStatistics)endpoint; stats.MessagesIn.Should().Be(0, "MessagesIn is written by the core around the route's consumer"); stats.BytesIn.Should().Be(0); } private sealed class EchoProcessor : IProcessor { public Task Process(IExchange exchange, CancellationToken ct = default) { exchange.Out = new Message("echo:" + exchange.In.Body); return Task.CompletedTask; } } } Path: redb-route/tests/redb.Route.Tests.WebSocket/WsStatisticsOwnershipTests.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.WebSocket/WsStatisticsOwnershipTests.cs ---- using System.Net; using System.Net.Sockets; using System.Net.WebSockets; using System.Text; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.WebSocket; namespace redb.Route.Tests.WebSocket; /// /// The statistics-ownership audit (plan KAFKA_HARDENING_AND_OPTIONS_SWEEP_PLAN, question 0). /// In a ROUTED consumer the core's StatisticsProcessor already counts MessagesIn/BytesIn/Errors, /// and a routed producer is counted by ToProcessor - the connector self-recording the same /// numbers double-counted every one of them. One owner: the core counts the pipeline, the /// connector counts only what the core cannot see. /// public sealed class WsStatisticsOwnershipTests : IAsyncLifetime { private RouteContext? _context; public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { if (_context is not null) await _context.DisposeAsync(); } private static int GetFreePort() => global::redb.Route.Tests.Shared.TestPorts.Next(); [Fact] public async Task RoutedConsumer_CountsEachFrameOnce() { var port = GetFreePort(); var uri = $"ws://127.0.0.1:{port}/count"; var processed = 0; _context = new RouteContext(); _context.AddComponent(new WsComponent()); _context.AddRoutes(r => r.From(uri).Process(_ => Interlocked.Increment(ref processed))); await _context.Start(); using var client = new ClientWebSocket(); await client.ConnectAsync(new Uri($"ws://127.0.0.1:{port}/count"), CancellationToken.None); await client.SendAsync(Encoding.UTF8.GetBytes("hello"), WebSocketMessageType.Text, true, CancellationToken.None); var deadline = DateTime.UtcNow.AddSeconds(10); while (Volatile.Read(ref processed) < 1 && DateTime.UtcNow < deadline) await Task.Delay(100); processed.Should().Be(1); var stats = (IEndpointStatistics)_context.GetEndpoint(uri); await TestWait.Until(() => stats.MessagesIn >= 1 && stats.BytesIn >= 5); // A double count would land a moment later: give it the time before the exact check. await Task.Delay(300); stats.MessagesIn.Should().Be(1, "one frame - the core already counts MessagesIn, the connector's own write doubled it"); stats.BytesIn.Should().Be(5, "and the bytes were doubled too"); } [Fact] public async Task RoutedProducer_CountsEachSendOnce() { var serverPort = GetFreePort(); var serverUri = $"ws://127.0.0.1:{serverPort}/sink"; var producerUri = $"ws://127.0.0.1:{serverPort}/sink?messageType=Text"; _context = new RouteContext(); _context.AddComponent(new WsComponent()); _context.AddRoutes(r => r.From(serverUri).Process(_ => { })); _context.AddRoutes(r => r.From("direct:out").To(producerUri)); await _context.Start(); using var template = new ProducerTemplate(_context); template.Start(); await template.SendAsync("direct:out", "payload"); var stats = (IEndpointStatistics)_context.GetEndpoint(producerUri); await TestWait.Until(() => stats.MessagesOut >= 1 && stats.BytesOut >= 7); // A double count would land a moment later: give it the time before the exact check. await Task.Delay(300); stats.MessagesOut.Should().Be(1, "one send - the route's .To() already counts through ToProcessor, the own write doubled it"); stats.BytesOut.Should().Be(7, "wire bytes stay with the connector and are written once"); } } Path: redb-route/tests/redb.Route.Tests.WebSocket/WsStreamingTests.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.WebSocket/WsStreamingTests.cs ---- using System.Net; using System.Net.Sockets; using System.Net.WebSockets; using System.Text; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.WebSocket; namespace redb.Route.Tests.WebSocket; /// /// Wire-level tests for when the route puts an /// of into /// .: every yield must /// turn into one text frame with endOfMessage=true, in order, all /// belonging to the same client request. /// public class WsStreamingTests : IAsyncLifetime { private int _port; private WsConsumer? _consumer; public Task InitializeAsync() { _port = GetFreePort(); return Task.CompletedTask; } public async Task DisposeAsync() { if (_consumer is not null) await _consumer.Stop(); } private async Task StartStreamingConsumerAsync(Func onProcess) { var component = new WsComponent(); var parameters = new Dictionary { ["messageType"] = WsMessageType.Text.ToString(), ["inOut"] = "true" }; var uri = new EndpointUri("ws", $"/127.0.0.1:{_port}/ws", $"ws:127.0.0.1:{_port}/ws", parameters); var endpoint = (WsEndpoint)component.CreateEndpoint(uri); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => onProcess(ci.Arg())); _consumer = new WsConsumer(endpoint, processor, endpoint.EndpointOptions); await _consumer.Start(); return _consumer; } /// Reads one full WebSocket text message (drains until EOM). private static async Task ReceiveMessageAsync(ClientWebSocket ws, CancellationToken ct) { var buffer = new byte[1024]; var sb = new StringBuilder(); while (true) { var result = await ws.ReceiveAsync(buffer, ct).ConfigureAwait(false); if (result.MessageType == WebSocketMessageType.Close) return string.Empty; sb.Append(Encoding.UTF8.GetString(buffer, 0, result.Count)); if (result.EndOfMessage) return sb.ToString(); } } [Fact] public async Task Streaming_OneFramePerYield_OrderPreserved() { await StartStreamingConsumerAsync(ex => { ex.Out = ex.In.Clone(); ex.Out.Body = ChunksAsync(["alpha", "beta", "gamma"], delayMs: 10); return Task.CompletedTask; }); using var client = new ClientWebSocket(); using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); await client.ConnectAsync(new Uri($"ws://127.0.0.1:{_port}/ws"), cts.Token); await client.SendAsync(Encoding.UTF8.GetBytes("go"), WebSocketMessageType.Text, endOfMessage: true, cts.Token); (await ReceiveMessageAsync(client, cts.Token)).Should().Be("alpha"); (await ReceiveMessageAsync(client, cts.Token)).Should().Be("beta"); (await ReceiveMessageAsync(client, cts.Token)).Should().Be("gamma"); // No CloseAsync: WsConsumer's receive loop does not echo a Close frame // (it just returns), so a client-initiated close would raise // "remote party closed without handshake". Tracked separately. } [Fact] public async Task Streaming_EmptyChunksSkipped() { await StartStreamingConsumerAsync(ex => { ex.Out = ex.In.Clone(); // Empty / null strings must NOT produce wire frames — matches the // contract WsConsumer follows (and what LLM providers emit between // SSE keep-alives). ex.Out.Body = ChunksAsync(["one", "", "two", "", "three"], delayMs: 10); return Task.CompletedTask; }); using var client = new ClientWebSocket(); using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); await client.ConnectAsync(new Uri($"ws://127.0.0.1:{_port}/ws"), cts.Token); await client.SendAsync(Encoding.UTF8.GetBytes("go"), WebSocketMessageType.Text, endOfMessage: true, cts.Token); (await ReceiveMessageAsync(client, cts.Token)).Should().Be("one"); (await ReceiveMessageAsync(client, cts.Token)).Should().Be("two"); (await ReceiveMessageAsync(client, cts.Token)).Should().Be("three"); // See note in Streaming_OneFramePerYield_OrderPreserved. } private static async IAsyncEnumerable ChunksAsync( string[] chunks, int delayMs, [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken ct = default) { foreach (var c in chunks) { await Task.Delay(delayMs, ct).ConfigureAwait(false); yield return c; } } private static int GetFreePort() => global::redb.Route.Tests.Shared.TestPorts.Next(); } Path: redb-route/tests/redb.Route.Tests.WebSocket/WsTelemetrySmokeTests.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.WebSocket/WsTelemetrySmokeTests.cs ---- using System.Diagnostics; using System.Net; using System.Net.Sockets; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Telemetry; using redb.Route.Tests.Shared; using redb.Route.WebSocket; namespace redb.Route.Tests.WebSocket; /// Smoke test for the P1 transport span opened by . public sealed class WsTelemetrySmokeTests : IAsyncLifetime { private int _port; private WsConsumer? _serverConsumer; public Task InitializeAsync() { _port = GetFreePort(); return Task.CompletedTask; } public async Task DisposeAsync() { if (_serverConsumer is not null) await _serverConsumer.Stop(); } [Fact] public async Task WsProducer_EmitsTransportSpanWithMessagingTags() { // Start an embedded WS server (consumer) var component = new WsComponent(); var pars = new Dictionary { ["messageType"] = "Text" }; var uri = new EndpointUri("ws", $"/127.0.0.1:{_port}/ws", $"ws:127.0.0.1:{_port}/ws", pars); var endpoint = (WsEndpoint)component.CreateEndpoint(uri); var processor = Substitute.For(); _serverConsumer = new WsConsumer(endpoint, processor, endpoint.EndpointOptions); await _serverConsumer.Start(); using var capture = new SpanCapture(); // this test's spans only var producer = (WsProducer)endpoint.CreateProducer(); await producer.Start(); try { await producer.Process(new Exchange(new Message("ping"))); await Task.Delay(100); } finally { await producer.Stop(); } var activities = capture.Spans; // The capture keeps only this test's trace; pick the producer's span in it by kind and by its own port, // never by position. var activity = activities.Should().ContainSingle(a => a.Kind == ActivityKind.Producer && IsOwnEndpoint(a, _port)).Subject; activity.Source.Name.Should().Be(RouteActivitySource.SourceName); activity.GetTagItem("messaging.system").Should().Be("websocket"); activity.GetTagItem("messaging.operation").Should().Be("send"); } private static bool IsOwnEndpoint(Activity activity, int port) => activity.GetTagItem("redb.route.endpoint") is string endpoint && endpoint.Contains($":{port}/"); private static int GetFreePort() => global::redb.Route.Tests.Shared.TestPorts.Next(); } Path: redb-route/tests/redb.Route.Tests.WebSocket/WsTraceTests.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.WebSocket/WsTraceTests.cs ---- using System.Diagnostics; using System.Net.WebSockets; using System.Text; using redb.Route.Abstractions; using redb.Route.Configuration; using redb.Route.Core; using redb.Route.Tests.Telemetry; using redb.Route.WebSocket; namespace redb.Route.Tests.WebSocket; /// /// A WebSocket frame carries no headers: the consumer opens a root span per routed message, linked to the trace context /// of the upgrade request when the client sent one, never a child of the connection's activity or of whoever started /// the routes. A failed route marks it red; our own stop does not. EnableTelemetry=false opens no span on either /// side. /// public sealed class WsTraceTests { private static readonly TimeSpan Wait = TimeSpan.FromSeconds(10); private readonly int _port = global::redb.Route.Tests.Shared.TestPorts.Next(); private string Uri => $"ws://127.0.0.1:{_port}/traced"; private RouteTelemetryProbe Spans(ActivityKind kind) => new(a => a.Kind == kind && RouteTelemetryProbe.Tag(a, RouteTelemetryProbe.EndpointTag)?.Contains($":{_port}", StringComparison.Ordinal) == true); private async Task StartServer(Func step, bool telemetry = true) { var ctx = new RouteContext(options: new RouteEngineOptions { EnableTelemetry = telemetry }); ctx.AddComponent(new WsComponent()); 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 Connect(string? traceparent = null) { var client = new ClientWebSocket(); if (traceparent is not null) client.Options.SetRequestHeader("traceparent", traceparent); await client.ConnectAsync(new System.Uri(Uri), CancellationToken.None); return client; } private static Task Send(ClientWebSocket client, string text) => client.SendAsync(Encoding.UTF8.GetBytes(text), WebSocketMessageType.Text, true, CancellationToken.None); 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_linked_to_the_handshake_context() { // The host traces its requests: the upgrade request's server span is the ambient activity of the socket loop. using var aspNet = new ActivityListener { ShouldListenTo = s => s.Name == "Microsoft.AspNetCore", Sample = (ref ActivityCreationOptions _) => ActivitySamplingResult.AllDataAndRecorded, }; ActivitySource.AddActivityListener(aspNet); using var probe = Spans(ActivityKind.Consumer); var handshake = new ActivityContext(ActivityTraceId.CreateRandom(), ActivitySpanId.CreateRandom(), ActivityTraceFlags.Recorded); await using (await StartServer((_, _) => Task.CompletedTask)) { using var client = await Connect($"00-{handshake.TraceId}-{handshake.SpanId}-01"); await Send(client, "a"); await Send(client, "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 frame carries no context; the long-lived connection is never its parent"); probe.Activities.Should().OnlyContain(a => a.TraceId != handshake.TraceId); probe.Activities.Should().OnlyContain(a => a.Links.Count() == 1 && a.Links.Single().Context.TraceId == handshake.TraceId && a.Links.Single().Context.SpanId == handshake.SpanId); } [Fact] public async Task A_connection_without_trace_headers_gives_spans_without_links() { using var probe = Spans(ActivityKind.Consumer); await using (await StartServer((_, _) => Task.CompletedTask)) { using var client = await Connect(); await Send(client, "a"); await Until(() => probe.Activities.Count >= 1); } probe.Activities.Should().ContainSingle().Which.Links.Should().BeEmpty(); } [Fact] public async Task A_connection_that_sends_nothing_opens_no_span() { using var probe = Spans(ActivityKind.Consumer); await using (await StartServer((_, _) => Task.CompletedTask)) { using var client = await Connect($"00-{ActivityTraceId.CreateRandom()}-{ActivitySpanId.CreateRandom()}-01"); 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 StartServer((_, _) => throw new InvalidOperationException("route failed"))) { using var client = await Connect(); await Send(client, "fail"); await Until(() => probe.Activities.Count >= 1); } probe.Activities.Should().ContainSingle().Which.Status.Should().Be(ActivityStatusCode.Error); } [Fact] public async Task Our_stop_cancelling_the_route_does_not_mark_the_span() { using var probe = Spans(ActivityKind.Consumer); var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(async ci => { entered.TrySetResult(); await Task.Delay(Timeout.Infinite, ci.Arg()); }); var component = new WsComponent(); var endpoint = (WsEndpoint)component.CreateEndpoint( new EndpointUri("ws", $"/127.0.0.1:{_port}/traced", $"ws:127.0.0.1:{_port}/traced", new Dictionary())); var consumer = new WsConsumer(endpoint, processor, endpoint.EndpointOptions); using var stop = new CancellationTokenSource(); await consumer.Start(stop.Token); try { using var client = await Connect(); await Send(client, "wait"); (await Task.WhenAny(entered.Task, Task.Delay(Wait))).Should().Be(entered.Task); // Our stop from above: the token the consumer was started with. await stop.CancelAsync(); await Until(() => probe.Activities.Count >= 1); } finally { await consumer.Stop(); } probe.Activities.Should().ContainSingle().Which.Status.Should().NotBe(ActivityStatusCode.Error, "our own stop cancelling the route is not a failure"); } [Fact] public async Task A_failed_send_marks_the_producer_span_red() { using var probe = Spans(ActivityKind.Producer); await using (var ctx = await StartServer((_, _) => Task.CompletedTask)) { using var template = new ProducerTemplate(ctx); template.Start(); await template.SendAsync($"{Uri}?mode=Server", new Exchange(new Message("broadcast"))); // A push to a connection that is not there fails. var gone = new Message("gone"); gone.Headers[WsHeaders.TargetConnection] = "no-such-connection"; var send = () => template.SendAsync($"{Uri}?mode=Server", new Exchange(gone)); await send.Should().ThrowAsync(); } probe.Activities.Should().HaveCount(2); probe.Activities[0].Status.Should().NotBe(ActivityStatusCode.Error); probe.Activities[1].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 StartServer((_, _) => { routed.TrySetResult(); return Task.CompletedTask; }, telemetry: false)) { using var client = await Connect($"00-{ActivityTraceId.CreateRandom()}-{ActivitySpanId.CreateRandom()}-01"); await Send(client, "off"); (await Task.WhenAny(routed.Task, Task.Delay(Wait))).Should().Be(routed.Task); using var template = new ProducerTemplate(ctx); template.Start(); await template.SendAsync($"{Uri}?mode=Server", new Exchange(new Message("off"))); } probe.Activities.Should().BeEmpty(); } } Path: redb-route/tests/redb.Route.Tests.WebSocket/redb.Route.Tests.WebSocket.csproj Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.WebSocket/redb.Route.Tests.WebSocket.csproj ----