fix(dashboard): derive gateway status from health checks; send config once per hub connection

SEC-27: DashboardSnapshot.GatewayStatus was hardcoded Healthy. It is now the
aggregate HealthCheckService status, evaluated once per snapshot tick (2s
bound, zero-wait gate) and cached for GetSnapshot; Unknown before the first
evaluation, on failure, or without a health service.

The startup-static EffectiveGatewayConfiguration is JsonIgnore'd on the
snapshot, so /hubs/snapshot ticks carry only volatile state. The hub sends it
once per connection (ConfigurationUpdated) and serves GetConfiguration().
Snapshot broadcasts are time-bounded (1s) so one slow client cannot delay
ticks. StatusBadge maps Unhealthy to Bad.
This commit is contained in:
Joseph Doherty
2026-10-22 06:18:02 -04:00
parent 3688fa19e6
commit 6733519ae5
7 changed files with 291 additions and 19 deletions
@@ -138,6 +138,35 @@ public sealed class DashboardSnapshotPublisherTests
Assert.True(snapshotService.PullCount >= 1);
}
/// <summary>
/// A broadcast that never completes — one remote client whose transport is wedged —
/// is abandoned at the send timeout, so later ticks still go out instead of every
/// viewer waiting on the slowest one.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task ExecuteAsync_WhenABroadcastNeverCompletes_LaterTicksStillGoOut()
{
CountingSnapshotService snapshotService = new();
RecordingHubContext hubContext = new();
hubContext.Proxy.StallFirstSend = true;
DashboardSnapshotPublisher publisher = new(
snapshotService,
hubContext,
ConnectedCounter(),
NullLogger<DashboardSnapshotPublisher>.Instance,
TimeSpan.FromMilliseconds(50),
IdlePollInterval,
sendTimeout: TimeSpan.FromMilliseconds(50));
using CancellationTokenSource cts = new();
await publisher.StartAsync(cts.Token).WaitAsync(TestTimeout);
await WaitUntilAsync(() => hubContext.SendCount >= 3);
await cts.CancelAsync();
await publisher.StopAsync(CancellationToken.None);
}
/// <summary>Creates a connection counter that already has one live viewer.</summary>
/// <returns>A counter reporting a single connection.</returns>
private static DashboardSnapshotHubConnectionCounter ConnectedCounter()
@@ -271,6 +300,9 @@ public sealed class DashboardSnapshotPublisherTests
/// <summary>Gets the group manager.</summary>
public IGroupManager Groups { get; } = new NoopGroupManager();
/// <summary>Gets the recording proxy every client lookup resolves to.</summary>
public RecordingClientProxy Proxy => _clients.AllProxy;
/// <summary>Gets the number of send calls recorded.</summary>
public int SendCount => _clients.AllProxy.SendCount;
}
@@ -329,6 +361,12 @@ public sealed class DashboardSnapshotPublisherTests
{
private int _sendCount;
/// <summary>
/// Gets or sets a value indicating whether the first send never completes and
/// ignores its cancellation token — a wedged client transport.
/// </summary>
public bool StallFirstSend { get; set; }
/// <summary>Gets the number of send calls recorded.</summary>
public int SendCount => Volatile.Read(ref _sendCount);
@@ -339,8 +377,8 @@ public sealed class DashboardSnapshotPublisherTests
/// <returns>A task that represents the asynchronous operation.</returns>
public Task SendCoreAsync(string method, object?[] args, CancellationToken cancellationToken = default)
{
Interlocked.Increment(ref _sendCount);
return Task.CompletedTask;
int count = Interlocked.Increment(ref _sendCount);
return StallFirstSend && count == 1 ? new TaskCompletionSource().Task : Task.CompletedTask;
}
}
@@ -1,4 +1,6 @@
using System.Globalization;
using System.Text.Json;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Time.Testing;
using ZB.MOM.WW.Auth.Abstractions.ApiKeys;
@@ -18,7 +20,8 @@ namespace ZB.MOM.WW.MxGateway.Tests.Gateway.Dashboard;
public sealed class DashboardSnapshotServiceTests
{
/// <summary>
/// Verifies snapshot returns empty collections and healthy status when registry is empty.
/// Verifies snapshot returns empty collections when registry is empty, and an
/// <c>Unknown</c> status when no health check service is available to evaluate.
/// </summary>
[Fact]
public void GetSnapshot_WhenRegistryEmpty_ReturnsEmptyOperationalState()
@@ -32,10 +35,76 @@ public sealed class DashboardSnapshotServiceTests
Assert.Empty(snapshot.Workers);
Assert.Empty(snapshot.Faults);
Assert.Contains(snapshot.Metrics, metric => metric.Name == "mxgateway.sessions.open" && metric.Value == 0);
Assert.Equal("Healthy", snapshot.GatewayStatus);
Assert.Equal(DashboardSnapshotService.UnknownStatus, snapshot.GatewayStatus);
Assert.NotNull(snapshot.Configuration);
}
/// <summary>
/// SEC-27: the gateway status is the aggregate of the registered health checks,
/// evaluated on the snapshot tick, not a hardcoded "Healthy".
/// </summary>
/// <param name="status">The aggregate status the health checks report.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
[Theory]
[InlineData(HealthStatus.Healthy)]
[InlineData(HealthStatus.Degraded)]
[InlineData(HealthStatus.Unhealthy)]
public async Task WatchSnapshotsAsync_ReportsTheHealthCheckStatus(HealthStatus status)
{
using GatewayMetrics metrics = new();
StubHealthCheckService health = new(status);
DashboardSnapshotService service = CreateService(new SessionRegistry(), metrics, healthCheckService: health);
using CancellationTokenSource cancellation = new();
await using IAsyncEnumerator<DashboardSnapshot> enumerator = service
.WatchSnapshotsAsync(cancellation.Token)
.GetAsyncEnumerator(cancellation.Token);
Assert.True(await enumerator.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5)));
Assert.Equal(status.ToString(), enumerator.Current.GatewayStatus);
// Cached for the synchronous seed path too, without a second evaluation.
Assert.Equal(status.ToString(), service.GetSnapshot().GatewayStatus);
Assert.Equal(1, health.CheckCount);
}
/// <summary>A health evaluation that throws is reported as Unknown, never as Healthy.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task WatchSnapshotsAsync_WhenHealthEvaluationThrows_ReportsUnknown()
{
using GatewayMetrics metrics = new();
StubHealthCheckService health = new(HealthStatus.Healthy) { Throw = true };
DashboardSnapshotService service = CreateService(new SessionRegistry(), metrics, healthCheckService: health);
using CancellationTokenSource cancellation = new();
await using IAsyncEnumerator<DashboardSnapshot> enumerator = service
.WatchSnapshotsAsync(cancellation.Token)
.GetAsyncEnumerator(cancellation.Token);
Assert.True(await enumerator.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5)));
Assert.Equal(DashboardSnapshotService.UnknownStatus, enumerator.Current.GatewayStatus);
}
/// <summary>
/// The startup-static configuration is not part of the serialized snapshot, so the
/// hub tick carries only volatile state; the hub sends it once per connection.
/// </summary>
[Fact]
public void GetSnapshot_WhenSerialized_OmitsTheConfiguration()
{
using GatewayMetrics metrics = new();
DashboardSnapshotService service = CreateService(new SessionRegistry(), metrics);
DashboardSnapshot snapshot = service.GetSnapshot();
using JsonDocument json = JsonDocument.Parse(JsonSerializer.Serialize(snapshot, JsonSerializerOptions.Web));
Assert.NotNull(snapshot.Configuration);
Assert.False(json.RootElement.TryGetProperty("configuration", out _));
Assert.True(json.RootElement.TryGetProperty("gatewayStatus", out _));
Assert.True(json.RootElement.TryGetProperty("sessions", out _));
}
/// <summary>
/// Verifies snapshot projects active, faulted, and closed session states with worker and metrics data.
/// </summary>
@@ -615,7 +684,8 @@ public sealed class DashboardSnapshotServiceTests
GatewayOptions? options = null,
IGalaxyHierarchyCache? galaxyHierarchyCache = null,
IApiKeyAdminStore? apiKeyAdminStore = null,
TimeProvider? timeProvider = null)
TimeProvider? timeProvider = null,
HealthCheckService? healthCheckService = null)
{
GatewayOptions resolvedOptions = options ?? new GatewayOptions
{
@@ -633,7 +703,38 @@ public sealed class DashboardSnapshotServiceTests
galaxyHierarchyCache ?? new StubGalaxyHierarchyCache(GalaxyHierarchyCacheEntry.Empty),
apiKeyAdminStore ?? new FakeApiKeyAdminStore(),
Options.Create(resolvedOptions),
timeProvider);
timeProvider,
healthCheckService: healthCheckService);
}
private sealed class StubHealthCheckService(HealthStatus status) : HealthCheckService
{
private int _checkCount;
/// <summary>Gets or sets a value indicating whether the evaluation throws.</summary>
public bool Throw { get; set; }
/// <summary>Gets the number of evaluations requested.</summary>
public int CheckCount => Volatile.Read(ref _checkCount);
/// <inheritdoc />
public override Task<HealthReport> CheckHealthAsync(
Func<HealthCheckRegistration, bool>? predicate,
CancellationToken cancellationToken = default)
{
Interlocked.Increment(ref _checkCount);
if (Throw)
{
throw new InvalidOperationException("health evaluation failed");
}
return Task.FromResult(new HealthReport(
new Dictionary<string, HealthReportEntry>
{
["stub"] = new(status, null, TimeSpan.Zero, null, null),
},
TimeSpan.Zero));
}
}
private sealed class StubGalaxyHierarchyCache(GalaxyHierarchyCacheEntry current) : IGalaxyHierarchyCache