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