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;
///
/// Regression for code review 2026-12-02 UI-2: overlapping LoadDataAsync flights on the
/// Deployment Status page used to share the one circuit-scoped repository (and so the one
/// DbContext); 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.
///
public class DeploymentsPerFlightScopeTests : BunitContext
{
///
/// Mimics EF Core's concurrency check: one repository instance (= one DbContext) refuses a
/// query while another of its queries is still awaiting.
///
private sealed class SingleOperationRepositoryFactory
{
private readonly TaskCompletionSource _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();
repo.QueryDeploymentListPageAsync(
Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any())
.Returns(_ => Run());
repo.GetDeploymentStatusCountsAsync(Arg.Any(), Arg.Any())
.Returns(DeploymentStatusCounts.Empty);
return repo;
async Task 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
{
///
public override Task GetAuthenticationStateAsync() => Task.FromResult(state);
}
/// A second flight started while the first is still querying must not fail on a shared context.
/// A task that represents the asynchronous operation.
[Fact]
public async Task OverlappingFlights_EachUseTheirOwnScope_AndNeitherFails()
{
var factory = new SingleOperationRepositoryFactory();
Services.AddScoped(_ => factory.Create());
Services.AddSingleton(
new DeploymentStatusNotifier(NullLogger.Instance));
var auth = new StubAuthStateProvider(new AuthenticationState(new ClaimsPrincipal(
new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, "deployer") }, "TestCookie"))));
Services.AddSingleton(auth);
Services.AddScoped(_ => new SiteScopeService(auth));
var cut = Render(); // 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? _handlers;
/// Handlers currently on the invocation list (removing an absent one is a no-op, as for a real event).
public int Subscribers => _handlers?.GetInvocationList().Length ?? 0;
public event Action? StatusChanged
{
add => _handlers += value;
remove => _handlers -= value;
}
public void NotifyStatusChanged(DeploymentStatusChange change) { }
}
///
/// 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).
///
/// A task that represents the asynchronous operation.
[Fact]
public async Task DisposedDuringFirstLoad_LeavesNoNotifierSubscription()
{
var factory = new SingleOperationRepositoryFactory();
Services.AddScoped(_ => factory.Create());
var notifier = new CountingNotifier();
Services.AddSingleton(notifier);
var auth = new StubAuthStateProvider(new AuthenticationState(new ClaimsPrincipal(
new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, "deployer") }, "TestCookie"))));
Services.AddSingleton(auth);
Services.AddScoped(_ => new SiteScopeService(auth));
var cut = Render(); // 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);
}
}