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
{