perf(worker): alarm poll loop skips the STA hop while nothing is subscribed (MXA-011, #256)

This commit is contained in:
Joseph Doherty
2026-12-03 09:52:23 -05:00
parent 0b93fe8263
commit ad30daf6e2
4 changed files with 66 additions and 5 deletions
@@ -585,6 +585,9 @@ public sealed class AlarmCommandExecutorTests
private sealed class FakeAlarmHandler : IAlarmCommandHandler
{
/// <inheritdoc />
public bool IsSubscribed => LastSubscription is not null && !UnsubscribeCalled;
/// <summary>Gets the last subscription expression.</summary>
public string? LastSubscription { get; private set; }
@@ -357,7 +357,7 @@ public sealed class MxAccessStaSessionTests
[Fact]
public async Task StartAsync_WithAlarmCommandHandlerFactory_PollOnceCalledViaSta()
{
FakeAlarmCommandHandler handler = new();
FakeAlarmCommandHandler handler = new() { IsSubscribed = true };
FakeMxAccessComObjectFactory factory = new();
FakeMxAccessEventSink eventSink = new();
using StaRuntime runtime = CreateRuntime();
@@ -383,6 +383,39 @@ public sealed class MxAccessStaSessionTests
Assert.Equal(runtime.StaThreadId, handler.LastPollThreadId);
}
/// <summary>
/// MXA-011: while nothing is subscribed the poll loop does not hop onto the STA at all, so an
/// idle worker takes no STA wake-ups at the poll rate; once subscribed, polling starts.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task RunAlarmPollLoop_WhileNotSubscribed_DoesNotPollThenPollsOnceSubscribed()
{
FakeAlarmCommandHandler handler = new();
using StaRuntime runtime = CreateRuntime();
using MxAccessStaSession session = new(
runtime,
new FakeMxAccessComObjectFactory(),
new FakeMxAccessEventSink(),
new MxAccessEventQueue(),
(_eq, _affinity, _comFactory) => handler);
session.AlarmPollInterval = TimeSpan.FromMilliseconds(10);
await session.StartAsync("session-1", workerProcessId: 1);
await Task.Delay(300);
Assert.Equal(0, handler.PollCount);
handler.IsSubscribed = true;
using CancellationTokenSource timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5));
while (handler.PollCount == 0 && !timeout.IsCancellationRequested)
{
await Task.Delay(20, CancellationToken.None);
}
Assert.True(handler.PollCount > 0, "Polling should start once the handler is subscribed.");
}
/// <summary>
/// Gap 2: Verifies that the STA poll loop stops when the session is disposed —
/// no further PollOnce calls after disposal. <see cref="MxAccessStaSession.Dispose"/>
@@ -395,7 +428,7 @@ public sealed class MxAccessStaSessionTests
[Fact]
public async Task Dispose_StopsAlarmPollLoop()
{
FakeAlarmCommandHandler handler = new();
FakeAlarmCommandHandler handler = new() { IsSubscribed = true };
FakeMxAccessComObjectFactory factory = new();
FakeMxAccessEventSink eventSink = new();
using StaRuntime runtime = CreateRuntime();
@@ -446,6 +479,7 @@ public sealed class MxAccessStaSessionTests
{
FakeAlarmCommandHandler handler = new()
{
IsSubscribed = true,
PollException = new System.Runtime.InteropServices.COMException(
"GetXmlCurrentAlarms2 failed.", unchecked((int)0x80004005)),
};
@@ -494,6 +528,7 @@ public sealed class MxAccessStaSessionTests
{
FakeAlarmCommandHandler handler = new()
{
IsSubscribed = true,
PollException = new InvalidOperationException(
"Alarm consumer accessed off its owning STA thread."),
};
@@ -538,7 +573,7 @@ public sealed class MxAccessStaSessionTests
[Fact]
public async Task CaptureHeartbeat_DuringAlarmPoll_ReportsStaCallInProgress()
{
FakeAlarmCommandHandler handler = new() { BlockPoll = true };
FakeAlarmCommandHandler handler = new() { BlockPoll = true, IsSubscribed = true };
FakeMxAccessComObjectFactory factory = new();
FakeMxAccessEventSink eventSink = new();
using StaRuntime runtime = CreateRuntime();
@@ -587,6 +622,7 @@ public sealed class MxAccessStaSessionTests
{
FakeAlarmCommandHandler handler = new()
{
IsSubscribed = true,
PollExceptionFactory = call => call % 3 == 0
? null
: new COMException("secret-tag-name GetXmlCurrentAlarms2 failed.", unchecked((int)0x80004005)),
@@ -634,6 +670,7 @@ public sealed class MxAccessStaSessionTests
{
FakeAlarmCommandHandler handler = new()
{
IsSubscribed = true,
PollException = new COMException("GetXmlCurrentAlarms2 failed.", unchecked((int)0x80004005)),
};
ConcurrentQueue<string> warnings = new();
@@ -718,7 +755,7 @@ public sealed class MxAccessStaSessionTests
public async Task RunAlarmPollLoop_AfterStaLoopFault_DoesNotRecordAlarmPollFault()
{
ControllableMessagePump pump = new();
FakeAlarmCommandHandler handler = new();
FakeAlarmCommandHandler handler = new() { IsSubscribed = true };
using StaRuntime runtime = new(new NoopComApartmentInitializer(), pump, TimeSpan.FromMilliseconds(25));
MxAccessEventQueue eventQueue = new();
using MxAccessStaSession session = new(
@@ -789,7 +826,13 @@ public sealed class MxAccessStaSessionTests
private int? lastPollThreadId;
/// <summary>Gets a value indicating whether the alarm client is currently subscribed.</summary>
public bool IsSubscribed { get; private set; }
public bool IsSubscribed
{
get => Volatile.Read(ref subscribed) != 0;
set => Volatile.Write(ref subscribed, value ? 1 : 0);
}
private int subscribed;
/// <summary>Gets the last alarm subscription name.</summary>
public string? LastSubscription { get; private set; }
@@ -14,6 +14,13 @@ namespace ZB.MOM.WW.MxGateway.Worker.MxAccess;
/// </summary>
public interface IAlarmCommandHandler : IDisposable
{
/// <summary>
/// Gets a value indicating whether an alarm subscription is active. Safe to read from any
/// thread. The STA alarm poll loop reads it to skip the STA hop entirely while nothing is
/// subscribed, so an idle session does not wake its STA every poll interval.
/// </summary>
bool IsSubscribed { get; }
/// <summary>
/// Begin an alarm subscription from the supplied command. The command's
/// <see cref="SubscribeAlarmsCommand.ForcedMode"/> and
@@ -424,6 +424,14 @@ public sealed class MxAccessStaSession : IWorkerRuntimeSession
return;
}
// No subscription means PollOnce would find no dispatcher and return. Skip the STA
// hop (a work item plus a message-loop wake) so a session that never subscribes, or
// has not yet, costs no STA time at the poll rate.
if (!handler.IsSubscribed)
{
continue;
}
try
{
await staRuntime.InvokeAsync(