Path: redb-route/redb.Route.Amqp/AmqpComponent.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.Amqp/AmqpComponent.cs ---- using System.Collections.Concurrent; using Amqp; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Extensions; using redb.Route.Core; namespace redb.Route.Amqp; /// /// AMQP 1.0 transport component for redb.Route. /// Scheme: amqp. /// /// URI format: amqp://address-name?host=broker&port=5672&user=admin&password=admin /// /// /// Supports any AMQP 1.0 broker: ActiveMQ Artemis, ActiveMQ Classic, Azure Service Bus, /// Amazon MQ, Qpid, and more. Pure AMQP 1.0 — no JMS wrappers. /// /// /// Owns a process-wide pool of instances, shared between endpoints by /// the same key model used for RabbitMQ: /// /// 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}/{vhost}@{user}#{ssl}". /// /// Sessions are owned per-endpoint (Session is a lightweight AMQP framing context). Connections /// survive endpoint Stop/Start cycles and are released on . /// /// public sealed class AmqpComponent : ComponentBase { private readonly ConcurrentDictionary>> _connections = new(StringComparer.Ordinal); /// public override string Scheme => "amqp"; /// public override IEndpoint CreateEndpoint(EndpointUri uri) { ArgumentNullException.ThrowIfNull(uri); var options = new AmqpEndpointOptions(); options.BindFromUri(uri.RawParameters); options.Validate(); options.ResolveBatch(EndpointUri.Sanitize(uri.BaseKey)); return new AmqpEndpoint(uri, this, options); } /// /// Returns the shared for the given endpoint, creating it on first /// request. Self-healing: if the cached connection has been closed (broker reset, network), /// it is evicted and recreated on the next call. /// internal async Task GetOrCreateConnectionAsync(AmqpEndpoint endpoint, CancellationToken ct) { var key = ResolveConnectionKey(endpoint.EndpointOptions); var lazy = _connections.GetOrAdd(key, k => new Lazy>(() => CreateConnectionAsync(k, endpoint, ct))); Connection conn; try { conn = await lazy.Value.ConfigureAwait(false); } catch { ((ICollection>>>)_connections) .Remove(new KeyValuePair>>(key, lazy)); throw; } if (conn.IsClosed) { ((ICollection>>>)_connections) .Remove(new KeyValuePair>>(key, lazy)); return await GetOrCreateConnectionAsync(endpoint, ct).ConfigureAwait(false); } return conn; } /// Number of currently pooled connections (for diagnostics and tests). internal int PooledConnectionCount => _connections.Count; /// Returns a snapshot of the open pooled connections (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; } /// Computes the pool key for the given endpoint options. internal static string ResolveConnectionKey(AmqpEndpointOptions opts) { if (!string.IsNullOrEmpty(opts.ConnectionFactory)) return "factory:" + opts.ConnectionFactory; return string.Concat( "inline:", opts.Host, ":", opts.Port.ToString(System.Globalization.CultureInfo.InvariantCulture), "/", opts.VirtualHost, "@", opts.User, opts.Ssl ? "#ssl" : string.Empty); } private async Task CreateConnectionAsync(string key, AmqpEndpoint endpoint, CancellationToken ct) { var settings = ResolveConnectionSettings(endpoint.EndpointOptions); var address = ConnectionAddress(settings); var connection = await settings.Build().CreateAsync(address).ConfigureAwait(false); endpoint.AttachConnectionEvents(connection); Logger?.LogInformation("AMQP connection opened [{Key}]: host={Host}, port={Port}, vHost={VHost}", key, address.Host, address.Port, settings.VirtualHost); return connection; } /// /// The settings a connection is opened with: the registry factory connectionFactory= names, whole (its host, /// port, credentials and TLS, not the URI's), or else the inline URI parameters. /// internal AmqpConnectionFactory ResolveConnectionSettings(AmqpEndpointOptions options) { if (!string.IsNullOrEmpty(options.ConnectionFactory)) { // A set-but-unknown name fails loud — never a silent fallback to URI params. var registryFactory = Context.GetRequiredFromRegistry(options.ConnectionFactory); Logger?.LogDebug("AMQP: using ConnectionFactory '{Name}' from registry", options.ConnectionFactory); return registryFactory; } return new AmqpConnectionFactory { Host = options.Host, Port = options.Port, User = options.User, Password = options.Password, ContainerId = options.ContainerId, VirtualHost = options.VirtualHost, Ssl = options.Ssl, }; } /// The address a connection is opened to: the first host of the settings. internal static Address ConnectionAddress(AmqpConnectionFactory settings) => settings.GetAddresses()[0]; /// public override async ValueTask DisposeAsync() { foreach (var (key, lazy) in _connections.ToArray()) { if (!lazy.IsValueCreated) continue; Connection? conn = null; try { conn = await lazy.Value.ConfigureAwait(false); } catch { /* failed initialisation */ } if (conn is null) continue; try { if (!conn.IsClosed) await conn.CloseAsync().ConfigureAwait(false); } catch (Exception ex) { Logger?.LogWarning(ex, "AMQP: error closing pooled connection [{Key}]", key); } } _connections.Clear(); Logger?.LogInformation("AMQP component disposed: connection pool drained"); } }