Path: redb-route/tests/redb.Route.Tests.IbmMq/IbmMqReconnectTests.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.IbmMq/IbmMqReconnectTests.cs
----
using System.Collections.Concurrent;
using IBM.WMQ;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.IbmMq;
using redb.Route.Processors;
using redb.Route.Tests.Conformance;
using redb.Route.Transactions;
namespace redb.Route.Tests.IbmMq;
///
/// A consumer outlives a queue manager restart: the restart breaks its connection (MQRC_CONNECTION_BROKEN or
/// MQRC_Q_MGR_QUIESCING), and once the queue manager is back the same route reads the queue again: batch and XMS
/// listener (poll mode is the restart case of ); a producer sends again: plain,
/// transacted (the commit finds the lost connection), request-reply with the poll and the XMS reply receiver.
/// Each reconnect is counted on the endpoint by its connection supervisor.
/// The restart is on : it runs only where
/// REDB_TEST_IBMMQ_CONTAINER names the queue manager's container and the docker CLI reaches it, elsewhere it is
/// skipped. Run it with tests/docker/run-fault-suite.sh --broker ibmmq, which starts the queue manager with host
/// networking (behind docker's published-port proxy a client connect made while the queue manager starts can hang, and
/// the managed client holds every later connect of the process behind it) and builds apart from the test run.
/// Expects IBM MQ at localhost:1414 with the queues of tests/docker/ibmmq/redb-tests.mqsc.
///
[Trait("Category", "Integration")]
[Collection("IbmMqIntegration")]
public sealed class IbmMqReconnectTests
{
private const string Queue = "DEV.QUEUE.RECONNECT";
private const string Connection =
"host=localhost&port=1414&channel=DEV.APP.SVRCONN&queueManager=QM1&user=app&password=admin";
private static readonly IbmMqStand Stand = IbmMqStand.Instance;
// A reconnect attempt that hangs while the queue manager starts is given up after 30 s; then the next one connects.
private static TimeSpan Wait => Stand.Wait;
[BrokerFaultTheory(IbmMqStand.ContainerVariable)]
[InlineData("&batching=true&maxBatchMessages=10&pollTimeoutMs=500&backoutQueue=DEV.QUEUE.BATCH.BOQ")]
[InlineData("&receiveMode=listener")]
[InlineData("&receiveMode=listener&transacted=true")]
public async Task A_consumer_reads_the_queue_again_after_the_queue_manager_restarts(string extra)
{
await Stand.DrainAsync(Queue, TimeSpan.Zero);
var received = new ConcurrentQueue();
var log = new ListLog();
await using var context = new RouteContext(loggerFactory: log);
context.AddComponent(new IbmMqComponent());
var uri = $"wmq:{Queue}?{Connection}&waitInterval=500{extra}";
context.AddRoutes(r => r.From(uri)
.Process(e =>
{
if (e.In.Body is List batch)
foreach (var m in batch) received.Enqueue(Text(m));
else
received.Enqueue(Text(e.In));
}));
await context.Start();
await Stand.PutAsync(Queue, "before");
(await Until(() => received.Contains("before"), Wait)).Should().BeTrue("the route reads the queue before the restart");
await Stand.Fault!.RestartAsync();
// The queue manager reports itself running a moment before its listener takes connections.
(await BrokerFault.UntilAsync(async () =>
{
try { await Stand.PutAsync(Queue, "after"); return true; }
catch (MQException) { return false; }
}, Wait, TimeSpan.FromMilliseconds(500))).Should().BeTrue("the queue manager takes the message once its listener is up");
(await Until(() => received.Contains("after"), Wait)).Should()
.BeTrue($"the consumer reconnects once the queue manager is back and reads what was put after the restart; log:{Environment.NewLine}{log}");
var statistics = (IEndpointStatistics)context.GetEndpoint(uri);
statistics.Reconnects.Should().BeGreaterThan(0, "the connection supervisor counts the reconnect on the endpoint");
statistics.HealthStatus.Should().NotBe(EndpointHealthStatus.Critical, "the connection is back");
}
[BrokerFaultTheory(IbmMqStand.ContainerVariable)]
[InlineData(false, false, "")]
[InlineData(false, true, "")]
[InlineData(true, false, "")]
[InlineData(true, false, "&receiveMode=listener")]
public async Task A_producer_sends_again_after_the_queue_manager_restarts(bool requestReply, bool transacted, string extra)
{
await Stand.DrainAsync(Queue, TimeSpan.Zero);
var log = new ListLog();
await using var context = new RouteContext(loggerFactory: log);
context.AddComponent(new IbmMqComponent());
if (requestReply)
// The responder: a consumer on the same queue answers every request.
context.AddRoutes(r => r.From($"wmq:{Queue}?{Connection}&waitInterval=500")
.Process(e => e.Out = new Message($"ECHO:{Text(e.In)}")));
await context.Start();
var endpoint = context.GetEndpoint($"wmq:{Queue}?{Connection}" + (requestReply ? "&replyTo=true&timeout=10" : "")
+ (transacted ? "&transacted=true" : "") + extra);
var producer = endpoint.CreateProducer();
await producer.Start();
try
{
(await Send(producer, "before", requestReply, transacted)).Should().BeTrue("the producer sends before the restart");
await Stand.Fault!.RestartAsync();
// Sends right after the restart fail (the lost connection, then a reconnect not yet due or refused); the
// producer reconnects on a later send.
var sent = await BrokerFault.UntilAsync(() => Send(producer, "after", requestReply, transacted), Wait,
TimeSpan.FromSeconds(1));
sent.Should().BeTrue($"the producer reconnects once the queue manager is back; log:{Environment.NewLine}{log}");
if (!requestReply)
(await Stand.DrainAsync(Queue, TimeSpan.FromSeconds(2))).Should().Contain("after");
((IEndpointStatistics)endpoint).Reconnects.Should().BeGreaterThan(0,
"the connection supervisor counts the reconnect on the endpoint");
}
finally
{
await producer.Stop();
}
}
///
/// One send; for request-reply it succeeds only with the responder's answer. A transacted send runs inside a
/// transacted block, as .Transacted() on a route does: the put and its MQCMIT happen as the block ends.
///
private static async Task Send(IProducer producer, string body, bool requestReply, bool transacted)
{
var exchange = new Exchange(new Message(body));
try
{
if (transacted)
await new TransactedProcessor(new DelegateProcessor((ex, ct) => producer.Process(ex, ct)), new TransactionPolicy())
.Process(exchange);
else
await producer.Process(exchange);
}
catch (Exception) { return false; }
return !requestReply || exchange.Out?.Body?.ToString() == $"ECHO:{body}";
}
private static string Text(IMessage message)
=> message.Body is byte[] bytes ? System.Text.Encoding.UTF8.GetString(bytes) : message.Body?.ToString() ?? "";
private static async Task Until(Func done, TimeSpan wait)
{
var deadline = DateTime.UtcNow + wait;
while (DateTime.UtcNow < deadline)
{
if (done()) return true;
await Task.Delay(500);
}
return done();
}
/// The warnings and errors the route logged, for the failure message.
private sealed class ListLog : Microsoft.Extensions.Logging.ILoggerFactory, Microsoft.Extensions.Logging.ILogger
{
private readonly ConcurrentQueue _lines = new();
public void AddProvider(Microsoft.Extensions.Logging.ILoggerProvider provider) { }
public Microsoft.Extensions.Logging.ILogger CreateLogger(string categoryName) => this;
public void Dispose() { }
public IDisposable? BeginScope(TState state) where TState : notnull => null;
public bool IsEnabled(Microsoft.Extensions.Logging.LogLevel logLevel) => logLevel >= Microsoft.Extensions.Logging.LogLevel.Information;
public void Log(Microsoft.Extensions.Logging.LogLevel logLevel, Microsoft.Extensions.Logging.EventId eventId, TState state,
Exception? exception, Func formatter)
=> _lines.Enqueue($"{DateTime.UtcNow:HH:mm:ss.fff} {logLevel} {formatter(state, exception)} {exception?.GetType().Name} {exception?.Message}");
public override string ToString() => string.Join("\n", _lines.TakeLast(40));
}
}