7addd846a1
A navigation while an awaited load was still running disposed the component first; the continuation then created a timer / added a singleton handler that nothing ever disposed, rooting the dead circuit for the life of the process. - Health: refresh timer created under _timerLock only if not disposed. - DataConnections: same for the health-poll timer; also stops before touching the disposed CTS when disposed during the first load. - Deployments: subscribe to IDeploymentStatusNotifier BEFORE the first load (the handler only schedules a reload; the generation guard orders flights). - PendingUpdatesHealthTiles: the Invalidated subscription and the poll timer are both created under a lifetime lock after a disposed check; Dispose unsubscribes only what was subscribed (covers a dispose during the auth-state await too). - AlarmSummary: StartTimer/StopTimer/Dispose atomic under _timerLock; StartTimer refuses after dispose (Topology.StartLiveUpdatesTimer idiom). Tests (each fails on the pre-fix component): HealthPageTests, DataConnectionsPageTests, DeploymentsPerFlightScopeTests, PendingUpdatesHealthTilesTests (x2), AlarmSummaryRenderTests - dispose mid-load, release the load, assert no timer and no handler left.
157 lines
7.2 KiB
C#
157 lines
7.2 KiB
C#
using System.Reflection;
|
|
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.Interfaces.Repositories;
|
|
using ZB.MOM.WW.ScadaBridge.Commons.Types.Deployment;
|
|
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 for code review 2026-12-02 UI-2: overlapping <c>LoadDataAsync</c> flights on the
|
|
/// Deployment Status page used to share the one circuit-scoped repository (and so the one
|
|
/// <c>DbContext</c>); EF refuses a second operation while one is in flight, so the newer flight
|
|
/// threw and the page showed "A second operation was started on this context instance". Each
|
|
/// flight now reads through its own DI scope.
|
|
/// </summary>
|
|
public class DeploymentsPerFlightScopeTests : BunitContext
|
|
{
|
|
/// <summary>
|
|
/// Mimics EF Core's concurrency check: one repository instance (= one DbContext) refuses a
|
|
/// query while another of its queries is still awaiting.
|
|
/// </summary>
|
|
private sealed class SingleOperationRepositoryFactory
|
|
{
|
|
private readonly TaskCompletionSource<DeploymentListPage> _firstCallGate =
|
|
new(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
private int _calls;
|
|
|
|
public int InstancesCreated;
|
|
|
|
public void ReleaseFirstCall() => _firstCallGate.TrySetResult(DeploymentListPage.Empty);
|
|
|
|
public IDeploymentManagerRepository Create()
|
|
{
|
|
Interlocked.Increment(ref InstancesCreated);
|
|
var inFlight = 0;
|
|
var repo = Substitute.For<IDeploymentManagerRepository>();
|
|
repo.QueryDeploymentListPageAsync(
|
|
Arg.Any<DeploymentListFilter>(), Arg.Any<int>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
|
.Returns(_ => Run());
|
|
repo.GetDeploymentStatusCountsAsync(Arg.Any<DeploymentListFilter>(), Arg.Any<CancellationToken>())
|
|
.Returns(DeploymentStatusCounts.Empty);
|
|
return repo;
|
|
|
|
async Task<DeploymentListPage> Run()
|
|
{
|
|
if (Interlocked.Exchange(ref inFlight, 1) == 1)
|
|
throw new InvalidOperationException("A second operation was started on this context instance.");
|
|
try
|
|
{
|
|
// Only the very first query (the initial render's) is held open.
|
|
if (Interlocked.Increment(ref _calls) == 1)
|
|
return await _firstCallGate.Task;
|
|
return DeploymentListPage.Empty;
|
|
}
|
|
finally { Volatile.Write(ref inFlight, 0); }
|
|
}
|
|
}
|
|
}
|
|
|
|
private sealed class StubAuthStateProvider(AuthenticationState state) : AuthenticationStateProvider
|
|
{
|
|
/// <inheritdoc />
|
|
public override Task<AuthenticationState> GetAuthenticationStateAsync() => Task.FromResult(state);
|
|
}
|
|
|
|
/// <summary>A second flight started while the first is still querying must not fail on a shared context.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task OverlappingFlights_EachUseTheirOwnScope_AndNeitherFails()
|
|
{
|
|
var factory = new SingleOperationRepositoryFactory();
|
|
Services.AddScoped(_ => factory.Create());
|
|
Services.AddSingleton<IDeploymentStatusNotifier>(
|
|
new DeploymentStatusNotifier(NullLogger<DeploymentStatusNotifier>.Instance));
|
|
var auth = new StubAuthStateProvider(new AuthenticationState(new ClaimsPrincipal(
|
|
new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, "deployer") }, "TestCookie"))));
|
|
Services.AddSingleton<AuthenticationStateProvider>(auth);
|
|
Services.AddScoped(_ => new SiteScopeService(auth));
|
|
|
|
var cut = Render<DeploymentsPage>(); // flight 1: blocked inside its query
|
|
|
|
var load = typeof(DeploymentsPage).GetMethod("LoadDataAsync", BindingFlags.Instance | BindingFlags.NonPublic)!;
|
|
Task? flight2 = null;
|
|
await cut.InvokeAsync(() => { flight2 = (Task)load.Invoke(cut.Instance, new object?[] { false })!; });
|
|
await flight2!.WaitAsync(TimeSpan.FromSeconds(5));
|
|
|
|
// Flight 2 is the newest generation, so an error it hit would be the one the page shows.
|
|
Assert.Null(ErrorMessage(cut.Instance));
|
|
|
|
factory.ReleaseFirstCall();
|
|
|
|
cut.WaitForAssertion(() => Assert.DoesNotContain("second operation", cut.Markup));
|
|
Assert.Null(ErrorMessage(cut.Instance));
|
|
Assert.True(factory.InstancesCreated >= 2, "each flight must resolve its repository from its own scope");
|
|
}
|
|
|
|
private static string? ErrorMessage(DeploymentsPage page) =>
|
|
(string?)typeof(DeploymentsPage)
|
|
.GetField("_errorMessage", BindingFlags.Instance | BindingFlags.NonPublic)!
|
|
.GetValue(page);
|
|
|
|
private sealed class CountingNotifier : IDeploymentStatusNotifier
|
|
{
|
|
private Action<DeploymentStatusChange>? _handlers;
|
|
|
|
/// <summary>Handlers currently on the invocation list (removing an absent one is a no-op, as for a real event).</summary>
|
|
public int Subscribers => _handlers?.GetInvocationList().Length ?? 0;
|
|
|
|
public event Action<DeploymentStatusChange>? StatusChanged
|
|
{
|
|
add => _handlers += value;
|
|
remove => _handlers -= value;
|
|
}
|
|
|
|
public void NotifyStatusChanged(DeploymentStatusChange change) { }
|
|
}
|
|
|
|
/// <summary>
|
|
/// Code review 2026-12-02 UI-4: disposed while the first load is in flight, the page must
|
|
/// leave no handler on the process-singleton status notifier (it used to subscribe after
|
|
/// the load, i.e. after Dispose had already unsubscribed nothing).
|
|
/// </summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task DisposedDuringFirstLoad_LeavesNoNotifierSubscription()
|
|
{
|
|
var factory = new SingleOperationRepositoryFactory();
|
|
Services.AddScoped(_ => factory.Create());
|
|
var notifier = new CountingNotifier();
|
|
Services.AddSingleton<IDeploymentStatusNotifier>(notifier);
|
|
var auth = new StubAuthStateProvider(new AuthenticationState(new ClaimsPrincipal(
|
|
new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, "deployer") }, "TestCookie"))));
|
|
Services.AddSingleton<AuthenticationStateProvider>(auth);
|
|
Services.AddScoped(_ => new SiteScopeService(auth));
|
|
|
|
var cut = Render<DeploymentsPage>(); // first load held open
|
|
var page = cut.Instance;
|
|
await cut.InvokeAsync(page.Dispose);
|
|
|
|
factory.ReleaseFirstCall();
|
|
// The first load has finished once _loading drops; OnInitializedAsync's tail runs in
|
|
// the same dispatcher step.
|
|
cut.WaitForAssertion(() => Assert.False((bool)typeof(DeploymentsPage)
|
|
.GetField("_loading", BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(page)!));
|
|
await cut.InvokeAsync(() => { });
|
|
|
|
Assert.Equal(0, notifier.Subscribers);
|
|
}
|
|
}
|