Path: redb-route/redb.Route.IbmMq/IbmMqConsumer.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.cs
----
using System.Collections.Concurrent;
using System.Diagnostics;
using IBM.WMQ;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Telemetry;
using RouteMessage = redb.Route.Core.Message;
namespace redb.Route.IbmMq;
///
/// IBM MQ consumer. Polls messages from a queue (MQGET) or subscribes to a topic,
/// with support for concurrent processing, transacted ack, backout/dead-letter,
/// and W3C distributed tracing.
///
public sealed partial class IbmMqConsumer : IConsumer
{
private readonly IbmMqEndpoint _endpoint;
public IEndpoint Endpoint => _endpoint;
private readonly IProcessor _processor;
private readonly IbmMqEndpointOptions _options;
private ILogger? _logger;
// ConcurrentConsumers is honoured as N REAL competing consumers, each with its OWN dedicated
// MQQueueManager connection + destination handle + serial receive loop. The MQ managed client is
// not thread-safe per connection and its syncpoint (commit/backout) is connection-scoped, so
// concurrency MUST come from N independent connections, never from fanning out one connection.
// NOTE: this applies to QUEUE destinations (opened INPUT_SHARED = competing consumers). For a
// TOPIC, N managed non-durable subscriptions would each receive a COPY of every message, so
// ConcurrentConsumers is clamped to 1 for topics (see Start).
private readonly List _workers = new();
private CancellationTokenSource? _cts;
private readonly InflightDrainGuard _drain = new();
// Event-driven receive path (ReceiveMode=Listener). When set, Start/Stop delegate entirely to
// the XMS engine and the poll workers above are never created. Opt-in; default stays poll.
private IbmMqXmsConsumerEngine? _xmsEngine;
private long _processedCount;
/// Number of messages successfully processed (summed across all worker loops).
public long ProcessedCount => Interlocked.Read(ref _processedCount);
///
/// One competing consumer: its own queue-manager connection, destination handle and loop. A reconnect replaces the
/// connection and the handle; the loop stays.
///
private sealed class Worker
{
public Worker(int index, MQQueueManager qm, ConnectionSupervisor supervisor)
{
Index = index;
Qm = qm;
Supervisor = supervisor;
}
public int Index { get; }
/// The supervisor of this worker's connection, registered with the endpoint while the worker lives.
public ConnectionSupervisor Supervisor { get; }
public MQQueueManager Qm { get; set; }
public MQQueue? Queue { get; set; }
public MQTopic? Topic { get; set; }
public Task? Loop { get; set; }
}
/// Creates an IBM MQ consumer.
public IbmMqConsumer(IbmMqEndpoint endpoint, IProcessor processor, IbmMqEndpointOptions options)
{
_endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint));
_processor = processor ?? throw new ArgumentNullException(nameof(processor));
_options = options ?? throw new ArgumentNullException(nameof(options));
_logger = endpoint.Logger;
_headerFilter = endpoint.HeaderFilterStrategy;
_backoutPause = new IbmMqBackoutPause(options.BackoutDelay);
}
/// The pause after a backout (backoutDelay), shared by every worker of this consumer.
private readonly IbmMqBackoutPause _backoutPause;
private readonly IHeaderFilterStrategy _headerFilter;
///
public async Task Start(CancellationToken ct = default)
{
// Event-driven path: hand off to the XMS listener engine and skip the poll workers entirely.
if (_options.ReceiveMode == IbmMqReceiveMode.Listener)
{
_logger ??= (_endpoint.Component as ComponentBase)?.Logger;
_xmsEngine = new IbmMqXmsConsumerEngine(
_endpoint, _processor, _options, _logger,
() => Interlocked.Increment(ref _processedCount));
try
{
await _xmsEngine.StartAsync(ct).ConfigureAwait(false);
}
catch
{
// Partial start (connection up, a session or consumer refused): close what came up, so a later
// Start opens one connection, not a second beside a half-open one.
await _xmsEngine.StopAsync(CancellationToken.None).ConfigureAwait(false);
_xmsEngine = null;
throw;
}
return;
}
var isTopic = _options.DestinationType == IbmMqDestinationType.Topic;
var workerCount = Math.Max(1, _options.ResolvedConcurrentConsumers);
// Topics can't be load-balanced across competing subscribers: each managed non-durable
// subscription gets its OWN copy of every message, so N subscriptions would DUPLICATE
// delivery, not share it. Clamp to a single subscriber and tell the operator why.
if (isTopic && workerCount > 1)
{
_logger?.LogWarning(
"IBM MQ: ConcurrentConsumers({N}) ignored for TOPIC destination {Destination} — parallel " +
"subscribers would each receive a full copy of every message (duplicate delivery), not share " +
"the load. Running a single subscriber. Use a QUEUE destination for competing consumers.",
workerCount, _endpoint.Destination);
workerCount = 1;
}
_cts = new CancellationTokenSource();
_drain.Start(ct);
try
{
for (var i = 0; i < workerCount; i++)
{
// Each worker owns its own MQQueueManager: the MQ managed client serialises MQI calls
// per connection, and the transacted syncpoint is connection-scoped — so real
// concurrency requires one dedicated connection per worker.
var qm = await _endpoint
.CreateDedicatedQueueManagerAsync($"consumer:{_endpoint.Destination}#{i}", ct)
.ConfigureAwait(false);
var worker = new Worker(i, qm,
_endpoint.Supervise($"wmq:{_endpoint.Destination} consumer worker {i}", _logger));
_workers.Add(worker); // a failure below still closes this worker's connection with the others
OpenWorkerDestination(worker);
if (i == 0)
_poison = ResolvePoisonChain(qm, worker.Queue);
worker.Loop = Task.Run(() => ReceiveLoopAsync(worker, _cts.Token), _cts.Token);
}
}
catch
{
// Partial start — tear down whatever came up so we don't leak connections/handles.
await StopWorkersAsync(ct).ConfigureAwait(false);
_drain.Dispose();
_cts?.Dispose();
_cts = null;
throw;
}
_logger ??= (_endpoint.Component as ComponentBase)?.Logger;
_logger?.LogInformation(
"IBM MQ consumer started: destination={Destination}, type={Type}, concurrent={Concurrent}",
_endpoint.Destination, _options.DestinationType, workerCount);
}
///
public async Task Stop(CancellationToken ct = default)
{
if (_xmsEngine != null)
{
await _xmsEngine.StopAsync(ct).ConfigureAwait(false);
_xmsEngine = null;
return;
}
_cts?.Cancel();
// Drain in-flight processing first (the loops may still be blocked in MQGET WAIT — they exit
// when the current get returns/times out; StopWorkersAsync awaits them).
await _drain.DrainAsync(ct, _logger, $"wmq:{_endpoint.Destination}").ConfigureAwait(false);
await StopWorkersAsync(ct).ConfigureAwait(false);
_cts?.Dispose();
_cts = null;
_drain.Dispose();
_logger?.LogInformation("IBM MQ consumer stopped: destination={Destination}", _endpoint.Destination);
}
/// Awaits every worker loop, closes its destination handle and disconnects its queue manager.
private async Task StopWorkersAsync(CancellationToken ct)
{
foreach (var w in _workers)
{
if (w.Loop != null)
{
try { await w.Loop.ConfigureAwait(false); }
catch (OperationCanceledException) { /* expected */ }
catch (Exception ex) { _logger?.LogDebug(ex, "IBM MQ worker loop faulted during stop"); }
}
CloseWorkerDestination(w);
try { if (w.Qm.IsConnected) w.Qm.Disconnect(); }
catch (Exception ex) { _logger?.LogDebug(ex, "IBM MQ: error disconnecting consumer queue manager during stop"); }
_endpoint.Unsupervise(w.Supervisor);
}
_workers.Clear();
}
// ── Receive loop ──
private async Task ReceiveLoopAsync(Worker worker, CancellationToken ct)
{
if (_options.Batch is { } batch)
{
await BatchReceiveLoopAsync(worker, batch, ct).ConfigureAwait(false);
return;
}
// Note: MQGMO_PROPERTIES_IN_HANDLE requires gmo.MessageHandle to be set via
// qm.CreateMessageHandle(). Without it, GetStringProperty calls in helpers can
// misbehave on the managed .NET client. Use queue-default property handling.
var gmo = new MQGetMessageOptions
{
Options = MQC.MQGMO_WAIT | MQC.MQGMO_FAIL_IF_QUIESCING,
WaitInterval = _options.WaitInterval,
};
if (_options.Convert)
gmo.Options |= MQC.MQGMO_CONVERT;
if (_options.Transacted == true)
gmo.Options |= MQC.MQGMO_SYNCPOINT;
else
gmo.Options |= MQC.MQGMO_NO_SYNCPOINT;
if (!string.IsNullOrEmpty(_options.Selector))
gmo.MatchOptions = MQC.MQMO_MATCH_MSG_ID;
while (!ct.IsCancellationRequested)
{
try
{
// backoutDelay: after a backout no worker of this consumer starts an MQGET until the pause has passed.
await _backoutPause.WaitAsync(ct).ConfigureAwait(false);
var msg = new MQMessage();
var getSw = Stopwatch.StartNew();
bool gotMessage = false;
try
{
if (_options.DestinationType == IbmMqDestinationType.Topic)
worker.Topic!.Get(msg, gmo);
else
worker.Queue!.Get(msg, gmo);
gotMessage = true;
}
catch (MQException ex) when (ex.ReasonCode == MQC.MQRC_NO_MSG_AVAILABLE)
{
// No message within WaitInterval — loop back
continue;
}
catch (MQException ex) when (ex.ReasonCode == MQC.MQRC_FORMAT_ERROR)
{
// MQGMO_CONVERT can't convert binary (MQFMT_NONE) data — proceed with unconverted payload
gotMessage = true;
}
catch (MQException ex) when (IbmMqConnectionLoss.IsConnectionLost(ex.ReasonCode))
{
// A queue manager restart or a network cut: connect again rather than end the worker.
if (ct.IsCancellationRequested || !await ReconnectWorkerAsync(worker, ex, ct).ConfigureAwait(false))
break;
continue;
}
finally
{
getSw.Stop();
}
// ─────────────────────────────────────────────────────────────
// KNOWN ISSUE — IBM MQ managed .NET client (amqmdnetstd.dll)
// ─────────────────────────────────────────────────────────────
// The managed IBM MQ client is NOT event-driven on MQGET with
// MQGMO_WAIT. It carries an internal polling tick of ~500 ms
// that is INDEPENDENT of the WaitInterval supplied in MQGMO:
// WaitInterval only governs the upper timeout, not the lower
// delivery-granularity bound. As a result the typical
// producer→consumer latency observed on this transport is
// ~500 ms even with SHARECNV(1) on the channel.
//
// The native (unmanaged) client is event-driven but requires
// the IBM MQ Client redistributable to be installed on the
// host — not viable for self-contained .NET deployments.
//
// Proper fix: rewrite ReceiveLoopAsync to use the managed
// async-consume API (MQQueue.Cb(...) + MQQueueManager.Ctl(
// MQOP_START, ...)). With the callback path the broker pushes
// messages to us and the per-message latency drops to ~0.
// This is a non-trivial refactor (callback-driven instead of
// poll-driven loop, different cancellation/back-pressure
// model) — tracked for a future release.
//
// The Debug log below lets ops confirm the diagnosis in the
// field: if "MQGET blocked for ~500 ms" appears consistently,
// it is the managed-client tick (need MQCB); if values are
// <50 ms while end-to-end latency is still ~500 ms, the
// bottleneck is on the producer side instead.
// ─────────────────────────────────────────────────────────────
if (gotMessage && getSw.ElapsedMilliseconds > 50)
{
_logger?.LogDebug(
"IBM MQ MQGET blocked for {ElapsedMs} ms before delivering message (destination={Destination})",
getSw.ElapsedMilliseconds, _endpoint.Destination);
}
_drain.Increment();
try
{
await ProcessMessageAsync(worker, msg, _drain.ProcessingToken).ConfigureAwait(false);
}
finally
{
_drain.Decrement();
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested) { break; }
catch (Exception ex)
{
_logger?.LogError(ex, "Error in IBM MQ receive loop: destination={Destination}",
_endpoint.Destination);
// Brief delay to avoid tight error loops
try { await Task.Delay(1000, ct).ConfigureAwait(false); }
catch (OperationCanceledException) { break; }
}
}
}
private async Task ProcessMessageAsync(Worker worker, MQMessage mqMsg, CancellationToken ct)
{
using var span = StartConsumerSpan(mqMsg);
_logger?.LogDebug(
"IBM MQ consumer: GOT message destination={Destination}, msgId={MsgId}, replyTo={ReplyTo}, msgType={MsgType}",
_endpoint.Destination,
IbmMqMessageHelper.BytesToHex(mqMsg.MessageId),
mqMsg.ReplyToQueueName?.Trim(),
mqMsg.MessageType);
// A poison message (backed out backoutThreshold times) goes to the backout queue instead of the route, in the
// same unit of work as its read, as the IBM MQ classes for JMS requeue it before delivery. Checked before the
// route: a message that fails every time never reaches a check after it.
if (await DivertPoisonAsync(worker, mqMsg).ConfigureAwait(false))
return;
var exchange = CreateExchange(mqMsg);
_logger?.LogDebug(
"IBM MQ consumer: exchange CREATED, pattern={Pattern}, about to invoke route processor",
exchange.Pattern);
// The syncpoint (commit/backout) is connection-scoped, so it belongs to this worker's queue manager and to
// this consumer. The route transaction owns the database and the outgoing sends; the message is committed
// below, once the whole unit of work ended well.
try
{
await _processor.Process(exchange, ct).ConfigureAwait(false);
exchange.ThrowIfUnhandledFailure();
_logger?.LogDebug(
"IBM MQ consumer: route processor RETURNED, hasOut={HasOut}, replyTo={ReplyTo}",
exchange.HasOut, mqMsg.ReplyToQueueName?.Trim());
// RPC reply: if the incoming message had ReplyTo, send the Out message back
if (!_options.DisableReplyTo && !string.IsNullOrWhiteSpace(mqMsg.ReplyToQueueName))
{
await SendReplyAsync(worker, exchange, mqMsg, ct).ConfigureAwait(false);
}
// Commit in non-transacted mode is implicitly done by MQGET without syncpoint. In transacted mode the
// consumer commits the syncpoint here, once the route and its transaction have succeeded.
if (_options.Transacted == true)
{
var ackAction = new IbmMqAckAction(worker.Qm, _logger);
await ackAction.Commit(ct).ConfigureAwait(false);
}
Interlocked.Increment(ref _processedCount);
}
catch (Exception ex)
{
// Our own stop (the processing token) is not a failure; any other cancellation is.
if (ex is not OperationCanceledException || !ct.IsCancellationRequested)
span.Activity.RecordFailure(ex);
_logger?.LogError(ex, "IBM MQ message processing error: destination={Destination}, msgId={MsgId}",
_endpoint.Destination, IbmMqMessageHelper.BytesToHex(mqMsg.MessageId));
if (_options.Transacted == true)
{
try
{
// Backout is connection-scoped — roll back only THIS worker's syncpoint.
worker.Qm.Backout();
_logger?.LogDebug("IBM MQ message rolled back after processing error");
// Our own stop backs the message out too, but nothing reads after it: no pause.
if (!ct.IsCancellationRequested)
_backoutPause.Begin();
}
catch (Exception rollbackEx)
{
_logger?.LogWarning(rollbackEx, "Failed to rollback IBM MQ message");
}
}
}
finally
{
await exchange.DisposeAsync().ConfigureAwait(false);
}
}
// ── Trace context propagation ──
private TransportSpan StartConsumerSpan(MQMessage mqMsg)
{
// The W3C context rides in the MQ message properties (RFH2 usr folder).
var span = RouteTelemetryExtensions.StartConsumerSpan(
(_endpoint.Component as ComponentBase)?.Context,
$"{_endpoint.Destination} receive", ActivityKind.Consumer,
"messaging.system", "wmq", _endpoint.Uri.NormalizedKey,
mqMsg, ReadProperty,
destination: _endpoint.Destination, operation: "receive");
if (span.Activity is { IsAllDataRequested: true } activity)
{
activity.SetTag("messaging.ibmmq.queue_manager", _options.QueueManager);
if (mqMsg.MessageId is { Length: > 0 })
activity.SetTag("messaging.message.id", IbmMqMessageHelper.BytesToHex(mqMsg.MessageId));
}
return span;
}
/// One message property, or null: MQ reports a property the message does not hold as MQRC 2471.
private static string? ReadProperty(MQMessage message, string name)
{
try { return message.GetStringProperty(name); }
catch (MQException ex) when (ex.ReasonCode == MQC.MQRC_PROPERTY_NOT_AVAILABLE) { return null; }
}
// ── Exchange creation ──
private Exchange CreateExchange(MQMessage mqMsg)
{
var body = IbmMqMessageHelper.ExtractBody(mqMsg);
var routeMsg = new RouteMessage(body);
// Map MQMD Format → ContentType
routeMsg.ContentType = IbmMqMessageHelper.FormatToContentType(mqMsg.Format);
// Copy MQMD → headers
if (_options.MqmdReadEnabled)
IbmMqMessageHelper.CopyMqmdToHeaders(mqMsg, routeMsg, _endpoint.Destination, _options.QueueManager);
// Copy RFH2 user properties → headers, as the endpoint's strategy lets them in
var exchange = Exchange.Create(routeMsg, _endpoint.ScopeFactory);
IbmMqMessageHelper.CopyRfh2UserProperties(mqMsg, routeMsg, _headerFilter, exchange);
// Determine exchange pattern
var hasReplyTo = !_options.DisableReplyTo && !string.IsNullOrWhiteSpace(mqMsg.ReplyToQueueName);
var isRequest = mqMsg.MessageType == MQC.MQMT_REQUEST;
var pattern = hasReplyTo && isRequest ? ExchangePattern.InOut : ExchangePattern.InOnly;
exchange.Pattern = pattern;
return exchange;
}
// ── RPC reply ──
private async Task SendReplyAsync(Worker worker, IExchange exchange, MQMessage originalMsg, CancellationToken ct)
{
try
{
var responseBody = exchange.HasOut
? exchange.Out!.Body
: exchange.In.Body;
var reply = new MQMessage();
if (responseBody is byte[] bytes)
{
reply.Write(bytes);
reply.Format = MQC.MQFMT_NONE;
}
else
{
var text = responseBody?.ToString() ?? string.Empty;
reply.WriteString(text);
reply.Format = MQC.MQFMT_STRING;
}
reply.CorrelationId = originalMsg.MessageId;
reply.MessageType = MQC.MQMT_REPLY;
// Round-trip user headers via RFH2 (matches producer-side BuildOutgoingMessage).
// targetClient=Mq promises raw MQMD+body on EVERY leg: a legacy requester that asked
// for no properties must not get an RFH2 on the reply either.
if (_options.TargetClient != IbmMqTargetClient.Mq)
{
var headerSource = exchange.HasOut ? exchange.Out! : exchange.In;
IbmMqMessageHelper.CopyHeadersToRfh2(reply, headerSource, _headerFilter, exchange);
}
var replyQueueName = originalMsg.ReplyToQueueName.Trim();
var replyQmName = originalMsg.ReplyToQueueManagerName?.Trim();
var qm = worker.Qm;
var openOptions = MQC.MQOO_OUTPUT | MQC.MQOO_FAIL_IF_QUIESCING;
MQQueue replyQueue;
if (!string.IsNullOrEmpty(replyQmName) && replyQmName != qm.Name.Trim())
replyQueue = qm.AccessQueue(replyQueueName, openOptions, replyQmName, null, null);
else
replyQueue = qm.AccessQueue(replyQueueName, openOptions);
try
{
var pmo = new MQPutMessageOptions { Options = MQC.MQPMO_NO_SYNCPOINT };
replyQueue.Put(reply, pmo);
_logger?.LogDebug(
"IBM MQ RPC reply sent: replyQueue={ReplyQueue}, correlationId={CorrelationId}",
replyQueueName, IbmMqMessageHelper.BytesToHex(reply.CorrelationId));
}
finally
{
try { replyQueue.Close(); }
catch (Exception closeEx)
{
_logger?.LogDebug(closeEx, "Error closing reply queue");
}
}
}
catch (Exception ex)
{
// Swallow: failed reply must not block the consumer slot. The original message
// has already been destructively read (MQGMO_NO_SYNCPOINT) or will be committed
// on the transactional path — the client will detect failure via its own RPC timeout.
var reason = (ex as MQException)?.ReasonCode;
_logger?.LogWarning(ex,
"IBM MQ: failed to send RPC reply to {ReplyQueue} (reason={Reason}): {Message} — original message will still be settled",
originalMsg.ReplyToQueueName?.Trim(), reason, ex.Message);
}
}
// ── Poison messages: the provider's chain ──
///
/// Where a poison message goes, as the IBM MQ classes for JMS decide it: the backout threshold and backout queue of
/// the endpoint when set, else the input queue's own BOTHRESH and BOQNAME; with a threshold in force and no backout
/// queue, the queue manager's dead letter queue (DEADQ). is 0 when the consumer does not read
/// under syncpoint (a message read without it is never backed out).
///
private sealed record PoisonChain(int Threshold, string? BackoutQueue, string? DeadLetterQueue)
{
public string? Target => BackoutQueue ?? DeadLetterQueue;
}
private PoisonChain _poison = new(0, null, null);
///
/// Resolves the chain once, with the first worker's connection: the input queue's BOTHRESH and BOQNAME (inquired on
/// the opened queue) and the queue manager's DEADQ, the endpoint's options over them. A threshold in force with
/// neither a backout queue nor a dead letter queue cannot work: the start fails.
///
private PoisonChain ResolvePoisonChain(MQQueueManager qm, MQQueue? queue)
{
var syncpoint = _options.Transacted == true || _options.Batch is not null;
var threshold = _options.BackoutThreshold;
var backoutQueue = Blank(_options.BackoutQueue);
if (queue is not null)
{
if (threshold <= 0)
threshold = queue.BackoutThreshold;
backoutQueue ??= Blank(queue.BackoutRequeueName);
}
var deadLetterQueue = Blank(qm.DeadLetterQueueName);
if (syncpoint && threshold > 0 && backoutQueue is null && deadLetterQueue is null)
throw new InvalidOperationException(
$"IBM MQ consumer on '{_endpoint.Destination}': a backout threshold of {threshold} is in force, but there is " +
"neither a backout queue (backoutQueue, or the queue's BOQNAME) nor a dead letter queue on the queue " +
"manager (DEADQ): a poison message would have nowhere to go.");
if (_options.Batch is not null && backoutQueue is null && deadLetterQueue is null)
throw new InvalidOperationException(
$"IBM MQ consumer on '{_endpoint.Destination}': batch mode needs a backout queue (backoutQueue, or the " +
"queue's BOQNAME) or a dead letter queue on the queue manager (DEADQ): the requests a batch cannot answer " +
"and the poison messages of failed batches go there.");
return new PoisonChain(syncpoint ? threshold : 0, backoutQueue, deadLetterQueue);
static string? Blank(string? name) => string.IsNullOrWhiteSpace(name) ? null : name.Trim();
}
///
/// A message read under syncpoint that was backed out as often as the threshold goes to the backout queue (or the
/// dead letter queue) and the unit of work commits, instead of the route running it again. true when the
/// message was taken care of here; false when it goes to the route.
///
private Task DivertPoisonAsync(Worker worker, MQMessage mqMsg)
{
if (_poison.Threshold <= 0 || mqMsg.BackoutCount < _poison.Threshold)
return Task.FromResult(false);
return Task.FromResult(MoveToBackoutQueue(worker, mqMsg,
$"backed out {mqMsg.BackoutCount} times (backout threshold {_poison.Threshold})", commit: true));
}
///
/// Puts on the backout queue, or the dead letter queue, under the worker's syncpoint, so its
/// read and the put commit together, and commits when . A put that fails backs the unit of
/// work out: the message returns to its queue.
///
private bool MoveToBackoutQueue(Worker worker, MQMessage mqMsg, string reason, bool commit)
{
var target = _poison.Target;
if (target is null)
return false;
try
{
PutToBackoutQueue(worker, mqMsg);
if (commit)
worker.Qm.Commit();
_logger?.LogWarning("IBM MQ message moved to {Target}: destination={Destination}, {Reason}",
target, _endpoint.Destination, reason);
}
catch (Exception ex)
{
_endpoint.RecordError(ex);
_logger?.LogError(ex, "Failed to move an IBM MQ message to {Target}; backing out", target);
try { worker.Qm.Backout(); }
catch (Exception backoutEx) { _logger?.LogWarning(backoutEx, "IBM MQ backout after a failed move failed"); }
_backoutPause.Begin();
}
return true;
}
///
/// Puts a message on the backout queue under the worker's syncpoint (it commits with the unit of work); without a
/// backout queue on the dead letter queue, behind a dead letter header as the provider writes it.
///
private void PutToBackoutQueue(Worker worker, MQMessage mqMsg)
{
var target = _poison.Target ?? throw new InvalidOperationException("No backout or dead letter queue.");
if (_poison.BackoutQueue is null)
IbmMqMessageHelper.WrapInDeadLetterHeader(mqMsg, MQC.MQRC_BACKOUT_THRESHOLD_REACHED,
_endpoint.Destination, _options.QueueManager);
using var queue = worker.Qm.AccessQueue(target, MQC.MQOO_OUTPUT | MQC.MQOO_FAIL_IF_QUIESCING);
queue.Put(mqMsg, new MQPutMessageOptions { Options = MQC.MQPMO_SYNCPOINT });
}
/// Opens the worker's destination on its connection: the queue, or a managed subscription for a topic.
private void OpenWorkerDestination(Worker worker)
{
if (_options.DestinationType == IbmMqDestinationType.Topic)
{
var subName = $"REDB.{_endpoint.Destination}.{Guid.NewGuid():N}";
worker.Topic = worker.Qm.AccessTopic(
_endpoint.Destination, null,
MQC.MQSO_CREATE | MQC.MQSO_NON_DURABLE | MQC.MQSO_MANAGED,
null, subName);
}
else
{
// INQUIRE: the poison chain reads the queue's BOTHRESH and BOQNAME.
var openOptions = MQC.MQOO_INPUT_SHARED | MQC.MQOO_INQUIRE | MQC.MQOO_FAIL_IF_QUIESCING;
worker.Queue = worker.Qm.AccessQueue(_endpoint.Destination, openOptions);
}
}
///
/// Reconnects a worker whose connection was lost: records the loss on the endpoint, closes what is left of the old
/// connection, and connects again and reopens the destination on the schedule of the worker's
/// , one bounded attempt at a time, until it succeeds or the consumer stops. While it
/// is away the endpoint's health says so. Returns false when the consumer stopped first.
///
private async Task ReconnectWorkerAsync(Worker worker, MQException lost, CancellationToken ct)
{
var supervisor = worker.Supervisor;
supervisor.Lost(lost);
CloseWorkerDestination(worker);
IbmMqConnectionLoss.DisconnectQuietly(worker.Qm, _logger);
return await supervisor.ReconnectAsync(async c =>
{
var qm = await supervisor.AttemptAsync(
a => _endpoint.CreateDedicatedQueueManagerAsync($"consumer:{_endpoint.Destination}#{worker.Index}", a),
late => IbmMqConnectionLoss.DisconnectQuietly(late, _logger), c).ConfigureAwait(false);
worker.Qm = qm;
try
{
OpenWorkerDestination(worker);
}
catch
{
CloseWorkerDestination(worker);
IbmMqConnectionLoss.DisconnectQuietly(qm, _logger);
throw;
}
}, ct).ConfigureAwait(false);
}
private void CloseWorkerDestination(Worker w)
{
if (w.Queue != null)
{
try { w.Queue.Close(); }
catch (Exception ex) { _logger?.LogWarning(ex, "Error closing IBM MQ queue"); }
w.Queue = null;
}
if (w.Topic != null)
{
try { w.Topic.Close(); }
catch (Exception ex) { _logger?.LogWarning(ex, "Error closing IBM MQ topic"); }
w.Topic = null;
}
}
}