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