Path: redb-route/tests/redb.Route.Tests/Core/EndpointSupervisionTests.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/Core/EndpointSupervisionTests.cs
----
using AwesomeAssertions;
using redb.Route.Abstractions;
using redb.Route.Configuration;
using redb.Route.Core;
namespace redb.Route.Tests.Core;
///
/// How connection supervisors feed an endpoint (): health as the worst of the
/// supervisors and the transport's own condition, errors and reconnects counted; and how
/// reconnects a lost connection on the next send.
///
public sealed class EndpointSupervisionTests : IAsyncLifetime
{
private RouteContext? _context;
public Task InitializeAsync() => Task.CompletedTask;
public async Task DisposeAsync()
{
if (_context is not null)
await _context.DisposeAsync();
}
private SupervisedEndpoint Endpoint(ReconnectOptions? reconnect = null)
{
_context = new RouteContext(options: new RouteEngineOptions { Reconnect = reconnect ?? new ReconnectOptions() });
_context.AddComponent(new SupervisedComponent());
return (SupervisedEndpoint)_context.GetEndpoint("sup://broker");
}
[Fact]
public void A_lost_connection_turns_the_endpoint_Warning_then_Critical_and_Healthy_again_once_restored()
{
var endpoint = Endpoint();
var worker = endpoint.Supervise("sup:broker worker 1", null);
endpoint.HealthStatus.Should().Be(EndpointHealthStatus.Healthy);
worker.Lost(new IOException("connection broken"));
endpoint.HealthStatus.Should().Be(EndpointHealthStatus.Warning);
endpoint.HealthReason.Should().Contain("sup:broker worker 1");
worker.Failed(new IOException("connect refused"));
endpoint.HealthStatus.Should().Be(EndpointHealthStatus.Critical);
worker.Restored();
endpoint.HealthStatus.Should().Be(EndpointHealthStatus.Healthy);
endpoint.Reconnects.Should().Be(1);
}
[Fact]
public void The_worst_of_the_supervisors_and_the_transport_condition_wins()
{
var endpoint = Endpoint();
var first = endpoint.Supervise("worker 1", null);
var second = endpoint.Supervise("worker 2", null);
first.Lost(new IOException("blip"));
second.Lost(new IOException("down"));
second.Failed(new IOException("refused"));
endpoint.HealthStatus.Should().Be(EndpointHealthStatus.Critical);
endpoint.HealthReason.Should().Contain("worker 2");
second.Restored();
endpoint.HealthStatus.Should().Be(EndpointHealthStatus.Warning);
endpoint.HealthReason.Should().Contain("worker 1");
endpoint.Condition = (EndpointHealthStatus.Critical, "transport says no");
endpoint.HealthStatus.Should().Be(EndpointHealthStatus.Critical);
endpoint.HealthReason.Should().Be("transport says no");
}
[Fact]
public void A_loss_does_not_raise_the_error_rate_but_a_failed_message_still_does()
{
var endpoint = Endpoint();
var worker = endpoint.Supervise("worker 1", null);
endpoint.RecordMessageIn();
worker.Lost(new IOException("broken"));
worker.Failed(new IOException("refused"));
worker.Restored();
endpoint.HealthStatus.Should().Be(EndpointHealthStatus.Healthy, "the connection is back and no message failed");
endpoint.RecordError(new InvalidOperationException("the route failed on a message"));
endpoint.Errors.Should().Be(1);
endpoint.HealthStatus.Should().Be(EndpointHealthStatus.Critical, "1 failed message of 1 is a high error rate");
}
[Fact]
public void A_removed_supervisor_no_longer_counts()
{
var endpoint = Endpoint();
var worker = endpoint.Supervise("worker 1", null);
worker.Lost(new IOException("down"));
worker.Failed(new IOException("refused"));
endpoint.Unsupervise(worker);
endpoint.HealthReason.Should().NotContain("worker 1");
}
[Fact]
public void A_loss_shows_masked_in_the_health_reason_not_in_errors_and_reset_clears_reconnects()
{
var endpoint = Endpoint();
var worker = endpoint.Supervise("worker 1", null);
worker.Lost(new IOException("connect to amqp://user:s3cret@host failed"));
endpoint.Errors.Should().Be(0, "a supervised loss is not a failed message");
endpoint.HealthReason.Should().Contain("connect to").And.NotContain("s3cret");
worker.LastFailure.Should().NotContain("s3cret");
worker.Restored();
endpoint.Reconnects.Should().Be(1);
endpoint.ResetStatistics();
endpoint.Reconnects.Should().Be(0);
}
[Fact]
public void The_context_reconnect_options_reach_the_supervisor()
{
var endpoint = Endpoint(new ReconnectOptions { Delay = TimeSpan.FromSeconds(5), MaxDelay = TimeSpan.FromMinutes(1) });
var worker = endpoint.Supervise("worker 1", null);
worker.Lost(new IOException("down"));
worker.DueIn.Should().BeGreaterThan(TimeSpan.FromSeconds(4));
}
[Fact]
public void Invalid_context_reconnect_options_stop_the_context_from_being_built()
{
FluentActions.Invoking(() => new RouteContext(options: new RouteEngineOptions
{
Reconnect = new ReconnectOptions { WarningPeriod = TimeSpan.FromSeconds(-1) },
}))
.Should().Throw().WithMessage("Reconnect.WarningPeriod*");
}
// ── ConnectableProducer ──
[Fact]
public async Task A_producer_that_never_loses_its_connection_sends_as_before()
{
var endpoint = Endpoint();
var producer = new FlakyProducer(endpoint);
await producer.Start();
await producer.Process(null!);
await producer.Process(null!);
producer.Connects.Should().Be(1);
endpoint.HealthStatus.Should().Be(EndpointHealthStatus.Healthy);
}
[Fact]
public async Task While_the_next_attempt_is_not_due_a_send_fails_at_once_saying_when_it_is()
{
var endpoint = Endpoint(new ReconnectOptions { Delay = TimeSpan.FromMinutes(5), MaxDelay = TimeSpan.FromMinutes(5) });
var producer = new FlakyProducer(endpoint);
await producer.Start();
producer.Lose(new IOException("MQRC_CONNECTION_BROKEN"));
producer.Lose(new IOException("MQRC_CONNECTION_BROKEN"));
producer.Losses.Should().Be(1, "what waits on the connection is failed once per loss");
var failure = await FluentActions.Awaiting(() => producer.Process(null!)).Should()
.ThrowAsync();
failure.Which.Message.Should().Contain("next reconnect attempt is due in").And.Contain("MQRC_CONNECTION_BROKEN");
producer.Connects.Should().Be(1);
endpoint.HealthStatus.Should().Be(EndpointHealthStatus.Warning);
}
[Fact]
public async Task Once_due_a_send_reconnects_a_failed_attempt_goes_Critical_and_the_next_one_restores()
{
var endpoint = Endpoint(new ReconnectOptions
{
Delay = TimeSpan.FromMilliseconds(1), MaxDelay = TimeSpan.FromMilliseconds(1),
});
var producer = new FlakyProducer(endpoint);
await producer.Start();
producer.Lose(new IOException("broken"));
producer.FailConnect = new IOException("refused");
await Task.Delay(20);
await FluentActions.Awaiting(() => producer.Process(null!)).Should().ThrowAsync().WithMessage("refused");
endpoint.HealthStatus.Should().Be(EndpointHealthStatus.Critical);
producer.FailConnect = null;
await Task.Delay(20);
await producer.Process(null!);
producer.Connects.Should().Be(3);
producer.Disconnects.Should().Be(3, "each attempt closes what is left first, a failed one also closes after itself");
endpoint.HealthStatus.Should().NotBe(EndpointHealthStatus.Critical);
endpoint.Reconnects.Should().Be(1);
}
[Fact]
public async Task Concurrent_sends_share_one_reconnect_attempt()
{
var endpoint = Endpoint(new ReconnectOptions
{
Delay = TimeSpan.FromMilliseconds(1), MaxDelay = TimeSpan.FromMilliseconds(1),
});
var producer = new FlakyProducer(endpoint);
await producer.Start();
producer.Lose(new IOException("broken"));
await Task.Delay(20);
var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
producer.Gate = gate.Task;
var sends = Enumerable.Range(0, 5).Select(_ => Task.Run(() => producer.Process(null!))).ToArray();
await Task.Delay(50);
gate.SetResult();
await Task.WhenAll(sends);
producer.Connects.Should().Be(2, "one cold start and one reconnect for all five sends");
}
[Fact]
public async Task A_stop_during_a_reconnect_waits_for_it_and_closes_what_it_opened()
{
var endpoint = Endpoint(new ReconnectOptions
{
Delay = TimeSpan.FromMilliseconds(1), MaxDelay = TimeSpan.FromMilliseconds(1),
});
var producer = new FlakyProducer(endpoint);
await producer.Start();
producer.Lose(new IOException("broken"));
await Task.Delay(20);
var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
producer.Gate = gate.Task;
var send = Task.Run(() => producer.Process(null!));
(await Until(() => producer.Connects == 2)).Should().BeTrue("the send is inside its reconnect");
var stop = producer.Stop();
await Task.Delay(100);
stop.IsCompleted.Should().BeFalse("the stop waits for the reconnect in flight");
gate.SetResult();
await stop.WaitAsync(TimeSpan.FromSeconds(5));
await send.WaitAsync(TimeSpan.FromSeconds(5));
producer.Open.Should().Be(0, "the connection the reconnect opened is closed by the stop");
await FluentActions.Awaiting(() => producer.Process(null!)).Should().ThrowAsync();
}
[Fact]
public async Task A_send_that_waited_behind_a_stop_does_not_reconnect()
{
var endpoint = Endpoint(new ReconnectOptions
{
Delay = TimeSpan.FromMilliseconds(1), MaxDelay = TimeSpan.FromMilliseconds(1),
});
var producer = new FlakyProducer(endpoint);
await producer.Start();
producer.Lose(new IOException("broken"));
await Task.Delay(20);
var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
producer.Gate = gate.Task;
var first = Task.Run(() => producer.Process(null!));
(await Until(() => producer.Connects == 2)).Should().BeTrue();
var second = Task.Run(() => producer.Process(null!)); // waits for the reconnect lock
await Task.Delay(50);
var stop = producer.Stop();
gate.SetResult();
await stop.WaitAsync(TimeSpan.FromSeconds(5));
await first.WaitAsync(TimeSpan.FromSeconds(5));
await FluentActions.Awaiting(() => second.WaitAsync(TimeSpan.FromSeconds(5))).Should()
.ThrowAsync().WithMessage("*not been started*");
producer.Connects.Should().Be(2, "no reconnect started behind the stop");
producer.Open.Should().Be(0);
}
private static async Task Until(Func done)
{
for (var i = 0; i < 200 && !done(); i++)
await Task.Delay(25);
return done();
}
[Fact]
public async Task A_stopped_producer_leaves_the_endpoint_health()
{
var endpoint = Endpoint(new ReconnectOptions { Delay = TimeSpan.FromMinutes(5), MaxDelay = TimeSpan.FromMinutes(5) });
var producer = new FlakyProducer(endpoint);
await producer.Start();
producer.Lose(new IOException("broken"));
endpoint.HealthStatus.Should().Be(EndpointHealthStatus.Warning);
await producer.Stop();
endpoint.HealthReason.Should().NotContain("sup:flaky");
}
private sealed class FlakyProducer(IEndpoint endpoint) : ConnectableProducer
{
public int Connects;
public int Disconnects;
public int Losses;
public Exception? FailConnect;
public Task? Gate;
public int Open; // connections opened and not closed yet
protected override IEndpoint ProducerEndpoint => endpoint;
protected override string ProducerName => "sup:flaky";
protected override async Task ConnectAsync(CancellationToken ct)
{
Interlocked.Increment(ref Connects);
if (Gate is { } gate)
await gate;
if (FailConnect is { } failure)
throw failure;
Interlocked.Exchange(ref Open, 1);
}
protected override Task DisconnectAsync(CancellationToken ct)
{
Interlocked.Increment(ref Disconnects);
Interlocked.Exchange(ref Open, 0);
return Task.CompletedTask;
}
protected override void OnConnectionLost(Exception cause) => Interlocked.Increment(ref Losses);
public void Lose(Exception cause) => MarkConnectionLost(cause);
public override async Task Process(IExchange exchange, CancellationToken ct = default)
{
EnsureStarted();
await EnsureConnectedAsync(ct);
}
}
private sealed class SupervisedComponent : ComponentBase
{
public override string Scheme => "sup";
public override IEndpoint CreateEndpoint(EndpointUri uri) => new SupervisedEndpoint(uri, this);
}
private sealed class SupervisedOptions : EndpointOptions
{
public override void Validate() { }
}
private sealed class SupervisedEndpoint(EndpointUri uri, IComponent component)
: EndpointBase(uri, component, new SupervisedOptions())
{
public (EndpointHealthStatus Status, string Reason)? Condition { get; set; }
protected override (EndpointHealthStatus Status, string Reason)? TransportCondition => Condition;
public override IProducer CreateProducer() => throw new NotSupportedException();
public override IConsumer CreateConsumer(IProcessor processor) => throw new NotSupportedException();
}
}