test: validate grpc data connections with local docker and opcua cli

This commit is contained in:
Joseph Doherty
2026-11-17 22:01:26 -05:00
parent 1df29a3124
commit 29fec57fac
194 changed files with 23327 additions and 740 deletions
@@ -66,6 +66,29 @@ internal sealed class DefaultSessionAdapter : ISessionAdapter
return await _session.ReadValueAsync(nodeId, ct);
}
/// <inheritdoc />
public async Task<DataValue> ReadValueAsync(NodeId nodeId, TimeSpan maximumAge, CancellationToken ct)
{
if (maximumAge < TimeSpan.Zero || maximumAge.TotalMilliseconds > int.MaxValue)
throw new ArgumentOutOfRangeException(nameof(maximumAge));
ArrayOf<ReadValueId> nodes = [new ReadValueId { NodeId = nodeId, AttributeId = Attributes.Value }];
var response = await _session.ReadAsync(null, maximumAge.TotalMilliseconds, TimestampsToReturn.Both, nodes, ct);
return ValidateReadResult(response.ResponseHeader, response.Results, nodeId);
}
internal static DataValue ValidateReadResult(ResponseHeader? header, ArrayOf<DataValue> results, NodeId nodeId)
{
var serviceStatus = header?.ServiceResult.Code ?? StatusCodes.BadUnexpectedError;
if (StatusCode.IsBad(serviceStatus))
throw new ServiceResultException(serviceStatus);
if (results.Count != 1)
throw new ServiceResultException(StatusCodes.BadUnexpectedError, $"Read response contained {results.Count} results for node {nodeId}.");
var value = results[0];
if (StatusCode.IsBad(value.StatusCode))
throw new ServiceResultException(value.StatusCode);
return value;
}
/// <inheritdoc />
public async Task<StatusCode> WriteValueAsync(NodeId nodeId, DataValue value, CancellationToken ct)
{
@@ -53,8 +53,7 @@ internal sealed class DefaultSubscriptionAdapter : ISubscriptionAdapter
onDataChange(nodeId.ToString(), notification.Value);
};
_subscription.AddItem(item);
await _subscription.ApplyChangesAsync(ct);
await AddItemAsync(item, ct);
var handle = item.ClientHandle;
_monitoredItems[handle] = item;
@@ -95,8 +94,7 @@ internal sealed class DefaultSubscriptionAdapter : ISubscriptionAdapter
if (Volatile.Read(ref _finishing) == 0 && e.NotificationValue is EventFieldList eventFields) onEvent(eventFields);
};
_subscription.AddItem(item);
await _subscription.ApplyChangesAsync(ct);
await AddItemAsync(item, ct);
var handle = item.ClientHandle;
_monitoredItems[handle] = item;
@@ -105,6 +103,24 @@ internal sealed class DefaultSubscriptionAdapter : ISubscriptionAdapter
return handle;
}
private async Task AddItemAsync(MonitoredItem item, CancellationToken ct)
{
_subscription.AddItem(item);
try
{
await _subscription.ApplyChangesAsync(ct);
if (item.Status.Error is { } error && StatusCode.IsBad(error.StatusCode))
throw new ServiceResultException(error.StatusCode);
}
catch
{
// Keep a rejected or interrupted add out of the tracked subscription; the
// SDK will carry any required deletion on its next ApplyChanges call.
_subscription.RemoveItem(item);
throw;
}
}
/// <inheritdoc />
public async Task ConditionRefreshAsync(CancellationToken ct)
{
@@ -61,6 +61,9 @@ internal interface ISessionAdapter : IDisposable
/// <returns>The current data value read from the server.</returns>
Task<DataValue> ReadValueAsync(NodeId nodeId, CancellationToken ct = default);
/// <summary>Reads a value using the supplied maximum cache age.</summary>
Task<DataValue> ReadValueAsync(NodeId nodeId, TimeSpan maximumAge, CancellationToken ct = default);
/// <summary>
/// Writes a typed value to a node on the connected OPC UA server.
/// </summary>
@@ -42,6 +42,20 @@ public interface IOpcUaClientService : IDisposable
/// <returns>The current data value of the node.</returns>
Task<DataValue> ReadValueAsync(NodeId nodeId, CancellationToken ct = default);
/// <summary>Reads a value allowing a cached value up to the specified age.</summary>
/// <param name="nodeId">The node whose value should be retrieved.</param>
/// <param name="maximumAge">Maximum cache age, from zero to Int32.MaxValue milliseconds.</param>
/// <param name="ct">The cancellation token that aborts the read request.</param>
/// <returns>The data value returned by the server.</returns>
Task<DataValue> ReadValueAsync(NodeId nodeId, TimeSpan maximumAge, CancellationToken ct = default)
{
if (maximumAge < TimeSpan.Zero || maximumAge.TotalMilliseconds > int.MaxValue)
throw new ArgumentOutOfRangeException(nameof(maximumAge));
if (maximumAge != TimeSpan.Zero)
throw new NotSupportedException("This client does not support reads with a maximum age.");
return ReadValueAsync(nodeId, ct);
}
/// <summary>
/// Writes an operator-supplied value to an OPC UA node after applying client-side type conversion when needed.
/// </summary>
@@ -155,7 +155,8 @@ public sealed class OpcUaClientService : IOpcUaClientService
// A new epoch first: a failover still connecting abandons itself instead of resurrecting the connection.
lock (_subscriptionLock) _connectionEpoch++;
var endpointUrl = _session?.EndpointUrl ?? _settings?.EndpointUrl ?? string.Empty;
// The SDK transport may already be disposed when teardown begins.
var endpointUrl = CurrentConnectionInfo?.EndpointUrl ?? _settings?.EndpointUrl ?? string.Empty;
// Snapshot the subscription adapter references under the lock so a concurrent
// RunFailoverAsync that nulls _dataSubscription / _alarmSubscription
@@ -210,6 +211,18 @@ public sealed class OpcUaClientService : IOpcUaClientService
return await _session!.ReadValueAsync(nodeId, ct);
}
/// <inheritdoc />
public async Task<DataValue> ReadValueAsync(NodeId nodeId, TimeSpan maximumAge, CancellationToken ct = default)
{
if (maximumAge < TimeSpan.Zero || maximumAge.TotalMilliseconds > int.MaxValue)
throw new ArgumentOutOfRangeException(nameof(maximumAge));
if (maximumAge == TimeSpan.Zero)
return await ReadValueAsync(nodeId, ct);
ThrowIfDisposed();
ThrowIfNotConnected();
return await _session!.ReadValueAsync(nodeId, maximumAge, ct);
}
/// <inheritdoc />
public async Task<StatusCode> WriteValueAsync(NodeId nodeId, object value, CancellationToken ct = default)
{
@@ -391,10 +404,17 @@ public sealed class OpcUaClientService : IOpcUaClientService
var monitorNode = sourceNodeId ?? ObjectIds.Server;
var subscription = await session.CreateSubscriptionAsync(intervalMs, ct);
lock (_subscriptionLock) _alarmSubscription = subscription;
var filter = CreateAlarmEventFilter();
await subscription.AddEventMonitoredItemAsync(
monitorNode, intervalMs, filter, AlarmCallback(session, subscription), ct);
try
{
var filter = CreateAlarmEventFilter();
await subscription.AddEventMonitoredItemAsync(
monitorNode, intervalMs, filter, AlarmCallback(session, subscription), ct);
}
catch
{
await CleanupFailedAlarmSubscriptionAsync(subscription);
throw;
}
lock (_subscriptionLock)
{
@@ -871,7 +891,7 @@ public sealed class OpcUaClientService : IOpcUaClientService
return;
var oldSession = _session;
var oldEndpoint = oldSession?.EndpointUrl ?? string.Empty;
var oldEndpoint = CurrentConnectionInfo?.EndpointUrl ?? _settings?.EndpointUrl ?? string.Empty;
if (!TransitionStateIfCurrent(epoch, ConnectionState.Reconnecting, oldEndpoint)) return;
Logger.Warning("Session lost on {EndpointUrl}. Attempting failover...", oldEndpoint);
@@ -1012,10 +1032,11 @@ public sealed class OpcUaClientService : IOpcUaClientService
if (alarmSubscription.HasValue)
{
var (sourceNodeId, intervalMs) = alarmSubscription.Value;
ISubscriptionAdapter? replayedAlarms = null;
try
{
var monitorNode = sourceNodeId ?? ObjectIds.Server;
var replayedAlarms = await session.CreateSubscriptionAsync(intervalMs, CancellationToken.None);
replayedAlarms = await session.CreateSubscriptionAsync(intervalMs, CancellationToken.None);
lock (_subscriptionLock) _alarmSubscription = replayedAlarms;
var filter = CreateAlarmEventFilter();
await replayedAlarms.AddEventMonitoredItemAsync(
@@ -1028,11 +1049,32 @@ public sealed class OpcUaClientService : IOpcUaClientService
}
catch (Exception ex)
{
if (replayedAlarms is not null) await CleanupFailedAlarmSubscriptionAsync(replayedAlarms);
Logger.Warning(ex, "Failed to replay alarm subscription");
}
}
}
private async Task CleanupFailedAlarmSubscriptionAsync(ISubscriptionAdapter subscription)
{
lock (_subscriptionLock)
{
if (ReferenceEquals(_alarmSubscription, subscription))
{
_alarmSubscription = null;
_activeAlarmSubscription = null;
}
}
using var cleanup = new CancellationTokenSource(TimeSpan.FromSeconds(5));
try { await subscription.DeleteAsync(cleanup.Token); }
catch (Exception ex) { Logger.Warning(ex, "Failed to delete rejected alarm subscription"); }
finally
{
try { subscription.Dispose(); }
catch (Exception ex) { Logger.Warning(ex, "Failed to dispose rejected alarm subscription"); }
}
}
private bool IsCurrentNotification(ISessionAdapter session, ISubscriptionAdapter subscription, bool alarm)
{
lock (_subscriptionLock)