using Akka.Actor; using Microsoft.EntityFrameworkCore; using Shouldly; using Xunit; 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.Configuration.Entities; using ZB.MOM.WW.OtOpcUa.Configuration.Enums; 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.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 #977 — deploy bookkeeping on the driver host: R-1 (a restart after a FAILED deploy must serve the last /// APPLIED deployment, not boot empty) and R-15 (an apply that throws part-way must not leave its revision looking /// cleanly served, so a re-dispatch re-applies). /// public sealed class DriverHostActorDeployBookkeepingTests : RuntimeActorTestBase { private static readonly NodeId TestNode = NodeId.Parse("driver-test"); private static readonly RevisionHash RevA = RevisionHash.Parse(new string('a', 64)); private static readonly RevisionHash RevB = RevisionHash.Parse(new string('b', 64)); [Fact] public void A_restart_after_a_failed_deploy_restores_the_last_applied_deployment() { var db = NewInMemoryDbFactory(); var a = Seed(db, RevA, "speed"); var b = Seed(db, RevB, "pressure"); var t0 = DateTime.UtcNow.AddMinutes(-10); AddNodeRow(db, a, NodeDeploymentStatus.Applied, t0); AddNodeRow(db, b, NodeDeploymentStatus.Failed, t0.AddMinutes(5), "apply threw"); // NEWER, failed var publish = CreateTestProbe(); var coordinator = CreateTestProbe(); var host = Sys.ActorOf(DriverHostActor.Props( db, TestNode, coordinator.Ref, localRoles: new HashSet { "driver" }, opcUaPublishActor: publish.Ref)); // The address space is rebuilt from A's artifact — before the fix the Failed arm went straight to an empty Steady. var rebuild = publish.FishForMessage( m => m.DeploymentId == a, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); rebuild.Artifact.ShouldBe(ArtifactOf(db, a)); // And A is the CURRENT revision: a re-dispatch of A is the idempotent clean ack, not a re-apply. host.Tell(new DispatchDeployment(a, RevA, CorrelationId.NewId())); coordinator.FishForMessage(m => m.DeploymentId == a, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken).Outcome.ShouldBe(ApplyAckOutcome.Applied); } [Fact] public void A_newest_applied_row_is_restored_exactly_as_before() { // Positive control for the selection above: the ordinary Applied-newest boot is unchanged. var db = NewInMemoryDbFactory(); var a = Seed(db, RevA, "speed"); AddNodeRow(db, a, NodeDeploymentStatus.Applied, DateTime.UtcNow); var publish = CreateTestProbe(); Sys.ActorOf(DriverHostActor.Props( db, TestNode, CreateTestProbe().Ref, localRoles: new HashSet { "driver" }, opcUaPublishActor: publish.Ref)); publish.FishForMessage( m => m.DeploymentId == a, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); } [Fact] public void A_failed_only_history_falls_back_to_the_node_local_cache() { var db = NewInMemoryDbFactory(); var b = Seed(db, RevB, "pressure"); AddNodeRow(db, b, NodeDeploymentStatus.Failed, DateTime.UtcNow, "apply threw"); var cachedBytes = ArtifactOf(db, b); var cachedId = DeploymentId.NewId(); var cache = new FixedCache(new CachedDeploymentArtifact( cachedId.ToString(), RevA.Value, cachedBytes, DateTimeOffset.UtcNow)); var publish = CreateTestProbe(); Sys.ActorOf(DriverHostActor.Props( db, TestNode, CreateTestProbe().Ref, localRoles: new HashSet { "driver" }, opcUaPublishActor: publish.Ref, deploymentArtifactCache: cache)); publish.FishForMessage( m => m.DeploymentId == cachedId, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); } [Fact] public void An_apply_that_throws_after_reconcile_leaves_its_revision_unconfirmed_so_a_redispatch_reapplies() { var db = NewInMemoryDbFactory(); var a = Seed(db, RevA, "speed"); var throwOnce = 1; var catalog = new LocalCatalogCoordinator(new CatalogActivation(), new DataPlaneAuthorityState(), () => new ServingIdentity(TestNode.Value, "process-1", "Primary", 0, 0)); catalog.BeforeSubscriptionApplyForTests = () => { if (Interlocked.Exchange(ref throwOnce, 0) == 1) throw new InvalidOperationException("subscription work failed"); }; var publish = CreateTestProbe(); var coordinator = CreateTestProbe(); var host = Sys.ActorOf(DriverHostActor.Props( db, TestNode, coordinator.Ref, localRoles: new HashSet { "driver" }, opcUaPublishActor: publish.Ref, catalogCoordinator: catalog)); host.Tell(new DispatchDeployment(a, RevA, CorrelationId.NewId())); coordinator.FishForMessage(m => m.DeploymentId == a, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken).Outcome.ShouldBe(ApplyAckOutcome.Failed); // Same revision again: it was never served, so it must RE-APPLY (an outcome-reporting rebuild), not short-circuit // to an immediate clean Applied. host.Tell(new DispatchDeployment(a, RevA, CorrelationId.NewId())); publish.FishForMessage( m => m.DeploymentId == a && m.ReportOutcome, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); } private static DeploymentId Seed(IDbContextFactory db, RevisionHash rev, string tag) => V3ArtifactSeeder.SeedV3Deployment(db, rev, rawTags: new[] { (Driver: "drv-1", DriverName: "Modbus", Device: "dev1", Tag: tag, DataType: "Double", Writable: false) }, unsRefs: new[] { (Area: "filling", Line: "line1", Equip: "station1", BackingTag: tag, Effective: (string?)null) }); private static void AddNodeRow(IDbContextFactory db, DeploymentId id, NodeDeploymentStatus status, DateTime startedAtUtc, string? reason = null) { using var ctx = db.CreateDbContext(); ctx.NodeDeploymentStates.Add(new NodeDeploymentState { NodeId = TestNode.Value, DeploymentId = id.Value, Status = status, StartedAtUtc = startedAtUtc, AppliedAtUtc = status == NodeDeploymentStatus.Applied ? startedAtUtc : null, FailureReason = reason, }); ctx.SaveChanges(); } private static byte[] ArtifactOf(IDbContextFactory db, DeploymentId id) { using var ctx = db.CreateDbContext(); return ctx.Deployments.Single(d => d.DeploymentId == id.Value).ArtifactBlob!; } private sealed class FixedCache(CachedDeploymentArtifact artifact) : IDeploymentArtifactCache { public Task StoreAsync(string clusterId, string deploymentId, string revisionHash, byte[] bytes, CancellationToken ct = default) => Task.CompletedTask; public Task GetCurrentAsync(string clusterId, CancellationToken ct = default) => Task.FromResult(artifact); public Task GetCurrentUnkeyedAsync(CancellationToken ct = default) => Task.FromResult(artifact); } }