From f55589f7823b32b9b38c3e3a965a5422e53a753f Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 09:38:56 -0500 Subject: [PATCH] perf(dashboard): run health checks on their own 10s cadence off the snapshot tick (DSH-003, #256) --- .../Dashboard/DashboardSnapshotService.cs | 73 ++++++++++++++++--- .../DashboardSnapshotServiceTests.cs | 60 ++++++++++++++- 2 files changed, 122 insertions(+), 11 deletions(-) diff --git a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardSnapshotService.cs b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardSnapshotService.cs index 1b1be7dc..5a2d15d6 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardSnapshotService.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardSnapshotService.cs @@ -23,8 +23,20 @@ public sealed class DashboardSnapshotService : IDashboardSnapshotService /// internal const string UnknownStatus = "Unknown"; - /// Upper bound on one health evaluation, so a hung check cannot stall the snapshot tick. - private static readonly TimeSpan GatewayStatusRefreshTimeout = TimeSpan.FromSeconds(2); + /// + /// Upper bound on one health evaluation. Longer than the slowest per-check timeout + /// (Galaxy SQL, 5 s) so a slow check reports its own Unhealthy result instead of + /// being cancelled into . The evaluation runs off the snapshot + /// tick, so the bound no longer affects snapshot cadence. + /// + private static readonly TimeSpan GatewayStatusRefreshTimeout = TimeSpan.FromSeconds(8); + + /// + /// 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. + /// + private static readonly TimeSpan GatewayStatusRefreshInterval = TimeSpan.FromSeconds(10); /// /// 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 _apiKeySummaries = Array.Empty(); private long _apiKeySummariesRefreshedAtTicks = NeverRefreshedTicks; // The effective configuration is built from IOptions and is startup-static: @@ -80,7 +93,7 @@ public sealed class DashboardSnapshotService : IDashboardSnapshotService /// Optional logger for the dashboard snapshot service. /// /// The gateway's registered health checks. - /// 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 . /// 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; + } + /// - /// 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 + /// . 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. + /// + 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."); + } + }); + } + + /// + /// Evaluates the registered health checks and caches the aggregate status /// for , which is synchronous and also serves page seeds - /// and hub connects between ticks. One evaluation per tick, not per - /// 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 + /// is reused: the checks include an auth-store + /// query and a Galaxy SQL round trip. /// /// Token to cancel the evaluation. /// A task that represents the asynchronous operation. 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 diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/DashboardSnapshotServiceTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/DashboardSnapshotServiceTests.cs index 23d016e1..014e7aac 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/DashboardSnapshotServiceTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/DashboardSnapshotServiceTests.cs @@ -85,6 +85,54 @@ public sealed class DashboardSnapshotServiceTests Assert.Equal(1, health.CheckCount); } + /// + /// 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. + /// + /// A task that represents the asynchronous operation. + [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 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(); + } + /// A health evaluation that throws is reported as Unknown, never as Healthy. /// A task that represents the asynchronous operation. [Fact] @@ -756,11 +804,14 @@ public sealed class DashboardSnapshotServiceTests /// Gets or sets a value indicating whether the evaluation throws. public bool Throw { get; set; } + /// Gets or sets a gate the evaluation awaits before reporting, to model a slow check. + public TaskCompletionSource? Gate { get; set; } + /// Gets the number of evaluations requested. public int CheckCount => Volatile.Read(ref _checkCount); /// - public override Task CheckHealthAsync( + public override async Task CheckHealthAsync( Func? 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 { ["stub"] = new(status, null, TimeSpan.Zero, null, null),