fix(centralui): no timers/subscriptions created after a mid-load dispose (UI-4, WP5 task 5.3)

A navigation while an awaited load was still running disposed the component
first; the continuation then created a timer / added a singleton handler that
nothing ever disposed, rooting the dead circuit for the life of the process.

- Health: refresh timer created under _timerLock only if not disposed.
- DataConnections: same for the health-poll timer; also stops before touching
  the disposed CTS when disposed during the first load.
- Deployments: subscribe to IDeploymentStatusNotifier BEFORE the first load
  (the handler only schedules a reload; the generation guard orders flights).
- PendingUpdatesHealthTiles: the Invalidated subscription and the poll timer are
  both created under a lifetime lock after a disposed check; Dispose unsubscribes
  only what was subscribed (covers a dispose during the auth-state await too).
- AlarmSummary: StartTimer/StopTimer/Dispose atomic under _timerLock; StartTimer
  refuses after dispose (Topology.StartLiveUpdatesTimer idiom).

Tests (each fails on the pre-fix component): HealthPageTests, DataConnectionsPageTests,
DeploymentsPerFlightScopeTests, PendingUpdatesHealthTilesTests (x2),
AlarmSummaryRenderTests - dispose mid-load, release the load, assert no timer and
no handler left.
This commit is contained in:
Joseph Doherty
2026-12-03 10:00:36 -05:00
parent 2969ee44e5
commit 7addd846a1
10 changed files with 312 additions and 33 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;
}
}
}
@@ -343,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) ───────────────────────────────────
@@ -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();
}
}
@@ -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;
}
}
}