277 lines
18 KiB
C#
277 lines
18 KiB
C#
using Microsoft.Extensions.Logging.Abstractions;
|
|
using Opc.Ua;
|
|
using Opc.Ua.Client;
|
|
using Shouldly;
|
|
using Xunit;
|
|
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
|
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;
|
|
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
|
|
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
|
|
|
public sealed partial class GrpcDataConfiguredDiscoveryWireTests
|
|
{
|
|
[Fact(Timeout = 90000)]
|
|
public async Task Real_sdk_browse_pages_through_nested_projection_and_preserves_array_metadata()
|
|
{
|
|
using var origin = new LocalDataFixture(additionalRawNodes: 2, servingGeneration: 1, nestedCatalog: true);
|
|
await WithComposedServer(origin, origin.Root, async (session, sink, _, _, _, _, anchor) =>
|
|
{
|
|
var client = (SessionClient)session;
|
|
var rootReferences = await BrowseAll(client, anchor, 1);
|
|
rootReferences.Count.ShouldBe(3);
|
|
var folder = rootReferences.Single(x => x.BrowseName.Name == "Driver");
|
|
folder.NodeClass.ShouldBe(NodeClass.Object);
|
|
var folderNode = ExpandedNodeId.ToNodeId(folder.NodeId, session.NamespaceUris);
|
|
var children = await BrowseAll(client, folderNode, 1);
|
|
children.Count.ShouldBe(2);
|
|
children.Select(x => x.BrowseName.Name).Order().ShouldBe(new[] { "Array", "Speed" });
|
|
children.ShouldAllBe(x => x.NodeClass == NodeClass.Variable);
|
|
var arrayNode = ExpandedNodeId.ToNodeId(children.Single(x => x.BrowseName.Name == "Array").NodeId, session.NamespaceUris);
|
|
var read = await client.ReadAsync(new RequestHeader(), 0, TimestampsToReturn.Neither,
|
|
[new ReadValueId { NodeId = arrayNode, AttributeId = Attributes.ValueRank },
|
|
new ReadValueId { NodeId = arrayNode, AttributeId = Attributes.ArrayDimensions },
|
|
new ReadValueId { NodeId = arrayNode, AttributeId = Attributes.DataType }], TestContext.Current.CancellationToken);
|
|
read.Results.ToArray()!.ShouldAllBe(x => StatusCode.IsGood(x.StatusCode));
|
|
read.Results[0].WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(1);
|
|
((uint[])read.Results[1].WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy)!).ShouldBe(new uint[] { 3 });
|
|
read.Results[2].WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(DataTypeIds.Byte);
|
|
var id = ProjectedDataIds.Identifier("map", origin.Raw.Address with { Identifier = "Plant/Driver/Array" });
|
|
((IProjectedNodeLookup)sink).TryGetNodeId(ProjectedDataIds.RawNamespaceUri, id, out var indexed).ShouldBeTrue();
|
|
indexed.ShouldNotBeNull().ShouldBe(arrayNode);
|
|
});
|
|
}
|
|
|
|
[Fact(Timeout = 90000)]
|
|
public async Task Uns_projection_browses_and_reads_the_origin_metadata_through_the_real_registry()
|
|
{
|
|
using var origin = new LocalDataFixture(servingGeneration: 1, nestedUnsCatalog: true);
|
|
var originRoot = origin.Uns with { Address = origin.Uns.Address with { Identifier = "Area" }, Subject = "Area" };
|
|
await WithComposedServer(origin, originRoot, async (session, sink, _, _, _, _, anchor) =>
|
|
{
|
|
var children = await BrowseAll((SessionClient)session, anchor, 1);
|
|
var child = children.ShouldHaveSingleItem();
|
|
child.BrowseName.Name.ShouldBe("Speed");
|
|
child.NodeClass.ShouldBe(NodeClass.Variable);
|
|
var node = ExpandedNodeId.ToNodeId(child.NodeId, session.NamespaceUris);
|
|
var expected = ProjectedDataIds.Identifier("map", origin.Uns.Address);
|
|
((IProjectedNodeLookup)sink).TryGetNodeId(ProjectedDataIds.UnsNamespaceUri, expected, out var indexed).ShouldBeTrue();
|
|
indexed.ShouldNotBeNull().ShouldBe(node);
|
|
var response = await ((SessionClient)session).ReadAsync(new RequestHeader(), 0, TimestampsToReturn.Neither,
|
|
[new ReadValueId { NodeId = node, AttributeId = Attributes.ValueRank },
|
|
new ReadValueId { NodeId = node, AttributeId = Attributes.DataType }], TestContext.Current.CancellationToken);
|
|
response.Results.ToArray()!.ShouldAllBe(x => StatusCode.IsGood(x.StatusCode));
|
|
response.Results[0].WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(-1);
|
|
response.Results[1].WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(DataTypeIds.Int32);
|
|
});
|
|
}
|
|
|
|
[Fact(Timeout = 90000)]
|
|
public async Task Local_browse_filters_ungranted_sibling_while_preserving_allowed_folder()
|
|
{
|
|
using var origin = new LocalDataFixture(servingGeneration: 1);
|
|
await WithComposedServer(origin, origin.Root, async (session, _, _, _, _, _, _) =>
|
|
{
|
|
var namespaceIndex = session.NamespaceUris.GetIndex(V3NodeIds.RawNamespaceUri);
|
|
namespaceIndex.ShouldBeGreaterThan(0);
|
|
var root = new NodeId(V3NodeIds.SharedRootFolderId, (ushort)namespaceIndex);
|
|
var children = await BrowseAll((SessionClient)session, root, 10);
|
|
children.ShouldContain(x => x.DisplayName.Text == "Plant");
|
|
children.ShouldNotContain(x => x.DisplayName.Text == "Outside");
|
|
}, restrictToPlant: true);
|
|
}
|
|
|
|
[Fact(Timeout = 90000)]
|
|
public async Task Mapped_value_root_is_discovered_headlessly_then_read_and_monitored_by_sdk()
|
|
{
|
|
LocalDataFixture? peer = null;
|
|
var subscriptions = new FakeSubscriptions(() => peer!.Serving);
|
|
using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions);
|
|
peer = origin;
|
|
origin.Publish(42);
|
|
await WithComposedServer(origin, origin.Raw, async (session, sink, resolver, applier, access, placements, anchor) =>
|
|
{
|
|
var discovery = new ConfiguredProjectionDiscovery(placements, resolver, applier, sink, access,
|
|
new DataBudget(TimeSpan.FromSeconds(5), 32, 128_000), 8);
|
|
var reference = Reference("map", DataRealm.Raw, origin.Raw.Address);
|
|
await using var lease = await discovery.ResolveAsync(reference, TestContext.Current.CancellationToken);
|
|
lease.ShouldNotBeNull();
|
|
lease.IsValid.ShouldBeTrue();
|
|
await subscriptions.Opened.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask()
|
|
.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
|
|
((IProjectedNodeLookup)sink).TryResolve(anchor, out var root).ShouldBeTrue();
|
|
root.ShouldNotBeNull().Metadata.ValueKind.ShouldBe(DataValueKind.Int32);
|
|
var client = (SessionClient)session;
|
|
var read = await client.ReadAsync(new RequestHeader(), 0, TimestampsToReturn.Neither,
|
|
[new ReadValueId { NodeId = anchor, AttributeId = Attributes.NodeClass }], TestContext.Current.CancellationToken);
|
|
read.Results[0].StatusCode.ShouldBe(StatusCodes.Good);
|
|
read.Results[0].WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe((int)NodeClass.Variable);
|
|
// A cold SDK read schedules a remote read; the next read can consume its published sample.
|
|
var deadline = DateTime.UtcNow.AddSeconds(10);
|
|
Opc.Ua.DataValue value;
|
|
do
|
|
{
|
|
var values = await client.ReadAsync(new RequestHeader(), 5000, TimestampsToReturn.Both,
|
|
[new ReadValueId { NodeId = anchor, AttributeId = Attributes.Value }], TestContext.Current.CancellationToken);
|
|
value = values.Results[0];
|
|
if (StatusCode.IsGood(value.StatusCode)) break;
|
|
await Task.Delay(25, TestContext.Current.CancellationToken);
|
|
} while (DateTime.UtcNow < deadline);
|
|
StatusCode.IsGood(value.StatusCode).ShouldBeTrue();
|
|
value.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(42);
|
|
var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 10, 0, true, 0,
|
|
TestContext.Current.CancellationToken)).SubscriptionId;
|
|
var monitored = await client.CreateMonitoredItemsAsync(new RequestHeader(), sub, TimestampsToReturn.Both,
|
|
[new MonitoredItemCreateRequest { ItemToMonitor = new ReadValueId { NodeId = anchor, AttributeId = Attributes.Value },
|
|
MonitoringMode = MonitoringMode.Reporting, RequestedParameters = new MonitoringParameters
|
|
{ ClientHandle = 1, SamplingInterval = 100, QueueSize = 1, DiscardOldest = true } }], TestContext.Current.CancellationToken);
|
|
monitored.Results[0].StatusCode.ShouldBe(StatusCodes.Good);
|
|
access.HasLiveDemand(DataRealm.Raw, ProjectedDataIds.Identifier("map", origin.Raw.Address)).ShouldBeTrue();
|
|
});
|
|
}
|
|
|
|
private async Task WithComposedServer(LocalDataFixture origin, DataView root,
|
|
Func<ISession, SdkAddressSpaceSink, RemoteNamespaceResolver, ProjectedNamespaceApplier, ProjectedDataAccess, ProjectedMappingDeploymentRuntime, NodeId, Task> exercise,
|
|
bool restrictToPlant = false)
|
|
{
|
|
var ct = TestContext.Current.CancellationToken;
|
|
var pki = Path.Combine(Path.GetTempPath(), $"composed-projection-{Guid.NewGuid():N}");
|
|
var port = 0;
|
|
var started = await OpcUaHostStart.StartAsync(p =>
|
|
{
|
|
port = p;
|
|
return new OpcUaApplicationHost(new OpcUaApplicationHostOptions
|
|
{
|
|
ApplicationName = "ComposedProjection", ApplicationUri = $"urn:composed:{Guid.NewGuid():N}",
|
|
OpcUaPort = p, PublicHostname = "127.0.0.1", PkiStoreRoot = pki,
|
|
EnabledSecurityProfiles = [OpcUaSecurityProfile.None], AutoAcceptUntrustedClientCertificates = true,
|
|
}, NullLogger<OpcUaApplicationHost>.Instance, new PeerAuthenticator(origin.Context));
|
|
}, () => new OtOpcUaSdkServer(), ct);
|
|
try
|
|
{
|
|
var connections = new FakeConnections(origin);
|
|
var authority = new DataPlaneAuthorityState();
|
|
var coordinator = new LocalCatalogCoordinator(new CatalogActivation(), authority,
|
|
() => new ServingIdentity("node-a", "boot", "Primary", 0, 0, 1));
|
|
var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, origin.Clock), origin.Clock);
|
|
using var resolver = new RemoteNamespaceResolver(new ProjectedCatalogCache(16, 128, origin.Clock, policy),
|
|
new BrowseContinuationRegistry(16, origin.Clock), connections, policy, 16, 2);
|
|
using var placements = new ProjectedMappingDeploymentRuntime(coordinator, resolver);
|
|
var attempt = Prepare(coordinator, restrictToPlant);
|
|
var mapping = Mapping(root);
|
|
if (root.Realm == DataRealm.Uns)
|
|
{
|
|
mapping.Realm = mapping.RemoteRealm = DataRealm.Uns;
|
|
mapping.LocalParentKind = "UnsArea";
|
|
mapping.LocalParentId = "area";
|
|
}
|
|
mapping.AllowedOperations |= DataOperations.Read | DataOperations.Metadata;
|
|
placements.Stage(attempt, [mapping], [Connection()]);
|
|
coordinator.Complete(attempt, true).ShouldBeTrue();
|
|
var manager = started.Server.NodeManager!;
|
|
manager.ProjectedBrowseClock = origin.Clock;
|
|
manager.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw);
|
|
manager.EnsureFolder("Outside", null, "Outside", AddressSpaceRealm.Raw);
|
|
if (root.Realm == DataRealm.Uns)
|
|
manager.EnsureFolder("area", null, "area", AddressSpaceRealm.Uns);
|
|
manager.DataPlaneAuthority = authority;
|
|
manager.Authorizer = new DataPlaneAuthorizer(authority, new TriePermissionEvaluator(authority.Tries, origin.Clock),
|
|
enabled: true, NullLogger.Instance, origin.Clock);
|
|
manager.MappedSubjectResolver = (realm, identifier) =>
|
|
resolver.TryResolveProjected(realm == AddressSpaceRealm.Raw ? DataRealm.Raw : DataRealm.Uns, identifier, out var proof) && proof is not null
|
|
? MappedNodeResolution.Mapped(proof.Metadata.View, proof.Subject, proof.Resolver, proof.Lease)
|
|
: MappedNodeResolution.Deny;
|
|
var sink = new SdkAddressSpaceSink(manager);
|
|
using var applier = new ProjectedNamespaceApplier(resolver, sink, 2);
|
|
using var access = new ProjectedDataAccess(resolver, sink, connections,
|
|
id => placements.TryGetConnectionId(id, out var connection) ? connection : null,
|
|
policy, new DirectPublisher(sink), origin.Clock, new(8, 4, 8_000_000, 2));
|
|
using var browse = new ProjectedBrowseAccess(placements, resolver, applier, sink,
|
|
(uri, id) => manager.TryGetNodeId(uri, id, out var node) ? node : null,
|
|
new DataBudget(TimeSpan.FromSeconds(5), 32, 128_000), 8);
|
|
manager.ProjectedBrowseAccess = browse;
|
|
manager.ProjectedDataAccess = access;
|
|
var identifier = ProjectedDataIds.Identifier("map", root.Address);
|
|
((IProjectedNodeLookup)sink).TryGetNodeId(ProjectedDataIds.NamespaceUri(root.Realm), identifier, out var node).ShouldBeTrue();
|
|
var anchor = node.ShouldNotBeNull();
|
|
using var session = await ConnectComposed(port, pki, ct);
|
|
await exercise(session, sink, resolver, applier, access, placements, anchor);
|
|
}
|
|
finally
|
|
{
|
|
await started.Host.DisposeAsync();
|
|
if (Directory.Exists(pki)) Directory.Delete(pki, recursive: true);
|
|
}
|
|
}
|
|
|
|
private static async Task<List<ReferenceDescription>> BrowseAll(SessionClient client, NodeId node, uint size)
|
|
{
|
|
var ct = TestContext.Current.CancellationToken;
|
|
var response = await client.BrowseAsync(new RequestHeader(), null, size, [new BrowseDescription
|
|
{
|
|
NodeId = node, BrowseDirection = BrowseDirection.Forward, ReferenceTypeId = ReferenceTypeIds.HierarchicalReferences,
|
|
IncludeSubtypes = true, ResultMask = (uint)BrowseResultMask.All,
|
|
}], ct);
|
|
var page = response.Results[0];
|
|
StatusCode.IsGood(page.StatusCode).ShouldBeTrue();
|
|
var references = new List<ReferenceDescription>(page.References.ToArray()!);
|
|
var cursor = page.ContinuationPoint;
|
|
while (!cursor.IsEmpty)
|
|
{
|
|
var next = await client.BrowseNextAsync(new RequestHeader(), false, [cursor], ct);
|
|
page = next.Results[0];
|
|
StatusCode.IsGood(page.StatusCode).ShouldBeTrue();
|
|
references.AddRange(page.References.ToArray()!);
|
|
cursor = page.ContinuationPoint;
|
|
}
|
|
return references;
|
|
}
|
|
|
|
private static async Task<ISession> ConnectComposed(int port, string pki, CancellationToken ct)
|
|
{
|
|
var clientPki = Path.Combine(pki, "client");
|
|
var security = new SecurityConfiguration
|
|
{
|
|
ApplicationCertificate = new CertificateIdentifier { StoreType = CertificateStoreType.Directory, StorePath = Path.Combine(clientPki, "own") },
|
|
TrustedIssuerCertificates = new CertificateTrustList { StoreType = CertificateStoreType.Directory, StorePath = Path.Combine(clientPki, "issuer") },
|
|
TrustedPeerCertificates = new CertificateTrustList { StoreType = CertificateStoreType.Directory, StorePath = Path.Combine(clientPki, "trusted") },
|
|
RejectedCertificateStore = new CertificateTrustList { StoreType = CertificateStoreType.Directory, StorePath = Path.Combine(clientPki, "rejected") },
|
|
AutoAcceptUntrustedCertificates = true,
|
|
};
|
|
var telemetry = DefaultTelemetry.Create(_ => { });
|
|
var config = new ApplicationConfiguration(telemetry)
|
|
{
|
|
ApplicationName = "ComposedClient", ApplicationUri = $"urn:composed-client:{Guid.NewGuid():N}",
|
|
ApplicationType = ApplicationType.Client, SecurityConfiguration = security,
|
|
ClientConfiguration = new ClientConfiguration { DefaultSessionTimeout = 60_000 },
|
|
};
|
|
await config.ValidateAsync(ApplicationType.Client, ct);
|
|
var endpoint = await CoreClientUtils.SelectEndpointAsync(config, $"opc.tcp://127.0.0.1:{port}/OtOpcUa", false, telemetry, ct);
|
|
return await new DefaultSessionFactory(telemetry).CreateAsync(config,
|
|
new ConfiguredEndpoint(null, endpoint!, EndpointConfiguration.Create(config)), false, false, "ComposedClient", 60_000,
|
|
new UserIdentity("apikey", System.Text.Encoding.UTF8.GetBytes("test-secret")), default, ct);
|
|
}
|
|
|
|
private sealed class DirectPublisher(SdkAddressSpaceSink sink) : IProjectedValuePublisher
|
|
{
|
|
public bool TryBind(ProjectedValueRoute route) => true;
|
|
public bool TryPublish(IReadOnlyList<ProjectedValueUpdate> updates) => ((IProjectedValueSink)sink).TryPublish(
|
|
updates.Select(x => new ProjectedValueWrite(x.Route.Realm, x.Route.LocalIdentifier, x.Route.ProjectionGeneration,
|
|
x.Route.Serving, x.Snapshot, x.OriginAgeBounds, x.ReceivedTimestamp, x.SourceProof, x.IsCompleteSnapshot)).ToArray());
|
|
public void Retire(ProjectedValueRoute route) { }
|
|
}
|
|
|
|
private sealed class PeerAuthenticator(DataAuthenticatedContext context) : IOpcUaUserAuthenticator
|
|
{
|
|
public Task<OpcUaUserAuthResult> AuthenticateUserNameAsync(string username, string password, CancellationToken ct) =>
|
|
Task.FromResult(username == "apikey" && password == "test-secret"
|
|
? OpcUaUserAuthResult.AllowKey(context.PrincipalId, [], context.ApiKeyId) with
|
|
{ CredentialVersion = context.CredentialVersion, CredentialExpiresUtc = context.CredentialExpiresUtc }
|
|
: OpcUaUserAuthResult.Deny("Invalid key"));
|
|
}
|
|
}
|