perf(dashboard): run health checks on their own 10s cadence off the snapshot tick (DSH-003, #256)

This commit is contained in:
Joseph Doherty
2026-12-03 09:38:56 -05:00
parent d12fd4f5a0
commit f55589f782
2 changed files with 122 additions and 11 deletions
@@ -23,8 +23,20 @@ public sealed class DashboardSnapshotService : IDashboardSnapshotService
/// </summary>
internal const string UnknownStatus = "Unknown";
/// <summary>Upper bound on one health evaluation, so a hung check cannot stall the snapshot tick.</summary>
private static readonly TimeSpan GatewayStatusRefreshTimeout = TimeSpan.FromSeconds(2);
/// <summary>
/// Upper bound on one health evaluation. Longer than the slowest per-check timeout
/// (Galaxy SQL, 5 s) so a slow check reports its own <c>Unhealthy</c> result instead of
/// being cancelled into <see cref="UnknownStatus"/>. The evaluation runs off the snapshot
/// tick, so the bound no longer affects snapshot cadence.
/// </summary>
private static readonly TimeSpan GatewayStatusRefreshTimeout = TimeSpan.FromSeconds(8);
/// <summary>
/// Minimum spacing between health evaluations. The checks open a SQLite connection and
/// round-trip to the Galaxy SQL server, so running them on every ~1s snapshot tick for as
/// long as a dashboard tab is open is a steady 1-2 Hz ping against both.
/// </summary>
private static readonly TimeSpan GatewayStatusRefreshInterval = TimeSpan.FromSeconds(10);
/// <summary>
/// Minimum spacing between API key list reads. The list is a SQLite query whose
@@ -53,6 +65,7 @@ public sealed class DashboardSnapshotService : IDashboardSnapshotService
private readonly SemaphoreSlim _apiKeySummaryRefreshGate = new(1, 1);
private readonly SemaphoreSlim _gatewayStatusRefreshGate = new(1, 1);
private string _gatewayStatus = UnknownStatus;
private long _gatewayStatusRefreshedAtTicks = NeverRefreshedTicks;
private IReadOnlyList<DashboardApiKeySummary> _apiKeySummaries = Array.Empty<DashboardApiKeySummary>();
private long _apiKeySummariesRefreshedAtTicks = NeverRefreshedTicks;
// The effective configuration is built from IOptions<GatewayOptions> and is startup-static:
@@ -80,7 +93,7 @@ public sealed class DashboardSnapshotService : IDashboardSnapshotService
/// <param name="logger">Optional logger for the dashboard snapshot service.</param>
/// <param name="healthCheckService">
/// The gateway's registered health checks. <see cref="DashboardSnapshot.GatewayStatus"/>
/// is the aggregate status of one evaluation per snapshot tick; without it the
/// is the aggregate status of the latest evaluation (refreshed every 10 s off the tick); without it the
/// status stays <see cref="UnknownStatus"/>.
/// </param>
public DashboardSnapshotService(
@@ -191,6 +204,8 @@ public sealed class DashboardSnapshotService : IDashboardSnapshotService
}
await RefreshApiKeySummariesAsync(cancellationToken).ConfigureAwait(false);
// The first snapshot waits for an evaluation so it never shows a status nobody checked.
await RefreshGatewayStatusAsync(cancellationToken).ConfigureAwait(false);
yield return GetSnapshot();
@@ -213,23 +228,55 @@ public sealed class DashboardSnapshotService : IDashboardSnapshotService
}
await RefreshApiKeySummariesAsync(cancellationToken).ConfigureAwait(false);
await RefreshGatewayStatusAsync(cancellationToken).ConfigureAwait(false);
StartGatewayStatusRefreshIfDue();
yield return GetSnapshot();
}
}
private bool IsGatewayStatusDue()
{
long refreshedAt = Volatile.Read(ref _gatewayStatusRefreshedAtTicks);
return refreshedAt == NeverRefreshedTicks
|| _timeProvider.GetUtcNow().UtcTicks - refreshedAt >= GatewayStatusRefreshInterval.Ticks;
}
/// <summary>
/// Evaluates the registered health checks once and caches the aggregate status
/// Starts a health evaluation in the background when the cached status is older than
/// <see cref="GatewayStatusRefreshInterval"/>. The snapshot tick reads the cached value and
/// never waits on a check, so a slow or unreachable Galaxy SQL server cannot slow the cadence.
/// </summary>
private void StartGatewayStatusRefreshIfDue()
{
if (_healthCheckService is null || _gatewayStatusRefreshGate.CurrentCount == 0 || !IsGatewayStatusDue())
{
return;
}
_ = Task.Run(async () =>
{
try
{
await RefreshGatewayStatusAsync(CancellationToken.None).ConfigureAwait(false);
}
catch (Exception exception)
{
_logger.LogDebug(exception, "Dashboard background health refresh failed.");
}
});
}
/// <summary>
/// Evaluates the registered health checks and caches the aggregate status
/// for <see cref="GetSnapshot"/>, which is synchronous and also serves page seeds
/// and hub connects between ticks. One evaluation per tick, not per
/// <see cref="GetSnapshot"/> call: the checks include an auth-store query, and the
/// tick is already the cadence at which the dashboard refreshes.
/// and hub connects between ticks. A cached status younger than
/// <see cref="GatewayStatusRefreshInterval"/> is reused: the checks include an auth-store
/// query and a Galaxy SQL round trip.
/// </summary>
/// <param name="cancellationToken">Token to cancel the evaluation.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public async Task RefreshGatewayStatusAsync(CancellationToken cancellationToken)
{
if (_healthCheckService is null)
if (_healthCheckService is null || !IsGatewayStatusDue())
{
return;
}
@@ -243,10 +290,17 @@ public sealed class DashboardSnapshotService : IDashboardSnapshotService
try
{
// An evaluation that finished while this call waited on the gate already refreshed the cache.
if (!IsGatewayStatusDue())
{
return;
}
using CancellationTokenSource timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeout.CancelAfter(GatewayStatusRefreshTimeout);
HealthReport report = await _healthCheckService.CheckHealthAsync(timeout.Token).ConfigureAwait(false);
Volatile.Write(ref _gatewayStatus, report.Status.ToString());
Volatile.Write(ref _gatewayStatusRefreshedAtTicks, _timeProvider.GetUtcNow().UtcTicks);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
@@ -256,6 +310,7 @@ public sealed class DashboardSnapshotService : IDashboardSnapshotService
{
// A health evaluation that cannot complete is not evidence of health.
Volatile.Write(ref _gatewayStatus, UnknownStatus);
Volatile.Write(ref _gatewayStatusRefreshedAtTicks, _timeProvider.GetUtcNow().UtcTicks);
_logger.LogDebug(exception, "Dashboard gateway health evaluation failed.");
}
finally
@@ -85,6 +85,54 @@ public sealed class DashboardSnapshotServiceTests
Assert.Equal(1, health.CheckCount);
}
/// <summary>
/// DSH-003: health checks run on their own cadence, off the snapshot tick. A slow check does not
/// slow the snapshots, and ticks inside the refresh interval do not re-run the checks.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task WatchSnapshotsAsync_WhenHealthCheckIsSlow_KeepsTickingAndEvaluatesOncePerInterval()
{
using GatewayMetrics metrics = new();
StubHealthCheckService health = new(HealthStatus.Healthy);
FakeTimeProvider timeProvider = new(DateTimeOffset.Parse("2026-08-15T00:00:00Z", CultureInfo.InvariantCulture));
DashboardSnapshotService service = CreateService(
new SessionRegistry(),
metrics,
new GatewayOptions { Dashboard = new DashboardOptions { SnapshotIntervalMilliseconds = 1000 } },
timeProvider: timeProvider,
healthCheckService: health);
using CancellationTokenSource cancellation = new(TimeSpan.FromSeconds(30));
await using IAsyncEnumerator<DashboardSnapshot> enumerator = service
.WatchSnapshotsAsync(cancellation.Token)
.GetAsyncEnumerator(cancellation.Token);
Assert.True(await enumerator.MoveNextAsync());
Assert.Equal(1, health.CheckCount);
// Ticks inside the refresh interval reuse the cached status.
await NextSnapshotAsync(enumerator, timeProvider, TimeSpan.FromSeconds(1));
await NextSnapshotAsync(enumerator, timeProvider, TimeSpan.FromSeconds(1));
Assert.Equal(1, health.CheckCount);
// Past the interval the next evaluation is slow; the tick still yields, with the cached value.
health.Gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
DashboardSnapshot during = await NextSnapshotAsync(enumerator, timeProvider, TimeSpan.FromSeconds(20));
Assert.Equal(HealthStatus.Healthy.ToString(), during.GatewayStatus);
DashboardSnapshot stillTicking = await NextSnapshotAsync(enumerator, timeProvider, TimeSpan.FromSeconds(1));
Assert.Equal(HealthStatus.Healthy.ToString(), stillTicking.GatewayStatus);
// The evaluation starts on a background task, so it can land just after the tick yields.
for (int i = 0; i < 500 && health.CheckCount < 2; i++)
{
await Task.Delay(10);
}
Assert.Equal(2, health.CheckCount);
health.Gate.SetResult();
}
/// <summary>A health evaluation that throws is reported as Unknown, never as Healthy.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
@@ -756,11 +804,14 @@ public sealed class DashboardSnapshotServiceTests
/// <summary>Gets or sets a value indicating whether the evaluation throws.</summary>
public bool Throw { get; set; }
/// <summary>Gets or sets a gate the evaluation awaits before reporting, to model a slow check.</summary>
public TaskCompletionSource? Gate { get; set; }
/// <summary>Gets the number of evaluations requested.</summary>
public int CheckCount => Volatile.Read(ref _checkCount);
/// <inheritdoc />
public override Task<HealthReport> CheckHealthAsync(
public override async Task<HealthReport> CheckHealthAsync(
Func<HealthCheckRegistration, bool>? predicate,
CancellationToken cancellationToken = default)
{
@@ -770,7 +821,12 @@ public sealed class DashboardSnapshotServiceTests
throw new InvalidOperationException("health evaluation failed");
}
return Task.FromResult(new HealthReport(
if (Gate is { } gate)
{
await gate.Task.WaitAsync(cancellationToken);
}
return (new HealthReport(
new Dictionary<string, HealthReportEntry>
{
["stub"] = new(status, null, TimeSpan.Zero, null, null),