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

@@ -8,7 +8,7 @@
| Last reviewed | 2026-05-16 | | Last reviewed | 2026-05-16 |
| Reviewer | claude-agent | | Reviewer | claude-agent |
| Commit reviewed | `9c60592` | | Commit reviewed | `9c60592` |
| Open findings | 1 | | Open findings | 0 |
## Summary ## Summary
@@ -318,7 +318,7 @@ longer imposes a fixed absolute cap. `dotnet build ScadaLink.slnx` clean;
|--|--| |--|--|
| Severity | Medium | | Severity | Medium |
| Category | Design-document adherence | | Category | Design-document adherence |
| Status | Open | | Status | Resolved |
| Location | `src/ScadaLink.CentralUI/Components/Pages/Deployment/Deployments.razor:196-216` | | Location | `src/ScadaLink.CentralUI/Components/Pages/Deployment/Deployments.razor:196-216` |
**Description** **Description**
@@ -341,16 +341,59 @@ If polling is kept as a fallback, fetch only changed/in-progress records.
**Resolution** **Resolution**
_Unresolved — a genuine SignalR-push fix requires an event source in another Resolved 2026-05-16 (commit `<pending>`) — cross-module fix (CentralUI +
module._ Verified 2026-05-16: `Deployments.razor` does poll every 10s, contrary DeploymentManager), explicitly authorized. Root cause confirmed against the
to the design doc. But a real push implementation needs the **Deployment source: `Deployments.razor` ran a `Timer` (`OnInitializedAsync``StartTimer`,
Manager** module (`ScadaLink.DeploymentManager``DeploymentService` / 10s interval) that, every tick and for every open Blazor circuit, reloaded all
`ArtifactDeploymentService` write the `DeploymentRecord` rows) to raise a deployment records (`GetAllDeploymentRecordsAsync`) and the full instance map
status-change event/observable that the page subscribes to; there is no such (`GetAllInstancesAsync`) — contradicting Component-CentralUI "Real-Time Updates"
event today and no CentralUI-only seam to subscribe to. Building that event ("transitions push to the UI immediately via SignalR … no polling required").
source is out of scope for a CentralUI-only review. Left Open and surfaced for a
follow-up that adds a deployment-status broadcaster in DeploymentManager (or a **Process/DI topology confirmed.** `ScadaLink.Host/Program.cs` calls both
design-doc amendment acknowledging the polling fallback). `AddDeploymentManager()` (line 75) and `AddCentralUI()` (line 77) on the same
`builder.Services` — DeploymentManager and the Central UI run **in the same
central Host process**, so a DI singleton is genuinely shared between the
DeploymentManager services and the Blazor circuit's scoped components. The
shared-singleton seam is real; no out-of-process fallback was needed.
**What was implemented — push-based updates.** A new
`IDeploymentStatusNotifier` (`ScadaLink.DeploymentManager/IDeploymentStatusNotifier.cs`)
with a C# `event Action<DeploymentStatusChange>` and a small payload
(`DeploymentStatusChange` = deployment id + instance id + new status). Its
implementation `DeploymentStatusNotifier` invokes each subscriber in isolation
and swallows/logs handler exceptions so a faulting circuit cannot break the
deployment pipeline. It is registered as a **singleton** in `AddDeploymentManager`
(`ServiceCollectionExtensions`). Every place `DeploymentService` writes a
`DeploymentRecord` status now raises the notifier: the `Pending` create, the
`InProgress` update, the site-response terminal update, the `Failed` cleanup
write in the catch block, and the `DeploymentManager-006` reconciled-`Success`
write — five call sites via a private `NotifyStatusChange` helper.
`ArtifactDeploymentService` was inspected and writes only
`SystemArtifactDeploymentRecord` rows, which `Deployments.razor` does not
display, so it correctly raises nothing. `Deployments.razor` no longer has a
`Timer`: `OnInitializedAsync` subscribes to `IDeploymentStatusNotifier.StatusChanged`,
the handler reloads via `InvokeAsync(StateHasChanged)` (the notifier event is
raised on the DeploymentManager service thread), and `Dispose` unsubscribes.
Blazor Server pushes the re-render to the browser over its SignalR circuit
automatically — satisfying the documented design. The existing "Pause/Resume
updates" toggle now gates whether incoming push events are acted on, and
"Refresh" still forces a manual reload. CLAUDE.md UI rules kept: Blazor Server +
Bootstrap, custom components, no third-party frameworks.
Regression tests fail against the pre-fix code and pass after. DeploymentManager
(`DeploymentStatusNotifierTests`): `DeployInstanceAsync_RaisesStatusChange_ForEveryRecordStatusWrite`
(pre-fix: no notifier, fails to compile / silent), plus
`NotifyStatusChanged_WithNoSubscribers_DoesNotThrow` and
`NotifyStatusChanged_ThrowingSubscriber_DoesNotBreakOtherSubscribers`;
`ServiceCollectionExtensionsTests.AddDeploymentManager_RegistersDeploymentStatusNotifier_AsSingleton`
pins the shared-singleton seam. CentralUI (`DeploymentsPushUpdateTests`):
`Deployments_DoesNotPoll_HasNoRefreshTimer` (pre-fix: the `_refreshTimer` field
existed — confirmed failing), `Deployments_StatusChange_TriggersReload`, and
`Deployments_Dispose_UnsubscribesFromNotifier`. `dotnet build ScadaLink.slnx`
clean (0 warnings); `tests/ScadaLink.DeploymentManager.Tests` 76 passed,
`tests/ScadaLink.CentralUI.Tests` 257 passed. (`TopologyPageTests`' DI fixture
was also updated to register the new notifier, since it constructs the real
`DeploymentService`.)
### CentralUI-007 — Monitoring nav links to Deployment-only pages are shown to all roles ### CentralUI-007 — Monitoring nav links to Deployment-only pages are shown to all roles

