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
@@ -53,6 +53,8 @@
private Timer? _timer;
private volatile bool _disposed;
private bool _subscribed;
private readonly object _lifetimeLock = new();
private bool _visible;
private IReadOnlySet<int>? _scopedSiteIds;
private PendingUpdatesSnapshot? _snapshot;
@@ -85,9 +87,23 @@
var (isSystemWide, sites) = SiteScopeService.Resolve(user);
_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();
_timer = new Timer(_ => _ = ReloadAsync(), null, PollInterval, PollInterval);
lock (_lifetimeLock)
{
if (_disposed) return;
_timer = new Timer(_ => _ = ReloadAsync(), null, PollInterval, PollInterval);
}
}
private void OnInvalidated() => _ = ReloadAsync();
@@ -131,12 +147,17 @@
public void Dispose()
{
_disposed = true;
if (_visible)
lock (_lifetimeLock)
{
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)]
@inject ISiteRepository SiteRepository
@inject IPendingUpdatesCache PendingUpdates
@inject ArtifactDeploymentService ArtifactDeploymentService
@inject Microsoft.Extensions.DependencyInjection.IServiceScopeFactory ScopeFactory
@using Microsoft.Extensions.DependencyInjection
@inject CommunicationService CommunicationService
@inject AuthenticationStateProvider AuthStateProvider
@inject NavigationManager NavigationManager
@@ -314,8 +315,11 @@
try
{
var user = await GetCurrentUserAsync();
var result = await ArtifactDeploymentService.RetryForSiteAsync(
site.Id, site.SiteIdentifier, user);
// Own DI scope (UI-3): the deploy's record, audit rows and revision stamp are all
// 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;
if (succeeded)
@@ -349,7 +353,9 @@
try
{
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;
if (succeeded)
@@ -4,7 +4,8 @@
@using ZB.MOM.WW.ScadaBridge.Commons.Types.Deployment
@using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums
@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.DeploymentManager.IDeploymentStatusNotifier DeploymentStatusNotifier
@implements IDisposable
@@ -342,8 +343,13 @@
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;
await LoadDataAsync();
}
// ── Push coalescing (arch-review WP2.4) ───────────────────────────────────
@@ -615,13 +621,20 @@
SiteIdScope: siteScope,
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);
// The tile counts deliberately ignore the status filter (see
// GetDeploymentStatusCountsAsync) so each tile keeps showing its own
// 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
// now the current one) — this flight's results are stale. Discard
@@ -646,7 +659,7 @@
if (_currentPage > _totalPages && _totalPages >= 1)
{
_currentPage = _totalPages;
var reread = await DeploymentManagerRepository
var reread = await deployments
.QueryDeploymentListPageAsync(filter, _currentPage, PageSize);
if (generation != _requestGeneration)
@@ -18,9 +18,6 @@
@inject ITemplateEngineRepository TemplateEngineRepository
@inject ISiteRepository SiteRepository
@inject IDeploymentManagerRepository DeploymentManagerRepository
@inject DeploymentService DeploymentService
@inject AreaService AreaService
@inject InstanceService InstanceService
@inject AuthenticationStateProvider AuthStateProvider
@inject ZB.MOM.WW.ScadaBridge.CentralUI.Auth.SiteScopeService SiteScope
@inject NavigationManager NavigationManager
@@ -977,7 +974,9 @@
{
var user = await GetCurrentUserAsync(inst.Id);
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)
{
_toast.ShowSuccess($"Instance '{inst.UniqueName}' deleted.");
@@ -1003,7 +1002,7 @@
{
var user = await GetCurrentUserAsync(inst.Id);
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)
{
_toast.ShowSuccess($"Instance '{inst.UniqueName}' enabled.");
@@ -1035,7 +1034,7 @@
{
var user = await GetCurrentUserAsync(inst.Id);
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)
{
_toast.ShowSuccess($"Instance '{inst.UniqueName}' disabled.");
@@ -1175,7 +1174,9 @@
string? diffError = null;
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)
{
diffResult = result.Value;
@@ -233,6 +233,7 @@
// DebugView.razor. The CTS is used to cancel the in-flight health query when
// the component is disposed.
private volatile bool _disposed;
private readonly object _timerLock = new();
private bool _healthTickInFlight;
private readonly CancellationTokenSource _disposeCts = new();
@@ -241,17 +242,24 @@
protected override async Task OnInitializedAsync()
{
await LoadDataAsync();
if (_disposed) return;
await LoadConnectionHealthAsync(_disposeCts.Token);
// 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
// disturbing the tree.
// 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;
_ = DispatchHealthTickAsync();
}, null, TimeSpan.FromSeconds(HealthRefreshSeconds), TimeSpan.FromSeconds(HealthRefreshSeconds));
_healthTimer = new Timer(_ =>
{
if (_disposed) return;
_ = DispatchHealthTickAsync();
}, null, TimeSpan.FromSeconds(HealthRefreshSeconds), TimeSpan.FromSeconds(HealthRefreshSeconds));
}
}
/// <summary>
@@ -479,9 +487,13 @@
// 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
// stop the timer. Mirrors Deployments.razor and DebugView.razor.
_disposed = true;
lock (_timerLock)
{
_disposed = true;
_healthTimer?.Dispose();
_healthTimer = null;
}
_disposeCts.Cancel();
_disposeCts.Dispose();
_healthTimer?.Dispose();
}
}
@@ -1,5 +1,8 @@
@page "/design/shared-scripts/create"
@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.Commons.Entities.Scripts
@using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories
@@ -278,8 +281,8 @@
if (Id.HasValue)
{
var user = await GetCurrentUserAsync();
var result = await SharedScriptService.UpdateSharedScriptAsync(
Id.Value, _formCode, _formParameters?.Trim(), _formReturn?.Trim(), user);
var result = await ScopeFactory.InNewScopeAsync((SharedScriptService svc) => svc.UpdateSharedScriptAsync(
Id.Value, _formCode, _formParameters?.Trim(), _formReturn?.Trim(), user));
if (result.IsSuccess)
{
NavigationManager.NavigateTo("/design/shared-scripts");
@@ -292,8 +295,8 @@
else
{
var user = await GetCurrentUserAsync();
var result = await SharedScriptService.CreateSharedScriptAsync(
_formName.Trim(), _formCode, _formParameters?.Trim(), _formReturn?.Trim(), user);
var result = await ScopeFactory.InNewScopeAsync((SharedScriptService svc) => svc.CreateSharedScriptAsync(
_formName.Trim(), _formCode, _formParameters?.Trim(), _formReturn?.Trim(), user));
if (result.IsSuccess)
{
NavigationManager.NavigateTo("/design/shared-scripts");
@@ -1,4 +1,7 @@
@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.Commons.Entities.Scripts
@using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories
@@ -151,7 +154,7 @@
try
{
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)
{
_toast.ShowSuccess($"Script '{script.Name}' deleted.");
@@ -1,4 +1,6 @@
@page "/design/templates/create"
@using Microsoft.Extensions.DependencyInjection
@inject IServiceScopeFactory ScopeFactory
@using ZB.MOM.WW.ScadaBridge.CentralUI.Services
@using ZB.MOM.WW.ScadaBridge.Security
@using ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates
@@ -6,7 +8,6 @@
@using ZB.MOM.WW.ScadaBridge.TemplateEngine
@attribute [Authorize(Policy = AuthorizationPolicies.RequireDesign)]
@inject ITemplateEngineRepository TemplateEngineRepository
@inject TemplateService TemplateService
@inject AuthenticationStateProvider AuthStateProvider
@inject NavigationManager NavigationManager
@@ -95,10 +96,10 @@
try
{
var user = await GetCurrentUserAsync();
var result = await TemplateService.CreateTemplateAsync(
var result = await ScopeFactory.InNewScopeAsync((TemplateService svc) => svc.CreateTemplateAsync(
_createName.Trim(), _createDescription?.Trim(),
_createParentId == 0 ? null : _createParentId, user,
folderId: FolderId);
folderId: FolderId));
if (result.IsSuccess)
{
@@ -2,6 +2,8 @@
@using ZB.MOM.WW.ScadaBridge.Commons.Messages.Management
@inject IServiceProvider MutationServices
@page "/design/templates/{Id:int}"
@using Microsoft.Extensions.DependencyInjection
@inject IServiceScopeFactory ScopeFactory
@using ZB.MOM.WW.ScadaBridge.Security
@using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances
@using ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates
@@ -569,7 +571,7 @@
try
{
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)
{
_toast.ShowSuccess($"Template '{_selectedTemplate.Name}' deleted.");
@@ -592,9 +594,9 @@
try
{
var user = await GetCurrentUserAsync();
var result = await TemplateService.UpdateTemplateAsync(
var result = await ScopeFactory.InNewScopeAsync((TemplateService svc) => svc.UpdateTemplateAsync(
_selectedTemplate.Id, _editName.Trim(), _editDescription?.Trim(),
_editParentId == 0 ? null : _editParentId, user);
_editParentId == 0 ? null : _editParentId, user));
if (result.IsSuccess)
{
@@ -818,7 +820,7 @@
IsInherited = attr.IsInherited,
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."); }
else _toast.ShowError(result.Error);
}
@@ -841,7 +843,7 @@
IsInherited = 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(); }
else _toast.ShowError(result.Error);
}
@@ -864,7 +866,7 @@
IsInherited = true,
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(); }
else _toast.ShowError(result.Error);
}
@@ -882,7 +884,7 @@
try
{
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)
{
var r = result.Value;
@@ -1284,7 +1286,7 @@
IsInherited = script.IsInherited,
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."); }
else _toast.ShowError(result.Error);
}
@@ -1308,7 +1310,7 @@
IsInherited = true,
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(); }
else _toast.ShowError(result.Error);
}
@@ -1426,7 +1428,7 @@
IsInherited = existing.IsInherited,
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;
_toast.ShowSuccess($"Attribute '{existing.Name}' updated.");
@@ -1442,7 +1444,7 @@
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;
_toast.ShowSuccess($"Attribute '{draft.Name}' added.");
@@ -1454,7 +1456,7 @@
var confirmed = await Dialog.ConfirmAsync("Delete Attribute", $"Delete attribute '{attr.Name}'?", danger: true);
if (!confirmed) return;
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)
{
_toast.ShowSuccess($"Attribute '{attr.Name}' deleted.");
@@ -1562,7 +1564,7 @@
Description = existing.Description,
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;
_toast.ShowSuccess($"Alarm '{existing.Name}' updated.");
@@ -1578,7 +1580,7 @@
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;
_toast.ShowSuccess($"Alarm '{draft.Name}' added.");
@@ -1590,7 +1592,7 @@
var confirmed = await Dialog.ConfirmAsync("Delete Alarm", $"Delete alarm '{alarm.Name}'?", danger: true);
if (!confirmed) return;
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)
{
_toast.ShowSuccess($"Alarm '{alarm.Name}' deleted.");
@@ -1698,7 +1700,7 @@
IsInherited = existing.IsInherited,
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;
_toast.ShowSuccess($"Script '{existing.Name}' updated.");
@@ -1716,7 +1718,7 @@
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;
_toast.ShowSuccess($"Script '{draft.Name}' added.");
@@ -1728,7 +1730,7 @@
var confirmed = await Dialog.ConfirmAsync("Delete Script", $"Delete script '{script.Name}'?", danger: true);
if (!confirmed) return;
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)
{
_toast.ShowSuccess($"Script '{script.Name}' deleted.");
@@ -1,4 +1,7 @@
@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.Commons.Entities.Templates
@using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories
@@ -8,8 +11,6 @@
@using ZB.MOM.WW.ScadaBridge.TemplateEngine.Services
@attribute [Authorize(Policy = AuthorizationPolicies.RequireDesign)]
@inject ITemplateEngineRepository TemplateEngineRepository
@inject TemplateService TemplateService
@inject TemplateFolderService TemplateFolderService
@inject AuthenticationStateProvider AuthStateProvider
@inject NavigationManager NavigationManager
@inject IDialogService Dialog
@@ -355,7 +356,7 @@
if (string.IsNullOrWhiteSpace(name)) return;
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)
{
_toast.ShowSuccess($"Folder '{result.Value.Name}' created.");
@@ -378,7 +379,7 @@
if (result is null) return;
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)
{
_toast.ShowSuccess($"Template '{label}' moved.");
@@ -430,7 +431,7 @@
if (result is null) return;
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)
{
_toast.ShowSuccess($"Folder '{label}' moved.");
@@ -451,7 +452,7 @@
private async Task ReorderFolder(int folderId, ReorderDirection direction)
{
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)
{
await LoadTemplatesAsync();
@@ -542,7 +543,7 @@
if (string.IsNullOrWhiteSpace(newName)) return;
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)
{
_toast.ShowSuccess("Folder renamed.");
@@ -560,7 +561,7 @@
if (!confirmed) return;
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)
{
_toast.ShowSuccess($"Folder '{label}' deleted.");
@@ -583,7 +584,7 @@
try
{
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)
{
_toast.ShowSuccess($"Template '{template.Name}' deleted.");
@@ -616,7 +617,7 @@
if (result is null) return;
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)
{
_toast.ShowSuccess($"Composed '{sourceName}' as '{result.SlotName}'.");
@@ -649,7 +650,7 @@
if (string.IsNullOrWhiteSpace(newName) || newName.Trim() == composition.InstanceName) return;
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)
{
_toast.ShowSuccess($"Slot renamed to '{newName.Trim()}'.");
@@ -670,7 +671,7 @@
if (!confirmed) return;
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)
{
_toast.ShowSuccess($"Composition '{composition.InstanceName}' removed.");
@@ -3,7 +3,9 @@ using System.Text.Json;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.ScadaBridge.CentralUI.Services;
using ZB.MOM.WW.ScadaBridge.CentralUI.Auth;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites;
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 IAuditService AuditService { 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
// 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
// BundleNameMap.Empty, which the importer normalises away.
var nameMap = BuildNameMap();
_result = await BundleImporter.ApplyAsync(
_session.SessionId,
_resolutions.Values.ToList(),
// Apply loads and rewrites existing rows, so it runs on its own DI scope
// (code review 2026-12-02 UI-1): the circuit's context reads without tracking
// 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,
CancellationToken.None,
nameMap: nameMap);
nameMap: nameMap));
_step = ImportWizardStep.Result;
}
catch (SemanticValidationException ex)
@@ -327,6 +327,7 @@
// seed-then-stream) starts warming while the initial poll runs.
SubscribeLive(siteId);
await RefreshAsync();
if (_disposed) return;
StartTimer();
// 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.
@@ -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()
{
StopTimer();
_refreshTimer = new Timer(_ =>
Timer? old;
lock (_timerLock)
{
_ = _pollGate.RunAsync(() => InvokeAsync(async () =>
old = _refreshTimer;
_refreshTimer = null;
if (!_disposed)
{
if (_disposed) return;
await RefreshAsync();
StateHasChanged();
}), error => System.Diagnostics.Trace.TraceWarning("AlarmSummary refresh failed: {0}", error));
}, null, TimeSpan.FromSeconds(_autoRefreshSeconds), TimeSpan.FromSeconds(_autoRefreshSeconds));
_refreshTimer = new Timer(_ =>
{
_ = _pollGate.RunAsync(() => InvokeAsync(async () =>
{
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()
{
_refreshTimer?.Dispose();
_refreshTimer = null;
Timer? old;
lock (_timerLock)
{
old = _refreshTimer;
_refreshTimer = null;
}
old?.Dispose();
}
// ── Live cache (plan #10, Task 5) ──────────────────────────────────────────
@@ -606,7 +628,10 @@
public void Dispose()
{
_disposed = true;
lock (_timerLock)
{
_disposed = true;
}
StopTimer();
DisposeLiveSubscription();
}
@@ -767,15 +767,23 @@
// and query the default site.
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;
await RefreshAllAsync(forceRefresh: false);
StateHasChanged();
}), error => System.Diagnostics.Trace.TraceWarning("Health refresh failed: {0}", error));
}, null, TimeSpan.FromSeconds(_autoRefreshSeconds), TimeSpan.FromSeconds(_autoRefreshSeconds));
_ = _pollGate.RunAsync(() => InvokeAsync(async () =>
{
if (_disposed) return;
await RefreshAllAsync(forceRefresh: false);
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
@@ -1041,10 +1049,15 @@
};
private volatile bool _disposed;
private readonly object _timerLock = new();
public void Dispose()
{
_disposed = true;
_refreshTimer?.Dispose();
lock (_timerLock)
{
_disposed = true;
_refreshTimer?.Dispose();
_refreshTimer = null;
}
}
}
@@ -838,26 +838,18 @@
}
/// <summary>
/// Server-side re-check for the Retry/Discard relay actions. Returns true for a
/// system-wide user, or when the row's source site resolves to a Site.Id in the
/// caller's permitted set. An unresolvable site identifier defaults to allowed
/// (legacy behaviour); the relay's own site-scope re-check is then the
/// final gate.
/// Server-side re-check for the Retry/Discard relay actions (fresh authority).
/// A system-wide user may act on any row — including one whose source site no
/// longer resolves (deleted or renamed), which the grid deliberately keeps showing
/// (code review 2026-12-02 UI-11: such rows used to be refused for everyone, even an
/// 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>
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)
{
if (await SiteScope.IsSystemWideAsync())
return true;
var resolved = (await SiteRepository.GetAllSitesAsync()).FirstOrDefault(s => s.SiteIdentifier == sourceSiteId);
return resolved is not null && await SiteScope.IsSiteAllowedAsync(resolved.Id);
}
@@ -602,11 +602,17 @@ public partial class SiteCallsReport
}
/// <summary>
/// Server-side re-check for the Retry/Discard relay. True for a system-wide
/// user, or when the row's source site maps to a Site.Id in the permitted set.
/// Server-side re-check for the Retry/Discard relay (fresh authority). A system-wide
/// 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>
private async Task<bool> IsRowSiteAllowedAsync(string sourceSite)
{
if (await SiteScope.IsSystemWideAsync())
return true;
var resolved = (await SiteRepository.GetAllSitesAsync()).FirstOrDefault(s => s.SiteIdentifier == sourceSite);
return resolved is not null && await SiteScope.IsSiteAllowedAsync(resolved.Id);
}
@@ -1,6 +1,7 @@
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.ScadaBridge.CentralUI.Auth;
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
// so Deployment/Monitoring pages can enforce site scoping.
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<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>());
}
}