Merge fix/review-2026-12-phase3 (2026-12-02 review fix plan)

This commit is contained in:
Joseph Doherty
2026-12-03 10:18:43 -05:00
25 changed files with 2328 additions and 125 deletions
+28 -4
View File
@@ -900,10 +900,16 @@ MXAccess item addresses for the `InAlarm`, `Acked`, `AckMsg`, and `Priority`
subtags (confirmed AVEVA `AlarmExtension` field names, verified against the live
ZB Galaxy `attribute_definition` rows).
The gateway refreshes this list on the existing alarm reconciliation cadence
and immediately before publishing a failover-to-subtag status. It compares a
canonical fingerprint of all six target fields and sends
`UpdateAlarmWatchListCommand` only for a material change. The worker constructs,
The gateway refreshes this list on the alarm reconciliation cadence, on a loop
of its own so a slow or hung Galaxy SQL query never delays a reconcile pass, and
immediately before publishing a failover-to-subtag status (bounded to 10 seconds,
after which the status is published with the last acknowledged list and the
periodic loop retries). The resolver caches a successful resolution against the
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
@@ -979,6 +985,24 @@ MXAccess does not guarantee the `Acked = false` update arrives before the
`InAlarm = false` update. The latch ensures a clear always emits `ACK_RTN`
when the alarm was acknowledged at any point during the active episode.
**Initial sync.** The first `InAlarm` value after subscribe is the alarm's
current state, not an observed raise. An alarm that is already active and
acknowledged can deliver `Acked = true` before `InAlarm = true`, and no later
`Acked` change arrives to correct it. So an `Acked = true` buffered before the
first `InAlarm` value is kept when that value is `true`: the raise is reported
as `ACK_ALM` (a Raise of an acknowledged alarm) and the latch is set. Any raise
after the first `InAlarm` value is a new episode and starts unacknowledged.
**Quality.** An `InAlarm` or `Acked` update whose MXAccess quality is not good
(OPC quality bits `0xC0` not both set — bad or uncertain), or whose value is
empty, is ignored and the alarm keeps its last known state. MXAccess reports an
engine going off scan or a reference becoming unresolved this way. Coercing the
empty value to `false` would report every active alarm on that object as
returned to normal, and the gateway's reconcile would confirm it from the
standby snapshot. The subtag provider already reports `degraded = true` on every
record, so holding state adds no new signal. Priority updates fall back to the
last known priority as before.
`SnapshotActive()` returns one `MxAlarmSnapshotRecord` per currently-active
alarm. State mapping:
+5 -2
View File
@@ -223,7 +223,10 @@ healthy subscribers. With `DisconnectSubscriber`, overflow terminates only the
affected stream while the MXAccess session remains active.
`ReplayBufferCapacity`, `ReplayRetentionSeconds` and `ReplayBufferMaxBytes` must
each be greater than or equal to zero (any dimension can be disabled with `0`). A returning subscriber
each be greater than or equal to zero (any dimension can be disabled with `0`).
`ReplayRetentionSeconds` is also capped at 86,400 (one day) and must be finite, so
an out-of-range value fails at startup instead of failing every `StreamEvents`
when the replay ring is first built. A returning subscriber
that asks for events older than the oldest still-retained event is told it missed
events (a "gap") and must re-snapshot; whatever is still retained is replayed.
@@ -530,7 +533,7 @@ behavior.
| `MxGateway:Alarms:Enabled` | `false` | Gates the gateway's always-on central alarm monitor. When `true`, the gateway opens one gateway-owned worker session dedicated to alarms, caches the active-alarm set, and fans it out to every client through the `StreamAlarms` RPC — no client opens its own session to see alarms. |
| `MxGateway:Alarms:SubscriptionExpression` | _(empty)_ | AVEVA alarm-subscription expression the monitor subscribes on startup, in canonical `\\<machine>\Galaxy!<area>` form. The literal `Galaxy` provider is correct regardless of the Galaxy database name. When empty and `Enabled` is `true`, the gateway falls back to `\\<MachineName>\Galaxy!<DefaultArea>` if `DefaultArea` is set. |
| `MxGateway:Alarms:DefaultArea` | _(empty)_ | Area name used to compose a default subscription when `SubscriptionExpression` is empty. If both are empty while `Enabled` is `true`, the monitor faults with a configuration diagnostic. |
| `MxGateway:Alarms:ReconcileIntervalSeconds` | `30` | How often the monitor re-resolves and, on material change, hot-swaps the subtag fallback watch-list, then reconciles its in-process alarm cache against the worker's authoritative active-alarm snapshot. The acknowledged watch-list fingerprint advances only after an OK worker reply. Floored at 5 seconds. |
| `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: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`. |
+1 -1
View File
@@ -274,7 +274,7 @@ bearer). Each hub class is `[Authorize(Policy = HubClientsPolicy)]`.
| Hub | Path | Producer | Payload | Routing |
|---|---|---|---|---|
| `DashboardSnapshotHub` | `/hubs/snapshot` | `DashboardSnapshotPublisher` (BackgroundService consuming `IDashboardSnapshotService.WatchSnapshotsAsync`) | `SnapshotUpdated`: `DashboardSnapshot` **without** `configuration`; `ConfigurationUpdated`: `EffectiveGatewayConfiguration` | Ticks go to all connected clients on every snapshot interval, but only while at least one client is connected (see "Idle gating" below). The effective configuration is startup-static and the largest part of the record, so it is `[JsonIgnore]`d on `DashboardSnapshot` and sent once per connection instead: `OnConnectedAsync` pushes `ConfigurationUpdated` and then the current `SnapshotUpdated`, and the hub method `GetConfiguration()` returns it on demand. Each tick broadcast is bounded to 1 s; a send that misses the bound is abandoned, so one slow client cannot delay the next tick for everyone. |
| `AlarmsHub` | `/hubs/alarms` | `AlarmsHubPublisher` (BackgroundService consuming `IGatewayAlarmService.StreamAsync(filter: null)`) | `AlarmFeedMessage` (`active_alarm` / `snapshot_complete` / `transition` / `provider_status` / `snapshot_status`) | Guarded by `MxGateway.Dashboard.Alarms`, not `HubClients`: a real authenticated dashboard role is required, so the `Authentication:Mode=Disabled` and anonymous-localhost bypasses are excluded (SEC-40). Connected clients auto-join `__alarms__`; all admitted clients receive every message — the feed is galaxy-wide and carries no session provenance, so no per-caller scoping applies (see "Alarm-feed visibility"). Publisher auto-reconnects every 5s on stream faults. Every subscription to the monitor — the first and each resubscribe — is preceded by an `AlarmFeedReset` frame (`{ generation }`, monotonic per process): the monitor primes each new subscription with a full `active_alarm` snapshot ending in `snapshot_complete`, so a client must discard its accumulated alarm state on the marker and rebuild from that snapshot rather than double-counting it. Each broadcast is bounded to 2 s and abandoned on timeout: awaiting it unbounded let one slow client stall the drain until the monitor dropped the publisher as a slow subscriber, and the resubscribe then replayed the whole snapshot to every client. The tradeoff: a client whose send is abandoned misses that one frame and receives no reset for it, so its alarm view can be stale until the next resubscribe (or until SignalR drops the stalled connection); there is no in-family consumer of `/hubs/alarms` today. The alarm value fields (`current_value` / `limit_value`) are stripped from a deep-cloned copy of the message when `Dashboard:ShowTagValues` is false (the default) — on both value-bearing payload arms, so neither a live transition nor a snapshot record leaks a process value; every other field still renders. The source message is never mutated: it fans out from the same feed to gRPC `StreamAlarms` subscribers, which this dashboard-display flag does not govern. Arms carrying no value are forwarded as-is, uncloned. |
| `AlarmsHub` | `/hubs/alarms` | `AlarmsHubPublisher` (BackgroundService consuming `IGatewayAlarmService.StreamAsync(filter: null)`) | `AlarmFeedMessage` (`active_alarm` / `snapshot_complete` / `transition` / `provider_status` / `snapshot_status`) | Guarded by `MxGateway.Dashboard.Alarms`, not `HubClients`: a real authenticated dashboard role is required, so the `Authentication:Mode=Disabled` and anonymous-localhost bypasses are excluded (SEC-40). Connected clients auto-join `__alarms__`; all admitted clients receive every message — the feed is galaxy-wide and carries no session provenance, so no per-caller scoping applies (see "Alarm-feed visibility"). Publisher auto-reconnects every 5s on stream faults. Every subscription to the monitor — the first and each resubscribe — is preceded by an `AlarmFeedReset` frame (`{ generation }`, monotonic per process): the monitor primes each new subscription with a full `active_alarm` snapshot ending in `snapshot_complete`, so a client must discard its accumulated alarm state on the marker and rebuild from that snapshot rather than double-counting it. The publisher's subscription normally opens before any browser connects, so `AlarmsHub.OnConnectedAsync` also primes each new connection itself: it joins the group, sends that client an `AlarmFeedReset` with generation `0`, then the provider status, snapshot status, `active_alarm` rows and `snapshot_complete` read from a fresh monitor subscription (redacted by the same rule). Without it a client connecting after startup saw only later transitions and never the standing alarms or the current provider status. The reset goes out before the snapshot is read, so a transition is either in the snapshot or arrives live after the reset; one applied while the snapshot rows are being sent can land ahead of the older row for the same alarm, which the alarm's next transition or reconcile repair corrects. Each broadcast is bounded to 2 s and abandoned on timeout: awaiting it unbounded let one slow client stall the drain until the monitor dropped the publisher as a slow subscriber, and the resubscribe then replayed the whole snapshot to every client. The tradeoff: a client whose send is abandoned misses that one frame and receives no reset for it, so its alarm view can be stale until the next resubscribe (or until SignalR drops the stalled connection); there is no in-family consumer of `/hubs/alarms` today. The alarm value fields (`current_value` / `limit_value`) are stripped from a deep-cloned copy of the message when `Dashboard:ShowTagValues` is false (the default) — on both value-bearing payload arms, so neither a live transition nor a snapshot record leaks a process value; every other field still renders. The source message is never mutated: it fans out from the same feed to gRPC `StreamAlarms` subscribers, which this dashboard-display flag does not govern. Arms carrying no value are forwarded as-is, uncloned. |
| `EventsHub` | `/hubs/events` | `DashboardEventBroadcaster` invoked by each session's internal dashboard-mirror subscriber on its `SessionEventDistributor` (registered when the session becomes Ready) | `MxEvent` | Clients call `SubscribeSession(sessionId)` to join `session:{id}`, which also registers them in `EventsHubViewerRegistry`. Delivery to the group goes through one bounded per-session pump (see "Mirror gating"), so a slow viewer loses its oldest events instead of accumulating pending sends — the mirror is gated on that registry, which counts hub and in-process viewers alike (see "Mirror gating" below). The dashboard is a first-class distributor subscriber, so it receives the session's events whether or not a gRPC client is streaming. It sees RAW session events — not the per-gRPC-subscriber `AfterWorkerSequence` filtering that `EventStreamService` applies at its own boundary — because the dashboard is a separate LDAP-authenticated monitoring view meant to show the session's full event activity. Tag values are stripped from the mirrored `MxEvent` copy by `DashboardEventBroadcaster` when `Dashboard:ShowTagValues` is false (the default) — event metadata (tag reference, quality, status, timestamps) still renders, but the value fields are blanked, so no value leaks through this seam. `SubscribeSession` is gated by `IDashboardSessionAcl` (SEC-25 / TST-15): a denied caller gets a `HubException`, is not joined to the group, and is not registered as a viewer, so the mirror stays off for a session nobody is legitimately watching. The same ACL gates the in-process seam the session-details page uses, so neither path is the weaker one. Value redaction remains an independent layer — it bounds what a *permitted* subscriber sees. |
No hub client ships in this repository: the server-rendered pages read the
+47 -4
View File
@@ -193,6 +193,44 @@ at-least-once: alarm-feed consumers (`StreamAlarms` clients and the dashboard
alarm hub) must apply transitions idempotently — treat one as "set this alarm to
this state", never as an increment or a toggle.
**Reconcile snapshots are versioned against the live feed.** The reply to
`QueryActiveAlarms` and a later live transition travel different paths, so a
snapshot can land after a transition it predates. Every live transition takes a
monotonic sequence number and stamps its alarm; a reconcile captures the sequence
before it sends the command, and leaves any alarm stamped after that capture
alone — no synthetic Clear for an alarm a newer live Raise added, no re-raise for
one a newer live Clear removed. The next pass reconciles it. A pass also treats a
changed original raise timestamp as a new instance (a Raise repair even when the
state is unchanged), and an alarm that is not in the cache is repaired as a Raise
followed by an Acknowledge when the worker reports it already acknowledged. A live
`Acknowledge` for an alarm the cache does not hold (an ack of an alarm that already
returned to normal) is forwarded on the feed but does not create a cache entry.
A non-OK reconcile reply is logged and surfaced on the monitor's `LastError`; on
the initial reconcile of a lifecycle it fails the lifecycle instead of entering
`Monitoring` with an empty cache.
**Monitor restart diffs instead of dropping the cache.** Feed subscribers outlive
the monitor's worker session, so when a lifecycle ends (worker exit, lease
overflow, command failure) the monitor keeps its cache as the previous
generation. The first reconcile of the next lifecycle diffs the new worker's
snapshot against it and broadcasts a Clear for every alarm that is no longer
active, and a repair for every alarm that changed. These Clears are not invented
events: like every reconcile repair they are feed transitions derived from the
worker's own authoritative snapshot, compared with the last set the feed
published, and the only difference from a periodic pass is that the gap spans a
session instead of one interval. Without them, an alarm that returned to normal
while the monitor was down stayed active on every attached consumer indefinitely,
because the new cache never contained it and nothing would ever clear it. While a
lifecycle is down the retained set is hidden from `CurrentAlarms`
(`QueryActiveAlarms` and the dashboard poll report no alarms rather than a set of
unknown age); a subscriber that attaches in that gap gets an empty snapshot and
is sent every active alarm as repairs on the first reconcile. Each lifecycle start
also broadcasts its re-baselined provider status, so a subscriber that last saw a
subtag failover learns the restarted monitor is back on the alarm manager. A
failed lifecycle restarts after 5 seconds, doubling per consecutive failure up to
5 minutes and resetting once a lifecycle reaches `Monitoring`; each attempt launches
a worker, so a permanent misconfiguration must not cycle one every few seconds.
### Alarm providers and failover
The alarm feed has two providers, both implemented worker-side:
@@ -213,11 +251,16 @@ The alarm feed has two providers, both implemented worker-side:
consecutive wnwrap COM failures — `Subscribe` or `PollOnce` throws or
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
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`
(default 30) it re-probes the still-subscribed primary. After
`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
emits `OnAlarmProviderModeChangedEvent` so the gateway can reconcile its
cache without a raise/clear storm.
@@ -291,8 +334,8 @@ frames, so the caveat precedes the records it qualifies — and thereafter only
a *change* of verdict (a status frame repeated every reconcile is one consumers
learn to ignore). The open-time frame is unconditional: an explicit
`truncated = false` is what separates a complete set from a gateway that never
sends the frame. A monitor restart drops the verdict with the cache generation it
describes, and because feed subscribers outlive the monitor's worker session that
sends the frame. A monitor restart drops the verdict with the worker session that
produced it, and because feed subscribers outlive the monitor's worker session that
drop is emitted as a clearing frame too. The flag
means "this active set may be incomplete", not "this record is unreliable" —
it is independent of the subtag-fallback `degraded` field above. It is not
@@ -10,6 +10,15 @@ namespace ZB.MOM.WW.MxGateway.Server.Alarms;
/// and composes the per-attribute subtag item addresses from the configured
/// subtag names.
/// </summary>
/// <remarks>
/// The alarm monitor re-resolves on every reconcile tick, but the watch-list only changes
/// when the galaxy is deployed. A successful resolution is therefore cached against the
/// Galaxy's last deploy time and the options instance it was built from: while both are
/// unchanged the same <see cref="AlarmWatchListResolution"/> instance is returned for the
/// cost of one deploy-time query, and the monitor recognizes it by reference and skips
/// re-fingerprinting (SEC-008). A failed discovery, or an unknown deploy time, is never
/// cached, so the next call queries again.
/// </remarks>
public sealed class AlarmWatchListResolver : IAlarmWatchListResolver
{
private const string ProviderLiteral = "Galaxy";
@@ -18,6 +27,8 @@ public sealed class AlarmWatchListResolver : IAlarmWatchListResolver
private readonly IGalaxyRepository _repository;
private readonly ILogger<AlarmWatchListResolver> _logger;
private readonly object _cacheSync = new();
private CachedResolution? _cache;
/// <summary>Initializes the watch-list resolver.</summary>
/// <param name="repository">Galaxy Repository used for alarm-attribute discovery.</param>
@@ -39,6 +50,25 @@ public sealed class AlarmWatchListResolver : IAlarmWatchListResolver
AlarmDiscoveryOptions discovery = options.Fallback.Discovery;
// Config-only lists depend on nothing but the options; GR-backed lists also on the
// galaxy's deploy time. Either way an unchanged key returns the cached instance.
DateTime? deployTime = discovery.UseGalaxyRepository
? await TryGetLastDeployTimeAsync(cancellationToken).ConfigureAwait(false)
: null;
bool cacheable = !discovery.UseGalaxyRepository || deployTime is not null;
if (cacheable)
{
lock (_cacheSync)
{
if (_cache is { } cached
&& ReferenceEquals(cached.Options, options)
&& cached.DeployTime == deployTime)
{
return cached.Resolution;
}
}
}
// The caller cannot grade an empty watch-list without knowing whether discovery
// was asked to contribute and whether it failed while doing so, because the failure is
// deliberately swallowed below.
@@ -154,13 +184,43 @@ public sealed class AlarmWatchListResolver : IAlarmWatchListResolver
_logger.LogDebug("Resolved alarm subtag watch-list with {TargetCount} target(s).", targets.Count);
}
return new AlarmWatchListResolution(
AlarmWatchListResolution resolution = new(
targets,
DiscoveryAttempted: discovery.UseGalaxyRepository,
DiscoveryFailed: discoveryFailureMessage is not null,
discoveryFailureMessage);
if (cacheable && !resolution.DiscoveryFailed)
{
lock (_cacheSync)
{
_cache = new CachedResolution(options, deployTime, resolution);
}
}
return resolution;
}
// The deploy-time query is the cache key, not a requirement: when it fails or the galaxy
// reports none, the caller simply resolves uncached, exactly as before the cache existed.
private async Task<DateTime?> TryGetLastDeployTimeAsync(CancellationToken cancellationToken)
{
try
{
return await _repository.GetLastDeployTimeAsync(cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
_logger.LogDebug(ex, "Galaxy last-deploy-time query failed; resolving the alarm watch-list uncached.");
return null;
}
}
private sealed record CachedResolution(
AlarmsOptions Options,
DateTime? DeployTime,
AlarmWatchListResolution Resolution);
/// <summary>
/// Derives the source-object reference for a configuration entry: the
/// substring before the first '.', or the whole string when there is no dot.
@@ -21,9 +21,16 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic
private const string MonitorClientName = "gateway-alarm-monitor";
private const string BackendName = "Galaxy";
private const int SubscriberQueueCapacity = 2048;
private static readonly TimeSpan RestartBackoff = TimeSpan.FromSeconds(5);
private static readonly TimeSpan DefaultInitialRestartBackoff = TimeSpan.FromSeconds(5);
private static readonly TimeSpan MaximumRestartBackoff = TimeSpan.FromMinutes(5);
private static readonly TimeSpan StartupGrace = TimeSpan.FromSeconds(2);
// Upper bound on the watch-list refresh the failover edge awaits before publishing the
// provider status. The refresh normally costs one deploy-time query (the resolver caches the
// alarm-attribute query per deploy), but a hung Galaxy SQL must not stall transition
// processing at the moment the feed is degraded (SEC-008).
private static readonly TimeSpan FailoverWatchListRefreshTimeout = TimeSpan.FromSeconds(10);
private readonly ISessionManager _sessionManager;
private readonly IAlarmWatchListResolver _watchListResolver;
private readonly GatewayMetrics _metrics;
@@ -49,6 +56,38 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic
// duplicate would be sitting in — and the map stays bounded by the feed's churn per interval.
private readonly Dictionary<string, Timestamp> _clearedByReconcile = new(StringComparer.Ordinal);
// Reconcile versioning, guarded by _sync (SEC-006). Every live transition takes the next
// sequence number and stamps its reference with it; a reconcile captures the sequence before
// it issues QueryActiveAlarms. A reference stamped after that capture changed live while the
// snapshot was in flight, so the snapshot is older than the cache for that alarm and must not
// overwrite it — neither by a synthetic Clear nor by a re-raise. Stamps at or below a pass's
// capture are superseded by that pass and pruned, which bounds the map by one interval's churn.
private long _liveSequence;
private readonly Dictionary<string, long> _liveStampByReference = new(StringComparer.Ordinal);
// Whether _alarms is the previous lifecycle's generation, guarded by _sync (SEC-005). A
// lifecycle that ends keeps its cache instead of dropping it: feed subscribers outlive the
// monitor's worker session and still hold that set, so the first reconcile of the next
// lifecycle diffs against it and broadcasts a Clear for every alarm that returned to normal
// during the gap. While stale the set is hidden from CurrentAlarms (the poll surfaces report
// nothing rather than a set of unknown age), and a subscriber that attaches in the gap gets an
// empty snapshot and is flagged for a full replay on that first reconcile.
private bool _cacheStale;
// Last watch-list resolution and its fingerprint hash, guarded by _sync (SEC-008). The resolver
// returns the same instance while the Galaxy deploy time is unchanged, so an unchanged
// resolution is recognized by reference and is not re-fingerprinted every refresh.
private AlarmWatchListResolution? _lastResolution;
private string _lastResolutionFingerprint = string.Empty;
// Serializes watch-list refreshes: the periodic refresh loop and the failover edge can both
// re-resolve and send UpdateAlarmWatchList, and two replacements must not interleave.
private readonly SemaphoreSlim _watchListRefreshGate = new(1, 1);
private int _consecutiveLifecycleFailures;
private string? _lastLifecycleFaultMessage;
private bool _reconcileFailing;
// Current provider status (mode + degraded + reason + since), guarded by _sync.
// Initialized to the alarm-manager, not-degraded baseline so a late joiner sees
// a sensible status even before any OnAlarmProviderModeChanged event arrives.
@@ -66,14 +105,16 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic
private bool _subtagCoverageMissing;
private string _subtagCoverageReason = string.Empty;
// The full canonical watch-list fingerprint acknowledged by the worker and its alarm
// The SHA-256 of the canonical watch-list fingerprint acknowledged by the worker, and its alarm
// references, guarded by _sync. The fingerprint advances only after an OK subscribe/update
// reply, so a rejected replacement remains material and is retried on the next refresh edge.
// Only the hash is retained: the canonical string covers the whole watch-list and would pin
// several MB for the process lifetime on a large galaxy.
private string _acknowledgedWatchListFingerprint = string.Empty;
private IReadOnlyCollection<string> _sentWatchListReferences = [];
// Whether the worker's most recent reconcile fetch was capped, guarded by _sync.
// Written only by ApplyReconcile (and cleared with the cache), so it describes the last full
// Written only by ApplyReconcile (and cleared when a lifecycle ends), so it describes the last full
// reconcile — not necessarily the current _alarms contents, which live transitions keep moving
// via ApplyTransition between passes. Read it as "as of the last reconcile, the worker's fetch
// was capped", which is the right granularity for a completeness caveat.
@@ -101,8 +142,39 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic
_metrics = metrics ?? throw new ArgumentNullException(nameof(metrics));
_options = (options ?? throw new ArgumentNullException(nameof(options))).Value.Alarms;
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
ReconcileInterval = TimeSpan.FromSeconds(Math.Max(5, _options.ReconcileIntervalSeconds));
}
/// <summary>
/// Computes the restart backoff after <paramref name="consecutiveFailures"/> failed
/// lifecycles in a row: the initial backoff, doubled per further failure, capped at five
/// minutes (SEC-010). Every attempt launches an x86 worker, so a permanent failure must not
/// cycle one every few seconds forever.
/// </summary>
/// <param name="initial">The first backoff.</param>
/// <param name="consecutiveFailures">Failed lifecycles in a row, at least 1.</param>
/// <returns>The delay before the next attempt.</returns>
internal static TimeSpan ComputeRestartBackoff(TimeSpan initial, int consecutiveFailures)
{
int doublings = Math.Clamp(consecutiveFailures - 1, 0, 30);
double ticks = initial.Ticks * Math.Pow(2, doublings);
return ticks >= MaximumRestartBackoff.Ticks ? MaximumRestartBackoff : TimeSpan.FromTicks((long)ticks);
}
/// <summary>
/// Gets or sets the reconcile cadence. Defaults to
/// <see cref="AlarmsOptions.ReconcileIntervalSeconds"/> floored at 5 seconds; settable so
/// tests can drive reconcile passes without waiting on the production cadence.
/// </summary>
internal TimeSpan ReconcileInterval { get; init; }
/// <summary>
/// Gets or sets the first restart backoff after a failed lifecycle. Doubles per consecutive
/// failure up to five minutes and resets once a lifecycle reaches Monitoring. Settable so
/// tests can drive restarts quickly.
/// </summary>
internal TimeSpan InitialRestartBackoff { get; init; } = DefaultInitialRestartBackoff;
/// <inheritdoc />
public GatewayAlarmMonitorState State => _state;
@@ -125,13 +197,18 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic
// Same clone semantics as an uncached read — callers still get instances no
// mutation can leak back into the cache — but built once per alarm-set
// generation instead of once per caller.
return _currentAlarmsProjection ??= _alarms.Values
.Select(alarm => alarm.Clone())
.ToArray();
return BuildProjection();
}
}
}
// Caller holds _sync. The memoized, cloned projection of the cache — empty while the cache is
// a retired lifecycle's generation (see _cacheStale).
private ActiveAlarmSnapshot[] BuildProjection() =>
_currentAlarmsProjection ??= _cacheStale
? []
: _alarms.Values.Select(alarm => alarm.Clone()).ToArray();
/// <inheritdoc />
public bool SnapshotTruncated
{
@@ -182,13 +259,32 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic
{
_state = GatewayAlarmMonitorState.Faulted;
_lastError = exception.Message;
_logger.LogWarning(
exception,
"Gateway alarm monitor lifecycle faulted; restarting in {Backoff}.",
RestartBackoff);
int failures = ++_consecutiveLifecycleFailures;
TimeSpan backoff = ComputeRestartBackoff(InitialRestartBackoff, failures);
// The first occurrence of a fault carries the stack; an identical repeat is one
// summary line, so a permanent misconfiguration does not grow the log by a stack
// trace per attempt (SEC-010).
if (string.Equals(exception.Message, _lastLifecycleFaultMessage, StringComparison.Ordinal))
{
_logger.LogWarning(
"Gateway alarm monitor lifecycle still faulting ({Diagnostic}); attempt {Attempt}, restarting in {Backoff}.",
exception.Message,
failures,
backoff);
}
else
{
_logger.LogWarning(
exception,
"Gateway alarm monitor lifecycle faulted; restarting in {Backoff}.",
backoff);
}
_lastLifecycleFaultMessage = exception.Message;
try
{
await Task.Delay(RestartBackoff, stoppingToken).ConfigureAwait(false);
await Task.Delay(backoff, stoppingToken).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
@@ -242,6 +338,11 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic
_providerDegraded = initialDegraded;
_providerReason = initialReason;
_providerSince = DateTimeOffset.UtcNow;
// Feed subscribers outlive the worker session and may still show the previous
// lifecycle's status (a Subtag failover, say). Auto mode raises no mode-change event at
// start, so without this frame they would keep it indefinitely (SEC-005).
BroadcastToAll(new AlarmFeedMessage { ProviderStatus = BuildProviderStatus() });
}
// Align the observable gauge with the lifecycle baseline without recording
@@ -273,10 +374,12 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic
using IEventSubscriberLease alarmLease = session.AttachInternalEventSubscriber(IsAlarmMonitorEvent);
await SubscribeAlarmsAsync(session.SessionId, subscription, stoppingToken).ConfigureAwait(false);
await ReconcileAsync(session.SessionId, stoppingToken).ConfigureAwait(false);
await ReconcileAsync(session.SessionId, initial: true, stoppingToken).ConfigureAwait(false);
_state = GatewayAlarmMonitorState.Monitoring;
_lastError = null;
_consecutiveLifecycleFailures = 0;
_lastLifecycleFaultMessage = null;
_logger.LogInformation(
"Gateway alarm monitor active on {Subscription} (session {SessionId}, worker pid {WorkerPid}).",
subscription,
@@ -285,6 +388,10 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic
using CancellationTokenSource linked = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken);
Task reconcileLoop = ReconcileLoopAsync(session.SessionId, linked.Token);
// The watch-list refresh runs on its own loop so a slow or hung Galaxy SQL query never
// delays the reconcile cadence (SEC-008).
Task watchListLoop = WatchListRefreshLoopAsync(session.SessionId, linked.Token);
try
{
// Consume mapped MxEvents through the session's single distributor pump (as an
@@ -318,11 +425,11 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic
await linked.CancelAsync().ConfigureAwait(false);
try
{
await reconcileLoop.ConfigureAwait(false);
await Task.WhenAll(reconcileLoop, watchListLoop).ConfigureAwait(false);
}
catch
{
// Reconcile-loop teardown errors are not actionable here.
// Reconcile/refresh-loop teardown errors are not actionable here.
}
}
@@ -333,7 +440,7 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic
finally
{
lock (_sync) { _session = null; }
ClearCache();
RetireCacheGeneration();
try
{
await _sessionManager.CloseSessionAsync(session.SessionId, CancellationToken.None).ConfigureAwait(false);
@@ -407,9 +514,10 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic
throw new InvalidOperationException($"Worker rejected SubscribeAlarms: {diagnostic}");
}
string fingerprint = FingerprintOf(resolution);
lock (_sync)
{
AcknowledgeWatchList(watchList);
AcknowledgeWatchList(watchList, fingerprint);
}
}
@@ -417,15 +525,12 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic
{
try
{
int seconds = Math.Max(5, _options.ReconcileIntervalSeconds);
using PeriodicTimer timer = new(TimeSpan.FromSeconds(seconds));
using PeriodicTimer timer = new(ReconcileInterval);
while (await timer.WaitForNextTickAsync(cancellationToken).ConfigureAwait(false))
{
try
{
await RefreshAlarmWatchListAsync(sessionId, broadcast: true, cancellationToken)
.ConfigureAwait(false);
await ReconcileAsync(sessionId, cancellationToken).ConfigureAwait(false);
await ReconcileAsync(sessionId, initial: false, cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
@@ -440,10 +545,28 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic
catch (OperationCanceledException)
{
}
catch (Exception exception)
{
// The loop task is awaited only in teardown, so a fault here (a timer period the
// runtime rejects, say) would otherwise end reconciliation silently (SEC-011).
_lastError = $"Alarm reconcile loop stopped: {exception.Message}";
_logger.LogError(exception, "Alarm reconcile loop stopped; missed transitions will not be repaired.");
}
}
private async Task ReconcileAsync(string sessionId, CancellationToken cancellationToken)
// One reconcile pass. The live sequence is captured BEFORE the command goes out, so
// ApplyReconcile can tell which cached entries changed live while the snapshot was in flight
// (SEC-006). A non-OK reply is not silent (SEC-009): it fails the lifecycle when it is the
// initial reconcile — entering Monitoring with an empty cache would look healthy and report
// zero alarms — and is a logged, surfaced error on a periodic pass.
private async Task ReconcileAsync(string sessionId, bool initial, CancellationToken cancellationToken)
{
long issuedAt;
lock (_sync)
{
issuedAt = _liveSequence;
}
WorkerCommandReply reply = await _sessionManager.InvokeAsync(
sessionId,
new WorkerCommand
@@ -457,16 +580,42 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic
cancellationToken)
.ConfigureAwait(false);
if (reply.Reply?.ProtocolStatus?.Code != ProtocolStatusCode.Ok)
QueryActiveAlarmsReplyPayload? payload = reply.Reply?.QueryActiveAlarms;
if (reply.Reply?.ProtocolStatus?.Code != ProtocolStatusCode.Ok || payload is null)
{
ProtocolStatusCode? code = reply.Reply?.ProtocolStatus?.Code;
string diagnostic = reply.Reply?.DiagnosticMessage is { Length: > 0 } detail
? detail
: reply.Reply?.ProtocolStatus?.Message is { Length: > 0 } message
? message
: payload is null && code == ProtocolStatusCode.Ok
? "reply carried no active-alarm payload"
: $"status {code}";
if (initial)
{
throw new InvalidOperationException($"Worker rejected the initial QueryActiveAlarms: {diagnostic}");
}
_lastError = $"Alarm reconcile failed: {diagnostic}";
if (!_reconcileFailing)
{
_reconcileFailing = true;
_logger.LogWarning(
"Alarm reconcile rejected by the worker ({Diagnostic}); keeping the current cache.",
diagnostic);
}
return;
}
QueryActiveAlarmsReplyPayload? payload = reply.Reply.QueryActiveAlarms;
if (payload is not null)
if (_reconcileFailing)
{
ApplyReconcile(payload.Snapshots, payload.SnapshotTruncated);
_reconcileFailing = false;
_lastError = null;
_logger.LogInformation("Alarm reconcile recovered.");
}
ApplyReconcile(payload.Snapshots, payload.SnapshotTruncated, issuedAt);
}
// Distributor-side filter for the monitor's internal lease: admits only the event bodies the
@@ -487,6 +636,10 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic
lock (_sync)
{
// Stamp the reference so a reconcile snapshot issued before this transition cannot
// overwrite what it did to the cache (SEC-006).
_liveStampByReference[reference] = ++_liveSequence;
if (transition.TransitionKind == AlarmTransitionKind.Clear)
{
bool wasKnown = _alarms.Remove(reference);
@@ -500,7 +653,7 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic
return;
}
}
else
else if (UpdatesCache(transition.TransitionKind, _alarms.ContainsKey(reference)))
{
ActiveAlarmSnapshot snapshot = SnapshotFromTransition(transition);
bool duplicate = _alarms.TryGetValue(reference, out ActiveAlarmSnapshot? existing)
@@ -517,6 +670,19 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic
}
}
// Which non-Clear transitions change the active-alarm cache. A Raise inserts or replaces the
// entry. An Acknowledge only moves an alarm the cache already holds to ActiveAcked: an
// acknowledge of an alarm that already returned to normal (the worker maps UNACK_RTN → ACK_RTN
// to Acknowledge) is history, and inserting it would list an inactive alarm as active until
// the next reconcile (SEC-007). Every other kind (Unspecified, the never-emitted Retrigger)
// carries no state the cache can trust. All of them are still broadcast to the feed.
private static bool UpdatesCache(AlarmTransitionKind kind, bool cached) => kind switch
{
AlarmTransitionKind.Raise => true,
AlarmTransitionKind.Acknowledge => cached,
_ => false,
};
// Best-effort dedup of the reconcile/live race. A reconcile that already synthesized
// this transition as a feed repair left the cache carrying the worker's transition timestamp
// and resulting state — both derived from the same worker-side value the live transition
@@ -567,8 +733,22 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic
// the provider switch.
if (toMode == AlarmProviderMode.Subtag)
{
await RefreshAlarmWatchListAsync(sessionId, broadcast: false, cancellationToken)
.ConfigureAwait(false);
using CancellationTokenSource bounded = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
bounded.CancelAfter(FailoverWatchListRefreshTimeout);
try
{
await RefreshAlarmWatchListAsync(sessionId, broadcast: false, bounded.Token)
.ConfigureAwait(false);
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
{
// Bounded so a hung Galaxy SQL cannot stall transition processing at the failover
// edge (SEC-008). The periodic refresh loop retries; the status below carries the
// last acknowledged coverage verdict meanwhile.
_logger.LogWarning(
"Alarm watch-list refresh on failover exceeded {Timeout}; publishing the provider status with the last acknowledged watch-list.",
FailoverWatchListRefreshTimeout);
}
}
AlarmProviderStatus status;
@@ -604,7 +784,7 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic
// so holding it across the await here would deadlock. Subscribers therefore
// see the ProviderStatus push (above) slightly before the cache is re-seeded
// by the reconcile — an accepted brief inconsistency.
await ReconcileAsync(sessionId, cancellationToken).ConfigureAwait(false);
await ReconcileAsync(sessionId, initial: false, cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
@@ -618,6 +798,45 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic
}
}
// Periodic watch-list refresh, on its own loop at the reconcile cadence so a slow Galaxy SQL
// query never delays a reconcile pass (SEC-008). The resolver caches the alarm-attribute query
// per Galaxy deploy time, so an unchanged galaxy costs one deploy-time query per tick.
private async Task WatchListRefreshLoopAsync(string sessionId, CancellationToken cancellationToken)
{
if (!CanUseSubtagFallback(MapForcedMode(_options.Fallback.Mode)))
{
return;
}
try
{
using PeriodicTimer timer = new(ReconcileInterval);
while (await timer.WaitForNextTickAsync(cancellationToken).ConfigureAwait(false))
{
try
{
await RefreshAlarmWatchListAsync(sessionId, broadcast: true, cancellationToken)
.ConfigureAwait(false);
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception exception)
{
_logger.LogDebug(exception, "Alarm watch-list refresh failed; keeping the last acknowledged watch list.");
}
}
}
catch (OperationCanceledException)
{
}
catch (Exception exception)
{
_logger.LogError(exception, "Alarm watch-list refresh loop stopped.");
}
}
private async Task RefreshAlarmWatchListAsync(
string sessionId,
bool broadcast,
@@ -629,6 +848,24 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic
return;
}
await _watchListRefreshGate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
await RefreshAlarmWatchListCoreAsync(sessionId, forcedMode, broadcast, cancellationToken)
.ConfigureAwait(false);
}
finally
{
_watchListRefreshGate.Release();
}
}
private async Task RefreshAlarmWatchListCoreAsync(
string sessionId,
AlarmProviderMode forcedMode,
bool broadcast,
CancellationToken cancellationToken)
{
AlarmWatchListResolution resolution;
try
{
@@ -646,7 +883,7 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic
return;
}
string resolvedFingerprint = CanonicalWatchListFingerprint(resolution.Targets);
string resolvedFingerprint = FingerprintOf(resolution);
string acknowledgedFingerprint;
lock (_sync)
{
@@ -684,7 +921,7 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic
{
if (code == ProtocolStatusCode.Ok)
{
AcknowledgeWatchList(resolution.Targets);
AcknowledgeWatchList(resolution.Targets, resolvedFingerprint);
SetSubtagCoverage(
GradeSubtagCoverage(forcedMode, resolution, staleAgainstSent: false),
broadcast);
@@ -706,14 +943,39 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic
|| _options.Fallback.Discovery.IncludeAttributes.Length > 0);
// Caller holds _sync.
private void AcknowledgeWatchList(IReadOnlyList<AlarmSubtagTarget> watchList)
private void AcknowledgeWatchList(IReadOnlyList<AlarmSubtagTarget> watchList, string fingerprint)
{
_acknowledgedWatchListFingerprint = CanonicalWatchListFingerprint(watchList);
_acknowledgedWatchListFingerprint = fingerprint;
_sentWatchListReferences = watchList
.Select(target => target.AlarmFullReference)
.ToHashSet(StringComparer.OrdinalIgnoreCase);
}
// The fingerprint hash of a resolution, computed once per resolution instance: the resolver
// hands back the same instance while the galaxy is undeployed, so the steady state builds no
// per-target strings at all (SEC-008).
private string FingerprintOf(AlarmWatchListResolution resolution)
{
lock (_sync)
{
if (ReferenceEquals(resolution, _lastResolution))
{
return _lastResolutionFingerprint;
}
}
string fingerprint = Convert.ToHexString(
System.Security.Cryptography.SHA256.HashData(
System.Text.Encoding.UTF8.GetBytes(CanonicalWatchListFingerprint(resolution.Targets))));
lock (_sync)
{
_lastResolution = resolution;
_lastResolutionFingerprint = fingerprint;
}
return fingerprint;
}
private static string CanonicalWatchListFingerprint(IEnumerable<AlarmSubtagTarget> watchList) =>
string.Join(
"\n",
@@ -891,7 +1153,21 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic
// The flag is set-level status, not a delta: it is recorded, and a CHANGE of verdict is pushed
// to the feed as a snapshot_status frame (SetSnapshotTruncated) so live consumers learn the
// completeness caveat without polling QueryActiveAlarms.
private void ApplyReconcile(IEnumerable<ActiveAlarmSnapshot> snapshots, bool snapshotTruncated)
//
// Versioning (SEC-006): the snapshot is a point-in-time read issued at `issuedAt` on the live
// sequence. An alarm stamped by a live transition after that point changed while the snapshot
// was in flight, so for that alarm the cache is newer than the snapshot: the pass leaves its
// cache entry (present or absent) alone and broadcasts no repair for it. The next pass, issued
// after the transition, reconciles it.
//
// Restart (SEC-005): the first pass of a lifecycle diffs against the previous lifecycle's
// retained cache, which is what every attached subscriber still holds, so an alarm that
// returned to normal while the monitor was down gets its Clear. Those Clears are derived from
// the worker's own snapshot of the new session compared with the last set the feed published —
// the same presence-delta repair every reconcile makes, not an invented event. A subscriber
// that attached during the gap was given an empty snapshot, so it is sent the whole set as
// Raise (and Acknowledge) repairs instead.
private void ApplyReconcile(IEnumerable<ActiveAlarmSnapshot> snapshots, bool snapshotTruncated, long issuedAt)
{
Dictionary<string, ActiveAlarmSnapshot> next = new(StringComparer.Ordinal);
foreach (ActiveAlarmSnapshot snapshot in snapshots)
@@ -908,8 +1184,22 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic
// guard against (one full reconcile interval); start this pass's generation fresh.
_clearedByReconcile.Clear();
bool firstPassAfterRestart = _cacheStale;
Func<Subscriber, bool> diffAudience = firstPassAfterRestart
? subscriber => !subscriber.NeedsFullReplay
: static _ => true;
Dictionary<string, ActiveAlarmSnapshot> rebuilt = new(StringComparer.Ordinal);
foreach (KeyValuePair<string, ActiveAlarmSnapshot> existing in _alarms)
{
if (ChangedLiveSince(existing.Key, issuedAt))
{
// The live feed moved this alarm after the snapshot was taken; keep its state.
rebuilt[existing.Key] = existing.Value;
continue;
}
if (!next.ContainsKey(existing.Key))
{
if (existing.Value.OriginalRaiseTimestamp is not null)
@@ -919,37 +1209,64 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic
Broadcast(
new AlarmFeedMessage { Transition = TransitionFromSnapshot(existing.Value, AlarmTransitionKind.Clear) },
existing.Key);
existing.Key,
diffAudience);
}
}
foreach (KeyValuePair<string, ActiveAlarmSnapshot> incoming in next)
{
if (!_alarms.TryGetValue(incoming.Key, out ActiveAlarmSnapshot? existing))
if (ChangedLiveSince(incoming.Key, issuedAt))
{
Broadcast(
new AlarmFeedMessage { Transition = TransitionFromSnapshot(incoming.Value, AlarmTransitionKind.Raise) },
incoming.Key);
// Absent from the cache because a live Clear (or nothing) came after the
// snapshot: the snapshot's presence is the older fact. Present: kept above.
continue;
}
else if (existing.CurrentState != incoming.Value.CurrentState)
rebuilt[incoming.Key] = incoming.Value;
_alarms.TryGetValue(incoming.Key, out ActiveAlarmSnapshot? existing);
foreach (AlarmTransitionKind kind in RepairKinds(existing, incoming.Value))
{
// The alarm was already known but the worker now reports a different state. An
// ActiveAcked snapshot repairs a missed Acknowledge. Any other incoming active
// state repairs a missed Raise for the incoming instance (including an
// acknowledged alarm reference that was cleared and re-raised between passes).
AlarmTransitionKind kind = incoming.Value.CurrentState == AlarmConditionState.ActiveAcked
? AlarmTransitionKind.Acknowledge
: AlarmTransitionKind.Raise;
Broadcast(
new AlarmFeedMessage { Transition = TransitionFromSnapshot(incoming.Value, kind) },
incoming.Key);
incoming.Key,
diffAudience);
}
if (firstPassAfterRestart)
{
foreach (AlarmTransitionKind kind in RepairKinds(existing: null, incoming.Value))
{
Broadcast(
new AlarmFeedMessage { Transition = TransitionFromSnapshot(incoming.Value, kind) },
incoming.Key,
static subscriber => subscriber.NeedsFullReplay);
}
}
}
_alarms.Clear();
foreach (KeyValuePair<string, ActiveAlarmSnapshot> incoming in next)
foreach (KeyValuePair<string, ActiveAlarmSnapshot> entry in rebuilt)
{
_alarms[incoming.Key] = incoming.Value;
_alarms[entry.Key] = entry.Value;
}
// Stamps at or below this pass's capture are superseded by it.
foreach (string reference in _liveStampByReference
.Where(stamp => stamp.Value <= issuedAt)
.Select(stamp => stamp.Key)
.ToArray())
{
_liveStampByReference.Remove(reference);
}
if (firstPassAfterRestart)
{
_cacheStale = false;
foreach (Subscriber subscriber in _subscribers)
{
subscriber.NeedsFullReplay = false;
}
}
SetSnapshotTruncated(snapshotTruncated);
@@ -957,6 +1274,46 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic
}
}
// Caller holds _sync. True when a live transition touched the reference after the reconcile
// whose live-sequence capture is issuedAt was issued.
private bool ChangedLiveSince(string reference, long issuedAt) =>
_liveStampByReference.TryGetValue(reference, out long stamp) && stamp > issuedAt;
// The feed repairs that move a subscriber holding `existing` (null: not holding the alarm) to
// the worker-reported `incoming` state.
//
// - Not held: Raise, plus Acknowledge when the alarm is already acknowledged, so a consumer
// applying transitions as "set this state" ends on ActiveAcked rather than Active.
// - Held, but a different instance (the original raise timestamp moved): the alarm cleared and
// re-raised between passes with both live transitions missed. That is a Raise even when the
// state is unchanged (SEC-009), plus Acknowledge when the new instance is already acked.
// - Held, same instance, state moved to ActiveAcked: a missed Acknowledge.
// - Held, same instance, any other state change: a Raise for the incoming state.
private static IEnumerable<AlarmTransitionKind> RepairKinds(ActiveAlarmSnapshot? existing, ActiveAlarmSnapshot incoming)
{
bool acked = incoming.CurrentState == AlarmConditionState.ActiveAcked;
bool newInstance = existing is null
|| (existing.OriginalRaiseTimestamp is not null
&& incoming.OriginalRaiseTimestamp is not null
&& !existing.OriginalRaiseTimestamp.Equals(incoming.OriginalRaiseTimestamp));
if (newInstance)
{
yield return AlarmTransitionKind.Raise;
if (acked)
{
yield return AlarmTransitionKind.Acknowledge;
}
yield break;
}
if (existing!.CurrentState != incoming.CurrentState)
{
yield return acked ? AlarmTransitionKind.Acknowledge : AlarmTransitionKind.Raise;
}
}
// Caller holds _sync. Records the truncation verdict and, on a CHANGE of verdict, pushes the
// feed-level snapshot_status frame. Edge-triggered rather than per-reconcile: a status frame
// repeated every reconcile interval is one consumers learn to ignore. The verdict describes the
@@ -980,12 +1337,15 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic
// a subscriber that has fallen behind is completed with an AlarmFeedSubscriberOverflowException
// and dropped. The typed fault is what lets StreamAlarms answer ResourceExhausted instead of
// treating a slow client as a gateway failure.
private void Broadcast(AlarmFeedMessage message, string reference)
private void Broadcast(AlarmFeedMessage message, string reference) => Broadcast(message, reference, null);
// Caller holds _sync. As Broadcast, restricted to the subscribers `audience` admits.
private void Broadcast(AlarmFeedMessage message, string reference, Func<Subscriber, bool>? audience)
{
for (int index = _subscribers.Count - 1; index >= 0; index--)
{
Subscriber subscriber = _subscribers[index];
if (!subscriber.Matches(reference))
if (!subscriber.Matches(reference) || (audience is not null && !audience(subscriber)))
{
continue;
}
@@ -1014,16 +1374,22 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic
}
}
private void ClearCache()
// Ends the cache generation of a lifecycle that stopped. The alarms are KEPT, marked stale,
// so the next lifecycle's first reconcile can diff against what subscribers were last told
// (see _cacheStale and ApplyReconcile); they are hidden from CurrentAlarms meanwhile.
private void RetireCacheGeneration()
{
lock (_sync)
{
_alarms.Clear();
// The truncation verdict describes the cache generation being discarded, so it goes
// with it. Carrying it across a monitor restart would caveat an empty set as "may be
// incomplete" on evidence from a session that no longer exists. Dropping a truncated
// verdict IS a completeness change, and feed subscribers outlive the monitor's worker
// session, so this routes through the edge path and they see the clearing frame.
_cacheStale = true;
_clearedByReconcile.Clear();
_liveStampByReference.Clear();
// The truncation verdict describes the session that produced it, so it is dropped with
// that session. Carrying it across a monitor restart would caveat the next set on
// evidence from a session that no longer exists. Dropping a truncated verdict IS a
// completeness change, and feed subscribers outlive the monitor's worker session, so
// this routes through the edge path and they see the clearing frame.
SetSnapshotTruncated(false);
_currentAlarmsProjection = null;
}
@@ -1057,15 +1423,17 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic
providerStatus = BuildProviderStatus();
snapshotTruncated = _snapshotTruncated;
// Attaching while the cache is a retired generation: the snapshot below is empty, so
// the next lifecycle's first reconcile sends this subscriber the whole set (SEC-005).
subscriber.NeedsFullReplay = _cacheStale;
// Take the memoized projection rather than cloning the whole set per attach: the
// clone runs at most once per alarm-set generation (shared with CurrentAlarms), so a
// burst of reconnecting subscribers no longer holds the broadcast lock for one full
// copy each. The array is never mutated once built — a write to _alarms replaces it
// with null — so capturing the reference here pins exactly the generation this
// subscriber registered against, which is what keeps snapshot-then-live ordering.
snapshot = _currentAlarmsProjection ??= _alarms.Values
.Select(alarm => alarm.Clone())
.ToArray();
snapshot = BuildProjection();
}
try
@@ -1372,6 +1740,12 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic
/// <summary>Gets the channel for publishing alarm messages to this subscriber.</summary>
public Channel<AlarmFeedMessage> Channel { get; } = channel;
/// <summary>
/// Gets or sets a value indicating whether this subscriber attached while the cache was
/// a retired generation and so received an empty snapshot. Guarded by the monitor's lock.
/// </summary>
public bool NeedsFullReplay { get; set; }
/// <summary>Determines whether the alarm reference matches this subscriber's filter.</summary>
/// <param name="reference">The alarm reference to match.</param>
/// <returns><see langword="true"/> if the reference matches this subscriber's prefix filter.</returns>
@@ -440,6 +440,9 @@ public sealed class GatewayOptionsValidator : OptionsValidatorBase<GatewayOption
// upper-bound pattern.
private const int MaximumEventQueueCapacity = int.MaxValue / 2;
// One day. Replay retention is a reconnect window, not an archive.
private const double MaximumReplayRetentionSeconds = 86_400;
private static void ValidateEvents(EventOptions options, ValidationBuilder builder)
{
AddIfNotPositive(options.QueueCapacity, "MxGateway:Events:QueueCapacity must be greater than zero.", builder);
@@ -462,9 +465,12 @@ public sealed class GatewayOptionsValidator : OptionsValidatorBase<GatewayOption
options.ReplayBufferCapacity,
"MxGateway:Events:ReplayBufferCapacity must be greater than or equal to zero.",
builder);
// Upper bound and finiteness: the value becomes TimeSpan.FromSeconds when the first
// event distributor is built, which throws on Infinity/NaN or anything past
// TimeSpan.MaxValue — a runtime failure of every StreamEvents instead of a startup one.
builder.RequireThat(
options.ReplayRetentionSeconds >= 0,
"MxGateway:Events:ReplayRetentionSeconds must be greater than or equal to zero.");
options.ReplayRetentionSeconds >= 0 && options.ReplayRetentionSeconds <= MaximumReplayRetentionSeconds,
$"MxGateway:Events:ReplayRetentionSeconds must be between 0 and {MaximumReplayRetentionSeconds}.");
builder.RequireThat(
options.ReplayBufferMaxBytes >= 0,
"MxGateway:Events:ReplayBufferMaxBytes must be greater than or equal to zero.");
@@ -578,6 +584,8 @@ public sealed class GatewayOptionsValidator : OptionsValidatorBase<GatewayOption
// fault on the STA rather than a slow poll.
private const int MaximumMaxAlarmsPerFetch = 65_536;
private const int MaximumAlarmReconcileIntervalSeconds = 86_400;
private static void ValidateAlarms(AlarmsOptions options, ValidationBuilder builder)
{
// Validated regardless of Enabled: both values are stamped onto every
@@ -626,6 +634,14 @@ public sealed class GatewayOptionsValidator : OptionsValidatorBase<GatewayOption
@"MxGateway:Alarms:SubscriptionExpression must start with '\\' (canonical \\<host>\Galaxy!<area> shape).");
}
// Above a day the reconcile stops being a cadence, and far above it PeriodicTimer
// rejects the period at runtime, which silently ended reconciliation (SEC-011).
if (options.ReconcileIntervalSeconds is < 1 or > MaximumAlarmReconcileIntervalSeconds)
{
builder.Add(
$"MxGateway:Alarms:ReconcileIntervalSeconds must be between 1 and {MaximumAlarmReconcileIntervalSeconds}.");
}
ValidateAlarmFallback(options.Fallback, builder);
}
@@ -9,6 +9,8 @@ namespace ZB.MOM.WW.MxGateway.Server.Dashboard.Hubs;
/// </summary>
/// <param name="Generation">
/// Monotonic subscription counter for this gateway process, starting at 1. Lets a
/// client tell a resubscribe from a duplicate delivery.
/// client tell a resubscribe from a duplicate delivery. Generation 0 is the per-connection
/// prime sent to a client when it connects, ahead of the current snapshot; a client handles
/// it exactly like any other reset.
/// </param>
public sealed record AlarmFeedReset(long Generation);
@@ -1,5 +1,8 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.MxGateway.Server.Alarms;
using ZB.MOM.WW.MxGateway.Server.Configuration;
namespace ZB.MOM.WW.MxGateway.Server.Dashboard.Hubs;
@@ -19,9 +22,17 @@ namespace ZB.MOM.WW.MxGateway.Server.Dashboard.Hubs;
/// read-only environment bypasses (<c>Authentication:Mode=Disabled</c>, anonymous localhost) no
/// longer receive the feed. The <c>/alarms</c> page carries the same policy — the two readers of
/// one monitor must not disagree about who may see it.
/// <para>
/// On connect the client is primed with the current state (a generation-0
/// <see cref="ResetMessage"/>, provider and snapshot status, the active alarms, then
/// <c>snapshot_complete</c>) before it relies on the group's live frames; see
/// <see cref="AlarmsHubPublisher.PrimeConnectionAsync"/>.
/// </para>
/// </remarks>
/// <param name="alarmService">The gateway's central alarm feed.</param>
/// <param name="options">Gateway options supplying <c>Dashboard:ShowTagValues</c>.</param>
[Authorize(Policy = DashboardAuthenticationDefaults.AlarmsPolicy)]
public sealed class AlarmsHub : Hub
public sealed class AlarmsHub(IGatewayAlarmService alarmService, IOptions<GatewayOptions> options) : Hub
{
/// <summary>Group every admitted connection joins on connect.</summary>
public const string AllAlarmsGroup = "__alarms__";
@@ -40,6 +51,14 @@ public sealed class AlarmsHub : Hub
public override async Task OnConnectedAsync()
{
await Groups.AddToGroupAsync(Context.ConnectionId, AllAlarmsGroup).ConfigureAwait(false);
// Joined first, so nothing broadcast after the snapshot is read can be missed (DSH-005).
await AlarmsHubPublisher.PrimeConnectionAsync(
alarmService,
Clients.Caller,
options.Value.Dashboard.ShowTagValues,
Context.ConnectionAborted)
.ConfigureAwait(false);
await base.OnConnectedAsync().ConfigureAwait(false);
}
}
@@ -146,6 +146,56 @@ public sealed class AlarmsHubPublisher : BackgroundService
}
}
/// <summary>
/// Primes one newly connected client with the feed's current state: a
/// <see cref="AlarmsHub.ResetMessage"/> marker with generation 0, then the provider
/// status, the snapshot status, one <c>active_alarm</c> frame per active alarm and the
/// <c>snapshot_complete</c> sentinel — the same preamble a <c>StreamAlarms</c> subscriber
/// gets, redacted by the same <c>ShowTagValues</c> rule as the group broadcast.
/// </summary>
/// <remarks>
/// The publisher holds one monitor subscription for the process lifetime and group-sends
/// the snapshot only when that subscription (re)opens, which is normally before any client
/// is connected; without this a client joining later saw only subsequent transitions
/// (DSH-005). The caller joins the group before priming and the reset is sent before the
/// snapshot is read, so a transition is either already in the snapshot or arrives as a
/// live frame after the reset. A transition applied while the snapshot frames are being
/// sent can arrive ahead of the (older) snapshot row for the same alarm; the next
/// transition or reconcile repair for that alarm corrects it, consistent with the feed's
/// at-least-once, apply-as-state contract.
/// </remarks>
/// <param name="alarmService">The gateway's central alarm feed.</param>
/// <param name="caller">The connecting client.</param>
/// <param name="showTagValues">Whether alarm values may reach browser clients.</param>
/// <param name="cancellationToken">The connection-aborted token.</param>
/// <returns>A task that completes once the snapshot sentinel has been sent.</returns>
internal static async Task PrimeConnectionAsync(
IGatewayAlarmService alarmService,
IClientProxy caller,
bool showTagValues,
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(alarmService);
ArgumentNullException.ThrowIfNull(caller);
await caller.SendAsync(AlarmsHub.ResetMessage, new AlarmFeedReset(0), cancellationToken)
.ConfigureAwait(false);
using CancellationTokenSource stop = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
await foreach (AlarmFeedMessage message in alarmService
.StreamAsync(alarmFilterPrefix: null, stop.Token)
.ConfigureAwait(false))
{
AlarmFeedMessage outbound = showTagValues ? message : RedactValues(message);
await caller.SendAsync(AlarmsHub.AlarmMessage, outbound, cancellationToken).ConfigureAwait(false);
if (message.PayloadCase == AlarmFeedMessage.PayloadOneofCase.SnapshotComplete)
{
// The preamble is complete; live frames reach this client through the group.
break;
}
}
}
/// <summary>
/// Sends one frame to the alarms group within the send timeout. A slow or failed
/// send is logged and dropped so the feed keeps draining; only host shutdown
@@ -193,7 +243,7 @@ public sealed class AlarmsHubPublisher : BackgroundService
/// names only the arms that have something to redact, so adding a valueless
/// arm to the contract needs no change here.
/// </returns>
private static AlarmFeedMessage RedactValues(AlarmFeedMessage source)
internal static AlarmFeedMessage RedactValues(AlarmFeedMessage source)
{
switch (source.PayloadCase)
{
@@ -26,6 +26,13 @@ public static class ApiKeyConstraintSerializer
/// Members absent from the JSON take their default: rows persisted before
/// <see cref="ApiKeyConstraints.DashboardTags"/> existed carry no <c>dashboard_tags</c>
/// member and deserialize to an untagged key, unchanged in every other respect.
/// <para>
/// The record's list parameters are non-nullable, but the serializer leaves a
/// constructor parameter that is absent from the JSON (or explicitly <c>null</c>) as
/// <see langword="null"/>. Every list is normalized to empty here, at load time, so a
/// sparse blob — hand-edited, or written by another tool — can neither throw in the
/// constraint checks nor hand the browse-scope provider a <see langword="null"/> scope.
/// </para>
/// </remarks>
public static ApiKeyConstraints Deserialize(string? json)
{
@@ -34,6 +41,22 @@ public static class ApiKeyConstraintSerializer
return ApiKeyConstraints.Empty;
}
return JsonSerializer.Deserialize<ApiKeyConstraints>(json, JsonOptions) ?? ApiKeyConstraints.Empty;
ApiKeyConstraints? parsed = JsonSerializer.Deserialize<ApiKeyConstraints>(json, JsonOptions);
if (parsed is null)
{
return ApiKeyConstraints.Empty;
}
// The analyzer sees these as never-null; the deserializer does not honour that.
return parsed with
{
ReadSubtrees = OrEmpty(parsed.ReadSubtrees),
WriteSubtrees = OrEmpty(parsed.WriteSubtrees),
ReadTagGlobs = OrEmpty(parsed.ReadTagGlobs),
WriteTagGlobs = OrEmpty(parsed.WriteTagGlobs),
BrowseSubtrees = OrEmpty(parsed.BrowseSubtrees),
};
}
private static IReadOnlyList<string> OrEmpty(IReadOnlyList<string>? list) => list ?? Array.Empty<string>();
}
@@ -445,6 +445,113 @@ public sealed class AlarmWatchListResolverTests
Assert.DoesNotContain(result, t => t.ActiveSubtag.Contains("Pump01", StringComparison.OrdinalIgnoreCase));
}
/// <summary>
/// SEC-008: while the galaxy's deploy time is unchanged, repeated resolutions reuse one
/// alarm-attribute query and return the same resolution instance (which the monitor
/// recognizes without re-fingerprinting). A deploy re-queries.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task ResolveAsync_UnchangedDeployTime_ReusesTheCachedResolution()
{
DeployingGalaxyRepository repo = new(
[
new GalaxyAlarmAttributeRow
{
FullTagReference = "Tank01.Level.HiHi",
SourceObjectReference = "Tank01",
Area = "Area1",
},
])
{
DeployTime = new DateTime(2026, 12, 1, 8, 0, 0, DateTimeKind.Utc),
};
AlarmWatchListResolver resolver = CreateResolver(repo);
AlarmsOptions options = Options();
AlarmWatchListResolution first = await resolver.ResolveAsync(options);
AlarmWatchListResolution second = await resolver.ResolveAsync(options);
AlarmWatchListResolution third = await resolver.ResolveAsync(options);
Assert.Same(first, second);
Assert.Same(first, third);
Assert.Equal(1, repo.GetAlarmAttributesCount);
Assert.Equal(3, repo.GetLastDeployTimeCount);
repo.DeployTime = repo.DeployTime!.Value.AddMinutes(5);
AlarmWatchListResolution afterDeploy = await resolver.ResolveAsync(options);
Assert.NotSame(first, afterDeploy);
Assert.Equal(2, repo.GetAlarmAttributesCount);
}
/// <summary>SEC-008: a failed discovery is never cached; the next resolution queries again.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task ResolveAsync_FailedDiscovery_IsNotCached()
{
DeployingGalaxyRepository repo = new([])
{
DeployTime = new DateTime(2026, 12, 1, 8, 0, 0, DateTimeKind.Utc),
FailAlarmAttributes = true,
};
AlarmWatchListResolver resolver = CreateResolver(repo);
AlarmsOptions options = Options();
AlarmWatchListResolution failed = await resolver.ResolveAsync(options);
Assert.True(failed.DiscoveryFailed);
repo.FailAlarmAttributes = false;
AlarmWatchListResolution recovered = await resolver.ResolveAsync(options);
Assert.False(recovered.DiscoveryFailed);
Assert.Equal(2, repo.GetAlarmAttributesCount);
}
/// <summary><see cref="IGalaxyRepository"/> with a settable deploy time, counting both queries.</summary>
/// <param name="rows">The alarm rows to return.</param>
private sealed class DeployingGalaxyRepository(List<GalaxyAlarmAttributeRow> rows) : IGalaxyRepository
{
/// <summary>Gets or sets the deploy time reported.</summary>
public DateTime? DeployTime { get; set; }
/// <summary>Gets or sets a value indicating whether the alarm-attribute query fails.</summary>
public bool FailAlarmAttributes { get; set; }
/// <summary>Gets the number of alarm-attribute queries.</summary>
public int GetAlarmAttributesCount { get; private set; }
/// <summary>Gets the number of deploy-time queries.</summary>
public int GetLastDeployTimeCount { get; private set; }
/// <inheritdoc />
public Task<bool> TestConnectionAsync(CancellationToken ct = default) => Task.FromResult(true);
/// <inheritdoc />
public Task<DateTime?> GetLastDeployTimeAsync(CancellationToken ct = default)
{
GetLastDeployTimeCount++;
return Task.FromResult(DeployTime);
}
/// <inheritdoc />
public Task<List<GalaxyHierarchyRow>> GetHierarchyAsync(CancellationToken ct = default) =>
Task.FromResult(new List<GalaxyHierarchyRow>());
/// <inheritdoc />
public Task<List<GalaxyAttributeRow>> GetAttributesAsync(CancellationToken ct = default) =>
Task.FromResult(new List<GalaxyAttributeRow>());
/// <inheritdoc />
public Task<List<GalaxyAlarmAttributeRow>> GetAlarmAttributesAsync(CancellationToken ct = default)
{
GetAlarmAttributesCount++;
return FailAlarmAttributes
? Task.FromException<List<GalaxyAlarmAttributeRow>>(new InvalidOperationException("gr offline"))
: Task.FromResult(rows);
}
}
/// <summary>In-memory <see cref="IGalaxyRepository"/> returning a fixed alarm rowset.</summary>
private sealed class StubGalaxyRepository(List<GalaxyAlarmAttributeRow> rows) : IGalaxyRepository
{
@@ -0,0 +1,835 @@
using System.Diagnostics.CodeAnalysis;
using System.Threading.Channels;
using Google.Protobuf.WellKnownTypes;
using Microsoft.Extensions.Logging.Abstractions;
using ZB.MOM.WW.MxGateway.Contracts.Proto;
using ZB.MOM.WW.MxGateway.Server.Alarms;
using ZB.MOM.WW.MxGateway.Server.Configuration;
using ZB.MOM.WW.MxGateway.Server.Metrics;
using ZB.MOM.WW.MxGateway.Server.Sessions;
using ZB.MOM.WW.MxGateway.Tests.TestSupport;
namespace ZB.MOM.WW.MxGateway.Tests.Alarms;
/// <summary>
/// Cache-correctness tests for <see cref="GatewayAlarmMonitor"/> from the 2026-12-02 review:
/// acknowledge of an uncached alarm (SEC-007), reconcile versioning against live transitions
/// (SEC-006), same-state re-raise and non-OK reconcile (SEC-009), and monitor restart
/// (SEC-005). The fake session manager hands out a fresh worker event stream per session, so
/// ending one session and letting the supervisor open the next is a real monitor restart.
/// </summary>
public sealed class GatewayAlarmMonitorCacheTests
{
private const string AlarmA = "Galaxy!Area.Tank01.Hi";
private const string AlarmB = "Galaxy!Area.Tank02.Hi";
private static readonly TimeSpan WaitTimeout = TimeSpan.FromSeconds(30);
/// <summary>
/// SEC-007: an alarm that raised and returned to normal unacknowledged is gone from the
/// cache; a later Acknowledge of that returned alarm is history and must not re-insert it as
/// an active-acked row. The transition itself still reaches the feed.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task AcknowledgeOfUncachedAlarm_IsBroadcastButNotCached()
{
using GatewayMetrics metrics = new();
FakeSessionManager sessions = new();
using GatewayAlarmMonitor monitor = CreateMonitor(sessions, metrics);
using CancellationTokenSource cts = new();
await monitor.StartAsync(cts.Token);
await WaitUntilAsync(() => monitor.State == GatewayAlarmMonitorState.Monitoring, WaitTimeout);
FeedRecorder feed = FeedRecorder.Start(monitor);
await feed.SnapshotComplete.WaitAsync(WaitTimeout);
sessions.EmitEvent(Transition(1, AlarmA, AlarmTransitionKind.Raise, Ts(0), Ts(0)));
sessions.EmitEvent(Transition(2, AlarmA, AlarmTransitionKind.Clear, Ts(5), Ts(0)));
sessions.EmitEvent(Transition(3, AlarmA, AlarmTransitionKind.Acknowledge, Ts(9), Ts(0)));
await feed.WaitForTransitionAsync(AlarmA, AlarmTransitionKind.Acknowledge, WaitTimeout);
Assert.Empty(monitor.CurrentAlarms);
await feed.StopAsync();
await cts.CancelAsync();
await monitor.StopAsync(CancellationToken.None);
}
/// <summary>SEC-007: an Acknowledge of an alarm the cache holds still moves it to ActiveAcked.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task AcknowledgeOfCachedAlarm_MovesItToActiveAcked()
{
using GatewayMetrics metrics = new();
FakeSessionManager sessions = new();
using GatewayAlarmMonitor monitor = CreateMonitor(sessions, metrics);
using CancellationTokenSource cts = new();
await monitor.StartAsync(cts.Token);
await WaitUntilAsync(() => monitor.State == GatewayAlarmMonitorState.Monitoring, WaitTimeout);
sessions.EmitEvent(Transition(1, AlarmA, AlarmTransitionKind.Raise, Ts(0), Ts(0)));
sessions.EmitEvent(Transition(2, AlarmA, AlarmTransitionKind.Acknowledge, Ts(3), Ts(0)));
await WaitUntilAsync(
() => monitor.CurrentAlarms.Any(a => a.AlarmFullReference == AlarmA
&& a.CurrentState == AlarmConditionState.ActiveAcked),
WaitTimeout);
await cts.CancelAsync();
await monitor.StopAsync(CancellationToken.None);
}
/// <summary>
/// SEC-006: a reconcile snapshot taken before a live Raise must not clear the alarm the
/// Raise put in the cache. The snapshot is parked after it is captured, the Raise is applied,
/// then the stale snapshot lands.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task StaleSnapshotWithoutLiveRaisedAlarm_DoesNotClearIt()
{
using GatewayMetrics metrics = new();
FakeSessionManager sessions = new();
using GatewayAlarmMonitor monitor = CreateMonitor(sessions, metrics, reconcileInterval: TimeSpan.FromMilliseconds(200));
using CancellationTokenSource cts = new();
await monitor.StartAsync(cts.Token);
await WaitUntilAsync(() => monitor.State == GatewayAlarmMonitorState.Monitoring, WaitTimeout);
FeedRecorder feed = FeedRecorder.Start(monitor);
await feed.SnapshotComplete.WaitAsync(WaitTimeout);
// The parked pass captures {B}: taken before A raised.
sessions.SetSnapshot(Snapshot(AlarmB, AlarmConditionState.Active, Ts(1), Ts(1)));
sessions.HoldNextReconcile();
await sessions.ReconcileParked.WaitAsync(WaitTimeout);
// Later passes see both, as the worker would once A raised.
sessions.SetSnapshot(
Snapshot(AlarmA, AlarmConditionState.Active, Ts(2), Ts(2)),
Snapshot(AlarmB, AlarmConditionState.Active, Ts(1), Ts(1)));
sessions.EmitEvent(Transition(1, AlarmA, AlarmTransitionKind.Raise, Ts(2), Ts(2)));
await WaitUntilAsync(() => monitor.CurrentAlarms.Any(a => a.AlarmFullReference == AlarmA), WaitTimeout);
sessions.ReleaseReconcile();
await feed.WaitForTransitionAsync(AlarmB, AlarmTransitionKind.Raise, WaitTimeout);
Assert.DoesNotContain(AlarmTransitionKind.Clear, feed.TransitionsFor(AlarmA));
Assert.Contains(monitor.CurrentAlarms, a => a.AlarmFullReference == AlarmA);
await feed.StopAsync();
await cts.CancelAsync();
await monitor.StopAsync(CancellationToken.None);
}
/// <summary>
/// SEC-006 mirror: a snapshot taken before a live Clear must not re-raise the cleared alarm.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task StaleSnapshotWithLiveClearedAlarm_DoesNotReRaiseIt()
{
using GatewayMetrics metrics = new();
FakeSessionManager sessions = new();
sessions.SetSnapshot(Snapshot(AlarmA, AlarmConditionState.Active, Ts(0), Ts(0)));
using GatewayAlarmMonitor monitor = CreateMonitor(sessions, metrics, reconcileInterval: TimeSpan.FromMilliseconds(200));
using CancellationTokenSource cts = new();
await monitor.StartAsync(cts.Token);
await WaitUntilAsync(() => monitor.CurrentAlarms.Any(a => a.AlarmFullReference == AlarmA), WaitTimeout);
FeedRecorder feed = FeedRecorder.Start(monitor);
await feed.SnapshotComplete.WaitAsync(WaitTimeout);
// The parked pass captures {A, B}: taken before A cleared.
sessions.SetSnapshot(
Snapshot(AlarmA, AlarmConditionState.Active, Ts(0), Ts(0)),
Snapshot(AlarmB, AlarmConditionState.Active, Ts(1), Ts(1)));
sessions.HoldNextReconcile();
await sessions.ReconcileParked.WaitAsync(WaitTimeout);
sessions.SetSnapshot(Snapshot(AlarmB, AlarmConditionState.Active, Ts(1), Ts(1)));
sessions.EmitEvent(Transition(1, AlarmA, AlarmTransitionKind.Clear, Ts(3), Ts(0)));
await feed.WaitForTransitionAsync(AlarmA, AlarmTransitionKind.Clear, WaitTimeout);
sessions.ReleaseReconcile();
await feed.WaitForTransitionAsync(AlarmB, AlarmTransitionKind.Raise, WaitTimeout);
Assert.Equal([AlarmTransitionKind.Clear], feed.TransitionsFor(AlarmA));
Assert.DoesNotContain(monitor.CurrentAlarms, a => a.AlarmFullReference == AlarmA);
await feed.StopAsync();
await cts.CancelAsync();
await monitor.StopAsync(CancellationToken.None);
}
/// <summary>
/// SEC-009: an alarm that cleared and re-raised between passes, with both live transitions
/// missed, is in the same state with a new original raise time. That is a new instance and
/// must be repaired with a Raise.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task SameStateReRaiseBetweenPasses_BroadcastsRaise()
{
using GatewayMetrics metrics = new();
FakeSessionManager sessions = new();
sessions.SetSnapshot(Snapshot(AlarmA, AlarmConditionState.Active, Ts(0), Ts(0)));
using GatewayAlarmMonitor monitor = CreateMonitor(sessions, metrics, reconcileInterval: TimeSpan.FromMilliseconds(200));
using CancellationTokenSource cts = new();
await monitor.StartAsync(cts.Token);
await WaitUntilAsync(() => monitor.CurrentAlarms.Any(a => a.AlarmFullReference == AlarmA), WaitTimeout);
FeedRecorder feed = FeedRecorder.Start(monitor);
await feed.SnapshotComplete.WaitAsync(WaitTimeout);
sessions.SetSnapshot(Snapshot(AlarmA, AlarmConditionState.Active, Ts(60), Ts(60)));
await feed.WaitForTransitionAsync(AlarmA, AlarmTransitionKind.Raise, WaitTimeout);
AlarmFeedMessage raise = feed.Live.First(m => m.PayloadCase == AlarmFeedMessage.PayloadOneofCase.Transition);
Assert.Equal(Ts(60), raise.Transition.OriginalRaiseTimestamp);
await feed.StopAsync();
await cts.CancelAsync();
await monitor.StopAsync(CancellationToken.None);
}
/// <summary>
/// SEC-009: a worker that rejects the initial QueryActiveAlarms must not leave a
/// healthy-looking monitor with an empty cache; the lifecycle fails and is retried.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task InitialReconcileRejected_FailsTheLifecycle()
{
using GatewayMetrics metrics = new();
FakeSessionManager sessions = new();
sessions.SetReconcileCode(ProtocolStatusCode.MxaccessFailure);
using GatewayAlarmMonitor monitor = CreateMonitor(sessions, metrics);
using CancellationTokenSource cts = new();
await monitor.StartAsync(cts.Token);
await WaitUntilAsync(() => sessions.Opens >= 2, WaitTimeout);
Assert.NotEqual(GatewayAlarmMonitorState.Monitoring, monitor.State);
Assert.Contains("QueryActiveAlarms", monitor.LastError ?? string.Empty, StringComparison.Ordinal);
await cts.CancelAsync();
await monitor.StopAsync(CancellationToken.None);
}
/// <summary>SEC-009: a rejected periodic reconcile is surfaced on LastError and keeps the cache.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task PeriodicReconcileRejected_IsSurfacedAndKeepsTheCache()
{
using GatewayMetrics metrics = new();
FakeSessionManager sessions = new();
sessions.SetSnapshot(Snapshot(AlarmA, AlarmConditionState.Active, Ts(0), Ts(0)));
using GatewayAlarmMonitor monitor = CreateMonitor(sessions, metrics, reconcileInterval: TimeSpan.FromMilliseconds(200));
using CancellationTokenSource cts = new();
await monitor.StartAsync(cts.Token);
await WaitUntilAsync(() => monitor.CurrentAlarms.Count == 1, WaitTimeout);
sessions.SetReconcileCode(ProtocolStatusCode.MxaccessFailure);
await WaitUntilAsync(
() => (monitor.LastError ?? string.Empty).Contains("Alarm reconcile failed", StringComparison.Ordinal),
WaitTimeout);
Assert.Equal(GatewayAlarmMonitorState.Monitoring, monitor.State);
Assert.Single(monitor.CurrentAlarms);
sessions.SetReconcileCode(ProtocolStatusCode.Ok);
await WaitUntilAsync(() => monitor.LastError is null, WaitTimeout);
await cts.CancelAsync();
await monitor.StopAsync(CancellationToken.None);
}
/// <summary>
/// SEC-005: an alarm that returned to normal while the monitor was restarting gets its Clear.
/// The first reconcile of the new lifecycle diffs against the retained previous generation
/// — what the subscriber still holds — instead of an emptied cache. An alarm still active in
/// the same state is not re-raised.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Restart_BroadcastsClearForAlarmsGoneDuringTheGap()
{
using GatewayMetrics metrics = new();
FakeSessionManager sessions = new();
sessions.SetSnapshot(
Snapshot(AlarmA, AlarmConditionState.Active, Ts(0), Ts(0)),
Snapshot(AlarmB, AlarmConditionState.Active, Ts(1), Ts(1)));
using GatewayAlarmMonitor monitor = CreateMonitor(sessions, metrics);
using CancellationTokenSource cts = new();
await monitor.StartAsync(cts.Token);
await WaitUntilAsync(() => monitor.CurrentAlarms.Count == 2, WaitTimeout);
FeedRecorder feed = FeedRecorder.Start(monitor);
await feed.SnapshotComplete.WaitAsync(WaitTimeout);
sessions.SetSnapshot(Snapshot(AlarmA, AlarmConditionState.Active, Ts(0), Ts(0)));
sessions.EndCurrentSession();
await feed.WaitForTransitionAsync(AlarmB, AlarmTransitionKind.Clear, WaitTimeout);
await WaitUntilAsync(() => monitor.State == GatewayAlarmMonitorState.Monitoring && sessions.Opens == 2, WaitTimeout);
Assert.Empty(feed.TransitionsFor(AlarmA));
Assert.Equal(AlarmA, Assert.Single(monitor.CurrentAlarms).AlarmFullReference);
await feed.StopAsync();
await cts.CancelAsync();
await monitor.StopAsync(CancellationToken.None);
}
/// <summary>
/// SEC-005: a subscriber that last saw a Subtag/degraded status is told the restarted
/// lifecycle's baseline (alarm manager) — Auto mode raises no mode-change event at start.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Restart_BroadcastsTheRebaselinedProviderStatus()
{
using GatewayMetrics metrics = new();
FakeSessionManager sessions = new();
using GatewayAlarmMonitor monitor = CreateMonitor(sessions, metrics);
using CancellationTokenSource cts = new();
await monitor.StartAsync(cts.Token);
await WaitUntilAsync(() => monitor.State == GatewayAlarmMonitorState.Monitoring, WaitTimeout);
FeedRecorder feed = FeedRecorder.Start(monitor);
await feed.SnapshotComplete.WaitAsync(WaitTimeout);
sessions.EmitEvent(ModeChange(AlarmProviderMode.Subtag, "alarmmgr failed"));
await WaitUntilAsync(
() => feed.Live.Any(m => m.PayloadCase == AlarmFeedMessage.PayloadOneofCase.ProviderStatus
&& m.ProviderStatus.Mode == AlarmProviderMode.Subtag),
WaitTimeout);
sessions.EndCurrentSession();
await WaitUntilAsync(
() => feed.Live
.Where(m => m.PayloadCase == AlarmFeedMessage.PayloadOneofCase.ProviderStatus)
.SkipWhile(m => m.ProviderStatus.Mode != AlarmProviderMode.Subtag)
.Any(m => m.ProviderStatus.Mode == AlarmProviderMode.Alarmmgr && !m.ProviderStatus.Degraded),
WaitTimeout);
await feed.StopAsync();
await cts.CancelAsync();
await monitor.StopAsync(CancellationToken.None);
}
/// <summary>
/// SEC-005: during the restart gap the retired set is hidden from CurrentAlarms and a
/// subscriber attaching then gets an empty snapshot; the first reconcile of the new
/// lifecycle sends that subscriber every active alarm (acknowledged ones as Raise then
/// Acknowledge).
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task SubscriberAttachedDuringRestartGap_ReceivesTheWholeSet()
{
using GatewayMetrics metrics = new();
FakeSessionManager sessions = new();
sessions.SetSnapshot(
Snapshot(AlarmA, AlarmConditionState.Active, Ts(0), Ts(0)),
Snapshot(AlarmB, AlarmConditionState.ActiveAcked, Ts(1), Ts(2)));
using GatewayAlarmMonitor monitor = CreateMonitor(sessions, metrics, restartBackoff: TimeSpan.FromSeconds(2));
using CancellationTokenSource cts = new();
await monitor.StartAsync(cts.Token);
await WaitUntilAsync(() => monitor.CurrentAlarms.Count == 2, WaitTimeout);
sessions.EndCurrentSession();
await WaitUntilAsync(() => monitor.State == GatewayAlarmMonitorState.Faulted, WaitTimeout);
Assert.Empty(monitor.CurrentAlarms);
FeedRecorder feed = FeedRecorder.Start(monitor);
await feed.SnapshotComplete.WaitAsync(WaitTimeout);
Assert.DoesNotContain(feed.Preamble, m => m.PayloadCase == AlarmFeedMessage.PayloadOneofCase.ActiveAlarm);
await feed.WaitForTransitionAsync(AlarmB, AlarmTransitionKind.Acknowledge, WaitTimeout);
Assert.Equal([AlarmTransitionKind.Raise], feed.TransitionsFor(AlarmA));
Assert.Equal([AlarmTransitionKind.Raise, AlarmTransitionKind.Acknowledge], feed.TransitionsFor(AlarmB));
Assert.Equal(2, monitor.CurrentAlarms.Count);
await feed.StopAsync();
await cts.CancelAsync();
await monitor.StopAsync(CancellationToken.None);
}
/// <summary>
/// SEC-008: the watch-list refresh runs on its own loop, so a Galaxy SQL query that hangs
/// does not hold up the reconcile cadence.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task HungWatchListRefresh_DoesNotDelayReconcile()
{
using GatewayMetrics metrics = new();
FakeSessionManager sessions = new();
HangingAfterFirstResolver resolver = new();
using GatewayAlarmMonitor monitor = CreateMonitor(
sessions,
metrics,
reconcileInterval: TimeSpan.FromMilliseconds(200),
resolver: resolver);
using CancellationTokenSource cts = new();
await monitor.StartAsync(cts.Token);
await WaitUntilAsync(() => monitor.State == GatewayAlarmMonitorState.Monitoring, WaitTimeout);
await WaitUntilAsync(() => resolver.Calls >= 2, WaitTimeout);
int reconcilesWhileHung = sessions.Reconciles;
await WaitUntilAsync(() => sessions.Reconciles >= reconcilesWhileHung + 3, WaitTimeout);
Assert.Equal(2, resolver.Calls);
await cts.CancelAsync();
await monitor.StopAsync(CancellationToken.None);
}
/// <summary>SEC-010: the restart backoff doubles per consecutive failure and is capped at five minutes.</summary>
[Fact]
public void RestartBackoff_IsExponentialAndCapped()
{
TimeSpan initial = TimeSpan.FromSeconds(5);
Assert.Equal(TimeSpan.FromSeconds(5), GatewayAlarmMonitor.ComputeRestartBackoff(initial, 1));
Assert.Equal(TimeSpan.FromSeconds(10), GatewayAlarmMonitor.ComputeRestartBackoff(initial, 2));
Assert.Equal(TimeSpan.FromSeconds(40), GatewayAlarmMonitor.ComputeRestartBackoff(initial, 4));
Assert.Equal(TimeSpan.FromMinutes(5), GatewayAlarmMonitor.ComputeRestartBackoff(initial, 8));
Assert.Equal(TimeSpan.FromMinutes(5), GatewayAlarmMonitor.ComputeRestartBackoff(initial, int.MaxValue));
}
/// <summary>
/// SEC-010: a lifecycle that keeps failing (here a rejected initial reconcile) opens worker
/// sessions at a growing interval rather than at a fixed cadence.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task PermanentLifecycleFailure_BacksOffBetweenAttempts()
{
using GatewayMetrics metrics = new();
FakeSessionManager sessions = new();
sessions.SetReconcileCode(ProtocolStatusCode.MxaccessFailure);
using GatewayAlarmMonitor monitor = CreateMonitor(sessions, metrics, restartBackoff: TimeSpan.FromMilliseconds(200));
using CancellationTokenSource cts = new();
System.Diagnostics.Stopwatch clock = System.Diagnostics.Stopwatch.StartNew();
await monitor.StartAsync(cts.Token);
// Backoffs 200, 400, 800 ms: the fourth open cannot come before ~1.4 s after the first.
await WaitUntilAsync(() => sessions.Opens >= 1, WaitTimeout);
TimeSpan firstOpen = clock.Elapsed;
await WaitUntilAsync(() => sessions.Opens >= 4, WaitTimeout);
Assert.True(clock.Elapsed - firstOpen >= TimeSpan.FromMilliseconds(1_300), $"Opens came too fast: {clock.Elapsed - firstOpen}");
await cts.CancelAsync();
await monitor.StopAsync(CancellationToken.None);
}
internal static GatewayAlarmMonitor CreateMonitor(
FakeSessionManager sessions,
GatewayMetrics metrics,
TimeSpan? reconcileInterval = null,
TimeSpan? restartBackoff = null,
IAlarmWatchListResolver? resolver = null)
{
AlarmsOptions options = new()
{
Enabled = true,
SubscriptionExpression = @"\\NODE\Galaxy!Area",
};
return new GatewayAlarmMonitor(
sessions,
resolver ?? new EmptyWatchListResolver(),
metrics,
Microsoft.Extensions.Options.Options.Create(new GatewayOptions { Alarms = options }),
NullLogger<GatewayAlarmMonitor>.Instance)
{
ReconcileInterval = reconcileInterval ?? TimeSpan.FromMinutes(10),
InitialRestartBackoff = restartBackoff ?? TimeSpan.FromMilliseconds(50),
};
}
internal static Timestamp Ts(int seconds) =>
Timestamp.FromDateTimeOffset(new DateTimeOffset(2026, 12, 3, 9, 0, 0, TimeSpan.Zero).AddSeconds(seconds));
internal static MxEvent Transition(
ulong sequence,
string reference,
AlarmTransitionKind kind,
Timestamp transitionTimestamp,
Timestamp originalRaise) => new()
{
Family = MxEventFamily.OnAlarmTransition,
WorkerSequence = sequence,
OnAlarmTransition = new OnAlarmTransitionEvent
{
AlarmFullReference = reference,
SourceObjectReference = "Tank",
AlarmTypeName = "AnalogLimitAlarm.Hi",
TransitionKind = kind,
Severity = 500,
SourceProvider = AlarmProviderMode.Alarmmgr,
TransitionTimestamp = transitionTimestamp,
OriginalRaiseTimestamp = originalRaise,
},
};
internal static MxEvent ModeChange(AlarmProviderMode mode, string reason) => new()
{
Family = MxEventFamily.OnAlarmProviderModeChanged,
OnAlarmProviderModeChanged = new OnAlarmProviderModeChangedEvent
{
Mode = mode,
Reason = reason,
At = Timestamp.FromDateTimeOffset(DateTimeOffset.UtcNow),
},
};
internal static ActiveAlarmSnapshot Snapshot(
string reference,
AlarmConditionState state,
Timestamp originalRaise,
Timestamp lastTransition) => new()
{
AlarmFullReference = reference,
SourceObjectReference = "Tank",
AlarmTypeName = "AnalogLimitAlarm.Hi",
CurrentState = state,
Severity = 500,
SourceProvider = AlarmProviderMode.Alarmmgr,
OriginalRaiseTimestamp = originalRaise,
LastTransitionTimestamp = lastTransition,
};
internal static Task WaitUntilAsync(Func<bool> condition, TimeSpan timeout)
=> Eventually.WaitUntilAsync(condition, timeout);
/// <summary>Records everything one feed subscription receives after its snapshot preamble.</summary>
internal sealed class FeedRecorder
{
private readonly List<AlarmFeedMessage> _preamble = [];
private readonly List<AlarmFeedMessage> _live = [];
private readonly TaskCompletionSource _snapshotComplete = new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly CancellationTokenSource _cts = new();
private Task _reader = Task.CompletedTask;
/// <summary>Gets a task that completes when the subscription's snapshot sentinel arrives.</summary>
public Task SnapshotComplete => _snapshotComplete.Task;
/// <summary>Gets a copy of the frames received before (and including) the snapshot sentinel.</summary>
public AlarmFeedMessage[] Preamble
{
get { lock (_preamble) { return [.. _preamble]; } }
}
/// <summary>Gets a copy of the frames received after the snapshot sentinel.</summary>
public AlarmFeedMessage[] Live
{
get { lock (_live) { return [.. _live]; } }
}
/// <summary>Starts a feed subscription on the monitor.</summary>
/// <param name="monitor">The monitor to subscribe to.</param>
/// <returns>The recorder.</returns>
public static FeedRecorder Start(GatewayAlarmMonitor monitor)
{
FeedRecorder recorder = new();
recorder._reader = Task.Run(async () =>
{
try
{
await foreach (AlarmFeedMessage message in monitor.StreamAsync(null, recorder._cts.Token))
{
if (recorder._snapshotComplete.Task.IsCompleted)
{
lock (recorder._live)
{
recorder._live.Add(message);
}
}
else
{
lock (recorder._preamble)
{
recorder._preamble.Add(message);
}
if (message.PayloadCase == AlarmFeedMessage.PayloadOneofCase.SnapshotComplete)
{
recorder._snapshotComplete.TrySetResult();
}
}
}
}
catch (OperationCanceledException)
{
// Expected when the test stops the recorder.
}
});
return recorder;
}
/// <summary>Gets the live transitions for one alarm, in arrival order.</summary>
/// <param name="reference">The alarm reference.</param>
/// <returns>The transition kinds.</returns>
public AlarmTransitionKind[] TransitionsFor(string reference) => Live
.Where(m => m.PayloadCase == AlarmFeedMessage.PayloadOneofCase.Transition
&& m.Transition.AlarmFullReference == reference)
.Select(m => m.Transition.TransitionKind)
.ToArray();
/// <summary>Waits for a live transition of the given kind for one alarm.</summary>
/// <param name="reference">The alarm reference.</param>
/// <param name="kind">The transition kind.</param>
/// <param name="timeout">The maximum time to wait.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public Task WaitForTransitionAsync(string reference, AlarmTransitionKind kind, TimeSpan timeout)
=> WaitUntilAsync(() => TransitionsFor(reference).Contains(kind), timeout);
/// <summary>Stops the subscription and waits for the reader to finish.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
public async Task StopAsync()
{
await _cts.CancelAsync();
await _reader;
_cts.Dispose();
}
}
/// <summary>
/// <see cref="IAlarmWatchListResolver"/> whose first call (the subscribe) resolves and
/// every later call hangs until cancelled — a Galaxy SQL server that stopped answering.
/// </summary>
private sealed class HangingAfterFirstResolver : IAlarmWatchListResolver
{
private int _calls;
/// <summary>Gets the number of resolutions started.</summary>
public int Calls => Volatile.Read(ref _calls);
/// <inheritdoc />
public async Task<AlarmWatchListResolution> ResolveAsync(
AlarmsOptions options,
CancellationToken cancellationToken = default)
{
if (Interlocked.Increment(ref _calls) > 1)
{
await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken).ConfigureAwait(false);
}
return new AlarmWatchListResolution(
[],
DiscoveryAttempted: true,
DiscoveryFailed: false,
DiscoveryFailureMessage: null);
}
}
/// <summary><see cref="IAlarmWatchListResolver"/> that resolves an empty watch-list.</summary>
private sealed class EmptyWatchListResolver : IAlarmWatchListResolver
{
/// <inheritdoc />
public Task<AlarmWatchListResolution> ResolveAsync(
AlarmsOptions options,
CancellationToken cancellationToken = default) =>
Task.FromResult(new AlarmWatchListResolution(
[],
DiscoveryAttempted: false,
DiscoveryFailed: false,
DiscoveryFailureMessage: null));
}
/// <summary>
/// <see cref="ISessionManager"/> that opens a genuinely Ready session with a fresh worker
/// event stream per open, answers <c>QueryActiveAlarms</c> from a settable snapshot (or a
/// settable non-OK code), and can park the next reconcile reply until released.
/// </summary>
internal sealed class FakeSessionManager : ISessionManager
{
private readonly object _sync = new();
private Channel<WorkerEvent> _events = Channel.CreateUnbounded<WorkerEvent>();
private ActiveAlarmSnapshot[] _snapshot = [];
private ProtocolStatusCode _reconcileCode = ProtocolStatusCode.Ok;
private TaskCompletionSource? _reconcileGate;
private TaskCompletionSource _reconcileParked = new(TaskCreationOptions.RunContinuationsAsynchronously);
private int _opens;
private int _reconciles;
/// <summary>Gets the number of sessions opened so far.</summary>
public int Opens => Volatile.Read(ref _opens);
/// <summary>Gets the number of <c>QueryActiveAlarms</c> commands received so far.</summary>
public int Reconciles => Volatile.Read(ref _reconciles);
/// <summary>Sets the snapshot every reconcile returns.</summary>
/// <param name="snapshots">The snapshots.</param>
public void SetSnapshot(params ActiveAlarmSnapshot[] snapshots)
{
lock (_sync)
{
_snapshot = snapshots;
}
}
/// <summary>Sets the protocol status every reconcile replies with.</summary>
/// <param name="code">The status code.</param>
public void SetReconcileCode(ProtocolStatusCode code)
{
lock (_sync)
{
_reconcileCode = code;
}
}
/// <summary>
/// Parks the next reconcile after it captures its reply snapshot, until
/// <see cref="ReleaseReconcile"/>. <see cref="ReconcileParked"/> completes when it parks.
/// </summary>
public void HoldNextReconcile()
{
lock (_sync)
{
_reconcileGate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
_reconcileParked = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
}
}
/// <summary>Gets a task that completes when a held reconcile has parked.</summary>
public Task ReconcileParked
{
get { lock (_sync) { return _reconcileParked.Task; } }
}
/// <summary>Releases a reconcile parked by <see cref="HoldNextReconcile"/>.</summary>
public void ReleaseReconcile()
{
lock (_sync)
{
_reconcileGate?.TrySetResult();
_reconcileGate = null;
}
}
/// <summary>Pushes a worker event into the current session's distributor pump.</summary>
/// <param name="mxEvent">The event.</param>
public void EmitEvent(MxEvent mxEvent)
{
lock (_sync)
{
_events.Writer.TryWrite(new WorkerEvent { Event = mxEvent });
}
}
/// <summary>Ends the current session's worker event stream, as a worker exit would.</summary>
public void EndCurrentSession()
{
lock (_sync)
{
_events.Writer.TryComplete();
}
}
/// <inheritdoc />
public Task<GatewaySession> OpenSessionAsync(
SessionOpenRequest request,
string? clientIdentity,
string? ownerKeyId,
CancellationToken cancellationToken)
{
Channel<WorkerEvent> events = Channel.CreateUnbounded<WorkerEvent>();
lock (_sync)
{
_events = events;
}
Interlocked.Increment(ref _opens);
GatewaySession session = new(
Guid.NewGuid().ToString("N"),
"Galaxy",
"pipe-test",
"nonce-test",
clientIdentity,
null,
null,
TimeSpan.FromSeconds(30),
TimeSpan.FromSeconds(30),
TimeSpan.FromSeconds(30),
DateTimeOffset.UtcNow);
session.AttachWorkerClient(new ChannelWorkerClient(session.SessionId, events.Reader));
session.MarkReady();
return Task.FromResult(session);
}
/// <inheritdoc />
public async Task<WorkerCommandReply> InvokeAsync(
string sessionId,
WorkerCommand command,
CancellationToken cancellationToken)
{
MxCommandReply reply = new()
{
ProtocolStatus = new ProtocolStatus { Code = ProtocolStatusCode.Ok },
};
if (command.Command?.Kind == MxCommandKind.QueryActiveAlarms)
{
Interlocked.Increment(ref _reconciles);
QueryActiveAlarmsReplyPayload payload = new();
Task? gate;
lock (_sync)
{
reply.ProtocolStatus.Code = _reconcileCode;
payload.Snapshots.AddRange(_snapshot.Select(snapshot => snapshot.Clone()));
gate = _reconcileGate?.Task;
if (gate is not null)
{
_reconcileParked.TrySetResult();
}
}
if (gate is not null)
{
await gate.WaitAsync(cancellationToken).ConfigureAwait(false);
}
if (reply.ProtocolStatus.Code == ProtocolStatusCode.Ok)
{
reply.QueryActiveAlarms = payload;
}
}
return new WorkerCommandReply { Reply = reply };
}
/// <inheritdoc />
public bool TryGetSession(string sessionId, [MaybeNullWhen(false)] out GatewaySession session)
{
session = null;
return false;
}
/// <inheritdoc />
public Task<SessionCloseResult> CloseSessionAsync(string sessionId, CancellationToken cancellationToken)
{
EndCurrentSession();
return Task.FromResult(new SessionCloseResult(sessionId, SessionState.Closed, AlreadyClosed: false));
}
/// <inheritdoc />
public Task<SessionCloseResult> KillWorkerAsync(string sessionId, string reason, CancellationToken cancellationToken) =>
Task.FromResult(new SessionCloseResult(sessionId, SessionState.Closed, AlreadyClosed: false));
/// <inheritdoc />
public Task<int> CloseExpiredLeasesAsync(DateTimeOffset now, CancellationToken cancellationToken) =>
Task.FromResult(0);
/// <inheritdoc />
public Task ShutdownAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}
}
@@ -704,6 +704,57 @@ public sealed class GatewayOptionsValidatorTests
f => f.Contains("MxGateway:Events:ReplayRetentionSeconds"));
}
/// <summary>
/// SEC-011: a retention past one day, or a non-finite one, fails at startup; otherwise
/// <c>TimeSpan.FromSeconds</c> throws when the first event distributor is built.
/// </summary>
/// <param name="seconds">Retention under test.</param>
[Theory]
[InlineData(86_400.5)]
[InlineData(1e12)]
[InlineData(double.PositiveInfinity)]
[InlineData(double.NaN)]
public void Validate_Fails_WhenReplayRetentionSecondsIsOutOfRange(double seconds)
{
GatewayOptions options = CloneWithEvents(
ValidOptions(),
new EventOptions { ReplayRetentionSeconds = seconds });
ValidateOptionsResult result = new GatewayOptionsValidator().Validate(null, options);
Assert.True(result.Failed);
Assert.Contains(
result.Failures!,
f => f.Contains("MxGateway:Events:ReplayRetentionSeconds", StringComparison.Ordinal));
}
/// <summary>SEC-011: the alarm reconcile interval must be between 1 second and one day when alarms are enabled.</summary>
/// <param name="seconds">Interval under test.</param>
/// <param name="valid">Whether the interval is expected to validate.</param>
[Theory]
[InlineData(0, false)]
[InlineData(-5, false)]
[InlineData(1, true)]
[InlineData(30, true)]
[InlineData(86_400, true)]
[InlineData(86_401, false)]
[InlineData(int.MaxValue, false)]
public void Validate_AlarmReconcileIntervalBounds(int seconds, bool valid)
{
GatewayOptions options = CloneWithAlarms(
ValidOptions(),
new AlarmsOptions
{
Enabled = true,
DefaultArea = "Galaxy",
ReconcileIntervalSeconds = seconds,
});
ValidateOptionsResult result = new GatewayOptionsValidator().Validate(null, options);
bool reported = result.Failures?.Any(
f => f.Contains("MxGateway:Alarms:ReconcileIntervalSeconds", StringComparison.Ordinal)) ?? false;
Assert.Equal(!valid, reported);
}
/// <summary>Verifies a zero <see cref="EventOptions.ReplayRetentionSeconds"/> passes validation.</summary>
[Fact]
public void Validate_Succeeds_WhenReplayRetentionSecondsIsZero()
@@ -287,6 +287,47 @@ public sealed class AlarmsHubPublisherTests
};
}
/// <summary>
/// DSH-005: a client connecting long after the publisher subscribed is primed with the
/// current state itself — a generation-0 reset, then the status frames, every active
/// alarm (values redacted) and the snapshot sentinel — without any new transition.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task PrimeConnectionAsync_SendsResetThenTheCurrentSnapshot()
{
AlarmFeedMessage activeOne = BuildActiveAlarm();
AlarmFeedMessage activeTwo = BuildActiveAlarm();
activeTwo.ActiveAlarm.AlarmFullReference = "Tank03.Level.Hi";
ScriptedAlarmService service = new(
[
new AlarmFeedMessage { ProviderStatus = new AlarmProviderStatus { Mode = AlarmProviderMode.Subtag, Degraded = true } },
new AlarmFeedMessage { SnapshotStatus = new AlarmSnapshotStatus { Truncated = false } },
activeOne,
activeTwo,
new AlarmFeedMessage { SnapshotComplete = true },
]);
CapturingClientProxy caller = new();
using CancellationTokenSource cts = new(TestTimeout);
await AlarmsHubPublisher.PrimeConnectionAsync(service, caller, showTagValues: false, cts.Token);
IReadOnlyList<(string Method, object? Argument)> frames = caller.Frames;
Assert.Equal(6, frames.Count);
Assert.Equal(AlarmsHub.ResetMessage, frames[0].Method);
Assert.Equal(new AlarmFeedReset(0), frames[0].Argument);
Assert.All(frames.Skip(1), frame => Assert.Equal(AlarmsHub.AlarmMessage, frame.Method));
IReadOnlyList<AlarmFeedMessage> sent = caller.Sent;
Assert.Equal(AlarmProviderMode.Subtag, sent[0].ProviderStatus.Mode);
Assert.Equal(AlarmFeedMessage.PayloadOneofCase.SnapshotStatus, sent[1].PayloadCase);
Assert.Equal("Tank02.Level.Lo", sent[2].ActiveAlarm.AlarmFullReference);
Assert.Equal("Tank03.Level.Hi", sent[3].ActiveAlarm.AlarmFullReference);
Assert.Null(sent[2].ActiveAlarm.CurrentValue);
Assert.Null(sent[3].ActiveAlarm.CurrentValue);
Assert.True(sent[4].SnapshotComplete);
}
/// <summary>
/// Yields one scripted batch per subscription. Every batch but the last ends its
/// stream — the monitor completing a subscription — so the publisher resubscribes;
@@ -107,4 +107,40 @@ public sealed class ApiKeyConstraintSerializerTests
Assert.Same(ApiKeyConstraints.Empty, ApiKeyConstraintSerializer.Deserialize(null));
Assert.Empty(ApiKeyConstraints.Empty.DashboardTags);
}
/// <summary>
/// SEC-013: a sparse blob (hand-edited, or written by another tool) omits list members.
/// Every absent list must come back empty rather than null, so the constraint checks and
/// the browse-scope provider never dereference or pass on a null list.
/// </summary>
[Fact]
public void Deserialize_SparseJson_YieldsEmptyListsNotNull()
{
ApiKeyConstraints constraints = ApiKeyConstraintSerializer.Deserialize("""{"read_subtrees":["A*"]}""");
Assert.Equal(["A*"], constraints.ReadSubtrees);
Assert.NotNull(constraints.WriteSubtrees);
Assert.NotNull(constraints.ReadTagGlobs);
Assert.NotNull(constraints.WriteTagGlobs);
Assert.NotNull(constraints.BrowseSubtrees);
Assert.Empty(constraints.BrowseSubtrees);
Assert.True(constraints.HasReadConstraints);
Assert.False(constraints.HasWriteConstraints);
Assert.False(constraints.IsEmpty);
}
/// <summary>SEC-013: explicit JSON nulls for the list members normalize to empty lists too.</summary>
[Fact]
public void Deserialize_ExplicitNullLists_YieldEmptyLists()
{
ApiKeyConstraints constraints = ApiKeyConstraintSerializer.Deserialize(
"""{"read_subtrees":null,"write_subtrees":null,"read_tag_globs":null,"write_tag_globs":null,"browse_subtrees":null,"read_alarm_only":true}""");
Assert.Empty(constraints.ReadSubtrees);
Assert.Empty(constraints.WriteSubtrees);
Assert.Empty(constraints.ReadTagGlobs);
Assert.Empty(constraints.WriteTagGlobs);
Assert.Empty(constraints.BrowseSubtrees);
Assert.True(constraints.HasReadConstraints);
}
}
@@ -151,12 +151,207 @@ public sealed class FailoverAlarmConsumerTests
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
{
Record = new MxAlarmSnapshotRecord { AlarmGuid = Guid.NewGuid() },
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>
[Fact]
public void Primary_FailsThresholdTimes_SwitchesToSubtag()
@@ -209,10 +404,11 @@ public sealed class FailoverAlarmConsumerTests
[Fact]
public void WhileDegraded_PrimaryHeals_FailsBackAfterStableProbes()
{
// threshold=1 so the initial Subscribe failure (PollOnce path) immediately
// switches to Subtag. stableProbes=2 means two consecutive clean PollOnce
// calls are needed before failback. ProbeOnce must NOT call Subscribe —
// WnWrapAlarmConsumer is single-subscribe; re-calling would always throw.
// The primary subscribes, then its polls start failing: threshold=1 so
// the first failed poll switches to Subtag. stableProbes=2 means two
// consecutive clean PollOnce calls are needed before failback. ProbeOnce
// must NOT call Subscribe on the subscribed primary — WnWrapAlarmConsumer
// is single-subscribe; re-calling would always throw.
FlakyPrimary primary = new FlakyPrimary { ThrowOnPoll = true };
StubStandby standby = new StubStandby();
FailoverSettings settings = new FailoverSettings(threshold: 1, probeIntervalSeconds: 0, stableProbes: 2);
@@ -221,7 +417,7 @@ public sealed class FailoverAlarmConsumerTests
List<AlarmProviderModeChange> changes = new List<AlarmProviderModeChange>();
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.Equal(AlarmProviderMode.Subtag, changes[changes.Count - 1].Mode);
@@ -279,16 +475,17 @@ public sealed class FailoverAlarmConsumerTests
[Fact]
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 };
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"); // Subscribe attempt (throws) → Subtag
FailOverAfterHealthySubscribe(sut, primary);
// 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;
Assert.Equal(1, subscribeCountAfterSetup);
Assert.Equal(AlarmProviderMode.Subtag, sut.Mode);
@@ -379,7 +576,7 @@ public sealed class FailoverAlarmConsumerTests
var primary = new FlakyPrimary { ThrowOnPoll = true };
var standby = new StubStandby();
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);
primary.ThrowOnPoll = false;
@@ -478,14 +675,15 @@ public sealed class FailoverAlarmConsumerTests
FailoverSettings settings = new FailoverSettings(threshold: 1, probeIntervalSeconds: 3600, stableProbes: 5);
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);
primary.ThrowOnPoll = false; // primary healthy so a probe would poll cleanly
int pollsBeforeProbe = primary.Polls;
sut.ProbeOnce(); // first probe runs: re-polls the primary
int pollsAfterFirstProbe = primary.Polls;
Assert.Equal(1, pollsAfterFirstProbe);
Assert.Equal(pollsBeforeProbe + 1, pollsAfterFirstProbe);
sut.ProbeOnce(); // within the 3600s interval → throttled, must NOT re-poll
@@ -75,6 +75,28 @@ public sealed class LmxSubtagAlarmSourceTests
Assert.Equal(DateTimeKind.Utc, received.TimestampUtc.Kind);
}
/// <summary>
/// Verifies the item quality reaches the normalized change, so the state
/// machine can hold state across a bad-quality update (MXA-005).
/// </summary>
[Fact]
public void HandleDataChange_CarriesQuality()
{
var server = new RecordingMxAccessServer();
using var source = new LmxSubtagAlarmSource(server, FakeServerHandle);
source.Advise(new[] { "Tank1.Alarm.InAlarm" });
int itemHandle = server.LastItemHandleFor("Tank1.Alarm.InAlarm");
SubtagValueChange? received = null;
source.ValueChanged += (_, change) => received = change;
source.HandleDataChange(itemHandle, pvItemValue: null, pftItemTimeStamp: null, quality: 0x08);
Assert.NotNull(received);
Assert.Equal(0x08, received!.Quality);
}
/// <summary>
/// Verifies <c>OnDataChange</c> for an unknown item handle is ignored
/// (no <see cref="LmxSubtagAlarmSource.ValueChanged"/> raised).
@@ -203,7 +203,11 @@ public sealed class SubtagAlarmStateMachineTests
/// active must emit nothing and must NOT latch
/// <c>AckedDuringEpisode</c> — otherwise a stale ack from a prior episode
/// would mis-latch the next raise into a spurious ACK_RTN on clear. The
/// subsequent raise/clear must therefore still emit UNACK_RTN.
/// subsequent raise/clear must therefore still emit UNACK_RTN. The
/// initial-sync <c>.active = false</c> is what marks the stale ack as a
/// prior episode's (an ack buffered before the FIRST <c>.active</c> value
/// is the initial state of an already-acked alarm — see
/// <see cref="AckedBeforeActive_AtInitialSync_KeepsTheAck"/>).
/// </summary>
[Fact]
public void AckedTrueWhileInactive_EmitsNothingAndDoesNotLatch()
@@ -215,6 +219,9 @@ public sealed class SubtagAlarmStateMachineTests
var ackEvents = sm.Apply("Tank01.Level.HiHi.acked", true, ts);
Assert.Empty(ackEvents);
// Initial sync: the alarm is not active.
Assert.Empty(sm.Apply("Tank01.Level.HiHi.active", false, ts.AddSeconds(1)));
// A fresh episode: raise then clear. Because the earlier ack must not
// have latched AckedDuringEpisode, the clear must be UNACK_RTN.
sm.Apply("Tank01.Level.HiHi.active", true, ts.AddSeconds(5));
@@ -257,4 +264,88 @@ public sealed class SubtagAlarmStateMachineTests
var snap = Assert.Single(sm.SnapshotActive());
Assert.Equal(750, snap.Priority);
}
/// <summary>
/// MXA-007: an alarm that is already active and acknowledged at subscribe
/// time may deliver <c>.acked = true</c> before <c>.active = true</c>. The
/// buffered ack is the alarm's real state and must survive the initial
/// raise; no later <c>.acked</c> change would restore it.
/// </summary>
[Fact]
public void AckedBeforeActive_AtInitialSync_KeepsTheAck()
{
var sm = new SubtagAlarmStateMachine(new[] { Target() });
var ts = new DateTime(2026, 6, 13, 9, 0, 0, DateTimeKind.Utc);
Assert.Empty(sm.Apply("Tank01.Level.HiHi.acked", true, ts));
var raise = Assert.Single(sm.Apply("Tank01.Level.HiHi.active", true, ts));
Assert.Equal(MxAlarmStateKind.AckAlm, raise.Record.State);
Assert.Equal(MxAlarmStateKind.AckAlm, Assert.Single(sm.SnapshotActive()).State);
// Its return is an acknowledged return.
var clear = Assert.Single(sm.Apply("Tank01.Level.HiHi.active", false, ts.AddSeconds(10)));
Assert.Equal(MxAlarmStateKind.AckRtn, clear.Record.State);
}
/// <summary>
/// MXA-007 boundary: once the initial sync is over, a raise is a new
/// episode and starts unacknowledged even if the acked subtag still reads
/// true from the previous episode.
/// </summary>
[Fact]
public void RaiseAfterInitialSync_StartsUnacknowledged()
{
var sm = new SubtagAlarmStateMachine(new[] { Target() });
var ts = new DateTime(2026, 6, 13, 9, 0, 0, DateTimeKind.Utc);
sm.Apply("Tank01.Level.HiHi.active", true, ts);
sm.Apply("Tank01.Level.HiHi.acked", true, ts.AddSeconds(1));
sm.Apply("Tank01.Level.HiHi.active", false, ts.AddSeconds(2));
var raise = Assert.Single(sm.Apply("Tank01.Level.HiHi.active", true, ts.AddSeconds(3)));
Assert.Equal(MxAlarmStateKind.UnackAlm, raise.Record.State);
}
/// <summary>
/// MXA-005: an <c>.active</c> update with an empty value (what MXAccess
/// delivers for an off-scan engine or an unresolved reference) must not
/// read as a return to normal. The alarm holds its last known state.
/// </summary>
[Fact]
public void ActiveUpdateWithNullValue_HoldsState()
{
var sm = new SubtagAlarmStateMachine(new[] { Target() });
var ts = new DateTime(2026, 6, 13, 9, 0, 0, DateTimeKind.Utc);
sm.Apply("Tank01.Level.HiHi.active", true, ts);
var events = sm.Apply("Tank01.Level.HiHi.active", null, ts.AddSeconds(5), quality: 0);
Assert.Empty(events);
Assert.Equal(MxAlarmStateKind.UnackAlm, Assert.Single(sm.SnapshotActive()).State);
}
/// <summary>
/// MXA-005: a bad- or uncertain-quality update is ignored even when it
/// carries a value; a later good update applies normally.
/// </summary>
/// <param name="quality">The non-good MXAccess quality.</param>
[Theory]
[InlineData(0x00)] // Bad
[InlineData(0x08)] // Bad: not connected
[InlineData(0x40)] // Uncertain
public void ActiveOrAckedUpdateWithNonGoodQuality_IsIgnored(int quality)
{
var sm = new SubtagAlarmStateMachine(new[] { Target() });
var ts = new DateTime(2026, 6, 13, 9, 0, 0, DateTimeKind.Utc);
sm.Apply("Tank01.Level.HiHi.active", true, ts, quality: 0xC0);
Assert.Empty(sm.Apply("Tank01.Level.HiHi.active", false, ts.AddSeconds(1), quality));
Assert.Empty(sm.Apply("Tank01.Level.HiHi.acked", true, ts.AddSeconds(2), quality));
Assert.Equal(MxAlarmStateKind.UnackAlm, Assert.Single(sm.SnapshotActive()).State);
// Good quality again: the clear is real.
var clear = Assert.Single(sm.Apply("Tank01.Level.HiHi.active", false, ts.AddSeconds(3), quality: 0xC0));
Assert.Equal(MxAlarmStateKind.UnackRtn, clear.Record.State);
}
}
@@ -255,7 +255,9 @@ public sealed class AlarmCommandHandler : IAlarmCommandHandler
failoverConfig?.ConsecutiveFailureThreshold ?? 3,
failoverConfig?.FailbackProbeIntervalSeconds ?? 30,
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
{
@@ -54,11 +54,21 @@ public sealed class FailoverAlarmConsumer : IMxAccessAlarmConsumer
Standby,
}
private readonly IMxAccessAlarmConsumer primary;
private readonly Func<IMxAccessAlarmConsumer>? primaryFactory;
private IMxAccessAlarmConsumer primary;
private IMxAccessAlarmConsumer standby;
private readonly FailoverSettings settings;
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 int consecutiveFailures;
private int cleanProbes;
@@ -75,8 +85,34 @@ public sealed class FailoverAlarmConsumer : IMxAccessAlarmConsumer
IMxAccessAlarmConsumer primary,
IMxAccessAlarmConsumer standby,
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.primaryFactory = primaryFactory;
this.standby = standby ?? throw new ArgumentNullException(nameof(standby));
this.settings = settings ?? throw new ArgumentNullException(nameof(settings));
@@ -138,22 +174,23 @@ public sealed class FailoverAlarmConsumer : IMxAccessAlarmConsumer
{
if (disposed) throw new ObjectDisposedException(nameof(FailoverAlarmConsumer));
// The primary is not torn down on failover and is therefore never
// re-subscribed during ProbeOnce, so the subscription expression does
// not need to be retained here.
// Retained so a primary whose subscribe failed can be rebuilt and
// subscribed later (EnsurePrimarySubscribed). A primary that did
// 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.
// 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
// failover counter.
standby.Subscribe(subscription);
standby.Subscribe(this.subscription);
// Drive the primary subscribe through the failure-counting wrapper so
// a COM failure here counts toward the failover threshold instead of
// escaping. Swallowing the exception is deliberate: the standby is
// already armed, so a failed primary subscribe just nudges the state
// machine toward (or into) standby rather than aborting startup.
RunPrimary(() => primary.Subscribe(subscription), "Subscribe");
RunPrimary(SubscribePrimary, "Subscribe");
}
/// <inheritdoc />
@@ -163,7 +200,16 @@ public sealed class FailoverAlarmConsumer : IMxAccessAlarmConsumer
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;
}
@@ -211,13 +257,14 @@ public sealed class FailoverAlarmConsumer : IMxAccessAlarmConsumer
/// successful initial subscribe).
/// </para>
/// <para>
/// <strong>Known v1 limitation.</strong> If the <em>original</em>
/// <c>Subscribe</c> itself failed (i.e., the primary never reached a
/// subscribed state — only reachable when
/// <see cref="FailoverSettings.Threshold"/> is 1), polling alone
/// cannot re-establish the subscription. That edge case is accepted
/// for v1: the operator must restart the session to force a fresh
/// subscribe attempt.
/// <strong>A primary that never subscribed.</strong> If the
/// <em>original</em> <c>Subscribe</c> failed, the primary is not
/// subscribed and its <c>PollOnce</c> would return without touching
/// COM — a silent "success". The probe therefore first rebuilds and
/// subscribes a fresh primary through the primary factory; until that
/// succeeds every probe fails, so the consumer never announces
/// "recovered" onto a dead primary (MXA-001). Without a factory the
/// primary cannot recover and the consumer stays on the standby.
/// </para>
/// </remarks>
public void ProbeOnce()
@@ -237,10 +284,13 @@ public sealed class FailoverAlarmConsumer : IMxAccessAlarmConsumer
try
{
// Re-poll the still-subscribed primary. Do NOT call Subscribe —
// WnWrapAlarmConsumer is single-subscribe and the primary remains
// subscribed across the failover; calling Subscribe again would
// always throw InvalidOperationException and prevent failback.
// Re-poll the still-subscribed primary. Do NOT call Subscribe on a
// subscribed primary — WnWrapAlarmConsumer is single-subscribe and
// the primary remains subscribed across the failover; calling
// Subscribe again would always throw InvalidOperationException and
// prevent failback. Only a primary that never subscribed is
// replaced and subscribed here.
EnsurePrimarySubscribed();
primary.PollOnce();
}
catch (Exception)
@@ -281,6 +331,58 @@ public sealed class FailoverAlarmConsumer : IMxAccessAlarmConsumer
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>
/// Runs a primary COM action, counting consecutive failures. A
/// <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)
{
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)
{
SwitchToStandby($"primary {operation} failed", hresult);
@@ -403,4 +505,19 @@ public sealed class FailoverAlarmConsumer : IMxAccessAlarmConsumer
primary.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;
}
}
}
@@ -85,9 +85,9 @@ public sealed class LmxSubtagAlarmSource : ISubtagAlarmSource
/// bypassing the live COM factory. Exposed via
/// <c>InternalsVisibleTo("ZB.MOM.WW.MxGateway.Worker.Tests")</c> so tests can
/// exercise <see cref="Advise"/> and
/// <see cref="HandleDataChange"/> without a live <c>LMXProxyServerClass</c>.
/// <see cref="HandleDataChange(int, object, object, int?)"/> without a live <c>LMXProxyServerClass</c>.
/// No COM event source is wired in this mode — tests drive
/// <see cref="HandleDataChange"/> directly to simulate an
/// <see cref="HandleDataChange(int, object, object, int?)"/> directly to simulate an
/// <c>OnDataChange</c> callback.
/// </summary>
/// <param name="server">The server abstraction to drive.</param>
@@ -154,6 +154,21 @@ public sealed class LmxSubtagAlarmSource : ISubtagAlarmSource
int phItemHandle,
object? pvItemValue,
object? pftItemTimeStamp)
=> HandleDataChange(phItemHandle, pvItemValue, pftItemTimeStamp, quality: null);
/// <summary>
/// Normalizes an MXAccess <c>OnDataChange</c> callback, carrying the
/// item quality, into a <see cref="SubtagValueChange"/>.
/// </summary>
/// <param name="phItemHandle">The MXAccess item handle that changed.</param>
/// <param name="pvItemValue">The new item value (left as a boxed COM variant; the state machine coerces it).</param>
/// <param name="pftItemTimeStamp">The item timestamp as delivered by MXAccess (a culture-formatted string).</param>
/// <param name="quality">The MXAccess item quality, or <see langword="null"/> when not reported.</param>
internal void HandleDataChange(
int phItemHandle,
object? pvItemValue,
object? pftItemTimeStamp,
int? quality)
{
if (!addressesByItemHandle.TryGetValue(phItemHandle, out string? itemAddress))
{
@@ -174,6 +189,7 @@ public sealed class LmxSubtagAlarmSource : ISubtagAlarmSource
ItemAddress = itemAddress,
Value = pvItemValue,
TimestampUtc = timestampUtc,
Quality = quality,
});
}
@@ -279,8 +295,10 @@ public sealed class LmxSubtagAlarmSource : ISubtagAlarmSource
/// <summary>
/// COM <c>OnDataChange</c> delegate target. Forwards to
/// <see cref="HandleDataChange"/>; the quality, status array, and server
/// handle carry no information the subtag fallback needs.
/// <see cref="HandleDataChange(int, object, object, int?)"/> with the
/// item quality, which the state machine uses to hold an alarm's state
/// across a bad-quality update; the status array and server handle carry
/// no information the subtag fallback needs.
/// </summary>
private void OnDataChange(
int hLMXServerHandle,
@@ -290,7 +308,7 @@ public sealed class LmxSubtagAlarmSource : ISubtagAlarmSource
object pftItemTimeStamp,
ref MXSTATUS_PROXY[] pVars)
{
HandleDataChange(phItemHandle, pvItemValue, pftItemTimeStamp);
HandleDataChange(phItemHandle, pvItemValue, pftItemTimeStamp, pwItemQuality);
}
private static DateTime ConvertTimestampUtc(object? pftItemTimeStamp)
@@ -197,7 +197,7 @@ public sealed class SubtagAlarmConsumer : IMxAccessAlarmConsumer
}
IReadOnlyList<MxAlarmTransitionEvent> transitions =
stateMachine.Apply(change.ItemAddress, change.Value, change.TimestampUtc);
stateMachine.Apply(change.ItemAddress, change.Value, change.TimestampUtc, change.Quality);
if (transitions.Count == 0)
{
return;
@@ -66,14 +66,45 @@ public sealed class SubtagAlarmStateMachine
}
/// <summary>
/// Applies a single subtag value change and returns any synthesized
/// transitions. Unknown addresses and no-op changes return an empty list.
/// Applies a single subtag value change whose quality is not reported
/// and returns any synthesized transitions. Unknown addresses and no-op
/// changes return an empty list.
/// </summary>
/// <param name="itemAddress">The subtag address whose value changed.</param>
/// <param name="value">The new value (bool, numeric, or string).</param>
/// <param name="timestampUtc">The UTC timestamp of the change.</param>
/// <returns>The synthesized alarm transitions, if any.</returns>
public IReadOnlyList<MxAlarmTransitionEvent> Apply(string itemAddress, object? value, DateTime timestampUtc)
=> Apply(itemAddress, value, timestampUtc, quality: null);
/// <summary>
/// Applies a single subtag value change and returns any synthesized
/// transitions. Unknown addresses, no-op changes, and state updates that
/// carry no trustworthy value return an empty list.
/// </summary>
/// <remarks>
/// An <c>.active</c> or <c>.acked</c> update whose quality is not good,
/// or whose value is empty, is ignored and the alarm keeps its last known
/// state. MXAccess reports an off-scan engine or an unresolved reference
/// with a bad quality and (typically) an empty value; coercing that to
/// <see langword="false"/> would report every active alarm on the object
/// as returned to normal when nothing is known about it (MXA-005). The
/// subtag provider is already reported as degraded whenever it serves, so
/// holding state needs no further signal.
/// </remarks>
/// <param name="itemAddress">The subtag address whose value changed.</param>
/// <param name="value">The new value (bool, numeric, or string).</param>
/// <param name="timestampUtc">The UTC timestamp of the change.</param>
/// <param name="quality">
/// The MXAccess (OPC-style) quality of the update, or <see langword="null"/>
/// when the source does not report one.
/// </param>
/// <returns>The synthesized alarm transitions, if any.</returns>
public IReadOnlyList<MxAlarmTransitionEvent> Apply(
string itemAddress,
object? value,
DateTime timestampUtc,
int? quality)
{
if (itemAddress is null || !_bindingsByAddress.TryGetValue(itemAddress, out SubtagBinding binding))
{
@@ -81,6 +112,12 @@ public sealed class SubtagAlarmStateMachine
}
AlarmState state = binding.State;
if ((binding.Role is SubtagRole.Active or SubtagRole.Acked)
&& (value is null || (quality.HasValue && !IsGoodQuality(quality.Value))))
{
return NoEvents;
}
switch (binding.Role)
{
case SubtagRole.Active:
@@ -117,8 +154,16 @@ public sealed class SubtagAlarmStateMachine
return records;
}
// OPC-style quality: the top two bits of the low byte are 11 for Good.
private static bool IsGoodQuality(int quality) => (quality & 0xC0) == 0xC0;
private IReadOnlyList<MxAlarmTransitionEvent> ApplyActive(AlarmState state, bool newActive, DateTime timestampUtc)
{
// The first usable .active value of this subscription is the initial
// sync, not an observed raise.
bool initialSync = !state.ActiveObserved;
state.ActiveObserved = true;
if (newActive == state.Active)
{
return NoEvents;
@@ -126,13 +171,24 @@ public sealed class SubtagAlarmStateMachine
if (newActive)
{
// false -> true: alarm raised, initially unacknowledged.
// false -> true: alarm raised, initially unacknowledged — except at
// initial sync, where an alarm that is already active and
// acknowledged may deliver its .acked = true before its
// .active = true. That buffered ack is the alarm's real state, and
// no further .acked change will arrive to restore it, so it is kept
// (MXA-007). A raise seen after initial sync is a new episode and
// starts unacknowledged.
bool alreadyAcked = initialSync && state.Acked;
MxAlarmStateKind previous = state.DerivedState();
state.Active = true;
state.Acked = false;
state.AckedDuringEpisode = false;
state.Acked = alreadyAcked;
state.AckedDuringEpisode = alreadyAcked;
state.FirstRaiseUtc = timestampUtc;
return Single(state, MxAlarmStateKind.UnackAlm, previous, timestampUtc);
return Single(
state,
alreadyAcked ? MxAlarmStateKind.AckAlm : MxAlarmStateKind.UnackAlm,
previous,
timestampUtc);
}
else
{
@@ -309,6 +365,13 @@ public sealed class SubtagAlarmStateMachine
/// <summary>Gets or sets whether the alarm is currently acknowledged.</summary>
public bool Acked { get; set; }
/// <summary>
/// Gets or sets whether a usable <c>.active</c> value has been applied
/// since subscribe. Until then an <c>.acked</c> value is buffered state
/// from the initial sync rather than an acknowledgement of a raise.
/// </summary>
public bool ActiveObserved { get; set; }
/// <summary>
/// Latches that the alarm was acknowledged at some point during the
/// current active episode, so a clear emits ACK_RTN even when the
@@ -13,4 +13,12 @@ public sealed class SubtagValueChange
/// <summary>Gets or sets the UTC timestamp the change was observed.</summary>
public DateTime TimestampUtc { get; set; }
/// <summary>
/// Gets or sets the MXAccess (OPC-style) quality of the update, or
/// <see langword="null"/> when the source does not report one. A
/// non-good quality makes the state machine hold the alarm's last
/// known state instead of coercing the value.
/// </summary>
public int? Quality { get; set; }
}