fix(galaxy): establish a changed alarm subscription by a QueryActiveAlarms re-read instead of waiting for a stream reopen (#925)

A sentinel comes only when StreamAlarms opens, so a subscription that became live
after the current stream's sentinel (or changed during its snapshot phase, F4)
stayed unknown until a reopen. The feed now re-reads the active set via the
gateway's existing QueryActiveAlarms (same monitor cache), replays entries as
restatements except where the live stream already delivered a newer message for
that alarm, and the driver then signals the still-live subscription. Coalesced
(one in flight + one follow-up), 3 bounded retries, Unimplemented not retried,
a failed re-read never signals.
This commit is contained in:
Joseph Doherty
2026-11-28 09:24:26 -05:00
parent 05f431f5d8
commit b4c27bd5b8
7 changed files with 617 additions and 10 deletions
@@ -169,6 +169,12 @@ 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;
// Production runtime owned by InitializeAsync (BuildProductionRuntimeAsync). The
// driver builds these when it opens a real gw session; tests bypass them by
@@ -1002,7 +1008,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 +1099,8 @@ 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;
if (releaseFeed)
{
try { await alarmFeed!.DisposeAsync().ConfigureAwait(false); }
@@ -2789,6 +2798,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 +3056,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 +3070,141 @@ 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()
{
try
{
while (true)
{
await RefreshAlarmSnapshotOnceAsync().ConfigureAwait(false);
// 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);
}
}
catch (Exception ex)
{
Volatile.Write(ref _alarmRefreshState, 0);
_logger.LogWarning(ex, "GalaxyDriver active-alarm re-read loop failed unexpectedly");
}
}
private async Task RefreshAlarmSnapshotOnceAsync()
{
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) return;
try
{
using var timeout = new CancellationTokenSource(AlarmSnapshotRefreshTimeout);
if (!await feed.RefreshSnapshotAsync(timeout.Token).ConfigureAwait(false)) return;
break;
}
catch (Exception ex) when (ex is ObjectDisposedException || _disposed)
{
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);
await Task.Delay(AlarmSnapshotRefreshRetryDelay).ConfigureAwait(false);
}
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,27 @@ 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 any message for since the in-flight re-read was issued (null when none is
// in flight). Guarded by _dispatchLock.
private HashSet<string>? _touchedDuringRefresh;
// 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 +112,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;
@@ -163,14 +195,82 @@ 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;
using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _cts.Token);
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 HashSet<string>(StringComparer.Ordinal);
lock (_dispatchLock) _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();
foreach (var entry in entries)
{
if (touched.Contains(entry.AlarmFullReference)) { superseded++; continue; }
DispatchSnapshotEntry(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 void Dispatch(AlarmFeedMessage message)
{
lock (_dispatchLock)
{
DispatchLocked(message);
}
}
private void DispatchLocked(AlarmFeedMessage message)
{
switch (message.PayloadCase)
{
case AlarmFeedMessage.PayloadOneofCase.ActiveAlarm:
_touchedDuringRefresh?.Add(message.ActiveAlarm.AlarmFullReference);
DispatchSnapshotEntry(message.ActiveAlarm);
break;
case AlarmFeedMessage.PayloadOneofCase.Transition:
_touchedDuringRefresh?.Add(message.Transition.AlarmFullReference);
DispatchTransition(message.Transition);
break;
case AlarmFeedMessage.PayloadOneofCase.SnapshotComplete:
@@ -318,5 +418,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,23 @@ 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 any message 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.
/// Completes true once every entry was raised; false when the feed has no query. 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);
}