Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorRedispatchTests.cs
T
Joseph Doherty 323bbd2a63 fix(deploy): #1107 re-send the deploy dispatch to nodes that have not acked
ConfigPublishCoordinator dispatched a deployment exactly once: on DPS a node whose
deployments registry entry had not gossiped to central missed it (#1106), on gRPC a
failed dial was dropped, and either way the deployment timed out at 120 s.

Coordinator: re-sends the same DispatchDeployment at +5/+15/+35 s (bounded by half the
remaining deadline) with the new additive TargetNodes naming only expected nodes whose
ack has not arrived (an ack still being persisted counts). Stops on last ack,
completion, time-out, supersede or schedule end; a recovered in-flight deployment gets
the same re-send. Counter otopcua.deploy.redispatched.

Transport: CentralCommunicationActor's gRPC fan dials only the named nodes; proto gains
repeated target_nodes = 4 (additive). On DPS, non-addressed nodes ignore the re-send.

Node (DriverHostActor): a re-send is idempotent per DeploymentId — ignored if not
addressed here or mid-apply; ANY copy of a deployment whose Applied ack is held on the
address-space outcome no longer starts a second apply; a re-send of a deployment it
already acked re-delivers the remembered ack (last 16) instead of re-applying (#601
would otherwise re-apply a degraded revision). Original dispatches are unchanged.

Docs: Redundancy.md §Dispatch re-send, Configuration.md, cluster-topology rule.
2026-12-04 22:29:17 -05:00

186 lines
9.5 KiB
C#

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;
/// <summary>
/// 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.
/// </summary>
[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<string> { "driver" },
opcUaPublishActor: publish.Ref));
var dispatch = new DispatchDeployment(deploymentId, RevA, CorrelationId.NewId());
actor.Tell(dispatch);
var rebuild = publish.FishForMessage<OpcUaPublishActor.RebuildAddressSpace>(_ => true, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
publish.Reply(new OpcUaPublishActor.RebuildCompleted(rebuild.Correlation, rebuild.DeploymentId, true, "failedNodes=1"));
var first = coordinator.ExpectMsg<ApplyAck>(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<ApplyAck>(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<OpcUaPublishActor.RebuildAddressSpace>(_ => 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<string> { "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<OpcUaPublishActor.RebuildAddressSpace>(_ => true, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
publish.Reply(new OpcUaPublishActor.RebuildCompleted(rebuild.Correlation, rebuild.DeploymentId, false, null));
coordinator.ExpectMsg<ApplyAck>(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<string> { "driver" },
opcUaPublishActor: publish.Ref));
var dispatch = new DispatchDeployment(deploymentId, RevA, CorrelationId.NewId());
actor.Tell(dispatch);
var rebuild = publish.FishForMessage<OpcUaPublishActor.RebuildAddressSpace>(_ => 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<ApplyAck>(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<object>() }));
var deploymentId = DeploymentId.NewId();
var coordinator = CreateTestProbe();
var actor = Sys.ActorOf(DriverHostActor.Props(
db, TestNode, coordinator.Ref,
localRoles: new HashSet<string> { "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<ApplyAck>(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();
}
}
private (IDbContextFactory<OtOpcUaConfigDbContext> 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);
}
/// <summary>A fetcher whose first fetch parks until <see cref="Release"/>.</summary>
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<byte[]?> 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<CachedDeploymentArtifact?> GetCurrentAsync(string clusterId, CancellationToken ct = default)
=> Task.FromResult<CachedDeploymentArtifact?>(null);
public Task<CachedDeploymentArtifact?> GetCurrentUnkeyedAsync(CancellationToken ct = default)
=> Task.FromResult<CachedDeploymentArtifact?>(null);
}
}