Merge branch 'review/wp5' into review/integration
This commit is contained in:
@@ -288,4 +288,70 @@ public class SitesPageTests : BunitContext
|
||||
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"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -358,4 +358,35 @@ public class DataConnectionsPageTests : BunitContext
|
||||
Assert.Contains("PLC-A", cut.Markup);
|
||||
Assert.Contains("PLC-B", cut.Markup);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Code review 2026-12-02 UI-4: a navigation during the initial loads disposes the page
|
||||
/// first; the continuation must not then start the 10 s health poll timer.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task DisposedDuringInitialLoad_CreatesNoHealthTimer()
|
||||
{
|
||||
SeedRepos();
|
||||
// Hold the SECOND initial load (the health map) open: the timer is created right
|
||||
// after it, so a dispose while it is in flight is the leak window.
|
||||
var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var gate = new TaskCompletionSource<IReadOnlyDictionary<int, ConnectionHealth>>(
|
||||
TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
_healthQuery.GetConnectionHealthAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(_ => { entered.TrySetResult(); return gate.Task; });
|
||||
|
||||
var cut = Render<DataConnectionsPage>();
|
||||
await entered.Task.WaitAsync(TimeSpan.FromSeconds(10));
|
||||
var page = cut.Instance;
|
||||
await cut.InvokeAsync(page.Dispose);
|
||||
|
||||
gate.SetResult(new Dictionary<int, ConnectionHealth>());
|
||||
await cut.InvokeAsync(() => { });
|
||||
await cut.InvokeAsync(() => { });
|
||||
|
||||
Assert.Null(typeof(DataConnectionsPage)
|
||||
.GetField("_healthTimer", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!
|
||||
.GetValue(page));
|
||||
}
|
||||
}
|
||||
|
||||
+156
@@ -0,0 +1,156 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -439,4 +439,28 @@ public class AlarmSummaryRenderTests : BunitContext
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Code review 2026-12-02 UI-4: picking a site runs a fan-out that can take seconds; if the
|
||||
/// page is disposed meanwhile, the continuation must not start the 15 s poll timer.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task DisposedDuringSiteFanOut_CreatesNoPollTimer()
|
||||
{
|
||||
var gate = new TaskCompletionSource<AlarmSummaryResult>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
_summary.GetSiteAlarmsAsync(Arg.Any<int>(), Arg.Any<CancellationToken>()).Returns(gate.Task);
|
||||
|
||||
var cut = Render<AlarmSummaryPage>();
|
||||
var page = cut.Instance;
|
||||
var change = cut.Find("[data-test='alarm-summary-site']").ChangeAsync(new() { Value = "1" });
|
||||
await cut.InvokeAsync(page.Dispose);
|
||||
|
||||
gate.SetResult(new AlarmSummaryResult(new List<AlarmSummaryRow>(), Array.Empty<string>()));
|
||||
await change.WaitAsync(TimeSpan.FromSeconds(10));
|
||||
|
||||
Assert.Null(typeof(AlarmSummaryPage)
|
||||
.GetField("_refreshTimer", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!
|
||||
.GetValue(page));
|
||||
}
|
||||
}
|
||||
|
||||
+65
@@ -106,4 +106,69 @@ public class PendingUpdatesHealthTilesTests : BunitContext
|
||||
|
||||
cut.WaitForAssertion(() => Assert.Equal("0", cut.Find("[data-test='pending-updates-instances'] h3").TextContent.Trim()));
|
||||
}
|
||||
|
||||
/// <summary>Counts subscriptions so a test can see a leaked handler on the singleton cache.</summary>
|
||||
private sealed class CountingCache : IPendingUpdatesCache
|
||||
{
|
||||
public TaskCompletionSource<PendingUpdatesSnapshot> Gate { get; } =
|
||||
new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
private Action? _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 Task<PendingUpdatesSnapshot> GetAsync(bool forceRefresh = false, CancellationToken cancellationToken = default)
|
||||
=> Gate.Task;
|
||||
|
||||
public event Action? Invalidated
|
||||
{
|
||||
add => _handlers += value;
|
||||
remove => _handlers -= value;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Code review 2026-12-02 UI-4: disposed while the first snapshot load is in flight, the
|
||||
/// tiles must not start their poll timer, and must leave no handler on the singleton cache.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task DisposedDuringFirstLoad_CreatesNoTimer_AndLeavesNoSubscription()
|
||||
{
|
||||
var cache = new CountingCache();
|
||||
var cut = RenderFor(cache, Role(Roles.Deployer));
|
||||
var tiles = cut.Instance;
|
||||
await cut.InvokeAsync(tiles.Dispose);
|
||||
|
||||
cache.Gate.SetResult(new PendingUpdatesSnapshot(DateTimeOffset.UtcNow, Array.Empty<SitePendingUpdates>()));
|
||||
await cut.InvokeAsync(() => { });
|
||||
await cut.InvokeAsync(() => { });
|
||||
|
||||
Assert.Null(typeof(PendingUpdatesHealthTiles)
|
||||
.GetField("_timer", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!
|
||||
.GetValue(tiles));
|
||||
Assert.Equal(0, cache.Subscribers);
|
||||
}
|
||||
|
||||
/// <summary>Disposed while the cascaded auth state is still pending, the tiles never subscribe.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task DisposedBeforeAuthResolves_NeverSubscribes()
|
||||
{
|
||||
var cache = new CountingCache();
|
||||
var auth = new TaskCompletionSource<AuthenticationState>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
Services.AddScoped<SiteScopeService>();
|
||||
Services.AddSingleton<IPendingUpdatesCache>(cache);
|
||||
var cut = Render<PendingUpdatesHealthTiles>(ps => ps.AddCascadingValue(auth.Task));
|
||||
var tiles = cut.Instance;
|
||||
await cut.InvokeAsync(tiles.Dispose);
|
||||
|
||||
auth.SetResult(new AuthenticationState(new ClaimsPrincipal(
|
||||
new ClaimsIdentity(new[] { Role(Roles.Deployer) }, "TestAuth"))));
|
||||
await cut.InvokeAsync(() => { });
|
||||
await cut.InvokeAsync(() => { });
|
||||
|
||||
Assert.Equal(0, cache.Subscribers);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -894,4 +894,39 @@ public class HealthPageTests : BunitContext
|
||||
Nodes: Array.Empty<SiteCallNodeKpiSnapshot>())));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Code review 2026-12-02 UI-4: navigating away while the initial loads are still running
|
||||
/// disposes the page first; the load's continuation must then not create the 10 s refresh
|
||||
/// timer (it would never be disposed and would root the dead circuit).
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task DisposedDuringInitialLoad_CreatesNoRefreshTimer()
|
||||
{
|
||||
SeedSites("site-a");
|
||||
var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var gate = new TaskCompletionSource<IReadOnlyList<KpiSeriesPoint>>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var kpiHistory = Substitute.For<IKpiHistoryQueryService>();
|
||||
kpiHistory.GetSeriesAsync(
|
||||
Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string?>(),
|
||||
Arg.Any<DateTime>(), Arg.Any<DateTime>(), Arg.Any<int?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_ => { entered.TrySetResult(); return gate.Task; });
|
||||
Services.AddSingleton(kpiHistory);
|
||||
|
||||
var host = RenderHealthPage();
|
||||
await entered.Task.WaitAsync(TimeSpan.FromSeconds(10)); // the last load phase is in flight
|
||||
var page = host.Instance;
|
||||
await host.InvokeAsync(page.Dispose);
|
||||
|
||||
gate.SetResult(SampleSeries());
|
||||
host.WaitForAssertion(() => Assert.False((bool)typeof(HealthPage)
|
||||
.GetField("_trendsLoading", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!
|
||||
.GetValue(page)!));
|
||||
await host.InvokeAsync(() => { });
|
||||
|
||||
Assert.Null(typeof(HealthPage)
|
||||
.GetField("_refreshTimer", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!
|
||||
.GetValue(page));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -179,6 +179,56 @@ public class NotificationReportPageTests : BunitContext
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Code review 2026-12-02 UI-11: a parked row whose source site no longer resolves (site
|
||||
/// deleted or renamed) stays visible; a system-wide user can Retry it, while a site-scoped
|
||||
/// user is still refused (there is no Site.Id to authorize against).
|
||||
/// </summary>
|
||||
/// <param name="siteScoped">Whether the caller carries a SiteId claim (site-scoped Deployer).</param>
|
||||
[Theory]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
public void Retry_OnRowFromADeletedSite_AllowedSystemWide_DeniedScoped(bool siteScoped)
|
||||
{
|
||||
_queryReply = _queryReply with
|
||||
{
|
||||
Notifications = new List<NotificationSummary>
|
||||
{
|
||||
new("notif-cccccccc-3333", "Email", "Ops On-Call", "Orphaned alert",
|
||||
"Parked", RetryCount: 5, LastError: "SMTP timeout", SourceSiteId: "deleted-site",
|
||||
SourceInstanceId: "Pump-009", CreatedAt: DateTimeOffset.UtcNow.AddMinutes(-30),
|
||||
DeliveredAt: null, IsStuck: false),
|
||||
},
|
||||
TotalCount = 1,
|
||||
};
|
||||
if (siteScoped)
|
||||
{
|
||||
var claims = new[]
|
||||
{
|
||||
new Claim(JwtTokenService.UsernameClaimType, "tester"),
|
||||
new Claim(JwtTokenService.RoleClaimType, "Deployer"),
|
||||
new Claim(JwtTokenService.SiteIdClaimType, "1"),
|
||||
};
|
||||
Services.AddSingleton<AuthenticationStateProvider>(
|
||||
new TestAuthStateProvider(new ClaimsPrincipal(new ClaimsIdentity(claims, "TestAuth"))));
|
||||
}
|
||||
|
||||
var cut = Render<NotificationReportPage>();
|
||||
cut.WaitForState(() => cut.Markup.Contains("Orphaned alert"));
|
||||
cut.FindAll("tbody tr").First(r => r.TextContent.Contains("Orphaned alert"))
|
||||
.QuerySelectorAll("button").First(b => b.TextContent.Contains("Retry")).Click();
|
||||
|
||||
if (siteScoped)
|
||||
{
|
||||
cut.WaitForAssertion(() => Assert.Contains("not permitted to act on notifications", cut.Markup));
|
||||
Assert.Empty(_retryRequests);
|
||||
}
|
||||
else
|
||||
{
|
||||
cut.WaitForAssertion(() => Assert.Equal("notif-cccccccc-3333", Assert.Single(_retryRequests).NotificationId));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Verifies that a query failure shows an error message.</summary>
|
||||
[Fact]
|
||||
public void QueryFailure_ShowsErrorMessage()
|
||||
|
||||
@@ -221,6 +221,56 @@ public class SiteCallsReportPageTests : BunitContext
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Code review 2026-12-02 UI-11: a parked cached call whose source site no longer resolves
|
||||
/// (site deleted or renamed) stays visible; a system-wide user can Retry it, while a
|
||||
/// site-scoped user is still refused.
|
||||
/// </summary>
|
||||
/// <param name="siteScoped">Whether the caller carries a SiteId claim (site-scoped Deployer).</param>
|
||||
[Theory]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
public void Retry_OnRowFromADeletedSite_AllowedSystemWide_DeniedScoped(bool siteScoped)
|
||||
{
|
||||
var orphanId = Guid.Parse("33333333-3333-3333-3333-333333333333");
|
||||
_queryReply = _queryReply with
|
||||
{
|
||||
SiteCalls = new List<SiteCallSummary>
|
||||
{
|
||||
new(orphanId, "deleted-site", "ApiOutbound", "ERP.Orphan", "Parked",
|
||||
RetryCount: 5, LastError: "HTTP 503", HttpStatus: 503,
|
||||
CreatedAtUtc: DateTime.UtcNow.AddMinutes(-30), UpdatedAtUtc: DateTime.UtcNow.AddMinutes(-5),
|
||||
TerminalAtUtc: null, IsStuck: false),
|
||||
},
|
||||
};
|
||||
if (siteScoped)
|
||||
{
|
||||
var claims = new[]
|
||||
{
|
||||
new Claim(JwtTokenService.UsernameClaimType, "tester"),
|
||||
new Claim(JwtTokenService.RoleClaimType, "Deployer"),
|
||||
new Claim(JwtTokenService.SiteIdClaimType, "1"),
|
||||
};
|
||||
Services.AddSingleton<AuthenticationStateProvider>(
|
||||
new TestAuthStateProvider(new ClaimsPrincipal(new ClaimsIdentity(claims, "TestAuth"))));
|
||||
}
|
||||
|
||||
var cut = Render<SiteCallsReportPage>();
|
||||
cut.WaitForState(() => cut.Markup.Contains("ERP.Orphan"));
|
||||
cut.FindAll("tbody tr").First(r => r.TextContent.Contains("ERP.Orphan"))
|
||||
.QuerySelectorAll("button").First(b => b.TextContent.Contains("Retry")).Click();
|
||||
|
||||
if (siteScoped)
|
||||
{
|
||||
cut.WaitForAssertion(() => Assert.Contains("not permitted to act on cached calls", cut.Markup));
|
||||
Assert.Empty(_retryRequests);
|
||||
}
|
||||
else
|
||||
{
|
||||
cut.WaitForAssertion(() => Assert.Equal(orphanId, Assert.Single(_retryRequests).TrackedOperationId));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Verifies that clicking Discard on a parked row relays the discard to the owning site.</summary>
|
||||
[Fact]
|
||||
public void ClickDiscard_OnParkedRow_RelaysDiscardToOwningSite()
|
||||
|
||||
+230
@@ -0,0 +1,230 @@
|
||||
using System.Text.RegularExpressions;
|
||||
using Microsoft.AspNetCore.Components.Server.Circuits;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
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.Entities.Templates;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Types.Templates;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
|
||||
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase;
|
||||
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Repositories;
|
||||
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Services;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.CentralUI.Tests.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Code review 2026-12-02 UI-1: the circuit-lifetime configuration DbContext served stale
|
||||
/// tracked entities after changes made in another scope. The circuit's context now reads with a
|
||||
/// no-tracking default (<see cref="CircuitDbContextTrackingHandler"/>), contexts in every other
|
||||
/// scope keep EF's tracking default, and no page runs a mutating service on the circuit's context.
|
||||
/// These tests drive the three scenarios from the finding against a real (SQLite) context.
|
||||
/// </summary>
|
||||
public sealed class CircuitDbContextTrackingTests : IDisposable
|
||||
{
|
||||
private readonly SqliteConnection _connection = new("Data Source=:memory:");
|
||||
private readonly ServiceProvider _root;
|
||||
|
||||
public CircuitDbContextTrackingTests()
|
||||
{
|
||||
_connection.Open();
|
||||
var options = new DbContextOptionsBuilder<ScadaBridgeDbContext>().UseSqlite(_connection).Options;
|
||||
var services = new ServiceCollection();
|
||||
services.AddScoped(_ => new ScadaBridgeDbContext(options));
|
||||
services.AddSingleton<ITemplateGraphWatermark, TemplateGraphWatermark>();
|
||||
services.AddScoped<ISiteRepository, SiteRepository>();
|
||||
services.AddScoped<ITemplateEngineRepository, TemplateEngineRepository>();
|
||||
services.AddScoped<CircuitDbContextTrackingHandler>();
|
||||
_root = services.BuildServiceProvider();
|
||||
using var scope = _root.CreateScope();
|
||||
scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>().Database.EnsureCreated();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_root.Dispose();
|
||||
_connection.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>Opens a scope shaped like a Blazor circuit: the circuit handler is built first.</summary>
|
||||
private IServiceScope OpenCircuitScope(bool withHandler = true)
|
||||
{
|
||||
var scope = _root.CreateScope();
|
||||
if (withHandler)
|
||||
scope.ServiceProvider.GetRequiredService<CircuitDbContextTrackingHandler>();
|
||||
return scope;
|
||||
}
|
||||
|
||||
private async Task InOtherScopeAsync(Func<ScadaBridgeDbContext, Task> change)
|
||||
{
|
||||
using var scope = _root.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
|
||||
await change(db);
|
||||
await db.SaveChangesAsync();
|
||||
}
|
||||
|
||||
private async Task<(int SiteA, int SiteB, int ConnectionId)> SeedConnectionAsync()
|
||||
{
|
||||
using var scope = _root.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
|
||||
var a = new Site("Site A", "site-a");
|
||||
var b = new Site("Site B", "site-b");
|
||||
db.Sites.AddRange(a, b);
|
||||
await db.SaveChangesAsync();
|
||||
var connection = new DataConnection("PLC", "OpcUa", a.Id);
|
||||
db.DataConnections.Add(connection);
|
||||
await db.SaveChangesAsync();
|
||||
return (a.Id, b.Id, connection.Id);
|
||||
}
|
||||
|
||||
/// <summary>The handler switches only the circuit scope's context; other scopes keep tracking.</summary>
|
||||
[Fact]
|
||||
public void Handler_SetsNoTrackingOnTheCircuitContextOnly()
|
||||
{
|
||||
using var circuit = OpenCircuitScope();
|
||||
using var command = _root.CreateScope();
|
||||
|
||||
Assert.Equal(QueryTrackingBehavior.NoTracking,
|
||||
circuit.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>().ChangeTracker.QueryTrackingBehavior);
|
||||
Assert.Equal(QueryTrackingBehavior.TrackAll,
|
||||
command.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>().ChangeTracker.QueryTrackingBehavior);
|
||||
}
|
||||
|
||||
/// <summary>The handler tolerates a host with no configuration database registered.</summary>
|
||||
[Fact]
|
||||
public void Handler_WithoutAConfigurationDatabase_IsANoOp()
|
||||
{
|
||||
using var empty = new ServiceCollection().BuildServiceProvider();
|
||||
_ = new CircuitDbContextTrackingHandler(empty);
|
||||
}
|
||||
|
||||
/// <summary>AddCentralUI registers the handler as a circuit handler.</summary>
|
||||
[Fact]
|
||||
public void AddCentralUI_RegistersTheTrackingHandler()
|
||||
{
|
||||
var services = new ServiceCollection();
|
||||
services.AddCentralUI();
|
||||
Assert.Contains(services, d => d.ServiceType == typeof(CircuitHandler)
|
||||
&& d.ImplementationType == typeof(CircuitDbContextTrackingHandler)
|
||||
&& d.Lifetime == ServiceLifetime.Scoped);
|
||||
}
|
||||
|
||||
/// <summary>Scenario 1: a data connection moved in another scope shows under its new site.</summary>
|
||||
/// <param name="withHandler">Whether the circuit scope runs the no-tracking handler.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Theory]
|
||||
[InlineData(true)]
|
||||
[InlineData(false)]
|
||||
public async Task MovedDataConnection_IsSeenOnReload(bool withHandler)
|
||||
{
|
||||
var (_, siteB, connectionId) = await SeedConnectionAsync();
|
||||
using var circuit = OpenCircuitScope(withHandler);
|
||||
var repo = circuit.ServiceProvider.GetRequiredService<ISiteRepository>();
|
||||
Assert.NotEqual(siteB, (await repo.GetAllDataConnectionsAsync()).Single().SiteId);
|
||||
|
||||
// The Move to Site… dialog moves it through the ManagementActor, i.e. another scope.
|
||||
await InOtherScopeAsync(async db => (await db.DataConnections.SingleAsync(c => c.Id == connectionId)).SiteId = siteB);
|
||||
|
||||
var reloaded = (await repo.GetAllDataConnectionsAsync()).Single().SiteId;
|
||||
if (withHandler)
|
||||
Assert.Equal(siteB, reloaded);
|
||||
else
|
||||
Assert.NotEqual(siteB, reloaded); // the pre-fix behaviour this guards against
|
||||
}
|
||||
|
||||
/// <summary>Scenario 2: a renamed / re-parented area is seen by the next Topology refresh.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task RenamedArea_IsSeenOnRefresh()
|
||||
{
|
||||
var (siteA, _, _) = await SeedConnectionAsync();
|
||||
int areaId;
|
||||
using (var seed = _root.CreateScope())
|
||||
{
|
||||
var db = seed.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
|
||||
var area = new Area("Line 1") { SiteId = siteA };
|
||||
db.Areas.Add(area);
|
||||
await db.SaveChangesAsync();
|
||||
areaId = area.Id;
|
||||
}
|
||||
|
||||
using var circuit = OpenCircuitScope();
|
||||
var repo = circuit.ServiceProvider.GetRequiredService<ITemplateEngineRepository>();
|
||||
Assert.Equal("Line 1", (await repo.GetAreasBySiteIdAsync(siteA)).Single().Name);
|
||||
|
||||
await InOtherScopeAsync(async db => (await db.Areas.SingleAsync(a => a.Id == areaId)).Name = "Line 1 (renamed)");
|
||||
|
||||
Assert.Equal("Line 1 (renamed)", (await repo.GetAreasBySiteIdAsync(siteA)).Single().Name);
|
||||
}
|
||||
|
||||
/// <summary>Scenario 3: a script edited by the CLI / an import is what the editor reloads.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task ScriptEditedElsewhere_IsWhatTheEditorReloads()
|
||||
{
|
||||
int templateId, scriptId;
|
||||
using (var seed = _root.CreateScope())
|
||||
{
|
||||
var db = seed.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
|
||||
var template = new Template("Pump");
|
||||
template.Scripts.Add(new TemplateScript("OnStart", "return 1;"));
|
||||
db.Templates.Add(template);
|
||||
await db.SaveChangesAsync();
|
||||
templateId = template.Id;
|
||||
scriptId = template.Scripts.Single().Id;
|
||||
}
|
||||
|
||||
using var circuit = OpenCircuitScope();
|
||||
var repo = circuit.ServiceProvider.GetRequiredService<ITemplateEngineRepository>();
|
||||
Assert.Equal("return 1;", (await repo.GetTemplateWithChildrenAsync(templateId))!.Scripts.Single().Code);
|
||||
|
||||
await InOtherScopeAsync(async db => (await db.TemplateScripts.SingleAsync(s => s.Id == scriptId)).Code = "return 2;");
|
||||
|
||||
Assert.Equal("return 2;", (await repo.GetScriptsByTemplateIdAsync(templateId)).Single().Code);
|
||||
Assert.Equal("return 2;", (await repo.GetTemplateWithChildrenAsync(templateId))!.Scripts.Single().Code);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The circuit's context reads without tracking, so a load-modify-save service run on it
|
||||
/// would silently persist nothing. Guard: no CentralUI page or component calls a mutating
|
||||
/// method on a circuit-injected instance of one of the load-modify-save services; those calls
|
||||
/// go through <see cref="ScopedServiceExtensions.InNewScopeAsync{TService, TResult}"/> (or the
|
||||
/// configuration command boundary).
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void NoPageMutatesThroughACircuitInjectedLoadModifySaveService()
|
||||
{
|
||||
var root = AppContext.BaseDirectory;
|
||||
for (var i = 0; i < 6; i++) root = Directory.GetParent(root)!.FullName;
|
||||
var uiRoot = Path.Combine(root, "src", "ZB.MOM.WW.ScadaBridge.CentralUI");
|
||||
Assert.True(Directory.Exists(uiRoot), uiRoot);
|
||||
|
||||
const string ServiceTypes = "TemplateService|TemplateFolderService|SharedScriptService|InstanceService|AreaService|"
|
||||
+ "SiteService|DeploymentService|ArtifactDeploymentService|IBundleImporter|TemplateDeletionService";
|
||||
var injected = new Regex(
|
||||
@"(?:@inject\s+(?:[\w.]+\.)?(?<type>" + ServiceTypes + @")\s+(?<name>\w+))"
|
||||
+ @"|(?:\[Inject\]\s*(?:private|public|protected|internal)?\s*(?:[\w.]+\.)?(?<type>" + ServiceTypes + @")\s+(?<name>\w+))");
|
||||
var offenders = new List<string>();
|
||||
foreach (var file in Directory.EnumerateFiles(uiRoot, "*.*", SearchOption.AllDirectories)
|
||||
.Where(f => f.EndsWith(".razor", StringComparison.Ordinal) || f.EndsWith(".razor.cs", StringComparison.Ordinal))
|
||||
.Where(f => !f.Contains($"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}", StringComparison.Ordinal)))
|
||||
{
|
||||
var text = File.ReadAllText(file);
|
||||
foreach (Match m in injected.Matches(text))
|
||||
{
|
||||
var name = m.Groups["name"].Value;
|
||||
var mutation = new Regex(@"\b" + Regex.Escape(name)
|
||||
+ @"\.(?:Create|Update|Delete|Add|Remove|Move|Rename|Reorder|Resync|Set|Enable|Disable|Deploy|Retry|Apply|Import)\w*\(");
|
||||
foreach (Match call in mutation.Matches(text))
|
||||
offenders.Add($"{Path.GetFileName(file)}: {call.Value}");
|
||||
}
|
||||
}
|
||||
|
||||
Assert.True(offenders.Count == 0,
|
||||
"Mutating call on a circuit-scoped service (run it via ScopeFactory.InNewScopeAsync instead): "
|
||||
+ string.Join("; ", offenders));
|
||||
}
|
||||
}
|
||||
@@ -523,6 +523,59 @@ public class TopologyPageTests : BunitContext
|
||||
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>
|
||||
[Fact]
|
||||
public void Renders_EmptyState_WhenNoSites()
|
||||
|
||||
Reference in New Issue
Block a user