View File

@@ -8,6 +8,7 @@
@inject IDeploymentManagerRepository DeploymentManagerRepository @inject IDeploymentManagerRepository DeploymentManagerRepository
@inject ITemplateEngineRepository TemplateEngineRepository @inject ITemplateEngineRepository TemplateEngineRepository
@inject ScadaLink.CentralUI.Auth.SiteScopeService SiteScope @inject ScadaLink.CentralUI.Auth.SiteScopeService SiteScope
@inject ScadaLink.DeploymentManager.IDeploymentStatusNotifier DeploymentStatusNotifier
@implements IDisposable @implements IDisposable
<div class="container-fluid mt-3"> <div class="container-fluid mt-3">
@@ -196,47 +197,42 @@
private Dictionary<int, string> _instanceNames = new(); private Dictionary<int, string> _instanceNames = new();
private bool _loading = true; private bool _loading = true;
private string? _errorMessage; private string? _errorMessage;
private Timer? _refreshTimer;
private bool _autoRefresh = true; private bool _autoRefresh = true;
private readonly HashSet<string> _expandedErrors = new(); private readonly HashSet<string> _expandedErrors = new();
private int _currentPage = 1; private int _currentPage = 1;
private int _totalPages; private int _totalPages;
private const int PageSize = 25; private const int PageSize = 25;
private static readonly TimeSpan RefreshInterval = TimeSpan.FromSeconds(10);
// CentralUI-006: deployment status updates are push-based, not polled.
// DeploymentManager raises IDeploymentStatusNotifier.StatusChanged on every
// deployment-record status write; this page subscribes to it and reloads,
// and Blazor Server pushes the re-render to the browser over its SignalR
// circuit — satisfying the design's "no polling required" requirement.
// The notifier event is raised on the DeploymentManager service thread, so
// the handler marshals onto the renderer via InvokeAsync.
protected override async Task OnInitializedAsync() protected override async Task OnInitializedAsync()
{ {
await LoadDataAsync(); await LoadDataAsync();
StartTimer(); DeploymentStatusNotifier.StatusChanged += OnDeploymentStatusChanged;
} }
private void StartTimer() private void OnDeploymentStatusChanged(ScadaLink.DeploymentManager.DeploymentStatusChange change)
{ {
_refreshTimer?.Dispose(); if (!_autoRefresh) return;
_refreshTimer = new Timer(_ => _ = InvokeAsync(async () =>
{ {
InvokeAsync(async () => await LoadDataAsync();
{ StateHasChanged();
if (!_autoRefresh) return; });
await LoadDataAsync();
StateHasChanged();
});
}, null, RefreshInterval, RefreshInterval);
} }
private void ToggleAutoRefresh() private void ToggleAutoRefresh()
{ {
// When paused, incoming push notifications are ignored; "Refresh" still
// forces a manual reload. No timer is involved either way.
_autoRefresh = !_autoRefresh; _autoRefresh = !_autoRefresh;
if (_autoRefresh)
{
StartTimer();
}
else
{
_refreshTimer?.Dispose();
_refreshTimer = null;
}
} }
private bool IsErrorExpanded(string deploymentId) => _expandedErrors.Contains(deploymentId); private bool IsErrorExpanded(string deploymentId) => _expandedErrors.Contains(deploymentId);
@@ -320,6 +316,8 @@
public void Dispose() public void Dispose()
{ {
_refreshTimer?.Dispose(); // Unsubscribe so a status change after the circuit is gone does not
// touch a disposed component (the notifier is a process singleton).
DeploymentStatusNotifier.StatusChanged -= OnDeploymentStatusChanged;
} }
} }

