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