diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriver.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriver.cs index 4f7ed821c..46cf7e968 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriver.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriver.cs @@ -38,7 +38,7 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy; /// /// 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 { /// Authored tags this driver could not dial — a TagConfig with no usable /// attributeRef has no MXAccess address to bind. @@ -162,6 +162,10 @@ public sealed class GalaxyDriver // handles are added/removed (HashSet.First() is unstable). private readonly List _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 _alarmSubscriptionRefs = Array.Empty(); + // 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 /// Raised when the gateway reports an alarm event for a subscribed Galaxy attribute. public event EventHandler? OnAlarmEvent; + /// + /// + /// grpc-data A1 (§5.1): raised on the feed thread for every snapshot_complete sentinel — after the + /// snapshot entries were bridged to — covering every alarm ref of the live + /// subscription. Suppressed exactly like (G5): nothing while no alarm + /// subscription is live. + /// + public event EventHandler? InitialAlarmStateDelivered; + /// Initializes a new instance of the class. /// The unique identifier for this driver instance. /// The Galaxy driver configuration options. @@ -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(handle); } @@ -2774,6 +2790,7 @@ public sealed class GalaxyDriver lock (_alarmHandlersLock) { _alarmSubscriptions.Remove(gash); + if (_alarmSubscriptions.Count == 0) _alarmSubscriptionRefs = Array.Empty(); } return Task.CompletedTask; } @@ -3003,6 +3020,30 @@ public sealed class GalaxyDriver } } + /// + /// grpc-data A1 (§5.1, Galaxy row): the feed's snapshot_complete sentinel, on the feed thread after + /// the snapshot entries were bridged. Signals the live subscription's refs; nothing while unsubscribed (G5). + /// + private void OnAlarmFeedSnapshotDelivered(object? sender, EventArgs e) + { + IReadOnlyList 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."); + } + } + /// /// Forwards every fan-out event to the public for /// ISubscribable consumers, AND routes ScanState changes to the per-platform diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/GatewayGalaxyAlarmFeed.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/GatewayGalaxyAlarmFeed.cs index d6ad71f0c..4a1e20e6e 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/GatewayGalaxyAlarmFeed.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/GatewayGalaxyAlarmFeed.cs @@ -74,6 +74,9 @@ internal sealed class GatewayGalaxyAlarmFeed : IGalaxyAlarmFeed /// Occurs when an alarm transition (raise, acknowledge, clear) is received from the Galaxy feed. public event EventHandler? OnAlarmTransition; + /// + public event EventHandler? SnapshotDelivered; + /// Initializes a new instance of the class. /// A factory delegate that opens the alarm stream. /// An optional logger for diagnostic output. @@ -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, diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/IGalaxyAlarmFeed.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/IGalaxyAlarmFeed.cs index 4ace8f26d..a68004b91 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/IGalaxyAlarmFeed.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/IGalaxyAlarmFeed.cs @@ -36,4 +36,14 @@ internal interface IGalaxyAlarmFeed : IAsyncDisposable /// task, for feeds with no snapshot phase (the test fakes raise synchronously). /// Task InitialSnapshotCompleted => Task.CompletedTask; + + /// + /// Raised synchronously on the feed thread for every snapshot_complete sentinel — the first + /// one and the one after each stream reopen — after every snapshot entry of that stream was raised on + /// . The ordered "standing alarms delivered" point the driver turns into + /// IAlarmInitialStateSignal.InitialAlarmStateDelivered (grpc-data plan §5.1, A1). Unlike + /// 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. + /// + event EventHandler? SnapshotDelivered { add { } remove { } } } diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/GalaxyInitialAlarmStateSignalTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/GalaxyInitialAlarmStateSignalTests.cs new file mode 100644 index 000000000..df84cf397 --- /dev/null +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/GalaxyInitialAlarmStateSignalTests.cs @@ -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; + +/// +/// grpc-data A1 (§5.1 Galaxy row): raises +/// on every snapshot_complete +/// sentinel of the REAL , on the feed thread, after the snapshot entries were +/// bridged to , 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). +/// +[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; + + /// (ii) the replay's events precede the signal on the same ordered path; the signal lists the refs. + [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}"]); + } + + /// Negative control: snapshot entries without their sentinel raise no signal. + [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]); + } + + /// (xi) G5: a sentinel that completes while no alarm subscription is live raises nothing. + [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]); + } + + /// + /// (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. + /// + [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 Record(GalaxyDriver driver) + { + var trace = new List(); + 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 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()); + } + + /// A real feed over test-written streams; each (re)open takes the next channel. + private sealed class ScriptedStreams : IAsyncDisposable + { + private readonly Channel> _opened = Channel.CreateUnbounded>(); + + public ScriptedStreams() + { + Feed = new GatewayGalaxyAlarmFeed((_, ct) => + { + var c = Channel.CreateUnbounded(); + _opened.Writer.TryWrite(c); + return c.Reader.ReadAllAsync(ct); + }, clientName: "SignalTest", reconnectDelay: TimeSpan.FromMilliseconds(10)); + } + + public GatewayGalaxyAlarmFeed Feed { get; } + + public async Task> 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 writer, Exception ex) => writer.TryComplete(ex); +}