Path: redb-route/redb.Route/Core/ConnectionSupervisor.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route/Core/ConnectionSupervisor.cs
----
using System.Globalization;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Configuration;
namespace redb.Route.Core;
///
/// Watches one connection or link of a consumer or a producer while its route runs. The connector reports what
/// happens (, , ); the supervisor keeps the
/// , the pause before the next attempt (), one log line when the
/// connection is lost and one when it comes back, the count of recoveries, and the health it gives its endpoint
/// (). A connector that restores the connection itself runs ; one whose
/// client restores it only reports.
///
/// Thread-safe. The read members (, , ) take no lock and do no
/// I/O, so health checks read them on every probe.
///
///
public sealed class ConnectionSupervisor
{
private readonly ReconnectOptions _options;
private readonly BackoffSchedule _schedule;
private readonly ILogger? _logger;
private readonly TimeProvider _time;
private readonly object _gate = new();
// Written under _gate; read without it (health probes), each field on its own.
private volatile ConnectionState _state = ConnectionState.Connected;
private volatile string? _lastFailure;
private long _lostAtTicks;
private long _nextAttemptTicks;
private int _attempt;
private long _reconnects;
private TimeSpan _delay;
// Set by the endpoint the supervisor is registered with (EndpointBase.Supervise).
private Func? _mask;
private Action? _recordReconnect;
/// Creates a supervisor.
///
/// What is supervised, for the log lines and the health reason: wmq:ORDERS consumer worker 2,
/// wmq:ORDERS reply receiver.
///
/// The pauses, the bound of one connect and the warning period.
/// Logger for the loss and recovery lines; failed attempts log at debug level.
/// Clock and timers; when null.
public ConnectionSupervisor(string name, ReconnectOptions options, ILogger? logger, TimeProvider? time = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(name);
ArgumentNullException.ThrowIfNull(options);
options.Validate();
Name = name;
_options = options;
_schedule = options.Schedule;
_logger = logger;
_time = time ?? TimeProvider.System;
_delay = _schedule.First;
}
/// What is supervised.
public string Name { get; }
///
/// The state now. A loss reads until an attempt fails, or, with a
/// , until the loss is older than it.
///
public ConnectionState State
{
get
{
var state = _state;
if (state == ConnectionState.Recovering && _options.WarningPeriod > TimeSpan.Zero
&& Outage >= _options.WarningPeriod)
return ConnectionState.Disconnected;
return state;
}
}
/// The message of the loss or of the last failed attempt, masked as the endpoint masks its errors.
public string? LastFailure => _lastFailure;
/// Time until the next attempt is due; zero when one may run now, and while connected.
public TimeSpan DueIn
{
get
{
if (_state == ConnectionState.Connected) return TimeSpan.Zero;
var left = Interlocked.Read(ref _nextAttemptTicks) - _time.GetUtcNow().UtcTicks;
return left > 0 ? TimeSpan.FromTicks(left) : TimeSpan.Zero;
}
}
/// Losses recovered from since the supervisor was created.
public long Reconnects => Interlocked.Read(ref _reconnects);
/// How long the current loss has lasted; zero while connected.
public TimeSpan Outage
{
get
{
if (_state == ConnectionState.Connected) return TimeSpan.Zero;
var lost = Interlocked.Read(ref _lostAtTicks);
var now = _time.GetUtcNow().UtcTicks;
return now > lost ? TimeSpan.FromTicks(now - lost) : TimeSpan.Zero;
}
}
///
/// The health this connection gives its endpoint: null while connected, Warning while
/// , Critical while .
///
public (EndpointHealthStatus Status, string Reason)? Condition
{
get
{
var state = State;
if (state == ConnectionState.Connected) return null;
var outage = FormatDuration(Outage);
var failure = _lastFailure is { Length: > 0 } f ? $": {f}" : string.Empty;
if (state == ConnectionState.Recovering)
return (EndpointHealthStatus.Warning, $"{Name}: connection lost {outage} ago, reconnecting{failure}");
return (EndpointHealthStatus.Critical,
$"{Name}: no connection for {outage}, next attempt in {FormatDuration(DueIn)}{failure}");
}
}
///
/// Receives every change (seam for listeners of connection changes); null sends them nowhere. Its
/// must return at once.
///
internal IConnectionEventSink? EventSink { get; set; }
///
/// Reports that the connection is lost. The first report after logs one
/// warning, records the error on the endpoint and starts the schedule: the first attempt is due
/// from now. Further reports while lost only replace .
///
///
/// true for the report that changed the state, so the caller fails the work that waits on the connection
/// once and starts one reconnect.
///
public bool Lost(Exception cause)
{
ArgumentNullException.ThrowIfNull(cause);
ConnectionEvent change;
lock (_gate)
{
_lastFailure = Mask(cause.Message);
if (_state != ConnectionState.Connected)
return false;
var now = _time.GetUtcNow().UtcTicks;
_delay = _schedule.First;
_attempt = 0;
Interlocked.Exchange(ref _lostAtTicks, now);
Interlocked.Exchange(ref _nextAttemptTicks, now + _delay.Ticks);
_state = ConnectionState.Recovering;
change = Change(ConnectionEventKind.Lost, cause, _delay);
// Posted under the gate: the events of one connection reach the sink in the order of the changes.
EventSink?.Post(change);
}
_logger?.LogWarning("{Connection} lost its connection: {Reason}; reconnecting", Name, change.ErrorMessage);
return true;
}
///
/// Reports that an attempt failed: the next one is due after a pause grown by ,
/// up to , and the state is (with a
/// warning period, once the loss is older than it). Logged at debug level, so a long outage writes two lines.
/// Ignored while connected.
///
public void Failed(Exception cause)
{
ArgumentNullException.ThrowIfNull(cause);
ConnectionEvent change;
TimeSpan delay;
int attempt;
lock (_gate)
{
if (_state == ConnectionState.Connected)
return;
_lastFailure = Mask(cause.Message);
attempt = ++_attempt;
// The pause before the first attempt was Delay (set by Lost); each failure grows it: 1, 2, 4 ... MaxDelay.
delay = _delay = _schedule.Next(_delay);
Interlocked.Exchange(ref _nextAttemptTicks, _time.GetUtcNow().UtcTicks + delay.Ticks);
if (_options.WarningPeriod <= TimeSpan.Zero || Outage >= _options.WarningPeriod)
_state = ConnectionState.Disconnected;
change = Change(ConnectionEventKind.AttemptFailed, cause, delay);
EventSink?.Post(change);
}
_logger?.LogDebug("{Connection} reconnect attempt {Attempt} failed: {Reason}; next attempt in {Delay}",
Name, attempt, change.ErrorMessage, FormatDuration(delay));
}
///
/// Reports that the connection is back: logs one information line with the length of the outage, counts the
/// recovery and resets the schedule. Ignored while connected.
///
public void Restored()
{
ConnectionEvent change;
TimeSpan outage;
lock (_gate)
{
if (_state == ConnectionState.Connected)
return;
outage = Outage;
Interlocked.Increment(ref _reconnects);
_state = ConnectionState.Connected;
_lastFailure = null;
_attempt = 0;
_delay = _schedule.First;
change = new ConnectionEvent(ConnectionEventKind.Restored, Name, ConnectionState.Connected, null, 0, null,
outage, Reconnects, _time.GetUtcNow());
EventSink?.Post(change);
}
_recordReconnect?.Invoke();
_logger?.LogInformation("{Connection} reconnected after {Outage}", Name, FormatDuration(outage));
}
///
/// Runs one connect bounded by . A connect that has not finished by then
/// fails with a ; if it still succeeds later, its result goes to
/// , which closes it. Errors of the connect propagate; the caller reports
/// (or lets do it).
///
public async Task AttemptAsync(Func> connect, Action discardLate, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(connect);
ArgumentNullException.ThrowIfNull(discardLate);
var connecting = connect(ct);
try
{
return await connecting.WaitAsync(_options.AttemptTimeout, _time, ct).ConfigureAwait(false);
}
catch (Exception ex) when (!connecting.IsCompleted)
{
_ = connecting.ContinueWith(t =>
{
try { discardLate(t.Result); }
catch (Exception closeEx) { _logger?.LogDebug(closeEx, "{Connection}: error closing a connect that was given up", Name); }
}, CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Default);
if (ex is TimeoutException)
throw new TimeoutException(
$"{Name}: the connect did not finish within {FormatDuration(_options.AttemptTimeout)} (Reconnect.AttemptTimeout).", ex);
throw;
}
}
///
/// The reconnect loop of a connector that restores its connection itself: waits until the next attempt is due, runs
/// , reports or , and repeats until an attempt
/// succeeds. A connect inside that can hang goes through .
/// Call it after .
///
/// true once restored; false when stopped it (the owner is stopping).
public async Task ReconnectAsync(Func reconnect, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(reconnect);
while (true)
{
try { await Task.Delay(DueIn, _time, ct).ConfigureAwait(false); }
catch (OperationCanceledException) { return false; }
try
{
await reconnect(ct).ConfigureAwait(false);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
return false;
}
catch (Exception ex)
{
Failed(ex);
continue;
}
Restored();
return true;
}
}
///
/// Links the supervisor to the endpoint it reports to: masking and the reconnect count. A loss is not counted in the
/// endpoint's errors: it shows in while it lasts, so health is Healthy again at recovery and the
/// error rate stays the rate of failed messages.
///
internal void AttachTo(Func mask, Action recordReconnect)
{
_mask = mask;
_recordReconnect = recordReconnect;
}
private string Mask(string text) => _mask is { } mask ? mask(text) : text;
private ConnectionEvent Change(ConnectionEventKind kind, Exception cause, TimeSpan nextDelay) =>
new(kind, Name, State, cause, _attempt, nextDelay, Outage, Reconnects, _time.GetUtcNow()) { ErrorMessage = _lastFailure };
/// A duration for logs, health reasons and errors, in the invariant culture ("1.5 s" under any locale).
internal static string FormatDuration(TimeSpan duration) =>
duration.TotalSeconds < 1 ? string.Create(CultureInfo.InvariantCulture, $"{duration.TotalMilliseconds:0} ms")
: duration.TotalMinutes < 1 ? string.Create(CultureInfo.InvariantCulture, $"{duration.TotalSeconds:0.#} s")
: duration.TotalHours < 1 ? string.Create(CultureInfo.InvariantCulture, $"{duration.TotalMinutes:0.#} min")
: string.Create(CultureInfo.InvariantCulture, $"{duration.TotalHours:0.#} h");
}