Files
ScadaBridge/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Deployment/DeploymentsPerFlightScopeTests.cs
T
Joseph Doherty 2e194f4eac fix(centralui): run long/concurrent page actions in their own DI scope (UI-2, UI-3, UI-8, WP5 task 5.2)
- Deployments: every LoadDataAsync flight reads through its own scope, so
  overlapping flights (push reload, debounce, page/tile click) no longer
  collide on the circuit DbContext; the generation guard still orders results.
- Sites: Deploy Artifacts (per site and to all sites) resolves
  ArtifactDeploymentService from a fresh scope, so the post-fan-out record,
  audit rows and revision stamp neither share the circuit context nor die
  with the circuit.
- Topology: Diff and Enable/Disable/Delete resolve DeploymentService from
  their own scope (like Deploy/Deploy all), so they cannot overlap the 15 s
  live tick; drops the unused AreaService/InstanceService injections.
- New ScopedServiceExtensions.InNewScopeAsync helper.

Tests: DeploymentsPerFlightScopeTests, SitesPageTests
DeployToAllSites_RunsInItsOwnScope_DisposedAfterTheAction, TopologyPageTests
UI8_InstanceActions_RunOnTheirOwnScope (all fail on the pre-fix pages).
2026-12-03 09:47:43 -05:00

109 lines
5.0 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);
}