fix(worker): count an unsubscribed alarm primary as failing and rebuild it (MXA-001, #249)
A wnwrap primary whose Subscribe failed polls as a silent no-op, so the failover counter reset and probes read as clean: failover never engaged (threshold 3) or falsely recovered onto a dead primary (threshold 1). FailoverAlarmConsumer now tracks whether the current primary subscribed; an unsubscribed primary is replaced by a fresh instance from the consumer factory and subscribed before it is polled or probed, and a failure there counts. Without a factory it reports the original subscribe HRESULT.
This commit is contained in:
+7
-2
@@ -210,11 +210,16 @@ The alarm feed has two providers, both implemented worker-side:
|
|||||||
consecutive wnwrap COM failures — `Subscribe` or `PollOnce` throws or
|
consecutive wnwrap COM failures — `Subscribe` or `PollOnce` throws or
|
||||||
returns a failure HRESULT — it activates the standby. The standby is armed
|
returns a failure HRESULT — it activates the standby. The standby is armed
|
||||||
(subscribed and adviseing) from the start so its state is warm at the moment
|
(subscribed and adviseing) from the start so its state is warm at the moment
|
||||||
of switch.
|
of switch. A primary whose `Subscribe` failed is not polled as if it were
|
||||||
|
healthy: wnwrap's `PollOnce` returns without touching COM until it is
|
||||||
|
subscribed, so each poll instead disposes the failed instance and subscribes
|
||||||
|
a fresh one, and a failure there counts toward the threshold.
|
||||||
- **Auto-failback:** while degraded, every `FailbackProbeIntervalSeconds`
|
- **Auto-failback:** while degraded, every `FailbackProbeIntervalSeconds`
|
||||||
(default 30) it re-probes the still-subscribed primary. After
|
(default 30) it re-probes the still-subscribed primary. After
|
||||||
`FailbackStableProbes` (default 3) consecutive clean polls it switches back
|
`FailbackStableProbes` (default 3) consecutive clean polls it switches back
|
||||||
to the alarm manager.
|
to the alarm manager. If the primary never subscribed, the probe first
|
||||||
|
rebuilds and subscribes a fresh primary; until that succeeds every probe
|
||||||
|
fails, so the consumer never reports "recovered" onto a dead primary.
|
||||||
- **On every switch:** the consumer snapshots the now-active provider and
|
- **On every switch:** the consumer snapshots the now-active provider and
|
||||||
emits `OnAlarmProviderModeChangedEvent` so the gateway can reconcile its
|
emits `OnAlarmProviderModeChangedEvent` so the gateway can reconcile its
|
||||||
cache without a raise/clear storm.
|
cache without a raise/clear storm.
|
||||||
|
|||||||
@@ -151,12 +151,207 @@ public sealed class FailoverAlarmConsumerTests
|
|||||||
public void Raise(MxAlarmTransitionEvent e) => AlarmTransitionEmitted?.Invoke(this, e);
|
public void Raise(MxAlarmTransitionEvent e) => AlarmTransitionEmitted?.Invoke(this, e);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Primary fake shaped like <see cref="WnWrapAlarmConsumer"/>: a failed
|
||||||
|
/// <see cref="Subscribe"/> leaves it unsubscribed, and
|
||||||
|
/// <see cref="PollOnce"/> then returns without doing anything instead of
|
||||||
|
/// throwing — the silent no-op that used to read as a healthy poll.
|
||||||
|
/// </summary>
|
||||||
|
private sealed class WnWrapShapedPrimary : IMxAccessAlarmConsumer
|
||||||
|
{
|
||||||
|
/// <summary>Raised when the fake forwards a simulated alarm transition.</summary>
|
||||||
|
public event EventHandler<MxAlarmTransitionEvent>? AlarmTransitionEmitted;
|
||||||
|
|
||||||
|
/// <summary>Gets or sets a value indicating whether <see cref="Subscribe"/> fails.</summary>
|
||||||
|
public bool FailSubscribe { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Gets a value indicating whether a subscribe completed.</summary>
|
||||||
|
public bool Subscribed { get; private set; }
|
||||||
|
|
||||||
|
/// <summary>Gets the number of polls that reached the (subscribed) COM path.</summary>
|
||||||
|
public int ComPolls { get; private set; }
|
||||||
|
|
||||||
|
/// <summary>Gets the number of <see cref="Subscribe"/> calls.</summary>
|
||||||
|
public int SubscribeCount { get; private set; }
|
||||||
|
|
||||||
|
/// <summary>Gets a value indicating whether the fake was disposed.</summary>
|
||||||
|
public bool Disposed { get; private set; }
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public void Subscribe(string s)
|
||||||
|
{
|
||||||
|
SubscribeCount++;
|
||||||
|
if (FailSubscribe)
|
||||||
|
{
|
||||||
|
throw new System.Runtime.InteropServices.COMException("register failed", unchecked((int)0x80004005));
|
||||||
|
}
|
||||||
|
|
||||||
|
Subscribed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public void PollOnce()
|
||||||
|
{
|
||||||
|
if (!Subscribed)
|
||||||
|
{
|
||||||
|
return; // the wnwrap shape: unsubscribed polls are silent no-ops
|
||||||
|
}
|
||||||
|
|
||||||
|
ComPolls++;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public AlarmAckTarget ResolveAckTarget(Guid g) => AlarmAckTarget.For("primary.guid.AckMsg");
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public AlarmAckTarget ResolveAckTargetByName(string n, string p, string gr) => AlarmAckTarget.For("primary.name.AckMsg");
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public IReadOnlyList<MxAlarmSnapshotRecord> SnapshotActiveAlarms(out bool truncated)
|
||||||
|
{
|
||||||
|
truncated = false;
|
||||||
|
return Array.Empty<MxAlarmSnapshotRecord>();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public void Dispose() => Disposed = true;
|
||||||
|
|
||||||
|
/// <summary>Raises <see cref="AlarmTransitionEmitted"/>.</summary>
|
||||||
|
/// <param name="e">The transition event to forward.</param>
|
||||||
|
public void Raise(MxAlarmTransitionEvent e) => AlarmTransitionEmitted?.Invoke(this, e);
|
||||||
|
}
|
||||||
|
|
||||||
private static MxAlarmTransitionEvent SampleTransition() => new MxAlarmTransitionEvent
|
private static MxAlarmTransitionEvent SampleTransition() => new MxAlarmTransitionEvent
|
||||||
{
|
{
|
||||||
Record = new MxAlarmSnapshotRecord { AlarmGuid = Guid.NewGuid() },
|
Record = new MxAlarmSnapshotRecord { AlarmGuid = Guid.NewGuid() },
|
||||||
PreviousState = MxAlarmStateKind.Unspecified,
|
PreviousState = MxAlarmStateKind.Unspecified,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Subscribes a healthy primary, then makes its polls fail and drives one
|
||||||
|
// poll, so a threshold-1 consumer fails over with the primary still
|
||||||
|
// subscribed — the transient-COM-fault shape failback probing is for.
|
||||||
|
private static void FailOverAfterHealthySubscribe(FailoverAlarmConsumer sut, FlakyPrimary primary)
|
||||||
|
{
|
||||||
|
primary.ThrowOnPoll = false;
|
||||||
|
sut.Subscribe(@"\\HOST\Galaxy!Area");
|
||||||
|
primary.ThrowOnPoll = true;
|
||||||
|
sut.PollOnce();
|
||||||
|
Assert.Equal(AlarmProviderMode.Subtag, sut.Mode);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <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
|
||||||
|
/// consumer reaches the threshold and fails over instead of sitting on a
|
||||||
|
/// dead primary.
|
||||||
|
/// </summary>
|
||||||
|
[Fact]
|
||||||
|
public void UnsubscribedPrimary_NoOpPolls_CountAsFailuresAndFailOver()
|
||||||
|
{
|
||||||
|
WnWrapShapedPrimary primary = new WnWrapShapedPrimary { FailSubscribe = true };
|
||||||
|
StubStandby standby = new StubStandby();
|
||||||
|
FailoverSettings settings = new FailoverSettings(threshold: 3, probeIntervalSeconds: 0, stableProbes: 1);
|
||||||
|
using FailoverAlarmConsumer sut = new FailoverAlarmConsumer(primary, standby, settings);
|
||||||
|
|
||||||
|
List<AlarmProviderModeChange> changes = new List<AlarmProviderModeChange>();
|
||||||
|
sut.ProviderModeChanged += (_, e) => changes.Add(e);
|
||||||
|
|
||||||
|
sut.Subscribe(@"\\HOST\Galaxy!Area"); // failure 1
|
||||||
|
sut.PollOnce(); // failure 2 (no-op poll is not success)
|
||||||
|
Assert.Equal(AlarmProviderMode.Alarmmgr, sut.Mode);
|
||||||
|
sut.PollOnce(); // failure 3 → switch
|
||||||
|
|
||||||
|
AlarmProviderModeChange change = Assert.Single(changes);
|
||||||
|
Assert.Equal(AlarmProviderMode.Subtag, change.Mode);
|
||||||
|
Assert.Equal(unchecked((int)0x80004005), change.HResult);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// MXA-001: without a way to rebuild the primary, a primary that never
|
||||||
|
/// subscribed must never be "recovered" onto — every probe fails.
|
||||||
|
/// </summary>
|
||||||
|
[Fact]
|
||||||
|
public void UnsubscribedPrimary_WithoutFactory_NeverFailsBack()
|
||||||
|
{
|
||||||
|
WnWrapShapedPrimary primary = new WnWrapShapedPrimary { FailSubscribe = true };
|
||||||
|
StubStandby standby = new StubStandby();
|
||||||
|
FailoverSettings settings = new FailoverSettings(threshold: 1, probeIntervalSeconds: 0, stableProbes: 3);
|
||||||
|
using FailoverAlarmConsumer sut = new FailoverAlarmConsumer(primary, standby, settings);
|
||||||
|
|
||||||
|
sut.Subscribe(@"\\HOST\Galaxy!Area"); // threshold=1 → Subtag
|
||||||
|
Assert.Equal(AlarmProviderMode.Subtag, sut.Mode);
|
||||||
|
|
||||||
|
for (int probe = 0; probe < 10; probe++)
|
||||||
|
{
|
||||||
|
sut.ProbeOnce();
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.Equal(AlarmProviderMode.Subtag, sut.Mode);
|
||||||
|
Assert.Equal(1, primary.SubscribeCount);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// MXA-001: with a primary factory, probing replaces the never-subscribed
|
||||||
|
/// primary with a fresh instance (disposing the failed one — never
|
||||||
|
/// re-subscribing the same object) and fails back only after the fresh
|
||||||
|
/// instance subscribed and then polled cleanly for the stable-probe run.
|
||||||
|
/// </summary>
|
||||||
|
[Fact]
|
||||||
|
public void UnsubscribedPrimary_WithFactory_FailsBackOnlyAfterFreshSubscribeSucceeds()
|
||||||
|
{
|
||||||
|
WnWrapShapedPrimary failed = new WnWrapShapedPrimary { FailSubscribe = true };
|
||||||
|
List<WnWrapShapedPrimary> built = new List<WnWrapShapedPrimary>();
|
||||||
|
bool alarmManagerUp = false;
|
||||||
|
StubStandby standby = new StubStandby();
|
||||||
|
FailoverSettings settings = new FailoverSettings(threshold: 1, probeIntervalSeconds: 0, stableProbes: 2);
|
||||||
|
using FailoverAlarmConsumer sut = new FailoverAlarmConsumer(
|
||||||
|
failed,
|
||||||
|
standby,
|
||||||
|
settings,
|
||||||
|
() =>
|
||||||
|
{
|
||||||
|
WnWrapShapedPrimary next = new WnWrapShapedPrimary { FailSubscribe = !alarmManagerUp };
|
||||||
|
built.Add(next);
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
|
||||||
|
List<AlarmProviderModeChange> changes = new List<AlarmProviderModeChange>();
|
||||||
|
sut.ProviderModeChanged += (_, e) => changes.Add(e);
|
||||||
|
|
||||||
|
sut.Subscribe(@"\\HOST\Galaxy!Area"); // threshold=1 → Subtag
|
||||||
|
Assert.Equal(AlarmProviderMode.Subtag, sut.Mode);
|
||||||
|
|
||||||
|
// Alarm manager still down: each probe rebuilds, the subscribe fails, no clean probe.
|
||||||
|
sut.ProbeOnce();
|
||||||
|
sut.ProbeOnce();
|
||||||
|
Assert.Equal(AlarmProviderMode.Subtag, sut.Mode);
|
||||||
|
Assert.True(failed.Disposed);
|
||||||
|
Assert.Equal(1, failed.SubscribeCount);
|
||||||
|
Assert.Equal(2, built.Count);
|
||||||
|
Assert.True(built[0].Disposed);
|
||||||
|
|
||||||
|
// Alarm manager back: the next rebuild subscribes and the clean run starts.
|
||||||
|
alarmManagerUp = true;
|
||||||
|
sut.ProbeOnce(); // fresh subscribe + clean poll 1
|
||||||
|
Assert.Equal(AlarmProviderMode.Subtag, sut.Mode);
|
||||||
|
sut.ProbeOnce(); // clean poll 2 → failback
|
||||||
|
|
||||||
|
Assert.Equal(AlarmProviderMode.Alarmmgr, sut.Mode);
|
||||||
|
Assert.Equal(3, built.Count);
|
||||||
|
WnWrapShapedPrimary live = built[2];
|
||||||
|
Assert.False(live.Disposed);
|
||||||
|
Assert.Equal(1, live.SubscribeCount);
|
||||||
|
Assert.Equal(2, live.ComPolls);
|
||||||
|
|
||||||
|
// The rebuilt primary's transitions are the ones forwarded now.
|
||||||
|
MxAlarmTransitionEvent? forwarded = null;
|
||||||
|
sut.AlarmTransitionEmitted += (_, e) => forwarded = e;
|
||||||
|
MxAlarmTransitionEvent transition = SampleTransition();
|
||||||
|
live.Raise(transition);
|
||||||
|
Assert.Same(transition, forwarded);
|
||||||
|
Assert.Equal(AlarmProviderMode.Alarmmgr, changes[changes.Count - 1].Mode);
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>Proves that the consumer switches to the subtag standby after the primary fails the configured threshold of consecutive times.</summary>
|
/// <summary>Proves that the consumer switches to the subtag standby after the primary fails the configured threshold of consecutive times.</summary>
|
||||||
[Fact]
|
[Fact]
|
||||||
public void Primary_FailsThresholdTimes_SwitchesToSubtag()
|
public void Primary_FailsThresholdTimes_SwitchesToSubtag()
|
||||||
@@ -209,10 +404,11 @@ public sealed class FailoverAlarmConsumerTests
|
|||||||
[Fact]
|
[Fact]
|
||||||
public void WhileDegraded_PrimaryHeals_FailsBackAfterStableProbes()
|
public void WhileDegraded_PrimaryHeals_FailsBackAfterStableProbes()
|
||||||
{
|
{
|
||||||
// threshold=1 so the initial Subscribe failure (PollOnce path) immediately
|
// The primary subscribes, then its polls start failing: threshold=1 so
|
||||||
// switches to Subtag. stableProbes=2 means two consecutive clean PollOnce
|
// the first failed poll switches to Subtag. stableProbes=2 means two
|
||||||
// calls are needed before failback. ProbeOnce must NOT call Subscribe —
|
// consecutive clean PollOnce calls are needed before failback. ProbeOnce
|
||||||
// WnWrapAlarmConsumer is single-subscribe; re-calling would always throw.
|
// must NOT call Subscribe on the subscribed primary — WnWrapAlarmConsumer
|
||||||
|
// is single-subscribe; re-calling would always throw.
|
||||||
FlakyPrimary primary = new FlakyPrimary { ThrowOnPoll = true };
|
FlakyPrimary primary = new FlakyPrimary { ThrowOnPoll = true };
|
||||||
StubStandby standby = new StubStandby();
|
StubStandby standby = new StubStandby();
|
||||||
FailoverSettings settings = new FailoverSettings(threshold: 1, probeIntervalSeconds: 0, stableProbes: 2);
|
FailoverSettings settings = new FailoverSettings(threshold: 1, probeIntervalSeconds: 0, stableProbes: 2);
|
||||||
@@ -221,7 +417,7 @@ public sealed class FailoverAlarmConsumerTests
|
|||||||
List<AlarmProviderModeChange> changes = new List<AlarmProviderModeChange>();
|
List<AlarmProviderModeChange> changes = new List<AlarmProviderModeChange>();
|
||||||
sut.ProviderModeChanged += (_, e) => changes.Add(e);
|
sut.ProviderModeChanged += (_, e) => changes.Add(e);
|
||||||
|
|
||||||
sut.Subscribe(@"\\HOST\Galaxy!Area"); // threshold=1 → Subtag (mode change 1)
|
FailOverAfterHealthySubscribe(sut, primary); // threshold=1 → Subtag (mode change 1)
|
||||||
Assert.Single(changes);
|
Assert.Single(changes);
|
||||||
Assert.Equal(AlarmProviderMode.Subtag, changes[changes.Count - 1].Mode);
|
Assert.Equal(AlarmProviderMode.Subtag, changes[changes.Count - 1].Mode);
|
||||||
|
|
||||||
@@ -279,16 +475,17 @@ public sealed class FailoverAlarmConsumerTests
|
|||||||
[Fact]
|
[Fact]
|
||||||
public void ProbeOnce_DoesNotCallPrimarySubscribe()
|
public void ProbeOnce_DoesNotCallPrimarySubscribe()
|
||||||
{
|
{
|
||||||
// threshold=1 → first Subscribe failure immediately switches to Subtag.
|
// threshold=1 → the first failed poll after a successful subscribe
|
||||||
|
// switches to Subtag.
|
||||||
FlakyPrimary primary = new FlakyPrimary { ThrowOnPoll = true };
|
FlakyPrimary primary = new FlakyPrimary { ThrowOnPoll = true };
|
||||||
StubStandby standby = new StubStandby();
|
StubStandby standby = new StubStandby();
|
||||||
FailoverSettings settings = new FailoverSettings(threshold: 1, probeIntervalSeconds: 0, stableProbes: 3);
|
FailoverSettings settings = new FailoverSettings(threshold: 1, probeIntervalSeconds: 0, stableProbes: 3);
|
||||||
using FailoverAlarmConsumer sut = new FailoverAlarmConsumer(primary, standby, settings);
|
using FailoverAlarmConsumer sut = new FailoverAlarmConsumer(primary, standby, settings);
|
||||||
|
|
||||||
sut.Subscribe(@"\\HOST\Galaxy!Area"); // Subscribe attempt (throws) → Subtag
|
FailOverAfterHealthySubscribe(sut, primary);
|
||||||
|
|
||||||
// Capture how many Subscribe calls the initial setup caused (exactly 1:
|
// Capture how many Subscribe calls the initial setup caused (exactly 1:
|
||||||
// the attempt that threw and triggered failover).
|
// the successful subscribe before the polls failed).
|
||||||
int subscribeCountAfterSetup = primary.SubscribeCount;
|
int subscribeCountAfterSetup = primary.SubscribeCount;
|
||||||
Assert.Equal(1, subscribeCountAfterSetup);
|
Assert.Equal(1, subscribeCountAfterSetup);
|
||||||
Assert.Equal(AlarmProviderMode.Subtag, sut.Mode);
|
Assert.Equal(AlarmProviderMode.Subtag, sut.Mode);
|
||||||
@@ -379,7 +576,7 @@ public sealed class FailoverAlarmConsumerTests
|
|||||||
var primary = new FlakyPrimary { ThrowOnPoll = true };
|
var primary = new FlakyPrimary { ThrowOnPoll = true };
|
||||||
var standby = new StubStandby();
|
var standby = new StubStandby();
|
||||||
using var sut = new FailoverAlarmConsumer(primary, standby, new FailoverSettings(threshold: 1, probeIntervalSeconds: 0, stableProbes: 3));
|
using var sut = new FailoverAlarmConsumer(primary, standby, new FailoverSettings(threshold: 1, probeIntervalSeconds: 0, stableProbes: 3));
|
||||||
sut.Subscribe(@"\\HOST\Galaxy!Area"); // threshold=1 → switch to Subtag
|
FailOverAfterHealthySubscribe(sut, primary); // threshold=1 → switch to Subtag
|
||||||
Assert.Equal(AlarmProviderMode.Subtag, sut.Mode);
|
Assert.Equal(AlarmProviderMode.Subtag, sut.Mode);
|
||||||
|
|
||||||
primary.ThrowOnPoll = false;
|
primary.ThrowOnPoll = false;
|
||||||
@@ -478,14 +675,15 @@ public sealed class FailoverAlarmConsumerTests
|
|||||||
FailoverSettings settings = new FailoverSettings(threshold: 1, probeIntervalSeconds: 3600, stableProbes: 5);
|
FailoverSettings settings = new FailoverSettings(threshold: 1, probeIntervalSeconds: 3600, stableProbes: 5);
|
||||||
using FailoverAlarmConsumer sut = new FailoverAlarmConsumer(primary, standby, settings);
|
using FailoverAlarmConsumer sut = new FailoverAlarmConsumer(primary, standby, settings);
|
||||||
|
|
||||||
sut.Subscribe(@"\\HOST\Galaxy!Area"); // threshold=1 → switch to Subtag
|
FailOverAfterHealthySubscribe(sut, primary); // threshold=1 → switch to Subtag
|
||||||
Assert.Equal(AlarmProviderMode.Subtag, sut.Mode);
|
Assert.Equal(AlarmProviderMode.Subtag, sut.Mode);
|
||||||
|
|
||||||
primary.ThrowOnPoll = false; // primary healthy so a probe would poll cleanly
|
primary.ThrowOnPoll = false; // primary healthy so a probe would poll cleanly
|
||||||
|
int pollsBeforeProbe = primary.Polls;
|
||||||
|
|
||||||
sut.ProbeOnce(); // first probe runs: re-polls the primary
|
sut.ProbeOnce(); // first probe runs: re-polls the primary
|
||||||
int pollsAfterFirstProbe = primary.Polls;
|
int pollsAfterFirstProbe = primary.Polls;
|
||||||
Assert.Equal(1, pollsAfterFirstProbe);
|
Assert.Equal(pollsBeforeProbe + 1, pollsAfterFirstProbe);
|
||||||
|
|
||||||
sut.ProbeOnce(); // within the 3600s interval → throttled, must NOT re-poll
|
sut.ProbeOnce(); // within the 3600s interval → throttled, must NOT re-poll
|
||||||
|
|
||||||
|
|||||||
@@ -255,7 +255,9 @@ public sealed class AlarmCommandHandler : IAlarmCommandHandler
|
|||||||
failoverConfig?.ConsecutiveFailureThreshold ?? 3,
|
failoverConfig?.ConsecutiveFailureThreshold ?? 3,
|
||||||
failoverConfig?.FailbackProbeIntervalSeconds ?? 30,
|
failoverConfig?.FailbackProbeIntervalSeconds ?? 30,
|
||||||
failoverConfig?.FailbackStableProbes ?? 3);
|
failoverConfig?.FailbackStableProbes ?? 3);
|
||||||
return new FailoverAlarmConsumer(primary, standby, settings);
|
// The factory lets the composite replace a primary whose
|
||||||
|
// Subscribe failed with a fresh wnwrap instance (MXA-001).
|
||||||
|
return new FailoverAlarmConsumer(primary, standby, settings, consumerFactory);
|
||||||
}
|
}
|
||||||
catch
|
catch
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -54,11 +54,21 @@ public sealed class FailoverAlarmConsumer : IMxAccessAlarmConsumer
|
|||||||
Standby,
|
Standby,
|
||||||
}
|
}
|
||||||
|
|
||||||
private readonly IMxAccessAlarmConsumer primary;
|
private readonly Func<IMxAccessAlarmConsumer>? primaryFactory;
|
||||||
|
private IMxAccessAlarmConsumer primary;
|
||||||
private IMxAccessAlarmConsumer standby;
|
private IMxAccessAlarmConsumer standby;
|
||||||
private readonly FailoverSettings settings;
|
private readonly FailoverSettings settings;
|
||||||
|
|
||||||
private Active active = Active.Primary;
|
private Active active = Active.Primary;
|
||||||
|
|
||||||
|
// Whether the CURRENT primary instance completed Subscribe. A primary whose
|
||||||
|
// Subscribe failed is not a healthy primary that happens to be quiet: the
|
||||||
|
// wnwrap consumer's PollOnce returns without touching COM until it is
|
||||||
|
// subscribed, so polling it would read as success, reset the failure
|
||||||
|
// counter, and (while degraded) count as a clean failback probe (MXA-001).
|
||||||
|
private bool primarySubscribed;
|
||||||
|
private int lastPrimarySubscribeHResult;
|
||||||
|
private string subscription = string.Empty;
|
||||||
private AlarmProviderMode mode = AlarmProviderMode.Alarmmgr;
|
private AlarmProviderMode mode = AlarmProviderMode.Alarmmgr;
|
||||||
private int consecutiveFailures;
|
private int consecutiveFailures;
|
||||||
private int cleanProbes;
|
private int cleanProbes;
|
||||||
@@ -75,8 +85,34 @@ public sealed class FailoverAlarmConsumer : IMxAccessAlarmConsumer
|
|||||||
IMxAccessAlarmConsumer primary,
|
IMxAccessAlarmConsumer primary,
|
||||||
IMxAccessAlarmConsumer standby,
|
IMxAccessAlarmConsumer standby,
|
||||||
FailoverSettings settings)
|
FailoverSettings settings)
|
||||||
|
: this(primary, standby, settings, primaryFactory: null)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Composes the failover consumer over its two children, with a factory
|
||||||
|
/// that builds a fresh primary when the current one never subscribed.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="primary">The PRIMARY (alarmmgr) consumer.</param>
|
||||||
|
/// <param name="standby">The STANDBY (subtag) consumer.</param>
|
||||||
|
/// <param name="settings">The failover/failback tunables.</param>
|
||||||
|
/// <param name="primaryFactory">
|
||||||
|
/// Builds a replacement primary after a failed <c>Subscribe</c>. The
|
||||||
|
/// wnwrap primary is single-subscribe and a failed subscribe can leave it
|
||||||
|
/// half-registered, so recovery disposes the failed instance (which
|
||||||
|
/// deregisters it) and subscribes a new one rather than re-subscribing
|
||||||
|
/// the same object. <see langword="null"/> means a primary whose
|
||||||
|
/// subscribe failed can never recover within this consumer's lifetime:
|
||||||
|
/// it keeps counting as a failure and is never failed back to.
|
||||||
|
/// </param>
|
||||||
|
public FailoverAlarmConsumer(
|
||||||
|
IMxAccessAlarmConsumer primary,
|
||||||
|
IMxAccessAlarmConsumer standby,
|
||||||
|
FailoverSettings settings,
|
||||||
|
Func<IMxAccessAlarmConsumer>? primaryFactory)
|
||||||
{
|
{
|
||||||
this.primary = primary ?? throw new ArgumentNullException(nameof(primary));
|
this.primary = primary ?? throw new ArgumentNullException(nameof(primary));
|
||||||
|
this.primaryFactory = primaryFactory;
|
||||||
this.standby = standby ?? throw new ArgumentNullException(nameof(standby));
|
this.standby = standby ?? throw new ArgumentNullException(nameof(standby));
|
||||||
this.settings = settings ?? throw new ArgumentNullException(nameof(settings));
|
this.settings = settings ?? throw new ArgumentNullException(nameof(settings));
|
||||||
|
|
||||||
@@ -138,22 +174,23 @@ public sealed class FailoverAlarmConsumer : IMxAccessAlarmConsumer
|
|||||||
{
|
{
|
||||||
if (disposed) throw new ObjectDisposedException(nameof(FailoverAlarmConsumer));
|
if (disposed) throw new ObjectDisposedException(nameof(FailoverAlarmConsumer));
|
||||||
|
|
||||||
// The primary is not torn down on failover and is therefore never
|
// Retained so a primary whose subscribe failed can be rebuilt and
|
||||||
// re-subscribed during ProbeOnce, so the subscription expression does
|
// subscribed later (EnsurePrimarySubscribed). A primary that did
|
||||||
// not need to be retained here.
|
// subscribe is never re-subscribed: failover does not tear it down.
|
||||||
|
this.subscription = subscription ?? string.Empty;
|
||||||
|
|
||||||
// Arm the standby first so it is warm regardless of primary outcome.
|
// Arm the standby first so it is warm regardless of primary outcome.
|
||||||
// A standby subscribe failure is a hard fault (the fallback itself is
|
// A standby subscribe failure is a hard fault (the fallback itself is
|
||||||
// broken) and is surfaced to the caller; it does not feed the primary
|
// broken) and is surfaced to the caller; it does not feed the primary
|
||||||
// failover counter.
|
// failover counter.
|
||||||
standby.Subscribe(subscription);
|
standby.Subscribe(this.subscription);
|
||||||
|
|
||||||
// Drive the primary subscribe through the failure-counting wrapper so
|
// Drive the primary subscribe through the failure-counting wrapper so
|
||||||
// a COM failure here counts toward the failover threshold instead of
|
// a COM failure here counts toward the failover threshold instead of
|
||||||
// escaping. Swallowing the exception is deliberate: the standby is
|
// escaping. Swallowing the exception is deliberate: the standby is
|
||||||
// already armed, so a failed primary subscribe just nudges the state
|
// already armed, so a failed primary subscribe just nudges the state
|
||||||
// machine toward (or into) standby rather than aborting startup.
|
// machine toward (or into) standby rather than aborting startup.
|
||||||
RunPrimary(() => primary.Subscribe(subscription), "Subscribe");
|
RunPrimary(SubscribePrimary, "Subscribe");
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
@@ -163,7 +200,16 @@ public sealed class FailoverAlarmConsumer : IMxAccessAlarmConsumer
|
|||||||
|
|
||||||
if (active == Active.Primary)
|
if (active == Active.Primary)
|
||||||
{
|
{
|
||||||
RunPrimary(() => primary.PollOnce(), "PollOnce");
|
// An unsubscribed primary is a failure, not a quiet success: retry
|
||||||
|
// its subscribe (on a fresh instance) or count the failure, so the
|
||||||
|
// threshold is reached and failover engages (MXA-001).
|
||||||
|
RunPrimary(
|
||||||
|
() =>
|
||||||
|
{
|
||||||
|
EnsurePrimarySubscribed();
|
||||||
|
primary.PollOnce();
|
||||||
|
},
|
||||||
|
"PollOnce");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -211,13 +257,14 @@ public sealed class FailoverAlarmConsumer : IMxAccessAlarmConsumer
|
|||||||
/// successful initial subscribe).
|
/// successful initial subscribe).
|
||||||
/// </para>
|
/// </para>
|
||||||
/// <para>
|
/// <para>
|
||||||
/// <strong>Known v1 limitation.</strong> If the <em>original</em>
|
/// <strong>A primary that never subscribed.</strong> If the
|
||||||
/// <c>Subscribe</c> itself failed (i.e., the primary never reached a
|
/// <em>original</em> <c>Subscribe</c> failed, the primary is not
|
||||||
/// subscribed state — only reachable when
|
/// subscribed and its <c>PollOnce</c> would return without touching
|
||||||
/// <see cref="FailoverSettings.Threshold"/> is 1), polling alone
|
/// COM — a silent "success". The probe therefore first rebuilds and
|
||||||
/// cannot re-establish the subscription. That edge case is accepted
|
/// subscribes a fresh primary through the primary factory; until that
|
||||||
/// for v1: the operator must restart the session to force a fresh
|
/// succeeds every probe fails, so the consumer never announces
|
||||||
/// subscribe attempt.
|
/// "recovered" onto a dead primary (MXA-001). Without a factory the
|
||||||
|
/// primary cannot recover and the consumer stays on the standby.
|
||||||
/// </para>
|
/// </para>
|
||||||
/// </remarks>
|
/// </remarks>
|
||||||
public void ProbeOnce()
|
public void ProbeOnce()
|
||||||
@@ -237,10 +284,13 @@ public sealed class FailoverAlarmConsumer : IMxAccessAlarmConsumer
|
|||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
// Re-poll the still-subscribed primary. Do NOT call Subscribe —
|
// Re-poll the still-subscribed primary. Do NOT call Subscribe on a
|
||||||
// WnWrapAlarmConsumer is single-subscribe and the primary remains
|
// subscribed primary — WnWrapAlarmConsumer is single-subscribe and
|
||||||
// subscribed across the failover; calling Subscribe again would
|
// the primary remains subscribed across the failover; calling
|
||||||
// always throw InvalidOperationException and prevent failback.
|
// Subscribe again would always throw InvalidOperationException and
|
||||||
|
// prevent failback. Only a primary that never subscribed is
|
||||||
|
// replaced and subscribed here.
|
||||||
|
EnsurePrimarySubscribed();
|
||||||
primary.PollOnce();
|
primary.PollOnce();
|
||||||
}
|
}
|
||||||
catch (Exception)
|
catch (Exception)
|
||||||
@@ -281,6 +331,58 @@ public sealed class FailoverAlarmConsumer : IMxAccessAlarmConsumer
|
|||||||
|
|
||||||
private IMxAccessAlarmConsumer ActiveChild => active == Active.Primary ? primary : standby;
|
private IMxAccessAlarmConsumer ActiveChild => active == Active.Primary ? primary : standby;
|
||||||
|
|
||||||
|
// Subscribes the current primary instance, recording the outcome so later
|
||||||
|
// polls and probes can tell a quiet primary from one that never subscribed.
|
||||||
|
private void SubscribePrimary()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
primary.Subscribe(subscription);
|
||||||
|
}
|
||||||
|
catch (COMException ex)
|
||||||
|
{
|
||||||
|
lastPrimarySubscribeHResult = ex.HResult;
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||||
|
{
|
||||||
|
lastPrimarySubscribeHResult = ex.InnerException is COMException inner ? inner.HResult : 0;
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
|
||||||
|
primarySubscribed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Brings the primary to a subscribed state or throws. A subscribed primary
|
||||||
|
// is left alone. A primary whose subscribe failed is disposed (which
|
||||||
|
// deregisters the wnwrap consumer it may have half-registered) and replaced
|
||||||
|
// by a fresh instance from the factory, which is then subscribed. With no
|
||||||
|
// factory the failure is reported again, carrying the original subscribe
|
||||||
|
// HRESULT, so the counters see a failure instead of a no-op poll.
|
||||||
|
private void EnsurePrimarySubscribed()
|
||||||
|
{
|
||||||
|
if (primarySubscribed) return;
|
||||||
|
|
||||||
|
if (primaryFactory is null)
|
||||||
|
{
|
||||||
|
throw new PrimaryNotSubscribedException(lastPrimarySubscribeHResult);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build the replacement before releasing the failed instance, so a
|
||||||
|
// factory failure leaves a usable (if unsubscribed) primary behind for
|
||||||
|
// snapshot and ack-target reads rather than a disposed one.
|
||||||
|
IMxAccessAlarmConsumer replacement = primaryFactory()
|
||||||
|
?? throw new InvalidOperationException("Alarm primary consumer factory returned null.");
|
||||||
|
|
||||||
|
IMxAccessAlarmConsumer failed = primary;
|
||||||
|
try { failed.AlarmTransitionEmitted -= OnChildTransition; } catch { /* best effort */ }
|
||||||
|
try { failed.Dispose(); } catch { /* the replacement is what matters */ }
|
||||||
|
|
||||||
|
primary = replacement;
|
||||||
|
replacement.AlarmTransitionEmitted += OnChildTransition;
|
||||||
|
SubscribePrimary();
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Runs a primary COM action, counting consecutive failures. A
|
/// Runs a primary COM action, counting consecutive failures. A
|
||||||
/// <see cref="COMException"/> (or any exception, treated as a COM
|
/// <see cref="COMException"/> (or any exception, treated as a COM
|
||||||
@@ -297,7 +399,7 @@ public sealed class FailoverAlarmConsumer : IMxAccessAlarmConsumer
|
|||||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||||
{
|
{
|
||||||
consecutiveFailures++;
|
consecutiveFailures++;
|
||||||
int hresult = ex is COMException ? ex.HResult : 0;
|
int hresult = ex is COMException or PrimaryNotSubscribedException ? ex.HResult : 0;
|
||||||
if (active == Active.Primary && consecutiveFailures >= settings.Threshold)
|
if (active == Active.Primary && consecutiveFailures >= settings.Threshold)
|
||||||
{
|
{
|
||||||
SwitchToStandby($"primary {operation} failed", hresult);
|
SwitchToStandby($"primary {operation} failed", hresult);
|
||||||
@@ -403,4 +505,19 @@ public sealed class FailoverAlarmConsumer : IMxAccessAlarmConsumer
|
|||||||
primary.Dispose();
|
primary.Dispose();
|
||||||
standby.Dispose();
|
standby.Dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Raised when the primary is polled or probed while it has never
|
||||||
|
/// completed <c>Subscribe</c> and cannot be rebuilt. Carries the HRESULT
|
||||||
|
/// of the failed subscribe so the provider-mode change reports the
|
||||||
|
/// original cause.
|
||||||
|
/// </summary>
|
||||||
|
private sealed class PrimaryNotSubscribedException : InvalidOperationException
|
||||||
|
{
|
||||||
|
public PrimaryNotSubscribedException(int hresult)
|
||||||
|
: base("The alarm-manager primary never completed Subscribe and cannot be rebuilt.")
|
||||||
|
{
|
||||||
|
HResult = hresult;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user