diff --git a/docs/AlarmClientDiscovery.md b/docs/AlarmClientDiscovery.md index 855e3dc9..16212bf9 100644 --- a/docs/AlarmClientDiscovery.md +++ b/docs/AlarmClientDiscovery.md @@ -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 diff --git a/docs/Contracts.md b/docs/Contracts.md index 12ec8736..d96f75f0 100644 --- a/docs/Contracts.md +++ b/docs/Contracts.md @@ -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 diff --git a/docs/GatewayConfiguration.md b/docs/GatewayConfiguration.md index 494da662..1e80456b 100644 --- a/docs/GatewayConfiguration.md +++ b/docs/GatewayConfiguration.md @@ -534,7 +534,7 @@ behavior. | `MxGateway:Alarms:SubscriptionExpression` | _(empty)_ | AVEVA alarm-subscription expression the monitor subscribes on startup, in canonical `\\\Galaxy!` form. The literal `Galaxy` provider is correct regardless of the Galaxy database name. When empty and `Enabled` is `true`, the gateway falls back to `\\\Galaxy!` 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`. | diff --git a/docs/MxAccessWorkerInstanceDesign.md b/docs/MxAccessWorkerInstanceDesign.md index 3d1be6d9..1f0bda2d 100644 --- a/docs/MxAccessWorkerInstanceDesign.md +++ b/docs/MxAccessWorkerInstanceDesign.md @@ -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 diff --git a/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/AlarmCommandExecutorTests.cs b/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/AlarmCommandExecutorTests.cs index a72645f7..e059741b 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/AlarmCommandExecutorTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/AlarmCommandExecutorTests.cs @@ -588,6 +588,9 @@ public sealed class AlarmCommandExecutorTests /// public bool IsSubscribed => LastSubscription is not null && !UnsubscribeCalled; + /// + public event EventHandler? SubscriptionActivated; + /// Gets the last subscription expression. public string? LastSubscription { get; private set; } @@ -627,6 +630,7 @@ public sealed class AlarmCommandExecutorTests { LastSubscription = command.SubscriptionExpression; LastSessionId = sessionId; + SubscriptionActivated?.Invoke(this, EventArgs.Empty); } /// Gets the most recent replacement watch list. diff --git a/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/AlarmCommandHandlerTests.cs b/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/AlarmCommandHandlerTests.cs index 597179b5..1ec624aa 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/AlarmCommandHandlerTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/AlarmCommandHandlerTests.cs @@ -644,6 +644,52 @@ public sealed class AlarmCommandHandlerTests Assert.Equal("33.AckMsg", AckItemOf(handler)); } + /// + /// 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. + /// + [Fact] + public void UpdateWatchList_OneTargetAdded_AdvisesOnlyTheAddedSubtagsOnTheExistingSource() + { + List sources = new List(); + 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 watchList = new List(); + 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); + } + /// /// 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 } } + /// Subtag source that counts the addresses it is asked to advise. + private sealed class CountingSubtagSource : ISubtagAlarmSource + { +#pragma warning disable CS0067 // Event never invoked — these tests count advise work, not transitions. + /// + public event EventHandler? ValueChanged; +#pragma warning restore CS0067 + + /// Gets the addresses currently advised. + public HashSet Advised { get; } = new HashSet(StringComparer.Ordinal); + + /// Gets the total number of advise operations performed (AddItem + Advise pairs). + public int AdvisedCount { get; private set; } + + /// Gets a value indicating whether the source was disposed. + public bool Disposed { get; private set; } + + /// + public void Advise(IReadOnlyCollection itemAddresses) + { + foreach (string address in itemAddresses) + { + if (Advised.Add(address)) + { + AdvisedCount++; + } + } + } + + /// + public void Unadvise(IReadOnlyCollection itemAddresses) + { + foreach (string address in itemAddresses) + { + Advised.Remove(address); + } + } + + /// + public void Dispose() => Disposed = true; + } + private sealed class RecordingAckWriter : IAlarmAckWriter { public string? LastItemAddress { get; private set; } diff --git a/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/FailoverAlarmConsumerTests.cs b/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/FailoverAlarmConsumerTests.cs index 6eb593c6..a37c67e6 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/FailoverAlarmConsumerTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/FailoverAlarmConsumerTests.cs @@ -239,6 +239,66 @@ public sealed class FailoverAlarmConsumerTests Assert.Equal(AlarmProviderMode.Subtag, sut.Mode); } + /// + /// 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. + /// + [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 forwarded = new List(); + 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? ValueChanged; + + public void Advise(IReadOnlyCollection itemAddresses) + { + } + + public void Unadvise(IReadOnlyCollection itemAddresses) + { + } + + public void Raise(string address, object value) => ValueChanged?.Invoke(this, new SubtagValueChange + { + ItemAddress = address, + Value = value, + TimestampUtc = DateTime.UtcNow, + }); + + public void Dispose() + { + } + } + /// /// 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 diff --git a/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/LmxSubtagAlarmSourceTests.cs b/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/LmxSubtagAlarmSourceTests.cs index b550b104..f07bfa1c 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/LmxSubtagAlarmSourceTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/LmxSubtagAlarmSourceTests.cs @@ -136,6 +136,61 @@ public sealed class LmxSubtagAlarmSourceTests Assert.Empty(server.Writes); } + /// + /// MXA-010: 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. + /// + [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 raised = new List(); + 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")); + } + + /// + /// 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. + /// + [Fact] + public void Advise_FailureAfterAddItem_IsRetriedAndRemovable() + { + var server = new RecordingMxAccessServer { FailAdviseCalls = 1 }; + using var source = new LmxSubtagAlarmSource(server, FakeServerHandle); + + Assert.Throws( + () => 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); + } + /// /// Verifies is idempotent: a /// second call performs no further teardown. @@ -217,9 +272,18 @@ public sealed class LmxSubtagAlarmSourceTests /// public void RemoveItem(int serverHandle, int itemHandle) => RemovedItemHandles.Add(itemHandle); + /// Gets or sets how many upcoming calls throw a COM failure. + public int FailAdviseCalls { get; set; } + /// 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); } diff --git a/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/MxAccessStaSessionTests.cs b/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/MxAccessStaSessionTests.cs index abda4563..46d614f2 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/MxAccessStaSessionTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/MxAccessStaSessionTests.cs @@ -416,6 +416,61 @@ public sealed class MxAccessStaSessionTests Assert.True(handler.PollCount > 0, "Polling should start once the handler is subscribed."); } + /// + /// 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 , so a parked loop + /// leaves the read count flat while a timer-driven one would add one read per interval. + /// + /// A task that represents the asynchronous operation. + [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 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."); + } + /// /// Gap 2: Verifies that the STA poll loop stops when the session is disposed — /// no further PollOnce calls after disposal. @@ -868,14 +923,36 @@ public sealed class MxAccessStaSessionTests private int pollCount; private int? lastPollThreadId; - /// Gets a value indicating whether the alarm client is currently subscribed. + /// + public event EventHandler? SubscriptionActivated; + + /// + /// Gets or sets a value indicating whether the alarm client is currently subscribed. Setting it + /// to true raises , as a successful Subscribe does. + /// 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; + + /// Gets how many times was read — once per poll-loop wake-up. + public int IsSubscribedReadCount => Volatile.Read(ref isSubscribedReads); /// Gets the last alarm subscription name. public string? LastSubscription { get; private set; } diff --git a/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/SubtagAlarmConsumerTests.cs b/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/SubtagAlarmConsumerTests.cs index 76b1be21..1b08f5d0 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/SubtagAlarmConsumerTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/SubtagAlarmConsumerTests.cs @@ -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); + + /// + /// 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. + /// + [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); + } + + /// + /// 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. + /// + [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 emitted = new List(); + 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); + } + + /// + /// 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. + /// + [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 emitted = new List(); + 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); + } + + /// + /// MXA-005 holds across the replay: a fresh alarm whose last delivered .active update had + /// bad quality is not initialised from it. + /// + [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 _)); + } + + /// + /// A failed advise rolls the update back: the subtags it added are unadvised again and the + /// consumer keeps serving the previous list, state included. + /// + [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( + () => 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 _)); + } + + /// A list that repeats an alarm reference is rejected before the source is touched. + [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( + () => 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 { /// Raised when an advised subtag reports a new value. @@ -251,23 +395,45 @@ public sealed class SubtagAlarmConsumerTests /// Gets the subtag addresses passed to . public List Advised { get; } = new List(); + /// Gets the subtag addresses passed to . + public List Unadvised { get; } = new List(); + + /// Gets or sets an address whose advise throws (after the addresses before it were advised). + public string? FailAdviseOf { get; set; } + /// public void Advise(IReadOnlyCollection 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); + } + } + + /// + public void Unadvise(IReadOnlyCollection itemAddresses) + { + Unadvised.AddRange(itemAddresses); } /// Raises a for the given subtag. /// The subtag address whose value changed. /// The new value. /// The UTC timestamp of the change. - public void Raise(string address, object? value, DateTime timestampUtc) + /// The item quality, or null when not reported. + 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, }); } diff --git a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/AlarmCommandHandler.cs b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/AlarmCommandHandler.cs index 39632734..98c32fbe 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/AlarmCommandHandler.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/AlarmCommandHandler.cs @@ -164,6 +164,9 @@ public sealed class AlarmCommandHandler : IAlarmCommandHandler get { lock (syncRoot) return dispatcher is not null; } } + /// + public event EventHandler? SubscriptionActivated; + /// 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 */ } } /// @@ -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); } diff --git a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/FailoverAlarmConsumer.cs b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/FailoverAlarmConsumer.cs index c290f292..100b0e9a 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/FailoverAlarmConsumer.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/FailoverAlarmConsumer.cs @@ -169,6 +169,32 @@ public sealed class FailoverAlarmConsumer : IMxAccessAlarmConsumer try { previous.Dispose(); } catch { /* replacement is already active */ } } + /// + /// Applies a replacement watch list to the current standby in place when the standby is a + /// , 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. + /// + /// The complete replacement watch list. + /// + /// when the standby was updated in place; + /// when it cannot be, and the caller must build a replacement for + /// . + /// + public bool TryUpdateStandbyWatchList(IReadOnlyList 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; + } + /// public void Subscribe(string subscription) { diff --git a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/IAlarmCommandHandler.cs b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/IAlarmCommandHandler.cs index bf49e213..74911834 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/IAlarmCommandHandler.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/IAlarmCommandHandler.cs @@ -21,6 +21,14 @@ public interface IAlarmCommandHandler : IDisposable /// bool IsSubscribed { get; } + /// + /// Raised after a call succeeds, on the thread that made it (the + /// STA). The STA alarm poll loop parks while 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. + /// + event EventHandler? SubscriptionActivated; + /// /// Begin an alarm subscription from the supplied command. The command's /// and diff --git a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/ISubtagAlarmSource.cs b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/ISubtagAlarmSource.cs index ef160c26..802d0ded 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/ISubtagAlarmSource.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/ISubtagAlarmSource.cs @@ -16,4 +16,13 @@ public interface ISubtagAlarmSource : IDisposable /// Begins advising the supplied MXAccess subtag item addresses. /// The subtag references to advise. void Advise(IReadOnlyCollection itemAddresses); + + /// + /// Stops advising the supplied subtag item addresses and drops them from the source, so + /// no further 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. + /// + /// The subtag references to stop advising. + void Unadvise(IReadOnlyCollection itemAddresses); } diff --git a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/LmxSubtagAlarmSource.cs b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/LmxSubtagAlarmSource.cs index 83c3ec7f..d17a7487 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/LmxSubtagAlarmSource.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/LmxSubtagAlarmSource.cs @@ -26,7 +26,7 @@ namespace ZB.MOM.WW.MxGateway.Worker.MxAccess; /// Threading. The LMXProxyServerClass CLSID is /// apartment-threaded and delivers OnDataChange via the STA /// message pump. Every method on this type — the lazy -/// creation and — must be +/// creation, and — must be /// invoked on the worker's STA that created the source, exactly as /// and /// require. The OnDataChange 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); + } + } + + /// + public void Unadvise(IReadOnlyCollection 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 */ } } } diff --git a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/MxAccessStaSession.cs b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/MxAccessStaSession.cs index bf220a73..119620b5 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/MxAccessStaSession.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/MxAccessStaSession.cs @@ -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; diff --git a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/SubtagAlarmConsumer.cs b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/SubtagAlarmConsumer.cs index 9418ead4..f0df5965 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/SubtagAlarmConsumer.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/SubtagAlarmConsumer.cs @@ -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 targetsByReference; - private readonly Dictionary referencesBySyntheticGuid; private readonly EventHandler 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 lastChangeByAddress = + new Dictionary(StringComparer.OrdinalIgnoreCase); + + private SubtagAlarmStateMachine stateMachine; + private Dictionary targetsByReference; + private Dictionary 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(StringComparer.OrdinalIgnoreCase); - this.referencesBySyntheticGuid = new Dictionary(); - - 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 } } + /// + /// 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. + /// + /// + /// + /// 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. + /// + /// + /// 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 the list is only recorded; + /// advises it. + /// + /// + /// The complete replacement watch list. + /// is . + /// The list repeats an alarm reference or a subtag address. + public void UpdateWatchList(IReadOnlyList 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 nextTargets, + out Dictionary nextGuids); + + List toAdvise = new List(); + foreach (string address in next.BoundAddresses) + { + if (!previous.IsBound(address)) + { + toAdvise.Add(address); + } + } + + List toUnadvise = new List(); + 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); + } + } + } + /// 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 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 watchList, + out Dictionary targets, + out Dictionary guids) + { + targets = new Dictionary(StringComparer.OrdinalIgnoreCase); + guids = new Dictionary(); + 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; diff --git a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/SubtagAlarmStateMachine.cs b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/SubtagAlarmStateMachine.cs index 84f1454f..5ebce23d 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/SubtagAlarmStateMachine.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/SubtagAlarmStateMachine.cs @@ -31,9 +31,30 @@ public sealed class SubtagAlarmStateMachine private readonly Dictionary _statesByReference = new(StringComparer.OrdinalIgnoreCase); private readonly Dictionary _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 _freshAddresses = new(); + private readonly List _freshActiveAddresses = new(); + /// Initializes the machine from the configured alarm subtag targets. /// The alarm targets whose subtags will be observed. public SubtagAlarmStateMachine(IEnumerable targets) + : this(targets, carryOver: null) + { + } + + /// + /// Initializes the machine for an updated watch list, carrying over the tracked state of + /// every alarm whose target is unchanged from . An alarm whose + /// target is new or differs in any field starts with fresh state, and its subtag addresses + /// are reported in . Construction validates the whole list + /// before anything is shared, and never modifies : a rejected + /// list leaves the previous machine fully usable. + /// + /// The alarm targets whose subtags will be observed. + /// The machine serving the previous watch list, or . + public SubtagAlarmStateMachine(IEnumerable 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); } + /// Gets the subtag addresses this machine observes (active, acked and priority). + public IReadOnlyCollection BoundAddresses => _bindingsByAddress.Keys; + + /// + /// 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 + /// .active subtag comes after all .acked and .priority subtags, so + /// replaying known values in this order initialises each fresh alarm with one transition + /// that already carries its acknowledgement and priority (MXA-007). + /// + public IReadOnlyCollection FreshAddresses => _freshAddresses; + + /// Returns whether is observed by this machine. + /// The subtag address (case-insensitive). + /// when the address is bound to an alarm. + public bool IsBound(string itemAddress) => _bindingsByAddress.ContainsKey(itemAddress); + /// /// 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 /// The configured alarm subtag target this state tracks. public AlarmState(AlarmSubtagTarget target) { + Target = target; (_providerName, _group, _tagName) = DeriveNameParts(target); } + /// Gets the watch-list target this state was built from. + public AlarmSubtagTarget Target { get; } + /// Gets or sets whether the alarm is currently active (raised). public bool Active { get; set; }