fix(dashboard): close the dropped live-read session; subscribe-and-track off the caller's token (DSH-002 #248, DSH-007, #253)

This commit is contained in:
Joseph Doherty
2026-12-03 09:47:46 -05:00
parent 0673b0c76c
commit 159524edd9
3 changed files with 131 additions and 17 deletions
+12
View File
@@ -637,6 +637,18 @@ its lease expires. One session means one worker process backs every dashboard
circuit; all access is serialised so the worker sees one in-flight command at a
time. Tag reads go through `GatewaySession.SubscribeBulkAsync` / `ReadBulkAsync`.
When a read fails for any reason other than cancellation, the service closes that
session before dropping it, and the next read opens a new one. A command timeout
or a non-Ok bulk reply leaves the session `Ready` with a live worker and its
advised tags; dropping only the reference left it in the registry until its lease
expired, and a Browse page that kept failing opened a new session every poll
until `MaxSessions` refused real clients. A Register failure on a freshly opened
session closes it the same way. The subscribe-and-track step and the eviction
unadvise run on `CancellationToken.None` (bounded by the session's command
timeout) and observe the caller's token only afterwards, so a page that cancels
its read mid-subscribe cannot leave tags advised on the worker that the advise
set does not track.
The advise set that backs those reads is capped at 256 tags (one browse page plus
headroom) and evicted least-recently-read-first. Without the cap every tag any
viewer ever inspected stayed advised on the single dashboard worker until the
@@ -147,12 +147,18 @@ public sealed class DashboardLiveDataService : IDashboardLiveDataService, IAsync
string[] toSubscribe = TouchAndCollectNewTags(tagAddresses, viewer, out HashSet<string> justRead);
if (toSubscribe.Length > 0)
{
await EvictForAsync(session, serverHandle, toSubscribe.Length, justRead, viewer, now, cancellationToken)
await EvictForAsync(session, serverHandle, toSubscribe.Length, justRead, viewer, now)
.ConfigureAwait(false);
// The subscribe and its tracking run as one step that the caller's token cannot
// split (DSH-007): a cancellation that lands after the worker advised the tags but
// before TrackSubscribed would leave advises nothing tracks — never unadvised, not
// counted against MaxSubscribedTags, and re-advised on the next read. The session's
// command timeout still bounds the call; the caller's token is observed after.
IReadOnlyList<SubscribeResult> subscribeResults = await session
.SubscribeBulkAsync(serverHandle, toSubscribe, cancellationToken)
.SubscribeBulkAsync(serverHandle, toSubscribe, CancellationToken.None)
.ConfigureAwait(false);
TrackSubscribed(toSubscribe, subscribeResults, viewer);
cancellationToken.ThrowIfCancellationRequested();
}
IReadOnlyList<BulkReadResult> results = await session
@@ -178,7 +184,17 @@ public sealed class DashboardLiveDataService : IDashboardLiveDataService, IAsync
}
catch (Exception exception) when (exception is not OperationCanceledException)
{
// Close the session being dropped, not just forget it (DSH-002). A command timeout or a
// non-Ok bulk reply leaves the session Ready with a live x86 worker and its advised
// tags; once unreferenced, nothing sweeps it until its lease expires, and the next poll
// opens another — a repeatedly failing Browse page could fill MaxSessions.
GatewaySession? failedSession = _session;
InvalidateSession();
if (failedSession is not null)
{
await CloseQuietlyAsync(failedSession.SessionId).ConfigureAwait(false);
}
_logger.LogWarning(exception, "Dashboard live read failed; the dashboard session will be re-opened.");
return new DashboardLiveReadResult([], exception.Message, null, null);
}
@@ -280,17 +296,16 @@ public sealed class DashboardLiveDataService : IDashboardLiveDataService, IAsync
// back at the cap). A read that subscribes nothing new evicts nothing, but it also
// cannot grow the set.
//
// Cancellation mid-eviction follows this file's policy: OperationCanceledException
// is deliberately not caught here or in ReadAsync, so it propagates with the tags
// already dropped from tracking — the same end state as a failed unadvise.
// The unadvise runs on CancellationToken.None, so a caller cancelling mid-read cannot
// strand evicted tags advised-but-untracked; only a failed unadvise can, and that is
// logged.
private async Task EvictForAsync(
GatewaySession session,
int serverHandle,
int incomingCount,
HashSet<string> justRead,
string reader,
DateTimeOffset now,
CancellationToken cancellationToken)
DateTimeOffset now)
{
int overflow = _subscribed.Count + incomingCount - MaxSubscribedTags;
if (overflow <= 0)
@@ -351,7 +366,10 @@ public sealed class DashboardLiveDataService : IDashboardLiveDataService, IAsync
try
{
await session.UnsubscribeBulkAsync(serverHandle, evictedHandles, cancellationToken)
// Not the caller's token: the evicted tags are already dropped from tracking, so an
// unadvise abandoned on cancellation would leave them advised with nothing to remove
// them (DSH-007). The session's command timeout bounds the call.
await session.UnsubscribeBulkAsync(serverHandle, evictedHandles, CancellationToken.None)
.ConfigureAwait(false);
}
catch (Exception exception) when (exception is not OperationCanceledException)
@@ -506,17 +524,28 @@ public sealed class DashboardLiveDataService : IDashboardLiveDataService, IAsync
cancellationToken)
.ConfigureAwait(false);
WorkerCommandReply reply = await session.InvokeAsync(
new WorkerCommand
{
Command = new MxCommand
// Until _session holds it, nothing else references the new session: any way out of the
// Register step (a fault, a timeout, the caller cancelling) must close it.
WorkerCommandReply reply;
try
{
reply = await session.InvokeAsync(
new WorkerCommand
{
Kind = MxCommandKind.Register,
Register = new RegisterCommand { ClientName = ClientName },
Command = new MxCommand
{
Kind = MxCommandKind.Register,
Register = new RegisterCommand { ClientName = ClientName },
},
},
},
cancellationToken)
.ConfigureAwait(false);
cancellationToken)
.ConfigureAwait(false);
}
catch
{
await CloseQuietlyAsync(session.SessionId).ConfigureAwait(false);
throw;
}
int? serverHandle = reply.Reply?.Register?.ServerHandle;
if (serverHandle is null)
@@ -342,6 +342,57 @@ public sealed class DashboardLiveDataServiceTests
Assert.Equal(DashboardTagValue.RedactedValueText, succeeded.ValueText);
}
/// <summary>
/// DSH-002: a read that fails without faulting the session (here a worker-side
/// bulk-read failure) closes the dashboard session it drops, so the next read's
/// fresh session never coexists with an orphaned one.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task ReadAsync_WhenReadFails_ClosesTheDroppedSession()
{
RecordingWorkerClient worker = new() { FailReadBulk = true };
await using FakeSessionManager sessionManager = new(worker);
await using DashboardLiveDataService service = CreateService(sessionManager);
DashboardLiveReadResult first = await service.ReadAsync(["Tank_001.PV"], CancellationToken.None);
Assert.NotNull(first.Error);
Assert.Equal(["dashboard-session-1"], sessionManager.ClosedSessionIds);
worker.FailReadBulk = false;
DashboardLiveReadResult second = await service.ReadAsync(["Tank_001.PV"], CancellationToken.None);
Assert.Null(second.Error);
Assert.Equal(2, sessionManager.OpenCount);
Assert.Equal("dashboard-session-2", second.SessionId);
Assert.Equal(["dashboard-session-1"], sessionManager.ClosedSessionIds);
}
/// <summary>
/// DSH-007: a caller that cancels after the worker advised the tags still gets them
/// tracked, so the next read does not advise them a second time.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task ReadAsync_CancelledMidSubscribe_StillTracksTheAdvisedTags()
{
RecordingWorkerClient worker = new();
await using FakeSessionManager sessionManager = new(worker);
await using DashboardLiveDataService service = CreateService(sessionManager);
using CancellationTokenSource pageToken = new();
worker.OnSubscribe = pageToken.Cancel;
await Assert.ThrowsAnyAsync<OperationCanceledException>(
() => service.ReadAsync(["Tank_001.PV", "Tank_002.PV"], pageToken.Token));
worker.OnSubscribe = null;
DashboardLiveReadResult next = await service.ReadAsync(["Tank_001.PV", "Tank_002.PV"], CancellationToken.None);
Assert.Null(next.Error);
Assert.Equal(["Tank_001.PV", "Tank_002.PV"], worker.SubscribedTags);
Assert.Equal(1, sessionManager.OpenCount);
}
private static DashboardLiveDataService CreateService(
ISessionManager sessionManager,
bool showTagValues = false,
@@ -414,9 +465,13 @@ public sealed class DashboardLiveDataServiceTests
return session is not null;
}
/// <summary>Gets the ids of the sessions the dashboard service closed, in order.</summary>
public List<string> ClosedSessionIds { get; } = [];
/// <inheritdoc />
public Task<SessionCloseResult> CloseSessionAsync(string sessionId, CancellationToken cancellationToken)
{
ClosedSessionIds.Add(sessionId);
return Task.FromResult(new SessionCloseResult(sessionId, SessionState.Closed, AlreadyClosed: false));
}
@@ -494,6 +549,16 @@ public sealed class DashboardLiveDataServiceTests
/// </summary>
public MxValue? ReadValue { get; set; }
/// <summary>Gets or sets a value indicating whether every bulk read throws, as a worker-side failure would.</summary>
public bool FailReadBulk { get; set; }
/// <summary>
/// Gets or sets a hook run after a subscribe was applied worker-side and before the
/// reply returns; the fake then honours the command's cancellation token, as a real
/// reply wait would.
/// </summary>
public Action? OnSubscribe { get; set; }
/// <summary>Gets the tag addresses whose bulk read comes back unsuccessful.</summary>
public HashSet<string> FailReadFor { get; } = new(StringComparer.OrdinalIgnoreCase);
@@ -527,6 +592,12 @@ public sealed class DashboardLiveDataServiceTests
break;
case MxCommandKind.SubscribeBulk:
reply.SubscribeBulk = Subscribe(mxCommand.SubscribeBulk.TagAddresses);
if (OnSubscribe is not null)
{
OnSubscribe();
cancellationToken.ThrowIfCancellationRequested();
}
break;
case MxCommandKind.UnsubscribeBulk:
UnsubscribeCommandCount++;
@@ -538,6 +609,8 @@ public sealed class DashboardLiveDataServiceTests
UnsubscribedHandles.AddRange(mxCommand.UnsubscribeBulk.ItemHandles);
reply.UnsubscribeBulk = new BulkSubscribeReply();
break;
case MxCommandKind.ReadBulk when FailReadBulk:
throw new InvalidOperationException("Simulated worker bulk-read failure.");
case MxCommandKind.ReadBulk:
reply.ReadBulk = Read(mxCommand.ReadBulk.TagAddresses);
break;