Bundle: redb-route / tests/redb.Route.Tests.AzureServiceBus (tests.redb.Route.Tests.AzureServiceBus.txt), 23 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.AzureServiceBus/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.AzureServiceBus/AckModeOptionsTests.cs
----
using AwesomeAssertions;
using redb.Route.Core;
using redb.Route.AzureServiceBus;
namespace redb.Route.Tests.AzureServiceBus;
///
/// 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 AzureServiceBusEndpointOptions Bind(params (string Key, string Value)[] parameters)
{
var options = new AzureServiceBusEndpointOptions();
options.BindFromUri(parameters.ToDictionary(p => p.Key, p => p.Value));
return options;
}
[Fact]
public void The_default_is_manual() => new AzureServiceBusEndpointOptions().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(("receiveMode", "ReceiveAndDelete"));
act.Should().Throw().WithMessage("*'receiveMode' is replaced by 'ackMode'*");
}
}
Path: redb-route/tests/redb.Route.Tests.AzureServiceBus/AsbConformanceTests.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.AzureServiceBus/AsbConformanceTests.cs
----
using redb.Route.Abstractions;
using redb.Route.AzureServiceBus;
using redb.Route.Tests.Conformance;
namespace redb.Route.Tests.AzureServiceBus;
///
/// The Service Bus connector against , on . The
/// emulator creates no entity on request, so the queues are fixed in tests/docker/servicebus/Config.json and a test
/// takes one emptied: queue.conformance, or queue.conformance.2 for a test that asks for two attempts. The
/// attempts are the entity's MaxDeliveryCount (3 and 2): a failed message is abandoned and the entity delivers it
/// again, then moves it to its dead letter queue. Not applicable here, and passing without running: the start while the
/// broker is down (the processor opens no connection when it starts: the route is Started at once and the client
/// connects by itself once the emulator is up). Runs alone: the restart case breaks the emulator for every connection of
/// the suite; every case needs the stand, so the class runs only in a fault run
/// (run-fault-suite.sh --broker servicebus).
///
[Trait("Category", "Integration")]
[Collection(AsbEmulatorRestartCollection.Name)]
public sealed class AsbConformanceTests : ConnectorConformance
{
private const string Queue = "queue.conformance";
private const string TwoAttemptsQueue = "queue.conformance.2";
protected override AsbFaultStand Stand => AsbFaultStand.Instance;
protected override ConnectorTraits Traits { get; } = new()
{
AckOnReceipt = true, Transactions = true, DeadLetter = true, Concurrency = true, Batch = true, LateBroker = false,
};
protected override int BrokerPort => 5672;
protected override IComponent CreateComponent() => new AzureServiceBusComponent();
protected override Task CreateQueueAsync(bool deadLetter) => TakeAsync(Queue);
protected override Task CreateQueueAsync(bool deadLetter, int attempts) => attempts switch
{
3 => TakeAsync(Queue),
2 => TakeAsync(TwoAttemptsQueue),
_ => throw new NotSupportedException($"No queue of the stand delivers a message {attempts} times."),
};
protected override async Task DeleteQueueAsync(ConformanceQueue queue)
{
await Stand.DrainAsync(queue.Name, TimeSpan.FromMilliseconds(500));
await Stand.DrainAsync(queue.DeadLetter!, TimeSpan.FromMilliseconds(500));
}
protected override string ConsumerUri(ConformanceQueue queue, ConsumerSettings settings)
{
var uri = $"asb://{queue.Name}?connectionString={AsbFaultStand.ConnectionString}";
if (settings.AckOnReceipt)
uri += "&ackMode=auto";
if (settings.Concurrency is { } concurrency)
uri += $"&maxConcurrentCalls={concurrency}";
if (settings.BatchSize is { } size)
uri += $"&batching=true&maxBatchMessages={size}&pollTimeoutMs={(int)settings.BatchWait.TotalMilliseconds}";
return uri;
}
protected override string ProducerUri(ConformanceQueue queue, bool transacted)
=> $"asb://{queue.Name}?connectionString={AsbFaultStand.ConnectionString}" + (transacted ? "&transacted=true" : "");
private async Task TakeAsync(string name)
{
var queue = new ConformanceQueue(name, $"{name}/$deadletterqueue");
await DeleteQueueAsync(queue);
return queue;
}
}
Path: redb-route/tests/redb.Route.Tests.AzureServiceBus/AsbConnectionEvents.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.AzureServiceBus/AsbConnectionEvents.cs
----
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Diagnostics.Tracing;
namespace redb.Route.Tests.AzureServiceBus;
///
/// Counts, in this process, the peeks of the Service Bus client (its Azure-Messaging-ServiceBus event source)
/// and the AMQP connections opened and closed under it (the Microsoft-Azure-Amqp event source), and keeps each
/// of them with its time on the given clock. The counts start when the listener is made and stop when it is disposed.
///
internal sealed class AsbConnectionEvents : EventListener
{
private readonly Stopwatch? _clock;
private readonly ConcurrentQueue _timeline = new();
private int _peeksStarted;
private int _peeksCompleted;
private int _connectionsOpened;
private int _connectionsClosed;
/// The clock the timeline is kept on.
public AsbConnectionEvents(Stopwatch clock)
{
_clock = clock;
}
/// The peeks the client started.
public int PeeksStarted => Volatile.Read(ref _peeksStarted);
/// The peeks the namespace answered.
public int PeeksCompleted => Volatile.Read(ref _peeksCompleted);
/// The AMQP connections opened.
public int ConnectionsOpened => Volatile.Read(ref _connectionsOpened);
/// The AMQP connections closed.
public int ConnectionsClosed => Volatile.Read(ref _connectionsClosed);
/// The counted events in order, each with its second on the clock.
public string Timeline => string.Join(", ", _timeline);
protected override void OnEventSourceCreated(EventSource eventSource)
{
if (eventSource.Name is "Azure-Messaging-ServiceBus" or "Microsoft-Azure-Amqp")
EnableEvents(eventSource, EventLevel.Verbose, EventKeywords.All);
}
protected override void OnEventWritten(EventWrittenEventArgs eventData)
{
switch (eventData.EventName)
{
case "PeekMessageStart":
Interlocked.Increment(ref _peeksStarted);
break;
case "PeekMessageComplete":
Interlocked.Increment(ref _peeksCompleted);
break;
case "AmqpOpenConnection":
Interlocked.Increment(ref _connectionsOpened);
break;
case "AmqpCloseConnection":
Interlocked.Increment(ref _connectionsClosed);
break;
default:
return;
}
// The base constructor enables the sources before this one has run.
if (_clock is not null)
_timeline.Enqueue($"{eventData.EventName} {_clock.Elapsed.TotalSeconds:0.0}");
}
}
Path: redb-route/tests/redb.Route.Tests.AzureServiceBus/AsbEmulatorQueue.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.AzureServiceBus/AsbEmulatorQueue.cs
----
namespace redb.Route.Tests.AzureServiceBus;
///
/// The emulator has one pre-created queue, queue.1, and the integration classes drain and receive from it. Run in
/// parallel they take each other's messages, so they share this collection and run one after another.
///
[CollectionDefinition(Name)]
public sealed class AsbEmulatorQueue
{
public const string Name = "asb-emulator-queue.1";
}
Path: redb-route/tests/redb.Route.Tests.AzureServiceBus/AsbFaultStand.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.AzureServiceBus/AsbFaultStand.cs
----
using System.Text;
using Azure.Messaging.ServiceBus;
using redb.Route.Tests.Conformance;
namespace redb.Route.Tests.AzureServiceBus;
///
/// The Service Bus stand of the fault runs: the emulator and its own SQL container, started by
/// tests/docker/run-fault-suite.sh --broker servicebus with the entities of tests/docker/servicebus/Config.json
/// (the emulator creates none on request), reached through Azure.Messaging.ServiceBus directly, not through the connector.
/// Both run with host networking: AMQP at localhost:5672 (the compose file publishes it at 5300 instead), SQL at 14330,
/// away from a SQL Server the host may run on 1433. Only the emulator's container is stopped and started; the SQL
/// container keeps the messages. The emulator image has no shell, so it is ready when it logs
/// after the fault.
///
public sealed class AsbFaultStand : IConnectorStand
{
/// The variable that names the emulator container a test may stop and restart.
public const string ContainerVariable = "REDB_TEST_ASB_CONTAINER";
/// The line the emulator logs once it serves AMQP.
public const string ReadyLog = "Emulator Service is Successfully Up!";
/// The connection string of the emulator.
public const string ConnectionString =
"Endpoint=sb://localhost:5672;SharedAccessKeyName=RootManageSharedAccessKey;" +
"SharedAccessKey=SAS_KEY_VALUE;UseDevelopmentEmulator=true;";
/// The session every message put on a session queue carries.
public const string Session = "fault-session";
/// The stand of this process.
public static AsbFaultStand Instance { get; } = new();
private AsbFaultStand()
{
}
///
public BrokerFault? Fault { get; } = BrokerFault.FromEnvironmentWithReadyLog(ContainerVariable, ReadyLog);
///
public TimeSpan Wait { get; } = BrokerFault.DefaultWait;
/// Whether is a session queue of the stand's Config.json (its name says so).
public static bool IsSessionQueue(string queue) => queue.Contains(".session", StringComparison.Ordinal);
///
public async Task PutAsync(string destination, string body, CancellationToken ct = default)
{
await using var client = new ServiceBusClient(ConnectionString);
await using var sender = client.CreateSender(destination);
var message = new ServiceBusMessage(Encoding.UTF8.GetBytes(body));
if (IsSessionQueue(destination))
message.SessionId = Session;
await sender.SendMessageAsync(message, ct);
}
///
/// Takes what holds. It locks and completes each message: a message the namespace
/// hands over after the receive has timed out stays in the closing receiver's buffer, and in ReceiveAndDelete it
/// would be gone with it; locked, it comes back when the lock ends.
///
public async Task> DrainAsync(string destination, TimeSpan wait, CancellationToken ct = default)
{
await using var client = new ServiceBusClient(ConnectionString);
var bodies = new List();
var (queue, subQueue) = destination.EndsWith("/$deadletterqueue", StringComparison.Ordinal)
? (destination[..^"/$deadletterqueue".Length], SubQueue.DeadLetter)
: (destination, SubQueue.None);
var options = new ServiceBusReceiverOptions { ReceiveMode = ServiceBusReceiveMode.PeekLock, SubQueue = subQueue };
ServiceBusReceiver receiver;
if (subQueue == SubQueue.None && IsSessionQueue(queue))
{
try
{
receiver = await client.AcceptSessionAsync(queue, Session,
new ServiceBusSessionReceiverOptions { ReceiveMode = ServiceBusReceiveMode.PeekLock }, ct);
}
catch (ServiceBusException ex) when (ex.Reason == ServiceBusFailureReason.SessionCannotBeLocked)
{
return bodies;
}
}
else
{
receiver = client.CreateReceiver(queue, options);
}
await using (receiver)
{
var first = wait;
while (true)
{
var batch = await receiver.ReceiveMessagesAsync(100, first, ct);
if (batch.Count == 0)
return bodies;
foreach (var message in batch)
{
await receiver.CompleteMessageAsync(message, ct);
bodies.Add(message.Body.ToString());
}
first = TimeSpan.FromMilliseconds(500);
}
}
}
}
Path: redb-route/tests/redb.Route.Tests.AzureServiceBus/AsbReconnectTests.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.AzureServiceBus/AsbReconnectTests.cs
----
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using redb.Route.Abstractions;
using redb.Route.AzureServiceBus;
using redb.Route.Configuration;
using redb.Route.Core;
using redb.Route.Tests.Conformance;
namespace redb.Route.Tests.AzureServiceBus;
///
/// A Service Bus consumer through a lost emulator, on , for each of its three kinds: the
/// processor, the session processor and the batch receiver. The client reconnects by itself; what the consumer owes is
/// the truth in health: while the emulator is away the endpoint shows a lost connection (not message errors: the error
/// count stays where it was), it counts one reconnect when the emulator is back, and the route reads on. The stop and
/// start of the emulator are : they run only where REDB_TEST_ASB_CONTAINER names its
/// container, elsewhere they are skipped. Run them with tests/docker/run-fault-suite.sh --broker servicebus.
///
[Trait("Category", "Integration")]
[Collection(AsbEmulatorRestartCollection.Name)]
public sealed class AsbReconnectTests
{
private static readonly AsbFaultStand Stand = AsbFaultStand.Instance;
[BrokerFaultTheory(AsbFaultStand.ContainerVariable)]
[InlineData("queue.fault.single", "")]
[InlineData("queue.fault.session", "enableSessions=true")]
[InlineData("queue.fault.batch", "batching=true&maxBatchMessages=10&pollTimeoutMs=500")]
public async Task A_consumer_shows_the_lost_emulator_in_health_and_reads_again_once_it_is_back(string queue, string query)
{
var fault = Stand.Fault!;
await Stand.DrainAsync(queue, TimeSpan.FromSeconds(1));
var received = new ConcurrentQueue();
await using var context = NewContext();
var uri = Uri(queue, query);
context.AddRoutes(r => r.From(uri).RouteId("restarted").Process(e => Collect(e, received)));
await context.Start();
await Stand.PutAsync(queue, "before");
(await Until(() => received.Contains("before"))).Should().BeTrue("the route reads the queue before the outage");
var statistics = (IEndpointStatistics)context.GetEndpoint(uri);
var errorsBefore = statistics.Errors;
await fault.StopAsync();
try
{
(await Until(() => statistics.HealthStatus != EndpointHealthStatus.Healthy)).Should().BeTrue(
"the endpoint shows that the emulator is gone");
statistics.HealthReason.Should().Contain("connection", $"the reason names the lost connection (last error: {statistics.LastErrorMessage})");
statistics.Errors.Should().Be(errorsBefore, $"a lost connection is not a failed message (last error: {statistics.LastErrorMessage})");
}
finally
{
await fault.StartAsync();
}
(await Until(() => statistics.Reconnects > 0)).Should().BeTrue("the endpoint counts the reconnect");
(await BrokerFault.UntilAsync(async () =>
{
try { await Stand.PutAsync(queue, "after"); return true; }
catch (Exception) { return false; }
}, Stand.Wait, TimeSpan.FromMilliseconds(500))).Should().BeTrue("the emulator takes a message once it is back");
(await Until(() => received.Contains("after"))).Should().BeTrue("the consumer reads what was put after the outage");
statistics.Reconnects.Should().Be(1, "one outage is one reconnect");
statistics.Errors.Should().Be(errorsBefore, $"a lost connection is not a failed message (last error: {statistics.LastErrorMessage})");
statistics.HealthStatus.Should().Be(EndpointHealthStatus.Healthy, $"the emulator is back ({statistics.HealthReason})");
context.GetRoute("restarted")!.Status.Should().Be(RouteStatus.Started, "a lost connection does not stop the route");
}
[BrokerFaultTheory(AsbFaultStand.ContainerVariable)]
[InlineData("queue.fault.single", "")]
[InlineData("queue.fault.session", "enableSessions=true")]
[InlineData("queue.fault.batch", "batching=true&maxBatchMessages=10&pollTimeoutMs=500")]
public async Task A_route_stops_in_time_while_the_emulator_is_away(string queue, string query)
{
var fault = Stand.Fault!;
await Stand.DrainAsync(queue, TimeSpan.FromSeconds(1));
var received = new ConcurrentQueue();
var context = NewContext();
var uri = Uri(queue, query);
context.AddRoutes(r => r.From(uri).RouteId("stopped").Process(e => Collect(e, received)));
await context.Start();
await Stand.PutAsync(queue, "before");
(await Until(() => received.Contains("before"))).Should().BeTrue();
var statistics = (IEndpointStatistics)context.GetEndpoint(uri);
await fault.StopAsync();
try
{
(await Until(() => statistics.HealthStatus != EndpointHealthStatus.Healthy)).Should().BeTrue(
"the consumer knows the emulator is gone");
var watch = Stopwatch.StartNew();
await context.Stop();
await context.DisposeAsync();
watch.Elapsed.Should().BeLessThan(TimeSpan.FromSeconds(30),
"a stop does not wait for the emulator or for a probe of it");
}
finally
{
await fault.StartAsync();
}
}
///
/// The probe of a lost consumer peeks the dead-letter queue through the consumer's own client, so the outage and the
/// recovery never hold a second connection. Counted in the test process, while the stand has no client open: the
/// probe's peeks from the client's own events, the AMQP connections the process opens from the AMQP library's
/// events, and the process's own established sockets to the emulator.
///
[BrokerFaultTheory(AsbFaultStand.ContainerVariable)]
[InlineData("queue.fault.single", "")]
[InlineData("queue.fault.session", "enableSessions=true")]
public async Task The_probe_of_a_lost_consumer_opens_no_second_connection(string queue, string query)
{
var fault = Stand.Fault!;
await Stand.DrainAsync(queue, TimeSpan.FromSeconds(1));
var received = new ConcurrentQueue();
await using var context = NewContext();
var uri = Uri(queue, query);
context.AddRoutes(r => r.From(uri).RouteId("probed").Process(e => Collect(e, received)));
await context.Start();
await Stand.PutAsync(queue, "before");
(await Until(() => received.Contains("before"))).Should().BeTrue("the route reads the queue before the outage");
var statistics = (IEndpointStatistics)context.GetEndpoint(uri);
// The stand's clients are closed by now: what stays established is the consumer's.
(await Until(() => EstablishedToEmulator().Count == 1)).Should().BeTrue(
$"only the consumer's connection is open ({EstablishedToEmulator().Count} established)");
var clock = Stopwatch.StartNew();
using var events = new AsbConnectionEvents(clock);
var most = 0;
var sockets = new ConcurrentDictionary();
using var sampling = new CancellationTokenSource();
var sampler = Task.Run(async () =>
{
while (!sampling.IsCancellationRequested)
{
var now = clock.Elapsed.TotalSeconds;
var open = EstablishedToEmulator();
most = Math.Max(most, open.Count);
foreach (var port in open)
sockets.AddOrUpdate(port, (now, now), (_, seen) => (seen.First, now));
await Task.Delay(20);
}
});
var marks = new List();
await fault.StopAsync();
marks.Add($"stopped {clock.Elapsed.TotalSeconds:0.0}");
try
{
(await Until(() => statistics.HealthStatus != EndpointHealthStatus.Healthy)).Should().BeTrue(
"the endpoint shows that the emulator is gone");
(await Until(() => events.PeeksStarted > 0)).Should().BeTrue("the probe peeks while the emulator is away");
}
finally
{
await fault.StartAsync();
marks.Add($"started {clock.Elapsed.TotalSeconds:0.0}");
}
(await Until(() => statistics.Reconnects > 0)).Should().BeTrue("the endpoint counts the reconnect");
marks.Add($"reconnect counted {clock.Elapsed.TotalSeconds:0.0}");
await Task.Delay(TimeSpan.FromSeconds(5));
await sampling.CancelAsync();
await sampler;
var lifetimes = string.Join(", ", sockets.OrderBy(s => s.Value.First)
.Select(s => $"port {s.Key} {s.Value.First:0.0}-{s.Value.Last:0.0}"));
var seen = $"peeks started {events.PeeksStarted}, completed {events.PeeksCompleted}; AMQP connections opened " +
$"{events.ConnectionsOpened}, closed {events.ConnectionsClosed}; most established sockets {most}; " +
$"{string.Join(", ", marks)}; sockets (s from the listener) {lifetimes}; events {events.Timeline}";
most.Should().Be(1, $"the consumer and its probe share one connection ({seen})");
EstablishedToEmulator().Count.Should().Be(1, $"one connection after the recovery ({seen})");
(events.ConnectionsOpened - events.ConnectionsClosed).Should().BeLessThanOrEqualTo(1,
$"the process holds no more than the consumer's connection ({seen})");
}
///
/// The local ports of the established TCP connections of this process to the emulator's AMQP port (the fault runs are Linux
/// containers): the rows of /proc/net/tcp and /proc/net/tcp6 in state 01 with remote port 5672 whose
/// socket inode is one of this process's descriptors. The tables are the host's (the stand runs with host
/// networking), so the inode keeps out the emulator's own connections to its port.
///
private static HashSet EstablishedToEmulator()
{
var own = new HashSet(StringComparer.Ordinal);
foreach (var descriptor in Directory.EnumerateFiles("/proc/self/fd"))
{
string? target;
try
{
target = new FileInfo(descriptor).LinkTarget;
}
catch (IOException)
{
continue;
}
if (target is not null && target.StartsWith("socket:[", StringComparison.Ordinal))
own.Add(target["socket:[".Length..^1]);
}
// A read of the table is not one snapshot: a row can come twice when the table changes under the read.
var ports = new HashSet(StringComparer.Ordinal);
foreach (var table in new[] { "/proc/net/tcp", "/proc/net/tcp6" })
{
if (!File.Exists(table))
continue;
foreach (var line in File.ReadLines(table).Skip(1))
{
var fields = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (fields.Length > 9 && fields[3] == "01" && fields[2].EndsWith(":1628", StringComparison.Ordinal)
&& own.Contains(fields[9]))
ports.Add(Convert.ToInt32(fields[1][(fields[1].LastIndexOf(':') + 1)..], 16).ToString(CultureInfo.InvariantCulture));
}
}
return ports;
}
private static string Uri(string queue, string query)
=> $"asb://{queue}?connectionString={AsbFaultStand.ConnectionString}" + (query.Length > 0 ? "&" + query : "");
private static RouteContext NewContext()
{
var context = new RouteContext(options: new RouteEngineOptions { ShutdownTimeout = TimeSpan.FromSeconds(5) });
context.AddComponent(new AzureServiceBusComponent());
return context;
}
private static void Collect(IExchange exchange, ConcurrentQueue into)
{
if (exchange.In.Body is List batch)
{
foreach (var message in batch)
into.Enqueue(Text(message.Body));
return;
}
into.Enqueue(Text(exchange.In.Body));
}
private static string Text(object? body) => body switch
{
byte[] bytes => Encoding.UTF8.GetString(bytes),
BinaryData data => data.ToString(),
null => "",
_ => 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;
}
}
/// An emulator stop cuts every connection of the suite, so nothing runs beside the fault tests.
[CollectionDefinition(Name, DisableParallelization = true)]
public sealed class AsbEmulatorRestartCollection
{
/// The collection's name.
public const string Name = "Service Bus emulator restart";
}
Path: redb-route/tests/redb.Route.Tests.AzureServiceBus/AsbSessionConformanceTests.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.AzureServiceBus/AsbSessionConformanceTests.cs
----
using redb.Route.Abstractions;
using redb.Route.AzureServiceBus;
using redb.Route.Tests.Conformance;
namespace redb.Route.Tests.AzureServiceBus;
///
/// The Service Bus session consumer (enableSessions=true) against , on
/// . Every message the stand and the producer put carries the session
/// . The queues are fixed in tests/docker/servicebus/Config.json:
/// queue.conformance.session, or queue.conformance.session.2 for a test that asks for two attempts (the
/// entity's MaxDeliveryCount). Not applicable here, and passing without running: the start while the broker is down
/// (as for ), concurrency (the messages of one session run one after the other) and
/// batches (a session entity is not read in batches). Runs alone and only in a fault run
/// (run-fault-suite.sh --broker servicebus).
///
[Trait("Category", "Integration")]
[Collection(AsbEmulatorRestartCollection.Name)]
public sealed class AsbSessionConformanceTests : ConnectorConformance
{
private const string Queue = "queue.conformance.session";
private const string TwoAttemptsQueue = "queue.conformance.session.2";
protected override AsbFaultStand Stand => AsbFaultStand.Instance;
protected override ConnectorTraits Traits { get; } = new()
{
AckOnReceipt = true, Transactions = true, DeadLetter = true, Concurrency = false, Batch = false, LateBroker = false,
};
protected override int BrokerPort => 5672;
protected override IComponent CreateComponent() => new AzureServiceBusComponent();
protected override Task CreateQueueAsync(bool deadLetter) => TakeAsync(Queue);
protected override Task CreateQueueAsync(bool deadLetter, int attempts) => attempts switch
{
3 => TakeAsync(Queue),
2 => TakeAsync(TwoAttemptsQueue),
_ => throw new NotSupportedException($"No queue of the stand delivers a message {attempts} times."),
};
protected override async Task DeleteQueueAsync(ConformanceQueue queue)
{
await Stand.DrainAsync(queue.Name, TimeSpan.FromMilliseconds(500));
await Stand.DrainAsync(queue.DeadLetter!, TimeSpan.FromMilliseconds(500));
}
protected override string ConsumerUri(ConformanceQueue queue, ConsumerSettings settings)
{
var uri = $"asb://{queue.Name}?connectionString={AsbFaultStand.ConnectionString}&enableSessions=true";
if (settings.AckOnReceipt)
uri += "&ackMode=auto";
return uri;
}
protected override string ProducerUri(ConformanceQueue queue, bool transacted)
=> $"asb://{queue.Name}?connectionString={AsbFaultStand.ConnectionString}&producerSessionId={AsbFaultStand.Session}"
+ (transacted ? "&transacted=true" : "");
private async Task TakeAsync(string name)
{
var queue = new ConformanceQueue(name, $"{name}/$deadletterqueue");
await DeleteQueueAsync(queue);
return queue;
}
}
Path: redb-route/tests/redb.Route.Tests.AzureServiceBus/AzureServiceBusBatchCommitTests.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.AzureServiceBus/AzureServiceBusBatchCommitTests.cs
----
using System.Collections.Concurrent;
using System.Text;
using redb.Route.Abstractions;
using redb.Route.AzureServiceBus;
using redb.Route.Core;
using redb.Route.Processors;
using redb.Route.Transactions;
namespace redb.Route.Tests.AzureServiceBus;
///
/// batchCommit=true: the sends a producer defers in a .Transacted() block leave as one Service Bus batch —
/// the entity takes it whole or not at all — and a block whose messages do not fit in one batch sends nothing. The batch
/// body no longer drops the items over its limits without a word.
///
[Trait("Category", "Integration")]
[Collection(AsbEmulatorQueue.Name)]
public sealed class AzureServiceBusBatchCommitTests
{
private const string ConnectionString =
"Endpoint=sb://localhost:5300;SharedAccessKeyName=RootManageSharedAccessKey;" +
"SharedAccessKey=SAS_KEY_VALUE;UseDevelopmentEmulator=true;";
private const string Queue = "queue.1";
private static string Tag() => Guid.NewGuid().ToString("N")[..8];
private static AzureServiceBusEndpoint CreateEndpoint(string? extraParams = null)
{
var qs = $"connectionString={ConnectionString}";
if (extraParams is not null) qs += $"&{extraParams}";
return (AzureServiceBusEndpoint)new AzureServiceBusComponent().CreateEndpoint(EndpointUriParser.Parse($"asb://{Queue}?{qs}"));
}
private static Task InTransaction(IExchange exchange, Func body) =>
new TransactedProcessor(new DelegateProcessor(body), new TransactionPolicy()).Process(exchange);
/// Everything that reaches the queue during the window, taken off it for good.
private static async Task> ReceiveFor(TimeSpan window)
{
var endpoint = CreateEndpoint("ackMode=auto&maxConcurrentCalls=10");
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 = endpoint.CreateConsumer(processor);
await consumer.Start();
await Task.Delay(window);
await consumer.Stop();
await endpoint.Stop();
return received;
}
[Fact]
public async Task The_sends_of_a_block_leave_as_one_batch()
{
var tag = Tag();
var endpoint = CreateEndpoint("batchCommit=true");
var producer = endpoint.CreateProducer();
await producer.Start();
await InTransaction(new Exchange(new Message($"{tag}-one")), async (ex, ct) =>
{
await producer.Process(ex, ct);
ex.In.Body = $"{tag}-two";
await producer.Process(ex, ct);
});
await producer.Stop();
await endpoint.Stop();
(await ReceiveFor(TimeSpan.FromSeconds(3))).Where(b => b.StartsWith(tag)).Order()
.Should().Equal($"{tag}-one", $"{tag}-two");
}
[Fact]
public async Task A_block_whose_messages_do_not_fit_in_one_batch_sends_nothing()
{
var tag = Tag();
var endpoint = CreateEndpoint("batchCommit=true&batchMaxSizeBytes=2048");
var producer = endpoint.CreateProducer();
await producer.Start();
var block = () => InTransaction(new Exchange(new Message($"{tag}-small")), async (ex, ct) =>
{
await producer.Process(ex, ct);
ex.In.Body = tag + new string('x', 3_000);
await producer.Process(ex, ct);
});
await block.Should().ThrowAsync().WithMessage("*do not fit in one Service Bus batch*");
await producer.Stop();
await endpoint.Stop();
(await ReceiveFor(TimeSpan.FromSeconds(3))).Where(b => b.StartsWith(tag))
.Should().BeEmpty("the small message is not sent without the one that did not fit");
}
[Fact]
public async Task A_list_body_over_batchMaxSizeBytes_fails_instead_of_dropping_the_rest()
{
var tag = Tag();
var endpoint = CreateEndpoint("batchMaxSizeBytes=2048");
var producer = endpoint.CreateProducer();
await producer.Start();
var big = new string('x', 1_500);
var send = () => producer.Process(new Exchange(new Message(new[] { $"{tag}-{big}", $"{tag}-{big}" })));
await send.Should().ThrowAsync().WithMessage("*do not fit in one Service Bus batch*");
await producer.Stop();
await endpoint.Stop();
(await ReceiveFor(TimeSpan.FromSeconds(3))).Where(b => b.Contains(tag)).Should().BeEmpty();
}
[Fact]
public void BatchCommit_contradicts_transacted_false()
{
var act = () => CreateEndpoint("batchCommit=true&transacted=false");
act.Should().Throw().WithMessage("*batchCommit*transacted=false*");
}
}
Path: redb-route/tests/redb.Route.Tests.AzureServiceBus/AzureServiceBusBatchOptionsTests.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.AzureServiceBus/AzureServiceBusBatchOptionsTests.cs
----
using Azure.Messaging.ServiceBus;
using redb.Route.Abstractions;
using redb.Route.AzureServiceBus;
using redb.Route.AzureServiceBus.Fluent;
using redb.Route.Core;
namespace redb.Route.Tests.AzureServiceBus;
/// The Service Bus batch options on the core contract, every start refusal of batch mode, and lock renewal.
public sealed class AzureServiceBusBatchOptionsTests
{
private const string Connection = "connectionString=Endpoint=sb://localhost;SharedAccessKeyName=k;SharedAccessKey=v";
private static AzureServiceBusEndpoint Endpoint(string query)
=> (AzureServiceBusEndpoint)new AzureServiceBusComponent().CreateEndpoint(
EndpointUriParser.Parse($"asb://orders?{Connection}&{query}"));
private static AzureServiceBusEndpointOptions Resolved(string query)
{
var options = new AzureServiceBusEndpointOptions();
options.BindFromUri(EndpointUriParser.Parse($"asb://orders?{Connection}&{query}").RawParameters);
options.ResolveBatch("asb://orders");
return options;
}
[Fact]
public void Batch_mode_is_off_by_default_and_on_with_batching()
{
Resolved("ackMode=manual").Batch.Should().BeNull();
var batch = Resolved("batching=true").Batch!;
batch.MaxMessages.Should().Be(100);
batch.PollTimeout.Should().Be(TimeSpan.FromSeconds(1));
batch.Interval.Should().BeNull();
var tuned = Resolved("batching=true&maxBatchMessages=20&pollTimeoutMs=250&batchingIntervalMs=4000").Batch!;
tuned.MaxMessages.Should().Be(20);
tuned.PollTimeout.Should().Be(TimeSpan.FromMilliseconds(250));
tuned.Interval.Should().Be(TimeSpan.FromSeconds(4));
}
[Fact]
public void Batch_mode_creates_the_batch_consumer()
=> Endpoint("batching=true").CreateConsumer(Substitute.For()).Should().BeOfType();
[Theory]
[InlineData("maxBatchMessages=10", "*sets maxBatchMessages without batching=true*")]
[InlineData("batchingIntervalMs=10", "*sets batchingIntervalMs without batching=true*")]
[InlineData("batching=true&enableSessions=true", "*batching=true cannot be combined with enableSessions=true*")]
[InlineData("batching=true&maxBatchMessages=0", "*maxBatchMessages must be at least 1*")]
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 = Asb.Queue("orders").ConnectionString("Endpoint=sb://test").Batching().MaxBatchMessages(20)
.PollTimeoutMs(250).BatchingIntervalMs(4000).Build();
uri.Should().Contain("batching=True").And.Contain("maxBatchMessages=20").And.Contain("pollTimeoutMs=250")
.And.Contain("batchingIntervalMs=4000");
}
[Fact]
public async Task The_locks_of_a_batch_are_renewed_while_the_route_runs_and_no_longer_after_it()
{
var consumer = (AzureServiceBusBatchConsumer)Endpoint("batching=true&maxAutoLockRenewalDuration=60")
.CreateConsumer(Substitute.For());
var receiver = Substitute.For();
var renewals = 0;
receiver.RenewMessageLockAsync(Arg.Any(), Arg.Any())
.Returns(_ => { Interlocked.Increment(ref renewals); return Task.CompletedTask; });
var items = new[]
{
ServiceBusModelFactory.ServiceBusReceivedMessage(messageId: "a", lockedUntil: DateTimeOffset.UtcNow.AddSeconds(2)),
ServiceBusModelFactory.ServiceBusReceivedMessage(messageId: "b", lockedUntil: DateTimeOffset.UtcNow.AddSeconds(2)),
};
var renewal = new AzureServiceBusBatchConsumer.LockRenewal(consumer, receiver, items);
await Task.Delay(2500);
var whileRunning = Volatile.Read(ref renewals);
renewal.Dispose();
await Task.Delay(2500);
whileRunning.Should().BeGreaterThanOrEqualTo(2, "every lock of the batch is renewed half-way to its end");
Volatile.Read(ref renewals).Should().Be(whileRunning, "once the route returned, nothing is renewed");
}
}
Path: redb-route/tests/redb.Route.Tests.AzureServiceBus/AzureServiceBusBatchTests.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.AzureServiceBus/AzureServiceBusBatchTests.cs
----
using System.Collections.Concurrent;
using System.Text;
using redb.Route.Abstractions;
using redb.Route.AzureServiceBus;
using redb.Route.Core;
namespace redb.Route.Tests.AzureServiceBus;
///
/// Batch mode of the Service Bus consumer against the emulator (queue.1, localhost:5300), on the core batch contract: a
/// batch closes by size or by the idle timeout, its body is a list of one message per Service Bus message, and it is
/// settled once after the route: completed on success, abandoned (delivered again) or dead-lettered on failure; a stop
/// abandons an unfinished batch.
///
[Trait("Category", "Integration")]
[Collection(AsbEmulatorQueue.Name)]
public sealed class AzureServiceBusBatchTests
{
private const string ConnectionString =
"Endpoint=sb://localhost:5300;SharedAccessKeyName=RootManageSharedAccessKey;" +
"SharedAccessKey=SAS_KEY_VALUE;UseDevelopmentEmulator=true;";
private const string Queue = "queue.1";
private static AzureServiceBusEndpoint Endpoint(string query = "")
=> (AzureServiceBusEndpoint)new AzureServiceBusComponent().CreateEndpoint(
EndpointUriParser.Parse($"asb://{Queue}?connectionString={ConnectionString}{(query.Length > 0 ? "&" + query : "")}"));
private static string Tag() => Guid.NewGuid().ToString("N")[..8];
private static async Task SendAsync(params IMessage[] messages)
{
var endpoint = Endpoint();
var producer = endpoint.CreateProducer();
await producer.Start();
await producer.Process(new Exchange(new Message(messages.ToList())));
await producer.Stop();
await endpoint.Stop();
}
private static IMessage Element(string body) => new Message(body) { Headers = { ["element"] = body } };
private static async Task DrainAsync(string query = "")
{
var endpoint = Endpoint("ackMode=auto&maxConcurrentCalls=5" + (query.Length > 0 ? "&" + query : ""));
var consumer = endpoint.CreateConsumer(Substitute.For());
await consumer.Start();
await Task.Delay(2000);
await consumer.Stop();
await endpoint.Stop();
}
/// Records each batch's messages that carry the tag; fails the calls fail picks.
private sealed class Route(string tag, Func? fail = null) : IProcessor
{
public readonly ConcurrentQueue> Batches = new();
private int _calls;
public Task Process(IExchange exchange, CancellationToken ct = default)
{
var batch = ((List)exchange.In.Body!).Where(m => Body(m).StartsWith(tag)).ToList();
if (batch.Count == 0)
return Task.CompletedTask;
Batches.Enqueue(batch);
if (fail?.Invoke(Interlocked.Increment(ref _calls), exchange) == true)
throw new InvalidOperationException("batch fails");
return Task.CompletedTask;
}
public static string Body(IMessage m) => m.Body is byte[] b ? Encoding.UTF8.GetString(b) : m.Body?.ToString() ?? "";
public int Delivered => Batches.Sum(b => b.Count);
}
private static async Task ConsumeAsync(Route route, string query, Func until, int settleMs = 1500)
{
var endpoint = Endpoint(query);
var consumer = endpoint.CreateConsumer(route);
await consumer.Start();
try
{
var deadline = DateTime.UtcNow.AddSeconds(20);
while (!until(route) && DateTime.UtcNow < deadline)
await Task.Delay(100);
await Task.Delay(settleMs);
}
finally
{
await consumer.Stop();
await endpoint.Stop();
}
return route;
}
[Fact]
public async Task A_full_batch_is_one_exchange_with_a_message_per_service_bus_message()
{
await DrainAsync();
var tag = Tag();
await SendAsync(Enumerable.Range(0, 5).Select(i => Element($"{tag}-{i}")).ToArray());
var route = await ConsumeAsync(new Route(tag), "batching=true&maxBatchMessages=5&pollTimeoutMs=3000", r => r.Delivered >= 5);
route.Batches.SelectMany(b => b).Select(Route.Body).Should().BeEquivalentTo(Enumerable.Range(0, 5).Select(i => $"{tag}-{i}"));
route.Batches.SelectMany(b => b).Should().OnlyContain(m => (string)m.Headers["element"]! == Route.Body(m)
&& m.Headers.ContainsKey(AzureServiceBusHeaders.MessageId));
route.Batches.Should().HaveCountLessThanOrEqualTo(2, "five messages fill one batch, at most two receives apart");
}
[Fact]
public async Task One_message_is_a_list_of_one_after_the_idle_timeout()
{
await DrainAsync();
var tag = Tag();
await SendAsync(Element($"{tag}-only"));
var route = await ConsumeAsync(new Route(tag), "batching=true&maxBatchMessages=10&pollTimeoutMs=500", r => r.Delivered >= 1);
route.Batches.Should().ContainSingle().Which.Select(Route.Body).Should().Equal($"{tag}-only");
}
[Fact]
public async Task A_failed_batch_is_abandoned_and_delivered_again()
{
await DrainAsync();
var tag = Tag();
await SendAsync(Element($"{tag}-x"), Element($"{tag}-y"));
var route = await ConsumeAsync(new Route(tag, (call, _) => call == 1),
"batching=true&maxBatchMessages=2&pollTimeoutMs=2000", r => r.Delivered >= 4);
var delivered = route.Batches.SelectMany(b => b).ToList();
delivered.Select(Route.Body).Should().BeEquivalentTo([$"{tag}-x", $"{tag}-y", $"{tag}-x", $"{tag}-y"],
"the abandoned messages come again and are completed the second time");
delivered.Max(m => Convert.ToInt32(m.Headers[AzureServiceBusHeaders.DeliveryCount])).Should().BeGreaterThanOrEqualTo(2);
}
[Fact]
public async Task With_autoDeadLetter_a_failed_batch_goes_to_the_dead_letter_subqueue()
{
await DrainAsync();
await DrainAsync("subQueue=deadletter");
var tag = Tag();
await SendAsync(Element($"{tag}-d1"), Element($"{tag}-d2"));
var failed = await ConsumeAsync(new Route(tag, (_, _) => true),
"batching=true&maxBatchMessages=2&pollTimeoutMs=2000&autoDeadLetter=true&deadLetterReason=batch-failed",
r => r.Delivered >= 2);
failed.Delivered.Should().Be(2, "a dead-lettered message does not come back");
var dead = await ConsumeAsync(new Route(tag), "subQueue=deadletter&batching=true&maxBatchMessages=10&pollTimeoutMs=2000",
r => r.Delivered >= 2);
dead.Batches.SelectMany(b => b).Select(Route.Body).Should().BeEquivalentTo($"{tag}-d1", $"{tag}-d2");
dead.Batches.SelectMany(b => b).Should().OnlyContain(m => (string)m.Headers[AzureServiceBusHeaders.DeadLetterReason]! == "batch-failed");
}
[Fact]
public async Task A_rolled_back_batch_is_abandoned_even_with_autoDeadLetter()
{
await DrainAsync();
var tag = Tag();
await SendAsync(Element($"{tag}-r"));
var route = await ConsumeAsync(new Route(tag, (call, exchange) =>
{
if (call == 1) exchange.MarkRollbackOnly();
return false;
}),
"batching=true&maxBatchMessages=1&pollTimeoutMs=1000&autoDeadLetter=true", r => r.Batches.Count >= 2);
route.Batches.Should().HaveCount(2, "a rollback is delivered again, not dead-lettered");
}
[Fact]
public async Task A_stop_abandons_the_unfinished_batch()
{
await DrainAsync();
var tag = Tag();
await SendAsync(Element($"{tag}-p"), Element($"{tag}-q"));
var first = new Route(tag);
var endpoint = Endpoint("batching=true&maxBatchMessages=10&pollTimeoutMs=10000");
var consumer = endpoint.CreateConsumer(first);
await consumer.Start();
await Task.Delay(3000);
await consumer.Stop();
await endpoint.Stop();
first.Batches.Should().BeEmpty("an interrupted batch is not run");
var again = await ConsumeAsync(new Route(tag), "batching=true&maxBatchMessages=2&pollTimeoutMs=2000", r => r.Delivered >= 2);
again.Batches.SelectMany(b => b).Select(Route.Body).Should().BeEquivalentTo($"{tag}-p", $"{tag}-q");
}
[Fact]
public async Task With_ackMode_auto_a_failed_batch_is_not_delivered_again()
{
await DrainAsync();
var tag = Tag();
await SendAsync(Element($"{tag}-g"), Element($"{tag}-h"));
var route = await ConsumeAsync(new Route(tag, (_, _) => true),
"batching=true&maxBatchMessages=2&pollTimeoutMs=2000&ackMode=auto", r => r.Delivered >= 2, settleMs: 3000);
route.Delivered.Should().Be(2, "ReceiveAndDelete: the messages are gone on receipt");
}
}
Path: redb-route/tests/redb.Route.Tests.AzureServiceBus/AzureServiceBusComponentTests.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.AzureServiceBus/AzureServiceBusComponentTests.cs
----
using redb.Route.Abstractions;
using redb.Route.AzureServiceBus;
using redb.Route.Core;
namespace redb.Route.Tests.AzureServiceBus;
public sealed class AzureServiceBusComponentTests
{
[Fact]
public void Scheme_IsAsb()
{
var component = new AzureServiceBusComponent();
component.Scheme.Should().Be("asb");
}
[Fact]
public void CreateEndpoint_WithValidOptions_ReturnsEndpoint()
{
var component = new AzureServiceBusComponent();
var uri = EndpointUriParser.Parse("asb://test-queue?connectionString=Endpoint=sb://test");
var endpoint = component.CreateEndpoint(uri);
endpoint.Should().NotBeNull();
endpoint.Uri.Should().Be(uri);
endpoint.Component.Should().Be(component);
}
[Fact]
public void CreateEndpoint_MissingConnectionString_Throws()
{
var component = new AzureServiceBusComponent();
var uri = EndpointUriParser.Parse("asb://test-queue");
var act = () => component.CreateEndpoint(uri);
act.Should().Throw();
}
[Fact]
public void CreateEndpoint_NullUri_Throws()
{
var component = new AzureServiceBusComponent();
var act = () => component.CreateEndpoint(null!);
act.Should().Throw();
}
[Fact]
public void CreateProducer_ReturnsProducer()
{
var component = new AzureServiceBusComponent();
var uri = EndpointUriParser.Parse("asb://test-queue?connectionString=Endpoint=sb://test");
var endpoint = component.CreateEndpoint(uri);
var producer = endpoint.CreateProducer();
producer.Should().NotBeNull();
}
[Fact]
public void CreateConsumer_ReturnsConsumer()
{
var component = new AzureServiceBusComponent();
var uri = EndpointUriParser.Parse("asb://test-queue?connectionString=Endpoint=sb://test");
var endpoint = component.CreateEndpoint(uri);
var processor = Substitute.For();
var consumer = endpoint.CreateConsumer(processor);
consumer.Should().NotBeNull();
}
[Fact]
public void CreateConsumer_WithSessions_ReturnsSessionConsumer()
{
var component = new AzureServiceBusComponent();
var uri = EndpointUriParser.Parse("asb://test-queue?connectionString=Endpoint=sb://test&enableSessions=true");
var endpoint = component.CreateEndpoint(uri);
var processor = Substitute.For();
var consumer = endpoint.CreateConsumer(processor);
consumer.Should().NotBeNull();
consumer.GetType().Name.Should().Contain("Session");
}
[Fact]
public void CreateEndpoint_WithSubscription_IsTopic()
{
var component = new AzureServiceBusComponent();
var uri = EndpointUriParser.Parse("asb://my-topic?connectionString=Endpoint=sb://test&subscriptionName=my-sub");
var endpoint = component.CreateEndpoint(uri);
// Verify the endpoint was created (internal IsTopic not directly accessible but the factory pattern works)
endpoint.Should().NotBeNull();
}
}
Path: redb-route/tests/redb.Route.Tests.AzureServiceBus/AzureServiceBusConnectionWatchTests.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.AzureServiceBus/AzureServiceBusConnectionWatchTests.cs
----
using System.Net.Sockets;
using Azure.Messaging.ServiceBus;
using redb.Route.Abstractions;
using redb.Route.AzureServiceBus;
using redb.Route.Core;
namespace redb.Route.Tests.AzureServiceBus;
///
/// What a Service Bus consumer hands its connection supervisor: only errors of the connection (a lost connection shows in
/// health and is not counted as a failed message); a receive brings the connection back; a probe, the dead-letter peek,
/// brings it back on an idle entity and ends with the consumer's stop. Driven by a fake .
///
public sealed class AzureServiceBusConnectionWatchTests
{
private static (AzureServiceBusEndpoint Endpoint, ServiceBusClient Client, ServiceBusReceiver Receiver) Endpoint()
{
var client = Substitute.For();
var receiver = Substitute.For();
client.CreateReceiver(Arg.Any(), Arg.Any()).Returns(receiver);
var endpoint = (AzureServiceBusEndpoint)new AzureServiceBusComponent().CreateEndpoint(
EndpointUriParser.Parse("asb://orders?connectionString=Endpoint=sb://test"));
endpoint.ClientSource = () => client;
return (endpoint, client, receiver);
}
private static ServiceBusException Lost() =>
new("the connection was closed", ServiceBusFailureReason.ServiceCommunicationProblem);
public static TheoryData Errors() => new()
{
{ Lost(), true },
{ new InvalidOperationException("receive failed", new IOException("reset", new SocketException(10054))), true },
{ new ServiceBusException("no such queue", ServiceBusFailureReason.MessagingEntityNotFound), false },
{ new ServiceBusException("timed out", ServiceBusFailureReason.ServiceTimeout), false },
{ new UnauthorizedAccessException("claim Listen is missing"), false },
{ new InvalidOperationException("the route failed"), false },
};
[Theory]
[MemberData(nameof(Errors))]
public void Only_an_error_of_the_connection_is_the_supervisors(Exception error, bool connection)
=> AzureServiceBusConnectionWatch.IsConnectionError(error).Should().Be(connection);
[Fact]
public void A_lost_connection_shows_in_health_without_an_error_and_a_receive_brings_it_back()
{
var (endpoint, client, _) = Endpoint();
var watch = new AzureServiceBusConnectionWatch(endpoint, client, null, null, probe: false);
var statistics = (IEndpointStatistics)endpoint;
watch.Report(Lost()).Should().BeTrue();
statistics.HealthStatus.Should().NotBe(EndpointHealthStatus.Healthy);
statistics.HealthReason.Should().Contain("connection lost");
statistics.Errors.Should().Be(0, "a lost connection is not a failed message");
watch.Report(Lost()).Should().BeTrue();
watch.Supervisor.State.Should().Be(ConnectionState.Disconnected,
"without a probe the client's own failed receive is the failed attempt");
statistics.HealthStatus.Should().Be(EndpointHealthStatus.Critical);
watch.Traffic();
watch.Supervisor.State.Should().Be(ConnectionState.Connected);
statistics.Reconnects.Should().Be(1);
statistics.HealthStatus.Should().Be(EndpointHealthStatus.Healthy);
watch.Stop();
}
[Fact]
public void An_error_that_is_not_the_connections_is_left_to_the_consumer()
{
var (endpoint, client, _) = Endpoint();
var watch = new AzureServiceBusConnectionWatch(endpoint, client, null, null, probe: true);
watch.Report(new ServiceBusException("no such queue", ServiceBusFailureReason.MessagingEntityNotFound))
.Should().BeFalse("the consumer records it on the endpoint: it is not a connection being retried");
watch.Supervisor.State.Should().Be(ConnectionState.Connected);
watch.Stop();
}
[Fact]
public void A_lost_session_lock_is_neither_a_failed_message_nor_a_lost_connection()
{
var (endpoint, client, _) = Endpoint();
var watch = new AzureServiceBusConnectionWatch(endpoint, client, null, null, probe: true);
watch.Report(new ServiceBusException("session lock lost", ServiceBusFailureReason.SessionLockLost)).Should().BeTrue(
"the session processor accepts a session again by itself");
watch.Supervisor.State.Should().Be(ConnectionState.Connected);
((IEndpointStatistics)endpoint).Errors.Should().Be(0);
watch.Stop();
}
[Fact]
public void While_the_connection_is_lost_any_error_of_a_receive_is_the_losss_reason()
{
var (endpoint, client, _) = Endpoint();
var watch = new AzureServiceBusConnectionWatch(endpoint, client, null, null, probe: false);
var statistics = (IEndpointStatistics)endpoint;
watch.Report(Lost());
watch.Report(new ServiceBusException("session lock lost", ServiceBusFailureReason.SessionLockLost)).Should().BeTrue();
watch.Report(new ServiceBusException("no such queue", ServiceBusFailureReason.MessagingEntityNotFound)).Should().BeTrue(
"a namespace coming back may refuse the entity for a moment");
statistics.Errors.Should().Be(0);
statistics.HealthReason.Should().Contain("no such queue", "the last failure is the reason health shows");
watch.Traffic();
watch.Report(new ServiceBusException("no such queue", ServiceBusFailureReason.MessagingEntityNotFound)).Should().BeFalse(
"connected again: a missing entity is the consumer's error to record");
watch.Stop();
}
[Fact]
public async Task On_an_idle_entity_the_dead_letter_peek_brings_the_connection_back()
{
var (endpoint, client, receiver) = Endpoint();
var watch = new AzureServiceBusConnectionWatch(endpoint, client, null, null, probe: true);
watch.Report(Lost());
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(10);
while (watch.Supervisor.State != ConnectionState.Connected && DateTime.UtcNow < deadline)
await Task.Delay(50);
watch.Supervisor.State.Should().Be(ConnectionState.Connected, "the peek answered");
((IEndpointStatistics)endpoint).Reconnects.Should().Be(1);
client.Received().CreateReceiver("orders",
Arg.Is(o => o.SubQueue == SubQueue.DeadLetter && o.ReceiveMode == ServiceBusReceiveMode.PeekLock));
await receiver.Received().PeekMessageAsync(Arg.Any(), Arg.Any());
watch.Stop();
}
[Fact]
public async Task A_stop_ends_a_probe_that_hangs()
{
var (endpoint, client, receiver) = Endpoint();
var peeking = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
receiver.PeekMessageAsync(Arg.Any(), Arg.Any()).Returns(async call =>
{
peeking.TrySetResult();
await Task.Delay(Timeout.Infinite, call.ArgAt(1));
return (ServiceBusReceivedMessage?)null;
});
var watch = new AzureServiceBusConnectionWatch(endpoint, client, null, null, probe: true);
watch.Report(Lost());
await peeking.Task.WaitAsync(TimeSpan.FromSeconds(10));
watch.Stop();
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(5);
while (receiver.ReceivedCalls().All(c => c.GetMethodInfo().Name != nameof(ServiceBusReceiver.DisposeAsync))
&& DateTime.UtcNow < deadline)
await Task.Delay(50);
await receiver.Received().DisposeAsync();
watch.Supervisor.State.Should().NotBe(ConnectionState.Connected, "nothing answered; the stop ended the probe");
}
}
Path: redb-route/tests/redb.Route.Tests.AzureServiceBus/AzureServiceBusDslTests.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.AzureServiceBus/AzureServiceBusDslTests.cs
----
using redb.Route.Core;
using redb.Route.AzureServiceBus;
using redb.Route.AzureServiceBus.Fluent;
namespace redb.Route.Tests.AzureServiceBus;
public sealed class AzureServiceBusDslTests
{
[Fact]
public void Queue_BuildsCorrectUri()
{
var uri = Asb.Queue("orders")
.ConnectionString("Endpoint=sb://test")
.Build();
uri.Should().StartWith("asb://orders?");
uri.Should().Contain("connectionString=");
}
[Fact]
public void Topic_BuildsCorrectUri()
{
var uri = Asb.Topic("events", "my-sub")
.ConnectionString("Endpoint=sb://test")
.Build();
uri.Should().StartWith("asb://events?");
uri.Should().Contain("subscriptionName=my-sub");
uri.Should().Contain("connectionString=");
}
[Fact]
public void Queue_WithSessions_BuildsCorrectUri()
{
var uri = Asb.Queue("orders")
.ConnectionString("Endpoint=sb://test")
.EnableSessions()
.SessionId("session-1")
.MaxConcurrentSessions(3)
.Build();
uri.Should().Contain("enableSessions=True");
uri.Should().Contain("sessionId=session-1");
uri.Should().Contain("maxConcurrentSessions=3");
}
[Fact]
public void Queue_WithConsumerOptions_BuildsCorrectUri()
{
var uri = Asb.Queue("orders")
.ConnectionString("Endpoint=sb://test")
.AckMode(AckMode.Auto)
.MaxConcurrentCalls(5)
.PrefetchCount(10)
.Build();
uri.Should().Contain("ackMode=auto");
uri.Should().Contain("maxConcurrentCalls=5");
uri.Should().Contain("prefetchCount=10");
}
[Fact]
public void Queue_WithProducerOptions_BuildsCorrectUri()
{
var uri = Asb.Queue("orders")
.ConnectionString("Endpoint=sb://test")
.ScheduleDelaySeconds(30)
.TimeToLive("00:05:00")
.Build();
uri.Should().Contain("scheduleDelaySeconds=30");
uri.Should().Contain("timeToLive=00%3A05%3A00");
}
[Fact]
public void Queue_WithDeadLetter_BuildsCorrectUri()
{
var uri = Asb.Queue("orders")
.ConnectionString("Endpoint=sb://test")
.SubQueue("deadletter")
.Build();
uri.Should().Contain("subQueue=deadletter");
}
[Fact]
public void Queue_WithTransacted_BuildsCorrectUri()
{
var uri = Asb.Queue("orders")
.ConnectionString("Endpoint=sb://test")
.Transacted()
.Build();
uri.Should().Contain("transacted=True");
}
[Fact]
public void Queue_WithAutoDeadLetter_BuildsCorrectUri()
{
var uri = Asb.Queue("orders")
.ConnectionString("Endpoint=sb://test")
.AutoDeadLetter()
.DeadLetterReason("test-reason")
.Build();
uri.Should().Contain("autoDeadLetter=True");
uri.Should().Contain("deadLetterReason=test-reason");
}
[Fact]
public void Queue_Minimal_NoQueryString()
{
var uri = Asb.Queue("orders").Build();
uri.Should().Be("asb://orders");
}
[Fact]
public void ImplicitStringConversion_Works()
{
string uri = Asb.Queue("test-q").ConnectionString("Endpoint=sb://x");
uri.Should().StartWith("asb://test-q?");
}
[Fact]
public void ToString_ReturnsBuild()
{
var builder = Asb.Queue("test-q").ConnectionString("Endpoint=sb://x");
builder.ToString().Should().Be(builder.Build());
}
[Fact]
public void ConnectionFactory_BuildsCorrectUri()
{
var uri = Asb.Queue("orders")
.ConnectionFactory("myFactory")
.Build();
uri.Should().Contain("connectionFactory=myFactory");
}
[Fact]
public void RetryOptions_BuildCorrectUri()
{
var uri = Asb.Queue("orders")
.ConnectionString("Endpoint=sb://test")
.RetryMaxRetries(5)
.RetryMode("Fixed")
.Build();
uri.Should().Contain("retryMaxRetries=5");
uri.Should().Contain("retryMode=Fixed");
}
}
Path: redb-route/tests/redb.Route.Tests.AzureServiceBus/AzureServiceBusEndpointOptionsTests.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.AzureServiceBus/AzureServiceBusEndpointOptionsTests.cs
----
using redb.Route.Core;
using Azure.Messaging.ServiceBus;
using redb.Route.AzureServiceBus;
namespace redb.Route.Tests.AzureServiceBus;
public sealed class AzureServiceBusEndpointOptionsTests
{
// ── Validate ──
[Fact]
public void Validate_MissingConnectionStringAndFactory_Throws()
{
var options = new AzureServiceBusEndpointOptions();
var act = () => options.Validate();
act.Should().Throw()
.WithParameterName("ConnectionString");
}
[Fact]
public void Validate_ConnectionString_IsValid()
{
var options = new AzureServiceBusEndpointOptions { ConnectionString = "Endpoint=sb://test" };
var act = () => options.Validate();
act.Should().NotThrow();
}
[Fact]
public void Validate_ConnectionFactory_AllowsMissingConnectionString()
{
var options = new AzureServiceBusEndpointOptions { ConnectionFactory = "myFactory" };
var act = () => options.Validate();
act.Should().NotThrow();
}
[Fact]
public void Validate_MaxConcurrentCallsZero_Throws()
{
var options = new AzureServiceBusEndpointOptions
{
ConnectionString = "Endpoint=sb://test",
MaxConcurrentCalls = "0"
};
var act = () => options.Validate();
act.Should().Throw().WithMessage("*maxConcurrentCalls*");
}
[Fact]
public void Validate_NegativePrefetchCount_Throws()
{
var options = new AzureServiceBusEndpointOptions
{
ConnectionString = "Endpoint=sb://test",
PrefetchCount = -1
};
var act = () => options.Validate();
act.Should().Throw()
.WithParameterName("PrefetchCount");
}
[Fact]
public void Bind_InvalidAckMode_Throws()
{
var options = new AzureServiceBusEndpointOptions();
var act = () => options.BindFromUri(new Dictionary { ["ackMode"] = "Invalid" });
act.Should().Throw().WithMessage("*ackMode=manual*ackMode=auto*");
}
[Fact]
public void Validate_InvalidSubQueue_Throws()
{
var options = new AzureServiceBusEndpointOptions
{
ConnectionString = "Endpoint=sb://test",
SubQueue = "invalid"
};
var act = () => options.Validate();
act.Should().Throw()
.WithParameterName("SubQueue");
}
[Fact]
public void Validate_MaxConcurrentSessionsZero_Throws()
{
var options = new AzureServiceBusEndpointOptions
{
ConnectionString = "Endpoint=sb://test",
MaxConcurrentSessions = 0
};
var act = () => options.Validate();
act.Should().Throw()
.WithParameterName("MaxConcurrentSessions");
}
[Fact]
public void Validate_InvalidRetryMode_Throws()
{
var options = new AzureServiceBusEndpointOptions
{
ConnectionString = "Endpoint=sb://test",
RetryMode = "invalid"
};
var act = () => options.Validate();
act.Should().Throw()
.WithParameterName("RetryMode");
}
// ── BindFromUri ──
[Fact]
public void BindFromUri_AllProperties_Bound()
{
var options = new AzureServiceBusEndpointOptions();
var parameters = new Dictionary
{
["connectionString"] = "Endpoint=sb://test",
["subscriptionName"] = "sub1",
["ackMode"] = "auto",
["maxConcurrentCalls"] = "5",
["prefetchCount"] = "10",
["maxAutoLockRenewalDuration"] = "600",
["subQueue"] = "deadletter",
["enableSessions"] = "true",
["sessionId"] = "session-1",
["maxConcurrentSessions"] = "3",
["sessionIdleTimeout"] = "120",
["autoDeadLetter"] = "true",
["deadLetterReason"] = "test-reason",
["transacted"] = "true",
["partitionKey"] = "pk-1",
["scheduleDelaySeconds"] = "30",
["timeToLive"] = "00:05:00",
["batchMaxSizeBytes"] = "512000",
["retryMaxRetries"] = "5",
["retryDelayMs"] = "1000",
["retryMaxDelayMs"] = "30000",
["retryMode"] = "Fixed"
};
options.BindFromUri(parameters);
options.ConnectionString.Should().Be("Endpoint=sb://test");
options.SubscriptionName.Should().Be("sub1");
options.AckMode.Should().Be(AckMode.Auto);
options.ResolvedMaxConcurrentCalls.Should().Be(5);
options.PrefetchCount.Should().Be(10);
options.MaxAutoLockRenewalDuration.Should().Be(600);
options.SubQueue.Should().Be("deadletter");
options.EnableSessions.Should().BeTrue();
options.SessionId.Should().Be("session-1");
options.MaxConcurrentSessions.Should().Be(3);
options.SessionIdleTimeout.Should().Be(120);
options.AutoDeadLetter.Should().BeTrue();
options.DeadLetterReason.Should().Be("test-reason");
options.Transacted.Should().BeTrue();
options.PartitionKey.Should().Be("pk-1");
options.ScheduleDelaySeconds.Should().Be(30);
options.TimeToLive.Should().Be("00:05:00");
options.BatchMaxSizeBytes.Should().Be(512000);
options.RetryMaxRetries.Should().Be(5);
options.RetryDelayMs.Should().Be(1000);
options.RetryMaxDelayMs.Should().Be(30000);
options.RetryMode.Should().Be("Fixed");
}
[Fact]
public void BindFromUri_DefaultValues()
{
var options = new AzureServiceBusEndpointOptions();
options.AckMode.Should().Be(AckMode.Manual);
options.ResolvedMaxConcurrentCalls.Should().Be(1);
options.PrefetchCount.Should().Be(0);
options.MaxAutoLockRenewalDuration.Should().Be(300);
options.EnableSessions.Should().BeFalse();
options.MaxConcurrentSessions.Should().Be(1);
options.AutoDeadLetter.Should().BeFalse();
options.Transacted.Should().BeNull("unset, a producer follows the enclosing .Transacted() block");
options.BatchMaxSizeBytes.Should().Be(256 * 1024);
options.RetryMaxRetries.Should().Be(3);
options.RetryDelayMs.Should().Be(800);
options.RetryMaxDelayMs.Should().Be(60_000);
options.RetryMode.Should().Be("Exponential");
}
// ── Parsed helpers ──
[Fact]
public void ParsedReceiveMode_PeekLock()
{
var options = new AzureServiceBusEndpointOptions { AckMode = AckMode.Manual };
options.ParsedReceiveMode.Should().Be(ServiceBusReceiveMode.PeekLock);
}
[Fact]
public void ParsedReceiveMode_ReceiveAndDelete()
{
var options = new AzureServiceBusEndpointOptions { AckMode = AckMode.Auto };
options.ParsedReceiveMode.Should().Be(ServiceBusReceiveMode.ReceiveAndDelete);
}
[Fact]
public void ParsedReceiveMode_CaseInsensitive()
{
var options = new AzureServiceBusEndpointOptions();
options.BindFromUri(new Dictionary { ["ackMode"] = "AUTO" });
options.ParsedReceiveMode.Should().Be(ServiceBusReceiveMode.ReceiveAndDelete);
}
[Fact]
public void ParsedSubQueue_DeadLetter()
{
var options = new AzureServiceBusEndpointOptions { SubQueue = "deadletter" };
options.ParsedSubQueue.Should().Be(SubQueue.DeadLetter);
}
[Fact]
public void ParsedSubQueue_TransferDeadLetter()
{
var options = new AzureServiceBusEndpointOptions { SubQueue = "transferdeadletter" };
options.ParsedSubQueue.Should().Be(SubQueue.TransferDeadLetter);
}
[Fact]
public void ParsedSubQueue_Null_WhenNotSet()
{
var options = new AzureServiceBusEndpointOptions();
options.ParsedSubQueue.Should().BeNull();
}
[Fact]
public void ParsedRetryMode_Exponential()
{
var options = new AzureServiceBusEndpointOptions { RetryMode = "Exponential" };
options.ParsedRetryMode.Should().Be(ServiceBusRetryMode.Exponential);
}
[Fact]
public void ParsedRetryMode_Fixed()
{
var options = new AzureServiceBusEndpointOptions { RetryMode = "Fixed" };
options.ParsedRetryMode.Should().Be(ServiceBusRetryMode.Fixed);
}
[Fact]
public void ParsedRetryMode_CaseInsensitive()
{
var options = new AzureServiceBusEndpointOptions { RetryMode = "fixed" };
options.ParsedRetryMode.Should().Be(ServiceBusRetryMode.Fixed);
}
[Theory]
[InlineData("enableBatch")]
[InlineData("batchMaxMessages")]
public void The_removed_list_options_are_refused_naming_what_took_their_place(string name)
{
var options = new AzureServiceBusEndpointOptions();
var act = () => options.BindFromUri(new Dictionary { ["connectionString"] = "Endpoint=sb://test", [name] = "1" });
act.Should().Throw().WithMessage($"*'{name}' is gone: any list body is sent as one Service Bus batch*");
}
}
Path: redb-route/tests/redb.Route.Tests.AzureServiceBus/AzureServiceBusFailedStartTests.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.AzureServiceBus/AzureServiceBusFailedStartTests.cs
----
using Azure.Messaging.ServiceBus;
using redb.Route.Abstractions;
using redb.Route.AzureServiceBus;
using redb.Route.Core;
namespace redb.Route.Tests.AzureServiceBus;
///
/// A consumer whose processor refuses to start lets that processor go: it is disposed, and a later start creates one new
/// processor instead of a second beside a half-started one. Driven by a fake through the
/// endpoint's ClientSource, no namespace needed.
///
public sealed class AzureServiceBusFailedStartTests
{
private static (AzureServiceBusEndpoint Endpoint, List Processors) Endpoint(bool firstStartFails)
{
var processors = new List();
var client = Substitute.For();
client.CreateProcessor(Arg.Any(), Arg.Any()).Returns(_ =>
{
var processor = Substitute.For();
processor.StartProcessingAsync(Arg.Any()).Returns(
firstStartFails && processors.Count == 0
? Task.FromException(new ServiceBusException("entity not found", ServiceBusFailureReason.MessagingEntityNotFound))
: Task.CompletedTask);
processors.Add(processor);
return processor;
});
var endpoint = (AzureServiceBusEndpoint)new AzureServiceBusComponent().CreateEndpoint(
EndpointUriParser.Parse("asb://orders?connectionString=Endpoint=sb://test"));
endpoint.ClientSource = () => client;
return (endpoint, processors);
}
[Fact]
public async Task A_processor_that_fails_to_start_is_disposed_and_the_next_start_creates_one()
{
var (endpoint, processors) = Endpoint(firstStartFails: true);
var consumer = endpoint.CreateConsumer(Substitute.For());
var first = () => consumer.Start();
await first.Should().ThrowAsync();
processors.Should().ContainSingle();
await processors[0].Received(1).DisposeAsync();
await consumer.Start();
processors.Should().HaveCount(2, "the second start creates one new processor");
await processors[1].Received(1).StartProcessingAsync(Arg.Any());
await processors[1].DidNotReceive().DisposeAsync();
}
}
Path: redb-route/tests/redb.Route.Tests.AzureServiceBus/AzureServiceBusHeaderFilterStrategyTests.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.AzureServiceBus/AzureServiceBusHeaderFilterStrategyTests.cs
----
using System.Text;
using redb.Route.Abstractions;
using redb.Route.AzureServiceBus;
using redb.Route.Core;
namespace redb.Route.Tests.AzureServiceBus;
///
/// headerFilterStrategy=#name on Azure Service Bus endpoints: on a producer it decides which exchange headers go
/// out as application properties, on a consumer which application properties come in. The consumer's redbAsb.*
/// metadata is set whatever the strategy says.
///
[Trait("Category", "Integration")]
[Collection(AsbEmulatorQueue.Name)]
public sealed class AzureServiceBusHeaderFilterStrategyTests
{
private const string ConnectionString =
"Endpoint=sb://localhost:5300;SharedAccessKeyName=RootManageSharedAccessKey;" +
"SharedAccessKey=SAS_KEY_VALUE;UseDevelopmentEmulator=true;";
private const string Uri = $"asb://queue.1?connectionString={ConnectionString}";
private static async Task> RoundTrip(string producerOptions, string consumerOptions)
{
var tag = $"hdr-strategy-{Guid.NewGuid():N}";
var received = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
await using var ctx = new RouteContext();
ctx.AddComponent(new AzureServiceBusComponent());
ctx.AddToRegistry("correlationOnly", new DefaultHeaderFilterStrategy { OutFilter = ["Correlation-ID"], FilterOnMatch = false });
ctx.AddToRegistry("noSecrets", new DefaultHeaderFilterStrategy { InFilter = ["Authorization"] });
// The emulator's queue is shared by the tests of this collection: only this test's message is taken.
ctx.AddRoutes(r => r.From(Uri + "&ackMode=auto" + consumerOptions).Process(e =>
{
if (e.In.Body is byte[] body && Encoding.UTF8.GetString(body) == tag)
received.TrySetResult(e);
}));
await ctx.Start();
var exchange = new Exchange(new Message(tag));
exchange.In.Headers["Correlation-ID"] = "c-42";
exchange.In.Headers["X-Corr"] = "c1";
exchange.In.Headers["Authorization"] = "Bearer secret";
var producer = ctx.GetEndpoint(Uri + producerOptions).CreateProducer();
await producer.Start();
await producer.Process(exchange);
await producer.Stop();
return new Dictionary((await received.Task.WaitAsync(TimeSpan.FromSeconds(30))).In.Headers);
}
[Fact]
public async Task OnAProducer_AWhitelistSendsOnlyTheNamedHeader()
{
var headers = await RoundTrip("&headerFilterStrategy=#correlationOnly", "");
headers["Correlation-ID"].Should().Be("c-42");
headers.Should().NotContainKey("X-Corr");
headers.Should().NotContainKey("Authorization");
headers.Should().ContainKey(AzureServiceBusHeaders.SequenceNumber,
"the consumer's own metadata is set whatever the strategy says");
}
[Fact]
public async Task OnAConsumer_TheStrategyDecidesWhatComesIn()
{
var headers = await RoundTrip("", "&headerFilterStrategy=#noSecrets");
headers["X-Corr"].Should().Be("c1");
headers.Should().NotContainKey("Authorization", "the consumer's strategy drops it on the way in");
}
}
Path: redb-route/tests/redb.Route.Tests.AzureServiceBus/AzureServiceBusHeaderMappingCharacterizationTests.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.AzureServiceBus/AzureServiceBusHeaderMappingCharacterizationTests.cs
----
using System.Text;
using redb.Route.Abstractions;
using redb.Route.AzureServiceBus;
using redb.Route.Core;
namespace redb.Route.Tests.AzureServiceBus;
///
/// What crosses an Azure Service Bus message today, producer to consumer: pinned before the header filter strategy
/// takes the rule over, so the transport's default keeps it exactly.
/// The producer sends every exchange header but its own redbAsb.* and null values as application properties,
/// with their own types; the consumer takes every application property back.
///
[Trait("Category", "Integration")]
[Collection(AsbEmulatorQueue.Name)]
public sealed class AzureServiceBusHeaderMappingCharacterizationTests
{
private const string ConnectionString =
"Endpoint=sb://localhost:5300;SharedAccessKeyName=RootManageSharedAccessKey;" +
"SharedAccessKey=SAS_KEY_VALUE;UseDevelopmentEmulator=true;";
private const string Uri = $"asb://queue.1?connectionString={ConnectionString}";
[Fact]
public async Task ProducerToConsumer_TheHeadersThatCrossTheMessage()
{
var tag = $"hdr-char-{Guid.NewGuid():N}";
var received = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
await using var ctx = new RouteContext();
ctx.AddComponent(new AzureServiceBusComponent());
// The emulator's queue is shared by the tests of this collection: only this test's message is taken.
ctx.AddRoutes(r => r.From(Uri + "&ackMode=auto").Process(e =>
{
if (e.In.Body is byte[] body && Encoding.UTF8.GetString(body) == tag)
received.TrySetResult(e);
}));
await ctx.Start();
var exchange = new Exchange(new Message(tag));
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[AzureServiceBusHeaders.Prefix + "Custom"] = "own";
var producer = ctx.GetEndpoint(Uri).CreateProducer();
await producer.Start();
await producer.Process(exchange);
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, "an application property keeps its type");
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(AzureServiceBusHeaders.Prefix + "Custom", "the producer keeps its own redbAsb.* back");
}
}
Path: redb-route/tests/redb.Route.Tests.AzureServiceBus/AzureServiceBusHeadersTests.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.AzureServiceBus/AzureServiceBusHeadersTests.cs
----
using redb.Route.AzureServiceBus;
namespace redb.Route.Tests.AzureServiceBus;
public sealed class AzureServiceBusHeadersTests
{
[Theory]
[InlineData(AzureServiceBusHeaders.MessageId)]
[InlineData(AzureServiceBusHeaders.CorrelationId)]
[InlineData(AzureServiceBusHeaders.SessionId)]
[InlineData(AzureServiceBusHeaders.PartitionKey)]
[InlineData(AzureServiceBusHeaders.Subject)]
[InlineData(AzureServiceBusHeaders.ContentType)]
[InlineData(AzureServiceBusHeaders.ReplyTo)]
[InlineData(AzureServiceBusHeaders.DeliveryCount)]
[InlineData(AzureServiceBusHeaders.EnqueuedTime)]
[InlineData(AzureServiceBusHeaders.SequenceNumber)]
[InlineData(AzureServiceBusHeaders.DeadLetterSource)]
[InlineData(AzureServiceBusHeaders.SessionState)]
[InlineData(AzureServiceBusHeaders.BatchMessageCount)]
public void AllHeaders_HaveCorrectPrefix(string headerKey)
{
headerKey.Should().StartWith(AzureServiceBusHeaders.Prefix);
}
[Theory]
[InlineData("redbAsb.MessageId", true)]
[InlineData("redbAsb.CustomHeader", true)]
[InlineData("SomeOtherHeader", false)]
[InlineData("redbEs.Index", false)]
[InlineData("", false)]
public void IsAsbHeader_DetectsPrefix(string key, bool expected)
{
AzureServiceBusHeaders.IsAsbHeader(key).Should().Be(expected);
}
[Fact]
public void Prefix_IsRedbAsb()
{
AzureServiceBusHeaders.Prefix.Should().Be("redbAsb.");
}
}
Path: redb-route/tests/redb.Route.Tests.AzureServiceBus/AzureServiceBusIntegrationTests.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.AzureServiceBus/AzureServiceBusIntegrationTests.cs
----
using System.Collections.Concurrent;
using System.Text;
using redb.Route.Abstractions;
using redb.Route.AzureServiceBus;
using redb.Route.Core;
using Xunit.Abstractions;
namespace redb.Route.Tests.AzureServiceBus;
///
/// Integration tests against Azure Service Bus Emulator.
/// Expects the emulator at localhost:5300 with pre-created entities:
/// - queue.1 (no sessions, MaxDeliveryCount=3)
/// - topic.1 with subscription.3 (no filter rules)
/// Each test uses unique message tags to prevent cross-TFM interference
/// when dotnet test runs all target frameworks in parallel.
///
[Trait("Category", "Integration")]
[Collection(AsbEmulatorQueue.Name)]
public sealed class AzureServiceBusIntegrationTests
{
private const string ConnectionString =
"Endpoint=sb://localhost:5300;SharedAccessKeyName=RootManageSharedAccessKey;" +
"SharedAccessKey=SAS_KEY_VALUE;UseDevelopmentEmulator=true;";
private const string Queue = "queue.1";
private const string Topic = "topic.1";
private const string Subscription = "subscription.3";
private readonly ITestOutputHelper _output;
public AzureServiceBusIntegrationTests(ITestOutputHelper output) => _output = output;
// ───── Helpers ─────
private static string Tag() => Guid.NewGuid().ToString("N")[..8];
private AzureServiceBusEndpoint CreateEndpoint(string entity, string? extraParams = null)
{
var qs = $"connectionString={ConnectionString}";
if (extraParams is not null) qs += $"&{extraParams}";
var uri = EndpointUriParser.Parse($"asb://{entity}?{qs}");
return (AzureServiceBusEndpoint)new AzureServiceBusComponent().CreateEndpoint(uri);
}
/// Drains leftover messages from an entity (best-effort cleanup).
private async Task DrainAsync(string entity, string? extraParams = null)
{
var ep = CreateEndpoint(entity,
$"ackMode=auto&maxConcurrentCalls=10{(extraParams is not null ? $"&{extraParams}" : "")}");
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(Task.CompletedTask);
var consumer = ep.CreateConsumer(processor);
await consumer.Start();
await Task.Delay(2000);
await consumer.Stop();
await ep.Stop();
}
// ───── Queue: Basic roundtrip ─────
[Fact]
public async Task Producer_SendsMessage_ConsumerReceives()
{
await DrainAsync(Queue);
var tag = Tag();
var epProd = CreateEndpoint(Queue);
var producer = epProd.CreateProducer();
await producer.Start();
var body = $"roundtrip-{tag}";
await producer.Process(new Exchange(new Message(body)));
await producer.Stop();
await epProd.Stop();
((IEndpointStatistics)epProd).BytesOut.Should().Be(System.Text.Encoding.UTF8.GetByteCount(body),
"the send counts the message body it sent");
var epCons = CreateEndpoint(Queue);
var tcs = new TaskCompletionSource();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(callInfo =>
{
var body = Encoding.UTF8.GetString((byte[])callInfo.Arg().In.Body!);
if (body.Contains(tag)) tcs.TrySetResult(body);
return Task.CompletedTask;
});
var consumer = epCons.CreateConsumer(processor);
await consumer.Start();
var completed = await Task.WhenAny(tcs.Task, Task.Delay(15_000));
await consumer.Stop();
await epCons.Stop();
completed.Should().Be(tcs.Task, "message should be received within timeout");
tcs.Task.Result.Should().Contain(tag);
}
// ───── Queue: Metadata headers ─────
[Fact]
public async Task Consumer_SetsAsbMetadataHeaders()
{
await DrainAsync(Queue);
var tag = Tag();
var epProd = CreateEndpoint(Queue);
var producer = epProd.CreateProducer();
await producer.Start();
var msg = new Message($"meta-{tag}");
msg.Headers[AzureServiceBusHeaders.CorrelationId] = "corr-123";
msg.Headers[AzureServiceBusHeaders.Subject] = "order.created";
await producer.Process(new Exchange(msg));
await producer.Stop();
await epProd.Stop();
var epCons = CreateEndpoint(Queue);
IExchange? captured = null;
var tcs = new TaskCompletionSource();
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!);
if (body.Contains(tag))
{
captured = ex;
tcs.TrySetResult();
}
return Task.CompletedTask;
});
var consumer = 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(AzureServiceBusHeaders.MessageId);
captured.In.Headers.Should().ContainKey(AzureServiceBusHeaders.SequenceNumber);
captured.In.Headers.Should().ContainKey(AzureServiceBusHeaders.EnqueuedTime);
captured.In.Headers.Should().ContainKey(AzureServiceBusHeaders.DeliveryCount);
captured.In.Headers[AzureServiceBusHeaders.CorrelationId].Should().Be("corr-123");
captured.In.Headers[AzureServiceBusHeaders.Subject].Should().Be("order.created");
}
// ───── Queue: Custom application properties ─────
[Fact]
public async Task Producer_ForwardsCustomHeaders()
{
await DrainAsync(Queue);
var tag = Tag();
var epProd = CreateEndpoint(Queue);
var producer = epProd.CreateProducer();
await producer.Start();
var msg = new Message($"hdr-{tag}");
msg.Headers["X-Custom-Id"] = "12345";
msg.Headers["X-Trace"] = "abc";
await producer.Process(new Exchange(msg));
await producer.Stop();
await epProd.Stop();
var epCons = CreateEndpoint(Queue);
IExchange? captured = null;
var tcs = new TaskCompletionSource();
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!);
if (body.Contains(tag))
{
captured = ex;
tcs.TrySetResult();
}
return Task.CompletedTask;
});
var consumer = 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");
captured.In.Headers["X-Trace"].Should().Be("abc");
}
// ───── Queue: ReceiveAndDelete mode ─────
[Fact]
public async Task Consumer_ReceiveAndDelete_ReceivesMessage()
{
await DrainAsync(Queue);
var tag = Tag();
var epProd = CreateEndpoint(Queue);
var producer = epProd.CreateProducer();
await producer.Start();
await producer.Process(new Exchange(new Message($"rad-{tag}")));
await producer.Stop();
await epProd.Stop();
var epCons = CreateEndpoint(Queue, "ackMode=auto");
var tcs = new TaskCompletionSource();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(callInfo =>
{
var body = Encoding.UTF8.GetString((byte[])callInfo.Arg().In.Body!);
if (body.Contains(tag)) tcs.TrySetResult(body);
return Task.CompletedTask;
});
var consumer = epCons.CreateConsumer(processor);
await consumer.Start();
var completed = await Task.WhenAny(tcs.Task, Task.Delay(15_000));
await consumer.Stop();
await epCons.Stop();
completed.Should().Be(tcs.Task);
tcs.Task.Result.Should().Contain(tag);
}
// ───── Queue: PeekLock auto dead-letter ─────
[Fact]
public async Task Consumer_AutoDeadLetter_MovesToDeadLetterQueue()
{
await DrainAsync(Queue);
await DrainAsync(Queue, "subQueue=deadletter");
var tag = Tag();
var epProd = CreateEndpoint(Queue);
var producer = epProd.CreateProducer();
await producer.Start();
await producer.Process(new Exchange(new Message($"dl-{tag}")));
await producer.Stop();
await epProd.Stop();
// Consumer that sets an exception on our message → triggers dead-letter
var epCons = CreateEndpoint(Queue, "autoDeadLetter=true&deadLetterReason=TestError");
var processedCount = 0;
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!);
if (body.Contains(tag))
{
ex.Exception = new InvalidOperationException("Simulated error");
Interlocked.Increment(ref processedCount);
}
return Task.CompletedTask;
});
var consumer = epCons.CreateConsumer(processor);
await consumer.Start();
// Wait enough for processing + dead-letter
await Task.Delay(5000);
await consumer.Stop();
await epCons.Stop();
processedCount.Should().BeGreaterThanOrEqualTo(1, "our tagged message should have been processed");
// Read from dead-letter sub-queue
var epDlq = CreateEndpoint(Queue, "subQueue=deadletter");
var tcs = new TaskCompletionSource();
var dlqProcessor = Substitute.For();
dlqProcessor.Process(Arg.Any(), Arg.Any())
.Returns(callInfo =>
{
var body = Encoding.UTF8.GetString((byte[])callInfo.Arg().In.Body!);
if (body.Contains(tag)) tcs.TrySetResult(body);
return Task.CompletedTask;
});
var dlqConsumer = epDlq.CreateConsumer(dlqProcessor);
await dlqConsumer.Start();
await Task.WhenAny(tcs.Task, Task.Delay(15_000));
await dlqConsumer.Stop();
await epDlq.Stop();
tcs.Task.IsCompletedSuccessfully.Should().BeTrue("message should appear in DLQ");
}
// ───── Queue: Transacted consumer — commit ─────
[Fact]
public async Task TransactedConsumer_Commit_CompletesMessage()
{
await DrainAsync(Queue);
var tag = Tag();
var epProd = CreateEndpoint(Queue);
var producer = epProd.CreateProducer();
await producer.Start();
await producer.Process(new Exchange(new Message($"tx-{tag}")));
await producer.Stop();
await epProd.Stop();
var epCons = CreateEndpoint(Queue, "transacted=true");
IExchange? captured = null;
var tcs = new TaskCompletionSource();
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!);
if (body.Contains(tag))
{
captured = ex;
tcs.TrySetResult();
}
return Task.CompletedTask;
});
var consumer = epCons.CreateConsumer(processor);
await consumer.Start();
await Task.WhenAny(tcs.Task, Task.Delay(15_000));
captured.Should().NotBeNull();
// The acknowledgement is the consumer's: once the route returned without a failure, the message is
// completed here, after the route transaction has committed the database and sent what it deferred.
await consumer.Stop();
await epCons.Stop();
// Verify our specific message is gone (no re-delivery)
var epVerify = CreateEndpoint(Queue, "ackMode=auto");
var foundOurs = false;
var verifyProcessor = Substitute.For();
verifyProcessor.Process(Arg.Any(), Arg.Any())
.Returns(callInfo =>
{
var body = Encoding.UTF8.GetString((byte[])callInfo.Arg().In.Body!);
if (body.Contains(tag)) foundOurs = true;
return Task.CompletedTask;
});
var verifyConsumer = epVerify.CreateConsumer(verifyProcessor);
await verifyConsumer.Start();
await Task.Delay(3000);
await verifyConsumer.Stop();
await epVerify.Stop();
foundOurs.Should().BeFalse("committed message should not be re-delivered");
}
// ───── Queue: Transacted consumer — rollback ─────
[Fact]
public async Task TransactedConsumer_Rollback_DoesNotThrow()
{
await DrainAsync(Queue);
var tag = Tag();
var epProd = CreateEndpoint(Queue);
var producer = epProd.CreateProducer();
await producer.Start();
await producer.Process(new Exchange(new Message($"rb-{tag}")));
await producer.Stop();
await epProd.Stop();
var epCons = CreateEndpoint(Queue, "transacted=true");
IExchange? captured = null;
var tcs = new TaskCompletionSource();
var deliveries = 0;
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!);
if (body.Contains(tag))
{
captured = ex;
// A failure the route leaves on the exchange: the consumer must abandon the message rather than
// acknowledge a unit of work that did not happen, so the broker delivers it again.
if (Interlocked.Increment(ref deliveries) >= 2)
tcs.TrySetResult();
ex.Exception = new InvalidOperationException("the route failed");
}
return Task.CompletedTask;
});
var consumer = epCons.CreateConsumer(processor);
await consumer.Start();
await Task.WhenAny(tcs.Task, Task.Delay(20_000));
await consumer.Stop();
await epCons.Stop();
captured.Should().NotBeNull();
deliveries.Should().BeGreaterThanOrEqualTo(2,
"a failed unit of work is not acknowledged, so the broker delivers the message again");
}
// ───── Queue: Multiple messages ─────
[Fact]
public async Task Roundtrip_MultipleMessages()
{
await DrainAsync(Queue);
var tag = Tag();
const int messageCount = 10;
var epProd = CreateEndpoint(Queue);
var producer = epProd.CreateProducer();
await producer.Start();
for (int i = 0; i < messageCount; i++)
await producer.Process(new Exchange(new Message($"multi-{tag}-{i}")));
await producer.Stop();
await epProd.Stop();
var epCons = CreateEndpoint(Queue, "maxConcurrentCalls=5");
var received = new ConcurrentBag();
var allReceived = new TaskCompletionSource();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(callInfo =>
{
var body = Encoding.UTF8.GetString((byte[])callInfo.Arg().In.Body!);
if (body.Contains(tag))
{
received.Add(body);
if (received.Count >= messageCount) allReceived.TrySetResult();
}
return Task.CompletedTask;
});
var consumer = epCons.CreateConsumer(processor);
await consumer.Start();
await Task.WhenAny(allReceived.Task, Task.Delay(30_000));
await consumer.Stop();
await epCons.Stop();
received.Count.Should().BeGreaterThanOrEqualTo(messageCount);
for (int i = 0; i < messageCount; i++)
received.Should().Contain($"multi-{tag}-{i}");
}
// ───── Topic/Subscription: Roundtrip ─────
[Fact]
public async Task Topic_Subscription_Roundtrip()
{
await DrainAsync(Topic, $"subscriptionName={Subscription}");
var tag = Tag();
var epProd = CreateEndpoint(Topic);
var producer = epProd.CreateProducer();
await producer.Start();
await producer.Process(new Exchange(new Message($"topic-{tag}")));
await producer.Stop();
await epProd.Stop();
var epCons = CreateEndpoint(Topic, $"subscriptionName={Subscription}");
var tcs = new TaskCompletionSource();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(callInfo =>
{
var body = Encoding.UTF8.GetString((byte[])callInfo.Arg().In.Body!);
if (body.Contains(tag)) tcs.TrySetResult(body);
return Task.CompletedTask;
});
var consumer = epCons.CreateConsumer(processor);
await consumer.Start();
await Task.WhenAny(tcs.Task, Task.Delay(15_000));
await consumer.Stop();
await epCons.Stop();
tcs.Task.IsCompletedSuccessfully.Should().BeTrue();
tcs.Task.Result.Should().Contain(tag);
}
// ───── Batch: Send multiple ─────
[Fact] public async Task A_list_of_IMessage_sends_each_element_with_its_own_body_and_properties() { await DrainAsync(Queue); var tag = Tag(); var epProd = CreateEndpoint(Queue); var producer = epProd.CreateProducer(); await producer.Start(); var parent = new Exchange(new Message(new List { new Message($"{tag}-a") { Headers = { ["element"] = "a" } }, new Message($"{tag}-b") { Headers = { ["element"] = "b" } }, })); parent.In.Headers["parentOnly"] = "p"; await producer.Process(parent); await producer.Stop(); await epProd.Stop(); var epCons = CreateEndpoint(Queue); var received = new ConcurrentDictionary>(); 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!); if (body.StartsWith(tag)) received[body] = ex.In.Headers.ToDictionary(h => h.Key, h => h.Value); return Task.CompletedTask; }); var consumer = epCons.CreateConsumer(processor); await consumer.Start(); var deadline = DateTime.UtcNow.AddSeconds(15); while (received.Count < 2 && DateTime.UtcNow < deadline) await Task.Delay(100); await consumer.Stop(); await epCons.Stop(); received.Keys.Should().BeEquivalentTo($"{tag}-a", $"{tag}-b"); received[$"{tag}-a"]["element"].Should().Be("a"); received[$"{tag}-b"]["element"].Should().Be("b"); received.Values.Should().OnlyContain(h => !h.ContainsKey("parentOnly"), "an IMessage element carries its own headers, none of the parent's"); received.Values.Select(h => h[AzureServiceBusHeaders.MessageId]).Distinct().Should().HaveCount(2); }
[Fact]
public async Task A_list_body_is_sent_as_one_batch_and_every_element_arrives()
{
await DrainAsync(Queue);
var tag = Tag();
var epProd = CreateEndpoint(Queue);
var producer = epProd.CreateProducer();
await producer.Start();
var items = Enumerable.Range(0, 5).Select(i => $"batch-{tag}-{i}").ToList();
var exchange = new Exchange(new Message(items));
await producer.Process(exchange);
exchange.In.Headers.Should().ContainKey(AzureServiceBusHeaders.BatchMessageCount);
((int)exchange.In.Headers[AzureServiceBusHeaders.BatchMessageCount]!).Should().Be(5);
await producer.Stop();
await epProd.Stop();
// Consume
var epCons = CreateEndpoint(Queue, "maxConcurrentCalls=5");
var received = new ConcurrentBag();
var allReceived = new TaskCompletionSource();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(callInfo =>
{
var body = Encoding.UTF8.GetString((byte[])callInfo.Arg().In.Body!);
if (body.Contains(tag))
{
received.Add(body);
if (received.Count >= 5) allReceived.TrySetResult();
}
return Task.CompletedTask;
});
var consumer = epCons.CreateConsumer(processor);
await consumer.Start();
await Task.WhenAny(allReceived.Task, Task.Delay(15_000));
await consumer.Stop();
await epCons.Stop();
received.Count.Should().Be(5);
}
// ───── Producer: MessageId preserved ─────
[Fact]
public async Task Producer_SetsMessageId_ConsumerReceivesIt()
{
await DrainAsync(Queue);
var tag = Tag();
var customId = $"custom-{tag}";
var epProd = CreateEndpoint(Queue);
var producer = epProd.CreateProducer();
await producer.Start();
var msg = new Message($"id-{tag}");
msg.Headers[AzureServiceBusHeaders.MessageId] = customId;
await producer.Process(new Exchange(msg));
await producer.Stop();
await epProd.Stop();
var epCons = CreateEndpoint(Queue);
IExchange? captured = null;
var tcs = new TaskCompletionSource();
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!);
if (body.Contains(tag))
{
captured = ex;
tcs.TrySetResult();
}
return Task.CompletedTask;
});
var consumer = 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[AzureServiceBusHeaders.MessageId].Should().Be(customId);
}
// ───── Consumer: PeekLock completes on successful processing ─────
[Fact]
public async Task Consumer_PeekLock_CompletesOnSuccess()
{
await DrainAsync(Queue);
var tag = Tag();
var epProd = CreateEndpoint(Queue);
var producer = epProd.CreateProducer();
await producer.Start();
await producer.Process(new Exchange(new Message($"pl-{tag}")));
await producer.Stop();
await epProd.Stop();
// First consumer — PeekLock, processes successfully → should complete
var epCons = CreateEndpoint(Queue);
var tcs = new TaskCompletionSource();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(callInfo =>
{
var body = Encoding.UTF8.GetString((byte[])callInfo.Arg().In.Body!);
if (body.Contains(tag)) tcs.TrySetResult();
return Task.CompletedTask;
});
var consumer = epCons.CreateConsumer(processor);
await consumer.Start();
await Task.WhenAny(tcs.Task, Task.Delay(15_000));
await consumer.Stop();
await epCons.Stop();
tcs.Task.IsCompletedSuccessfully.Should().BeTrue("message should be processed");
// Verify our specific message is not re-delivered
var epVerify = CreateEndpoint(Queue, "ackMode=auto");
var foundOurs = false;
var verifyProcessor = Substitute.For();
verifyProcessor.Process(Arg.Any(), Arg.Any())
.Returns(callInfo =>
{
var body = Encoding.UTF8.GetString((byte[])callInfo.Arg().In.Body!);
if (body.Contains(tag)) foundOurs = true;
return Task.CompletedTask;
});
var verifyConsumer = epVerify.CreateConsumer(verifyProcessor);
await verifyConsumer.Start();
await Task.Delay(3000);
await verifyConsumer.Stop();
await epVerify.Stop();
foundOurs.Should().BeFalse("completed message should not be re-delivered");
}
// ───── Consumer: Processing error abandons message ─────
[Fact]
public async Task Consumer_ProcessingError_AbandonsMessage()
{
await DrainAsync(Queue);
var tag = Tag();
var epProd = CreateEndpoint(Queue);
var producer = epProd.CreateProducer();
await producer.Start();
await producer.Process(new Exchange(new Message($"err-{tag}")));
await producer.Stop();
await epProd.Stop();
// Consumer that throws on our message — should be abandoned
var epCons = CreateEndpoint(Queue);
var tcs = new TaskCompletionSource();
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(callInfo =>
{
var body = Encoding.UTF8.GetString((byte[])callInfo.Arg().In.Body!);
if (body.Contains(tag))
{
tcs.TrySetResult();
throw new InvalidOperationException("simulated failure");
}
return Task.CompletedTask;
});
var consumer = epCons.CreateConsumer(processor);
await consumer.Start();
await Task.WhenAny(tcs.Task, Task.Delay(15_000));
await consumer.Stop();
await epCons.Stop();
// Message should be re-delivered (abandoned, not completed)
var epRetry = CreateEndpoint(Queue, "ackMode=auto");
var retryTcs = new TaskCompletionSource();
var retryProcessor = Substitute.For();
retryProcessor.Process(Arg.Any(), Arg.Any())
.Returns(callInfo =>
{
var body = Encoding.UTF8.GetString((byte[])callInfo.Arg().In.Body!);
if (body.Contains(tag)) retryTcs.TrySetResult(body);
return Task.CompletedTask;
});
var retryConsumer = epRetry.CreateConsumer(retryProcessor);
await retryConsumer.Start();
await Task.WhenAny(retryTcs.Task, Task.Delay(15_000));
await retryConsumer.Stop();
await epRetry.Stop();
retryTcs.Task.IsCompletedSuccessfully.Should().BeTrue("abandoned message should be re-delivered");
retryTcs.Task.Result.Should().Contain(tag);
}
}
Path: redb-route/tests/redb.Route.Tests.AzureServiceBus/AzureServiceBusTelemetrySmokeTests.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.AzureServiceBus/AzureServiceBusTelemetrySmokeTests.cs
----
using System.Diagnostics;
using redb.Route.Abstractions;
using redb.Route.AzureServiceBus;
using redb.Route.Core;
using redb.Route.Telemetry;
using redb.Route.Tests.Shared;
using Xunit.Abstractions;
namespace redb.Route.Tests.AzureServiceBus;
///
/// Smoke test for the P1 transport span opened by .
/// Requires Azure Service Bus emulator on localhost:5300 with queue.1.
///
[Trait("Category", "Integration")]
[Collection(AsbEmulatorQueue.Name)]
public sealed class AzureServiceBusTelemetrySmokeTests
{
private const string ConnectionString =
"Endpoint=sb://localhost:5300;SharedAccessKeyName=RootManageSharedAccessKey;" +
"SharedAccessKey=SAS_KEY_VALUE;UseDevelopmentEmulator=true;";
private const string Queue = "queue.1";
private readonly ITestOutputHelper _output;
public AzureServiceBusTelemetrySmokeTests(ITestOutputHelper output) => _output = output;
[Fact]
public async Task AzureServiceBusProducer_EmitsTransportSpanWithMessagingTags()
{
var uri = EndpointUriParser.Parse($"asb://{Queue}?connectionString={ConnectionString}");
var endpoint = (AzureServiceBusEndpoint)new AzureServiceBusComponent().CreateEndpoint(uri);
var producer = endpoint.CreateProducer();
await producer.Start();
using var capture = new SpanCapture(); // this test's spans only
try
{
await producer.Process(new Exchange(new Message($"smoke-{Guid.NewGuid():N}")));
}
catch (Exception ex)
{
_output.WriteLine($"ASB Send failed (acceptable for smoke): {ex.GetType().Name}: {ex.Message}");
}
finally
{
await producer.Stop();
await endpoint.Stop();
}
var activities = capture.Spans;
activities.Should().NotBeEmpty();
var activity = activities.First();
activity.Source.Name.Should().Be(RouteActivitySource.SourceName);
activity.Kind.Should().Be(ActivityKind.Producer);
activity.GetTagItem("messaging.system").Should().Be("azureservicebus");
activity.GetTagItem("messaging.operation").Should().Be("send");
activity.GetTagItem("messaging.destination.name").Should().Be(Queue);
activity.GetTagItem("redb.route.endpoint").Should().NotBeNull();
}
}
Path: redb-route/tests/redb.Route.Tests.AzureServiceBus/AzureServiceBusTracePropagationTests.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.AzureServiceBus/AzureServiceBusTracePropagationTests.cs
----
using System.Diagnostics;
using Azure.Messaging.ServiceBus;
using redb.Route.Abstractions;
using redb.Route.AzureServiceBus;
using redb.Route.Configuration;
using redb.Route.Core;
using redb.Route.Telemetry;
using redb.Route.Tests.Telemetry;
namespace redb.Route.Tests.AzureServiceBus;
///
/// A Service Bus message carries its trace context in the application properties, the traceparent value under
/// Azure's name Diagnostic-Id. The consumer opens a receive span per message: a child of the sender's context,
/// a root without one, 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 Diagnostic-Id copied from a received
/// message. EnableTelemetry=false opens none of these spans, while a context that came in still goes out.
/// Requires the Azure Service Bus emulator on localhost:5300 with queue.1.
///
[Trait("Category", "Integration")]
[Collection(AsbEmulatorQueue.Name)]
public sealed class AzureServiceBusTracePropagationTests
{
private const string ConnectionString =
"Endpoint=sb://localhost:5300;SharedAccessKeyName=RootManageSharedAccessKey;" +
"SharedAccessKey=SAS_KEY_VALUE;UseDevelopmentEmulator=true;";
private const string Queue = "queue.1";
private const string DiagnosticId = "Diagnostic-Id";
private static readonly string QueueUri = $"asb://{Queue}?connectionString={ConnectionString}";
private static readonly TimeSpan Wait = TimeSpan.FromSeconds(20);
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 ReceiveSpansOf(string messageId)
=> new(a => a.Kind == ActivityKind.Consumer && RouteTelemetryProbe.Tag(a, "messaging.message.id") == messageId);
/// Sends one message straight through the SDK, as a sender that is not redb would.
private static async Task SendRaw(string messageId, IDictionary? properties = null)
{
await using var client = new ServiceBusClient(ConnectionString);
await using var sender = client.CreateSender(Queue);
var message = new ServiceBusMessage(BinaryData.FromString(messageId)) { MessageId = messageId };
foreach (var (key, value) in properties ?? new Dictionary())
message.ApplicationProperties[key] = value;
await sender.SendMessageAsync(message);
}
/// Receives the message with straight through the SDK, completing what it reads.
private static async Task ReceiveRaw(string messageId)
{
await using var client = new ServiceBusClient(ConnectionString);
await using var receiver = client.CreateReceiver(Queue);
var deadline = DateTime.UtcNow + Wait;
while (DateTime.UtcNow < deadline)
{
var message = await receiver.ReceiveMessageAsync(TimeSpan.FromSeconds(2));
if (message is null) continue;
await receiver.CompleteMessageAsync(message);
if (message.MessageId == messageId) return message;
}
throw new TimeoutException($"Message {messageId} did not arrive on {Queue}.");
}
/// A context with one consuming route whose step is .
private static async Task StartConsumer(string routeId, Action step, bool telemetry = true)
{
var ctx = new RouteContext(options: new RouteEngineOptions { EnableTelemetry = telemetry });
ctx.AddComponent(new AzureServiceBusComponent());
ctx.AddRoutes(r => r.From(QueueUri).RouteId(routeId).Process(step));
await ctx.Start();
return ctx;
}
private static string Tag() => Guid.NewGuid().ToString("N")[..12];
[Fact]
public async Task A_message_without_context_opens_a_root_receive_span()
{
var id = $"root-{Tag()}";
using var probe = ReceiveSpansOf(id);
var done = new TaskCompletionSource();
await using (await StartConsumer($"asb-trace-{id}", e => { if (e.In.GetHeader(AzureServiceBusHeaders.MessageId) == id) done.TrySetResult(); }))
{
await SendRaw(id);
(await Task.WhenAny(done.Task, Task.Delay(Wait))).Should().Be(done.Task);
}
var receive = probe.Activities.Should().ContainSingle().Subject;
receive.ParentSpanId.Should().Be(default(ActivitySpanId), "a message that carries no context starts a trace");
receive.Source.Name.Should().Be(RouteActivitySource.SourceName);
receive.GetTagItem("messaging.system").Should().Be("azureservicebus");
receive.GetTagItem("messaging.operation").Should().Be("receive");
receive.GetTagItem("messaging.destination.name").Should().Be(Queue);
RouteTelemetryProbe.Tag(receive, RouteTelemetryProbe.EndpointTag).Should().StartWith("asb://");
}
[Fact]
public async Task A_message_with_context_continues_the_senders_trace_and_the_route_runs_under_it()
{
var id = $"child-{Tag()}";
var routeId = $"asb-trace-{id}";
using var probe = ReceiveSpansOf(id);
using var routes = RouteTelemetryProbe.ForRouteIdPrefix(routeId);
var caller = Caller();
var done = new TaskCompletionSource();
await using (await StartConsumer(routeId, e => { if (e.In.GetHeader(AzureServiceBusHeaders.MessageId) == id) done.TrySetResult(); }))
{
await SendRaw(id, new Dictionary { [DiagnosticId] = caller.Header });
(await Task.WhenAny(done.Task, Task.Delay(Wait))).Should().Be(done.Task);
}
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,
"the route runs inside the receive");
}
[Fact]
public async Task The_senders_baggage_reaches_the_route()
{
var id = $"bag-{Tag()}";
using var probe = ReceiveSpansOf(id); // a listener: without one no span opens to carry the baggage
var caller = Caller();
var seen = new TaskCompletionSource();
await using (await StartConsumer($"asb-trace-{id}", e =>
{
if (e.In.GetHeader(AzureServiceBusHeaders.MessageId) == id)
seen.TrySetResult(Activity.Current?.GetBaggageItem("tenant"));
}))
{
await SendRaw(id, new Dictionary { [DiagnosticId] = 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 id = $"fail-{Tag()}";
using var probe = ReceiveSpansOf(id);
var failed = new TaskCompletionSource();
await using (await StartConsumer($"asb-trace-{id}", e =>
{
if (e.In.GetHeader(AzureServiceBusHeaders.MessageId) != id) return;
failed.TrySetResult();
throw new InvalidOperationException("route failed");
}))
{
await SendRaw(id);
(await Task.WhenAny(failed.Task, Task.Delay(Wait))).Should().Be(failed.Task);
// The span ends after settlement; give the handler the time to get there.
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);
}
[Fact]
public async Task A_timeout_inside_the_route_marks_the_receive_span_red()
{
var id = $"timeout-{Tag()}";
using var probe = ReceiveSpansOf(id);
var thrown = new TaskCompletionSource();
await using (await StartConsumer($"asb-trace-{id}", e =>
{
if (e.In.GetHeader(AzureServiceBusHeaders.MessageId) != id) return;
thrown.TrySetResult();
throw new TaskCanceledException("a call inside the route timed out");
}))
{
await SendRaw(id);
(await Task.WhenAny(thrown.Task, Task.Delay(Wait))).Should().Be(thrown.Task);
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 id = $"stop-{Tag()}";
using var probe = ReceiveSpansOf(id);
var started = new TaskCompletionSource();
var ctx = new RouteContext(options: new RouteEngineOptions { ShutdownTimeout = TimeSpan.FromSeconds(2) });
ctx.AddComponent(new AzureServiceBusComponent());
ctx.AddRoutes(r => r.From(QueueUri).RouteId($"asb-trace-{id}").Process(async (e, ct) =>
{
if (e.In.GetHeader(AzureServiceBusHeaders.MessageId) != id) return;
started.TrySetResult();
await Task.Delay(Timeout.Infinite, ct);
}));
await ctx.Start();
await SendRaw(id);
(await Task.WhenAny(started.Task, Task.Delay(Wait))).Should().Be(started.Task);
await ctx.DisposeAsync(); // the processor stops and cancels the handler's 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 id = $"send-{Tag()}";
var stale = Caller();
await using var ctx = new RouteContext();
ctx.AddComponent(new AzureServiceBusComponent());
await ctx.Start();
using var sends = new RouteTelemetryProbe(a => a.Kind == ActivityKind.Producer
&& a.GetTagItem("messaging.destination.name") as string == Queue);
using var outer = new Activity("caller").Start();
var exchange = new Exchange(new Message(id));
exchange.In.Headers[AzureServiceBusHeaders.MessageId] = id;
exchange.In.Headers[DiagnosticId] = stale.Header; // what the header bridge copies from a received message
using (var template = new ProducerTemplate(ctx))
{
template.Start();
await template.SendAsync(QueueUri, exchange);
}
var send = sends.Activities.Single(a => a.TraceId == outer.TraceId);
var received = await ReceiveRaw(id);
received.ApplicationProperties[DiagnosticId].Should().Be($"00-{outer.TraceId}-{send.SpanId}-{(int)send.ActivityTraceFlags:x2}",
"the next hop is a child of the send, not of the hop the copied header names");
}
[Fact]
public async Task Tracing_off_opens_no_span_and_still_passes_the_context_on()
{
var id = $"off-{Tag()}";
using var receives = ReceiveSpansOf(id);
await using var ctx = new RouteContext(options: new RouteEngineOptions { EnableTelemetry = false });
ctx.AddComponent(new AzureServiceBusComponent());
await ctx.Start();
using var sends = new RouteTelemetryProbe(a => a.Kind == ActivityKind.Producer
&& a.GetTagItem("messaging.destination.name") as string == Queue);
using var outer = new Activity("caller").Start();
var exchange = new Exchange(new Message(id));
exchange.In.Headers[AzureServiceBusHeaders.MessageId] = id;
using (var template = new ProducerTemplate(ctx))
{
template.Start();
await template.SendAsync(QueueUri, exchange);
}
var received = await ReceiveRaw(id);
received.ApplicationProperties[DiagnosticId].Should().Be(outer.Id,
"with no send span the ambient context goes out");
sends.Activities.Where(a => a.TraceId == outer.TraceId).Should().BeEmpty();
var done = new TaskCompletionSource();
await using (await StartConsumer($"asb-trace-{id}", e => { if (e.In.GetHeader(AzureServiceBusHeaders.MessageId) == id) done.TrySetResult(); }, telemetry: false))
{
await SendRaw(id, new Dictionary { [DiagnosticId] = Caller().Header });
(await Task.WhenAny(done.Task, Task.Delay(Wait))).Should().Be(done.Task);
}
receives.Activities.Should().BeEmpty();
}
}
Path: redb-route/tests/redb.Route.Tests.AzureServiceBus/AzureServiceBusTransactedSendTests.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.AzureServiceBus/AzureServiceBusTransactedSendTests.cs
----
using System.Collections.Concurrent;
using System.Text;
using redb.Route.Abstractions;
using redb.Route.AzureServiceBus;
using redb.Route.Core;
using redb.Route.Processors;
using redb.Route.Transactions;
namespace redb.Route.Tests.AzureServiceBus;
///
/// Service Bus sends inside .Transacted(): unset, they join the block and leave only after the database commits;
/// transacted=false sends at once, outside the block's transaction (the Service Bus client would otherwise enlist
/// in it on its own); transacted=true outside a block is refused.
///
[Trait("Category", "Integration")]
[Collection(AsbEmulatorQueue.Name)]
public sealed class AzureServiceBusTransactedSendTests
{
private const string ConnectionString =
"Endpoint=sb://localhost:5300;SharedAccessKeyName=RootManageSharedAccessKey;" +
"SharedAccessKey=SAS_KEY_VALUE;UseDevelopmentEmulator=true;";
private const string Queue = "queue.1";
private static string Tag() => Guid.NewGuid().ToString("N")[..8];
private static AzureServiceBusEndpoint CreateEndpoint(string? extraParams = null)
{
var qs = $"connectionString={ConnectionString}";
if (extraParams is not null) qs += $"&{extraParams}";
return (AzureServiceBusEndpoint)new AzureServiceBusComponent().CreateEndpoint(EndpointUriParser.Parse($"asb://{Queue}?{qs}"));
}
private static Task InTransaction(IExchange exchange, Func body) =>
new TransactedProcessor(new DelegateProcessor(body), new TransactionPolicy()).Process(exchange);
private static async Task SendFromAFailedBlock(string body, string? producerParams)
{
var endpoint = CreateEndpoint(producerParams);
var producer = endpoint.CreateProducer();
await producer.Start();
var failed = () => InTransaction(new Exchange(new Message(body)), async (ex, ct) =>
{
await producer.Process(ex, ct);
throw new InvalidOperationException("the unit of work failed");
});
await failed.Should().ThrowAsync();
await producer.Stop();
await endpoint.Stop();
}
/// Everything that reaches the queue during the window, taken off it for good.
private static async Task> ReceiveFor(TimeSpan window)
{
var endpoint = CreateEndpoint("ackMode=auto&maxConcurrentCalls=10");
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 = endpoint.CreateConsumer(processor);
await consumer.Start();
await Task.Delay(window);
await consumer.Stop();
await endpoint.Stop();
return received;
}
[Fact]
public async Task Send_without_transacted_joins_the_block_and_leaves_nothing_when_it_fails()
{
var body = $"join-{Tag()}";
await SendFromAFailedBlock(body, producerParams: null);
(await ReceiveFor(TimeSpan.FromSeconds(4))).Should().NotContain(body,
"inside .Transacted() a send joins the transaction unless transacted=false opts out");
}
[Fact]
public async Task Send_with_transacted_false_goes_out_at_once_even_from_a_failed_block()
{
var body = $"optout-{Tag()}";
await SendFromAFailedBlock(body, "transacted=false");
(await ReceiveFor(TimeSpan.FromSeconds(4))).Should().Contain(body);
}
[Fact]
public async Task Consumer_abandons_a_rolled_back_unit_of_work_so_it_is_delivered_again()
{
await ReceiveFor(TimeSpan.FromSeconds(2)); // start from an empty queue
var body = $"rbonly-{Tag()}";
var endpoint = CreateEndpoint();
var producer = endpoint.CreateProducer();
await producer.Start();
await producer.Process(new Exchange(new Message(body)));
await producer.Stop();
await endpoint.Stop();
// What .RollbackAll() does inside .Transacted(): mark the unit of work rollback-only and stop the route.
var deliveries = 0;
var deliveredAgain = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var route = new TransactedProcessor(new DelegateProcessor(ex =>
{
if (Encoding.UTF8.GetString((byte[])ex.In.Body!) != body) return;
if (Interlocked.Increment(ref deliveries) >= 2) deliveredAgain.TrySetResult();
ex.MarkRollbackOnly();
ex.Stop();
}), new TransactionPolicy());
var consumerEndpoint = CreateEndpoint();
var consumer = consumerEndpoint.CreateConsumer(route);
await consumer.Start();
await Task.WhenAny(deliveredAgain.Task, Task.Delay(15_000));
await consumer.Stop();
await consumerEndpoint.Stop();
deliveries.Should().BeGreaterThanOrEqualTo(2,
"a rolled-back unit of work is abandoned, not completed, so Service Bus delivers the message again");
}
[Fact]
public async Task Send_with_transacted_true_outside_a_block_is_refused()
{
var endpoint = CreateEndpoint("transacted=true");
var producer = endpoint.CreateProducer();
await producer.Start();
var act = () => producer.Process(new Exchange(new Message($"none-{Tag()}")));
await act.Should().ThrowAsync().WithMessage("*Transacted()*");
await producer.Stop();
await endpoint.Stop();
}
}
Path: redb-route/tests/redb.Route.Tests.AzureServiceBus/redb.Route.Tests.AzureServiceBus.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.AzureServiceBus/redb.Route.Tests.AzureServiceBus.csproj
----