fix(galaxy): clear told-active alarms absent from a complete snapshot (#944); handle provider_status/snapshot_status, withhold truncated snapshots (#945)

#944: a snapshot/QueryActiveAlarms lists active alarms only, so a Clear dropped while the
host's OnAlarmEvent handler was detached (or the stream was down) was never recovered. The
driver records which alarms it delivered as active; on a COMPLETE read (sentinel or re-read,
new IGalaxyAlarmFeed.ActiveSetDelivered, raised under the dispatch lock) it synthesises a
restatement Clear for told-active alarms of the live subscription the read does not name,
before the known-state signal. A re-read counts alarms the live stream restated meanwhile as present.

#945: provider_status / snapshot_status no longer fall to the decode-failure default (logged +
counters). A snapshot flagged truncated (snapshot_status or per-record flag) is not complete: no
sweep, no known-state signal; when the gateway clears the verdict the driver re-reads.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Joseph Doherty
2026-12-01 19:29:41 -05:00
parent 6b60845931
commit 6d1d5ed559
5 changed files with 744 additions and 15 deletions
+5 -1
View File
@@ -214,9 +214,13 @@ Every (re)open of `StreamAlarms` replays the gateway's active-alarm snapshot. `G
- If a stream (re)opened while the query was in flight, the whole re-read is discarded and does not signal. An alarm that cleared in the reopen gap is simply absent from the new snapshot, so the query's entry for it would be a phantom `Active`. The reopened stream's own sentinel covers the subscription.
- A re-read is not started while the current stream has not yet delivered its sentinel.
- **Bounded.** One re-read runs at a time. Requests that arrive while it runs collapse into one follow-up run. A failure is retried 3 times, 5 s apart. A gateway without the RPC (`Unimplemented`) is not retried. A re-read that fails never signals: the conditions stay unknown, F5 diagnoses them, and the next stream sentinel signals as before.
- **Residuals.** The query can be *ahead* of the stream: it can show a raise whose live `Raise` is still queued. That `Raise` then lands on an already-active condition, and the host treats it as the re-statement it is. Like every snapshot replay, the query lists active alarms only. An alarm that cleared while no subscription was live, so that its live `Clear` was dropped, is not cleared by it. This is a pre-existing limit of every snapshot replay.
- **Residuals.** The query can be *ahead* of the stream: it can show a raise whose live `Raise` is still queued. That `Raise` then lands on an already-active condition, and the host treats it as the re-statement it is. Like every snapshot replay, the query lists active alarms only; a `Clear` dropped while no handler was attached is recovered by the sweep below (#944).
- **In practice.** A deploy that changes a Galaxy driver's alarm tags also changes its config, so the driver respawns and its fresh feed's first sentinel covers the new set (#665: there is no in-place path). The re-read is the safety net for the paths where the feed outlives the subscription.
**Clearing alarms a complete snapshot no longer lists (#944).** A snapshot or `QueryActiveAlarms` result lists ACTIVE alarms only, so an alarm whose live `Clear` was dropped (no alarm subscription, or `DriverInstanceActor` had detached its `OnAlarmEvent` handler, or the stream was down) stayed Active on the node after every replay. The driver now keeps, per ConditionId (RawPath), the alarms it last DELIVERED to a handler as active (Raise / Retrigger / ActiveAcknowledged; a delivered Clear removes the entry, a dropped one does not). The feed raises `IGalaxyAlarmFeed.ActiveSetDelivered` for each COMPLETE read: a stream's `snapshot_complete` sentinel (before `SnapshotDelivered`) or a successful re-read. The driver then synthesises a `Clear` (flagged `IsRestatement`) for every told-active alarm of the live subscription that the read does not name, ahead of the known-state signal. Serialisation: the event is raised under the feed's dispatch lock, and a re-read names the alarms the live stream restated while it was in flight as present, so a live `Raise` newer than the query is never cleared. Alarms outside the live subscription are never swept. The same sweep also repairs an alarm that cleared during a stream gap (gateway restart).
**`provider_status` / `snapshot_status` frames and truncated snapshots (#945).** The gateway's stream opens with a `provider_status` and a `snapshot_status` frame and repeats them on failover/failback and on a change of the truncation verdict. Both are consumed, not counted as `galaxy.alarm_feed.transitions.decoding_failures`: `provider_status` is logged (Warning when degraded, i.e. the subtag fallback) and counted on `galaxy.alarm_feed.provider_status` (tags `mode`, `degraded`); `snapshot_status` is logged and counted on `galaxy.alarm_feed.snapshot_status` (tag `truncated`). A snapshot the gateway flags as possibly incomplete (latest `snapshot_status.truncated`, or, for a gateway that sends no status frame, a per-record `from_truncated_snapshot` on an entry; a re-read is also judged by its entries' flags) is **not complete**: its entries are still raised, but `SnapshotDelivered` / `ActiveSetDelivered` are not (no known-state signal, and no sweep, since absence from a possibly-truncated set proves nothing; counter `galaxy.alarm_feed.snapshot_withheld`). When the gateway later reports `truncated = false` after a withheld read, the feed raises `SnapshotTruncationCleared` and the driver re-reads the active set, whose complete result sweeps and signals. Until then the conditions stay unknown (F5 diagnoses them). A re-read that straddles the clearing frame is not retried (bounded); it waits for the next sentinel or subscription refresh.
## Testing
- **Unit tests**: `tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/` — fakes the gateway gRPC surface; covers Browse, Runtime, Health, and Config in isolation.
@@ -173,6 +173,12 @@ public sealed class GalaxyDriver
// _alarmHandlersLock). A subscription that becomes live after that point gets no sentinel of its own until the
// stream reopens, so it is established by a re-read of the active-alarm set instead.
private bool _streamSnapshotDelivered;
// lmxopcua#944: the alarms (keyed by ConditionId = RawPath) whose last state the driver actually DELIVERED to a
// OnAlarmEvent handler as active (Raise / Retrigger / ActiveAcknowledged), with the transition that said so (the
// template of a synthesised Clear). A Clear delivered removes the entry; one dropped (no alarm subscription, or the
// host actor had detached its handler) does not, so a complete snapshot that no longer lists the alarm can still
// clear it. Guarded by _alarmHandlersLock.
private readonly Dictionary<string, GalaxyAlarmTransition> _toldActive = new(StringComparer.Ordinal);
// lmxopcua#925: the active-alarm re-read coalescer — 0 idle, 1 running, 2 running with another run requested.
private int _alarmRefreshState;
// Cancelled (and replaced) by every runtime teardown, so an in-flight re-read or its retry wait stops quietly.
@@ -1097,6 +1103,8 @@ public sealed class GalaxyDriver
alarmFeed.OnAlarmTransition -= OnAlarmFeedTransition;
alarmFeed.SnapshotDelivered -= OnAlarmFeedSnapshotDelivered;
alarmFeed.StreamOpened -= OnAlarmFeedStreamOpened;
alarmFeed.ActiveSetDelivered -= OnAlarmFeedActiveSetDelivered;
alarmFeed.SnapshotTruncationCleared -= OnAlarmFeedSnapshotTruncationCleared;
_alarmFeedWired = false;
}
if (releaseFeed) _alarmFeed = null;
@@ -2760,6 +2768,8 @@ public sealed class GalaxyDriver
_alarmFeed.OnAlarmTransition += OnAlarmFeedTransition;
_alarmFeed.SnapshotDelivered += OnAlarmFeedSnapshotDelivered;
_alarmFeed.StreamOpened += OnAlarmFeedStreamOpened;
_alarmFeed.ActiveSetDelivered += OnAlarmFeedActiveSetDelivered;
_alarmFeed.SnapshotTruncationCleared += OnAlarmFeedSnapshotTruncationCleared;
_alarmFeed.Start();
_alarmFeedWired = true;
}
@@ -3046,9 +3056,26 @@ public sealed class GalaxyDriver
},
// A snapshot entry re-states upstream state — history-only signal for the host.
IsRestatement: transition.IsRestatement);
var sink = OnAlarmEvent;
if (sink is null) return; // nobody attached (the host actor detached its handler): not told, so not recorded
// lmxopcua#944: what the host is now told, for the clear-absent sweep.
lock (_alarmHandlersLock)
{
switch (transition.TransitionKind)
{
case GalaxyAlarmTransitionKind.Raise:
case GalaxyAlarmTransitionKind.Retrigger:
case GalaxyAlarmTransitionKind.ActiveAcknowledged:
_toldActive[conditionRawPath] = transition;
break;
case GalaxyAlarmTransitionKind.Clear:
_toldActive.Remove(conditionRawPath);
break;
}
}
try
{
OnAlarmEvent?.Invoke(this, args);
sink.Invoke(this, args);
}
catch (Exception ex)
{
@@ -3058,6 +3085,59 @@ public sealed class GalaxyDriver
}
}
/// <summary>
/// lmxopcua#944: the feed read the gateway's COMPLETE active-alarm set (a stream sentinel or a re-read). A
/// snapshot lists ACTIVE alarms only, so an alarm the host was last told was active that is absent from it has
/// cleared — and its live <c>Clear</c> was dropped while no handler / no alarm subscription was attached (a
/// stream gap or a detached <c>DriverInstanceActor</c> handler). Each such alarm of the live subscription gets a
/// synthesised, restatement-flagged Clear through the normal bridge, before the known-state signal. Runs on the
/// feed thread, serialised with live dispatch, so no live message can interleave. A truncated set never reaches here (#945).
/// </summary>
private void OnAlarmFeedActiveSetDelivered(object? sender, GalaxyAlarmSetEventArgs e)
{
lock (_alarmHandlersLock)
{
if (_toldActive.Count == 0 || _alarmSubscriptions.Count == 0) return;
}
var present = new HashSet<string>(StringComparer.Ordinal);
foreach (var alarm in e.Present)
present.Add(ResolveAlarmRawPath(alarm.AlarmFullReference, alarm.SourceObjectReference));
List<GalaxyAlarmTransition> stale = [];
lock (_alarmHandlersLock)
{
if (_alarmSubscriptions.Count == 0) return;
var subscribed = new HashSet<string>(_alarmSubscriptionRefs, StringComparer.Ordinal);
foreach (var (conditionId, told) in _toldActive)
{
if (subscribed.Contains(conditionId) && !present.Contains(conditionId)) stale.Add(told);
}
}
foreach (var told in stale)
{
_logger.LogInformation(
"GalaxyDriver alarm {AlarmRef} was last reported active but is absent from the gateway's complete active-alarm set — clearing it (its Clear was missed while the alarm handler or subscription was detached).",
told.AlarmFullReference);
OnAlarmFeedTransition(this, told with
{
TransitionKind = GalaxyAlarmTransitionKind.Clear,
TransitionTimestampUtc = DateTime.UtcNow,
OperatorUser = string.Empty,
OperatorComment = string.Empty,
IsRestatement = true,
});
}
}
/// <summary>
/// lmxopcua#945: the gateway stopped flagging its active-alarm set as truncated after a read was withheld for it —
/// re-read the (now complete) set so the withheld sweep and known-state signal happen.
/// </summary>
private void OnAlarmFeedSnapshotTruncationCleared(object? sender, EventArgs e) =>
RequestAlarmSnapshotRefresh("the gateway cleared its truncated-snapshot verdict");
/// <summary>A1 review round 2 F4: a feed stream (re)opened — record the subscription its snapshot is delivered under.</summary>
private void OnAlarmFeedStreamOpened(object? sender, EventArgs e)
{
@@ -63,7 +63,16 @@ internal sealed class GatewayGalaxyAlarmFeed : IGalaxyAlarmFeed
description: "Alarm feed messages decoded and forwarded to driver-level handlers.");
private static readonly Counter<long> AlarmTransitionsDecodingFailures =
Meter.CreateCounter<long>("galaxy.alarm_feed.transitions.decoding_failures", unit: "{event}",
description: "Alarm feed messages dropped for a missing body or unspecified transition kind.");
description: "Alarm feed messages dropped for an unrecognised payload or an unspecified transition/condition kind.");
private static readonly Counter<long> AlarmProviderStatusFrames =
Meter.CreateCounter<long>("galaxy.alarm_feed.provider_status", unit: "{frame}",
description: "provider_status frames received on the alarm stream (lmxopcua#945); tagged by provider mode and degraded.");
private static readonly Counter<long> AlarmSnapshotStatusFrames =
Meter.CreateCounter<long>("galaxy.alarm_feed.snapshot_status", unit: "{frame}",
description: "snapshot_status frames received on the alarm stream (lmxopcua#945); tagged by the truncated verdict.");
private static readonly Counter<long> AlarmSnapshotsWithheld =
Meter.CreateCounter<long>("galaxy.alarm_feed.snapshot_withheld", unit: "{snapshot}",
description: "Active-alarm snapshots (stream sentinels or re-reads) not vouched complete because the gateway flagged the set as truncated (lmxopcua#945).");
private static readonly Counter<long> AlarmSnapshotRefreshes =
Meter.CreateCounter<long>("galaxy.alarm_feed.snapshot_refreshes", unit: "{refresh}",
description: "Active-alarm set re-reads (QueryActiveAlarms) completed while the alarm stream stayed open (lmxopcua#925).");
@@ -83,7 +92,9 @@ internal sealed class GatewayGalaxyAlarmFeed : IGalaxyAlarmFeed
// The alarms the live stream delivered a message for since the in-flight re-read was issued (null when none is in
// flight), mapped to whether any of them carried the FULL state (snapshot entry, Raise, Retrigger, Clear) — true —
// or only the ack dimension (Acknowledge) — false. Guarded by _dispatchLock.
private Dictionary<string, bool>? _touchedDuringRefresh;
private Dictionary<string, Touched>? _touchedDuringRefresh;
private readonly record struct Touched(bool FullState, string SourceObjectReference);
// Review r1 #2: bumped (under _dispatchLock) each time a stream is (re)opened, before any of its messages. A
// re-read replays only if no stream opened since it was issued: an alarm that cleared in a reopen gap is merely
// ABSENT from the new snapshot, so the touched map cannot catch the re-read's stale entry for it.
@@ -91,6 +102,18 @@ internal sealed class GatewayGalaxyAlarmFeed : IGalaxyAlarmFeed
// Whether the current stream has delivered its snapshot_complete sentinel. Guarded by _dispatchLock. A re-read is
// pointless (and could signal mid-snapshot) while it has not: that stream's own sentinel covers the subscription.
private bool _streamSnapshotComplete;
// lmxopcua#944: the alarms the current stream's snapshot phase delivered (before its sentinel) — what the sentinel
// vouches is standing. Cleared when a stream opens. Guarded by _dispatchLock.
private readonly List<GalaxyAlarmIdentity> _streamSnapshotEntries = new();
// lmxopcua#945: the gateway's latest snapshot_status verdict on the current stream (null until one arrives — an
// older gateway sends none), and whether a snapshot entry of this stream carried the per-record truncation flag.
// Guarded by _dispatchLock; reset when a stream opens.
private bool? _statusTruncated;
private bool _entryTruncated;
// lmxopcua#945: a read (sentinel or re-read) was withheld as truncated; the next "no longer truncated" status
// frame must tell the driver to re-read. Guarded by _dispatchLock; reset when a stream opens (its own sentinel
// re-evaluates the verdict).
private bool _awaitingCompleteSet;
// One re-read at a time (a second one waits for the first).
private readonly SemaphoreSlim _refreshGate = new(1, 1);
private readonly ILogger _logger;
@@ -114,6 +137,12 @@ internal sealed class GatewayGalaxyAlarmFeed : IGalaxyAlarmFeed
/// <inheritdoc />
public event EventHandler? StreamOpened;
/// <inheritdoc />
public event EventHandler<GalaxyAlarmSetEventArgs>? ActiveSetDelivered;
/// <inheritdoc />
public event EventHandler? SnapshotTruncationCleared;
/// <summary>Initializes a new instance of the <see cref="GatewayGalaxyAlarmFeed"/> class.</summary>
/// <param name="streamFactory">A factory delegate that opens the alarm stream.</param>
/// <param name="logger">An optional logger for diagnostic output.</param>
@@ -174,6 +203,10 @@ internal sealed class GatewayGalaxyAlarmFeed : IGalaxyAlarmFeed
{
_streamEpoch++;
_streamSnapshotComplete = false;
_streamSnapshotEntries.Clear();
_statusTruncated = null;
_entryTruncated = false;
_awaitingCompleteSet = false;
}
// A1 review round 2 F4: before any message of this stream, on this (the dispatch) thread.
@@ -225,7 +258,7 @@ internal sealed class GatewayGalaxyAlarmFeed : IGalaxyAlarmFeed
{
// Track BEFORE the query is issued: any live message dispatched from here on may be newer than the
// query's view of that alarm.
var touched = new Dictionary<string, bool>(StringComparer.Ordinal);
var touched = new Dictionary<string, Touched>(StringComparer.Ordinal);
long epoch;
lock (_dispatchLock)
{
@@ -248,6 +281,7 @@ internal sealed class GatewayGalaxyAlarmFeed : IGalaxyAlarmFeed
}
var superseded = 0;
var complete = false;
lock (_dispatchLock)
{
linked.Token.ThrowIfCancellationRequested();
@@ -260,11 +294,11 @@ internal sealed class GatewayGalaxyAlarmFeed : IGalaxyAlarmFeed
}
foreach (var entry in entries)
{
if (!touched.TryGetValue(entry.AlarmFullReference, out var fullState))
if (!touched.TryGetValue(entry.AlarmFullReference, out var touch))
{
DispatchSnapshotEntry(entry);
}
else if (fullState)
else if (touch.FullState)
{
superseded++; // a newer full statement of this alarm already reached the host
}
@@ -277,6 +311,33 @@ internal sealed class GatewayGalaxyAlarmFeed : IGalaxyAlarmFeed
: entry);
}
}
// lmxopcua#945: a set the gateway flagged as truncated (a per-record flag, or the stream's latest
// snapshot_status) is not vouched complete - absence from it proves nothing, so no sweep and no signal.
var truncated = _statusTruncated == true || entries.Exists(e => e.FromTruncatedSnapshot);
if (truncated)
{
// Wait for the gateway's "no longer truncated" frame. If the status already says false (the read
// straddled the clearing frame) nothing will announce it again, and re-reading from here could
// loop on an inconsistent gateway: stay unknown until the next stream sentinel / subscription
// refresh instead (bounded).
_awaitingCompleteSet = _statusTruncated != false;
AlarmSnapshotsWithheld.Add(1, _clientTag);
_logger.LogWarning(
"Galaxy alarm feed re-read returned a snapshot the gateway flagged as truncated - the active-alarm set may be incomplete; not treating it as complete until the gateway clears the verdict.");
}
else
{
complete = true;
// lmxopcua#944: every alarm this read names, plus the ones the live stream restated meanwhile
// (the query may predate their raise). Serialised with live dispatch by the lock held here.
var present = new List<GalaxyAlarmIdentity>(entries.Count + touched.Count);
foreach (var entry in entries)
present.Add(new GalaxyAlarmIdentity(entry.AlarmFullReference, entry.SourceObjectReference));
foreach (var (reference, touch) in touched)
present.Add(new GalaxyAlarmIdentity(reference, touch.SourceObjectReference));
RaiseActiveSetDelivered(present);
}
}
AlarmSnapshotRefreshes.Add(1, _clientTag);
@@ -284,7 +345,7 @@ internal sealed class GatewayGalaxyAlarmFeed : IGalaxyAlarmFeed
_logger.LogDebug(
"Galaxy alarm feed re-read the active-alarm set: {Count} entr(ies) replayed, {Superseded} superseded by the live stream.",
entries.Count - superseded, superseded);
return true;
return complete;
}
finally
{
@@ -305,10 +366,11 @@ internal sealed class GatewayGalaxyAlarmFeed : IGalaxyAlarmFeed
}
/// <summary>Under <see cref="_dispatchLock"/>: note a live message for an alarm while a re-read is in flight.</summary>
private void NoteTouched(string reference, bool fullState)
private void NoteTouched(string reference, string sourceObjectReference, bool fullState)
{
if (_touchedDuringRefresh is not { } touched) return;
touched[reference] = fullState || (touched.TryGetValue(reference, out var prior) && prior);
touched[reference] = new Touched(
fullState || (touched.TryGetValue(reference, out var prior) && prior.FullState), sourceObjectReference);
}
private void Dispatch(AlarmFeedMessage message)
@@ -324,12 +386,18 @@ internal sealed class GatewayGalaxyAlarmFeed : IGalaxyAlarmFeed
switch (message.PayloadCase)
{
case AlarmFeedMessage.PayloadOneofCase.ActiveAlarm:
NoteTouched(message.ActiveAlarm.AlarmFullReference, fullState: true);
NoteTouched(message.ActiveAlarm.AlarmFullReference, message.ActiveAlarm.SourceObjectReference, fullState: true);
if (!_streamSnapshotComplete)
{
_streamSnapshotEntries.Add(new GalaxyAlarmIdentity(
message.ActiveAlarm.AlarmFullReference, message.ActiveAlarm.SourceObjectReference));
if (message.ActiveAlarm.FromTruncatedSnapshot) _entryTruncated = true;
}
DispatchSnapshotEntry(message.ActiveAlarm);
break;
case AlarmFeedMessage.PayloadOneofCase.Transition:
// An Acknowledge carries only the ack dimension; every other kind restates the active state too.
NoteTouched(message.Transition.AlarmFullReference,
NoteTouched(message.Transition.AlarmFullReference, message.Transition.SourceObjectReference,
fullState: message.Transition.TransitionKind != AlarmTransitionKind.Acknowledge);
DispatchTransition(message.Transition);
break;
@@ -337,10 +405,46 @@ internal sealed class GatewayGalaxyAlarmFeed : IGalaxyAlarmFeed
_logger.LogDebug("Galaxy alarm feed active-alarm snapshot complete.");
_initialSnapshot.TrySetResult();
_streamSnapshotComplete = true; // before the signal, whose handler may request a re-read
// grpc-data A1: the ordered per-sentinel signal — on THIS thread, after the snapshot entries above
if (_statusTruncated ?? _entryTruncated)
{
// lmxopcua#945: the gateway flagged this snapshot as possibly missing alarms. Its entries were raised,
// but it does not vouch for the set: no sweep of absent alarms and no known-state signal until the
// verdict clears (then the driver re-reads - SnapshotTruncationCleared).
_awaitingCompleteSet = true;
AlarmSnapshotsWithheld.Add(1, _clientTag);
_logger.LogWarning(
"Galaxy alarm feed snapshot ({Count} entr(ies)) was flagged truncated by the gateway - the active-alarm set may be incomplete; initial alarm state is not signalled until the gateway clears the verdict.",
_streamSnapshotEntries.Count);
break;
}
// lmxopcua#944: the complete set first, so an absent-alarm clear precedes the known-state signal.
RaiseActiveSetDelivered(_streamSnapshotEntries.ToArray());
// grpc-data A1: the ordered per-sentinel signal - on THIS thread, after the snapshot entries above
// were raised; every reopened stream's sentinel raises it again.
RaiseSnapshotDelivered();
break;
case AlarmFeedMessage.PayloadOneofCase.ProviderStatus:
// lmxopcua#945: informational - the gateway's alarm provider mode (failover/failback). Not a decode failure.
AlarmProviderStatusFrames.Add(1,
_clientTag,
new KeyValuePair<string, object?>("mode", message.ProviderStatus.Mode.ToString()),
new KeyValuePair<string, object?>("degraded", message.ProviderStatus.Degraded));
if (message.ProviderStatus.Degraded)
{
_logger.LogWarning(
"Galaxy alarm feed provider status: {Mode} (degraded) since {Since:o} - {Reason}",
message.ProviderStatus.Mode, message.ProviderStatus.Since?.ToDateTime(), message.ProviderStatus.Reason);
}
else
{
_logger.LogInformation(
"Galaxy alarm feed provider status: {Mode} - {Reason}",
message.ProviderStatus.Mode, message.ProviderStatus.Reason);
}
break;
case AlarmFeedMessage.PayloadOneofCase.SnapshotStatus:
OnSnapshotStatus(message.SnapshotStatus.Truncated);
break;
default:
// Empty oneof — worker / gateway version skew. Count and drop.
AlarmTransitionsDecodingFailures.Add(1, _clientTag);
@@ -348,6 +452,26 @@ internal sealed class GatewayGalaxyAlarmFeed : IGalaxyAlarmFeed
}
}
/// <summary>Under <see cref="_dispatchLock"/>: the gateway's snapshot-completeness verdict changed or was restated (lmxopcua#945).</summary>
private void OnSnapshotStatus(bool truncated)
{
AlarmSnapshotStatusFrames.Add(1, _clientTag, new KeyValuePair<string, object?>("truncated", truncated));
_statusTruncated = truncated;
if (truncated)
{
_logger.LogWarning(
"Galaxy alarm feed snapshot status: the gateway's active-alarm set may be INCOMPLETE (truncated worker fetch) - absent alarms are not cleared and the initial alarm state is not signalled while this holds.");
return;
}
_logger.LogInformation("Galaxy alarm feed snapshot status: the active-alarm set is complete.");
_entryTruncated = false; // the per-record flags described the truncated generation
if (_awaitingCompleteSet)
{
_awaitingCompleteSet = false;
RaiseTruncationCleared();
}
}
/// <summary>
/// Decode one entry of the initial active-alarm snapshot. Each currently-active
/// alarm is surfaced as a transition so the OPC UA Part 9 condition layer sees
@@ -446,6 +570,30 @@ internal sealed class GatewayGalaxyAlarmFeed : IGalaxyAlarmFeed
}
}
private void RaiseActiveSetDelivered(IReadOnlyList<GalaxyAlarmIdentity> present)
{
try
{
ActiveSetDelivered?.Invoke(this, new GalaxyAlarmSetEventArgs(present));
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Galaxy alarm feed ActiveSetDelivered handler threw - continuing.");
}
}
private void RaiseTruncationCleared()
{
try
{
SnapshotTruncationCleared?.Invoke(this, EventArgs.Empty);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Galaxy alarm feed SnapshotTruncationCleared handler threw - continuing.");
}
}
private void RaiseSnapshotDelivered()
{
try
@@ -69,10 +69,50 @@ internal interface IGalaxyAlarmFeed : IAsyncDisposable
/// it would be a phantom transition. An Acknowledge alone is merged instead (an Active entry replays as
/// ActiveAcked). Completes true once every entry was raised; false — nothing replayed — when the feed has no
/// query, is disposed, the current stream has not delivered its sentinel yet, or a stream (re)opened while the
/// query was in flight (that stream's own sentinel then covers the subscription). Throws on an RPC failure.
/// Raises no signal itself — the caller decides which subscription the re-read establishes.
/// query was in flight (that stream's own sentinel then covers the subscription), or the gateway flagged the set
/// as possibly truncated (#945 — the entries ARE still replayed, but the set is not vouched complete, so
/// <see cref="ActiveSetDelivered"/> is not raised and the caller must not signal). Throws on an RPC failure.
/// Raises no signal itself — the caller decides which subscription the re-read establishes. On a COMPLETE
/// re-read it raises <see cref="ActiveSetDelivered"/> (synchronously, before returning).
/// </summary>
/// <param name="cancellationToken">A cancellation token.</param>
/// <returns>True when the set was re-read and its entries raised.</returns>
Task<bool> RefreshSnapshotAsync(CancellationToken cancellationToken) => Task.FromResult(false);
/// <summary>
/// lmxopcua#944: raised synchronously on the feed thread, serialised with live dispatch, each time the feed has
/// read the gateway's COMPLETE active-alarm set — a stream's <c>snapshot_complete</c> sentinel (before
/// <see cref="SnapshotDelivered"/>) or a successful <see cref="RefreshSnapshotAsync"/> re-read — after every
/// entry was raised on <see cref="OnAlarmTransition"/>. Carries the alarms that read vouches are standing (or
/// were just restated by the live stream); a snapshot lists ACTIVE alarms only, so the driver clears any alarm
/// it last told the host was active that is absent from it. Never raised for a set the gateway flagged as
/// truncated (#945): absence from a possibly-incomplete set proves nothing. The default accessors make it a
/// no-op for feeds with no snapshot phase.
/// </summary>
event EventHandler<GalaxyAlarmSetEventArgs>? ActiveSetDelivered { add { } remove { } }
/// <summary>
/// lmxopcua#945: raised synchronously on the feed thread when the gateway's <c>snapshot_status</c> verdict
/// goes from truncated back to complete AFTER a read was withheld because it was truncated (<see cref="SnapshotDelivered"/>
/// and <see cref="ActiveSetDelivered"/> were not raised for it). The cache is complete now, so the driver
/// re-reads the active-alarm set to establish what the withheld read could not. The default accessors make it a no-op.
/// </summary>
event EventHandler? SnapshotTruncationCleared { add { } remove { } }
}
/// <summary>One alarm named by a <see cref="GalaxyAlarmSetEventArgs"/>: the two references the driver resolves a RawPath from.</summary>
/// <param name="AlarmFullReference">The gateway's provider-qualified alarm reference.</param>
/// <param name="SourceObjectReference">The source reference (<c>tag.Attr</c>), possibly empty.</param>
internal readonly record struct GalaxyAlarmIdentity(string AlarmFullReference, string SourceObjectReference);
/// <summary>Payload of <see cref="IGalaxyAlarmFeed.ActiveSetDelivered"/> (lmxopcua#944).</summary>
internal sealed class GalaxyAlarmSetEventArgs : EventArgs
{
/// <summary>Creates the payload.</summary>
/// <param name="present">Every alarm the complete read named, plus any the live stream restated while a re-read was in flight.</param>
public GalaxyAlarmSetEventArgs(IReadOnlyList<GalaxyAlarmIdentity> present) =>
Present = present ?? throw new ArgumentNullException(nameof(present));
/// <summary>Every alarm the complete read vouches for.</summary>
public IReadOnlyList<GalaxyAlarmIdentity> Present { get; }
}
@@ -0,0 +1,457 @@
using System.Diagnostics.Metrics;
using System.Runtime.CompilerServices;
using System.Threading.Channels;
using Google.Protobuf.WellKnownTypes;
using Shouldly;
using Xunit;
using ZB.MOM.WW.MxGateway.Contracts.Proto;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using AlarmTransitionKind = ZB.MOM.WW.MxGateway.Contracts.Proto.AlarmTransitionKind;
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Config;
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime;
namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests.Runtime;
/// <summary>
/// lmxopcua#944: a complete active-alarm snapshot (stream sentinel or QueryActiveAlarms re-read) lists ACTIVE alarms
/// only, so an alarm the host was last told was active that is absent from it cleared while the driver's handler was
/// detached — the driver clears it. lmxopcua#945: <c>provider_status</c> / <c>snapshot_status</c> frames are handled
/// (not decode failures), and a snapshot the gateway flags as truncated is not complete (no sweep, no signal).
/// </summary>
[Trait("Feature", "GrpcData")]
public sealed class GalaxyAlarmClearAbsentTests
{
private const string Tank1 = "Tank01.Level.HiHi";
private const string Tank2 = "Tank02.Level.HiHi";
private static CancellationToken Ct => TestContext.Current.CancellationToken;
/// <summary>The #944 scenario: the Clear arrives while the host's handler is detached; the reopened stream's snapshot omits the alarm.</summary>
[Fact]
public async Task A_clear_dropped_while_the_handler_was_detached_is_recovered_by_the_next_complete_snapshot()
{
await using var rig = new Rig();
using var driver = NewDriver(rig.Feed);
var host = new HostProbe(driver);
await driver.SubscribeAlarmsAsync([Tank1, Tank2], Ct);
var s = await rig.NextStreamAsync();
await s.WriteAsync(Snapshot(Tank1, AlarmConditionState.Active), Ct);
await s.WriteAsync(Snapshot(Tank2, AlarmConditionState.ActiveAcked), Ct);
await s.WriteAsync(new AlarmFeedMessage { SnapshotComplete = true }, Ct);
await TestWait.UntilAsync(() => host.Count == 3, "snapshot entries + signal", () => host.Dump());
host.Detach();
await s.WriteAsync(Live(Tank1, AlarmTransitionKind.Clear), Ct);
await Task.Delay(100, Ct); // the dropped Clear reached nobody
host.Attach();
s.TryComplete(new InvalidOperationException("gateway stream fault"));
var s2 = await rig.NextStreamAsync();
await s2.WriteAsync(Snapshot(Tank2, AlarmConditionState.ActiveAcked), Ct); // Tank1 absent: it cleared
await s2.WriteAsync(new AlarmFeedMessage { SnapshotComplete = true }, Ct);
await TestWait.UntilAsync(() => host.Count == 6, "restated Tank2, the recovered Tank1 clear, the signal", () => host.Dump());
host.Snapshot().Skip(3).ShouldBe([
"event:" + Tank2 + ":ActiveAcknowledged:restatement",
"event:" + Tank1 + ":Clear:restatement",
$"signal:{Tank1},{Tank2}",
], "the clear precedes the known-state signal; the still-active alarm is not cleared");
}
/// <summary>Negative control: a Clear the host DID receive is not repeated by a later snapshot that omits the alarm.</summary>
[Fact]
public async Task A_delivered_clear_is_not_repeated_by_a_later_snapshot()
{
await using var rig = new Rig();
using var driver = NewDriver(rig.Feed);
var host = new HostProbe(driver);
await driver.SubscribeAlarmsAsync([Tank1], Ct);
var s = await rig.NextStreamAsync();
await s.WriteAsync(Snapshot(Tank1, AlarmConditionState.Active), Ct);
await s.WriteAsync(new AlarmFeedMessage { SnapshotComplete = true }, Ct);
await s.WriteAsync(Live(Tank1, AlarmTransitionKind.Clear), Ct);
await TestWait.UntilAsync(() => host.Count == 3, "entry, signal, live clear", () => host.Dump());
s.TryComplete(new InvalidOperationException("reopen"));
var s2 = await rig.NextStreamAsync();
await s2.WriteAsync(new AlarmFeedMessage { SnapshotComplete = true }, Ct);
await TestWait.UntilAsync(() => host.Count == 4, "the reopened stream's signal", () => host.Dump());
await Task.Delay(100, Ct);
host.Snapshot()[3].ShouldBe("signal:" + Tank1);
host.Count.ShouldBe(4, "no synthesised Clear");
}
/// <summary>An alarm outside the live subscription is never swept (positive control: the subscribed one is).</summary>
[Fact]
public async Task Only_the_live_subscriptions_alarms_are_swept()
{
await using var rig = new Rig();
using var driver = NewDriver(rig.Feed);
var host = new HostProbe(driver);
var h = await driver.SubscribeAlarmsAsync([Tank1, Tank2], Ct);
var s = await rig.NextStreamAsync();
await s.WriteAsync(Snapshot(Tank1, AlarmConditionState.Active), Ct);
await s.WriteAsync(Snapshot(Tank2, AlarmConditionState.Active), Ct);
await s.WriteAsync(new AlarmFeedMessage { SnapshotComplete = true }, Ct);
await TestWait.UntilAsync(() => host.Count == 3, "entries + signal", () => host.Dump());
await driver.UnsubscribeAlarmsAsync(h, Ct);
await driver.SubscribeAlarmsAsync([Tank1], Ct); // Tank2 left the subscription
var q = await rig.NextQueryAsync();
q.Complete(); // both cleared upstream
await TestWait.UntilAsync(() => host.Count == 5, "Tank1 clear + signal", () => host.Dump());
await Task.Delay(100, Ct);
host.Snapshot().Skip(3).ShouldBe(["event:" + Tank1 + ":Clear:restatement", "signal:" + Tank1]);
}
/// <summary>The re-read path recovers a dropped Clear too.</summary>
[Fact]
public async Task A_complete_reread_clears_an_absent_told_active_alarm_before_it_signals()
{
await using var rig = new Rig();
using var driver = NewDriver(rig.Feed);
var host = new HostProbe(driver);
var h = await driver.SubscribeAlarmsAsync([Tank1], Ct);
var s = await rig.NextStreamAsync();
await s.WriteAsync(Snapshot(Tank1, AlarmConditionState.Active), Ct);
await s.WriteAsync(new AlarmFeedMessage { SnapshotComplete = true }, Ct);
await TestWait.UntilAsync(() => host.Count == 2, "entry + signal", () => host.Dump());
host.Detach();
await s.WriteAsync(Live(Tank1, AlarmTransitionKind.Clear), Ct);
await Task.Delay(100, Ct);
host.Attach();
await driver.UnsubscribeAlarmsAsync(h, Ct);
await driver.SubscribeAlarmsAsync([Tank1], Ct);
(await rig.NextQueryAsync()).Complete();
await TestWait.UntilAsync(() => host.Count == 4, "clear + signal", () => host.Dump());
host.Snapshot().Skip(2).ShouldBe(["event:" + Tank1 + ":Clear:restatement", "signal:" + Tank1]);
}
/// <summary>
/// A live Raise that lands while a re-read is in flight may postdate the query's view: the alarm is absent from the
/// query but must NOT be cleared. (Positive control above: an untouched absent alarm is.)
/// </summary>
[Fact]
public async Task A_live_raise_during_a_reread_is_not_cleared_by_it()
{
await using var rig = new Rig();
using var driver = NewDriver(rig.Feed);
var host = new HostProbe(driver);
var h = await driver.SubscribeAlarmsAsync([Tank1, Tank2], Ct);
var s = await rig.NextStreamAsync();
await s.WriteAsync(new AlarmFeedMessage { SnapshotComplete = true }, Ct);
await TestWait.UntilAsync(() => host.Count == 1, "signal", () => host.Dump());
await driver.UnsubscribeAlarmsAsync(h, Ct);
await driver.SubscribeAlarmsAsync([Tank1, Tank2], Ct);
var q = await rig.NextQueryAsync();
await s.WriteAsync(Live(Tank2, AlarmTransitionKind.Raise), Ct); // after the query was issued; the query does not list it
await TestWait.UntilAsync(() => host.Count == 2, "the live raise", () => host.Dump());
q.Complete();
await TestWait.UntilAsync(() => host.Count == 3, "the signal", () => host.Dump());
await Task.Delay(100, Ct);
host.Snapshot().Skip(1).ShouldBe(["event:" + Tank2 + ":Raise:live", $"signal:{Tank1},{Tank2}"]);
// Same alarm, no live message this time ⇒ absent means cleared (the control that the sweep really runs here).
// (Wait for the first re-read's coalescer to go idle before re-subscribing, so exactly one more query runs.)
await Task.Delay(100, Ct);
await driver.UnsubscribeAlarmsAsync(await driver.SubscribeAlarmsAsync([Tank1, Tank2], Ct), Ct);
await driver.SubscribeAlarmsAsync([Tank1, Tank2], Ct);
(await rig.NextQueryAsync()).Complete();
await TestWait.UntilAsync(() => host.Snapshot().Contains("event:" + Tank2 + ":Clear:restatement"),
"the control sweep", () => host.Dump());
}
/// <summary>#945: provider_status and snapshot_status are not decode failures, and do not disturb the feed.</summary>
[Fact]
public async Task Provider_and_snapshot_status_frames_are_not_counted_as_decoding_failures()
{
var client = "StatusFrames-" + Guid.NewGuid().ToString("N");
var failures = 0;
var providerFrames = 0;
var statusFrames = 0;
using var listener = new MeterListener();
listener.InstrumentPublished = (i, l) =>
{
if (i.Meter.Name == EventPump.MeterName && i.Name.StartsWith("galaxy.alarm_feed.", StringComparison.Ordinal))
l.EnableMeasurementEvents(i);
};
listener.SetMeasurementEventCallback<long>((i, v, tags, _) =>
{
if (!tags.ToArray().Any(t => t.Key == "galaxy.client" && Equals(t.Value, client))) return;
switch (i.Name)
{
case "galaxy.alarm_feed.transitions.decoding_failures": Interlocked.Add(ref failures, (int)v); break;
case "galaxy.alarm_feed.provider_status": Interlocked.Add(ref providerFrames, (int)v); break;
case "galaxy.alarm_feed.snapshot_status": Interlocked.Add(ref statusFrames, (int)v); break;
}
});
listener.Start();
var signalled = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
await using var feed = new GatewayGalaxyAlarmFeed(
(_, ct) => Stream(ct), clientName: client);
feed.SnapshotDelivered += (_, _) => signalled.TrySetResult();
feed.Start();
await TestWait.ForAsync(signalled.Task, "the sentinel after the status frames", () => $"f={failures}");
listener.RecordObservableInstruments();
failures.ShouldBe(0);
providerFrames.ShouldBe(2);
statusFrames.ShouldBe(1);
static async IAsyncEnumerable<AlarmFeedMessage> Stream([EnumeratorCancellation] CancellationToken ct)
{
yield return new AlarmFeedMessage
{
ProviderStatus = new AlarmProviderStatus { Mode = AlarmProviderMode.Alarmmgr, Reason = "startup" },
};
yield return new AlarmFeedMessage { SnapshotStatus = new AlarmSnapshotStatus { Truncated = false } };
yield return new AlarmFeedMessage
{
ProviderStatus = new AlarmProviderStatus { Mode = AlarmProviderMode.Subtag, Degraded = true, Reason = "failover" },
};
yield return new AlarmFeedMessage { SnapshotComplete = true };
await Task.Delay(Timeout.Infinite, ct);
}
}
/// <summary>
/// #945: a snapshot the gateway flags truncated (snapshot_status) still raises its entries but is not complete —
/// no sweep of an absent told-active alarm and no known-state signal — until the verdict clears; then the driver
/// re-reads, and that complete set sweeps and signals.
/// </summary>
[Fact]
public async Task A_truncated_snapshot_is_not_complete_until_the_gateway_clears_the_verdict()
{
await using var rig = new Rig();
using var driver = NewDriver(rig.Feed);
var host = new HostProbe(driver);
await driver.SubscribeAlarmsAsync([Tank1, Tank2], Ct);
var s = await rig.NextStreamAsync();
await s.WriteAsync(Snapshot(Tank1, AlarmConditionState.Active), Ct);
await s.WriteAsync(Snapshot(Tank2, AlarmConditionState.Active), Ct);
await s.WriteAsync(new AlarmFeedMessage { SnapshotComplete = true }, Ct);
await TestWait.UntilAsync(() => host.Count == 3, "entries + signal", () => host.Dump());
s.TryComplete(new InvalidOperationException("gateway restart"));
var s2 = await rig.NextStreamAsync();
await s2.WriteAsync(new AlarmFeedMessage { SnapshotStatus = new AlarmSnapshotStatus { Truncated = true } }, Ct);
await s2.WriteAsync(Snapshot(Tank1, AlarmConditionState.Active), Ct); // Tank2 is merely missing from the capped fetch
await s2.WriteAsync(new AlarmFeedMessage { SnapshotComplete = true }, Ct);
await TestWait.UntilAsync(() => host.Count == 4, "the truncated snapshot's entry", () => host.Dump());
await Task.Delay(200, Ct);
host.Snapshot().Skip(3).ShouldBe(["event:" + Tank1 + ":Retrigger:restatement"],
"no Clear for the absent Tank2 and no signal while the set is possibly incomplete");
rig.QueryCount.ShouldBe(0);
await s2.WriteAsync(new AlarmFeedMessage { SnapshotStatus = new AlarmSnapshotStatus { Truncated = false } }, Ct);
var q = await rig.NextQueryAsync(); // the driver re-reads the now-complete set
q.Complete(Entry(Tank1, AlarmConditionState.Active)); // Tank2 really is gone
await TestWait.UntilAsync(() => host.Count == 7, "re-read entry, the absent clear, the signal", () => host.Dump());
host.Snapshot().Skip(4).ShouldBe([
"event:" + Tank1 + ":Retrigger:restatement",
"event:" + Tank2 + ":Clear:restatement",
$"signal:{Tank1},{Tank2}",
]);
}
/// <summary>#945: an older gateway sends no snapshot_status; the per-record flag alone withholds the snapshot.</summary>
[Fact]
public async Task A_snapshot_entry_flagged_truncated_withholds_the_signal()
{
await using var rig = new Rig();
using var driver = NewDriver(rig.Feed);
var host = new HostProbe(driver);
await driver.SubscribeAlarmsAsync([Tank1], Ct);
var s = await rig.NextStreamAsync();
var flagged = Snapshot(Tank1, AlarmConditionState.Active);
flagged.ActiveAlarm.FromTruncatedSnapshot = true;
await s.WriteAsync(flagged, Ct);
await s.WriteAsync(new AlarmFeedMessage { SnapshotComplete = true }, Ct);
await TestWait.UntilAsync(() => host.Count == 1, "the entry", () => host.Dump());
await Task.Delay(200, Ct);
host.Count.ShouldBe(1, "a truncated snapshot does not signal");
}
/// <summary>
/// #945: a re-read that returns truncated entries replays them but neither sweeps nor signals (it returns false,
/// so the driver does not signal); positive control: the unflagged re-read of the same shape signals.
/// </summary>
[Fact]
public async Task A_truncated_reread_replays_without_sweeping_or_signalling()
{
await using var rig = new Rig();
using var driver = NewDriver(rig.Feed);
var host = new HostProbe(driver);
var h = await driver.SubscribeAlarmsAsync([Tank1, Tank2], Ct);
var s = await rig.NextStreamAsync();
await s.WriteAsync(Snapshot(Tank2, AlarmConditionState.Active), Ct);
await s.WriteAsync(new AlarmFeedMessage { SnapshotComplete = true }, Ct);
await TestWait.UntilAsync(() => host.Count == 2, "entry + signal", () => host.Dump());
await driver.UnsubscribeAlarmsAsync(h, Ct);
await driver.SubscribeAlarmsAsync([Tank1, Tank2], Ct);
var flagged = Entry(Tank1, AlarmConditionState.Active);
flagged.FromTruncatedSnapshot = true;
(await rig.NextQueryAsync()).Complete(flagged); // Tank2 absent, but the set is truncated
await TestWait.UntilAsync(() => host.Count == 3, "the replayed entry", () => host.Dump());
await Task.Delay(200, Ct);
host.Count.ShouldBe(3, "no Clear for Tank2 and no signal");
host.Snapshot()[2].ShouldBe("event:" + Tank1 + ":Retrigger:restatement");
}
// ---- scaffolding ----
/// <summary>Stands in for <c>DriverInstanceActor</c>: attaches/detaches its handlers and records what it was told.</summary>
private sealed class HostProbe
{
private readonly GalaxyDriver _driver;
private readonly List<string> _trace = new();
public HostProbe(GalaxyDriver driver)
{
_driver = driver;
Attach();
}
public int Count { get { lock (_trace) return _trace.Count; } }
public string[] Snapshot() { lock (_trace) return _trace.ToArray(); }
public string Dump() { lock (_trace) return string.Join(" | ", _trace); }
public void Attach()
{
_driver.OnAlarmEvent += OnEvent;
_driver.InitialAlarmStateDelivered += OnSignal;
}
public void Detach()
{
_driver.OnAlarmEvent -= OnEvent;
_driver.InitialAlarmStateDelivered -= OnSignal;
}
private void OnEvent(object? sender, AlarmEventArgs e)
{
lock (_trace) _trace.Add($"event:{e.ConditionId}:{e.Kind}:{(e.IsRestatement ? "restatement" : "live")}");
}
private void OnSignal(object? sender, AlarmInitialStateEventArgs e)
{
lock (_trace) _trace.Add("signal:" + string.Join(',', e.ConditionIds));
}
}
private static ActiveAlarmSnapshot Entry(string reference, AlarmConditionState state) => new()
{
AlarmFullReference = reference,
SourceObjectReference = reference.Split('.')[0],
AlarmTypeName = "AnalogLimitAlarm.HiHi",
Severity = 750,
CurrentState = state,
Category = "Process",
Description = "Tank high-high level",
LastTransitionTimestamp = Timestamp.FromDateTime(DateTime.UtcNow),
};
private static AlarmFeedMessage Snapshot(string reference, AlarmConditionState state) =>
new() { ActiveAlarm = Entry(reference, state) };
private static AlarmFeedMessage Live(string reference, AlarmTransitionKind kind) => new()
{
Transition = new OnAlarmTransitionEvent
{
AlarmFullReference = reference,
SourceObjectReference = reference.Split('.')[0],
AlarmTypeName = "AnalogLimitAlarm.HiHi",
TransitionKind = kind,
Severity = 750,
Description = "Tank high-high level",
TransitionTimestamp = Timestamp.FromDateTime(DateTime.UtcNow),
},
};
private static GalaxyDriver NewDriver(IGalaxyAlarmFeed feed)
{
var options = new GalaxyDriverOptions(
new GalaxyGatewayOptions("http://localhost:5000", "literal-api-key"),
new GalaxyMxAccessOptions("ClearAbsentTest"),
new GalaxyRepositoryOptions(),
new GalaxyReconnectOptions());
return new GalaxyDriver(
driverInstanceId: "drv-1",
options: options,
hierarchySource: null,
alarmAcknowledger: null,
alarmFeed: feed,
ackCredentialResolver: FixedAckCredentialResolver.Fallback());
}
private sealed class ScriptedQuery
{
private readonly TaskCompletionSource<ActiveAlarmSnapshot[]> _result = new(TaskCreationOptions.RunContinuationsAsynchronously);
public Task<ActiveAlarmSnapshot[]> Result => _result.Task;
public void Complete(params ActiveAlarmSnapshot[] entries) => _result.TrySetResult(entries);
}
private sealed class Rig : IAsyncDisposable
{
private readonly Channel<Channel<AlarmFeedMessage>> _opened = Channel.CreateUnbounded<Channel<AlarmFeedMessage>>();
private readonly Channel<ScriptedQuery> _queries = Channel.CreateUnbounded<ScriptedQuery>();
private int _queryCount;
public Rig()
{
Feed = new GatewayGalaxyAlarmFeed((_, ct) =>
{
var c = Channel.CreateUnbounded<AlarmFeedMessage>();
_opened.Writer.TryWrite(c);
return c.Reader.ReadAllAsync(ct);
}, clientName: "ClearAbsentTest", reconnectDelay: TimeSpan.FromMilliseconds(10), queryFactory: QueryAsync);
}
public GatewayGalaxyAlarmFeed Feed { get; }
public int QueryCount => Volatile.Read(ref _queryCount);
private async IAsyncEnumerable<ActiveAlarmSnapshot> QueryAsync(
QueryActiveAlarmsRequest request, [EnumeratorCancellation] CancellationToken ct)
{
Interlocked.Increment(ref _queryCount);
var q = new ScriptedQuery();
_queries.Writer.TryWrite(q);
foreach (var entry in await q.Result.WaitAsync(ct)) yield return entry;
}
public async Task<ChannelWriter<AlarmFeedMessage>> NextStreamAsync()
{
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
return (await _opened.Reader.ReadAsync(cts.Token)).Writer;
}
public async Task<ScriptedQuery> NextQueryAsync()
{
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
return await _queries.Reader.ReadAsync(cts.Token);
}
public ValueTask DisposeAsync() => Feed.DisposeAsync();
}
}