View File

@@ -41,6 +41,7 @@ public class DeploymentService
private readonly OperationLockManager _lockManager; private readonly OperationLockManager _lockManager;
private readonly IAuditService _auditService; private readonly IAuditService _auditService;
private readonly DiffService _diffService; private readonly DiffService _diffService;
private readonly IDeploymentStatusNotifier _statusNotifier;
private readonly DeploymentManagerOptions _options; private readonly DeploymentManagerOptions _options;
private readonly ILogger<DeploymentService> _logger; private readonly ILogger<DeploymentService> _logger;
@@ -60,6 +61,7 @@ public class DeploymentService
OperationLockManager lockManager, OperationLockManager lockManager,
IAuditService auditService, IAuditService auditService,
DiffService diffService, DiffService diffService,
IDeploymentStatusNotifier statusNotifier,
IOptions<DeploymentManagerOptions> options, IOptions<DeploymentManagerOptions> options,
ILogger<DeploymentService> logger) ILogger<DeploymentService> logger)
{ {
@@ -70,10 +72,21 @@ public class DeploymentService
_lockManager = lockManager; _lockManager = lockManager;
_auditService = auditService; _auditService = auditService;
_diffService = diffService; _diffService = diffService;
_statusNotifier = statusNotifier;
_options = options.Value; _options = options.Value;
_logger = logger; _logger = logger;
} }
/// <summary>
/// CentralUI-006: raises a push notification that a deployment record's
/// status was just persisted, so the Central UI deployment-status page can
/// re-render over its SignalR circuit instead of polling. Called at every
/// point a <see cref="DeploymentRecord"/> status is written.
/// </summary>
private void NotifyStatusChange(DeploymentRecord record) =>
_statusNotifier.NotifyStatusChanged(
new DeploymentStatusChange(record.DeploymentId, record.InstanceId, record.Status));
/// <summary> /// <summary>
/// Resolves the site's string identifier from the numeric DB ID. /// Resolves the site's string identifier from the numeric DB ID.
/// The communication layer routes by string identifier (e.g. "site-a"), not DB ID. /// The communication layer routes by string identifier (e.g. "site-a"), not DB ID.
@@ -155,11 +168,13 @@ public class DeploymentService
await _repository.AddDeploymentRecordAsync(record, cancellationToken); await _repository.AddDeploymentRecordAsync(record, cancellationToken);
await _repository.SaveChangesAsync(cancellationToken); await _repository.SaveChangesAsync(cancellationToken);
NotifyStatusChange(record);
// Update status to InProgress // Update status to InProgress
record.Status = DeploymentStatus.InProgress; record.Status = DeploymentStatus.InProgress;
await _repository.UpdateDeploymentRecordAsync(record, cancellationToken); await _repository.UpdateDeploymentRecordAsync(record, cancellationToken);
await _repository.SaveChangesAsync(cancellationToken); await _repository.SaveChangesAsync(cancellationToken);
NotifyStatusChange(record);
try try
{ {
@@ -187,6 +202,7 @@ public class DeploymentService
// non-Success record while the site is running the new config. // non-Success record while the site is running the new config.
await _repository.UpdateDeploymentRecordAsync(record, cancellationToken); await _repository.UpdateDeploymentRecordAsync(record, cancellationToken);
await _repository.SaveChangesAsync(cancellationToken); await _repository.SaveChangesAsync(cancellationToken);
NotifyStatusChange(record);
if (response.Status == DeploymentStatus.Success) if (response.Status == DeploymentStatus.Success)
{ {
@@ -253,6 +269,7 @@ public class DeploymentService
{ {
await _repository.UpdateDeploymentRecordAsync(record, CancellationToken.None); await _repository.UpdateDeploymentRecordAsync(record, CancellationToken.None);
await _repository.SaveChangesAsync(CancellationToken.None); await _repository.SaveChangesAsync(CancellationToken.None);
NotifyStatusChange(record);
await _auditService.LogAsync(user, "DeployFailed", "Instance", instanceId.ToString(), await _auditService.LogAsync(user, "DeployFailed", "Instance", instanceId.ToString(),
instance.UniqueName, new { DeploymentId = deploymentId, Error = ex.Message }, instance.UniqueName, new { DeploymentId = deploymentId, Error = ex.Message },
@@ -624,6 +641,7 @@ public class DeploymentService
prior.CompletedAt = DateTimeOffset.UtcNow; prior.CompletedAt = DateTimeOffset.UtcNow;
await _repository.UpdateDeploymentRecordAsync(prior, cancellationToken); await _repository.UpdateDeploymentRecordAsync(prior, cancellationToken);
await _repository.SaveChangesAsync(cancellationToken); await _repository.SaveChangesAsync(cancellationToken);
NotifyStatusChange(prior);
await _auditService.LogAsync(prior.DeployedBy, "DeployReconciled", "Instance", await _auditService.LogAsync(prior.DeployedBy, "DeployReconciled", "Instance",
instance.Id.ToString(), instance.UniqueName, instance.Id.ToString(), instance.UniqueName,

View File

@@ -0,0 +1,51 @@
using Microsoft.Extensions.Logging;
namespace ScadaLink.DeploymentManager;
/// <summary>
/// Default <see cref="IDeploymentStatusNotifier"/> implementation. A simple
/// in-process event broadcaster: registered as a DI singleton so it is shared
/// between the central-process <see cref="DeploymentService"/> and the Central
/// UI's Blazor circuits (CentralUI-006).
///
/// A throwing subscriber must never break the deployment pipeline, so each
/// handler is invoked individually and its exceptions are caught and logged.
/// </summary>
public sealed class DeploymentStatusNotifier : IDeploymentStatusNotifier
{
private readonly ILogger<DeploymentStatusNotifier> _logger;
public DeploymentStatusNotifier(ILogger<DeploymentStatusNotifier> logger)
{
_logger = logger;
}
/// <inheritdoc />
public event Action<DeploymentStatusChange>? StatusChanged;
/// <inheritdoc />
public void NotifyStatusChanged(DeploymentStatusChange change)
{
var handlers = StatusChanged;
if (handlers == null)
return;
// Invoke each subscriber in isolation: one faulting handler (e.g. a
// disposed Blazor circuit) must not stop the others from being notified
// and must not propagate back into the deployment pipeline.
foreach (var handler in handlers.GetInvocationList())
{
try
{
((Action<DeploymentStatusChange>)handler)(change);
}
catch (Exception ex)
{
_logger.LogWarning(ex,
"A deployment-status-change subscriber threw for deployment {DeploymentId} " +
"(status {Status}); continuing with remaining subscribers",
change.DeploymentId, change.Status);
}
}
}
}

View File

@@ -0,0 +1,49 @@
using ScadaLink.Commons.Types.Enums;
namespace ScadaLink.DeploymentManager;
/// <summary>
/// Payload describing a single deployment-record status change. Kept small —
/// just the deployment identity, the owning instance, and the new status — so
/// it is cheap to raise on the hot path and cheap for subscribers to handle.
/// </summary>
/// <param name="DeploymentId">The unique deployment ID whose status changed.</param>
/// <param name="InstanceId">The instance the deployment record belongs to.</param>
/// <param name="Status">The status the deployment record was just written with.</param>
public readonly record struct DeploymentStatusChange(
string DeploymentId,
int InstanceId,
DeploymentStatus Status);
/// <summary>
/// CentralUI-006: push-based deployment-status change notification.
///
/// The design (Component-CentralUI "Real-Time Updates") requires deployment
/// status transitions to push to the UI immediately via SignalR, with no
/// polling. <see cref="DeploymentService"/> raises <see cref="StatusChanged"/>
/// whenever it writes a <see cref="Commons.Entities.Deployment.DeploymentRecord"/>
/// status; the Central UI's deployment-status page subscribes to it and
/// re-renders over its existing Blazor Server SignalR circuit.
///
/// Registered as a DI singleton (see <see cref="ServiceCollectionExtensions.AddDeploymentManager"/>)
/// so the scoped <see cref="DeploymentService"/> and the Blazor circuit's
/// scoped page component share the same instance — both run in the same
/// central Host process.
/// </summary>
public interface IDeploymentStatusNotifier
{
/// <summary>
/// Raised after a deployment record's status has been written. Handlers run
/// synchronously on the caller's thread; subscribers must not block and
/// should marshal any UI work onto their own dispatcher.
/// </summary>
event Action<DeploymentStatusChange>? StatusChanged;
/// <summary>
/// Raises <see cref="StatusChanged"/>. Called by <see cref="DeploymentService"/>
/// at every point a deployment record's status is persisted. A throwing
/// subscriber must not break the deployment pipeline, so handler exceptions
/// are swallowed by the implementation.
/// </summary>
void NotifyStatusChanged(DeploymentStatusChange change);
}

View File

@@ -27,6 +27,14 @@ public static class ServiceCollectionExtensions
// the declared option-class defaults apply. // the declared option-class defaults apply.
services.AddOptions<DeploymentManagerOptions>(); services.AddOptions<DeploymentManagerOptions>();
services.AddSingleton<OperationLockManager>(); services.AddSingleton<OperationLockManager>();
// CentralUI-006: push-based deployment-status notification. Registered
// as a singleton so the scoped DeploymentService and the Central UI's
// scoped Blazor page component share one instance — both run in the
// same central Host process. The deployment-status page subscribes to
// it instead of polling the database every 10 seconds.
services.AddSingleton<IDeploymentStatusNotifier, DeploymentStatusNotifier>();
services.AddScoped<IFlatteningPipeline, FlatteningPipeline>(); services.AddScoped<IFlatteningPipeline, FlatteningPipeline>();
services.AddScoped<DeploymentService>(); services.AddScoped<DeploymentService>();
services.AddScoped<ArtifactDeploymentService>(); services.AddScoped<ArtifactDeploymentService>();

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 // DeploymentService gained a DiffService dependency (DeploymentManager
// contract change); register it so the page's DI graph resolves. // contract change); register it so the page's DI graph resolves.
Services.AddScoped<ScadaLink.TemplateEngine.Flattening.DiffService>(); 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<DeploymentService>();
Services.AddScoped<AreaService>(); Services.AddScoped<AreaService>();
Services.AddScoped<InstanceService>(); Services.AddScoped<InstanceService>();

View File

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