using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness; namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; [Trait("Feature", "GrpcData"), Trait("Category", "Unit"), Trait("Phase", "P06")] public sealed class GrpcDataRecoveryAdmissionTests { [Fact(Timeout = 30000)] public async Task Canceling_unopened_stream_releases_its_slot_without_explicit_disposal() { var demand = new DeferredSubscriptionDemand(); var capacity = new SubscriptionTransportCapacity(1, 1, 1_000_000); var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1)); LocalDataFixture? fixture = null; using (fixture = new LocalDataFixture(targetSubscriptions: (context, target) => new LocalSubscriptionService(fixture!.Services, context, target, demand, limits, capacity))) using (var cancellation = new CancellationTokenSource()) { await using var firstConnection = fixture.Connection(); await using var secondConnection = fixture.Connection(); var first = await firstConnection.SubscribeAsync(cancellation.Token); try { var session = first.ShouldBeOfType(); cancellation.Cancel(); await session.Completion.WaitAsync(TimeSpan.FromSeconds(2), TestContext.Current.CancellationToken); await using var replacement = await secondConnection.SubscribeAsync(TestContext.Current.CancellationToken); } finally { await first.DisposeAsync(); } } } [Fact(Timeout = 30000)] public async Task Unopened_stream_expires_on_a_bounded_handshake_deadline() { var demand = new DeferredSubscriptionDemand(); var capacity = new SubscriptionTransportCapacity(1, 1, 1_000_000); var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1), PreOpenTimeout: TimeSpan.FromSeconds(3)); LocalDataFixture? fixture = null; using (fixture = new LocalDataFixture(targetSubscriptions: (context, target) => new LocalSubscriptionService(fixture!.Services, context, target, demand, limits, capacity))) { await using var firstConnection = fixture.Connection(); await using var secondConnection = fixture.Connection(); var first = await firstConnection.SubscribeAsync(TestContext.Current.CancellationToken); try { var session = first.ShouldBeOfType(); fixture.Clock.Advance(TimeSpan.FromSeconds(3)); await session.Completion.WaitAsync(TimeSpan.FromSeconds(2), TestContext.Current.CancellationToken); await using var replacement = await secondConnection.SubscribeAsync(TestContext.Current.CancellationToken); } finally { await first.DisposeAsync(); } } } [Fact(Timeout = 30000)] public async Task Oversized_ack_timeout_is_rejected_without_poisoning_the_command_id() { var demand = new DeferredSubscriptionDemand(); demand.Accept(); var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000); var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1)); LocalDataFixture? fixture = null; using (fixture = new LocalDataFixture(targetSubscriptions: (context, target) => new LocalSubscriptionService(fixture!.Services, context, target, demand, limits, capacity))) { await using var connection = fixture.Connection(); await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken); var invalid = new OpenSubscription("s", 1, "same-command", TimeSpan.MaxValue, [], true, TimeSpan.FromSeconds(30), LocalDataFixture.Budget); await Should.ThrowAsync(() => subscription.SendAsync(invalid, TestContext.Current.CancellationToken)); await subscription.SendAsync(invalid with { AcknowledgementTimeout = TimeSpan.FromSeconds(5) }, TestContext.Current.CancellationToken); await using var reader = subscription.ReadAllAsync(TestContext.Current.CancellationToken) .GetAsyncEnumerator(TestContext.Current.CancellationToken); (await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldBeTrue(); reader.Current.ShouldBeOfType().CommandId.ShouldBe("same-command"); } } [Fact] public void Expired_snapshot_permit_retains_its_quota_while_a_physical_owner_is_alive() { var clock = new ManualTimeProvider(); var scheduler = new SnapshotAdmissionScheduler(1, 1, 1_000, maxLifetime: TimeSpan.FromSeconds(2), clock: clock); scheduler.TryAcquire("peer", 1, out var lease, out _).ShouldBeTrue(); var permit = lease.ShouldBeOfType(); permit.TryGrow(500).ShouldBeTrue(); permit.TryRetain(out var physicalOwner).ShouldBeTrue(); clock.Advance(TimeSpan.FromSeconds(2)); permit.IsValid.ShouldBeFalse(); scheduler.TryAcquire("peer", 1, out _, out _).ShouldBeFalse("expired physical ownership remains charged"); physicalOwner!.Dispose(); scheduler.TryAcquire("peer", 1, out var next, out _).ShouldBeTrue(); next!.Dispose(); permit.Dispose(); } [Fact] public void Snapshot_permits_grow_before_retention_and_respect_global_and_principal_bytes() { var scheduler = new SnapshotAdmissionScheduler(4, 2, 1_000, maxPrincipalBytes: 700); scheduler.TryAcquire("a", 1, out var first, out _).ShouldBeTrue(); scheduler.TryAcquire("b", 1, out var second, out _).ShouldBeTrue(); var firstPermit = first.ShouldBeOfType(); var secondPermit = second.ShouldBeOfType(); firstPermit.TryGrow(600).ShouldBeTrue(); firstPermit.TryGrow(100).ShouldBeFalse(); secondPermit.TryGrow(400).ShouldBeFalse(); secondPermit.TryGrow(398).ShouldBeTrue(); firstPermit.Dispose(); secondPermit.Dispose(); scheduler.TryAcquire("a", 700, out var replacement, out _).ShouldBeTrue(); replacement!.Dispose(); } [Fact(Timeout = 30000)] public async Task Stream_open_rejects_old_authority_epoch_while_current_epoch_and_same_key_succeed() { var demand = new DeferredSubscriptionDemand(); demand.Accept(); var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000); var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1)); LocalDataFixture? fixture = null; using (fixture = new LocalDataFixture(advanceAuthority: true, targetSubscriptions: (context, target) => new LocalSubscriptionService(fixture!.Services, context, target, demand, limits, capacity))) { fixture.Context.AuthorityEpoch.ShouldBe(2); var target = new DataTarget(DataTargetMode.Node, "cluster", "node-a"); await using var fresh = fixture.Services.Create(fixture.Context, target); await using var accepted = await fresh.SubscribeAsync(TestContext.Current.CancellationToken); var staleContext = fixture.Context with { AuthorityEpoch = 1 }; await using var stale = fixture.Services.Create(staleContext, target); await Should.ThrowAsync(() => stale.SubscribeAsync(TestContext.Current.CancellationToken)); } } [Fact] public void Snapshot_admission_bounds_principal_bytes_send_rate_lifetime_and_retry_guidance() { var clock = new ManualTimeProvider(); var scheduler = new SnapshotAdmissionScheduler(4, 2, 1_000, maxPrincipalBytes: 700, globalBytesPerSecond: 100, principalBytesPerSecond: 60, maxLifetime: TimeSpan.FromSeconds(2), clock: clock); scheduler.TryAcquire("peer", 600, out var first, out _).ShouldBeTrue(); scheduler.TryAcquire("PEER", 101, out _, out var quotaRetry).ShouldBeFalse(); quotaRetry.ShouldBeGreaterThan(TimeSpan.Zero); scheduler.TryConsume("peer", 60, out _).ShouldBeTrue(); scheduler.TryConsume("PEER", 1, out var retry).ShouldBeFalse(); retry.ShouldBeGreaterThanOrEqualTo(TimeSpan.FromSeconds(1)); retry.ShouldBeLessThan(TimeSpan.FromSeconds(2)); scheduler.TryConsume("other", 41, out _).ShouldBeFalse(); clock.Advance(TimeSpan.FromSeconds(1)); scheduler.TryConsume("other", 41, out _).ShouldBeTrue(); clock.Advance(TimeSpan.FromSeconds(1)); first.ShouldBeOfType().IsValid.ShouldBeFalse(); scheduler.TryAcquire("PEER", 700, out var afterExpiry, out _).ShouldBeTrue(); first!.Dispose(); afterExpiry!.Dispose(); } [Fact(Timeout = 30000)] public async Task Idle_streams_obey_shared_principal_admission_and_disposal_releases_the_slot() { var demand = new DeferredSubscriptionDemand(); var capacity = new SubscriptionTransportCapacity(1, 1, 1_000_000); var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1)); LocalDataFixture? fixture = null; using (fixture = new LocalDataFixture(subscriptions: context => new LocalSubscriptionService(fixture!.Services, context, new(DataTargetMode.Node, "cluster", "node-a"), demand, limits, capacity))) { await using var firstConnection = fixture.Connection(); await using var secondConnection = fixture.Connection(); var first = await firstConnection.SubscribeAsync(TestContext.Current.CancellationToken); await Should.ThrowAsync(() => secondConnection.SubscribeAsync(TestContext.Current.CancellationToken)); await first.DisposeAsync(); await using var replacement = await secondConnection.SubscribeAsync(TestContext.Current.CancellationToken); } } [Fact] public void Transport_capacity_is_shared_across_sessions_and_principals() { var capacity = new SubscriptionTransportCapacity(2, 1, 1_000); capacity.TryReserve("a", 400, out var first).ShouldBeTrue(); capacity.TryReserve("A", 100, out _).ShouldBeFalse("principal quota is case-insensitive"); capacity.TryReserve("a", 100, out _).ShouldBeFalse(); capacity.TryReserve("b", 700, out _).ShouldBeFalse(); capacity.TryReserve("b", 600, out var second).ShouldBeTrue(); capacity.TryReserve("c", 1, out _).ShouldBeFalse(); first!.Dispose(); first.Dispose(); capacity.TryReserve("c", 400, out var third).ShouldBeTrue(); third!.Dispose(); second!.Dispose(); capacity.ActiveOperations.ShouldBe(0); } [Fact] public void Snapshot_capacity_is_global_and_per_principal_and_disposal_releases_it_once() { var scheduler = new SnapshotAdmissionScheduler(maxConcurrent: 2, maxPerPrincipal: 1, maxBytes: 1000); scheduler.TryAcquire("a", 400, out var first).ShouldBeTrue(); scheduler.TryAcquire("A", 100, out _).ShouldBeFalse("principal quota is case-insensitive"); scheduler.TryAcquire("a", 100, out _).ShouldBeFalse(); scheduler.TryAcquire("b", 700, out _).ShouldBeFalse(); scheduler.TryAcquire("b", 600, out var second).ShouldBeTrue(); scheduler.TryAcquire("c", 1, out _).ShouldBeFalse(); first!.Dispose(); first.Dispose(); scheduler.TryAcquire("c", 400, out var replacement).ShouldBeTrue(); replacement!.Dispose(); second!.Dispose(); scheduler.TryAcquire("a", 1000, out var last).ShouldBeTrue(); last!.Dispose(); } }