using System.Security.Cryptography; using System.Text; using System.Threading.Channels; using Microsoft.Extensions.Logging.Abstractions; using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; 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; using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; using ZB.MOM.WW.OtOpcUa.Runtime.Drivers; using DataBrowseRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.BrowseRequest; using DataReadRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadRequest; using DataReadResult = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadResult; namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; [Trait("Category", "Integration"), Trait("Feature", "GrpcData"), Trait("Phase", "P08Wire")] public sealed partial class GrpcDataConfiguredDiscoveryWireTests { [Fact(Timeout = 15000)] public void Mint_reuses_one_mapping_capability_until_the_published_attempt_changes() { using var origin = new LocalDataFixture(servingGeneration: 1); 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), new FakeConnections(origin), policy, 16, 2); using var placements = new ProjectedMappingDeploymentRuntime(coordinator, resolver); var attempt = Prepare(coordinator); var mapping = Mapping(origin.Root); placements.Stage(attempt, [mapping], [Connection()]); coordinator.Complete(attempt, true).ShouldBeTrue(); placements.TryAcquireConfiguredCapability("map", DataRealm.Raw, out var first, out var firstPlacement).ShouldBeTrue(); placements.TryAcquireConfiguredCapability("map", DataRealm.Raw, out var second, out var secondPlacement).ShouldBeTrue(); first.ShouldNotBeNull(); firstPlacement.ShouldNotBeNull(); secondPlacement.ShouldNotBeNull(); second.ShouldBeSameAs(first); firstPlacement!.Mapping.Revision++; secondPlacement!.Mapping.Revision.ShouldBe(1); var replacement = Prepare(coordinator); placements.Stage(replacement, [mapping], [Connection()]); coordinator.Complete(replacement, true).ShouldBeTrue(); placements.TryAcquireConfiguredCapability("map", DataRealm.Raw, out var fresh, out var freshPlacement).ShouldBeTrue(); fresh.ShouldNotBeNull().ShouldNotBeSameAs(first); first!.Matches("map", freshPlacement!.Anchor, freshPlacement!.Authority).ShouldBeFalse(); } [Fact(Timeout = 90000)] public async Task Configured_interest_browses_and_subscribes_without_an_sdk_caller_and_retires_on_removal_and_deployment() { var pki = Path.Combine(Path.GetTempPath(), $"configured-projection-{Guid.NewGuid():N}"); var started = await OpcUaHostStart.StartAsync(port => new OpcUaApplicationHost(new OpcUaApplicationHostOptions { ApplicationName = "ConfiguredProjection", ApplicationUri = $"urn:configured:{Guid.NewGuid():N}", OpcUaPort = port, PublicHostname = "localhost", PkiStoreRoot = pki, }, NullLogger.Instance), () => new OtOpcUaSdkServer(), TestContext.Current.CancellationToken); try { LocalDataFixture? peer = null; var subscriptions = new FakeSubscriptions(() => peer!.Serving); using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions); peer = origin; 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); var mapping = Mapping(origin.Root); placements.Stage(attempt, [mapping], [Connection()]); coordinator.Complete(attempt, true).ShouldBeTrue(); var placement = placements.Active.ShouldHaveSingleItem(); var manager = started.Server.NodeManager!; manager.ShouldNotBeNull(); manager.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw); manager.TryGetNodeId(V3NodeIds.RawNamespaceUri, "Plant", out var parentId).ShouldBeTrue(); var parent = parentId.ShouldNotBeNull(); var sink = new SdkAddressSpaceSink(manager); var anchorId = ProjectedDataIds.Identifier("map", placement.Anchor.Address); var anchor = new ProjectedAnchorDefinition(DataRealm.Raw, anchorId, parent, "Remote", "Plant/Remote", "map", 1, () => placement.Authority.IsActive); ((IProjectedAnchorSink)sink).TryEnsureProjectedAnchor(anchor, out _).ShouldBeTrue(); 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 Publisher(), origin.Clock, new(8, 4, 2_000_000, 2)); 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); var identifier = ProjectedDataIds.Identifier("map", origin.Raw.Address); await using (var owner = new ConfiguredProjectedInterestOwner(discovery, 8)) { owner.SetInterest(reference, true); await subscriptions.Opened.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask().WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken); connections.BrowseCalls.ShouldBeGreaterThan(0); ((IProjectedNodeLookup)sink).TryGetNodeId(ProjectedDataIds.RawNamespaceUri, identifier, out var node).ShouldBeTrue(); node.ShouldNotBeNull(); ((IProjectedNodeLookup)sink).TryResolve(node!.Value, out var materialized).ShouldBeTrue(); materialized.ShouldNotBeNull(); access.HasLiveDemand(DataRealm.Raw, identifier).ShouldBeTrue(); var wrongMap = Reference("unconfigured", DataRealm.Raw, origin.Raw.Address); var wrongRealm = Reference("map", DataRealm.Uns, origin.Raw.Address); (await discovery.ResolveAsync(wrongMap, TestContext.Current.CancellationToken)).ShouldBeNull(); (await discovery.ResolveAsync(wrongRealm, TestContext.Current.CancellationToken)).ShouldBeNull(); var forged = origin.Raw.Address with { Identifier = "outside-the-exported-page" }; (await discovery.ResolveAsync(Reference("map", DataRealm.Raw, forged), TestContext.Current.CancellationToken)).ShouldBeNull(); subscriptions.Opens.ShouldBe(1, "decoded addresses must not create a subscription without a verified page"); var browsesBeforeExpiry = connections.BrowseCalls; origin.Clock.Advance(TimeSpan.FromSeconds(16)); await subscriptions.Closed.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask().WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken); await subscriptions.Opened.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask().WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken); connections.BrowseCalls.ShouldBeGreaterThan(browsesBeforeExpiry, "expired metadata must be renewed from the peer"); access.HasLiveDemand(DataRealm.Raw, identifier).ShouldBeTrue(); owner.SetInterest(reference, false); await subscriptions.Closed.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask().WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken); } await using (var owner = new ConfiguredProjectedInterestOwner(discovery, 8)) { owner.SetInterest(reference, true); await subscriptions.Opened.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask().WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken); var replacement = Prepare(coordinator); await subscriptions.Closed.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask().WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken); mapping.Enabled = false; placements.Stage(replacement, [mapping], [Connection()]); coordinator.Complete(replacement, true).ShouldBeTrue(); (await discovery.ResolveAsync(reference, TestContext.Current.CancellationToken)).ShouldBeNull(); } } finally { await started.Host.DisposeAsync(); if (Directory.Exists(pki)) Directory.Delete(pki, recursive: true); } } private static string Reference(string mapping, DataRealm realm, DataAddress address) => ProjectedDataIds.DependencyReference(realm, ProjectedDataIds.Identifier(mapping, address)); private static RemoteNamespaceMapping Mapping(DataView root) => new() { RemoteNamespaceMappingId = "map", ClusterId = "cluster", DataConnectionId = "link", Revision = 1, Enabled = true, Realm = DataRealm.Raw, RemoteRealm = DataRealm.Raw, LocalParentKind = "RawFolder", LocalParentId = "folder", BranchName = "Remote", RemoteRootEntityId = root.Subject, RemoteNamespaceUri = root.Address.NamespaceUri, RemoteIdentifierKind = root.Address.IdentifierKind, RemoteIdentifier = root.Address.Identifier, AllowedOperations = DataOperations.Browse | DataOperations.Subscribe, MetadataLeaseMilliseconds = 15000, StaleTimeoutMilliseconds = 30000, }; private static DataConnection Connection() => new() { DataConnectionId = "link", ClusterId = "cluster", Enabled = true, ExpectedClusterId = "cluster" }; private static CatalogAttempt Prepare(LocalCatalogCoordinator coordinator, bool restrictToPlant = false, bool allowWrite = false, int? localPermissions = null) { var bytes = Encoding.UTF8.GetBytes(""" {"Clusters":[{"ClusterId":"cluster","Name":"Cluster","Enterprise":"ent","Site":"site","CreatedBy":"test","RedundancyMode":0,"Enabled":true}], "Nodes":[{"NodeId":"node-a","ClusterId":"cluster","Host":"node-a","ApplicationUri":"urn:node-a","CreatedBy":"test","Enabled":true,"MaintenanceMode":false}], "ApiKeys":[{"ApiKeyId":"peer-key","Name":"peer-key","SecretHash":"hash","Principal":"peer","Enabled":true}], "NodeAcls":[{"NodeAclId":"acl","ClusterId":"cluster","Principal":"peer","ScopeKind":0,"PermissionFlags":7}], "RawFolders":[{"RawFolderId":"folder","ClusterId":"cluster","Name":"Plant"}], "DriverInstances":[],"Devices":[],"TagGroups":[],"Tags":[],"UnsAreas":[{"UnsAreaId":"area","ClusterId":"cluster","Name":"area"}],"UnsLines":[],"Equipment":[],"UnsTagReferences":[],"VirtualTags":[], "DataConnections":[],"RemoteNamespaceMappings":[], "DataExports":[{"DataExportId":"raw","ClusterId":"cluster","Enabled":true,"Realm":1,"RootKind":"Cluster","RootEntityId":"cluster","PrincipalId":"peer","AllowedOperations":7}]} """); if (restrictToPlant) bytes = Encoding.UTF8.GetBytes(Encoding.UTF8.GetString(bytes).Replace( "\"ScopeKind\":0,\"PermissionFlags\":7", "\"ScopeKind\":7,\"ScopeId\":\"folder\",\"PermissionFlags\":7", StringComparison.Ordinal)); if (allowWrite) bytes = Encoding.UTF8.GetBytes(Encoding.UTF8.GetString(bytes).Replace("\"PermissionFlags\":7", "\"PermissionFlags\":23", StringComparison.Ordinal)); if (localPermissions is { } permissions) bytes = Encoding.UTF8.GetBytes(Encoding.UTF8.GetString(bytes).Replace( allowWrite ? "\"PermissionFlags\":23" : "\"PermissionFlags\":7", $"\"PermissionFlags\":{permissions}", StringComparison.Ordinal)); var attempt = coordinator.BeginAttempt(Convert.ToHexStringLower(SHA256.HashData(bytes))); coordinator.InstallAuthority(attempt, DeploymentArtifact.ParseDataPlaneAuthority(bytes, "node-a")).ShouldBeTrue(); using var parsed = DeploymentArtifact.Open(bytes); coordinator.Stage(attempt, parsed.ParseLocalCatalogSnapshot("node-a")!).ShouldBeTrue(); return attempt; } private sealed class Publisher : IProjectedValuePublisher { public bool TryBind(ProjectedValueRoute route) => true; public bool TryPublish(IReadOnlyList updates) => true; public void Retire(ProjectedValueRoute route) { } } private sealed class FakeConnections(LocalDataFixture peer) : IGrpcDataAdapterConnectionSource { private int _browseCalls; public int BrowseCalls => Volatile.Read(ref _browseCalls); public ValueTask AcquireAsync(string connectionId, CancellationToken cancellationToken) => ValueTask.FromResult(connectionId == "link" ? new Lease(new Connection(peer.Connection(), this)) : null); private sealed class Lease(IDataConnection connection) : IGrpcDataAdapterConnectionLease { public IDataConnection Connection => connection; public CancellationToken CancellationToken => CancellationToken.None; public ValueTask DisposeAsync() => connection.DisposeAsync(); } private sealed class Connection(IDataConnection inner, FakeConnections owner) : IDataConnection { public DataTarget Target => inner.Target; public TimeProvider Clock => inner.Clock; public Task GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => inner.GetCapabilitiesAsync(budget, cancellationToken); public Task BrowseAsync(DataBrowseRequest request, CancellationToken cancellationToken) { Interlocked.Increment(ref owner._browseCalls); return inner.BrowseAsync(request, cancellationToken); } public Task>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) => inner.GetMetadataAsync(request, cancellationToken); public Task> ReadAsync(DataReadRequest request, CancellationToken cancellationToken) => inner.ReadAsync(request, cancellationToken); public Task> WriteAsync(WriteBatch request, CancellationToken cancellationToken) => inner.WriteAsync(request, cancellationToken); public Task SubscribeAsync(CancellationToken cancellationToken) => inner.SubscribeAsync(cancellationToken); public ValueTask DisposeAsync() => inner.DisposeAsync(); } } private sealed class FakeSubscriptions(Func serving) : IDataSubscriptionService { public readonly Channel Opened = Channel.CreateUnbounded(); public readonly Channel Closed = Channel.CreateUnbounded(); // Opt-in controlled origin frames; the existing discovery cases keep their empty snapshots. public TimeProvider? SampleClock; public int SnapshotValue = 7; public long SnapshotVersion = 1; public bool HoldNextSnapshotEnd; public readonly Channel ItemsAdded = Channel.CreateUnbounded(); public readonly Channel SnapshotEndHeld = Channel.CreateUnbounded(); private int _opens; public int Opens => Volatile.Read(ref _opens); public Task SubscribeAsync(CancellationToken cancellationToken) { var number = Interlocked.Increment(ref _opens); return Task.FromResult(new Stream(this, serving(), number)); } public sealed class Stream(FakeSubscriptions owner, ServingIdentity serving, int number) : IDataSubscription, IDataSubscriptionProvenance { private readonly Channel _frames = Channel.CreateUnbounded(); private readonly Dictionary _ids = new(); private readonly object _gate = new(); private string? _subscriptionId; private long _epoch; private DataItemHandle? _currentHandle; private bool _snapshotEndHeld; public TimeSpan Interval { get; private set; } private int _removeCommands, _addCommands; public int RemoveCommands => Volatile.Read(ref _removeCommands); public int AddCommands => Volatile.Read(ref _addCommands); private long _sequence; private ulong _handle; public ServingIdentity Serving => serving; public Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken) { lock (_gate) { _subscriptionId = command.SubscriptionId; _epoch = command.StreamEpoch; if (command is RemoveSubscriptionItems) Interlocked.Increment(ref _removeCommands); if (command is AddSubscriptionItems) Interlocked.Increment(ref _addCommands); IReadOnlyList items = command switch { OpenSubscription open => open.Items, AddSubscriptionItems add => add.Items, _ => [] }; var acks = items.Select(item => new DataSubscriptionItemAck(item.ClientItemId, DataItemStatus.Good, new DataItemHandle(command.SubscriptionId, command.StreamEpoch, ++_handle, 1), item.Settings, null)).ToArray(); foreach (var ack in acks) if (ack.Handle is not null) _ids[ack.Handle] = ack.ClientItemId; if (command is RemoveSubscriptionItems remove) acks = remove.Items.Select(handle => new DataSubscriptionItemAck(_ids[handle], DataItemStatus.Good, handle, null, null)).ToArray(); _frames.Writer.TryWrite(new DataSubscriptionAck(command.SubscriptionId, command.StreamEpoch, ++_sequence, command.CommandId, acks)); if (items.Count > 0) { owner.Opened.Writer.TryWrite(number); Interval = items[0].Settings.PublishingInterval; _currentHandle = acks[0].Handle; _frames.Writer.TryWrite(new DataSubscriptionControl(command.SubscriptionId, command.StreamEpoch, ++_sequence, DataStreamControlKind.SnapshotBegin, [], serving.CatalogEpoch, serving.AuthorityEpoch, null)); if (owner.SampleClock is { } clock) EmitValueCore(owner.SnapshotVersion, owner.SnapshotValue, clock.GetUtcNow(), TimeSpan.Zero, snapshot: true); if (owner.HoldNextSnapshotEnd) { owner.HoldNextSnapshotEnd = false; _snapshotEndHeld = true; owner.SnapshotEndHeld.Writer.TryWrite(this); } else EndSnapshot(); owner.ItemsAdded.Writer.TryWrite(this); } return Task.CompletedTask; } } public void EmitValue(long version, int value, DateTimeOffset sourceTimestamp, TimeSpan age) { lock (_gate) EmitValueCore(version, value, sourceTimestamp, age, snapshot: false); } public void EmitValueWithoutSourceTimestamp(long version, int value, TimeSpan age) { lock (_gate) EmitValueCore(version, value, null, age, snapshot: false); } private void EmitValueCore(long version, int value, DateTimeOffset? sourceTimestamp, TimeSpan age, bool snapshot) { var sample = new DataSample( ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue.FromScalar(DataValueKind.Int32, value), 0, sourceTimestamp, sourceTimestamp, serving, version); _frames.Writer.TryWrite(new DataSubscriptionValues(_subscriptionId!, _epoch, ++_sequence, snapshot, [new DataSubscriptionValue(_currentHandle!, sample, new(age, age), DataReadiness.Ready)])); } private void EndSnapshot() => _frames.Writer.TryWrite(new DataSubscriptionControl(_subscriptionId!, _epoch, ++_sequence, DataStreamControlKind.SnapshotEnd, [], serving.CatalogEpoch, serving.AuthorityEpoch, null)); public void ReleaseSnapshotEnd() { lock (_gate) { if (!_snapshotEndHeld) throw new InvalidOperationException("No origin snapshot is held."); _snapshotEndHeld = false; EndSnapshot(); } } public IAsyncEnumerable ReadAllAsync(CancellationToken cancellationToken) => _frames.Reader.ReadAllAsync(cancellationToken); public ValueTask DisposeAsync() { _frames.Writer.TryComplete(); owner.Closed.Writer.TryWrite(number); return ValueTask.CompletedTask; } } } }