Bundle: redb-route / redb.Route.IbmMq (redb.Route.IbmMq.txt), 22 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/redb.Route.IbmMq/Extensions/ServiceCollectionExtensions.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/Extensions/ServiceCollectionExtensions.cs
----
using Microsoft.Extensions.DependencyInjection;
using redb.Route.Extensions;
namespace redb.Route.IbmMq;
///
/// Extension methods for registering the IBM MQ transport in a DI container.
///
public static class ServiceCollectionExtensions
{
///
/// Registers the in the route context so that
/// ibmmq: URIs are resolved.
///
///
/// services.AddRedbRoute(route =>
/// {
/// route.Services.AddRedbRouteIbmMq();
/// route.AddRouteBuilder<MyRoutes>();
/// });
///
///
///
public static IServiceCollection AddRedbRouteIbmMq(this IServiceCollection services)
{
// IRouteContextConfigurator is applied by RouteHostedService at startup --
// the correct registration hook (a lazy marker singleton never fires).
services.AddRouteComponent();
return services;
}
}
Path: redb-route/redb.Route.IbmMq/Fluent/IbmMqDsl.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/Fluent/IbmMqDsl.cs
----
using System.Text;
using redb.Route.Abstractions;
namespace redb.Route.IbmMq;
///
/// Fluent API for IBM MQ endpoints.
///
/// .From(Wmq.Queue("DEV.QUEUE.1").Host("mq-host").QueueManager("QM1").Channel("DEV.APP.SVRCONN"))
/// .To(Wmq.Queue("ORDERS.OUT").Host("mq-host").Persistent())
/// .From(Wmq.Topic("EVENTS/ORDER").Host("mq-host").QueueManager("QM1"))
///
///
public static class Wmq
{
/// Creates an IBM MQ queue endpoint.
public static IbmMqBuilder Queue(string name) => new(name, IbmMqDestinationType.Queue);
/// Creates an IBM MQ topic endpoint.
public static IbmMqBuilder Topic(string name) => new(name, IbmMqDestinationType.Topic);
}
///
/// Fluent builder for IBM MQ endpoint URIs.
///
public sealed class IbmMqBuilder
{
private readonly string _destination;
private readonly IbmMqDestinationType _destType;
// Connection
private string? _connectionFactory;
private string? _host;
private int? _port;
private string? _channel;
private string? _queueManager;
private string? _user;
private string? _password;
private string? _clientId;
// Consumer
private IbmMqReceiveMode? _receiveMode;
private string? _concurrentConsumers;
private int? _waitInterval;
private bool _batching;
private int? _maxBatchMessages;
private int? _pollTimeoutMs;
private int? _batchingIntervalMs;
private bool _disableReplyTo;
private int? _backoutThreshold;
private string? _backoutQueue;
private int? _backoutDelay;
private string? _selector;
private bool? _convert;
// Producer
private IbmMqPersistence? _persistence;
private string? _persistenceExpr;
private string? _priority;
private string? _expiry;
private IbmMqTargetClient? _targetClient;
private IbmMqMessageType? _messageType;
private string? _messageTypeExpr;
// Transactions
private bool? _transacted;
// Dead Letter
// RPC
private bool _replyTo;
private bool _preserveMessageQos;
private string? _replyToQueue;
private string? _replyToQueueManager;
private string? _temporaryModel;
private int? _timeout;
private IbmMqCorrelationPattern? _correlationPattern;
// SSL
private string? _sslCipherSpec;
private string? _sslCertLabel;
private string? _sslPeerName;
private string? _sslKeyRepository;
private int? _sslKeyResetCount;
// Advanced
private int? _ccsid;
private bool? _mqmdWriteEnabled;
private bool? _mqmdReadEnabled;
internal IbmMqBuilder(string destination, IbmMqDestinationType destType)
{
ArgumentException.ThrowIfNullOrWhiteSpace(destination);
_destination = destination;
_destType = destType;
}
// ── Connection ────────────────────────────────────────────────────
/// Use a named connection factory registered in DI.
public IbmMqBuilder ConnectionFactory(string name) { _connectionFactory = name; return this; }
/// Queue manager hostname. Default "localhost".
public IbmMqBuilder Host(string host) { _host = host; return this; }
/// MQ listener port. Default 1414.
public IbmMqBuilder Port(int port) { _port = port; return this; }
/// Server-connection channel. Default "DEV.APP.SVRCONN".
public IbmMqBuilder Channel(string channel) { _channel = channel; return this; }
/// Queue manager name. Default "QM1".
public IbmMqBuilder QueueManager(string qm) { _queueManager = qm; return this; }
/// Authentication user.
public IbmMqBuilder User(string user) { _user = user; return this; }
/// Authentication password.
public IbmMqBuilder Password(string password) { _password = password; return this; }
/// Client identifier for connection tracking.
public IbmMqBuilder ClientId(string id) { _clientId = id; return this; }
// ── Consumer ──────────────────────────────────────────────────────
///
/// Receive strategy: (synchronous MQGET-WAIT, default) or
/// (event-driven XMS push, <50 ms latency).
///
public IbmMqBuilder ReceiveMode(IbmMqReceiveMode mode) { _receiveMode = mode; return this; }
/// Shortcut for ReceiveMode(IbmMqReceiveMode.Listener) — event-driven XMS receive.
public IbmMqBuilder Listener() { _receiveMode = IbmMqReceiveMode.Listener; return this; }
/// Number of concurrent consumers. Default 1.
public IbmMqBuilder ConcurrentConsumers(int count) { _concurrentConsumers = count.ToString(); return this; }
/// Consumer parallelism as a string: a number or "auto" (= max(CPU, 2)).
public IbmMqBuilder ConcurrentConsumers(string count) { _concurrentConsumers = count; return this; }
/// MQGET wait interval in milliseconds. Default 5000.
public IbmMqBuilder WaitInterval(int ms) { _waitInterval = ms; return this; }
/// Batch mode (batching=true): the route gets the messages as a List<IMessage>, read under syncpoint.
public IbmMqBuilder Batching() { _batching = true; return this; }
/// Largest number of messages in a batch (maxBatchMessages, default 100).
public IbmMqBuilder MaxBatchMessages(int max) { _maxBatchMessages = max; return this; }
/// Idle timeout of a batch in milliseconds (pollTimeoutMs, default 1000).
public IbmMqBuilder PollTimeoutMs(int ms) { _pollTimeoutMs = ms; return this; }
/// Hard limit of a batch in milliseconds from its first message (batchingIntervalMs).
public IbmMqBuilder BatchingIntervalMs(int ms) { _batchingIntervalMs = ms; return this; }
/// The consumer ignores a request's reply-to (Apache Camel disableReplyTo): no reply, and a batch takes it.
public IbmMqBuilder DisableReplyTo() { _disableReplyTo = true; return this; }
/// Backout threshold before routing to backout queue.
public IbmMqBuilder BackoutThreshold(int threshold) { _backoutThreshold = threshold; return this; }
/// Backout (poison message) queue name.
public IbmMqBuilder BackoutQueue(string queue) { _backoutQueue = queue; return this; }
///
/// Pause after a backout in milliseconds (default 1000, 0 = none): no worker of the consumer reads again until it
/// has passed. Poll and batch modes. redb's addition, not in Apache Camel.
///
public IbmMqBuilder BackoutDelay(int ms) { _backoutDelay = ms; return this; }
/// Message selector expression.
public IbmMqBuilder Selector(string selector) { _selector = selector; return this; }
/// Apply MQGMO_CONVERT on receive. Default true.
public IbmMqBuilder Convert(bool convert = true) { _convert = convert; return this; }
// ── Producer ──────────────────────────────────────────────────────
/// Set messages as persistent.
public IbmMqBuilder Persistent() { _persistence = IbmMqPersistence.Persistent; return this; }
/// Set messages as non-persistent.
public IbmMqBuilder NonPersistent() { _persistence = IbmMqPersistence.NonPersistent; return this; }
/// Message persistence mode.
public IbmMqBuilder Persistence(IbmMqPersistence mode) { _persistence = mode; return this; }
/// Message persistence from an expression (resolves to enum name or numeric value).
public IbmMqBuilder Persistence(IExpression expr) { _persistenceExpr = expr.ToTemplateString(); return this; }
/// Message priority (0–9). -1 = queue default.
public IbmMqBuilder Priority(int priority) { _priority = priority.ToString(); return this; }
/// Message priority from an expression.
public IbmMqBuilder Priority(IExpression expr) { _priority = expr.ToTemplateString(); return this; }
/// Message expiry in tenths of a second. -1 = unlimited.
public IbmMqBuilder Expiry(int tenthsOfSecond) { _expiry = tenthsOfSecond.ToString(); return this; }
/// Message expiry from an expression.
public IbmMqBuilder Expiry(IExpression expr) { _expiry = expr.ToTemplateString(); return this; }
/// Target client mode — Jms (with RFH2) or Mq (raw MQMD).
public IbmMqBuilder TargetClient(IbmMqTargetClient client) { _targetClient = client; return this; }
/// Message type for outgoing messages.
public IbmMqBuilder MessageType(IbmMqMessageType type) { _messageType = type; return this; }
/// Message type from an expression (resolves to enum name or numeric value).
public IbmMqBuilder MessageType(IExpression expr) { _messageTypeExpr = expr.ToTemplateString(); return this; }
// ── Transactions ──────────────────────────────────────────────────
/// Enable local MQ transactions.
public IbmMqBuilder Transacted() { _transacted = true; return this; }
///
/// Sets transacted explicitly. false sends at once even inside a .Transacted() block, outside its
/// transaction; left unset, a producer follows the block.
///
public IbmMqBuilder Transacted(bool value) { _transacted = value; return this; }
// DeadLetterQueue/MaxRedeliveries verbs removed (the options sweep): a second,
// dead vocabulary for poison handling - the implemented one is IBM MQ's native
// BackoutThreshold/BackoutQueue pair (BOTHRESH/BOQNAME), see .BackoutThreshold().
// ── RPC ───────────────────────────────────────────────────────────
/// Enable request/reply pattern.
public IbmMqBuilder ReplyTo() { _replyTo = true; return this; }
///
/// Keep the reply-to headers as the reply-to of an ordinary send (Apache Camel preserveMessageQos); without it a
/// forwarded sender's reply-to is not carried on.
///
public IbmMqBuilder PreserveMessageQos() { _preserveMessageQos = true; return this; }
/// Reply-to queue name (if not using dynamic temporary queue).
public IbmMqBuilder ReplyToQueue(string queue) { _replyToQueue = queue; _replyTo = true; return this; }
/// Reply-to queue manager.
public IbmMqBuilder ReplyToQueueManager(string qm) { _replyToQueueManager = qm; return this; }
///
/// Model queue of the dynamic reply queue (IBM MQ TEMPMODEL). Default SYSTEM.DEFAULT.MODEL.QUEUE; the
/// developer image grants its app user DEV.APP.MODEL.QUEUE.
///
public IbmMqBuilder TemporaryModel(string modelQueue) { _temporaryModel = modelQueue; return this; }
/// RPC timeout in seconds. Default 30.
public IbmMqBuilder Timeout(int seconds) { _timeout = seconds; return this; }
/// RPC correlation pattern — MsgId or CorrelId.
public IbmMqBuilder CorrelationPattern(IbmMqCorrelationPattern pattern) { _correlationPattern = pattern; return this; }
// ── SSL ───────────────────────────────────────────────────────────
/// SSL CipherSpec name.
public IbmMqBuilder SslCipherSpec(string cipher) { _sslCipherSpec = cipher; return this; }
/// SSL certificate label.
public IbmMqBuilder SslCertLabel(string label) { _sslCertLabel = label; return this; }
/// SSL peer name (DN pattern).
public IbmMqBuilder SslPeerName(string peerName) { _sslPeerName = peerName; return this; }
/// SSL key repository path (without .kdb extension).
public IbmMqBuilder SslKeyRepository(string path) { _sslKeyRepository = path; return this; }
/// SSL key reset count in bytes.
public IbmMqBuilder SslKeyResetCount(int bytes) { _sslKeyResetCount = bytes; return this; }
// ── Advanced ──────────────────────────────────────────────────────
/// Coded Character Set ID. Default 1208 (UTF-8).
public IbmMqBuilder CCSID(int ccsid) { _ccsid = ccsid; return this; }
/// Allow writing MQMD fields from exchange headers.
public IbmMqBuilder MqmdWriteEnabled(bool enabled = true) { _mqmdWriteEnabled = enabled; return this; }
/// Read all MQMD fields into exchange headers. Default true.
public IbmMqBuilder MqmdReadEnabled(bool enabled = true) { _mqmdReadEnabled = enabled; return this; }
// ── Build ─────────────────────────────────────────────────────────
/// Builds the IBM MQ endpoint URI string.
public string Build()
{
var sb = new StringBuilder();
sb.Append("wmq:");
sb.Append(_destination);
var sep = '?';
void Append(string key, string value)
{
sb.Append(sep); sb.Append(key); sb.Append('=');
sb.Append(Uri.EscapeDataString(value)); sep = '&';
}
void AppendIf(string key, string? value) { if (value != null) Append(key, value); }
void AppendBool(string key, bool value) { if (value) Append(key, "true"); }
void AppendBoolExplicit(string key, bool? value)
{
if (value.HasValue) Append(key, value.Value.ToString().ToLowerInvariant());
}
void AppendInt(string key, int? value) { if (value.HasValue) Append(key, value.Value.ToString()); }
void AppendIntOrExpression(string key, string? value)
{
if (value is null) return;
if (value.Contains("${"))
Append(key + "Expression", value);
else
Append(key, value);
}
// Destination type (only if topic — queue is default)
if (_destType == IbmMqDestinationType.Topic)
Append("destinationType", "Topic");
// Connection
AppendIf("connectionFactory", _connectionFactory);
AppendIf("host", _host);
AppendInt("port", _port);
AppendIf("channel", _channel);
AppendIf("queueManager", _queueManager);
AppendIf("user", _user);
AppendIf("password", _password);
AppendIf("clientId", _clientId);
// Consumer
if (_receiveMode.HasValue)
Append("receiveMode", _receiveMode.Value.ToString());
AppendIf("concurrentConsumers", _concurrentConsumers);
AppendInt("waitInterval", _waitInterval);
AppendBool("batching", _batching);
AppendInt("maxBatchMessages", _maxBatchMessages);
AppendInt("pollTimeoutMs", _pollTimeoutMs);
AppendInt("batchingIntervalMs", _batchingIntervalMs);
AppendBool("disableReplyTo", _disableReplyTo);
AppendInt("backoutThreshold", _backoutThreshold);
AppendInt("backoutDelay", _backoutDelay);
AppendIf("backoutQueue", _backoutQueue);
AppendIf("selector", _selector);
AppendBoolExplicit("convert", _convert);
// Producer
if (_persistence.HasValue)
Append("persistence", _persistence.Value.ToString());
if (_persistenceExpr is not null)
Append("persistenceExpression", _persistenceExpr);
AppendIntOrExpression("priority", _priority);
AppendIntOrExpression("expiry", _expiry);
if (_targetClient.HasValue)
Append("targetClient", _targetClient.Value.ToString());
if (_messageType.HasValue)
Append("messageType", _messageType.Value.ToString());
if (_messageTypeExpr is not null)
Append("messageTypeExpression", _messageTypeExpr);
// Transactions
if (_transacted is { } transacted) Append("transacted", transacted ? "true" : "false");
// Dead Letter
// RPC
AppendBool("replyTo", _replyTo);
AppendBool("preserveMessageQos", _preserveMessageQos);
AppendIf("replyToQueue", _replyToQueue);
AppendIf("replyToQueueManager", _replyToQueueManager);
AppendIf("temporaryModel", _temporaryModel);
AppendInt("timeout", _timeout);
if (_correlationPattern.HasValue)
Append("correlationPattern", _correlationPattern.Value.ToString());
// SSL
AppendIf("sslCipherSpec", _sslCipherSpec);
AppendIf("sslCertLabel", _sslCertLabel);
AppendIf("sslPeerName", _sslPeerName);
AppendIf("sslKeyRepository", _sslKeyRepository);
AppendInt("sslKeyResetCount", _sslKeyResetCount);
// Advanced
AppendInt("cCSID", _ccsid);
AppendBoolExplicit("mqmdWriteEnabled", _mqmdWriteEnabled);
AppendBoolExplicit("mqmdReadEnabled", _mqmdReadEnabled);
return sb.ToString();
}
/// Implicit conversion to URI string.
public static implicit operator string(IbmMqBuilder b) => b.Build();
///
public override string ToString() => Build();
}
Path: redb-route/redb.Route.IbmMq/IbmMqAckAction.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/IbmMqAckAction.cs
----
using IBM.WMQ;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
namespace redb.Route.IbmMq;
///
/// Deferred IBM MQ acknowledgement action. Wraps MQCMIT/MQBACK on the queue manager.
///
internal sealed class IbmMqAckAction : ITransactedAction
{
private readonly MQQueueManager _queueManager;
private readonly ILogger? _logger;
public IbmMqAckAction(MQQueueManager queueManager, ILogger? logger)
{
_queueManager = queueManager;
_logger = logger;
}
///
public Task Commit(CancellationToken ct = default)
{
_queueManager.Commit();
_logger?.LogDebug("IBM MQ ack committed (MQCMIT)");
return Task.CompletedTask;
}
///
public Task Rollback(CancellationToken ct = default)
{
_queueManager.Backout();
_logger?.LogDebug("IBM MQ nack (MQBACK)");
return Task.CompletedTask;
}
}
Path: redb-route/redb.Route.IbmMq/IbmMqBackoutPause.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/IbmMqBackoutPause.cs
----
namespace redb.Route.IbmMq;
///
/// The consumer's pause after a backout (backoutDelay): once a worker backs a failed message (or batch) out, no
/// worker of the consumer starts another MQGET until the delay has passed, so the backed-out message is not taken again
/// at once. A later backout extends the pause; it never shortens it. A delay of zero keeps no pause.
///
internal sealed class IbmMqBackoutPause
{
private readonly TimeSpan _delay;
private readonly TimeProvider _time;
private long _resumeAt = long.MinValue;
public IbmMqBackoutPause(int delayMs, TimeProvider? time = null)
{
_delay = TimeSpan.FromMilliseconds(delayMs);
_time = time ?? TimeProvider.System;
}
/// Starts (or extends) the pause after a backout.
public void Begin()
{
if (_delay <= TimeSpan.Zero)
return;
var resumeAt = _time.GetTimestamp() + (long)(_delay.TotalSeconds * _time.TimestampFrequency);
long current;
do
{
current = Interlocked.Read(ref _resumeAt);
if (current >= resumeAt)
return;
}
while (Interlocked.CompareExchange(ref _resumeAt, resumeAt, current) != current);
}
/// What is left of the pause; zero when there is none.
public TimeSpan Remaining
{
get
{
var resumeAt = Interlocked.Read(ref _resumeAt);
if (resumeAt == long.MinValue)
return TimeSpan.Zero;
var left = resumeAt - _time.GetTimestamp();
return left <= 0 ? TimeSpan.Zero : TimeSpan.FromSeconds((double)left / _time.TimestampFrequency);
}
}
/// Waits out the pause, or at most when given.
public async Task WaitAsync(CancellationToken ct, TimeSpan? max = null)
{
var left = Remaining;
while (left > TimeSpan.Zero)
{
if (max is { } limit && left > limit)
left = limit;
await Task.Delay(left, _time, ct).ConfigureAwait(false);
if (max is not null)
return;
left = Remaining;
}
}
}
Path: redb-route/redb.Route.IbmMq/IbmMqComponent.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/IbmMqComponent.cs
----
using System.Collections.Concurrent;
using System.Text;
using IBM.WMQ;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Extensions;
namespace redb.Route.IbmMq;
///
/// IBM MQ transport component for redb.Route.
/// Scheme: wmq.
///
/// URI format: wmq:QUEUE.NAME?host=mq-host&port=1414&channel=DEV.APP.SVRCONN&queueManager=QM1
///
///
/// Supports queues (point-to-point) and topics (pub/sub) via native IBM MQ client.
/// Full MQI access — transactions, message groups, dead-letter, RPC, SSL/TLS, W3C telemetry.
///
///
/// Owns a process-wide pool of connections shared between
/// endpoints by the same identity model used for RabbitMQ and AMQP:
///
/// - connectionFactory=name on the URI \u2192 key "factory:{name}". Two factories
/// with identical inline parameters but different names produce two distinct connections.
/// - Otherwise \u2192 key "inline:{host}:{port}/{queueManager}#{channel}@{user}[#ssl]".
///
/// MQQueueManager is shareable across threads in the IBM .NET managed client. Per-consumer
/// MQQueue/MQTopic handles remain opened per-endpoint and are released on Stop. The pooled
/// queue managers survive Stop/Start cycles and are released only on
/// .
///
///
public sealed class IbmMqComponent : ComponentBase
{
private readonly ConcurrentDictionary>> _connections = new(StringComparer.Ordinal);
static IbmMqComponent()
{
// IBM MQ managed client needs Windows code pages (e.g. 1252) for MQGMO_CONVERT
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
}
///
public override string Scheme => "wmq";
///
public override IEndpoint CreateEndpoint(EndpointUri uri)
{
ArgumentNullException.ThrowIfNull(uri);
var options = new IbmMqEndpointOptions();
options.BindFromUri(uri.RawParameters);
options.Validate();
options.ResolveBatch(EndpointUri.Sanitize(uri.BaseKey));
return new IbmMqEndpoint(uri, this, options);
}
///
/// Returns the shared for the given endpoint, creating the
/// connection on first request. Self-healing: if the cached connection is no longer
/// connected, it is evicted and recreated on the next call.
///
internal async Task GetOrCreateQueueManagerAsync(IbmMqEndpoint endpoint, CancellationToken ct)
{
var key = ResolveConnectionKey(endpoint.EndpointOptions);
var lazy = _connections.GetOrAdd(key, k =>
new Lazy>(() => CreateQueueManagerAsync(k, endpoint, ct)));
MQQueueManager qm;
try
{
qm = await lazy.Value.ConfigureAwait(false);
}
catch
{
((ICollection>>>)_connections)
.Remove(new KeyValuePair>>(key, lazy));
throw;
}
if (!qm.IsConnected)
{
((ICollection>>>)_connections)
.Remove(new KeyValuePair>>(key, lazy));
return await GetOrCreateQueueManagerAsync(endpoint, ct).ConfigureAwait(false);
}
return qm;
}
/// Number of currently pooled queue managers (for diagnostics and tests).
internal int PooledConnectionCount => _connections.Count;
/// Returns a snapshot of the open pooled queue managers (for diagnostics and tests).
internal async Task> GetPooledConnectionsAsync()
{
var list = new List();
foreach (var lazy in _connections.Values)
{
if (!lazy.IsValueCreated) continue;
try { list.Add(await lazy.Value.ConfigureAwait(false)); }
catch { /* skip failed entries */ }
}
return list;
}
///
/// The connection an endpoint's options describe (see ): the factory
/// connectionFactory names, which takes priority over the inline options, or the inline options. A name
/// nothing is registered under fails here, when the endpoint is created.
///
internal IbmMqConnectionFactory ResolveConnection(IbmMqEndpointOptions options)
=> string.IsNullOrEmpty(options.ConnectionFactory)
? IbmMqConnectionFactory.FromOptions(options)
: Context.GetRequiredFromRegistry(options.ConnectionFactory);
/// Computes the pool key for the given endpoint options.
internal static string ResolveConnectionKey(IbmMqEndpointOptions opts)
{
if (!string.IsNullOrEmpty(opts.ConnectionFactory))
return "factory:" + opts.ConnectionFactory;
var inv = System.Globalization.CultureInfo.InvariantCulture;
return string.Concat(
"inline:",
opts.Host, ":", opts.Port.ToString(inv),
"/", opts.QueueManager,
"#", opts.Channel,
"@", opts.User ?? string.Empty,
string.IsNullOrEmpty(opts.SslCipherSpec) ? string.Empty : "#ssl");
}
private Task CreateQueueManagerAsync(string key, IbmMqEndpoint endpoint, CancellationToken ct)
{
// MQQueueManager constructor is synchronous and blocking. Push it to a thread-pool
// worker so async callers do not block on socket setup.
return Task.Run(() =>
{
var connection = endpoint.Connection;
var qm = new MQQueueManager(connection.QueueManager, connection.BuildConnectionProperties());
Logger?.LogInformation(
"IBM MQ connection opened [{Key}]: queueManager={QueueManager}, host={Host}:{Port}, channel={Channel}",
key, connection.QueueManager, connection.Host, connection.Port, connection.Channel);
return qm;
}, ct);
}
///
/// Creates a brand-new that is NOT pooled and is owned by
/// the caller (consumer/producer). The IBM .NET managed client serialises MQI calls
/// per connection, so a long-running MQGET WAIT on a shared connection blocks every
/// other MQI call (PUT/OPEN/GET) on the same connection. To avoid that, producers and
/// consumers each open their own dedicated MQQueueManager.
/// The caller is responsible for calling Disconnect() on shutdown.
///
internal Task CreateDedicatedQueueManagerAsync(IbmMqEndpoint endpoint, string ownerTag, CancellationToken ct)
{
return Task.Run(() =>
{
var connection = endpoint.Connection;
var qm = new MQQueueManager(connection.QueueManager, connection.BuildConnectionProperties());
Logger?.LogInformation(
"IBM MQ dedicated connection opened [{Owner}]: queueManager={QueueManager}, host={Host}:{Port}, channel={Channel}",
ownerTag, connection.QueueManager, connection.Host, connection.Port, connection.Channel);
return qm;
}, ct);
}
///
public override async ValueTask DisposeAsync()
{
foreach (var (key, lazy) in _connections.ToArray())
{
if (!lazy.IsValueCreated) continue;
MQQueueManager? qm = null;
try { qm = await lazy.Value.ConfigureAwait(false); }
catch { /* failed initialisation */ }
if (qm is null) continue;
try
{
if (qm.IsConnected) qm.Disconnect();
}
catch (Exception ex)
{
Logger?.LogWarning(ex, "IBM MQ: error disconnecting pooled queue manager [{Key}]", key);
}
}
_connections.Clear();
Logger?.LogInformation("IBM MQ component disposed: connection pool drained");
}
}
Path: redb-route/redb.Route.IbmMq/IbmMqConnectionFactory.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/IbmMqConnectionFactory.cs
----
using System.Collections;
using IBM.WMQ;
using redb.Route.Core;
namespace redb.Route.IbmMq;
///
/// IBM MQ connection factory configuration. Standalone POCO — register in DI or reference by name.
///
/// Encapsulates all connection properties:
/// host/port/channel, authentication, SSL/TLS, and tuning.
///
///
public sealed class IbmMqConnectionFactory
{
// ── Connection coordinates ──
/// Queue manager hostname. Comma-separated for multi-instance failover. (default: localhost)
public string Host { get; set; } = "localhost";
/// MQ listener port. (default: 1414)
public int Port { get; set; } = 1414;
/// Server-connection channel. (default: DEV.APP.SVRCONN)
public string Channel { get; set; } = "DEV.APP.SVRCONN";
/// Queue manager name.
public string QueueManager { get; set; } = "QM1";
/// Authentication user.
public string? User { get; set; }
/// Authentication password.
[Sensitive]
public string? Password { get; set; }
/// Client name for connection tracking.
public string? ClientName { get; set; }
// ── Transport ──
/// Transport type: client (TCP), bindings (local), or managed. (default: managed client)
public string TransportType { get; set; } = MQC.TRANSPORT_MQSERIES_MANAGED;
// ── SSL/TLS ──
/// SSL CipherSpec (e.g. TLS_RSA_WITH_AES_256_CBC_SHA256).
public string? SslCipherSpec { get; set; }
/// SSL certificate label in keystore.
public string? SslCertLabel { get; set; }
/// Distinguished Name pattern for peer validation.
public string? SslPeerName { get; set; }
/// Path to key repository (.kdb file, without extension).
public string? SslKeyRepository { get; set; }
/// Bytes before SSL secret key renegotiation. 0 = disabled.
public int SslKeyResetCount { get; set; }
// ── Request-reply ──
///
/// Model queue of the temporary reply queue a request-reply producer opens when no replyToQueue is set; IBM
/// MQ's TEMPMODEL (temporaryModel on its JMS connection factory, XMSC.WMQ_TEMPORARY_MODEL in XMS).
/// The connecting user needs display, get, put and inquire on it. (default: SYSTEM.DEFAULT.MODEL.QUEUE)
///
public string TemporaryModel { get; set; } = DefaultTemporaryModel;
/// IBM MQ's default model queue, the default of .
public const string DefaultTemporaryModel = "SYSTEM.DEFAULT.MODEL.QUEUE";
// ── Tuning ──
/// CCSID for the connection. (default: 1208 = UTF-8)
public int CCSID { get; set; } = 1208;
///
/// Builds a of MQ connection properties suitable for
/// constructor.
///
public Hashtable BuildConnectionProperties()
{
var props = new Hashtable
{
{ MQC.TRANSPORT_PROPERTY, TransportType },
{ MQC.HOST_NAME_PROPERTY, Host },
{ MQC.PORT_PROPERTY, Port },
{ MQC.CHANNEL_PROPERTY, Channel },
{ MQC.CCSID_PROPERTY, CCSID },
};
if (!string.IsNullOrEmpty(User))
props[MQC.USER_ID_PROPERTY] = User;
if (!string.IsNullOrEmpty(Password))
props[MQC.PASSWORD_PROPERTY] = Password;
if (!string.IsNullOrEmpty(ClientName))
props[MQC.APPNAME_PROPERTY] = ClientName;
// SSL/TLS
if (!string.IsNullOrEmpty(SslCipherSpec))
props[MQC.SSL_CIPHER_SPEC_PROPERTY] = SslCipherSpec;
// Bytes before the SSL secret key is renegotiated - a dead option until the options sweep.
if (SslKeyResetCount > 0)
props[MQC.SSL_RESET_COUNT_PROPERTY] = SslKeyResetCount;
if (!string.IsNullOrEmpty(SslCertLabel))
props[MQC.SSL_CERT_STORE_PROPERTY] = SslCertLabel;
if (!string.IsNullOrEmpty(SslPeerName))
props[MQC.SSL_PEER_NAME_PROPERTY] = SslPeerName;
if (!string.IsNullOrEmpty(SslKeyRepository))
MQEnvironment.SSLKeyRepository = SslKeyRepository;
return props;
}
///
/// The connection an endpoint without connectionFactory describes on its URI: the inline options, with the
/// managed client transport the inline form has always used.
///
internal static IbmMqConnectionFactory FromOptions(IbmMqEndpointOptions options) => new()
{
Host = options.Host,
Port = options.Port,
Channel = options.Channel,
QueueManager = options.QueueManager,
User = options.User,
Password = options.Password,
ClientName = options.ClientId,
TransportType = MQC.TRANSPORT_MQSERIES_MANAGED,
SslCipherSpec = options.SslCipherSpec,
SslCertLabel = options.SslCertLabel,
SslPeerName = options.SslPeerName,
SslKeyRepository = options.SslKeyRepository,
SslKeyResetCount = options.SslKeyResetCount,
TemporaryModel = options.TemporaryModel,
CCSID = options.CCSID,
};
/// Opens an XMS connection (the event-driven consumer and the reply listener) to this queue manager.
internal IBM.XMS.IConnection CreateXmsConnection()
{
var factory = IBM.XMS.XMSFactoryFactory.GetInstance(IBM.XMS.XMSC.CT_WMQ).CreateConnectionFactory();
factory.SetStringProperty(IBM.XMS.XMSC.WMQ_HOST_NAME, Host);
factory.SetIntProperty(IBM.XMS.XMSC.WMQ_PORT, Port);
factory.SetStringProperty(IBM.XMS.XMSC.WMQ_CHANNEL, Channel);
factory.SetStringProperty(IBM.XMS.XMSC.WMQ_QUEUE_MANAGER, QueueManager);
factory.SetIntProperty(IBM.XMS.XMSC.WMQ_CONNECTION_MODE, IBM.XMS.XMSC.WMQ_CM_CLIENT);
if (!string.IsNullOrEmpty(ClientName))
factory.SetStringProperty(IBM.XMS.XMSC.CLIENT_ID, ClientName);
if (!string.IsNullOrEmpty(SslCipherSpec))
factory.SetStringProperty(IBM.XMS.XMSC.WMQ_SSL_CIPHER_SPEC, SslCipherSpec);
// Bytes before the SSL secret key is renegotiated, the same contract as the MQ-classes connection.
if (SslKeyResetCount > 0)
factory.SetIntProperty(IBM.XMS.XMSC.WMQ_SSL_KEY_RESETCOUNT, SslKeyResetCount);
// The model of the temporary queue the reply listener creates (CreateTemporaryQueue).
factory.SetStringProperty(IBM.XMS.XMSC.WMQ_TEMPORARY_MODEL, TemporaryModel);
return string.IsNullOrEmpty(User) ? factory.CreateConnection() : factory.CreateConnection(User, Password);
}
}
Path: redb-route/redb.Route.IbmMq/IbmMqConnectionLoss.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/IbmMqConnectionLoss.cs
----
using IBM.WMQ;
using Microsoft.Extensions.Logging;
namespace redb.Route.IbmMq;
///
/// What the IBM MQ consumer and producer share about a lost connection: which reason codes say it is gone, and how to
/// close what is left of it. The schedule of reconnect attempts and the bound of one attempt are the core's
/// .
///
internal static class IbmMqConnectionLoss
{
///
/// The reason codes that say a connection is gone or going: the queue manager quiesces, stops or restarts, the
/// network cut the connection, or the call was interrupted while the client reconnected. The owner reconnects on
/// them instead of using a dead handle.
///
internal static bool IsConnectionLost(int reasonCode) => reasonCode
is MQC.MQRC_CONNECTION_BROKEN or MQC.MQRC_Q_MGR_QUIESCING or MQC.MQRC_CONNECTION_QUIESCING
or MQC.MQRC_Q_MGR_STOPPING or MQC.MQRC_CONNECTION_STOPPING or MQC.MQRC_HCONN_ERROR
or MQC.MQRC_Q_MGR_NOT_AVAILABLE or MQC.MQRC_CALL_INTERRUPTED;
/// Disconnects a connection that is lost or no longer wanted; errors are logged at debug level only.
internal static void DisconnectQuietly(MQQueueManager? qm, ILogger? logger)
{
if (qm is null) return;
try { if (qm.IsConnected) qm.Disconnect(); }
catch (Exception ex) { logger?.LogDebug(ex, "IBM MQ: error disconnecting a lost connection"); }
}
}
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;
}
}
}
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;
}
}
}
Path: redb-route/redb.Route.IbmMq/IbmMqEndpoint.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/IbmMqEndpoint.cs
----
using IBM.WMQ;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Core;
namespace redb.Route.IbmMq;
///
/// IBM MQ endpoint. Delegates connection ownership to via a
/// process-wide pool keyed by connection identity.
///
/// The endpoint owns only its consumer/producer handles (MQQueue / MQTopic). Pooled queue
/// managers survive Stop/Start cycles and are released only when the parent
/// is disposed.
///
///
public sealed class IbmMqEndpoint : EndpointBase
{
private readonly IbmMqComponent _component;
private bool _closed;
/// Logger from the parent component.
internal ILogger? Logger { get; }
/// Destination name (queue or topic) extracted from the URI path.
public string Destination { get; }
/// Creates an IBM MQ endpoint.
public IbmMqEndpoint(EndpointUri uri, IbmMqComponent component, IbmMqEndpointOptions options)
: base(uri, component, options)
{
_component = component;
Logger = component.Logger;
Destination = uri.Path;
_headerFilter = new EndpointHeaderFilter(this, options.HeaderFilterStrategy);
Connection = component.ResolveConnection(options);
XmsConnectionSource = Connection.CreateXmsConnection;
}
///
/// The queue manager this endpoint connects to: the factory connectionFactory=name names in the context
/// registry, or the inline options when there is none.
///
internal IbmMqConnectionFactory Connection { get; }
///
/// Opens the XMS connection of the event-driven consumer: of
/// . A test sets a fake here to drive a start that fails part-way without a broker.
///
internal Func XmsConnectionSource { get; set; }
private readonly EndpointHeaderFilter _headerFilter;
///
/// The header filter strategy of this endpoint: the one headerFilterStrategy=#name names, or
/// . A name the registry does not hold fails when the producer or
/// consumer is built.
///
internal IHeaderFilterStrategy HeaderFilterStrategy => _headerFilter.Or(IbmMqHeaderFilterStrategy.Default);
/// Typed access to options.
internal new IbmMqEndpointOptions Options => base.Options;
/// Typed options exposed for the component pool.
internal IbmMqEndpointOptions EndpointOptions => Options;
///
public override IProducer CreateProducer() => new IbmMqProducer(this, Options);
///
public override IConsumer CreateConsumer(IProcessor processor) => new IbmMqConsumer(this, processor, Options);
///
/// Returns the shared instance from the component pool,
/// connecting on first use.
///
internal Task GetQueueManagerAsync(CancellationToken ct = default)
=> _component.GetOrCreateQueueManagerAsync(this, ct);
///
/// Creates a fresh dedicated owned by the caller.
/// Producers and consumers use this instead of the shared pool to avoid MQI-call
/// serialisation deadlocks (MQGET WAIT on the shared connection would otherwise
/// block concurrent MQPUTs / MQOPENs).
///
internal Task CreateDedicatedQueueManagerAsync(string ownerTag, CancellationToken ct = default)
=> _component.CreateDedicatedQueueManagerAsync(this, ownerTag, ct);
///
/// Opens an MQ queue with the specified open options.
///
internal async Task OpenQueueAsync(int openOptions, CancellationToken ct = default)
{
var qm = await GetQueueManagerAsync(ct).ConfigureAwait(false);
return qm.AccessQueue(Destination, openOptions);
}
///
/// Opens an MQ topic for subscribing with the specified subscribe options.
///
internal async Task OpenTopicAsync(string topicString, int subscribeOptions, CancellationToken ct = default)
{
var qm = await GetQueueManagerAsync(ct).ConfigureAwait(false);
var subName = $"REDB.{Destination}.{Guid.NewGuid():N}";
return qm.AccessTopic(topicString, null, MQC.MQSO_CREATE | subscribeOptions, null, subName);
}
///
/// Opens an MQ topic for publishing with the specified open options.
///
internal async Task OpenTopicForPublishAsync(string topicString, int openOptions, CancellationToken ct = default)
{
var qm = await GetQueueManagerAsync(ct).ConfigureAwait(false);
return qm.AccessTopic(topicString, null, MQC.MQTOPIC_OPEN_AS_PUBLICATION, openOptions);
}
///
public override async Task Stop(CancellationToken ct = default)
{
if (_closed) return;
_closed = true;
// The MQQueueManager is owned by IbmMqComponent and is NOT disconnected here \u2014 it
// survives Stop/Start cycles and is released only on RouteContext.DisposeAsync
// (which calls Component.DisposeAsync).
Logger?.LogInformation("IBM MQ endpoint stopped: {Uri}", EndpointUri.ForLog(Uri.ToString(), Logger));
await base.Stop(ct).ConfigureAwait(false);
}
}
Path: redb-route/redb.Route.IbmMq/IbmMqEndpointOptions.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/IbmMqEndpointOptions.cs
----
using redb.Route.Abstractions;
using redb.Route.Batching;
using redb.Route.Core;
namespace redb.Route.IbmMq;
///
/// Destination type for IBM MQ endpoints.
///
public enum IbmMqDestinationType
{
/// Point-to-point queue.
Queue,
/// Publish/subscribe topic.
Topic
}
///
/// Consumer receive strategy.
///
public enum IbmMqReceiveMode
{
///
/// Synchronous MQGET-WAIT poll loop (IBM.WMQ). Default, battle-tested, but the managed
/// client carries an internal ~500 ms poll tick, so delivery latency is ~250–500 ms.
///
Poll,
///
/// Event-driven push via XMS .NET MessageListener (IBM.XMS). The broker pushes
/// messages the instant they arrive, dropping delivery latency to <50 ms. This is the
/// only supported event-driven receive path on the managed .NET client (IBM.WMQ exposes no
/// public MQCB). Opt-in — remains the default fallback.
///
Listener
}
///
/// IBM MQ message persistence mode.
///
public enum IbmMqPersistence
{
/// Use the queue's default persistence setting.
AsQDef = -1,
/// Non-persistent (faster, may be lost on restart).
NonPersistent = 0,
/// Persistent (written to disk, survives restart).
Persistent = 1
}
///
/// IBM MQ message type (MQMT_*).
///
public enum IbmMqMessageType
{
/// Normal one-way message.
Datagram = 8,
/// Request expecting a reply.
Request = 1,
/// Reply to a request.
Reply = 2,
/// Report message.
Report = 4
}
///
/// Target client mode — controls whether MQRFH2 headers are included.
///
public enum IbmMqTargetClient
{
/// Include MQRFH2 for JMS interoperability.
Jms,
/// Raw MQMD only — no RFH2 header.
Mq
}
///
/// RPC correlation pattern — how replies are matched to requests.
///
public enum IbmMqCorrelationPattern
{
/// Reply CorrelId = Request MsgId (standard IBM MQ pattern).
MsgId,
/// Reply CorrelId = Request CorrelId (JMS pattern).
CorrelId
}
///
/// Endpoint options for IBM MQ transport. All properties are auto-bound from URI query parameters.
///
/// URI format: ibmmq:QUEUE.NAME?host=mq-host&port=1414&channel=DEV.APP.SVRCONN&queueManager=QM1
///
///
public sealed class IbmMqEndpointOptions : EndpointOptions
{
// ── Connection ───────────────────────────────────────────────────
/// Named connection factory from registry. Takes priority over inline params.
[RegistryReference(typeof(IbmMqConnectionFactory))]
public string? ConnectionFactory { get; set; }
///
/// A registry reference (#name) to an that
/// decides which headers this endpoint carries between the exchange and the message's header catalogue (a
/// request, a consumed message, a reply both ways), in place of .
///
[RegistryReference(typeof(IHeaderFilterStrategy))]
public string? HeaderFilterStrategy { get; set; }
/// Queue manager hostname. (default: localhost)
public string Host { get; set; } = "localhost";
/// Queue manager listener port. (default: 1414)
public int Port { get; set; } = 1414;
/// Server-connection channel name. (default: DEV.APP.SVRCONN)
public string Channel { get; set; } = "DEV.APP.SVRCONN";
/// Queue manager name. (required)
public string QueueManager { get; set; } = "QM1";
/// Authentication user.
public string? User { get; set; }
/// Authentication password.
[Sensitive]
public string? Password { get; set; }
/// Client identifier for connection tracking.
public string? ClientId { get; set; }
// ── Destination ──────────────────────────────────────────────────
/// Destination type: Queue or Topic. (default: Queue)
public IbmMqDestinationType DestinationType { get; set; } = IbmMqDestinationType.Queue;
// ── Consumer ─────────────────────────────────────────────────────
///
/// Receive strategy: Poll (synchronous MQGET-WAIT, default) or Listener
/// (event-driven XMS MessageListener, <50 ms latency). (default: Poll)
///
public IbmMqReceiveMode ReceiveMode { get; set; } = IbmMqReceiveMode.Poll;
/// Concurrent consumer sessions: a number or "auto" (= max(CPU, 2)). Default 1. Topics clamp to 1 (parallel subscriptions would duplicate delivery).
// A string so "auto" binds verbatim instead of silently degrading to the int default.
public string? ConcurrentConsumers { get; set; }
/// Resolved consumer parallelism (see ).
public int ResolvedConcurrentConsumers => ConcurrencyOption.Resolve(ConcurrentConsumers, "concurrentConsumers");
/// MQGET wait interval in milliseconds. 0 = no wait. (default: 5000)
public int WaitInterval { get; set; } = 5000;
///
/// With transacted=true or in batch mode: a message backed out this many times (over the input queue's BOTHRESH) goes to
/// instead of the route, in the unit of work of its read. 0 = off.
///
public int BackoutThreshold { get; set; }
///
/// Queue a poison message goes to (and, in batch mode, a request), over the input queue's BOQNAME; without either, the
/// queue manager's dead letter queue.
///
public string? BackoutQueue { get; set; }
///
/// Pause after a backout, in milliseconds (default 1000): once the consumer backs out a failed message
/// (transacted=true) or a failed batch, none of its workers starts another MQGET until the pause has passed,
/// so the message does not come straight back; IBM MQ itself does not delay a backed-out message. 0 = no pause, the
/// message is read again at once. Poll and batch modes; in listener mode the XMS client sets the tempo and the
/// option does not act. A worker already waiting in MQGET when another worker backs out is not held back. This
/// option is redb's addition: Apache Camel has no such option.
///
public int BackoutDelay { get; set; } = 1000;
///
/// Apache Camel disableReplyTo: the consumer does not act on a request's reply-to. It sends no reply, and a
/// batch consumer takes such a message into its batch instead of moving it to the backout queue.
///
public bool DisableReplyTo { get; set; }
// ── Batch mode ──
///
/// Batch mode (Apache Camel batching): the route gets one InOnly exchange whose body is a
/// List<IMessage> of up to messages, read under syncpoint and committed
/// once after the route (backed out when it fails). Poll receive mode only.
///
public bool Batching { get; set; }
/// Largest number of messages in a batch (default 100). Batch mode only.
public int? MaxBatchMessages { get; set; }
///
/// Batch mode: a batch with messages is sent on once no message came for this many milliseconds, restarted by
/// every message (default 1000).
///
public int PollTimeoutMs { get; set; } = 1000;
/// Batch mode: a batch is sent on once this many milliseconds have passed since its first message.
public int? BatchingIntervalMs { get; set; }
/// The default of .
internal const int DefaultMaxBatchMessages = 100;
/// The batch options, or null outside batch mode. Set by .
internal BatchOptions? Batch { get; private set; }
///
/// Resolves the batch options. Fails, naming the endpoint, where batch mode cannot work: a batch option without
/// batching=true, a value out of range, receiveMode=listener (batches are read with MQGET under
/// syncpoint) and request-reply (replyTo=true: a batch is one-way). A batch also needs a backout or dead
/// letter queue, checked when the consumer starts (the queue's BOQNAME and the queue manager's DEADQ count).
///
internal void ResolveBatch(string endpoint)
{
Batch = BatchOptions.Resolve(endpoint, Batching, MaxBatchMessages, PollTimeoutMs, BatchingIntervalMs,
DefaultMaxBatchMessages);
if (Batch is null)
return;
if (ReceiveMode == IbmMqReceiveMode.Listener)
throw new InvalidOperationException(
$"Endpoint '{endpoint}': batching=true cannot be combined with receiveMode=listener: a batch is read with " +
"MQGET under syncpoint and committed once. Use receiveMode=poll.");
if (ReplyTo)
throw new InvalidOperationException(
$"Endpoint '{endpoint}': batching=true cannot be combined with replyTo=true: a batch is one-way (InOnly) " +
"and nobody would answer a request in it.");
}
///
protected override string? UnknownParameterHint(string name)
=> name.Equals("batchSize", StringComparison.OrdinalIgnoreCase)
? "'batchSize' did nothing and is gone; batch mode is batching=true with maxBatchMessages=N, read under " +
"syncpoint and committed once per batch."
: null;
/// Message selector expression (for topic subscriptions).
public string? Selector { get; set; }
/// Apply MQGMO_CONVERT on receive. (default: true)
public bool Convert { get; set; } = true;
// ── Producer ─────────────────────────────────────────────────────
/// Message persistence mode. (default: AsQDef)
public IbmMqPersistence Persistence { get; set; } = IbmMqPersistence.AsQDef;
/// Expression override for persistence (resolves to enum name or numeric value).
public string? PersistenceExpression { get; set; }
/// Message priority. -1 = use queue default. (default: -1)
public int Priority { get; set; } = -1;
/// Expression override for priority (resolves to int).
public string? PriorityExpression { get; set; }
/// Message expiry in tenths of a second. -1 = unlimited. (default: -1)
public int Expiry { get; set; } = -1;
/// Expression override for expiry (resolves to int).
public string? ExpiryExpression { get; set; }
/// Target client mode — Jms (with MQRFH2) or Mq (raw MQMD). (default: Jms)
public IbmMqTargetClient TargetClient { get; set; } = IbmMqTargetClient.Jms;
/// Message type for outgoing messages. (default: Datagram)
public IbmMqMessageType MessageType { get; set; } = IbmMqMessageType.Datagram;
/// Expression override for message type (resolves to enum name or numeric value).
public string? MessageTypeExpression { get; set; }
// ── Transactions ─────────────────────────────────────────────────
///
/// Consumer: true gets under syncpoint and commits (MQCMIT/MQBACK) with the route. Producer: whether the put
/// joins the enclosing .Transacted() block. Unset, it follows the block: deferred until the database commits
/// inside one, put at once outside. true requires a block and fails outside one; false puts at once
/// even inside one. A request-reply producer () always puts at once and refuses true.
///
public bool? Transacted { get; set; }
// DeadLetterQueue/MaxRedeliveries are gone (the options sweep): both were declared
// and read by nothing - a second vocabulary for poison handling next to the IMPLEMENTED one,
// IBM MQ's native BackoutThreshold/BackoutQueue (BOTHRESH/BOQNAME) in the XMS engine.
// ── RPC (Request/Reply) ──────────────────────────────────────────
/// Enable request/reply pattern. (default: false)
public bool ReplyTo { get; set; }
///
/// Apache Camel preserveMessageQos: an ordinary (not request-reply) put keeps the redbIbmMq.ReplyToQueue and
/// redbIbmMq.ReplyToQueueManager headers as the message's reply-to. Off by default, as in Camel's JMS: a message
/// consumed with a sender's reply-to and forwarded to this endpoint does not carry that reply-to on, so no consumer
/// answers into a queue of another system. The correlation id is always carried.
///
public bool PreserveMessageQos { get; set; }
/// Reply-to queue name. If empty, uses dynamic/temporary reply queue.
public string? ReplyToQueue { get; set; }
///
/// Model queue of the temporary reply queue opened when is empty: IBM MQ's
/// TEMPMODEL, temporaryModel on its JMS connection factory. With connectionFactory set it is
/// taken from that factory () instead.
/// (default: SYSTEM.DEFAULT.MODEL.QUEUE)
///
public string TemporaryModel { get; set; } = IbmMqConnectionFactory.DefaultTemporaryModel;
/// Reply-to queue manager. If empty, uses local queue manager.
public string? ReplyToQueueManager { get; set; }
/// RPC timeout in seconds. (default: 30)
public int Timeout { get; set; } = 30;
/// How to correlate RPC replies. (default: MsgId)
public IbmMqCorrelationPattern CorrelationPattern { get; set; } = IbmMqCorrelationPattern.MsgId;
// ── SSL/TLS ──────────────────────────────────────────────────────
/// SSL CipherSpec name (e.g. TLS_RSA_WITH_AES_256_CBC_SHA256).
public string? SslCipherSpec { get; set; }
/// SSL certificate label in keystore.
public string? SslCertLabel { get; set; }
/// Distinguished Name pattern for peer validation.
public string? SslPeerName { get; set; }
/// Path to the key repository (.kdb file without extension).
public string? SslKeyRepository { get; set; }
/// Number of bytes before SSL secret key is renegotiated. 0 = disabled.
public int SslKeyResetCount { get; set; }
// ── Advanced ─────────────────────────────────────────────────────
/// Coded Character Set ID for message body. (default: 1208 = UTF-8)
public int CCSID { get; set; } = 1208;
///
/// Allow writing the advanced/raw MQMD fields from exchange headers — message type, format,
/// group id, message sequence number. (default: false, mirrors IBM MQ JMS WMQ_MQMD_WRITE_ENABLED)
/// The standard JMS-equivalent fields (correlation id, priority, expiry, persistence,
/// reply-to queue/manager) always forward from headers regardless of this flag.
///
public bool MqmdWriteEnabled { get; set; }
/// Populate all MQMD fields into exchange headers on receive. (default: true)
public bool MqmdReadEnabled { get; set; } = true;
///
public override void Validate()
{
if (string.IsNullOrWhiteSpace(QueueManager))
throw new ArgumentException("IBM MQ queueManager is required.");
if (string.IsNullOrWhiteSpace(Host))
throw new ArgumentException("IBM MQ host is required.");
if (string.IsNullOrWhiteSpace(Channel))
throw new ArgumentException("IBM MQ channel is required.");
if (Port is < 1 or > 65535)
throw new ArgumentException($"IBM MQ port must be 1–65535, got: {Port}");
_ = ConcurrencyOption.Resolve(ConcurrentConsumers, "concurrentConsumers"); // loud on garbage
if (WaitInterval < 0)
throw new ArgumentException($"IBM MQ waitInterval must be >= 0, got: {WaitInterval}");
if (BackoutDelay < 0)
throw new ArgumentException($"IBM MQ backoutDelay must be >= 0, got: {BackoutDelay}");
if (Timeout < 1)
throw new ArgumentException($"IBM MQ rpc timeout must be >= 1, got: {Timeout}");
// An IBM MQ object name: 1 to 48 characters.
if (string.IsNullOrWhiteSpace(TemporaryModel) || TemporaryModel.Length > 48)
throw new ArgumentException(
$"IBM MQ temporaryModel must be a queue name of 1 to 48 characters, got: '{TemporaryModel}'");
}
}
Path: redb-route/redb.Route.IbmMq/IbmMqHeaderFilterStrategy.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/IbmMqHeaderFilterStrategy.cs
----
using redb.Route.Abstractions;
namespace redb.Route.IbmMq;
///
/// The default of the IBM MQ component. An endpoint's
/// headerFilterStrategy=#name replaces it; derive from it to add to it.
///
/// A producer's request and a consumer's reply carry every exchange header but the component's own
/// redbIbmMq.* and null values in the message's header catalogue; a consumed message and a request-reply's
/// reply bring every catalogued header in, on the poll and the XMS receive paths alike. Whatever the strategy, MQMD
/// fields are read from and written to the redbIbmMq.* headers by name, targetClient=Mq sends no
/// catalogue at all, and trace context is written by the telemetry layer.
///
///
public class IbmMqHeaderFilterStrategy : IHeaderFilterStrategy
{
/// The default strategy of an IBM MQ endpoint.
public static IbmMqHeaderFilterStrategy Default { get; } = new();
///
public virtual bool FilterOutgoing(string name, object? value, IExchange exchange)
=> value is null || IbmMqHeaders.IsRedbHeader(name);
///
public virtual bool FilterIncoming(string name, object? value, IExchange exchange) => false;
}
Path: redb-route/redb.Route.IbmMq/IbmMqHeaders.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/IbmMqHeaders.cs
----
namespace redb.Route.IbmMq;
///
/// Well-known header constants used by the IBM MQ component.
/// Headers prefixed with redbIbmMq. carry broker metadata on incoming messages.
///
public static class IbmMqHeaders
{
/// Common prefix for all IBM MQ component headers.
public const string Prefix = "redbIbmMq.";
// ── MQMD fields set on the In message by the consumer ────────────
/// Queue or topic the message was received from.
public const string Destination = "redbIbmMq.Destination";
/// Queue manager name.
public const string QueueManager = "redbIbmMq.QueueManager";
/// MQMD MsgId (hex string).
public const string MsgId = "redbIbmMq.MsgId";
/// MQMD CorrelId (hex string).
public const string CorrelId = "redbIbmMq.CorrelId";
/// MQMD Format (e.g. MQFMT_STRING, MQFMT_NONE, MQHRF2).
public const string Format = "redbIbmMq.Format";
/// MQMD Coded Character Set ID.
public const string CCSID = "redbIbmMq.CCSID";
/// MQMD Encoding.
public const string Encoding = "redbIbmMq.Encoding";
/// MQMD Persistence.
public const string Persistence = "redbIbmMq.Persistence";
/// MQMD Priority.
public const string Priority = "redbIbmMq.Priority";
/// MQMD Expiry (tenths of a second, -1 = unlimited).
public const string Expiry = "redbIbmMq.Expiry";
/// MQMD ReplyToQ.
public const string ReplyToQueue = "redbIbmMq.ReplyToQueue";
/// MQMD ReplyToQMgr.
public const string ReplyToQueueManager = "redbIbmMq.ReplyToQueueManager";
/// MQMD MsgType (Datagram, Request, Reply, Report).
public const string MsgType = "redbIbmMq.MsgType";
/// MQMD PutApplName.
public const string PutApplName = "redbIbmMq.PutApplName";
/// MQMD PutApplType.
public const string PutApplType = "redbIbmMq.PutApplType";
/// MQMD GroupId (hex string).
public const string GroupId = "redbIbmMq.GroupId";
/// MQMD MsgSeqNumber within group.
public const string MsgSeqNumber = "redbIbmMq.MsgSeqNumber";
/// MQMD Feedback code.
public const string Feedback = "redbIbmMq.Feedback";
/// MQMD Report options.
public const string ReportOptions = "redbIbmMq.ReportOptions";
/// MQMD UserIdentifier.
public const string UserIdentifier = "redbIbmMq.UserIdentifier";
/// MQMD BackoutCount.
public const string BackoutCount = "redbIbmMq.BackoutCount";
/// MQMD PutDateTime.
public const string PutDateTime = "redbIbmMq.PutDateTime";
// ── Internal property carrying the user-header catalogue ────────────
///
/// Name of the MQ message property that carries all user headers as a single JSON object.
///
/// Bundling into one property is necessary because MQ property names forbid hyphens, so HTTP-style
/// header names (X-Custom-Id) can't be individual properties. The name is unqualified
/// (no dotted folder prefix) so it lands in the JMS usr folder — the standard, interoperable
/// user-property location that both the IBM.WMQ (poll) and IBM.XMS (listener) clients, and any other
/// JMS client, read and write. (A dotted name would create a custom MQRFH2 folder that JMS clients,
/// including XMS, do not surface as user properties.)
///
///
internal const string HeaderCatalogue = "redbIbmMqHeaders";
/// Returns true if the header key belongs to the IBM MQ component.
public static bool IsRedbHeader(string key) =>
key.StartsWith(Prefix, StringComparison.OrdinalIgnoreCase);
}
Path: redb-route/redb.Route.IbmMq/IbmMqMessageHelper.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/IbmMqMessageHelper.cs
----
using System.Text;
using IBM.WMQ;
using redb.Route.Abstractions;
using RouteMessage = redb.Route.Core.Message;
namespace redb.Route.IbmMq;
///
/// Helpers for IBM MQ message body extraction, MQMD→headers mapping, and exchange→MQMessage building.
///
public static class IbmMqMessageHelper
{
///
/// Puts a dead letter header (MQDLH, version 1) in front of 's data, as IBM MQ does for a
/// message it moves to the dead letter queue: the reason, the queue and queue manager it was on, the encoding,
/// character set and format of the data behind it; the message's format becomes MQFMT_DEAD_LETTER_HEADER.
///
internal static void WrapInDeadLetterHeader(MQMessage msg, int reason, string queue, string queueManager)
{
msg.Seek(0);
var data = msg.ReadBytes(msg.MessageLength);
var format = msg.Format;
msg.ClearMessage();
msg.Write(Fixed("DLH ", 4));
msg.WriteInt4(MQC.MQDLH_VERSION_1);
msg.WriteInt4(reason);
msg.Write(Fixed(queue, 48));
msg.Write(Fixed(queueManager, 48));
msg.WriteInt4(msg.Encoding);
msg.WriteInt4(msg.CharacterSet);
msg.Write(Fixed(format, 8));
msg.WriteInt4(MQC.MQAT_DEFAULT);
msg.Write(Fixed("redb.Route", 28));
var now = DateTime.UtcNow;
msg.Write(Fixed(now.ToString("yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture), 8));
msg.Write(Fixed(now.ToString("HHmmssff", System.Globalization.CultureInfo.InvariantCulture), 8));
msg.Write(data);
msg.Format = MQC.MQFMT_DEAD_LETTER_HEADER;
static byte[] Fixed(string text, int length)
{
var bytes = System.Text.Encoding.ASCII.GetBytes((text ?? string.Empty).PadRight(length));
return bytes.Length == length ? bytes : bytes[..length];
}
}
///
/// Extracts the body from an as a string or byte[].
/// Uses Format and CCSID to decide encoding.
///
public static object ExtractBody(MQMessage msg)
{
var dataLength = msg.DataLength;
if (dataLength == 0) return string.Empty;
// MQFMT_STRING or MQFMT_RF_HEADER_2 → read as text
var fmt = msg.Format.Trim();
if (fmt == MQC.MQFMT_STRING.Trim() || fmt == MQC.MQFMT_RF_HEADER_2.Trim())
{
return msg.ReadString(dataLength);
}
// Binary payload
return msg.ReadBytes(dataLength);
}
///
/// Copies MQMD fields into redb.Route message headers with redbIbmMq.* prefix.
///
public static void CopyMqmdToHeaders(MQMessage mqMsg, RouteMessage routeMsg, string destination, string queueManager)
{
routeMsg.Headers[IbmMqHeaders.Destination] = destination;
routeMsg.Headers[IbmMqHeaders.QueueManager] = queueManager;
if (mqMsg.MessageId != null && mqMsg.MessageId.Length > 0)
routeMsg.Headers[IbmMqHeaders.MsgId] = BytesToHex(mqMsg.MessageId);
if (mqMsg.CorrelationId != null && mqMsg.CorrelationId.Length > 0)
routeMsg.Headers[IbmMqHeaders.CorrelId] = BytesToHex(mqMsg.CorrelationId);
routeMsg.Headers[IbmMqHeaders.Format] = mqMsg.Format.Trim();
routeMsg.Headers[IbmMqHeaders.CCSID] = mqMsg.CharacterSet;
routeMsg.Headers[IbmMqHeaders.Encoding] = mqMsg.Encoding;
routeMsg.Headers[IbmMqHeaders.Persistence] = mqMsg.Persistence;
routeMsg.Headers[IbmMqHeaders.Priority] = mqMsg.Priority;
routeMsg.Headers[IbmMqHeaders.Expiry] = mqMsg.Expiry;
routeMsg.Headers[IbmMqHeaders.MsgType] = mqMsg.MessageType;
routeMsg.Headers[IbmMqHeaders.Feedback] = mqMsg.Feedback;
routeMsg.Headers[IbmMqHeaders.ReportOptions] = mqMsg.Report;
routeMsg.Headers[IbmMqHeaders.BackoutCount] = mqMsg.BackoutCount;
if (!string.IsNullOrWhiteSpace(mqMsg.ReplyToQueueName))
routeMsg.Headers[IbmMqHeaders.ReplyToQueue] = mqMsg.ReplyToQueueName.Trim();
if (!string.IsNullOrWhiteSpace(mqMsg.ReplyToQueueManagerName))
routeMsg.Headers[IbmMqHeaders.ReplyToQueueManager] = mqMsg.ReplyToQueueManagerName.Trim();
if (!string.IsNullOrWhiteSpace(mqMsg.UserId))
routeMsg.Headers[IbmMqHeaders.UserIdentifier] = mqMsg.UserId.Trim();
if (!string.IsNullOrWhiteSpace(mqMsg.PutApplicationName))
routeMsg.Headers[IbmMqHeaders.PutApplName] = mqMsg.PutApplicationName.Trim();
routeMsg.Headers[IbmMqHeaders.PutApplType] = mqMsg.PutApplicationType;
if (mqMsg.GroupId != null && mqMsg.GroupId.Length > 0 && !IsEmptyBytes(mqMsg.GroupId))
routeMsg.Headers[IbmMqHeaders.GroupId] = BytesToHex(mqMsg.GroupId);
if (mqMsg.MessageSequenceNumber > 0)
routeMsg.Headers[IbmMqHeaders.MsgSeqNumber] = mqMsg.MessageSequenceNumber;
try
{
var putDate = mqMsg.PutDateTime;
routeMsg.Headers[IbmMqHeaders.PutDateTime] = putDate;
}
catch
{
// PutDateTime may throw if date fields are empty/invalid
}
}
///
/// Copies RFH2 user properties (if present) that lets in into exchange headers;
/// is the one they come into (for a request-reply's reply, the request's).
/// IBM MQ JMS messages carry user-defined properties in the MQRFH2 usr folder.
///
public static void CopyRfh2UserProperties(MQMessage mqMsg, RouteMessage routeMsg,
IHeaderFilterStrategy headerFilter, IExchange exchange)
{
string? json = null;
try { json = mqMsg.GetStringProperty(IbmMqHeaders.HeaderCatalogue); }
catch { /* property not present */ }
if (string.IsNullOrEmpty(json)) return;
try
{
var dict = System.Text.Json.JsonSerializer.Deserialize>(json);
if (dict is null) return;
foreach (var (key, value) in dict)
{
if (headerFilter.FilterIncoming(key, value, exchange)) continue;
routeMsg.Headers[key] = value;
}
}
catch { /* malformed JSON — skip */ }
}
///
/// Copies the headers of a route message that lets out into the MQ message's RFH2
/// user property folder (using the same JSON-encoded property as ).
///
public static void CopyHeadersToRfh2(MQMessage mqMsg, IMessage routeMsg,
IHeaderFilterStrategy headerFilter, IExchange exchange)
{
var customHeaders = new Dictionary();
foreach (var (key, value) in routeMsg.Headers)
{
if (value is null) continue;
if (headerFilter.FilterOutgoing(key, value, exchange)) continue;
customHeaders[key] = value.ToString()!;
}
if (customHeaders.Count == 0) return;
var json = System.Text.Json.JsonSerializer.Serialize(customHeaders);
mqMsg.SetStringProperty(IbmMqHeaders.HeaderCatalogue, json);
}
///
/// Builds an from an exchange for sending; decides which
/// exchange headers go into the header catalogue.
///
public static MQMessage BuildOutgoingMessage(
IExchange exchange,
IbmMqEndpointOptions options,
IHeaderFilterStrategy headerFilter)
{
var msg = new MQMessage
{
CharacterSet = options.CCSID,
Format = MQC.MQFMT_STRING,
};
// Persistence: header > expression > static
var persistence = options.Persistence;
if (options.PersistenceExpression is not null)
{
var resolved = options.ResolveOption(options.PersistenceExpression, exchange);
if (resolved is not null && Enum.TryParse(resolved, true, out var parsedPers))
persistence = parsedPers;
}
msg.Persistence = persistence switch
{
IbmMqPersistence.Persistent => MQC.MQPER_PERSISTENT,
IbmMqPersistence.NonPersistent => MQC.MQPER_NOT_PERSISTENT,
_ => MQC.MQPER_PERSISTENCE_AS_Q_DEF
};
// Priority: header > expression > static
var priority = options.Priority;
if (options.PriorityExpression is not null)
{
var resolved = options.ResolveOption(options.PriorityExpression, exchange);
if (resolved is not null && int.TryParse(resolved, out var parsedPrio))
priority = parsedPrio;
}
if (priority >= 0)
msg.Priority = priority;
// Expiry: header > expression > static
var expiry = options.Expiry;
if (options.ExpiryExpression is not null)
{
var resolved = options.ResolveOption(options.ExpiryExpression, exchange);
if (resolved is not null && int.TryParse(resolved, out var parsedExp))
expiry = parsedExp;
}
if (expiry >= 0)
msg.Expiry = expiry;
// Message type: header > expression > static
var messageType = (int)options.MessageType;
if (options.MessageTypeExpression is not null)
{
var resolved = options.ResolveOption(options.MessageTypeExpression, exchange);
if (resolved is not null && Enum.TryParse(resolved, true, out var parsedMt))
messageType = (int)parsedMt;
}
msg.MessageType = messageType;
// Body
var body = exchange.In.Body;
var contentType = exchange.In.ContentType;
switch (body)
{
case byte[] bytes:
msg.Write(bytes);
msg.Format = contentType is not null ? ContentTypeToFormat(contentType) : MQC.MQFMT_NONE;
break;
case string str:
msg.WriteString(str);
msg.Format = contentType is not null ? ContentTypeToFormat(contentType) : MQC.MQFMT_STRING;
break;
case null:
break;
default:
msg.WriteString(body.ToString() ?? string.Empty);
break;
}
// Copy exchange headers → single JSON-encoded MQ property
// (MQ property names forbid hyphens, so individual SetStringProperty won't
// work for standard HTTP-style headers like X-Custom-Id)
var customHeaders = new Dictionary();
foreach (var (key, value) in exchange.In.Headers)
{
if (value is null) continue;
if (headerFilter.FilterOutgoing(key, value, exchange)) continue;
customHeaders[key] = value.ToString()!;
}
// targetClient=Mq: a legacy MQ application expects raw MQMD+body. Message properties are
// what materializes as an MQRFH2 for property-aware paths, so in Mq mode none are written
// (the MQMD fields below are fine - they are descriptor, not properties). The option was
// declared and read by nothing until the options sweep.
if (customHeaders.Count > 0 && options.TargetClient != IbmMqTargetClient.Mq)
{
var json = System.Text.Json.JsonSerializer.Serialize(customHeaders);
msg.SetStringProperty(IbmMqHeaders.HeaderCatalogue, json);
}
// Standard, JMS-equivalent MQMD fields forward from headers BY DEFAULT (header wins over
// option/expression) — mirrors what a WMQ JMS client maps from JMSCorrelationID/JMSPriority/
// JMSExpiration/JMSDeliveryMode/JMSReplyTo, so a naive consume→produce round-trip preserves them.
ApplyStandardMqmdFromHeaders(msg, exchange, options.PreserveMessageQos);
// Advanced / raw MQMD fields (message type, format, grouping) only when explicitly enabled —
// mirrors IBM MQ JMS's WMQ_MQMD_WRITE_ENABLED, since these can alter message semantics.
if (options.MqmdWriteEnabled)
ApplyAdvancedMqmdFromHeaders(msg, exchange);
return msg;
}
///
/// Applies the standard, JMS-equivalent MQMD fields from exchange headers (header wins).
/// Always active: these are the fields a WMQ JMS client forwards by default.
///
private static void ApplyStandardMqmdFromHeaders(MQMessage msg, IExchange exchange, bool preserveReplyTo)
{
var headers = exchange.In.Headers;
if (headers.TryGetValue(IbmMqHeaders.CorrelId, out var cid) && cid is string cidStr)
msg.CorrelationId = HexToBytes(cidStr);
if (headers.TryGetValue(IbmMqHeaders.Priority, out var prio) && prio is int prioInt)
msg.Priority = prioInt;
if (headers.TryGetValue(IbmMqHeaders.Expiry, out var exp) && exp is int expInt)
msg.Expiry = expInt;
if (headers.TryGetValue(IbmMqHeaders.Persistence, out var pers) && pers is int persInt)
msg.Persistence = persInt;
// The reply-to only with preserveMessageQos, as Camel's JMS: a sender's reply-to forwarded here must not make another
// consumer answer into it. A request-reply put sets its own reply queue after this.
if (!preserveReplyTo)
return;
if (headers.TryGetValue(IbmMqHeaders.ReplyToQueue, out var rtq) && rtq is string rtqStr)
msg.ReplyToQueueName = rtqStr;
if (headers.TryGetValue(IbmMqHeaders.ReplyToQueueManager, out var rtqm) && rtqm is string rtqmStr)
msg.ReplyToQueueManagerName = rtqmStr;
}
///
/// Applies the advanced / raw MQMD fields from exchange headers — gated behind MqmdWriteEnabled
/// (mirrors IBM MQ JMS's WMQ_MQMD_WRITE_ENABLED) as these can change message semantics.
///
private static void ApplyAdvancedMqmdFromHeaders(MQMessage msg, IExchange exchange)
{
var headers = exchange.In.Headers;
if (headers.TryGetValue(IbmMqHeaders.MsgType, out var mt) && mt is int mtInt)
msg.MessageType = mtInt;
if (headers.TryGetValue(IbmMqHeaders.Format, out var fmt) && fmt is string fmtStr)
msg.Format = fmtStr;
if (headers.TryGetValue(IbmMqHeaders.GroupId, out var gid) && gid is string gidStr)
msg.GroupId = HexToBytes(gidStr);
if (headers.TryGetValue(IbmMqHeaders.MsgSeqNumber, out var seq) && seq is int seqInt)
msg.MessageSequenceNumber = seqInt;
}
// ── Format ↔ ContentType mapping ──
/// Maps MQMD Format to a MIME content type.
public static string? FormatToContentType(string? format)
{
if (format is null) return null;
var fmt = format.Trim();
if (fmt.Length == 0) return "application/octet-stream"; // MQFMT_NONE = 8 spaces
if (fmt == MQC.MQFMT_STRING.Trim()) return "text/plain";
if (fmt == MQC.MQFMT_RF_HEADER_2.Trim()) return "text/plain";
return null;
}
/// Maps a MIME content type to the best MQMD Format.
public static string ContentTypeToFormat(string? contentType)
{
if (string.IsNullOrWhiteSpace(contentType)) return MQC.MQFMT_STRING;
if (contentType.StartsWith("application/octet-stream", StringComparison.OrdinalIgnoreCase))
return MQC.MQFMT_NONE;
// text/*, application/json, application/xml etc. → string format
return MQC.MQFMT_STRING;
}
// ── Helpers ──
internal static string BytesToHex(byte[] bytes)
{
return Convert.ToHexString(bytes);
}
internal static byte[] HexToBytes(string hex)
{
return Convert.FromHexString(hex);
}
private static bool IsEmptyBytes(byte[] bytes)
{
foreach (var b in bytes)
if (b != 0) return false;
return true;
}
}
Path: redb-route/redb.Route.IbmMq/IbmMqProducer.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/IbmMqProducer.cs
----
using System.Collections.Concurrent;
using System.Diagnostics;
using IBM.WMQ;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Transactions;
using redb.Route.Core;
using redb.Route.Telemetry;
using RouteMessage = redb.Route.Core.Message;
namespace redb.Route.IbmMq;
///
/// IBM MQ producer. Sends messages to a queue or topic via MQPUT with support for:
///
/// - Immediate — direct MQPUT.
/// - Transactional — deferred send via .
/// - RPC — request/reply with correlation matching.
///
///
public sealed class IbmMqProducer : ConnectableProducer
{
private readonly IbmMqEndpoint _endpoint;
private readonly IbmMqEndpointOptions _options;
private MQQueue? _outputQueue;
private MQTopic? _outputTopic;
private MQQueueManager? _qm;
// ── RPC infrastructure ──
private readonly ConcurrentDictionary _pendingResponses = new();
private readonly IHeaderFilterStrategy _headerFilter;
/// A request waiting for its reply: the reply's headers are filtered against the request exchange.
private sealed record PendingReply(TaskCompletionSource Reply, IExchange Request);
private MQQueue? _replyQueue;
private readonly SemaphoreSlim _rpcLock = new(1, 1);
// The deferred puts of a block go out as one batch per producer; its commits take turns on the shared connection.
private readonly string _batchKey = $"ibmmq-batch-{Guid.NewGuid():N}";
private readonly SemaphoreSlim _commitLock = new(1, 1);
private volatile bool _rpcSetup;
private CancellationTokenSource? _rpcCts;
private Task? _rpcTask;
// Event-driven reply reception (receiveMode=listener): an XMS MessageListener on the reply queue
// instead of the poll-MQGET loop below. Opt-in; the request is still sent over IBM.WMQ.
private IbmMqXmsReplyReceiver? _xmsReply;
private bool UseXmsReply => _options.ReceiveMode == IbmMqReceiveMode.Listener;
/// Creates an IBM MQ producer.
public IbmMqProducer(IbmMqEndpoint endpoint, IbmMqEndpointOptions options)
{
_endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint));
_options = options ?? throw new ArgumentNullException(nameof(options));
_headerFilter = endpoint.HeaderFilterStrategy;
// A request-reply send cannot wait for the commit: the reply it waits for would never come.
if (_options.ReplyTo && _options.Transacted == true)
throw new InvalidOperationException(
$"'{ProducerName}' is a request-reply producer (replyTo=true): the request has to leave at once for its " +
"reply to arrive, so it cannot be deferred to the commit of a transaction. Drop transacted=true: a " +
"request-reply send always goes out at once, outside the transaction.");
}
///
protected override IEndpoint ProducerEndpoint => _endpoint;
///
protected override string ProducerName => $"wmq:{_endpoint.Destination}";
///
protected override async Task ConnectAsync(CancellationToken ct)
{
// Each producer owns its own MQQueueManager to avoid MQI-call serialisation
// deadlocks with consumers / RPC reply loops on the same broker connection.
// A connect made while the queue manager starts can hang: the attempt is bounded by Reconnect.AttemptTimeout,
// and a connection it still opens later is disconnected.
var qm = await Supervisor.AttemptAsync(
c => _endpoint.CreateDedicatedQueueManagerAsync($"producer:{_endpoint.Destination}", c),
late => IbmMqConnectionLoss.DisconnectQuietly(late, Logger), ct).ConfigureAwait(false);
await OpenOnAsync(qm, ct).ConfigureAwait(false);
}
/// Opens the producer's destination, and its reply receiver for request-reply, on a new connection.
private async Task OpenOnAsync(MQQueueManager qm, CancellationToken ct)
{
_qm = qm;
if (_options.DestinationType == IbmMqDestinationType.Topic)
{
_outputTopic = _qm.AccessTopic(
_endpoint.Destination, null,
MQC.MQTOPIC_OPEN_AS_PUBLICATION,
MQC.MQOO_OUTPUT | MQC.MQOO_FAIL_IF_QUIESCING);
}
else
{
var openOptions = MQC.MQOO_OUTPUT | MQC.MQOO_FAIL_IF_QUIESCING;
_outputQueue = _qm.AccessQueue(_endpoint.Destination, openOptions);
}
if (_options.ReplyTo)
await SetupReplyReceiverAsync(ct).ConfigureAwait(false);
}
///
protected override async Task DisconnectAsync(CancellationToken ct)
{
foreach (var pending in _pendingResponses)
pending.Value.Reply.TrySetCanceled(ct);
_pendingResponses.Clear();
if (_xmsReply != null)
{
try { await _xmsReply.StopAsync(ct).ConfigureAwait(false); }
catch (Exception ex) { Logger?.LogDebug(ex, "IBM MQ: error stopping XMS reply receiver during stop"); }
_xmsReply = null;
_rpcSetup = false;
}
_rpcCts?.Cancel();
if (_rpcTask != null)
{
try { await _rpcTask.ConfigureAwait(false); }
catch (OperationCanceledException) { }
_rpcTask = null;
}
_rpcCts?.Dispose();
_rpcCts = null;
if (_replyQueue != null)
{
try { _replyQueue.Close(); }
catch (Exception ex) { Logger?.LogDebug(ex, "IBM MQ: error closing reply queue during stop"); }
_replyQueue = null;
_rpcSetup = false;
}
if (_outputQueue != null)
{
try { _outputQueue.Close(); }
catch (Exception ex) { Logger?.LogDebug(ex, "IBM MQ: error closing output queue during stop"); }
_outputQueue = null;
}
if (_outputTopic != null)
{
try { _outputTopic.Close(); }
catch (Exception ex) { Logger?.LogDebug(ex, "IBM MQ: error closing output topic during stop"); }
_outputTopic = null;
}
if (_qm != null)
{
try { if (_qm.IsConnected) _qm.Disconnect(); }
catch (Exception ex) { Logger?.LogDebug(ex, "IBM MQ: error disconnecting producer queue manager during stop"); }
_qm = null;
}
}
///
public override async Task Process(IExchange exchange, CancellationToken ct = default)
{
EnsureStarted();
await EnsureConnectedAsync(ct).ConfigureAwait(false);
using var activity = RouteTelemetryExtensions.StartTransportSpan(
(_endpoint.Component as ComponentBase)?.Context,
$"{_endpoint.Destination} publish", ActivityKind.Producer,
"messaging.system", "wmq", _endpoint.Uri.NormalizedKey,
destination: _endpoint.Destination, operation: "publish");
if (activity is { IsAllDataRequested: true })
activity.SetTag("messaging.ibmmq.queue_manager", _options.QueueManager);
// A list of IMessage is sent element by element, each its own MQ message with its own body and headers, in one
// unit of work: MQPUT of each under syncpoint and one MQCMIT, or MQBACK and nothing goes. A plain list has no
// wire form here, and one request cannot wait for many replies: both are refused.
var body = exchange.In.Body;
if (ListBody.Messages(body) is { } messages)
{
if (_options.ReplyTo)
throw ListBody.RequestReplyRefusal(EndpointUri.Sanitize(_endpoint.Uri.BaseKey), messages.Count);
try
{
await SendListAsync(exchange, messages, activity, ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested)
{
activity.RecordFailure(ex);
MarkLostIfConnection(ex);
throw;
}
return;
}
if (ListBody.IsPlainList(body))
throw ListBody.PlainListRefusal(EndpointUri.Sanitize(_endpoint.Uri.BaseKey), body!);
var msg = IbmMqMessageHelper.BuildOutgoingMessage(exchange, _options, _headerFilter);
// Inject W3C trace context into MQ message properties (RFH2 usr folder) - not in
// targetClient=Mq mode, where a legacy app must see raw MQMD+body with no properties.
// The context of this send replaces a traceparent copied from a received message; with tracing off, the
// context that came in goes out.
if (_options.TargetClient != IbmMqTargetClient.Mq)
RouteTelemetryExtensions.InjectTraceContext(activity, msg, static (m, name, value) => m.SetStringProperty(name, value));
try
{
if (_options.ReplyTo)
{
await ProcessRpcAsync(exchange, msg, ct).ConfigureAwait(false);
}
else if (TransactedActions.Defers(exchange, _options.Transacted))
ProcessTransactional(exchange, msg);
else
ProcessImmediate(msg);
}
catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested)
{
activity.RecordFailure(ex);
MarkLostIfConnection(ex);
throw;
}
}
// ── Lost connection ──
///
/// Marks the connection lost when (or an exception inside it) carries a lost-connection
/// reason code: the producer's supervisor records it on the endpoint, the requests still waiting for a reply on that
/// connection fail at once (), and the next reconnects. The failed
/// send is not resent: a put that failed this way may or may not have reached the queue manager.
///
private void MarkLostIfConnection(Exception failure)
{
for (var e = failure; e != null; e = e.InnerException)
{
if (e is MQException mq && IbmMqConnectionLoss.IsConnectionLost(mq.ReasonCode))
{
MarkConnectionLost(mq);
return;
}
}
}
///
protected override void OnConnectionLost(Exception cause)
{
foreach (var key in _pendingResponses.Keys)
{
if (_pendingResponses.TryRemove(key, out var pending))
pending.Reply.TrySetException(new InvalidOperationException(
$"{ProducerName}: the connection to the queue manager was lost before the reply came", cause));
}
}
// ── A list of messages ──
///
/// Builds one MQ message per element, each from an exchange of its own (its body and headers), and sends them as one
/// unit of work: inside a .Transacted() block they join this producer's batch for the block, outside one they
/// are put under syncpoint and committed together now, or backed out together.
///
private async Task SendListAsync(IExchange exchange, IReadOnlyList messages, Activity? activity,
CancellationToken ct)
{
var built = new List(messages.Count);
foreach (var message in messages)
{
var element = ListBody.ElementExchange(exchange, message);
try
{
var msg = IbmMqMessageHelper.BuildOutgoingMessage(element, _options, _headerFilter);
if (_options.TargetClient != IbmMqTargetClient.Mq)
RouteTelemetryExtensions.InjectTraceContext(activity, msg, static (m, name, value) => m.SetStringProperty(name, value));
built.Add(msg);
}
finally
{
if (element is IAsyncDisposable disposable)
await disposable.DisposeAsync().ConfigureAwait(false);
}
}
activity?.SetTag("messaging.batch.message_count", built.Count);
var qm = _qm ?? throw new InvalidOperationException("IBM MQ producer not connected");
if (TransactedActions.Defers(exchange, _options.Transacted))
{
var joined = TransactedActions.JoinBatch(exchange, _batchKey,
() => NewSendBatch(qm),
ProducerName);
foreach (var msg in built)
joined.Add(msg);
return;
}
var unit = NewSendBatch(qm);
foreach (var msg in built)
unit.Add(msg);
await unit.Commit(ct).ConfigureAwait(false);
}
// ── Immediate send ──
private void ProcessImmediate(MQMessage msg)
{
var pmo = new MQPutMessageOptions
{
Options = MQC.MQPMO_NO_SYNCPOINT | MQC.MQPMO_FAIL_IF_QUIESCING
};
PutMessage(msg, pmo);
Logger?.LogDebug("IBM MQ immediate send: destination={Destination}", _endpoint.Destination);
}
// ── Transactional deferred send ──
private void ProcessTransactional(IExchange exchange, MQMessage msg)
{
// The message joins this producer's batch for the block: on commit all its puts go under syncpoint and one
// MQCMIT commits them together, or MQBACK drops them all.
var qm = _qm ?? throw new InvalidOperationException("IBM MQ producer not connected");
var batch = TransactedActions.JoinBatch(exchange, _batchKey,
() => NewSendBatch(qm),
ProducerName);
batch.Add(msg);
}
// ── RPC (request/reply) ──
private async Task ProcessRpcAsync(IExchange exchange, MQMessage msg, CancellationToken ct)
{
if (!_rpcSetup)
{
await SetupReplyReceiverAsync(ct).ConfigureAwait(false);
}
// Set up reply-to
var replyToQueue = _options.ReplyToQueue;
if (UseXmsReply)
replyToQueue = _xmsReply!.ReplyQueueName;
else if (string.IsNullOrEmpty(replyToQueue) && _replyQueue != null)
replyToQueue = _replyQueue.Name.Trim();
// The request's reply-to is always this producer's, queue and queue manager alike: a forwarded one kept by
// preserveMessageQos must not name another queue manager for the reply this producer waits for.
msg.ReplyToQueueName = replyToQueue ?? string.Empty;
msg.ReplyToQueueManagerName = _options.ReplyToQueueManager ?? string.Empty;
msg.MessageType = MQC.MQMT_REQUEST;
// Per IBM MQ Application Programming Guide ("Request and reply messages"):
// when using a temporary dynamic reply queue, set the request expiry to
// bound the lifetime of orphan requests if the caller goes away before the
// reply arrives. IBM MQ silently discards expired messages at MQGET, so the
// consumer never sees them and the reply queue can be safely deleted.
// Units: tenths of a second. MQEI_UNLIMITED == -1 (constructor default).
// Only set if the caller didn't already specify an expiry (via header or
// endpoint option resolved in IbmMqMessageHelper.ApplyOptionsToMqMessage).
if (msg.Expiry == MQC.MQEI_UNLIMITED)
msg.Expiry = Math.Max(1, _options.Timeout * 10);
// Put the message
var pmo = new MQPutMessageOptions
{
Options = MQC.MQPMO_NO_SYNCPOINT | MQC.MQPMO_FAIL_IF_QUIESCING
};
PutMessage(msg, pmo);
// The correlation key depends on the pattern
var correlKey = _options.CorrelationPattern == IbmMqCorrelationPattern.CorrelId
? IbmMqMessageHelper.BytesToHex(msg.CorrelationId)
: IbmMqMessageHelper.BytesToHex(msg.MessageId);
var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
_pendingResponses[correlKey] = new PendingReply(tcs, exchange);
Logger?.LogDebug("IBM MQ RPC request sent: correlKey={CorrelKey}, replyTo={ReplyTo}",
correlKey, replyToQueue);
try
{
using var timeoutCts = new CancellationTokenSource(TimeSpan.FromSeconds(_options.Timeout));
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, timeoutCts.Token);
var responseTask = tcs.Task;
var completed = await Task.WhenAny(responseTask, Task.Delay(Timeout.Infinite, linked.Token))
.ConfigureAwait(false);
if (completed != responseTask)
{
_pendingResponses.TryRemove(correlKey, out _);
throw new TimeoutException(
$"IBM MQ RPC timeout ({_options.Timeout}s): destination={_endpoint.Destination}");
}
var response = await responseTask.ConfigureAwait(false);
exchange.Out = response;
exchange.Pattern = ExchangePattern.InOut;
Logger?.LogDebug("IBM MQ RPC response received: correlKey={CorrelKey}", correlKey);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
_pendingResponses.TryRemove(correlKey, out _);
Logger?.LogError(ex, "IBM MQ RPC timeout/error: destination={Destination}, correlKey={CorrelKey}",
_endpoint.Destination, correlKey);
throw;
}
}
// ── RPC reply receiver setup ──
private async Task SetupReplyReceiverAsync(CancellationToken ct)
{
if (_rpcSetup) return;
await _rpcLock.WaitAsync(ct).ConfigureAwait(false);
try
{
if (_rpcSetup) return;
// Event-driven path: an XMS listener on the reply queue replaces the WMQ poll loop below.
if (UseXmsReply)
{
_xmsReply = new IbmMqXmsReplyReceiver(_options, _endpoint.Connection, Logger, _headerFilter, (correlKey, buildResponse) =>
{
if (!_pendingResponses.TryRemove(correlKey, out var pending)) return;
try
{
pending.Reply.TrySetResult(buildResponse(pending.Request));
}
catch (Exception ex)
{
pending.Reply.TrySetException(ex);
}
}, MarkConnectionLost);
await _xmsReply.StartAsync(ct).ConfigureAwait(false);
_rpcSetup = true;
Logger?.LogDebug("IBM MQ XMS RPC reply receiver created: replyQueue={ReplyQueue}", _xmsReply.ReplyQueueName);
return;
}
var replyQueueName = _options.ReplyToQueue;
if (string.IsNullOrEmpty(replyQueueName))
{
// Open the model queue (temporaryModel, IBM MQ's TEMPMODEL) to create a dynamic temporary reply queue
var qm = _qm ?? throw new InvalidOperationException("IBM MQ producer not connected");
_replyQueue = qm.AccessQueue(
_endpoint.Connection.TemporaryModel,
MQC.MQOO_INPUT_SHARED | MQC.MQOO_FAIL_IF_QUIESCING,
qm.Name,
"REDB.RPL.*",
string.Empty);
replyQueueName = _replyQueue.Name.Trim();
}
else
{
// Open an existing reply queue
var qm = _qm ?? throw new InvalidOperationException("IBM MQ producer not connected");
_replyQueue = qm.AccessQueue(
replyQueueName,
MQC.MQOO_INPUT_SHARED | MQC.MQOO_FAIL_IF_QUIESCING);
}
_rpcCts = new CancellationTokenSource();
_rpcTask = Task.Run(() => RpcReceiveLoopAsync(_rpcCts.Token), _rpcCts.Token);
_rpcSetup = true;
Logger?.LogDebug("IBM MQ RPC reply receiver created: replyQueue={ReplyQueue}", replyQueueName);
}
finally
{
_rpcLock.Release();
}
}
private async Task RpcReceiveLoopAsync(CancellationToken ct)
{
var gmo = new MQGetMessageOptions
{
Options = MQC.MQGMO_WAIT | MQC.MQGMO_NO_SYNCPOINT |
MQC.MQGMO_FAIL_IF_QUIESCING | MQC.MQGMO_CONVERT,
WaitInterval = 2000,
};
while (!ct.IsCancellationRequested && _replyQueue != null)
{
try
{
var replyMsg = new MQMessage();
try
{
_replyQueue.Get(replyMsg, gmo);
}
catch (MQException ex) when (ex.ReasonCode == MQC.MQRC_NO_MSG_AVAILABLE)
{
continue;
}
var correlKey = _options.CorrelationPattern == IbmMqCorrelationPattern.CorrelId
? IbmMqMessageHelper.BytesToHex(replyMsg.CorrelationId)
: IbmMqMessageHelper.BytesToHex(replyMsg.CorrelationId); // Reply always has correlId
if (_pendingResponses.TryRemove(correlKey, out var pending))
{
try
{
var body = IbmMqMessageHelper.ExtractBody(replyMsg);
var response = new RouteMessage(body);
if (_options.MqmdReadEnabled)
IbmMqMessageHelper.CopyMqmdToHeaders(replyMsg, response,
_replyQueue.Name.Trim(), _options.QueueManager);
// Pick up user headers that the responder stamped via RFH2
IbmMqMessageHelper.CopyRfh2UserProperties(replyMsg, response, _headerFilter, pending.Request);
pending.Reply.TrySetResult(response);
}
catch (Exception ex)
{
pending.Reply.TrySetException(ex);
}
}
}
catch (MQException ex) when (IbmMqConnectionLoss.IsConnectionLost(ex.ReasonCode))
{
// The waiting requests fail at once; the next send reconnects and starts a new reply loop.
if (!ct.IsCancellationRequested)
MarkConnectionLost(ex);
break;
}
catch (OperationCanceledException) when (ct.IsCancellationRequested) { break; }
catch (Exception ex)
{
Logger?.LogError(ex, "Error in IBM MQ RPC reply receive loop");
try { await Task.Delay(500, ct).ConfigureAwait(false); }
catch (OperationCanceledException) { break; }
}
}
}
// ── Message put ──
private void PutMessage(MQMessage msg, MQPutMessageOptions pmo)
{
if (_options.DestinationType == IbmMqDestinationType.Topic)
_outputTopic!.Put(msg, pmo);
else
_outputQueue!.Put(msg, pmo);
_endpoint.RecordBytesOut(msg.MessageLength);
}
// The puts of one transacted block or one list body, committed together; their bytes count once committed.
private IbmMqSendBatch NewSendBatch(MQQueueManager qm) =>
new(_outputQueue, _outputTopic, _options.DestinationType, _endpoint.Destination, qm, _commitLock, Logger,
_endpoint.RecordBytesOut, MarkConnectionLost);
// ── Helpers ──
}
Path: redb-route/redb.Route.IbmMq/IbmMqSendBatch.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/IbmMqSendBatch.cs
----
using System.Collections.Concurrent;
using IBM.WMQ;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
namespace redb.Route.IbmMq;
///
/// The deferred puts of one producer in one transacted block. On commit every message is put under syncpoint and the
/// unit of work is committed once (MQCMIT), so the block's puts arrive together or not at all; a failed put backs the
/// unit of work out (MQBACK). On rollback nothing has been put. A lost connection during the puts or the commit is
/// reported to the producer, so its next send reconnects; one during MQCMIT leaves the outcome in doubt and says so.
///
internal sealed class IbmMqSendBatch : ITransactedAction
{
private readonly ConcurrentQueue _messages = new();
private readonly MQQueue? _queue;
private readonly MQTopic? _topic;
private readonly IbmMqDestinationType _destinationType;
private readonly string _destination;
private readonly MQQueueManager _queueManager;
private readonly SemaphoreSlim _commitLock;
private readonly ILogger? _logger;
private readonly Action _recordBytesOut;
private readonly Action _onConnectionLost;
///
/// The producer's lock: its connection is shared by every exchange, and a unit of work belongs to the connection, so
/// one batch at a time puts and commits on it. Another batch's MQCMIT would otherwise commit half of this one.
///
/// The endpoint's BytesOut, given the batch's message bytes once MQCMIT succeeded.
/// Tells the producer its connection is lost, when a put or the commit says so.
public IbmMqSendBatch(
MQQueue? queue,
MQTopic? topic,
IbmMqDestinationType destinationType,
string destination,
MQQueueManager queueManager,
SemaphoreSlim commitLock,
ILogger? logger,
Action recordBytesOut,
Action onConnectionLost)
{
_queue = queue;
_topic = topic;
_destinationType = destinationType;
_destination = destination;
_queueManager = queueManager;
_commitLock = commitLock;
_logger = logger;
_recordBytesOut = recordBytesOut;
_onConnectionLost = onConnectionLost;
}
/// Adds a message to the batch, after the ones the block deferred before it.
public void Add(MQMessage message) => _messages.Enqueue(message);
///
public async Task Commit(CancellationToken ct = default)
{
await _commitLock.WaitAsync(ct).ConfigureAwait(false);
try
{
var pmo = new MQPutMessageOptions
{
Options = MQC.MQPMO_SYNCPOINT | MQC.MQPMO_FAIL_IF_QUIESCING
};
var committing = false;
try
{
foreach (var message in _messages)
{
if (_destinationType == IbmMqDestinationType.Topic)
_topic!.Put(message, pmo);
else
_queue!.Put(message, pmo);
}
committing = true;
_queueManager.Commit();
}
catch (MQException ex) when (IbmMqConnectionLoss.IsConnectionLost(ex.ReasonCode))
{
// The queue manager backs out an uncommitted unit of work when its connection ends, so there is nothing
// to back out here. A loss during MQCMIT itself leaves the outcome unknown: the commit may have been
// done before the connection broke.
if (committing)
_logger?.LogWarning(ex,
"IBM MQ connection lost during the commit of a transactional batch: destination={Destination}, " +
"messages={Count}. The outcome is in doubt: the messages may or may not have been committed.",
_destination, _messages.Count);
_onConnectionLost(ex);
throw;
}
catch (MQException)
{
// None of the batch may stand without the rest: back the unit of work out, then report the failure.
BackOut();
throw;
}
long sent = 0;
foreach (var message in _messages)
sent += message.MessageLength;
_recordBytesOut(sent);
_logger?.LogDebug("IBM MQ transactional batch committed: destination={Destination}, messages={Count}",
_destination, _messages.Count);
}
finally
{
_commitLock.Release();
}
}
///
public Task Rollback(CancellationToken ct = default)
{
_logger?.LogDebug("IBM MQ transactional batch rolled back: destination={Destination}, messages={Count}",
_destination, _messages.Count);
return Task.CompletedTask;
}
private void BackOut()
{
try
{
_queueManager.Backout();
}
catch (MQException backoutEx)
{
_logger?.LogWarning(backoutEx,
"IBM MQ backout after a failed batch put failed: destination={Destination}. The unit of work ends with the " +
"connection.", _destination);
}
}
}
Path: redb-route/redb.Route.IbmMq/IbmMqXmsAckAction.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/IbmMqXmsAckAction.cs
----
using IBM.XMS;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
namespace redb.Route.IbmMq;
///
/// Deferred acknowledgement for the XMS (event-driven) receive path: commit/rollback of a
/// transacted XMS (JMS SESSION_TRANSACTED), the XMS analogue of
/// (which wraps MQCMIT/MQBACK on an IBM.WMQ connection).
///
/// Session affinity. A transacted JMS session commits/rolls back on the same session
/// that delivered the message. Because the XMS engine runs the whole route synchronously inside the
/// listener callback, both the route's transaction unit-of-work and the engine's own settle call
/// execute on that session's dispatch thread — so this action always commits the session that
/// delivered the message. (JMS permits commit/rollback inside onMessage; only
/// creating/closing the session there is forbidden.)
///
///
/// Idempotent. Whichever settles first wins and the other is a no-op: a route-level
/// .Transaction() block (via TransactedProcessor) settles the action as part of the
/// route unit-of-work; if the route has no transaction block, the engine settles it directly after
/// the route returns. This makes transacted listener mode correct with or without a route
/// transaction, and prevents a double commit/rollback when both paths are present.
///
///
internal sealed class IbmMqXmsAckAction : ITransactedAction
{
private readonly ISession _session;
private readonly ILogger? _logger;
private int _settled; // 0 = pending, 1 = committed/rolled back
public IbmMqXmsAckAction(ISession session, ILogger? logger)
{
_session = session;
_logger = logger;
}
/// True once the session has been committed or rolled back through this action.
public bool Settled => Volatile.Read(ref _settled) != 0;
///
public Task Commit(CancellationToken ct = default)
{
if (Interlocked.CompareExchange(ref _settled, 1, 0) != 0)
return Task.CompletedTask; // already settled — no-op
_session.Commit();
_logger?.LogDebug("IBM MQ XMS ack committed (session.Commit)");
return Task.CompletedTask;
}
///
public Task Rollback(CancellationToken ct = default)
{
if (Interlocked.CompareExchange(ref _settled, 1, 0) != 0)
return Task.CompletedTask; // already settled — no-op
_session.Rollback();
_logger?.LogDebug("IBM MQ XMS nack (session.Rollback)");
return Task.CompletedTask;
}
}
Path: redb-route/redb.Route.IbmMq/IbmMqXmsConsumerEngine.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/IbmMqXmsConsumerEngine.cs
----
using System.Collections.Concurrent;
using System.Diagnostics;
using IBM.XMS;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Telemetry;
using redb.Route.Transactions;
using RouteMessage = redb.Route.Core.Message;
using XmsMessage = IBM.XMS.IMessage;
namespace redb.Route.IbmMq;
///
/// Event-driven IBM MQ receive engine built on XMS .NET (IBM.XMS).
///
/// Activated by = .
/// Unlike the default poll loop (, synchronous MQGET-WAIT on IBM.WMQ, which
/// carries the managed client's internal ~500 ms tick), the broker pushes messages into an
/// XMS MessageListener the instant they arrive — dropping delivery latency to <50 ms.
///
///
/// Threading / back-pressure (plan §5a). XMS invokes the listener on a client-managed dispatch
/// thread, one message at a time per session. We run the whole route synchronously inside the
/// callback: a session will not deliver its next message until the current one returns, so each
/// session carries a single in-flight exchange. ConcurrentConsumers=N on a queue creates N
/// sessions on the shared connection (N competing consumers, N in-flight, queue-manager load-balanced);
/// a topic clamps to one subscriber (parallel subscriptions would duplicate delivery). XMS forbids
/// creating/closing a session inside the callback, so all session objects are built up-front in
/// and torn down in .
///
///
/// Acknowledgement. When is false the session uses
/// AutoAcknowledge: the message is settled (destructively consumed) when the callback returns,
/// and processing errors are logged but swallowed — a failed route does not redeliver, mirroring the
/// non-transacted poll path. When Transacted is true the session is SESSION_TRANSACTED
/// and an is registered on the exchange: a route-level
/// .Transaction() block commits/rolls back the session as part of its unit-of-work exactly like
/// the poll path's ; if the route has no transaction block, the engine
/// settles the session itself (commit on success, rollback on error) after the route returns. The ack
/// action is idempotent, so the two paths never double-settle.
///
///
/// Parity with the poll path. The listener path also honours request-reply (a message whose
/// JMSReplyTo is set gets an InOut exchange and the Out body is sent back with the
/// request's message id as correlation id), the backout threshold (a message whose delivery count has
/// reached BackoutThreshold is copied to BackoutQueue), and W3C trace-context propagation
/// (traceparent/tracestate read from the message properties to continue the distributed
/// trace). RPC reply and the backout copy are issued on the delivering session, so under
/// transacted they commit atomically with consuming the request.
///
///
internal sealed class IbmMqXmsConsumerEngine
{
private readonly IbmMqEndpoint _endpoint;
private readonly IProcessor _processor;
private readonly IbmMqEndpointOptions _options;
private readonly ILogger? _logger;
private readonly Action _onProcessed;
private readonly InflightDrainGuard _drain = new();
private readonly bool _transacted;
// The open connection with its sessions; replaced as a whole by a reconnect.
private XmsConnection? _open;
private readonly object _openLock = new();
private int _workerCount;
private volatile bool _stopping;
// Connection supervision: a lost connection (the exception listener) is closed and opened again in the background on
// the supervisor's schedule, while the endpoint's health says so.
private ConnectionSupervisor? _supervisor;
private CancellationTokenSource? _reconnectCts;
private Task? _reconnectTask;
/// One XMS connection and the workers whose sessions it carries.
private sealed record XmsConnection(IConnection Connection, List Workers);
///
/// One competing consumer: an XMS session (single-threaded — delivers one message at a time) plus its
/// consumer. ConcurrentConsumers=N on a queue creates N of these on the shared connection, so N
/// listeners run concurrently and the queue manager load-balances across them. The transacted syncpoint
/// is per-session, so commit/rollback binds to the that delivered the message.
///
private sealed class XmsWorker
{
public required ISession Session { get; init; }
public required IMessageConsumer Consumer { get; init; }
}
public IbmMqXmsConsumerEngine(
IbmMqEndpoint endpoint,
IProcessor processor,
IbmMqEndpointOptions options,
ILogger? logger,
Action onProcessed)
{
_endpoint = endpoint;
_processor = processor;
_options = options;
_logger = logger;
_onProcessed = onProcessed;
_transacted = options.Transacted == true;
_headerFilter = endpoint.HeaderFilterStrategy;
}
private readonly IHeaderFilterStrategy _headerFilter;
public async Task StartAsync(CancellationToken ct)
{
_drain.Start(ct);
var isTopic = _options.DestinationType == IbmMqDestinationType.Topic;
_workerCount = Math.Max(1, _options.ResolvedConcurrentConsumers);
// Topics can't be load-balanced across competing subscribers: each non-durable subscription
// gets its OWN copy of every message, so N subscribers would DUPLICATE delivery, not share it.
// Clamp to one subscriber and tell the operator why — same rule as the poll path.
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;
}
_supervisor = _endpoint.Supervise($"wmq:{_endpoint.Destination} listener", _logger);
_reconnectCts = new CancellationTokenSource();
// XMS connection/session setup is synchronous and blocking (socket handshake). Push it to a
// thread-pool worker so async callers don't block on it, mirroring IbmMqComponent's queue-manager
// creation.
var open = await Task.Run(OpenConnection, ct).ConfigureAwait(false);
lock (_openLock) _open = open;
_logger?.LogInformation(
"IBM MQ consumer started (XMS listener): destination={Destination}, type={Type}, concurrent={Concurrent}",
_endpoint.Destination, _options.DestinationType, open.Workers.Count);
}
///
/// Opens a connection with one session and consumer per worker and starts delivery; a failure part-way closes what
/// came up and rethrows, so no half-open connection is left behind.
///
private XmsConnection OpenConnection()
{
var connection = _endpoint.XmsConnectionSource();
var open = new XmsConnection(connection, new List());
try
{
connection.ExceptionListener = ex => OnConnectionException(connection, ex);
var isTopic = _options.DestinationType == IbmMqDestinationType.Topic;
for (var i = 0; i < _workerCount; i++)
{
// Transacted → SESSION_TRANSACTED (commit/rollback via IbmMqXmsAckAction); otherwise
// AutoAcknowledge settles the message destructively when the listener returns. Each worker
// owns its own session so the transacted syncpoint stays per-consumer.
var session = _transacted
? connection.CreateSession(transacted: true, AcknowledgeMode.SessionTransacted)
: connection.CreateSession(transacted: false, AcknowledgeMode.AutoAcknowledge);
IMessageConsumer consumer;
try
{
IDestination destination = isTopic
? session.CreateTopic(_endpoint.Destination)
: session.CreateQueue(_endpoint.Destination);
consumer = string.IsNullOrEmpty(_options.Selector)
? session.CreateConsumer(destination)
: session.CreateConsumer(destination, _options.Selector);
}
catch
{
try { session.Close(); }
catch (Exception ex) { _logger?.LogDebug(ex, "IBM MQ XMS: error closing session"); }
throw;
}
// Capture THIS worker's session so commit/rollback binds to the session that delivered.
consumer.MessageListener = m => OnMessage(m, session);
open.Workers.Add(new XmsWorker { Session = session, Consumer = consumer });
}
// Nothing is delivered until the connection is started.
connection.Start();
return open;
}
catch
{
CloseConnection(open, stop: false);
throw;
}
}
/// Closes the consumers, the sessions and the connection; errors are logged at debug level only.
private void CloseConnection(XmsConnection open, bool stop)
{
if (stop)
{
try { open.Connection.Stop(); }
catch (Exception ex) { _logger?.LogDebug(ex, "IBM MQ XMS: error stopping connection"); }
}
foreach (var w in open.Workers)
{
try { w.Consumer.Close(); }
catch (Exception ex) { _logger?.LogDebug(ex, "IBM MQ XMS: error closing consumer"); }
try { w.Session.Close(); }
catch (Exception ex) { _logger?.LogDebug(ex, "IBM MQ XMS: error closing session"); }
}
try { open.Connection.Close(); }
catch (Exception ex) { _logger?.LogDebug(ex, "IBM MQ XMS: error closing connection"); }
}
public async Task StopAsync(CancellationToken ct)
{
_stopping = true;
// A reconnect in progress ends first, so it does not open a connection behind the stop.
_reconnectCts?.Cancel();
if (_reconnectTask is { } reconnecting)
{
try { await reconnecting.ConfigureAwait(false); }
catch (Exception ex) { _logger?.LogDebug(ex, "IBM MQ XMS: reconnect ended with an error during stop"); }
}
XmsConnection? open;
lock (_openLock)
{
open = _open;
_open = null;
}
// Stop delivery first so no new callbacks fire, then drain the in-flight one (the listener may
// still be running the route synchronously), then close the XMS objects.
if (open is not null)
{
try { open.Connection.Stop(); }
catch (Exception ex) { _logger?.LogDebug(ex, "IBM MQ XMS: error stopping connection"); }
}
await _drain.DrainAsync(ct, _logger, $"xms:{_endpoint.Destination}").ConfigureAwait(false);
if (open is not null)
CloseConnection(open, stop: false);
_drain.Dispose();
_reconnectCts?.Dispose();
_reconnectCts = null;
_reconnectTask = null;
if (_supervisor is not null)
{
_endpoint.Unsupervise(_supervisor);
_supervisor = null;
}
_logger?.LogInformation("IBM MQ consumer stopped (XMS listener): destination={Destination}", _endpoint.Destination);
}
///
/// The XMS connection failed: a queue manager restart or a network cut. A failure of the current connection starts
/// one background reconnect (a late report from a connection already replaced is ignored); while the consumer stops,
/// nothing is done.
///
private void OnConnectionException(IConnection connection, Exception ex)
{
if (_stopping) return;
var supervisor = _supervisor;
if (supervisor is null) return;
XmsConnection? lost;
lock (_openLock)
{
if (_open is null || !ReferenceEquals(_open.Connection, connection))
return;
lost = _open;
_open = null;
}
supervisor.Lost(ex);
var stop = _reconnectCts?.Token ?? CancellationToken.None;
_reconnectTask = Task.Run(() => ReconnectAsync(lost, supervisor, stop), CancellationToken.None);
}
///
/// Closes the lost connection (messages in flight on it are not settled: transacted ones return to the queue) and
/// opens a new one on the supervisor's schedule, one bounded attempt at a time, until it succeeds or the consumer stops.
///
private async Task ReconnectAsync(XmsConnection lost, ConnectionSupervisor supervisor, CancellationToken stop)
{
CloseConnection(lost, stop: false);
await supervisor.ReconnectAsync(async c =>
{
var open = await supervisor.AttemptAsync(
a => Task.Run(OpenConnection, a),
late => CloseConnection(late, stop: true), c).ConfigureAwait(false);
bool keep;
lock (_openLock)
{
keep = !_stopping;
if (keep) _open = open;
}
if (!keep)
{
CloseConnection(open, stop: true);
throw new OperationCanceledException(stop);
}
}, stop).ConfigureAwait(false);
}
// ── Listener callback (XMS dispatch thread) ──
private void OnMessage(XmsMessage message, ISession session)
{
if (_stopping || _drain.ProcessingToken.IsCancellationRequested)
return;
_drain.Increment();
var ct = _drain.ProcessingToken;
// A poison message (backed out backoutThreshold times) goes to the backout queue instead of the route, in the
// session's unit of work, 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 (_transacted && _options.BackoutThreshold > 0)
{
var diverted = false;
try
{
diverted = MoveToBackoutQueueIfExceeded(session, message);
if (diverted)
session.Commit();
}
catch (Exception ex)
{
// The move or its commit failed: roll back, the message returns to its queue.
diverted = true;
_endpoint.RecordError(ex);
_logger?.LogError(ex, "IBM MQ XMS: moving a poison message to the backout queue failed; rolling back");
try { session.Rollback(); } catch (Exception rollbackEx) { _logger?.LogWarning(rollbackEx, "IBM MQ XMS: rollback failed"); }
}
if (diverted)
{
_drain.Decrement();
return;
}
}
// Continue the W3C distributed trace carried in the message properties.
using var span = StartConsumerSpan(message);
var exchange = CreateExchange(message);
// Transacted: commit/rollback is bound to THIS delivering session and stays with this engine. The route
// transaction owns the database and the outgoing sends; the session is settled below, once the whole
// unit of work ended well.
IbmMqXmsAckAction? ack = null;
if (_transacted)
ack = new IbmMqXmsAckAction(session, _logger);
try
{
// Run the route to completion on the callback thread (plan §5a): this blocks the session's
// delivery of the next message, giving one-in-flight back-pressure per session. Bridging the
// async pipeline onto the synchronous XMS thread is intentional — there is no ambient
// SynchronizationContext in this server-side library, so GetResult() will not deadlock.
_processor.Process(exchange, ct).GetAwaiter().GetResult();
exchange.ThrowIfUnhandledFailure();
// Request-reply: send the Out body back to JMSReplyTo. On the delivering session, so under
// transacted it commits atomically with consuming the request.
if (!_options.DisableReplyTo)
SendReply(session, message, exchange);
// Commit the delivering session (no-op if a route .Transaction() block already committed it).
ack?.Commit(ct).GetAwaiter().GetResult();
_onProcessed();
}
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 XMS message processing error: destination={Destination}", _endpoint.Destination);
// Transacted: roll back so the message is redelivered / backout-counted (no-op if a route
// .Transaction() block already rolled back). Non-transacted (ack == null): swallow — auto-ack
// has already settled the message destructively, matching the non-transacted poll path.
if (ack != null)
{
try { ack.Rollback(ct).GetAwaiter().GetResult(); }
catch (Exception rollbackEx) { _logger?.LogWarning(rollbackEx, "IBM MQ XMS: session rollback failed"); }
}
}
finally
{
try { exchange.DisposeAsync().AsTask().GetAwaiter().GetResult(); }
catch (Exception disposeEx) { _logger?.LogDebug(disposeEx, "IBM MQ XMS: exchange dispose faulted"); }
_drain.Decrement();
}
}
// ── XMS message → redb exchange ──
private Exchange CreateExchange(XmsMessage message)
{
object body;
string? contentType;
switch (message)
{
case ITextMessage text:
body = text.Text ?? string.Empty;
contentType = "text/plain";
break;
case IBytesMessage bytes:
var length = (int)bytes.BodyLength;
var buffer = new byte[length];
if (length > 0) bytes.ReadBytes(buffer);
body = buffer;
contentType = "application/octet-stream";
break;
default:
body = string.Empty;
contentType = null;
break;
}
var routeMsg = new RouteMessage(body) { ContentType = contentType };
// Carry the same redbIbmMq.* metadata and user headers as the poll path.
var exchange = Exchange.Create(routeMsg, _endpoint.ScopeFactory);
IbmMqXmsHeaderMapper.CopyToHeaders(message, routeMsg, _endpoint.Destination, _options, _headerFilter, exchange);
// A request carrying a reply destination is request-reply (InOut); otherwise one-way (InOnly).
exchange.Pattern = !_options.DisableReplyTo && HasReplyTo(message) ? ExchangePattern.InOut : ExchangePattern.InOnly;
return exchange;
}
// ── W3C trace context propagation ──
private TransportSpan StartConsumerSpan(XmsMessage message)
{
var span = RouteTelemetryExtensions.StartConsumerSpan(
(_endpoint.Component as ComponentBase)?.Context,
$"{_endpoint.Destination} receive", ActivityKind.Consumer,
"messaging.system", "wmq", _endpoint.Uri.NormalizedKey,
message, TryGetStringProperty,
destination: _endpoint.Destination, operation: "receive");
if (span.Activity is { IsAllDataRequested: true } activity)
activity.SetTag("messaging.ibmmq.queue_manager", _options.QueueManager);
return span;
}
// ── RPC reply ──
private void SendReply(ISession session, XmsMessage request, IExchange exchange)
{
IDestination? replyTo;
try { replyTo = request.JMSReplyTo; } catch { return; }
if (replyTo is null) return;
try
{
var responseBody = exchange.HasOut ? exchange.Out!.Body : exchange.In.Body;
XmsMessage reply;
if (responseBody is byte[] bytes)
{
var bm = session.CreateBytesMessage();
bm.WriteBytes(bytes);
reply = bm;
}
else
{
reply = session.CreateTextMessage(responseBody?.ToString() ?? string.Empty);
}
// Standard IBM MQ correlation: reply MQMD CorrelId = request MQMD MsgId (as bytes). Setting it
// via JMSCorrelationIDAsBytes lands it in the MQMD field the (non-JMS) MQ requester matches on;
// a plain string JMSCorrelationID would go into an RFH2 folder the requester never reads.
var msgIdBytes = JmsMessageIdToBytes(request.JMSMessageID);
if (msgIdBytes is not null)
try { reply.JMSCorrelationIDAsBytes = msgIdBytes; } catch { /* best-effort */ }
else
try { reply.JMSCorrelationID = request.JMSMessageID; } catch { /* best-effort */ }
// Send to a FRESH queue destination built from the reply queue's name rather than the
// JMSReplyTo object parsed off the received message: XMS treats the parsed destination as a
// temporary destination owned by the requester's connection and refuses to send to it from
// ours (IllegalStateException). A plain queue destination by name is an ordinary send.
var replyDest = session.CreateQueue(replyTo.Name);
// targetClient=Mq promises raw MQMD+body on EVERY leg: without this, XMS attaches an
// MQRFH2 (jms/mcd folders) to the reply and the legacy requester's body parser breaks
// - the exact thing the option exists to prevent.
if (_options.TargetClient == IbmMqTargetClient.Mq)
replyDest.SetIntProperty(XMSC.WMQ_TARGET_CLIENT, XMSC.WMQ_TARGET_DEST_MQ);
var producer = session.CreateProducer(replyDest);
// Reply non-persistent: RPC reply queues are typically temporary dynamic queues, which reject
// persistent messages (MQRC_PERSISTENT_NOT_ALLOWED). XMS defaults a producer to Persistent
// (the JMS default), unlike the poll path which inherits the queue's own default persistence.
producer.DeliveryMode = DeliveryMode.NonPersistent;
try { producer.Send(reply); }
finally { try { producer.Close(); } catch { /* ignore */ } }
_logger?.LogDebug("IBM MQ XMS RPC reply sent to {ReplyTo}", replyTo.Name);
}
catch (Exception ex)
{
// A failed reply must not block the consumer slot — the client detects it via its RPC timeout.
_logger?.LogWarning(ex, "IBM MQ XMS: failed to send RPC reply — request will still be settled");
}
}
// ── Backout queue ──
///
/// Sends a message delivered more than backoutThreshold times to the backout queue on the delivering
/// (transacted) session, so the caller's commit takes it off its queue and puts it on the backout queue together.
/// true when it was sent; false when it is not a poison message, or no backout queue is configured.
///
private bool MoveToBackoutQueueIfExceeded(ISession session, XmsMessage message)
{
int deliveryCount;
try { deliveryCount = message.GetIntProperty(XMSC.JMSX_DELIVERY_COUNT); }
catch { return false; } // property not available — nothing to decide on
// JMSXDeliveryCount is 1 on first delivery; backout count is deliveries minus the current one.
var backoutCount = deliveryCount - 1;
if (backoutCount < _options.BackoutThreshold) return false;
var boqName = _options.BackoutQueue;
if (string.IsNullOrWhiteSpace(boqName))
{
_logger?.LogError(
"IBM MQ XMS: message on {Destination} backed out {BackoutCount} times, but no backoutQueue is configured: " +
"it goes to the route again", _endpoint.Destination, backoutCount);
return false;
}
var boq = session.CreateQueue(boqName);
var producer = session.CreateProducer(boq);
try { producer.Send(message); }
finally { try { producer.Close(); } catch { /* ignore */ } }
_logger?.LogWarning(
"IBM MQ XMS: poison message moved to backout queue {BackoutQueue} (destination={Destination}, backoutCount={BackoutCount})",
boqName, _endpoint.Destination, backoutCount);
return true;
}
private static bool HasReplyTo(XmsMessage message)
{
try { return message.JMSReplyTo is not null; }
catch { return false; }
}
/// Parses a JMS message id ("ID:" + hex) into the raw MQMD message-id bytes, or null.
private static byte[]? JmsMessageIdToBytes(string? jmsMessageId)
{
if (string.IsNullOrEmpty(jmsMessageId)) return null;
var hex = jmsMessageId.StartsWith("ID:", StringComparison.Ordinal) ? jmsMessageId[3..] : jmsMessageId;
if (hex.Length == 0 || hex.Length % 2 != 0) return null;
try { return Convert.FromHexString(hex); }
catch { return null; }
}
private static string? TryGetStringProperty(XmsMessage message, string name)
{
try { return message.PropertyExists(name) ? message.GetStringProperty(name) : null; }
catch { return null; }
}
}
Path: redb-route/redb.Route.IbmMq/IbmMqXmsHeaderMapper.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/IbmMqXmsHeaderMapper.cs
----
using IBM.XMS;
using redb.Route.Abstractions;
using RouteMessage = redb.Route.Core.Message;
using XmsMessage = IBM.XMS.IMessage;
namespace redb.Route.IbmMq;
///
/// Maps an XMS message's JMS/MQMD metadata and user headers onto a redb route message, so the
/// event-driven (XMS) receive path carries the same redbIbmMq.* and application headers as the
/// poll path ( +
/// ).
///
/// User headers are read from the single JSON-encoded property the
/// redb producer writes — the exact counterpart of the poll consumer's RFH2 read — so a redb→redb hop
/// round-trips application headers identically on either receive mode.
///
///
internal static class IbmMqXmsHeaderMapper
{
///
/// The metadata and the user headers lets in; is the
/// one they come into (for a request-reply's reply, the request's).
///
public static void CopyToHeaders(XmsMessage msg, RouteMessage routeMsg, string destination, IbmMqEndpointOptions options,
IHeaderFilterStrategy headerFilter, IExchange exchange)
{
// MQMD-equivalent metadata — gated by MqmdReadEnabled exactly like the poll path.
if (options.MqmdReadEnabled)
{
routeMsg.Headers[IbmMqHeaders.Destination] = destination;
routeMsg.Headers[IbmMqHeaders.QueueManager] = options.QueueManager;
var msgId = MessageIdToHex(TryGet(() => msg.JMSMessageID));
if (!string.IsNullOrEmpty(msgId))
routeMsg.Headers[IbmMqHeaders.MsgId] = msgId;
var correlBytes = TryGet(() => msg.JMSCorrelationIDAsBytes);
if (correlBytes is { Length: > 0 })
routeMsg.Headers[IbmMqHeaders.CorrelId] = IbmMqMessageHelper.BytesToHex(correlBytes);
var priority = TryGetStruct(() => msg.JMSPriority);
if (priority.HasValue)
routeMsg.Headers[IbmMqHeaders.Priority] = priority.Value;
var replyToName = TryGet(() => msg.JMSReplyTo?.Name);
if (!string.IsNullOrEmpty(replyToName))
routeMsg.Headers[IbmMqHeaders.ReplyToQueue] = BareQueueName(replyToName);
var deliveryCount = TryGetStruct(() => msg.GetIntProperty(XMSC.JMSX_DELIVERY_COUNT));
if (deliveryCount is > 0)
routeMsg.Headers[IbmMqHeaders.BackoutCount] = deliveryCount.Value - 1;
}
CopyUserHeaders(msg, routeMsg, headerFilter, exchange);
}
/// Reads the redb producer's JSON header catalogue and applies each user header the strategy lets in.
private static void CopyUserHeaders(XmsMessage msg, RouteMessage routeMsg, IHeaderFilterStrategy headerFilter, IExchange exchange)
{
var json = TryGet(() => msg.GetStringProperty(IbmMqHeaders.HeaderCatalogue));
if (string.IsNullOrEmpty(json)) return;
try
{
var dict = System.Text.Json.JsonSerializer.Deserialize>(json);
if (dict is null) return;
foreach (var (key, value) in dict)
{
if (headerFilter.FilterIncoming(key, value, exchange)) continue;
routeMsg.Headers[key] = value;
}
}
catch { /* malformed JSON — skip, matching the poll path */ }
}
/// JMS message id ("ID:" + hex) → the raw hex the poll path stores for MQMD MsgId.
private static string? MessageIdToHex(string? jmsMessageId)
{
if (string.IsNullOrEmpty(jmsMessageId)) return null;
return jmsMessageId.StartsWith("ID:", StringComparison.Ordinal) ? jmsMessageId[3..] : jmsMessageId;
}
/// Bare MQ queue name from an XMS destination name (queue://qmgr/NAME or plain).
private static string BareQueueName(string name)
{
var slash = name.LastIndexOf('/');
return (slash >= 0 ? name[(slash + 1)..] : name).Trim();
}
private static T? TryGet(Func f) where T : class
{
try { return f(); } catch { return null; }
}
private static T? TryGetStruct(Func f) where T : struct
{
try { return f(); } catch { return null; }
}
}
Path: redb-route/redb.Route.IbmMq/IbmMqXmsReplyReceiver.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/IbmMqXmsReplyReceiver.cs
----
using IBM.XMS;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using RouteMessage = redb.Route.Core.Message;
using XmsMessage = IBM.XMS.IMessage;
namespace redb.Route.IbmMq;
///
/// Event-driven RPC reply receiver for — the client leg of request-reply.
///
/// Replaces the producer's poll-MQGET reply loop with an XMS MessageListener on the reply queue,
/// so waiting for the response also drops from the managed client's ~500 ms poll tick to single-digit
/// milliseconds. Opt-in via receiveMode=listener. The request itself is still sent over IBM.WMQ;
/// only reply reception moves to XMS, so send behaviour is unchanged.
///
///
/// For a dynamic reply queue the receiver creates an XMS temporary queue — owned by this XMS
/// connection, which also consumes it, so there is no cross-connection ownership issue — and exposes its
/// bare MQ queue name via for the producer to stamp on the request's
/// ReplyToQueueName. The (non-JMS) MQ responder then puts the reply there by name.
///
///
/// A lost XMS connection is reported to the producer through its exception listener: the requests waiting for a reply
/// fail at once, and the producer's next send builds a new receiver (and a new temporary queue) on a new connection.
///
///
internal sealed class IbmMqXmsReplyReceiver
{
private readonly IbmMqEndpointOptions _options;
private readonly IbmMqConnectionFactory _connectionFactory;
private readonly ILogger? _logger;
private readonly IHeaderFilterStrategy _headerFilter;
// (correlationKey, build): build makes the response for the request exchange the key belongs to, whose strategy
// lets the reply's user headers in against that exchange.
private readonly Action> _onReply;
private readonly Action _onConnectionLost;
private volatile bool _stopping;
private IConnection? _connection;
private ISession? _session;
private IMessageConsumer? _consumer;
private IDestination? _tempReplyQueue;
/// Bare MQ queue name to set on outgoing requests' ReplyToQueueName.
public string ReplyQueueName { get; private set; } = string.Empty;
public IbmMqXmsReplyReceiver(IbmMqEndpointOptions options, IbmMqConnectionFactory connection, ILogger? logger,
IHeaderFilterStrategy headerFilter, Action> onReply,
Action onConnectionLost)
{
_options = options;
_connectionFactory = connection;
_logger = logger;
_headerFilter = headerFilter;
_onReply = onReply;
_onConnectionLost = onConnectionLost;
}
public async Task StartAsync(CancellationToken ct)
{
// Connection/session setup is synchronous and blocking — push it off the caller's thread.
await Task.Run(() =>
{
_connection = _connectionFactory.CreateXmsConnection();
_connection.ExceptionListener = OnConnectionException;
_session = _connection.CreateSession(transacted: false, AcknowledgeMode.AutoAcknowledge);
IDestination replyDest;
if (string.IsNullOrEmpty(_options.ReplyToQueue))
{
_tempReplyQueue = _session.CreateTemporaryQueue();
replyDest = _tempReplyQueue;
ReplyQueueName = ExtractQueueName(_tempReplyQueue);
}
else
{
replyDest = _session.CreateQueue(_options.ReplyToQueue);
ReplyQueueName = _options.ReplyToQueue;
}
_consumer = _session.CreateConsumer(replyDest);
_consumer.MessageListener = OnReply;
_connection.Start();
}, ct).ConfigureAwait(false);
_logger?.LogDebug("IBM MQ XMS RPC reply receiver started: replyQueue={ReplyQueue}", ReplyQueueName);
}
public Task StopAsync(CancellationToken ct)
{
_stopping = true;
try { _connection?.Stop(); } catch (Exception ex) { _logger?.LogDebug(ex, "IBM MQ XMS reply: error stopping connection"); }
try { _consumer?.Close(); } catch (Exception ex) { _logger?.LogDebug(ex, "IBM MQ XMS reply: error closing consumer"); }
try { _tempReplyQueue?.Dispose(); } catch (Exception ex) { _logger?.LogDebug(ex, "IBM MQ XMS reply: error deleting temp queue"); }
try { _session?.Close(); } catch (Exception ex) { _logger?.LogDebug(ex, "IBM MQ XMS reply: error closing session"); }
try { _connection?.Close(); } catch (Exception ex) { _logger?.LogDebug(ex, "IBM MQ XMS reply: error closing connection"); }
_consumer = null;
_tempReplyQueue = null;
_session = null;
_connection = null;
return Task.CompletedTask;
}
/// The XMS connection failed (a queue manager restart, a network cut): the producer reconnects.
private void OnConnectionException(Exception ex)
{
if (_stopping) return;
try { _onConnectionLost(ex); }
catch (Exception callbackEx) { _logger?.LogDebug(callbackEx, "IBM MQ XMS reply: error reporting a lost connection"); }
}
private void OnReply(XmsMessage message)
{
try
{
// The responder sets the reply's MQMD CorrelId to the request's MsgId; match on it, exactly
// like the poll loop keys `_pendingResponses` by hex(reply.CorrelationId).
byte[]? corr = null;
try { corr = message.JMSCorrelationIDAsBytes; } catch { /* no correlation */ }
var correlKey = IbmMqMessageHelper.BytesToHex(corr ?? Array.Empty());
_onReply(correlKey, request => BuildResponse(message, request));
}
catch (Exception ex)
{
_logger?.LogWarning(ex, "IBM MQ XMS: failed to handle RPC reply");
}
}
private RouteMessage BuildResponse(XmsMessage message, IExchange request)
{
object body;
string? contentType;
switch (message)
{
case ITextMessage text:
body = text.Text ?? string.Empty;
contentType = "text/plain";
break;
case IBytesMessage bytes:
var length = (int)bytes.BodyLength;
var buffer = new byte[length];
if (length > 0) bytes.ReadBytes(buffer);
body = buffer;
contentType = "application/octet-stream";
break;
default:
body = string.Empty;
contentType = null;
break;
}
var response = new RouteMessage(body) { ContentType = contentType };
// Same redbIbmMq.* metadata and user headers the poll reply path stamps on the response.
IbmMqXmsHeaderMapper.CopyToHeaders(message, response, ReplyQueueName, _options, _headerFilter, request);
return response;
}
/// Resolves the bare MQ queue name from an XMS destination (property or queue://qmgr/NAME name).
private static string ExtractQueueName(IDestination dest)
{
try
{
var wmqName = dest.GetStringProperty(XMSC.WMQ_QUEUE_NAME);
if (!string.IsNullOrEmpty(wmqName)) return wmqName.Trim();
}
catch { /* fall through to Name */ }
var name = dest.Name ?? string.Empty;
var slash = name.LastIndexOf('/');
return (slash >= 0 ? name[(slash + 1)..] : name).Trim();
}
}
Path: redb-route/redb.Route.IbmMq/README.md
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/README.md
----
# redb.Route.IbmMq
> Documentation and articles:
IBM MQ (WebSphere MQ) transport for **redb.Route** ESB framework.
Native MQI access via `IBMXMSDotnetClient` (IBM.WMQ + IBM.XMS) — queues, topics, transactions, RPC, message groups, SSL/TLS, and W3C telemetry. Consumers can poll (default) or receive **event-driven** via an XMS `MessageListener` (`receiveMode=listener`, sub-50 ms latency).
[](https://www.nuget.org/packages/redb.Route.IbmMq)
[](../../LICENSE)
## Installation
```bash
dotnet add package redb.Route.IbmMq
```
## Quick Start
```csharp
services.AddRedbRoute(route =>
{
route.Services.AddRedbRouteIbmMq();
route.AddRouteBuilder();
});
```
```csharp
public class MyRoutes : RouteBuilder
{
protected override void Configure()
{
From("wmq:DEV.QUEUE.1?host=mq-host&queueManager=QM1&channel=DEV.APP.SVRCONN")
.Log("Received: ${body}")
.To("wmq:ORDERS.OUT?host=mq-host&queueManager=QM1&channel=DEV.APP.SVRCONN");
}
}
```
## URI Format
```
wmq:{destination}?{options}
```
`{destination}` — queue or topic name (e.g. `DEV.QUEUE.1`, `EVENTS/ORDER`).
## Fluent DSL
```csharp
// Queue (point-to-point)
From(Wmq.Queue("DEV.QUEUE.1")
.Host("mq-host")
.QueueManager("QM1")
.Channel("DEV.APP.SVRCONN")
.User("app")
.Password("passw0rd"))
// Topic (pub/sub)
From(Wmq.Topic("EVENTS/ORDER")
.Host("mq-host")
.QueueManager("QM1")
.ConcurrentConsumers(4))
// Persistent send with JMS interop
.To(Wmq.Queue("ORDERS.OUT")
.Host("mq-host")
.Persistent()
.TargetClient(IbmMqTargetClient.Jms))
// Transacted
From(Wmq.Queue("TXN.QUEUE")
.Host("mq-host")
.Transacted())
// RPC (request/reply)
.To(Wmq.Queue("RPC.SERVICE")
.Host("mq-host")
.ReplyTo()
.Timeout(10))
// SSL/TLS
From(Wmq.Queue("SECURE.QUEUE")
.Host("mq-host")
.SslCipherSpec("TLS_RSA_WITH_AES_256_CBC_SHA256")
.SslKeyRepository("/var/mqm/ssl/key"))
```
## Event-Driven Receive (XMS Listener)
By default the consumer **polls** with a blocking `MQGET`-`WAIT`. The IBM.WMQ managed .NET client carries
an internal ~500 ms tick, so on an idle/low-traffic queue messages arrive ~250–500 ms after they were put.
Setting `receiveMode=listener` switches to an **event-driven** receive built on **XMS .NET** (`IBM.XMS`),
where the broker pushes messages into a `MessageListener` the instant they arrive — dropping delivery
latency to **single-digit milliseconds**. (IBM.WMQ exposes no public async-consume API, so XMS is the only
supported event-driven path on the managed .NET client.)
```csharp
// URI
From("wmq:ORDERS?host=mq-host&queueManager=QM1&channel=DEV.APP.SVRCONN&receiveMode=listener")
// Fluent
From(Wmq.Queue("ORDERS").Host("mq-host").QueueManager("QM1").Listener())
```
It is **opt-in** — `Poll` remains the default, so existing routes are unchanged. The listener path honours
the same consumer semantics as the poll path:
- **Transacted** (`transacted=true`) — a `SESSION_TRANSACTED` session; commit on success, rollback (redeliver)
on error, on the delivering session. A route-level `.Transaction()` block settles it as part of the route
unit-of-work; without one the engine settles it directly.
- **`concurrentConsumers=N`** — N XMS sessions on the shared connection (competing consumers, one in-flight
per session for back-pressure). A topic clamps to a single subscriber.
- **RPC reply**, **backout threshold**, and **W3C trace-context propagation** all work as on the poll path.
- **Headers** — the same `redbIbmMq.*` MQMD metadata and application (user) headers as the poll path.
User headers travel in the JMS `usr` folder, so they interoperate across IBM.WMQ, IBM.XMS and any JMS client.
- **RPC client leg** — a producer doing request-reply (`replyTo=true`) with `receiveMode=listener` also
receives the response event-driven (XMS listener on the reply queue), so the whole round-trip is fast
(~16 ms warm vs the ~250–500 ms poll floor). The request is still sent over IBM.WMQ; only reply
reception moves to XMS. A dynamic reply queue uses an XMS temporary queue.
A dynamic reply queue (`replyTo=true` without `replyToQueue`, on the poll path and the listener path alike) is
created from the model queue `temporaryModel` (IBM MQ's `TEMPMODEL`, default `SYSTEM.DEFAULT.MODEL.QUEUE`), so the
connecting user needs `+dsp +get +put +inq` on that model queue
(`SET AUTHREC PROFILE(SYSTEM.DEFAULT.MODEL.QUEUE) OBJTYPE(QUEUE) PRINCIPAL('app') AUTHADD(DSP,GET,PUT,INQ)`); the
IBM MQ 9.4 developer image does not grant it to `app`, which gets `DEV.APP.MODEL.QUEUE` instead
(`temporaryModel=DEV.APP.MODEL.QUEUE`). With `connectionFactory` the model is the factory's `TemporaryModel`.
> The listener runs each route synchronously on the XMS dispatch thread (one in-flight message per session),
> which is what provides natural back-pressure. Reverting to the poll path is a matter of flipping the option
> back to `Poll` (or omitting it).
## Batch mode
`batching=true` makes the consumer hand the route one exchange per batch, by the batch contract every broker of
redb.Route follows. Poll receive mode only.
- Each worker (`concurrentConsumers`) reads a batch with MQGET under its connection's syncpoint: up to
`maxBatchMessages` (default 100), sent on once no message came for `pollTimeoutMs` (default 1000, restarted by every
message) or once `batchingIntervalMs` has passed since the first message.
- The body is a `List`, one message per MQ message with its own body and `redbIbmMq.*` headers, even for a
batch of one; the size is `body.Count`. `redbIbmMq.Destination` and `redbIbmMq.QueueManager` are set on the batch
message. The exchange is InOnly. `Split` over the body gives each part its message.
- The batch is committed (MQCMIT) once after the route. A failed batch is backed out (MQBACK), the rule of a failed
single message: every message returns to the queue with its backout count raised, and once it reaches
`backoutThreshold` it goes to `backoutQueue` instead of into a batch.
- A request (a message with a reply-to queue) cannot be answered from a one-way batch: it goes to `backoutQueue` in the
batch's unit of work, with an error in the log and the endpoint statistics. `disableReplyTo=true` ignores the
reply-to: such messages are batched and nobody replies (single mode too: no reply is sent).
- A batch half collected when the consumer stops is backed out: its messages return to the queue.
- The start fails for a batch option without `batching=true`, a value out of range, `receiveMode=listener`,
`replyTo=true`, and, when the consumer starts, no backout queue (`backoutQueue`, the queue's BOQNAME) and no dead
letter queue on the queue manager.
## Poison messages
A consumer that reads under syncpoint (`transacted=true` in poll mode, or batch mode) backs a failed message out, and
the message comes again with its backout count raised. It follows the provider's chain, as the IBM MQ classes for JMS
do: once the backout count reaches the threshold, the message goes to the backout queue in the unit of work of its read,
instead of to the route.
- The threshold is `backoutThreshold`, else the input queue's BOTHRESH; the backout queue is `backoutQueue`, else the
input queue's BOQNAME. The endpoint's options override the queue's attributes.
- With a threshold and no backout queue, the message goes to the queue manager's dead letter queue (DEADQ), behind a
dead letter header (MQDLH, reason MQRC_BACKOUT_THRESHOLD_REACHED), as the provider puts it there.
- With a threshold and neither a backout queue nor a dead letter queue, the consumer does not start.
- With no threshold anywhere (BOTHRESH 0 and no option), a message that always fails comes back after every backout until
something stops it: give the route an error handler (`OnException`, a dead letter channel) that decides its end.
- In listener mode the XMS client runs the same chain itself on the queue's BOTHRESH and BOQNAME (`backoutThreshold`
below BOTHRESH applies as above). The client moves the message with its context: the application's user needs
PASSALL (and PUT) on the backout queue and the dead letter queue, or the move fails with MQRC_NOT_AUTHORIZED (2035)
and the message stays on the input queue.
### The pause after a backout
IBM MQ does not delay a backed-out message: the next MQGET takes it again at once. After a backout (a failed message
with `transacted=true`, a failed batch, a poison message whose move failed) the consumer pauses for `backoutDelay`
milliseconds (default 1000): none of its workers starts another MQGET until the pause has passed, and a later backout
extends it. `backoutDelay=0` keeps no pause, as before the option.
- This option is redb's addition: Apache Camel and the IBM MQ classes for JMS have no such option.
- Poll and batch modes. In listener mode the XMS client sets the tempo and the option does not act.
- A worker already waiting in MQGET when another worker backs out is not held back: with `concurrentConsumers` above 1
that worker can take the message before the pause ends.
- The consumer's own stop backs out its message in flight without a pause.
## A lost connection
Every connection of this connector runs on the Route connection supervisor: the schedule, the log lines, the health
and the connection events are the ones described under "Lost connections" in the redb.Route README, set once for the
context under `RedbRoute:Reconnect` (by default: first attempt after 1 s, then twice as long each time up to 30 s, one
attempt given up after 30 s). The reason codes taken as a lost connection: `MQRC_CONNECTION_BROKEN`,
`MQRC_Q_MGR_QUIESCING`, `MQRC_CONNECTION_QUIESCING`, `MQRC_Q_MGR_STOPPING`, `MQRC_CONNECTION_STOPPING`,
`MQRC_HCONN_ERROR`, `MQRC_Q_MGR_NOT_AVAILABLE` and `MQRC_CALL_INTERRUPTED`.
While a connection is lost the endpoint's health is `Warning`, and `Critical` once an attempt to reconnect failed; a
consumer route whose endpoint is `Critical` is `Unhealthy` in the route health check. Each connection is supervised on
its own and named in the health reason and the events: `wmq:ORDERS consumer worker 2`, `wmq:ORDERS listener`,
`wmq:ORDERS` for the producer.
**Poll consumer (single or batch).** A worker does not end: it closes what is left of its connection and connects
again on the schedule until it is connected or the consumer stops; a connection an attempt opens after it was given up
is closed. What the worker held under syncpoint the queue manager backed out, so those messages are read again.
**Listener consumer (`receiveMode=listener`).** The XMS connection's exception listener reports the loss; the consumer
closes the connection with its sessions and opens a new one, with all its sessions, on the schedule. Messages in flight
on the broken sessions are not settled: under `transacted=true` they return to the queue.
**Producer.** A producer whose connection is lost fails the send that found it out and fails at once every
request-reply call still waiting for its reply on that connection, with the poll reply loop and with the XMS reply
receiver (`receiveMode=listener`) alike. Its next send reconnects first (a new connection, the destination, and for
request-reply the reply queue or a new temporary queue), one bounded attempt: a send that comes before the next attempt
is due fails at once and says when it is due. A transacted send (`.Transacted()` or `transacted=true`) whose puts or
MQCMIT meet the lost connection reports it too, so the next send reconnects; a connection lost during MQCMIT itself
leaves the outcome in doubt, and a warning line says so. **A failed send is not resent.** A put that failed because the
connection broke may or may not have reached the queue manager; whether to send again (and accept a possible duplicate)
is the route's decision, through its error handler or redelivery.
A connect that reaches a queue manager still starting through a port proxy (a Docker published port, for one) can
hang in the managed client, and in our tests every later connect of the same process then waited behind it for
minutes. With the queue manager on host networking, or a listener the client reaches directly, this was not seen.
## A list body
A list of `IMessage` (a batch consumer's body, for one) is sent element by element, each element its own MQ message
with its own body and headers, none of the exchange's, in one unit of work: every MQPUT under syncpoint and one MQCMIT,
or MQBACK and nothing goes. Inside a `.Transacted()` block they join the producer's batch for the block. A plain list
(one whose text would be its type name) is refused, and so is any list at a request-reply producer (`replyTo=true`).
## Options Reference
### Connection
| Option | Default | Description |
|---|---|---|
| `host` | `localhost` | Queue manager host |
| `port` | `1414` | MQ listener port |
| `channel` | `DEV.APP.SVRCONN` | Server-connection channel |
| `queueManager` | `QM1` | Queue manager name |
| `user` | — | Auth username |
| `password` | — | Auth password |
| `clientId` | — | Client identifier |
| `connectionFactory` | — | Name of an `IbmMqConnectionFactory` in the context registry; takes priority over the inline connection options |
### Destination
| Option | Default | Description |
|---|---|---|
| `destinationType` | `Queue` | `Queue` or `Topic` |
### Consumer
| Option | Default | Description |
|---|---|---|
| `receiveMode` | `Poll` | `Poll` (MQGET-WAIT) or `Listener` (event-driven XMS, <50 ms) |
| `concurrentConsumers` | `1` | Parallel consumers |
| `waitInterval` | `5000` | MQGET wait (ms), poll mode only |
| `batching` | `false` | Batch mode (poll receive mode); see [Batch mode](#batch-mode) |
| `maxBatchMessages` | `100` | Largest batch |
| `pollTimeoutMs` | `1000` | Batch mode: idle timeout of a batch (ms) |
| `batchingIntervalMs` | — | Batch mode: hard limit of a batch from its first message (ms) |
| `disableReplyTo` | `false` | Do not act on a request's reply-to: no reply, and a batch takes it |
| `backoutThreshold` | the queue's BOTHRESH | With `transacted=true` (poll mode) or in batch mode: a message backed out this many times goes to the backout queue instead of the route, in the unit of work of its read (0 on both = off); see [Poison messages](#poison-messages) |
| `backoutQueue` | the queue's BOQNAME | Backout queue; without one, the queue manager's dead letter queue |
| `backoutDelay` | `1000` | Pause after a backout (ms) before the consumer reads again, poll and batch modes; 0 = none; redb's addition, not in Apache Camel; see [The pause after a backout](#the-pause-after-a-backout) |
| `selector` | — | Message selector |
| `convert` | `true` | Apply MQGMO_CONVERT |
### Producer
| Option | Default | Description |
|---|---|---|
| `persistence` | `AsQDef` | `Persistent`, `NonPersistent`, `AsQDef` |
| `priority` | `-1` | Priority (0–9, -1 = queue default) |
| `expiry` | `-1` | Expiry (tenths/sec, -1 = unlimited) |
| `targetClient` | `Jms` | `Jms` (with MQRFH2) or `Mq` (raw MQMD) |
| `messageType` | `Datagram` | `Datagram`, `Request`, `Reply`, `Report` |
### Transactions
| Option | Default | Description |
|---|---|---|
| `transacted` | unset | Consumer: `true` gets under syncpoint (MQCMIT/MQBACK). Producer: unset follows an enclosing `.Transacted()` block (the put waits for the database commit), `false` puts at once, `true` requires a block. A request-reply producer always puts at once and refuses `true` |
The deferred puts of one producer in a block are committed in one unit of work: every put under syncpoint, then one
MQCMIT, so they arrive together, in order, or not at all (a failed put backs them all out). The producer's batches take
turns on its connection, because a unit of work belongs to the connection.
### RPC
| Option | Default | Description |
|---|---|---|
| `replyTo` | `false` | Enable request/reply |
| `replyToQueue` | — | Reply queue (or dynamic temp) |
| `replyToQueueManager` | — | Reply QM |
| `temporaryModel` | `SYSTEM.DEFAULT.MODEL.QUEUE` | Model queue of the dynamic reply queue (IBM MQ `TEMPMODEL`) |
| `preserveMessageQos` | `false` | Keep the `redbIbmMq.ReplyToQueue` and `redbIbmMq.ReplyToQueueManager` headers on an ordinary put |
| `timeout` | `30` | RPC timeout (seconds) |
| `correlationPattern` | `MsgId` | `MsgId` or `CorrelId` |
### SSL/TLS
| Option | Default | Description |
|---|---|---|
| `sslCipherSpec` | — | CipherSpec name |
| `sslCertLabel` | — | Certificate label |
| `sslPeerName` | — | Peer DN pattern |
| `sslKeyRepository` | — | Key repo path (.kdb) |
| `sslKeyResetCount` | `0` | Key renegotiation (bytes) |
### Advanced
| Option | Default | Description |
|---|---|---|
| `cCSID` | `1208` | Coded Character Set ID |
| `mqmdWriteEnabled` | `false` | Write MQMD from headers |
| `mqmdReadEnabled` | `true` | Read MQMD into headers |
## Headers
All IBM MQ metadata headers are prefixed with `redbIbmMq.`:
- `redbIbmMq.MsgId` — message ID (hex)
- `redbIbmMq.CorrelId` — correlation ID (hex)
- `redbIbmMq.Format` — MQMD format
- `redbIbmMq.Persistence` — persistence flag
- `redbIbmMq.Priority` — priority
- `redbIbmMq.Expiry` — expiry
- `redbIbmMq.ReplyToQueue` — reply-to queue. Not carried on by an ordinary (not request-reply) put unless
`preserveMessageQos=true`: a message consumed with a sender's reply-to and forwarded here does not make another
consumer answer into a queue of another system, as in Apache Camel's JMS. The correlation id is always carried; a
request-reply put sets its own reply-to queue.
- `redbIbmMq.MsgType` — message type
- `redbIbmMq.BackoutCount` — backout count
- ... and more (see `IbmMqHeaders` class)
### Header filter strategy
The other exchange headers travel in one JSON-encoded message property (MQ property names forbid hyphens), as text;
the consumer unpacks them on the poll and the XMS path alike, and a request-reply carries them both ways.
`headerFilterStrategy=#name` names an `IHeaderFilterStrategy` in the registry that decides which headers cross, as
in Apache Camel: outgoing for a request and a consumer's reply, incoming for a delivery and the reply a
request-reply producer receives. It replaces the default, `IbmMqHeaderFilterStrategy` (keeps `redbIbmMq.*` back),
entirely; derive from that class to add to it. MQMD fields, `targetClient=Mq` (no properties at all) and the trace
context are not the strategy's.
```csharp
ctx.AddToRegistry("correlationOnly", new DefaultHeaderFilterStrategy
{
OutFilter = ["Correlation-ID"],
FilterOnMatch = false, // a whitelist: only the listed headers go out
});
// wmq:ORDERS.Q?queueManager=QM1&headerFilterStrategy=#correlationOnly
```
## Telemetry
On the `redb.Route` activity source (`AddSource("redb.Route")`). The W3C context travels in the MQRFH2 user properties
`traceparent`, `tracestate` and `baggage` (not with `targetClient=Mq`, which sends no properties).
- **Consumer**, poll and listener alike. One `Consumer` span per message, `{destination} receive`, over the whole unit
of work. Its parent is the sender's `traceparent`; without one — a message with no properties included — it is a
root, never a child of the activity the receive loop inherited from whoever started the routes. The sender's baggage
is back on it, the route's spans are its children, and a failed route marks it an error.
- **Producer.** One `Producer` span per send, `{destination} publish`; an error when the send fails. The message
carries the context of this span.
- `RouteEngineOptions.EnableTelemetry = false` opens neither span. A context that came in still goes out.
Tags: `messaging.system` = `wmq`, `messaging.operation` = `receive` / `publish`, `messaging.destination.name`,
`messaging.ibmmq.queue_manager`, `messaging.message.id` (MQMD MsgId, poll path), `redb.route.endpoint`.
## Docker (Dev/Test)
```bash
docker compose -f docker-compose.tests.yml up -d ibmmq
```
Default dev credentials:
- **Host**: `localhost:1414`
- **Queue Manager**: `QM1`
- **Channel**: `DEV.APP.SVRCONN`
- **User**: `app` / `passw0rd`
- **Web Console**: `https://localhost:9443/ibmmq/console` (`admin` / `passw0rd`)
Pre-created queues: `DEV.QUEUE.1` … `DEV.QUEUE.5`, `DEV.DEAD.LETTER.QUEUE`.
## Named connection factory
Keep credentials out of the route URI: register a factory in the context registry and
reference it by name. A set-but-unknown name fails loud at startup, when the endpoint is created: a typo can never
silently fall back to inline URI parameters.
```csharp
context.AddToRegistry("prod", new IbmMqConnectionFactory
{
Host = "mq.internal",
QueueManager = "QM1",
Channel = "DEV.APP.SVRCONN",
User = "app",
Password = secrets.MqPassword,
});
// wmq://DEV.QUEUE.1?connectionFactory=prod
```
The factory describes the whole connection: host, port, channel, queue manager, user and password, client name,
transport, TLS settings and CCSID all come from it, for the MQ-classes connections and the XMS listener alike.
Connection options written on the same URI are not used. Endpoints naming the same factory share one pooled
connection; without `connectionFactory` the inline options describe the connection.
## Concurrency
The default is **1** concurrent consumer — the industry norm (Camel, Spring, the Azure SDK all
ship 1): a single consumer preserves ordering and your handlers need no thread safety.
Parallelism is an explicit opt-in:
```
concurrentConsumers=4 # a fixed worker count
concurrentConsumers=auto # max(CPU count, 2) — the NServiceBus formula
```
Anything else — `0`, a negative, a typo — fails at endpoint creation naming the option (the old
int-typed option silently fell back to 1). Raising the value trades ordering for throughput:
messages from the same queue are processed out of order, and your processors must be safe to
run in parallel.
IBM MQ specifics: `concurrentConsumers` on a TOPIC clamps to 1 — parallel non-durable
subscriptions would each receive a full copy of every message (duplicate delivery), not share
the load. Use a QUEUE destination for competing consumers.
Path: redb-route/redb.Route.IbmMq/redb.Route.IbmMq.csproj
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/redb.Route.IbmMq.csproj
----
redb.Route.IbmMq
IBM MQ (WebSphere MQ) transport for redb.Route ESB framework. Native MQI access via IBMMQDotnetClient — queues, topics, transactions, RPC, message groups, SSL/TLS, and W3C telemetry.
esb;messaging;ibmmq;websphere;mq;redb
README.md