Files
ScadaBridge/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Deployment/DeploymentsPushUpdateTests.cs
T
Joseph Doherty 35ce14138c feat(centralui): server-side paging + server-computed status counts on Deployments (R3)
The Deployment Status page client-materialized the whole deployment list. It read
EVERY DeploymentRecord — an insert-only table, one row per deploy attempt for the
retention window — plus EVERY Instance, then site-scoped, sorted, counted the four
status tiles and sliced a 25-row page in the Blazor circuit's memory. That ran on
first render AND on every IDeploymentStatusNotifier push, so the cost scaled with
the age of the system rather than the size of the page.

All four jobs move into SQL:

- `IDeploymentManagerRepository.QueryDeploymentListPageAsync(filter, page, size)`
  returns one page of `DeploymentListRow` — DeploymentRecord INNER JOINed to
  Instance, so the instance display name and site travel with the rows that need
  them — plus the total count of the filtered set. The join is exact: the FK is
  Restrict and DeleteInstanceAsync removes the records first, so no orphan exists.
- `GetDeploymentStatusCountsAsync(filter)` returns the tile counts from ONE grouped
  aggregation, deliberately ignoring the filter's Status: the tiles are the status
  BREAKDOWN of the filtered set, so honouring it would zero three of four tiles the
  moment an operator clicked one.
- Site scoping runs in the query as `SiteIdScope` resolved through the record's
  instance (DeploymentRecord has no SiteId of its own). An EMPTY grant stays a real
  filter matching nothing, never "unconstrained".
- The now-callerless whole-table `GetAllDeploymentRecordsAsync` is deleted.

OFFSET paging, not the Audit Log's keyset cursor, and deliberately so: this page's
pager is numbered and jump-to-any-page, so it needs a page count, which only a total
can give it — a keyset cursor can express neither, and the total is required for the
tiles regardless. The deep-offset cost that pushes high-volume tables to keyset is
bounded here by the terminal-record retention purge, unlike the 365-day AuditLog.
This mirrors the Notification Outbox, offset-paged for the same reason. Ordering is
DeployedAt DESC, Id DESC — the Id tie-break is load-bearing, because DeployedAt ties
on rapid redeploys and an unstable sort key makes offset paging repeat or drop rows.

UI: the four status tiles become the status filter (click to apply, click again to
clear, aria-pressed, phrasing-only content so a <button> stays valid), plus a
free-text search matched DB-side against instance name, deployment id, revision hash
and initiating user. Search is TRAILING-edge debounced at 500ms — the same Timer +
lock + _disposed idiom as the existing leading-edge push coalescer, minus the leading
edge, because a search box must not query on the first keystroke. A filter change
resets to page 1; a page past the end falls back to the last real page. Bootstrap
only, existing PagerWindow pager retained.

The WP2.4 push coalescing is unchanged and still earns its keep: server paging shrank
what a reload costs, not how many arrive — it now bounds database round-trips rather
than table scans.

Tests: 19 new SQLite repository tests (paging slice + total, tie-break stability
across pages, page/size clamping, past-the-end, the joined projection, every filter
dimension incl. the empty-scope security case, and the grouped counts' status-blind
contract); 15 new bUnit page tests (page-1 request, server total drives the pager,
Next re-queries, tiles show server counts not page counts, tile filter + toggle,
system-wide vs site-scoped scope push, debounce collapses a keystroke burst to one
query, clear-filters, dispose with an armed timer). The two existing Deployments
suites re-point their reload assertions at the new query.

Doc: Component-CentralUI.md Deployment section — the "no server-side paging" known
residual is replaced by the shipped design.
2026-08-15 03:31:28 -04:00

