using Akka.Actor; 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.Drivers; using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness; namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers; [Trait("Feature", "GrpcData"), Trait("Category", "Unit"), Trait("Phase", "P06")] public sealed class GrpcDataDriverDemandBridgeTests : RuntimeActorTestBase { private static readonly DataSubscriptionSettings Settings = new(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null); private static SubscriptionAuthorizedView View() { var view = new DataView(new("cluster", "urn:raw", "string", "tag"), DataRealm.Raw, null, 0, "subject"); var source = SourceKey.ForDriver("cluster", "driver", "tag", "node", "inc"); return new SubscriptionAuthorizedView(view, source, new("node", "inc", "Primary", 1, 1), new(view, "tag", "Variable", DataValueKind.Int32, -1, [], false, DataOperations.Subscribe, 1, "tag", null, false), "principal", "export", new(DataTargetMode.Node, "cluster", "node"), DataConsistency.Primary, () => true); } [Fact] public async Task Shared_interests_wait_for_driver_ack_and_last_release_removes_physical_demand() { var host = CreateTestProbe(); var registry = new UpstreamDemandRegistry(8, 16); using var source = new DriverHostSubscriptionDemandSource(Wrap(host.Ref), registry, maxDrivers: 8, maxInterests: 16, timeout: PresenceBudget, ownership: new SubscriptionAcquisitionCapacity(8)); var firstTask = source.AcquireAsync(View(), Settings, TestContext.Current.CancellationToken).AsTask(); var demand = host.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); demand.DriverInstanceId.ShouldBe("driver"); demand.FullReferences.ShouldBe(["tag"]); firstTask.IsCompleted.ShouldBeFalse(); host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(demand.DesiredRevision, 7, Settings.SamplingInterval, true)); var first = await firstTask.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); first.Status.ShouldBe(DataItemStatus.Good); first.Boundary.ShouldBe(demand.DesiredRevision); var secondPending = source.AcquireAsync(View(), Settings, TestContext.Current.CancellationToken).AsTask(); var verified = host.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); verified.DesiredRevision.ShouldBe(demand.DesiredRevision); host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(verified.DesiredRevision, 7, Settings.SamplingInterval, true)); var second = await secondPending.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); second.Status.ShouldBe(DataItemStatus.Good); first.Lease.ShouldNotBeNull().Dispose(); second.Lease.ShouldNotBeNull().Dispose(); var removed = host.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); removed.FullReferences.ShouldBeEmpty(); host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(removed.DesiredRevision, 7, TimeSpan.Zero, true)); } [Fact] public async Task Slower_physical_floor_rejects_interest_and_restores_previous_demand() { var host = CreateTestProbe(); var registry = new UpstreamDemandRegistry(8, 16); using var source = new DriverHostSubscriptionDemandSource(Wrap(host.Ref), registry, maxDrivers: 8, maxInterests: 16, timeout: PresenceBudget, ownership: new SubscriptionAcquisitionCapacity(8)); var request = Settings with { SamplingInterval = TimeSpan.FromMilliseconds(1) }; var pending = source.AcquireAsync(View(), request, TestContext.Current.CancellationToken).AsTask(); var demand = host.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(demand.DesiredRevision, 7, TimeSpan.FromMilliseconds(100), true)); var result = await pending.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); result.Status.ShouldNotBe(DataItemStatus.Good); result.Lease.ShouldBeNull(); var removed = host.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); removed.FullReferences.ShouldBeEmpty(); host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(removed.DesiredRevision, 7, TimeSpan.Zero, true)); } [Fact] public async Task Relaxation_waits_for_proven_busy_cleanup_then_applies_latest_refs() { var host = CreateTestProbe(); var registry = new UpstreamDemandRegistry(8, 16); using var source = new DriverHostSubscriptionDemandSource(Wrap(host.Ref), registry, 8, 16, PresenceBudget, new SubscriptionAcquisitionCapacity(8)); var firstPending = source.AcquireAsync(View(), Settings, TestContext.Current.CancellationToken).AsTask(); var firstApply = host.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(firstApply.DesiredRevision, 7, Settings.SamplingInterval, true)); var first = await firstPending.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); var secondView = View() with { Source = SourceKey.ForDriver("cluster", "driver", "next", "node", "inc") }; var secondPending = source.AcquireAsync(secondView, Settings, TestContext.Current.CancellationToken).AsTask(); var expanded = host.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); expanded.FullReferences.ShouldBe(["next", "tag"]); host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(expanded.DesiredRevision, 7, Settings.SamplingInterval, true)); var second = await secondPending.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); second.Lease.ShouldNotBeNull().Dispose(); var relaxation = host.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); relaxation.FullReferences.ShouldBe(["tag"]); var cleanup = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(relaxation.DesiredRevision, 7, TimeSpan.Zero, false, Busy: true, RetryWhenReady: cleanup.Task)); cleanup.SetResult(true); var retried = host.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); retried.FullReferences.ShouldBe(["tag"]); host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(retried.DesiredRevision, 7, Settings.SamplingInterval, true)); first.Lease.ShouldNotBeNull().Dispose(); var removed = host.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); removed.FullReferences.ShouldBeEmpty(); host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(removed.DesiredRevision, 7, TimeSpan.Zero, true)); } [Fact] public async Task A_busy_driver_does_not_block_a_different_driver() { var host = CreateTestProbe(); var registry = new UpstreamDemandRegistry(8, 16); using var source = new DriverHostSubscriptionDemandSource(Wrap(host.Ref), registry, 8, 16, PresenceBudget, new SubscriptionAcquisitionCapacity(8)); var firstPending = source.AcquireAsync(View(), Settings, TestContext.Current.CancellationToken).AsTask(); var initial = host.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(initial.DesiredRevision, 7, Settings.SamplingInterval, true)); var first = await firstPending.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); var nextView = View() with { Source = SourceKey.ForDriver("cluster", "driver", "next", "node", "inc") }; var secondPending = source.AcquireAsync(nextView, Settings, TestContext.Current.CancellationToken).AsTask(); var expanded = host.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(expanded.DesiredRevision, 7, Settings.SamplingInterval, true)); var second = await secondPending.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); second.Lease.ShouldNotBeNull().Dispose(); var relax = host.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); var blocked = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(relax.DesiredRevision, 7, TimeSpan.Zero, false, Busy: true, RetryWhenReady: blocked.Task)); var otherView = View() with { Source = SourceKey.ForDriver("cluster", "driver2", "tag", "node", "inc") }; var otherPending = source.AcquireAsync(otherView, Settings, TestContext.Current.CancellationToken).AsTask(); var otherApply = host.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); otherApply.DriverInstanceId.ShouldBe("driver2"); host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(otherApply.DesiredRevision, 8, Settings.SamplingInterval, true)); var other = await otherPending.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); other.Status.ShouldBe(DataItemStatus.Good); blocked.TrySetResult(false); first.Lease.ShouldNotBeNull().Dispose(); other.Lease.ShouldNotBeNull().Dispose(); } [Fact] public async Task A_driver_with_an_unanswered_first_ack_does_not_block_another_driver() { var host = CreateTestProbe(); using var source = new DriverHostSubscriptionDemandSource(Wrap(host.Ref), new UpstreamDemandRegistry(8, 16), 8, 16, PresenceBudget, new SubscriptionAcquisitionCapacity(8)); var pendingA = source.AcquireAsync(View(), Settings, TestContext.Current.CancellationToken).AsTask(); var requestA = host.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); var replyA = host.LastSender; var otherView = View() with { Source = SourceKey.ForDriver("cluster", "driver2", "tag", "node", "inc") }; var pendingB = source.AcquireAsync(otherView, Settings, TestContext.Current.CancellationToken).AsTask(); var requestB = host.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); requestB.DriverInstanceId.ShouldBe("driver2"); host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(requestB.DesiredRevision, 8, Settings.SamplingInterval, true)); var second = await pendingB.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); second.Status.ShouldBe(DataItemStatus.Good); pendingA.IsCompleted.ShouldBeFalse(); replyA.Tell(new DriverInstanceActor.AcquisitionDemandApplied(requestA.DesiredRevision, 7, Settings.SamplingInterval, true)); var first = await pendingA.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); first.Status.ShouldBe(DataItemStatus.Good); first.Lease?.Dispose(); second.Lease?.Dispose(); } [Fact] public async Task Identical_interest_churn_does_not_rescan_all_existing_interests() { var host = Sys.ActorOf(Props.Create(() => new AutomaticAckHost())); using var source = new DriverHostSubscriptionDemandSource(host, new UpstreamDemandRegistry(4, 2048), 4, 2048, PresenceBudget, new SubscriptionAcquisitionCapacity(4)); var leases = new List(); for (var i = 0; i < 1024; i++) { var result = await source.AcquireAsync(View(), Settings, TestContext.Current.CancellationToken); leases.Add(result.Lease.ShouldNotBeNull()); } var before = source.ReferenceVisitCount; for (var i = 0; i < 64; i++) { var result = await source.AcquireAsync(View(), Settings, TestContext.Current.CancellationToken); leases.Add(result.Lease.ShouldNotBeNull()); } (source.ReferenceVisitCount - before).ShouldBeLessThan(1024L, "each add must not scan the existing 1,000 interests"); foreach (var lease in leases) lease.Dispose(); } [Fact] public async Task Canceled_expansion_rolls_back_with_a_revision_newer_than_the_late_expansion() { var host = CreateTestProbe(); using var source = new DriverHostSubscriptionDemandSource(Wrap(host.Ref), new UpstreamDemandRegistry(8, 16), 8, 16, PresenceBudget, new SubscriptionAcquisitionCapacity(8)); var aPending = source.AcquireAsync(View(), Settings, TestContext.Current.CancellationToken).AsTask(); var a = host.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(a.DesiredRevision, 7, Settings.SamplingInterval, true)); var first = await aPending.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); using var cancel = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken); var bView = View() with { Source = SourceKey.ForDriver("cluster", "driver", "next", "node", "inc") }; var bPending = source.AcquireAsync(bView, Settings, cancel.Token).AsTask(); var b = host.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); b.DesiredRevision.ShouldBeGreaterThan(a.DesiredRevision); var lateReply = host.LastSender; cancel.Cancel(); await Should.ThrowAsync(() => bPending); var rollback = host.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); rollback.FullReferences.ShouldBe(["tag"]); rollback.DesiredRevision.ShouldBeGreaterThan(b.DesiredRevision); lateReply.Tell(new DriverInstanceActor.AcquisitionDemandApplied(b.DesiredRevision, 7, Settings.SamplingInterval, true)); host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(rollback.DesiredRevision, 7, Settings.SamplingInterval, true)); first.Lease.ShouldNotBeNull().Dispose(); } private IActorRef Wrap(IActorRef target) => Sys.ActorOf(Props.Create(() => new OwnerProxy(target))); private sealed class OwnerProxy : ReceiveActor { public OwnerProxy(IActorRef target) { Receive(_ => Sender.Tell(new DriverHostActor.AcquisitionOwnerRegistered(true, 1))); Receive(message => Sender.Tell(new DriverHostActor.AcquisitionDemandOpened(true, message.RequestedKeyGeneration))); Receive(_ => Sender.Tell(new DriverHostActor.AcquisitionOpenAborted(true))); Receive(message => target.Forward(message)); } } private sealed class AutomaticAckHost : ReceiveActor { public AutomaticAckHost() { Receive(_ => Sender.Tell(new DriverHostActor.AcquisitionOwnerRegistered(true, 1))); Receive(message => Sender.Tell(new DriverHostActor.AcquisitionDemandOpened(true, message.RequestedKeyGeneration))); Receive(_ => Sender.Tell(new DriverHostActor.AcquisitionOpenAborted(true))); Receive(message => Sender.Tell(new DriverInstanceActor.AcquisitionDemandApplied( message.DesiredRevision, 7, message.SamplingInterval == TimeSpan.Zero ? TimeSpan.FromMilliseconds(100) : message.SamplingInterval, true))); } } }