Path: redb-route/tests/redb.Route.Tests/Core/ConnectionSupervisorTests.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/ConnectionSupervisorTests.cs
----
using AwesomeAssertions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Time.Testing;
using redb.Route.Abstractions;
using redb.Route.Configuration;
using redb.Route.Core;
namespace redb.Route.Tests.Core;
///
/// : the state of one supervised connection, the pauses between reconnect attempts, the
/// bound of one connect, the log lines and the health it gives its endpoint. Time is a .
///
public sealed class ConnectionSupervisorTests
{
private static readonly DateTimeOffset Start = new(2026, 12, 5, 10, 0, 0, TimeSpan.Zero);
private readonly FakeTimeProvider _time = new(Start);
private readonly CapturingLogger _log = new();
private ConnectionSupervisor Create(ReconnectOptions? options = null) =>
new("wmq:ORDERS consumer worker 1", options ?? new ReconnectOptions(), _log, _time);
[Fact]
public void Pauses_start_at_one_second_double_after_each_failure_and_stop_at_thirty()
{
var supervisor = Create();
supervisor.Lost(new IOException("broken")).Should().BeTrue();
supervisor.DueIn.Should().Be(TimeSpan.FromSeconds(1));
var seen = new List();
for (var i = 0; i < 7; i++)
{
supervisor.Failed(new IOException("still down"));
seen.Add(supervisor.DueIn);
}
seen.Select(d => d.TotalSeconds).Should().Equal(2, 4, 8, 16, 30, 30, 30);
}
[Fact]
public void DueIn_counts_down_with_the_clock()
{
var supervisor = Create();
supervisor.Lost(new IOException("broken"));
_time.Advance(TimeSpan.FromMilliseconds(400));
supervisor.DueIn.Should().Be(TimeSpan.FromMilliseconds(600));
_time.Advance(TimeSpan.FromSeconds(5));
supervisor.DueIn.Should().Be(TimeSpan.Zero);
}
[Fact]
public void Restored_resets_the_schedule_for_the_next_loss()
{
var supervisor = Create();
supervisor.Lost(new IOException("first"));
supervisor.Failed(new IOException("down"));
supervisor.Failed(new IOException("down"));
supervisor.Restored();
supervisor.Lost(new IOException("second")).Should().BeTrue();
supervisor.DueIn.Should().Be(TimeSpan.FromSeconds(1));
supervisor.Failed(new IOException("down"));
supervisor.DueIn.Should().Be(TimeSpan.FromSeconds(2));
}
[Fact]
public void A_loss_is_Warning_until_an_attempt_fails_then_Critical_then_nothing_once_restored()
{
var supervisor = Create();
supervisor.State.Should().Be(ConnectionState.Connected);
supervisor.Condition.Should().BeNull();
supervisor.Lost(new IOException("MQRC_CONNECTION_BROKEN"));
supervisor.State.Should().Be(ConnectionState.Recovering);
supervisor.Condition!.Value.Status.Should().Be(EndpointHealthStatus.Warning);
supervisor.Condition!.Value.Reason.Should().Contain("wmq:ORDERS consumer worker 1").And.Contain("MQRC_CONNECTION_BROKEN");
supervisor.Failed(new IOException("connect refused"));
supervisor.State.Should().Be(ConnectionState.Disconnected);
supervisor.Condition!.Value.Status.Should().Be(EndpointHealthStatus.Critical);
supervisor.Condition!.Value.Reason.Should().Contain("connect refused").And.Contain("next attempt in 2 s");
supervisor.Restored();
supervisor.State.Should().Be(ConnectionState.Connected);
supervisor.Condition.Should().BeNull();
supervisor.LastFailure.Should().BeNull();
supervisor.Reconnects.Should().Be(1);
}
[Fact]
public void With_a_warning_period_a_loss_stays_Warning_until_the_period_has_passed()
{
var supervisor = Create(new ReconnectOptions { WarningPeriod = TimeSpan.FromSeconds(30) });
supervisor.Lost(new IOException("blip"));
supervisor.Failed(new IOException("still down"));
supervisor.State.Should().Be(ConnectionState.Recovering, "a failed attempt inside the warning period is not Critical yet");
_time.Advance(TimeSpan.FromSeconds(30));
supervisor.State.Should().Be(ConnectionState.Disconnected, "the loss outlived the warning period");
supervisor.Condition!.Value.Status.Should().Be(EndpointHealthStatus.Critical);
}
[Fact]
public void One_warning_per_loss_and_one_information_per_recovery_however_many_reports()
{
var supervisor = Create();
supervisor.Lost(new IOException("broken")).Should().BeTrue();
supervisor.Lost(new IOException("broken again")).Should().BeFalse("the loss is already known");
for (var i = 0; i < 5; i++)
supervisor.Failed(new IOException("down"));
supervisor.Restored();
supervisor.Restored();
_log.Entries.Count(e => e.Level == LogLevel.Warning).Should().Be(1);
_log.Entries.Count(e => e.Level == LogLevel.Information).Should().Be(1);
_log.Entries.Single(e => e.Level == LogLevel.Information).Text.Should().Contain("reconnected after");
_log.Entries.Count(e => e.Level >= LogLevel.Error).Should().Be(0);
supervisor.Reconnects.Should().Be(1);
}
[Fact]
public void A_repeated_loss_report_replaces_the_last_failure()
{
var supervisor = Create();
supervisor.Lost(new IOException("first"));
supervisor.Lost(new IOException("second"));
supervisor.LastFailure.Should().Be("second");
}
[Fact]
public void Failed_and_Restored_are_ignored_while_connected()
{
var supervisor = Create();
supervisor.Failed(new IOException("stray"));
supervisor.Restored();
supervisor.State.Should().Be(ConnectionState.Connected);
supervisor.Reconnects.Should().Be(0);
_log.Entries.Should().BeEmpty();
}
[Fact]
public async Task A_connect_that_does_not_finish_in_time_fails_and_its_late_result_is_closed()
{
var supervisor = Create(new ReconnectOptions { AttemptTimeout = TimeSpan.FromSeconds(30) });
var connect = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var closed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var attempt = supervisor.AttemptAsync(_ => connect.Task, closed.SetResult, CancellationToken.None);
_time.Advance(TimeSpan.FromSeconds(30));
var failure = await FluentActions.Awaiting(() => attempt).Should().ThrowAsync();
failure.Which.Message.Should().Contain("Reconnect.AttemptTimeout");
connect.SetResult("late connection");
(await closed.Task.WaitAsync(TimeSpan.FromSeconds(5))).Should().Be("late connection");
}
[Fact]
public async Task A_connect_in_time_returns_its_result()
{
var supervisor = Create();
var result = await supervisor.AttemptAsync(_ => Task.FromResult(42), _ => throw new InvalidOperationException(),
CancellationToken.None);
result.Should().Be(42);
}
[Fact]
public async Task A_cancelled_attempt_throws_cancellation()
{
var supervisor = Create();
using var cts = new CancellationTokenSource();
var never = new TaskCompletionSource();
var attempt = supervisor.AttemptAsync(_ => never.Task, _ => { }, cts.Token);
cts.Cancel();
await FluentActions.Awaiting(() => attempt).Should().ThrowAsync();
}
[Fact]
public async Task The_reconnect_loop_waits_each_pause_retries_and_reports_the_recovery()
{
var supervisor = Create();
supervisor.Lost(new IOException("broken"));
var calls = 0;
var loop = supervisor.ReconnectAsync(_ =>
{
calls++;
return calls < 3 ? Task.FromException(new IOException($"refused {calls}")) : Task.CompletedTask;
}, CancellationToken.None);
await AdvanceUntil(() => calls == 1, TimeSpan.FromSeconds(1));
supervisor.State.Should().Be(ConnectionState.Disconnected);
supervisor.DueIn.Should().Be(TimeSpan.FromSeconds(2));
await AdvanceUntil(() => calls == 2, TimeSpan.FromSeconds(2));
await AdvanceUntil(() => calls == 3, TimeSpan.FromSeconds(4));
(await loop.WaitAsync(TimeSpan.FromSeconds(5))).Should().BeTrue();
supervisor.State.Should().Be(ConnectionState.Connected);
supervisor.Reconnects.Should().Be(1);
}
[Fact]
public async Task The_reconnect_loop_ends_with_false_when_its_owner_stops()
{
var supervisor = Create();
supervisor.Lost(new IOException("broken"));
using var cts = new CancellationTokenSource();
var loop = supervisor.ReconnectAsync(_ => Task.FromException(new IOException("down")), cts.Token);
cts.Cancel();
(await loop.WaitAsync(TimeSpan.FromSeconds(5))).Should().BeFalse();
supervisor.State.Should().NotBe(ConnectionState.Connected);
}
[Fact]
public void Every_change_goes_to_the_event_sink_in_order()
{
var supervisor = Create();
var sink = new ListSink();
supervisor.EventSink = sink;
supervisor.Lost(new IOException("broken"));
_time.Advance(TimeSpan.FromSeconds(1));
supervisor.Failed(new IOException("refused"));
_time.Advance(TimeSpan.FromSeconds(2));
supervisor.Restored();
sink.Changes.Select(c => c.Kind).Should().Equal(
ConnectionEventKind.Lost, ConnectionEventKind.AttemptFailed, ConnectionEventKind.Restored);
var failed = sink.Changes[1];
failed.Attempt.Should().Be(1);
failed.NextDelay.Should().Be(TimeSpan.FromSeconds(2));
failed.Outage.Should().Be(TimeSpan.FromSeconds(1));
failed.State.Should().Be(ConnectionState.Disconnected);
failed.Connection.Should().Be("wmq:ORDERS consumer worker 1");
var restored = sink.Changes[2];
restored.Outage.Should().Be(TimeSpan.FromSeconds(3));
restored.Reconnects.Should().Be(1);
restored.Error.Should().BeNull();
}
[Fact]
public void Durations_in_the_health_reason_use_the_invariant_culture()
{
var saved = System.Globalization.CultureInfo.CurrentCulture;
System.Globalization.CultureInfo.CurrentCulture = new System.Globalization.CultureInfo("ru-RU");
try
{
var supervisor = Create();
supervisor.Lost(new IOException("broken"));
supervisor.Failed(new IOException("refused"));
_time.Advance(TimeSpan.FromMilliseconds(500));
supervisor.Condition!.Value.Reason.Should().Contain("next attempt in 1.5 s");
}
finally
{
System.Globalization.CultureInfo.CurrentCulture = saved;
}
}
[Fact]
public async Task Events_of_one_connection_reach_the_sink_in_the_order_of_the_changes_under_concurrent_reports()
{
var supervisor = Create();
var sink = new ListSink();
supervisor.EventSink = sink;
using var start = new ManualResetEventSlim();
var reporters = Enumerable.Range(0, 4).Select(t => Task.Run(() =>
{
start.Wait();
for (var i = 0; i < 2000; i++)
{
switch ((i + t) % 3)
{
case 0: supervisor.Lost(new IOException("broken")); break;
case 1: supervisor.Failed(new IOException("refused")); break;
default: supervisor.Restored(); break;
}
}
})).ToArray();
start.Set();
await Task.WhenAll(reporters);
// A valid sequence per outage: Lost, then AttemptFailed with attempts 1, 2, 3 ..., then Restored.
var expectedAttempt = 0;
var connected = true;
long reconnects = 0;
foreach (var change in sink.Changes)
{
switch (change.Kind)
{
case ConnectionEventKind.Lost:
connected.Should().BeTrue("a loss follows a connected state");
connected = false;
expectedAttempt = 0;
break;
case ConnectionEventKind.AttemptFailed:
connected.Should().BeFalse("a failed attempt belongs to an outage");
change.Attempt.Should().Be(++expectedAttempt);
break;
default:
connected.Should().BeFalse("a recovery ends an outage");
connected = true;
change.Reconnects.Should().Be(++reconnects);
break;
}
}
sink.Changes.Should().NotBeEmpty();
}
[Theory]
[InlineData(0, 2, 30)]
[InlineData(1, 0.5, 30)]
[InlineData(5, 2, 1)]
public void Invalid_options_are_refused(double delaySeconds, double multiplier, double maxSeconds)
{
var options = new ReconnectOptions
{
Delay = TimeSpan.FromSeconds(delaySeconds),
Multiplier = multiplier,
MaxDelay = TimeSpan.FromSeconds(maxSeconds),
};
FluentActions.Invoking(() => Create(options)).Should().Throw()
.WithMessage("Reconnect.*");
}
[Fact]
public void A_non_positive_attempt_timeout_is_refused()
{
FluentActions.Invoking(() => Create(new ReconnectOptions { AttemptTimeout = TimeSpan.Zero }))
.Should().Throw().WithMessage("Reconnect.AttemptTimeout*");
}
private async Task AdvanceUntil(Func condition, TimeSpan step)
{
// The loop runs on the thread pool: let it reach its delay before the clock moves, then wait for the attempt.
for (var i = 0; i < 200 && !condition(); i++)
{
await Task.Delay(10);
if (i % 5 == 4) _time.Advance(step);
}
condition().Should().BeTrue();
}
private sealed class ListSink : IConnectionEventSink
{
public List Changes { get; } = [];
public void Post(ConnectionEvent change)
{
lock (Changes)
Changes.Add(change);
}
}
internal sealed class CapturingLogger : ILogger
{
public List<(LogLevel Level, string Text)> Entries { get; } = [];
public IDisposable? BeginScope(TState state) where TState : notnull => null;
public bool IsEnabled(LogLevel logLevel) => true;
public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception,
Func formatter)
{
lock (Entries)
Entries.Add((logLevel, formatter(state, exception)));
}
}
}