Bundle: redb-route / tests/Shared (tests.Shared.txt), 11 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/Shared/Conformance/BrokerFault.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/BrokerFault.cs
----
using System.Diagnostics;
using System.Globalization;
namespace redb.Route.Tests.Conformance;
///
/// Breaks the broker of a test stand through the docker CLI: restarts its container (every
/// connection to it is cut), freezes it (connections stay open and nothing answers, no RST),
/// lets it go on.
///
/// Rules the IBM MQ restart runs paid for:
/// the broker runs with host networking (docker run --network host), because behind docker's published-port
/// proxy a client connect made while the broker starts can hang for minutes;
/// the broker is back when its own health command says so (readinessCommand), not when a client connect
/// succeeds, because a client connect made too early can hang and hold up the connector's own;
/// the first send after a restart may still be refused, so a test retries it ().
///
///
/// The docker CLI must reach the broker's container: on a stand the test container gets the host's docker socket and
/// CLI (tests/docker/run-fault-suite.sh does that).
///
///
public sealed class BrokerFault
{
///
/// The variable that sets in whole seconds, for a slow stand host. Unset: 120 s.
///
public const string WaitVariable = "REDB_TEST_BROKER_WAIT_SECONDS";
private readonly string[] _readinessCommand;
private readonly Func, CancellationToken, Task> _docker;
private readonly TimeSpan _poll;
// A broker without a shell (a distroless image) is ready when it writes this line after the fault, not by a command.
private readonly string? _readyLog;
private string _since = "";
/// The broker's container, by its exact name.
///
/// The broker's own health command, run with docker exec inside the container; exit code 0 means ready. Each
/// element is one argument, spaces included ("sh", "-c", "a && b").
///
public BrokerFault(string container, params string[] readinessCommand)
: this(container, readinessCommand, DefaultWait, RunDockerAsync, TimeSpan.FromSeconds(1))
{
}
internal BrokerFault(string container, string[] readinessCommand, TimeSpan readyWithin,
Func, CancellationToken, Task> docker, TimeSpan poll, string? readyLog = null)
{
if (string.IsNullOrWhiteSpace(container))
throw new ArgumentException("The broker's container name is required.", nameof(container));
if (readinessCommand.Length == 0 && readyLog is null)
throw new ArgumentException("The broker's health command is required.", nameof(readinessCommand));
Container = container;
_readyLog = readyLog;
_readinessCommand = readinessCommand;
ReadyWithin = readyWithin;
_docker = docker;
_poll = poll;
}
/// The broker's container.
public string Container { get; }
/// How long waits for the broker's health command to pass.
public TimeSpan ReadyWithin { get; }
///
/// How long a test waits for the broker or the route: seconds, 120 s when it is unset.
///
public static TimeSpan DefaultWait
{
get
{
var raw = Environment.GetEnvironmentVariable(WaitVariable);
if (string.IsNullOrEmpty(raw))
return TimeSpan.FromSeconds(120);
if (!int.TryParse(raw, NumberStyles.None, CultureInfo.InvariantCulture, out var seconds) || seconds <= 0)
throw new InvalidOperationException($"{WaitVariable}='{raw}' is not a positive number of seconds.");
return TimeSpan.FromSeconds(seconds);
}
}
///
/// The fault for the container named by , or null when it is unset.
///
public static BrokerFault? FromEnvironment(string containerVariable, params string[] readinessCommand)
{
var container = Environment.GetEnvironmentVariable(containerVariable);
return string.IsNullOrEmpty(container) ? null : new BrokerFault(container, readinessCommand);
}
///
/// The fault for the container named by , or null when it is unset, for a
/// broker with no shell to run a health command in: it is ready when its log has written
/// after the fault.
///
public static BrokerFault? FromEnvironmentWithReadyLog(string containerVariable, string readyLog)
{
var container = Environment.GetEnvironmentVariable(containerVariable);
return string.IsNullOrEmpty(container)
? null
: new BrokerFault(container, [], DefaultWait, RunDockerAsync, TimeSpan.FromSeconds(1), readyLog);
}
///
/// Restarts the broker's container (docker stops it with a 10 s grace) and returns once its health command
/// passes; throws when it does not pass within .
///
public async Task RestartAsync(CancellationToken ct = default)
{
MarkFault();
await RunAsync(["restart", "-t", "10", Container], ct).ConfigureAwait(false);
await WaitReadyAsync(ct).ConfigureAwait(false);
}
///
/// Stops the broker's container (a 10 s grace) and leaves it stopped: every connection is cut and nothing takes new
/// ones until , so a test can look at the connector during the outage.
///
public Task StopAsync(CancellationToken ct = default) => RunAsync(["stop", "-t", "10", Container], ct);
/// Starts the container stopped and returns once the broker is ready.
public async Task StartAsync(CancellationToken ct = default)
{
MarkFault();
await RunAsync(["start", Container], ct).ConfigureAwait(false);
await WaitReadyAsync(ct).ConfigureAwait(false);
}
// The ready line of a broker without a shell counts only when written after this moment: the container's log keeps
// the line of every earlier start.
private void MarkFault() =>
_since = DateTime.UtcNow.AddSeconds(-1).ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture);
/// Freezes the broker's container: its connections stay open and nothing answers on them.
public Task PauseAsync(CancellationToken ct = default) => RunAsync(["pause", Container], ct);
/// Lets a paused broker go on; the connections it held are served again.
public Task UnpauseAsync(CancellationToken ct = default) => RunAsync(["unpause", Container], ct);
/// Returns once the broker's health command passes; throws when it does not within .
public async Task WaitReadyAsync(CancellationToken ct = default)
{
string[] check = _readyLog is null
? ["exec", Container, .._readinessCommand]
: ["logs", "--since", _since.Length > 0 ? _since : "1970-01-01T00:00:00Z", Container];
var deadline = DateTime.UtcNow + ReadyWithin;
DockerResult last;
while (true)
{
last = await _docker(check, ct).ConfigureAwait(false);
if (last.ExitCode == 0 && (_readyLog is null || last.Output.Contains(_readyLog, StringComparison.Ordinal)))
return;
if (DateTime.UtcNow >= deadline)
break;
await Task.Delay(_poll, ct).ConfigureAwait(false);
}
throw new InvalidOperationException(
$"The broker in {Container} is not ready {ReadyWithin.TotalSeconds:0} s after the fault: 'docker {Show(check)}' " +
$"exits {last.ExitCode}: {last.Output}");
}
///
/// Runs until it returns true or has passed, with
/// between attempts; returns the last result. For the first send after a fault, which the
/// broker may still refuse.
///
public static async Task UntilAsync(Func> attempt, TimeSpan within, TimeSpan pause,
CancellationToken ct = default)
{
var deadline = DateTime.UtcNow + within;
while (DateTime.UtcNow < deadline)
{
if (await attempt().ConfigureAwait(false))
return true;
await Task.Delay(pause, ct).ConfigureAwait(false);
}
return await attempt().ConfigureAwait(false);
}
private async Task RunAsync(string[] arguments, CancellationToken ct)
{
var result = await _docker(arguments, ct).ConfigureAwait(false);
if (result.ExitCode != 0)
throw new InvalidOperationException($"'docker {Show(arguments)}' exits {result.ExitCode}: {result.Output}");
}
// An argument with spaces (sh -c "test -f ... && ...") must stay one argument: it goes into the argument list as is.
private static string Show(IEnumerable arguments)
=> string.Join(' ', arguments.Select(a => a.Contains(' ') ? $"\"{a}\"" : a));
private static async Task RunDockerAsync(IReadOnlyList arguments, CancellationToken ct)
{
var start = new ProcessStartInfo("docker")
{
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
};
foreach (var argument in arguments)
start.ArgumentList.Add(argument);
using var docker = Process.Start(start) ?? throw new InvalidOperationException("The docker CLI does not start.");
var stdout = docker.StandardOutput.ReadToEndAsync(ct);
var stderr = docker.StandardError.ReadToEndAsync(ct);
await docker.WaitForExitAsync(ct).ConfigureAwait(false);
return new DockerResult(docker.ExitCode, ((await stdout) + (await stderr)).Trim());
}
}
/// What one docker CLI call gave: its exit code and its output, standard error included.
internal readonly record struct DockerResult(int ExitCode, string Output);
Path: redb-route/tests/Shared/Conformance/BrokerFaultFactAttribute.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/BrokerFaultFactAttribute.cs
----
namespace redb.Route.Tests.Conformance;
///
/// A fact of that breaks the broker's container: skipped unless
/// is set, as tests/docker/run-fault-suite.sh does. The release gate does not set it.
/// The test itself finds the container through the stand ().
///
public sealed class BrokerFaultFactAttribute : FactAttribute
{
/// The variable a fault run sets.
public const string Variable = "REDB_TEST_BROKER_FAULTS";
/// Skips the fact outside a fault run.
public BrokerFaultFactAttribute()
{
if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable(Variable)))
Skip = $"{Variable} is not set: the test breaks the broker's container with docker. Not run by the release " +
"gate; run it by hand with tests/docker/run-fault-suite.sh before a release that touches the " +
"connector's connection handling.";
}
}
Path: redb-route/tests/Shared/Conformance/BrokerFaultTheoryAttribute.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/BrokerFaultTheoryAttribute.cs
----
namespace redb.Route.Tests.Conformance;
///
/// A theory that breaks the broker's container (): skipped unless the variable it names holds
/// the container's name. The release gate does not set it; such tests run by hand on a stand, with
/// tests/docker/run-fault-suite.sh, before a release that touches the connector's connection handling.
///
internal sealed class BrokerFaultTheoryAttribute : TheoryAttribute
{
/// The variable that names the broker's container.
public BrokerFaultTheoryAttribute(string containerVariable)
{
ContainerVariable = containerVariable;
if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable(containerVariable)))
Skip = $"{containerVariable} is not set: the test breaks the broker's container with docker. Not run by the " +
"release gate; run it by hand with tests/docker/run-fault-suite.sh before a release that touches the " +
"connector's connection handling.";
}
/// The variable that names the broker's container.
public string ContainerVariable { get; }
}
Path: redb-route/tests/Shared/Conformance/ConnectorConformance.Flow.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/ConnectorConformance.Flow.cs
----
using System.Collections.Concurrent;
using System.Diagnostics;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Telemetry;
namespace redb.Route.Tests.Conformance;
///
/// The part of about what goes through: headers and the trace context across
/// the broker, the statistics of both sides, the concurrency bound under a slow route, and a batch accepted, rejected
/// and returned.
///
public abstract partial class ConnectorConformance
{
private const string HeaderName = "x-conformance-id";
[Fact]
public async Task A_header_set_by_the_sender_reaches_the_route_and_both_sides_count_the_message_and_its_bytes()
{
var queue = await CreateQueueAsync(deadLetter: false);
try
{
var received = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
await using var context = NewContext();
var consumerUri = ConsumerUri(queue, new ConsumerSettings());
context.AddRoutes(r => r.From(consumerUri).Process(e => received.TrySetResult(e.In)));
var producerUri = ProducerUri(queue, transacted: false);
AddSendRoute(context, producerUri);
await context.Start();
const string body = "a message with a header";
await SendAsync(context, body, new Dictionary { [HeaderName] = "42" });
var message = await received.Task.WaitAsync(Wait);
Text(message).Should().Be(body);
message.Headers.Should().ContainKey(HeaderName);
message.Headers[HeaderName]?.ToString().Should().Be("42", "a header set by the sender crosses the broker");
var sent = (IEndpointStatistics)context.GetEndpoint(producerUri);
var read = (IEndpointStatistics)context.GetEndpoint(consumerUri);
sent.MessagesOut.Should().BeGreaterThanOrEqualTo(1);
sent.BytesOut.Should().BeGreaterThanOrEqualTo(body.Length, "the producer counts the bytes it sent");
(await Until(() => read.MessagesIn >= 1)).Should().BeTrue("the consumer counts the message it read");
read.BytesIn.Should().BeGreaterThanOrEqualTo(body.Length, "the consumer counts the bytes it read");
}
finally
{
await DeleteQueueAsync(queue);
}
}
[Fact]
public async Task The_trace_context_of_the_sender_crosses_the_broker_to_the_route()
{
var queue = await CreateQueueAsync(deadLetter: false);
using var listener = new ActivityListener
{
ShouldListenTo = source => source.Name == RouteActivitySource.SourceName,
Sample = (ref ActivityCreationOptions _) => ActivitySamplingResult.AllDataAndRecorded,
};
ActivitySource.AddActivityListener(listener);
try
{
var routeActivity = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
await using var context = NewContext();
context.AddRoutes(r => r.From(ConsumerUri(queue, new ConsumerSettings()))
.Process(_ => routeActivity.TrySetResult(Activity.Current)));
AddSendRoute(context, ProducerUri(queue, transacted: false));
await context.Start();
ActivityTraceId senderTrace;
using (var sender = RouteActivitySource.Source.StartActivity("conformance sender"))
{
sender.Should().NotBeNull();
senderTrace = sender!.TraceId;
await SendAsync(context, "traced");
}
var activity = await routeActivity.Task.WaitAsync(Wait);
activity.Should().NotBeNull("the route runs inside the consumer's receive span");
var receive = activity;
while (receive is not null && receive.Kind != ActivityKind.Consumer)
receive = receive.Parent;
receive.Should().NotBeNull("the route's span has the consumer's receive span above it");
receive!.TraceId.Should().Be(senderTrace, "the receive span continues the sender's trace");
}
finally
{
await DeleteQueueAsync(queue);
}
}
[Fact]
public async Task No_more_messages_run_at_once_than_the_concurrency_bound_under_a_slow_route()
{
if (!Traits.Concurrency)
return;
var queue = await CreateQueueAsync(deadLetter: false);
try
{
const int messages = 6;
var running = 0;
var peak = 0;
var done = 0;
await using (var context = NewContext())
{
context.AddRoutes(r => r.From(ConsumerUri(queue, new ConsumerSettings { Concurrency = 2 })).Process(async (_, ct) =>
{
var now = Interlocked.Increment(ref running);
int seen;
while ((seen = Volatile.Read(ref peak)) < now && Interlocked.CompareExchange(ref peak, now, seen) != seen) { }
await Task.Delay(300, ct);
Interlocked.Decrement(ref running);
Interlocked.Increment(ref done);
}));
for (var i = 0; i < messages; i++)
await Stand.PutAsync(queue.Name, $"m{i}");
await context.Start();
(await Until(() => Volatile.Read(ref done) == messages)).Should().BeTrue("every message is run");
}
Volatile.Read(ref peak).Should().Be(2, "two at a time: more breaks the bound, fewer means the bound is not used");
}
finally
{
await DeleteQueueAsync(queue);
}
}
[Fact]
public async Task A_batch_is_handed_to_the_route_as_one_list_and_acknowledged_after_it()
{
if (!Traits.Batch)
return;
var queue = await CreateQueueAsync(deadLetter: false);
try
{
var batches = new ConcurrentQueue();
await using (var context = NewContext())
{
context.AddRoutes(r => r.From(ConsumerUri(queue, new ConsumerSettings { BatchSize = 3 }))
.Process(e => batches.Enqueue(Batch(e).Select(Text).ToArray())));
foreach (var body in new[] { "a", "b", "c" })
await Stand.PutAsync(queue.Name, body);
await context.Start();
(await Until(() => batches.Sum(b => b.Length) == 3)).Should().BeTrue("all three are run");
await Task.Delay(500);
}
batches.Should().ContainSingle().Which.Should().BeEquivalentTo(["a", "b", "c"], "three messages, one batch of three");
(await Stand.DrainAsync(queue.Name, TimeSpan.FromSeconds(1))).Should().BeEmpty("the batch is acknowledged after the route");
}
finally
{
await DeleteQueueAsync(queue);
}
}
[Fact]
public async Task A_batch_that_fails_its_attempts_sends_every_message_of_it_to_the_dead_letter_queue()
{
if (!Traits.Batch || !Traits.DeadLetter)
return;
var queue = await CreateQueueAsync(deadLetter: true, attempts: 2);
try
{
var attempts = 0;
var deadLettered = new List();
await using (var context = NewContext())
{
context.AddRoutes(r => r.From(ConsumerUri(queue, new ConsumerSettings { BatchSize = 2, Attempts = 2 }))
.Process(_ =>
{
Interlocked.Increment(ref attempts);
throw new InvalidOperationException("the batch fails");
}));
await Stand.PutAsync(queue.Name, "a");
await Stand.PutAsync(queue.Name, "b");
await context.Start();
var deadline = DateTime.UtcNow + Wait;
while (deadLettered.Count < 2 && DateTime.UtcNow < deadline)
deadLettered.AddRange(await Stand.DrainAsync(queue.DeadLetter!, TimeSpan.FromSeconds(1)));
}
deadLettered.Should().BeEquivalentTo(["a", "b"], "every message of the rejected batch");
Volatile.Read(ref attempts).Should().Be(2, "the batch runs its attempts and no more");
(await Stand.DrainAsync(queue.Name, TimeSpan.FromSeconds(1))).Should().BeEmpty();
}
finally
{
await DeleteQueueAsync(queue);
}
}
[Fact]
public async Task A_batch_half_collected_when_the_consumer_stops_is_not_run_and_its_messages_go_back()
{
if (!Traits.Batch)
return;
var queue = await CreateQueueAsync(deadLetter: false);
try
{
var runs = 0;
var context = NewContext();
var settings = new ConsumerSettings { BatchSize = 10, BatchWait = TimeSpan.FromMinutes(1) };
context.AddRoutes(r => r.From(ConsumerUri(queue, settings)).Process(_ => Interlocked.Increment(ref runs)));
await Stand.PutAsync(queue.Name, "a");
await Stand.PutAsync(queue.Name, "b");
await context.Start();
await Task.Delay(TimeSpan.FromSeconds(3));
await context.Stop();
await context.DisposeAsync();
Volatile.Read(ref runs).Should().Be(0, "the batch was still being collected");
(await Stand.DrainAsync(queue.Name, Wait)).Should().BeEquivalentTo(["a", "b"], "both went back to the queue");
}
finally
{
await DeleteQueueAsync(queue);
}
}
/// The messages of a batch exchange.
protected static IReadOnlyList Batch(IExchange exchange) => exchange.In.Body switch
{
IReadOnlyList list => list,
IEnumerable items => items.ToList(),
var body => throw new InvalidOperationException($"A batch body is a list of messages, not {body?.GetType().Name ?? "null"}."),
};
private const string SendRoute = "direct://conformance-send";
///
/// A route from to , added before the context starts: a send
/// goes through a route's send step, which counts the message on the endpoint, as in a real route.
///
protected static void AddSendRoute(RouteContext context, string producerUri)
=> context.AddRoutes(r => r.From(SendRoute).To(producerUri));
/// Sends one message through the route of .
protected static async Task SendAsync(RouteContext context, string body, IReadOnlyDictionary? headers = null)
{
var producer = context.GetEndpoint(SendRoute).CreateProducer();
await producer.Start();
try
{
var message = new Message(body);
foreach (var (name, value) in headers ?? new Dictionary())
message.Headers[name] = value;
await producer.Process(new Exchange(message));
}
finally
{
await producer.Stop();
}
}
}
Path: redb-route/tests/Shared/Conformance/ConnectorConformance.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/ConnectorConformance.cs
----
using System.Collections.Concurrent;
using System.Text;
using redb.Route.Abstractions;
using redb.Route.Configuration;
using redb.Route.Core;
using redb.Route.Processors;
using redb.Route.Transactions;
namespace redb.Route.Tests.Conformance;
///
/// What a queue connector must do, as tests a connector's suite inherits: the class gives the endpoints and the stand,
/// the tests check the connector against the broker read and written through the broker's own client
/// (). This part holds the lifecycle and the acknowledgement: a start while the broker is
/// down, a broker restart, a stop with a message in work, a retry, a poison message, receipt acknowledgement and a
/// rolled back send. A case the connector does not have () passes without running; the
/// trait list of the suite says which ones those are.
///
/// The restart case breaks the broker's container: it runs only in a fault run (),
/// so a suite that inherits this class puts it in a collection that runs alone.
///
///
/// The connector's stand.
public abstract partial class ConnectorConformance where TStand : IConnectorStand
{
/// How long a test waits for the broker or the route.
protected TimeSpan Wait => Stand.Wait;
/// The broker the suite runs against.
protected abstract TStand Stand { get; }
/// What the connector has; the cases it lacks pass without running.
protected abstract ConnectorTraits Traits { get; }
/// The port the broker takes connections on, for the case of a start while the broker is down.
protected abstract int BrokerPort { get; }
/// A new component of the connector, added to each test's context.
protected abstract IComponent CreateComponent();
///
/// Makes an empty queue for one test, with a dead letter queue when is set; the queue
/// takes messages put by before a consumer starts.
///
protected abstract Task CreateQueueAsync(bool deadLetter);
///
/// The queue of a test that asks for attempts per message. Where the broker counts the
/// attempts on the queue itself (the delivery count of a Service Bus entity), the queue is chosen by them; by default
/// the connector counts them and this is .
///
protected virtual Task CreateQueueAsync(bool deadLetter, int attempts) => CreateQueueAsync(deadLetter);
/// Removes what made, or empties it where the queues are fixed.
protected abstract Task DeleteQueueAsync(ConformanceQueue queue);
/// The consumer endpoint on with .
protected abstract string ConsumerUri(ConformanceQueue queue, ConsumerSettings settings);
///
/// The producer endpoint that sends to ; joins a transacted block.
///
protected abstract string ProducerUri(ConformanceQueue queue, bool transacted);
///
/// Whether takes messages again after a broker restart; a broker that keeps nothing over a
/// restart has it only once the consumer declared it anew. Default: true.
///
protected virtual Task QueueIsBackAsync(ConformanceQueue queue) => Task.FromResult(true);
/// The text of a received message: UTF-8 bytes or a string.
protected virtual string Text(IMessage message) => message.Body switch
{
byte[] bytes => Encoding.UTF8.GetString(bytes),
null => "",
var body => body.ToString() ?? "",
};
[Fact]
public async Task A_consumer_started_while_the_broker_is_down_receives_once_it_is_up()
{
if (!Traits.LateBroker)
return;
var queue = await CreateQueueAsync(deadLetter: false);
try
{
await using var broker = new LateBroker("localhost", BrokerPort);
var received = new ConcurrentQueue();
await using var context = NewContext(new RouteEngineOptions
{
ShutdownTimeout = TimeSpan.FromSeconds(5),
ConsumerStartRetry = new ConsumerStartRetryOptions
{
Delay = TimeSpan.FromMilliseconds(200), Multiplier = 1.0, MaxDelay = TimeSpan.FromMilliseconds(200),
},
});
context.AddRoutes(r => r.From(ConsumerUri(queue, new ConsumerSettings { Port = broker.Port })).RouteId("late")
.Process(e => received.Enqueue(Text(e.In))));
await context.Start();
context.GetRoute("late")!.Status.Should().Be(RouteStatus.Errored, "nothing takes connections on the port yet");
broker.Open();
(await Until(() => context.GetRoute("late")!.Status == RouteStatus.Started)).Should()
.BeTrue("the consumer start retry starts the consumer once the broker is up");
await Stand.PutAsync(queue.Name, "after the broker came up");
(await Until(() => received.Contains("after the broker came up"))).Should().BeTrue();
}
finally
{
await DeleteQueueAsync(queue);
}
}
[BrokerFaultFact]
public async Task A_consumer_reads_the_queue_again_after_the_broker_restarts()
{
var fault = Stand.Fault ?? throw new InvalidOperationException(
"A fault run without the broker's container: the stand's container variable is not set.");
var queue = await CreateQueueAsync(deadLetter: false);
try
{
var received = new ConcurrentQueue();
await using var context = NewContext();
var uri = ConsumerUri(queue, new ConsumerSettings());
context.AddRoutes(r => r.From(uri).RouteId("restarted").Process(e => received.Enqueue(Text(e.In))));
await context.Start();
await Stand.PutAsync(queue.Name, "before");
(await Until(() => received.Contains("before"))).Should().BeTrue("the route reads the queue before the restart");
await fault.RestartAsync();
var statistics = (IEndpointStatistics)context.GetEndpoint(uri);
(await Until(() => statistics.Reconnects > 0)).Should().BeTrue("the connection supervisor counts the reconnect");
// The broker may take the first put after a restart only once its listener and the queue are back.
(await BrokerFault.UntilAsync(() => QueueIsBackAsync(queue), Wait, TimeSpan.FromMilliseconds(500))).Should()
.BeTrue("the queue is back with the subscription");
(await BrokerFault.UntilAsync(async () =>
{
try { await Stand.PutAsync(queue.Name, "after"); return true; }
catch (Exception) { return false; }
}, Wait, TimeSpan.FromMilliseconds(500))).Should().BeTrue("the broker takes a message once it is back");
(await Until(() => received.Contains("after"))).Should().BeTrue("the consumer reads what was put after the restart");
statistics.Reconnects.Should().Be(1, "one restart is one reconnect");
statistics.HealthStatus.Should().Be(EndpointHealthStatus.Healthy, "the connection is back");
context.GetRoute("restarted")!.Status.Should().Be(RouteStatus.Started, "a lost connection does not stop the route");
}
finally
{
await DeleteQueueAsync(queue);
}
}
[Fact]
public async Task A_stop_waits_for_the_message_in_work_and_nothing_goes_back_to_the_queue()
{
var queue = await CreateQueueAsync(deadLetter: false);
try
{
var started = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var finished = 0;
var context = NewContext();
context.AddRoutes(r => r.From(ConsumerUri(queue, new ConsumerSettings())).Process(async (_, ct) =>
{
started.TrySetResult();
await Task.Delay(500, ct);
Interlocked.Increment(ref finished);
}));
await context.Start();
await Stand.PutAsync(queue.Name, "in work");
await started.Task.WaitAsync(Wait);
await context.Stop();
await context.DisposeAsync();
Volatile.Read(ref finished).Should().Be(1, "the stop waits for the message in work");
(await Stand.DrainAsync(queue.Name, TimeSpan.FromSeconds(1))).Should().BeEmpty(
"the message finished before the stop is acknowledged");
}
finally
{
await DeleteQueueAsync(queue);
}
}
[Fact]
public async Task A_failed_message_is_tried_again_and_acknowledged_once_it_succeeds()
{
var queue = await CreateQueueAsync(deadLetter: Traits.DeadLetter, attempts: 3);
try
{
var attempts = 0;
var done = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
await using (var context = NewContext())
{
context.AddRoutes(r => r.From(ConsumerUri(queue, new ConsumerSettings { Attempts = 3 })).Process(_ =>
{
if (Interlocked.Increment(ref attempts) < 3)
throw new InvalidOperationException("this attempt fails");
done.TrySetResult();
}));
await context.Start();
await Stand.PutAsync(queue.Name, "flaky");
await done.Task.WaitAsync(Wait);
await Task.Delay(500);
}
Volatile.Read(ref attempts).Should().Be(3, "two failed attempts, then the one that succeeds");
(await Stand.DrainAsync(queue.Name, TimeSpan.FromSeconds(1))).Should().BeEmpty("the success is acknowledged");
if (queue.DeadLetter is { } deadLetter)
(await Stand.DrainAsync(deadLetter, TimeSpan.FromSeconds(1))).Should().BeEmpty("it never failed for good");
}
finally
{
await DeleteQueueAsync(queue);
}
}
[Fact]
public async Task A_poison_message_lands_in_the_dead_letter_queue_after_its_attempts()
{
if (!Traits.DeadLetter)
return;
var queue = await CreateQueueAsync(deadLetter: true, attempts: 3);
try
{
var attempts = 0;
IReadOnlyList deadLettered;
await using (var context = NewContext())
{
context.AddRoutes(r => r.From(ConsumerUri(queue, new ConsumerSettings { Attempts = 3 })).Process(_ =>
{
Interlocked.Increment(ref attempts);
throw new InvalidOperationException("always fails");
}));
await context.Start();
await Stand.PutAsync(queue.Name, "poison");
deadLettered = await Stand.DrainAsync(queue.DeadLetter!, Wait);
await Task.Delay(500);
}
deadLettered.Should().Equal("poison");
Volatile.Read(ref attempts).Should().Be(3, "three attempts and no more: a poison message must not loop");
(await Stand.DrainAsync(queue.Name, TimeSpan.FromSeconds(1))).Should().BeEmpty();
}
finally
{
await DeleteQueueAsync(queue);
}
}
[Fact]
public async Task With_acknowledgement_on_receipt_a_failed_message_is_not_tried_again()
{
if (!Traits.AckOnReceipt)
return;
var queue = await CreateQueueAsync(deadLetter: false);
try
{
var attempts = 0;
await using (var context = NewContext())
{
// One attempt in the consumer: what is checked is that the broker does not deliver the message again.
var settings = new ConsumerSettings { AckOnReceipt = true, Attempts = 1 };
context.AddRoutes(r => r.From(ConsumerUri(queue, settings)).Process(_ =>
{
Interlocked.Increment(ref attempts);
throw new InvalidOperationException("fails");
}));
await context.Start();
await Stand.PutAsync(queue.Name, "at most once");
(await Until(() => Volatile.Read(ref attempts) > 0)).Should().BeTrue();
await Task.Delay(2000);
}
Volatile.Read(ref attempts).Should().Be(1,
"the broker settled the message when it handed it over and does not deliver it again");
(await Stand.DrainAsync(queue.Name, TimeSpan.FromSeconds(1))).Should().BeEmpty();
}
finally
{
await DeleteQueueAsync(queue);
}
}
[Fact]
public async Task A_send_in_a_rolled_back_block_sends_nothing_and_one_in_a_committed_block_arrives()
{
if (!Traits.Transactions)
return;
var queue = await CreateQueueAsync(deadLetter: false);
try
{
await using var context = NewContext();
await context.Start();
var producer = context.GetEndpoint(ProducerUri(queue, transacted: true)).CreateProducer();
await producer.Start();
try
{
var failed = () => InTransaction(new Exchange(new Message("rolled back")), async (e, ct) =>
{
await producer.Process(e, ct);
throw new InvalidOperationException("the unit of work failed");
});
await failed.Should().ThrowAsync();
await InTransaction(new Exchange(new Message("committed")), (e, ct) => producer.Process(e, ct));
}
finally
{
await producer.Stop();
}
(await Stand.DrainAsync(queue.Name, Wait)).Should().Equal(["committed"],
"the rolled back send never reaches the queue, the committed one does");
}
finally
{
await DeleteQueueAsync(queue);
}
}
/// A context with the connector's component.
protected RouteContext NewContext(RouteEngineOptions? options = null)
{
var context = options is null ? new RouteContext() : new RouteContext(options: options);
context.AddComponent(CreateComponent());
return context;
}
/// Runs as a .Transacted() block does: the sends commit or roll back with it.
protected static Task InTransaction(IExchange exchange, Func body)
=> new TransactedProcessor(new DelegateProcessor(body), new TransactionPolicy()).Process(exchange);
/// Waits up to for .
protected async Task Until(Func condition)
{
var deadline = DateTime.UtcNow + Wait;
while (!condition())
{
if (DateTime.UtcNow > deadline)
return false;
await Task.Delay(50);
}
return true;
}
}
/// What a connector has, for : a case it lacks passes without running.
public sealed record ConnectorTraits
{
/// The broker can settle a message on hand-off (at most once): RabbitMQ ackMode=auto.
public bool AckOnReceipt { get; init; }
/// A producer joins a transacted block: its sends commit or roll back with it.
public bool Transactions { get; init; }
/// A message that fails all its attempts goes to a dead letter queue.
public bool DeadLetter { get; init; }
/// The consumer runs more than one message at a time when asked ().
public bool Concurrency { get; init; }
/// The consumer hands the route a batch of messages ().
public bool Batch { get; init; }
///
/// A consumer started while nothing takes connections fails its start and comes up through the consumer start retry
/// once the broker is there (, a port opened late). false where that does not apply:
/// the client opens no connection at start, or it is sent past the late port to the address the broker announces.
///
public bool LateBroker { get; init; } = true;
}
/// A queue of one conformance test: its name and its dead letter queue, if it has one.
public sealed record ConformanceQueue(string Name, string? DeadLetter);
/// How a conformance test wants its consumer.
public sealed record ConsumerSettings
{
/// Attempts per message, the first included; null: the connector's default.
public int? Attempts { get; init; }
/// The broker settles the message on hand-off.
public bool AckOnReceipt { get; init; }
/// The port to connect to instead of the broker's (a ); null: the broker's.
public int? Port { get; init; }
/// How many messages run at once; null: the connector's default.
public int? Concurrency { get; init; }
///
/// Batch mode: up to this many messages per exchange, the body a list of ; null: one
/// message per exchange.
///
public int? BatchSize { get; init; }
/// In batch mode, how long the consumer waits for more messages before it runs a batch that is not full.
public TimeSpan BatchWait { get; init; } = TimeSpan.FromSeconds(2);
}
Path: redb-route/tests/Shared/Conformance/IConnectorStand.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/IConnectorStand.cs
----
namespace redb.Route.Tests.Conformance;
///
/// The broker a connector's suite runs against, reached without the connector: a test puts raw messages in and reads
/// them out through the broker's own client, so what it checks does not depend on the code under test. When the
/// broker runs in a container the suite may break, breaks it.
///
public interface IConnectorStand
{
///
/// Restarts and pauses the broker's container; null when no container is named, and the tests that need it
/// are skipped ().
///
BrokerFault? Fault { get; }
/// How long a test waits for the broker or the route to get somewhere: .
TimeSpan Wait { get; }
/// Puts one text message on with the broker's own client.
Task PutAsync(string destination, string body, CancellationToken ct = default);
///
/// Takes every message off with the broker's own client and returns their texts;
/// waits up to for the first one.
///
Task> DrainAsync(string destination, TimeSpan wait, CancellationToken ct = default);
}
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();
}
}
Path: redb-route/tests/Shared/SpanCapture.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/SpanCapture.cs
----
using System.Collections.Concurrent;
using System.Diagnostics;
using OpenTelemetry;
using OpenTelemetry.Trace;
using redb.Route.Telemetry;
namespace redb.Route.Tests.Shared;
///
/// Collects the route spans of one test through the OpenTelemetry SDK. A tracer provider sees every span the route
/// source emits in the process, those of test classes running in parallel included, and it records them from their
/// threads. The capture therefore opens a root span for the test, keeps only the route spans of that trace (what the
/// test itself caused), and keeps them in a thread-safe queue.
///
///
/// Create it before the step that emits the span, in the test's own flow: the root becomes
/// for the rest of the test, so the spans the step opens are its children.
///
internal sealed class SpanCapture : IDisposable
{
private static readonly ActivitySource TestSource = new("redb.Route.Tests.SpanCapture");
private readonly ConcurrentQueue _spans = new();
private readonly TracerProvider _provider;
// Set right after the provider is built. Between the two, a span of a test running in parallel can end and reach
// the collector: it must find no root and keep nothing, never throw into that test's thread (findings register
// row 45: a NullReferenceException here failed FileProducer tests that use no capture at all).
private volatile Activity? _root;
public SpanCapture()
{
_provider = Sdk.CreateTracerProviderBuilder()
.AddSource(RouteActivitySource.SourceName, TestSource.Name)
.AddProcessor(new Collector(this))
.Build()!;
_root = TestSource.StartActivity("test")
?? throw new InvalidOperationException("The capture's own tracer provider must sample the test root span.");
}
/// The route spans of this test, after the provider has been flushed.
public IReadOnlyList Spans
{
get
{
_provider.ForceFlush(1000);
return _spans.ToArray();
}
}
public void Dispose()
{
_root?.Dispose();
_provider.Dispose();
}
private sealed class Collector(SpanCapture owner) : BaseProcessor
{
public override void OnEnd(Activity data)
{
if (owner._root is { } root && data.Source.Name == RouteActivitySource.SourceName && data.TraceId == root.TraceId)
owner._spans.Enqueue(data);
}
}
}
Path: redb-route/tests/Shared/TestDatabases.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/TestDatabases.cs
----
using System.Data.Common;
namespace redb.Route.Tests.Shared;
///
/// Where the database suites find PostgreSQL and SQL Server. The connection strings in the tests and their
/// appsettings stay as they are; REDB_TEST_PG (host:port) and REDB_TEST_MSSQL (host,port)
/// move them to another server, for example the release gate's fresh test databases instead of a machine's permanent
/// ones. Without the variables a connection string comes back unchanged. A variable that carries a whole connection
/// string of its own (ROUTE_SQL_PG_CS, REDB_MSSQL_CS and the like) still wins: these apply only to the defaults.
/// REDB_TEST_MSSQL_DATABASE also replaces the database of a SQL Server string: the Linux gate runs the suites on
/// the host's permanent SQL Server, in a database of the run, never in the shared redb the strings name.
///
internal static class TestDatabases
{
public const string PostgresVariable = "REDB_TEST_PG";
public const string MsSqlVariable = "REDB_TEST_MSSQL";
public const string MsSqlDatabaseVariable = "REDB_TEST_MSSQL_DATABASE";
/// The PostgreSQL connection string, with host and port from REDB_TEST_PG when it is set.
public static string Postgres(string connectionString)
=> Postgres(connectionString, Environment.GetEnvironmentVariable(PostgresVariable));
/// The PostgreSQL connection string moved to (host:port); null or empty keeps it.
public static string Postgres(string connectionString, string? target)
{
target = target?.Trim();
if (string.IsNullOrEmpty(target)) return connectionString;
var colon = target.LastIndexOf(':');
var host = colon > 0 ? target[..colon] : target;
var port = colon > 0 ? target[(colon + 1)..] : "5432";
var builder = new DbConnectionStringBuilder { ConnectionString = connectionString };
foreach (var key in new[] { "Host", "Server", "Port" })
builder.Remove(key);
builder["Host"] = host;
builder["Port"] = port;
return builder.ConnectionString;
}
///
/// The SQL Server connection string, with its server from REDB_TEST_MSSQL and its database from
/// REDB_TEST_MSSQL_DATABASE when they are set.
///
public static string MsSql(string connectionString)
=> MsSql(connectionString, Environment.GetEnvironmentVariable(MsSqlVariable),
Environment.GetEnvironmentVariable(MsSqlDatabaseVariable));
///
/// The SQL Server connection string moved to (host,port) and to
/// ; null or empty keeps that part.
///
public static string MsSql(string connectionString, string? target, string? database = null)
{
target = target?.Trim();
database = database?.Trim();
if (string.IsNullOrEmpty(target) && string.IsNullOrEmpty(database)) return connectionString;
var builder = new DbConnectionStringBuilder { ConnectionString = connectionString };
if (!string.IsNullOrEmpty(target))
{
foreach (var key in new[] { "Server", "Data Source", "Address", "Addr", "Network Address" })
builder.Remove(key);
builder["Server"] = target;
}
if (!string.IsNullOrEmpty(database))
{
foreach (var key in new[] { "Database", "Initial Catalog" })
builder.Remove(key);
builder["Database"] = database;
}
return builder.ConnectionString;
}
}
Path: redb-route/tests/Shared/TestPorts.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/TestPorts.cs
----
using System.Net;
using System.Net.Sockets;
namespace redb.Route.Tests.Shared;
///
/// Ports for test servers. The old recipe — bind port 0, read the number, close, let Kestrel bind it later —
/// took the number from the ephemeral range (Windows 49152–65535, Linux 32768–60999), the same range the OS
/// hands out for the local end of every outgoing client connection. Between the close and Kestrel's bind the
/// port could go to a client socket of a test running in parallel (three TFMs and several projects run at
/// once), and the server failed with "address already in use".
///
/// Here the ports come from 20000–32767, below both ephemeral ranges, so the OS never gives them to a client
/// socket. Each process starts at its own random point and walks forward, so parallel processes rarely meet,
/// and every port is checked by binding it before it is handed out (a port reserved by Hyper-V or held by a
/// container fails that check and is skipped). A number is never handed out twice in one process.
///
///
internal static class TestPorts
{
private const int First = 20000;
private const int Last = 32767;
private const int Span = Last - First + 1;
private static readonly int Start = Random.Shared.Next(Span);
private static int _taken = -1;
/// A port nothing listens on at the moment, outside the ephemeral range.
public static int Next()
{
for (var attempt = 0; attempt < Span; attempt++)
{
var port = First + (Start + Interlocked.Increment(ref _taken)) % Span;
if (IsFree(port))
return port;
}
throw new InvalidOperationException($"No free port left in {First}-{Last} for this test process.");
}
private static bool IsFree(int port)
{
using var probe = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Windows otherwise lets a bind share a port someone holds on another address of the machine.
if (OperatingSystem.IsWindows())
probe.ExclusiveAddressUse = true;
try
{
// The loopback: tests listen there, and a probe on all interfaces is what makes a desktop firewall ask.
// A port someone holds on 0.0.0.0 (an interop container's published port) still fails this bind.
probe.Bind(new IPEndPoint(IPAddress.Loopback, port));
return true;
}
catch (SocketException)
{
// In use, or excluded by the OS: this port is not the answer, the next one is tried.
return false;
}
}
}
Path: redb-route/tests/Shared/TestStand.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/TestStand.cs
----
namespace redb.Route.Tests.Shared;
///
/// The test stand of docker-compose.tests.yml: its keys and shared folders are written by
/// tests/docker/gen-certs.sh into tests/docker/.generated (git-ignored). Found by walking up from the
/// test's bin folder, so it works in this repository and in the published redb-route tree alike.
///
internal static class TestStand
{
///
/// tests/docker/.generated/<subfolder>, or, when no stand folder is found above the bin folder, that
/// relative path itself (the test then reports the missing files, which names what to run).
///
public static string Generated(string subfolder)
{
for (var dir = new DirectoryInfo(AppContext.BaseDirectory); dir is not null; dir = dir.Parent)
{
var docker = Path.Combine(dir.FullName, "tests", "docker");
if (File.Exists(Path.Combine(docker, "gen-certs.sh")))
return Path.Combine(docker, ".generated", subfolder);
}
return Path.Combine("tests", "docker", ".generated", subfolder);
}
/// The command that starts a profile of the stand, for skip and failure texts.
public static string Up(string profile)
=> $"docker compose -f redb.Route/docker-compose.tests.yml --profile {profile} up -d --wait";
}