diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient/OpcUaClientDriver.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient/OpcUaClientDriver.cs index eab80f26d..0c5ba3f50 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient/OpcUaClientDriver.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient/OpcUaClientDriver.cs @@ -29,7 +29,7 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient; /// back on its own recovers in place. /// /// -public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWritable, ISubscribable, IHostConnectivityProbe, IAlarmSource, ISkippedTagReporter, IDriverConnectionLossSource, IDisposable, IAsyncDisposable +public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWritable, ISubscribable, IHostConnectivityProbe, IAlarmSource, IAlarmInitialStateSignal, ISkippedTagReporter, IDriverConnectionLossSource, IDisposable, IAsyncDisposable { /// Authored tags whose TagConfig carried no usable nodeId, so there is no upstream node /// to dial. This driver's skip path was the quietest of the twelve: NamespaceMap @@ -122,6 +122,16 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit /// Occurs when an alarm event is received from the remote OPC UA server. public event EventHandler? OnAlarmEvent; + /// + /// + /// grpc-data A1 (§5.1 OpcUaClient row, F1/G2): raised from the per-event route when a subscription's + /// RefreshEndEventType arrives — after every refreshed event before it was routed (the alarm subscription + /// publishes sequentially) — covering that subscription's alarm RawPaths. NOT when ConditionRefresh returns. An + /// upstream without ConditionRefresh raises it once per refresh attempt with Unsignalable (the host's + /// backstop applies). + /// + public event EventHandler? InitialAlarmStateDelivered; + // ---- ISubscribable + IHostConnectivityProbe state ---- private readonly System.Collections.Concurrent.ConcurrentDictionary _subscriptions = new(); @@ -245,10 +255,19 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit var item = new MonitoredItem(telemetry: null!, new MonitoredItemOptions { DisplayName = "Server/Events" }); _alarmSubscriptions[id] = new RemoteAlarmSubscription( new Subscription(telemetry: null!, new SubscriptionOptions { DisplayName = $"{AlarmSubscriptionNamePrefix}{id}" }), - handle, item, (_, _) => { }); + handle, item, (_, _) => { }, refs.ToArray()); return handle; } + /// Test-only seam: the ConditionRefresh of the alarm subscription behind was + /// refused as unsupported (grpc-data A1: reports InitialStateUnsignalable as the refresh catch does). + /// The alarm subscription handle. + internal void ReportRefreshUnsupportedForTest(IAlarmSubscriptionHandle handle) + { + if (handle is OpcUaAlarmSubscriptionHandle h && _alarmSubscriptions.TryGetValue(h.Id, out var ras)) + ReportRefreshUnsignalable(ras.Subscription); + } + /// /// Test-only seam to install the that connect builds at /// runtime, so the v3 RawPath → upstream node id resolution can be exercised without a live @@ -2442,17 +2461,7 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit }); BeginAlarmSubscription(sourceNodeIds); - var subscription = new Subscription(telemetry: null!, new SubscriptionOptions - { - DisplayName = $"{AlarmSubscriptionNamePrefix}{id}", - PublishingInterval = 500, // 500ms — alarms don't need fast polling; the server pushes - KeepAliveCount = _options.SubscriptionKeepAliveCount, - LifetimeCount = _options.SubscriptionLifetimeCount, - MaxNotificationsPerPublish = _options.SubscriptionMaxNotificationsPerPublish, - PublishingEnabled = true, - Priority = 0, - TimestampsToReturn = TimestampsToReturn.Both, - }); + var subscription = new Subscription(telemetry: null!, BuildAlarmSubscriptionOptions(id)); // EventFilter SelectClauses — pick the standard BaseEventType fields we need to // materialize an AlarmEventArgs. Field positions are indexed by the AlarmField* @@ -2583,10 +2592,33 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit await subscription.CreateItemsAsync(cancellationToken).ConfigureAwait(false); ThrowIfSubscribeSuperseded(subscribeGeneration); - _alarmSubscriptions[id] = new RemoteAlarmSubscription(subscription, handle, eventItem, notifHandler); + _alarmSubscriptions[id] = new RemoteAlarmSubscription(subscription, handle, eventItem, notifHandler, + sourceFilter.Values.Distinct(StringComparer.Ordinal).ToArray()); } } + /// + /// The SDK options of alarm subscription . grpc-data A1 (G2) pins + /// SequentialPublishing = true here: without it the SDK's message workers may process a later publish + /// response before an earlier one, so a refresh replay's RefreshEnd could overtake its refreshed events. + /// + /// The alarm subscription id (display-name suffix). + /// The options. + internal SubscriptionOptions BuildAlarmSubscriptionOptions(long id) => new() + { + DisplayName = $"{AlarmSubscriptionNamePrefix}{id}", + PublishingInterval = 500, // 500ms — alarms don't need fast polling; the server pushes + // grpc-data A1 (G2): a refresh replay can span publish responses; only sequential publishing makes the + // SDK deliver them in sequence-number order, so the RefreshEnd signal is routed after every refreshed event. + SequentialPublishing = true, + KeepAliveCount = _options.SubscriptionKeepAliveCount, + LifetimeCount = _options.SubscriptionLifetimeCount, + MaxNotificationsPerPublish = _options.SubscriptionMaxNotificationsPerPublish, + PublishingEnabled = true, + Priority = 0, + TimestampsToReturn = TimestampsToReturn.Both, + }; + /// public async Task UnsubscribeAlarmsAsync(IAlarmSubscriptionHandle handle, CancellationToken cancellationToken) { @@ -2803,6 +2835,19 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit return; } + if (IsRefreshEnd(fields)) + { + // grpc-data A1 (F1): the refresh replay this subscription requested is complete and every refreshed event + // before it was routed (sequential publishing, G2). Under the emission lock, so the signal is ordered + // behind every emission. Covers the subscription's alarm RawPaths. + lock (_alarmStateLock) + { + if (handle is OpcUaAlarmSubscriptionHandle h && _alarmSubscriptions.TryGetValue(h.Id, out var ras)) + RaiseInitialAlarmState(ras.AlarmRefs, unsignalable: false); + } + return; + } + // Projection, the per-RawPath bookkeeping AND the emission run under one lock, so two notifications for // one condition (two publish threads; two subscriptions across a resubscribe) can never compute their // kinds from the same prior, nor reach the host out of order. The host's handler only marshals. @@ -2855,6 +2900,27 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit fields.Count > AlarmFieldEventType && UpstreamValueMapping.ToClr(fields[AlarmFieldEventType]) is NodeId t && t == ObjectTypeIds.RefreshRequiredEventType; + /// True for a RefreshEndEventType event — the end of a ConditionRefresh replay (grpc-data A1). + /// The event's fields. + /// Whether the event is a RefreshEnd marker. + internal static bool IsRefreshEnd(IReadOnlyList fields) => + fields.Count > AlarmFieldEventType && UpstreamValueMapping.ToClr(fields[AlarmFieldEventType]) is NodeId t + && t == ObjectTypeIds.RefreshEndEventType; + + private void RaiseInitialAlarmState(IReadOnlyList refs, bool unsignalable) + { + if (refs.Count == 0) return; + try + { + InitialAlarmStateDelivered?.Invoke(this, new AlarmInitialStateEventArgs(refs, unsignalable)); + } + catch (Exception ex) + { + _logger.LogWarning(ex, "OpcUaClientDriver '{DriverInstanceId}': InitialAlarmStateDelivered handler threw.", + _driverInstanceId); + } + } + /// True for the three ConditionRefresh marker event types — never alarms. /// The event's EventType. /// Whether it is a refresh marker. @@ -2886,6 +2952,9 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit } catch (ServiceResultException ex) when (IsConditionRefreshUnsupported(ex.StatusCode)) { + // grpc-data A1: no RefreshEnd will ever come — InitialStateUnsignalable for this subscription's refs, so + // the host's OpcUaClient backstop decides when they become known (documented residual). + ReportRefreshUnsignalable(subscription); if (Interlocked.Exchange(ref _conditionRefreshUnsupportedLogged, 1) == 0) _logger.LogInformation( "OpcUaClientDriver '{DriverInstanceId}': upstream server does not support ConditionRefresh " + @@ -2905,6 +2974,18 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit } } + /// grpc-data A1: report InitialStateUnsignalable for the refs of the alarm subscription + /// backs (the upstream has no ConditionRefresh). + /// The SDK alarm subscription whose refresh was refused as unsupported. + internal void ReportRefreshUnsignalable(Subscription subscription) + { + foreach (var ras in _alarmSubscriptions.Values) + { + if (!ReferenceEquals(ras.Subscription, subscription)) continue; + lock (_alarmStateLock) RaiseInitialAlarmState(ras.AlarmRefs, unsignalable: true); + } + } + /// /// ConditionRefresh every alarm subscription on the current session (matched by display name): after /// a keep-alive outage the session survived and on a RefreshRequired event. Events missed during the @@ -3156,7 +3237,8 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit Subscription Subscription, OpcUaAlarmSubscriptionHandle Handle, MonitoredItem EventItem, - MonitoredItemNotificationEventHandler Handler); + MonitoredItemNotificationEventHandler Handler, + IReadOnlyList AlarmRefs); private sealed record OpcUaAlarmSubscriptionHandle(long Id) : IAlarmSubscriptionHandle { diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests/OpcUaClientInitialAlarmStateSignalTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests/OpcUaClientInitialAlarmStateSignalTests.cs new file mode 100644 index 000000000..01c4f3c34 --- /dev/null +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests/OpcUaClientInitialAlarmStateSignalTests.cs @@ -0,0 +1,238 @@ +using Opc.Ua; +using Opc.Ua.Client; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; + +namespace ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests; + +/// +/// grpc-data A1 (§5.1 OpcUaClient row): the driver raises +/// on the subscription's +/// RefreshEndEventType — on the event route, after the refreshed events before it (F1) — never when +/// ConditionRefresh returns; an upstream without ConditionRefresh reports Unsignalable (vi); the alarm +/// subscription publishes sequentially (G2). +/// +[Trait("Category", "Unit")] +[Trait("Feature", "GrpcData")] +[Trait("Phase", "A1")] +public sealed class OpcUaClientInitialAlarmStateSignalTests +{ + private const string Trip1 = "Plant/opc/plc/Trip1"; + + /// + /// (iii) F1: the refresh call has returned but the refreshed events arrive later; nothing is signalled until + /// the RefreshEnd, which follows the refreshed Active event on the same route. + /// + [Fact] + public void Known_only_on_RefreshEnd_after_the_refreshed_events() + { + using var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions(), "opcua-a1-f1"); + var trace = Record(drv); + var handle = drv.AddAlarmSubscriptionForTest([Trip1]); + var index = new Dictionary { ["ns=3;s=Alarms.Trip1"] = Trip1 }; + + // ConditionRefreshAsync "returned" here — and nothing was signalled for it. + drv.RouteAlarmEvent(Marker(ObjectTypeIds.RefreshStartEventType), index, handle); + trace.ShouldBeEmpty(); + drv.RouteAlarmEvent(Condition(active: true, acked: false), index, handle); + trace.ShouldBe(["event:" + Trip1 + ":Retrigger"]); + + drv.RouteAlarmEvent(Marker(ObjectTypeIds.RefreshEndEventType), index, handle); + trace.ShouldBe(["event:" + Trip1 + ":Retrigger", "signal:" + Trip1]); + } + + /// A RefreshEnd for a subscription that was released (no live alarm subscription, G5) signals nothing. + [Fact] + public void RefreshEnd_of_a_released_subscription_signals_nothing() + { + using var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions(), "opcua-a1-g5"); + var trace = Record(drv); + var live = drv.AddAlarmSubscriptionForTest([Trip1]); + var index = new Dictionary(); + + drv.RouteAlarmEvent(Marker(ObjectTypeIds.RefreshEndEventType), index, new StrayHandle()); + trace.ShouldBeEmpty(); + // Positive control: the live subscription's RefreshEnd does signal. + drv.RouteAlarmEvent(Marker(ObjectTypeIds.RefreshEndEventType), index, live); + trace.ShouldBe(["signal:" + Trip1]); + } + + /// (vi) an upstream without ConditionRefresh reports the subscription's refs unsignalable (backstop). + [Fact] + public void Unsupported_ConditionRefresh_reports_the_refs_unsignalable() + { + using var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions(), "opcua-a1-backstop"); + var raised = new List(); + drv.InitialAlarmStateDelivered += (_, e) => raised.Add(e); + var handle = drv.AddAlarmSubscriptionForTest([Trip1, "Plant/opc/plc/Trip2"]); + + drv.ReportRefreshUnsupportedForTest(handle); + + raised.ShouldHaveSingleItem(); + raised[0].Unsignalable.ShouldBeTrue(); + raised[0].ConditionIds.ShouldBe([Trip1, "Plant/opc/plc/Trip2"]); + } + + /// (ix) G2 configuration pin: the alarm subscription publishes sequentially; data subscriptions untouched. + [Fact] + public void Alarm_subscription_sets_SequentialPublishing() + { + using var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions(), "opcua-a1-g2-pin"); + var options = drv.BuildAlarmSubscriptionOptions(7); + options.SequentialPublishing.ShouldBeTrue(); + options.DisplayName.ShouldEndWith("7"); + } + + /// + /// (ix) G2: a refresh replay split across two publish responses that ARRIVE out of order (seq 2 = RefreshEnd + /// before seq 1 = the refreshed Active event). Through the real SDK subscription with the driver's alarm + /// options, the event route still sees the refreshed event first and the RefreshEnd last. + /// + [Fact] + public async Task Out_of_order_publish_responses_route_the_RefreshEnd_last() + { + using var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions(), "opcua-a1-g2"); + var trace = Record(drv); + var handle = drv.AddAlarmSubscriptionForTest([Trip1]); + var index = new Dictionary { ["ns=3;s=Alarms.Trip1"] = Trip1 }; + + var replay = await SdkReplay.DeliverAsync(drv.BuildAlarmSubscriptionOptions(1), + [(2u, Marker(ObjectTypeIds.RefreshEndEventType)), (1u, Condition(active: true, acked: false))], + fields => drv.RouteAlarmEvent(fields, index, handle)); + + replay.ShouldBe([1u, 2u], "the SDK processed the publish responses in sequence-number order"); + trace.ShouldBe(["event:" + Trip1 + ":Retrigger", "signal:" + Trip1]); + } + + private static List Record(OpcUaClientDriver drv) + { + var trace = new List(); + drv.OnAlarmEvent += (_, e) => { lock (trace) trace.Add($"event:{e.ConditionId}:{e.Kind}"); }; + drv.InitialAlarmStateDelivered += (_, e) => + { + lock (trace) trace.Add("signal:" + string.Join(',', e.ConditionIds)); + }; + return trace; + } + + private static List Marker(NodeId type) => + [ + Variant.From(new byte[] { 9 }.ToByteString()), + new Variant(type), + new Variant(ObjectIds.Server), + new Variant(new LocalizedText("refresh")), + new Variant((ushort)100), + new Variant(DateTime.UtcNow), + Variant.Null, + Variant.Null, + Variant.Null, + Variant.Null, + ]; + + private static List Condition(bool active, bool acked) => + [ + Variant.From(new byte[] { 1 }.ToByteString()), + new Variant(new NodeId("TripAlarmType", 3)), + new Variant(NodeId.Parse("ns=3;s=Alarms.Trip1")), + new Variant(new LocalizedText("tripped")), + new Variant((ushort)700), + new Variant(DateTime.UtcNow), + new Variant(NodeId.Parse("ns=3;s=Alarms.Trip1.Cond")), + new Variant(active), + new Variant(acked), + Variant.Null, + ]; + + private sealed class StrayHandle : IAlarmSubscriptionHandle + { + public string DiagnosticId => "stray"; + } +} + +/// +/// Feeds notification messages into a REAL SDK (no session) through its internal +/// publish-response cache, in the given arrival order, and records the order the SDK's message worker +/// delivered them to the event monitored item. +/// +internal static class SdkReplay +{ + public static async Task> DeliverAsync( + SubscriptionOptions options, IReadOnlyList<(uint Seq, List Fields)> arrivals, Action> route) + { + var delivered = new List(); + var done = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var subscription = new Subscription(telemetry: null!, options); + var item = new MonitoredItem(telemetry: null!, new MonitoredItemOptions + { + DisplayName = "Server/Events", + StartNodeId = ObjectIds.Server, + AttributeId = Attributes.EventNotifier, + Filter = new EventFilter(), + }); + item.Notification += (_, args) => + { + if (args.NotificationValue is not EventFieldList efl) return; + var fields = efl.EventFields.ToList(); + var seq = OpcUaClientDriver.IsRefreshEnd(fields) ? 2u : 1u; // the test's two messages, by content + lock (delivered) + { + delivered.Add(seq); + route(fields); + if (delivered.Count == arrivals.Count) done.TrySetResult(); + } + }; + subscription.AddItem(item); + + var save = typeof(Subscription).GetMethods( + System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | + System.Reflection.BindingFlags.NonPublic) + .FirstOrDefault(m => m.Name == "SaveMessageInCache" && m.GetParameters().Length == 2) + ?? throw new InvalidOperationException("SDK Subscription.SaveMessageInCache not found"); + // The message worker is started with the keep-alive timer (normally by Create/Transfer on a live session). + var startWorker = typeof(Subscription).GetMethod("StartKeepAliveTimer", + System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic) + ?? throw new InvalidOperationException("SDK Subscription.StartKeepAliveTimer not found"); + startWorker.Invoke(subscription, null); + var available = arrivals.Select(a => a.Seq).OrderBy(s => s).ToArray(); + foreach (var (seq, fields) in arrivals) + { + var message = new NotificationMessage + { + SequenceNumber = seq, + PublishTime = DateTime.UtcNow, + NotificationData = + [ + new ExtensionObject(new EventNotificationList + { + Events = [new EventFieldList { ClientHandle = item.ClientHandle, EventFields = fields.ToArray() }], + }), + ], + }; + save.Invoke(subscription, [ToParam(save, available), message]); + // Let the message worker run on the early arrival before the next one lands — a real gap between + // two publish responses, so a non-sequential worker would process the later sequence number first. + await Task.Delay(300); + } + + try + { + await done.Task.WaitAsync(TimeSpan.FromSeconds(10)); + } + finally + { + subscription.Dispose(); + } + + return delivered; + } + + private static object ToParam(System.Reflection.MethodInfo save, uint[] available) + { + var t = save.GetParameters()[0].ParameterType; + if (t.IsInstanceOfType(available)) return available; + var implicitOp = t.GetMethods().FirstOrDefault(m => m.Name == "op_Implicit" && m.ReturnType == t + && m.GetParameters()[0].ParameterType == typeof(uint[])); + return implicitOp?.Invoke(null, [available]) ?? Activator.CreateInstance(t, available)!; + } +}