Path: redb-route/redb.Route.Amqp/AmqpEndpoint.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/AmqpEndpoint.cs ---- using Amqp; using Amqp.Framing; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using AmqpSymbol = global::Amqp.Types.Symbol; namespace redb.Route.Amqp; /// /// AMQP 1.0 endpoint. Manages a shared and , /// creates producer/consumer links on demand. /// /// Supports all AMQP 1.0 brokers: ActiveMQ Artemis, Classic, Azure Service Bus, Amazon MQ, Qpid. /// /// public sealed class AmqpEndpoint : EndpointBase { private readonly AmqpComponent _component; private readonly SemaphoreSlim _sessionLock = new(1, 1); private Session? _session; private bool _closed; /// Logger from the parent component. internal ILogger? Logger { get; } /// AMQP address (node name) extracted from the URI path. public string Address { get; } /// Creates an AMQP endpoint. public AmqpEndpoint(EndpointUri uri, AmqpComponent component, AmqpEndpointOptions options) : base(uri, component, options) { _component = component; Logger = component.Logger; Address = uri.Path; // AMQP 1.0 (3.5.3): a terminus that asks the peer for a dynamic node carries no address. if (options.Dynamic && !string.IsNullOrEmpty(Address)) throw new ArgumentException( $"AMQP endpoint '{uri}': 'dynamic=true' asks the broker to create a node and name it, so the URI names " + $"no address; drop '{Address}' or 'dynamic'."); _headerFilter = new EndpointHeaderFilter(this, options.HeaderFilterStrategy); } private readonly EndpointHeaderFilter _headerFilter; /// /// The header filter strategy of this endpoint: the one headerFilterStrategy=#name names, or /// . A name the registry does not hold fails when the producer or /// consumer is built. /// internal IHeaderFilterStrategy HeaderFilterStrategy => _headerFilter.Or(AmqpHeaderFilterStrategy.Default); /// Typed access to options. internal new AmqpEndpointOptions Options => base.Options; /// Typed options exposed for the component pool. internal AmqpEndpointOptions EndpointOptions => Options; /// public override IProducer CreateProducer() => new AmqpProducer(this, Options); /// public override IConsumer CreateConsumer(IProcessor processor) => new AmqpConsumer(this, processor, Options); /// /// Creates a sender link on the shared session. Thread-safe. /// /// /// Terminus for the sender side. expiryPolicy and terminusTimeout ride here — both were /// declared options that nothing read (until the options sweep): ResolveExpiryPolicy() /// existed and was called by nobody. /// internal Target BuildTargetTerminus() => new() { Address = Options.Dynamic ? null : Address, Dynamic = Options.Dynamic, Durable = Options.Durable, ExpiryPolicy = Options.ResolveExpiryPolicy(), Timeout = Options.TerminusTimeout, }; /// Terminus for the receiver side — same wiring as . internal Source BuildSourceTerminus() => new() { Address = Options.Dynamic ? null : Address, Dynamic = Options.Dynamic, Durable = Options.Durable, ExpiryPolicy = Options.ResolveExpiryPolicy(), Timeout = Options.TerminusTimeout, }; internal async Task CreateSenderLinkAsync(string? name = null, CancellationToken ct = default) { await EnsureConnectionAsync(ct).ConfigureAwait(false); var linkName = name ?? $"sender-{Address}-{Guid.NewGuid():N}"; var target = BuildTargetTerminus(); var caps = Options.ResolveCapabilities(); if (caps.Length > 0) target.Capabilities = caps.Select(c => new AmqpSymbol(c)).ToArray(); var attach = new Attach { Target = target, SndSettleMode = (SenderSettleMode)Options.SenderSettleMode, RcvSettleMode = (ReceiverSettleMode)Options.ReceiverSettleMode, }; // A dynamic target is a node the broker creates and names; the attach answer carries that name. OnAttached? onAttached = Options.Dynamic ? (_, remote) => Logger?.LogInformation("AMQP sender link {Name} sends to the dynamic node {Address}", linkName, (remote.Target as Target)?.Address) : null; var sender = new SenderLink(_session!, linkName, attach, onAttached); Logger?.LogDebug("AMQP sender link created: address={Address}, name={Name}", Address, linkName); return sender; } /// /// Creates a receiver link on the shared session. Thread-safe. /// internal async Task CreateReceiverLinkAsync(string? name = null, CancellationToken ct = default) { await EnsureConnectionAsync(ct).ConfigureAwait(false); return BuildReceiver(_session!, name); } /// /// Creates a receiver link on a FRESH dedicated (its own session on the /// pooled connection), returned alongside that session so the caller owns and closes both. /// /// This is how runs ConcurrentConsumers(N) as N real competing /// consumers: AMQPNetLite / objects are NOT thread-safe, so /// concurrent receive/accept must not share one session. Each worker gets its own session + /// receiver and drives them from a single thread. /// /// internal async Task<(Session Session, ReceiverLink Receiver)> CreateDedicatedReceiverAsync( string? name = null, OnAttached? onAttached = null, CancellationToken ct = default) { var connection = await _component.GetOrCreateConnectionAsync(this, ct).ConfigureAwait(false); var session = new Session(connection); try { var receiver = BuildReceiver(session, name, onAttached); return (session, receiver); } catch { try { await session.CloseAsync().ConfigureAwait(false); } catch { /* best-effort */ } throw; } } /// Builds a configured (source, filters, credit) on the given session. private ReceiverLink BuildReceiver(Session session, string? name, OnAttached? onAttached = null) { var linkName = name ?? $"receiver-{Address}-{Guid.NewGuid():N}"; var source = BuildSourceTerminus(); var caps = Options.ResolveCapabilities(); if (caps.Length > 0) source.Capabilities = caps.Select(c => new AmqpSymbol(c)).ToArray(); if (!string.IsNullOrEmpty(Options.DistributionMode)) source.DistributionMode = new AmqpSymbol(Options.DistributionMode); if (!string.IsNullOrEmpty(Options.FilterSelector)) { source.FilterSet = new global::Amqp.Types.Map { { new AmqpSymbol("apache.org:selector-filter:string"), new global::Amqp.Types.DescribedValue( new AmqpSymbol("apache.org:selector-filter:string"), Options.FilterSelector) } }; } var attach = new Attach { Source = source, SndSettleMode = (SenderSettleMode)Options.SenderSettleMode, RcvSettleMode = (ReceiverSettleMode)Options.ReceiverSettleMode, }; var receiver = new ReceiverLink(session, linkName, attach, onAttached); receiver.SetCredit(Options.Credit, true); Logger?.LogDebug("AMQP receiver link created: address={Address}, name={Name}, credit={Credit}", Address, linkName, Options.Credit); return receiver; } /// Gets the current session (for transacted operations). internal Session? CurrentSession => _session; /// Ensures connection is available (used by producer for RPC link setup). internal async Task EnsureConnectionForRpcAsync(CancellationToken ct = default) { await EnsureConnectionAsync(ct).ConfigureAwait(false); } /// /// Ensures the per-endpoint is open on a pooled connection. Thread-safe. /// The is owned by ; this endpoint owns /// only the session. On Stop the session is closed but the pooled connection survives. /// private async Task EnsureConnectionAsync(CancellationToken ct) { if (_session is { IsClosed: false }) return; await _sessionLock.WaitAsync(ct).ConfigureAwait(false); try { if (_session is { IsClosed: false }) return; var connection = await _component.GetOrCreateConnectionAsync(this, ct).ConfigureAwait(false); _session = new Session(connection); // The pool key names the connection as the "connection opened" log does: the factory, or the inline host. Logger?.LogInformation("AMQP session opened on pooled connection [{Key}]: address={Address}", AmqpComponent.ResolveConnectionKey(Options), Address); } finally { _sessionLock.Release(); } } /// /// Subscribes diagnostic logging to connection-level events. Invoked by /// exactly once per pooled connection. /// internal void AttachConnectionEvents(Connection connection) { connection.Closed += OnConnectionClosed; } private void OnConnectionClosed(IAmqpObject sender, global::Amqp.Framing.Error error) { if (error != null) { Logger?.LogWarning("AMQP connection closed with error: {Condition} — {Description}", error.Condition, error.Description); } else { Logger?.LogInformation("AMQP connection closed gracefully"); } } /// public override async Task Stop(CancellationToken ct = default) { if (_closed) return; _closed = true; // Close the per-endpoint Session. The pooled Connection is owned by AmqpComponent // and is NOT closed here — it survives Stop/Start cycles and is released only on // RouteContext.DisposeAsync (which calls Component.DisposeAsync). if (_session is { IsClosed: false }) { try { await _session.CloseAsync().ConfigureAwait(false); } catch (Exception ex) { Logger?.LogWarning(ex, "Error closing AMQP session"); } } _session = null; Logger?.LogInformation("AMQP endpoint stopped: {Uri}", EndpointUri.ForLog(Uri.ToString(), Logger)); } }