feat(grpc-data): A1 — OpcUaClient signals on RefreshEnd, sequential alarm publishing, Unsignalable without ConditionRefresh

This commit is contained in:
Joseph Doherty
2026-11-24 10:14:56 -05:00
parent b7f742efda
commit 4e984b160e
2 changed files with 335 additions and 15 deletions
@@ -29,7 +29,7 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient;
/// back on its own recovers in place.
/// </para>
/// </remarks>
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
{
/// <summary>Authored tags whose TagConfig carried no usable <c>nodeId</c>, so there is no upstream node
/// to dial. This driver's skip path was the quietest of the twelve: <c>NamespaceMap</c>
@@ -122,6 +122,16 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
/// <summary>Occurs when an alarm event is received from the remote OPC UA server.</summary>
public event EventHandler<AlarmEventArgs>? OnAlarmEvent;
/// <inheritdoc />
/// <remarks>
/// grpc-data A1 (§5.1 OpcUaClient row, F1/G2): raised from the per-event route when a subscription's
/// <c>RefreshEndEventType</c> 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 <c>Unsignalable</c> (the host's
/// backstop applies).
/// </remarks>
public event EventHandler<AlarmInitialStateEventArgs>? InitialAlarmStateDelivered;
// ---- ISubscribable + IHostConnectivityProbe state ----
private readonly System.Collections.Concurrent.ConcurrentDictionary<long, RemoteSubscription> _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;
}
/// <summary>Test-only seam: the ConditionRefresh of the alarm subscription behind <paramref name="handle"/> was
/// refused as unsupported (grpc-data A1: reports InitialStateUnsignalable as the refresh catch does).</summary>
/// <param name="handle">The alarm subscription handle.</param>
internal void ReportRefreshUnsupportedForTest(IAlarmSubscriptionHandle handle)
{
if (handle is OpcUaAlarmSubscriptionHandle h && _alarmSubscriptions.TryGetValue(h.Id, out var ras))
ReportRefreshUnsignalable(ras.Subscription);
}
/// <summary>
/// Test-only seam to install the <see cref="NamespaceMap"/> 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());
}
}
/// <summary>
/// The SDK options of alarm subscription <paramref name="id"/>. grpc-data A1 (G2) pins
/// <c>SequentialPublishing = true</c> 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.
/// </summary>
/// <param name="id">The alarm subscription id (display-name suffix).</param>
/// <returns>The options.</returns>
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,
};
/// <inheritdoc />
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;
/// <summary>True for a <c>RefreshEndEventType</c> event — the end of a ConditionRefresh replay (grpc-data A1).</summary>
/// <param name="fields">The event's fields.</param>
/// <returns>Whether the event is a RefreshEnd marker.</returns>
internal static bool IsRefreshEnd(IReadOnlyList<Variant> fields) =>
fields.Count > AlarmFieldEventType && UpstreamValueMapping.ToClr(fields[AlarmFieldEventType]) is NodeId t
&& t == ObjectTypeIds.RefreshEndEventType;
private void RaiseInitialAlarmState(IReadOnlyList<string> 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);
}
}
/// <summary>True for the three ConditionRefresh marker event types — never alarms.</summary>
/// <param name="eventType">The event's EventType.</param>
/// <returns>Whether it is a refresh marker.</returns>
@@ -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
}
}
/// <summary>grpc-data A1: report <c>InitialStateUnsignalable</c> for the refs of the alarm subscription
/// <paramref name="subscription"/> backs (the upstream has no ConditionRefresh).</summary>
/// <param name="subscription">The SDK alarm subscription whose refresh was refused as unsupported.</param>
internal void ReportRefreshUnsignalable(Subscription subscription)
{
foreach (var ras in _alarmSubscriptions.Values)
{
if (!ReferenceEquals(ras.Subscription, subscription)) continue;
lock (_alarmStateLock) RaiseInitialAlarmState(ras.AlarmRefs, unsignalable: true);
}
}
/// <summary>
/// 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<string> AlarmRefs);
private sealed record OpcUaAlarmSubscriptionHandle(long Id) : IAlarmSubscriptionHandle
{
@@ -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;
/// <summary>
/// grpc-data A1 (§5.1 OpcUaClient row): the driver raises
/// <see cref="IAlarmInitialStateSignal.InitialAlarmStateDelivered"/> on the subscription's
/// <c>RefreshEndEventType</c> — on the event route, after the refreshed events before it (F1) — never when
/// ConditionRefresh returns; an upstream without ConditionRefresh reports <c>Unsignalable</c> (vi); the alarm
/// subscription publishes sequentially (G2).
/// </summary>
[Trait("Category", "Unit")]
[Trait("Feature", "GrpcData")]
[Trait("Phase", "A1")]
public sealed class OpcUaClientInitialAlarmStateSignalTests
{
private const string Trip1 = "Plant/opc/plc/Trip1";
/// <summary>
/// (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.
/// </summary>
[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<string, string> { ["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]);
}
/// <summary>A RefreshEnd for a subscription that was released (no live alarm subscription, G5) signals nothing.</summary>
[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<string, string>();
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]);
}
/// <summary>(vi) an upstream without ConditionRefresh reports the subscription's refs unsignalable (backstop).</summary>
[Fact]
public void Unsupported_ConditionRefresh_reports_the_refs_unsignalable()
{
using var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions(), "opcua-a1-backstop");
var raised = new List<AlarmInitialStateEventArgs>();
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"]);
}
/// <summary>(ix) G2 configuration pin: the alarm subscription publishes sequentially; data subscriptions untouched.</summary>
[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");
}
/// <summary>
/// (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.
/// </summary>
[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<string, string> { ["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<string> Record(OpcUaClientDriver drv)
{
var trace = new List<string>();
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<Variant> 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<Variant> 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";
}
}
/// <summary>
/// Feeds notification messages into a REAL SDK <see cref="Subscription"/> (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.
/// </summary>
internal static class SdkReplay
{
public static async Task<List<uint>> DeliverAsync(
SubscriptionOptions options, IReadOnlyList<(uint Seq, List<Variant> Fields)> arrivals, Action<List<Variant>> route)
{
var delivered = new List<uint>();
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)!;
}
}