perf(worker): alarm watch-list update diffs the subtag standby instead of rebuilding it (MXA-010, #258)

UpdateAlarmWatchList rebuilt the standby: a second MXAccess registration, an
AddItem/Advise for every watched subtag, then an Unregister of the old source —
work proportional to the whole list for a one-alarm change (reproduced by the
previous commit's test). The subtag standby now takes the list as a diff:
added alarms' subtags are advised on the existing source, removed alarms'
subtags are unadvised, and unchanged alarms keep their advice and state.

The update stays all-or-nothing: the list is validated and the additions
advised before the swap, and an advise failure unadvises what it added and
keeps the previous list. A changed target starts fresh and is initialised from
the last delivered subtag values (acked/priority before active, MXA-007; bad
quality still ignored, MXA-005). LmxSubtagAlarmSource tracks an item from
AddItem so an Advise failure is retryable and removable.
This commit is contained in:
Joseph Doherty
2026-12-03 13:10:31 -05:00
parent d8553b1ff7
commit a38578d0e2
13 changed files with 653 additions and 42 deletions
@@ -868,6 +868,15 @@ public sealed class AlarmCommandHandlerTests
}
}
/// <inheritdoc />
public void Unadvise(IReadOnlyCollection<string> itemAddresses)
{
foreach (string address in itemAddresses)
{
Advised.Remove(address);
}
}
/// <inheritdoc />
public void Dispose() => Disposed = true;
}
@@ -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);
}
@@ -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,
});
}
@@ -296,6 +296,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)
{
@@ -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 */ }
}
}
@@ -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; }