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