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).
This commit is contained in:
@@ -12,7 +12,8 @@
|
|||||||
@attribute [Authorize(Policy = AuthorizationPolicies.RequireAdmin)]
|
@attribute [Authorize(Policy = AuthorizationPolicies.RequireAdmin)]
|
||||||
@inject ISiteRepository SiteRepository
|
@inject ISiteRepository SiteRepository
|
||||||
@inject IPendingUpdatesCache PendingUpdates
|
@inject IPendingUpdatesCache PendingUpdates
|
||||||
@inject ArtifactDeploymentService ArtifactDeploymentService
|
@inject Microsoft.Extensions.DependencyInjection.IServiceScopeFactory ScopeFactory
|
||||||
|
@using Microsoft.Extensions.DependencyInjection
|
||||||
@inject CommunicationService CommunicationService
|
@inject CommunicationService CommunicationService
|
||||||
@inject AuthenticationStateProvider AuthStateProvider
|
@inject AuthenticationStateProvider AuthStateProvider
|
||||||
@inject NavigationManager NavigationManager
|
@inject NavigationManager NavigationManager
|
||||||
@@ -314,8 +315,11 @@
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
var user = await GetCurrentUserAsync();
|
var user = await GetCurrentUserAsync();
|
||||||
var result = await ArtifactDeploymentService.RetryForSiteAsync(
|
// Own DI scope (UI-3): the deploy's record, audit rows and revision stamp are all
|
||||||
site.Id, site.SiteIdentifier, user);
|
// written after the site fan-out, so it must neither share the circuit's context
|
||||||
|
// with whatever the operator does next nor die with the circuit if the tab closes.
|
||||||
|
var result = await ScopeFactory.InNewScopeAsync(
|
||||||
|
(ArtifactDeploymentService svc) => svc.RetryForSiteAsync(site.Id, site.SiteIdentifier, user));
|
||||||
|
|
||||||
succeeded = result.IsSuccess;
|
succeeded = result.IsSuccess;
|
||||||
if (succeeded)
|
if (succeeded)
|
||||||
@@ -349,7 +353,9 @@
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
var user = await GetCurrentUserAsync();
|
var user = await GetCurrentUserAsync();
|
||||||
var result = await ArtifactDeploymentService.DeployToAllSitesAsync(user);
|
// Own DI scope (UI-3) — see DeployArtifacts.
|
||||||
|
var result = await ScopeFactory.InNewScopeAsync(
|
||||||
|
(ArtifactDeploymentService svc) => svc.DeployToAllSitesAsync(user));
|
||||||
|
|
||||||
succeeded = result.IsSuccess;
|
succeeded = result.IsSuccess;
|
||||||
if (succeeded)
|
if (succeeded)
|
||||||
|
|||||||
@@ -4,7 +4,8 @@
|
|||||||
@using ZB.MOM.WW.ScadaBridge.Commons.Types.Deployment
|
@using ZB.MOM.WW.ScadaBridge.Commons.Types.Deployment
|
||||||
@using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums
|
@using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums
|
||||||
@attribute [Authorize(Policy = AuthorizationPolicies.RequireDeployment)]
|
@attribute [Authorize(Policy = AuthorizationPolicies.RequireDeployment)]
|
||||||
@inject IDeploymentManagerRepository DeploymentManagerRepository
|
@inject Microsoft.Extensions.DependencyInjection.IServiceScopeFactory ScopeFactory
|
||||||
|
@using Microsoft.Extensions.DependencyInjection
|
||||||
@inject ZB.MOM.WW.ScadaBridge.CentralUI.Auth.SiteScopeService SiteScope
|
@inject ZB.MOM.WW.ScadaBridge.CentralUI.Auth.SiteScopeService SiteScope
|
||||||
@inject ZB.MOM.WW.ScadaBridge.DeploymentManager.IDeploymentStatusNotifier DeploymentStatusNotifier
|
@inject ZB.MOM.WW.ScadaBridge.DeploymentManager.IDeploymentStatusNotifier DeploymentStatusNotifier
|
||||||
@implements IDisposable
|
@implements IDisposable
|
||||||
@@ -615,13 +616,20 @@
|
|||||||
SiteIdScope: siteScope,
|
SiteIdScope: siteScope,
|
||||||
SearchMode: _searchContains ? DeploymentSearchMode.Contains : DeploymentSearchMode.Prefix);
|
SearchMode: _searchContains ? DeploymentSearchMode.Contains : DeploymentSearchMode.Prefix);
|
||||||
|
|
||||||
var page = await DeploymentManagerRepository
|
// Each flight reads through its OWN DI scope (UI-2): flights overlap by design
|
||||||
|
// (push reload, search debounce, page/tile click), and two of them on the one
|
||||||
|
// circuit-scoped DbContext would throw "A second operation was started on this
|
||||||
|
// context instance". The generation guard still decides whose results apply.
|
||||||
|
await using var readScope = ScopeFactory.CreateAsyncScope();
|
||||||
|
var deployments = readScope.ServiceProvider.GetRequiredService<IDeploymentManagerRepository>();
|
||||||
|
|
||||||
|
var page = await deployments
|
||||||
.QueryDeploymentListPageAsync(filter, pageToQuery, PageSize);
|
.QueryDeploymentListPageAsync(filter, pageToQuery, PageSize);
|
||||||
|
|
||||||
// The tile counts deliberately ignore the status filter (see
|
// The tile counts deliberately ignore the status filter (see
|
||||||
// GetDeploymentStatusCountsAsync) so each tile keeps showing its own
|
// GetDeploymentStatusCountsAsync) so each tile keeps showing its own
|
||||||
// total while it is the one selected.
|
// total while it is the one selected.
|
||||||
var counts = await DeploymentManagerRepository.GetDeploymentStatusCountsAsync(filter);
|
var counts = await deployments.GetDeploymentStatusCountsAsync(filter);
|
||||||
|
|
||||||
// A newer flight has started since this one began (its generation is
|
// A newer flight has started since this one began (its generation is
|
||||||
// now the current one) — this flight's results are stale. Discard
|
// now the current one) — this flight's results are stale. Discard
|
||||||
@@ -646,7 +654,7 @@
|
|||||||
if (_currentPage > _totalPages && _totalPages >= 1)
|
if (_currentPage > _totalPages && _totalPages >= 1)
|
||||||
{
|
{
|
||||||
_currentPage = _totalPages;
|
_currentPage = _totalPages;
|
||||||
var reread = await DeploymentManagerRepository
|
var reread = await deployments
|
||||||
.QueryDeploymentListPageAsync(filter, _currentPage, PageSize);
|
.QueryDeploymentListPageAsync(filter, _currentPage, PageSize);
|
||||||
|
|
||||||
if (generation != _requestGeneration)
|
if (generation != _requestGeneration)
|
||||||
|
|||||||
@@ -18,9 +18,6 @@
|
|||||||
@inject ITemplateEngineRepository TemplateEngineRepository
|
@inject ITemplateEngineRepository TemplateEngineRepository
|
||||||
@inject ISiteRepository SiteRepository
|
@inject ISiteRepository SiteRepository
|
||||||
@inject IDeploymentManagerRepository DeploymentManagerRepository
|
@inject IDeploymentManagerRepository DeploymentManagerRepository
|
||||||
@inject DeploymentService DeploymentService
|
|
||||||
@inject AreaService AreaService
|
|
||||||
@inject InstanceService InstanceService
|
|
||||||
@inject AuthenticationStateProvider AuthStateProvider
|
@inject AuthenticationStateProvider AuthStateProvider
|
||||||
@inject ZB.MOM.WW.ScadaBridge.CentralUI.Auth.SiteScopeService SiteScope
|
@inject ZB.MOM.WW.ScadaBridge.CentralUI.Auth.SiteScopeService SiteScope
|
||||||
@inject NavigationManager NavigationManager
|
@inject NavigationManager NavigationManager
|
||||||
@@ -977,7 +974,9 @@
|
|||||||
{
|
{
|
||||||
var user = await GetCurrentUserAsync(inst.Id);
|
var user = await GetCurrentUserAsync(inst.Id);
|
||||||
if (user is null) return;
|
if (user is null) return;
|
||||||
var result = await DeploymentService.DeleteInstanceAsync(inst.Id, user);
|
// Own DI scope (UI-8): the lifecycle command must not share the circuit's context
|
||||||
|
// with the 15 s live tick.
|
||||||
|
var result = await ScopeFactory.InNewScopeAsync((DeploymentService svc) => svc.DeleteInstanceAsync(inst.Id, user));
|
||||||
if (result.IsSuccess)
|
if (result.IsSuccess)
|
||||||
{
|
{
|
||||||
_toast.ShowSuccess($"Instance '{inst.UniqueName}' deleted.");
|
_toast.ShowSuccess($"Instance '{inst.UniqueName}' deleted.");
|
||||||
@@ -1003,7 +1002,7 @@
|
|||||||
{
|
{
|
||||||
var user = await GetCurrentUserAsync(inst.Id);
|
var user = await GetCurrentUserAsync(inst.Id);
|
||||||
if (user is null) return;
|
if (user is null) return;
|
||||||
var result = await DeploymentService.EnableInstanceAsync(inst.Id, user);
|
var result = await ScopeFactory.InNewScopeAsync((DeploymentService svc) => svc.EnableInstanceAsync(inst.Id, user));
|
||||||
if (result.IsSuccess)
|
if (result.IsSuccess)
|
||||||
{
|
{
|
||||||
_toast.ShowSuccess($"Instance '{inst.UniqueName}' enabled.");
|
_toast.ShowSuccess($"Instance '{inst.UniqueName}' enabled.");
|
||||||
@@ -1035,7 +1034,7 @@
|
|||||||
{
|
{
|
||||||
var user = await GetCurrentUserAsync(inst.Id);
|
var user = await GetCurrentUserAsync(inst.Id);
|
||||||
if (user is null) return;
|
if (user is null) return;
|
||||||
var result = await DeploymentService.DisableInstanceAsync(inst.Id, user);
|
var result = await ScopeFactory.InNewScopeAsync((DeploymentService svc) => svc.DisableInstanceAsync(inst.Id, user));
|
||||||
if (result.IsSuccess)
|
if (result.IsSuccess)
|
||||||
{
|
{
|
||||||
_toast.ShowSuccess($"Instance '{inst.UniqueName}' disabled.");
|
_toast.ShowSuccess($"Instance '{inst.UniqueName}' disabled.");
|
||||||
@@ -1175,7 +1174,9 @@
|
|||||||
string? diffError = null;
|
string? diffError = null;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var result = await DeploymentService.GetDeploymentComparisonAsync(inst.Id);
|
// Own DI scope (UI-8): the diff re-flattens the instance (a multi-query read) and
|
||||||
|
// must not overlap the live tick on the circuit's context.
|
||||||
|
var result = await ScopeFactory.InNewScopeAsync((DeploymentService svc) => svc.GetDeploymentComparisonAsync(inst.Id));
|
||||||
if (result.IsSuccess)
|
if (result.IsSuccess)
|
||||||
{
|
{
|
||||||
diffResult = result.Value;
|
diffResult = result.Value;
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
|
||||||
|
namespace ZB.MOM.WW.ScadaBridge.CentralUI.Services;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Runs one page action against a service resolved from its own DI scope (and therefore its
|
||||||
|
/// own <c>ScadaBridgeDbContext</c>), instead of the circuit-lifetime scope the page lives in.
|
||||||
|
/// </summary>
|
||||||
|
/// <remarks>
|
||||||
|
/// <para>
|
||||||
|
/// Use this for every page action that <b>mutates</b> configuration through a scoped service
|
||||||
|
/// (template / folder / shared-script edits, deploys, lifecycle commands, bundle import) and for
|
||||||
|
/// long or concurrent reads that could overlap another query on the circuit context
|
||||||
|
/// (code review 2026-12-02, UI-1/UI-2/UI-3/UI-8).
|
||||||
|
/// </para>
|
||||||
|
/// <para>
|
||||||
|
/// The circuit's own context runs with a no-tracking default
|
||||||
|
/// (<c>CircuitDbContextTrackingHandler</c>), so a load-modify-save service run on it would
|
||||||
|
/// silently persist nothing. A fresh scope gets an ordinary tracking context that starts empty,
|
||||||
|
/// so the service always reads the current row and its write lands; the scope is disposed when
|
||||||
|
/// the action ends, so nothing stale is left behind for the next action, and the action does
|
||||||
|
/// not depend on (or die with) the circuit's scope.
|
||||||
|
/// </para>
|
||||||
|
/// </remarks>
|
||||||
|
public static class ScopedServiceExtensions
|
||||||
|
{
|
||||||
|
/// <summary>Resolves <typeparamref name="TService"/> from a fresh scope and runs <paramref name="action"/> on it.</summary>
|
||||||
|
/// <typeparam name="TService">The scoped service to resolve.</typeparam>
|
||||||
|
/// <typeparam name="TResult">The action's result type.</typeparam>
|
||||||
|
/// <param name="scopes">The root scope factory.</param>
|
||||||
|
/// <param name="action">The action to run; it must finish with the scope (do not return deferred work).</param>
|
||||||
|
/// <returns>The action's result.</returns>
|
||||||
|
public static async Task<TResult> InNewScopeAsync<TService, TResult>(
|
||||||
|
this IServiceScopeFactory scopes, Func<TService, Task<TResult>> action)
|
||||||
|
where TService : notnull
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(scopes);
|
||||||
|
ArgumentNullException.ThrowIfNull(action);
|
||||||
|
await using var scope = scopes.CreateAsyncScope();
|
||||||
|
return await action(scope.ServiceProvider.GetRequiredService<TService>());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -288,4 +288,70 @@ public class SitesPageTests : BunitContext
|
|||||||
Assert.Contains("Artifacts: unavailable", cut.Markup);
|
Assert.Contains("Artifacts: unavailable", cut.Markup);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>Marks the DI scope an artifact deploy ran in, so the test can see it was disposed.</summary>
|
||||||
|
private sealed class ScopeProbe : IDisposable
|
||||||
|
{
|
||||||
|
public bool Disposed { get; private set; }
|
||||||
|
public void Dispose() => Disposed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class ProbingArtifactDeploymentService : ArtifactDeploymentService
|
||||||
|
{
|
||||||
|
private readonly ScopeProbe _probe;
|
||||||
|
private readonly Action<ScopeProbe> _onDeploy;
|
||||||
|
|
||||||
|
public ProbingArtifactDeploymentService(ISiteRepository siteRepo, CommunicationService comms, ScopeProbe probe, Action<ScopeProbe> onDeploy)
|
||||||
|
: base(siteRepo, Substitute.For<IDeploymentManagerRepository>(), Substitute.For<ITemplateEngineRepository>(),
|
||||||
|
Substitute.For<IExternalSystemRepository>(), comms, Substitute.For<IAuditService>(),
|
||||||
|
Options.Create(new DeploymentManagerOptions()), NullLogger<ArtifactDeploymentService>.Instance,
|
||||||
|
new ArtifactRevisionHashService(), new SiteSecretsCollector(Substitute.For<ISecretStore>()))
|
||||||
|
{
|
||||||
|
_probe = probe;
|
||||||
|
_onDeploy = onDeploy;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override Task<ZB.MOM.WW.ScadaBridge.Commons.Types.Result<ArtifactDeploymentSummary>> DeployToAllSitesAsync(
|
||||||
|
string user, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
_onDeploy(_probe);
|
||||||
|
return Task.FromResult(ZB.MOM.WW.ScadaBridge.Commons.Types.Result<ArtifactDeploymentSummary>.Success(
|
||||||
|
new ArtifactDeploymentSummary("dep-1", Array.Empty<SiteArtifactResult>(), 0, 0)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Code review 2026-12-02 UI-3: "Deploy artifacts to all sites" must run on its own DI scope
|
||||||
|
/// (its own DbContext) — not the circuit's — so the post-fan-out record / audit / revision
|
||||||
|
/// stamp neither collide with other page queries nor die with the circuit. The scope the
|
||||||
|
/// deploy ran in is created for the action and disposed when it ends.
|
||||||
|
/// </summary>
|
||||||
|
[Fact]
|
||||||
|
public void DeployToAllSites_RunsInItsOwnScope_DisposedAfterTheAction()
|
||||||
|
{
|
||||||
|
RegisterServices();
|
||||||
|
_siteRepo.GetAllSitesAsync().Returns(Sites(1));
|
||||||
|
_siteRepo.GetAllDataConnectionsAsync().Returns(new List<DataConnection>());
|
||||||
|
|
||||||
|
// The deploy actions demand a fresh Administrator check.
|
||||||
|
Services.AddSingleton<AuthenticationStateProvider>(new TestAuthStateProvider(new ClaimsPrincipal(
|
||||||
|
new ClaimsIdentity(new[]
|
||||||
|
{
|
||||||
|
new Claim(ZB.MOM.WW.ScadaBridge.Security.JwtTokenService.UsernameClaimType, "admin"),
|
||||||
|
new Claim(ZB.MOM.WW.ScadaBridge.Security.JwtTokenService.RoleClaimType, "Administrator"),
|
||||||
|
}, "TestAuth"))));
|
||||||
|
|
||||||
|
ScopeProbe? deployScope = null;
|
||||||
|
Services.AddScoped<ScopeProbe>();
|
||||||
|
Services.AddScoped<ArtifactDeploymentService>(sp => new ProbingArtifactDeploymentService(
|
||||||
|
_siteRepo, sp.GetRequiredService<CommunicationService>(), sp.GetRequiredService<ScopeProbe>(),
|
||||||
|
probe => deployScope = probe));
|
||||||
|
|
||||||
|
var cut = Render<SitesPage>();
|
||||||
|
cut.FindAll("button").First(b => b.TextContent.Contains("Deploy artifacts to all sites", StringComparison.OrdinalIgnoreCase)).Click();
|
||||||
|
|
||||||
|
cut.WaitForAssertion(() => Assert.NotNull(deployScope));
|
||||||
|
cut.WaitForAssertion(() => Assert.True(deployScope!.Disposed,
|
||||||
|
"the deploy must own a fresh scope that ends with the action, not the circuit's scope"));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+108
@@ -0,0 +1,108 @@
|
|||||||
|
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);
|
||||||
|
}
|
||||||
@@ -523,6 +523,59 @@ public class TopologyPageTests : BunitContext
|
|||||||
await _repo.Received(revoked ? 0 : 1).AddAreaAsync(Arg.Any<Area>(), Arg.Any<CancellationToken>());
|
await _repo.Received(revoked ? 0 : 1).AddAreaAsync(Arg.Any<Area>(), Arg.Any<CancellationToken>());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>Marks the DI scope a DeploymentService was resolved from.</summary>
|
||||||
|
private sealed class ScopeProbe : IDisposable
|
||||||
|
{
|
||||||
|
public bool Disposed { get; private set; }
|
||||||
|
public void Dispose() => Disposed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Code review 2026-12-02 UI-8: Diff and the Enable / Disable / Delete lifecycle commands must
|
||||||
|
/// resolve <see cref="DeploymentService"/> from their own DI scope (their own DbContext) so they
|
||||||
|
/// can never overlap the 15 s live tick on the circuit's context. Each action's scope is
|
||||||
|
/// created for it and disposed when it ends.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="handlerName">The private page handler to drive.</param>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
|
[Theory]
|
||||||
|
[InlineData("ShowDiff")]
|
||||||
|
[InlineData("EnableInstance")]
|
||||||
|
public async Task UI8_InstanceActions_RunOnTheirOwnScope(string handlerName)
|
||||||
|
{
|
||||||
|
var instance = new Instance("Pump") { Id = 100, SiteId = 1, AreaId = null, State = InstanceState.Disabled };
|
||||||
|
SeedRepos(sites: [new Site("Plant", "plant") { Id = 1 }], instances: [instance]);
|
||||||
|
_repo.GetInstanceByIdAsync(100, Arg.Any<CancellationToken>()).Returns(instance);
|
||||||
|
|
||||||
|
var probes = new List<ScopeProbe>();
|
||||||
|
Services.AddScoped<ScopeProbe>();
|
||||||
|
Services.AddScoped<DeploymentService>(sp =>
|
||||||
|
{
|
||||||
|
lock (probes) probes.Add(sp.GetRequiredService<ScopeProbe>());
|
||||||
|
return ActivatorUtilities.CreateInstance<DeploymentService>(sp);
|
||||||
|
});
|
||||||
|
|
||||||
|
JSInterop.Mode = JSRuntimeMode.Loose; // the diff dialog's host uses JS interop
|
||||||
|
var cut = RenderLoadedTopology();
|
||||||
|
lock (probes) probes.Clear(); // anything resolved while rendering is not the action's
|
||||||
|
|
||||||
|
var handler = typeof(TopologyPage).GetMethod(handlerName,
|
||||||
|
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!;
|
||||||
|
Task? action = null;
|
||||||
|
// Not awaited inside InvokeAsync: ShowDiff ends by awaiting a dialog that nobody closes.
|
||||||
|
await cut.InvokeAsync(() => { action = (Task)handler.Invoke(cut.Instance, [instance])!; });
|
||||||
|
|
||||||
|
cut.WaitForAssertion(() =>
|
||||||
|
{
|
||||||
|
lock (probes)
|
||||||
|
{
|
||||||
|
Assert.NotEmpty(probes);
|
||||||
|
Assert.All(probes, p => Assert.True(p.Disposed,
|
||||||
|
"the action must own a fresh scope that ends with it, not the circuit's scope"));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>Verifies that an empty state is rendered when there are no sites.</summary>
|
/// <summary>Verifies that an empty state is rendered when there are no sites.</summary>
|
||||||
[Fact]
|
[Fact]
|
||||||
public void Renders_EmptyState_WhenNoSites()
|
public void Renders_EmptyState_WhenNoSites()
|
||||||
|
|||||||
Reference in New Issue
Block a user