Path: redb-route/tests/Shared/Conformance/LateBroker.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/Shared/Conformance/LateBroker.cs
----
using System.Net;
using System.Net.Sockets;
namespace redb.Route.Tests.Conformance;
///
/// A broker that is down until : a port that refuses connections, then forwards each one to the real
/// broker. The broker itself is never stopped, so a test of a start while the broker is down needs no docker.
///
public sealed class LateBroker : IAsyncDisposable
{
private readonly string _host;
private readonly int _port;
private readonly CancellationTokenSource _cts = new();
private TcpListener? _listener;
private Task? _accept;
/// The real broker's host.
/// The real broker's port.
public LateBroker(string host, int port)
{
_host = host;
_port = port;
}
/// The port that stands for the broker; nothing listens on it before .
public int Port { get; } = FreePort();
/// The broker comes up: connections to reach the real broker from now on.
public void Open()
{
_listener = new TcpListener(IPAddress.Loopback, Port);
_listener.Start();
_accept = AcceptAsync(_listener, _cts.Token);
}
private async Task AcceptAsync(TcpListener listener, CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
TcpClient client;
try { client = await listener.AcceptTcpClientAsync(ct); }
catch (Exception) { return; }
_ = ForwardAsync(client, ct);
}
}
private async Task ForwardAsync(TcpClient client, CancellationToken ct)
{
using (client)
using (var broker = new TcpClient())
{
try
{
await broker.ConnectAsync(_host, _port, ct);
var a = client.GetStream();
var b = broker.GetStream();
await Task.WhenAny(a.CopyToAsync(b, ct), b.CopyToAsync(a, ct));
}
catch (Exception)
{
// A closed side ends the forward.
}
}
}
private static int FreePort()
{
var probe = new TcpListener(IPAddress.Loopback, 0);
probe.Start();
var port = ((IPEndPoint)probe.LocalEndpoint).Port;
probe.Stop();
return port;
}
///
public async ValueTask DisposeAsync()
{
await _cts.CancelAsync();
_listener?.Stop();
if (_accept is not null)
await _accept;
_cts.Dispose();
}
}