perf(ui): shared KPI cache, live-cache-backed alarm summary, coalesced debug renders
This commit is contained in:
+169
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user