Bundle: redb-route / tests/redb.Route.Tests.Amqp (tests.redb.Route.Tests.Amqp.txt), 31 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/tests/redb.Route.Tests.Amqp/AckModeOptionsTests.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/tests/redb.Route.Tests.Amqp/AckModeOptionsTests.cs
----
using AwesomeAssertions;
using redb.Route.Core;
using redb.Route.Amqp;
namespace redb.Route.Tests.Amqp;
///
/// ackMode, the one option that says when a consumer settles what it received (manual: after the route,
/// auto: on receipt). The connector's former option is refused with its replacement named.
///
public class AckModeOptionsTests
{
private static AmqpEndpointOptions Bind(params (string Key, string Value)[] parameters)
{
var options = new AmqpEndpointOptions();
options.BindFromUri(parameters.ToDictionary(p => p.Key, p => p.Value));
return options;
}
[Fact]
public void The_default_is_manual() => new AmqpEndpointOptions().AckMode.Should().Be(AckMode.Manual);
[Fact]
public void Auto_binds_from_the_uri() => Bind(("ackMode", "auto")).AckMode.Should().Be(AckMode.Auto);
[Fact]
public void The_former_option_is_refused_with_its_replacement()
{
var act = () => Bind(("autoAccept", "false"));
act.Should().Throw().WithMessage("*'autoAccept' is replaced by 'ackMode'*");
}
}
Path: redb-route/tests/redb.Route.Tests.Amqp/AmqpBatchIntegrationTests.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/tests/redb.Route.Tests.Amqp/AmqpBatchIntegrationTests.cs
----
using System.Collections.Concurrent;
using System.Text;
using Amqp;
using Amqp.Framing;
using redb.Route.Abstractions;
using redb.Route.Amqp;
using redb.Route.Core;
using AmqpMessage = global::Amqp.Message;
namespace redb.Route.Tests.Amqp;
///
/// Batch mode of the AMQP 1.0 consumer against ActiveMQ Artemis (localhost:5673, admin/admin), on the core batch
/// contract: a batch closes by size or by the idle timeout, its body is a list of one message per delivery with that
/// delivery's body and headers, it is settled once after the route (accepted on success, released for redelivery on
/// failure), a stop gives an unfinished batch back, and a delivery with a reply-to is rejected unless disableReplyTo.
///
[Trait("Category", "Integration")]
public sealed class AmqpBatchIntegrationTests
{
private const string Broker = "host=localhost&port=5673&user=admin&password=admin";
private static AmqpEndpoint Endpoint(string address, string query)
=> (AmqpEndpoint)new AmqpComponent().CreateEndpoint(EndpointUriParser.Parse($"amqp://{address}?{Broker}&{query}"));
private static async Task SendAsync(string address, params (string Body, string? ReplyTo)[] messages)
{
var connection = await Connection.Factory.CreateAsync(new Address("amqp://admin:admin@localhost:5673"));
try
{
var session = new Session(connection);
// An ANYCAST target (the queue capability), as the consumer reads it: without it Artemis creates the address
// MULTICAST on the first send, and an ANYCAST receiver link is refused.
var sender = new SenderLink(session, $"test-sender-{Guid.NewGuid():N}",
new Target { Address = address, Capabilities = [new global::Amqp.Types.Symbol("queue")] }, null);
foreach (var (body, replyTo) in messages)
{
var msg = new AmqpMessage(body)
{
Properties = new Properties { MessageId = Guid.NewGuid().ToString("N"), ReplyTo = replyTo },
ApplicationProperties = new ApplicationProperties { ["tag"] = "t-" + body },
};
await sender.SendAsync(msg).WaitAsync(TimeSpan.FromSeconds(15));
}
await sender.CloseAsync();
await session.CloseAsync();
}
finally
{
await connection.CloseAsync();
}
}
private static Task SendAsync(string address, params string[] bodies)
=> SendAsync(address, bodies.Select(b => (b, (string?)null)).ToArray());
/// Records each batch as the list of its bodies; fails the batches says to.
private sealed class Route(Func? fail = null) : IProcessor
{
public readonly ConcurrentQueue> Batches = new();
private int _calls;
public Task Process(IExchange exchange, CancellationToken ct = default)
{
var call = Interlocked.Increment(ref _calls);
Batches.Enqueue(((List)exchange.In.Body!).ToList());
if (fail?.Invoke(call) == true)
throw new InvalidOperationException($"batch {call} fails");
return Task.CompletedTask;
}
public IEnumerable Bodies(List batch)
=> batch.Select(m => m.Body is byte[] bytes ? Encoding.UTF8.GetString(bytes) : m.Body?.ToString() ?? "");
public int Delivered => Batches.Sum(b => b.Count);
}
private static async Task WaitUntil(Func condition, int timeoutMs = 15_000)
{
var deadline = DateTime.UtcNow.AddMilliseconds(timeoutMs);
while (!condition() && DateTime.UtcNow < deadline)
await Task.Delay(50);
return condition();
}
[Fact]
public async Task A_full_batch_is_one_exchange_with_a_message_per_delivery()
{
var address = $"batch.size.{Guid.NewGuid():N}";
await SendAsync(address, "a", "b", "c", "d", "e");
var route = new Route();
var endpoint = Endpoint(address, "batching=true&maxBatchMessages=5&pollTimeoutMs=5000");
var consumer = endpoint.CreateConsumer(route);
await consumer.Start().WaitAsync(TimeSpan.FromSeconds(30));
try
{
(await WaitUntil(() => route.Batches.Count >= 1)).Should().BeTrue();
}
finally
{
await consumer.Stop().WaitAsync(TimeSpan.FromSeconds(30));
await endpoint.Stop();
}
var batch = route.Batches.Single();
route.Bodies(batch).Should().Equal("a", "b", "c", "d", "e");
batch.Select(m => m.Headers["tag"]).Should().Equal("t-a", "t-b", "t-c", "t-d", "t-e");
batch.Should().OnlyContain(m => m.Headers.ContainsKey(AmqpHeaders.MessageId));
}
[Fact]
public async Task A_batch_closes_by_the_idle_timeout_and_one_delivery_is_a_list_too()
{
var address = $"batch.idle.{Guid.NewGuid():N}";
var route = new Route();
var endpoint = Endpoint(address, "batching=true&maxBatchMessages=10&pollTimeoutMs=500");
var consumer = endpoint.CreateConsumer(route);
await consumer.Start().WaitAsync(TimeSpan.FromSeconds(30));
try
{
await SendAsync(address, "only");
(await WaitUntil(() => route.Batches.Count >= 1)).Should().BeTrue();
await Task.Delay(1000);
}
finally
{
await consumer.Stop().WaitAsync(TimeSpan.FromSeconds(30));
await endpoint.Stop();
}
route.Batches.Should().ContainSingle();
route.Bodies(route.Batches.Single()).Should().Equal("only");
}
[Fact]
public async Task A_failed_batch_is_released_and_delivered_again()
{
var address = $"batch.fail.{Guid.NewGuid():N}";
await SendAsync(address, "x", "y", "z");
var route = new Route(fail: call => call == 1);
var endpoint = Endpoint(address, "batching=true&maxBatchMessages=3&pollTimeoutMs=2000");
var consumer = endpoint.CreateConsumer(route);
await consumer.Start().WaitAsync(TimeSpan.FromSeconds(30));
try
{
(await WaitUntil(() => route.Batches.Count >= 2)).Should().BeTrue("the released deliveries come again");
await Task.Delay(1500);
}
finally
{
await consumer.Stop().WaitAsync(TimeSpan.FromSeconds(30));
await endpoint.Stop();
}
var batches = route.Batches.ToList();
batches.Should().HaveCount(2, "the second batch is accepted and nothing comes a third time");
route.Bodies(batches[1]).Should().BeEquivalentTo("x", "y", "z");
}
[Fact]
public async Task A_stop_gives_the_unfinished_batch_back()
{
var address = $"batch.stop.{Guid.NewGuid():N}";
await SendAsync(address, "p", "q");
var first = new Route();
var endpoint = Endpoint(address, "batching=true&maxBatchMessages=10&pollTimeoutMs=8000");
var consumer = endpoint.CreateConsumer(first);
await consumer.Start().WaitAsync(TimeSpan.FromSeconds(30));
await Task.Delay(1500); // both deliveries are in the collector; the idle timeout is far away
await consumer.Stop().WaitAsync(TimeSpan.FromSeconds(30));
await endpoint.Stop();
first.Batches.Should().BeEmpty("an interrupted batch is not run");
var again = new Route();
var endpoint2 = Endpoint(address, "batching=true&maxBatchMessages=2&pollTimeoutMs=2000");
var consumer2 = endpoint2.CreateConsumer(again);
await consumer2.Start().WaitAsync(TimeSpan.FromSeconds(30));
try
{
(await WaitUntil(() => again.Delivered >= 2)).Should().BeTrue("the released deliveries come again");
}
finally
{
await consumer2.Stop().WaitAsync(TimeSpan.FromSeconds(30));
await endpoint2.Stop();
}
again.Batches.SelectMany(again.Bodies).Should().BeEquivalentTo("p", "q");
}
[Fact]
public async Task A_delivery_with_a_reply_to_is_rejected_and_the_rest_goes_on()
{
var address = $"batch.reply.{Guid.NewGuid():N}";
var marker = Guid.NewGuid().ToString("N");
await SendAsync(address, ("one", null), ("request-" + marker, "some.reply.address"), ("two", null));
var route = new Route();
var endpoint = Endpoint(address, "batching=true&maxBatchMessages=2&pollTimeoutMs=1500");
var consumer = endpoint.CreateConsumer(route);
await consumer.Start().WaitAsync(TimeSpan.FromSeconds(30));
try
{
(await WaitUntil(() => route.Delivered >= 2)).Should().BeTrue();
await Task.Delay(1500);
}
finally
{
await consumer.Stop().WaitAsync(TimeSpan.FromSeconds(30));
await endpoint.Stop();
}
route.Batches.SelectMany(route.Bodies).Should().BeEquivalentTo("one", "two");
(await DeadLetteredAsync("request-" + marker)).Should().BeTrue("Artemis moves a rejected delivery to its dead letter address");
}
[Fact]
public async Task With_disableReplyTo_a_delivery_with_a_reply_to_is_batched_without_a_reply()
{
var address = $"batch.noreply.{Guid.NewGuid():N}";
await SendAsync(address, ("one", null), ("asks", "some.reply.address"));
var route = new Route();
var endpoint = Endpoint(address, "batching=true&maxBatchMessages=2&pollTimeoutMs=3000&disableReplyTo=true");
var consumer = endpoint.CreateConsumer(route);
await consumer.Start().WaitAsync(TimeSpan.FromSeconds(30));
try
{
(await WaitUntil(() => route.Delivered >= 2)).Should().BeTrue();
}
finally
{
await consumer.Stop().WaitAsync(TimeSpan.FromSeconds(30));
await endpoint.Stop();
}
route.Batches.SelectMany(route.Bodies).Should().BeEquivalentTo("one", "asks");
}
[Fact]
public async Task Concurrent_workers_each_batch_and_every_delivery_is_processed_once()
{
var address = $"batch.workers.{Guid.NewGuid():N}";
await SendAsync(address, Enumerable.Range(0, 40).Select(i => $"m{i}").ToArray());
var route = new Route();
var endpoint = Endpoint(address, "batching=true&maxBatchMessages=10&pollTimeoutMs=1000&concurrentConsumers=2&credit=10");
var consumer = endpoint.CreateConsumer(route);
await consumer.Start().WaitAsync(TimeSpan.FromSeconds(30));
try
{
(await WaitUntil(() => route.Delivered >= 40)).Should().BeTrue();
await Task.Delay(1500);
}
finally
{
await consumer.Stop().WaitAsync(TimeSpan.FromSeconds(30));
await endpoint.Stop();
}
route.Batches.SelectMany(route.Bodies).Should().BeEquivalentTo(Enumerable.Range(0, 40).Select(i => $"m{i}"));
route.Batches.Should().OnlyContain(b => b.Count <= 10);
}
[Fact]
public async Task With_ackMode_auto_a_failed_batch_is_not_delivered_again()
{
var address = $"batch.auto.{Guid.NewGuid():N}";
await SendAsync(address, "g", "h");
var route = new Route(fail: _ => true);
var endpoint = Endpoint(address, "batching=true&maxBatchMessages=2&pollTimeoutMs=2000&ackMode=auto");
var consumer = endpoint.CreateConsumer(route);
await consumer.Start().WaitAsync(TimeSpan.FromSeconds(30));
try
{
(await WaitUntil(() => route.Batches.Count >= 1)).Should().BeTrue();
await Task.Delay(2500);
}
finally
{
await consumer.Stop().WaitAsync(TimeSpan.FromSeconds(30));
await endpoint.Stop();
}
route.Batches.Should().ContainSingle("ackMode=auto accepts on receipt, before the route");
}
/// Whether the delivery with sits in Artemis's dead letter queue (DLQ).
private static async Task DeadLetteredAsync(string body)
{
var connection = await Connection.Factory.CreateAsync(new Address("amqp://admin:admin@localhost:5673"));
try
{
var session = new Session(connection);
var receiver = new ReceiverLink(session, $"test-dlq-{Guid.NewGuid():N}",
new Source { Address = "DLQ", Capabilities = [new global::Amqp.Types.Symbol("queue")] }, null);
var deadline = DateTime.UtcNow.AddSeconds(10);
while (DateTime.UtcNow < deadline)
{
var msg = await receiver.ReceiveAsync(TimeSpan.FromSeconds(1));
if (msg is null) continue;
var text = msg.Body is byte[] bytes ? Encoding.UTF8.GetString(bytes) : msg.Body?.ToString();
if (text == body)
{
receiver.Accept(msg);
return true;
}
receiver.Release(msg);
}
return false;
}
finally
{
await connection.CloseAsync();
}
}
// ── A wait under one millisecond (the collector's last wait before a deadline) ──
/// Opens a receiver link on an empty queue .
private static async Task<(Connection Connection, ReceiverLink Receiver)> OpenReceiver(string address)
{
var connection = await Connection.Factory.CreateAsync(new Address("amqp://admin:admin@localhost:5673"));
var receiver = new ReceiverLink(new Session(connection), $"test-receiver-{Guid.NewGuid():N}",
new Source { Address = address, Capabilities = [new global::Amqp.Types.Symbol("queue")] }, null);
return (connection, receiver);
}
[Fact]
public async Task AMQPNetLite_never_completes_a_receive_shorter_than_a_millisecond()
{
// The cause the consumer works around: ReceiveAsync counts whole milliseconds, and 0 ms with no delivery at hand
// creates no waiter. Should the library ever complete it, WholeMilliseconds may go.
var (connection, receiver) = await OpenReceiver($"batch.submillisecond.{Guid.NewGuid():N}");
try
{
var receive = receiver.ReceiveAsync(TimeSpan.FromTicks(5_000));
(await Task.WhenAny(receive, Task.Delay(2_000))).Should().NotBeSameAs(receive);
}
finally
{
await connection.CloseAsync();
}
}
[Fact]
public async Task The_batch_receive_completes_after_a_wait_shorter_than_a_millisecond()
{
var address = $"batch.submillisecond.{Guid.NewGuid():N}";
var consumer = (AmqpConsumer)Endpoint(address, "batching=true").CreateConsumer(new Route());
var (connection, receiver) = await OpenReceiver(address);
try
{
var receive = consumer.ReceiveIntoBatchAsync(receiver, [], 10, TimeSpan.FromTicks(5_000), CancellationToken.None)
.AsTask();
(await receive.WaitAsync(TimeSpan.FromSeconds(5))).Should().Be(0, "no delivery came, and the wait ended");
}
finally
{
await connection.CloseAsync();
}
}
[Theory]
[InlineData(5_000L, 1)] // 0.5 ms
[InlineData(0L, 1)]
[InlineData(12_000L, 2)] // 1.2 ms
[InlineData(50_000L, 5)] // 5 ms
public void A_wait_is_rounded_up_to_whole_milliseconds_and_at_least_one(long ticks, int milliseconds)
=> AmqpConsumer.WholeMilliseconds(TimeSpan.FromTicks(ticks)).Should().Be(TimeSpan.FromMilliseconds(milliseconds));
}
Path: redb-route/tests/redb.Route.Tests.Amqp/AmqpBatchOptionsTests.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/tests/redb.Route.Tests.Amqp/AmqpBatchOptionsTests.cs
----
using redb.Route.Amqp;
using redb.Route.Core;
namespace redb.Route.Tests.Amqp;
/// The AMQP 1.0 batch options on the core contract, and every start refusal of batch mode.
public sealed class AmqpBatchOptionsTests
{
private static AmqpEndpoint Endpoint(string query)
=> (AmqpEndpoint)new AmqpComponent().CreateEndpoint(EndpointUriParser.Parse($"amqp://orders?host=localhost&{query}"));
[Fact]
public void Batch_mode_is_off_by_default_and_on_with_batching()
{
Endpoint("credit=50").EndpointOptions.Batch.Should().BeNull();
var batch = Endpoint("batching=true&credit=50").EndpointOptions.Batch!;
batch.MaxMessages.Should().Be(50, "the default batch is the link's credit");
batch.PollTimeout.Should().Be(TimeSpan.FromSeconds(1));
batch.Interval.Should().BeNull();
var tuned = Endpoint("batching=true&maxBatchMessages=20&pollTimeoutMs=250&batchingIntervalMs=4000").EndpointOptions.Batch!;
(tuned.MaxMessages, tuned.PollTimeout, tuned.Interval).Should().Be((20, TimeSpan.FromMilliseconds(250), TimeSpan.FromSeconds(4)));
}
[Theory]
[InlineData("maxBatchMessages=10", "*sets maxBatchMessages without batching=true*")]
[InlineData("batchingIntervalMs=10", "*sets batchingIntervalMs without batching=true*")]
[InlineData("batching=true&credit=10&maxBatchMessages=11", "*maxBatchMessages=11 is larger than credit=10*")]
[InlineData("batching=true&replyTo=true", "*batching=true cannot be combined with replyTo=true*")]
[InlineData("batching=true&pollTimeoutMs=0", "*pollTimeoutMs must be positive*")]
public void Batch_mode_that_cannot_work_fails_at_endpoint_creation(string query, string message)
{
var act = () => Endpoint(query);
act.Should().Throw().WithMessage(message);
}
[Fact]
public void The_builder_writes_the_batch_options()
{
var uri = AmqpDsl.Address("orders").Batching().MaxBatchMessages(20).PollTimeoutMs(250)
.BatchingIntervalMs(4000).DisableReplyTo().Build();
uri.Should().Contain("batching=true").And.Contain("maxBatchMessages=20").And.Contain("pollTimeoutMs=250")
.And.Contain("batchingIntervalMs=4000").And.Contain("disableReplyTo=true");
}
}
Path: redb-route/tests/redb.Route.Tests.Amqp/AmqpBuilderTests.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/tests/redb.Route.Tests.Amqp/AmqpBuilderTests.cs
----
using redb.Route.Core;
using redb.Route.Amqp;
namespace redb.Route.Tests.Amqp;
public class AmqpBuilderTests
{
// ── Factory ─────────────────────────────────────────────────────
[Fact]
public void Address_StartsWithAmqpScheme()
{
var uri = AmqpDsl.Address("orders").Build();
uri.Should().StartWith("amqp:orders");
}
[Fact]
public void NullAddress_Throws()
{
var act = () => AmqpDsl.Address(null!);
act.Should().Throw();
}
// ── Connection ──────────────────────────────────────────────────
[Fact]
public void Host_SetsParam()
{
var uri = AmqpDsl.Address("q").Host("broker1").Build();
uri.Should().Contain("host=broker1");
}
[Fact]
public void Port_SetsParam()
{
var uri = AmqpDsl.Address("q").Port(5673).Build();
uri.Should().Contain("port=5673");
}
[Fact]
public void User_SetsParam()
{
var uri = AmqpDsl.Address("q").User("admin").Build();
uri.Should().Contain("user=admin");
}
[Fact]
public void Password_SetsParam()
{
var uri = AmqpDsl.Address("q").Password("secret").Build();
uri.Should().Contain("password=secret");
}
[Fact]
public void Ssl_SetsParam()
{
var uri = AmqpDsl.Address("q").Ssl().Build();
uri.Should().Contain("ssl=true");
}
[Fact]
public void VirtualHost_SetsParam()
{
var uri = AmqpDsl.Address("q").VirtualHost("/test").Build();
uri.Should().Contain("virtualHost=");
}
// ── Consumer ────────────────────────────────────────────────────
[Fact]
public void Credit_SetsParam()
{
var uri = AmqpDsl.Address("q").Credit(200).Build();
uri.Should().Contain("credit=200");
}
[Fact]
public void ConcurrentConsumers_SetsParam()
{
var uri = AmqpDsl.Address("q").ConcurrentConsumers(4).Build();
uri.Should().Contain("concurrentConsumers=4");
}
[Fact]
public void AckModeAuto_SetsParam()
{
var uri = AmqpDsl.Address("q").AckMode(AckMode.Auto).Build();
uri.Should().Contain("ackMode=auto");
}
// ── Producer ────────────────────────────────────────────────────
[Fact]
public void MessageDurable_SetsParam()
{
var uri = AmqpDsl.Address("q").MessageDurable().Build();
uri.Should().Contain("messageDurable=true");
}
[Fact]
public void ContentType_SetsParam()
{
var uri = AmqpDsl.Address("q").ContentType("application/json").Build();
uri.Should().Contain("contentType=application%2Fjson");
}
[Fact]
public void Transacted_SetsParam()
{
var uri = AmqpDsl.Address("q").Transacted().Build();
uri.Should().Contain("transacted=true");
}
[Fact]
public void Transacted_false_is_written_out_to_send_at_once_inside_a_block()
{
var uri = AmqpDsl.Address("q").Transacted(false).Build();
uri.Should().Contain("transacted=false");
}
[Fact]
public void Transacted_left_unset_is_not_written_so_the_producer_follows_the_block()
{
var uri = AmqpDsl.Address("q").Build();
uri.Should().NotContain("transacted");
}
[Fact]
public void Declare_SetsParam()
{
var uri = AmqpDsl.Address("q").Declare().Build();
uri.Should().Contain("declare=true");
}
[Fact]
public void RoutingType_SetsParam()
{
var uri = AmqpDsl.Address("q").RoutingType("MULTICAST").Build();
uri.Should().Contain("routingType=MULTICAST");
}
// ── Conversion ──────────────────────────────────────────────────
[Fact]
public void ImplicitConversion_ReturnsUri()
{
string uri = AmqpDsl.Address("notifications").Host("broker1");
uri.Should().StartWith("amqp:notifications?");
}
[Fact]
public void ToString_ReturnsSameAsBuild()
{
var builder = AmqpDsl.Address("q").Host("broker1").User("admin");
builder.ToString().Should().Be(builder.Build());
}
// ── Full chain ──────────────────────────────────────────────────
[Fact]
public void FullChain_BuildsCorrectUri()
{
var uri = AmqpDsl.Address("orders")
.Host("amqp.example.com")
.Port(5672)
.User("admin")
.Password("secret")
.ConcurrentConsumers(4)
.Transacted()
.Declare()
.Build();
uri.Should().StartWith("amqp:orders?");
uri.Should().Contain("host=amqp.example.com");
uri.Should().Contain("port=5672");
uri.Should().Contain("concurrentConsumers=4");
uri.Should().Contain("transacted=true");
uri.Should().Contain("declare=true");
}
// ── Round-trip ──────────────────────────────────────────────────
[Fact]
public void RoundTrip_ParseAndReconstruct()
{
var original = AmqpDsl.Address("q").Host("broker1").Port(5672).Build();
var parsed = EndpointUriParser.Parse(original);
parsed.Scheme.Should().Be("amqp");
parsed.Path.Should().Be("q");
parsed.RawParameters["host"].Should().Be("broker1");
parsed.RawParameters["port"].Should().Be("5672");
}
}
Path: redb-route/tests/redb.Route.Tests.Amqp/AmqpComponentTests.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/tests/redb.Route.Tests.Amqp/AmqpComponentTests.cs
----
using redb.Route.Core;
using redb.Route.Amqp;
namespace redb.Route.Tests.Amqp;
public sealed class AmqpComponentTests
{
private readonly AmqpComponent _sut = new();
[Fact]
public void Scheme_ReturnsAmqp()
{
_sut.Scheme.Should().Be("amqp");
}
[Fact]
public void CreateEndpoint_ValidUri_ReturnsAmqpEndpoint()
{
var uri = EndpointUriParser.Parse("amqp://my-queue?host=localhost");
var endpoint = _sut.CreateEndpoint(uri);
endpoint.Should().BeOfType();
var ep = (AmqpEndpoint)endpoint;
ep.Address.Should().Be("my-queue");
}
[Fact]
public void CreateEndpoint_NullUri_Throws()
{
var act = () => _sut.CreateEndpoint(null!);
act.Should().Throw();
}
[Fact]
public void CreateEndpoint_WithConnectionParams_ParsesCorrectly()
{
var uri = EndpointUriParser.Parse(
"amqp://orders?host=broker1&port=5673&user=admin&password=secret&ssl=true");
var endpoint = (AmqpEndpoint)_sut.CreateEndpoint(uri);
endpoint.Address.Should().Be("orders");
}
[Fact]
public void CreateEndpoint_WithCapabilitiesAndRouting_ParsesCorrectly()
{
var uri = EndpointUriParser.Parse(
"amqp://my-topic?host=localhost&capabilities=topic,shared&routingType=MULTICAST&durable=2");
var endpoint = (AmqpEndpoint)_sut.CreateEndpoint(uri);
endpoint.Address.Should().Be("my-topic");
}
[Fact]
public void CreateEndpoint_WithConsumerOptions_ParsesCorrectly()
{
var uri = EndpointUriParser.Parse(
"amqp://q1?host=localhost&credit=50&concurrentConsumers=4&ackMode=auto&receiveTimeout=30");
var endpoint = (AmqpEndpoint)_sut.CreateEndpoint(uri);
endpoint.Address.Should().Be("q1");
}
[Fact]
public void CreateEndpoint_WithRpcOptions_ParsesCorrectly()
{
var uri = EndpointUriParser.Parse("amqp://rpc-queue?host=localhost&replyTo=true&timeout=15");
var endpoint = (AmqpEndpoint)_sut.CreateEndpoint(uri);
endpoint.Address.Should().Be("rpc-queue");
}
[Fact]
public void CreateEndpoint_WithProducerDefaults_ParsesCorrectly()
{
var uri = EndpointUriParser.Parse(
"amqp://events?host=localhost&messageDurable=false&messagePriority=7&messageTtl=60000&contentType=application/json");
var endpoint = (AmqpEndpoint)_sut.CreateEndpoint(uri);
endpoint.Address.Should().Be("events");
}
[Fact]
public void CreateEndpoint_WithSettlementModes_ParsesCorrectly()
{
var uri = EndpointUriParser.Parse(
"amqp://q?host=localhost&senderSettleMode=1&receiverSettleMode=1");
var endpoint = (AmqpEndpoint)_sut.CreateEndpoint(uri);
endpoint.Address.Should().Be("q");
}
[Fact]
public void CreateEndpoint_WithTransactedMode_ParsesCorrectly()
{
var uri = EndpointUriParser.Parse("amqp://tx-queue?host=localhost&transacted=true");
var endpoint = (AmqpEndpoint)_sut.CreateEndpoint(uri);
endpoint.Address.Should().Be("tx-queue");
}
}
Path: redb-route/tests/redb.Route.Tests.Amqp/AmqpConcurrencyTests.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/tests/redb.Route.Tests.Amqp/AmqpConcurrencyTests.cs
----
using System.Collections.Concurrent;
using System.Text;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Amqp;
using Xunit.Abstractions;
namespace redb.Route.Tests.Amqp;
///
/// End-to-end regression tests for the consumer-concurrency fix: ConcurrentConsumers(N) must
/// actually process up to N messages in parallel (it used to be a dead semaphore on a serial receive
/// loop). Expects an AMQP 1.0 broker (ActiveMQ Artemis) at localhost:5673 (admin/admin).
///
[Trait("Category", "Integration")]
public sealed class AmqpConcurrencyTests
{
private const string Host = "localhost";
private const int Port = 5673;
private const string User = "admin";
private const string Password = "admin";
private readonly ITestOutputHelper _output;
public AmqpConcurrencyTests(ITestOutputHelper output) => _output = output;
private static AmqpEndpoint CreateEndpoint(string address, string? extraParams = null)
{
var qs = $"host={Host}&port={Port}&user={User}&password={Password}";
if (extraParams is not null) qs += $"&{extraParams}";
var uri = EndpointUriParser.Parse($"amqp://{address}?{qs}");
var component = new AmqpComponent();
return (AmqpEndpoint)component.CreateEndpoint(uri);
}
private static async Task PublishAsync(string address, IEnumerable bodies)
{
var ep = CreateEndpoint(address);
var producer = (AmqpProducer)ep.CreateProducer();
await producer.Start();
foreach (var b in bodies)
await producer.Process(new Exchange(new Message(b)));
await producer.Stop();
await ep.Stop();
}
[Fact]
public async Task ConcurrentConsumers_ProcessesInParallel()
{
// Before the fix: a single serial receive loop awaited Process inline, so max concurrency was
// always 1 regardless of ConcurrentConsumers. Now N workers = N competing consumers.
const int concurrency = 5;
const int messageCount = 20;
var address = $"conc.{Guid.NewGuid():N}";
await PublishAsync(address, Enumerable.Range(0, messageCount).Select(i => $"msg-{i}"));
// credit=1 keeps each competing consumer holding a single unsettled message at a time, so the
// broker load-balances fairly across the N workers (a high credit lets one worker's prefetch
// buffer hoard the queue and process it serially — real behaviour, tune credit for balancing).
var epCons = CreateEndpoint(address, $"concurrentConsumers={concurrency}&credit=1");
var current = 0;
var maxConcurrent = 0;
var processed = 0;
var gate = new object();
var allDone = new TaskCompletionSource();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(async _ =>
{
var now = Interlocked.Increment(ref current);
lock (gate) { if (now > maxConcurrent) maxConcurrent = now; }
await Task.Delay(250);
Interlocked.Decrement(ref current);
if (Interlocked.Increment(ref processed) >= messageCount) allDone.TrySetResult();
});
var consumer = (AmqpConsumer)epCons.CreateConsumer(processor);
await consumer.Start();
await Task.WhenAny(allDone.Task, Task.Delay(25_000));
await consumer.Stop();
await epCons.Stop();
_output.WriteLine($"processed={processed}, maxConcurrent={maxConcurrent}");
processed.Should().BeGreaterThanOrEqualTo(messageCount);
maxConcurrent.Should().BeGreaterThan(1,
"ConcurrentConsumers(5) must process deliveries in parallel — the serial-loop bug caps this at 1");
maxConcurrent.Should().BeGreaterThanOrEqualTo(3,
"with 5 competing consumers and 20 queued messages, several should run at once");
}
[Fact]
public async Task ConcurrentConsumersOne_ProcessesSerially()
{
// Lower bound: the default (1) must stay strictly serial, proving the knob gates parallelism.
const int messageCount = 8;
var address = $"serial.{Guid.NewGuid():N}";
await PublishAsync(address, Enumerable.Range(0, messageCount).Select(i => $"msg-{i}"));
var epCons = CreateEndpoint(address, "concurrentConsumers=1");
var current = 0;
var maxConcurrent = 0;
var processed = 0;
var gate = new object();
var allDone = new TaskCompletionSource();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(async _ =>
{
var now = Interlocked.Increment(ref current);
lock (gate) { if (now > maxConcurrent) maxConcurrent = now; }
await Task.Delay(100);
Interlocked.Decrement(ref current);
if (Interlocked.Increment(ref processed) >= messageCount) allDone.TrySetResult();
});
var consumer = (AmqpConsumer)epCons.CreateConsumer(processor);
await consumer.Start();
await Task.WhenAny(allDone.Task, Task.Delay(15_000));
await consumer.Stop();
await epCons.Stop();
_output.WriteLine($"processed={processed}, maxConcurrent={maxConcurrent}");
processed.Should().BeGreaterThanOrEqualTo(messageCount);
maxConcurrent.Should().Be(1, "ConcurrentConsumers(1) must process strictly one message at a time");
}
[Fact]
public async Task ConcurrentConsumers_AllMessagesProcessedExactlyOnce()
{
// Competing consumers must SHARE the queue (anycast), not each get a copy: every message is
// processed, and the total count equals what was published (no duplication, no loss).
const int concurrency = 4;
const int messageCount = 40;
var address = $"share.{Guid.NewGuid():N}";
await PublishAsync(address, Enumerable.Range(0, messageCount).Select(i => $"m-{i}"));
var epCons = CreateEndpoint(address, $"concurrentConsumers={concurrency}");
var received = new ConcurrentBag();
var allDone = new TaskCompletionSource();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(ci =>
{
received.Add(Encoding.UTF8.GetString((byte[])ci.Arg().In.Body!));
if (received.Count >= messageCount) allDone.TrySetResult();
return Task.CompletedTask;
});
var consumer = (AmqpConsumer)epCons.CreateConsumer(processor);
await consumer.Start();
await Task.WhenAny(allDone.Task, Task.Delay(20_000));
await consumer.Stop();
await epCons.Stop();
var distinct = received.Distinct().ToList();
_output.WriteLine($"received={received.Count}, distinct={distinct.Count}");
distinct.Count.Should().Be(messageCount, "every published message is delivered exactly once across the competing consumers");
received.Count.Should().Be(messageCount, "competing consumers share the queue — no duplicate delivery");
}
}
Path: redb-route/tests/redb.Route.Tests.Amqp/AmqpConnectionFactoryTests.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/tests/redb.Route.Tests.Amqp/AmqpConnectionFactoryTests.cs
----
using redb.Route.Amqp;
namespace redb.Route.Tests.Amqp;
public sealed class AmqpConnectionFactoryTests
{
[Fact]
public void Defaults_AreReasonable()
{
var factory = new AmqpConnectionFactory();
factory.Host.Should().Be("localhost");
factory.Port.Should().Be(5672);
factory.User.Should().BeNull();
factory.Password.Should().BeNull();
factory.ContainerId.Should().BeNull();
factory.VirtualHost.Should().BeNull();
factory.IdleTimeout.Should().Be(120_000);
factory.MaxFrameSize.Should().Be(256 * 1024);
factory.MaxSessions.Should().Be(8);
factory.NoDelay.Should().BeTrue();
factory.KeepAlive.Should().BeFalse();
factory.Ssl.Should().BeFalse();
factory.SaslMechanism.Should().Be(SaslMechanism.Auto);
}
[Fact]
public void Build_ReturnsConfiguredConnectionFactory()
{
var factory = new AmqpConnectionFactory
{
Host = "broker-host",
Port = 5673,
User = "admin",
Password = "secret",
VirtualHost = "/myVhost",
IdleTimeout = 60_000,
MaxFrameSize = 512 * 1024,
MaxSessions = 16,
};
var result = factory.Build();
result.Should().NotBeNull();
result.AMQP.HostName.Should().Be("/myVhost");
result.AMQP.IdleTimeout.Should().Be(60_000);
result.AMQP.MaxFrameSize.Should().Be(512 * 1024);
result.AMQP.MaxSessionsPerConnection.Should().Be(16);
}
[Fact]
public void Build_WithKeepAlive_ConfiguresTcpKeepAlive()
{
var factory = new AmqpConnectionFactory { KeepAlive = true };
var result = factory.Build();
result.TCP.KeepAlive.Should().NotBeNull();
}
[Fact]
public void Build_NoKeepAlive_TcpKeepAliveIsNull()
{
var factory = new AmqpConnectionFactory { KeepAlive = false };
var result = factory.Build();
result.TCP.KeepAlive.Should().BeNull();
}
[Fact]
public void Build_WithNoDelay_ConfiguresTcpNoDelay()
{
var factory = new AmqpConnectionFactory { NoDelay = true };
var result = factory.Build();
result.TCP.NoDelay.Should().BeTrue();
}
[Fact]
public void Build_GeneratesContainerId_WhenNotSet()
{
var factory = new AmqpConnectionFactory();
var result = factory.Build();
result.AMQP.ContainerId.Should().StartWith("redb-route-");
}
[Fact]
public void Build_UsesExplicitContainerId()
{
var factory = new AmqpConnectionFactory { ContainerId = "my-container" };
var result = factory.Build();
result.AMQP.ContainerId.Should().Be("my-container");
}
[Fact]
public void Build_UsesClientNameAsContainerIdFallback()
{
var factory = new AmqpConnectionFactory { ClientName = "my-app" };
var result = factory.Build();
result.AMQP.ContainerId.Should().Be("my-app");
}
[Fact]
public void Build_ContainerIdTakesPriorityOverClientName()
{
var factory = new AmqpConnectionFactory { ContainerId = "container-1", ClientName = "app-1" };
var result = factory.Build();
result.AMQP.ContainerId.Should().Be("container-1");
}
[Fact]
public void BuildAddress_DefaultAmqp()
{
var factory = new AmqpConnectionFactory();
var addr = factory.BuildAddress();
addr.Scheme.Should().BeOneOf("amqp", "AMQP");
addr.Host.Should().Be("localhost");
addr.Port.Should().Be(5672);
}
[Fact]
public void BuildAddress_WithSsl_ReturnsAmqps()
{
var factory = new AmqpConnectionFactory { Ssl = true, Port = 5671 };
var addr = factory.BuildAddress();
addr.Scheme.Should().BeOneOf("amqps", "AMQPS");
addr.Port.Should().Be(5671);
}
[Fact]
public void BuildAddress_WithCredentials()
{
var factory = new AmqpConnectionFactory { User = "admin", Password = "pass" };
var addr = factory.BuildAddress();
addr.User.Should().Be("admin");
addr.Password.Should().Be("pass");
}
[Fact]
public void GetAddresses_SingleHost_ReturnsOneAddress()
{
var factory = new AmqpConnectionFactory { Host = "broker1", Port = 5672 };
var addrs = factory.GetAddresses();
addrs.Should().HaveCount(1);
addrs[0].Host.Should().Be("broker1");
addrs[0].Port.Should().Be(5672);
}
[Fact]
public void GetAddresses_ClusterHosts_ReturnsMultiple()
{
var factory = new AmqpConnectionFactory { Host = "b1, b2, b3", Port = 5672 };
var addrs = factory.GetAddresses();
addrs.Should().HaveCount(3);
addrs[0].Host.Should().Be("b1");
addrs[1].Host.Should().Be("b2");
addrs[2].Host.Should().Be("b3");
}
[Fact]
public void GetAddresses_WithSsl_AllUseAmqps()
{
var factory = new AmqpConnectionFactory { Host = "a, b", Port = 5671, Ssl = true };
var addrs = factory.GetAddresses();
addrs.Should().HaveCount(2);
foreach (var addr in addrs)
addr.Scheme.Should().BeOneOf("amqps", "AMQPS");
}
[Fact]
public void Build_WithSslEnabled_DoesNotThrow()
{
var factory = new AmqpConnectionFactory
{
Ssl = true,
TrustAllCertificates = true,
};
var act = () => factory.Build();
act.Should().NotThrow();
}
[Fact]
public void Build_WithBufferSizes_ConfiguresTcpBuffers()
{
var factory = new AmqpConnectionFactory
{
SendBufferSize = 65536,
ReceiveBufferSize = 131072,
SendTimeout = 5000,
ReceiveTimeout = 10000,
};
var result = factory.Build();
result.TCP.SendBufferSize.Should().Be(65536);
result.TCP.ReceiveBufferSize.Should().Be(131072);
result.TCP.SendTimeout.Should().Be(5000);
result.TCP.ReceiveTimeout.Should().Be(10000);
}
}
Path: redb-route/tests/redb.Route.Tests.Amqp/AmqpConnectionPoolIntegrationTests.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/tests/redb.Route.Tests.Amqp/AmqpConnectionPoolIntegrationTests.cs
----
using redb.Route.Abstractions;
using redb.Route.Amqp;
using redb.Route.Core;
using Xunit.Abstractions;
namespace redb.Route.Tests.Amqp;
///
/// Integration tests for the connection pool against a live AMQP 1.0
/// broker (ActiveMQ Artemis). Validates the new shared-connection model: identical inline
/// parameters share one underlying Connection, named factories partition by name,
/// endpoint Stop does not affect the pool, and component DisposeAsync drains the pool.
///
[Trait("Category", "Integration")]
public sealed class AmqpConnectionPoolIntegrationTests
{
private const string Host = "localhost";
private const int Port = 5673;
private const string User = "admin";
private const string Password = "admin";
private readonly ITestOutputHelper _output;
public AmqpConnectionPoolIntegrationTests(ITestOutputHelper output) => _output = output;
private static AmqpEndpoint CreateEndpoint(AmqpComponent component, string address, string? extraParams = null)
{
var qs = $"host={Host}&port={Port}&user={User}&password={Password}";
if (extraParams is not null) qs += $"&{extraParams}";
var uri = EndpointUriParser.Parse($"amqp://{address}?{qs}");
return (AmqpEndpoint)component.CreateEndpoint(uri);
}
[Fact]
public async Task Pool_TwoEndpointsIdenticalParams_ShareSingleConnection()
{
var component = new AmqpComponent();
var addrA = $"pool.share.a.{Guid.NewGuid():N}";
var addrB = $"pool.share.b.{Guid.NewGuid():N}";
var epA = CreateEndpoint(component, addrA);
var epB = CreateEndpoint(component, addrB);
var pa = (AmqpProducer)epA.CreateProducer();
var pb = (AmqpProducer)epB.CreateProducer();
await pa.Start();
await pb.Start();
component.PooledConnectionCount.Should().Be(1, "both endpoints have identical inline params");
var conns = await component.GetPooledConnectionsAsync();
conns.Should().HaveCount(1);
conns[0].IsClosed.Should().BeFalse();
await pa.Process(new Exchange(new Message("from-a")));
await pb.Process(new Exchange(new Message("from-b")));
await pa.Stop(); await pb.Stop();
await epA.Stop(); await epB.Stop();
await component.DisposeAsync();
_output.WriteLine("AMQP shared connection: 2 endpoints, 1 Connection.");
}
[Fact]
public async Task Pool_DifferentFactoryNames_ProduceDistinctConnections()
{
var component = new AmqpComponent();
var ctx = new RouteContext();
ctx.AddComponent(component);
var f1 = new AmqpConnectionFactory
{ Host = Host, Port = Port, User = User, Password = Password };
var f2 = new AmqpConnectionFactory
{ Host = Host, Port = Port, User = User, Password = Password };
ctx.AddToRegistry("amqp-1", f1);
ctx.AddToRegistry("amqp-2", f2);
var addrA = $"pool.fac.a.{Guid.NewGuid():N}";
var addrB = $"pool.fac.b.{Guid.NewGuid():N}";
var epA = CreateEndpoint(component, addrA, "connectionFactory=amqp-1");
var epB = CreateEndpoint(component, addrB, "connectionFactory=amqp-2");
var pa = (AmqpProducer)epA.CreateProducer();
var pb = (AmqpProducer)epB.CreateProducer();
await pa.Start();
await pb.Start();
component.PooledConnectionCount.Should().Be(2,
"two named factories produce two distinct pooled connections even when params match");
var conns = await component.GetPooledConnectionsAsync();
conns.Should().HaveCount(2);
conns.Should().OnlyContain(c => !c.IsClosed);
ReferenceEquals(conns[0], conns[1]).Should().BeFalse();
await pa.Stop(); await pb.Stop();
await epA.Stop(); await epB.Stop();
await ctx.DisposeAsync();
}
///
/// The URI names only the factory, and the broker is not where the URI defaults point (localhost:5672): the
/// connection goes where the factory says. It used to take host, port and credentials from the URI defaults.
///
[Fact]
public async Task A_named_factory_alone_takes_the_connection_to_its_own_broker()
{
var component = new AmqpComponent();
await using var ctx = new RouteContext();
ctx.AddComponent(component);
ctx.AddToRegistry("broker", new AmqpConnectionFactory { Host = Host, Port = Port, User = User, Password = Password });
var address = $"pool.factory-only.{Guid.NewGuid():N}";
var endpoint = (AmqpEndpoint)component.CreateEndpoint(
EndpointUriParser.Parse($"amqp://{address}?connectionFactory=broker"));
var producer = (AmqpProducer)endpoint.CreateProducer();
await producer.Start();
await producer.Process(new Exchange(new Message("through the factory")));
var conns = await component.GetPooledConnectionsAsync();
conns.Should().ContainSingle().Which.IsClosed.Should().BeFalse();
await producer.Stop();
await endpoint.Stop();
}
[Fact]
public async Task Pool_StopOneEndpoint_PooledConnectionRemains_OtherEndpointStillWorks()
{
var component = new AmqpComponent();
var addrA = $"pool.stop.a.{Guid.NewGuid():N}";
var addrB = $"pool.stop.b.{Guid.NewGuid():N}";
var epA = CreateEndpoint(component, addrA);
var epB = CreateEndpoint(component, addrB);
var prodA = (AmqpProducer)epA.CreateProducer();
var prodB = (AmqpProducer)epB.CreateProducer();
await prodA.Start();
await prodB.Start();
component.PooledConnectionCount.Should().Be(1);
await prodA.Stop();
await epA.Stop();
var conns = await component.GetPooledConnectionsAsync();
conns.Should().HaveCount(1);
conns[0].IsClosed.Should().BeFalse("pooled connection survives endpoint Stop");
await prodB.Process(new Exchange(new Message("after-a-stopped")));
await prodB.Stop();
await epB.Stop();
await component.DisposeAsync();
}
[Fact]
public async Task Pool_DisposeAsync_ClosesAllPooledConnections()
{
var component = new AmqpComponent();
var address = $"pool.dispose.{Guid.NewGuid():N}";
var endpoint = CreateEndpoint(component, address);
var producer = (AmqpProducer)endpoint.CreateProducer();
await producer.Start();
await producer.Process(new Exchange(new Message("dispose-test")));
var conns = await component.GetPooledConnectionsAsync();
conns.Should().HaveCount(1);
var pooled = conns[0];
pooled.IsClosed.Should().BeFalse();
await producer.Stop();
await endpoint.Stop();
await component.DisposeAsync();
pooled.IsClosed.Should().BeTrue("DisposeAsync must close all pooled Connection instances");
component.PooledConnectionCount.Should().Be(0);
}
[Fact]
public async Task Pool_RestartEndpoint_ReusesPooledConnection()
{
// Validates lifecycle: Stop+restart of the endpoint reuses the already-pooled connection.
var component = new AmqpComponent();
var address = $"pool.restart.{Guid.NewGuid():N}";
var epA = CreateEndpoint(component, address);
var prodA = (AmqpProducer)epA.CreateProducer();
await prodA.Start();
await prodA.Process(new Exchange(new Message("first")));
var initial = (await component.GetPooledConnectionsAsync())[0];
await prodA.Stop();
await epA.Stop();
// Pooled connection survives Stop
var afterStop = await component.GetPooledConnectionsAsync();
afterStop.Should().HaveCount(1);
afterStop[0].IsClosed.Should().BeFalse();
ReferenceEquals(afterStop[0], initial).Should().BeTrue();
// Recreate endpoint with same params; new producer must use the existing pooled conn.
var epB = CreateEndpoint(component, address);
var prodB = (AmqpProducer)epB.CreateProducer();
await prodB.Start();
await prodB.Process(new Exchange(new Message("second")));
component.PooledConnectionCount.Should().Be(1);
var conns = await component.GetPooledConnectionsAsync();
ReferenceEquals(conns[0], initial).Should().BeTrue("pool reuses the existing Connection");
await prodB.Stop();
await epB.Stop();
await component.DisposeAsync();
}
}
Path: redb-route/tests/redb.Route.Tests.Amqp/AmqpConnectionPoolTests.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/tests/redb.Route.Tests.Amqp/AmqpConnectionPoolTests.cs
----
using redb.Route.Amqp;
using redb.Route.Core;
namespace redb.Route.Tests.Amqp;
///
/// Pure-logic tests for the AMQP connection-pool key resolution implemented in
/// . Same identity model as RabbitMQ: factory-name keyed,
/// inline auto-deduplicated.
///
public sealed class AmqpConnectionPoolTests
{
private static AmqpEndpointOptions OptionsFromUri(string uri)
{
var parsed = EndpointUriParser.Parse(uri);
var opts = new AmqpEndpointOptions();
opts.BindFromUri(parsed.RawParameters);
opts.Validate();
return opts;
}
[Fact]
public void ResolveKey_FactoryName_ProducesFactoryKey()
{
var opts = OptionsFromUri("amqp://addr?host=h&connectionFactory=primary");
AmqpComponent.ResolveConnectionKey(opts).Should().Be("factory:primary");
}
[Fact]
public void ResolveKey_NoFactory_ProducesInlineKey()
{
var opts = OptionsFromUri("amqp://addr?host=broker&port=5672&user=alice");
var key = AmqpComponent.ResolveConnectionKey(opts);
key.Should().StartWith("inline:broker:5672/").And.EndWith("@alice");
}
[Fact]
public void ResolveKey_TwoFactoriesDifferentNamesSameInlineParams_ProduceDistinctKeys()
{
var a = OptionsFromUri("amqp://q?host=h&connectionFactory=conn1");
var b = OptionsFromUri("amqp://q?host=h&connectionFactory=conn2");
AmqpComponent.ResolveConnectionKey(a).Should().Be("factory:conn1");
AmqpComponent.ResolveConnectionKey(b).Should().Be("factory:conn2");
}
[Fact]
public void ResolveKey_TwoEndpointsIdenticalInlineParams_ShareKey()
{
var a = OptionsFromUri("amqp://qA?host=h&port=5672&user=u");
var b = OptionsFromUri("amqp://qB?host=h&port=5672&user=u");
AmqpComponent.ResolveConnectionKey(a)
.Should().Be(AmqpComponent.ResolveConnectionKey(b));
}
[Fact]
public void ResolveKey_DifferentInlineHosts_ProduceDistinctKeys()
{
var a = OptionsFromUri("amqp://q?host=h1&user=u");
var b = OptionsFromUri("amqp://q?host=h2&user=u");
AmqpComponent.ResolveConnectionKey(a)
.Should().NotBe(AmqpComponent.ResolveConnectionKey(b));
}
[Fact]
public void ResolveKey_InlineWithSsl_AppendsSslMarker()
{
var opts = OptionsFromUri("amqp://addr?host=secure&port=5671&user=u&ssl=true");
AmqpComponent.ResolveConnectionKey(opts).Should().EndWith("#ssl");
}
///
/// connectionFactory= takes the whole connection from the registry factory: host, port, credentials and TLS. The
/// address used to come from the URI options, so a factory's broker other than localhost:5672 was never reached.
///
[Fact]
public async Task A_named_factory_gives_the_connection_its_host_port_credentials_and_tls()
{
var component = new AmqpComponent();
await using var context = new RouteContext();
context.AddComponent(component);
context.AddToRegistry("broker", new AmqpConnectionFactory
{
Host = "artemis.internal, artemis-2.internal", Port = 5999, User = "svc", Password = "pw", Ssl = true,
});
var settings = component.ResolveConnectionSettings(OptionsFromUri("amqp://orders?connectionFactory=broker"));
var address = AmqpComponent.ConnectionAddress(settings);
address.Host.Should().Be("artemis.internal");
address.Port.Should().Be(5999);
address.User.Should().Be("svc");
address.Password.Should().Be("pw");
address.Scheme.Should().Be("amqps");
}
[Fact]
public async Task Without_a_factory_the_connection_takes_the_URI_parameters()
{
var component = new AmqpComponent();
await using var context = new RouteContext();
context.AddComponent(component);
var settings = component.ResolveConnectionSettings(
OptionsFromUri("amqp://orders?host=broker-a,broker-b&port=5673&user=alice&password=secret"));
var address = AmqpComponent.ConnectionAddress(settings);
address.Host.Should().Be("broker-a");
address.Port.Should().Be(5673);
address.User.Should().Be("alice");
address.Scheme.Should().Be("amqp");
}
[Fact]
public async Task An_unknown_factory_name_fails_instead_of_using_the_URI()
{
var component = new AmqpComponent();
await using var context = new RouteContext();
context.AddComponent(component);
var resolve = () => component.ResolveConnectionSettings(OptionsFromUri("amqp://orders?connectionFactory=missing"));
resolve.Should().Throw().WithMessage("*missing*");
}
[Fact]
public void Component_DisposeAsync_OnEmptyPool_DoesNotThrow()
{
var component = new AmqpComponent();
var act = async () => await component.DisposeAsync();
act.Should().NotThrowAsync();
}
}
Path: redb-route/tests/redb.Route.Tests.Amqp/AmqpConsumerReattachTests.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/tests/redb.Route.Tests.Amqp/AmqpConsumerReattachTests.cs
----
using System.Collections.Concurrent;
using System.Net;
using System.Net.Sockets;
using Amqp;
using Amqp.Framing;
using Amqp.Listener;
using redb.Route.Abstractions;
using redb.Route.Amqp;
using redb.Route.Configuration;
using redb.Route.Core;
using AmqpMessage = global::Amqp.Message;
namespace redb.Route.Tests.Amqp;
///
/// The AMQP consumer attaches its receiver link again when the broker takes it away, on the connection supervisor of
/// its worker (F-6). The broker is AMQPNetLite's own in the test process: it can detach a
/// link while the connection stays, and drop every connection by closing. Single and batch, and a stop while the
/// consumer waits for a broker that does not come back.
///
public sealed class AmqpConsumerReattachTests : IAsyncDisposable
{
private static readonly TimeSpan Wait = TimeSpan.FromSeconds(20);
private readonly int _port = FreePort();
private readonly Source _source = new();
private ContainerHost? _host;
public AmqpConsumerReattachTests() => OpenHost();
public ValueTask DisposeAsync()
{
_host?.Close();
return ValueTask.CompletedTask;
}
[Theory]
[InlineData("")]
[InlineData("&batching=true&maxBatchMessages=10&pollTimeoutMs=100")]
public async Task A_link_the_broker_detaches_is_attached_again_and_the_route_reads_on(string extra)
{
var (context, received, uri) = await StartAsync(extra);
await using (context)
{
_source.Enqueue("before");
(await Until(() => received.Contains("before"))).Should().BeTrue();
_source.DetachAll(new Error(new global::Amqp.Types.Symbol("amqp:link:detach-forced")) { Description = "test" });
_source.Enqueue("after");
(await Until(() => received.Contains("after"))).Should().BeTrue("the worker attaches its link again and reads on");
var statistics = (IEndpointStatistics)context.GetEndpoint(uri);
statistics.Reconnects.Should().Be(1, "the reattach is counted once");
statistics.HealthStatus.Should().Be(EndpointHealthStatus.Healthy);
context.GetRoute("reader")!.Status.Should().Be(RouteStatus.Started);
}
}
[Theory]
[InlineData("")]
[InlineData("&batching=true&maxBatchMessages=10&pollTimeoutMs=100")]
public async Task A_lost_connection_is_opened_again_and_the_link_attached_on_it(string extra)
{
var (context, received, uri) = await StartAsync(extra);
await using (context)
{
_source.Enqueue("before");
(await Until(() => received.Contains("before"))).Should().BeTrue();
_host!.Close();
var statistics = (IEndpointStatistics)context.GetEndpoint(uri);
(await Until(() => statistics.HealthStatus != EndpointHealthStatus.Healthy)).Should().BeTrue(
"health shows the lost link while it is away");
OpenHost();
(await Until(() => statistics.Reconnects == 1)).Should().BeTrue("the worker attaches its link on a new connection");
_source.Enqueue("after");
(await Until(() => received.Contains("after"))).Should().BeTrue();
statistics.HealthStatus.Should().Be(EndpointHealthStatus.Healthy);
}
}
[Fact]
public async Task A_stop_while_the_broker_is_away_ends_the_reattach_and_opens_nothing()
{
var (context, received, uri) = await StartAsync("");
_source.Enqueue("before");
(await Until(() => received.Contains("before"))).Should().BeTrue();
_host!.Close();
_host = null;
var statistics = (IEndpointStatistics)context.GetEndpoint(uri);
(await Until(() => statistics.HealthStatus != EndpointHealthStatus.Healthy)).Should().BeTrue();
var stop = context.Stop();
(await Task.WhenAny(stop, Task.Delay(Wait))).Should().BeSameAs(stop, "the stop ends the reattach loop");
await context.DisposeAsync();
statistics.Reconnects.Should().Be(0);
}
private async Task<(RouteContext Context, ConcurrentQueue Received, string Uri)> StartAsync(string extra)
{
var context = new RouteContext(options: new RouteEngineOptions
{
ShutdownTimeout = TimeSpan.FromSeconds(5),
Reconnect = new ReconnectOptions
{
Delay = TimeSpan.FromMilliseconds(100), MaxDelay = TimeSpan.FromMilliseconds(200),
AttemptTimeout = TimeSpan.FromSeconds(5),
},
});
context.AddComponent(new AmqpComponent());
var received = new ConcurrentQueue();
var uri = $"amqp://{Source.Address}?host=localhost&port={_port}&timeout=5&receiveTimeout=1{extra}";
context.AddRoutes(r => r.From(uri).RouteId("reader").Process(e =>
{
if (e.In.Body is IEnumerable batch)
foreach (var message in batch)
received.Enqueue(Text(message.Body));
else
received.Enqueue(Text(e.In.Body));
}));
await context.Start();
return (context, received, uri);
}
private void OpenHost()
{
var host = new ContainerHost(new Address($"amqp://localhost:{_port}"));
// The connector always opens a SASL layer (ANONYMOUS without a user).
host.Listeners[0].SASL.EnableAnonymousMechanism = true;
host.RegisterMessageSource(Source.Address, _source);
host.Open();
_host = host;
}
// The consumer hands the route the body as UTF-8 bytes.
private static string Text(object? body) => body is byte[] bytes ? System.Text.Encoding.UTF8.GetString(bytes) : body?.ToString() ?? "";
private static int FreePort()
{
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
listener.Stop();
return port;
}
private static async Task Until(Func condition)
{
var deadline = DateTime.UtcNow + Wait;
while (!condition())
{
if (DateTime.UtcNow > deadline)
return false;
await Task.Delay(50);
}
return true;
}
///
/// The address the consumer reads: hands out what the test enqueues, one message per credit, and keeps the links it
/// serves so the test can detach them as a broker does.
///
private sealed class Source : IMessageSource
{
public const string Address = "orders";
private readonly ConcurrentQueue _bodies = new();
private readonly SemaphoreSlim _available = new(0);
private readonly ConcurrentDictionary _links = new();
public void Enqueue(string body)
{
_bodies.Enqueue(body);
_available.Release();
}
public void DetachAll(Error error)
{
foreach (var link in _links.Keys)
{
_links.TryRemove(link, out _);
link.Close(TimeSpan.Zero, error);
}
}
public async Task GetMessageAsync(ListenerLink link)
{
_links.TryAdd(link, true);
while (true)
{
await _available.WaitAsync();
if (link.IsClosed)
{
_available.Release();
return null!;
}
if (_bodies.TryDequeue(out var body))
return new ReceiveContext(link, new AmqpMessage(body));
}
}
public void DisposeMessage(ReceiveContext receiveContext, DispositionContext dispositionContext)
=> dispositionContext.Complete();
}
}
Path: redb-route/tests/redb.Route.Tests.Amqp/AmqpConsumerTests.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/tests/redb.Route.Tests.Amqp/AmqpConsumerTests.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Amqp;
namespace redb.Route.Tests.Amqp;
public sealed class AmqpConsumerTests
{
private readonly AmqpComponent _component = new();
private AmqpEndpoint CreateEndpoint(string uriStr)
{
var uri = EndpointUriParser.Parse(uriStr);
return (AmqpEndpoint)_component.CreateEndpoint(uri);
}
[Fact]
public void Ctor_NullEndpoint_Throws()
{
var opts = new AmqpEndpointOptions();
var proc = Substitute.For();
var act = () => new AmqpConsumer(null!, proc, opts);
act.Should().Throw();
}
[Fact]
public void Ctor_NullProcessor_Throws()
{
var ep = CreateEndpoint("amqp://q?host=localhost");
var opts = new AmqpEndpointOptions();
var act = () => new AmqpConsumer(ep, null!, opts);
act.Should().Throw();
}
[Fact]
public void Ctor_NullOptions_Throws()
{
var ep = CreateEndpoint("amqp://q?host=localhost");
var proc = Substitute.For();
var act = () => new AmqpConsumer(ep, proc, null!);
act.Should().Throw();
}
[Fact]
public void ProcessedCount_InitiallyZero()
{
var ep = CreateEndpoint("amqp://q?host=localhost");
var proc = Substitute.For();
var opts = new AmqpEndpointOptions();
var consumer = new AmqpConsumer(ep, proc, opts);
consumer.ProcessedCount.Should().Be(0);
}
}
Path: redb-route/tests/redb.Route.Tests.Amqp/AmqpEndpointOptionsTests.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/tests/redb.Route.Tests.Amqp/AmqpEndpointOptionsTests.cs
----
using redb.Route.Core;
using redb.Route.Amqp;
namespace redb.Route.Tests.Amqp;
public sealed class AmqpEndpointOptionsTests
{
[Fact]
public void Defaults_AreReasonable()
{
var opts = new AmqpEndpointOptions();
opts.Host.Should().Be("localhost");
opts.Port.Should().Be(5672);
opts.User.Should().BeNull();
opts.Password.Should().BeNull();
opts.Ssl.Should().BeFalse();
opts.Durable.Should().Be(0u);
opts.ExpiryPolicy.Should().Be("session-end");
opts.DistributionMode.Should().BeNull();
opts.Dynamic.Should().BeFalse();
opts.FilterSelector.Should().BeNull();
opts.Capabilities.Should().BeNull();
opts.SenderSettleMode.Should().Be(2);
opts.ReceiverSettleMode.Should().Be(0);
opts.Credit.Should().Be(100);
opts.AckMode.Should().Be(AckMode.Manual);
opts.ResolvedConcurrentConsumers.Should().Be(1);
opts.ReceiveTimeout.Should().Be(60);
opts.MessageDurable.Should().BeTrue();
opts.MessagePriority.Should().Be(4);
opts.MessageTtl.Should().Be(0u);
opts.ContentType.Should().Be("text/plain");
opts.Subject.Should().BeNull();
opts.GroupId.Should().BeNull();
opts.ReplyTo.Should().BeFalse();
opts.Timeout.Should().Be(30);
opts.Transacted.Should().BeNull("unset, a producer follows the enclosing .Transacted() block");
opts.Declare.Should().BeFalse();
opts.RoutingType.Should().Be("ANYCAST");
}
[Fact]
public void Validate_InvalidPort_Throws()
{
var opts = new AmqpEndpointOptions { Port = 0 };
var act = () => opts.Validate();
act.Should().Throw().WithMessage("*port*");
}
[Fact]
public void Validate_PortTooHigh_Throws()
{
var opts = new AmqpEndpointOptions { Port = 99999 };
var act = () => opts.Validate();
act.Should().Throw().WithMessage("*port*");
}
[Fact]
public void Validate_NegativeCredit_Throws()
{
var opts = new AmqpEndpointOptions { Credit = -1 };
var act = () => opts.Validate();
act.Should().Throw().WithMessage("*credit*");
}
[Fact]
public void Validate_ZeroConcurrentConsumers_Throws()
{
var opts = new AmqpEndpointOptions { ConcurrentConsumers = "0" };
var act = () => opts.Validate();
act.Should().Throw().WithMessage("*concurrentConsumers*");
}
[Fact]
public void Validate_InvalidSenderSettleMode_Throws()
{
var opts = new AmqpEndpointOptions { SenderSettleMode = 5 };
var act = () => opts.Validate();
act.Should().Throw().WithMessage("*SenderSettleMode*");
}
[Fact]
public void Validate_InvalidReceiverSettleMode_Throws()
{
var opts = new AmqpEndpointOptions { ReceiverSettleMode = 3 };
var act = () => opts.Validate();
act.Should().Throw().WithMessage("*ReceiverSettleMode*");
}
[Fact]
public void Validate_InvalidDurable_Throws()
{
var opts = new AmqpEndpointOptions { Durable = 5 };
var act = () => opts.Validate();
act.Should().Throw().WithMessage("*Durable*");
}
[Fact]
public void Validate_ValidOptions_DoesNotThrow()
{
var opts = new AmqpEndpointOptions
{
Port = 5673,
Credit = 50,
ConcurrentConsumers = "4",
SenderSettleMode = 1,
ReceiverSettleMode = 1,
Durable = 2,
};
var act = () => opts.Validate();
act.Should().NotThrow();
}
// ── ResolveCapabilities ──
[Fact]
public void ResolveCapabilities_DefaultAnycast_IncludesQueue()
{
var opts = new AmqpEndpointOptions { RoutingType = "ANYCAST" };
var caps = opts.ResolveCapabilities();
caps.Should().Contain("queue");
}
[Fact]
public void ResolveCapabilities_Multicast_IncludesTopic()
{
var opts = new AmqpEndpointOptions { RoutingType = "MULTICAST" };
var caps = opts.ResolveCapabilities();
caps.Should().Contain("topic");
}
[Fact]
public void ResolveCapabilities_ExplicitCapabilities_Combined()
{
var opts = new AmqpEndpointOptions
{
Capabilities = "shared,global",
RoutingType = "MULTICAST"
};
var caps = opts.ResolveCapabilities();
caps.Should().Contain("shared");
caps.Should().Contain("global");
caps.Should().Contain("topic");
}
[Fact]
public void ResolveCapabilities_NoDuplicateWhenCapMatchesRouting()
{
var opts = new AmqpEndpointOptions
{
Capabilities = "queue",
RoutingType = "ANYCAST"
};
var caps = opts.ResolveCapabilities();
caps.Count(c => c == "queue").Should().Be(1);
}
// ── ResolveExpiryPolicy ──
[Fact]
public void ResolveExpiryPolicy_SessionEnd_Default()
{
var opts = new AmqpEndpointOptions();
var policy = opts.ResolveExpiryPolicy();
policy.ToString().Should().Be("session-end");
}
[Theory]
[InlineData("link-detach", "link-detach")]
[InlineData("session-end", "session-end")]
[InlineData("connection-close", "connection-close")]
[InlineData("never", "never")]
public void ResolveExpiryPolicy_MapsCorrectly(string input, string expected)
{
var opts = new AmqpEndpointOptions { ExpiryPolicy = input };
opts.ResolveExpiryPolicy().ToString().Should().Be(expected);
}
[Fact]
public void ExpiryPolicy_Typo_FailsLoud_AtValidation()
{
// The silent session-end fallback meant a durable subscription with expiryPolicy=nevr
// quietly lost messages between restarts.
var opts = new AmqpEndpointOptions { ExpiryPolicy = "garbage" };
var act = () => opts.Validate();
act.Should().Throw()
.WithMessage("*expiryPolicy*", "the error must name the option")
.WithMessage("*link-detach*", "and list the valid values");
}
}
Path: redb-route/tests/redb.Route.Tests.Amqp/AmqpEndpointTests.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/tests/redb.Route.Tests.Amqp/AmqpEndpointTests.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Amqp;
namespace redb.Route.Tests.Amqp;
public sealed class AmqpEndpointTests
{
private readonly AmqpComponent _component = new();
private AmqpEndpoint CreateEndpoint(string uriStr)
{
var uri = EndpointUriParser.Parse(uriStr);
return (AmqpEndpoint)_component.CreateEndpoint(uri);
}
[Fact]
public void Address_ExtractedFromPath()
{
var ep = CreateEndpoint("amqp://my-queue?host=localhost");
ep.Address.Should().Be("my-queue");
}
[Fact]
public void CreateProducer_ReturnsAmqpProducer()
{
var ep = CreateEndpoint("amqp://q?host=localhost");
var producer = ep.CreateProducer();
producer.Should().BeOfType();
}
[Fact]
public void CreateConsumer_ReturnsAmqpConsumer()
{
var ep = CreateEndpoint("amqp://q?host=localhost");
var processor = Substitute.For();
var consumer = ep.CreateConsumer(processor);
consumer.Should().BeOfType();
}
[Fact]
public void Component_IsAmqpComponent()
{
var ep = CreateEndpoint("amqp://q?host=localhost");
ep.Component.Should().BeSameAs(_component);
}
[Fact]
public void Uri_PreservesOriginal()
{
var ep = CreateEndpoint("amqp://my-queue?host=broker1");
ep.Uri.Scheme.Should().Be("amqp");
ep.Uri.Path.Should().Be("my-queue");
}
// ── The options sweep: the terminus pair ──────────────────────────────────
[Fact]
public void Terminus_CarriesExpiryPolicyAndTimeout()
{
// expiryPolicy had a resolver nobody called; terminusTimeout had nothing at all.
var ep = CreateEndpoint("amqp://my-queue?host=localhost&expiryPolicy=never&terminusTimeout=30");
var source = ep.BuildSourceTerminus();
source.ExpiryPolicy.ToString().Should().Be("never",
"expiryPolicy must reach the terminus, not be a dead option");
source.Timeout.Should().Be(30u);
var target = ep.BuildTargetTerminus();
target.ExpiryPolicy.ToString().Should().Be("never");
target.Timeout.Should().Be(30u);
}
[Fact]
public void Terminus_DefaultsMatchAmqpDefaults()
{
var ep = CreateEndpoint("amqp://my-queue?host=localhost");
var source = ep.BuildSourceTerminus();
source.ExpiryPolicy.ToString().Should().Be("session-end", "the AMQP 1.0 default");
source.Timeout.Should().Be(0u);
}
}
Path: redb-route/tests/redb.Route.Tests.Amqp/AmqpExpressionTests.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/tests/redb.Route.Tests.Amqp/AmqpExpressionTests.cs
----
using redb.Route.Abstractions;
using redb.Route.Amqp;
using redb.Route.Core;
using redb.Route.Expressions;
namespace redb.Route.Tests.Amqp;
///
/// Tests for expression resolution in AMQP producer options (Phase 1).
/// Verifies that expression properties bind correctly and resolve at runtime.
///
public class AmqpExpressionTests
{
// ── BindFromUri: expression binds to *Expression property ────────
[Fact]
public void BindFromUri_MessagePriorityExpression_BindsCorrectly()
{
var opts = new AmqpEndpointOptions();
opts.BindFromUri(new Dictionary
{
["host"] = "localhost",
["messagePriorityExpression"] = "${header.prio}"
});
opts.MessagePriorityExpression.Should().Be("${header.prio}");
opts.MessagePriority.Should().Be(4); // default unchanged
}
[Fact]
public void BindFromUri_MessageTtlExpression_BindsCorrectly()
{
var opts = new AmqpEndpointOptions();
opts.BindFromUri(new Dictionary
{
["host"] = "localhost",
["messageTtlExpression"] = "${header.ttl}"
});
opts.MessageTtlExpression.Should().Be("${header.ttl}");
opts.MessageTtl.Should().Be(0); // default unchanged
}
// ── ResolveOption: string properties resolve expressions ─────────
[Fact]
public void ResolveOption_Subject_ResolvesExpression()
{
var opts = new AmqpEndpointOptions { Subject = "order-${header.orderId}" };
var msg = new Message("body");
msg.Headers["orderId"] = "12345";
var exchange = new Exchange(msg);
opts.ResolveOption(opts.Subject, exchange).Should().Be("order-12345");
}
[Fact]
public void ResolveOption_GroupId_ResolvesExpression()
{
var opts = new AmqpEndpointOptions { GroupId = "group-${header.region}" };
var msg = new Message("body");
msg.Headers["region"] = "eu-west";
var exchange = new Exchange(msg);
opts.ResolveOption(opts.GroupId, exchange).Should().Be("group-eu-west");
}
[Fact]
public void ResolveOption_ContentType_ResolvesExpression()
{
var opts = new AmqpEndpointOptions { ContentType = "${header.ct}" };
var msg = new Message("body");
msg.Headers["ct"] = "application/json";
var exchange = new Exchange(msg);
opts.ResolveOption(opts.ContentType, exchange).Should().Be("application/json");
}
[Fact]
public void ResolveOption_Subject_StaticValue_ReturnsAsIs()
{
var opts = new AmqpEndpointOptions { Subject = "static-subject" };
var exchange = new Exchange(new Message("body"));
opts.ResolveOption(opts.Subject, exchange).Should().Be("static-subject");
}
// ── ResolveOption: numeric expressions resolve then TryParse ─────
[Fact]
public void ResolveOption_MessagePriorityExpression_ResolvesFromExchange()
{
var opts = new AmqpEndpointOptions { MessagePriorityExpression = "${header.prio}" };
var msg = new Message("body");
msg.Headers["prio"] = "7";
var exchange = new Exchange(msg);
var resolved = opts.ResolveOption(opts.MessagePriorityExpression, exchange);
resolved.Should().Be("7");
byte.TryParse(resolved, out var prio).Should().BeTrue();
prio.Should().Be(7);
}
[Fact]
public void ResolveOption_MessageTtlExpression_ResolvesFromExchange()
{
var opts = new AmqpEndpointOptions { MessageTtlExpression = "${header.ttl}" };
var msg = new Message("body");
msg.Headers["ttl"] = "60000";
var exchange = new Exchange(msg);
var resolved = opts.ResolveOption(opts.MessageTtlExpression, exchange);
resolved.Should().Be("60000");
uint.TryParse(resolved, out var ttl).Should().BeTrue();
ttl.Should().Be(60000u);
}
// ── DSL: expression routing in Build ─────────────────────────────
[Fact]
public void DslBuild_MessagePriorityExpression_RoutesToExpressionParam()
{
var uri = AmqpDsl.Address("test-queue")
.Host("localhost")
.MessagePriority(new HeaderExpression("prio"))
.Build();
uri.Should().Contain("messagePriorityExpression=");
uri.Should().NotContain("&messagePriority=");
}
[Fact]
public void DslBuild_MessagePriorityStatic_RoutesToNormalParam()
{
var uri = AmqpDsl.Address("test-queue")
.Host("localhost")
.MessagePriority(7)
.Build();
uri.Should().Contain("messagePriority=7");
uri.Should().NotContain("messagePriorityExpression");
}
[Fact]
public void DslBuild_MessageTtlExpression_RoutesToExpressionParam()
{
var uri = AmqpDsl.Address("test-queue")
.Host("localhost")
.MessageTtl(new HeaderExpression("ttl"))
.Build();
uri.Should().Contain("messageTtlExpression=");
uri.Should().NotContain("&messageTtl=");
}
[Fact]
public void DslBuild_SubjectExpression_StoresTemplateString()
{
var uri = AmqpDsl.Address("test-queue")
.Host("localhost")
.Subject(new HeaderExpression("subj"))
.Build();
uri.Should().Contain("subject=");
}
[Fact]
public void DslBuild_GroupIdExpression_StoresTemplateString()
{
var uri = AmqpDsl.Address("test-queue")
.Host("localhost")
.GroupId(new HeaderExpression("grp"))
.Build();
uri.Should().Contain("groupId=");
}
[Fact]
public void DslBuild_ContentTypeExpression_StoresTemplateString()
{
var uri = AmqpDsl.Address("test-queue")
.Host("localhost")
.ContentType(new HeaderExpression("ct"))
.Build();
uri.Should().Contain("contentType=");
}
}
Path: redb-route/tests/redb.Route.Tests.Amqp/AmqpHeaderFilterStrategyTests.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/tests/redb.Route.Tests.Amqp/AmqpHeaderFilterStrategyTests.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Amqp;
namespace redb.Route.Tests.Amqp;
///
/// headerFilterStrategy=#name on AMQP 1.0 endpoints: on a producer it decides which exchange headers go out
/// with the request and which application-properties of the reply come back, on a consumer which application-properties
/// come in and which headers go out with the reply. Standard property names and the consumer's redbAmqp.* metadata stay
/// outside the strategy.
///
[Trait("Category", "Integration")]
public sealed class AmqpHeaderFilterStrategyTests
{
private static string Uri(string queue, string? extra = null)
=> $"amqp://{queue}?host=localhost&port=5673&user=admin&password=admin{extra}";
private static RouteContext Context()
{
var ctx = new RouteContext();
ctx.AddComponent(new AmqpComponent());
ctx.AddToRegistry("correlationOnly", new DefaultHeaderFilterStrategy { OutFilter = ["Correlation-ID"], FilterOnMatch = false });
ctx.AddToRegistry("noSecrets", new DefaultHeaderFilterStrategy { InFilter = ["Authorization"] });
return ctx;
}
private static async Task> Deliver(string producerOptions, string consumerOptions)
{
var queue = $"hdr-strategy-{Guid.NewGuid():N}";
var received = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
await using var ctx = Context();
ctx.AddRoutes(r => r.From(Uri(queue, consumerOptions)).Process(e => received.TrySetResult(e)));
await ctx.Start();
var exchange = new Exchange(new Message("body"));
exchange.In.Headers["Correlation-ID"] = "c-42";
exchange.In.Headers["X-Corr"] = "c1";
exchange.In.Headers["Authorization"] = "Bearer secret";
exchange.In.Headers["MessageId"] = "m-1";
var producer = ctx.GetEndpoint(Uri(queue, producerOptions)).CreateProducer();
await producer.Start();
await producer.Process(exchange);
await producer.Stop();
return new Dictionary((await received.Task.WaitAsync(TimeSpan.FromSeconds(30))).In.Headers);
}
private static async Task> Reply(string producerOptions, string consumerOptions)
{
var queue = $"hdr-strategy-rpc-{Guid.NewGuid():N}";
await using var ctx = Context();
ctx.AddRoutes(r => r.From(Uri(queue, consumerOptions)).Process(e =>
{
e.In.Headers.Clear();
e.In.Headers["Correlation-ID"] = "c-42";
e.In.Headers["X-Reply"] = "r1";
e.In.Headers["Authorization"] = "Bearer secret";
e.In.Body = "reply";
}));
await ctx.Start();
var producer = ctx.GetEndpoint(Uri(queue, "&replyTo=true&timeout=15" + producerOptions)).CreateProducer();
await producer.Start();
var exchange = new Exchange(new Message("request"));
await producer.Process(exchange);
await producer.Stop();
return new Dictionary((exchange.HasOut ? exchange.Out! : exchange.In).Headers);
}
[Fact]
public async Task OnAProducer_AWhitelistSendsOnlyTheNamedHeader()
{
var headers = await Deliver("&headerFilterStrategy=#correlationOnly", "");
headers["Correlation-ID"].Should().Be("c-42");
headers.Should().NotContainKey("X-Corr");
headers.Should().NotContainKey("Authorization");
headers["MessageId"].Should().Be("m-1", "a standard property name goes into the property whatever the strategy says");
headers.Should().ContainKey(AmqpHeaders.Address, "the consumer's own metadata is set whatever the strategy says");
}
[Fact]
public async Task OnAConsumer_TheStrategyDecidesWhatComesIn()
{
var headers = await Deliver("", "&headerFilterStrategy=#noSecrets");
headers["X-Corr"].Should().Be("c1");
headers.Should().NotContainKey("Authorization", "the consumer's strategy drops it on the way in");
}
[Fact]
public async Task OnAReplyingConsumer_TheStrategyDecidesWhatTheReplyCarries()
{
var headers = await Reply("", "&headerFilterStrategy=#correlationOnly");
headers["Correlation-ID"].Should().Be("c-42");
headers.Should().NotContainKey("X-Reply");
headers.Should().NotContainKey("Authorization");
}
[Fact]
public async Task OnARequestReplyProducer_TheStrategyDecidesWhatComesBackWithTheReply()
{
var headers = await Reply("&headerFilterStrategy=#noSecrets", "");
headers["X-Reply"].Should().Be("r1");
headers.Should().NotContainKey("Authorization", "the producer's strategy drops it on the way back in");
}
}
Path: redb-route/tests/redb.Route.Tests.Amqp/AmqpHeaderMappingCharacterizationTests.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/tests/redb.Route.Tests.Amqp/AmqpHeaderMappingCharacterizationTests.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Amqp;
namespace redb.Route.Tests.Amqp;
///
/// What crosses an AMQP 1.0 message today, both ways of a request-reply: pinned before the header filter strategy
/// takes the rule over, so the transport's default keeps it exactly.
/// The producer and the replying consumer send every exchange header but their own redbAmqp.*, the AMQP standard
/// property names and null values; the consumer takes every application property back.
///
[Trait("Category", "Integration")]
public sealed class AmqpHeaderMappingCharacterizationTests
{
private static string Uri(string queue, string? extra = null)
=> $"amqp://{queue}?host=localhost&port=5673&user=admin&password=admin{extra}";
private static Exchange Sample()
{
var exchange = new Exchange(new Message("body"));
exchange.In.Headers["X-Corr"] = "c1";
exchange.In.Headers["X-Int"] = 42;
exchange.In.Headers["X-Null"] = null;
exchange.In.Headers["Authorization"] = "Bearer secret";
exchange.In.Headers["redbHttp.Method"] = "DELETE";
exchange.In.Headers["MessageId"] = "m-1";
exchange.In.Headers[AmqpHeaders.Prefix + "Custom"] = "own";
return exchange;
}
[Fact]
public async Task ProducerToConsumer_TheHeadersThatCrossTheMessage()
{
var queue = $"hdr-char-{Guid.NewGuid():N}";
var received = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
await using var ctx = new RouteContext();
ctx.AddComponent(new AmqpComponent());
ctx.AddRoutes(r => r.From(Uri(queue)).Process(e => received.TrySetResult(e)));
await ctx.Start();
var producer = ctx.GetEndpoint(Uri(queue)).CreateProducer();
await producer.Start();
await producer.Process(Sample());
await producer.Stop();
var headers = (await received.Task.WaitAsync(TimeSpan.FromSeconds(30))).In.Headers;
headers["X-Corr"].Should().Be("c1");
headers["X-Int"].Should().Be(42, "a number crosses as an AMQP number");
headers.Should().NotContainKey("X-Null", "a null value is skipped");
headers["Authorization"].Should().Be("Bearer secret", "nothing filters a credential");
headers["redbHttp.Method"].Should().Be("DELETE", "a control header of another transport crosses (finding 3.1)");
headers.Should().NotContainKey(AmqpHeaders.Prefix + "Custom", "the producer keeps its own redbRmq.* back");
headers["MessageId"].Should().Be("m-1",
"a header named after a message property is sent as that property, and comes back under its name");
}
[Fact]
public async Task RpcReply_TheHeadersThatCrossTheReply()
{
var queue = $"hdr-char-rpc-{Guid.NewGuid():N}";
await using var ctx = new RouteContext();
ctx.AddComponent(new AmqpComponent());
ctx.AddRoutes(r => r.From(Uri(queue)).Process(e =>
{
e.In.Headers.Clear();
e.In.Headers["X-Reply"] = "r1";
e.In.Headers["X-Int"] = 7;
e.In.Headers["X-Null"] = null;
e.In.Headers["redbHttp.Method"] = "PUT";
e.In.Headers[AmqpHeaders.Prefix + "Custom"] = "own";
e.In.Body = "reply";
}));
await ctx.Start();
var producer = ctx.GetEndpoint(Uri(queue, "&replyTo=true&timeout=15")).CreateProducer();
await producer.Start();
var exchange = new Exchange(new Message("request"));
await producer.Process(exchange);
await producer.Stop();
var headers = (exchange.HasOut ? exchange.Out! : exchange.In).Headers;
headers["X-Reply"].Should().Be("r1");
headers["X-Int"].Should().Be(7, "a reply keeps a number an AMQP number (RabbitMQ sends it as text)");
headers.Should().NotContainKey("X-Null");
headers["redbHttp.Method"].Should().Be("PUT", "a control header crosses the reply too");
headers.Should().NotContainKey(AmqpHeaders.Prefix + "Custom");
}
}
Path: redb-route/tests/redb.Route.Tests.Amqp/AmqpHeadersTests.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/tests/redb.Route.Tests.Amqp/AmqpHeadersTests.cs
----
using redb.Route.Amqp;
namespace redb.Route.Tests.Amqp;
public sealed class AmqpHeadersTests
{
[Fact]
public void Naming_StandardPropertiesAreBare_EnvelopeIsPrefixed()
{
// Transport / envelope metadata (no standard AMQP name) → redbAmqp.* prefix.
AmqpHeaders.Address.Should().StartWith("redbAmqp.");
AmqpHeaders.DeliveryCount.Should().StartWith("redbAmqp.");
AmqpHeaders.FirstAcquirer.Should().StartWith("redbAmqp.");
// Standard AMQP 1.0 properties → bare, well-known names (self-documenting, round-trip).
AmqpHeaders.MessageId.Should().Be("MessageId");
AmqpHeaders.CorrelationId.Should().Be("CorrelationId");
AmqpHeaders.ReplyTo.Should().Be("ReplyTo");
AmqpHeaders.Subject.Should().Be("Subject");
}
[Fact]
public void IsRedbHeader_WithRedbPrefix_ReturnsTrue()
{
AmqpHeaders.IsRedbHeader("redbAmqp.address").Should().BeTrue();
AmqpHeaders.IsRedbHeader("redbAmqp.messageId").Should().BeTrue();
}
[Fact]
public void IsRedbHeader_WithoutPrefix_ReturnsFalse()
{
AmqpHeaders.IsRedbHeader("X-Custom-Header").Should().BeFalse();
AmqpHeaders.IsRedbHeader("traceparent").Should().BeFalse();
}
[Fact]
public void IsRedbHeader_Empty_ReturnsFalse()
{
AmqpHeaders.IsRedbHeader("").Should().BeFalse();
}
[Fact]
public void IsRedbHeader_Null_ThrowsOrReturnsFalse()
{
// null input is a programming error — either throws or returns false
var act = () => AmqpHeaders.IsRedbHeader(null!);
try
{
act().Should().BeFalse();
}
catch (NullReferenceException)
{
// also acceptable
}
}
[Fact]
public void AllConstants_AreDistinct()
{
var all = new[]
{
AmqpHeaders.Address, AmqpHeaders.MessageId, AmqpHeaders.CorrelationId,
AmqpHeaders.ReplyTo, AmqpHeaders.ContentType, AmqpHeaders.Subject,
AmqpHeaders.GroupId, AmqpHeaders.GroupSequence, AmqpHeaders.CreationTime,
AmqpHeaders.AbsoluteExpiryTime, AmqpHeaders.Durable, AmqpHeaders.Priority,
AmqpHeaders.Ttl, AmqpHeaders.DeliveryCount, AmqpHeaders.FirstAcquirer,
AmqpHeaders.SenderSettleMode, AmqpHeaders.ReceiverSettleMode
};
all.Should().OnlyHaveUniqueItems();
}
}
Path: redb-route/tests/redb.Route.Tests.Amqp/AmqpIntegrationTests.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/tests/redb.Route.Tests.Amqp/AmqpIntegrationTests.cs
----
using System.Collections.Concurrent;
using System.Text;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Transactions;
using redb.Route.Processors;
using redb.Route.Amqp;
using Xunit.Abstractions;
namespace redb.Route.Tests.Amqp;
///
/// Integration tests against a real AMQP 1.0 broker (ActiveMQ Artemis).
/// Expects Artemis at localhost:5673 (admin/admin).
///
[Trait("Category", "Integration")]
public sealed class AmqpIntegrationTests
{
private const string Host = "localhost";
private const int Port = 5673;
private const string User = "admin";
private const string Password = "admin";
private readonly ITestOutputHelper _output;
public AmqpIntegrationTests(ITestOutputHelper output) => _output = output;
// ───── Helpers ─────
private AmqpEndpoint CreateEndpoint(string address, string? extraParams = null)
{
var qs = $"host={Host}&port={Port}&user={User}&password={Password}";
if (extraParams is not null) qs += $"&{extraParams}";
var uri = EndpointUriParser.Parse($"amqp://{address}?{qs}");
var component = new AmqpComponent();
return (AmqpEndpoint)component.CreateEndpoint(uri);
}
// ───── Tests ─────
[Fact]
public async Task Producer_SendsMessage_ConsumerReceives()
{
var address = $"test.{Guid.NewGuid():N}";
_output.WriteLine($"Address: {address}");
var epProd = CreateEndpoint(address);
var producer = (AmqpProducer)epProd.CreateProducer();
await producer.Start();
var exchange = new Exchange(new Message("Hello AMQP"));
await producer.Process(exchange);
await producer.Stop();
await epProd.Stop();
// Consume
var epCons = CreateEndpoint(address);
var received = new ConcurrentBag();
var tcs = new TaskCompletionSource();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(callInfo =>
{
var ex = callInfo.Arg();
received.Add(Encoding.UTF8.GetString((byte[])ex.In.Body!));
tcs.TrySetResult();
return Task.CompletedTask;
});
var consumer = (AmqpConsumer)epCons.CreateConsumer(processor);
await consumer.Start();
await Task.WhenAny(tcs.Task, Task.Delay(15_000));
await consumer.Stop();
await epCons.Stop();
received.Should().Contain("Hello AMQP");
}
[Fact]
public async Task Consumer_SetsAmqpMetadataHeaders()
{
var address = $"test.meta.{Guid.NewGuid():N}";
var epProd = CreateEndpoint(address);
var producer = (AmqpProducer)epProd.CreateProducer();
await producer.Start();
var exchange = new Exchange(new Message("meta-test"));
await producer.Process(exchange);
await producer.Stop();
await epProd.Stop();
var epCons = CreateEndpoint(address);
IExchange? capturedExchange = null;
var tcs = new TaskCompletionSource();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(callInfo =>
{
capturedExchange = callInfo.Arg();
tcs.TrySetResult();
return Task.CompletedTask;
});
var consumer = (AmqpConsumer)epCons.CreateConsumer(processor);
await consumer.Start();
await Task.WhenAny(tcs.Task, Task.Delay(15_000));
await consumer.Stop();
await epCons.Stop();
capturedExchange.Should().NotBeNull();
capturedExchange!.In.Headers.Should().ContainKey(AmqpHeaders.Address);
capturedExchange.In.Headers.Should().ContainKey(AmqpHeaders.MessageId);
capturedExchange.In.Headers.Should().ContainKey(AmqpHeaders.Durable);
capturedExchange.In.Headers.Should().ContainKey(AmqpHeaders.Priority);
}
[Fact]
public async Task Producer_ForwardsCustomHeaders()
{
var address = $"test.hdr.{Guid.NewGuid():N}";
var epProd = CreateEndpoint(address);
var producer = (AmqpProducer)epProd.CreateProducer();
await producer.Start();
var msg = new Message("hdr-data");
msg.Headers["X-Custom-Id"] = "12345";
msg.Headers["X-Trace"] = "abc";
var exchange = new Exchange(msg);
await producer.Process(exchange);
await producer.Stop();
await epProd.Stop();
var epCons = CreateEndpoint(address);
IExchange? captured = null;
var tcs = new TaskCompletionSource();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(callInfo =>
{
captured = callInfo.Arg();
tcs.TrySetResult();
return Task.CompletedTask;
});
var consumer = (AmqpConsumer)epCons.CreateConsumer(processor);
await consumer.Start();
await Task.WhenAny(tcs.Task, Task.Delay(15_000));
await consumer.Stop();
await epCons.Stop();
captured.Should().NotBeNull();
captured!.In.Headers.Should().ContainKey("X-Custom-Id");
captured.In.Headers["X-Custom-Id"].Should().Be("12345");
captured.In.Headers.Should().ContainKey("X-Trace");
}
/// Runs inside a transacted block, as .Transacted() on a route does.
private static Task InTransaction(IExchange exchange, Func body) =>
new TransactedProcessor(new DelegateProcessor(body), new TransactionPolicy()).Process(exchange);
[Fact]
public async Task TransactedProducer_Commit_DeliversMessage()
{
var address = $"test.tx.{Guid.NewGuid():N}";
var epProd = CreateEndpoint(address, "transacted=true");
var producer = (AmqpProducer)epProd.CreateProducer();
await producer.Start();
var exchange = new Exchange(new Message("transacted"));
await InTransaction(exchange, (ex, ct) => producer.Process(ex, ct)); // the send is committed as the block ends
await producer.Stop();
await epProd.Stop();
// Verify delivered
var epCons = CreateEndpoint(address);
var received = new ConcurrentBag();
var tcs = new TaskCompletionSource();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(callInfo =>
{
received.Add(Encoding.UTF8.GetString((byte[])callInfo.Arg().In.Body!));
tcs.TrySetResult();
return Task.CompletedTask;
});
var consumer = (AmqpConsumer)epCons.CreateConsumer(processor);
await consumer.Start();
await Task.WhenAny(tcs.Task, Task.Delay(15_000));
await consumer.Stop();
await epCons.Stop();
received.Should().Contain("transacted");
}
[Fact]
public async Task TransactedProducer_Rollback_MessageNotDelivered()
{
var address = $"test.rollback.{Guid.NewGuid():N}";
var epProd = CreateEndpoint(address, "transacted=true");
var producer = (AmqpProducer)epProd.CreateProducer();
await producer.Start();
var exchange = new Exchange(new Message("should-not-arrive"));
var failed = () => InTransaction(exchange, async (ex, ct) =>
{
await producer.Process(ex, ct);
throw new InvalidOperationException("the unit of work failed");
});
await failed.Should().ThrowAsync(); // the send is rolled back with it
await producer.Stop();
await epProd.Stop();
// Should timeout with no message
var epCons = CreateEndpoint(address);
var received = new ConcurrentBag();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(callInfo =>
{
received.Add(Encoding.UTF8.GetString((byte[])callInfo.Arg().In.Body!));
return Task.CompletedTask;
});
var consumer = (AmqpConsumer)epCons.CreateConsumer(processor);
await consumer.Start();
await Task.Delay(3000);
await consumer.Stop();
await epCons.Stop();
received.Should().BeEmpty("message was rolled back, not committed");
}
/// Sends one message from inside a .Transacted() block that then fails; returns what reached the address.
private async Task> SendFromAFailedBlock(string address, string? producerParams)
{
var epProd = CreateEndpoint(address, producerParams);
var producer = (AmqpProducer)epProd.CreateProducer();
await producer.Start();
var failed = () => InTransaction(new Exchange(new Message("sent-from-a-failed-block")), async (ex, ct) =>
{
await producer.Process(ex, ct);
throw new InvalidOperationException("the unit of work failed");
});
await failed.Should().ThrowAsync();
await producer.Stop();
await epProd.Stop();
var epCons = CreateEndpoint(address);
var received = new ConcurrentBag();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(callInfo =>
{
received.Add(Encoding.UTF8.GetString((byte[])callInfo.Arg().In.Body!));
return Task.CompletedTask;
});
var consumer = (AmqpConsumer)epCons.CreateConsumer(processor);
await consumer.Start();
await Task.Delay(3000);
await consumer.Stop();
await epCons.Stop();
return received;
}
[Fact]
public async Task Producer_without_transacted_joins_the_block_and_sends_nothing_when_it_fails()
{
var received = await SendFromAFailedBlock($"test.join.{Guid.NewGuid():N}", producerParams: null);
received.Should().BeEmpty("inside .Transacted() a send joins the transaction unless transacted=false opts out");
}
[Fact]
public async Task Producer_with_transacted_false_sends_at_once_even_from_a_failed_block()
{
var received = await SendFromAFailedBlock($"test.optout.{Guid.NewGuid():N}", "transacted=false");
received.Should().ContainSingle().Which.Should().Be("sent-from-a-failed-block");
}
/// What reaches within three seconds.
private async Task> ReceiveFrom(string address)
{
var epCons = CreateEndpoint(address);
var received = new ConcurrentQueue();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(callInfo =>
{
received.Enqueue(Encoding.UTF8.GetString((byte[])callInfo.Arg().In.Body!));
return Task.CompletedTask;
});
var consumer = (AmqpConsumer)epCons.CreateConsumer(processor);
await consumer.Start();
await Task.Delay(3000);
await consumer.Stop();
await epCons.Stop();
return received.ToArray();
}
[Fact]
public async Task Deferred_sends_of_one_producer_arrive_in_the_order_the_route_made_them()
{
var address = $"test.batch.order.{Guid.NewGuid():N}";
var epProd = CreateEndpoint(address);
var producer = (AmqpProducer)epProd.CreateProducer();
await producer.Start();
await InTransaction(new Exchange(new Message("one")), async (ex, ct) =>
{
await producer.Process(ex, ct);
ex.In.Body = "two";
await producer.Process(ex, ct);
});
await producer.Stop();
await epProd.Stop();
(await ReceiveFrom(address)).Should().Equal("one", "two");
}
[Fact]
public void Request_reply_producer_refuses_transacted_true()
{
var endpoint = CreateEndpoint($"test.rpc.{Guid.NewGuid():N}", "replyTo=true&transacted=true");
var act = () => endpoint.CreateProducer();
act.Should().Throw().WithMessage("*replyTo*transacted*");
}
[Fact]
public async Task Roundtrip_MultipleMessages()
{
var address = $"test.rt.{Guid.NewGuid():N}";
const int messageCount = 10;
var epProd = CreateEndpoint(address);
var producer = (AmqpProducer)epProd.CreateProducer();
await producer.Start();
for (int i = 0; i < messageCount; i++)
{
var exchange = new Exchange(new Message($"msg-{i}"));
await producer.Process(exchange);
}
await producer.Stop();
await epProd.Stop();
var epCons = CreateEndpoint(address);
var received = new ConcurrentBag();
var allReceived = new TaskCompletionSource();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(callInfo =>
{
received.Add(Encoding.UTF8.GetString((byte[])callInfo.Arg().In.Body!));
if (received.Count >= messageCount) allReceived.TrySetResult();
return Task.CompletedTask;
});
var consumer = (AmqpConsumer)epCons.CreateConsumer(processor);
await consumer.Start();
await Task.WhenAny(allReceived.Task, Task.Delay(15_000));
await consumer.Stop();
await epCons.Stop();
received.Count.Should().BeGreaterThanOrEqualTo(messageCount);
for (int i = 0; i < messageCount; i++)
received.Should().Contain($"msg-{i}");
}
[Fact]
public async Task Rpc_RequestReply_ReturnsResponse()
{
var address = $"test.rpc.{Guid.NewGuid():N}";
// Start a "server" consumer that echoes back with a prefix
var epServer = CreateEndpoint(address);
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(callInfo =>
{
var ex = callInfo.Arg();
var body = Encoding.UTF8.GetString((byte[])ex.In.Body!);
ex.Out = new Message($"ECHO:{body}");
return Task.CompletedTask;
});
var consumer = (AmqpConsumer)epServer.CreateConsumer(processor);
await consumer.Start();
// RPC client
var epClient = CreateEndpoint(address, "replyTo=true&timeout=15");
var rpcProducer = (AmqpProducer)epClient.CreateProducer();
await rpcProducer.Start();
var exchange = new Exchange(new Message("ping"));
await rpcProducer.Process(exchange);
await rpcProducer.Stop();
await epClient.Stop();
await consumer.Stop();
await epServer.Stop();
exchange.HasOut.Should().BeTrue();
Encoding.UTF8.GetString((byte[])exchange.Out!.Body!).Should().Be("ECHO:ping");
}
[Fact]
public async Task ConcurrentConsumers_ProcessInParallel()
{
var address = $"test.concurrent.{Guid.NewGuid():N}";
const int messageCount = 20;
// Send messages
var epProd = CreateEndpoint(address);
var producer = (AmqpProducer)epProd.CreateProducer();
await producer.Start();
for (int i = 0; i < messageCount; i++)
{
var exchange = new Exchange(new Message($"concurrent-{i}"));
await producer.Process(exchange);
}
await producer.Stop();
await epProd.Stop();
// Consume with concurrency=4
var epCons = CreateEndpoint(address, "concurrentConsumers=4&credit=20");
var received = new ConcurrentBag();
var allReceived = new TaskCompletionSource();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(async callInfo =>
{
received.Add(Encoding.UTF8.GetString((byte[])callInfo.Arg().In.Body!));
await Task.Delay(50); // simulate work
if (received.Count >= messageCount) allReceived.TrySetResult();
});
var consumer = (AmqpConsumer)epCons.CreateConsumer(processor);
await consumer.Start();
await Task.WhenAny(allReceived.Task, Task.Delay(15_000));
await consumer.Stop();
await epCons.Stop();
received.Count.Should().BeGreaterThanOrEqualTo(messageCount);
}
[Fact]
public async Task ProducerDefaults_DurableAndPriority_SetCorrectly()
{
var address = $"test.defaults.{Guid.NewGuid():N}";
var epProd = CreateEndpoint(address, "messageDurable=true&messagePriority=7");
var producer = (AmqpProducer)epProd.CreateProducer();
await producer.Start();
var exchange = new Exchange(new Message("priority-msg"));
await producer.Process(exchange);
await producer.Stop();
await epProd.Stop();
var epCons = CreateEndpoint(address);
IExchange? captured = null;
var tcs = new TaskCompletionSource();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(callInfo =>
{
captured = callInfo.Arg();
tcs.TrySetResult();
return Task.CompletedTask;
});
var consumer = (AmqpConsumer)epCons.CreateConsumer(processor);
await consumer.Start();
await Task.WhenAny(tcs.Task, Task.Delay(15_000));
await consumer.Stop();
await epCons.Stop();
captured.Should().NotBeNull();
captured!.In.Headers[AmqpHeaders.Durable].Should().Be(true);
captured.In.Headers[AmqpHeaders.Priority].Should().Be((byte)7);
}
[Fact]
public async Task TransactedConsumer_CommitsOnSuccess()
{
var address = $"test.txcons.{Guid.NewGuid():N}";
// Publish a message normally (non-transacted producer)
var epProd = CreateEndpoint(address);
var producer = (AmqpProducer)epProd.CreateProducer();
await producer.Start();
await producer.Process(new Exchange(new Message("tx-consumer-msg")));
await producer.Stop();
await epProd.Stop();
// Consume with transacted=true
var epCons = CreateEndpoint(address, "transacted=true");
IExchange? captured = null;
var tcs = new TaskCompletionSource();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(callInfo =>
{
captured = callInfo.Arg();
tcs.TrySetResult();
return Task.CompletedTask;
});
var consumer = (AmqpConsumer)epCons.CreateConsumer(processor);
await consumer.Start();
await Task.WhenAny(tcs.Task, Task.Delay(15_000));
// Allow ProcessMessageAsync to fully complete (accept + increment counter)
// after the mock fires tcs — there's a window between processor return and ProcessedCount++
var sw = System.Diagnostics.Stopwatch.StartNew();
while (consumer.ProcessedCount < 1 && sw.ElapsedMilliseconds < 3_000)
await Task.Delay(50);
await consumer.Stop();
await epCons.Stop();
captured.Should().NotBeNull();
Encoding.UTF8.GetString((byte[])captured!.In.Body!).Should().Be("tx-consumer-msg");
consumer.ProcessedCount.Should().BeGreaterThanOrEqualTo(1);
}
// ── Expression resolution roundtrip ─────────────────────────────
[Fact]
public async Task Producer_ExpressionSubjectAndPriority_ResolvedOnSend()
{
var address = $"test.expr.{Guid.NewGuid():N}";
// Subject and priority come from expressions
var epProd = CreateEndpoint(address,
"subject=${header.subj}&messagePriorityExpression=${header.prio}");
var producer = (AmqpProducer)epProd.CreateProducer();
await producer.Start();
var msg = new Message("expr-test");
msg.Headers["subj"] = "order-42";
msg.Headers["prio"] = "7";
var exchange = new Exchange(msg);
await producer.Process(exchange);
await producer.Stop();
await epProd.Stop();
// Consume and verify resolved values
var epCons = CreateEndpoint(address);
IExchange? captured = null;
var tcs = new TaskCompletionSource();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(callInfo =>
{
captured = callInfo.Arg();
tcs.TrySetResult();
return Task.CompletedTask;
});
var consumer = (AmqpConsumer)epCons.CreateConsumer(processor);
await consumer.Start();
await Task.WhenAny(tcs.Task, Task.Delay(15_000));
await consumer.Stop();
await epCons.Stop();
captured.Should().NotBeNull();
captured!.In.Headers[AmqpHeaders.Subject].Should().Be("order-42");
captured.In.Headers[AmqpHeaders.Priority].Should().BeOneOf((byte)7, (int)7);
}
}
Path: redb-route/tests/redb.Route.Tests.Amqp/AmqpListRefusalTests.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/tests/redb.Route.Tests.Amqp/AmqpListRefusalTests.cs
----
using redb.Route.Abstractions;
using redb.Route.Amqp;
using redb.Route.Core;
namespace redb.Route.Tests.Amqp;
///
/// A list body at the AMQP 1.0 producer: it sends no list, so a list of IMessage is refused with the advice to Split it
/// and a plain list is refused; neither goes out as the type name. Expects ActiveMQ Artemis at localhost:5673.
///
[Trait("Category", "Integration")]
public sealed class AmqpListRefusalTests
{
private const string Connection = "host=localhost&port=5673&user=admin&password=admin";
private static async Task StartProducer(string address)
{
var uri = EndpointUriParser.Parse($"amqp://{address}?{Connection}");
var producer = (AmqpProducer)((AmqpEndpoint)new AmqpComponent().CreateEndpoint(uri)).CreateProducer();
await producer.Start();
return producer;
}
[Fact]
public async Task A_list_of_messages_is_refused_with_the_advice_to_split_it()
{
var producer = await StartProducer($"list.{Guid.NewGuid():N}");
try
{
var act = () => producer.Process(new Exchange(new Message(new List { new Message("a") })));
await act.Should().ThrowAsync().WithMessage("*Split the list*");
}
finally
{
await producer.Stop();
}
}
[Fact]
public async Task A_plain_list_is_refused()
{
var producer = await StartProducer($"list.{Guid.NewGuid():N}");
try
{
var act = () => producer.Process(new Exchange(new Message(new List { 1 })));
await act.Should().ThrowAsync().WithMessage("*List*IMessage*");
}
finally
{
await producer.Stop();
}
}
}
Path: redb-route/tests/redb.Route.Tests.Amqp/AmqpLocalTransactionTests.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/tests/redb.Route.Tests.Amqp/AmqpLocalTransactionTests.cs
----
using System.Net.Http.Headers;
using System.Text;
using Amqp;
using Amqp.Framing;
using Amqp.Types;
using redb.Route.Abstractions;
using redb.Route.Amqp;
using redb.Route.Core;
using redb.Route.Processors;
using redb.Route.Transactions;
using AmqpMessage = global::Amqp.Message;
using RouteMessage = redb.Route.Core.Message;
namespace redb.Route.Tests.Amqp;
///
/// localTransactions=true against ActiveMQ Artemis: the sends a producer defers in a .Transacted() block commit
/// in one AMQP local transaction — all of them or none. The "none" case needs a send the broker refuses: an address under
/// redb-full.# holds at most 4 KB and fails what does not fit (set through Artemis' management, so the test does
/// not depend on the broker's configuration surviving a container restart).
///
[Trait("Category", "Integration")]
public sealed class AmqpLocalTransactionTests : IAsyncLifetime
{
private const string Host = "localhost";
private const int Port = 5673;
private const string Url = "amqp://admin:admin@localhost:5673";
public async Task InitializeAsync()
{
using var http = new HttpClient();
http.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes("admin:admin")));
http.DefaultRequestHeaders.Add("Origin", "http://localhost");
const string request = """
{"type":"exec","mbean":"org.apache.activemq.artemis:broker=\"0.0.0.0\"",
"operation":"addAddressSettings(java.lang.String,java.lang.String)",
"arguments":["redb-full.#","{\"maxSizeBytes\":4096,\"pageSizeBytes\":1024,\"addressFullMessagePolicy\":\"FAIL\"}"]}
""";
var response = await http.PostAsync("http://localhost:8161/console/jolokia/",
new StringContent(request, Encoding.UTF8, "application/json"));
(await response.Content.ReadAsStringAsync()).Should().Contain("\"status\":200", "the test sets up the full address itself");
}
public Task DisposeAsync() => Task.CompletedTask;
private static async Task StartProducer(string address, string? parameters = "localTransactions=true")
{
var query = $"host={Host}&port={Port}&user=admin&password=admin";
if (parameters is not null) query += $"&{parameters}";
var endpoint = (AmqpEndpoint)new AmqpComponent().CreateEndpoint(EndpointUriParser.Parse($"amqp://{address}?{query}"));
var producer = (AmqpProducer)endpoint.CreateProducer();
await producer.Start();
return producer;
}
private static Task InTransaction(IExchange exchange, Func body) =>
new TransactedProcessor(new DelegateProcessor(body), new TransactionPolicy()).Process(exchange);
private static async Task> Drain(string address)
{
var connection = await Connection.Factory.CreateAsync(new Address(Url));
try
{
var receiver = new ReceiverLink(new Session(connection), $"drain-{Guid.NewGuid():N}", new Attach
{
Source = new Source { Address = address, Capabilities = [new Symbol("queue")] },
Target = new Target(),
}, null);
var bodies = new List();
while (await receiver.ReceiveAsync(TimeSpan.FromSeconds(2)) is { } message)
{
bodies.Add(message.Body switch { byte[] b => Encoding.UTF8.GetString(b), var body => body?.ToString() ?? "" });
receiver.Accept(message);
}
return bodies;
}
finally
{
await connection.CloseAsync();
}
}
[Fact]
public async Task The_sends_of_a_block_commit_in_one_transaction()
{
var address = $"redb-tx.{Guid.NewGuid():N}";
var producer = await StartProducer(address);
await InTransaction(new Exchange(new RouteMessage("one")), async (ex, ct) =>
{
await producer.Process(ex, ct);
ex.In.Body = "two";
await producer.Process(ex, ct);
});
await producer.Stop();
(await Drain(address)).Should().Equal("one", "two");
}
[Fact]
public async Task A_send_that_cannot_complete_takes_the_whole_transaction_down()
{
var address = $"redb-full.{Guid.NewGuid():N}";
// timeout=3: Artemis does not refuse a send to a full address, it withholds the credit; the step times out.
var producer = await StartProducer(address, "localTransactions=true&timeout=3");
// Artemis takes a message while the address is under its limit, whatever the message's size: the first send
// fills the 4 KB address, the second finds it full and gets no credit.
var block = () => InTransaction(new Exchange(new RouteMessage(new string('x', 8_000))), async (ex, ct) =>
{
await producer.Process(ex, ct);
ex.In.Body = "second";
await producer.Process(ex, ct);
});
await block.Should().ThrowAsync();
await producer.Stop();
(await Drain(address)).Should().BeEmpty("the first send is discharged as failed with the second");
}
[Fact]
public void It_contradicts_a_request_reply_producer()
{
var act = () => new AmqpComponent().CreateEndpoint(EndpointUriParser.Parse(
$"amqp://q?host={Host}&port={Port}&localTransactions=true&replyTo=true"));
act.Should().Throw().WithMessage("*localTransactions*replyTo*");
}
[Fact]
public void It_contradicts_transacted_false()
{
var act = () => new AmqpComponent().CreateEndpoint(EndpointUriParser.Parse(
$"amqp://q?host={Host}&port={Port}&localTransactions=true&transacted=false"));
act.Should().Throw().WithMessage("*localTransactions*transacted=false*");
}
[Fact]
public void The_builder_writes_it_out()
{
AmqpDsl.Address("q").LocalTransactions().Build().Should().Contain("localTransactions=true");
AmqpDsl.Address("q").Build().Should().NotContain("localTransactions");
}
}
Path: redb-route/tests/redb.Route.Tests.Amqp/AmqpManualTransactionProbeTests.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/tests/redb.Route.Tests.Amqp/AmqpManualTransactionProbeTests.cs
----
using System.Diagnostics;
using Amqp;
using Amqp.Framing;
using Amqp.Transactions;
using Amqp.Types;
using Xunit.Abstractions;
namespace redb.Route.Tests.Amqp;
///
/// PROBE: does the broker (ActiveMQ Artemis on localhost:5673) answer an AMQP 1.0 transaction driven by hand — a
/// controller link to its coordinator, Declare, sends carrying TransactionalState, Discharge — the way the client's
/// System.Transactions path never got an answer to its discharge?
///
[Trait("Category", "Integration")]
public sealed class AmqpManualTransactionProbeTests
{
private const string Url = "amqp://admin:admin@localhost:5673";
private static readonly TimeSpan Wait = TimeSpan.FromSeconds(10);
private readonly ITestOutputHelper _output;
public AmqpManualTransactionProbeTests(ITestOutputHelper output) => _output = output;
private static Task SendAsync(SenderLink link, Message message, DeliveryState? state)
{
var done = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
link.Send(message, state, (_, _, outcome, _) => done.TrySetResult(outcome), null);
return done.Task.WaitAsync(Wait);
}
private static Message Control(object body) => new() { BodySection = new AmqpValue { Value = body } };
private async Task> Drain(Session session, string queue)
{
var receiver = new ReceiverLink(session, $"probe-receiver-{Guid.NewGuid():N}", new Attach
{
Source = new Source { Address = queue, Capabilities = [new Symbol("queue")] },
Target = new Target(),
}, null);
var bodies = new List();
while (await receiver.ReceiveAsync(TimeSpan.FromSeconds(2)) is { } message)
{
bodies.Add(message.Body?.ToString() ?? "");
receiver.Accept(message);
}
await receiver.CloseAsync();
return bodies;
}
private async Task> SendInATransaction(bool commit)
{
var queue = $"probe-tx-{Guid.NewGuid():N}";
var connection = await Connection.Factory.CreateAsync(new Address(Url));
try
{
var session = new Session(connection);
var controller = new SenderLink(session, $"probe-controller-{Guid.NewGuid():N}", new Attach
{
Source = new Source(),
Target = new Coordinator { Capabilities = [TxnCapabilities.LocalTransactions] },
}, null);
// "queue": an anycast address on Artemis, which keeps what nobody has subscribed to yet.
var sender = new SenderLink(session, $"probe-sender-{Guid.NewGuid():N}", new Attach
{
Source = new Source(),
Target = new Target { Address = queue, Capabilities = [new Symbol("queue")] },
}, null);
var clock = Stopwatch.StartNew();
var declared = await SendAsync(controller, Control(new Declare()), null);
_output.WriteLine($"declare -> {declared} in {clock.ElapsedMilliseconds} ms");
var txnId = declared.Should().BeOfType().Subject.TxnId;
foreach (var body in new[] { "one", "two" })
{
var sent = await SendAsync(sender, new Message(body), new TransactionalState { TxnId = txnId });
_output.WriteLine($"send {body} -> {sent}");
}
clock.Restart();
var discharged = await SendAsync(controller, Control(new Discharge { TxnId = txnId, Fail = !commit }), null);
_output.WriteLine($"discharge(fail={!commit}) -> {discharged} in {clock.ElapsedMilliseconds} ms");
discharged.Should().BeOfType();
await sender.CloseAsync();
await controller.CloseAsync();
return await Drain(session, queue);
}
finally
{
await connection.CloseAsync();
}
}
[Fact]
public async Task A_committed_transaction_delivers_its_messages()
{
(await SendInATransaction(commit: true)).Should().Equal("one", "two");
}
[Fact]
public async Task A_failed_transaction_delivers_nothing()
{
(await SendInATransaction(commit: false)).Should().BeEmpty();
}
}
Path: redb-route/tests/redb.Route.Tests.Amqp/AmqpMulticastAndDynamicTests.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/tests/redb.Route.Tests.Amqp/AmqpMulticastAndDynamicTests.cs
----
using System.Collections.Concurrent;
using System.Text;
using redb.Route.Abstractions;
using redb.Route.Amqp;
using redb.Route.Core;
using Xunit.Abstractions;
namespace redb.Route.Tests.Amqp;
///
/// A MULTICAST address and a dynamic node give every receiver link its own copy or its own node, so a consumer
/// runs one link whatever concurrentConsumers says; dynamic=true reads the node the broker creates.
/// Expects ActiveMQ Artemis at localhost:5673 (admin/admin).
///
[Trait("Category", "Integration")]
public sealed class AmqpMulticastAndDynamicTests
{
private const string Credentials = "host=localhost&port=5673&user=admin&password=admin";
private readonly ITestOutputHelper _output;
public AmqpMulticastAndDynamicTests(ITestOutputHelper output) => _output = output;
private static AmqpEndpoint Endpoint(string address, string extraParams = "")
=> (AmqpEndpoint)new AmqpComponent().CreateEndpoint(
EndpointUriParser.Parse($"amqp://{address}?{Credentials}{extraParams}"));
private static (IProcessor Processor, ConcurrentQueue Received) Recorder()
{
var received = new ConcurrentQueue();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(callInfo =>
{
var body = callInfo.Arg().In.Body;
received.Enqueue(body is byte[] bytes ? Encoding.UTF8.GetString(bytes) : body?.ToString() ?? "");
return Task.CompletedTask;
});
return (processor, received);
}
private static async Task SendAsync(string address, string extraParams, string body)
{
var endpoint = Endpoint(address, extraParams);
var producer = (AmqpProducer)endpoint.CreateProducer();
await producer.Start();
await producer.Process(new Exchange(new Message(body)));
await producer.Stop();
await endpoint.Stop();
}
[Fact]
public async Task A_multicast_consumer_with_concurrent_consumers_processes_each_message_once()
{
var address = $"multicast.{Guid.NewGuid():N}";
var recorder = Recorder();
var endpoint = Endpoint(address, "&routingType=MULTICAST&concurrentConsumers=3");
var consumer = (AmqpConsumer)endpoint.CreateConsumer(recorder.Processor);
await consumer.Start();
await SendAsync(address, "&routingType=MULTICAST", "once");
var deadline = DateTime.UtcNow.AddSeconds(15);
while (recorder.Received.IsEmpty && DateTime.UtcNow < deadline)
await Task.Delay(50);
// Room for the copies a second or third link would get.
await Task.Delay(1_000);
await consumer.Stop();
await endpoint.Stop();
_output.WriteLine($"processed {recorder.Received.Count} time(s)");
recorder.Received.Should().Equal("once");
}
[Fact]
public async Task A_dynamic_consumer_reads_the_node_the_broker_created_for_it()
{
var recorder = Recorder();
var endpoint = Endpoint("", "&dynamic=true&concurrentConsumers=2");
var consumer = (AmqpConsumer)endpoint.CreateConsumer(recorder.Processor);
await consumer.Start();
_output.WriteLine($"dynamic node: {consumer.Address}");
consumer.Address.Should().NotBeNullOrEmpty("the broker names the node it creates");
await SendAsync(consumer.Address, "", "to the dynamic node");
var deadline = DateTime.UtcNow.AddSeconds(15);
while (recorder.Received.IsEmpty && DateTime.UtcNow < deadline)
await Task.Delay(50);
await consumer.Stop();
await endpoint.Stop();
recorder.Received.Should().Equal("to the dynamic node");
}
///
/// On a MULTICAST address the subscription is the receiver link: it exists once the broker answered the attach.
/// Start used to return before that answer, so a message sent right after it could go to nobody.
///
[Fact]
public async Task A_message_sent_right_after_Start_on_a_multicast_address_is_received()
{
var address = $"multicast.{Guid.NewGuid():N}";
var producerEndpoint = Endpoint(address, "&routingType=MULTICAST");
var producer = (AmqpProducer)producerEndpoint.CreateProducer();
await producer.Start();
var recorder = Recorder();
var endpoint = Endpoint(address, "&routingType=MULTICAST");
var consumer = (AmqpConsumer)endpoint.CreateConsumer(recorder.Processor);
try
{
await consumer.Start();
await producer.Process(new Exchange(new Message("right after start")));
var deadline = DateTime.UtcNow.AddSeconds(15);
while (recorder.Received.IsEmpty && DateTime.UtcNow < deadline)
await Task.Delay(20);
recorder.Received.Should().Equal("right after start");
}
finally
{
await consumer.Stop();
await endpoint.Stop();
await producer.Stop();
await producerEndpoint.Stop();
}
}
///
/// A link the broker refuses fails Start, naming the consumer and the broker's reason. It used to be logged by the
/// receive loop while the consumer counted as started and never received. Here: an ANYCAST receiver on an address
/// that exists for MULTICAST only.
///
[Fact]
public async Task A_receiver_link_the_broker_refuses_fails_Start_and_names_the_consumer()
{
var address = $"multicast-only.{Guid.NewGuid():N}";
var multicastEndpoint = Endpoint(address, "&routingType=MULTICAST");
var multicast = (AmqpConsumer)multicastEndpoint.CreateConsumer(Recorder().Processor);
await multicast.Start();
var endpoint = Endpoint(address, "&routingType=ANYCAST&timeout=10");
var consumer = (AmqpConsumer)endpoint.CreateConsumer(Recorder().Processor);
try
{
var start = () => consumer.Start();
var refused = await start.Should().ThrowAsync();
_output.WriteLine(refused.Which.Message);
refused.WithMessage($"AMQP consumer amqp:{address} cannot start: the broker refused the receiver link*");
}
finally
{
await endpoint.Stop();
await multicast.Stop();
await multicastEndpoint.Stop();
}
}
[Fact]
public void A_dynamic_endpoint_with_an_address_is_refused()
{
var act = () => Endpoint("orders", "&dynamic=true");
act.Should().Throw().WithMessage("*dynamic*");
}
}
Path: redb-route/tests/redb.Route.Tests.Amqp/AmqpPoisonMessageTests.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/tests/redb.Route.Tests.Amqp/AmqpPoisonMessageTests.cs
----
using System.Text;
using Amqp;
using Amqp.Framing;
using redb.Route.Abstractions;
using redb.Route.Amqp;
using redb.Route.Core;
using AmqpMessage = global::Amqp.Message;
namespace redb.Route.Tests.Amqp;
///
/// A message the route always fails is bounded by the broker: the consumer gives a failed delivery back as a failed
/// one (modified with delivery-failed), the broker counts each attempt, and at its maximum delivery count
/// (Artemis: max-delivery-attempts, 10 by default) moves the message to its dead letter address. A
/// released delivery is not counted, and the message came back without end. Single and batch. Expects ActiveMQ
/// Artemis at localhost:5673 (admin/admin) with its default address settings (dead letter address DLQ).
///
[Trait("Category", "Integration")]
public sealed class AmqpPoisonMessageTests
{
private const string Broker = "host=localhost&port=5673&user=admin&password=admin";
private const string BrokerAddress = "amqp://admin:admin@localhost:5673";
[Theory]
[InlineData("")]
[InlineData("&batching=true&maxBatchMessages=10&pollTimeoutMs=200")]
public async Task A_message_that_always_fails_reaches_the_brokers_delivery_limit_and_its_dead_letter_address(string extra)
{
var address = $"poison.{Guid.NewGuid():N}";
var body = $"poison-{Guid.NewGuid():N}";
await SendAsync(address, body);
var deliveries = 0;
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any()).Returns(call =>
{
Interlocked.Increment(ref deliveries);
throw new InvalidOperationException("the route fails every delivery");
});
var endpoint = (AmqpEndpoint)new AmqpComponent().CreateEndpoint(EndpointUriParser.Parse($"amqp://{address}?{Broker}{extra}"));
var consumer = endpoint.CreateConsumer(processor);
await consumer.Start();
try
{
// The count settles when the broker stops redelivering; a released message never lets it settle.
var last = -1;
var deadline = DateTime.UtcNow.AddSeconds(30);
while (DateTime.UtcNow < deadline)
{
await Task.Delay(2000);
var now = Volatile.Read(ref deliveries);
if (now > 0 && now == last) break;
last = now;
}
}
finally
{
await consumer.Stop();
await endpoint.Stop();
}
deliveries.Should().BeInRange(1, 20, "the broker stops redelivering at its maximum delivery count");
(await DeadLettered(body)).Should().BeTrue("the broker moves the message to its dead letter address");
}
private static async Task SendAsync(string address, string body)
{
var connection = await Connection.Factory.CreateAsync(new Address(BrokerAddress));
try
{
var session = new Session(connection);
var sender = new SenderLink(session, $"test-sender-{Guid.NewGuid():N}",
new Target { Address = address, Capabilities = [new global::Amqp.Types.Symbol("queue")] }, null);
await sender.SendAsync(new AmqpMessage(body) { Properties = new Properties { MessageId = Guid.NewGuid().ToString("N") } });
await sender.CloseAsync();
}
finally
{
await connection.CloseAsync();
}
}
/// Looks for the body on the DLQ queue; takes it when found and leaves every other message there.
private static async Task DeadLettered(string body)
{
var connection = await Connection.Factory.CreateAsync(new Address(BrokerAddress));
try
{
var session = new Session(connection);
var receiver = new ReceiverLink(session, $"test-dlq-{Guid.NewGuid():N}",
new Source { Address = "DLQ", Capabilities = [new global::Amqp.Types.Symbol("queue")] }, null);
var deadline = DateTime.UtcNow.AddSeconds(10);
var others = new List();
try
{
while (DateTime.UtcNow < deadline)
{
var msg = await receiver.ReceiveAsync(TimeSpan.FromSeconds(1));
if (msg is null) continue;
var text = msg.Body as string ?? (msg.Body is byte[] b ? Encoding.UTF8.GetString(b) : msg.Body?.ToString());
if (text == body)
{
receiver.Accept(msg);
return true;
}
others.Add(msg);
}
return false;
}
finally
{
foreach (var other in others) receiver.Release(other);
await receiver.CloseAsync();
}
}
finally
{
await connection.CloseAsync();
}
}
}
Path: redb-route/tests/redb.Route.Tests.Amqp/AmqpProducerTests.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/tests/redb.Route.Tests.Amqp/AmqpProducerTests.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Amqp;
namespace redb.Route.Tests.Amqp;
public sealed class AmqpProducerTests
{
private readonly AmqpComponent _component = new();
private AmqpEndpoint CreateEndpoint(string uriStr)
{
var uri = EndpointUriParser.Parse(uriStr);
return (AmqpEndpoint)_component.CreateEndpoint(uri);
}
[Fact]
public void Ctor_NullEndpoint_Throws()
{
var opts = new AmqpEndpointOptions();
var act = () => new AmqpProducer(null!, opts);
act.Should().Throw();
}
[Fact]
public void Ctor_NullOptions_Throws()
{
var ep = CreateEndpoint("amqp://q?host=localhost");
var act = () => new AmqpProducer(ep, null!);
act.Should().Throw();
}
[Fact]
public async Task Process_BeforeStart_Throws()
{
var ep = CreateEndpoint("amqp://q?host=localhost");
var producer = new AmqpProducer(ep, new AmqpEndpointOptions());
var exchange = new Exchange(new Message("test"));
var act = () => producer.Process(exchange);
await act.Should().ThrowAsync().WithMessage("*not been started*");
}
[Fact]
public async Task Stop_BeforeStart_DoesNotThrow()
{
var ep = CreateEndpoint("amqp://q?host=localhost");
var producer = new AmqpProducer(ep, new AmqpEndpointOptions());
var act = () => producer.Stop();
await act.Should().NotThrowAsync();
}
}
Path: redb-route/tests/redb.Route.Tests.Amqp/AmqpReconnectTests.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/tests/redb.Route.Tests.Amqp/AmqpReconnectTests.cs
----
using System.Collections.Concurrent;
using redb.Route.Abstractions;
using redb.Route.Amqp;
using redb.Route.Core;
using redb.Route.Tests.Conformance;
namespace redb.Route.Tests.Amqp;
///
/// A consumer outlives a broker restart: the restart closes its connection and with it every receiver link, and once
/// the broker is back the same route reads the address again, single and batch, and the endpoint counts one reconnect.
/// The restart is on : it runs only where
/// REDB_TEST_AMQP_CONTAINER names the broker's container, elsewhere it is skipped. Run it with
/// tests/docker/run-fault-suite.sh --broker artemis.
///
[Trait("Category", "Integration")]
[Collection(AmqpBrokerRestartCollection.Name)]
public sealed class AmqpReconnectTests
{
// ANYCAST: the stand puts to the queue of the address; without it Artemis auto-creates a MULTICAST address for the
// receiver and the put goes past it.
private const string Broker = "host=localhost&port=5673&user=admin&password=admin&routingType=ANYCAST";
private static readonly AmqpStand Stand = AmqpStand.Instance;
[BrokerFaultTheory(AmqpStand.ContainerVariable)]
[InlineData("")]
[InlineData("&batching=true&maxBatchMessages=10&pollTimeoutMs=200")]
public async Task A_consumer_reads_the_address_again_after_the_broker_restarts(string extra)
{
var address = $"restart.{Guid.NewGuid():N}";
var received = new ConcurrentQueue();
await using var context = new RouteContext();
context.AddComponent(new AmqpComponent());
var uri = $"amqp://{address}?{Broker}{extra}";
context.AddRoutes(r => r.From(uri).RouteId("restarted").Process(e =>
{
// The consumer hands the route the body as UTF-8 bytes.
if (e.In.Body is IEnumerable batch)
foreach (var message in batch)
received.Enqueue(Text(message.Body));
else
received.Enqueue(Text(e.In.Body));
}));
await context.Start();
await Stand.PutAsync(address, "before");
(await Until(() => received.Contains("before"))).Should().BeTrue("the route reads the address before the restart");
await Stand.Fault!.RestartAsync();
(await BrokerFault.UntilAsync(async () =>
{
try { await Stand.PutAsync(address, "after"); return true; }
catch (Exception) { return false; }
}, Stand.Wait, TimeSpan.FromMilliseconds(500))).Should().BeTrue("the broker takes a message once it is back");
(await Until(() => received.Contains("after"))).Should().BeTrue("the consumer reads what was put after the restart");
var statistics = (IEndpointStatistics)context.GetEndpoint(uri);
statistics.Reconnects.Should().Be(1, "one restart is one reconnect");
statistics.HealthStatus.Should().Be(EndpointHealthStatus.Healthy, "the receiver link is back");
context.GetRoute("restarted")!.Status.Should().Be(RouteStatus.Started, "a lost connection does not stop the route");
}
private static string Text(object? body)
=> body is byte[] bytes ? System.Text.Encoding.UTF8.GetString(bytes) : body?.ToString() ?? "";
private static async Task Until(Func condition)
{
var deadline = DateTime.UtcNow + Stand.Wait;
while (!condition())
{
if (DateTime.UtcNow > deadline)
return false;
await Task.Delay(100);
}
return true;
}
}
/// A broker restart cuts every connection of the suite, so nothing runs beside the restart tests.
[CollectionDefinition(Name, DisableParallelization = true)]
public sealed class AmqpBrokerRestartCollection
{
/// The collection's name.
public const string Name = "AMQP broker restart";
}
Path: redb-route/tests/redb.Route.Tests.Amqp/AmqpReplyToBridgeTests.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/tests/redb.Route.Tests.Amqp/AmqpReplyToBridgeTests.cs
----
using redb.Route.Abstractions;
using redb.Route.Amqp;
using redb.Route.Core;
namespace redb.Route.Tests.Amqp;
///
/// A sender's reply-to does not travel across a bridge, as in Apache Camel's JMS: a message consumed with a reply-to and
/// forwarded by an ordinary send goes out without it, unless the producer sets preserveMessageQos=true. The
/// correlation id is carried; a request-reply producer sets its own reply-to. Expects ActiveMQ Artemis at
/// localhost:5673 (admin/admin).
///
[Trait("Category", "Integration")]
public sealed class AmqpReplyToBridgeTests
{
private const string Connection = "host=localhost&port=5673&user=admin&password=admin";
///
/// Sends one message with the given reply-to and correlation id to an input address, bridges it by a route to an
/// output address, and returns the headers the forwarded message arrived with.
///
private static async Task> Bridge(string producerOptions, string? senderReplyTo,
Action? routeStep = null)
{
var input = $"bridge.in.{Guid.NewGuid():N}";
var output = $"bridge.out.{Guid.NewGuid():N}";
var arrived = new TaskCompletionSource>(TaskCreationOptions.RunContinuationsAsynchronously);
await using var context = new RouteContext();
context.AddComponent(new AmqpComponent());
context.AddRoutes(r =>
{
r.From($"amqp://{input}?{Connection}")
.Process(ex => routeStep?.Invoke(ex))
.To($"amqp://{output}?{Connection}{producerOptions}");
r.From($"amqp://{output}?{Connection}")
.Process(ex => arrived.TrySetResult(new Dictionary(ex.In.Headers)));
});
await context.Start();
// The sender: an ordinary send that names its reply address on purpose.
var sender = context.GetEndpoint($"amqp://{input}?{Connection}&preserveMessageQos=true").CreateProducer();
await sender.Start();
var message = new Message("bridged");
message.Headers[AmqpHeaders.CorrelationId] = "corr-1";
if (senderReplyTo is not null)
message.Headers[AmqpHeaders.ReplyTo] = senderReplyTo;
await sender.Process(new Exchange(message));
await sender.Stop();
return await arrived.Task.WaitAsync(TimeSpan.FromSeconds(20));
}
[Fact]
public async Task A_forwarded_message_goes_out_without_the_senders_reply_to_and_keeps_its_correlation_id()
{
var forwarded = await Bridge(producerOptions: "", senderReplyTo: "sender.replies");
forwarded.Should().NotContainKey(AmqpHeaders.ReplyTo, "an ordinary send does not carry a sender's reply-to on");
forwarded[AmqpHeaders.CorrelationId]?.ToString().Should().Be("corr-1");
}
[Fact]
public async Task With_preserveMessageQos_the_forwarded_message_keeps_the_senders_reply_to()
{
var forwarded = await Bridge(producerOptions: "&preserveMessageQos=true", senderReplyTo: "sender.replies");
forwarded[AmqpHeaders.ReplyTo].Should().Be("sender.replies");
forwarded[AmqpHeaders.CorrelationId]?.ToString().Should().Be("corr-1");
}
[Theory]
[InlineData("", false)]
[InlineData("&preserveMessageQos=true", true)]
public async Task A_reply_to_header_set_by_the_route_follows_the_same_rule(string producerOptions, bool kept)
{
var forwarded = await Bridge(producerOptions, senderReplyTo: null,
routeStep: ex => ex.In.Headers[AmqpHeaders.ReplyTo] = "route.named.replies");
if (kept)
forwarded[AmqpHeaders.ReplyTo].Should().Be("route.named.replies");
else
forwarded.Should().NotContainKey(AmqpHeaders.ReplyTo);
}
[Fact]
public async Task A_request_reply_producer_sets_its_own_reply_to_over_a_forwarded_one()
{
var address = $"bridge.rpc.{Guid.NewGuid():N}";
await using var context = new RouteContext();
context.AddComponent(new AmqpComponent());
context.AddRoutes(r => r
.From($"amqp://{address}?{Connection}")
.Process(ex => ex.Out = new Message("pong")));
await context.Start();
var producer = context.GetEndpoint($"amqp://{address}?{Connection}&replyTo=true&timeout=15&preserveMessageQos=true")
.CreateProducer();
await producer.Start();
try
{
var exchange = new Exchange(new Message("ping"));
exchange.In.Headers[AmqpHeaders.ReplyTo] = "an.address.of.another.system";
await producer.Process(exchange);
exchange.HasOut.Should().BeTrue("the reply came back to the producer's own reply address");
var body = exchange.Out!.Body is byte[] bytes ? System.Text.Encoding.UTF8.GetString(bytes) : exchange.Out.Body?.ToString();
body.Should().Be("pong");
}
finally
{
await producer.Stop();
}
}
}
Path: redb-route/tests/redb.Route.Tests.Amqp/AmqpStand.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/tests/redb.Route.Tests.Amqp/AmqpStand.cs
----
using Amqp;
using Amqp.Framing;
using redb.Route.Tests.Conformance;
using AmqpMessage = global::Amqp.Message;
namespace redb.Route.Tests.Amqp;
///
/// The AMQP 1.0 stand: ActiveMQ Artemis at localhost:5673 (admin/admin), reached through AMQPNetLite directly, not
/// through the connector. Its container, when names it, is broken with
/// ; the broker is ready when its AMQP acceptor takes connections again.
///
public sealed class AmqpStand : IConnectorStand
{
/// The variable that names the Artemis container a test may restart.
public const string ContainerVariable = "REDB_TEST_AMQP_CONTAINER";
/// The broker's address for the stand's own client.
public const string BrokerAddress = "amqp://admin:admin@localhost:5673";
private static readonly global::Amqp.Types.Symbol QueueCapability = new("queue");
/// The stand of this process.
public static AmqpStand Instance { get; } = new();
private AmqpStand()
{
}
///
public BrokerFault? Fault { get; } = BrokerFault.FromEnvironment(ContainerVariable, "nc", "-z", "localhost", "5673");
///
public TimeSpan Wait { get; } = BrokerFault.DefaultWait;
///
public async Task PutAsync(string destination, string body, CancellationToken ct = default)
{
var connection = await Connection.Factory.CreateAsync(new Address(BrokerAddress)).WaitAsync(ct);
try
{
var session = new Session(connection);
var sender = new SenderLink(session, $"stand-sender-{Guid.NewGuid():N}",
new Target { Address = destination, Capabilities = [QueueCapability] }, null);
await sender.SendAsync(new AmqpMessage(body) { Properties = new Properties { MessageId = Guid.NewGuid().ToString("N") } });
await sender.CloseAsync();
}
finally
{
await connection.CloseAsync();
}
}
///
public async Task> DrainAsync(string destination, TimeSpan wait, CancellationToken ct = default)
{
var bodies = new List();
var connection = await Connection.Factory.CreateAsync(new Address(BrokerAddress)).WaitAsync(ct);
try
{
var session = new Session(connection);
var receiver = new ReceiverLink(session, $"stand-receiver-{Guid.NewGuid():N}",
new Source { Address = destination, Capabilities = [QueueCapability] }, null);
var next = wait;
while (await receiver.ReceiveAsync(next) is { } message)
{
receiver.Accept(message);
bodies.Add(message.Body?.ToString() ?? "");
next = TimeSpan.FromMilliseconds(500);
}
await receiver.CloseAsync();
}
finally
{
await connection.CloseAsync();
}
return bodies;
}
}
Path: redb-route/tests/redb.Route.Tests.Amqp/AmqpTracePropagationTests.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/tests/redb.Route.Tests.Amqp/AmqpTracePropagationTests.cs
----
using System.Diagnostics;
using Amqp;
using Amqp.Framing;
using redb.Route.Abstractions;
using redb.Route.Amqp;
using redb.Route.Configuration;
using redb.Route.Core;
using redb.Route.Telemetry;
using redb.Route.Tests.Telemetry;
using AmqpMessage = global::Amqp.Message;
using Message = redb.Route.Core.Message;
namespace redb.Route.Tests.Amqp;
///
/// W3C trace context through AMQP application-properties, through the connector itself against a real broker. The
/// consumer opens a receive span per message: a child of the sender's context, or a root without one — never a child
/// of the activity the receive loop inherited from whoever started it — with the sender's baggage back on it and the
/// route's spans under it; a failed route marks it red. The producer writes the context of its own send span over a
/// copied one. EnableTelemetry=false opens none of these spans, while the ambient context still goes out.
/// Expects ActiveMQ Artemis at localhost:5673 (admin/admin).
///
[Trait("Category", "Integration")]
public sealed class AmqpTracePropagationTests
{
private const string Broker = "localhost";
private const int Port = 5673;
private const string User = "admin";
private const string Password = "admin";
private static readonly TimeSpan Wait = TimeSpan.FromSeconds(15);
private static string NewAddress() => $"trace.{Guid.NewGuid():N}";
private static string Uri(string address) => $"amqp://{address}?host={Broker}&port={Port}&user={User}&password={Password}";
private static (ActivityTraceId TraceId, ActivitySpanId SpanId, string Header) Caller()
{
var traceId = ActivityTraceId.CreateRandom();
var spanId = ActivitySpanId.CreateRandom();
return (traceId, spanId, $"00-{traceId}-{spanId}-01");
}
private static RouteTelemetryProbe SpansOf(string address, ActivityKind kind)
=> new(a => a.Kind == kind && RouteTelemetryProbe.Tag(a, "messaging.destination.name") == address);
/// Sends one message straight through AMQPNetLite, as a sender that is not redb would.
private static async Task SendRaw(string address, IDictionary? properties = null)
{
var connection = await Connection.Factory.CreateAsync(new Address(Broker, Port, User, Password, scheme: "AMQP"));
try
{
var session = new Session(connection);
var sender = new SenderLink(session, "trace-test-sender", address);
var message = new AmqpMessage("payload");
if (properties is not null)
{
message.ApplicationProperties = new ApplicationProperties();
foreach (var (key, value) in properties)
message.ApplicationProperties.Map[key] = value;
}
await sender.SendAsync(message);
await sender.CloseAsync();
}
finally
{
await connection.CloseAsync();
}
}
/// Receives one message straight through AMQPNetLite.
private static async Task ReceiveRaw(string address)
{
var connection = await Connection.Factory.CreateAsync(new Address(Broker, Port, User, Password, scheme: "AMQP"));
try
{
var receiver = new ReceiverLink(new Session(connection), "trace-test-receiver", address);
var message = await receiver.ReceiveAsync(Wait)
?? throw new TimeoutException($"No message arrived on {address}.");
receiver.Accept(message);
await receiver.CloseAsync();
return message;
}
finally
{
await connection.CloseAsync();
}
}
///
/// A context with one consuming route, started inside a host span: the receive loop inherits it, the way it inherits
/// whatever activity the application held when it started the routes.
///
private static async Task StartConsumer(string address, Action step, bool telemetry = true)
{
var ctx = new RouteContext(options: new RouteEngineOptions { EnableTelemetry = telemetry });
ctx.AddComponent(new AmqpComponent());
ctx.AddRoutes(r => r.From(Uri(address)).RouteId($"amqp-{address}").Process(step));
using (new Activity("host startup").SetIdFormat(ActivityIdFormat.W3C).Start())
await ctx.Start();
return ctx;
}
private static async Task Arrived(TaskCompletionSource done)
=> (await Task.WhenAny(done.Task, Task.Delay(Wait))).Should().Be(done.Task, "the message should reach the route");
[Fact]
public async Task A_message_without_context_opens_a_root_receive_span()
{
var address = NewAddress();
using var probe = SpansOf(address, ActivityKind.Consumer);
var done = new TaskCompletionSource();
await using (await StartConsumer(address, _ => done.TrySetResult()))
{
await SendRaw(address);
await Arrived(done);
}
var receive = probe.Activities.Should().ContainSingle().Subject;
receive.ParentSpanId.Should().Be(default(ActivitySpanId),
"a message that carries no context starts a trace, not a child of the host's startup span");
receive.GetTagItem("messaging.system").Should().Be("amqp");
RouteTelemetryProbe.Tag(receive, RouteTelemetryProbe.EndpointTag).Should().StartWith("amqp://");
}
[Fact]
public async Task A_message_with_context_continues_the_senders_trace_and_the_route_runs_under_it()
{
var address = NewAddress();
using var probe = SpansOf(address, ActivityKind.Consumer);
using var routes = RouteTelemetryProbe.ForRouteIdPrefix($"amqp-{address}");
var caller = Caller();
var done = new TaskCompletionSource();
await using (await StartConsumer(address, _ => done.TrySetResult()))
{
await SendRaw(address, new Dictionary { ["traceparent"] = caller.Header });
await Arrived(done);
}
var receive = probe.Activities.Should().ContainSingle().Subject;
receive.TraceId.Should().Be(caller.TraceId);
receive.ParentSpanId.Should().Be(caller.SpanId);
routes.Activities.Should().ContainSingle().Which.ParentSpanId.Should().Be(receive.SpanId);
}
[Fact]
public async Task The_senders_baggage_reaches_the_route()
{
var address = NewAddress();
using var probe = SpansOf(address, ActivityKind.Consumer);
var seen = new TaskCompletionSource();
await using (await StartConsumer(address, _ => seen.TrySetResult(Activity.Current?.GetBaggageItem("tenant"))))
{
await SendRaw(address, new Dictionary { ["traceparent"] = Caller().Header, ["baggage"] = "tenant=t1" });
(await Task.WhenAny(seen.Task, Task.Delay(Wait))).Should().Be(seen.Task);
}
seen.Task.Result.Should().Be("t1");
}
[Fact]
public async Task A_failed_route_marks_the_receive_span_red()
{
var address = NewAddress();
using var probe = SpansOf(address, ActivityKind.Consumer);
var failed = new TaskCompletionSource();
await using (await StartConsumer(address, _ =>
{
failed.TrySetResult();
throw new InvalidOperationException("route failed");
}))
{
await SendRaw(address);
await Arrived(failed);
var deadline = DateTime.UtcNow + Wait;
while (probe.Activities.Count == 0 && DateTime.UtcNow < deadline)
await Task.Delay(100);
}
probe.Activities.Should().NotBeEmpty();
probe.Activities[0].Status.Should().Be(ActivityStatusCode.Error);
}
[Fact]
public async Task A_timeout_inside_the_route_marks_the_receive_span_red()
{
var address = NewAddress();
using var probe = SpansOf(address, ActivityKind.Consumer);
var thrown = new TaskCompletionSource();
await using (await StartConsumer(address, _ =>
{
thrown.TrySetResult();
throw new TaskCanceledException("a call inside the route timed out");
}))
{
await SendRaw(address);
await Arrived(thrown);
var deadline = DateTime.UtcNow + Wait;
while (probe.Activities.Count == 0 && DateTime.UtcNow < deadline)
await Task.Delay(100);
}
probe.Activities.Should().NotBeEmpty();
probe.Activities[0].Status.Should().Be(ActivityStatusCode.Error, "a cancellation nobody asked for is a failure");
}
[Fact]
public async Task Stopping_the_consumer_does_not_mark_the_interrupted_message_red()
{
var address = NewAddress();
using var probe = SpansOf(address, ActivityKind.Consumer);
var started = new TaskCompletionSource();
var ctx = new RouteContext(options: new RouteEngineOptions { ShutdownTimeout = TimeSpan.FromSeconds(2) });
ctx.AddComponent(new AmqpComponent());
ctx.AddRoutes(r => r.From(Uri(address)).Process(async (_, ct) =>
{
started.TrySetResult();
await Task.Delay(Timeout.Infinite, ct);
}));
await ctx.Start();
await SendRaw(address);
await Arrived(started);
await ctx.DisposeAsync(); // the drain gives up and cancels the processing token
var deadline = DateTime.UtcNow + Wait;
while (probe.Activities.Count == 0 && DateTime.UtcNow < deadline)
await Task.Delay(100);
probe.Activities.Should().NotBeEmpty();
probe.Activities.Should().OnlyContain(a => a.Status != ActivityStatusCode.Error, "our own stop is not a failure");
}
[Fact]
public async Task The_producer_sends_the_context_of_its_own_span_over_a_copied_one()
{
var address = NewAddress();
using var sends = SpansOf(address, ActivityKind.Producer);
await using var ctx = new RouteContext();
ctx.AddComponent(new AmqpComponent());
await ctx.Start();
using var outer = new Activity("caller").SetIdFormat(ActivityIdFormat.W3C).Start();
var exchange = new Exchange(new Message("payload"));
exchange.In.Headers["traceparent"] = Caller().Header; // what the header bridge copies from a received message
using (var template = new ProducerTemplate(ctx))
{
template.Start();
await template.SendAsync(Uri(address), exchange);
}
var send = sends.Activities.Should().ContainSingle().Subject;
var received = await ReceiveRaw(address);
received.ApplicationProperties.Map["traceparent"].Should().Be($"00-{outer.TraceId}-{send.SpanId}-{(int)send.ActivityTraceFlags:x2}");
}
[Fact]
public async Task Tracing_off_opens_no_span_and_still_passes_the_context_on()
{
var address = NewAddress();
using var spans = new RouteTelemetryProbe(a => RouteTelemetryProbe.Tag(a, "messaging.destination.name") == address);
await using var ctx = new RouteContext(options: new RouteEngineOptions { EnableTelemetry = false });
ctx.AddComponent(new AmqpComponent());
await ctx.Start();
using var outer = new Activity("caller").SetIdFormat(ActivityIdFormat.W3C).Start();
using (var template = new ProducerTemplate(ctx))
{
template.Start();
await template.SendAsync(Uri(address), new Exchange(new Message("payload")));
}
var received = await ReceiveRaw(address);
received.ApplicationProperties.Map["traceparent"].Should().Be(outer.Id, "with no send span the ambient context goes out");
var done = new TaskCompletionSource();
await using (await StartConsumer(address, _ => done.TrySetResult(), telemetry: false))
{
await SendRaw(address, new Dictionary { ["traceparent"] = Caller().Header });
await Arrived(done);
}
spans.Activities.Should().BeEmpty();
}
}
Path: redb-route/tests/redb.Route.Tests.Amqp/ConsumerShapedEntryPointTests.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/tests/redb.Route.Tests.Amqp/ConsumerShapedEntryPointTests.cs
----
using AwesomeAssertions;
using redb.Route.Amqp;
// A namespace outside redb.Route and the one using a consumer writes: the entry point must be reachable by its short
// name. AMQPNetLite's root namespace `Amqp` (with its type `Address`) shadowed a class of that name, so
// `Amqp.Address(...)` did not compile in a consumer's file; this file is the compile check for the short name.
namespace Shop.Integration.AmqpConsumerCheck;
public class ConsumerShapedEntryPointTests
{
[Fact]
public void TheEntryPoint_IsReachableByItsShortName_WithOnlyThePackageUsing()
{
string uri = AmqpDsl.Address("orders").Host("amqp.local").Port(5672);
uri.Should().StartWith("amqp:orders");
uri.Should().Contain("host=amqp.local");
}
}
Path: redb-route/tests/redb.Route.Tests.Amqp/PreserveMessageQosOptionTests.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/tests/redb.Route.Tests.Amqp/PreserveMessageQosOptionTests.cs
----
using redb.Route.Amqp;
using redb.Route.Core;
namespace redb.Route.Tests.Amqp;
/// preserveMessageQos (Apache Camel's name): off by default, set from the URI and the builder.
public sealed class PreserveMessageQosOptionTests
{
[Fact]
public void Off_by_default()
=> new AmqpEndpointOptions().PreserveMessageQos.Should().BeFalse();
[Fact]
public void Set_from_the_uri()
{
var options = new AmqpEndpointOptions();
options.BindFromUri(EndpointUriParser.Parse("amqp://q?preserveMessageQos=true").RawParameters);
options.PreserveMessageQos.Should().BeTrue();
}
[Fact]
public void Set_by_the_builder()
{
AmqpDsl.Address("q").PreserveMessageQos().Build().Should().Contain("preserveMessageQos=true");
AmqpDsl.Address("q").Build().Should().NotContain("preserveMessageQos");
}
}
Path: redb-route/tests/redb.Route.Tests.Amqp/redb.Route.Tests.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/tests/redb.Route.Tests.Amqp/redb.Route.Tests.Amqp.csproj
----