Merge branch 'review/wp5' into review/integration

This commit is contained in:
Joseph Doherty
2026-12-03 10:41:19 -05:00
29 changed files with 1093 additions and 112 deletions
+11 -3
View File
@@ -275,7 +275,7 @@ Per-leaf alarm rendering (leaf nodes are individual conditions for native alarms
- Monitor and manage centrally-delivered notifications. The Notification Outbox dispatches every notification store-and-forwarded from sites and logs each one to the central `Notifications` table. - Monitor and manage centrally-delivered notifications. The Notification Outbox dispatches every notification store-and-forwarded from sites and logs each one to the central `Notifications` table.
- **KPI tiles** at the top of the page: queue depth (`Pending` + `Retrying`), stuck count, parked count, delivered in the last interval, and oldest pending age. The KPIs are central-computed on demand from the `Notifications` table. - **KPI tiles** at the top of the page: queue depth (`Pending` + `Retrying`), stuck count, parked count, delivered in the last interval, and oldest pending age. The KPIs are central-computed on demand from the `Notifications` table.
- A **queryable notification list** filterable by status, type, source site, notification list, and time range, with a **stuck-only toggle** and keyword search on subject. Each row shows the notification's status, retry count, last error, and key timestamps. - A **queryable notification list** filterable by status, type, source site, notification list, and time range, with a **stuck-only toggle** and keyword search on subject. Each row shows the notification's status, retry count, last error, and key timestamps.
- **Retry** and **Discard** actions are available on parked notifications: Retry returns the notification to `Pending` and resets `RetryCount` / `NextAttemptAt`; Discard moves it to `Discarded`. The row is retained either way so the table stays a complete audit record. - **Retry** and **Discard** actions are available on parked notifications: Retry returns the notification to `Pending` and resets `RetryCount` / `NextAttemptAt`; Discard moves it to `Discarded`. The row is retained either way so the table stays a complete audit record. The action re-checks site scope at click time: a system-wide user may act on any row, including one whose source site no longer resolves (deleted or renamed — such rows stay listed); a site-scoped user may act only on rows of a permitted site, and not on an unresolvable one (code review 2026-12-02 UI-11).
- Each row exposes a **"View audit history"** action that opens the Audit Log page pre-filtered to `CorrelationId = NotificationId`, surfacing every operational audit event recorded for that notification. - Each row exposes a **"View audit history"** action that opens the Audit Log page pre-filtered to `CorrelationId = NotificationId`, surfacing every operational audit event recorded for that notification.
- **Stuck rows are visually badged** — a notification is stuck if it is `Pending` or `Retrying` and older than the configurable stuck-age threshold. Stuck detection is display-only; there is no automated escalation or alerting. - **Stuck rows are visually badged** — a notification is stuck if it is `Pending` or `Retrying` and older than the configurable stuck-age threshold. Stuck detection is display-only; there is no automated escalation or alerting.
- All queries are served from the central `Notifications` table — no remote per-site queries are needed, unlike the Parked Message Management page. - All queries are served from the central `Notifications` table — no remote per-site queries are needed, unlike the Parked Message Management page.
@@ -293,7 +293,7 @@ Per-leaf alarm rendering (leaf nodes are individual conditions for native alarms
### Site Calls (Deployment Role) ### Site Calls (Deployment Role)
- Monitor cached calls store-and-forwarded from sites — `ExternalSystem.CachedCall()` and `Database.CachedWrite()` operations. Scoped to the `ExternalCall` and `DatabaseWrite` kinds only; notifications keep their separate Notification Outbox page and are not merged here. - Monitor cached calls store-and-forwarded from sites — `ExternalSystem.CachedCall()` and `Database.CachedWrite()` operations. Scoped to the `ExternalCall` and `DatabaseWrite` kinds only; notifications keep their separate Notification Outbox page and are not merged here.
- A **queryable cached-call list** filterable by site, kind, status, and time range. Each row shows the call's timestamp, site, kind, target summary, status badge, retry count, and last error. - A **queryable cached-call list** filterable by site, kind, status, and time range. Each row shows the call's timestamp, site, kind, target summary, status badge, retry count, and last error.
- **Retry** and **Discard** actions are available on `Parked` rows only — `Failed` rows are not actionable, since a permanent failure would simply fail again and its error was already returned synchronously to the calling script. The actions issue central→site commands to the owning site; if the site is offline the UI surfaces a "site unreachable" message. - **Retry** and **Discard** actions are available on `Parked` rows only — `Failed` rows are not actionable, since a permanent failure would simply fail again and its error was already returned synchronously to the calling script. The actions issue central→site commands to the owning site; if the site is offline the UI surfaces a "site unreachable" message. Site scope is re-checked at click time exactly as on the Notification Outbox page: a system-wide user may act on a row whose source site no longer resolves, a site-scoped user may not (UI-11).
- Each row exposes a **"View audit history"** action that opens the Audit Log page pre-filtered to `CorrelationId = TrackedOperationId`, showing every operational audit event recorded for that cached call. - Each row exposes a **"View audit history"** action that opens the Audit Log page pre-filtered to `CorrelationId = TrackedOperationId`, showing every operational audit event recorded for that cached call.
- Data is served from the central Site Call Audit component's `SiteCalls` table. The page is **read-mostly** — an eventually-consistent mirror of site state; the site remains the source of truth. - Data is served from the central Site Call Audit component's `SiteCalls` table. The page is **read-mostly** — an eventually-consistent mirror of site state; the site remains the source of truth.
- **Site scope is applied in the query (code review 2026-12-02 UI-7):** a site-scoped user's permitted site identifiers ride `SiteCallQueryRequest.SourceSitesFilter`, so keyset paging runs over in-scope rows and Next is gated on the server page size. Before, the query was unscoped and the client dropped other sites' rows after paging, so any page with an out-of-scope row was "short" and disabled Next. - **Site scope is applied in the query (code review 2026-12-02 UI-7):** a site-scoped user's permitted site identifiers ride `SiteCallQueryRequest.SourceSitesFilter`, so keyset paging runs over in-scope rows and Next is gated on the server page size. Before, the query was unscoped and the client dropped other sites' rows after paging, so any page with an out-of-scope row was "short" and disabled Next.
@@ -365,12 +365,20 @@ Per-leaf alarm rendering (leaf nodes are individual conditions for native alarms
### Configuration mutations and live circuit authority (2026-09-09) ### Configuration mutations and live circuit authority (2026-09-09)
Page configuration handlers use `ConfigurationCommandService` and the guarded management command boundary. Database changes and their scrubbed audit entries commit in one transaction, including generated entity IDs. Existing instance service operations execute through the same transaction seam and retain their domain validation and audit ownership. Circuit read tracking is cleared after a separate transaction scope changes configuration. Page configuration handlers use `ConfigurationCommandService` and the guarded management command boundary. Database changes and their scrubbed audit entries commit in one transaction, including generated entity IDs. Existing instance service operations execute through the same transaction seam and retain their domain validation and audit ownership. Circuit read tracking is cleared after a separate transaction scope changes configuration (a no-op since the circuit context stopped tracking — see below).
Cookie circuits retain their initial principal without retaining `HttpContext`; authoritative reads re-map stored directory groups against current grants. Mutation handlers recheck role and persisted target site immediately before dispatch. Passive session pings do not count as user activity. Trusted browser input posts an antiforgery-protected activity signal; the server activity tracker also makes it visible to the existing circuit. Cookie circuits retain their initial principal without retaining `HttpContext`; authoritative reads re-map stored directory groups against current grants. Mutation handlers recheck role and persisted target site immediately before dispatch. Passive session pings do not count as user activity. Trusted browser input posts an antiforgery-protected activity signal; the server activity tracker also makes it visible to the existing circuit.
The explicit server-configured development auto-login mode preserves its synthetic all-role principal. It uses the Cookies scheme but has no LDAP group claims; it must not enter directory re-mapping. This exception follows validated `AuthDisableLoginOptions`, never a caller-supplied claim. The explicit server-configured development auto-login mode preserves its synthetic all-role principal. It uses the Cookies scheme but has no LDAP group claims; it must not enter directory re-mapping. This exception follows validated `AuthDisableLoginOptions`, never a caller-supplied claim.
### Circuit DbContext lifetime (code review 2026-12-02, UI-1/2/3/8)
In Blazor Server one DI scope — and so one scoped `ScadaBridgeDbContext` — lives for the whole circuit. That context now reads with a **no-tracking default**: `CircuitDbContextTrackingHandler` (a `CircuitHandler`, resolved when the circuit host is built, before any component) sets `ChangeTracker.QueryTrackingBehavior = NoTracking` on the circuit scope's context only. Every reload therefore sees the database as it is, including changes made in another scope — a data connection moved through the management actor, an area renamed by another user, a template script edited by the CLI or a Transport import. Contexts in every other scope (management-actor commands, the configuration command transaction, HTTP request scopes, hosted services, singleton actors) keep EF's tracking default.
No page mutates configuration on the circuit's context. Writes go through `ConfigurationCommandService` (its own transaction scope), the `ManagementActor`, or `ScopedServiceExtensions.InNewScopeAsync`, which resolves the load-modify-save service (`TemplateService`, `TemplateFolderService`, `SharedScriptService`, `DeploymentService`, `ArtifactDeploymentService`, `IBundleImporter.ApplyAsync`) from a fresh scope with an empty tracking context and disposes it when the action ends. A source-scan test (`CircuitDbContextTrackingTests`) fails the build if a page calls a mutating method on a circuit-injected instance of one of those services. Adding-only writes on the circuit context (an audit row, a bundle-unlock attempt) are unaffected by the tracking default.
Long or concurrent page work also runs on its own scope, so it can neither collide with another query on the circuit context ("A second operation was started on this context instance") nor die with the circuit: each Deployments-page load flight, the Sites page's **Deploy Artifacts** (per site and to all sites, whose record, audit rows and revision stamp are written after the site fan-out), and Topology's **Diff**, **Enable**, **Disable** and **Delete** (alongside the existing Deploy / Deploy all / staleness checks).
### Isolated Test Run workers ### Isolated Test Run workers
Test Run executes in a disposable `CentralUI.SandboxWorker` process. A process-wide admission gate permits at most four workers. Queueing, compilation, execution and gateway calls consume the requested deadline (1–10 seconds); cancellation kills the process tree and capacity is released only after confirmed exit. Console capture retains at most 32,000 characters with an explicit truncation marker; return JSON is limited to 32,000 bytes. Private IPC frames are limited to 1 MiB and stderr is drained without accumulation. Each worker has a 512 MiB managed-heap ceiling. The worker is a resource/lifetime boundary; the semantic script trust policy still gates compilation. Test Run executes in a disposable `CentralUI.SandboxWorker` process. A process-wide admission gate permits at most four workers. Queueing, compilation, execution and gateway calls consume the requested deadline (1–10 seconds); cancellation kills the process tree and capacity is released only after confirmed exit. Console capture retains at most 32,000 characters with an explicit truncation marker; return JSON is limited to 32,000 bytes. Private IPC frames are limited to 1 MiB and stderr is drained without accumulation. Each worker has a 512 MiB managed-heap ceiling. The worker is a resource/lifetime boundary; the semantic script trust policy still gates compilation.
@@ -53,6 +53,8 @@
private Timer? _timer; private Timer? _timer;
private volatile bool _disposed; private volatile bool _disposed;
private bool _subscribed;
private readonly object _lifetimeLock = new();
private bool _visible; private bool _visible;
private IReadOnlySet<int>? _scopedSiteIds; private IReadOnlySet<int>? _scopedSiteIds;
private PendingUpdatesSnapshot? _snapshot; private PendingUpdatesSnapshot? _snapshot;
@@ -85,9 +87,23 @@
var (isSystemWide, sites) = SiteScopeService.Resolve(user); var (isSystemWide, sites) = SiteScopeService.Resolve(user);
_scopedSiteIds = isSystemWide ? null : sites; _scopedSiteIds = isSystemWide ? null : sites;
PendingUpdates.Invalidated += OnInvalidated; // UI-4: the component may have been disposed during an await above or below;
// Dispose() has then already run and must not be followed by a subscription to the
// process-singleton cache or a new timer (both would root this dead component).
// Subscribe/create and dispose are atomic under _lifetimeLock.
lock (_lifetimeLock)
{
if (_disposed) return;
PendingUpdates.Invalidated += OnInvalidated;
_subscribed = true;
}
await LoadAsync(); await LoadAsync();
_timer = new Timer(_ => _ = ReloadAsync(), null, PollInterval, PollInterval); lock (_lifetimeLock)
{
if (_disposed) return;
_timer = new Timer(_ => _ = ReloadAsync(), null, PollInterval, PollInterval);
}
} }
private void OnInvalidated() => _ = ReloadAsync(); private void OnInvalidated() => _ = ReloadAsync();
@@ -131,12 +147,17 @@
public void Dispose() public void Dispose()
{ {
_disposed = true; lock (_lifetimeLock)
if (_visible)
{ {
PendingUpdates.Invalidated -= OnInvalidated; _disposed = true;
} if (_subscribed)
{
PendingUpdates.Invalidated -= OnInvalidated;
_subscribed = false;
}
_timer?.Dispose(); _timer?.Dispose();
_timer = null;
}
} }
} }
@@ -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
@@ -342,8 +343,13 @@
protected override async Task OnInitializedAsync() protected override async Task OnInitializedAsync()
{ {
await LoadDataAsync(); // UI-4: subscribe BEFORE the first load. Subscribing after it meant a navigation
// during the load ran Dispose() first (unsubscribing a handler that was not yet
// added), and the continuation then added a dead component to the process-singleton
// notifier's invocation list for good. A push during the initial load is harmless:
// the handler only schedules a reload, and the generation guard orders the flights.
DeploymentStatusNotifier.StatusChanged += OnDeploymentStatusChanged; DeploymentStatusNotifier.StatusChanged += OnDeploymentStatusChanged;
await LoadDataAsync();
} }
// ── Push coalescing (arch-review WP2.4) ─────────────────────────────────── // ── Push coalescing (arch-review WP2.4) ───────────────────────────────────
@@ -615,13 +621,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 +659,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;
@@ -233,6 +233,7 @@
// DebugView.razor. The CTS is used to cancel the in-flight health query when // DebugView.razor. The CTS is used to cancel the in-flight health query when
// the component is disposed. // the component is disposed.
private volatile bool _disposed; private volatile bool _disposed;
private readonly object _timerLock = new();
private bool _healthTickInFlight; private bool _healthTickInFlight;
private readonly CancellationTokenSource _disposeCts = new(); private readonly CancellationTokenSource _disposeCts = new();
@@ -241,17 +242,24 @@
protected override async Task OnInitializedAsync() protected override async Task OnInitializedAsync()
{ {
await LoadDataAsync(); await LoadDataAsync();
if (_disposed) return;
await LoadConnectionHealthAsync(_disposeCts.Token); await LoadConnectionHealthAsync(_disposeCts.Token);
// Poll the live health map on the same cadence as the Health dashboard. // Poll the live health map on the same cadence as the Health dashboard.
// Best-effort: a failed query leaves the prior map in place rather than // Best-effort: a failed query leaves the prior map in place rather than
// disturbing the tree. // disturbing the tree.
// CentralUI-022 pattern: guard against dispose race — see _disposed field. // CentralUI-022 pattern: guard against dispose race — see _disposed field.
_healthTimer = new Timer(_ => // UI-4: a navigation during the loads above has already run Dispose(), which found
// no timer; create-vs-dispose is atomic under _timerLock so none is leaked.
lock (_timerLock)
{ {
if (_disposed) return; if (_disposed) return;
_ = DispatchHealthTickAsync(); _healthTimer = new Timer(_ =>
}, null, TimeSpan.FromSeconds(HealthRefreshSeconds), TimeSpan.FromSeconds(HealthRefreshSeconds)); {
if (_disposed) return;
_ = DispatchHealthTickAsync();
}, null, TimeSpan.FromSeconds(HealthRefreshSeconds), TimeSpan.FromSeconds(HealthRefreshSeconds));
}
} }
/// <summary> /// <summary>
@@ -479,9 +487,13 @@
// CentralUI-022 pattern: set the guard FIRST so any tick already in flight // CentralUI-022 pattern: set the guard FIRST so any tick already in flight
// on the thread-pool no-ops, then cancel the in-flight health query, then // on the thread-pool no-ops, then cancel the in-flight health query, then
// stop the timer. Mirrors Deployments.razor and DebugView.razor. // stop the timer. Mirrors Deployments.razor and DebugView.razor.
_disposed = true; lock (_timerLock)
{
_disposed = true;
_healthTimer?.Dispose();
_healthTimer = null;
}
_disposeCts.Cancel(); _disposeCts.Cancel();
_disposeCts.Dispose(); _disposeCts.Dispose();
_healthTimer?.Dispose();
} }
} }
@@ -1,5 +1,8 @@
@page "/design/shared-scripts/create" @page "/design/shared-scripts/create"
@page "/design/shared-scripts/{Id:int}/edit" @page "/design/shared-scripts/{Id:int}/edit"
@using ZB.MOM.WW.ScadaBridge.CentralUI.Services
@using Microsoft.Extensions.DependencyInjection
@inject IServiceScopeFactory ScopeFactory
@using ZB.MOM.WW.ScadaBridge.Security @using ZB.MOM.WW.ScadaBridge.Security
@using ZB.MOM.WW.ScadaBridge.Commons.Entities.Scripts @using ZB.MOM.WW.ScadaBridge.Commons.Entities.Scripts
@using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories @using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories
@@ -278,8 +281,8 @@
if (Id.HasValue) if (Id.HasValue)
{ {
var user = await GetCurrentUserAsync(); var user = await GetCurrentUserAsync();
var result = await SharedScriptService.UpdateSharedScriptAsync( var result = await ScopeFactory.InNewScopeAsync((SharedScriptService svc) => svc.UpdateSharedScriptAsync(
Id.Value, _formCode, _formParameters?.Trim(), _formReturn?.Trim(), user); Id.Value, _formCode, _formParameters?.Trim(), _formReturn?.Trim(), user));
if (result.IsSuccess) if (result.IsSuccess)
{ {
NavigationManager.NavigateTo("/design/shared-scripts"); NavigationManager.NavigateTo("/design/shared-scripts");
@@ -292,8 +295,8 @@
else else
{ {
var user = await GetCurrentUserAsync(); var user = await GetCurrentUserAsync();
var result = await SharedScriptService.CreateSharedScriptAsync( var result = await ScopeFactory.InNewScopeAsync((SharedScriptService svc) => svc.CreateSharedScriptAsync(
_formName.Trim(), _formCode, _formParameters?.Trim(), _formReturn?.Trim(), user); _formName.Trim(), _formCode, _formParameters?.Trim(), _formReturn?.Trim(), user));
if (result.IsSuccess) if (result.IsSuccess)
{ {
NavigationManager.NavigateTo("/design/shared-scripts"); NavigationManager.NavigateTo("/design/shared-scripts");
@@ -1,4 +1,7 @@
@page "/design/shared-scripts" @page "/design/shared-scripts"
@using ZB.MOM.WW.ScadaBridge.CentralUI.Services
@using Microsoft.Extensions.DependencyInjection
@inject IServiceScopeFactory ScopeFactory
@using ZB.MOM.WW.ScadaBridge.Security @using ZB.MOM.WW.ScadaBridge.Security
@using ZB.MOM.WW.ScadaBridge.Commons.Entities.Scripts @using ZB.MOM.WW.ScadaBridge.Commons.Entities.Scripts
@using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories @using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories
@@ -151,7 +154,7 @@
try try
{ {
var user = await GetCurrentUserAsync(); var user = await GetCurrentUserAsync();
var result = await SharedScriptService.DeleteSharedScriptAsync(script.Id, user); var result = await ScopeFactory.InNewScopeAsync((SharedScriptService svc) => svc.DeleteSharedScriptAsync(script.Id, user));
if (result.IsSuccess) if (result.IsSuccess)
{ {
_toast.ShowSuccess($"Script '{script.Name}' deleted."); _toast.ShowSuccess($"Script '{script.Name}' deleted.");
@@ -1,4 +1,6 @@
@page "/design/templates/create" @page "/design/templates/create"
@using Microsoft.Extensions.DependencyInjection
@inject IServiceScopeFactory ScopeFactory
@using ZB.MOM.WW.ScadaBridge.CentralUI.Services @using ZB.MOM.WW.ScadaBridge.CentralUI.Services
@using ZB.MOM.WW.ScadaBridge.Security @using ZB.MOM.WW.ScadaBridge.Security
@using ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates @using ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates
@@ -6,7 +8,6 @@
@using ZB.MOM.WW.ScadaBridge.TemplateEngine @using ZB.MOM.WW.ScadaBridge.TemplateEngine
@attribute [Authorize(Policy = AuthorizationPolicies.RequireDesign)] @attribute [Authorize(Policy = AuthorizationPolicies.RequireDesign)]
@inject ITemplateEngineRepository TemplateEngineRepository @inject ITemplateEngineRepository TemplateEngineRepository
@inject TemplateService TemplateService
@inject AuthenticationStateProvider AuthStateProvider @inject AuthenticationStateProvider AuthStateProvider
@inject NavigationManager NavigationManager @inject NavigationManager NavigationManager
@@ -95,10 +96,10 @@
try try
{ {
var user = await GetCurrentUserAsync(); var user = await GetCurrentUserAsync();
var result = await TemplateService.CreateTemplateAsync( var result = await ScopeFactory.InNewScopeAsync((TemplateService svc) => svc.CreateTemplateAsync(
_createName.Trim(), _createDescription?.Trim(), _createName.Trim(), _createDescription?.Trim(),
_createParentId == 0 ? null : _createParentId, user, _createParentId == 0 ? null : _createParentId, user,
folderId: FolderId); folderId: FolderId));
if (result.IsSuccess) if (result.IsSuccess)
{ {
@@ -2,6 +2,8 @@
@using ZB.MOM.WW.ScadaBridge.Commons.Messages.Management @using ZB.MOM.WW.ScadaBridge.Commons.Messages.Management
@inject IServiceProvider MutationServices @inject IServiceProvider MutationServices
@page "/design/templates/{Id:int}" @page "/design/templates/{Id:int}"
@using Microsoft.Extensions.DependencyInjection
@inject IServiceScopeFactory ScopeFactory
@using ZB.MOM.WW.ScadaBridge.Security @using ZB.MOM.WW.ScadaBridge.Security
@using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances @using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances
@using ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates @using ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates
@@ -569,7 +571,7 @@
try try
{ {
var user = await GetCurrentUserAsync(); var user = await GetCurrentUserAsync();
var result = await TemplateService.DeleteTemplateAsync(_selectedTemplate.Id, user); var result = await ScopeFactory.InNewScopeAsync((TemplateService svc) => svc.DeleteTemplateAsync(_selectedTemplate.Id, user));
if (result.IsSuccess) if (result.IsSuccess)
{ {
_toast.ShowSuccess($"Template '{_selectedTemplate.Name}' deleted."); _toast.ShowSuccess($"Template '{_selectedTemplate.Name}' deleted.");
@@ -592,9 +594,9 @@
try try
{ {
var user = await GetCurrentUserAsync(); var user = await GetCurrentUserAsync();
var result = await TemplateService.UpdateTemplateAsync( var result = await ScopeFactory.InNewScopeAsync((TemplateService svc) => svc.UpdateTemplateAsync(
_selectedTemplate.Id, _editName.Trim(), _editDescription?.Trim(), _selectedTemplate.Id, _editName.Trim(), _editDescription?.Trim(),
_editParentId == 0 ? null : _editParentId, user); _editParentId == 0 ? null : _editParentId, user));
if (result.IsSuccess) if (result.IsSuccess)
{ {
@@ -818,7 +820,7 @@
IsInherited = attr.IsInherited, IsInherited = attr.IsInherited,
LockedInDerived = newValue, LockedInDerived = newValue,
}; };
var result = await TemplateService.UpdateAttributeAsync(attr.Id, proposed, user); var result = await ScopeFactory.InNewScopeAsync((TemplateService svc) => svc.UpdateAttributeAsync(attr.Id, proposed, user));
if (result.IsSuccess) { attr.LockedInDerived = newValue; _toast.ShowSuccess("Lock-in-derived updated."); } if (result.IsSuccess) { attr.LockedInDerived = newValue; _toast.ShowSuccess("Lock-in-derived updated."); }
else _toast.ShowError(result.Error); else _toast.ShowError(result.Error);
} }
@@ -841,7 +843,7 @@
IsInherited = false, IsInherited = false,
LockedInDerived = false, LockedInDerived = false,
}; };
var result = await TemplateService.UpdateAttributeAsync(attr.Id, proposed, user); var result = await ScopeFactory.InNewScopeAsync((TemplateService svc) => svc.UpdateAttributeAsync(attr.Id, proposed, user));
if (result.IsSuccess) { _toast.ShowSuccess($"Override saved for '{attr.Name}'."); await LoadAsync(); } if (result.IsSuccess) { _toast.ShowSuccess($"Override saved for '{attr.Name}'."); await LoadAsync(); }
else _toast.ShowError(result.Error); else _toast.ShowError(result.Error);
} }
@@ -864,7 +866,7 @@
IsInherited = true, IsInherited = true,
LockedInDerived = false, LockedInDerived = false,
}; };
var result = await TemplateService.UpdateAttributeAsync(attr.Id, proposed, user); var result = await ScopeFactory.InNewScopeAsync((TemplateService svc) => svc.UpdateAttributeAsync(attr.Id, proposed, user));
if (result.IsSuccess) { _toast.ShowSuccess($"'{attr.Name}' reverted to base."); await LoadAsync(); } if (result.IsSuccess) { _toast.ShowSuccess($"'{attr.Name}' reverted to base."); await LoadAsync(); }
else _toast.ShowError(result.Error); else _toast.ShowError(result.Error);
} }
@@ -882,7 +884,7 @@
try try
{ {
var user = await GetCurrentUserAsync(); var user = await GetCurrentUserAsync();
var result = await TemplateService.ResyncInheritedMembersAsync(Id, user); var result = await ScopeFactory.InNewScopeAsync((TemplateService svc) => svc.ResyncInheritedMembersAsync(Id, user));
if (result.IsSuccess) if (result.IsSuccess)
{ {
var r = result.Value; var r = result.Value;
@@ -1284,7 +1286,7 @@
IsInherited = script.IsInherited, IsInherited = script.IsInherited,
LockedInDerived = newValue, LockedInDerived = newValue,
}; };
var result = await TemplateService.UpdateScriptAsync(script.Id, proposed, user); var result = await ScopeFactory.InNewScopeAsync((TemplateService svc) => svc.UpdateScriptAsync(script.Id, proposed, user));
if (result.IsSuccess) { script.LockedInDerived = newValue; _toast.ShowSuccess("Lock-in-derived updated."); } if (result.IsSuccess) { script.LockedInDerived = newValue; _toast.ShowSuccess("Lock-in-derived updated."); }
else _toast.ShowError(result.Error); else _toast.ShowError(result.Error);
} }
@@ -1308,7 +1310,7 @@
IsInherited = true, IsInherited = true,
LockedInDerived = false, LockedInDerived = false,
}; };
var result = await TemplateService.UpdateScriptAsync(script.Id, proposed, user); var result = await ScopeFactory.InNewScopeAsync((TemplateService svc) => svc.UpdateScriptAsync(script.Id, proposed, user));
if (result.IsSuccess) { _toast.ShowSuccess($"Script '{script.Name}' reverted to base."); await LoadAsync(); } if (result.IsSuccess) { _toast.ShowSuccess($"Script '{script.Name}' reverted to base."); await LoadAsync(); }
else _toast.ShowError(result.Error); else _toast.ShowError(result.Error);
} }
@@ -1426,7 +1428,7 @@
IsInherited = existing.IsInherited, IsInherited = existing.IsInherited,
LockedInDerived = existing.LockedInDerived, LockedInDerived = existing.LockedInDerived,
}; };
var result = await TemplateService.UpdateAttributeAsync(id, proposed, user); var result = await ScopeFactory.InNewScopeAsync((TemplateService svc) => svc.UpdateAttributeAsync(id, proposed, user));
if (!result.IsSuccess) return result.Error; if (!result.IsSuccess) return result.Error;
_toast.ShowSuccess($"Attribute '{existing.Name}' updated."); _toast.ShowSuccess($"Attribute '{existing.Name}' updated.");
@@ -1442,7 +1444,7 @@
DataSourceReference = draft.DataSourceRef?.Trim() DataSourceReference = draft.DataSourceRef?.Trim()
}; };
var addResult = await TemplateService.AddAttributeAsync(_selectedTemplate.Id, attr, user); var addResult = await ScopeFactory.InNewScopeAsync((TemplateService svc) => svc.AddAttributeAsync(_selectedTemplate.Id, attr, user));
if (!addResult.IsSuccess) return addResult.Error; if (!addResult.IsSuccess) return addResult.Error;
_toast.ShowSuccess($"Attribute '{draft.Name}' added."); _toast.ShowSuccess($"Attribute '{draft.Name}' added.");
@@ -1454,7 +1456,7 @@
var confirmed = await Dialog.ConfirmAsync("Delete Attribute", $"Delete attribute '{attr.Name}'?", danger: true); var confirmed = await Dialog.ConfirmAsync("Delete Attribute", $"Delete attribute '{attr.Name}'?", danger: true);
if (!confirmed) return; if (!confirmed) return;
var user = await GetCurrentUserAsync(); var user = await GetCurrentUserAsync();
var result = await TemplateService.DeleteAttributeAsync(attr.Id, user); var result = await ScopeFactory.InNewScopeAsync((TemplateService svc) => svc.DeleteAttributeAsync(attr.Id, user));
if (result.IsSuccess) if (result.IsSuccess)
{ {
_toast.ShowSuccess($"Attribute '{attr.Name}' deleted."); _toast.ShowSuccess($"Attribute '{attr.Name}' deleted.");
@@ -1562,7 +1564,7 @@
Description = existing.Description, Description = existing.Description,
OnTriggerScriptId = existing.OnTriggerScriptId, OnTriggerScriptId = existing.OnTriggerScriptId,
}; };
var result = await TemplateService.UpdateAlarmAsync(id, proposed, user); var result = await ScopeFactory.InNewScopeAsync((TemplateService svc) => svc.UpdateAlarmAsync(id, proposed, user));
if (!result.IsSuccess) return result.Error; if (!result.IsSuccess) return result.Error;
_toast.ShowSuccess($"Alarm '{existing.Name}' updated."); _toast.ShowSuccess($"Alarm '{existing.Name}' updated.");
@@ -1578,7 +1580,7 @@
IsMesReportable = draft.IsMesReportable IsMesReportable = draft.IsMesReportable
}; };
var addResult = await TemplateService.AddAlarmAsync(_selectedTemplate.Id, alarm, user); var addResult = await ScopeFactory.InNewScopeAsync((TemplateService svc) => svc.AddAlarmAsync(_selectedTemplate.Id, alarm, user));
if (!addResult.IsSuccess) return addResult.Error; if (!addResult.IsSuccess) return addResult.Error;
_toast.ShowSuccess($"Alarm '{draft.Name}' added."); _toast.ShowSuccess($"Alarm '{draft.Name}' added.");
@@ -1590,7 +1592,7 @@
var confirmed = await Dialog.ConfirmAsync("Delete Alarm", $"Delete alarm '{alarm.Name}'?", danger: true); var confirmed = await Dialog.ConfirmAsync("Delete Alarm", $"Delete alarm '{alarm.Name}'?", danger: true);
if (!confirmed) return; if (!confirmed) return;
var user = await GetCurrentUserAsync(); var user = await GetCurrentUserAsync();
var result = await TemplateService.DeleteAlarmAsync(alarm.Id, user); var result = await ScopeFactory.InNewScopeAsync((TemplateService svc) => svc.DeleteAlarmAsync(alarm.Id, user));
if (result.IsSuccess) if (result.IsSuccess)
{ {
_toast.ShowSuccess($"Alarm '{alarm.Name}' deleted."); _toast.ShowSuccess($"Alarm '{alarm.Name}' deleted.");
@@ -1698,7 +1700,7 @@
IsInherited = existing.IsInherited, IsInherited = existing.IsInherited,
LockedInDerived = existing.LockedInDerived, LockedInDerived = existing.LockedInDerived,
}; };
var result = await TemplateService.UpdateScriptAsync(id, proposed, user); var result = await ScopeFactory.InNewScopeAsync((TemplateService svc) => svc.UpdateScriptAsync(id, proposed, user));
if (!result.IsSuccess) return result.Error; if (!result.IsSuccess) return result.Error;
_toast.ShowSuccess($"Script '{existing.Name}' updated."); _toast.ShowSuccess($"Script '{existing.Name}' updated.");
@@ -1716,7 +1718,7 @@
ExecutionTimeoutSeconds = NormalizeExecutionTimeout(draft.ExecutionTimeoutSeconds) ExecutionTimeoutSeconds = NormalizeExecutionTimeout(draft.ExecutionTimeoutSeconds)
}; };
var addResult = await TemplateService.AddScriptAsync(_selectedTemplate.Id, script, user); var addResult = await ScopeFactory.InNewScopeAsync((TemplateService svc) => svc.AddScriptAsync(_selectedTemplate.Id, script, user));
if (!addResult.IsSuccess) return addResult.Error; if (!addResult.IsSuccess) return addResult.Error;
_toast.ShowSuccess($"Script '{draft.Name}' added."); _toast.ShowSuccess($"Script '{draft.Name}' added.");
@@ -1728,7 +1730,7 @@
var confirmed = await Dialog.ConfirmAsync("Delete Script", $"Delete script '{script.Name}'?", danger: true); var confirmed = await Dialog.ConfirmAsync("Delete Script", $"Delete script '{script.Name}'?", danger: true);
if (!confirmed) return; if (!confirmed) return;
var user = await GetCurrentUserAsync(); var user = await GetCurrentUserAsync();
var result = await TemplateService.DeleteScriptAsync(script.Id, user); var result = await ScopeFactory.InNewScopeAsync((TemplateService svc) => svc.DeleteScriptAsync(script.Id, user));
if (result.IsSuccess) if (result.IsSuccess)
{ {
_toast.ShowSuccess($"Script '{script.Name}' deleted."); _toast.ShowSuccess($"Script '{script.Name}' deleted.");
@@ -1,4 +1,7 @@
@page "/design/templates" @page "/design/templates"
@using ZB.MOM.WW.ScadaBridge.CentralUI.Services
@using Microsoft.Extensions.DependencyInjection
@inject IServiceScopeFactory ScopeFactory
@using ZB.MOM.WW.ScadaBridge.Security @using ZB.MOM.WW.ScadaBridge.Security
@using ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates @using ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates
@using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories @using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories
@@ -8,8 +11,6 @@
@using ZB.MOM.WW.ScadaBridge.TemplateEngine.Services @using ZB.MOM.WW.ScadaBridge.TemplateEngine.Services
@attribute [Authorize(Policy = AuthorizationPolicies.RequireDesign)] @attribute [Authorize(Policy = AuthorizationPolicies.RequireDesign)]
@inject ITemplateEngineRepository TemplateEngineRepository @inject ITemplateEngineRepository TemplateEngineRepository
@inject TemplateService TemplateService
@inject TemplateFolderService TemplateFolderService
@inject AuthenticationStateProvider AuthStateProvider @inject AuthenticationStateProvider AuthStateProvider
@inject NavigationManager NavigationManager @inject NavigationManager NavigationManager
@inject IDialogService Dialog @inject IDialogService Dialog
@@ -355,7 +356,7 @@
if (string.IsNullOrWhiteSpace(name)) return; if (string.IsNullOrWhiteSpace(name)) return;
var user = await GetCurrentUserAsync(); var user = await GetCurrentUserAsync();
var result = await TemplateFolderService.CreateFolderAsync(name.Trim(), parentFolderId, user); var result = await ScopeFactory.InNewScopeAsync((TemplateFolderService svc) => svc.CreateFolderAsync(name.Trim(), parentFolderId, user));
if (result.IsSuccess) if (result.IsSuccess)
{ {
_toast.ShowSuccess($"Folder '{result.Value.Name}' created."); _toast.ShowSuccess($"Folder '{result.Value.Name}' created.");
@@ -378,7 +379,7 @@
if (result is null) return; if (result is null) return;
var user = await GetCurrentUserAsync(); var user = await GetCurrentUserAsync();
var moved = await TemplateService.MoveTemplateAsync(templateId, result.NewFolderId, user); var moved = await ScopeFactory.InNewScopeAsync((TemplateService svc) => svc.MoveTemplateAsync(templateId, result.NewFolderId, user));
if (moved.IsSuccess) if (moved.IsSuccess)
{ {
_toast.ShowSuccess($"Template '{label}' moved."); _toast.ShowSuccess($"Template '{label}' moved.");
@@ -430,7 +431,7 @@
if (result is null) return; if (result is null) return;
var user = await GetCurrentUserAsync(); var user = await GetCurrentUserAsync();
var moved = await TemplateFolderService.MoveFolderAsync(folderId, result.NewParentId, user); var moved = await ScopeFactory.InNewScopeAsync((TemplateFolderService svc) => svc.MoveFolderAsync(folderId, result.NewParentId, user));
if (moved.IsSuccess) if (moved.IsSuccess)
{ {
_toast.ShowSuccess($"Folder '{label}' moved."); _toast.ShowSuccess($"Folder '{label}' moved.");
@@ -451,7 +452,7 @@
private async Task ReorderFolder(int folderId, ReorderDirection direction) private async Task ReorderFolder(int folderId, ReorderDirection direction)
{ {
var user = await GetCurrentUserAsync(); var user = await GetCurrentUserAsync();
var result = await TemplateFolderService.ReorderFolderAsync(folderId, direction, user); var result = await ScopeFactory.InNewScopeAsync((TemplateFolderService svc) => svc.ReorderFolderAsync(folderId, direction, user));
if (result.IsSuccess) if (result.IsSuccess)
{ {
await LoadTemplatesAsync(); await LoadTemplatesAsync();
@@ -542,7 +543,7 @@
if (string.IsNullOrWhiteSpace(newName)) return; if (string.IsNullOrWhiteSpace(newName)) return;
var user = await GetCurrentUserAsync(); var user = await GetCurrentUserAsync();
var result = await TemplateFolderService.RenameFolderAsync(folderId, newName, user); var result = await ScopeFactory.InNewScopeAsync((TemplateFolderService svc) => svc.RenameFolderAsync(folderId, newName, user));
if (result.IsSuccess) if (result.IsSuccess)
{ {
_toast.ShowSuccess("Folder renamed."); _toast.ShowSuccess("Folder renamed.");
@@ -560,7 +561,7 @@
if (!confirmed) return; if (!confirmed) return;
var user = await GetCurrentUserAsync(); var user = await GetCurrentUserAsync();
var result = await TemplateFolderService.DeleteFolderAsync(folderId, user); var result = await ScopeFactory.InNewScopeAsync((TemplateFolderService svc) => svc.DeleteFolderAsync(folderId, user));
if (result.IsSuccess) if (result.IsSuccess)
{ {
_toast.ShowSuccess($"Folder '{label}' deleted."); _toast.ShowSuccess($"Folder '{label}' deleted.");
@@ -583,7 +584,7 @@
try try
{ {
var user = await GetCurrentUserAsync(); var user = await GetCurrentUserAsync();
var result = await TemplateService.DeleteTemplateAsync(template.Id, user); var result = await ScopeFactory.InNewScopeAsync((TemplateService svc) => svc.DeleteTemplateAsync(template.Id, user));
if (result.IsSuccess) if (result.IsSuccess)
{ {
_toast.ShowSuccess($"Template '{template.Name}' deleted."); _toast.ShowSuccess($"Template '{template.Name}' deleted.");
@@ -616,7 +617,7 @@
if (result is null) return; if (result is null) return;
var user = await GetCurrentUserAsync(); var user = await GetCurrentUserAsync();
var composed = await TemplateService.AddCompositionAsync(result.ParentTemplateId, sourceId, result.SlotName, user); var composed = await ScopeFactory.InNewScopeAsync((TemplateService svc) => svc.AddCompositionAsync(result.ParentTemplateId, sourceId, result.SlotName, user));
if (composed.IsSuccess) if (composed.IsSuccess)
{ {
_toast.ShowSuccess($"Composed '{sourceName}' as '{result.SlotName}'."); _toast.ShowSuccess($"Composed '{sourceName}' as '{result.SlotName}'.");
@@ -649,7 +650,7 @@
if (string.IsNullOrWhiteSpace(newName) || newName.Trim() == composition.InstanceName) return; if (string.IsNullOrWhiteSpace(newName) || newName.Trim() == composition.InstanceName) return;
var user = await GetCurrentUserAsync(); var user = await GetCurrentUserAsync();
var result = await TemplateService.RenameCompositionAsync(composition.Id, newName.Trim(), user); var result = await ScopeFactory.InNewScopeAsync((TemplateService svc) => svc.RenameCompositionAsync(composition.Id, newName.Trim(), user));
if (result.IsSuccess) if (result.IsSuccess)
{ {
_toast.ShowSuccess($"Slot renamed to '{newName.Trim()}'."); _toast.ShowSuccess($"Slot renamed to '{newName.Trim()}'.");
@@ -670,7 +671,7 @@
if (!confirmed) return; if (!confirmed) return;
var user = await GetCurrentUserAsync(); var user = await GetCurrentUserAsync();
var result = await TemplateService.DeleteCompositionAsync(composition.Id, user); var result = await ScopeFactory.InNewScopeAsync((TemplateService svc) => svc.DeleteCompositionAsync(composition.Id, user));
if (result.IsSuccess) if (result.IsSuccess)
{ {
_toast.ShowSuccess($"Composition '{composition.InstanceName}' removed."); _toast.ShowSuccess($"Composition '{composition.InstanceName}' removed.");
@@ -3,7 +3,9 @@ using System.Text.Json;
using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization; using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Forms; using Microsoft.AspNetCore.Components.Forms;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using ZB.MOM.WW.ScadaBridge.CentralUI.Services;
using ZB.MOM.WW.ScadaBridge.CentralUI.Auth; using ZB.MOM.WW.ScadaBridge.CentralUI.Auth;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites; using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories; using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
@@ -85,6 +87,7 @@ public partial class TransportImport : ComponentBase, IDisposable
[Inject] private IOptions<TransportOptions> Options { get; set; } = default!; [Inject] private IOptions<TransportOptions> Options { get; set; } = default!;
[Inject] private IAuditService AuditService { get; set; } = default!; [Inject] private IAuditService AuditService { get; set; } = default!;
[Inject] private ScadaBridgeDbContext DbContext { get; set; } = default!; [Inject] private ScadaBridgeDbContext DbContext { get; set; } = default!;
[Inject] private IServiceScopeFactory ScopeFactory { get; set; } = default!;
// Register row 44: the per-IP-per-hour unlock throttle needs the caller's // Register row 44: the per-IP-per-hour unlock throttle needs the caller's
// address, and HttpContext is long gone by the time a circuit submits a // address, and HttpContext is long gone by the time a circuit submits a
@@ -923,12 +926,18 @@ public partial class TransportImport : ComponentBase, IDisposable
// central-config-only bundles (no required mappings) this is // central-config-only bundles (no required mappings) this is
// BundleNameMap.Empty, which the importer normalises away. // BundleNameMap.Empty, which the importer normalises away.
var nameMap = BuildNameMap(); var nameMap = BuildNameMap();
_result = await BundleImporter.ApplyAsync( // Apply loads and rewrites existing rows, so it runs on its own DI scope
_session.SessionId, // (code review 2026-12-02 UI-1): the circuit's context reads without tracking
_resolutions.Values.ToList(), // and must never carry a write. The session lives in the singleton store, so a
// fresh importer instance continues the same session.
var sessionId = _session.SessionId;
var resolutions = _resolutions.Values.ToList();
_result = await ScopeFactory.InNewScopeAsync((IBundleImporter importer) => importer.ApplyAsync(
sessionId,
resolutions,
user, user,
CancellationToken.None, CancellationToken.None,
nameMap: nameMap); nameMap: nameMap));
_step = ImportWizardStep.Result; _step = ImportWizardStep.Result;
} }
catch (SemanticValidationException ex) catch (SemanticValidationException ex)
@@ -327,6 +327,7 @@
// seed-then-stream) starts warming while the initial poll runs. // seed-then-stream) starts warming while the initial poll runs.
SubscribeLive(siteId); SubscribeLive(siteId);
await RefreshAsync(); await RefreshAsync();
if (_disposed) return;
StartTimer(); StartTimer();
// If another circuit already warmed the cache for this site, the initial // If another circuit already warmed the cache for this site, the initial
// poll may be staler than what's live — apply the live snapshot on top. // poll may be staler than what's live — apply the live snapshot on top.
@@ -393,24 +394,45 @@
} }
} }
// UI-4: StartTimer runs after OnSiteChangedAsync's awaited fan-out, which can take
// seconds against an unreachable site. If the operator navigated away meanwhile,
// Dispose() has already run; creating the timer then would leak it (rooting this dead
// component) for the life of the process. Create / stop / dispose are atomic under
// _timerLock and creation is refused once disposed.
private readonly object _timerLock = new();
private void StartTimer() private void StartTimer()
{ {
StopTimer(); Timer? old;
_refreshTimer = new Timer(_ => lock (_timerLock)
{ {
_ = _pollGate.RunAsync(() => InvokeAsync(async () => old = _refreshTimer;
_refreshTimer = null;
if (!_disposed)
{ {
if (_disposed) return; _refreshTimer = new Timer(_ =>
await RefreshAsync(); {
StateHasChanged(); _ = _pollGate.RunAsync(() => InvokeAsync(async () =>
}), error => System.Diagnostics.Trace.TraceWarning("AlarmSummary refresh failed: {0}", error)); {
}, null, TimeSpan.FromSeconds(_autoRefreshSeconds), TimeSpan.FromSeconds(_autoRefreshSeconds)); if (_disposed) return;
await RefreshAsync();
StateHasChanged();
}), error => System.Diagnostics.Trace.TraceWarning("AlarmSummary refresh failed: {0}", error));
}, null, TimeSpan.FromSeconds(_autoRefreshSeconds), TimeSpan.FromSeconds(_autoRefreshSeconds));
}
}
old?.Dispose();
} }
private void StopTimer() private void StopTimer()
{ {
_refreshTimer?.Dispose(); Timer? old;
_refreshTimer = null; lock (_timerLock)
{
old = _refreshTimer;
_refreshTimer = null;
}
old?.Dispose();
} }
// ── Live cache (plan #10, Task 5) ────────────────────────────────────────── // ── Live cache (plan #10, Task 5) ──────────────────────────────────────────
@@ -606,7 +628,10 @@
public void Dispose() public void Dispose()
{ {
_disposed = true; lock (_timerLock)
{
_disposed = true;
}
StopTimer(); StopTimer();
DisposeLiveSubscription(); DisposeLiveSubscription();
} }
@@ -767,15 +767,23 @@
// and query the default site. // and query the default site.
await LoadSiteHealthTrendsAsync(); await LoadSiteHealthTrendsAsync();
_refreshTimer = new Timer(_ => // UI-4: the operator may have navigated away during the loads above. Dispose()
// has then already run and found no timer, so creating one now would leak it
// (and root this dead component) for the life of the process. Create-vs-dispose
// is atomic under _timerLock.
lock (_timerLock)
{ {
_ = _pollGate.RunAsync(() => InvokeAsync(async () => if (_disposed) return;
_refreshTimer = new Timer(_ =>
{ {
if (_disposed) return; _ = _pollGate.RunAsync(() => InvokeAsync(async () =>
await RefreshAllAsync(forceRefresh: false); {
StateHasChanged(); if (_disposed) return;
}), error => System.Diagnostics.Trace.TraceWarning("Health refresh failed: {0}", error)); await RefreshAllAsync(forceRefresh: false);
}, null, TimeSpan.FromSeconds(_autoRefreshSeconds), TimeSpan.FromSeconds(_autoRefreshSeconds)); StateHasChanged();
}), error => System.Diagnostics.Trace.TraceWarning("Health refresh failed: {0}", error));
}, null, TimeSpan.FromSeconds(_autoRefreshSeconds), TimeSpan.FromSeconds(_autoRefreshSeconds));
}
} }
// Re-query when the operator picks a different site. Best-effort: the load // Re-query when the operator picks a different site. Best-effort: the load
@@ -1041,10 +1049,15 @@
}; };
private volatile bool _disposed; private volatile bool _disposed;
private readonly object _timerLock = new();
public void Dispose() public void Dispose()
{ {
_disposed = true; lock (_timerLock)
_refreshTimer?.Dispose(); {
_disposed = true;
_refreshTimer?.Dispose();
_refreshTimer = null;
}
} }
} }
@@ -838,26 +838,18 @@
} }
/// <summary> /// <summary>
/// Server-side re-check for the Retry/Discard relay actions. Returns true for a /// Server-side re-check for the Retry/Discard relay actions (fresh authority).
/// system-wide user, or when the row's source site resolves to a Site.Id in the /// A system-wide user may act on any row — including one whose source site no
/// caller's permitted set. An unresolvable site identifier defaults to allowed /// longer resolves (deleted or renamed), which the grid deliberately keeps showing
/// (legacy behaviour); the relay's own site-scope re-check is then the /// (code review 2026-12-02 UI-11: such rows used to be refused for everyone, even an
/// final gate. /// Administrator, so they could not be cleared). A site-scoped user may act only
/// when the row's site resolves to a <c>Site.Id</c> in their permitted set; an
/// unresolvable site is denied for them.
/// </summary> /// </summary>
private bool IsRowSiteAllowedSync(string sourceSiteId)
{
if (_siteScopeSystemWide)
return true;
var resolved = _allSites.FirstOrDefault(s => s.SiteIdentifier == sourceSiteId);
if (resolved is null)
return true;
return _permittedSiteIds.Contains(resolved.Id);
}
private async Task<bool> IsRowSiteAllowedAsync(string sourceSiteId) private async Task<bool> IsRowSiteAllowedAsync(string sourceSiteId)
{ {
if (await SiteScope.IsSystemWideAsync())
return true;
var resolved = (await SiteRepository.GetAllSitesAsync()).FirstOrDefault(s => s.SiteIdentifier == sourceSiteId); var resolved = (await SiteRepository.GetAllSitesAsync()).FirstOrDefault(s => s.SiteIdentifier == sourceSiteId);
return resolved is not null && await SiteScope.IsSiteAllowedAsync(resolved.Id); return resolved is not null && await SiteScope.IsSiteAllowedAsync(resolved.Id);
} }
@@ -602,11 +602,17 @@ public partial class SiteCallsReport
} }
/// <summary> /// <summary>
/// Server-side re-check for the Retry/Discard relay. True for a system-wide /// Server-side re-check for the Retry/Discard relay (fresh authority). A system-wide
/// user, or when the row's source site maps to a Site.Id in the permitted set. /// user may act on any row, including one whose source site no longer resolves
/// (deleted or renamed) — code review 2026-12-02 UI-11: such rows used to be refused
/// for everyone, even an Administrator. A site-scoped user may act only when the
/// row's site maps to a Site.Id in their permitted set; an unresolvable site is
/// denied for them.
/// </summary> /// </summary>
private async Task<bool> IsRowSiteAllowedAsync(string sourceSite) private async Task<bool> IsRowSiteAllowedAsync(string sourceSite)
{ {
if (await SiteScope.IsSystemWideAsync())
return true;
var resolved = (await SiteRepository.GetAllSitesAsync()).FirstOrDefault(s => s.SiteIdentifier == sourceSite); var resolved = (await SiteRepository.GetAllSitesAsync()).FirstOrDefault(s => s.SiteIdentifier == sourceSite);
return resolved is not null && await SiteScope.IsSiteAllowedAsync(resolved.Id); return resolved is not null && await SiteScope.IsSiteAllowedAsync(resolved.Id);
} }
@@ -1,6 +1,7 @@
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services; using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services;
using Microsoft.AspNetCore.Components.Authorization; using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using ZB.MOM.WW.ScadaBridge.CentralUI.Auth; using ZB.MOM.WW.ScadaBridge.CentralUI.Auth;
using ZB.MOM.WW.ScadaBridge.CentralUI.Components.Shared; using ZB.MOM.WW.ScadaBridge.CentralUI.Components.Shared;
@@ -38,6 +39,12 @@ public static class ServiceCollectionExtensions
// Resolves the current user's permitted site set from their SiteId claims // Resolves the current user's permitted site set from their SiteId claims
// so Deployment/Monitoring pages can enforce site scoping. // so Deployment/Monitoring pages can enforce site scoping.
services.AddScoped<SiteScopeService>(); services.AddScoped<SiteScopeService>();
// Code review 2026-12-02 UI-1: the circuit-lifetime configuration DbContext reads
// without tracking, so a reload always sees changes made in other scopes. Mutating
// page actions run on their own scope (ConfigurationCommandService, the management
// actor, or ScopedServiceExtensions.InNewScopeAsync), never on the circuit's context.
services.TryAddEnumerable(ServiceDescriptor.Scoped<
Microsoft.AspNetCore.Components.Server.Circuits.CircuitHandler, CircuitDbContextTrackingHandler>());
services.AddScoped<AuthorizedManualFailoverService>(); services.AddScoped<AuthorizedManualFailoverService>();
services.AddScoped<ConfigurationCommandService>(); services.AddScoped<ConfigurationCommandService>();
@@ -0,0 +1,56 @@
using Microsoft.AspNetCore.Components.Server.Circuits;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase;
namespace ZB.MOM.WW.ScadaBridge.CentralUI.Services;
/// <summary>
/// Gives each Blazor Server circuit's <see cref="ScadaBridgeDbContext"/> a no-tracking query
/// default (code review 2026-12-02, UI-1).
/// </summary>
/// <remarks>
/// <para>
/// The configuration <see cref="ScadaBridgeDbContext"/> is registered scoped, and in Blazor
/// Server one DI scope lives for the whole circuit — hours, across page navigations. With EF's
/// default tracking behaviour every entity a page ever loaded stayed in that context's change
/// tracker, and a later tracking query for the same key returned the first-loaded instance
/// without refreshing its values. Changes made in any other scope (the management actor, another
/// user, the CLI, a Transport import) were therefore never seen by the circuit: a moved data
/// connection stayed under its old site, a renamed area kept its old name on the live Topology,
/// and a template script re-opened after a CLI edit showed — and on save wrote back — the old body.
/// </para>
/// <para>
/// Only the circuit's context is switched; contexts in every other scope (management-actor
/// commands, the configuration command transaction, HTTP request scopes, hosted services,
/// singleton actors) keep EF's tracking default, so the shared services that load-modify-save
/// still work there. Page actions that mutate configuration never run on the circuit's context:
/// they go through <c>ConfigurationCommandService</c> (its own transaction scope), the
/// <c>ManagementActor</c>, or <see cref="ScopedServiceExtensions.InNewScopeAsync{TService, TResult}"/>.
/// </para>
/// <para>
/// The switch is made in the constructor: the circuit factory resolves every
/// <see cref="CircuitHandler"/> from the new circuit's scope while it builds the circuit host,
/// before any component is created, so no page query can run on the context first. The context is
/// resolved optionally because hosts without the configuration database (tests, a non-central
/// role) have none.
/// </para>
/// </remarks>
public sealed class CircuitDbContextTrackingHandler : CircuitHandler
{
/// <summary>The query-tracking behaviour every circuit's configuration context runs with.</summary>
public const QueryTrackingBehavior CircuitQueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
/// <summary>Switches the circuit scope's configuration context to the no-tracking default.</summary>
/// <param name="circuitServices">The circuit's scoped service provider.</param>
public CircuitDbContextTrackingHandler(IServiceProvider circuitServices)
{
ArgumentNullException.ThrowIfNull(circuitServices);
var context = circuitServices.GetService<ScadaBridgeDbContext>();
if (context is not null)
context.ChangeTracker.QueryTrackingBehavior = CircuitQueryTrackingBehavior;
}
/// <summary>Runs ahead of other handlers so nothing observes the context first.</summary>
public override int Order => int.MinValue;
}
@@ -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
/// (<see cref="CircuitDbContextTrackingHandler"/>), 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"));
}
} }
@@ -358,4 +358,35 @@ public class DataConnectionsPageTests : BunitContext
Assert.Contains("PLC-A", cut.Markup); Assert.Contains("PLC-A", cut.Markup);
Assert.Contains("PLC-B", 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));
}
} }
@@ -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));
}
} }
@@ -106,4 +106,69 @@ public class PendingUpdatesHealthTilesTests : BunitContext
cut.WaitForAssertion(() => Assert.Equal("0", cut.Find("[data-test='pending-updates-instances'] h3").TextContent.Trim())); 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>()))); 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> /// <summary>Verifies that a query failure shows an error message.</summary>
[Fact] [Fact]
public void QueryFailure_ShowsErrorMessage() 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> /// <summary>Verifies that clicking Discard on a parked row relays the discard to the owning site.</summary>
[Fact] [Fact]
public void ClickDiscard_OnParkedRow_RelaysDiscardToOwningSite() public void ClickDiscard_OnParkedRow_RelaysDiscardToOwningSite()
@@ -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>()); 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()