159 lines
6.6 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.Commons.Types.Enums;
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 tests for CentralUI-006. Component-CentralUI "Real-Time Updates"
/// states deployment status transitions push to the UI immediately via SignalR
/// with no polling. The page previously ran a 10-second <c>Timer</c> that
/// reloaded every deployment record + instance map per tick. The fix removes
/// the timer and subscribes to <see cref="IDeploymentStatusNotifier"/>, which
/// <c>DeploymentService</c> raises on every deployment-record status write;
/// Blazor Server then pushes the re-render over its SignalR circuit.
///
/// <para>
/// The "did it reload?" assertions moved from <c>GetAllDeploymentRecordsAsync</c>
/// to <c>QueryDeploymentListPageAsync</c> when the page's read path went
/// server-paged (residual R3) — the push mechanism under test is unchanged, only
/// the query it drives.
/// </para>
/// </summary>
public class DeploymentsPushUpdateTests : BunitContext
{
private IDeploymentManagerRepository _deployRepo = null!;
private DeploymentStatusNotifier _notifier = null!;
private void RegisterServices()
{
_deployRepo = Substitute.For<IDeploymentManagerRepository>();
_notifier = new DeploymentStatusNotifier(NullLogger<DeploymentStatusNotifier>.Instance);
_deployRepo.QueryDeploymentListPageAsync(
Arg.Any<DeploymentListFilter>(), Arg.Any<int>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(DeploymentListPage.Empty);
_deployRepo.GetDeploymentStatusCountsAsync(
Arg.Any<DeploymentListFilter>(), Arg.Any<CancellationToken>())
.Returns(DeploymentStatusCounts.Empty);
Services.AddSingleton(_deployRepo);
Services.AddSingleton<IDeploymentStatusNotifier>(_notifier);
var identity = new ClaimsIdentity(
new[] { new Claim(ClaimTypes.Name, "deployer") }, "TestCookie");
var stubAuth = new StubAuthStateProvider(
new AuthenticationState(new ClaimsPrincipal(identity)));
Services.AddSingleton<AuthenticationStateProvider>(stubAuth);
Services.AddScoped(_ => new SiteScopeService(stubAuth));
}
private sealed class StubAuthStateProvider : AuthenticationStateProvider
{
private readonly AuthenticationState _state;
public StubAuthStateProvider(AuthenticationState state) => _state = state;
public override Task<AuthenticationState> GetAuthenticationStateAsync()
=> Task.FromResult(_state);
}
[Fact]
public void Deployments_DoesNotPoll_HasNoRefreshTimer()
{
// The 10-second polling Timer must be gone — push replaces polling.
var timerField = typeof(DeploymentsPage).GetField(
"_refreshTimer", BindingFlags.Instance | BindingFlags.NonPublic);
Assert.Null(timerField);
}
[Fact]
public void Deployments_StatusChange_TriggersReload()
{
RegisterServices();
var cut = Render<DeploymentsPage>();
// Initial load: the paged query is issued once.
_deployRepo.ClearReceivedCalls();
// A deployment status write in DeploymentManager raises the notifier;
// the page must reload in response (no polling timer involved).
_notifier.NotifyStatusChanged(
new DeploymentStatusChange("dep-1", 1, DeploymentStatus.Success));
cut.WaitForAssertion(() =>
_deployRepo.Received().QueryDeploymentListPageAsync(
Arg.Any<DeploymentListFilter>(), Arg.Any<int>(), Arg.Any<int>(), Arg.Any<CancellationToken>()));
}
[Fact]
public void Deployments_Dispose_UnsubscribesFromNotifier()
{
RegisterServices();
var cut = Render<DeploymentsPage>();
cut.Instance.Dispose();
_deployRepo.ClearReceivedCalls();
// After disposal, a status change must NOT touch the disposed component.
_notifier.NotifyStatusChanged(
new DeploymentStatusChange("dep-2", 1, DeploymentStatus.Failed));
_deployRepo.DidNotReceive().QueryDeploymentListPageAsync(
Arg.Any<DeploymentListFilter>(), Arg.Any<int>(), Arg.Any<int>(), Arg.Any<CancellationToken>());
}
/// <summary>
/// Regression test for CentralUI-022. The notifier is a process singleton:
/// it can read its subscriber list and begin invoking
/// <c>OnDeploymentStatusChanged</c> on the DeploymentManager thread an
/// instant before the component is disposed. The handler must no-op against
/// a disposed component rather than letting <c>InvokeAsync</c> throw an
/// unobserved <see cref="ObjectDisposedException"/>.
/// </summary>
[Fact]
public void Deployments_HasDisposalGuardField()
{
var field = typeof(DeploymentsPage).GetField(
"_disposed", BindingFlags.Instance | BindingFlags.NonPublic);
Assert.NotNull(field);
Assert.Equal(typeof(bool), field!.FieldType);
}
[Fact]
public void Deployments_StatusChangeAfterDispose_DoesNotThrowOrReload()
{
RegisterServices();
var cut = Render<DeploymentsPage>();
var component = cut.Instance;
component.Dispose();
_deployRepo.ClearReceivedCalls();
// Simulate the race: the notifier captured the handler before the
// Dispose() unsubscribe and invokes it directly against the now-disposed
// component. Pre-fix this dispatched InvokeAsync against a dead circuit
// and threw ObjectDisposedException on a fire-and-forget task.
var handler = typeof(DeploymentsPage).GetMethod(
"OnDeploymentStatusChanged", BindingFlags.Instance | BindingFlags.NonPublic)!;
var ex = Record.Exception(() => handler.Invoke(component,
new object[] { new DeploymentStatusChange("dep-9", 1, DeploymentStatus.Success) }));
Assert.Null(ex);
// The guard short-circuits before any reload is attempted.
_deployRepo.DidNotReceive().QueryDeploymentListPageAsync(
Arg.Any<DeploymentListFilter>(), Arg.Any<int>(), Arg.Any<int>(), Arg.Any<CancellationToken>());
}
}