fix(central-ui): resolve CentralUI-006 — push-based deployment status via IDeploymentStatusNotifier, remove 10s polling timer

This commit is contained in:
Joseph Doherty
2026-05-17 00:02:45 -04:00
parent a55502254e
commit 34588ae10c
11 changed files with 459 additions and 36 deletions

View File

@@ -0,0 +1,112 @@
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 ScadaLink.CentralUI.Auth;
using ScadaLink.Commons.Entities.Deployment;
using ScadaLink.Commons.Entities.Instances;
using ScadaLink.Commons.Interfaces.Repositories;
using ScadaLink.Commons.Types.Enums;
using ScadaLink.DeploymentManager;
using DeploymentsPage = ScadaLink.CentralUI.Components.Pages.Deployment.Deployments;
namespace ScadaLink.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.
/// </summary>
public class DeploymentsPushUpdateTests : BunitContext
{
private IDeploymentManagerRepository _deployRepo = null!;
private ITemplateEngineRepository _templateRepo = null!;
private DeploymentStatusNotifier _notifier = null!;
private void RegisterServices()
{
_deployRepo = Substitute.For<IDeploymentManagerRepository>();
_templateRepo = Substitute.For<ITemplateEngineRepository>();
_notifier = new DeploymentStatusNotifier(NullLogger<DeploymentStatusNotifier>.Instance);
_templateRepo.GetAllInstancesAsync(Arg.Any<CancellationToken>())
.Returns(new List<Instance>
{
new("Inst-1") { Id = 1, SiteId = 1 }
});
_deployRepo.GetAllDeploymentRecordsAsync(Arg.Any<CancellationToken>())
.Returns(new List<DeploymentRecord>());
Services.AddSingleton(_deployRepo);
Services.AddSingleton(_templateRepo);
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: instances + records each fetched once.
_deployRepo.ClearReceivedCalls();
_templateRepo.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().GetAllDeploymentRecordsAsync(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()
.GetAllDeploymentRecordsAsync(Arg.Any<CancellationToken>());
}
}

View File

@@ -57,6 +57,11 @@ public class TopologyPageTests : BunitContext
// DeploymentService gained a DiffService dependency (DeploymentManager
// contract change); register it so the page's DI graph resolves.
Services.AddScoped<ScadaLink.TemplateEngine.Flattening.DiffService>();
// CentralUI-006: DeploymentService now also depends on the
// deployment-status notifier (a process singleton in production).
Services.AddSingleton<ScadaLink.DeploymentManager.IDeploymentStatusNotifier>(
new ScadaLink.DeploymentManager.DeploymentStatusNotifier(
NullLogger<ScadaLink.DeploymentManager.DeploymentStatusNotifier>.Instance));
Services.AddScoped<DeploymentService>();
Services.AddScoped<AreaService>();
Services.AddScoped<InstanceService>();

View File

@@ -47,7 +47,9 @@ public class DeploymentServiceTests : TestKit
var siteRepo = Substitute.For<ISiteRepository>();
_service = new DeploymentService(
_repo, siteRepo, _pipeline, _comms, _lockManager, _audit,
new DiffService(), options,
new DiffService(),
new DeploymentStatusNotifier(NullLogger<DeploymentStatusNotifier>.Instance),
options,
NullLogger<DeploymentService>.Instance);
}
@@ -577,6 +579,7 @@ public class DeploymentServiceTests : TestKit
return new DeploymentService(
_repo, siteRepo, _pipeline, comms, _lockManager, _audit,
new DiffService(),
new DeploymentStatusNotifier(NullLogger<DeploymentStatusNotifier>.Instance),
Options.Create(new DeploymentManagerOptions { OperationLockTimeout = TimeSpan.FromSeconds(5) }),
NullLogger<DeploymentService>.Instance);
}
@@ -792,6 +795,7 @@ public class DeploymentServiceTests : TestKit
var service = new DeploymentService(
_repo, siteRepo, _pipeline, comms, _lockManager, _audit,
new DiffService(),
new DeploymentStatusNotifier(NullLogger<DeploymentStatusNotifier>.Instance),
Options.Create(new DeploymentManagerOptions
{
OperationLockTimeout = TimeSpan.FromSeconds(5),

View File

@@ -0,0 +1,114 @@
using Akka.TestKit.Xunit2;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using NSubstitute;
using ScadaLink.Commons.Entities.Deployment;
using ScadaLink.Commons.Entities.Instances;
using ScadaLink.Commons.Interfaces.Repositories;
using ScadaLink.Commons.Interfaces.Services;
using ScadaLink.Commons.Types;
using ScadaLink.Commons.Types.Enums;
using ScadaLink.Commons.Types.Flattening;
using ScadaLink.Communication;
using ScadaLink.TemplateEngine.Flattening;
namespace ScadaLink.DeploymentManager.Tests;
/// <summary>
/// CentralUI-006: regression tests proving <see cref="DeploymentService"/>
/// raises <see cref="IDeploymentStatusNotifier.StatusChanged"/> whenever it
/// writes a deployment record's status. This is the event source the Central
/// UI deployment-status page subscribes to instead of polling.
/// </summary>
public class DeploymentStatusNotifierTests : TestKit
{
private readonly IDeploymentManagerRepository _repo;
private readonly IFlatteningPipeline _pipeline;
private readonly CommunicationService _comms;
private readonly OperationLockManager _lockManager;
private readonly IAuditService _audit;
private readonly DeploymentStatusNotifier _notifier;
private readonly DeploymentService _service;
public DeploymentStatusNotifierTests()
{
_repo = Substitute.For<IDeploymentManagerRepository>();
_pipeline = Substitute.For<IFlatteningPipeline>();
_comms = new CommunicationService(
Options.Create(new CommunicationOptions()),
NullLogger<CommunicationService>.Instance);
_lockManager = new OperationLockManager();
_audit = Substitute.For<IAuditService>();
_notifier = new DeploymentStatusNotifier(NullLogger<DeploymentStatusNotifier>.Instance);
var options = Options.Create(new DeploymentManagerOptions
{
OperationLockTimeout = TimeSpan.FromSeconds(5)
});
var siteRepo = Substitute.For<ISiteRepository>();
_service = new DeploymentService(
_repo, siteRepo, _pipeline, _comms, _lockManager, _audit,
new DiffService(), _notifier, options,
NullLogger<DeploymentService>.Instance);
}
[Fact]
public async Task DeployInstanceAsync_RaisesStatusChange_ForEveryRecordStatusWrite()
{
var instance = new Instance("TestInst") { Id = 7, SiteId = 1, State = InstanceState.NotDeployed };
_repo.GetInstanceByIdAsync(7).Returns(instance);
var config = new FlattenedConfiguration { InstanceUniqueName = "TestInst" };
_pipeline.FlattenAndValidateAsync(7, Arg.Any<CancellationToken>())
.Returns(Result<FlatteningPipelineResult>.Success(
new FlatteningPipelineResult(config, "sha256:abc", ValidationResult.Success())));
var changes = new List<DeploymentStatusChange>();
_notifier.StatusChanged += c => changes.Add(c);
// _comms has no actor set, so the deploy reaches the catch block and
// the record ends Failed. The notifier must fire for the Pending,
// InProgress and Failed writes — not be silent (the pre-fix behaviour).
var result = await _service.DeployInstanceAsync(7, "admin");
Assert.True(result.IsFailure);
Assert.NotEmpty(changes);
Assert.All(changes, c => Assert.Equal(7, c.InstanceId));
Assert.Contains(changes, c => c.Status == DeploymentStatus.Pending);
Assert.Contains(changes, c => c.Status == DeploymentStatus.InProgress);
Assert.Contains(changes, c => c.Status == DeploymentStatus.Failed);
// All notifications carry the same deployment id (the one created here).
var deploymentId = changes[0].DeploymentId;
Assert.False(string.IsNullOrEmpty(deploymentId));
Assert.All(changes, c => Assert.Equal(deploymentId, c.DeploymentId));
}
[Fact]
public void NotifyStatusChanged_WithNoSubscribers_DoesNotThrow()
{
var notifier = new DeploymentStatusNotifier(NullLogger<DeploymentStatusNotifier>.Instance);
var ex = Record.Exception(() =>
notifier.NotifyStatusChanged(new DeploymentStatusChange("dep-1", 1, DeploymentStatus.Success)));
Assert.Null(ex);
}
[Fact]
public void NotifyStatusChanged_ThrowingSubscriber_DoesNotBreakOtherSubscribers()
{
var notifier = new DeploymentStatusNotifier(NullLogger<DeploymentStatusNotifier>.Instance);
var reached = false;
notifier.StatusChanged += _ => throw new InvalidOperationException("boom");
notifier.StatusChanged += _ => reached = true;
var ex = Record.Exception(() =>
notifier.NotifyStatusChanged(new DeploymentStatusChange("dep-2", 2, DeploymentStatus.InProgress)));
Assert.Null(ex);
Assert.True(reached, "a faulting subscriber must not stop later subscribers from being notified");
}
}

View File

@@ -56,4 +56,25 @@ public class ServiceCollectionExtensionsTests
{
Assert.Equal("ScadaLink:DeploymentManager", ServiceCollectionExtensions.OptionsSection);
}
// CentralUI-006: the deployment-status notifier must be a singleton so the
// scoped DeploymentService and the Central UI's scoped Blazor page share
// one instance — without that, a push notification raised by the service
// would never reach the page's subscription.
[Fact]
public void AddDeploymentManager_RegistersDeploymentStatusNotifier_AsSingleton()
{
var services = new ServiceCollection();
services.AddLogging();
services.AddDeploymentManager();
using var provider = services.BuildServiceProvider();
var fromRoot = provider.GetRequiredService<IDeploymentStatusNotifier>();
using var scope = provider.CreateScope();
var fromScope = scope.ServiceProvider.GetRequiredService<IDeploymentStatusNotifier>();
Assert.IsType<DeploymentStatusNotifier>(fromRoot);
Assert.Same(fromRoot, fromScope);
}
}