fix(sessions): renew the lease on last-subscriber detach; purge item registrations on Unregister (SES-004, SES-007, #253)

This commit is contained in:
Joseph Doherty
2026-12-03 09:39:19 -05:00
parent d12fd4f5a0
commit 3d4d5f2b04
3 changed files with 132 additions and 4 deletions
+2 -2
View File
@@ -230,7 +230,7 @@ The repair transitions the monitor's reconcile broadcasts on the alarm feed (Rai
The same one-distributor-per-session rule is enforced at the other end of the lifecycle. Session disposal disposes the distributor and latches the fact, so an attach that passed its readiness gate and then lost the CPU until the session was torn down throws `SessionNotReady` rather than constructing a replacement distributor. A replacement can never be pumped — the pump-start flag is a one-way latch — so its subscriber would block on an empty channel that is never completed until the client's own deadline expired, with no error, log or metric to explain it. Every attach entry point (`AttachEventSubscriber`, `AttachEventSubscriberWithReplay`, `AttachInternalEventSubscriber`) fails this way, and each rolls back the subscriber-count slot it took, so a caller that loses the race to teardown sees the same failure it would have seen a moment later from the readiness gate.
Sessions open with `MxGateway:Sessions:DefaultLeaseSeconds` (default 1800) added to the open timestamp. Unary client activity refreshes the lease by the same duration (`TouchClientActivity` is the only path that moves the lease). `IsLeaseExpired` cooperates with `SessionManager.CloseExpiredLeasesAsync`, which iterates a registry snapshot and closes any session whose lease has expired with `LeaseExpiredReason`. `SessionLeaseMonitorHostedService` runs that sweep every `MxGateway:Sessions:LeaseSweepIntervalSeconds` seconds (default 30).
Sessions open with `MxGateway:Sessions:DefaultLeaseSeconds` (default 1800) added to the open timestamp. Unary client activity refreshes the lease by the same duration (`TouchClientActivity`), and so does the detach of the last external event subscriber: streaming is client activity, and the lease does not age while a subscriber is attached (`IsLeaseExpired` is held false), but its deadline is only moved on unary calls. Without the renewal at detach, a client that streamed for longer than `DefaultLeaseSeconds` with no unary call would drop its stream with a lease already in the past, and the next sweep would close it as `lease-expired` (which takes precedence) before its detach-grace window. `IsLeaseExpired` cooperates with `SessionManager.CloseExpiredLeasesAsync`, which iterates a registry snapshot and closes any session whose lease has expired with `LeaseExpiredReason`. `SessionLeaseMonitorHostedService` runs that sweep every `MxGateway:Sessions:LeaseSweepIntervalSeconds` seconds (default 30).
#### Lazy dashboard mirror
@@ -258,7 +258,7 @@ The asymmetry with `CloseExpiredLeasesAsync` — whose `ParallelOptions` *is* to
`MxGateway:Sessions:DetachGraceSeconds` (default 30) is a bounded retention window kept after a session's *last external (gRPC) event-stream subscriber* drops, so a client can reconnect to the same session instead of having it torn down on the first stream disconnect. While the window is open the session stays `Ready` and fully usable — worker commands continue to work and a reconnecting subscriber re-attaches normally. Because retention is keyed on the *external* subscriber count (`_activeEventSubscriberCount`), and the gateway-owned internal dashboard mirror registers directly on the distributor with `isInternal: true` and is therefore *not* counted, a session whose only remaining subscriber is the dashboard mirror still enters detach-grace.
Mechanically: when the last external subscriber detaches and `DetachGraceSeconds > 0`, `DetachEventSubscriber` stamps `DetachedAtUtc` from the session's `TimeProvider` under `_syncRoot` (the detach→grace-start transition). `AttachEventSubscriber` clears `DetachedAtUtc` under the same lock when a subscriber re-attaches (the reattach→grace-cancel transition), so the two races and the sweeper's read all serialize on `_syncRoot`. `SessionManager.CloseExpiredLeasesAsync` checks `IsDetachGraceExpired(now)` alongside `IsLeaseExpired(now)`: a session detached for at least `DetachGraceSeconds` with no active external subscriber is closed by the same lease sweep, with the distinct `DetachGraceExpiredReason` (`"detach-grace-expired"`) so operators can tell a short reconnect-window expiry from a long idle-lease expiry. Setting `DetachGraceSeconds` to `0` disables retention and reverts to the original behavior: a detached session is retained only until its normal lease expires.
Mechanically: when the last external subscriber detaches and `DetachGraceSeconds > 0`, `DetachEventSubscriber` stamps `DetachedAtUtc` from the session's `TimeProvider` under `_syncRoot` (the detach→grace-start transition). `AttachEventSubscriber` clears `DetachedAtUtc` under the same lock when a subscriber re-attaches (the reattach→grace-cancel transition), so the two races and the sweeper's read all serialize on `_syncRoot`. `SessionManager.CloseExpiredLeasesAsync` checks `IsDetachGraceExpired(now)` alongside `IsLeaseExpired(now)`: a session detached for at least `DetachGraceSeconds` with no active external subscriber is closed by the same lease sweep, with the distinct `DetachGraceExpiredReason` (`"detach-grace-expired"`) so operators can tell a short reconnect-window expiry from a long idle-lease expiry. Setting `DetachGraceSeconds` to `0` disables retention and reverts to the original behavior: a detached session is retained only until its normal lease expires, counted from the detach.
`DetachGraceSeconds` controls retention and expiry only; the reconnect/replay path that re-attaches a dropped client to a retained session is described in [Reconnect and replay](#reconnect-and-replay).
@@ -1697,6 +1697,13 @@ public sealed class GatewaySession : IAsyncDisposable
case MxCommandKind.UnsubscribeBulk:
RemoveItems(command.UnsubscribeBulk.ServerHandle, command.UnsubscribeBulk.ItemHandles);
break;
case MxCommandKind.Unregister:
// Unregister invalidates every item under the server handle in MXAccess, so
// keeping their registrations would grow _items on each register/unregister
// cycle and leave stale tag addresses for the constraint checks to read if
// MXAccess hands the same handle values out again.
RemoveServerItems(command.Unregister.ServerHandle);
break;
}
}
}
@@ -2630,6 +2637,28 @@ public sealed class GatewaySession : IAsyncDisposable
}
}
private void RemoveServerItems(int serverHandle)
{
List<(int ServerHandle, int ItemHandle)>? stale = null;
foreach ((int ServerHandle, int ItemHandle) key in _items.Keys)
{
if (key.ServerHandle == serverHandle)
{
(stale ??= []).Add(key);
}
}
if (stale is null)
{
return;
}
foreach ((int ServerHandle, int ItemHandle) key in stale)
{
_items.Remove(key);
}
}
private void DetachEventSubscriber()
{
lock (_syncRoot)
@@ -2659,11 +2688,23 @@ public sealed class GatewaySession : IAsyncDisposable
// before any subscriber registered; that never-subscribed session must not enter the
// grace window.
if (_everHadEventSubscriber
&& _detachGrace > TimeSpan.Zero
&& _activeEventSubscriberCount == 0
&& _state is not (SessionState.Closing or SessionState.Closed or SessionState.Faulted))
{
_detachedAtUtc = _eventStreaming.TimeProvider.GetUtcNow();
DateTimeOffset now = _eventStreaming.TimeProvider.GetUtcNow();
// Streaming is client activity, and the detach is its last moment. The lease only
// moves on unary commands, so a client that streamed for longer than the lease with
// no unary call would otherwise detach with a lease already in the past — and the
// next sweep would close it as lease-expired (which takes precedence) before the
// detach-grace window it is entitled to. Renewing here keeps the reconnect window.
_lastClientActivityAt = now;
_leaseExpiresAt = now + LeaseDuration;
if (_detachGrace > TimeSpan.Zero)
{
_detachedAtUtc = now;
}
}
}
}
@@ -595,6 +595,93 @@ public sealed class GatewaySessionTests
second.Dispose();
}
/// <summary>
/// SES-004: a client that only streams (no unary call) for longer than the lease must still
/// get its full detach-grace window when the stream drops. The detach renews the lease, so
/// the session is neither lease-expired nor grace-expired until the grace elapses, and is
/// then closed for detach-grace rather than for the lease.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task DetachGrace_StreamOutlivesLease_DetachStillGetsFullGraceWindow()
{
FakeTimeProvider clock = new(DateTimeOffset.UtcNow);
FakeWorkerClient workerClient = new();
await using GatewaySession session = CreateReadySessionWithDetachGrace(
workerClient,
clock,
detachGrace: TimeSpan.FromSeconds(30));
IEventSubscriberLease lease = session.AttachEventSubscriber(maxSubscribers: 1);
// Stream for longer than the 30-minute lease with no unary command.
clock.Advance(TimeSpan.FromMinutes(31));
lease.Dispose();
clock.Advance(TimeSpan.FromSeconds(5));
Assert.False(session.IsLeaseExpired(clock.GetUtcNow()));
Assert.False(session.IsDetachGraceExpired(clock.GetUtcNow()));
Assert.False(session.TryBeginCloseIfExpired(clock.GetUtcNow(), out _));
Assert.Equal(SessionState.Ready, session.State);
clock.Advance(TimeSpan.FromSeconds(25));
Assert.False(session.IsLeaseExpired(clock.GetUtcNow()));
Assert.True(session.IsDetachGraceExpired(clock.GetUtcNow()));
}
/// <summary>
/// SES-007: a successful <c>Unregister</c> drops every item registration under that server
/// handle (MXAccess invalidates them all), and leaves other server handles alone.
/// </summary>
[Fact]
public void TrackCommandReply_SuccessfulUnregister_PurgesThatServerHandlesItems()
{
GatewaySession session = CreateSession();
TrackAddItem(session, serverHandle: 1, itemHandle: 10, "A.PV");
TrackAddItem(session, serverHandle: 1, itemHandle: 11, "B.PV");
TrackAddItem(session, serverHandle: 1, itemHandle: 12, "C.PV");
TrackAddItem(session, serverHandle: 2, itemHandle: 10, "D.PV");
session.TrackCommandReply(
new MxCommand { Kind = MxCommandKind.Unregister, Unregister = new UnregisterCommand { ServerHandle = 1 } },
new MxCommandReply { ProtocolStatus = MxAccessGrpcMapper.Ok() });
Assert.False(session.TryGetItemRegistration(1, 10, out _));
Assert.False(session.TryGetItemRegistration(1, 11, out _));
Assert.False(session.TryGetItemRegistration(1, 12, out _));
Assert.True(session.TryGetItemRegistration(2, 10, out SessionItemRegistration other));
Assert.Equal("D.PV", other.TagAddress);
}
/// <summary>A failed <c>Unregister</c> leaves the registrations in place.</summary>
[Fact]
public void TrackCommandReply_FailedUnregister_KeepsRegistrations()
{
GatewaySession session = CreateSession();
TrackAddItem(session, serverHandle: 1, itemHandle: 10, "A.PV");
session.TrackCommandReply(
new MxCommand { Kind = MxCommandKind.Unregister, Unregister = new UnregisterCommand { ServerHandle = 1 } },
new MxCommandReply { ProtocolStatus = new ProtocolStatus { Code = ProtocolStatusCode.MxaccessFailure } });
Assert.True(session.TryGetItemRegistration(1, 10, out _));
}
private static void TrackAddItem(GatewaySession session, int serverHandle, int itemHandle, string tagAddress)
{
session.TrackCommandReply(
new MxCommand
{
Kind = MxCommandKind.AddItem,
AddItem = new AddItemCommand { ServerHandle = serverHandle, ItemDefinition = tagAddress },
},
new MxCommandReply
{
ProtocolStatus = MxAccessGrpcMapper.Ok(),
AddItem = new AddItemReply { ItemHandle = itemHandle },
});
}
/// <summary>
/// With detach-grace disabled (<c>0</c>), dropping the last subscriber must
/// match today's behavior: the session stays <see cref="SessionState.Ready"/> with no