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);