using System.Text.Json; using Akka.Actor; using Microsoft.EntityFrameworkCore; using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Commons.Interfaces; using ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy; using ZB.MOM.WW.OtOpcUa.Commons.Types; using ZB.MOM.WW.OtOpcUa.Configuration; using ZB.MOM.WW.OtOpcUa.Runtime.DeploymentCache; using ZB.MOM.WW.OtOpcUa.Runtime.Drivers; using ZB.MOM.WW.OtOpcUa.Runtime.OpcUa; using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness; namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers; /// /// Gitea #1107 — the node side of the coordinator's dispatch re-send. A re-send names the nodes that have not /// acked; it must never make a node apply the same deployment twice (under #601 a second apply of a degraded /// revision is a full re-apply), and a late or duplicate copy must be harmless. /// [Collection("opcua-publish-meters")] public sealed class DriverHostActorRedispatchTests : RuntimeActorTestBase { private static readonly NodeId TestNode = NodeId.Parse("driver-test"); private static readonly RevisionHash RevA = RevisionHash.Parse(new string('a', 64)); private static readonly TimeSpan Quiet = TimeSpan.FromMilliseconds(400); [Fact] public void A_resend_of_a_deployment_already_acked_degraded_re_sends_the_ack_instead_of_re_applying() { var (db, deploymentId) = SeedOneTagDeployment(); var coordinator = CreateTestProbe(); var publish = CreateTestProbe(); var actor = Sys.ActorOf(DriverHostActor.Props( db, TestNode, coordinator.Ref, localRoles: new HashSet { "driver" }, opcUaPublishActor: publish.Ref)); var dispatch = new DispatchDeployment(deploymentId, RevA, CorrelationId.NewId()); actor.Tell(dispatch); var rebuild = publish.FishForMessage(_ => true, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); publish.Reply(new OpcUaPublishActor.RebuildCompleted(rebuild.Correlation, rebuild.DeploymentId, true, "failedNodes=1")); var first = coordinator.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); first.Degraded.ShouldBeTrue(); // The coordinator never saw that ack and re-sends to this node (node id case differs, as SQL/DNS may). actor.Tell(dispatch with { TargetNodes = ["DRIVER-TEST"] }); var again = coordinator.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); again.ShouldBe(first); // the SAME answer, not a new apply's publish.ExpectNoMsg(Quiet, TestContext.Current.CancellationToken); // Positive control: an ORIGINAL dispatch of a degraded revision still re-applies (#601) — so the silence above // is the re-send being recognised, not a host that has stopped applying. actor.Tell(new DispatchDeployment(deploymentId, RevA, CorrelationId.NewId())); publish.FishForMessage(_ => true, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); } [Fact] public void A_resend_addressed_to_another_node_is_ignored() { var (db, deploymentId) = SeedOneTagDeployment(); var coordinator = CreateTestProbe(); var publish = CreateTestProbe(); var actor = Sys.ActorOf(DriverHostActor.Props( db, TestNode, coordinator.Ref, localRoles: new HashSet { "driver" }, opcUaPublishActor: publish.Ref)); actor.Tell(new DispatchDeployment(deploymentId, RevA, CorrelationId.NewId(), TargetNodes: ["driver-other"])); publish.ExpectNoMsg(Quiet, TestContext.Current.CancellationToken); coordinator.ExpectNoMsg(TimeSpan.Zero, TestContext.Current.CancellationToken); // Positive control: the same re-send naming THIS node (never acked here) is a first apply. actor.Tell(new DispatchDeployment(deploymentId, RevA, CorrelationId.NewId(), TargetNodes: ["driver-other", "driver-test"])); var rebuild = publish.FishForMessage(_ => true, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); publish.Reply(new OpcUaPublishActor.RebuildCompleted(rebuild.Correlation, rebuild.DeploymentId, false, null)); coordinator.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken) .Outcome.ShouldBe(ApplyAckOutcome.Applied); } [Fact] public void A_duplicate_while_the_ack_waits_on_the_address_space_outcome_does_not_apply_twice() { var (db, deploymentId) = SeedOneTagDeployment(); var coordinator = CreateTestProbe(); var publish = CreateTestProbe(); var actor = Sys.ActorOf(DriverHostActor.Props( db, TestNode, coordinator.Ref, localRoles: new HashSet { "driver" }, opcUaPublishActor: publish.Ref)); var dispatch = new DispatchDeployment(deploymentId, RevA, CorrelationId.NewId()); actor.Tell(dispatch); var rebuild = publish.FishForMessage(_ => true, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); // The ack is held on the outcome. Neither a re-send nor a plain duplicate may start a second apply. actor.Tell(dispatch with { TargetNodes = [TestNode.Value] }); actor.Tell(dispatch); publish.ExpectNoMsg(Quiet, TestContext.Current.CancellationToken); coordinator.ExpectNoMsg(TimeSpan.Zero, TestContext.Current.CancellationToken); // Exactly one ack, when the one apply's outcome lands. actor.Tell(new OpcUaPublishActor.RebuildCompleted(rebuild.Correlation, rebuild.DeploymentId, false, null), publish.Ref); coordinator.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken) .Outcome.ShouldBe(ApplyAckOutcome.Applied); coordinator.ExpectNoMsg(Quiet, TestContext.Current.CancellationToken); publish.ExpectNoMsg(TimeSpan.Zero, TestContext.Current.CancellationToken); } [Fact] public void A_resend_arriving_mid_apply_does_not_start_a_second_apply() { var db = NewInMemoryDbFactory(); var fetcher = new GatedFetcher(JsonSerializer.SerializeToUtf8Bytes(new { DriverInstances = Array.Empty() })); var deploymentId = DeploymentId.NewId(); var coordinator = CreateTestProbe(); var actor = Sys.ActorOf(DriverHostActor.Props( db, TestNode, coordinator.Ref, localRoles: new HashSet { "driver" }, deploymentArtifactCache: new NullArtifactCache(), fetchAndCacheMode: true, artifactFetcher: fetcher)); try { var dispatch = new DispatchDeployment(deploymentId, RevA, CorrelationId.NewId()); actor.Tell(dispatch); AwaitAssert(() => fetcher.Calls.ShouldBe(1), duration: PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); // Re-sends while the artifact fetch is still parked. actor.Tell(dispatch with { TargetNodes = [TestNode.Value] }); actor.Tell(dispatch with { TargetNodes = [TestNode.Value] }); fetcher.Release(); // Presence: the one apply acks... coordinator.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken) .Outcome.ShouldBe(ApplyAckOutcome.Applied); // ...absence: no second fetch, no second ack. coordinator.ExpectNoMsg(Quiet, TestContext.Current.CancellationToken); fetcher.Calls.ShouldBe(1); } finally { fetcher.Release(); } } [Fact] public void A_resend_of_a_deployment_whose_apply_FAILED_retries_the_apply_and_a_later_resend_replays_the_success() { // #1111: the first fetch fails (a central blip), the second succeeds. var db = NewInMemoryDbFactory(); var fetcher = new ScriptedFetcher(null, EmptyArtifact); var deploymentId = DeploymentId.NewId(); var coordinator = CreateTestProbe(); var actor = Sys.ActorOf(DriverHostActor.Props( db, TestNode, coordinator.Ref, localRoles: new HashSet { "driver" }, deploymentArtifactCache: new NullArtifactCache(), fetchAndCacheMode: true, artifactFetcher: fetcher)); var dispatch = new DispatchDeployment(deploymentId, RevA, CorrelationId.NewId()); actor.Tell(dispatch); coordinator.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken) .Outcome.ShouldBe(ApplyAckOutcome.Failed); // The coordinator never saw the Failed ack and re-sends: the node RETRIES rather than replaying Failed. actor.Tell(dispatch with { TargetNodes = [TestNode.Value] }); coordinator.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken) .Outcome.ShouldBe(ApplyAckOutcome.Applied); fetcher.Calls.ShouldBe(2); // A further re-send (that Applied ack lost too) replays it — the retry did not turn re-sends into re-applies. actor.Tell(dispatch with { TargetNodes = [TestNode.Value] }); coordinator.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken) .Outcome.ShouldBe(ApplyAckOutcome.Applied); coordinator.ExpectNoMsg(Quiet, TestContext.Current.CancellationToken); fetcher.Calls.ShouldBe(2); } [Fact] public void A_resend_of_an_OLDER_failed_deployment_replays_Failed_rather_than_rolling_back_a_newer_apply() { var db = NewInMemoryDbFactory(); var fetcher = new ScriptedFetcher(null, EmptyArtifact); var coordinator = CreateTestProbe(); var actor = Sys.ActorOf(DriverHostActor.Props( db, TestNode, coordinator.Ref, localRoles: new HashSet { "driver" }, deploymentArtifactCache: new NullArtifactCache(), fetchAndCacheMode: true, artifactFetcher: fetcher)); var older = new DispatchDeployment(DeploymentId.NewId(), RevA, CorrelationId.NewId()); actor.Tell(older); var failed = coordinator.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); failed.Outcome.ShouldBe(ApplyAckOutcome.Failed); // A newer deployment is applied after it. actor.Tell(new DispatchDeployment(DeploymentId.NewId(), RevisionHash.Parse(new string('b', 64)), CorrelationId.NewId())); coordinator.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken) .Outcome.ShouldBe(ApplyAckOutcome.Applied); fetcher.Calls.ShouldBe(2); // A stale re-send of the older, failed deployment: the remembered Failed is replayed, nothing is fetched. actor.Tell(older with { TargetNodes = [TestNode.Value] }); coordinator.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken) .ShouldBe(failed); coordinator.ExpectNoMsg(Quiet, TestContext.Current.CancellationToken); fetcher.Calls.ShouldBe(2); // Positive control: an ORIGINAL dispatch of that same deployment does fetch and apply, so the silence above is // the stale-retry guard, not a host that has stopped fetching. actor.Tell(older); coordinator.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken) .Outcome.ShouldBe(ApplyAckOutcome.Applied); fetcher.Calls.ShouldBe(3); } [Fact] public void A_resend_of_a_failed_deployment_is_not_retried_while_a_NEWER_applys_ack_is_still_held() { // #1111 review: the newer deployment's Applied ack is held on its address-space outcome, so the failed one is // still this node's latest ANSWER — only the held-ack guard stops the stale re-send from re-applying the older // revision over the newer one (and the newer one's held Applied ack then going out for a rolled-back node). var db = NewInMemoryDbFactory(); var fetcher = new ScriptedFetcher(null, EmptyArtifact); var coordinator = CreateTestProbe(); var publish = CreateTestProbe(); var actor = Sys.ActorOf(DriverHostActor.Props( db, TestNode, coordinator.Ref, localRoles: new HashSet { "driver" }, deploymentArtifactCache: new NullArtifactCache(), fetchAndCacheMode: true, artifactFetcher: fetcher, opcUaPublishActor: publish.Ref, applyOutcomeTimeout: TimeSpan.FromSeconds(60))); var older = new DispatchDeployment(DeploymentId.NewId(), RevA, CorrelationId.NewId()); actor.Tell(older); var failed = coordinator.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); failed.Outcome.ShouldBe(ApplyAckOutcome.Failed); // The newer deployment applies; its Applied ack is HELD (the address-space outcome has not landed). var newer = new DispatchDeployment(DeploymentId.NewId(), RevisionHash.Parse(new string('b', 64)), CorrelationId.NewId()); actor.Tell(newer); var rebuild = publish.FishForMessage(_ => true, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); rebuild.DeploymentId.ShouldBe(newer.DeploymentId); fetcher.Calls.ShouldBe(2); // A stale re-send of the older, failed deployment: replays Failed, fetches nothing, starts no rebuild. actor.Tell(older with { TargetNodes = [TestNode.Value] }); coordinator.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken) .ShouldBe(failed); coordinator.ExpectNoMsg(Quiet, TestContext.Current.CancellationToken); fetcher.Calls.ShouldBe(2); // The held ack is still the newer deployment's, and goes out clean when its outcome lands. actor.Tell(new OpcUaPublishActor.RebuildCompleted(rebuild.Correlation, rebuild.DeploymentId, false, null), publish.Ref); var ack = coordinator.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); ack.DeploymentId.ShouldBe(newer.DeploymentId); ack.Outcome.ShouldBe(ApplyAckOutcome.Applied); ack.Degraded.ShouldBeFalse(); // Positive control: an ORIGINAL dispatch of the older deployment does fetch — the silence above was the guard. actor.Tell(older); publish.FishForMessage(r => r.DeploymentId == older.DeploymentId, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); fetcher.Calls.ShouldBe(3); } [Fact] public void A_late_resend_bounds_the_address_space_wait_to_the_deadline_it_carries() { var (db, deploymentId) = SeedOneTagDeployment(); var coordinator = CreateTestProbe(); var publish = CreateTestProbe(); // A long configured wait, so a degraded ack within seconds can only be the re-send's bound. var actor = Sys.ActorOf(DriverHostActor.Props( db, TestNode, coordinator.Ref, localRoles: new HashSet { "driver" }, opcUaPublishActor: publish.Ref, applyOutcomeTimeout: TimeSpan.FromSeconds(60))); // First reached by a re-send with 17 s of central's deadline left => 17 - 15 = 2 s of address-space wait. actor.Tell(new DispatchDeployment(deploymentId, RevA, CorrelationId.NewId(), TargetNodes: [TestNode.Value], DeadlineRemaining: TimeSpan.FromSeconds(17))); publish.FishForMessage(_ => true, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); // The outcome never arrives. var ack = coordinator.ExpectMsg(TimeSpan.FromSeconds(10), cancellationToken: TestContext.Current.CancellationToken); ack.Outcome.ShouldBe(ApplyAckOutcome.Applied); ack.Degraded.ShouldBeTrue(); ack.DegradedReason.ShouldNotBeNull(); ack.DegradedReason.ShouldStartWith(DriverHostActor.OutcomeNotReportedReasonPrefix); ack.DegradedReason.ShouldContain("(2s)"); } [Fact] public void An_original_dispatch_keeps_the_full_address_space_wait() { // Positive control for the bound above: same set-up, no DeadlineRemaining — the ack stays held past the // re-send's 2 s, and is released (clean) only by the outcome. var (db, deploymentId) = SeedOneTagDeployment(); var coordinator = CreateTestProbe(); var publish = CreateTestProbe(); var actor = Sys.ActorOf(DriverHostActor.Props( db, TestNode, coordinator.Ref, localRoles: new HashSet { "driver" }, opcUaPublishActor: publish.Ref, applyOutcomeTimeout: TimeSpan.FromSeconds(60))); actor.Tell(new DispatchDeployment(deploymentId, RevA, CorrelationId.NewId())); var rebuild = publish.FishForMessage(_ => true, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); coordinator.ExpectNoMsg(TimeSpan.FromSeconds(4), TestContext.Current.CancellationToken); actor.Tell(new OpcUaPublishActor.RebuildCompleted(rebuild.Correlation, rebuild.DeploymentId, false, null), publish.Ref); var ack = coordinator.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); ack.Outcome.ShouldBe(ApplyAckOutcome.Applied); ack.Degraded.ShouldBeFalse(); } private static readonly byte[] EmptyArtifact = JsonSerializer.SerializeToUtf8Bytes(new { DriverInstances = Array.Empty() }); /// A fetcher answering each call with the next scripted result (null = "no answer"); the last repeats. private sealed class ScriptedFetcher(params byte[]?[] results) : IDeploymentArtifactFetcher { private int _calls; public int Calls => Volatile.Read(ref _calls); public Task FetchAsync(string deploymentId, string expectedRevisionHash, CancellationToken ct) { var n = Interlocked.Increment(ref _calls); return Task.FromResult(results[Math.Min(n, results.Length) - 1]); } } private (IDbContextFactory Db, DeploymentId Id) SeedOneTagDeployment() { var db = NewInMemoryDbFactory(); var id = V3ArtifactSeeder.SeedV3Deployment(db, RevA, rawTags: new[] { (Driver: "drv-1", DriverName: "Modbus", Device: "dev1", Tag: "speed", DataType: "Double", Writable: false) }, unsRefs: new[] { (Area: "filling", Line: "line1", Equip: "station1", BackingTag: "speed", Effective: (string?)null) }); return (db, id); } /// A fetcher whose first fetch parks until . private sealed class GatedFetcher(byte[] bytes) : IDeploymentArtifactFetcher { private readonly TaskCompletionSource _gate = new(TaskCreationOptions.RunContinuationsAsynchronously); private int _calls; public int Calls => Volatile.Read(ref _calls); public void Release() => _gate.TrySetResult(); public async Task FetchAsync(string deploymentId, string expectedRevisionHash, CancellationToken ct) { if (Interlocked.Increment(ref _calls) == 1) await _gate.Task.ConfigureAwait(false); return bytes; } } private sealed class NullArtifactCache : IDeploymentArtifactCache { public Task StoreAsync(string clusterId, string deploymentId, string revisionHash, byte[] artifact, CancellationToken ct = default) => Task.CompletedTask; public Task GetCurrentAsync(string clusterId, CancellationToken ct = default) => Task.FromResult(null); public Task GetCurrentUnkeyedAsync(CancellationToken ct = default) => Task.FromResult(null); } }