using System.Threading.Channels; 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(); }); } [Fact(Timeout = 90000), Trait("Phase", "P10Wire")] public async Task Cold_sdk_read_publishes_with_default_one_mib_transport_budget() { var ct = TestContext.Current.CancellationToken; LocalDataFixture? peer = null; var subscriptions = new FakeSubscriptions(() => peer!.Serving); using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions); peer = origin; origin.Publish(42); var published = Channel.CreateUnbounded(); 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); await using var lease = await discovery.ResolveAsync(Reference("map", DataRealm.Raw, origin.Raw.Address), ct); lease.ShouldNotBeNull(); await subscriptions.Opened.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); var client = (SessionClient)session; var first = await client.ReadAsync(new RequestHeader(), 5000, TimestampsToReturn.Both, [new ReadValueId { NodeId = anchor, AttributeId = Attributes.Value }], ct); first.Results[0].StatusCode.ShouldBe(StatusCodes.BadWaitingForInitialData); var update = await published.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); update.Snapshot.Value.ShouldBe(42); var result = await client.ReadAsync(new RequestHeader(), 5000, TimestampsToReturn.Both, [new ReadValueId { NodeId = anchor, AttributeId = Attributes.Value }], ct); StatusCode.IsGood(result.Results[0].StatusCode).ShouldBeTrue(); result.Results[0].WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(42); }, onPublished: update => published.Writer.TryWrite(update), maxUnaryBytes: 1024 * 1024); } [Theory(Timeout = 90000), Trait("Phase", "P10Wire")] [InlineData(DataWriteState.DriverConfirmedSuccess)] [InlineData(DataWriteState.OutcomeUnknown)] public async Task Sdk_mapped_write_uses_default_one_mib_budget_and_is_dispatched_once(DataWriteState outcome) { var ct = TestContext.Current.CancellationToken; LocalDataFixture? peer = null; var subscriptions = new FakeSubscriptions(() => peer!.Serving); var writes = new RecordingOriginWrites(outcome); using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions, writes: _ => writes); peer = origin; 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); await using var lease = await discovery.ResolveAsync(Reference("map", DataRealm.Raw, origin.Raw.Address), ct); lease.ShouldNotBeNull(); await subscriptions.Opened.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); var response = await ((SessionClient)session).WriteAsync(new RequestHeader(), [new WriteValue { NodeId = anchor, AttributeId = Attributes.Value, Value = new Opc.Ua.DataValue(new Variant(77), StatusCodes.Good) }], ct); response.Results.ToArray()!.ShouldHaveSingleItem().ShouldBe(outcome == DataWriteState.DriverConfirmedSuccess ? StatusCodes.Good : StatusCodes.UncertainLastUsableValue); writes.Calls.ShouldBe(1, "neither a success nor an ambiguous outcome may be replayed"); writes.Value.ShouldBe(77); writes.Budget.ShouldNotBeNull().MaxBytes.ShouldBe(1024 * 1024); }, maxUnaryBytes: 1024 * 1024, allowWrite: true); } private sealed class RecordingOriginWrites(DataWriteState outcome) : IDataWriteService { private int _calls; internal int Calls => Volatile.Read(ref _calls); internal object? Value; internal DataBudget? Budget; public Task> WriteAsync(WriteBatch request, CancellationToken cancellationToken) { Interlocked.Increment(ref _calls); Budget = request.Budget; Value = request.Items.Single().Value.GetScalar(); var status = outcome == DataWriteState.DriverConfirmedSuccess ? StatusCodes.Good.Code : StatusCodes.BadTimeout.Code; return Task.FromResult>([new(request.Items[0].CorrelationId, new(outcome, status, null))]); } } [Theory(Timeout = 90000), Trait("Phase", "P11Wire")] [InlineData(false)] [InlineData(true)] public async Task Actual_sdk_monitored_item_recovers_from_an_older_snapshot_using_the_quiet_current_cadence(bool holdHealthyNotification) { var ct = TestContext.Current.CancellationToken; LocalDataFixture? peer = null; var subscriptions = new FakeSubscriptions(() => peer!.Serving); using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions); peer = origin; subscriptions.SampleClock = origin.Clock; var published = Channel.CreateUnbounded(); await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, access, _, anchor) => { var client = (SessionClient)session; // Browsing materializes the value root through the real registry without adding a headless demand. await BrowseAll(client, anchor, 1); ((IProjectedNodeLookup)sink).TryResolve(anchor, out var definition).ShouldBeTrue(); definition.ShouldNotBeNull().Metadata.ValueKind.ShouldBe(DataValueKind.Int32); var slow = (await client.CreateSubscriptionAsync(new RequestHeader(), 200, 300, 1, 0, true, 0, ct)).SubscriptionId; await AddComposedItem(client, slow, anchor, 1, 200, ct); var slowStream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 7), ct); (await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good); await client.SetPublishingModeAsync(new RequestHeader(), false, [slow], ct); var fast = (await client.CreateSubscriptionAsync(new RequestHeader(), 50, 300, 1, 0, true, 0, ct)).SubscriptionId; await AddComposedItem(client, fast, anchor, 2, 50, ct); var fastStream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); fastStream.Interval.ShouldNotBe(slowStream.Interval); (await PublishComposedValue(client, 2, ct)).StatusCode.ShouldBe(StatusCodes.Good); access.HasLiveDemand(DataRealm.Raw, definition!.LocalIdentifier).ShouldBeTrue(); // A queue of one overwrites repeated values with the same timestamp. The slow item's // retained evidence is genuinely ambiguous; the fast item consumes each sample. var timestamp = origin.Clock.GetUtcNow().AddMinutes(-1); fastStream.EmitValue(2, 42, timestamp, TimeSpan.Zero); (await PublishComposedValue(client, 2, ct)).WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(42); fastStream.EmitValue(3, 44, timestamp, TimeSpan.Zero); (await PublishComposedValue(client, 2, ct)).StatusCode.ShouldBe(StatusCodes.Good); fastStream.EmitValue(4, 42, timestamp, TimeSpan.Zero); (await PublishComposedValue(client, 2, ct)).StatusCode.ShouldBe(StatusCodes.Good); subscriptions.SnapshotVersion = 4; subscriptions.SnapshotValue = 42; subscriptions.HoldNextSnapshotEnd = true; await client.SetPublishingModeAsync(new RequestHeader(), false, [fast], ct); await client.SetPublishingModeAsync(new RequestHeader(), true, [slow], ct); var rejected = await PublishComposedValue(client, 1, ct); StatusCode.IsGood(rejected.StatusCode).ShouldBeFalse("ambiguous retained evidence must fail closed and request a baseline"); var held = await subscriptions.SnapshotEndHeld.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); held.ShouldBeSameAs(slowStream); subscriptions.Opens.ShouldBe(2, "refreshing the slow item must retain both existing upstream streams"); await client.SetPublishingModeAsync(new RequestHeader(), false, [slow], ct); if (!holdHealthyNotification) await client.SetPublishingModeAsync(new RequestHeader(), true, [fast], ct); var currentTimestamp = timestamp.AddSeconds(1); fastStream.EmitValue(5, 43, currentTimestamp, TimeSpan.FromSeconds(28)); if (!holdHealthyNotification) { var healthy = await PublishComposedValue(client, 2, ct); healthy.StatusCode.ShouldBe(StatusCodes.Good); healthy.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(43, "ordinary deltas must continue while the other cadence's snapshot is held"); } var current = await NextPublished(published.Reader, x => Equals(x.Snapshot.Value, 43) && !x.IsCompleteSnapshot, ct); current.SourceProof.IsValid.ShouldBeTrue(); origin.Clock.Advance(TimeSpan.FromSeconds(1)); held.ReleaseSnapshotEnd(); // No further source frame is sent. The old N barrier must complete recovery using already admitted N+1. var recovered = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 43), ct); recovered.SourceProof.ShouldBeSameAs(current.SourceProof); recovered.ReceivedTimestamp.ShouldBe(current.ReceivedTimestamp); recovered.OriginAgeBounds.ShouldBe(current.OriginAgeBounds); recovered.Snapshot.SourceTimestampUtc.ShouldBe(currentTimestamp.UtcDateTime); slowStream.RemoveCommands.ShouldBe(1); slowStream.AddCommands.ShouldBe(1); fastStream.RemoveCommands.ShouldBe(0); fastStream.AddCommands.ShouldBe(0); if (holdHealthyNotification) { // The fast item still holds the original 43. Replaying that exact cached evidence for // another item's recovery must not manufacture a second, ambiguous healthy candidate. await client.SetPublishingModeAsync(new RequestHeader(), true, [fast], ct); var healthy = await PublishComposedValue(client, 2, ct); healthy.StatusCode.ShouldBe(StatusCodes.Good, "another cadence's complete replay must preserve the healthy item's queued evidence"); healthy.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(43); healthy.SourceTimestamp.ShouldBe((DateTimeUtc)currentTimestamp.UtcDateTime); fastStream.RemoveCommands.ShouldBe(0, "a healthy item must not request a replacement registration"); fastStream.AddCommands.ShouldBe(0, "a healthy item must retain its existing registration"); } await client.SetPublishingModeAsync(new RequestHeader(), false, [fast], ct); await client.SetPublishingModeAsync(new RequestHeader(), true, [slow], ct); var notification = await PublishComposedNotification(client, 1, ct); var delivered = notification.Value; delivered.StatusCode.ShouldBe(StatusCodes.Good); delivered.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(43); delivered.SourceTimestamp.ShouldBe((DateTimeUtc)currentTimestamp.UtcDateTime); subscriptions.Opens.ShouldBe(2); origin.Clock.Advance(TimeSpan.FromSeconds(2)); var replay = await client.RepublishAsync(new RequestHeader(), slow, notification.Sequence, ct); var expired = ComposedChanges(replay.NotificationMessage).Single(x => x.ClientHandle == 1).Value; StatusCode.IsGood(expired.StatusCode).ShouldBeFalse( "recovery must retain the original ingress age: 28 seconds plus three elapsed seconds exceeds the 30 second limit"); }, onPublished: update => published.Writer.TryWrite(update)); } private static async Task AddComposedItem(SessionClient client, uint subscription, NodeId node, uint handle, double interval, CancellationToken ct) { var response = await client.CreateMonitoredItemsAsync(new RequestHeader(), subscription, TimestampsToReturn.Both, [new MonitoredItemCreateRequest { ItemToMonitor = new ReadValueId { NodeId = node, AttributeId = Attributes.Value }, MonitoringMode = MonitoringMode.Reporting, RequestedParameters = new MonitoringParameters { ClientHandle = handle, SamplingInterval = interval, QueueSize = 1, DiscardOldest = true, Filter = new ExtensionObject(new DataChangeFilter { Trigger = Opc.Ua.DataChangeTrigger.StatusValueTimestamp }) } }], ct); response.Results[0].StatusCode.ShouldBe(StatusCodes.Good); } private static async Task PublishComposedValue(SessionClient client, uint handle, CancellationToken ct) => (await PublishComposedNotification(client, handle, ct)).Value; private static IEnumerable ComposedChanges(NotificationMessage message) { foreach (var payload in message.NotificationData.ToArray()!) if (payload.TryGetValue(out var changes)) foreach (var change in changes.MonitoredItems.ToArray()!) yield return change; } private static async Task<(Opc.Ua.DataValue Value, uint Sequence)> PublishComposedNotification( SessionClient client, uint handle, CancellationToken ct) { using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); timeout.CancelAfter(TimeSpan.FromSeconds(10)); while (true) { var response = await client.PublishAsync(new RequestHeader(), default, timeout.Token); foreach (var change in ComposedChanges(response.NotificationMessage)) if (change.ClientHandle == handle) return (change.Value, response.NotificationMessage.SequenceNumber); } } private static async Task NextPublished(ChannelReader reader, Func predicate, CancellationToken ct) { using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); timeout.CancelAfter(TimeSpan.FromSeconds(10)); while (true) { var update = await reader.ReadAsync(timeout.Token); if (predicate(update)) return update; } } private async Task WithComposedServer(LocalDataFixture origin, DataView root, Func exercise, bool restrictToPlant = false, Action? onPublished = null, bool mountAtRealmRoot = false, long maxUnaryBytes = 8_000_000, bool allowWrite = false, IGrpcDataAdapterConnectionSource? connectionSource = null, int? staleTimeoutMilliseconds = null, Func? renewalSinkFactory = null, Action? onCoordinator = null, int? localPermissions = null, bool allowHistory = false, Action? onHistory = null, Action? configureMapping = null) { 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.Instance, new PeerAuthenticator(origin.Context)); }, () => new OtOpcUaSdkServer(), ct); try { var connections = connectionSource ?? new FakeConnections(origin); var authority = new DataPlaneAuthorityState(); var coordinator = new LocalCatalogCoordinator(new CatalogActivation(), authority, () => new ServingIdentity("node-a", "boot", "Primary", 0, 0, 1)); onCoordinator?.Invoke(coordinator); 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, allowWrite, localPermissions); var mapping = Mapping(root); if (staleTimeoutMilliseconds is { } stale) mapping.StaleTimeoutMilliseconds = stale; if (root.Realm == DataRealm.Uns) { mapping.Realm = mapping.RemoteRealm = DataRealm.Uns; mapping.LocalParentKind = "UnsArea"; mapping.LocalParentId = "area"; } if (mountAtRealmRoot) { mapping.LocalParentKind = "Cluster"; mapping.LocalParentId = "cluster"; } mapping.AllowedOperations |= DataOperations.Read | DataOperations.Metadata; if (allowWrite) { mapping.AllowedOperations |= DataOperations.Write; mapping.WriteThrough = true; } if (allowHistory) mapping.AllowedOperations |= DataOperations.HistoryRead; configureMapping?.Invoke(mapping); 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); await using var publisher = new QueuedComposedPublisher(sink, onPublished); using var access = new ProjectedDataAccess(resolver, sink, connections, id => placements.TryGetConnectionId(id, out var connection) ? connection : null, policy, publisher, origin.Clock, new(8, 4, maxUnaryBytes, 2), renewalSink: renewalSinkFactory?.Invoke(sink) ?? sink); 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; // H3: projected HistoryRead through the same deployed connections. using var history = new ProjectedHistoryAccess(access, connections, id => placements.TryGetHistoryAssemblyBudget(id, out var bytes) ? bytes : null, origin.Clock) { ReleaseCoalesce = TimeSpan.Zero }; // the flush delay runs on the (manual) fixture clock manager.ProjectedHistoryAccess = history; onHistory?.Invoke(history, manager); 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> 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(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 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); } // The real publication port accepts owned work before the SDK worker takes the node-manager lock. // Keep that ordering here too: Runtime must never enter the SDK while holding a source gate. private sealed class QueuedComposedPublisher : IProjectedValuePublisher, IAsyncDisposable { private sealed record Batch(ProjectedValueUpdate[] Updates, long Bytes); private readonly Channel _pending = Channel.CreateBounded(new BoundedChannelOptions(16) { SingleReader = true, FullMode = BoundedChannelFullMode.Wait, AllowSynchronousContinuations = false }); private readonly object _gate = new(); private readonly SdkAddressSpaceSink _sink; private readonly Action? _onPublished; private readonly Task _worker; private int _count; private long _bytes; private bool _disposed; public QueuedComposedPublisher(SdkAddressSpaceSink sink, Action? onPublished) { _sink = sink; _onPublished = onPublished; _worker = Task.Run(ApplyAsync); } public bool TryBind(ProjectedValueRoute route) => true; public bool TryPublish(IReadOnlyList updates) { long bytes; try { bytes = checked(256 + updates.Sum(x => checked(512 + OwnedDataSample.Estimate(x.Snapshot.Value)))); } catch (Exception error) when (error is ArgumentException or OverflowException) { return false; } lock (_gate) { if (_disposed || _count >= 16 || bytes > 8_000_000 - _bytes) return false; _count++; _bytes += bytes; } try { var owned = updates.Select(x => x with { Snapshot = x.Snapshot with { Value = OwnedDataSample.CopyLegacy(x.Snapshot.Value) } }).ToArray(); if (_pending.Writer.TryWrite(new(owned, bytes))) return true; } catch { Release(bytes); throw; } Release(bytes); return false; } private void Release(long bytes) { lock (_gate) { _count--; _bytes -= bytes; } } private async Task ApplyAsync() { await foreach (var batch in _pending.Reader.ReadAllAsync()) { try { if (batch.Updates.Any(x => !x.SourceProof.IsValid || (x.MaximumSampleAge is { } maximum && !x.OriginAgeBounds.Advance( x.SourceProof.Clock.GetElapsedTime(x.ReceivedTimestamp)).IsFresh(maximum)))) continue; var accepted = ((IProjectedValueSink)_sink).TryPublish(batch.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, x.SourceVersion)).ToArray()); if (accepted) foreach (var update in batch.Updates) _onPublished?.Invoke(update); } finally { Release(batch.Bytes); } } } public void Retire(ProjectedValueRoute route) { } public async ValueTask DisposeAsync() { lock (_gate) { _disposed = true; _pending.Writer.TryComplete(); } await _worker; } } private sealed class PeerAuthenticator(DataAuthenticatedContext context) : IOpcUaUserAuthenticator { public Task 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")); } }