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
@@ -1,8 +1,10 @@
using System.Collections.ObjectModel;
using NodeId = Opc.Ua.NodeId;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
@@ -94,7 +96,10 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
public ProjectedParentSnapshot TryGetParent(ProjectedBrowseRequest request) => _cache.TryGetParent(request);
public IProjectedPageGuard? CaptureParentGuard(ProjectedBrowseRequest request, ProjectedParentSnapshot expected) => _cache.CaptureParentGuard(request, expected);
public bool TryResolveProjected(DataRealm realm, string localId, out ProjectedNodeProof? proof) => _cache.TryResolveProjected(realm, localId, out proof);
public bool IsUsableProof(ProjectedNodeProof proof) => _cache.IsUsableProof(proof);
public bool TryPinProjected(DataRealm realm, string localId, out IDisposable? pin) => _cache.TryPinProjected(realm, localId, out pin);
internal bool TryPinExpiredRecoveryPair(ProjectedNodeProof previous, ProjectedNodeProof successor, out IDisposable? pin) =>
_cache.TryPinExpiredRecoveryPair(previous, successor, out pin);
public async Task<IProjectedPreparedPage> PreparePageAsync(ProjectedBrowseRequest request, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(request); request.Budget.Validate(); request.Parent.Validate();
@@ -228,7 +233,8 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
return PreparedPage.Failed(ProjectionPageStatus.Unavailable);
var maxLease = TimeSpan.FromMilliseconds(binding.Mapping.MetadataLeaseMilliseconds);
var lease = new BoundProjectionLease(new MetadataAuthorityLease(serving, branch.Lease, request.RequestStartedTimestamp, maxLease, TimeSpan.Zero, Clock),
connection.CancellationToken, binding.LocalAuthority, _cache, request.MappingId, generation, () => IsCurrent(binding));
connection.CancellationToken, binding.LocalAuthority, _cache, request.MappingId, generation, () => IsCurrent(binding), connection.RouteCurrent,
connection.RouteIdentity, connection.Connection.Target, binding);
if (!lease.IsValid) return PreparedPage.Failed(ProjectionPageStatus.Unavailable);
var parentScope = previousParent?.Subject.Scope ?? binding.LocalScope;
var ancestry = previousParent?.Subject.LocalAncestry ?? binding.LocalAncestry;
@@ -273,6 +279,130 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
{
lock (_sync) return !_disposed && _mappings.TryGetValue(binding.Mapping.RemoteNamespaceMappingId, out var current) && ReferenceEquals(current, binding);
}
private sealed class ExactAuthority(ProjectedNodeProof proof) : IProjectedRetainedAuthority
{
private ProjectedNodeProof _proof = proof;
public long RetainedBytes { get; } = checked(2048L + ProjectedProofSize.Estimate(proof));
internal void Adopt(ProjectedNodeProof committed) => Volatile.Write(ref _proof, committed);
internal bool IsFor(ProjectedNodeProof committed) => ReferenceEquals(Volatile.Read(ref _proof), committed);
public bool IsCurrent()
{
var proof = Volatile.Read(ref _proof);
try { return proof.Lease.IsValid && proof.Resolver.LocalAuthority.IsActive &&
proof.Resolver.Resolve(proof.Metadata.View, proof.Subject).Kind == MappedSubjectResolutionKind.Mapped; }
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { return false; }
}
}
internal static bool DefinitionOwnsProof(ProjectedVariableDefinition definition, ProjectedNodeProof proof) =>
definition.AuthorityIsCurrent.Target is ExactAuthority authority && authority.IsFor(proof) && authority.IsCurrent();
// Refresh exactly one already-owned projected item. This deliberately creates no Browse
// page, cursor or sibling visibility and does not create a physical subscription.
internal async Task<bool> RenewExactAsync(ProjectedNodeProof previous, ProjectedVariableDefinition definition,
NodeId nodeId, DataCallerIdentity? caller, ConfiguredProjectionCapability? configured,
IProjectedNamespacePageSink sink, DataBudget budget, Func<bool> demandActive, CancellationToken cancellationToken, bool overlap = false)
{
var mapping = previous.Metadata.View.MappingId;
if (mapping is null || previous.Subject.Scope.Segments.Count == 0) return false;
ProjectedMappingBinding binding;
lock (_sync)
{
if (_disposed || !_mappings.TryGetValue(mapping, out binding!)) return false;
}
bool CallerAllowed() => demandActive() && (configured is not null
? configured.Matches(mapping, previous.Metadata.View, binding.LocalAuthority)
: caller is not null && _policy.IsCallerUsable(caller) &&
_policy.AuthorizeLocal(caller, OpcUaOperation.CreateMonitoredItems, previous.Subject.Scope));
if (!IsCurrent(binding) || !binding.LocalAuthority.IsActive || !CallerAllowed() ||
previous.Metadata.View.MappingRevision != binding.Mapping.Revision || previous.Metadata.View.Realm != binding.Mapping.Realm ||
previous.OriginMetadata.View.MappingId is not null ||
previous.Subject.Scope.Kind != binding.LocalScope.Kind ||
!string.Equals(previous.Subject.Scope.ClusterId, binding.LocalScope.ClusterId, StringComparison.OrdinalIgnoreCase) ||
previous.Subject.Scope.Segments.Count < binding.LocalScope.Segments.Count ||
!previous.Subject.Scope.Segments.Take(binding.LocalScope.Segments.Count).SequenceEqual(binding.LocalScope.Segments, StringComparer.Ordinal) ||
!previous.Subject.LocalAncestry.SequenceEqual(binding.LocalAncestry, StringComparer.OrdinalIgnoreCase)) return false;
if (!await _fetchSlots.WaitAsync(0, cancellationToken).ConfigureAwait(false)) return false;
IGrpcDataAdapterConnectionLease? connection = null;
try
{
var started = Clock.GetTimestamp();
using var timeout = new CancellationTokenSource(budget.Timeout, Clock);
using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeout.Token);
connection = await _source.AcquireAsync(binding.Mapping.DataConnectionId, linked.Token).ConfigureAwait(false);
if (connection is null || !ReferenceEquals(connection.Connection.Clock, Clock) ||
!string.Equals(connection.Connection.Target.ExpectedClusterId, previous.OriginMetadata.View.Address.OriginClusterId, StringComparison.OrdinalIgnoreCase)) return false;
using var route = CancellationTokenSource.CreateLinkedTokenSource(linked.Token, connection.CancellationToken);
var capabilities = await connection.Connection.GetCapabilitiesAsync(budget, route.Token).ConfigureAwait(false);
capabilities.Validate();
var serving = capabilities.Serving;
var target = connection.Connection.Target;
if (!capabilities.MetadataItemLeases || capabilities.Readiness != DataReadiness.Ready ||
(capabilities.Operations & DataOperations.Metadata) == 0 || serving.ServingGeneration <= 0 ||
!(string.Equals(serving.Role, "Primary", StringComparison.OrdinalIgnoreCase) ||
target.Mode == DataTargetMode.Node && target.Consistency == DataConsistency.ReadyReplica && string.Equals(serving.Role, "Secondary", StringComparison.OrdinalIgnoreCase))) return false;
var elapsed = Clock.GetElapsedTime(started, Clock.GetTimestamp());
if (elapsed < TimeSpan.Zero || elapsed >= budget.Timeout) return false;
var results = await connection.Connection.GetMetadataAsync(new([previous.OriginMetadata.View],
budget with { MaxItems = 1, Timeout = budget.Timeout - elapsed }), route.Token).ConfigureAwait(false);
elapsed = Clock.GetElapsedTime(started, Clock.GetTimestamp());
if (elapsed < TimeSpan.Zero || elapsed >= budget.Timeout || linked.IsCancellationRequested) return false;
if (results.Count != 1 || results[0].CorrelationId != "0" || results[0].Status != DataItemStatus.Good ||
results[0].Value is not { } metadata || results[0].Lease is not { } remoteLease ||
metadata.View != previous.OriginMetadata.View || metadata.Serving != serving || metadata.CatalogRevision != serving.CatalogEpoch ||
remoteLease.CatalogEpoch != serving.CatalogEpoch || remoteLease.AuthorityEpoch != serving.AuthorityEpoch ||
remoteLease.Duration <= TimeSpan.Zero || remoteLease.Duration > capabilities.Limits.MaxMetadataLease ||
metadata.BrowseName != previous.OriginMetadata.BrowseName || metadata.NodeKind != previous.OriginMetadata.NodeKind ||
metadata.ValueKind != previous.OriginMetadata.ValueKind || metadata.ValueRank != previous.OriginMetadata.ValueRank ||
metadata.ArrayElementKind != previous.OriginMetadata.ArrayElementKind ||
!metadata.Dimensions.SequenceEqual(previous.OriginMetadata.Dimensions) ||
(metadata.AllowedOperations & binding.Mapping.AllowedOperations & DataOperations.Subscribe) == 0 ||
!IsCurrent(binding) || !CallerAllowed() || connection.CancellationToken.IsCancellationRequested) return false;
metadata.Validate(); remoteLease.Validate();
var generation = _cache.CaptureGeneration(mapping);
var maximumLease = TimeSpan.FromMilliseconds(binding.Mapping.MetadataLeaseMilliseconds);
if (caller?.CredentialExpiresUtc is { } expiry)
{
var remaining = expiry - Clock.GetUtcNow();
if (remaining <= TimeSpan.Zero) return false;
if (remaining < maximumLease) maximumLease = remaining;
}
var lease = new BoundProjectionLease(new MetadataAuthorityLease(serving, remoteLease, started, maximumLease, TimeSpan.Zero, Clock),
connection.CancellationToken, binding.LocalAuthority, _cache, mapping, generation, () => IsCurrent(binding), connection.RouteCurrent,
connection.RouteIdentity, connection.Connection.Target, binding);
var subject = previous.Subject with { Serving = serving, AllowedOperations = binding.Mapping.AllowedOperations & metadata.AllowedOperations,
WriteThrough = binding.Mapping.WriteThrough && metadata.Writable };
var mapped = metadata with { View = previous.Metadata.View };
var resolver = new MappedSubjectResolver([subject], serving.CatalogEpoch, binding.LocalAuthority);
var renewed = new ProjectedNodeProof(previous.LocalIdentifier, mapped, subject, resolver, lease, generation, metadata,
TimeSpan.FromMilliseconds(binding.Mapping.StaleTimeoutMilliseconds));
var guard = new ExactAuthority(renewed);
if (!guard.IsCurrent() || caller is not null && !_policy.AuthorizeMapped(caller, OpcUaOperation.CreateMonitoredItems,
mapped.View, serving, subject, resolver, lease)) return false;
var newDefinition = new ProjectedVariableDefinition(definition.Realm, definition.LocalIdentifier, definition.Parent,
mapped, generation, guard.IsCurrent) { Lifetime = definition.Lifetime };
return sink.TryRenewExact(nodeId, definition, newDefinition, () =>
{
var duration = Clock.GetElapsedTime(started, Clock.GetTimestamp());
if (linked.IsCancellationRequested || cancellationToken.IsCancellationRequested || connection.CancellationToken.IsCancellationRequested ||
duration < TimeSpan.Zero || duration >= budget.Timeout ||
!IsCurrent(binding) || !CallerAllowed() || !guard.IsCurrent()) return false;
ProjectedNodeProof? actual;
var committed = overlap ? _cache.TryRenewOverlap(previous, renewed, binding.Mapping.MaxProjectionNodes, out actual) :
_cache.TryRenewExact(previous, renewed, binding.Mapping.MaxProjectionNodes, out actual);
if (!committed || actual is null) return false;
guard.Adopt(actual);
return guard.IsCurrent();
});
}
catch (Exception ex) when (ex is not OutOfMemoryException) { return false; }
finally
{
try { if (connection is not null) await connection.DisposeAsync().ConfigureAwait(false); }
catch (Exception) { }
finally { _fetchSlots.Release(); }
}
}
public void Dispose()
{
ProjectedMappingBinding[] old;