Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DeploymentArtifactApplyCostTests.cs
T
Joseph Doherty e967042fbb fix(runtime): #1054 the artifact hash moves off the OPC UA pinned thread; new mux readers are guarded into ConsumerRefs
#995 follow-up 1: OpcUaPublishActor still SHA-256'd every rebuild's artifact once on its pinned
thread (WithArtifactRevision). DriverHostActor already hashes the same bytes for its catalog
attempt, so it now stamps RebuildAddressSpace.ArtifactRevision at all three send sites (deploy
apply, boot-from-cache, bootstrap restore) from a per-blob ConditionalWeakTable memo (one hash
per blob instance, no lifetime extension). The publish actor's fallback hash stays for unstamped
senders and is observable through TestHooks.OnArtifactHashed.

#995 follow-up 2: DependencyMuxConsumerRegistrationGuardTests scans src for every
DependencyMuxActor.RegisterInterest sender; an unlisted one fails with the instruction to fold
its refs into DriverHostActor.ConsumerRefs, and each listed replay-opting consumer's composition
term must still appear in ConsumerRefs (mutation-checked). The historization recorder is the one
exempt, non-replay registrant.
2026-12-03 15:10:24 -05:00

134 lines
7.9 KiB
C#

using System.Text;
using System.Text.Json.Nodes;
using Akka.Actor;
using Microsoft.Extensions.Logging.Abstractions;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Commons.Types;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
using ZB.MOM.WW.OtOpcUa.Runtime.OpcUa;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers;
/// <summary>
/// Gitea #995 (review 2026-12-02 R-14): apply-time artifact work was repeated. The data projection (a full
/// deserialise of every topology table + <c>ValidateDeployed</c>) ran three times inside
/// <c>ParseDataPlaneAuthority</c> alone — even for a node with ZERO data rows, because the composer always emits the
/// three arrays — and up to four more in the driver host's catalog staging. The publish actor also re-parsed the
/// whole artifact on its pinned thread just to read the cluster's redundancy mode, and hashed it up to three times.
/// </summary>
public sealed class DeploymentArtifactApplyCostTests : RuntimeActorTestBase
{
[Fact]
public void One_data_projection_serves_every_consumer_of_one_parsed_artifact()
{
using var parsed = DeploymentArtifact.Open(GrpcDataCatalogStagingTests.Artifact());
// Exactly the calls one apply makes (DriverHostActor.StageCatalog): authority (3 row parses inside) + snapshot +
// connections + mappings + connections again.
var authority = parsed.ParseDataPlaneAuthority("node-a");
parsed.ParseLocalCatalogSnapshot("node-a").ShouldNotBeNull();
parsed.ParseDataConnections("node-a");
parsed.ParseRemoteNamespaceMappings("node-a");
parsed.ParseDataConnections("node-a");
parsed.ParseDataExports("node-a").Count.ShouldBe(1, "the projection still answers (positive control)");
authority.CatalogValid.ShouldBeTrue();
parsed.DataProjectionBuilds.ShouldBe(1);
}
[Fact]
public void An_artifact_with_empty_data_arrays_builds_no_projection_for_the_authority()
{
var root = JsonNode.Parse(GrpcDataCatalogStagingTests.Artifact())!.AsObject();
root["DataExports"] = new JsonArray();
using var parsed = DeploymentArtifact.Open(Encoding.UTF8.GetBytes(root.ToJsonString()));
var authority = parsed.ParseDataPlaneAuthority("node-a");
authority.Keys.Count.ShouldBe(1, "keys still parse (positive control)");
parsed.ParseDataConnections("node-a").ShouldBeEmpty();
parsed.ParseDataExports("node-a").ShouldBeEmpty();
parsed.ParseRemoteNamespaceMappings("node-a").ShouldBeEmpty();
parsed.DataProjectionBuilds.ShouldBe(0);
}
[Fact]
public void An_invalid_data_row_still_fails_every_row_parser_from_the_memoised_projection()
{
using var parsed = DeploymentArtifact.Open(GrpcDataCatalogStagingTests.Artifact(invalidExport: true));
Should.Throw<InvalidDataException>(() => parsed.ParseDataExports("node-a"));
Should.Throw<InvalidDataException>(() => parsed.ParseDataExports("node-a"));
parsed.ParseDataPlaneAuthority("node-a").CatalogValid.ShouldBeFalse();
parsed.DataProjectionBuilds.ShouldBe(1);
}
[Fact]
public void The_redundancy_mode_cross_check_reads_the_plan_steps_parse_not_the_actor_thread()
{
var planThread = 0;
var readThreads = new List<int>();
var hooks = new OpcUaPublishActor.TestHooks
{
BeforePlan = () => Volatile.Write(ref planThread, Environment.CurrentManagedThreadId),
OnRedundancyModeRead = id => { lock (readThreads) readThreads.Add(id); },
};
var sink = new NullSink();
var actor = Sys.ActorOf(OpcUaPublishActor.PropsForTests(
sink, new AddressSpaceApplier(sink, NullLogger<AddressSpaceApplier>.Instance), hooks,
localNode: NodeId.Parse("x:1"), redundancy: new WarmRedundancySettings(OpcUaRedundancyMode.Warm)));
var artifact = Encoding.UTF8.GetBytes("{\"Clusters\":[{\"ClusterId\":\"c1\",\"RedundancyMode\":\"None\"}],\"Nodes\":[]}");
EventFilter.Error(contains: "RedundancyMode for this node's cluster is None").ExpectOne(() =>
{
actor.Tell(new OpcUaPublishActor.RebuildAddressSpace(CorrelationId.NewId(), DeploymentId.NewId(), artifact, ReportOutcome: true));
ExpectMsg<OpcUaPublishActor.RebuildCompleted>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
}, TestContext.Current.CancellationToken);
lock (readThreads) readThreads.ShouldBe([Volatile.Read(ref planThread)], "one read, on the plan step's thread");
}
/// <summary>Gitea #1054: a rebuild that arrives stamped with its artifact's revision (as every <c>DriverHostActor</c>
/// send now is) is not hashed again on the publish actor's pinned thread; an unstamped one is hashed once (the
/// positive control — the hook does observe the fallback).</summary>
[Fact]
public void A_stamped_rebuild_is_not_hashed_on_the_publish_actor_and_an_unstamped_one_is_hashed_once()
{
var hashes = 0;
var hooks = new OpcUaPublishActor.TestHooks { OnArtifactHashed = _ => Interlocked.Increment(ref hashes) };
var sink = new NullSink();
var actor = Sys.ActorOf(OpcUaPublishActor.PropsForTests(
sink, new AddressSpaceApplier(sink, NullLogger<AddressSpaceApplier>.Instance), hooks, localNode: NodeId.Parse("x:1")));
var artifact = Encoding.UTF8.GetBytes("{\"Clusters\":[],\"Nodes\":[]}");
var revision = Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(artifact));
actor.Tell(new OpcUaPublishActor.RebuildAddressSpace(CorrelationId.NewId(), DeploymentId.NewId(), artifact,
ReportOutcome: true, ArtifactRevision: revision));
ExpectMsg<OpcUaPublishActor.RebuildCompleted>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
Volatile.Read(ref hashes).ShouldBe(0, "the stamped revision must be reused, not recomputed on the pinned thread");
actor.Tell(new OpcUaPublishActor.RebuildAddressSpace(CorrelationId.NewId(), DeploymentId.NewId(), artifact, ReportOutcome: true));
ExpectMsg<OpcUaPublishActor.RebuildCompleted>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
Volatile.Read(ref hashes).ShouldBe(1, "an unstamped request is hashed exactly once");
}
private sealed class NullSink : IOpcUaAddressSpaceSink
{
public void WriteValue(string nodeId, object? value, uint statusCode, DateTime ts, AddressSpaceRealm realm) { }
public void WriteAlarmQuality(string alarmNodeId, uint statusCode, DateTime ts, AddressSpaceRealm realm) { }
public void WriteAlarmCondition(string alarmNodeId, AlarmConditionSnapshot state, DateTime ts, AddressSpaceRealm realm) { }
public void MaterialiseAlarmCondition(string alarmNodeId, string equipmentNodeId, string displayName, string alarmType, int severity, AddressSpaceRealm realm, bool isNative = false) { }
public void EnsureFolder(string folderNodeId, string? parentNodeId, string displayName, AddressSpaceRealm realm) { }
public void EnsureVariable(string variableNodeId, string? parentFolderNodeId, string displayName, string dataType, bool writable, AddressSpaceRealm realm, string? historianTagname = null, bool isArray = false, uint? arrayLength = null, bool refuseArrayOnScalar = false) { }
public void RebuildAddressSpace() { }
public void RaiseNodesAddedModelChange(string affectedNodeId, AddressSpaceRealm realm) { }
public void WireAlarmNotifiers(string alarmNodeId, AddressSpaceRealm alarmRealm, IReadOnlyList<string> notifierFolderNodeIds, AddressSpaceRealm notifierFolderRealm) { }
public void AddReference(string sourceNodeId, AddressSpaceRealm sourceRealm, string targetNodeId, AddressSpaceRealm targetRealm, string referenceType = "Organizes") { }
}
}