Merge branch 'worktree-agent-acc1e4b5202e79d46' into arch-review-remediation

This commit is contained in:
Joseph Doherty
2026-08-14 21:15:31 -04:00
19 changed files with 1554 additions and 64 deletions
@@ -0,0 +1,144 @@
using System.Collections;
using System.Reflection;
using System.Security.Claims;
using Bunit;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using NSubstitute;
using ZB.MOM.WW.ScadaBridge.CentralUI.Auth;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Streaming;
using ZB.MOM.WW.ScadaBridge.Communication;
using ZB.MOM.WW.ScadaBridge.Communication.Grpc;
using DebugViewPage = ZB.MOM.WW.ScadaBridge.CentralUI.Components.Pages.Deployment.DebugView;
namespace ZB.MOM.WW.ScadaBridge.CentralUI.Tests.Deployment;
/// <summary>
/// Regression tests for the Debug View render coalescing (arch-review WP2.4). Every streamed
/// event used to marshal onto the circuit dispatcher and call <c>StateHasChanged</c> on its
/// own, so a chatty instance drove one full render — and two full composition-tree rebuilds —
/// per value change. Events are now buffered and applied once per ~250 ms window: a burst
/// costs a handful of renders instead of one per event, and no event is dropped.
/// </summary>
public class DebugViewRenderCoalescingTests : BunitContext
{
private IRenderedComponent<DebugViewPage> RenderPage()
{
JSInterop.Mode = JSRuntimeMode.Loose;
var repo = Substitute.For<ITemplateEngineRepository>();
var siteRepo = Substitute.For<ISiteRepository>();
siteRepo.GetAllSitesAsync().Returns(new List<Site>());
Services.AddSingleton(repo);
Services.AddSingleton(siteRepo);
var comms = new CommunicationService(
Options.Create(new CommunicationOptions()),
NullLogger<CommunicationService>.Instance);
Services.AddSingleton(comms);
var grpcFactory = new SiteStreamGrpcClientFactory(NullLoggerFactory.Instance);
var debugStream = new DebugStreamService(
comms, new ServiceCollection().BuildServiceProvider(), grpcFactory,
NullLogger<DebugStreamService>.Instance);
Services.AddSingleton(debugStream);
var identity = new ClaimsIdentity(
new[] { new Claim(ClaimTypes.Name, "deployer") }, "TestCookie");
var stubAuth = new StubAuthStateProvider(
new AuthenticationState(new ClaimsPrincipal(identity)));
Services.AddSingleton<AuthenticationStateProvider>(stubAuth);
Services.AddScoped(_ => new SiteScopeService(stubAuth));
return Render<DebugViewPage>();
}
private sealed class StubAuthStateProvider : AuthenticationStateProvider
{
private readonly AuthenticationState _state;
public StubAuthStateProvider(AuthenticationState state) => _state = state;
public override Task<AuthenticationState> GetAuthenticationStateAsync()
=> Task.FromResult(_state);
}
private static MethodInfo HandleStreamEvent => typeof(DebugViewPage).GetMethod(
"HandleStreamEvent", BindingFlags.Instance | BindingFlags.NonPublic)!;
private static IDictionary AttributeValues(DebugViewPage c) => (IDictionary)
typeof(DebugViewPage).GetField("_attributeValues",
BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(c)!;
private static void Send(DebugViewPage page, string name, object value) =>
HandleStreamEvent.Invoke(page, new object[]
{
new AttributeValueChanged("Inst-1", name, name, value, "Good", DateTimeOffset.UtcNow),
});
[Fact]
public void BurstOfEvents_RendersOnce_ButAppliesEveryEvent()
{
var cut = RenderPage();
var dict = AttributeValues(cut.Instance);
var rendersBefore = cut.RenderCount;
const int burst = 300;
for (var i = 0; i < burst; i++)
{
Send(cut.Instance, $"Tag.{i}", i);
}
cut.WaitForState(() => dict.Count == burst, TimeSpan.FromSeconds(5));
// Pre-fix this was one render per event. The window may close mid-burst, so allow a
// few flushes — the point is that it is a small constant, not O(events).
var renders = cut.RenderCount - rendersBefore;
Assert.InRange(renders, 1, 5);
}
[Fact]
public void RepeatedUpdatesToOneTag_CollapseToTheLatestValue()
{
var cut = RenderPage();
var dict = AttributeValues(cut.Instance);
for (var i = 0; i < 50; i++)
{
Send(cut.Instance, "Pump.Speed", i);
}
cut.WaitForState(() => dict.Count == 1, TimeSpan.FromSeconds(5));
var applied = (AttributeValueChanged)dict["Pump.Speed"]!;
Assert.Equal(49, applied.Value);
}
[Fact]
public void EventArrivingAfterAFlush_StillArmsANewWindow()
{
var cut = RenderPage();
var dict = AttributeValues(cut.Instance);
Send(cut.Instance, "First", 1);
cut.WaitForState(() => dict.Count == 1, TimeSpan.FromSeconds(5));
// The window disarms on drain; a later event must arm a fresh one rather than
// sitting in the pending map until some unrelated event happens to arrive.
Send(cut.Instance, "Second", 2);
cut.WaitForState(() => dict.Count == 2, TimeSpan.FromSeconds(5));
}
[Fact]
public void EventsAfterDispose_AreDroppedWithoutThrowing()
{
var cut = RenderPage();
cut.Instance.Dispose();
var ex = Record.Exception(() => Send(cut.Instance, "Late", 1));
Assert.Null(ex);
Assert.Empty(AttributeValues(cut.Instance));
}
}
@@ -0,0 +1,127 @@
using System.Security.Claims;
using Bunit;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using NSubstitute;
using ZB.MOM.WW.ScadaBridge.CentralUI.Auth;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Deployment;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
using ZB.MOM.WW.ScadaBridge.DeploymentManager;
using DeploymentsPage = ZB.MOM.WW.ScadaBridge.CentralUI.Components.Pages.Deployment.Deployments;
namespace ZB.MOM.WW.ScadaBridge.CentralUI.Tests.Deployment;
/// <summary>
/// Regression tests for the Deployment Status push coalescing (arch-review WP2.4). One
/// notifier callback reloads EVERY deployment record plus EVERY instance, and the notifier
/// fires per status write — so a multi-instance deploy produced a stampede of full reloads
/// per circuit. The reload is now leading-edge debounced: the first push after an idle gap
/// is still immediate, and a burst behind it collapses into one trailing reload.
/// </summary>
public class DeploymentsReloadDebounceTests : BunitContext
{
private IDeploymentManagerRepository _deployRepo = null!;
private ITemplateEngineRepository _templateRepo = null!;
private DeploymentStatusNotifier _notifier = null!;
private void RegisterServices()
{
_deployRepo = Substitute.For<IDeploymentManagerRepository>();
_templateRepo = Substitute.For<ITemplateEngineRepository>();
_notifier = new DeploymentStatusNotifier(NullLogger<DeploymentStatusNotifier>.Instance);
_templateRepo.GetAllInstancesAsync(Arg.Any<CancellationToken>())
.Returns(new List<Instance> { new("Inst-1") { Id = 1, SiteId = 1 } });
_deployRepo.GetAllDeploymentRecordsAsync(Arg.Any<CancellationToken>())
.Returns(new List<DeploymentRecord>());
Services.AddSingleton(_deployRepo);
Services.AddSingleton(_templateRepo);
Services.AddSingleton<IDeploymentStatusNotifier>(_notifier);
var identity = new ClaimsIdentity(
new[] { new Claim(ClaimTypes.Name, "deployer") }, "TestCookie");
var stubAuth = new StubAuthStateProvider(
new AuthenticationState(new ClaimsPrincipal(identity)));
Services.AddSingleton<AuthenticationStateProvider>(stubAuth);
Services.AddScoped(_ => new SiteScopeService(stubAuth));
}
private sealed class StubAuthStateProvider : AuthenticationStateProvider
{
private readonly AuthenticationState _state;
public StubAuthStateProvider(AuthenticationState state) => _state = state;
public override Task<AuthenticationState> GetAuthenticationStateAsync()
=> Task.FromResult(_state);
}
[Fact]
public void BurstOfStatusWrites_CollapsesIntoFarFewerReloads()
{
RegisterServices();
var cut = Render<DeploymentsPage>();
cut.WaitForAssertion(() =>
_deployRepo.Received().GetAllDeploymentRecordsAsync(Arg.Any<CancellationToken>()));
_deployRepo.ClearReceivedCalls();
// A 40-instance site deploy: every status write raises the notifier.
for (var i = 0; i < 40; i++)
{
_notifier.NotifyStatusChanged(
new DeploymentStatusChange($"dep-{i}", 1, DeploymentStatus.InProgress));
}
// Leading edge fires at once; the rest ride one trailing reload.
cut.WaitForAssertion(() =>
_deployRepo.Received().GetAllDeploymentRecordsAsync(Arg.Any<CancellationToken>()));
// Let the trailing window close before counting.
Thread.Sleep(900);
var reloads = _deployRepo.ReceivedCalls()
.Count(c => c.GetMethodInfo().Name == nameof(IDeploymentManagerRepository.GetAllDeploymentRecordsAsync));
Assert.InRange(reloads, 1, 4);
}
[Fact]
public void FirstPushAfterIdle_ReloadsImmediately()
{
RegisterServices();
var cut = Render<DeploymentsPage>();
cut.WaitForAssertion(() =>
_deployRepo.Received().GetAllDeploymentRecordsAsync(Arg.Any<CancellationToken>()));
_deployRepo.ClearReceivedCalls();
// Idle since the initial load — the leading edge must not wait out the window.
Thread.Sleep(600);
_notifier.NotifyStatusChanged(
new DeploymentStatusChange("dep-1", 1, DeploymentStatus.Success));
cut.WaitForAssertion(
() => _deployRepo.Received().GetAllDeploymentRecordsAsync(Arg.Any<CancellationToken>()),
TimeSpan.FromMilliseconds(400));
}
[Fact]
public void DisposeDuringACoalesceWindow_DoesNotReload()
{
RegisterServices();
var cut = Render<DeploymentsPage>();
cut.WaitForAssertion(() =>
_deployRepo.Received().GetAllDeploymentRecordsAsync(Arg.Any<CancellationToken>()));
// Two pushes: the first takes the leading edge, the second arms the trailing timer.
_notifier.NotifyStatusChanged(new DeploymentStatusChange("dep-1", 1, DeploymentStatus.InProgress));
_notifier.NotifyStatusChanged(new DeploymentStatusChange("dep-2", 1, DeploymentStatus.InProgress));
cut.Instance.Dispose();
_deployRepo.ClearReceivedCalls();
// The armed timer must be disposed with the component, not fire against it.
Thread.Sleep(900);
_deployRepo.DidNotReceive().GetAllDeploymentRecordsAsync(Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,113 @@
using System.Security.Claims;
using Bunit;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.Extensions.DependencyInjection;
using NSubstitute;
using ZB.MOM.WW.ScadaBridge.CentralUI.Services;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Streaming;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
using ZB.MOM.WW.ScadaBridge.Communication;
using ZB.MOM.WW.ScadaBridge.Security;
using AlarmSummaryPage = ZB.MOM.WW.ScadaBridge.CentralUI.Components.Pages.Monitoring.AlarmSummary;
namespace ZB.MOM.WW.ScadaBridge.CentralUI.Tests.Monitoring;
/// <summary>
/// Covers the Alarm Summary flat table's two rendering paths (arch-review WP2.4). A short
/// list renders every row with a plain foreach; past the threshold the same row template is
/// handed to <c>Virtualize</c> so a site with thousands of alarms stops materialising the
/// whole table into the circuit's render tree on every delta. Row markup — including the
/// <c>data-test</c> hook the operator tests key off — is identical either way.
/// </summary>
public class AlarmSummaryVirtualizeTests : BunitContext
{
private readonly IAlarmSummaryService _summary = Substitute.For<IAlarmSummaryService>();
private readonly ISiteRepository _siteRepo = Substitute.For<ISiteRepository>();
private void Arrange(int rowCount)
{
JSInterop.Mode = JSRuntimeMode.Loose;
var rows = Enumerable.Range(0, rowCount)
.Select(i => new AlarmSummaryRow(
$"inst-{i:D4}",
new AlarmStateChanged($"inst-{i:D4}", $"alarm-{i:D4}", AlarmState.Active, i, DateTimeOffset.UtcNow)))
.ToList();
_summary.GetSiteAlarmsAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(Task.FromResult(new AlarmSummaryResult(rows, Array.Empty<string>())));
_summary.ComputeRollup(Arg.Any<IReadOnlyList<AlarmSummaryRow>>())
.Returns(new AlarmRollup(rowCount, rowCount, 0, new Dictionary<AlarmKind, int>()));
Services.AddSingleton(_summary);
_siteRepo.GetAllSitesAsync(Arg.Any<CancellationToken>())
.Returns(Task.FromResult<IReadOnlyList<Site>>(new List<Site>
{
new("Site 1", "site1") { Id = 1 },
}));
Services.AddSingleton(_siteRepo);
Services.AddSingleton<ISiteAlarmLiveCache>(new InertLiveCache());
var claims = new[]
{
new Claim(JwtTokenService.UsernameClaimType, "tester"),
new Claim(JwtTokenService.RoleClaimType, "Administrator"),
};
Services.AddSingleton<AuthenticationStateProvider>(
new TestAuthStateProvider(new ClaimsPrincipal(new ClaimsIdentity(claims, "TestAuth"))));
Services.AddAuthorizationCore();
}
private IRenderedComponent<AlarmSummaryPage> RenderWithSiteSelected()
{
var cut = Render<AlarmSummaryPage>();
cut.Find("[data-test='alarm-summary-site']").Change("1");
return cut;
}
[Fact]
public void ShortList_RendersEveryRowInline()
{
Arrange(rowCount: 20);
var cut = RenderWithSiteSelected();
cut.WaitForAssertion(() =>
Assert.Equal(20, cut.FindAll("tr[data-test='alarm-summary-row']").Count));
// The row-count line is unchanged by either path.
Assert.Contains("Showing 20 of 20", cut.Markup);
}
[Fact]
public void LongList_VirtualizesWithoutRenderingEveryRow()
{
Arrange(rowCount: 2000);
var cut = RenderWithSiteSelected();
cut.WaitForAssertion(() => Assert.Contains("Showing 2000 of 2000", cut.Markup));
var rendered = cut.FindAll("tr[data-test='alarm-summary-row']").Count;
Assert.InRange(rendered, 1, 1999);
// Rows still carry the same shape — instance name, alarm name, severity.
Assert.Contains("alarm-", cut.Markup);
}
/// <summary>Never goes live, so the page keeps its poll snapshot for these tests.</summary>
private sealed class InertLiveCache : ISiteAlarmLiveCache
{
public IDisposable Subscribe(int siteId, Action onChanged) => new NoOp();
public IReadOnlyList<AlarmStateChanged> GetCurrentAlarms(int siteId) =>
Array.Empty<AlarmStateChanged>();
public bool IsLive(int siteId) => false;
private sealed class NoOp : IDisposable
{
public void Dispose() { }
}
}
}
@@ -64,6 +64,14 @@ public class HealthPageTests : BunitContext
_comms.SetSiteCallAudit(siteCallAudit);
Services.AddSingleton(_comms);
// arch-review WP2.4 — the page no longer queries CommunicationService /
// IAuditLogQueryService per circuit; it reads the process-level memoized
// KPI cache. The real cache is registered here (not a substitute) so the
// scripted-actor seam above is still what actually answers.
Services.AddSingleton<IKpiSnapshotCache>(sp => new KpiSnapshotCache(
sp.GetRequiredService<CommunicationService>(),
sp.GetRequiredService<IServiceScopeFactory>()));
var aggregator = Substitute.For<ICentralHealthAggregator>();
aggregator.GetAllSiteStates()
.Returns(new Dictionary<string, SiteHealthState>());
@@ -71,6 +71,13 @@ public class NotificationKpisPageTests : BunitContext
Services.AddSingleton(_comms);
// arch-review WP2.4 — the page reads the process-level memoized KPI cache
// rather than querying CommunicationService per circuit. The real cache is
// registered so the scripted-actor seam above still answers the queries.
Services.AddSingleton<IKpiSnapshotCache>(sp => new KpiSnapshotCache(
sp.GetRequiredService<CommunicationService>(),
sp.GetRequiredService<IServiceScopeFactory>()));
var siteRepo = Substitute.For<ISiteRepository>();
siteRepo.GetAllSitesAsync(Arg.Any<CancellationToken>())
.Returns(Task.FromResult<IReadOnlyList<Site>>(new List<Site>
@@ -0,0 +1,169 @@
using Microsoft.Extensions.DependencyInjection;
using NSubstitute;
using ZB.MOM.WW.ScadaBridge.CentralUI.Services;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.DebugView;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Streaming;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
using ZB.MOM.WW.ScadaBridge.Communication;
namespace ZB.MOM.WW.ScadaBridge.CentralUI.Tests.Services;
/// <summary>
/// Unit tests for <see cref="SharedAlarmSummaryService"/> (arch-review WP2.4). The Alarm
/// Summary page polls per circuit; the shared façade must collapse those into ONE per-site
/// fan-out per freshness window, and must widen that window while the live alarm cache is
/// serving the site (where the poll only still supplies the not-reporting list).
/// </summary>
public class SharedAlarmSummaryServiceTests : IDisposable
{
private const int SiteId = 7;
private const string SiteIdentifier = "plant-a";
private static readonly DateTimeOffset T0 = new(2026, 8, 14, 9, 0, 0, TimeSpan.Zero);
private readonly ITemplateEngineRepository _instanceRepo = Substitute.For<ITemplateEngineRepository>();
private readonly ISiteRepository _siteRepo = Substitute.For<ISiteRepository>();
private readonly IInstanceSnapshotClient _snapshotClient = Substitute.For<IInstanceSnapshotClient>();
private readonly FakeLiveCache _liveCache = new();
private readonly ServiceProvider _provider;
private DateTimeOffset _now = T0;
public SharedAlarmSummaryServiceTests()
{
_siteRepo.GetSiteByIdAsync(SiteId, Arg.Any<CancellationToken>())
.Returns(new Site("Plant A", SiteIdentifier) { Id = SiteId });
_instanceRepo.GetInstancesBySiteIdAsync(SiteId, Arg.Any<CancellationToken>())
.Returns(new List<Instance>
{
new("inst-a") { Id = 1, SiteId = SiteId, State = InstanceState.Enabled },
});
_snapshotClient.GetSnapshotAsync(SiteIdentifier, "inst-a", Arg.Any<CancellationToken>())
.Returns(new DebugViewSnapshot(
"inst-a",
Array.Empty<AttributeValueChanged>(),
new[] { new AlarmStateChanged("inst-a", "A-alarm", AlarmState.Active, 500, T0) },
T0));
var services = new ServiceCollection();
services.AddSingleton(_instanceRepo);
services.AddSingleton(_siteRepo);
services.AddSingleton(_snapshotClient);
services.AddScoped<AlarmSummaryService>();
_provider = services.BuildServiceProvider();
}
private SharedAlarmSummaryService CreateSut(TimeSpan liveCacheTtl) =>
new(_provider.GetRequiredService<IServiceScopeFactory>(), _liveCache, liveCacheTtl, () => _now);
[Fact]
public async Task ConcurrentCircuits_ShareOneFanOut()
{
var sut = CreateSut(TimeSpan.FromSeconds(60));
var results = await Task.WhenAll(Enumerable.Range(0, 8).Select(_ => sut.GetSiteAlarmsAsync(SiteId)));
await _instanceRepo.Received(1).GetInstancesBySiteIdAsync(SiteId, Arg.Any<CancellationToken>());
Assert.All(results, r => Assert.Single(r.Alarms));
}
[Fact]
public async Task ColdLiveCache_RefreshesWithinThePageTick()
{
var sut = CreateSut(TimeSpan.FromSeconds(60));
_liveCache.Live = false;
await sut.GetSiteAlarmsAsync(SiteId);
// The page polls every 15s and, while the cache is cold, the poll is its
// authoritative rebuild — so the memo must have expired by then.
_now = T0.AddSeconds(15);
await sut.GetSiteAlarmsAsync(SiteId);
await _instanceRepo.Received(2).GetInstancesBySiteIdAsync(SiteId, Arg.Any<CancellationToken>());
}
[Fact]
public async Task LiveCacheServing_WidensTheWindowToTheReconcileInterval()
{
var sut = CreateSut(TimeSpan.FromSeconds(60));
_liveCache.Live = true;
await sut.GetSiteAlarmsAsync(SiteId);
_now = T0.AddSeconds(30);
await sut.GetSiteAlarmsAsync(SiteId);
// Live deltas own the rows; only the not-reporting list still comes from the
// fan-out, so a 30s-old answer is fine and costs no second fan-out.
await _instanceRepo.Received(1).GetInstancesBySiteIdAsync(SiteId, Arg.Any<CancellationToken>());
_now = T0.AddSeconds(61);
await sut.GetSiteAlarmsAsync(SiteId);
await _instanceRepo.Received(2).GetInstancesBySiteIdAsync(SiteId, Arg.Any<CancellationToken>());
}
[Fact]
public async Task DifferentSites_DoNotShareAMemoSlot()
{
const int otherSite = 8;
_siteRepo.GetSiteByIdAsync(otherSite, Arg.Any<CancellationToken>())
.Returns(new Site("Plant B", "plant-b") { Id = otherSite });
_instanceRepo.GetInstancesBySiteIdAsync(otherSite, Arg.Any<CancellationToken>())
.Returns(new List<Instance>());
var sut = CreateSut(TimeSpan.FromSeconds(60));
await sut.GetSiteAlarmsAsync(SiteId);
await sut.GetSiteAlarmsAsync(otherSite);
await _instanceRepo.Received(1).GetInstancesBySiteIdAsync(SiteId, Arg.Any<CancellationToken>());
await _instanceRepo.Received(1).GetInstancesBySiteIdAsync(otherSite, Arg.Any<CancellationToken>());
}
[Fact]
public void PureMethods_MatchTheDirectImplementation()
{
var sut = CreateSut(TimeSpan.FromSeconds(60));
var direct = new AlarmSummaryService(_instanceRepo, _siteRepo, _snapshotClient);
var alarms = new List<AlarmStateChanged>
{
new("inst-b", "B-alarm", AlarmState.Active, 900, T0),
new("inst-a", "A-alarm", AlarmState.Normal, 100, T0),
};
var shared = sut.BuildFromLiveAlarms(alarms);
var expected = direct.BuildFromLiveAlarms(alarms);
Assert.Equal(
expected.Alarms.Select(r => r.Alarm.AlarmName),
shared.Alarms.Select(r => r.Alarm.AlarmName));
var expectedRollup = direct.ComputeRollup(expected.Alarms);
var sharedRollup = sut.ComputeRollup(shared.Alarms);
Assert.Equal(expectedRollup.TotalActive, sharedRollup.TotalActive);
Assert.Equal(expectedRollup.WorstSeverity, sharedRollup.WorstSeverity);
Assert.Equal(expectedRollup.UnackedCount, sharedRollup.UnackedCount);
Assert.Equal(expectedRollup.CountsByKind, sharedRollup.CountsByKind);
}
public void Dispose() => _provider.Dispose();
/// <summary>Liveness-only stub — the façade consults nothing else on the live cache.</summary>
private sealed class FakeLiveCache : ISiteAlarmLiveCache
{
public bool Live { get; set; }
public IDisposable Subscribe(int siteId, Action onChanged) => new NoOp();
public IReadOnlyList<AlarmStateChanged> GetCurrentAlarms(int siteId) =>
Array.Empty<AlarmStateChanged>();
public bool IsLive(int siteId) => Live;
private sealed class NoOp : IDisposable
{
public void Dispose() { }
}
}
}
@@ -0,0 +1,166 @@
using ZB.MOM.WW.ScadaBridge.CentralUI.Services;
namespace ZB.MOM.WW.ScadaBridge.CentralUI.Tests.Services;
/// <summary>
/// Unit tests for <see cref="SingleFlightMemo{T}"/> — the primitive behind the process-level
/// KPI snapshot cache and the shared Alarm Summary fan-out (arch-review WP2.4). The two
/// properties the whole optimisation rests on are tested here: <b>single-flight</b> (N
/// concurrent circuits asking the same question produce ONE query) and <b>TTL</b> (a query
/// answered inside the freshness window is served from memory, and one outside it is not).
/// </summary>
public class SingleFlightMemoTests
{
private static readonly DateTimeOffset T0 = new(2026, 8, 14, 9, 0, 0, TimeSpan.Zero);
[Fact]
public async Task ConcurrentCallers_ShareOneFlight()
{
var released = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);
var invocations = 0;
var memo = new SingleFlightMemo<int>(TimeSpan.FromSeconds(10), () => T0);
// Ten circuits ask while the first flight is still in progress.
var waiters = Enumerable.Range(0, 10)
.Select(_ => memo.GetAsync(() =>
{
Interlocked.Increment(ref invocations);
return released.Task;
}))
.ToArray();
released.SetResult(42);
var results = await Task.WhenAll(waiters);
Assert.Equal(1, invocations);
Assert.Equal(1, memo.FlightCount);
Assert.All(results, r => Assert.Equal(42, r));
}
[Fact]
public async Task WithinTtl_ServesTheMemoizedValue_WithoutRequerying()
{
var now = T0;
var invocations = 0;
var memo = new SingleFlightMemo<int>(TimeSpan.FromSeconds(8), () => now);
var first = await memo.GetAsync(() => Task.FromResult(++invocations));
now = T0.AddSeconds(7);
var second = await memo.GetAsync(() => Task.FromResult(++invocations));
Assert.Equal(1, first);
Assert.Equal(1, second);
Assert.Equal(1, memo.FlightCount);
}
[Fact]
public async Task AfterTtl_RequeriesOnce()
{
var now = T0;
var invocations = 0;
var memo = new SingleFlightMemo<int>(TimeSpan.FromSeconds(8), () => now);
await memo.GetAsync(() => Task.FromResult(++invocations));
now = T0.AddSeconds(9);
var refreshed = await memo.GetAsync(() => Task.FromResult(++invocations));
Assert.Equal(2, refreshed);
Assert.Equal(2, memo.FlightCount);
}
[Fact]
public async Task ForceRefresh_BypassesAFreshValue()
{
var now = T0;
var invocations = 0;
var memo = new SingleFlightMemo<int>(TimeSpan.FromSeconds(60), () => now);
await memo.GetAsync(() => Task.FromResult(++invocations));
var forced = await memo.GetAsync(() => Task.FromResult(++invocations), forceRefresh: true);
Assert.Equal(2, forced);
Assert.Equal(2, memo.FlightCount);
}
[Fact]
public async Task ForceRefresh_StillJoinsAnInFlightRound()
{
var released = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);
var invocations = 0;
var memo = new SingleFlightMemo<int>(TimeSpan.FromSeconds(60), () => T0);
var first = memo.GetAsync(() =>
{
Interlocked.Increment(ref invocations);
return released.Task;
});
// A burst of operator "Refresh" clicks must not multiply the query.
var forcedA = memo.GetAsync(() => Task.FromResult(-1), forceRefresh: true);
var forcedB = memo.GetAsync(() => Task.FromResult(-1), forceRefresh: true);
released.SetResult(7);
Assert.Equal(7, await first);
Assert.Equal(7, await forcedA);
Assert.Equal(7, await forcedB);
Assert.Equal(1, invocations);
}
[Fact]
public async Task Failure_IsNotMemoized_AndTheNextCallerRetries()
{
var now = T0;
var invocations = 0;
var memo = new SingleFlightMemo<int>(TimeSpan.FromSeconds(60), () => now);
await Assert.ThrowsAsync<InvalidOperationException>(() =>
memo.GetAsync(() =>
{
invocations++;
return Task.FromException<int>(new InvalidOperationException("KPI query failed"));
}));
// Same instant, well inside the TTL — a cached fault would starve the tiles for a
// whole window, so the next caller must produce a new flight.
var recovered = await memo.GetAsync(() => Task.FromResult(++invocations));
Assert.Equal(2, recovered);
Assert.Equal(2, memo.FlightCount);
}
[Fact]
public async Task TtlOverride_AppliesToThatFlight()
{
var now = T0;
var invocations = 0;
var memo = new SingleFlightMemo<int>(TimeSpan.FromSeconds(5), () => now);
// Produced under a 60s override — still fresh 30s later despite the 5s default.
await memo.GetAsync(() => Task.FromResult(++invocations), ttlOverride: TimeSpan.FromSeconds(60));
now = T0.AddSeconds(30);
var second = await memo.GetAsync(() => Task.FromResult(++invocations));
Assert.Equal(1, second);
Assert.Equal(1, memo.FlightCount);
}
[Fact]
public async Task CallerCancellation_DoesNotCancelTheSharedFlight()
{
var released = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);
var memo = new SingleFlightMemo<int>(TimeSpan.FromSeconds(60), () => T0);
using var giveUp = new CancellationTokenSource();
var impatient = memo.GetAsync(() => released.Task, cancellationToken: giveUp.Token);
var patient = memo.GetAsync(() => Task.FromResult(-1));
giveUp.Cancel();
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => impatient);
// The abandoned wait must not have taken the round down with it.
released.SetResult(99);
Assert.Equal(99, await patient);
}
}