using ZB.MOM.WW.OtOpcUa.Configuration.Entities; using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; using ZB.MOM.WW.OtOpcUa.Core.Authorization; using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness; namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; [Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P08")] public sealed class GrpcDataFederatedBrowseTests { [Fact, Trait("Phase", "P11")] public void Exact_renewal_allows_one_pinned_predecessor_for_a_one_node_mapping() { using var fixture = new LocalDataFixture(); var policy = new DataOperationPolicy(fixture.Authority, new TriePermissionEvaluator(fixture.Authority.Tries, fixture.Clock), fixture.Clock); var cache = new ProjectedCatalogCache(2, 3, fixture.Clock, policy); var caller = new DataCallerIdentity(fixture.Context.PrincipalId, fixture.Context.ApiKeyId, fixture.Context.CredentialVersion, fixture.Context.CredentialExpiresUtc); var request = Request(fixture.Clock) with { Caller = caller }; cache.CaptureGeneration("mapping"); var local = fixture.Activation.CaptureAuthority(); MetadataAuthorityLease Lease() => new(fixture.Serving with { ServingGeneration = 1 }, new MetadataLease(1, 1, TimeSpan.FromSeconds(1)), fixture.Clock.GetTimestamp(), TimeSpan.FromSeconds(1), TimeSpan.Zero, fixture.Clock); var initialLease = Lease(); var original = ParentProof(fixture, request, initialLease, local); cache.TryPublish(request, new(ProjectionPageStatus.Ready, [original], true, null, 1, initialLease, local, original)).ShouldBeTrue(); cache.TryResolveProjected(DataRealm.Raw, original.LocalIdentifier, out var installed).ShouldBeTrue(); cache.TryPinProjected(DataRealm.Raw, original.LocalIdentifier, out var oldPin).ShouldBeTrue(); try { fixture.Clock.Advance(TimeSpan.FromSeconds(2)); var freshLease = Lease(); var fresh = ParentProof(fixture, request, freshLease, local); cache.TryRenewExact(installed!, fresh, maximumMappingNodes: 1, out var renewed).ShouldBeTrue(); renewed.ShouldNotBeNull(); cache.TryPinProjected(DataRealm.Raw, original.LocalIdentifier, out var currentPin).ShouldBeTrue(); try { fixture.Clock.Advance(TimeSpan.FromSeconds(2)); var laterLease = Lease(); var later = ParentProof(fixture, request, laterLease, local); cache.TryRenewExact(installed!, later, maximumMappingNodes: 1, out _).ShouldBeFalse( "a node cannot accumulate an unbounded chain of pinned historical proofs"); } finally { currentPin!.Dispose(); } } finally { oldPin!.Dispose(); } } [Fact] public void Missing_or_unavailable_parent_is_not_reported_as_a_successful_empty_branch() { var clock = new ManualTimeProvider(); var cache = new ProjectedCatalogCache(4, 8, clock); var request = Request(clock); var pending = cache.TryGetParent(request); pending.Status.ShouldBe(ProjectionPageStatus.Pending); pending.Complete.ShouldBeFalse(); cache.MarkUnavailable(request.MappingId, request.Parent); var unavailable = cache.TryGetParent(request); unavailable.Status.ShouldBe(ProjectionPageStatus.Unavailable); unavailable.Complete.ShouldBeFalse(); } [Fact] public void Unknown_projected_identity_fails_closed_instead_of_becoming_local() { var clock = new ManualTimeProvider(); var cache = new ProjectedCatalogCache(4, 8, clock); cache.TryResolveProjected(DataRealm.Raw, "unknown", out var proof).ShouldBeFalse(); proof.ShouldBeNull(); } [Fact] public void Empty_complete_page_expires_with_its_authority_lease() { using var fixture = new LocalDataFixture(); var policy = new DataOperationPolicy(fixture.Authority, new TriePermissionEvaluator(fixture.Authority.Tries, fixture.Clock), fixture.Clock); var cache = new ProjectedCatalogCache(4, 8, fixture.Clock, policy); var caller = new DataCallerIdentity(fixture.Context.PrincipalId, fixture.Context.ApiKeyId, fixture.Context.CredentialVersion, fixture.Context.CredentialExpiresUtc); var request = Request(fixture.Clock) with { Caller = caller }; cache.CaptureGeneration(request.MappingId).ShouldBe(1); var lease = new MetadataAuthorityLease(fixture.Serving with { ServingGeneration = 1 }, new MetadataLease(1, 1, TimeSpan.FromSeconds(1)), fixture.Clock.GetTimestamp(), TimeSpan.FromSeconds(1), TimeSpan.Zero, fixture.Clock); var local = fixture.Activation.CaptureAuthority(); var page = new ProjectedParentSnapshot(ProjectionPageStatus.Ready, [], true, null, 1, Lease: lease, LocalAuthority: local, ParentProof: ParentProof(fixture, request, lease, local)); cache.TryPublish(request, page).ShouldBeTrue(); cache.TryGetParent(request).Status.ShouldBe(ProjectionPageStatus.Ready); fixture.Clock.Advance(TimeSpan.FromSeconds(2)); cache.TryGetParent(request).Status.ShouldBe(ProjectionPageStatus.Unavailable); } [Fact] public void Invalidated_pinned_metadata_stays_charged_until_last_pin_is_released() { using var fixture = new LocalDataFixture(); var policy = new DataOperationPolicy(fixture.Authority, new TriePermissionEvaluator(fixture.Authority.Tries, fixture.Clock), fixture.Clock); var cache = new ProjectedCatalogCache(4, 1, fixture.Clock, policy); var caller = new DataCallerIdentity(fixture.Context.PrincipalId, fixture.Context.ApiKeyId, fixture.Context.CredentialVersion, fixture.Context.CredentialExpiresUtc); var request = Request(fixture.Clock) with { Caller = caller }; cache.CaptureGeneration(request.MappingId).ShouldBe(1); var local = fixture.Activation.CaptureAuthority(); var lease = new MetadataAuthorityLease(fixture.Serving with { ServingGeneration = 1 }, new MetadataLease(1, 1, TimeSpan.FromSeconds(15)), fixture.Clock.GetTimestamp(), TimeSpan.FromSeconds(15), TimeSpan.Zero, fixture.Clock); ProjectedNodeProof Proof(string id, string identifier, long generation = 1) { var view = new DataView(new DataAddress("origin", "urn:raw", "string", identifier), DataRealm.Raw, "mapping", 1, "Plant/branch/" + id); var scope = new NodeScope { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw, Segments = ["Plant", "branch", id] }; var subject = new MappedNamespaceSubject(view, scope, ["folder"], lease.Serving, DataOperations.Browse); var resolver = new MappedSubjectResolver([subject], fixture.Serving.CatalogEpoch, local); var metadata = new DataMetadata(view, id, "Tag", DataValueKind.Int32, -1, [], false, DataOperations.Browse, 1, null, null, false, Serving: lease.Serving); var origin = metadata with { View = view with { MappingId = null, MappingRevision = 0, Subject = "origin/" + id } }; return new ProjectedNodeProof(ProjectedDataIds.Identifier("mapping", view.Address), metadata, subject, resolver, lease, generation, origin); } var first = Proof("first", "first"); first.OriginMetadata.View.Subject.ShouldBe("origin/first"); first.OriginMetadata.View.MappingId.ShouldBeNull(); first.Metadata.View.MappingId.ShouldBe("mapping"); cache.TryPublish(request, new(ProjectionPageStatus.Ready, [first], true, null, 1, lease, local, ParentProof(fixture, request, lease, local))).ShouldBeTrue(); cache.TryPinProjected(DataRealm.Raw, first.LocalIdentifier, out var pin).ShouldBeTrue(); cache.MarkUnavailable(request.MappingId, request.Parent); cache.TryResolveProjected(DataRealm.Raw, first.LocalIdentifier, out _).ShouldBeFalse(); cache.TryPublish(request, new(ProjectionPageStatus.Ready, [Proof("second", "second", 2)], true, null, 2, lease, local, ParentProof(fixture, request, lease, local, 2))).ShouldBeFalse(); pin!.Dispose(); cache.TryPublish(request, new(ProjectionPageStatus.Ready, [Proof("second", "second", 2)], true, null, 2, lease, local, ParentProof(fixture, request, lease, local, 2))).ShouldBeTrue(); } [Fact] public void Empty_page_still_consumes_the_aggregate_metadata_byte_budget() { using var fixture = new LocalDataFixture(); var policy = new DataOperationPolicy(fixture.Authority, new TriePermissionEvaluator(fixture.Authority.Tries, fixture.Clock), fixture.Clock); var cache = new ProjectedCatalogCache(4, 8, fixture.Clock, policy, maxBytes: 128); var caller = new DataCallerIdentity(fixture.Context.PrincipalId, fixture.Context.ApiKeyId, fixture.Context.CredentialVersion, fixture.Context.CredentialExpiresUtc); var request = Request(fixture.Clock) with { Caller = caller }; cache.CaptureGeneration(request.MappingId); var lease = new MetadataAuthorityLease(fixture.Serving with { ServingGeneration = 1 }, new MetadataLease(1, 1, TimeSpan.FromSeconds(1)), fixture.Clock.GetTimestamp(), TimeSpan.FromSeconds(1), TimeSpan.Zero, fixture.Clock); var local = fixture.Activation.CaptureAuthority(); cache.TryPublish(request, new(ProjectionPageStatus.Ready, [], true, null, 1, lease, local, ParentProof(fixture, request, lease, local))).ShouldBeFalse(); } [Fact] public void Empty_page_cannot_bypass_local_parent_browse_authorization() { using var fixture = new LocalDataFixture(); var policy = new DataOperationPolicy(fixture.Authority, new TriePermissionEvaluator(fixture.Authority.Tries, fixture.Clock), fixture.Clock); var cache = new ProjectedCatalogCache(4, 8, fixture.Clock, policy); var caller = new DataCallerIdentity(fixture.Context.PrincipalId, fixture.Context.ApiKeyId, fixture.Context.CredentialVersion, fixture.Context.CredentialExpiresUtc); var request = Request(fixture.Clock) with { Caller = caller }; cache.CaptureGeneration("mapping"); var lease = new MetadataAuthorityLease(fixture.Serving with { ServingGeneration = 1 }, new MetadataLease(1, 1, TimeSpan.FromSeconds(1)), fixture.Clock.GetTimestamp(), TimeSpan.FromSeconds(1), TimeSpan.Zero, fixture.Clock); var local = fixture.Activation.CaptureAuthority(); var denied = ParentProof(fixture, request, lease, local, forbidden: true); cache.TryPublish(request, new(ProjectionPageStatus.Ready, [], true, null, 1, lease, local, denied)).ShouldBeFalse(); } [Fact(Timeout = 30000)] public async Task Prepared_remote_page_keeps_origin_subject_and_publishes_only_after_commit() { using var fixture = new LocalDataFixture(); var policy = new DataOperationPolicy(fixture.Authority, new TriePermissionEvaluator(fixture.Authority.Tries, fixture.Clock), fixture.Clock); var cache = new ProjectedCatalogCache(4, 8, fixture.Clock, policy); var source = new FakeProjectionSource(fixture.Clock, fixture.Serving); using var resolver = new RemoteNamespaceResolver(cache, new BrowseContinuationRegistry(8, fixture.Clock), source, policy, 4, 8); var caller = new DataCallerIdentity(fixture.Context.PrincipalId, fixture.Context.ApiKeyId, fixture.Context.CredentialVersion, fixture.Context.CredentialExpiresUtc); var request = Request(fixture.Clock) with { Caller = caller }; var mapping = new RemoteNamespaceMapping { RemoteNamespaceMappingId = "mapping", ClusterId = "cluster", DataConnectionId = "connection", Revision = 1, Enabled = true, Realm = DataRealm.Raw, RemoteRealm = DataRealm.Raw, BranchName = "branch", RemoteRootEntityId = "root", RemoteNamespaceUri = "urn:raw", RemoteIdentifierKind = "string", RemoteIdentifier = "plant", AllowedOperations = DataOperations.Browse }; resolver.ApplyMappings([new ProjectedMappingBinding(mapping, request.Parent, new NodeScope { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw, Segments = ["Plant", "branch"] }, ["folder"], fixture.Activation.CaptureAuthority(), (_, _) => false)]); using var prepared = await resolver.PreparePageAsync(request, TestContext.Current.CancellationToken).WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); prepared.Snapshot.Status.ShouldBe(ProjectionPageStatus.Ready); resolver.TryGetParent(request).Status.ShouldBe(ProjectionPageStatus.Pending); var item = prepared.Snapshot.Items.ShouldHaveSingleItem(); item.OriginMetadata.View.Subject.ShouldBe("origin/child"); item.OriginMetadata.View.MappingId.ShouldBeNull(); item.Metadata.View.MappingId.ShouldBe("mapping"); prepared.TryCommit().ShouldBeTrue(); resolver.TryGetParent(request).Status.ShouldBe(ProjectionPageStatus.Ready); resolver.TryResolveProjected(DataRealm.Raw, item.LocalIdentifier, out var live).ShouldBeTrue(); live.ShouldNotBeNull().OriginMetadata.View.Subject.ShouldBe("origin/child"); } [Fact(Timeout = 30000)] public async Task Concurrent_identical_browse_waiters_share_one_bounded_origin_fetch() { using var fixture = new LocalDataFixture(); var source = new FakeProjectionSource(fixture.Clock, fixture.Serving); source.Connection.BlockBrowse = true; using var resolver = CreateResolver(fixture, source, out var request); var ct = TestContext.Current.CancellationToken; using var stop = CancellationTokenSource.CreateLinkedTokenSource(ct); Task? firstTask = null, secondTask = null; try { firstTask = resolver.PreparePageAsync(request, stop.Token); await source.Connection.BrowseEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), ct); secondTask = resolver.PreparePageAsync(request, stop.Token); source.Connection.ReleaseBrowse.TrySetResult(); using var first = await firstTask.WaitAsync(TimeSpan.FromSeconds(5), ct); using var second = await secondTask.WaitAsync(TimeSpan.FromSeconds(5), ct); first.Snapshot.Status.ShouldBe(ProjectionPageStatus.Ready); second.Snapshot.Status.ShouldBe(ProjectionPageStatus.Ready); source.Connection.BrowseCalls.ShouldBe(1); first.TryCommit().ShouldBeTrue(); second.TryCommit().ShouldBeTrue(); } finally { source.Connection.ReleaseBrowse.TrySetResult(); stop.Cancel(); await DrainAsync(firstTask); await DrainAsync(secondTask); } } [Fact(Timeout = 30000)] public async Task Retiring_mapping_before_commit_fences_the_prepared_page() { using var fixture = new LocalDataFixture(); var source = new FakeProjectionSource(fixture.Clock, fixture.Serving); using var resolver = CreateResolver(fixture, source, out var request); using var prepared = await resolver.PreparePageAsync(request, TestContext.Current.CancellationToken).WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); prepared.Snapshot.Status.ShouldBe(ProjectionPageStatus.Ready); resolver.ApplyMappings([]); prepared.TryCommit().ShouldBeFalse(); resolver.TryResolveProjected(DataRealm.Raw, prepared.Snapshot.Items[0].LocalIdentifier, out _).ShouldBeFalse(); } [Fact(Timeout = 30000)] public async Task Cancelling_one_shared_waiter_does_not_cancel_the_other() { using var fixture = new LocalDataFixture(); var source = new FakeProjectionSource(fixture.Clock, fixture.Serving); source.Connection.BlockBrowse = true; using var resolver = CreateResolver(fixture, source, out var request); using var cancelFirst = new CancellationTokenSource(); var ct = TestContext.Current.CancellationToken; Task? first = null, second = null; try { first = resolver.PreparePageAsync(request, cancelFirst.Token); await source.Connection.BrowseEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), ct); second = resolver.PreparePageAsync(request, ct); cancelFirst.Cancel(); await Assert.ThrowsAnyAsync(async () => await first.WaitAsync(TimeSpan.FromSeconds(5), ct)); source.Connection.ReleaseBrowse.TrySetResult(); using var result = await second.WaitAsync(TimeSpan.FromSeconds(5), ct); result.Snapshot.Status.ShouldBe(ProjectionPageStatus.Ready); source.Connection.BrowseCalls.ShouldBe(1); } finally { source.Connection.ReleaseBrowse.TrySetResult(); cancelFirst.Cancel(); await DrainAsync(first); await DrainAsync(second); } } [Fact(Timeout = 30000)] public async Task Last_cancelled_waiter_keeps_physical_capacity_until_peer_finishes() { using var fixture = new LocalDataFixture(); var source = new FakeProjectionSource(fixture.Clock, fixture.Serving); source.Connection.BlockBrowse = true; source.Connection.IgnoreCancellation = true; using var resolver = CreateResolver(fixture, source, out var request); using var cancel = new CancellationTokenSource(); var ct = TestContext.Current.CancellationToken; Task? first = null; try { first = resolver.PreparePageAsync(request, cancel.Token); await source.Connection.BrowseEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), ct); cancel.Cancel(); await Assert.ThrowsAnyAsync(async () => await first.WaitAsync(TimeSpan.FromSeconds(5), ct)); using (var blocked = await resolver.PreparePageAsync(request, ct).WaitAsync(TimeSpan.FromSeconds(5), ct)) blocked.Snapshot.Status.ShouldBe(ProjectionPageStatus.Unavailable); source.Connection.BrowseCalls.ShouldBe(1); source.Connection.ReleaseBrowse.TrySetResult(); await source.LeaseDisposed.Task.WaitAsync(TimeSpan.FromSeconds(5), ct); using var after = await resolver.PreparePageAsync(request, ct).WaitAsync(TimeSpan.FromSeconds(5), ct); after.Snapshot.Status.ShouldBe(ProjectionPageStatus.Ready); } finally { source.Connection.ReleaseBrowse.TrySetResult(); cancel.Cancel(); await DrainAsync(first); } } [Fact(Timeout = 30000)] public async Task Duplicate_sibling_across_pages_is_rejected_without_consuming_the_cursor() { using var fixture = new LocalDataFixture(); var source = new FakeProjectionSource(fixture.Clock, fixture.Serving); source.Connection.DuplicateSecondPage = true; using var resolver = CreateResolver(fixture, source, out var request); var ct = TestContext.Current.CancellationToken; using var first = await resolver.PreparePageAsync(request, ct).WaitAsync(TimeSpan.FromSeconds(5), ct); first.Snapshot.Complete.ShouldBeFalse(); first.TryCommit().ShouldBeTrue(); var next = first.Snapshot.Continuation.ShouldNotBeNull(); var followup = request with { Continuation = next }; using var second = await resolver.PreparePageAsync(followup, ct).WaitAsync(TimeSpan.FromSeconds(5), ct); second.TryCommit().ShouldBeFalse(); using var retry = await resolver.PreparePageAsync(followup, ct).WaitAsync(TimeSpan.FromSeconds(5), ct); retry.Snapshot.Status.ShouldBe(ProjectionPageStatus.Ready); } [Fact(Timeout = 30000)] public async Task Unversioned_remote_serving_generation_cannot_authorize_a_projection() { using var fixture = new LocalDataFixture(); var source = new FakeProjectionSource(fixture.Clock, fixture.Serving with { ServingGeneration = 0 }, preserveGeneration: true); using var resolver = CreateResolver(fixture, source, out var request); using var result = await resolver.PreparePageAsync(request, TestContext.Current.CancellationToken).WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); result.Snapshot.Status.ShouldBe(ProjectionPageStatus.Unavailable); } [Fact] public void Expired_unpinned_pages_and_nodes_are_reclaimed_for_new_work() { using var fixture = new LocalDataFixture(); var policy = new DataOperationPolicy(fixture.Authority, new TriePermissionEvaluator(fixture.Authority.Tries, fixture.Clock), fixture.Clock); var cache = new ProjectedCatalogCache(1, 1, fixture.Clock, policy); var caller = new DataCallerIdentity(fixture.Context.PrincipalId, fixture.Context.ApiKeyId, fixture.Context.CredentialVersion, fixture.Context.CredentialExpiresUtc); var request = Request(fixture.Clock) with { Caller = caller }; cache.CaptureGeneration("mapping"); var local = fixture.Activation.CaptureAuthority(); MetadataAuthorityLease Lease() => new(fixture.Serving with { ServingGeneration = 1 }, new MetadataLease(1, 1, TimeSpan.FromSeconds(1)), fixture.Clock.GetTimestamp(), TimeSpan.FromSeconds(1), TimeSpan.Zero, fixture.Clock); var firstLease = Lease(); var first = ParentProof(fixture, request, firstLease, local); cache.TryPublish(request, new(ProjectionPageStatus.Ready, [first], true, null, 1, firstLease, local, first)).ShouldBeTrue(); fixture.Clock.Advance(TimeSpan.FromSeconds(2)); var secondRequest = request with { Filter = "new-filter" }; var secondLease = Lease(); var second = ParentProof(fixture, secondRequest, secondLease, local); cache.TryPublish(secondRequest, new(ProjectionPageStatus.Ready, [second], true, null, 1, secondLease, local, second)).ShouldBeTrue(); cache.TryGetParent(secondRequest).Status.ShouldBe(ProjectionPageStatus.Ready); } [Fact] public void Pinned_expired_proof_does_not_prevent_current_identical_placement_from_renewing() { using var fixture = new LocalDataFixture(); var policy = new DataOperationPolicy(fixture.Authority, new TriePermissionEvaluator(fixture.Authority.Tries, fixture.Clock), fixture.Clock); var cache = new ProjectedCatalogCache(2, 2, fixture.Clock, policy); var caller = new DataCallerIdentity(fixture.Context.PrincipalId, fixture.Context.ApiKeyId, fixture.Context.CredentialVersion, fixture.Context.CredentialExpiresUtc); var request = Request(fixture.Clock) with { Caller = caller }; cache.CaptureGeneration("mapping"); var local = fixture.Activation.CaptureAuthority(); MetadataAuthorityLease Lease() => new(fixture.Serving with { ServingGeneration = 1 }, new MetadataLease(1, 1, TimeSpan.FromSeconds(1)), fixture.Clock.GetTimestamp(), TimeSpan.FromSeconds(1), TimeSpan.Zero, fixture.Clock); var oldLease = Lease(); var old = ParentProof(fixture, request, oldLease, local); cache.TryPublish(request, new(ProjectionPageStatus.Ready, [old], true, null, 1, oldLease, local, old)).ShouldBeTrue(); cache.TryPinProjected(DataRealm.Raw, old.LocalIdentifier, out var pin).ShouldBeTrue(); try { fixture.Clock.Advance(TimeSpan.FromSeconds(2)); var renewedLease = Lease(); var renewed = ParentProof(fixture, request, renewedLease, local); cache.TryPublish(request, new(ProjectionPageStatus.Ready, [renewed], true, null, 1, renewedLease, local, renewed)).ShouldBeTrue(); cache.TryResolveProjected(DataRealm.Raw, old.LocalIdentifier, out var current).ShouldBeTrue(); current.ShouldNotBeNull().Lease.ShouldBeSameAs(renewedLease); } finally { pin!.Dispose(); } } [Fact] public void Parent_filter_and_caller_identifiers_are_charged_to_byte_budget() { using var fixture = new LocalDataFixture(); var policy = new DataOperationPolicy(fixture.Authority, new TriePermissionEvaluator(fixture.Authority.Tries, fixture.Clock), fixture.Clock); var cache = new ProjectedCatalogCache(4, 8, fixture.Clock, policy, maxBytes: 4096); var caller = new DataCallerIdentity(fixture.Context.PrincipalId, fixture.Context.ApiKeyId, fixture.Context.CredentialVersion, fixture.Context.CredentialExpiresUtc); var request = Request(fixture.Clock) with { Caller = caller, Filter = new string('x', 5000) }; cache.CaptureGeneration("mapping"); var lease = new MetadataAuthorityLease(fixture.Serving with { ServingGeneration = 1 }, new MetadataLease(1, 1, TimeSpan.FromSeconds(10)), fixture.Clock.GetTimestamp(), TimeSpan.FromSeconds(10), TimeSpan.Zero, fixture.Clock); var local = fixture.Activation.CaptureAuthority(); var parent = ParentProof(fixture, request, lease, local); cache.TryPublish(request, new(ProjectionPageStatus.Ready, [], true, null, 1, lease, local, parent)).ShouldBeFalse(); } [Fact(Timeout = 30000)] public async Task Projection_depth_is_relative_to_mapping_anchor_not_local_scope_depth() { using var fixture = new LocalDataFixture(); var source = new FakeProjectionSource(fixture.Clock, fixture.Serving); using var resolver = CreateResolver(fixture, source, out var request, maximumDepth: 1); using var result = await resolver.PreparePageAsync(request, TestContext.Current.CancellationToken).WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); result.Snapshot.Status.ShouldBe(ProjectionPageStatus.Ready); result.TryCommit().ShouldBeTrue(); } [Fact(Timeout = 30000)] public async Task Mapping_node_limit_applies_across_continuation_pages() { using var fixture = new LocalDataFixture(); var source = new FakeProjectionSource(fixture.Clock, fixture.Serving); source.Connection.DistinctSecondPage = true; using var resolver = CreateResolver(fixture, source, out var request, maximumNodes: 1); var ct = TestContext.Current.CancellationToken; using var first = await resolver.PreparePageAsync(request, ct).WaitAsync(TimeSpan.FromSeconds(5), ct); first.Snapshot.Status.ShouldBe(ProjectionPageStatus.Ready); first.TryCommit().ShouldBeTrue(); var next = first.Snapshot.Continuation.ShouldNotBeNull(); using var second = await resolver.PreparePageAsync(request with { Continuation = next }, ct).WaitAsync(TimeSpan.FromSeconds(5), ct); (second.Snapshot.Status != ProjectionPageStatus.Ready || !second.TryCommit()).ShouldBeTrue(); } [Fact(Timeout = 30000)] public async Task Cancelled_queued_fetches_remain_bounded_until_physical_work_finishes() { using var fixture = new LocalDataFixture(); var source = new FakeProjectionSource(fixture.Clock, fixture.Serving); var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); using var entered = new SemaphoreSlim(0); Task BeforeFetch(CancellationToken _) { entered.Release(); return gate.Task; } using var resolver = CreateResolver(fixture, source, out var request, beforeFetch: BeforeFetch); var ct = TestContext.Current.CancellationToken; try { for (var i = 0; i < 16; i++) { using var cancel = new CancellationTokenSource(); var task = resolver.PreparePageAsync(request with { Filter = i.ToString() }, cancel.Token); (await entered.WaitAsync(TimeSpan.FromSeconds(5), ct)).ShouldBeTrue(); cancel.Cancel(); await Assert.ThrowsAnyAsync(async () => await task.WaitAsync(TimeSpan.FromSeconds(5), ct)); } resolver.OutstandingPhysicalJobs.ShouldBe(16); using var rejected = await resolver.PreparePageAsync(request with { Filter = "overflow" }, ct).WaitAsync(TimeSpan.FromSeconds(5), ct); rejected.Snapshot.Status.ShouldBe(ProjectionPageStatus.Unavailable); resolver.OutstandingPhysicalJobs.ShouldBe(16); } finally { gate.TrySetResult(); } await resolver.WaitForPhysicalJobsAsync().WaitAsync(TimeSpan.FromSeconds(5), ct); resolver.OutstandingPhysicalJobs.ShouldBe(0); using var recovered = await resolver.PreparePageAsync(request, ct).WaitAsync(TimeSpan.FromSeconds(5), ct); recovered.Snapshot.Status.ShouldBe(ProjectionPageStatus.Ready); } [Fact] public void Publishing_a_fresh_page_does_not_revalidate_unrelated_live_pages() { using var fixture = new LocalDataFixture(); var policy = new DataOperationPolicy(fixture.Authority, new TriePermissionEvaluator(fixture.Authority.Tries, fixture.Clock), fixture.Clock); var cache = new ProjectedCatalogCache(8, 8, fixture.Clock, policy); var caller = new DataCallerIdentity(fixture.Context.PrincipalId, fixture.Context.ApiKeyId, fixture.Context.CredentialVersion, fixture.Context.CredentialExpiresUtc); var request = Request(fixture.Clock) with { Caller = caller }; cache.CaptureGeneration("mapping"); var local = fixture.Activation.CaptureAuthority(); var inner = new MetadataAuthorityLease(fixture.Serving with { ServingGeneration = 1 }, new MetadataLease(1, 1, TimeSpan.FromSeconds(10)), fixture.Clock.GetTimestamp(), TimeSpan.FromSeconds(10), TimeSpan.Zero, fixture.Clock); var tracked = new CountingLease(inner); var parent = ParentProof(fixture, request, tracked, local); cache.TryPublish(request, new(ProjectionPageStatus.Ready, [parent], true, null, 1, tracked, local, parent)).ShouldBeTrue(); tracked.Reads = 0; var other = request with { Filter = "another-query" }; var otherParent = ParentProof(fixture, other, inner, local); cache.TryPublish(other, new(ProjectionPageStatus.Ready, [], true, null, 1, inner, local, otherParent)).ShouldBeTrue(); tracked.Reads.ShouldBe(0); } [Fact] public void Captured_page_validity_does_not_revisit_siblings_for_each_returned_name() { using var fixture = new LocalDataFixture(); var (cache, request, tracked) = LargeGuardPage(fixture); var page = cache.TryGetParent(request); var guard = cache.CaptureParentGuard(request, page).ShouldNotBeNull(); tracked.Reads = 0; for (var i = 0; i < 200; i++) guard.IsCurrent.ShouldBeTrue(); tracked.Reads.ShouldBe(0, "per-child emission checks must not authorize the other 199 siblings again"); cache.MarkUnavailable(request.MappingId, request.Parent); guard.IsCurrent.ShouldBeFalse(); } [Fact] public void Captured_page_guard_does_not_keep_a_retired_page_graph_alive() { using var fixture = new LocalDataFixture(); var (cache, request, _) = LargeGuardPage(fixture); var (guard, weak) = Capture(cache, request); cache.MarkUnavailable(request.MappingId, request.Parent); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); weak.IsAlive.ShouldBeFalse("a cursor guard owns its detached control proof, not the retired page graph"); guard.IsCurrent.ShouldBeFalse(); GC.KeepAlive(guard); [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] static (IProjectedPageGuard Guard, WeakReference Page) Capture(ProjectedCatalogCache cache, ProjectedBrowseRequest request) { var page = cache.TryGetParent(request); return (cache.CaptureParentGuard(request, page).ShouldNotBeNull(), new WeakReference(page)); } } [Theory] [InlineData(false)] [InlineData(true)] public void Oversized_origin_metadata_is_charged_for_parent_and_child_proofs(bool child) { using var fixture = new LocalDataFixture(); var policy = new DataOperationPolicy(fixture.Authority, new TriePermissionEvaluator(fixture.Authority.Tries, fixture.Clock), fixture.Clock); var cache = new ProjectedCatalogCache(4, 8, fixture.Clock, policy, maxBytes: 32768); var caller = new DataCallerIdentity(fixture.Context.PrincipalId, fixture.Context.ApiKeyId, fixture.Context.CredentialVersion, fixture.Context.CredentialExpiresUtc); var request = Request(fixture.Clock) with { Caller = caller }; cache.CaptureGeneration(request.MappingId); var local = fixture.Activation.CaptureAuthority(); var lease = new MetadataAuthorityLease(fixture.Serving with { ServingGeneration = 1 }, new MetadataLease(1, 1, TimeSpan.FromSeconds(10)), fixture.Clock.GetTimestamp(), TimeSpan.FromSeconds(10), TimeSpan.Zero, fixture.Clock); var parent = ParentProof(fixture, request, lease, local); var large = parent with { OriginMetadata = parent.OriginMetadata with { StableSourceId = new string('x', 32768), EngineeringUnits = new string('u', 32768) } }; cache.TryPublish(request, new(ProjectionPageStatus.Ready, child ? [large] : [], true, null, 1, lease, local, child ? parent : large)).ShouldBeFalse(); } private static (ProjectedCatalogCache Cache, ProjectedBrowseRequest Request, CountingLease Tracked) LargeGuardPage(LocalDataFixture fixture) { var policy = new DataOperationPolicy(fixture.Authority, new TriePermissionEvaluator(fixture.Authority.Tries, fixture.Clock), fixture.Clock); var cache = new ProjectedCatalogCache(4, 512, fixture.Clock, policy); var caller = new DataCallerIdentity(fixture.Context.PrincipalId, fixture.Context.ApiKeyId, fixture.Context.CredentialVersion, fixture.Context.CredentialExpiresUtc); var request = Request(fixture.Clock) with { Caller = caller, Budget = new DataBudget(TimeSpan.FromSeconds(3), 256, 1_000_000) }; cache.CaptureGeneration("mapping"); var local = fixture.Activation.CaptureAuthority(); var lease = new MetadataAuthorityLease(fixture.Serving with { ServingGeneration = 1 }, new MetadataLease(1, 1, TimeSpan.FromSeconds(10)), fixture.Clock.GetTimestamp(), TimeSpan.FromSeconds(10), TimeSpan.Zero, fixture.Clock); var tracked = new CountingLease(lease); var children = Enumerable.Range(0, 200).Select(index => { var id = "child" + index; var view = request.Parent with { Address = request.Parent.Address with { Identifier = id }, Subject = "local/anchor/" + id }; var subject = new MappedNamespaceSubject(view, new NodeScope { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw, Segments = ["Plant", id] }, ["folder"], lease.Serving, DataOperations.Browse); var metadata = new DataMetadata(view, id, "Tag", DataValueKind.Int32, -1, [], false, DataOperations.Browse, 1, null, null, false, Serving: lease.Serving); var origin = metadata with { View = view with { MappingId = null, MappingRevision = 0, Subject = "origin/" + id } }; return new ProjectedNodeProof(ProjectedDataIds.Identifier("mapping", view.Address), metadata, subject, new MappedSubjectResolver([subject], 1, local), tracked, 1, origin); }).ToArray(); cache.TryPublish(request, new(ProjectionPageStatus.Ready, children, true, null, 1, lease, local, ParentProof(fixture, request, lease, local))).ShouldBeTrue(); return (cache, request, tracked); } private sealed class CountingLease(IDataAuthorizationLease inner) : IDataAuthorizationLease { public int Reads { get; set; } public bool IsValid { get { Reads++; return inner.IsValid; } } public ServingIdentity Serving => inner.Serving; } [Fact(Timeout = 30000)] public async Task Per_mapping_limit_reclaims_expired_nodes_even_when_global_capacity_is_available() { using var fixture = new LocalDataFixture(); var source = new FakeProjectionSource(fixture.Clock, fixture.Serving); source.Connection.DistinctFiltered = true; using var resolver = CreateResolver(fixture, source, out var request, maximumNodes: 1); var ct = TestContext.Current.CancellationToken; using (var first = await resolver.PreparePageAsync(request, ct).WaitAsync(TimeSpan.FromSeconds(5), ct)) { first.Snapshot.Status.ShouldBe(ProjectionPageStatus.Ready); first.TryCommit().ShouldBeTrue(); } fixture.Clock.Advance(TimeSpan.FromSeconds(11)); var next = request with { Filter = "other", RequestStartedTimestamp = fixture.Clock.GetTimestamp() }; using var second = await resolver.PreparePageAsync(next, ct).WaitAsync(TimeSpan.FromSeconds(5), ct); second.Snapshot.Status.ShouldBe(ProjectionPageStatus.Ready); second.TryCommit().ShouldBeTrue(); } private static async Task DrainAsync(Task? task) { if (task is null) return; try { (await task.WaitAsync(TimeSpan.FromSeconds(5))).Dispose(); } catch (Exception ex) when (ex is OperationCanceledException or TimeoutException or InvalidOperationException) { } } private static RemoteNamespaceResolver CreateResolver(LocalDataFixture fixture, IGrpcDataAdapterConnectionSource source, out ProjectedBrowseRequest request, int? maximumDepth = null, int? maximumNodes = null, Func? beforeFetch = null) { var policy = new DataOperationPolicy(fixture.Authority, new TriePermissionEvaluator(fixture.Authority.Tries, fixture.Clock), fixture.Clock); var cache = new ProjectedCatalogCache(4, 8, fixture.Clock, policy); var resolver = new RemoteNamespaceResolver(cache, new BrowseContinuationRegistry(8, fixture.Clock), source, policy, 4, 1, beforeFetch); var caller = new DataCallerIdentity(fixture.Context.PrincipalId, fixture.Context.ApiKeyId, fixture.Context.CredentialVersion, fixture.Context.CredentialExpiresUtc); request = Request(fixture.Clock) with { Caller = caller }; var mapping = new RemoteNamespaceMapping { RemoteNamespaceMappingId = "mapping", ClusterId = "cluster", DataConnectionId = "connection", Revision = 1, Enabled = true, Realm = DataRealm.Raw, RemoteRealm = DataRealm.Raw, BranchName = "branch", RemoteRootEntityId = "root", RemoteNamespaceUri = "urn:raw", RemoteIdentifierKind = "string", RemoteIdentifier = "plant", AllowedOperations = DataOperations.Browse }; if (maximumDepth is { } depth) mapping.MaxProjectionDepth = depth; if (maximumNodes is { } nodes) mapping.MaxProjectionNodes = nodes; resolver.ApplyMappings([new ProjectedMappingBinding(mapping, request.Parent, new NodeScope { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw, Segments = ["Plant", "branch"] }, ["folder"], fixture.Activation.CaptureAuthority(), (_, _) => false)]); return resolver; } private sealed class FakeProjectionSource(TimeProvider clock, ServingIdentity serving, bool preserveGeneration = false) : IGrpcDataAdapterConnectionSource { public FakeProjectionConnection Connection { get; } = new(clock, !preserveGeneration && serving.ServingGeneration == 0 ? serving with { ServingGeneration = 1 } : serving); public TaskCompletionSource LeaseDisposed { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); public ValueTask AcquireAsync(string connectionId, CancellationToken cancellationToken) => ValueTask.FromResult(new FakeProjectionLease(Connection, () => LeaseDisposed.TrySetResult())); } private sealed class FakeProjectionLease(IDataConnection connection, Action released) : IGrpcDataAdapterConnectionLease { public IDataConnection Connection => connection; public CancellationToken CancellationToken => CancellationToken.None; public ValueTask DisposeAsync() { released(); return ValueTask.CompletedTask; } } private sealed class FakeProjectionConnection(TimeProvider clock, ServingIdentity serving) : IDataConnection { public DataTarget Target => new(DataTargetMode.Node, "origin", "remote"); public TimeProvider Clock => clock; public Task GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => throw new NotSupportedException(); public Task>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) { var root = request.Views[0] with { Subject = "origin/root" }; var metadata = new DataMetadata(root, "root", "Folder", DataValueKind.Null, -1, [], false, DataOperations.Browse, 1, null, null, false, Serving: serving); return Task.FromResult>>([new("0", DataItemStatus.Good, metadata, null)]); } public bool BlockBrowse { get; set; } public bool IgnoreCancellation { get; set; } public bool DuplicateSecondPage { get; set; } public bool DistinctSecondPage { get; set; } public bool DistinctFiltered { get; set; } public TaskCompletionSource BrowseEntered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); public TaskCompletionSource ReleaseBrowse { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); private int _browseCalls; public int BrowseCalls => Volatile.Read(ref _browseCalls); public async Task BrowseAsync(BrowseRequest request, CancellationToken cancellationToken) { Interlocked.Increment(ref _browseCalls); BrowseEntered.TrySetResult(); if (BlockBrowse) await ReleaseBrowse.Task.WaitAsync(TimeSpan.FromSeconds(5), IgnoreCancellation ? CancellationToken.None : cancellationToken); var id = ((DuplicateSecondPage || DistinctSecondPage) && request.Continuation is not null || DistinctFiltered && request.Filter is not null) ? "plant/other-child" : "plant/child"; var child = new DataView(new DataAddress("origin", "urn:raw", "string", id), DataRealm.Raw, null, 0, "origin/child"); var metadata = new DataMetadata(child, (DistinctSecondPage && request.Continuation is not null || DistinctFiltered && request.Filter is not null) ? "other" : "child", "Tag", DataValueKind.Int32, -1, [], false, DataOperations.Browse, 1, null, null, false, Serving: serving); var continuation = (DuplicateSecondPage || DistinctSecondPage) && request.Continuation is null ? "peer-next" : null; return new DataBrowseBranch(request.Parent, DataItemStatus.Good, [metadata], continuation is null, continuation, new MetadataLease(1, 1, TimeSpan.FromSeconds(10)), serving); } public Task> ReadAsync(ReadRequest request, CancellationToken cancellationToken) => throw new NotSupportedException(); public Task> WriteAsync(WriteBatch request, CancellationToken cancellationToken) => throw new NotSupportedException(); public Task SubscribeAsync(CancellationToken cancellationToken) => throw new NotSupportedException(); public ValueTask DisposeAsync() => ValueTask.CompletedTask; } private static ProjectedNodeProof ParentProof(LocalDataFixture fixture, ProjectedBrowseRequest request, IDataAuthorizationLease lease, IDataMappedCatalogAuthority local, long generation = 1, bool forbidden = false) { var view = request.Parent; var scope = new NodeScope { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw, Segments = [forbidden ? "Forbidden" : "Plant"] }; var subject = new MappedNamespaceSubject(view, scope, ["folder"], lease.Serving, DataOperations.Browse); var resolver = new MappedSubjectResolver([subject], fixture.Serving.CatalogEpoch, local); var metadata = new DataMetadata(view, "branch", "Folder", DataValueKind.Null, -1, [], false, DataOperations.Browse, 1, null, null, false, Serving: lease.Serving); var origin = metadata with { View = view with { MappingId = null, MappingRevision = 0, Subject = "origin/plant" } }; return new ProjectedNodeProof(ProjectedDataIds.Identifier("mapping", view.Address), metadata, subject, resolver, lease, generation, origin); } private static ProjectedBrowseRequest Request(TimeProvider clock) => new("mapping", new DataView(new DataAddress("origin", "urn:raw", "string", "plant"), DataRealm.Raw, "mapping", 1, "local/anchor"), null, null, new DataCallerIdentity("peer", "key", "credential", null), new DataBudget(TimeSpan.FromSeconds(3), 20, 10000), clock.GetTimestamp()); }