Merge #925: Galaxy re-reads active alarms (QueryActiveAlarms) when the subscription changes after the stream sentinel, then signals initial state; ack-merge + reopen-epoch review fixes
This commit is contained in:
@@ -206,6 +206,17 @@ The session-less alarm feed (`GatewayGalaxyAlarmFeed`) and alarm acknowledger (`
|
||||
|
||||
Every (re)open of `StreamAlarms` replays the gateway's active-alarm snapshot. `GatewayGalaxyAlarmFeed` maps each entry to a transition flagged `IsRestatement` (#656): `Active` → `Retrigger` (upstream's unack is authoritative), `ActiveAcked` → `ActiveAcknowledged` (one atomic active+acked projection — the old `Acknowledge` mapping projected an acked alarm **inactive** on a cold host), `Inactive` → `Clear`. The host writes no `/alerts` row for a replayed entry that changes nothing the condition shows, so a gateway reconnect no longer duplicates history; live `Transition` messages are never flagged. The gateway folds UnackRtn and AckRtn into `Inactive`, so an inactive-unacked alarm cannot be distinguished at reconnect (gateway contract limit).
|
||||
|
||||
**Establishing a changed alarm subscription without a stream reopen (#925).** The driver turns each `snapshot_complete` sentinel into `IAlarmInitialStateSignal.InitialAlarmStateDelivered` (grpc-data A1) for the live alarm subscription, but a sentinel only comes when `StreamAlarms` opens. A subscription that becomes live while the stream is already past its sentinel (a re-subscribe with a changed alarm set, a reconnect that kept the session-less feed, or a change during the snapshot phase, which the sentinel cannot vouch for) would otherwise stay "unknown" (Uncertain on gRPC-data consumers) until the stream happened to reopen. The driver now re-reads the active-alarm set with the gateway's `QueryActiveAlarms` RPC instead. That RPC serves the same monitor cache as the stream's opening snapshot and needs the same `EventsRead` scope.
|
||||
- **How a re-read is applied.** The entries are replayed exactly like snapshot entries: as restatements, with the same kind mapping. The signal follows the replay, and only if the subscription the re-read was made under is still the live one.
|
||||
- **Why there are no phantom transitions.** The stream stays open. Live dispatch and the replay are serialised, so each check below and its replay happen as one step.
|
||||
- An entry is skipped when the live stream delivered a full-state message for the same alarm after the query was issued (a snapshot entry, `Raise`, `Retrigger` or `Clear`), because that message is at least as new as the query's view of it (counter `galaxy.alarm_feed.snapshot_refresh.superseded`).
|
||||
- An `Acknowledge` carries only the ack, so it is merged, not treated as superseding: an `Active` entry replays as `ActiveAcked`. Skipping it would have marked a cold condition known while it still showed inactive.
|
||||
- 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.
|
||||
- **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.
|
||||
|
||||
## 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.
|
||||
|
||||
@@ -476,7 +476,7 @@ conditions re-report (`NM:5639-5651`). Some state changes never produce an event
|
||||
|
||||
| Driver | Exact hook | Signal raised |
|
||||
|---|---|---|
|
||||
| Galaxy | `GatewayGalaxyAlarmFeed.cs:168`, where the gateway's `snapshot_complete` sentinel is handled in `Dispatch` on the feed thread after the snapshot entries (`:155-169`) | On **every** sentinel, covering every condition of the feed's current subscription. The existing `InitialSnapshotCompleted` task (`:69`) stays for its current users but is not the signal: it is one-shot per feed instance (the reopen loop `:140-152` does not reset it), and its `RunContinuationsAsynchronously` continuation could overtake queued transitions. After a gateway stream reopen, the reopened stream's sentinel signals again |
|
||||
| Galaxy | `GatewayGalaxyAlarmFeed.cs:168`, where the gateway's `snapshot_complete` sentinel is handled in `Dispatch` on the feed thread after the snapshot entries (`:155-169`) | On **every** sentinel, covering every condition of the feed's current subscription. The existing `InitialSnapshotCompleted` task (`:69`) stays for its current users but is not the signal: it is one-shot per feed instance (the reopen loop `:140-152` does not reset it), and its `RunContinuationsAsynchronously` continuation could overtake queued transitions. After a gateway stream reopen, the reopened stream's sentinel signals again. **#925:** a subscription that becomes live after the current stream's sentinel (or changes during its snapshot phase) is established by a `QueryActiveAlarms` re-read instead: the entries are replayed as restatements, except where a newer live message already arrived, and then the signal is raised (`docs/drivers/Galaxy.md`) |
|
||||
| OpcUaClient (**F1**, **G2**) | The per-event route that today drops `RefreshEndEventType` as a marker (`OpcUaClientDriver.cs:3066-3067`, `IsRefreshMarker` `:2860-2864`), reached from `OnEventNotification` (`:2749-2762`) | On receipt of `RefreshEndEventType`, covering every condition of that alarm subscription, after the refreshed events delivered before it were projected. **Not** when `TryConditionRefreshAsync` returns (`:2881-2900`). See G2 below for ordering across publish responses |
|
||||
| FOCAS | `FocasAlarmProjection.PollOnceAsync` per-host loop (`:243-276`): after `NoteAlarmReadSucceeded(host)` (`:273`) and that host's `Tick` (`:274`). The `continue` path for a failed host (`:253-272`) raises nothing | **Per host**: the condition ids of that host's alarm tags, after its read succeeded and its transitions were emitted. Raised again on each later successful read |
|
||||
| AbCip ALMD/ALMA | `AbCipAlarmProjection.Tick` (`:195`), called from `RunPollLoopAsync` (`:251`); a node whose `InAlarm` read is non-Good is skipped (`:211`) | **Per node**: at the end of each `Tick`, the condition ids of the nodes whose `InAlarm` (and, for ALMA, all plan refs) read Good in that tick. Skipped nodes are excluded |
|
||||
|
||||
@@ -215,6 +215,26 @@ Heidenhain legs are **blocked**: Galaxy needs the VPN and mxaccessgw, and Heiden
|
||||
sentinel, which comes only on a stream reopen. Until then F5 diagnoses it.
|
||||
- This is by design (vii): the snapshot that preceded the subscribe may have carried that alarm while it was unroutable.
|
||||
- Open question: should the driver ask the gateway for a fresh snapshot on a changed subscription set?
|
||||
**Answered by #925 (2026-11-28):** yes. mxaccessgw already serves `QueryActiveAlarms` from the same monitor cache as the
|
||||
stream snapshot, so no gateway change was needed. A subscribe on a stream that is past its sentinel, and a sentinel for
|
||||
a stream opened under an earlier subscription (F4), both trigger a re-read. The re-read is replayed as restatements; an
|
||||
entry is skipped when the live stream already delivered a newer message for that alarm. Then the live subscription is
|
||||
signalled. Re-reads are coalesced: one in flight plus one follow-up. A failed re-read is retried 3 times and never
|
||||
signals. Tests: `GalaxyAlarmSnapshotRefreshTests` (6). Each of these mutations turns a test red: no re-read on subscribe
|
||||
(5 red), no supersede check, no handle check at the signal, Unimplemented retried, no re-read at a mismatched sentinel,
|
||||
no coalescing. The F5 re-arm for deploy-added refs was already in place (`RearmConditionSignalsAfterReindex`, review
|
||||
round 1). **Not live-gated:** no Galaxy or mxaccessgw is reachable (wonder-box hold).
|
||||
**#925 review round 1:**
|
||||
- *Ack-only supersede:* a live `Acknowledge` no longer supersedes an entry. It is merged instead (Active ⇒ ActiveAcked).
|
||||
Test `An_acknowledge_during_the_reread_merges_into_its_entry_instead_of_superseding_it`. Red on the original code, and
|
||||
on either mutation: ack counted as full state, or no merge.
|
||||
- *Reopen during the query:* a stream epoch is bumped before `StreamOpened`. A changed epoch at replay time drops the
|
||||
re-read and its signal. No re-read starts before the current stream's sentinel. Test
|
||||
`A_stream_reopen_during_the_reread_drops_its_replay_and_its_signal`. Red on the original code (phantom Tank2
|
||||
Retrigger plus a second signal), and with the epoch check removed.
|
||||
- *Lows:* a dispose race returns false instead of throwing `ObjectDisposedException`. The retry wait and the RPC observe
|
||||
a teardown token, which every runtime teardown cancels. An unexpected failure no longer discards a queued follow-up.
|
||||
- Galaxy.Tests: 645 passed, 13 skipped. The 13 alarm-signal tests passed 15 runs out of 15.
|
||||
- **OpcUaClient: no signal suppression on an SDK-reported sequence gap during a refresh.** Plan G2 says such a `RefreshEnd`
|
||||
"does not signal".
|
||||
- The SDK 2.0.1 surface the driver sees (the per-item `Notification` callback) exposes no per-message gap or republish
|
||||
|
||||
@@ -169,6 +169,14 @@ public sealed class GalaxyDriver
|
||||
// _alarmHandlersLock). A sentinel signals only if it is still the live one — entries delivered before a later
|
||||
// subscription (or while none was live) were not delivered under it.
|
||||
private GalaxyAlarmSubscriptionHandle? _streamOpenedUnder;
|
||||
// lmxopcua#925: whether the feed's CURRENT stream has delivered its snapshot_complete sentinel (guarded by
|
||||
// _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#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.
|
||||
private CancellationTokenSource _alarmRefreshCts = new();
|
||||
|
||||
// Production runtime owned by InitializeAsync (BuildProductionRuntimeAsync). The
|
||||
// driver builds these when it opens a real gw session; tests bypass them by
|
||||
@@ -1002,7 +1010,8 @@ public sealed class GalaxyDriver
|
||||
// so they hang off the owned MxGatewayClient, not the worker session.
|
||||
_alarmAcknowledger ??= new GatewayGalaxyAlarmAcknowledger(_ownedMxClient, _logger);
|
||||
_alarmFeed ??= new GatewayGalaxyAlarmFeed(
|
||||
_ownedMxClient.StreamAlarmsAsync, _logger, _options.MxAccess.ClientName);
|
||||
_ownedMxClient.StreamAlarmsAsync, _logger, _options.MxAccess.ClientName,
|
||||
queryFactory: _ownedMxClient.QueryActiveAlarmsAsync);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -1092,6 +1101,11 @@ public sealed class GalaxyDriver
|
||||
}
|
||||
if (releaseFeed) _alarmFeed = null;
|
||||
}
|
||||
// lmxopcua#925: the next feed (or the re-wired injected one) starts with no delivered stream snapshot.
|
||||
lock (_alarmHandlersLock) _streamSnapshotDelivered = false;
|
||||
// A re-read in flight (or waiting to retry) belongs to the torn-down runtime. Not disposed: its token may
|
||||
// still be observed by the unwinding re-read.
|
||||
Interlocked.Exchange(ref _alarmRefreshCts, new CancellationTokenSource()).Cancel();
|
||||
if (releaseFeed)
|
||||
{
|
||||
try { await alarmFeed!.DisposeAsync().ConfigureAwait(false); }
|
||||
@@ -2789,6 +2803,14 @@ public sealed class GalaxyDriver
|
||||
}
|
||||
throw;
|
||||
}
|
||||
|
||||
// lmxopcua#925: the feed's stream is already past its sentinel (a re-subscribe on a live stream — a changed
|
||||
// alarm set, or a reconnect that kept the session-less feed), so no sentinel will ever come for THIS
|
||||
// subscription until the stream happens to reopen. Re-read the active-alarm set instead. A stream still in its
|
||||
// snapshot phase is handled at its sentinel (OnAlarmFeedSnapshotDelivered).
|
||||
bool refresh;
|
||||
lock (_alarmHandlersLock) refresh = _streamSnapshotDelivered && ReferenceEquals(_alarmSubscriptions.FirstOrDefault(), handle);
|
||||
if (refresh) RequestAlarmSnapshotRefresh("alarm subscription changed while the feed stream was open");
|
||||
return Task.FromResult<IAlarmSubscriptionHandle>(handle);
|
||||
}
|
||||
|
||||
@@ -3039,7 +3061,11 @@ public sealed class GalaxyDriver
|
||||
/// <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)
|
||||
{
|
||||
lock (_alarmHandlersLock) _streamOpenedUnder = _alarmSubscriptions.Count > 0 ? _alarmSubscriptions[0] : null;
|
||||
lock (_alarmHandlersLock)
|
||||
{
|
||||
_streamOpenedUnder = _alarmSubscriptions.Count > 0 ? _alarmSubscriptions[0] : null;
|
||||
_streamSnapshotDelivered = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -3049,18 +3075,143 @@ public sealed class GalaxyDriver
|
||||
private void OnAlarmFeedSnapshotDelivered(object? sender, EventArgs e)
|
||||
{
|
||||
IReadOnlyList<string> refs;
|
||||
bool deliveredUnderLive;
|
||||
lock (_alarmHandlersLock)
|
||||
{
|
||||
_streamSnapshotDelivered = true;
|
||||
if (_alarmSubscriptions.Count == 0) return;
|
||||
// A1 review round 2 F4: only a stream whose whole snapshot was delivered under THIS subscription.
|
||||
if (!ReferenceEquals(_alarmSubscriptions[0], _streamOpenedUnder))
|
||||
{
|
||||
_logger.LogDebug("GalaxyDriver alarm sentinel for a stream opened under an earlier (or no) subscription — not signalled; the next stream's sentinel will.");
|
||||
return;
|
||||
}
|
||||
refs = _alarmSubscriptionRefs;
|
||||
// A1 review round 2 F4: only a stream whose whole snapshot was delivered under THIS subscription.
|
||||
deliveredUnderLive = ReferenceEquals(_alarmSubscriptions[0], _streamOpenedUnder);
|
||||
}
|
||||
|
||||
if (!deliveredUnderLive)
|
||||
{
|
||||
// lmxopcua#925: the subscription changed during the snapshot phase, so this sentinel cannot vouch for it and
|
||||
// no later sentinel comes until the stream reopens — re-read the active-alarm set instead (when the gateway
|
||||
// client supports it; otherwise the next stream's sentinel signals, and F5 diagnoses the wait).
|
||||
_logger.LogDebug("GalaxyDriver alarm sentinel for a stream opened under an earlier (or no) subscription — not signalled; re-reading the active-alarm set.");
|
||||
RequestAlarmSnapshotRefresh("alarm subscription changed during the feed's snapshot phase");
|
||||
return;
|
||||
}
|
||||
|
||||
if (refs.Count == 0) return;
|
||||
try
|
||||
{
|
||||
InitialAlarmStateDelivered?.Invoke(this, new AlarmInitialStateEventArgs(refs));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "GalaxyDriver InitialAlarmStateDelivered handler threw — continuing.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Delay between attempts of a failed active-alarm re-read (lmxopcua#925) — tests shorten it.</summary>
|
||||
internal TimeSpan AlarmSnapshotRefreshRetryDelay { get; set; } = TimeSpan.FromSeconds(5);
|
||||
|
||||
/// <summary>Attempts per active-alarm re-read before it gives up (the next stream sentinel or F5 then takes over).</summary>
|
||||
internal const int AlarmSnapshotRefreshAttempts = 3;
|
||||
|
||||
private static readonly TimeSpan AlarmSnapshotRefreshTimeout = TimeSpan.FromSeconds(30);
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#925: schedule a re-read of the gateway's active-alarm set that, once replayed, signals the live
|
||||
/// subscription's refs as delivered — the gap-free replacement for a <c>snapshot_complete</c> sentinel the
|
||||
/// open stream will not send again. Coalesced: at most one re-read runs, and requests made while it runs
|
||||
/// collapse into ONE follow-up run. A no-op when the feed has no query (test fakes, or a feed built without one).
|
||||
/// </summary>
|
||||
private void RequestAlarmSnapshotRefresh(string reason)
|
||||
{
|
||||
IGalaxyAlarmFeed? feed;
|
||||
lock (_alarmFeedLock) feed = _alarmFeedWired ? _alarmFeed : null;
|
||||
if (feed is null || !feed.SupportsSnapshotRefresh || _disposed) return;
|
||||
while (true)
|
||||
{
|
||||
switch (Volatile.Read(ref _alarmRefreshState))
|
||||
{
|
||||
case 0:
|
||||
if (Interlocked.CompareExchange(ref _alarmRefreshState, 1, 0) != 0) continue;
|
||||
_logger.LogDebug("GalaxyDriver re-reading the active-alarm set: {Reason}", reason);
|
||||
_ = Task.Run(RunAlarmSnapshotRefreshesAsync);
|
||||
return;
|
||||
case 1:
|
||||
if (Interlocked.CompareExchange(ref _alarmRefreshState, 2, 1) != 1) continue;
|
||||
return;
|
||||
default:
|
||||
return; // a follow-up run is already queued
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task RunAlarmSnapshotRefreshesAsync()
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
try
|
||||
{
|
||||
await RefreshAlarmSnapshotOnceAsync(Volatile.Read(ref _alarmRefreshCts).Token).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Logged, then the coalescing step below still runs: a follow-up requested meanwhile is not lost.
|
||||
_logger.LogWarning(ex, "GalaxyDriver active-alarm re-read failed unexpectedly");
|
||||
}
|
||||
// 1 → 0: nothing was requested meanwhile. 2: run once more for the requests that arrived.
|
||||
if (Interlocked.CompareExchange(ref _alarmRefreshState, 0, 1) == 1) return;
|
||||
Volatile.Write(ref _alarmRefreshState, 1);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task RefreshAlarmSnapshotOnceAsync(CancellationToken teardown)
|
||||
{
|
||||
GalaxyAlarmSubscriptionHandle? under;
|
||||
IGalaxyAlarmFeed? feed;
|
||||
lock (_alarmFeedLock) feed = _alarmFeedWired ? _alarmFeed : null;
|
||||
lock (_alarmHandlersLock) under = _alarmSubscriptions.Count > 0 ? _alarmSubscriptions[0] : null;
|
||||
if (feed is null || under is null) return;
|
||||
|
||||
for (var attempt = 1; ; attempt++)
|
||||
{
|
||||
if (_disposed || teardown.IsCancellationRequested) return;
|
||||
try
|
||||
{
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(teardown);
|
||||
timeout.CancelAfter(AlarmSnapshotRefreshTimeout);
|
||||
if (!await feed.RefreshSnapshotAsync(timeout.Token).ConfigureAwait(false)) return;
|
||||
break;
|
||||
}
|
||||
catch (Exception ex) when (ex is ObjectDisposedException || _disposed || teardown.IsCancellationRequested)
|
||||
{
|
||||
return; // the feed or the driver is being torn down
|
||||
}
|
||||
catch (Grpc.Core.RpcException ex) when (ex.StatusCode == Grpc.Core.StatusCode.Unimplemented)
|
||||
{
|
||||
_logger.LogWarning("GalaxyDriver: the gateway does not implement QueryActiveAlarms — alarm conditions of a changed subscription stay unestablished until the feed stream reopens");
|
||||
return;
|
||||
}
|
||||
catch (Exception ex) when (attempt < AlarmSnapshotRefreshAttempts)
|
||||
{
|
||||
_logger.LogWarning("GalaxyDriver active-alarm re-read attempt {Attempt} failed ({Reason}); retrying in {Delay}",
|
||||
attempt, ex.Message, AlarmSnapshotRefreshRetryDelay);
|
||||
try { await Task.Delay(AlarmSnapshotRefreshRetryDelay, teardown).ConfigureAwait(false); }
|
||||
catch (OperationCanceledException) { return; } // torn down while waiting to retry
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "GalaxyDriver active-alarm re-read failed after {Attempts} attempts — the subscription's alarm conditions stay unestablished until the feed stream reopens", attempt);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Signal only for the subscription the re-read was made under, through the feed that made it: a subscription
|
||||
// that replaced it requested its own (coalesced) run; a torn-down feed's replay was never bridged.
|
||||
IReadOnlyList<string> refs;
|
||||
lock (_alarmFeedLock) if (!_alarmFeedWired || !ReferenceEquals(_alarmFeed, feed)) return;
|
||||
lock (_alarmHandlersLock)
|
||||
{
|
||||
if (_alarmSubscriptions.Count == 0 || !ReferenceEquals(_alarmSubscriptions[0], under)) return;
|
||||
refs = _alarmSubscriptionRefs;
|
||||
}
|
||||
if (refs.Count == 0) return;
|
||||
try
|
||||
{
|
||||
|
||||
@@ -43,6 +43,16 @@ internal sealed class GatewayGalaxyAlarmFeed : IGalaxyAlarmFeed
|
||||
internal delegate IAsyncEnumerable<AlarmFeedMessage> AlarmStreamFactory(
|
||||
StreamAlarmsRequest request, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Reads the gateway's current active-alarm set (lmxopcua#925). Matches the method group
|
||||
/// <c>MxGatewayClient.QueryActiveAlarmsAsync</c>.
|
||||
/// </summary>
|
||||
/// <param name="request">The query request parameters.</param>
|
||||
/// <param name="cancellationToken">A cancellation token.</param>
|
||||
/// <returns>The async stream of active-alarm snapshots.</returns>
|
||||
internal delegate IAsyncEnumerable<ActiveAlarmSnapshot> ActiveAlarmQueryFactory(
|
||||
QueryActiveAlarmsRequest request, CancellationToken cancellationToken);
|
||||
|
||||
private static readonly TimeSpan DefaultReconnectDelay = TimeSpan.FromSeconds(5);
|
||||
|
||||
// Shares the driver meter name so a host-level MeterListener catches feed counters
|
||||
@@ -54,11 +64,35 @@ internal sealed class GatewayGalaxyAlarmFeed : IGalaxyAlarmFeed
|
||||
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.");
|
||||
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).");
|
||||
private static readonly Counter<long> AlarmSnapshotRefreshEntriesSuperseded =
|
||||
Meter.CreateCounter<long>("galaxy.alarm_feed.snapshot_refresh.superseded", unit: "{entry}",
|
||||
description: "Re-read entries not replayed because the live stream delivered a newer message for the same alarm.");
|
||||
private static readonly Counter<long> AlarmFeedReconnects =
|
||||
Meter.CreateCounter<long>("galaxy.alarm_feed.reconnects", unit: "{reconnect}",
|
||||
description: "Times the alarm feed re-opened its StreamAlarms stream after a transport fault.");
|
||||
|
||||
private readonly AlarmStreamFactory _streamFactory;
|
||||
private readonly ActiveAlarmQueryFactory? _queryFactory;
|
||||
|
||||
// lmxopcua#925: serialises live dispatch with a re-read's replay, so "did the live stream already deliver a newer
|
||||
// message for this alarm" and the replay of the re-read entry are one atomic step.
|
||||
private readonly Lock _dispatchLock = new();
|
||||
// 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;
|
||||
// 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.
|
||||
private long _streamEpoch;
|
||||
// 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;
|
||||
// One re-read at a time (a second one waits for the first).
|
||||
private readonly SemaphoreSlim _refreshGate = new(1, 1);
|
||||
private readonly ILogger _logger;
|
||||
private readonly string _alarmFilterPrefix;
|
||||
private readonly TimeSpan _reconnectDelay;
|
||||
@@ -86,14 +120,20 @@ internal sealed class GatewayGalaxyAlarmFeed : IGalaxyAlarmFeed
|
||||
/// <param name="clientName">An optional client name for tagging log entries.</param>
|
||||
/// <param name="alarmFilterPrefix">An optional prefix to filter alarms in the stream.</param>
|
||||
/// <param name="reconnectDelay">An optional delay before reconnecting after a stream fault.</param>
|
||||
/// <param name="queryFactory">
|
||||
/// An optional factory over the gateway's <c>QueryActiveAlarms</c> RPC; when given, <see cref="RefreshSnapshotAsync"/>
|
||||
/// re-reads the active-alarm set without reopening the stream (lmxopcua#925).
|
||||
/// </param>
|
||||
public GatewayGalaxyAlarmFeed(
|
||||
AlarmStreamFactory streamFactory,
|
||||
ILogger? logger = null,
|
||||
string? clientName = null,
|
||||
string? alarmFilterPrefix = null,
|
||||
TimeSpan? reconnectDelay = null)
|
||||
TimeSpan? reconnectDelay = null,
|
||||
ActiveAlarmQueryFactory? queryFactory = null)
|
||||
{
|
||||
_streamFactory = streamFactory ?? throw new ArgumentNullException(nameof(streamFactory));
|
||||
_queryFactory = queryFactory;
|
||||
_logger = logger ?? NullLogger.Instance;
|
||||
_alarmFilterPrefix = alarmFilterPrefix ?? string.Empty;
|
||||
_reconnectDelay = reconnectDelay ?? DefaultReconnectDelay;
|
||||
@@ -130,6 +170,12 @@ internal sealed class GatewayGalaxyAlarmFeed : IGalaxyAlarmFeed
|
||||
AlarmFilterPrefix = _alarmFilterPrefix,
|
||||
};
|
||||
|
||||
lock (_dispatchLock)
|
||||
{
|
||||
_streamEpoch++;
|
||||
_streamSnapshotComplete = false;
|
||||
}
|
||||
|
||||
// A1 review round 2 F4: before any message of this stream, on this (the dispatch) thread.
|
||||
try { StreamOpened?.Invoke(this, EventArgs.Empty); }
|
||||
catch (Exception ex) { _logger.LogWarning(ex, "Galaxy alarm feed StreamOpened handler threw — continuing."); }
|
||||
@@ -163,19 +209,134 @@ internal sealed class GatewayGalaxyAlarmFeed : IGalaxyAlarmFeed
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool SupportsSnapshotRefresh => _queryFactory is not null;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<bool> RefreshSnapshotAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (_queryFactory is null || _disposed) return false;
|
||||
CancellationTokenSource linked;
|
||||
try { linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _cts.Token); }
|
||||
catch (ObjectDisposedException) { return false; } // disposed concurrently: not an RPC failure
|
||||
using var _ = linked;
|
||||
await _refreshGate.WaitAsync(linked.Token).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
// 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);
|
||||
long epoch;
|
||||
lock (_dispatchLock)
|
||||
{
|
||||
if (!_streamSnapshotComplete) return false; // the current stream's own sentinel covers it
|
||||
epoch = _streamEpoch;
|
||||
_touchedDuringRefresh = touched;
|
||||
}
|
||||
try
|
||||
{
|
||||
var entries = new List<ActiveAlarmSnapshot>();
|
||||
var request = new QueryActiveAlarmsRequest
|
||||
{
|
||||
ClientCorrelationId = Guid.NewGuid().ToString("N"),
|
||||
AlarmFilterPrefix = _alarmFilterPrefix,
|
||||
};
|
||||
await foreach (var entry in _queryFactory(request, linked.Token)
|
||||
.WithCancellation(linked.Token).ConfigureAwait(false))
|
||||
{
|
||||
entries.Add(entry);
|
||||
}
|
||||
|
||||
var superseded = 0;
|
||||
lock (_dispatchLock)
|
||||
{
|
||||
linked.Token.ThrowIfCancellationRequested();
|
||||
if (_streamEpoch != epoch)
|
||||
{
|
||||
// Review r1 #2: a stream (re)opened meanwhile. Its snapshot (and sentinel) is the newer
|
||||
// statement of every alarm; replaying this older view could resurrect one that cleared in the gap.
|
||||
_logger.LogDebug("Galaxy alarm feed re-read discarded: the stream reopened while it was in flight.");
|
||||
return false;
|
||||
}
|
||||
foreach (var entry in entries)
|
||||
{
|
||||
if (!touched.TryGetValue(entry.AlarmFullReference, out var fullState))
|
||||
{
|
||||
DispatchSnapshotEntry(entry);
|
||||
}
|
||||
else if (fullState)
|
||||
{
|
||||
superseded++; // a newer full statement of this alarm already reached the host
|
||||
}
|
||||
else
|
||||
{
|
||||
// Review r1 #1: only acknowledged since the query read it — the entry's ACTIVE state still
|
||||
// stands, merged with the ack (Active ⇒ ActiveAcked; ActiveAcked / Inactive unchanged).
|
||||
DispatchSnapshotEntry(entry.CurrentState == AlarmConditionState.Active
|
||||
? MergeAcknowledged(entry)
|
||||
: entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
AlarmSnapshotRefreshes.Add(1, _clientTag);
|
||||
if (superseded > 0) AlarmSnapshotRefreshEntriesSuperseded.Add(superseded, _clientTag);
|
||||
_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;
|
||||
}
|
||||
finally
|
||||
{
|
||||
lock (_dispatchLock) _touchedDuringRefresh = null;
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_refreshGate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private static ActiveAlarmSnapshot MergeAcknowledged(ActiveAlarmSnapshot entry)
|
||||
{
|
||||
var merged = entry.Clone();
|
||||
merged.CurrentState = AlarmConditionState.ActiveAcked;
|
||||
return merged;
|
||||
}
|
||||
|
||||
/// <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)
|
||||
{
|
||||
if (_touchedDuringRefresh is not { } touched) return;
|
||||
touched[reference] = fullState || (touched.TryGetValue(reference, out var prior) && prior);
|
||||
}
|
||||
|
||||
private void Dispatch(AlarmFeedMessage message)
|
||||
{
|
||||
lock (_dispatchLock)
|
||||
{
|
||||
DispatchLocked(message);
|
||||
}
|
||||
}
|
||||
|
||||
private void DispatchLocked(AlarmFeedMessage message)
|
||||
{
|
||||
switch (message.PayloadCase)
|
||||
{
|
||||
case AlarmFeedMessage.PayloadOneofCase.ActiveAlarm:
|
||||
NoteTouched(message.ActiveAlarm.AlarmFullReference, fullState: 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,
|
||||
fullState: message.Transition.TransitionKind != AlarmTransitionKind.Acknowledge);
|
||||
DispatchTransition(message.Transition);
|
||||
break;
|
||||
case AlarmFeedMessage.PayloadOneofCase.SnapshotComplete:
|
||||
_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
|
||||
// were raised; every reopened stream's sentinel raises it again.
|
||||
RaiseSnapshotDelivered();
|
||||
@@ -318,5 +479,6 @@ internal sealed class GatewayGalaxyAlarmFeed : IGalaxyAlarmFeed
|
||||
try { await _loop.ConfigureAwait(false); } catch { /* shutdown */ }
|
||||
}
|
||||
_cts.Dispose();
|
||||
// _refreshGate is deliberately not disposed: a re-read unwinding from the cancellation above still releases it.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,4 +53,26 @@ internal interface IGalaxyAlarmFeed : IAsyncDisposable
|
||||
/// sentinel signals only if that subscription is still the live one. The default accessors make it a no-op.
|
||||
/// </summary>
|
||||
event EventHandler? StreamOpened { add { } remove { } }
|
||||
|
||||
/// <summary>
|
||||
/// True when <see cref="RefreshSnapshotAsync"/> can re-read the gateway's active-alarm set without reopening
|
||||
/// the stream (lmxopcua#925). The default is false, for feeds with no query (the test fakes).
|
||||
/// </summary>
|
||||
bool SupportsSnapshotRefresh => false;
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#925: re-read the gateway's current active-alarm set (<c>QueryActiveAlarms</c>, the same monitor
|
||||
/// cache the stream's opening snapshot comes from) and raise each entry on <see cref="OnAlarmTransition"/> as a
|
||||
/// restatement, exactly like a snapshot entry, while the live stream stays open. An entry is skipped when the
|
||||
/// live stream delivered a full-state message (snapshot entry, Raise, Retrigger, Clear) for the same alarm after
|
||||
/// the query was issued: that message is at least as new as the query's view, and replaying the older view after
|
||||
/// 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.
|
||||
/// </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);
|
||||
}
|
||||
|
||||
+392
@@ -0,0 +1,392 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Threading.Channels;
|
||||
using Google.Protobuf.WellKnownTypes;
|
||||
using Grpc.Core;
|
||||
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#925: a subscription that becomes live while the feed's stream is already past its
|
||||
/// <c>snapshot_complete</c> sentinel (a changed alarm set, a reconnect that kept the session-less feed, or a change
|
||||
/// during the snapshot phase — F4) is established by a re-read of the gateway's active-alarm set
|
||||
/// (<c>QueryActiveAlarms</c>) instead of waiting, indefinitely, for the stream to reopen. The re-read is replayed as
|
||||
/// restatements, never over a newer live message for the same alarm, and the signal follows its replay.
|
||||
/// </summary>
|
||||
[Trait("Feature", "GrpcData")]
|
||||
[Trait("Phase", "A1")]
|
||||
public sealed class GalaxyAlarmSnapshotRefreshTests
|
||||
{
|
||||
private const string Tank1 = "Tank01.Level.HiHi";
|
||||
private const string Tank2 = "Tank02.Level.HiHi";
|
||||
|
||||
private static CancellationToken Ct => TestContext.Current.CancellationToken;
|
||||
|
||||
/// <summary>The deploy-added condition is established without a stream reopen: re-read entry, then the signal.</summary>
|
||||
[Fact]
|
||||
public async Task A_resubscribe_on_a_live_stream_rereads_the_active_set_and_signals_after_its_entries()
|
||||
{
|
||||
await using var rig = new Rig();
|
||||
using var driver = NewDriver(rig.Feed);
|
||||
var trace = Record(driver);
|
||||
|
||||
var h1 = await driver.SubscribeAlarmsAsync([Tank1], Ct);
|
||||
var s = await rig.NextStreamAsync();
|
||||
await s.WriteAsync(new AlarmFeedMessage { SnapshotComplete = true }, Ct);
|
||||
await TestWait.UntilAsync(() => Count(trace) == 1, "the first sentinel's signal", () => Dump(trace));
|
||||
rig.QueryCount.ShouldBe(0, "the first subscription is covered by the stream's own sentinel");
|
||||
|
||||
await driver.UnsubscribeAlarmsAsync(h1, Ct);
|
||||
await driver.SubscribeAlarmsAsync([Tank1, Tank2], Ct);
|
||||
var q = await rig.NextQueryAsync();
|
||||
await Task.Delay(100, Ct);
|
||||
Count(trace).ShouldBe(1, "no signal before the re-read completed");
|
||||
q.Complete(Entry(Tank2, AlarmConditionState.Active));
|
||||
|
||||
await TestWait.UntilAsync(() => Count(trace) == 3, "the re-read entry then the signal", () => Dump(trace));
|
||||
Snapshot(trace).ShouldBe(["signal:" + Tank1, "event:" + Tank2 + ":Retrigger:restatement", $"signal:{Tank1},{Tank2}"]);
|
||||
rig.StreamOpens.ShouldBe(1, "the stream was not reopened");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// No phantom transition: a live message delivered after the re-read was issued is at least as new as the re-read's
|
||||
/// view of that alarm, so the re-read's (older) entry for it is not replayed. Positive control: the other alarm's
|
||||
/// entry in the same re-read IS replayed.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task A_live_transition_after_the_reread_was_issued_supersedes_its_entry_for_that_alarm()
|
||||
{
|
||||
await using var rig = new Rig();
|
||||
using var driver = NewDriver(rig.Feed);
|
||||
var trace = Record(driver);
|
||||
|
||||
var h1 = await driver.SubscribeAlarmsAsync([Tank1], Ct);
|
||||
var s = await rig.NextStreamAsync();
|
||||
await s.WriteAsync(new AlarmFeedMessage { SnapshotComplete = true }, Ct);
|
||||
await TestWait.UntilAsync(() => Count(trace) == 1, "the first sentinel's signal", () => Dump(trace));
|
||||
|
||||
await driver.UnsubscribeAlarmsAsync(h1, Ct);
|
||||
await driver.SubscribeAlarmsAsync([Tank1, Tank2], Ct);
|
||||
var q = await rig.NextQueryAsync();
|
||||
// While the query is in flight Tank2 clears on the live stream; the query's view still has it Active.
|
||||
await s.WriteAsync(Transition(Tank2, AlarmTransitionKind.Clear), Ct);
|
||||
await TestWait.UntilAsync(() => Count(trace) == 2, "the live clear", () => Dump(trace));
|
||||
q.Complete(Entry(Tank1, AlarmConditionState.ActiveAcked), Entry(Tank2, AlarmConditionState.Active));
|
||||
|
||||
await TestWait.UntilAsync(() => Count(trace) == 4, "the re-read's Tank1 entry then the signal", () => Dump(trace));
|
||||
await Task.Delay(100, Ct);
|
||||
Snapshot(trace).ShouldBe([
|
||||
"signal:" + Tank1,
|
||||
"event:" + Tank2 + ":Clear:live",
|
||||
"event:" + Tank1 + ":ActiveAcknowledged:restatement",
|
||||
$"signal:{Tank1},{Tank2}",
|
||||
]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Review r1 #1: an Acknowledge carries only the ack dimension, so it does not supersede the re-read's view of
|
||||
/// the alarm's ACTIVE state. Tank2 is Active+unacked when the query reads it; an operator acks it before the
|
||||
/// replay ⇒ the replay must project Active+acked (not skip it and then signal a cold, inactive condition known).
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task An_acknowledge_during_the_reread_merges_into_its_entry_instead_of_superseding_it()
|
||||
{
|
||||
await using var rig = new Rig();
|
||||
using var driver = NewDriver(rig.Feed);
|
||||
var trace = Record(driver);
|
||||
|
||||
var h1 = await driver.SubscribeAlarmsAsync([Tank1], Ct);
|
||||
var s = await rig.NextStreamAsync();
|
||||
await s.WriteAsync(new AlarmFeedMessage { SnapshotComplete = true }, Ct);
|
||||
await TestWait.UntilAsync(() => Count(trace) == 1, "the first sentinel's signal", () => Dump(trace));
|
||||
|
||||
await driver.UnsubscribeAlarmsAsync(h1, Ct);
|
||||
await driver.SubscribeAlarmsAsync([Tank1, Tank2], Ct);
|
||||
var q = await rig.NextQueryAsync();
|
||||
await s.WriteAsync(Transition(Tank2, AlarmTransitionKind.Acknowledge), Ct);
|
||||
await TestWait.UntilAsync(() => Count(trace) == 2, "the live acknowledge", () => Dump(trace));
|
||||
q.Complete(Entry(Tank2, AlarmConditionState.Active));
|
||||
|
||||
await TestWait.UntilAsync(() => Count(trace) == 4, "the merged entry then the signal", () => Dump(trace));
|
||||
Snapshot(trace).ShouldBe([
|
||||
"signal:" + Tank1,
|
||||
"event:" + Tank2 + ":Acknowledge:live",
|
||||
"event:" + Tank2 + ":ActiveAcknowledged:restatement",
|
||||
$"signal:{Tank1},{Tank2}",
|
||||
]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Review r1 #2: the stream reopens while the query is in flight. An alarm that cleared in the gap is simply
|
||||
/// absent from the reopened stream's snapshot (never "touched"), so the query's stale Active entry must NOT be
|
||||
/// replayed, and the re-read must not signal — the reopened stream's own sentinel covers the subscription.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task A_stream_reopen_during_the_reread_drops_its_replay_and_its_signal()
|
||||
{
|
||||
await using var rig = new Rig();
|
||||
using var driver = NewDriver(rig.Feed);
|
||||
var trace = Record(driver);
|
||||
|
||||
var h1 = await driver.SubscribeAlarmsAsync([Tank1], Ct);
|
||||
var s = await rig.NextStreamAsync();
|
||||
await s.WriteAsync(new AlarmFeedMessage { SnapshotComplete = true }, Ct);
|
||||
await TestWait.UntilAsync(() => Count(trace) == 1, "the first sentinel's signal", () => Dump(trace));
|
||||
|
||||
await driver.UnsubscribeAlarmsAsync(h1, Ct);
|
||||
await driver.SubscribeAlarmsAsync([Tank1, Tank2], Ct);
|
||||
var q = await rig.NextQueryAsync();
|
||||
s.TryComplete(new InvalidOperationException("gateway stream fault"));
|
||||
var s2 = await rig.NextStreamAsync();
|
||||
await s2.WriteAsync(new AlarmFeedMessage { SnapshotComplete = true }, Ct); // Tank2 cleared in the gap: absent
|
||||
await TestWait.UntilAsync(() => Count(trace) == 2, "the reopened stream's signal", () => Dump(trace));
|
||||
q.Complete(Entry(Tank2, AlarmConditionState.Active)); // stale: read before the clear
|
||||
|
||||
await Task.Delay(200, Ct);
|
||||
Snapshot(trace).ShouldBe(["signal:" + Tank1, $"signal:{Tank1},{Tank2}"],
|
||||
"no phantom Active from the stale re-read, and no second signal");
|
||||
rig.QueryCount.ShouldBe(1, "positive control: the re-read really ran");
|
||||
}
|
||||
|
||||
/// <summary>F4: a subscription changed during the snapshot phase is re-read at the sentinel instead of waiting for a reopen.</summary>
|
||||
[Fact]
|
||||
public async Task A_sentinel_under_an_earlier_subscription_triggers_a_reread_that_signals()
|
||||
{
|
||||
await using var rig = new Rig();
|
||||
using var driver = NewDriver(rig.Feed);
|
||||
var trace = Record(driver);
|
||||
|
||||
var first = await driver.SubscribeAlarmsAsync([Tank1], Ct);
|
||||
var s = await rig.NextStreamAsync();
|
||||
await driver.UnsubscribeAlarmsAsync(first, Ct);
|
||||
await driver.SubscribeAlarmsAsync([Tank1, Tank2], Ct); // snapshot phase still running: no re-read yet
|
||||
await Task.Delay(100, Ct);
|
||||
rig.QueryCount.ShouldBe(0, "the stream has not delivered its sentinel, so the subscribe does not re-read");
|
||||
|
||||
await s.WriteAsync(new AlarmFeedMessage { SnapshotComplete = true }, Ct);
|
||||
var q = await rig.NextQueryAsync();
|
||||
Count(trace).ShouldBe(0, "the mismatched sentinel itself still does not signal");
|
||||
q.Complete();
|
||||
|
||||
await TestWait.UntilAsync(() => Count(trace) == 1, "the re-read's signal", () => Dump(trace));
|
||||
Snapshot(trace).ShouldBe([$"signal:{Tank1},{Tank2}"]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A failed re-read retries a bounded number of times, then gives up WITHOUT signalling (the conditions stay
|
||||
/// unknown — F5 diagnoses them). Positive control: the next stream's sentinel still signals.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task A_failing_reread_retries_boundedly_and_never_signals()
|
||||
{
|
||||
await using var rig = new Rig();
|
||||
using var driver = NewDriver(rig.Feed);
|
||||
driver.AlarmSnapshotRefreshRetryDelay = TimeSpan.FromMilliseconds(10);
|
||||
var trace = Record(driver);
|
||||
|
||||
var h1 = await driver.SubscribeAlarmsAsync([Tank1], Ct);
|
||||
var s = await rig.NextStreamAsync();
|
||||
await s.WriteAsync(new AlarmFeedMessage { SnapshotComplete = true }, Ct);
|
||||
await TestWait.UntilAsync(() => Count(trace) == 1, "the first sentinel's signal", () => Dump(trace));
|
||||
|
||||
await driver.UnsubscribeAlarmsAsync(h1, Ct);
|
||||
await driver.SubscribeAlarmsAsync([Tank1, Tank2], Ct);
|
||||
for (var i = 0; i < GalaxyDriver.AlarmSnapshotRefreshAttempts; i++)
|
||||
(await rig.NextQueryAsync()).Fail(new RpcException(new Status(StatusCode.Unavailable, "gateway busy")));
|
||||
await Task.Delay(200, Ct);
|
||||
rig.QueryCount.ShouldBe(GalaxyDriver.AlarmSnapshotRefreshAttempts);
|
||||
Count(trace).ShouldBe(1, "a failed re-read never signals");
|
||||
|
||||
s.TryComplete(new InvalidOperationException("reopen"));
|
||||
var s2 = await rig.NextStreamAsync();
|
||||
await s2.WriteAsync(new AlarmFeedMessage { SnapshotComplete = true }, Ct);
|
||||
await TestWait.UntilAsync(() => Count(trace) == 2, "the reopened stream's signal", () => Dump(trace));
|
||||
Snapshot(trace)[1].ShouldBe($"signal:{Tank1},{Tank2}");
|
||||
}
|
||||
|
||||
/// <summary>An old gateway without the RPC: one attempt, no retry, no signal.</summary>
|
||||
[Fact]
|
||||
public async Task An_unimplemented_query_is_not_retried()
|
||||
{
|
||||
await using var rig = new Rig();
|
||||
using var driver = NewDriver(rig.Feed);
|
||||
driver.AlarmSnapshotRefreshRetryDelay = TimeSpan.FromMilliseconds(10);
|
||||
var trace = Record(driver);
|
||||
|
||||
var h1 = await driver.SubscribeAlarmsAsync([Tank1], Ct);
|
||||
var s = await rig.NextStreamAsync();
|
||||
await s.WriteAsync(new AlarmFeedMessage { SnapshotComplete = true }, Ct);
|
||||
await TestWait.UntilAsync(() => Count(trace) == 1, "the first sentinel's signal", () => Dump(trace));
|
||||
|
||||
await driver.UnsubscribeAlarmsAsync(h1, Ct);
|
||||
await driver.SubscribeAlarmsAsync([Tank1, Tank2], Ct);
|
||||
(await rig.NextQueryAsync()).Fail(new RpcException(new Status(StatusCode.Unimplemented, "no such method")));
|
||||
await Task.Delay(200, Ct);
|
||||
rig.QueryCount.ShouldBe(1);
|
||||
Count(trace).ShouldBe(1);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Bounded: a burst of re-subscribes while a re-read is in flight collapses into ONE follow-up re-read, and only
|
||||
/// the follow-up (made under the subscription that is live at the end) signals.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Resubscribes_during_a_reread_coalesce_into_one_followup()
|
||||
{
|
||||
await using var rig = new Rig();
|
||||
using var driver = NewDriver(rig.Feed);
|
||||
var trace = Record(driver);
|
||||
|
||||
var h = await driver.SubscribeAlarmsAsync([Tank1], Ct);
|
||||
var s = await rig.NextStreamAsync();
|
||||
await s.WriteAsync(new AlarmFeedMessage { SnapshotComplete = true }, Ct);
|
||||
await TestWait.UntilAsync(() => Count(trace) == 1, "the first sentinel's signal", () => Dump(trace));
|
||||
|
||||
await driver.UnsubscribeAlarmsAsync(h, Ct);
|
||||
h = await driver.SubscribeAlarmsAsync([Tank1, Tank2], Ct);
|
||||
var q1 = await rig.NextQueryAsync();
|
||||
for (var i = 0; i < 5; i++)
|
||||
{
|
||||
await driver.UnsubscribeAlarmsAsync(h, Ct);
|
||||
h = await driver.SubscribeAlarmsAsync(i % 2 == 0 ? [Tank2] : [Tank1, Tank2], Ct);
|
||||
}
|
||||
q1.Complete();
|
||||
var q2 = await rig.NextQueryAsync();
|
||||
q2.Complete();
|
||||
|
||||
await TestWait.UntilAsync(() => Count(trace) == 2, "the follow-up's signal", () => Dump(trace));
|
||||
await Task.Delay(200, Ct);
|
||||
rig.QueryCount.ShouldBe(2, "five re-subscribes during one re-read coalesce into one follow-up");
|
||||
Snapshot(trace).ShouldBe(["signal:" + Tank1, "signal:" + Tank2],
|
||||
"the first re-read was made under a replaced subscription, so only the follow-up signals — for the live set");
|
||||
}
|
||||
|
||||
private static int Count(List<string> trace) { lock (trace) return trace.Count; }
|
||||
|
||||
private static string[] Snapshot(List<string> trace) { lock (trace) return trace.ToArray(); }
|
||||
|
||||
private static string Dump(List<string> trace) { lock (trace) return string.Join(" | ", trace); }
|
||||
|
||||
private static List<string> Record(GalaxyDriver driver)
|
||||
{
|
||||
var trace = new List<string>();
|
||||
driver.OnAlarmEvent += (_, e) =>
|
||||
{
|
||||
lock (trace) trace.Add($"event:{e.ConditionId}:{e.Kind}:{(e.IsRestatement ? "restatement" : "live")}");
|
||||
};
|
||||
driver.InitialAlarmStateDelivered += (_, e) =>
|
||||
{
|
||||
lock (trace) trace.Add("signal:" + string.Join(',', e.ConditionIds));
|
||||
};
|
||||
return trace;
|
||||
}
|
||||
|
||||
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 Transition(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("RefreshTest"),
|
||||
new GalaxyRepositoryOptions(),
|
||||
new GalaxyReconnectOptions());
|
||||
return new GalaxyDriver(
|
||||
driverInstanceId: "drv-1",
|
||||
options: options,
|
||||
hierarchySource: null,
|
||||
alarmAcknowledger: null,
|
||||
alarmFeed: feed,
|
||||
ackCredentialResolver: FixedAckCredentialResolver.Fallback());
|
||||
}
|
||||
|
||||
/// <summary>One scripted <c>QueryActiveAlarms</c> call: the test completes or fails it.</summary>
|
||||
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);
|
||||
|
||||
public void Fail(Exception ex) => _result.TrySetException(ex);
|
||||
}
|
||||
|
||||
/// <summary>A real feed over test-written streams and a scripted query.</summary>
|
||||
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;
|
||||
private int _streamOpens;
|
||||
|
||||
public Rig()
|
||||
{
|
||||
Feed = new GatewayGalaxyAlarmFeed((_, ct) =>
|
||||
{
|
||||
Interlocked.Increment(ref _streamOpens);
|
||||
var c = Channel.CreateUnbounded<AlarmFeedMessage>();
|
||||
_opened.Writer.TryWrite(c);
|
||||
return c.Reader.ReadAllAsync(ct);
|
||||
}, clientName: "RefreshTest", reconnectDelay: TimeSpan.FromMilliseconds(10), queryFactory: QueryAsync);
|
||||
}
|
||||
|
||||
public GatewayGalaxyAlarmFeed Feed { get; }
|
||||
|
||||
public int QueryCount => Volatile.Read(ref _queryCount);
|
||||
|
||||
public int StreamOpens => Volatile.Read(ref _streamOpens);
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user