Merge fix/258-worker-followup
This commit is contained in:
@@ -909,10 +909,11 @@ Galaxy's last deploy time (`GetLastDeployTimeAsync`), so an undeployed galaxy
|
||||
costs one deploy-time query per refresh rather than the alarm-attribute query
|
||||
and a rebuilt list; a failed discovery or an unknown deploy time is not cached.
|
||||
The gateway compares a SHA-256 of a canonical fingerprint of all six target
|
||||
fields and sends `UpdateAlarmWatchListCommand` only for a material change. The worker constructs,
|
||||
subscribes, and attaches the replacement standby on its STA before swapping it
|
||||
in; a setup failure leaves the previous standby and the current primary/subtag
|
||||
mode unchanged. The gateway advances its acknowledged fingerprint only after an
|
||||
fields and sends `UpdateAlarmWatchListCommand` only for a material change. The worker applies
|
||||
the new list to its existing subtag standby as a diff on its STA — advising only
|
||||
added alarms' subtags, unadvising only removed ones, and keeping the state of
|
||||
unchanged alarms; a failure leaves the previous list in force and the current
|
||||
primary/subtag mode unchanged. The gateway advances its acknowledged fingerprint only after an
|
||||
OK reply, so a rejected update remains degraded and is retried.
|
||||
|
||||
`SubscribeAlarmsCommand.fallback_enabled` distinguishes an initially empty but
|
||||
|
||||
+5
-3
@@ -45,9 +45,11 @@ The shared alarm command model includes `SubscribeAlarms` and
|
||||
initial watch list explicitly fallback-capable, allowing discovery recovery to
|
||||
populate a standby without restarting the primary alarm-manager subscription.
|
||||
`UpdateAlarmWatchListCommand.watch_list` is the complete replacement list. The
|
||||
worker prepares the replacement on its STA before swapping it into the existing
|
||||
failover consumer and returns a normal `MxCommandReply`; callers must treat only
|
||||
`protocol_status = OK` as acknowledgement of the new list.
|
||||
worker applies it to the existing failover consumer's standby as a diff on its
|
||||
STA (advising added alarms, unadvising removed ones, keeping unchanged alarms'
|
||||
state) and returns a normal `MxCommandReply`; a failed update leaves the previous
|
||||
list in force. Callers must treat only `protocol_status = OK` as acknowledgement
|
||||
of the new list.
|
||||
|
||||
`AcknowledgeAlarmRequest` carries the operator's identity: `operator_user`
|
||||
(required), `operator_password` (field 6) and `operator_domain` (field 7). The
|
||||
|
||||
@@ -534,7 +534,7 @@ behavior.
|
||||
| `MxGateway:Alarms:SubscriptionExpression` | _(empty)_ | AVEVA alarm-subscription expression the monitor subscribes on startup, in canonical `\\<machine>\Galaxy!<area>` form. The literal `Galaxy` provider is correct regardless of the Galaxy database name. When empty and `Enabled` is `true`, the gateway falls back to `\\<MachineName>\Galaxy!<DefaultArea>` if `DefaultArea` is set. |
|
||||
| `MxGateway:Alarms:DefaultArea` | _(empty)_ | Area name used to compose a default subscription when `SubscriptionExpression` is empty. If both are empty while `Enabled` is `true`, the monitor faults with a configuration diagnostic. |
|
||||
| `MxGateway:Alarms:ReconcileIntervalSeconds` | `30` | How often the monitor reconciles its in-process alarm cache against the worker's authoritative active-alarm snapshot, and, on a separate loop at the same cadence, re-resolves and on material change hot-swaps the subtag fallback watch-list (the resolution is cached per Galaxy deploy time, so an undeployed galaxy costs one deploy-time query per tick). The acknowledged watch-list fingerprint advances only after an OK worker reply. Must be between 1 and 86,400 when `Enabled` is true; the monitor floors it at 5 seconds. |
|
||||
| `MxGateway:Alarms:PollIntervalMilliseconds` | `500` | Cadence at which the worker's STA polls the AVEVA alarm consumer (`GetXmlCurrentAlarms2`) for the active-alarm snapshot the live feed diffs. Must be between `100` and `3600000` (one hour): every poll is a COM call plus an XML parse on the same STA that serves reads and writes, so a tighter cadence starves the command path, while a value above an hour stops being a cadence and silently disables alarm polling. The gateway conveys the value to the worker via the `MXGATEWAY_ALARM_POLL_INTERVAL_MS` environment variable; a missing or out-of-range value leaves the worker on the 500 ms default rather than failing the session. |
|
||||
| `MxGateway:Alarms:PollIntervalMilliseconds` | `500` | Cadence at which the worker's STA polls the AVEVA alarm consumer (`GetXmlCurrentAlarms2`) for the active-alarm snapshot the live feed diffs. The worker polls only while the session has an alarm subscription; an unsubscribed session's poll loop is parked and costs nothing at this cadence. Must be between `100` and `3600000` (one hour): every poll is a COM call plus an XML parse on the same STA that serves reads and writes, so a tighter cadence starves the command path, while a value above an hour stops being a cadence and silently disables alarm polling. The gateway conveys the value to the worker via the `MXGATEWAY_ALARM_POLL_INTERVAL_MS` environment variable; a missing or out-of-range value leaves the worker on the 500 ms default rather than failing the session. |
|
||||
| `MxGateway:Alarms:MaxAlarmsPerFetch` | `1024` | Cap the worker passes to `GetXmlCurrentAlarms2`'s `maxAlmCnt`. Must be between `64` and `65536` — the worker is a 32-bit process that materializes each reply as one BSTR (streamed into one record per alarm, not a DOM), so an unbounded cap faults the STA with an out-of-memory rather than merely slowing it. It doubles as the **truncation threshold**: a fetch returning exactly this many records is treated as truncated, because the COM API caps its reply with no "more available" flag. On a truncated poll the worker retains the alarms the capped reply could not mention instead of letting their absence read as a clear, and logs a rate-limited `AlarmSnapshotTruncated` warning to its stderr (identifiers and counts only). **Remediation when you see that warning: raise this value** so the steady-state active-alarm count fits inside one fetch. A galaxy permanently above the cap holds stale entries in the snapshot until a sub-cap poll, and loses clear→re-raise cycles that happen entirely out of window (see `docs/DesignDecisions.md`). Conveyed to the worker via the `MXGATEWAY_ALARM_MAX_ALARMS_PER_FETCH` environment variable; a missing or out-of-range value leaves the worker on the 1024 default. |
|
||||
| `MxGateway:Alarms:AckClientName` | `MxGateway` | MXAccess client name the alarm worker's ack writer registers with; the Historian records it as each acknowledgement's OperatorNode. 1-64 printable characters. Conveyed via `MXGATEWAY_ALARM_ACK_CLIENT_NAME`. |
|
||||
|
||||
|
||||
@@ -459,14 +459,30 @@ its entry.
|
||||
## Live alarm watch-list replacement
|
||||
|
||||
An auto-mode `SubscribeAlarms` with `fallback_enabled = true` always builds a
|
||||
`FailoverAlarmConsumer`, even when initial discovery supplied no targets. The
|
||||
handler retains the subscription expression so `UpdateAlarmWatchList` can build
|
||||
and subscribe a new subtag consumer entirely on the session STA. The failover
|
||||
consumer attaches the replacement's transition callback before swapping the
|
||||
standby reference, then detaches and disposes the old standby. If construction,
|
||||
subscription, or attachment fails, it disposes the replacement and preserves
|
||||
the old standby. The active-provider selector is never reset, so primary mode
|
||||
stays primary and subtag mode immediately delegates to the new standby.
|
||||
`FailoverAlarmConsumer`, even when initial discovery supplied no targets.
|
||||
`UpdateAlarmWatchList` runs entirely on the session STA and applies the new list
|
||||
to the existing `SubtagAlarmConsumer` as a diff (MXA-010): the subtags of added
|
||||
alarms are advised on the standby's existing `LmxSubtagAlarmSource`, the subtags
|
||||
of removed alarms are unadvised (`UnAdvise` + `RemoveItem`), and an alarm whose
|
||||
target is unchanged in every field keeps its advice and its tracked state, so no
|
||||
transition is re-emitted for it. Rebuilding the standby instead cost a second
|
||||
MXAccess registration and an `AddItem`/`Advise` for every watched subtag on each
|
||||
change, however small. An alarm whose target changed is treated as removed and
|
||||
re-added and starts from fresh state; when its subtags are already advised, the
|
||||
consumer initialises it from the last value delivered for each subtag (acked and
|
||||
priority before active, so an already-acknowledged alarm syncs as `ACK_ALM`)
|
||||
rather than re-advising.
|
||||
|
||||
The update is all-or-nothing. The new list is validated and the added subtags
|
||||
are advised before anything is swapped; if advising fails, the subtags the call
|
||||
added are unadvised again, the standby keeps serving the previous list, and the
|
||||
command fails. Unadvising removed subtags happens after the swap and is best
|
||||
effort, because an unbound subtag's callbacks are already ignored. A standby that
|
||||
is not a `SubtagAlarmConsumer` (a test seam) is still rebuilt: the handler
|
||||
retains the subscription expression, builds and subscribes a replacement, and the
|
||||
failover consumer attaches its transition callback before swapping it in and
|
||||
disposing the old one. Either way the active-provider selector is never reset, so
|
||||
primary mode stays primary and subtag mode keeps delegating to the standby.
|
||||
|
||||
## COM Creation
|
||||
|
||||
@@ -1067,6 +1083,19 @@ the STA more than 75 s without pumping *should* fault — that is the ceiling's
|
||||
contract). The flag is named generically so any future non-dispatcher STA work
|
||||
reuses it.
|
||||
|
||||
The poll loop runs only while the handler has an alarm subscription (MXA-011).
|
||||
It starts with the session but parks on a semaphore while
|
||||
`IAlarmCommandHandler.IsSubscribed` is false, so a session that never subscribes
|
||||
to alarms — or has unsubscribed — takes no timer, thread-pool or STA wake-ups at
|
||||
the poll rate. A successful `Subscribe` raises `SubscriptionActivated`, which
|
||||
releases the semaphore; the loop then resumes ticking at `AlarmPollInterval`.
|
||||
While subscribed it never parks, so the failover consumer still sees every
|
||||
`PollOnce` it counts primary failures and failback probes on (MXA-001). Shutdown
|
||||
cancels a parked loop the same way as a sleeping one, so the graceful-shutdown
|
||||
join and its grace bound (MXA-003) are unchanged. The consecutive-failure count
|
||||
below resets when the loop parks, so a new subscription does not inherit an
|
||||
earlier one's failure run.
|
||||
|
||||
A `PollOnce` that throws does not fault the session on the first failure. The
|
||||
poll loop counts consecutive failures and records the alarm-poll fault
|
||||
(`MxaccessEventConversionFailed`) only when the count reaches
|
||||
|
||||
@@ -588,6 +588,9 @@ public sealed class AlarmCommandExecutorTests
|
||||
/// <inheritdoc />
|
||||
public bool IsSubscribed => LastSubscription is not null && !UnsubscribeCalled;
|
||||
|
||||
/// <inheritdoc />
|
||||
public event EventHandler? SubscriptionActivated;
|
||||
|
||||
/// <summary>Gets the last subscription expression.</summary>
|
||||
public string? LastSubscription { get; private set; }
|
||||
|
||||
@@ -627,6 +630,7 @@ public sealed class AlarmCommandExecutorTests
|
||||
{
|
||||
LastSubscription = command.SubscriptionExpression;
|
||||
LastSessionId = sessionId;
|
||||
SubscriptionActivated?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
|
||||
/// <summary>Gets the most recent replacement watch list.</summary>
|
||||
|
||||
@@ -644,6 +644,52 @@ public sealed class AlarmCommandHandlerTests
|
||||
Assert.Equal("33.AckMsg", AckItemOf(handler));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// MXA-010: adding one alarm to a fallback watch list advises only that alarm's subtags on
|
||||
/// the existing subtag source. Rebuilding the standby instead created a second source (a
|
||||
/// second MXAccess server registration), re-advised every watched subtag on it, and
|
||||
/// unregistered the first — work proportional to the whole watch list for a one-item change.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void UpdateWatchList_OneTargetAdded_AdvisesOnlyTheAddedSubtagsOnTheExistingSource()
|
||||
{
|
||||
List<CountingSubtagSource> sources = new List<CountingSubtagSource>();
|
||||
AlarmCommandHandler handler = new AlarmCommandHandler(
|
||||
new MxAccessEventQueue(),
|
||||
() => new FakeConsumer(),
|
||||
threadAffinityCheck: null,
|
||||
comFactory: null,
|
||||
standbyFactory: watchList =>
|
||||
{
|
||||
CountingSubtagSource source = new CountingSubtagSource();
|
||||
sources.Add(source);
|
||||
return new SubtagAlarmConsumer(source, watchList);
|
||||
},
|
||||
ackWriterFactory: () => new RecordingAckWriter());
|
||||
SubscribeAlarmsCommand subscribe = new SubscribeAlarmsCommand
|
||||
{
|
||||
SubscriptionExpression = @"\\HOST\Galaxy!Area",
|
||||
FallbackEnabled = true,
|
||||
};
|
||||
List<AlarmSubtagTarget> watchList = new List<AlarmSubtagTarget>();
|
||||
for (int i = 0; i < 50; i++)
|
||||
{
|
||||
watchList.Add(NewTarget($"Galaxy!Area.Tank{i:D2}.Alarm"));
|
||||
}
|
||||
|
||||
subscribe.WatchList.AddRange(watchList);
|
||||
handler.Subscribe(subscribe, "s1");
|
||||
Assert.Single(sources);
|
||||
Assert.Equal(100, sources[0].AdvisedCount);
|
||||
|
||||
watchList.Add(NewTarget("Galaxy!Area.Tank50.Alarm"));
|
||||
handler.UpdateWatchList(watchList);
|
||||
|
||||
Assert.Single(sources);
|
||||
Assert.False(sources[0].Disposed);
|
||||
Assert.Equal(102, sources[0].AdvisedCount);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A non-failover subscribe (alarmmgr-only) never enqueues a
|
||||
/// provider-mode-changed event, and a subsequent Unsubscribe detaches
|
||||
@@ -793,6 +839,48 @@ public sealed class AlarmCommandHandlerTests
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Subtag source that counts the addresses it is asked to advise.</summary>
|
||||
private sealed class CountingSubtagSource : ISubtagAlarmSource
|
||||
{
|
||||
#pragma warning disable CS0067 // Event never invoked — these tests count advise work, not transitions.
|
||||
/// <inheritdoc />
|
||||
public event EventHandler<SubtagValueChange>? ValueChanged;
|
||||
#pragma warning restore CS0067
|
||||
|
||||
/// <summary>Gets the addresses currently advised.</summary>
|
||||
public HashSet<string> Advised { get; } = new HashSet<string>(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>Gets the total number of advise operations performed (AddItem + Advise pairs).</summary>
|
||||
public int AdvisedCount { get; private set; }
|
||||
|
||||
/// <summary>Gets a value indicating whether the source was disposed.</summary>
|
||||
public bool Disposed { get; private set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Advise(IReadOnlyCollection<string> itemAddresses)
|
||||
{
|
||||
foreach (string address in itemAddresses)
|
||||
{
|
||||
if (Advised.Add(address))
|
||||
{
|
||||
AdvisedCount++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Unadvise(IReadOnlyCollection<string> itemAddresses)
|
||||
{
|
||||
foreach (string address in itemAddresses)
|
||||
{
|
||||
Advised.Remove(address);
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Dispose() => Disposed = true;
|
||||
}
|
||||
|
||||
private sealed class RecordingAckWriter : IAlarmAckWriter
|
||||
{
|
||||
public string? LastItemAddress { get; private set; }
|
||||
|
||||
@@ -239,6 +239,66 @@ public sealed class FailoverAlarmConsumerTests
|
||||
Assert.Equal(AlarmProviderMode.Subtag, sut.Mode);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// MXA-010: while failed over, an in-place watch-list update on the subtag standby keeps
|
||||
/// subtag mode, and the added alarm's transitions are forwarded from the same standby. A
|
||||
/// standby that is not a subtag consumer reports that it needs a rebuild instead.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void TryUpdateStandbyWatchList_WhileFailedOver_UpdatesSubtagStandbyInPlaceAndKeepsMode()
|
||||
{
|
||||
FlakyPrimary primary = new FlakyPrimary();
|
||||
RaisingSubtagSource source = new RaisingSubtagSource();
|
||||
SubtagAlarmConsumer standby = new SubtagAlarmConsumer(source, new[] { SubtagTarget("Tank01") });
|
||||
FailoverSettings settings = new FailoverSettings(threshold: 1, probeIntervalSeconds: 0, stableProbes: 3);
|
||||
using FailoverAlarmConsumer sut = new FailoverAlarmConsumer(primary, standby, settings);
|
||||
FailOverAfterHealthySubscribe(sut, primary);
|
||||
List<MxAlarmTransitionEvent> forwarded = new List<MxAlarmTransitionEvent>();
|
||||
sut.AlarmTransitionEmitted += (_, e) => forwarded.Add(e);
|
||||
|
||||
Assert.True(sut.TryUpdateStandbyWatchList(new[] { SubtagTarget("Tank01"), SubtagTarget("Tank02") }));
|
||||
|
||||
Assert.Equal(AlarmProviderMode.Subtag, sut.Mode);
|
||||
source.Raise("Tank02.Alarm.InAlarm", true);
|
||||
Assert.Equal(MxAlarmStateKind.UnackAlm, Assert.Single(forwarded).Record.State);
|
||||
|
||||
using FailoverAlarmConsumer stubbed = new FailoverAlarmConsumer(new FlakyPrimary(), new StubStandby(), settings);
|
||||
Assert.False(stubbed.TryUpdateStandbyWatchList(new[] { SubtagTarget("Tank01") }));
|
||||
}
|
||||
|
||||
private static AlarmSubtagTarget SubtagTarget(string tank) => new AlarmSubtagTarget
|
||||
{
|
||||
AlarmFullReference = $"Galaxy!Area.{tank}.Alarm",
|
||||
SourceObjectReference = tank,
|
||||
ActiveSubtag = $"{tank}.Alarm.InAlarm",
|
||||
AckedSubtag = $"{tank}.Alarm.Acked",
|
||||
AckCommentSubtag = $"{tank}.Alarm.AckMsg",
|
||||
};
|
||||
|
||||
private sealed class RaisingSubtagSource : ISubtagAlarmSource
|
||||
{
|
||||
public event EventHandler<SubtagValueChange>? ValueChanged;
|
||||
|
||||
public void Advise(IReadOnlyCollection<string> itemAddresses)
|
||||
{
|
||||
}
|
||||
|
||||
public void Unadvise(IReadOnlyCollection<string> itemAddresses)
|
||||
{
|
||||
}
|
||||
|
||||
public void Raise(string address, object value) => ValueChanged?.Invoke(this, new SubtagValueChange
|
||||
{
|
||||
ItemAddress = address,
|
||||
Value = value,
|
||||
TimestampUtc = DateTime.UtcNow,
|
||||
});
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// MXA-001: a primary whose Subscribe failed, and whose PollOnce is then a
|
||||
/// silent no-op (the wnwrap shape), must still count as failing, so the
|
||||
|
||||
@@ -136,6 +136,61 @@ public sealed class LmxSubtagAlarmSourceTests
|
||||
Assert.Empty(server.Writes);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// MXA-010: <see cref="LmxSubtagAlarmSource.Unadvise"/> tears down only the named items
|
||||
/// (UnAdvise then RemoveItem), skips addresses it never advised, stops raising for the
|
||||
/// removed handle, and leaves the server registered for the items that remain.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Unadvise_RemovesOnlyNamedItemsAndStopsTheirCallbacks()
|
||||
{
|
||||
var server = new RecordingMxAccessServer();
|
||||
using var source = new LmxSubtagAlarmSource(server, FakeServerHandle);
|
||||
source.Advise(new[] { "Tank1.Alarm.Subtag", "Tank2.Alarm.Subtag" });
|
||||
int removedHandle = server.LastItemHandleFor("Tank1.Alarm.Subtag");
|
||||
int keptHandle = server.LastItemHandleFor("Tank2.Alarm.Subtag");
|
||||
List<string> raised = new List<string>();
|
||||
source.ValueChanged += (_, change) => raised.Add(change.ItemAddress);
|
||||
|
||||
source.Unadvise(new[] { "Tank1.Alarm.Subtag", "Never.Advised" });
|
||||
|
||||
Assert.Equal(new[] { removedHandle }, server.UnAdvisedItemHandles);
|
||||
Assert.Equal(new[] { removedHandle }, server.RemovedItemHandles);
|
||||
Assert.Equal(0, server.UnregisterCount);
|
||||
|
||||
source.HandleDataChange(removedHandle, pvItemValue: true, pftItemTimeStamp: null);
|
||||
source.HandleDataChange(keptHandle, pvItemValue: true, pftItemTimeStamp: null);
|
||||
Assert.Equal(new[] { "Tank2.Alarm.Subtag" }, raised);
|
||||
|
||||
// A removed address can be advised again, on a new item.
|
||||
source.Advise(new[] { "Tank1.Alarm.Subtag" });
|
||||
Assert.Equal(3, server.AdviseCount);
|
||||
Assert.NotEqual(removedHandle, server.LastItemHandleFor("Tank1.Alarm.Subtag"));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An item whose Advise failed after AddItem stays known to the source: a retried Advise
|
||||
/// finishes advising it instead of skipping it, and Unadvise removes it rather than leaving
|
||||
/// it orphaned on the server.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Advise_FailureAfterAddItem_IsRetriedAndRemovable()
|
||||
{
|
||||
var server = new RecordingMxAccessServer { FailAdviseCalls = 1 };
|
||||
using var source = new LmxSubtagAlarmSource(server, FakeServerHandle);
|
||||
|
||||
Assert.Throws<System.Runtime.InteropServices.COMException>(
|
||||
() => source.Advise(new[] { "Tank1.Alarm.Subtag" }));
|
||||
int handle = server.LastItemHandleFor("Tank1.Alarm.Subtag");
|
||||
|
||||
source.Advise(new[] { "Tank1.Alarm.Subtag" });
|
||||
Assert.Single(server.AddedItems);
|
||||
Assert.Equal(1, server.AdviseCount);
|
||||
|
||||
source.Unadvise(new[] { "Tank1.Alarm.Subtag" });
|
||||
Assert.Equal(new[] { handle }, server.RemovedItemHandles);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies <see cref="LmxSubtagAlarmSource.Dispose"/> is idempotent: a
|
||||
/// second call performs no further teardown.
|
||||
@@ -217,9 +272,18 @@ public sealed class LmxSubtagAlarmSourceTests
|
||||
/// <inheritdoc />
|
||||
public void RemoveItem(int serverHandle, int itemHandle) => RemovedItemHandles.Add(itemHandle);
|
||||
|
||||
/// <summary>Gets or sets how many upcoming <see cref="Advise"/> calls throw a COM failure.</summary>
|
||||
public int FailAdviseCalls { get; set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Advise(int serverHandle, int itemHandle)
|
||||
{
|
||||
if (FailAdviseCalls > 0)
|
||||
{
|
||||
FailAdviseCalls--;
|
||||
throw new System.Runtime.InteropServices.COMException("simulated Advise failure", unchecked((int)0x80004005));
|
||||
}
|
||||
|
||||
AdviseCount++;
|
||||
AdvisedServerHandles.Add(serverHandle);
|
||||
}
|
||||
|
||||
@@ -416,6 +416,61 @@ public sealed class MxAccessStaSessionTests
|
||||
Assert.True(handler.PollCount > 0, "Polling should start once the handler is subscribed.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// MXA-011: an unsubscribed poll loop parks instead of waking on its timer, polls once a
|
||||
/// subscription activates, parks again after unsubscribe, and resumes on the next subscribe.
|
||||
/// Each loop wake-up reads <see cref="FakeAlarmCommandHandler.IsSubscribed"/>, so a parked loop
|
||||
/// leaves the read count flat while a timer-driven one would add one read per interval.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task RunAlarmPollLoop_WhileUnsubscribed_ParksWithoutTimerWakeUps()
|
||||
{
|
||||
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);
|
||||
|
||||
// Never subscribed: one check, then parked. A 10 ms timer would read ~30 times here.
|
||||
await Task.Delay(300);
|
||||
Assert.InRange(handler.IsSubscribedReadCount, 1, 2);
|
||||
Assert.Equal(0, handler.PollCount);
|
||||
|
||||
handler.IsSubscribed = true;
|
||||
await WaitForAsync(() => handler.PollCount >= 3);
|
||||
|
||||
// Unsubscribe: the loop notices on its next wake-up and parks again.
|
||||
handler.IsSubscribed = false;
|
||||
await Task.Delay(100);
|
||||
int readsWhenParked = handler.IsSubscribedReadCount;
|
||||
int pollsWhenParked = handler.PollCount;
|
||||
await Task.Delay(300);
|
||||
Assert.InRange(handler.IsSubscribedReadCount - readsWhenParked, 0, 1);
|
||||
Assert.Equal(pollsWhenParked, handler.PollCount);
|
||||
|
||||
// A later subscribe wakes it again.
|
||||
handler.IsSubscribed = true;
|
||||
await WaitForAsync(() => handler.PollCount > pollsWhenParked);
|
||||
}
|
||||
|
||||
private static async Task WaitForAsync(Func<bool> condition)
|
||||
{
|
||||
using CancellationTokenSource timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5));
|
||||
while (!condition() && !timeout.IsCancellationRequested)
|
||||
{
|
||||
await Task.Delay(10, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
Assert.True(condition(), "Condition not met within 5 seconds.");
|
||||
}
|
||||
|
||||
/// <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"/>
|
||||
@@ -868,14 +923,36 @@ public sealed class MxAccessStaSessionTests
|
||||
private int pollCount;
|
||||
private int? lastPollThreadId;
|
||||
|
||||
/// <summary>Gets a value indicating whether the alarm client is currently subscribed.</summary>
|
||||
/// <inheritdoc />
|
||||
public event EventHandler? SubscriptionActivated;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether the alarm client is currently subscribed. Setting it
|
||||
/// to true raises <see cref="SubscriptionActivated"/>, as a successful Subscribe does.
|
||||
/// </summary>
|
||||
public bool IsSubscribed
|
||||
{
|
||||
get => Volatile.Read(ref subscribed) != 0;
|
||||
set => Volatile.Write(ref subscribed, value ? 1 : 0);
|
||||
get
|
||||
{
|
||||
Interlocked.Increment(ref isSubscribedReads);
|
||||
return Volatile.Read(ref subscribed) != 0;
|
||||
}
|
||||
|
||||
set
|
||||
{
|
||||
Volatile.Write(ref subscribed, value ? 1 : 0);
|
||||
if (value)
|
||||
{
|
||||
SubscriptionActivated?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private int subscribed;
|
||||
private int isSubscribedReads;
|
||||
|
||||
/// <summary>Gets how many times <see cref="IsSubscribed"/> was read — once per poll-loop wake-up.</summary>
|
||||
public int IsSubscribedReadCount => Volatile.Read(ref isSubscribedReads);
|
||||
|
||||
/// <summary>Gets the last alarm subscription name.</summary>
|
||||
public string? LastSubscription { get; private set; }
|
||||
|
||||
@@ -243,6 +243,150 @@ public sealed class SubtagAlarmConsumerTests
|
||||
Assert.Equal(AlarmAckOutcome.AlarmNotFound, consumer.ResolveAckTarget(Guid.NewGuid()).Failure);
|
||||
}
|
||||
|
||||
private static AlarmSubtagTarget Target(string tank, string ackSuffix = "AckMsg") => new AlarmSubtagTarget
|
||||
{
|
||||
AlarmFullReference = $"Galaxy!TestArea.{tank}.Level.HiHi",
|
||||
SourceObjectReference = tank,
|
||||
ActiveSubtag = $"{tank}.Level.HiHi.InAlarm",
|
||||
AckedSubtag = $"{tank}.Level.HiHi.Acked",
|
||||
AckCommentSubtag = $"{tank}.Level.HiHi.{ackSuffix}",
|
||||
};
|
||||
|
||||
private static readonly DateTime T0 = new DateTime(2026, 12, 3, 10, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
/// <summary>
|
||||
/// MXA-010: a watch-list update advises only the added alarm's subtags and unadvises only
|
||||
/// the removed alarm's; the alarm present in both lists is not touched.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void UpdateWatchList_AdvisesAddedAndUnadvisesRemovedOnly()
|
||||
{
|
||||
FakeSource source = new FakeSource();
|
||||
using SubtagAlarmConsumer consumer = new SubtagAlarmConsumer(source, new[] { Target("Tank01"), Target("Tank02") });
|
||||
consumer.Subscribe(@"\\HOST\Galaxy!TestArea");
|
||||
source.Advised.Clear();
|
||||
|
||||
consumer.UpdateWatchList(new[] { Target("Tank02"), Target("Tank03") });
|
||||
|
||||
Assert.Equal(new[] { "Tank03.Level.HiHi.InAlarm", "Tank03.Level.HiHi.Acked" }, source.Advised);
|
||||
Assert.Equal(new[] { "Tank01.Level.HiHi.InAlarm", "Tank01.Level.HiHi.Acked" }, source.Unadvised);
|
||||
Assert.False(consumer.ResolveAckTargetByName("Tank01.Level.HiHi", "Galaxy", "TestArea").Found);
|
||||
Assert.True(consumer.ResolveAckTargetByName("Tank03.Level.HiHi", "Galaxy", "TestArea").Found);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An alarm whose target is unchanged keeps its state across the update: no transition is
|
||||
/// re-emitted for it, it stays in the snapshot, and its acknowledged-during-episode latch
|
||||
/// still yields ACK_RTN on clear.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void UpdateWatchList_UnchangedAlarm_KeepsStateWithoutReemitting()
|
||||
{
|
||||
FakeSource source = new FakeSource();
|
||||
using SubtagAlarmConsumer consumer = new SubtagAlarmConsumer(source, new[] { Target("Tank01") });
|
||||
consumer.Subscribe(@"\\HOST\Galaxy!TestArea");
|
||||
source.Raise("Tank01.Level.HiHi.InAlarm", true, T0);
|
||||
source.Raise("Tank01.Level.HiHi.Acked", true, T0);
|
||||
List<MxAlarmTransitionEvent> emitted = new List<MxAlarmTransitionEvent>();
|
||||
consumer.AlarmTransitionEmitted += (_, e) => emitted.Add(e);
|
||||
|
||||
consumer.UpdateWatchList(new[] { Target("Tank01"), Target("Tank02") });
|
||||
|
||||
Assert.Empty(emitted);
|
||||
MxAlarmSnapshotRecord active = Assert.Single(consumer.SnapshotActiveAlarms(out _));
|
||||
Assert.Equal(MxAlarmStateKind.AckAlm, active.State);
|
||||
|
||||
source.Raise("Tank01.Level.HiHi.Acked", false, T0.AddSeconds(1));
|
||||
source.Raise("Tank01.Level.HiHi.InAlarm", false, T0.AddSeconds(2));
|
||||
Assert.Equal(MxAlarmStateKind.AckRtn, Assert.Single(emitted).Record.State);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An alarm whose target changed starts from fresh state, initialised from the last value
|
||||
/// already delivered for its still-advised subtags (the initial sync an Advise would give),
|
||||
/// without re-advising them; the new ack-comment subtag is what acks resolve to.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void UpdateWatchList_ChangedTarget_ReinitialisesFromLastDeliveredValues()
|
||||
{
|
||||
FakeSource source = new FakeSource();
|
||||
using SubtagAlarmConsumer consumer = new SubtagAlarmConsumer(source, new[] { Target("Tank01") });
|
||||
consumer.Subscribe(@"\\HOST\Galaxy!TestArea");
|
||||
source.Raise("Tank01.Level.HiHi.Acked", true, T0);
|
||||
source.Raise("Tank01.Level.HiHi.InAlarm", true, T0);
|
||||
source.Advised.Clear();
|
||||
List<MxAlarmTransitionEvent> emitted = new List<MxAlarmTransitionEvent>();
|
||||
consumer.AlarmTransitionEmitted += (_, e) => emitted.Add(e);
|
||||
|
||||
consumer.UpdateWatchList(new[] { Target("Tank01", ackSuffix: "AckComment") });
|
||||
|
||||
Assert.Empty(source.Advised);
|
||||
Assert.Empty(source.Unadvised);
|
||||
// MXA-007: the buffered ack replayed before .active keeps the alarm acknowledged.
|
||||
Assert.Equal(MxAlarmStateKind.AckAlm, Assert.Single(emitted).Record.State);
|
||||
Assert.Equal(
|
||||
"Tank01.Level.HiHi.AckComment",
|
||||
consumer.ResolveAckTargetByName("Tank01.Level.HiHi", "Galaxy", "TestArea").ItemAddress);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// MXA-005 holds across the replay: a fresh alarm whose last delivered .active update had
|
||||
/// bad quality is not initialised from it.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void UpdateWatchList_ChangedTarget_DoesNotReplayBadQualityValue()
|
||||
{
|
||||
FakeSource source = new FakeSource();
|
||||
using SubtagAlarmConsumer consumer = new SubtagAlarmConsumer(source, new[] { Target("Tank01") });
|
||||
consumer.Subscribe(@"\\HOST\Galaxy!TestArea");
|
||||
source.Raise("Tank01.Level.HiHi.InAlarm", true, T0, quality: 0x04);
|
||||
|
||||
consumer.UpdateWatchList(new[] { Target("Tank01", ackSuffix: "AckComment") });
|
||||
|
||||
Assert.Empty(consumer.SnapshotActiveAlarms(out _));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A failed advise rolls the update back: the subtags it added are unadvised again and the
|
||||
/// consumer keeps serving the previous list, state included.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void UpdateWatchList_AdviseFails_RollsBackToPreviousList()
|
||||
{
|
||||
FakeSource source = new FakeSource();
|
||||
using SubtagAlarmConsumer consumer = new SubtagAlarmConsumer(source, new[] { Target("Tank01") });
|
||||
consumer.Subscribe(@"\\HOST\Galaxy!TestArea");
|
||||
source.Raise("Tank01.Level.HiHi.InAlarm", true, T0);
|
||||
source.FailAdviseOf = "Tank03.Level.HiHi.InAlarm";
|
||||
|
||||
Assert.Throws<System.Runtime.InteropServices.COMException>(
|
||||
() => consumer.UpdateWatchList(new[] { Target("Tank02"), Target("Tank03") }));
|
||||
|
||||
Assert.Equal(
|
||||
new[] { "Tank02.Level.HiHi.InAlarm", "Tank02.Level.HiHi.Acked", "Tank03.Level.HiHi.InAlarm", "Tank03.Level.HiHi.Acked" },
|
||||
source.Unadvised);
|
||||
Assert.True(consumer.ResolveAckTargetByName("Tank01.Level.HiHi", "Galaxy", "TestArea").Found);
|
||||
Assert.False(consumer.ResolveAckTargetByName("Tank02.Level.HiHi", "Galaxy", "TestArea").Found);
|
||||
Assert.Single(consumer.SnapshotActiveAlarms(out _));
|
||||
}
|
||||
|
||||
/// <summary>A list that repeats an alarm reference is rejected before the source is touched.</summary>
|
||||
[Fact]
|
||||
public void UpdateWatchList_DuplicateReference_ThrowsWithoutTouchingSource()
|
||||
{
|
||||
FakeSource source = new FakeSource();
|
||||
using SubtagAlarmConsumer consumer = new SubtagAlarmConsumer(source, new[] { Target("Tank01") });
|
||||
consumer.Subscribe(@"\\HOST\Galaxy!TestArea");
|
||||
source.Advised.Clear();
|
||||
|
||||
Assert.Throws<ArgumentException>(
|
||||
() => consumer.UpdateWatchList(new[] { Target("Tank02"), Target("Tank02") }));
|
||||
|
||||
Assert.Empty(source.Advised);
|
||||
Assert.Empty(source.Unadvised);
|
||||
Assert.True(consumer.ResolveAckTargetByName("Tank01.Level.HiHi", "Galaxy", "TestArea").Found);
|
||||
}
|
||||
|
||||
private sealed class FakeSource : ISubtagAlarmSource
|
||||
{
|
||||
/// <summary>Raised when an advised subtag reports a new value.</summary>
|
||||
@@ -251,23 +395,45 @@ public sealed class SubtagAlarmConsumerTests
|
||||
/// <summary>Gets the subtag addresses passed to <see cref="Advise"/>.</summary>
|
||||
public List<string> Advised { get; } = new List<string>();
|
||||
|
||||
/// <summary>Gets the subtag addresses passed to <see cref="Unadvise"/>.</summary>
|
||||
public List<string> Unadvised { get; } = new List<string>();
|
||||
|
||||
/// <summary>Gets or sets an address whose advise throws (after the addresses before it were advised).</summary>
|
||||
public string? FailAdviseOf { get; set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Advise(IReadOnlyCollection<string> itemAddresses)
|
||||
{
|
||||
Advised.AddRange(itemAddresses);
|
||||
foreach (string address in itemAddresses)
|
||||
{
|
||||
if (address == FailAdviseOf)
|
||||
{
|
||||
throw new System.Runtime.InteropServices.COMException("simulated AddItem failure", unchecked((int)0x80004005));
|
||||
}
|
||||
|
||||
Advised.Add(address);
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Unadvise(IReadOnlyCollection<string> itemAddresses)
|
||||
{
|
||||
Unadvised.AddRange(itemAddresses);
|
||||
}
|
||||
|
||||
/// <summary>Raises a <see cref="SubtagValueChange"/> for the given subtag.</summary>
|
||||
/// <param name="address">The subtag address whose value changed.</param>
|
||||
/// <param name="value">The new value.</param>
|
||||
/// <param name="timestampUtc">The UTC timestamp of the change.</param>
|
||||
public void Raise(string address, object? value, DateTime timestampUtc)
|
||||
/// <param name="quality">The item quality, or null when not reported.</param>
|
||||
public void Raise(string address, object? value, DateTime timestampUtc, int? quality = null)
|
||||
{
|
||||
ValueChanged?.Invoke(this, new SubtagValueChange
|
||||
{
|
||||
ItemAddress = address,
|
||||
Value = value,
|
||||
TimestampUtc = timestampUtc,
|
||||
Quality = quality,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -164,6 +164,9 @@ public sealed class AlarmCommandHandler : IAlarmCommandHandler
|
||||
get { lock (syncRoot) return dispatcher is not null; }
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public event EventHandler? SubscriptionActivated;
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Subscribe(SubscribeAlarmsCommand command, string sessionId)
|
||||
{
|
||||
@@ -210,6 +213,11 @@ public sealed class AlarmCommandHandler : IAlarmCommandHandler
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
// Outside the lock: the subscription is in force, so wake the parked poll loop. A
|
||||
// listener failure must not turn a successful subscribe into a failed command.
|
||||
try { SubscriptionActivated?.Invoke(this, EventArgs.Empty); }
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException) { /* swallow */ }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -296,6 +304,14 @@ public sealed class AlarmCommandHandler : IAlarmCommandHandler
|
||||
"UpdateAlarmWatchList requires an active fallback-capable alarm subscription.");
|
||||
}
|
||||
|
||||
// The subtag standby takes the new list as a diff: only added and removed alarms cost
|
||||
// COM calls, and unchanged alarms keep their state (MXA-010). Any other standby is
|
||||
// rebuilt and swapped.
|
||||
if (failoverConsumer.TryUpdateStandbyWatchList(watchList))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
IMxAccessAlarmConsumer replacement = BuildStandby(watchList);
|
||||
failoverConsumer.ReplaceStandby(replacement, subscriptionExpression);
|
||||
}
|
||||
|
||||
@@ -169,6 +169,32 @@ public sealed class FailoverAlarmConsumer : IMxAccessAlarmConsumer
|
||||
try { previous.Dispose(); } catch { /* replacement is already active */ }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Applies a replacement watch list to the current standby in place when the standby is a
|
||||
/// <see cref="SubtagAlarmConsumer"/>, which advises only the added subtags and unadvises
|
||||
/// only the removed ones instead of being rebuilt (MXA-010). A failure leaves the standby
|
||||
/// serving its previous list. The active-provider selector is untouched either way.
|
||||
/// </summary>
|
||||
/// <param name="watchList">The complete replacement watch list.</param>
|
||||
/// <returns>
|
||||
/// <see langword="true"/> when the standby was updated in place; <see langword="false"/>
|
||||
/// when it cannot be, and the caller must build a replacement for
|
||||
/// <see cref="ReplaceStandby"/>.
|
||||
/// </returns>
|
||||
public bool TryUpdateStandbyWatchList(IReadOnlyList<AlarmSubtagTarget> watchList)
|
||||
{
|
||||
if (disposed) throw new ObjectDisposedException(nameof(FailoverAlarmConsumer));
|
||||
if (watchList is null) throw new ArgumentNullException(nameof(watchList));
|
||||
|
||||
if (standby is not SubtagAlarmConsumer subtagStandby)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
subtagStandby.UpdateWatchList(watchList);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Subscribe(string subscription)
|
||||
{
|
||||
|
||||
@@ -21,6 +21,14 @@ public interface IAlarmCommandHandler : IDisposable
|
||||
/// </summary>
|
||||
bool IsSubscribed { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Raised after a <see cref="Subscribe"/> call succeeds, on the thread that made it (the
|
||||
/// STA). The STA alarm poll loop parks while <see cref="IsSubscribed"/> is false and waits on
|
||||
/// this signal instead of a timer, so a session that is not subscribed takes no timer or
|
||||
/// thread-pool wake-ups at all. Handlers must be cheap and must not throw.
|
||||
/// </summary>
|
||||
event EventHandler? SubscriptionActivated;
|
||||
|
||||
/// <summary>
|
||||
/// Begin an alarm subscription from the supplied command. The command's
|
||||
/// <see cref="SubscribeAlarmsCommand.ForcedMode"/> and
|
||||
|
||||
@@ -16,4 +16,13 @@ public interface ISubtagAlarmSource : IDisposable
|
||||
/// <summary>Begins advising the supplied MXAccess subtag item addresses.</summary>
|
||||
/// <param name="itemAddresses">The subtag references to advise.</param>
|
||||
void Advise(IReadOnlyCollection<string> itemAddresses);
|
||||
|
||||
/// <summary>
|
||||
/// Stops advising the supplied subtag item addresses and drops them from the source, so
|
||||
/// no further <see cref="ValueChanged"/> is raised for them. Best effort: an address that
|
||||
/// is not advised is skipped, and a COM failure removing one address does not stop the
|
||||
/// rest. Used to shrink a live watch list without rebuilding the source.
|
||||
/// </summary>
|
||||
/// <param name="itemAddresses">The subtag references to stop advising.</param>
|
||||
void Unadvise(IReadOnlyCollection<string> itemAddresses);
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ namespace ZB.MOM.WW.MxGateway.Worker.MxAccess;
|
||||
/// <strong>Threading.</strong> The <c>LMXProxyServerClass</c> CLSID is
|
||||
/// apartment-threaded and delivers <c>OnDataChange</c> via the STA
|
||||
/// message pump. Every method on this type — the lazy <see cref="Advise"/>
|
||||
/// creation and <see cref="Dispose"/> — must be
|
||||
/// creation, <see cref="Unadvise"/> and <see cref="Dispose"/> — must be
|
||||
/// invoked on the worker's STA that created the source, exactly as
|
||||
/// <see cref="MxAccessSession"/> and <see cref="WnWrapAlarmConsumer"/>
|
||||
/// require. The <c>OnDataChange</c> COM event also arrives on that STA.
|
||||
@@ -126,16 +126,64 @@ public sealed class LmxSubtagAlarmSource : ISubtagAlarmSource
|
||||
continue;
|
||||
}
|
||||
|
||||
if (itemHandlesByAddress.ContainsKey(itemAddress!))
|
||||
if (itemHandlesByAddress.TryGetValue(itemAddress!, out int existingHandle))
|
||||
{
|
||||
// Added earlier but its Advise failed: finish advising it instead of skipping it.
|
||||
if (!advisedItemHandles.Contains(existingHandle))
|
||||
{
|
||||
mxServer.Advise(serverHandle, existingHandle);
|
||||
advisedItemHandles.Add(existingHandle);
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// Track the item as soon as it is added, so an Advise failure leaves it known to
|
||||
// Unadvise (which removes it) rather than orphaned on the server until Unregister.
|
||||
int itemHandle = mxServer.AddItem(serverHandle, itemAddress!);
|
||||
itemHandlesByAddress[itemAddress!] = itemHandle;
|
||||
addressesByItemHandle[itemHandle] = itemAddress!;
|
||||
mxServer.Advise(serverHandle, itemHandle);
|
||||
advisedItemHandles.Add(itemHandle);
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Unadvise(IReadOnlyCollection<string> itemAddresses)
|
||||
{
|
||||
if (itemAddresses is null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(itemAddresses));
|
||||
}
|
||||
|
||||
ThrowIfDisposed();
|
||||
|
||||
IMxAccessServer? mxServer = server;
|
||||
foreach (string? itemAddress in itemAddresses)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(itemAddress)
|
||||
|| !itemHandlesByAddress.TryGetValue(itemAddress!, out int itemHandle))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
int itemHandle = mxServer.AddItem(serverHandle, itemAddress!);
|
||||
mxServer.Advise(serverHandle, itemHandle);
|
||||
itemHandlesByAddress[itemAddress!] = itemHandle;
|
||||
addressesByItemHandle[itemHandle] = itemAddress!;
|
||||
advisedItemHandles.Add(itemHandle);
|
||||
// Drop the mapping first so a callback already queued for this handle is ignored
|
||||
// even if the COM calls below fail.
|
||||
itemHandlesByAddress.Remove(itemAddress!);
|
||||
addressesByItemHandle.Remove(itemHandle);
|
||||
bool wasAdvised = advisedItemHandles.Remove(itemHandle);
|
||||
|
||||
if (mxServer is null || !registered)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (wasAdvised)
|
||||
{
|
||||
try { mxServer.UnAdvise(serverHandle, itemHandle); } catch { /* best effort */ }
|
||||
}
|
||||
|
||||
try { mxServer.RemoveItem(serverHandle, itemHandle); } catch { /* best effort */ }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -65,6 +65,11 @@ public sealed class MxAccessStaSession : IWorkerRuntimeSession
|
||||
private IAlarmCommandHandler? alarmCommandHandler;
|
||||
private CancellationTokenSource? alarmPollCts;
|
||||
private Task? alarmPollTask;
|
||||
|
||||
// Wakes the parked alarm poll loop when the handler subscribes (MXA-011). Count 0..1: a signal
|
||||
// that arrives before the loop parks is kept, so a subscribe racing the park is never missed.
|
||||
private SemaphoreSlim? alarmPollWake;
|
||||
private EventHandler? alarmSubscriptionActivatedHandler;
|
||||
private int? alarmConsumerThreadId;
|
||||
|
||||
// True on the STA thread exactly around the alarm PollOnce COM call. The alarm poll runs outside
|
||||
@@ -392,15 +397,59 @@ public sealed class MxAccessStaSession : IWorkerRuntimeSession
|
||||
|
||||
if (alarmCommandHandler is not null)
|
||||
{
|
||||
SemaphoreSlim wake = new SemaphoreSlim(0, 1);
|
||||
alarmPollWake = wake;
|
||||
alarmSubscriptionActivatedHandler = (_, _) => SignalAlarmPollWake(wake);
|
||||
alarmCommandHandler.SubscriptionActivated += alarmSubscriptionActivatedHandler;
|
||||
alarmPollCts = new CancellationTokenSource();
|
||||
alarmPollTask = RunAlarmPollLoopAsync(alarmCommandHandler, alarmPollCts.Token);
|
||||
alarmPollTask = RunAlarmPollLoopAsync(alarmCommandHandler, wake, alarmPollCts.Token);
|
||||
}
|
||||
|
||||
return ready;
|
||||
}
|
||||
|
||||
private static void SignalAlarmPollWake(SemaphoreSlim wake)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (wake.CurrentCount == 0)
|
||||
{
|
||||
wake.Release();
|
||||
}
|
||||
}
|
||||
catch (SemaphoreFullException)
|
||||
{
|
||||
// Already signalled by a concurrent subscribe — one pending wake is enough.
|
||||
}
|
||||
catch (ObjectDisposedException)
|
||||
{
|
||||
// The session is shutting down; there is no loop left to wake.
|
||||
}
|
||||
}
|
||||
|
||||
// Detaches the subscribe signal and disposes the wake semaphore. Called after the poll loop
|
||||
// was cancelled (and joined, when it stopped in time): a loop still parked sees the
|
||||
// cancellation first, and one that outlived the join treats a disposed semaphore as a stop.
|
||||
private void ReleaseAlarmPollWake()
|
||||
{
|
||||
SemaphoreSlim? wake = alarmPollWake;
|
||||
EventHandler? activated = alarmSubscriptionActivatedHandler;
|
||||
alarmPollWake = null;
|
||||
alarmSubscriptionActivatedHandler = null;
|
||||
if (activated is not null && alarmCommandHandler is not null)
|
||||
{
|
||||
try { alarmCommandHandler.SubscriptionActivated -= activated; } catch { /* best effort */ }
|
||||
}
|
||||
|
||||
if (wake is not null)
|
||||
{
|
||||
try { wake.Dispose(); } catch { /* best effort */ }
|
||||
}
|
||||
}
|
||||
|
||||
private Task RunAlarmPollLoopAsync(
|
||||
IAlarmCommandHandler handler,
|
||||
SemaphoreSlim wake,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
TimeSpan pollInterval = AlarmPollInterval;
|
||||
@@ -410,6 +459,31 @@ public sealed class MxAccessStaSession : IWorkerRuntimeSession
|
||||
int consecutiveFailures = 0;
|
||||
while (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
// Park while nothing is subscribed (MXA-011): no timer, no thread-pool wake-up and
|
||||
// no STA hop until SubscriptionActivated signals. The loop never parks while a
|
||||
// subscription is in force, so the failover consumer still gets every PollOnce it
|
||||
// counts failures and failback probes on, and shutdown cancels a parked loop as
|
||||
// promptly as a sleeping one. A failure run does not carry across subscriptions.
|
||||
if (!handler.IsSubscribed)
|
||||
{
|
||||
consecutiveFailures = 0;
|
||||
try
|
||||
{
|
||||
await wake.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
catch (ObjectDisposedException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Re-check: a stale signal from an earlier subscription parks again.
|
||||
continue;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await Task.Delay(pollInterval, cancellationToken).ConfigureAwait(false);
|
||||
@@ -424,9 +498,8 @@ 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.
|
||||
// Unsubscribed during the delay: PollOnce would find no dispatcher. Skip the STA hop
|
||||
// and park on the next iteration.
|
||||
if (!handler.IsSubscribed)
|
||||
{
|
||||
continue;
|
||||
@@ -806,6 +879,7 @@ public sealed class MxAccessStaSession : IWorkerRuntimeSession
|
||||
}
|
||||
|
||||
pollCtsToDispose.Dispose();
|
||||
ReleaseAlarmPollWake();
|
||||
}
|
||||
|
||||
// Stop the alarm consumer's polling timer and tear down the
|
||||
@@ -954,6 +1028,7 @@ public sealed class MxAccessStaSession : IWorkerRuntimeSession
|
||||
catch (ObjectDisposedException) { }
|
||||
}
|
||||
try { pollCtsToDispose.Dispose(); } catch { }
|
||||
ReleaseAlarmPollWake();
|
||||
}
|
||||
|
||||
IAlarmCommandHandler? alarmHandlerToDispose = alarmCommandHandler;
|
||||
|
||||
@@ -37,10 +37,18 @@ namespace ZB.MOM.WW.MxGateway.Worker.MxAccess;
|
||||
public sealed class SubtagAlarmConsumer : IMxAccessAlarmConsumer
|
||||
{
|
||||
private readonly ISubtagAlarmSource source;
|
||||
private readonly SubtagAlarmStateMachine stateMachine;
|
||||
private readonly Dictionary<string, AlarmSubtagTarget> targetsByReference;
|
||||
private readonly Dictionary<Guid, string> referencesBySyntheticGuid;
|
||||
private readonly EventHandler<SubtagValueChange> valueChangedHandler;
|
||||
|
||||
// The most recent change per advised address. A watch-list update that re-binds an already
|
||||
// advised address to a fresh alarm state replays it instead of re-advising the subtag: MXAccess
|
||||
// delivers a subtag's current value once, on Advise, so a fresh state would otherwise wait for
|
||||
// the next real change to learn it.
|
||||
private readonly Dictionary<string, SubtagValueChange> lastChangeByAddress =
|
||||
new Dictionary<string, SubtagValueChange>(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
private SubtagAlarmStateMachine stateMachine;
|
||||
private Dictionary<string, AlarmSubtagTarget> targetsByReference;
|
||||
private Dictionary<Guid, string> referencesBySyntheticGuid;
|
||||
private bool subscribed;
|
||||
private bool disposed;
|
||||
|
||||
@@ -66,16 +74,7 @@ public sealed class SubtagAlarmConsumer : IMxAccessAlarmConsumer
|
||||
}
|
||||
|
||||
this.stateMachine = new SubtagAlarmStateMachine(watchList);
|
||||
this.targetsByReference = new Dictionary<string, AlarmSubtagTarget>(StringComparer.OrdinalIgnoreCase);
|
||||
this.referencesBySyntheticGuid = new Dictionary<Guid, string>();
|
||||
|
||||
foreach (AlarmSubtagTarget target in watchList)
|
||||
{
|
||||
string reference = target.AlarmFullReference ?? string.Empty;
|
||||
this.targetsByReference[reference] = target;
|
||||
this.referencesBySyntheticGuid[SyntheticAlarmGuid.ForReference(reference)] = reference;
|
||||
}
|
||||
|
||||
BuildTargetMaps(watchList, out this.targetsByReference, out this.referencesBySyntheticGuid);
|
||||
this.valueChangedHandler = OnValueChanged;
|
||||
}
|
||||
|
||||
@@ -104,6 +103,121 @@ public sealed class SubtagAlarmConsumer : IMxAccessAlarmConsumer
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Replaces the watch list in place, applying only the difference to the subtag source:
|
||||
/// subtags of added alarms are advised, subtags of removed alarms are unadvised, and an alarm
|
||||
/// whose target is unchanged keeps both its advice and its tracked state (MXA-010). An alarm
|
||||
/// whose target changed in any field is treated as removed and re-added, starting from fresh
|
||||
/// state.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// The update is all-or-nothing from the caller's view. The new list is validated (a
|
||||
/// duplicate reference or subtag address throws) and the added subtags are advised before
|
||||
/// anything is swapped; if advising fails, the subtags this call added are unadvised again
|
||||
/// and the consumer keeps serving the previous list. Unadvising removed subtags happens
|
||||
/// after the swap and is best effort, because a removed subtag that cannot be unadvised is
|
||||
/// already unbound and its callbacks are ignored.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// An alarm whose state is fresh but whose subtag was already advised (its target changed,
|
||||
/// or the address moved to another alarm) is initialised from the last value delivered for
|
||||
/// that subtag, the same initial sync an Advise would deliver. Transitions this produces
|
||||
/// are emitted like any other. Before <see cref="Subscribe"/> the list is only recorded;
|
||||
/// <see cref="Subscribe"/> advises it.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
/// <param name="watchList">The complete replacement watch list.</param>
|
||||
/// <exception cref="ArgumentNullException"><paramref name="watchList"/> is <see langword="null"/>.</exception>
|
||||
/// <exception cref="ArgumentException">The list repeats an alarm reference or a subtag address.</exception>
|
||||
public void UpdateWatchList(IReadOnlyList<AlarmSubtagTarget> watchList)
|
||||
{
|
||||
if (disposed)
|
||||
{
|
||||
throw new ObjectDisposedException(nameof(SubtagAlarmConsumer));
|
||||
}
|
||||
|
||||
if (watchList is null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(watchList));
|
||||
}
|
||||
|
||||
SubtagAlarmStateMachine previous = stateMachine;
|
||||
SubtagAlarmStateMachine next = new SubtagAlarmStateMachine(watchList, previous);
|
||||
BuildTargetMaps(
|
||||
watchList,
|
||||
out Dictionary<string, AlarmSubtagTarget> nextTargets,
|
||||
out Dictionary<Guid, string> nextGuids);
|
||||
|
||||
List<string> toAdvise = new List<string>();
|
||||
foreach (string address in next.BoundAddresses)
|
||||
{
|
||||
if (!previous.IsBound(address))
|
||||
{
|
||||
toAdvise.Add(address);
|
||||
}
|
||||
}
|
||||
|
||||
List<string> toUnadvise = new List<string>();
|
||||
foreach (string address in previous.BoundAddresses)
|
||||
{
|
||||
if (!next.IsBound(address))
|
||||
{
|
||||
toUnadvise.Add(address);
|
||||
}
|
||||
}
|
||||
|
||||
if (subscribed && toAdvise.Count > 0)
|
||||
{
|
||||
try
|
||||
{
|
||||
source.Advise(toAdvise);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Roll back what this call added so the source again matches the list still in
|
||||
// force. None of these addresses is bound in the previous list, so nothing it
|
||||
// still serves is touched.
|
||||
try { source.Unadvise(toAdvise); } catch { /* best effort — preserve the advise failure */ }
|
||||
foreach (string address in toAdvise)
|
||||
{
|
||||
lastChangeByAddress.Remove(address);
|
||||
}
|
||||
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
stateMachine = next;
|
||||
targetsByReference = nextTargets;
|
||||
referencesBySyntheticGuid = nextGuids;
|
||||
|
||||
if (!subscribed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (toUnadvise.Count > 0)
|
||||
{
|
||||
try { source.Unadvise(toUnadvise); } catch { /* best effort — the addresses are already unbound */ }
|
||||
foreach (string address in toUnadvise)
|
||||
{
|
||||
lastChangeByAddress.Remove(address);
|
||||
}
|
||||
}
|
||||
|
||||
// Initial sync for alarms that start fresh on an address whose value already arrived —
|
||||
// either advised under the previous list, or delivered re-entrantly while Advise ran
|
||||
// above, when the previous machine had no binding for it yet.
|
||||
foreach (string address in next.FreshAddresses)
|
||||
{
|
||||
if (lastChangeByAddress.TryGetValue(address, out SubtagValueChange change))
|
||||
{
|
||||
ApplyAndEmit(change);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public AlarmAckTarget ResolveAckTarget(Guid alarmGuid)
|
||||
{
|
||||
@@ -164,6 +278,7 @@ public sealed class SubtagAlarmConsumer : IMxAccessAlarmConsumer
|
||||
}
|
||||
|
||||
disposed = true;
|
||||
lastChangeByAddress.Clear();
|
||||
|
||||
if (subscribed)
|
||||
{
|
||||
@@ -196,6 +311,16 @@ public sealed class SubtagAlarmConsumer : IMxAccessAlarmConsumer
|
||||
return;
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(change.ItemAddress))
|
||||
{
|
||||
lastChangeByAddress[change.ItemAddress] = change;
|
||||
}
|
||||
|
||||
ApplyAndEmit(change);
|
||||
}
|
||||
|
||||
private void ApplyAndEmit(SubtagValueChange change)
|
||||
{
|
||||
IReadOnlyList<MxAlarmTransitionEvent> transitions =
|
||||
stateMachine.Apply(change.ItemAddress, change.Value, change.TimestampUtc, change.Quality);
|
||||
if (transitions.Count == 0)
|
||||
@@ -244,6 +369,21 @@ public sealed class SubtagAlarmConsumer : IMxAccessAlarmConsumer
|
||||
return target;
|
||||
}
|
||||
|
||||
private static void BuildTargetMaps(
|
||||
IReadOnlyList<AlarmSubtagTarget> watchList,
|
||||
out Dictionary<string, AlarmSubtagTarget> targets,
|
||||
out Dictionary<Guid, string> guids)
|
||||
{
|
||||
targets = new Dictionary<string, AlarmSubtagTarget>(StringComparer.OrdinalIgnoreCase);
|
||||
guids = new Dictionary<Guid, string>();
|
||||
foreach (AlarmSubtagTarget target in watchList)
|
||||
{
|
||||
string reference = target.AlarmFullReference ?? string.Empty;
|
||||
targets[reference] = target;
|
||||
guids[SyntheticAlarmGuid.ForReference(reference)] = reference;
|
||||
}
|
||||
}
|
||||
|
||||
private static AlarmAckTarget ToAckTarget(AlarmSubtagTarget target)
|
||||
{
|
||||
string ackItem = target.AckCommentSubtag ?? string.Empty;
|
||||
|
||||
@@ -31,9 +31,30 @@ public sealed class SubtagAlarmStateMachine
|
||||
private readonly Dictionary<string, AlarmState> _statesByReference = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly Dictionary<string, SubtagBinding> _bindingsByAddress = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
// Subtag addresses bound to an alarm state created by this instance rather than carried over
|
||||
// from a previous machine; on a watch-list update these need an initial value. The .active
|
||||
// subtags are kept apart so FreshAddresses can list them last.
|
||||
private readonly List<string> _freshAddresses = new();
|
||||
private readonly List<string> _freshActiveAddresses = new();
|
||||
|
||||
/// <summary>Initializes the machine from the configured alarm subtag targets.</summary>
|
||||
/// <param name="targets">The alarm targets whose subtags will be observed.</param>
|
||||
public SubtagAlarmStateMachine(IEnumerable<AlarmSubtagTarget> targets)
|
||||
: this(targets, carryOver: null)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the machine for an updated watch list, carrying over the tracked state of
|
||||
/// every alarm whose target is unchanged from <paramref name="carryOver"/>. An alarm whose
|
||||
/// target is new or differs in any field starts with fresh state, and its subtag addresses
|
||||
/// are reported in <see cref="FreshAddresses"/>. Construction validates the whole list
|
||||
/// before anything is shared, and never modifies <paramref name="carryOver"/>: a rejected
|
||||
/// list leaves the previous machine fully usable.
|
||||
/// </summary>
|
||||
/// <param name="targets">The alarm targets whose subtags will be observed.</param>
|
||||
/// <param name="carryOver">The machine serving the previous watch list, or <see langword="null"/>.</param>
|
||||
public SubtagAlarmStateMachine(IEnumerable<AlarmSubtagTarget> targets, SubtagAlarmStateMachine? carryOver)
|
||||
{
|
||||
if (targets is null)
|
||||
{
|
||||
@@ -56,15 +77,48 @@ public sealed class SubtagAlarmStateMachine
|
||||
nameof(targets));
|
||||
}
|
||||
|
||||
var state = new AlarmState(target);
|
||||
// An unchanged target keeps its state object, so its active/acked/priority history
|
||||
// survives the update and its subtags need no re-advise or re-sync. Sharing the object
|
||||
// is safe: the previous machine is discarded once this one is committed, and until
|
||||
// then either machine applies the same updates to it.
|
||||
bool carried = false;
|
||||
AlarmState? state = null;
|
||||
if (carryOver is not null
|
||||
&& carryOver._statesByReference.TryGetValue(reference, out AlarmState previous)
|
||||
&& previous.Target.Equals(target))
|
||||
{
|
||||
state = previous;
|
||||
carried = true;
|
||||
}
|
||||
|
||||
state ??= new AlarmState(target);
|
||||
_statesByReference[reference] = state;
|
||||
|
||||
Bind(target.ActiveSubtag, state, SubtagRole.Active);
|
||||
Bind(target.AckedSubtag, state, SubtagRole.Acked);
|
||||
Bind(target.PrioritySubtag, state, SubtagRole.Priority);
|
||||
Bind(target.ActiveSubtag, state, SubtagRole.Active, carried);
|
||||
Bind(target.AckedSubtag, state, SubtagRole.Acked, carried);
|
||||
Bind(target.PrioritySubtag, state, SubtagRole.Priority, carried);
|
||||
}
|
||||
|
||||
_freshAddresses.AddRange(_freshActiveAddresses);
|
||||
}
|
||||
|
||||
/// <summary>Gets the subtag addresses this machine observes (active, acked and priority).</summary>
|
||||
public IReadOnlyCollection<string> BoundAddresses => _bindingsByAddress.Keys;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the subtag addresses bound to an alarm whose state this machine created rather than
|
||||
/// carried over — every address for a machine built without a carry-over source. Every
|
||||
/// <c>.active</c> subtag comes after all <c>.acked</c> and <c>.priority</c> subtags, so
|
||||
/// replaying known values in this order initialises each fresh alarm with one transition
|
||||
/// that already carries its acknowledgement and priority (MXA-007).
|
||||
/// </summary>
|
||||
public IReadOnlyCollection<string> FreshAddresses => _freshAddresses;
|
||||
|
||||
/// <summary>Returns whether <paramref name="itemAddress"/> is observed by this machine.</summary>
|
||||
/// <param name="itemAddress">The subtag address (case-insensitive).</param>
|
||||
/// <returns><see langword="true"/> when the address is bound to an alarm.</returns>
|
||||
public bool IsBound(string itemAddress) => _bindingsByAddress.ContainsKey(itemAddress);
|
||||
|
||||
/// <summary>
|
||||
/// Applies a single subtag value change whose quality is not reported
|
||||
/// and returns any synthesized transitions. Unknown addresses and no-op
|
||||
@@ -250,7 +304,7 @@ public sealed class SubtagAlarmStateMachine
|
||||
};
|
||||
}
|
||||
|
||||
private void Bind(string? address, AlarmState state, SubtagRole role)
|
||||
private void Bind(string? address, AlarmState state, SubtagRole role, bool carried)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(address))
|
||||
{
|
||||
@@ -262,6 +316,10 @@ public sealed class SubtagAlarmStateMachine
|
||||
}
|
||||
|
||||
_bindingsByAddress[address!] = new SubtagBinding(state, role);
|
||||
if (!carried)
|
||||
{
|
||||
(role == SubtagRole.Active ? _freshActiveAddresses : _freshAddresses).Add(address!);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -356,9 +414,13 @@ public sealed class SubtagAlarmStateMachine
|
||||
/// <param name="target">The configured alarm subtag target this state tracks.</param>
|
||||
public AlarmState(AlarmSubtagTarget target)
|
||||
{
|
||||
Target = target;
|
||||
(_providerName, _group, _tagName) = DeriveNameParts(target);
|
||||
}
|
||||
|
||||
/// <summary>Gets the watch-list target this state was built from.</summary>
|
||||
public AlarmSubtagTarget Target { get; }
|
||||
|
||||
/// <summary>Gets or sets whether the alarm is currently active (raised).</summary>
|
||||
public bool Active { get; set; }
|
||||
|
||||
|
||||
Reference in New Issue
Block a user