Path: redb-route/redb.Route.IbmMq/IbmMqConsumer.Batch.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/redb.Route.IbmMq/IbmMqConsumer.Batch.cs
----
using IBM.WMQ;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Batching;
using redb.Route.Core;
using redb.Route.Telemetry;
using RouteMessage = redb.Route.Core.Message;
namespace redb.Route.IbmMq;
///
/// Batch mode of the IBM MQ consumer (batching=true, poll receive mode), on the core batch contract: each worker
/// reads a batch with MQGET under its connection's syncpoint, runs it through the route once and commits it (MQCMIT)
/// or backs it out (MQBACK), the rule of a failed single message for every message of the batch. A poison message
/// and a request (a message that asks for a reply, unless disableReplyTo) go to the backout queue in the
/// batch's unit of work instead of into the batch.
///
public sealed partial class IbmMqConsumer
{
private async Task BatchReceiveLoopAsync(Worker worker, BatchOptions batch, CancellationToken stop)
{
var settlement = new IbmMqBatchSettlement(this, worker);
var dispatcher = new BatchDispatcher(_processor, settlement, ToMessage, _endpoint.ScopeFactory,
[IbmMqHeaders.Destination, IbmMqHeaders.QueueManager]);
var collector = new BatchCollector(batch, (into, max, wait, ct) => ReceiveIntoBatch(worker, into, max, wait, ct));
while (!stop.IsCancellationRequested)
{
try { await _backoutPause.WaitAsync(stop).ConfigureAwait(false); }
catch (OperationCanceledException) { return; }
CollectedBatch collected;
try
{
collected = await collector.CollectAsync(stop).ConfigureAwait(false);
}
catch (MQException ex) when (IbmMqConnectionLoss.IsConnectionLost(ex.ReasonCode))
{
// The lost connection backed out what was collected under syncpoint; connect again and collect anew.
if (stop.IsCancellationRequested || !await ReconnectWorkerAsync(worker, ex, stop).ConfigureAwait(false))
return;
continue;
}
catch (Exception ex)
{
_endpoint.RecordError(ex);
_logger?.LogError(ex, "IBM MQ batch collection failed: destination={Destination}", _endpoint.Destination);
BackoutQuietly(worker);
try { await Task.Delay(1000, stop).ConfigureAwait(false); }
catch (OperationCanceledException) { return; }
continue;
}
if (collected.Items.Count == 0)
{
// Messages moved to the backout queue while nothing was batched: their unit of work commits on its own.
CommitQuietly(worker);
continue;
}
if (collected.Interrupted)
{
await settlement.ReturnAsync(collected.Items, CancellationToken.None).ConfigureAwait(false);
return;
}
var items = collected.Items;
using var span = BatchDispatcher.StartSpan(
(_endpoint.Component as ComponentBase)?.Context, $"{_endpoint.Destination} receive", "wmq",
_endpoint.Uri.NormalizedKey, _endpoint.Destination,
items.Select(m => RouteTelemetryExtensions.ExtractTraceContext(m, ReadProperty)), items.Count);
_drain.Increment();
try
{
var outcome = await dispatcher.DispatchAsync(items, span, _drain.ProcessingToken).ConfigureAwait(false);
if (outcome == BatchOutcome.Accepted)
Interlocked.Add(ref _processedCount, items.Count);
}
catch (OperationCanceledException) when (_drain.ProcessingToken.IsCancellationRequested)
{
return;
}
catch (Exception ex)
{
_endpoint.RecordError(ex);
_logger?.LogError(ex, "IBM MQ batch failed to settle: destination={Destination}", _endpoint.Destination);
BackoutQuietly(worker);
_backoutPause.Begin();
}
finally
{
_drain.Decrement();
}
}
}
///
/// The transport's part of collection: MQGET under syncpoint, waiting up to in slices short
/// enough to notice a stop. A message that must not go into the batch goes to the backout queue in the same unit
/// of work, and the wait goes on for the next one. While another worker's backout pause (backoutDelay) lasts,
/// no MQGET starts: the wait passes in the pause.
///
private async ValueTask ReceiveIntoBatch(Worker worker, List into, int max, TimeSpan wait, CancellationToken ct)
{
var gmo = new MQGetMessageOptions { Options = MQC.MQGMO_WAIT | MQC.MQGMO_FAIL_IF_QUIESCING | MQC.MQGMO_SYNCPOINT };
if (_options.Convert)
gmo.Options |= MQC.MQGMO_CONVERT;
var deadline = DateTime.UtcNow + wait;
while (true)
{
ct.ThrowIfCancellationRequested();
var remaining = deadline - DateTime.UtcNow;
if (remaining <= TimeSpan.Zero)
return 0;
if (_backoutPause.Remaining > TimeSpan.Zero)
{
await _backoutPause.WaitAsync(ct, remaining).ConfigureAwait(false);
continue;
}
gmo.WaitInterval = (int)Math.Clamp(remaining.TotalMilliseconds, 1, 500);
var message = new MQMessage();
try
{
if (_options.DestinationType == IbmMqDestinationType.Topic)
worker.Topic!.Get(message, gmo);
else
worker.Queue!.Get(message, gmo);
}
catch (MQException ex) when (ex.ReasonCode == MQC.MQRC_NO_MSG_AVAILABLE)
{
continue;
}
catch (MQException ex) when (ex.ReasonCode == MQC.MQRC_FORMAT_ERROR)
{
// MQGMO_CONVERT cannot convert binary data: the unconverted payload is what the batch gets.
}
if (DivertFromBatch(worker, message))
continue;
into.Add(message);
return 1;
}
}
///
/// Moves a message that must not go into the batch to the backout queue, under the batch's syncpoint: a poison
/// message (backed out backoutThreshold times), and a request, which a one-way batch cannot answer, unless
/// disableReplyTo. The move commits with the batch, or on its own when the batch stays empty.
///
private bool DivertFromBatch(Worker worker, MQMessage message)
{
string reason;
if (_poison.Threshold > 0 && message.BackoutCount >= _poison.Threshold)
{
reason = $"backed out {message.BackoutCount} times (backout threshold {_poison.Threshold})";
}
else if (!_options.DisableReplyTo && message.MessageType == MQC.MQMT_REQUEST
&& !string.IsNullOrWhiteSpace(message.ReplyToQueueName))
{
reason = $"is a request with reply-to queue '{message.ReplyToQueueName.Trim()}', which a one-way batch cannot " +
"answer (set disableReplyTo=true to batch it without a reply)";
var refused = new InvalidOperationException(
$"IBM MQ batch consumer on '{_endpoint.Destination}' received a request: it goes to the backout queue.");
_endpoint.RecordError(refused);
}
else
{
return false;
}
// Batch mode starts only with a backout or dead letter queue, so the move always has a target. A put that fails throws: the
// collection ends and the whole unit of work, the messages already collected included, is backed out.
PutToBackoutQueue(worker, message);
_logger?.LogWarning("IBM MQ message moved to {Target}: destination={Destination}, {Reason}",
_poison.Target, _endpoint.Destination, reason);
return true;
}
/// One MQ message into a message, mapped as a single message's exchange message is.
private IMessage ToMessage(MQMessage mqMsg, IExchange batch)
{
var routeMsg = new RouteMessage(IbmMqMessageHelper.ExtractBody(mqMsg))
{
ContentType = IbmMqMessageHelper.FormatToContentType(mqMsg.Format),
};
if (_options.MqmdReadEnabled)
IbmMqMessageHelper.CopyMqmdToHeaders(mqMsg, routeMsg, _endpoint.Destination, _options.QueueManager);
IbmMqMessageHelper.CopyRfh2UserProperties(mqMsg, routeMsg, _headerFilter, batch);
return routeMsg;
}
private void CommitQuietly(Worker worker)
{
try { worker.Qm.Commit(); }
catch (Exception ex) { _logger?.LogWarning(ex, "IBM MQ commit of an empty batch's unit of work failed"); }
}
private void BackoutQuietly(Worker worker)
{
try { worker.Qm.Backout(); }
catch (Exception ex) { _logger?.LogWarning(ex, "IBM MQ backout failed"); }
}
///
/// IBM MQ's settlement of a batch: the worker's syncpoint, all messages at once. Accept commits, a failure and a
/// return back out: every message returns to its queue with its backout count raised.
///
private sealed class IbmMqBatchSettlement(IbmMqConsumer owner, Worker worker) : IBatchSettlement
{
public ValueTask BeforeRouteAsync(IExchange batch, IReadOnlyList items, CancellationToken ct)
=> ValueTask.FromResult(null);
public ValueTask AcceptAsync(IExchange batch, IReadOnlyList items, CancellationToken ct)
{
worker.Qm.Commit();
return ValueTask.CompletedTask;
}
public ValueTask RejectAsync(IExchange batch, IReadOnlyList items, Exception failure, CancellationToken ct)
{
owner._logger?.LogError(failure, "IBM MQ batch of {Count} failed on {Destination}: backed out",
items.Count, owner._endpoint.Destination);
worker.Qm.Backout();
owner._backoutPause.Begin();
return ValueTask.CompletedTask;
}
public ValueTask ReturnAsync(IReadOnlyList items, CancellationToken ct)
{
owner.BackoutQuietly(worker);
return ValueTask.CompletedTask;
}
}
}