feat(grpc-data): A1 — Galaxy raises InitialAlarmStateDelivered on every snapshot_complete sentinel
This commit is contained in:
@@ -38,7 +38,7 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy;
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public sealed class GalaxyDriver
|
||||
: IDriver, ITagDiscovery, IReadable, IWritable, ISubscribable, IRediscoverable, IHostConnectivityProbe, IAlarmSource, IAlarmAcknowledgePreflight, IAlarmAcknowledgeConfirmation, ISkippedTagReporter, IDisposable, IAsyncDisposable
|
||||
: IDriver, ITagDiscovery, IReadable, IWritable, ISubscribable, IRediscoverable, IHostConnectivityProbe, IAlarmSource, IAlarmInitialStateSignal, IAlarmAcknowledgePreflight, IAlarmAcknowledgeConfirmation, ISkippedTagReporter, IDisposable, IAsyncDisposable
|
||||
{
|
||||
/// <summary>Authored tags this driver could not dial — a TagConfig with no usable
|
||||
/// <c>attributeRef</c> has no MXAccess address to bind.</summary>
|
||||
@@ -162,6 +162,10 @@ public sealed class GalaxyDriver
|
||||
// handles are added/removed (HashSet.First() is unstable).
|
||||
private readonly List<GalaxyAlarmSubscriptionHandle> _alarmSubscriptions = new();
|
||||
|
||||
// grpc-data A1: the alarm refs (RawPaths) of the live subscription — what a sentinel signal covers. Under
|
||||
// _alarmHandlersLock, replaced with the handle.
|
||||
private IReadOnlyList<string> _alarmSubscriptionRefs = Array.Empty<string>();
|
||||
|
||||
// Production runtime owned by InitializeAsync (BuildProductionRuntimeAsync). The
|
||||
// driver builds these when it opens a real gw session; tests bypass them by
|
||||
// injecting seams via the internal ctor, which leaves both fields null and skips
|
||||
@@ -300,6 +304,15 @@ public sealed class GalaxyDriver
|
||||
/// <summary>Raised when the gateway reports an alarm event for a subscribed Galaxy attribute.</summary>
|
||||
public event EventHandler<AlarmEventArgs>? OnAlarmEvent;
|
||||
|
||||
/// <inheritdoc />
|
||||
/// <remarks>
|
||||
/// grpc-data A1 (§5.1): raised on the feed thread for every <c>snapshot_complete</c> sentinel — after the
|
||||
/// snapshot entries were bridged to <see cref="OnAlarmEvent"/> — covering every alarm ref of the live
|
||||
/// subscription. Suppressed exactly like <see cref="OnAlarmEvent"/> (G5): nothing while no alarm
|
||||
/// subscription is live.
|
||||
/// </remarks>
|
||||
public event EventHandler<AlarmInitialStateEventArgs>? InitialAlarmStateDelivered;
|
||||
|
||||
/// <summary>Initializes a new instance of the <see cref="GalaxyDriver"/> class.</summary>
|
||||
/// <param name="driverInstanceId">The unique identifier for this driver instance.</param>
|
||||
/// <param name="options">The Galaxy driver configuration options.</param>
|
||||
@@ -1069,6 +1082,7 @@ public sealed class GalaxyDriver
|
||||
if (alarmFeed is not null && _alarmFeedWired)
|
||||
{
|
||||
alarmFeed.OnAlarmTransition -= OnAlarmFeedTransition;
|
||||
alarmFeed.SnapshotDelivered -= OnAlarmFeedSnapshotDelivered;
|
||||
_alarmFeedWired = false;
|
||||
}
|
||||
if (releaseFeed) _alarmFeed = null;
|
||||
@@ -2725,6 +2739,7 @@ public sealed class GalaxyDriver
|
||||
}
|
||||
if (_alarmFeedWired) return;
|
||||
_alarmFeed.OnAlarmTransition += OnAlarmFeedTransition;
|
||||
_alarmFeed.SnapshotDelivered += OnAlarmFeedSnapshotDelivered;
|
||||
_alarmFeed.Start();
|
||||
_alarmFeedWired = true;
|
||||
}
|
||||
@@ -2756,6 +2771,7 @@ public sealed class GalaxyDriver
|
||||
// replacing the set with the latest handle is semantically faithful and bounds it at 1.
|
||||
_alarmSubscriptions.Clear();
|
||||
_alarmSubscriptions.Add(handle);
|
||||
_alarmSubscriptionRefs = sourceNodeIds.ToArray();
|
||||
}
|
||||
return Task.FromResult<IAlarmSubscriptionHandle>(handle);
|
||||
}
|
||||
@@ -2774,6 +2790,7 @@ public sealed class GalaxyDriver
|
||||
lock (_alarmHandlersLock)
|
||||
{
|
||||
_alarmSubscriptions.Remove(gash);
|
||||
if (_alarmSubscriptions.Count == 0) _alarmSubscriptionRefs = Array.Empty<string>();
|
||||
}
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
@@ -3003,6 +3020,30 @@ public sealed class GalaxyDriver
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// grpc-data A1 (§5.1, Galaxy row): the feed's <c>snapshot_complete</c> sentinel, on the feed thread after
|
||||
/// the snapshot entries were bridged. Signals the live subscription's refs; nothing while unsubscribed (G5).
|
||||
/// </summary>
|
||||
private void OnAlarmFeedSnapshotDelivered(object? sender, EventArgs e)
|
||||
{
|
||||
IReadOnlyList<string> refs;
|
||||
lock (_alarmHandlersLock)
|
||||
{
|
||||
if (_alarmSubscriptions.Count == 0) return;
|
||||
refs = _alarmSubscriptionRefs;
|
||||
}
|
||||
|
||||
if (refs.Count == 0) return;
|
||||
try
|
||||
{
|
||||
InitialAlarmStateDelivered?.Invoke(this, new AlarmInitialStateEventArgs(refs));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "GalaxyDriver InitialAlarmStateDelivered handler threw — continuing.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Forwards every fan-out event to the public <see cref="OnDataChange"/> for
|
||||
/// ISubscribable consumers, AND routes ScanState changes to the per-platform
|
||||
|
||||
@@ -74,6 +74,9 @@ internal sealed class GatewayGalaxyAlarmFeed : IGalaxyAlarmFeed
|
||||
/// <summary>Occurs when an alarm transition (raise, acknowledge, clear) is received from the Galaxy feed.</summary>
|
||||
public event EventHandler<GalaxyAlarmTransition>? OnAlarmTransition;
|
||||
|
||||
/// <inheritdoc />
|
||||
public event EventHandler? SnapshotDelivered;
|
||||
|
||||
/// <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>
|
||||
@@ -166,6 +169,9 @@ internal sealed class GatewayGalaxyAlarmFeed : IGalaxyAlarmFeed
|
||||
case AlarmFeedMessage.PayloadOneofCase.SnapshotComplete:
|
||||
_logger.LogDebug("Galaxy alarm feed active-alarm snapshot complete.");
|
||||
_initialSnapshot.TrySetResult();
|
||||
// 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;
|
||||
default:
|
||||
// Empty oneof — worker / gateway version skew. Count and drop.
|
||||
@@ -272,6 +278,18 @@ internal sealed class GatewayGalaxyAlarmFeed : IGalaxyAlarmFeed
|
||||
}
|
||||
}
|
||||
|
||||
private void RaiseSnapshotDelivered()
|
||||
{
|
||||
try
|
||||
{
|
||||
SnapshotDelivered?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Galaxy alarm feed SnapshotDelivered handler threw — continuing.");
|
||||
}
|
||||
}
|
||||
|
||||
private static GalaxyAlarmTransitionKind MapTransitionKind(AlarmTransitionKind kind) => kind switch
|
||||
{
|
||||
AlarmTransitionKind.Raise => GalaxyAlarmTransitionKind.Raise,
|
||||
|
||||
@@ -36,4 +36,14 @@ internal interface IGalaxyAlarmFeed : IAsyncDisposable
|
||||
/// task, for feeds with no snapshot phase (the test fakes raise synchronously).
|
||||
/// </summary>
|
||||
Task InitialSnapshotCompleted => Task.CompletedTask;
|
||||
|
||||
/// <summary>
|
||||
/// Raised synchronously on the feed thread for <b>every</b> <c>snapshot_complete</c> sentinel — the first
|
||||
/// one and the one after each stream reopen — after every snapshot entry of that stream was raised on
|
||||
/// <see cref="OnAlarmTransition"/>. The ordered "standing alarms delivered" point the driver turns into
|
||||
/// <c>IAlarmInitialStateSignal.InitialAlarmStateDelivered</c> (grpc-data plan §5.1, A1). Unlike
|
||||
/// <see cref="InitialSnapshotCompleted"/> it is not one-shot and never runs as a task continuation (F2).
|
||||
/// The default accessors make it a no-op for feeds with no snapshot phase.
|
||||
/// </summary>
|
||||
event EventHandler? SnapshotDelivered { add { } remove { } }
|
||||
}
|
||||
|
||||
+203
@@ -0,0 +1,203 @@
|
||||
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 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>
|
||||
/// grpc-data A1 (§5.1 Galaxy row): <see cref="GalaxyDriver"/> raises
|
||||
/// <see cref="IAlarmInitialStateSignal.InitialAlarmStateDelivered"/> on <b>every</b> <c>snapshot_complete</c>
|
||||
/// sentinel of the REAL <see cref="GatewayGalaxyAlarmFeed"/>, on the feed thread, after the snapshot entries were
|
||||
/// bridged to <see cref="IAlarmSource.OnAlarmEvent"/>, covering the live subscription's refs; never while no alarm
|
||||
/// subscription is live (G5); and again on a reopened stream's sentinel, so a condition a deploy added is covered
|
||||
/// by the next one (vii).
|
||||
/// </summary>
|
||||
[Trait("Feature", "GrpcData")]
|
||||
[Trait("Phase", "A1")]
|
||||
public sealed class GalaxyInitialAlarmStateSignalTests
|
||||
{
|
||||
private const string Tank1 = "Tank01.Level.HiHi";
|
||||
private const string Tank2 = "Tank02.Level.HiHi";
|
||||
|
||||
private static CancellationToken Ct => TestContext.Current.CancellationToken;
|
||||
|
||||
/// <summary>(ii) the replay's events precede the signal on the same ordered path; the signal lists the refs.</summary>
|
||||
[Fact]
|
||||
public async Task Sentinel_signals_after_the_snapshot_entries_covering_the_subscribed_refs()
|
||||
{
|
||||
await using var streams = new ScriptedStreams();
|
||||
using var driver = NewDriver(streams.Feed);
|
||||
var trace = Record(driver);
|
||||
|
||||
await driver.SubscribeAlarmsAsync([Tank1, Tank2], Ct);
|
||||
var s = await streams.NextAsync();
|
||||
await s.WriteAsync(Snapshot(Tank1, AlarmConditionState.Active), Ct);
|
||||
await s.WriteAsync(Snapshot(Tank2, AlarmConditionState.Inactive), Ct);
|
||||
await s.WriteAsync(new AlarmFeedMessage { SnapshotComplete = true }, Ct);
|
||||
|
||||
await TestWait.UntilAsync(() => trace.Count == 3, "two snapshot events then the signal", () => Dump(trace));
|
||||
trace.ShouldBe(["event:" + Tank1, "event:" + Tank2, $"signal:{Tank1},{Tank2}"]);
|
||||
}
|
||||
|
||||
/// <summary>Negative control: snapshot entries without their sentinel raise no signal.</summary>
|
||||
[Fact]
|
||||
public async Task No_signal_before_the_sentinel()
|
||||
{
|
||||
await using var streams = new ScriptedStreams();
|
||||
using var driver = NewDriver(streams.Feed);
|
||||
var trace = Record(driver);
|
||||
|
||||
await driver.SubscribeAlarmsAsync([Tank1], Ct);
|
||||
var s = await streams.NextAsync();
|
||||
await s.WriteAsync(Snapshot(Tank1, AlarmConditionState.Active), Ct);
|
||||
await TestWait.UntilAsync(() => trace.Count == 1, "the snapshot event", () => Dump(trace));
|
||||
await Task.Delay(150, Ct);
|
||||
trace.ShouldBe(["event:" + Tank1]);
|
||||
}
|
||||
|
||||
/// <summary>(xi) G5: a sentinel that completes while no alarm subscription is live raises nothing.</summary>
|
||||
[Fact]
|
||||
public async Task Sentinel_while_unsubscribed_raises_nothing()
|
||||
{
|
||||
await using var streams = new ScriptedStreams();
|
||||
using var driver = NewDriver(streams.Feed);
|
||||
var trace = Record(driver);
|
||||
|
||||
var handle = await driver.SubscribeAlarmsAsync([Tank1], Ct);
|
||||
var s = await streams.NextAsync();
|
||||
// Registered AFTER the driver's own handler (wired by the subscribe), so it runs once the driver handled it.
|
||||
var unsubscribedSentinel = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
streams.Feed.SnapshotDelivered += (_, _) => unsubscribedSentinel.TrySetResult();
|
||||
await driver.UnsubscribeAlarmsAsync(handle, Ct);
|
||||
await s.WriteAsync(Snapshot(Tank1, AlarmConditionState.Active), Ct);
|
||||
await s.WriteAsync(new AlarmFeedMessage { SnapshotComplete = true }, Ct);
|
||||
await unsubscribedSentinel.Task.WaitAsync(TimeSpan.FromSeconds(10), Ct);
|
||||
// Positive control on the same stream: a live re-subscribe + the next reopen's sentinel DOES signal.
|
||||
await driver.SubscribeAlarmsAsync([Tank1], Ct);
|
||||
s.Complete(new InvalidOperationException("reopen"));
|
||||
var s2 = await streams.NextAsync();
|
||||
await s2.WriteAsync(new AlarmFeedMessage { SnapshotComplete = true }, Ct);
|
||||
|
||||
await TestWait.UntilAsync(() => trace.Count >= 1, "the post-resubscribe signal", () => Dump(trace));
|
||||
await Task.Delay(100, Ct);
|
||||
trace.ShouldBe(["signal:" + Tank1]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// (vii) a stream reopen re-signals; a deploy that adds a condition (re-subscribe with the larger set) is
|
||||
/// covered by the NEXT sentinel, not before it.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Reopened_stream_signals_again_and_covers_a_condition_a_deploy_added()
|
||||
{
|
||||
await using var streams = new ScriptedStreams();
|
||||
using var driver = NewDriver(streams.Feed);
|
||||
var trace = Record(driver);
|
||||
|
||||
var h1 = await driver.SubscribeAlarmsAsync([Tank1], Ct);
|
||||
var s1 = await streams.NextAsync();
|
||||
await s1.WriteAsync(new AlarmFeedMessage { SnapshotComplete = true }, Ct);
|
||||
await TestWait.UntilAsync(() => trace.Count == 1, "first sentinel", () => Dump(trace));
|
||||
|
||||
s1.Complete(new InvalidOperationException("gateway stream fault"));
|
||||
var s2 = await streams.NextAsync();
|
||||
await s2.WriteAsync(new AlarmFeedMessage { SnapshotComplete = true }, Ct);
|
||||
await TestWait.UntilAsync(() => trace.Count == 2, "reopened stream's sentinel", () => Dump(trace));
|
||||
|
||||
// Deploy adds Tank2: DriverInstanceActor releases the old handle and subscribes the larger set.
|
||||
await driver.UnsubscribeAlarmsAsync(h1, Ct);
|
||||
await driver.SubscribeAlarmsAsync([Tank1, Tank2], Ct);
|
||||
await Task.Delay(100, Ct);
|
||||
trace.Count.ShouldBe(2, "a subscribe alone is not a signal — the active-alarm set was not re-read");
|
||||
|
||||
s2.Complete(new InvalidOperationException("gateway stream fault"));
|
||||
var s3 = await streams.NextAsync();
|
||||
await s3.WriteAsync(Snapshot(Tank2, AlarmConditionState.Active), Ct);
|
||||
await s3.WriteAsync(new AlarmFeedMessage { SnapshotComplete = true }, Ct);
|
||||
await TestWait.UntilAsync(() => trace.Count == 4, "the next sentinel", () => Dump(trace));
|
||||
trace.ShouldBe(["signal:" + Tank1, "signal:" + Tank1, "event:" + Tank2, $"signal:{Tank1},{Tank2}"]);
|
||||
}
|
||||
|
||||
private static List<string> Record(GalaxyDriver driver)
|
||||
{
|
||||
var trace = new List<string>();
|
||||
driver.OnAlarmEvent += (_, e) => { lock (trace) trace.Add("event:" + e.ConditionId); };
|
||||
driver.InitialAlarmStateDelivered += (_, e) =>
|
||||
{
|
||||
lock (trace) trace.Add("signal:" + string.Join(',', e.ConditionIds));
|
||||
};
|
||||
return trace;
|
||||
}
|
||||
|
||||
private static string Dump(List<string> trace)
|
||||
{
|
||||
lock (trace) return string.Join(" | ", trace);
|
||||
}
|
||||
|
||||
private static AlarmFeedMessage Snapshot(string reference, AlarmConditionState state) => new()
|
||||
{
|
||||
ActiveAlarm = new ActiveAlarmSnapshot
|
||||
{
|
||||
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 GalaxyDriver NewDriver(IGalaxyAlarmFeed feed)
|
||||
{
|
||||
var options = new GalaxyDriverOptions(
|
||||
new GalaxyGatewayOptions("http://localhost:5000", "literal-api-key"),
|
||||
new GalaxyMxAccessOptions("SignalTest"),
|
||||
new GalaxyRepositoryOptions(),
|
||||
new GalaxyReconnectOptions());
|
||||
return new GalaxyDriver(
|
||||
driverInstanceId: "drv-1",
|
||||
options: options,
|
||||
hierarchySource: null,
|
||||
alarmAcknowledger: null,
|
||||
alarmFeed: feed,
|
||||
ackCredentialResolver: FixedAckCredentialResolver.Fallback());
|
||||
}
|
||||
|
||||
/// <summary>A real feed over test-written streams; each (re)open takes the next channel.</summary>
|
||||
private sealed class ScriptedStreams : IAsyncDisposable
|
||||
{
|
||||
private readonly Channel<Channel<AlarmFeedMessage>> _opened = Channel.CreateUnbounded<Channel<AlarmFeedMessage>>();
|
||||
|
||||
public ScriptedStreams()
|
||||
{
|
||||
Feed = new GatewayGalaxyAlarmFeed((_, ct) =>
|
||||
{
|
||||
var c = Channel.CreateUnbounded<AlarmFeedMessage>();
|
||||
_opened.Writer.TryWrite(c);
|
||||
return c.Reader.ReadAllAsync(ct);
|
||||
}, clientName: "SignalTest", reconnectDelay: TimeSpan.FromMilliseconds(10));
|
||||
}
|
||||
|
||||
public GatewayGalaxyAlarmFeed Feed { get; }
|
||||
|
||||
public async Task<ChannelWriter<AlarmFeedMessage>> NextAsync()
|
||||
{
|
||||
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
|
||||
return (await _opened.Reader.ReadAsync(cts.Token)).Writer;
|
||||
}
|
||||
|
||||
public ValueTask DisposeAsync() => Feed.DisposeAsync();
|
||||
}
|
||||
}
|
||||
|
||||
file static class ChannelWriterExtensions
|
||||
{
|
||||
public static void Complete(this ChannelWriter<AlarmFeedMessage> writer, Exception ex) => writer.TryComplete(ex);
|
||||
}
|
||||
Reference in New Issue
Block a user