Bundle: redb-route / redb.Route.Amqp (redb.Route.Amqp.txt), 14 files Snapshot: 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 Index: https://redbase.app/src/dev-2026-12-06/redb-route/_index.txt ==== 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"); } } Path: redb-route/redb.Route.Amqp/AmqpConnectionFactory.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/AmqpConnectionFactory.cs ---- using System.Security.Authentication; using redb.Route.Core; namespace redb.Route.Amqp; /// /// AMQP 1.0 connection factory configuration. Standalone POCO — register in DI or reference by name. /// /// Covers all settings: /// SASL, SSL/TLS, TCP tuning, AMQP protocol limits, and reconnect policy. /// /// public sealed class AmqpConnectionFactory { // ── Connection coordinates ── /// /// Broker host (default: localhost). In a comma-separated list the connection opens to the first host; the others /// are not tried. /// public string Host { get; set; } = "localhost"; /// AMQP port (default: 5672, or 5671 for AMQPS). public int Port { get; set; } = 5672; /// Username for SASL PLAIN authentication. public string? User { get; set; } /// Password for SASL PLAIN authentication. [Sensitive] public string? Password { get; set; } /// Container ID sent during AMQP Open. Identifies this client to the broker. public string? ContainerId { get; set; } /// Virtual host / AMQP hostname field (used by Azure Service Bus, multi-tenant brokers). public string? VirtualHost { get; set; } /// Client name for logging/diagnostics (maps to ContainerId if not set). public string? ClientName { get; set; } // ── AMQP protocol limits ── /// Idle timeout in milliseconds. 0 = disabled. (default: 120000) public int IdleTimeout { get; set; } = 120_000; /// Maximum frame size in bytes. (default: 256KB) public int MaxFrameSize { get; set; } = 256 * 1024; /// Maximum sessions per connection. (default: 8) public ushort MaxSessions { get; set; } = 8; // ── TCP tuning ── /// TCP NoDelay (Nagle off). (default: true) public bool NoDelay { get; set; } = true; /// TCP keepalive. (default: false) public bool KeepAlive { get; set; } /// TCP send buffer size in bytes. 0 = OS default. public int SendBufferSize { get; set; } /// TCP receive buffer size in bytes. 0 = OS default. public int ReceiveBufferSize { get; set; } /// TCP send timeout in milliseconds. 0 = infinite. public int SendTimeout { get; set; } /// TCP receive timeout in milliseconds. 0 = infinite. public int ReceiveTimeout { get; set; } // ── SSL/TLS ── /// Enable SSL/TLS (amqps://). (default: false) public bool Ssl { get; set; } /// SSL protocols to use. (default: None — OS negotiates) public SslProtocols SslProtocols { get; set; } = SslProtocols.None; /// Path to client certificate file (PFX/PEM) for mTLS. public string? SslCertPath { get; set; } /// Password for client certificate. [Sensitive] public string? SslCertPassword { get; set; } /// Check certificate revocation. (default: false) public bool CheckCertRevocation { get; set; } /// Skip server certificate validation (DANGEROUS — dev only). (default: false) public bool TrustAllCertificates { get; set; } // ── SASL ── /// /// SASL mechanism: PLAIN, EXTERNAL, ANONYMOUS. (default: PLAIN if User is set, ANONYMOUS otherwise) /// public SaslMechanism SaslMechanism { get; set; } = SaslMechanism.Auto; // Reconnect settings were removed: the component's connection pool already // self-heals (a closed connection is evicted and recreated on the next call), and the // factory-level Reconnect/ReconnectInterval/MaxReconnectAttempts were never read. // ── Build ── /// /// Builds a native configured from these settings. /// public global::Amqp.ConnectionFactory Build() { var factory = new global::Amqp.ConnectionFactory(); // AMQP settings var containerId = ContainerId ?? ClientName ?? $"redb-route-{Guid.NewGuid():N}"; factory.AMQP.ContainerId = containerId; factory.AMQP.HostName = VirtualHost; factory.AMQP.IdleTimeout = IdleTimeout; factory.AMQP.MaxFrameSize = MaxFrameSize; factory.AMQP.MaxSessionsPerConnection = MaxSessions; // TCP settings factory.TCP.NoDelay = NoDelay; if (KeepAlive) factory.TCP.KeepAlive = new global::Amqp.TcpKeepAliveSettings { KeepAliveTime = 30000, KeepAliveInterval = 10000 }; if (SendBufferSize > 0) factory.TCP.SendBufferSize = SendBufferSize; if (ReceiveBufferSize > 0) factory.TCP.ReceiveBufferSize = ReceiveBufferSize; if (SendTimeout > 0) factory.TCP.SendTimeout = SendTimeout; if (ReceiveTimeout > 0) factory.TCP.ReceiveTimeout = ReceiveTimeout; // SASL ConfigureSasl(factory); // SSL if (Ssl) ConfigureSsl(factory); return factory; } /// /// Builds an from the current host/port/user/password settings. /// public global::Amqp.Address BuildAddress() { var scheme = Ssl ? "amqps" : "amqp"; return new global::Amqp.Address(Host, Port, User, Password, "/", scheme); } /// /// Parses comma-separated hosts and returns one address per host, in list order. The component connects to the /// first one. /// public global::Amqp.Address[] GetAddresses() { var hosts = Host.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); if (hosts.Length <= 1) return [BuildAddress()]; var scheme = Ssl ? "amqps" : "amqp"; return hosts.Select(h => new global::Amqp.Address(h, Port, User, Password, "/", scheme)).ToArray(); } private void ConfigureSasl(global::Amqp.ConnectionFactory factory) { var mechanism = SaslMechanism; if (mechanism == SaslMechanism.Auto) { mechanism = !string.IsNullOrEmpty(User) ? SaslMechanism.Plain : SaslMechanism.Anonymous; } // SASL PLAIN is handled automatically by AMQPNetLite when User/Password are in the Address. // Only External and Anonymous need explicit profile configuration. factory.SASL.Profile = mechanism switch { SaslMechanism.External => global::Amqp.Sasl.SaslProfile.External, SaslMechanism.Anonymous => global::Amqp.Sasl.SaslProfile.Anonymous, _ => null // PLAIN: auto-detected from Address credentials }; } private void ConfigureSsl(global::Amqp.ConnectionFactory factory) { factory.SSL.Protocols = SslProtocols; factory.SSL.CheckCertificateRevocation = CheckCertRevocation; if (!string.IsNullOrEmpty(SslCertPath)) { var cert = string.IsNullOrEmpty(SslCertPassword) ? new System.Security.Cryptography.X509Certificates.X509Certificate2(SslCertPath) : new System.Security.Cryptography.X509Certificates.X509Certificate2(SslCertPath, SslCertPassword); factory.SSL.ClientCertificates.Add(cert); } if (TrustAllCertificates) { factory.SSL.RemoteCertificateValidationCallback = (_, _, _, _) => true; } } } /// SASL authentication mechanism. public enum SaslMechanism { /// Auto-detect: PLAIN if User is set, ANONYMOUS otherwise. Auto, /// SASL PLAIN (username/password). Plain, /// SASL EXTERNAL (client certificate). External, /// SASL ANONYMOUS (no credentials). Anonymous } Path: redb-route/redb.Route.Amqp/AmqpConsumer.Batch.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/AmqpConsumer.Batch.cs ---- using Amqp; using Amqp.Framing; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Batching; using redb.Route.Core; using redb.Route.Telemetry; using AmqpMessage = global::Amqp.Message; namespace redb.Route.Amqp; /// /// Batch mode of the AMQP 1.0 consumer (batching=true), on the core batch contract: each worker collects up to /// maxBatchMessages deliveries of its receiver link, runs them through the route once and settles them once. /// Success accepts every delivery; a failure applies the rule of a failed single delivery to each of them: released, /// so the broker delivers it again. A batch the consumer stops on is given back: released, or, once the stop has closed /// the link, returned by the broker on detach. A delivery that asks for a reply cannot /// be answered from a one-way batch: unless disableReplyTo=true, it is rejected at once (the broker moves a /// rejected delivery to its dead letter address, where it has one) and the rest goes on. /// public sealed partial class AmqpConsumer { private async Task BatchLoopAsync(Worker worker, BatchOptions batch, CancellationToken stop) { // One pass per link: a link the broker closed, or lost with the connection under it, is attached again on the // schedule, and the deliveries it held unsettled come back from the broker. while (!stop.IsCancellationRequested) { // A link that ends its pass is attached again at once: a detached link is not IsClosed until it has closed. if (worker.Receiver is { IsClosed: false } receiver && !await BatchLinkLoopAsync(receiver, batch, stop).ConfigureAwait(false)) return; if (!await ReattachAsync(worker, stop).ConfigureAwait(false)) return; } } /// /// Collects and runs batches on one link until the link closes (returns true: the caller attaches it again) or /// the consumer stops (returns false). /// private async Task BatchLinkLoopAsync(ReceiverLink receiver, BatchOptions batch, CancellationToken stop) { var settlement = new AmqpBatchSettlement(this, receiver); var dispatcher = new BatchDispatcher(_processor, settlement, ToMessage, _endpoint.ScopeFactory, [AmqpHeaders.Address]); var collector = new BatchCollector(batch, (into, max, wait, ct) => ReceiveIntoBatchAsync(receiver, into, max, wait, ct)); while (!stop.IsCancellationRequested && !receiver.IsClosed) { CollectedBatch collected; try { collected = await collector.CollectAsync(stop).ConfigureAwait(false); } catch (Exception ex) when (!stop.IsCancellationRequested && (ex is AmqpException || receiver.IsClosed)) { // The link went away under the collection (a detach throws while the link is still closing): not an error // of a message; the caller attaches it again. _logger?.LogDebug(ex, "AMQP batch receive ended with the link closed: address={Address}", _address); return true; } catch (Exception ex) when (!stop.IsCancellationRequested) { _endpoint.RecordError(ex); _logger?.LogError(ex, "Error in AMQP batch receive: address={Address}", _address); continue; } catch (Exception ex) { _logger?.LogDebug(ex, "AMQP batch receive ended by the stop"); return false; } if (collected.Items.Count == 0) continue; if (collected.Interrupted) { await settlement.ReturnAsync(collected.Items, CancellationToken.None).ConfigureAwait(false); return false; } var items = collected.Items; using var span = BatchDispatcher.StartSpan( (_endpoint.Component as ComponentBase)?.Context, $"{_address} receive", "amqp", _endpoint.Uri.NormalizedKey, _address, items.Select(m => RouteTelemetryExtensions.ExtractTraceContext(m.ApplicationProperties?.Map, static (map, name) => map is not null && map.TryGetValue(name, out var raw) ? raw?.ToString() : null)), items.Count); _drain.Increment(); try { if (await dispatcher.DispatchAsync(items, span, _drain.ProcessingToken).ConfigureAwait(false) == BatchOutcome.Accepted) Interlocked.Add(ref _processedCount, items.Count); } catch (OperationCanceledException) when (_drain.ProcessingToken.IsCancellationRequested) { return false; } catch (Exception ex) { _endpoint.RecordError(ex); _logger?.LogError(ex, "AMQP batch failed to settle: address={Address}", _address); } finally { _drain.Decrement(); } } return !stop.IsCancellationRequested; } /// /// The transport's part of collection: one delivery from the link, waiting at most . The link /// has no cancellable receive: a stop is seen when the wait ends, or when the stop closes the link. /// internal async ValueTask ReceiveIntoBatchAsync(ReceiverLink receiver, List into, int max, TimeSpan wait, CancellationToken ct) { ct.ThrowIfCancellationRequested(); var msg = await receiver.ReceiveAsync(WholeMilliseconds(wait)).ConfigureAwait(false); if (msg is null) { ct.ThrowIfCancellationRequested(); return 0; } if (!_options.DisableReplyTo && !string.IsNullOrEmpty(msg.Properties?.ReplyTo)) { RejectRequest(receiver, msg); ct.ThrowIfCancellationRequested(); return 0; } into.Add(msg); ct.ThrowIfCancellationRequested(); return 1; } /// /// The wait rounded up to whole milliseconds, at least one. AMQPNetLite's ReceiveAsync(TimeSpan) counts whole /// milliseconds and drops the rest, and a receive of 0 ms with no delivery at hand creates no waiter: its task never /// completes. The collector's last wait before the idle or hard deadline can be under a millisecond, and the worker /// then waited forever, receiving nothing and holding the consumer's stop. /// internal static TimeSpan WholeMilliseconds(TimeSpan wait) => TimeSpan.FromMilliseconds(Math.Max(1, Math.Ceiling(wait.TotalMilliseconds))); /// A delivery with a reply-to in batch mode: rejected at once, recorded, and the batch goes on. private void RejectRequest(ReceiverLink receiver, AmqpMessage msg) { var refused = new InvalidOperationException( $"AMQP batch consumer on '{_address}' received a delivery with reply-to '{msg.Properties!.ReplyTo}': a batch is " + "one-way and nobody would answer it, so it is rejected (to the dead letter address, if the broker has one). " + "Set disableReplyTo=true to batch such deliveries without a reply."); _endpoint.RecordError(refused); _logger?.LogError(refused, "{Message}", refused.Message); if (_options.AckMode == AckMode.Auto) { // ackMode=auto settles on receipt, as a single delivery: accepted, gone. receiver.Accept(msg); return; } try { receiver.Reject(msg, new Error(new global::Amqp.Types.Symbol("amqp:not-implemented")) { Description = "a batch consumer does not answer requests", }); } catch (Exception ex) { _logger?.LogWarning(ex, "AMQP: rejecting a delivery with a reply-to failed"); } } /// /// AMQP's settlement of a batch: each delivery on the link it came on. One instance per worker, used by one batch at /// a time. /// private sealed class AmqpBatchSettlement(AmqpConsumer owner, ReceiverLink receiver) : IBatchSettlement { /// The batch in flight was accepted on receipt (ackMode=auto): there is nothing to give back. private bool _acceptedOnReceipt; public ValueTask BeforeRouteAsync(IExchange batch, IReadOnlyList items, CancellationToken ct) { // ackMode=auto: accepted on receipt, before the route runs (at-most-once), as a single delivery is. if (owner._options.AckMode == AckMode.Auto) { Settle(items, receiver.Accept, "accept"); _acceptedOnReceipt = true; } return ValueTask.FromResult(null); } public ValueTask AcceptAsync(IExchange batch, IReadOnlyList items, CancellationToken ct) { if (!_acceptedOnReceipt) Settle(items, receiver.Accept, "accept"); _acceptedOnReceipt = false; return ValueTask.CompletedTask; } public ValueTask RejectAsync(IExchange batch, IReadOnlyList items, Exception failure, CancellationToken ct) { owner._logger?.LogError(failure, "AMQP batch of {Count} failed: address={Address}; given back as failed for redelivery", items.Count, owner._address); if (!_acceptedOnReceipt) Settle(items, m => receiver.Modify(m, deliveryFailed: true), "modify"); _acceptedOnReceipt = false; return ValueTask.CompletedTask; } public ValueTask ReturnAsync(IReadOnlyList items, CancellationToken ct) { // A closed link gave its unsettled deliveries back to the broker when it detached. if (!_acceptedOnReceipt && !receiver.IsClosed) Settle(items, receiver.Release, "release"); _acceptedOnReceipt = false; return ValueTask.CompletedTask; } /// Settles each delivery; one that fails (a link closed under it) is logged and the broker gives it back. private void Settle(IReadOnlyList items, Action settle, string operation) { foreach (var msg in items) { try { settle(msg); } catch (Exception ex) { owner._endpoint.RecordError(ex); owner._logger?.LogWarning(ex, "AMQP batch {Operation} failed for messageId={MessageId} on {Address}", operation, msg.Properties?.MessageId, owner._address); } } } } } Path: redb-route/redb.Route.Amqp/AmqpConsumer.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/AmqpConsumer.cs ---- using System.Collections.Concurrent; using System.Diagnostics; using System.Text; using Amqp; using Amqp.Framing; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Telemetry; using AmqpMessage = global::Amqp.Message; using RouteMessage = redb.Route.Core.Message; namespace redb.Route.Amqp; /// /// AMQP 1.0 consumer. Receives messages via with support for: /// concurrent processing, automatic/manual accept, RPC reply, and batch mode (batching=true, see the /// AmqpConsumer.Batch.cs part). /// public sealed partial class AmqpConsumer : IConsumer { private readonly AmqpEndpoint _endpoint; public IEndpoint Endpoint => _endpoint; private readonly IProcessor _processor; private readonly AmqpEndpointOptions _options; private ILogger? _logger; // ConcurrentConsumers is honoured as N REAL competing consumers: each Worker owns its own AMQP // session + receiver link and drives a single serial receive loop. AMQPNetLite sessions/links are // not thread-safe, so concurrency comes from N independent workers, never from sharing one link. private readonly List _workers = new(); // The node the consumer reads: the URI address, or the name the broker gave a dynamic node. private string _address; /// /// The node this consumer reads: the address of the URI, or, with dynamic=true, the name the broker gave /// the node it created (known once has returned). Senders reach the consumer at this address. /// public string Address => _address; private CancellationTokenSource? _cts; private readonly InflightDrainGuard _drain = new(); private long _processedCount; /// Number of messages successfully processed (summed across all worker loops). public long ProcessedCount => Interlocked.Read(ref _processedCount); /// /// One competing consumer: its own AMQP session, receiver link and receive-loop task, and the supervisor of its link. /// A link the broker closes (a detach, or the connection under it lost) is attached again on a new session by the /// worker's loop, so the session and the link change over the worker's life. /// private sealed class Worker { public Worker(int index, ConnectionSupervisor supervisor) { Index = index; Supervisor = supervisor; } public int Index { get; } public ConnectionSupervisor Supervisor { get; } public Session? Session { get; set; } public ReceiverLink? Receiver { get; set; } public Task? Loop { get; set; } } /// Creates an AMQP consumer. public AmqpConsumer(AmqpEndpoint endpoint, IProcessor processor, AmqpEndpointOptions options) { _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); _processor = processor ?? throw new ArgumentNullException(nameof(processor)); _options = options ?? throw new ArgumentNullException(nameof(options)); _logger = endpoint.Logger; _address = endpoint.Address; _headerFilter = endpoint.HeaderFilterStrategy; } private readonly IHeaderFilterStrategy _headerFilter; /// public async Task Start(CancellationToken ct = default) { var workerCount = Math.Max(1, _options.ResolvedConcurrentConsumers); _logger ??= (_endpoint.Component as ComponentBase)?.Logger; // Each worker is a receiver link of its own. On a MULTICAST (topic) address every link is a subscription // that gets a COPY of each message, and every dynamic link gets a node of its own: N workers would not // share the work, they would process each message N times or read N different nodes. One link, as IBM MQ // does for a topic. var multicast = _options.ResolveCapabilities().Contains("topic", StringComparer.OrdinalIgnoreCase); if (workerCount > 1 && (multicast || _options.Dynamic)) { _logger?.LogWarning( "AMQP: ConcurrentConsumers({N}) ignored for {Kind} {Address}: each receiver link would get a copy of " + "every message instead of a share of them, so the consumer runs one link", workerCount, multicast ? "MULTICAST address" : "a dynamic node", _address); workerCount = 1; } _cts = new CancellationTokenSource(); _drain.Start(ct); try { for (var i = 0; i < workerCount; i++) { var worker = new Worker(i, _endpoint.Supervise($"amqp:{_endpoint.Address} consumer worker {i}", _logger)); _workers.Add(worker); await AttachAsync(worker, ct).ConfigureAwait(false); worker.Loop = _options.Batch is { } batch ? Task.Run(() => BatchLoopAsync(worker, batch, _cts.Token), _cts.Token) : Task.Run(() => ReceiveLoopAsync(worker, _cts.Token), _cts.Token); } } catch { // Partial start — tear down whatever came up so we don't leak sessions/links. await StopWorkersAsync(ct).ConfigureAwait(false); _drain.Dispose(); _cts?.Dispose(); _cts = null; throw; } _logger?.LogInformation( "AMQP consumer started: address={Address}, credit={Credit}, concurrent={Concurrent}, batch={Batch}", _address, _options.Credit, workerCount, _options.Batch?.MaxMessages); } /// The consumer as errors name it: its scheme and the address of its URI. private string ConsumerName => $"AMQP consumer amqp:{_endpoint.Address}"; /// /// The broker's attach answer. An accepted receiver link comes back with a source (for a dynamic node, the address /// the broker gave it); a refused one comes back without a source and is detached right after with the reason. /// Frames of a connection are handled one after another, so the detach cannot pass the handler subscribed here. /// private void OnLinkAttached(ILink link, Attach remote, TaskCompletionSource attached, string failing) { if (remote.Source is Source source) { attached.TrySetResult(source.Address); return; } link.Closed += (_, error) => attached.TrySetException(Refused(error, failing)); if (link.IsClosed) attached.TrySetException(Refused(link.Error, failing)); } private InvalidOperationException Refused(Error? error, string failing) => new( $"{ConsumerName} {failing}: the broker refused the receiver link" + (error is null ? "." : $" ({error.Condition}: {error.Description}).")); private const string StartFailing = "cannot start"; private const string ReattachFailing = "cannot attach its receiver link again"; /// /// Opens the worker's session and receiver link at start. The link waits for the broker's attach answer before /// Start returns: without the wait a refused link (an unknown address, no permission) was only logged by the receive /// loop and the consumer stayed "started" without receiving, and on a topic the subscription did not exist yet when /// Start returned. /// private async Task AttachAsync(Worker worker, CancellationToken ct) { var (session, receiver, address) = await OpenLinkAsync(worker.Index, StartFailing, ct).ConfigureAwait(false); worker.Session = session; worker.Receiver = receiver; if (_options.Dynamic) _address = address!; } /// /// A session and a receiver link the broker accepted, with the address its answer names. Nothing is left open when it /// fails: no answer within timeout, a refusal, or a dynamic node the broker did not create. /// private async Task<(Session Session, ReceiverLink Receiver, string? Address)> OpenLinkAsync(int index, string failing, CancellationToken ct) { var attached = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var (session, receiver) = await _endpoint .CreateDedicatedReceiverAsync($"receiver-{_endpoint.Address}-{index}-{Guid.NewGuid():N}", (link, remote) => OnLinkAttached(link, remote, attached, failing), ct) .ConfigureAwait(false); try { string? address; try { address = await attached.Task.WaitAsync(TimeSpan.FromSeconds(_options.Timeout), ct).ConfigureAwait(false); } catch (TimeoutException ex) { throw new InvalidOperationException( $"{ConsumerName} {failing}: the broker did not answer the receiver link within {_options.Timeout} s.", ex); } // The broker names the dynamic node in its attach answer; the route reads that node. if (_options.Dynamic && string.IsNullOrEmpty(address)) throw new InvalidOperationException( $"{ConsumerName} {failing}: the broker created no dynamic node for the receiver link."); return (session, receiver, address); } catch { await CloseLinkQuietlyAsync(session, receiver).ConfigureAwait(false); throw; } } /// /// Attaches a worker's link again after the broker closed it: reports the loss to the worker's supervisor, closes what /// is left of the old session, and opens a new session and link on the supervisor's schedule, one bounded attempt at /// a time (the component replaces a closed connection on the way), until it succeeds or the consumer stops. While it /// is away the endpoint's health says so. Returns false when the consumer stopped first. A dynamic node is a new /// node with a new name after the reattach: senders find the consumer at again. /// private async Task ReattachAsync(Worker worker, CancellationToken ct) { // A failed receive can resume on the connection's frame pump; the reattach waits for frames, so it leaves it. await Task.Yield(); var supervisor = worker.Supervisor; supervisor.Lost(LinkLost(worker.Receiver)); await CloseLinkQuietlyAsync(worker.Session, worker.Receiver).ConfigureAwait(false); worker.Receiver = null; worker.Session = null; return await supervisor.ReconnectAsync(async c => { var (session, receiver, address) = await supervisor.AttemptAsync( a => OpenLinkAsync(worker.Index, ReattachFailing, a), late => _ = CloseLinkQuietlyAsync(late.Session, late.Receiver), c).ConfigureAwait(false); worker.Session = session; worker.Receiver = receiver; if (_options.Dynamic && address != _address) { _logger?.LogWarning("AMQP consumer reads the new dynamic node {Address} after its link was attached again " + "(it read {Old})", address, _address); _address = address!; } }, ct).ConfigureAwait(false); } /// Why the worker's link is gone: the broker's error on it, or a link closed without one. private Exception LinkLost(ReceiverLink? receiver) => receiver?.Error is { } error ? new AmqpException(error) : new InvalidOperationException($"the receiver link of amqp:{_address} was closed"); // A close waits for the broker's answer; on a connection that is gone without a TCP close it would wait out the // client's default, so the reattach does not start before this. private TimeSpan CloseWait => TimeSpan.FromSeconds(Math.Max(1, _options.Timeout)); private async Task CloseLinkQuietlyAsync(Session? session, ReceiverLink? receiver) { if (receiver is { IsClosed: false }) { try { await receiver.CloseAsync(CloseWait, null).ConfigureAwait(false); } catch (Exception ex) { _logger?.LogDebug(ex, "Error closing an AMQP receiver link"); } } if (session is { IsClosed: false }) { try { await session.CloseAsync(CloseWait, null).ConfigureAwait(false); } catch (Exception ex) { _logger?.LogDebug(ex, "Error closing an AMQP session"); } } } /// public async Task Stop(CancellationToken ct = default) { // Step 1: stop accepting new messages _cts?.Cancel(); // Close receivers BEFORE awaiting the loops — this unblocks ReceiveAsync (which doesn't // accept a CancellationToken). Then drain in-flight processing, then await the loops. // Batch mode keeps the links open until the batches in flight are settled on them (the drain below), then closes // them: a link receive cannot be cancelled, and closing the link ends it. The broker gives back the unsettled // deliveries of a batch still being collected when its link detaches. if (_options.Batch is null) { foreach (var w in _workers) { if (w.Receiver is { IsClosed: false }) { try { await w.Receiver.CloseAsync().ConfigureAwait(false); } catch (Exception ex) { _logger?.LogWarning(ex, "Error closing AMQP receiver link"); } } } } // Step 2: drain in-flight processing await _drain.DrainAsync(ct, _logger, $"amqp:{_address}").ConfigureAwait(false); // Batch mode: the batches in flight are settled; closing the links now ends a receive that is still waiting. if (_options.Batch is not null) { foreach (var w in _workers) { if (w.Receiver is { IsClosed: false }) { try { await w.Receiver.CloseAsync().ConfigureAwait(false); } catch (Exception ex) { _logger?.LogWarning(ex, "Error closing AMQP receiver link"); } } } } await StopWorkersAsync(ct).ConfigureAwait(false); _cts?.Dispose(); _cts = null; _drain.Dispose(); _logger ??= (_endpoint.Component as ComponentBase)?.Logger; _logger?.LogInformation("AMQP consumer stopped: address={Address}", _address); } /// Awaits every worker loop and closes its receiver + dedicated session. private async Task StopWorkersAsync(CancellationToken ct) { foreach (var w in _workers) { if (w.Loop != null) { try { await w.Loop.ConfigureAwait(false); } catch (OperationCanceledException) { /* expected */ } catch (Exception ex) { _logger?.LogDebug(ex, "AMQP worker loop faulted during stop"); } } if (w.Receiver is { IsClosed: false }) { try { await w.Receiver.CloseAsync().ConfigureAwait(false); } catch (Exception ex) { _logger?.LogDebug(ex, "Error closing AMQP receiver link during stop"); } } if (w.Session is { IsClosed: false }) { try { await w.Session.CloseAsync().ConfigureAwait(false); } catch (Exception ex) { _logger?.LogDebug(ex, "Error closing AMQP worker session during stop"); } } _endpoint.Unsupervise(w.Supervisor); } _workers.Clear(); } // ── Receive loop ── private async Task ReceiveLoopAsync(Worker worker, CancellationToken ct) { var receiveTimeout = _options.ReceiveTimeout > 0 ? TimeSpan.FromSeconds(_options.ReceiveTimeout) : TimeSpan.FromSeconds(60); while (!ct.IsCancellationRequested) { // A link the broker closed, or lost with the connection under it, is attached again on the schedule. var receiver = worker.Receiver; if (receiver is null or { IsClosed: true }) { if (!await ReattachAsync(worker, ct).ConfigureAwait(false)) break; continue; } AmqpMessage? msg = null; try { msg = await receiver.ReceiveAsync(receiveTimeout).ConfigureAwait(false); if (msg == null) continue; _drain.Increment(); try { await ProcessMessageAsync(worker, msg, _drain.ProcessingToken).ConfigureAwait(false); } finally { _drain.Decrement(); } } catch (OperationCanceledException) when (ct.IsCancellationRequested) { break; } catch (AmqpException ex) when (ct.IsCancellationRequested) { _logger?.LogDebug(ex, "AMQP receive cancelled during shutdown"); break; } catch (Exception ex) when (ex is AmqpException || receiver.IsClosed) { // The link went away under the receive: not an error of a message. A detach is thrown while the link is // still closing (IsClosed is not yet set, and a receive throws again at once), so the loop does not wait // for IsClosed: it reports the loss to the supervisor and attaches the link again now. _logger?.LogDebug(ex, "AMQP receive ended with the link closed: address={Address}", _address); if (!await ReattachAsync(worker, ct).ConfigureAwait(false)) break; } catch (Exception ex) { // Transport-level failure - invisible to the core's statistics wrappers, so the // endpoint records it itself. Pipeline errors stay with StatisticsProcessor. _endpoint.RecordError(ex); _logger?.LogError(ex, "Error in AMQP receive loop: address={Address}", _address); if (msg != null && receiver is { IsClosed: false }) { try { receiver.Release(msg); } catch (Exception relEx) { _logger?.LogWarning(relEx, "AMQP: failed to release message after error"); } } } } } private async Task ProcessMessageAsync(Worker worker, AmqpMessage msg, CancellationToken ct) { using var span = StartConsumerSpan(msg); var exchange = CreateExchange(msg); var receiver = worker.Receiver; var session = worker.Session; if (receiver is null or { IsClosed: true } || session is null) { _logger?.LogWarning("AMQP: receiver closed before message could be processed"); return; } // The delivery is settled by this consumer once the whole unit of work ended well, not by the route // transaction: the transaction owns the database and the outgoing sends. var ackAction = new AmqpAckAction(receiver, msg, _logger); // ackMode=auto: settled on receipt, before the route runs; a failure below does not bring it back. if (_options.AckMode == AckMode.Auto) await ackAction.Commit(ct).ConfigureAwait(false); var pipelineFailed = false; try { try { await _processor.Process(exchange, ct).ConfigureAwait(false); exchange.ThrowIfUnhandledFailure(); } catch { pipelineFailed = true; throw; } // RPC reply, unless disableReplyTo if (!_options.DisableReplyTo && !string.IsNullOrEmpty(msg.Properties?.ReplyTo)) { await SendReplyAsync(session, exchange, msg.Properties.ReplyTo, msg.Properties.CorrelationId?.ToString()) .ConfigureAwait(false); } // Accept (settle) the message // Settle through the ack action: a route-level .Transacted() may already have accepted it (Settled). if (_options.AckMode == AckMode.Manual && !ackAction.Settled && receiver is { IsClosed: false }) { await ackAction.Commit(ct).ConfigureAwait(false); } Interlocked.Increment(ref _processedCount); } 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); // A pipeline failure is already counted by the core's StatisticsProcessor; a settle // failure AFTER a successful pipeline is invisible to the core, so the transport // records it. if (!pipelineFailed) _endpoint.RecordError(ex); _logger?.LogError(ex, "AMQP message processing error: address={Address}, messageId={MessageId}", _address, msg.Properties?.MessageId); if (receiver is { IsClosed: false }) { try { await ackAction.Rollback(ct).ConfigureAwait(false); } catch (Exception releaseEx) { _logger?.LogWarning(releaseEx, "Error releasing AMQP message"); } } } finally { await exchange.DisposeAsync().ConfigureAwait(false); } } // ── Trace context propagation ── private TransportSpan StartConsumerSpan(AmqpMessage msg) { var span = RouteTelemetryExtensions.StartConsumerSpan( (_endpoint.Component as ComponentBase)?.Context, $"{_address} receive", ActivityKind.Consumer, "messaging.system", "amqp", _endpoint.Uri.NormalizedKey, msg.ApplicationProperties?.Map, static (map, name) => map is not null && map.TryGetValue(name, out var raw) ? raw?.ToString() : null, destination: _address, operation: "receive"); if (span.Activity is { IsAllDataRequested: true } activity) { if (msg.Properties?.MessageId is { } msgId) activity.SetTag("messaging.message.id", msgId); if (msg.Properties?.Subject is { } subject) activity.SetTag("messaging.amqp.subject", subject); } return span; } // ── Exchange creation ── private Exchange CreateExchange(AmqpMessage msg) { var routeMsg = new RouteMessage(); var exchange = Exchange.Create(routeMsg, _endpoint.ScopeFactory); FillMessage(msg, routeMsg, exchange); // A delivery with a reply-to is a request, unless disableReplyTo (Camel's) says to ignore reply-to. exchange.Pattern = !_options.DisableReplyTo && !string.IsNullOrEmpty(msg.Properties?.ReplyTo) ? ExchangePattern.InOut : ExchangePattern.InOnly; return exchange; } /// One delivery as an element of a batch, built as a single delivery's message is. private RouteMessage ToMessage(AmqpMessage msg, IExchange batch) { var routeMsg = new RouteMessage(); FillMessage(msg, routeMsg, batch); return routeMsg; } /// The body and headers of a delivery: application properties as the strategy lets them in, the AMQP properties. private void FillMessage(AmqpMessage msg, RouteMessage routeMsg, IExchange exchange) { routeMsg.Body = AmqpMessageHelper.ExtractBody(msg); AmqpMessageHelper.CopyApplicationProperties(msg, routeMsg, _headerFilter, exchange); // Standard AMQP properties → bare header names (self-documenting, round-trip via the producer); // transport metadata (Address/DeliveryCount/FirstAcquirer) → redbAmqp.* (no standard name). routeMsg.Headers[AmqpHeaders.Address] = _address; if (msg.Properties != null) { if (msg.Properties.MessageId != null) routeMsg.Headers[AmqpHeaders.MessageId] = msg.Properties.MessageId.ToString()!; if (msg.Properties.CorrelationId != null) routeMsg.Headers[AmqpHeaders.CorrelationId] = msg.Properties.CorrelationId.ToString()!; if (!string.IsNullOrEmpty(msg.Properties.ReplyTo)) routeMsg.Headers[AmqpHeaders.ReplyTo] = msg.Properties.ReplyTo; if (!string.IsNullOrEmpty(msg.Properties.ContentType)) { routeMsg.Headers[AmqpHeaders.ContentType] = msg.Properties.ContentType; routeMsg.ContentType = msg.Properties.ContentType; } if (!string.IsNullOrEmpty(msg.Properties.Subject)) routeMsg.Headers[AmqpHeaders.Subject] = msg.Properties.Subject; if (!string.IsNullOrEmpty(msg.Properties.GroupId)) routeMsg.Headers[AmqpHeaders.GroupId] = msg.Properties.GroupId; if (msg.Properties.GroupSequence > 0) routeMsg.Headers[AmqpHeaders.GroupSequence] = msg.Properties.GroupSequence; if (msg.Properties.CreationTime != default) routeMsg.Headers[AmqpHeaders.CreationTime] = msg.Properties.CreationTime; if (msg.Properties.AbsoluteExpiryTime != default) routeMsg.Headers[AmqpHeaders.AbsoluteExpiryTime] = msg.Properties.AbsoluteExpiryTime; if (!string.IsNullOrEmpty(msg.Properties.ContentEncoding)) routeMsg.Headers[AmqpHeaders.ContentEncoding] = msg.Properties.ContentEncoding; if (!string.IsNullOrEmpty(msg.Properties.To)) routeMsg.Headers[AmqpHeaders.To] = msg.Properties.To; if (!string.IsNullOrEmpty(msg.Properties.ReplyToGroupId)) routeMsg.Headers[AmqpHeaders.ReplyToGroupId] = msg.Properties.ReplyToGroupId; if (msg.Properties.UserId is { Length: > 0 } userId) routeMsg.Headers[AmqpHeaders.UserId] = System.Text.Encoding.UTF8.GetString(userId); } if (msg.Header != null) { routeMsg.Headers[AmqpHeaders.Durable] = msg.Header.Durable; routeMsg.Headers[AmqpHeaders.Priority] = msg.Header.Priority; if (msg.Header.Ttl > 0) routeMsg.Headers[AmqpHeaders.Ttl] = msg.Header.Ttl; routeMsg.Headers[AmqpHeaders.DeliveryCount] = msg.Header.DeliveryCount; routeMsg.Headers[AmqpHeaders.FirstAcquirer] = msg.Header.FirstAcquirer; } } // ── RPC reply ── private async Task SendReplyAsync(Session session, IExchange exchange, string replyTo, string? correlationId) { try { var responseBody = exchange.HasOut ? exchange.Out!.Body : exchange.In.Body; object wireBody = responseBody switch { byte[] bytes => (object)bytes, string str => str, null => Array.Empty(), var other => other.ToString() ?? string.Empty }; var reply = new AmqpMessage(wireBody) { Properties = new Properties { ContentType = exchange.In.ContentType ?? _options.ContentType } }; if (!string.IsNullOrEmpty(correlationId)) reply.Properties.CorrelationId = correlationId; // Response headers → application-properties, as the endpoint's strategy lets them out var responseHeaders = exchange.HasOut ? exchange.Out!.Headers : exchange.In.Headers; var appProps = new ApplicationProperties(); foreach (var (key, value) in responseHeaders) { if (value is null) continue; if (_headerFilter.FilterOutgoing(key, value, exchange)) continue; appProps[key] = value switch { string s => s, int or long or float or double or bool => value, _ => value.ToString()! }; } if (appProps.Map.Count > 0) reply.ApplicationProperties = appProps; // Reply on the WORKER's own session (never the shared endpoint session) — each worker // runs on its own AMQP session, so concurrent replies never race on a shared session. var replySender = new SenderLink( session, $"reply-sender-{Guid.NewGuid():N}", replyTo); // Bounded send timeout: a dead reply address (client gone, queue removed) // must not block the consumer slot indefinitely. The original message will // still be accepted by the caller — the client will see its own RPC timeout. var sendTimeout = TimeSpan.FromSeconds(_options.ReplyTimeout > 0 ? _options.ReplyTimeout : 2); await replySender.SendAsync(reply, sendTimeout).ConfigureAwait(false); try { await replySender.CloseAsync(TimeSpan.FromSeconds(2)).ConfigureAwait(false); } catch (Exception closeEx) { _logger?.LogWarning(closeEx, "AMQP: error closing reply sender, forcing close"); replySender.Close(TimeSpan.Zero); } _logger?.LogDebug("AMQP RPC reply sent: replyTo={ReplyTo}, correlationId={CorrelationId}", replyTo, correlationId); } catch (Exception ex) { // Swallow: failed reply must not prevent accepting the original message. // Client will detect failure via its own RPC timeout. _logger?.LogWarning(ex, "AMQP: failed to send RPC reply to {ReplyTo} (correlationId={CorrelationId}) — original message will still be accepted", replyTo, correlationId); } } } /// Deferred AMQP acknowledgement action. internal sealed class AmqpAckAction : ITransactedAction { private int _settled; /// True once the delivery was accepted or released, by either the deferred (transaction) or the inline path. public bool Settled => Volatile.Read(ref _settled) == 1; private readonly ReceiverLink _receiver; private readonly AmqpMessage _msg; private readonly ILogger? _logger; public AmqpAckAction(ReceiverLink receiver, AmqpMessage msg, ILogger? logger) { _receiver = receiver; _msg = msg; _logger = logger; } /// public Task Commit(CancellationToken ct = default) { if (Interlocked.Exchange(ref _settled, 1) != 0) return Task.CompletedTask; _receiver.Accept(_msg); _logger?.LogDebug("AMQP ack committed"); return Task.CompletedTask; } /// /// Gives the delivery back as a failed one: the modified outcome with delivery-failed, so the broker /// counts the attempt and a message that always fails ends at its maximum delivery count (Artemis moves it to the /// dead letter address). The released outcome is not counted, and such a message would come back without end. /// public Task Rollback(CancellationToken ct = default) { if (Interlocked.Exchange(ref _settled, 1) != 0) return Task.CompletedTask; _receiver.Modify(_msg, deliveryFailed: true); _logger?.LogDebug("AMQP nack (modified, delivery-failed)"); return Task.CompletedTask; } } 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)); } } Path: redb-route/redb.Route.Amqp/AmqpEndpointOptions.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/AmqpEndpointOptions.cs ---- using redb.Route.Abstractions; using redb.Route.Batching; using redb.Route.Core; using AmqpSymbol = global::Amqp.Types.Symbol; namespace redb.Route.Amqp; /// /// Endpoint options for AMQP 1.0 transport. All properties are auto-bound from URI query parameters. /// /// URI format: amqp://address?host=broker&port=5672&user=admin&password=admin&... /// /// /// Supports: ActiveMQ Artemis, ActiveMQ Classic, Azure Service Bus, Amazon MQ, Qpid, any AMQP 1.0 broker. /// /// public sealed class AmqpEndpointOptions : EndpointOptions { // ── Connection (override per-endpoint, fallback to component-level factory) ── /// Named connection factory from registry. Takes priority over inline params. [RegistryReference(typeof(AmqpConnectionFactory))] public string? ConnectionFactory { get; set; } /// /// Broker host (default: localhost). In a comma-separated list the connection opens to the first host; the others /// are not tried. /// public string Host { get; set; } = "localhost"; /// /// A registry reference (#name) to an that /// decides which headers this endpoint carries between the exchange and AMQP application-properties (a request, /// a consumed message, a reply both ways), in place of . /// [RegistryReference(typeof(IHeaderFilterStrategy))] public string? HeaderFilterStrategy { get; set; } /// Broker port. (default: 5672) public int Port { get; set; } = 5672; /// SASL username. public string? User { get; set; } /// SASL password. [Sensitive] public string? Password { get; set; } /// Container ID for this connection. public string? ContainerId { get; set; } /// Virtual host / AMQP hostname. public string? VirtualHost { get; set; } /// Enable SSL/TLS. public bool Ssl { get; set; } // ── AMQP terminus (Source/Target) ── /// /// Terminus durability: 0 = none, 1 = configuration, 2 = unsettled-state. /// Maps to Source.Durable / Target.Durable. (default: 0) /// public uint Durable { get; set; } /// /// Expiry policy for the terminus: link-detach, session-end, connection-close, never. (default: session-end) /// public string ExpiryPolicy { get; set; } = "session-end"; /// Terminus timeout in seconds. (default: 0) public uint TerminusTimeout { get; set; } /// Distribution mode for the source: move or copy. (default: move) public string? DistributionMode { get; set; } /// Create dynamic terminus (broker assigns name). (default: false) public bool Dynamic { get; set; } /// /// JMS/AMQP selector filter expression. Applied as a Source filter. /// Example: color='red' AND weight > 10 /// public string? FilterSelector { get; set; } /// /// Terminus capabilities. Comma-separated AMQP symbols. /// Examples: topic, queue, shared, global. /// Artemis uses these to distinguish address types. /// public string? Capabilities { get; set; } // ── Link settlement ── /// /// Sender settle mode: Unsettled (0), Settled (1), Mixed (2). (default: Mixed) /// Controls at-most-once vs at-least-once delivery for producers. /// public int SenderSettleMode { get; set; } = 2; /// /// Receiver settle mode: First (0 = auto-ack), Second (1 = explicit ack). (default: First) /// public int ReceiverSettleMode { get; set; } // ── Consumer ── /// Link credit (prefetch). How many messages the broker can send before ack. (default: 100) public int Credit { get; set; } = 100; /// /// When a delivery is settled (). Manual (default): accepted after a turn that ended /// well, released for redelivery on failure (at-least-once). Auto: accepted on receipt, before the route runs /// (at-most-once). /// public AckMode AckMode { get; set; } = AckMode.Manual; /// protected override string? UnknownParameterHint(string name) => name.Equals("autoAccept", StringComparison.OrdinalIgnoreCase) ? "'autoAccept' is replaced by 'ackMode': ackMode=manual (the default) accepts after the route, as autoAccept=true did; " + "ackMode=auto accepts on receipt. autoAccept=false left every delivery unsettled, with nothing to settle it." : null; /// Concurrent consumer workers: a number or "auto" (= max(CPU, 2)). Default 1 (serial, ordering preserved). // A string so "auto" binds verbatim instead of silently degrading to the int default. public string? ConcurrentConsumers { get; set; } /// Resolved consumer parallelism (see ). public int ResolvedConcurrentConsumers => ConcurrencyOption.Resolve(ConcurrentConsumers, "concurrentConsumers"); /// Consumer receive timeout in seconds. 0 = infinite wait. (default: 60) public int ReceiveTimeout { get; set; } = 60; /// /// The consumer ignores a delivery's reply-to (Apache Camel disableReplyTo): the exchange is InOnly and no reply /// is sent. In batch mode such a delivery then goes into the batch instead of being rejected. /// public bool DisableReplyTo { get; set; } // ── Batch mode ── /// /// Batch mode (Apache Camel batching): the route gets one InOnly exchange whose body is a /// List<IMessage> of up to deliveries of one receiver link, settled once /// after the route: accepted on success, released for redelivery on failure, as a single delivery is. /// public bool Batching { get; set; } /// Largest number of deliveries in a batch (default ). At most . public int? MaxBatchMessages { get; set; } /// /// Batch mode: a batch with deliveries is sent on once no delivery came for this many milliseconds, restarted by /// every delivery (default 1000). /// public int PollTimeoutMs { get; set; } = 1000; /// Batch mode: a batch is sent on once this many milliseconds have passed since its first delivery. public int? BatchingIntervalMs { get; set; } /// The batch options, or null outside batch mode. Set by . internal BatchOptions? Batch { get; private set; } /// /// Resolves the batch options. Fails, naming the endpoint, where batch mode cannot work: a batch option without /// batching=true, a value out of range, a batch larger than (the broker sends no more /// unsettled deliveries than the link's credit), and an endpoint configured for request-reply (a batch is InOnly). /// internal void ResolveBatch(string endpoint) { Batch = BatchOptions.Resolve(endpoint, Batching, MaxBatchMessages, PollTimeoutMs, BatchingIntervalMs, Credit); if (Batch is null) return; if (Batch.MaxMessages > Credit) throw new InvalidOperationException( $"Endpoint '{endpoint}': maxBatchMessages={Batch.MaxMessages} is larger than credit={Credit}; the broker " + "never sends more unsettled deliveries than the link's credit, so such a batch would only ever close by its " + "timeout. Raise credit, or lower maxBatchMessages."); if (ReplyTo) throw new InvalidOperationException( $"Endpoint '{endpoint}': batching=true cannot be combined with replyTo=true: a batch is one-way (InOnly) " + "and nobody would answer a request in it."); } // ── Producer: message defaults ── /// Set AMQP header.durable on outgoing messages. (default: true) public bool MessageDurable { get; set; } = true; /// Default message priority (0–9). (default: 4) public byte MessagePriority { get; set; } = 4; /// Message priority as expression (e.g. ${body['priority']}). Resolved at runtime, overrides if set. public string? MessagePriorityExpression { get; set; } /// Default message TTL in milliseconds. 0 = no expiry. public uint MessageTtl { get; set; } /// Message TTL as expression (e.g. ${body['ttl']}). Resolved at runtime, overrides if set. public string? MessageTtlExpression { get; set; } /// Default content-type for outgoing messages. (default: text/plain) public string ContentType { get; set; } = "text/plain"; /// AMQP subject/routing property on outgoing messages. public string? Subject { get; set; } /// AMQP group-id for message grouping. public string? GroupId { get; set; } /// Enable request/reply pattern (creates temp reply-to address). (default: false) public bool ReplyTo { get; set; } /// /// Apache Camel preserveMessageQos: an ordinary (not request-reply) send keeps the ReplyTo and /// ReplyToGroupId headers as the message's reply-to. Off by default, as in Camel's JMS: a message consumed with a /// sender's reply-to and forwarded to this endpoint does not carry that reply-to on, so no consumer answers into an /// address of another system. The correlation id is always carried. /// public bool PreserveMessageQos { get; set; } /// /// Request/reply timeout in seconds; with it also bounds each step of a transaction /// (declare, every send, discharge). (default: 30) /// public int Timeout { get; set; } = 30; /// /// Send-side timeout (seconds) for the consumer's RPC reply SenderLink.SendAsync. /// Kept short on purpose: if the originating client has gone away its reply address is /// dead, and a long send timeout would block the consumer slot. (default: 2) /// public int ReplyTimeout { get; set; } = 2; // ── Transacted ── /// /// Producer: whether the send joins the enclosing .Transacted() block. Unset, it follows the block: deferred /// until the database commits inside one, sent at once outside. true requires a block and fails outside one; /// false sends at once even inside one, outside the block's transaction. A request-reply producer /// () always sends at once and refuses true. /// public bool? Transacted { get; set; } /// /// Producer: the sends it defers in a .Transacted() block commit in one AMQP local transaction when the block /// commits — a coordinator link declares it, the sends carry it, one discharge commits it — so they arrive together /// or not at all; a rejected send, or any failure before the discharge, discharges it as failed. The broker must /// support AMQP local transactions (ActiveMQ Artemis, Qpid, Azure Service Bus; not RabbitMQ's AMQP 1.0 plugin): one /// that refuses the coordinator fails the commit. Unset, the deferred sends go out one after the other. /// public bool LocalTransactions { get; set; } // ── Topology ── /// /// Declare the address on the broker if it doesn't exist. Requires broker support. /// Artemis auto-creates by default. (default: false) /// public bool Declare { get; set; } /// /// Routing type for Artemis: ANYCAST (queue semantics) or MULTICAST (topic semantics). /// Mapped to capabilities. (default: ANYCAST) /// public string RoutingType { get; set; } = "ANYCAST"; /// public override void Validate() { if (Port is < 1 or > 65535) throw new ArgumentException($"AMQP port must be 1–65535, got: {Port}"); if (Credit < 0) throw new ArgumentException($"AMQP credit (prefetch) must be >= 0, got: {Credit}"); _ = ConcurrencyOption.Resolve(ConcurrentConsumers, "concurrentConsumers"); // loud on garbage if (SenderSettleMode is < 0 or > 2) throw new ArgumentException($"SenderSettleMode must be 0–2, got: {SenderSettleMode}"); if (ReceiverSettleMode is < 0 or > 1) throw new ArgumentException($"ReceiverSettleMode must be 0–1, got: {ReceiverSettleMode}"); if (Durable > 2) throw new ArgumentException($"Durable must be 0–2, got: {Durable}"); // A typo must fail at endpoint creation, not silently at terminus build time. ResolveExpiryPolicy(); if (LocalTransactions && ReplyTo) throw new ArgumentException( "'localTransactions' commits deferred sends, and a request-reply producer (replyTo=true) never defers " + "one: its request has to leave at once for the reply to come. Drop one of the two."); if (LocalTransactions && Transacted == false) throw new ArgumentException( "'localTransactions' commits the sends deferred in a .Transacted() block, and 'transacted=false' sends at " + "once, deferring none. Drop one of the two."); } /// /// Resolves the terminus capabilities as an array of AMQP symbols. /// Combines explicit Capabilities with RoutingType for Artemis compatibility. /// internal string[] ResolveCapabilities() { var caps = new List(); if (!string.IsNullOrEmpty(Capabilities)) { caps.AddRange(Capabilities.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)); } // Artemis routing type as capability if (!string.IsNullOrEmpty(RoutingType)) { var rt = RoutingType.ToUpperInvariant() switch { "ANYCAST" => "queue", "MULTICAST" => "topic", _ => RoutingType.ToLowerInvariant() }; if (!caps.Contains(rt, StringComparer.OrdinalIgnoreCase)) caps.Add(rt); } return caps.ToArray(); } /// /// Maps the ExpiryPolicy string to the AMQP symbol value. A typo throws instead of silently /// becoming session-end — on a durable subscription that silent fallback meant the broker /// dropped the subscription between restarts. /// internal AmqpSymbol ResolveExpiryPolicy() { return ExpiryPolicy.ToLowerInvariant() switch { "link-detach" => new AmqpSymbol("link-detach"), "session-end" => new AmqpSymbol("session-end"), "connection-close" => new AmqpSymbol("connection-close"), "never" => new AmqpSymbol("never"), _ => throw new ArgumentException( $"Invalid value '{ExpiryPolicy}' for option 'expiryPolicy'. " + "Valid values: link-detach, session-end, connection-close, never.") }; } } Path: redb-route/redb.Route.Amqp/AmqpHeaderFilterStrategy.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/AmqpHeaderFilterStrategy.cs ---- using redb.Route.Abstractions; namespace redb.Route.Amqp; /// /// The default of the AMQP 1.0 component, Apache Camel's /// AmqpHeaderFilterStrategy counterpart. An endpoint's headerFilterStrategy=#name replaces it; derive /// from it to add to it. /// /// A producer's request and a consumer's reply carry every exchange header but the component's own /// redbAmqp.* and null values as application-properties; a consumed message and a request-reply's reply bring /// every application-property in. Whatever the strategy, a producer sends the standard AMQP property names /// (MessageId, CorrelationId, Subject...) as those properties, not as application-properties, /// the consumer sets the standard properties and the redbAmqp.* delivery metadata by name, and trace context /// is written by the telemetry layer. /// /// public class AmqpHeaderFilterStrategy : IHeaderFilterStrategy { /// The default strategy of an AMQP endpoint. public static AmqpHeaderFilterStrategy Default { get; } = new(); /// public virtual bool FilterOutgoing(string name, object? value, IExchange exchange) => value is null || AmqpHeaders.IsRedbHeader(name); /// public virtual bool FilterIncoming(string name, object? value, IExchange exchange) => false; } Path: redb-route/redb.Route.Amqp/AmqpHeaders.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/AmqpHeaders.cs ---- namespace redb.Route.Amqp; /// /// Well-known header constants used by the AMQP 1.0 component. /// Headers prefixed with redbAmqp. carry broker metadata on incoming messages. /// public static class AmqpHeaders { /// Common prefix for redb-specific AMQP envelope headers (transport metadata). public const string Prefix = "redbAmqp."; // ── Standard AMQP 1.0 properties (well-known names → BARE, self-documenting) ── // Sections `Properties` and `Header`. Bare names mean no docs needed and a // consume→produce round-trip carries them through — same convention as the RabbitMQ // component. Caveat: common-word names (Subject/Priority/…) can collide with a // business header of the same name. /// AMQP message-id property. public const string MessageId = "MessageId"; /// AMQP correlation-id property. public const string CorrelationId = "CorrelationId"; /// AMQP reply-to property. public const string ReplyTo = "ReplyTo"; /// AMQP content-type property. public const string ContentType = "ContentType"; /// AMQP content-encoding property. public const string ContentEncoding = "ContentEncoding"; /// AMQP subject property. public const string Subject = "Subject"; /// AMQP to property. public const string To = "To"; /// AMQP user-id property (binary on the wire). public const string UserId = "UserId"; /// AMQP group-id property. public const string GroupId = "GroupId"; /// AMQP group-sequence property. public const string GroupSequence = "GroupSequence"; /// AMQP reply-to-group-id property. public const string ReplyToGroupId = "ReplyToGroupId"; /// AMQP creation-time property. public const string CreationTime = "CreationTime"; /// AMQP absolute-expiry-time property. public const string AbsoluteExpiryTime = "AbsoluteExpiryTime"; /// Whether the message is durable (header.durable). public const string Durable = "Durable"; /// Message priority (header.priority). public const string Priority = "Priority"; /// TTL in milliseconds (header.ttl). public const string Ttl = "Ttl"; // ── Envelope / transport metadata (no standard property name → redb-prefixed, read-only) ── /// AMQP address the message was received from. public const string Address = "redbAmqp.Address"; /// Delivery count (header.delivery-count). public const string DeliveryCount = "redbAmqp.DeliveryCount"; /// Whether first-acquirer flag was set. public const string FirstAcquirer = "redbAmqp.FirstAcquirer"; /// Sender settle mode used for this link. public const string SenderSettleMode = "redbAmqp.SenderSettleMode"; /// Receiver settle mode used for this link. public const string ReceiverSettleMode = "redbAmqp.ReceiverSettleMode"; /// Returns true if the header key belongs to the AMQP component. public static bool IsRedbHeader(string key) => key.StartsWith(Prefix, StringComparison.OrdinalIgnoreCase); } Path: redb-route/redb.Route.Amqp/AmqpMessageHelper.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/AmqpMessageHelper.cs ---- using System.Text; using Amqp; using Amqp.Framing; using redb.Route.Abstractions; using AmqpMessage = global::Amqp.Message; namespace redb.Route.Amqp; /// /// Helpers for AMQP message body extraction and property mapping. /// internal static class AmqpMessageHelper { /// /// Extracts the body from an AMQP message as raw bytes or string. /// Handles: string, byte[], Data section, AmqpValue section. /// public static object ExtractBody(AmqpMessage message) { return message.Body switch { byte[] bytes => bytes, Data data => data.Binary, string s => Encoding.UTF8.GetBytes(s), AmqpValue value => Encoding.UTF8.GetBytes(value.Value?.ToString() ?? string.Empty), null => Array.Empty(), _ => Encoding.UTF8.GetBytes(message.Body.ToString() ?? string.Empty) }; } /// /// Copies the AMQP application-properties that lets in into a redb.Route message's /// headers; is the one they come into (for a request-reply's reply, the request's). /// public static void CopyApplicationProperties(AmqpMessage amqpMessage, redb.Route.Core.Message routeMessage, IHeaderFilterStrategy headerFilter, IExchange exchange) { if (amqpMessage.ApplicationProperties?.Map == null) return; foreach (var kvp in amqpMessage.ApplicationProperties.Map) { var key = kvp.Key?.ToString(); if (string.IsNullOrEmpty(key)) continue; object? value = kvp.Value switch { byte[] bytes => Encoding.UTF8.GetString(bytes), string str => str, _ => kvp.Value }; if (value is null) continue; if (headerFilter.FilterIncoming(key, value, exchange)) continue; routeMessage.Headers[key] = value; } } } Path: redb-route/redb.Route.Amqp/AmqpProducer.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/AmqpProducer.cs ---- using System.Collections.Concurrent; using System.Diagnostics; using System.Text; using System.Transactions; using Amqp; using Amqp.Framing; using Amqp.Transactions; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Transactions; using redb.Route.Core; using redb.Route.Telemetry; using AmqpMessage = global::Amqp.Message; using RouteMessage = redb.Route.Core.Message; namespace redb.Route.Amqp; /// /// AMQP 1.0 producer. Sends messages via a with support for: /// /// Immediate — direct send via SenderLink.SendAsync. /// Transactional — deferred send via . /// RPC — request/reply with a temporary dynamic receiver link. /// /// public sealed class AmqpProducer : ConnectableProducer { private readonly AmqpEndpoint _endpoint; private readonly AmqpEndpointOptions _options; /// Bare names of standard AMQP properties — excluded from the application-properties bulk copy. private static readonly HashSet StandardPropertyNames = new(StringComparer.OrdinalIgnoreCase) { "MessageId", "CorrelationId", "ReplyTo", "ContentType", "ContentEncoding", "Subject", "To", "UserId", "GroupId", "GroupSequence", "ReplyToGroupId", "CreationTime", "AbsoluteExpiryTime", "Durable", "Priority", "Ttl" }; private SenderLink? _sender; // ── Local transactions (localTransactions=true) ── // The client's own transaction support goes through System.Transactions, and its discharge never got an answer from // the broker; driven by hand on the public protocol types — a coordinator // link, Declare, sends carrying TransactionalState, Discharge — the same broker answers at once. One transaction at a // time per producer: they take turns. private readonly SemaphoreSlim _transactionTurn = new(1, 1); private readonly string _batchKey = $"amqp-tx-{Guid.NewGuid():N}"; private SenderLink? _controller; // ── 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 ReceiverLink? _replyReceiver; private string? _replyAddress; private readonly SemaphoreSlim _rpcLock = new(1, 1); private volatile bool _rpcSetup; private CancellationTokenSource? _rpcCts; private Task? _rpcTask; /// Creates an AMQP producer. public AmqpProducer(AmqpEndpoint endpoint, AmqpEndpointOptions 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 => $"amqp:{_endpoint.Address}"; /// protected override async Task ConnectAsync(CancellationToken ct) { _sender = await _endpoint.CreateSenderLinkAsync(ct: ct).ConfigureAwait(false); try { if (_options.ReplyTo) await SetupReplyReceiverAsync(ct).ConfigureAwait(false); } catch (Exception ex) { Logger?.LogError(ex, "AMQP producer ConnectAsync failed for address {Address}", _endpoint.Address); if (_sender is { IsClosed: false }) { try { await _sender.CloseAsync().ConfigureAwait(false); } catch (Exception closeEx) { Logger?.LogWarning(closeEx, "AMQP: error closing sender during ConnectAsync cleanup"); } } _sender = null; throw; } } /// protected override async Task DisconnectAsync(CancellationToken ct) { foreach (var pending in _pendingResponses) pending.Value.Reply.TrySetCanceled(ct); _pendingResponses.Clear(); _rpcCts?.Cancel(); if (_rpcTask != null) { try { await _rpcTask.ConfigureAwait(false); } catch (OperationCanceledException) { } _rpcTask = null; } _rpcCts?.Dispose(); _rpcCts = null; if (_replyReceiver is { IsClosed: false }) { try { await _replyReceiver.CloseAsync().ConfigureAwait(false); } catch (Exception ex) { Logger?.LogDebug(ex, "AMQP: error closing reply receiver during stop"); } } _replyReceiver = null; _replyAddress = null; _rpcSetup = false; if (_controller is { IsClosed: false }) { try { await _controller.CloseAsync().ConfigureAwait(false); } catch (Exception ex) { Logger?.LogDebug(ex, "AMQP: error closing the transaction controller during stop"); } } _controller = null; if (_sender is { IsClosed: false }) { try { await _sender.CloseAsync().ConfigureAwait(false); } catch (Exception ex) { Logger?.LogDebug(ex, "AMQP: error closing sender during stop"); } } _sender = null; } /// public override async Task Process(IExchange exchange, CancellationToken ct = default) { EnsureStarted(); // This connector does not send a list element by element: a list of IMessage is refused with the advice to Split // it, and a plain list has no wire form here. Its text would otherwise be the type name. var inBody = exchange.In.Body; if (ListBody.Messages(inBody) is { } messages) throw new InvalidOperationException( $"Endpoint '{EndpointUri.Sanitize(_endpoint.Uri.BaseKey)}' does not send a list of {messages.Count} messages " + "element by element: Split the list to send each as its own message."); if (ListBody.IsPlainList(inBody)) throw ListBody.PlainListRefusal(EndpointUri.Sanitize(_endpoint.Uri.BaseKey), inBody!); EnsureSender(); using var activity = RouteTelemetryExtensions.StartTransportSpan( (_endpoint.Component as ComponentBase)?.Context, $"{_endpoint.Address} publish", ActivityKind.Producer, "messaging.system", "amqp", _endpoint.Uri.NormalizedKey, destination: _endpoint.Address, operation: "publish"); var msg = PrepareMessage(exchange); if (activity is { IsAllDataRequested: true } && msg.Properties?.Subject is { } subject) activity.SetTag("messaging.amqp.subject", subject); // The context of this send, over a traceparent the header bridge copied from a received message; with // tracing off, the context that came in. The application-properties section is created only to hold it. RouteTelemetryExtensions.InjectTraceContext(activity, msg, static (m, name, value) => (m.ApplicationProperties ??= new ApplicationProperties()).Map[name] = value); if (!_options.ReplyTo && TransactedActions.Defers(exchange, _options.Transacted)) { ProcessTransactional(exchange, msg); return; } // The AMQP client enlists a send in the ambient System.Transactions transaction on its own. A send that goes out // at once (transacted=false, request-reply, or no enclosing block) must not: it would wait for the block's commit, // and next to a database in the same block it would escalate the transaction to a distributed one. using (new TransactionScope(TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled)) { try { if (_options.ReplyTo) await ProcessRpcAsync(exchange, msg, ct).ConfigureAwait(false); else await ProcessImmediateAsync(msg, ct).ConfigureAwait(false); } catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested) { activity.RecordFailure(ex); throw; } } } // ── Immediate send ── private async Task ProcessImmediateAsync(AmqpMessage msg, CancellationToken ct) { await _sender!.SendAsync(msg).ConfigureAwait(false); // Wire-level bytes are the connector's to record: the core's ToProcessor counts // MessagesOut/Errors for a routed producer but has no idea of payload sizes. var payload = PayloadSize(msg); if (payload > 0) _endpoint.RecordBytesOut(payload); Logger?.LogDebug("AMQP immediate send: address={Address}", _endpoint.Address); } /// /// Payload size of an outgoing message. Checked against the BODY SECTION: AMQPNetLite's /// Message.Body getter unwraps a Data section to its byte[] and our own /// builds an AmqpValue - so the old /// msg.Body is Data pattern was never true and BytesOut stayed at zero forever. /// private static int PayloadSize(AmqpMessage msg) => msg.BodySection switch { Data { Binary.Length: > 0 } d => d.Binary.Length, AmqpValue { Value: byte[] b } => b.Length, AmqpValue { Value: string s } => System.Text.Encoding.UTF8.GetByteCount(s), _ => 0, }; // ── Transactional deferred send ── private void ProcessTransactional(IExchange exchange, AmqpMessage msg) { var cloned = CloneMessage(msg); if (_options.LocalTransactions) { // The block's sends through this producer commit in one AMQP local transaction when the block commits. TransactedActions.JoinBatch(exchange, _batchKey, () => new AmqpTransactionBatch(this), ProducerName).Add(cloned); return; } var action = new AmqpSendAction(_sender!, cloned, _endpoint.Address, Logger); TransactedActions.Register(exchange, $"amqp-send-{Guid.NewGuid():N}", action, ProducerName); } // ── Local transaction ── /// /// Sends in one AMQP local transaction: declare, send each carrying the transaction id, /// discharge. A send the broker does not accept, or any failure before the discharge, discharges the transaction as /// failed, so none of them is delivered, and propagates. /// internal async Task CommitTransactionAsync(IReadOnlyList messages, CancellationToken ct) { await _transactionTurn.WaitAsync(ct).ConfigureAwait(false); try { var sender = _sender is { IsClosed: false } live ? live : throw new InvalidOperationException( $"'{ProducerName}' is stopped or its link is closed: the transaction cannot be committed."); var controller = Controller(sender); var txnId = await DeclareAsync(controller).ConfigureAwait(false); try { foreach (var message in messages) { var outcome = await SendAsync(sender, message, new TransactionalState { TxnId = txnId }).ConfigureAwait(false); if (!IsAccepted(outcome)) throw new InvalidOperationException( $"AMQP broker did not accept a send to '{_endpoint.Address}' in the transaction: {Describe(outcome)}."); } var committed = await SendAsync(controller, Control(new Discharge { TxnId = txnId, Fail = false }), null) .ConfigureAwait(false); if (!IsAccepted(committed)) throw new InvalidOperationException( $"AMQP broker did not commit the transaction on '{_endpoint.Address}': {Describe(committed)}."); } catch (Exception failure) { await DischargeAsFailedAsync(controller, txnId, failure).ConfigureAwait(false); throw; } foreach (var message in messages) { var payload = PayloadSize(message); if (payload > 0) _endpoint.RecordBytesOut(payload); } Logger?.LogDebug("AMQP local transaction committed: address={Address}, messages={Count}", _endpoint.Address, messages.Count); } finally { _transactionTurn.Release(); } } /// The link to the broker's transaction coordinator, on the session the sends go through. private SenderLink Controller(SenderLink sender) { if (_controller is { IsClosed: false } controller && ReferenceEquals(controller.Session, sender.Session)) return controller; _controller = new SenderLink(sender.Session, $"txn-controller-{_endpoint.Address}-{Guid.NewGuid():N}", new Attach { Source = new Source(), Target = new Coordinator { Capabilities = [TxnCapabilities.LocalTransactions], }, }, null); return _controller; } private async Task DeclareAsync(SenderLink controller) { Outcome declared; try { declared = await SendAsync(controller, Control(new Declare()), null).ConfigureAwait(false); } catch (Exception ex) when (controller.IsClosed) { throw new InvalidOperationException( $"AMQP broker for '{_endpoint.Address}' refused the transaction coordinator ({controller.Error?.Description ?? ex.Message}): " + "localTransactions needs a broker with AMQP local transactions (ActiveMQ Artemis, Qpid, Azure Service Bus).", ex); } return declared is Declared { TxnId: { } txnId } ? txnId : throw new InvalidOperationException( $"AMQP broker for '{_endpoint.Address}' did not declare a transaction: {Describe(declared)}."); } private async Task DischargeAsFailedAsync(SenderLink controller, byte[] txnId, Exception failure) { try { await SendAsync(controller, Control(new Discharge { TxnId = txnId, Fail = true }), null).ConfigureAwait(false); } catch (Exception dischargeFailure) { // Nothing was committed either way: the broker drops an undischarged transaction with the link. Logger?.LogWarning(dischargeFailure, "AMQP: discharging the failed transaction on {Address} failed too (the original failure: {Failure})", _endpoint.Address, failure.Message); } } /// /// One step of the transaction, bounded by timeout: a broker that withholds credit (Artemis on a full address) /// or never settles fails the step instead of holding the block's commit. /// private Task SendAsync(SenderLink link, AmqpMessage message, DeliveryState? state) { var outcome = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); link.Send(message, state, (_, _, result, _) => outcome.TrySetResult(result), null); return outcome.Task.WaitAsync(TimeSpan.FromSeconds(_options.Timeout)); } private static AmqpMessage Control(object body) => new() { BodySection = new AmqpValue { Value = body } }; /// The client hands the outcome of a transactional send over unwrapped from its TransactionalState. private static bool IsAccepted(Outcome? outcome) => outcome is Accepted; private static string Describe(Outcome? outcome) => outcome switch { Rejected { Error: { } error } => $"rejected ({error.Condition}: {error.Description})", null => "no outcome", _ => outcome.ToString() ?? outcome.GetType().Name, }; // ── RPC (request/reply) ── private async Task ProcessRpcAsync(IExchange exchange, AmqpMessage msg, CancellationToken ct) { if (!_rpcSetup) await SetupReplyReceiverAsync(ct).ConfigureAwait(false); var correlationId = Guid.NewGuid().ToString(); msg.Properties.CorrelationId = correlationId; msg.Properties.ReplyTo = _replyAddress; msg.Properties.ReplyToGroupId = null; // the reply is this producer's, never a forwarded group's var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); _pendingResponses[correlationId] = new PendingReply(tcs, exchange); try { await _sender!.SendAsync(msg).ConfigureAwait(false); Logger?.LogDebug("AMQP RPC request sent: correlationId={CorrelationId}, replyTo={ReplyTo}", correlationId, _replyAddress); 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(correlationId, out _); throw new TimeoutException( $"AMQP RPC timeout ({_options.Timeout}s): address={_endpoint.Address}"); } var response = await responseTask.ConfigureAwait(false); exchange.Out = response; exchange.Pattern = ExchangePattern.InOut; Logger?.LogDebug("AMQP RPC response received: correlationId={CorrelationId}", correlationId); } catch (Exception ex) when (ex is not OperationCanceledException) { Logger?.LogError(ex, "AMQP RPC timeout/error: address={Address}, correlationId={CorrelationId}", _endpoint.Address, correlationId); _pendingResponses.TryRemove(correlationId, out _); throw; } } // ── RPC reply receiver setup ── private async Task SetupReplyReceiverAsync(CancellationToken ct) { if (_rpcSetup) return; await _rpcLock.WaitAsync(ct).ConfigureAwait(false); try { if (_rpcSetup) return; await _endpoint.EnsureConnectionForRpcAsync(ct).ConfigureAwait(false); var source = new Source { Dynamic = true }; var addressTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); _replyReceiver = new ReceiverLink( _endpoint.CurrentSession!, $"reply-{_endpoint.Address}-{Guid.NewGuid():N}", source, (link, attach) => { var remoteSource = attach.Source as Source; addressTcs.TrySetResult(remoteSource?.Address ?? string.Empty); }); _replyReceiver.SetCredit(_options.ResolvedConcurrentConsumers * 3, true); // Wait for broker to assign the dynamic address _replyAddress = await addressTcs.Task.ConfigureAwait(false); _rpcCts = new CancellationTokenSource(); _rpcTask = Task.Run(() => RpcReceiveLoopAsync(_rpcCts.Token), _rpcCts.Token); _rpcSetup = true; Logger?.LogDebug("AMQP RPC reply receiver created: replyAddress={ReplyAddress}", _replyAddress); } finally { _rpcLock.Release(); } } private async Task RpcReceiveLoopAsync(CancellationToken ct) { while (!ct.IsCancellationRequested && _replyReceiver is { IsClosed: false }) { try { var rMsg = await _replyReceiver.ReceiveAsync(TimeSpan.FromSeconds(5)).ConfigureAwait(false); if (rMsg == null) continue; var cid = rMsg.Properties?.CorrelationId?.ToString(); if (!string.IsNullOrEmpty(cid) && _pendingResponses.TryRemove(cid, out var pending)) { try { var body = AmqpMessageHelper.ExtractBody(rMsg); var response = new RouteMessage(body); AmqpMessageHelper.CopyApplicationProperties(rMsg, response, _headerFilter, pending.Request); pending.Reply.TrySetResult(response); } catch (Exception ex) { pending.Reply.TrySetException(ex); } } _replyReceiver.Accept(rMsg); } catch (AmqpException) when (ct.IsCancellationRequested) { break; } catch (Exception ex) { Logger?.LogError(ex, "Error in AMQP RPC receive loop: address={Address}", _endpoint.Address); } } } // ── Message preparation ── private AmqpMessage PrepareMessage(IExchange exchange) { var body = exchange.In.Body switch { byte[] bytes => (object)bytes, string str => str, null => string.Empty, var other => other.ToString() ?? string.Empty }; // Resolve priority: header > expression > static byte priority = _options.MessagePriority; if (exchange.In.Headers.TryGetValue(AmqpHeaders.Priority, out var prioObj)) { if (prioObj is byte prioByte) priority = prioByte; else if (prioObj is int prioInt) priority = (byte)Math.Clamp(prioInt, 0, 9); } else if (!string.IsNullOrEmpty(_options.MessagePriorityExpression)) { var resolved = _options.ResolveOption(_options.MessagePriorityExpression, exchange); if (resolved != null && byte.TryParse(resolved, out var exprPrio)) priority = exprPrio; } // Resolve TTL: header > expression > static uint ttl = _options.MessageTtl; if (exchange.In.Headers.TryGetValue(AmqpHeaders.Ttl, out var ttlObj)) { if (ttlObj is uint ttlUint) ttl = ttlUint; else if (ttlObj is int ttlInt && ttlInt > 0) ttl = (uint)ttlInt; } else if (!string.IsNullOrEmpty(_options.MessageTtlExpression)) { var resolved = _options.ResolveOption(_options.MessageTtlExpression, exchange); if (resolved != null && uint.TryParse(resolved, out var exprTtl)) ttl = exprTtl; } // Resolve string properties: header > expression > static var contentType = exchange.In.ContentType ?? _options.ResolveOption(_options.ContentType, exchange); var subject = _options.ResolveOption(_options.Subject, exchange); var groupId = _options.ResolveOption(_options.GroupId, exchange); var msg = new AmqpMessage(body) { Header = new Header { Durable = _options.MessageDurable, Priority = priority, }, Properties = new Properties { MessageId = Guid.NewGuid().ToString(), ContentType = contentType, } }; if (ttl > 0) msg.Header.Ttl = ttl; if (!string.IsNullOrEmpty(subject)) msg.Properties.Subject = subject; if (!string.IsNullOrEmpty(groupId)) msg.Properties.GroupId = groupId; // Exchange headers → AMQP application-properties: standard property names go into the properties below, // the endpoint's strategy decides the rest. var appProps = new ApplicationProperties(); foreach (var (key, value) in exchange.In.Headers) { if (StandardPropertyNames.Contains(key)) continue; if (value is null) continue; if (_headerFilter.FilterOutgoing(key, value, exchange)) continue; appProps[key] = value switch { string s => s, int or long or float or double or bool => value, _ => value.ToString()! }; } if (appProps.Map.Count > 0) msg.ApplicationProperties = appProps; // ── Forward AMQP properties from headers ────────────────────────────────── // Bare well-known names (MessageId/CorrelationId/ReplyTo/Subject/GroupId/To/…) — same // convention as the RabbitMQ component; redbAmqp.* is also accepted for back-compat. // Header wins over option/default. Typed values (DateTime/uint/bool) round-trip from the // consumer as-is; string forms are parsed as a fallback. if (TryHdr(exchange, AmqpHeaders.MessageId, out var midH)) msg.Properties.MessageId = midH; if (TryHdr(exchange, AmqpHeaders.CorrelationId, out var cidH)) msg.Properties.CorrelationId = cidH; // The reply-to only with preserveMessageQos, as Camel's JMS: a sender's reply-to forwarded here must not make another // consumer answer into it. A request-reply send sets its own reply address after this. if (_options.PreserveMessageQos && TryHdr(exchange, AmqpHeaders.ReplyTo, out var rtoH)) msg.Properties.ReplyTo = rtoH; if (TryHdr(exchange, AmqpHeaders.Subject, out var subjH)) msg.Properties.Subject = subjH; if (TryHdr(exchange, AmqpHeaders.GroupId, out var gidH)) msg.Properties.GroupId = gidH; if (TryHdr(exchange, AmqpHeaders.To, out var toH)) msg.Properties.To = toH; if (TryHdr(exchange, AmqpHeaders.ContentEncoding, out var ceH)) msg.Properties.ContentEncoding = ceH; if (_options.PreserveMessageQos && TryHdr(exchange, AmqpHeaders.ReplyToGroupId, out var rtgH)) msg.Properties.ReplyToGroupId = rtgH; if (TryHdr(exchange, AmqpHeaders.UserId, out var uidH)) msg.Properties.UserId = Encoding.UTF8.GetBytes(uidH); if (TryRaw(exchange, AmqpHeaders.GroupSequence, out var gsRaw)) { if (gsRaw is uint gsu) msg.Properties.GroupSequence = gsu; else if (uint.TryParse(gsRaw.ToString(), out var gsp)) msg.Properties.GroupSequence = gsp; } if (TryRaw(exchange, AmqpHeaders.CreationTime, out var ctRaw)) { if (ctRaw is DateTime ctd) msg.Properties.CreationTime = ctd; else if (DateTime.TryParse(ctRaw.ToString(), System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.RoundtripKind, out var ctp)) msg.Properties.CreationTime = ctp; } if (TryRaw(exchange, AmqpHeaders.AbsoluteExpiryTime, out var aeRaw)) { if (aeRaw is DateTime aed) msg.Properties.AbsoluteExpiryTime = aed; else if (DateTime.TryParse(aeRaw.ToString(), System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.RoundtripKind, out var aep)) msg.Properties.AbsoluteExpiryTime = aep; } if (TryRaw(exchange, AmqpHeaders.Durable, out var durRaw)) { if (durRaw is bool durb) msg.Header.Durable = durb; else if (bool.TryParse(durRaw.ToString(), out var durp)) msg.Header.Durable = durp; } return msg; } /// Reads a header by bare name, then redbAmqp.<name> for back-compat; true when found non-empty (as string). private static bool TryHdr(IExchange exchange, string name, out string value) { if ((exchange.In.Headers.TryGetValue(name, out var v) || exchange.In.Headers.TryGetValue(AmqpHeaders.Prefix + name, out v)) && v is not null) { value = v.ToString() ?? string.Empty; return !string.IsNullOrEmpty(value); } value = string.Empty; return false; } /// Reads a header's raw value by bare name, then redbAmqp.<name> for back-compat. private static bool TryRaw(IExchange exchange, string name, out object value) { if ((exchange.In.Headers.TryGetValue(name, out var v) || exchange.In.Headers.TryGetValue(AmqpHeaders.Prefix + name, out v)) && v is not null) { value = v; return true; } value = null!; return false; } // ── Helpers ── private void EnsureSender() { if (_sender is null or { IsClosed: true }) throw new InvalidOperationException("AMQP sender link is not available. The producer might need restart."); } private static AmqpMessage CloneMessage(AmqpMessage source) { var buffer = source.Encode(); return AmqpMessage.Decode(buffer); } } /// Deferred AMQP send action. internal sealed class AmqpSendAction : ITransactedAction { private readonly SenderLink _sender; private readonly AmqpMessage _msg; private readonly string _address; private readonly ILogger? _logger; public AmqpSendAction(SenderLink sender, AmqpMessage msg, string address, ILogger? logger) { _sender = sender; _msg = msg; _address = address; _logger = logger; } /// public async Task Commit(CancellationToken ct = default) { await _sender.SendAsync(_msg).ConfigureAwait(false); _logger?.LogDebug("AMQP transactional send committed: address={Address}", _address); } /// public Task Rollback(CancellationToken ct = default) { _logger?.LogDebug("AMQP transactional send rolled back: address={Address}", _address); return Task.CompletedTask; } } /// /// The sends an AMQP producer with localTransactions deferred in one .Transacted() block, committed in one /// AMQP local transaction when the block commits. /// internal sealed class AmqpTransactionBatch : ITransactedAction { private readonly AmqpProducer _producer; private readonly ConcurrentQueue _messages = new(); public AmqpTransactionBatch(AmqpProducer producer) => _producer = producer; public void Add(AmqpMessage message) => _messages.Enqueue(message); public Task Commit(CancellationToken ct = default) => _producer.CommitTransactionAsync(_messages.ToArray(), ct); // The block rolled back before the transaction was declared: nothing was sent. public Task Rollback(CancellationToken ct = default) => Task.CompletedTask; } Path: redb-route/redb.Route.Amqp/Extensions/ServiceCollectionExtensions.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/Extensions/ServiceCollectionExtensions.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Route.Extensions; namespace redb.Route.Amqp; /// /// Extension methods for registering the AMQP 1.0 transport in a DI container. /// public static class ServiceCollectionExtensions { /// /// Registers the in the route context so that /// amqp:// URIs are resolved. /// /// /// services.AddRedbRoute(route => /// { /// route.Services.AddRedbRouteAmqp(); /// route.AddRouteBuilder<MyRoutes>(); /// }); /// /// /// public static IServiceCollection AddRedbRouteAmqp(this IServiceCollection services) { // IRouteContextConfigurator is applied by RouteHostedService at startup -- // the correct registration hook (a lazy marker singleton never fires). services.AddRouteComponent(); return services; } } Path: redb-route/redb.Route.Amqp/Fluent/AmqpDsl.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/Fluent/AmqpDsl.cs ---- using System.Text; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Amqp; /// /// Fluent API for AMQP 1.0 endpoints. /// /// .From(AmqpDsl.Address("orders").Host("broker1").User("admin").Password("secret")) /// .To(AmqpDsl.Address("notifications").Host("broker1").MessageDurable()) /// /// public static class AmqpDsl { /// Creates an AMQP endpoint for the given address (terminus name). public static AmqpBuilder Address(string name) => new(name); } /// /// Fluent builder for AMQP 1.0 endpoint URIs. /// public sealed class AmqpBuilder { private readonly string _address; // Connection private string? _connectionFactory; private string? _host; private int? _port; private string? _user; private string? _password; private string? _containerId; private string? _virtualHost; private bool _ssl; // Link private uint? _durable; private string? _expiryPolicy; private uint? _terminusTimeout; private string? _distributionMode; private bool _dynamic; private string? _filterSelector; private string? _capabilities; private int? _senderSettleMode; private int? _receiverSettleMode; // Consumer private int? _credit; private AckMode? _ackMode; private string? _concurrentConsumers; private int? _receiveTimeout; // Producer private bool? _messageDurable; private string? _messagePriority; private string? _messageTtl; private string? _contentType; private string? _subject; private string? _groupId; private bool _replyTo; private bool _preserveMessageQos; private bool _disableReplyTo; private bool _batching; private int? _maxBatchMessages; private int? _pollTimeoutMs; private int? _batchingIntervalMs; private int? _timeout; private bool? _transacted; private bool _localTransactions; private bool _declare; private string? _routingType; internal AmqpBuilder(string address) { ArgumentException.ThrowIfNullOrWhiteSpace(address); _address = address; } // ── Connection ──────────────────────────────────────────────────── /// Use a named connection factory registered in DI. public AmqpBuilder ConnectionFactory(string name) { _connectionFactory = name; return this; } /// Broker hostname. Default "localhost". public AmqpBuilder Host(string host) { _host = host; return this; } /// Broker port. Default 5672. public AmqpBuilder Port(int port) { _port = port; return this; } /// Username for authentication. public AmqpBuilder User(string user) { _user = user; return this; } /// Password for authentication. public AmqpBuilder Password(string password) { _password = password; return this; } /// AMQP container ID. public AmqpBuilder ContainerId(string id) { _containerId = id; return this; } /// Virtual host. public AmqpBuilder VirtualHost(string vhost) { _virtualHost = vhost; return this; } /// Enable SSL/TLS. public AmqpBuilder Ssl() { _ssl = true; return this; } // ── Link ────────────────────────────────────────────────────────── /// Terminus durability mode: 0=None, 1=Configuration, 2=UnsettledState. public AmqpBuilder Durable(uint mode) { _durable = mode; return this; } /// Expiry policy: "link-detach", "session-end", "connection-close", "never". public AmqpBuilder ExpiryPolicy(string policy) { _expiryPolicy = policy; return this; } /// Terminus timeout in seconds. public AmqpBuilder TerminusTimeout(uint seconds) { _terminusTimeout = seconds; return this; } /// Distribution mode: "move" (competing consumers) or "copy" (pub/sub). public AmqpBuilder DistributionMode(string mode) { _distributionMode = mode; return this; } /// Request a dynamically created terminus. public AmqpBuilder Dynamic() { _dynamic = true; return this; } /// JMS-style selector filter. public AmqpBuilder FilterSelector(string selector) { _filterSelector = selector; return this; } /// Terminus capabilities (comma-separated). public AmqpBuilder Capabilities(string caps) { _capabilities = caps; return this; } /// Sender settle mode: 0=Unsettled, 1=Settled, 2=Mixed. public AmqpBuilder SenderSettleMode(int mode) { _senderSettleMode = mode; return this; } /// Receiver settle mode: 0=First, 1=Second. public AmqpBuilder ReceiverSettleMode(int mode) { _receiverSettleMode = mode; return this; } // ── Consumer ────────────────────────────────────────────────────── /// Link credit (prefetch). Default 100. public AmqpBuilder Credit(int credit) { _credit = credit; return this; } /// When a delivery is settled: after the route (, default) or on receipt (). public AmqpBuilder AckMode(AckMode mode) { _ackMode = mode; return this; } /// Number of concurrent consumers. Default 1. public AmqpBuilder ConcurrentConsumers(int count) { _concurrentConsumers = count.ToString(); return this; } /// Consumer parallelism as a string: a number or "auto" (= max(CPU, 2)). public AmqpBuilder ConcurrentConsumers(string count) { _concurrentConsumers = count; return this; } /// Receive timeout in seconds. Default 60. public AmqpBuilder ReceiveTimeout(int seconds) { _receiveTimeout = seconds; return this; } // ── Producer ────────────────────────────────────────────────────── /// Mark sent messages as durable. Default true. public AmqpBuilder MessageDurable(bool durable = true) { _messageDurable = durable; return this; } /// Message priority. Default 4. public AmqpBuilder MessagePriority(byte priority) { _messagePriority = priority.ToString(); return this; } /// Message priority from an expression. public AmqpBuilder MessagePriority(IExpression priority) { _messagePriority = priority.ToTemplateString(); return this; } /// Message TTL in milliseconds. Default 0 (no expiry). public AmqpBuilder MessageTtl(uint ms) { _messageTtl = ms.ToString(); return this; } /// Message TTL from an expression. public AmqpBuilder MessageTtl(IExpression ms) { _messageTtl = ms.ToTemplateString(); return this; } /// Content type. Default "text/plain". public AmqpBuilder ContentType(string type) { _contentType = type; return this; } /// Content type from an expression. public AmqpBuilder ContentType(IExpression type) { _contentType = type.ToTemplateString(); return this; } /// Message subject. public AmqpBuilder Subject(string subject) { _subject = subject; return this; } /// Message subject from an expression. public AmqpBuilder Subject(IExpression subject) { _subject = subject.ToTemplateString(); return this; } /// Message group ID. public AmqpBuilder GroupId(string id) { _groupId = id; return this; } /// Message group ID from an expression. public AmqpBuilder GroupId(IExpression id) { _groupId = id.ToTemplateString(); return this; } /// Enable request-reply with dynamic reply-to address. public AmqpBuilder ReplyTo() { _replyTo = true; return this; } /// /// Keep the reply-to headers as the reply-to of an ordinary send (Apache Camel preserveMessageQos); without it a /// forwarded sender's reply-to is not carried on. /// public AmqpBuilder PreserveMessageQos() { _preserveMessageQos = true; return this; } /// The consumer ignores a delivery's reply-to (Apache Camel disableReplyTo): no reply, and a batch takes it. public AmqpBuilder DisableReplyTo() { _disableReplyTo = true; return this; } /// Batch mode (batching=true): the route gets the deliveries as a List<IMessage>. public AmqpBuilder Batching() { _batching = true; return this; } /// Largest number of deliveries in a batch (maxBatchMessages, default and maximum credit). public AmqpBuilder MaxBatchMessages(int max) { _maxBatchMessages = max; return this; } /// Batch mode: the idle timeout in milliseconds, restarted by every delivery (pollTimeoutMs, default 1000). public AmqpBuilder PollTimeoutMs(int ms) { _pollTimeoutMs = ms; return this; } /// Batch mode: the hard limit in milliseconds since a batch's first delivery (batchingIntervalMs). public AmqpBuilder BatchingIntervalMs(int ms) { _batchingIntervalMs = ms; return this; } /// Operation timeout in seconds. Default 30. public AmqpBuilder Timeout(int seconds) { _timeout = seconds; return this; } /// Enable transacted sessions. public AmqpBuilder Transacted() { _transacted = true; return this; } /// /// Sets transacted explicitly. false sends at once even inside a .Transacted() block, outside its /// transaction; left unset, a producer follows the block. /// public AmqpBuilder Transacted(bool value) { _transacted = value; return this; } /// /// Sets localTransactions: the sends this producer defers in a .Transacted() block commit in one AMQP /// local transaction, all or none. The broker must support AMQP local transactions (Artemis, Qpid, Azure Service Bus). /// public AmqpBuilder LocalTransactions() { _localTransactions = true; return this; } /// Declare the address on the broker if it does not exist. public AmqpBuilder Declare() { _declare = true; return this; } /// Routing type for declaration: "ANYCAST" or "MULTICAST". public AmqpBuilder RoutingType(string type) { _routingType = type; return this; } // ── Build ───────────────────────────────────────────────────────── /// Builds the AMQP endpoint URI string. public string Build() { var sb = new StringBuilder(); sb.Append("amqp:"); sb.Append(_address); var sep = '?'; void Append(string key, string value) { sb.Append(sep); sb.Append(key); sb.Append('='); sb.Append(Uri.EscapeDataString(value)); sep = '&'; } void AppendIf(string key, string? value) { if (value != null) Append(key, value); } void AppendBool(string key, bool value) { if (value) Append(key, "true"); } void AppendBoolExplicit(string key, bool? value) { if (value.HasValue) Append(key, value.Value.ToString().ToLowerInvariant()); } void AppendInt(string key, int? value) { if (value.HasValue) Append(key, value.Value.ToString()); } void AppendUint(string key, uint? value) { if (value.HasValue) Append(key, value.Value.ToString()); } // Route int-or-expression params to the correct property void AppendIntOrExpression(string key, string? value) { if (value == null) return; if (value.Contains("${")) Append(key + "Expression", value); else Append(key, value); } // Connection AppendIf("connectionFactory", _connectionFactory); AppendIf("host", _host); AppendInt("port", _port); AppendIf("user", _user); AppendIf("password", _password); AppendIf("containerId", _containerId); AppendIf("virtualHost", _virtualHost); AppendBool("ssl", _ssl); // Link AppendUint("durable", _durable); AppendIf("expiryPolicy", _expiryPolicy); AppendUint("terminusTimeout", _terminusTimeout); AppendIf("distributionMode", _distributionMode); AppendBool("dynamic", _dynamic); AppendIf("filterSelector", _filterSelector); AppendIf("capabilities", _capabilities); AppendInt("senderSettleMode", _senderSettleMode); AppendInt("receiverSettleMode", _receiverSettleMode); // Consumer AppendInt("credit", _credit); if (_ackMode is { } ackMode) Append("ackMode", ackMode.ToString().ToLowerInvariant()); AppendIf("concurrentConsumers", _concurrentConsumers); AppendInt("receiveTimeout", _receiveTimeout); // Producer AppendBoolExplicit("messageDurable", _messageDurable); AppendIntOrExpression("messagePriority", _messagePriority); AppendIntOrExpression("messageTtl", _messageTtl); AppendIf("contentType", _contentType); AppendIf("subject", _subject); AppendIf("groupId", _groupId); AppendBool("replyTo", _replyTo); AppendBool("preserveMessageQos", _preserveMessageQos); AppendBool("disableReplyTo", _disableReplyTo); AppendBool("batching", _batching); AppendInt("maxBatchMessages", _maxBatchMessages); AppendInt("pollTimeoutMs", _pollTimeoutMs); AppendInt("batchingIntervalMs", _batchingIntervalMs); AppendInt("timeout", _timeout); if (_transacted is { } transacted) Append("transacted", transacted ? "true" : "false"); if (_localTransactions) Append("localTransactions", "true"); AppendBool("declare", _declare); AppendIf("routingType", _routingType); return sb.ToString(); } /// Implicit conversion to URI string. public static implicit operator string(AmqpBuilder b) => b.Build(); /// public override string ToString() => Build(); } Path: redb-route/redb.Route.Amqp/README.md 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/README.md ---- # redb.Route.Amqp AMQP 1.0 transport for redb.Route via AMQPNetLite. Supports ActiveMQ Artemis, ActiveMQ Classic, Azure Service Bus, Amazon MQ, Qpid, and any AMQP 1.0 compliant broker. [![NuGet](https://img.shields.io/nuget/v/redb.Route.Amqp?label=NuGet&color=blue)](https://www.nuget.org/packages/redb.Route.Amqp) [![License: Apache 2.0](https://img.shields.io/badge/license-Apache%202.0-blue)](../../LICENSE) ## Installation ```bash dotnet add package redb.Route.Amqp ``` ## Usage ### Fluent DSL ```csharp using redb.Route.Amqp; // Consume from AMQP address From(AmqpDsl.Address("orders") .Host("artemis.local").Port(5672) .User("admin").Password("secret") .Credit(10) .Durable(2)) // terminus durability: 0 None, 1 Configuration, 2 UnsettledState .Log("Received order: ${body}") .To("direct://process"); // Produce to AMQP address From("direct://send") .To(AmqpDsl.Address("events") .Host("artemis.local") .User("admin").Password("secret") .MessageDurable() .ContentType("application/json")); // Azure Service Bus From(AmqpDsl.Address("orders") .Host("mybus.servicebus.windows.net").Port(5671) .User("policy-name").Password("shared-access-key") .Ssl() .ContainerId("route-consumer")) .To("direct://handle"); ``` ## Fluent Builder API | Category | Methods | |----------|---------| | **Connection** | `.Host()`, `.Port()`, `.User()`, `.Password()`, `.ContainerId()`, `.VirtualHost()`, `.Ssl()`, `.ConnectionFactory()` | | **Link** | `.Durable(mode)`, `.ExpiryPolicy()`, `.TerminusTimeout()`, `.DistributionMode()`, `.Dynamic()`, `.FilterSelector()`, `.Capabilities()`, `.SenderSettleMode()`, `.ReceiverSettleMode()` | | **Consumer** | `.Credit()`, `.AckMode()`, `.ConcurrentConsumers()`, `.ReceiveTimeout()`, `.DisableReplyTo()`, `.Batching()`, `.MaxBatchMessages()`, `.PollTimeoutMs()`, `.BatchingIntervalMs()` | | **Producer** | `.MessageDurable()`, `.MessagePriority()`, `.MessageTtl()`, `.ContentType()`, `.Subject()`, `.GroupId()`, `.ReplyTo()`, `.PreserveMessageQos()`, `.Timeout()`, `.Transacted()`, `.LocalTransactions()`, `.Declare()`, `.RoutingType()` | ## A failed delivery With `ackMode=manual` (the default) a delivery is accepted after the route ends well. When the route fails, the consumer gives the delivery back as a failed one: the AMQP `modified` outcome with `delivery-failed`. The broker counts the attempt and delivers the message again; a message that always fails stops at the broker's maximum delivery count (ActiveMQ Artemis: `max-delivery-attempts`, 10 by default, then the dead letter address). With `ackMode=auto` the delivery is accepted on receipt, before the route, and a failure does not bring it back. ## Batch mode `batching=true` makes the consumer hand the route one exchange per batch of deliveries, by the batch contract every broker of redb.Route follows. Apache Camel has no batch consumer for AMQP; the contract is redb.Route's own, the same as for Kafka, RabbitMQ, IBM MQ and SQS. - `maxBatchMessages` caps the batch (default and maximum: `credit`, as the broker never sends a link more unsettled deliveries than its credit); `pollTimeoutMs` (default 1000) sends a batch on once no delivery came for that long, restarted by every delivery; `batchingIntervalMs` sends it on once that long has passed since its first delivery. A batch option without `batching=true`, a value out of range, `maxBatchMessages` above `credit` and `batching=true` with `replyTo=true` fail the start. - The body is a `List`, one message per delivery with its own body, application properties and AMQP properties as headers, even for a batch of one; the size is `body.Count`. `redbAmqp.Address` is set on the batch message. The exchange is InOnly. `Split` over the body gives each part its delivery. - `concurrentConsumers` workers each own a receiver link and collect and run one batch at a time. - Every delivery of the batch is accepted after the route. A failed batch follows the rule of a failed delivery for every delivery in it: each is given back as failed (see above), and the broker delivers it again up to its maximum delivery count. With `ackMode=auto` the deliveries are accepted on receipt, before the route, and a failure does not bring them back. - A delivery with a reply-to cannot be answered from a one-way batch: it is not put into the batch but rejected at once (the AMQP `rejected` outcome; ActiveMQ Artemis moves it to the dead letter address), with an error in the log and the endpoint statistics. `disableReplyTo=true` (Apache Camel's name, single mode too: no reply, the exchange is InOnly) batches such deliveries and nobody replies. - A batch half collected when the consumer stops is not run: its deliveries are given back to the broker (released, or returned on detach). The stop lets the batches in flight settle, then closes the links. ## A list body This producer does not send a list: a list of `IMessage` is refused with the advice to `Split` it, and any other list whose text would be its type name is refused too. ## Transactions Inside a route's `.Transacted()` block a send **joins the transaction**: it goes out once the database has committed and is dropped if the block rolls back. `.Transacted(false)` sends at once, outside the transaction; `.Transacted()` requires an enclosing block and fails the step outside one. A request-reply producer (`.ReplyTo()`) always sends at once and refuses `.Transacted()`. The AMQP client would enlist a send in the ambient `System.Transactions` transaction by itself. The connector never lets it: a send that leaves at once runs with the ambient transaction suppressed and a deferred one after the transaction closed, so the broker never becomes a second resource next to the database. See the framework-wide **Transactions** guide (`TRANSACTIONS.md` in the [redb.Route repository](https://github.com/redbase-app/redb)). ### Several sends in one block: `localTransactions` By default the sends a producer deferred in a block go out one after the other: a failure part-way leaves the earlier ones sent. With `localTransactions=true` (`.LocalTransactions()`) they commit in one **AMQP local transaction**: the connector opens a link to the broker's transaction coordinator, declares a transaction, sends every message carrying it and discharges it once — all of them arrive, or none. A send that cannot complete (the broker refuses it, or does not settle it within `timeout` seconds — Artemis withholds credit on a full address) discharges the transaction as failed, and the block's commit fails. The producer's transactions take turns on its link. The broker must support AMQP local transactions: ActiveMQ Artemis, Apache Qpid, Azure Service Bus do; RabbitMQ's AMQP 1.0 plugin does not, and a broker that refuses the coordinator fails the commit with that said. The client's own `System.Transactions` support is not used: its discharge never got an answer from Artemis, while the same transaction driven through the protocol's own frames is answered at once. ## Headers Exchange headers become application-properties of a sent message and of a reply, and the application-properties of a delivery or a reply come back as exchange headers. The standard property names (`MessageId`, `CorrelationId`, `Subject`...) go into the message properties instead; `redbAmqp.*` headers are exchange metadata and stay back. The reply-to of a delivery is not carried on: an ordinary (not request-reply) send leaves the `ReplyTo` and `ReplyToGroupId` headers out, so a message consumed with a sender's reply-to and forwarded here does not make another consumer answer into an address of another system, as in Apache Camel's JMS. `preserveMessageQos=true` (`.PreserveMessageQos()`) keeps them, for a bridge that needs them or a route that names a reply address on an ordinary send. The correlation id is always carried; a request-reply send (`replyTo=true`) sets its own reply-to. `headerFilterStrategy=#name` names an `IHeaderFilterStrategy` in the registry that decides which headers the endpoint carries, as in Apache Camel, in both directions of a request and a reply. It replaces the default, `AmqpHeaderFilterStrategy`, entirely; derive from that class to add to it. The standard properties, the consumer's `redbAmqp.*` metadata and the trace context are set whatever the strategy says. ```csharp ctx.AddToRegistry("correlationOnly", new DefaultHeaderFilterStrategy { OutFilter = ["Correlation-ID"], FilterOnMatch = false, // a whitelist: only the listed headers go out }); // amqp://orders?host=localhost&headerFilterStrategy=#correlationOnly ``` ## Part of [redb.Route](../README.md) — ESB & EIP Framework for .NET ## Named connection factory Keep credentials out of the route URI: register a factory in the context registry and reference it by name. A set-but-unknown name fails loud at startup — a typo can never silently fall back to inline URI parameters. ```csharp context.AddToRegistry("prod", new AmqpConnectionFactory { Host = "broker.internal", User = "svc-orders", Password = secrets.AmqpPassword, }); // amqp://orders?connectionFactory=prod ``` ## Concurrency The default is **1** concurrent consumer — the industry norm (Camel, Spring, the Azure SDK all ship 1): a single consumer preserves ordering and your handlers need no thread safety. Parallelism is an explicit opt-in: ``` concurrentConsumers=4 # a fixed worker count concurrentConsumers=auto # max(CPU count, 2) — the NServiceBus formula ``` Anything else — `0`, a negative, a typo — fails at endpoint creation naming the option (the old int-typed option silently fell back to 1). Raising the value trades ordering for throughput: messages from the same queue are processed out of order, and your processors must be safe to run in parallel. A MULTICAST address (`routingType=MULTICAST` or the `topic` capability) and a dynamic node (`dynamic=true`) run one receiver link whatever the value, with a warning: there every link is a subscription or a node of its own, so N links would process each message N times instead of sharing them, as IBM MQ topics do. ## Dynamic node `dynamic=true` with no address asks the broker to create a node and name it (AMQP 1.0, 3.5.3). The consumer reads that node, and `AmqpConsumer.Address` and the `redbAmqp.Address` header carry its name once the consumer has started, for senders to reach it. A producer with `dynamic=true` sends to a node the broker creates for it and logs its name. An endpoint with both an address and `dynamic=true` is refused. ## Start `Start()` returns once the broker has accepted every receiver link of the consumer, so a MULTICAST subscription is in place and a message sent right after the start is received. A link the broker refuses (an address it does not serve, a routing type the address lacks, no permission) fails the start with `AMQP consumer amqp:
cannot start: the broker refused the receiver link (: )`; no answer within `timeout` seconds fails it too. ## A lost link When the broker detaches a receiver link (a forced detach, a deleted address, a restart) or the connection under it drops, the worker attaches its link again on a new session, on a new connection when the old one is gone. The deliveries the old link held unsettled come back from the broker. While the link is away the endpoint's health is `Warning`, then `Critical` once an attempt to attach it failed; a Warning is logged when it is lost and an Information when it is back, and `Reconnects` counts each return. Attempts follow `RedbRoute:Reconnect` (delay, multiplier, cap, attempt timeout); a loss is not counted in `Errors`. With `dynamic=true` the new link gets a new node from the broker, and `AmqpConsumer.Address` names it. ## Tracing On the `redb.Route` activity source (`AddSource("redb.Route")`). The W3C context travels in the application properties: `traceparent`, `tracestate`, `baggage`. - **Consumer.** One `Consumer` span per message, `{address} receive`, over the whole unit of work, settlement included. Its parent is the sender's `traceparent`; without one it is a root, never a child of the activity the receive loop inherited from whoever started the routes. The sender's baggage is back on it, the route's spans are its children, it carries `redb.route.endpoint`, `messaging.message.id` and `messaging.amqp.subject`, and a failed route marks it an error. - **Producer.** One `Producer` span per send, `{address} publish`; an error when the send fails. The message carries the context of this span: a `traceparent` the header bridge copied from a received message is replaced. - `RouteEngineOptions.EnableTelemetry = false` opens neither span. A context that came in still goes out. Path: redb-route/redb.Route.Amqp/redb.Route.Amqp.csproj 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/redb.Route.Amqp.csproj ---- redb.Route.Amqp AMQP 1.0 transport for redb.Route ESB framework. Supports ActiveMQ Artemis, ActiveMQ Classic, Azure Service Bus, Amazon MQ, Qpid, and any AMQP 1.0 compliant broker. esb;messaging;amqp;activemq;artemis;redb README.md