Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/DataConnections/GrpcDataArtifactProjectionTests.cs
T
2026-11-23 09:55:03 -05:00

229 lines
11 KiB
C#

using System.IO.Compression;
using System.Text;
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using Shouldly;
using Xunit;
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.Configuration.Validation;
using ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Tests.DataConnections;
[Trait("Category", "Unit")]
[Trait("Feature", "GrpcData")]
[Trait("Phase", "P02")]
public sealed class GrpcDataArtifactProjectionTests
{
private const string NodeA = "node-a:4840";
private const string NodeB = "node-b:4840";
private static readonly DateTime Timestamp = new(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc);
[Fact]
public void New_collections_and_nested_sets_have_stable_bytes_independent_of_enumeration()
{
var first = Snapshot();
var second = Snapshot(reverse: true);
first.DataConnections.Count.ShouldBe(2);
first.DataConnections[0].ConsumerNodeIds.Count.ShouldBe(2);
var a = ConfigComposer.Compose(first);
var b = ConfigComposer.Compose(second);
a.Blob.ShouldBe(b.Blob);
a.RevisionHash.ShouldBe(b.RevisionHash);
using var json = JsonDocument.Parse(Inflate(a.Blob));
json.RootElement.GetProperty("DataConnections").EnumerateArray()
.Select(x => x.GetProperty("DataConnectionId").GetString()).ShouldBe(["connection-a", "connection-z"]);
json.RootElement.GetProperty("DataExports").EnumerateArray()
.Select(x => x.GetProperty("DataExportId").GetString()).ShouldBe(["export-a", "export-z"]);
json.RootElement.GetProperty("RemoteNamespaceMappings").EnumerateArray()
.Select(x => x.GetProperty("RemoteNamespaceMappingId").GetString()).ShouldBe(["mapping-a", "mapping-z"]);
}
[Fact]
public void Ordered_endpoint_preference_is_preserved_and_changes_the_revision()
{
var first = Snapshot();
var second = Snapshot();
second.DataConnections[0].Endpoints.Reverse();
var a = ConfigComposer.Compose(first);
var b = ConfigComposer.Compose(second);
b.RevisionHash.ShouldNotBe(a.RevisionHash);
DeploymentArtifact.ParseDataConnections(a.Blob, NodeA).Single(x => x.DataConnectionId == "connection-a")
.Endpoints.ShouldBe(["https://node-b:7443", "https://node-b-backup:7443"]);
}
[Theory]
[InlineData("connection")]
[InlineData("export")]
[InlineData("mapping")]
[InlineData("connection-revision")]
[InlineData("export-revision")]
[InlineData("mapping-revision")]
[InlineData("grant")]
[InlineData("mapping-acl")]
[InlineData("maintenance")]
public void Disable_revision_authority_and_maintenance_edits_change_the_deployed_hash(string edit)
{
var before = Snapshot();
var after = Snapshot();
switch (edit)
{
case "connection": after.DataConnections[0].Enabled = false; break;
case "export": after.DataExports[0].Enabled = false; break;
case "mapping": after.RemoteNamespaceMappings[0].Enabled = false; break;
case "connection-revision": after.DataConnections[0].Revision++; break;
case "export-revision": after.DataExports[0].Revision++; break;
case "mapping-revision": after.RemoteNamespaceMappings[0].Revision++; break;
case "grant": after.DataExports[0].AllowedOperations = DataOperations.Browse; break;
case "mapping-acl": after.NodeAcls[0].PermissionFlags = NodePermissions.Browse; break;
case "maintenance": after.ClusterNodes[1].MaintenanceMode = true; break;
default: throw new ArgumentOutOfRangeException(nameof(edit));
}
ConfigComposer.Compose(after).RevisionHash.ShouldNotBe(ConfigComposer.Compose(before).RevisionHash);
}
[Fact]
public void Connection_credentials_serialize_as_references_while_existing_api_key_hashes_survive()
{
var artifact = ConfigComposer.Compose(Snapshot());
using var json = JsonDocument.Parse(Inflate(artifact.Blob));
var connection = json.RootElement.GetProperty("DataConnections")[0];
connection.GetProperty("SecretReference").GetString().ShouldBe("secret:data/upstream");
connection.GetProperty("SecretScopeClusterId").GetString().ShouldBe("cluster-local");
connection.EnumerateObject().Select(p => p.Name).ShouldNotContain("Secret");
connection.EnumerateObject().Select(p => p.Name).ShouldNotContain("ApiKey");
connection.EnumerateObject().Select(p => p.Name).ShouldNotContain("PresentedSecret");
json.RootElement.GetProperty("ApiKeys")[0].GetProperty("SecretHash").GetString()
.ShouldBe("existing-peppered-hash");
DeploymentArtifact.ParseDataConnections(artifact.Blob, NodeA).ShouldAllBe(c => c.SecretReference == "secret:data/upstream");
}
[Fact]
public void Composed_A_only_same_cluster_connection_and_mount_are_absent_on_B()
{
var snapshot = Snapshot();
foreach (var connection in snapshot.DataConnections)
{
connection.ConsumerNodeIds = [NodeA];
connection.TargetMode = DataTargetMode.Node;
connection.ExpectedClusterId = "cluster-local";
connection.ExpectedNodeId = NodeB;
connection.EligibleTargetNodeIds = [];
connection.Endpoints = ["https://node-b:7443"];
}
foreach (var mapping in snapshot.RemoteNamespaceMappings) mapping.ConsumerNodeIds = [NodeA];
var blob = ConfigComposer.Compose(snapshot).Blob;
DeploymentArtifact.ParseDataConnections(blob, NodeA).Count.ShouldBe(2);
DeploymentArtifact.ParseRemoteNamespaceMappings(blob, NodeA).Count.ShouldBe(2);
DeploymentArtifact.ParseDataConnections(blob, NodeB).ShouldBeEmpty();
DeploymentArtifact.ParseRemoteNamespaceMappings(blob, NodeB).ShouldBeEmpty();
DeploymentArtifact.ParseDataConnections(blob, "unlisted:4840").ShouldBeEmpty();
DeploymentArtifact.ParseRemoteNamespaceMappings(blob, "unlisted:4840").ShouldBeEmpty();
DeploymentArtifact.ParseDataExports(blob, "unlisted:4840").ShouldBeEmpty();
}
[Fact]
public async Task Database_snapshot_carries_all_three_new_collections_into_the_artifact()
{
var options = new DbContextOptionsBuilder<OtOpcUaConfigDbContext>()
.UseInMemoryDatabase(Guid.NewGuid().ToString("N")).Options;
await using var db = new OtOpcUaConfigDbContext(options);
var snapshot = Snapshot();
db.ServerClusters.AddRange(snapshot.ServerClusters);
db.ClusterNodes.AddRange(snapshot.ClusterNodes);
db.RawFolders.AddRange(snapshot.RawFolders);
db.DataConnections.AddRange(snapshot.DataConnections);
db.DataExports.AddRange(snapshot.DataExports);
db.RemoteNamespaceMappings.AddRange(snapshot.RemoteNamespaceMappings);
await db.SaveChangesAsync(TestContext.Current.CancellationToken);
var artifact = await ConfigComposer.SnapshotAndFlattenAsync(db, TestContext.Current.CancellationToken);
DeploymentArtifact.ParseDataConnections(artifact.Blob, NodeA).Select(x => x.DataConnectionId).ShouldBe(["connection-a", "connection-z"]);
DeploymentArtifact.ParseDataExports(artifact.Blob, NodeA).Select(x => x.DataExportId).ShouldBe(["export-a", "export-z"]);
DeploymentArtifact.ParseRemoteNamespaceMappings(artifact.Blob, NodeA).Select(x => x.RemoteNamespaceMappingId).ShouldBe(["mapping-a", "mapping-z"]);
}
private static DraftSnapshot Snapshot(bool reverse = false)
{
var connections = new[] { Connection("connection-a"), Connection("connection-z") };
var mappings = new[] { Mapping("mapping-a", "connection-a"), Mapping("mapping-z", "connection-z") };
var exports = new[] { Export("export-a"), Export("export-z") };
if (reverse)
{
Array.Reverse(connections);
Array.Reverse(mappings);
Array.Reverse(exports);
foreach (var connection in connections)
{
connection.ConsumerNodeIds.Reverse();
connection.EligibleTargetNodeIds.Reverse();
}
foreach (var mapping in mappings) mapping.ConsumerNodeIds.Reverse();
}
return new DraftSnapshot
{
GenerationId = 0, ClusterId = "cluster-local",
ServerClusters = [new ServerCluster { ClusterId = "cluster-local", Name = "local", Enterprise = "ent", Site = "site",
RedundancyMode = RedundancyMode.None, CreatedBy = "test", CreatedAt = Timestamp }],
ClusterNodes = [Node(NodeA), Node(NodeB)],
RawFolders = [new RawFolder { RawFolderId = "local-root", ClusterId = "cluster-local", Name = "Local" }],
DataConnections = connections, DataExports = exports, RemoteNamespaceMappings = mappings,
NodeAcls = [new NodeAcl { NodeAclId = "mapping-grant", ClusterId = "cluster-local", Principal = "viewer",
ScopeKind = NodeAclScopeKind.RemoteNamespaceMapping, ScopeId = "mapping-a", PermissionFlags = NodePermissions.Read }],
ApiKeys = [new ApiKey { ApiKeyRowId = Guid.Empty, ApiKeyId = "key", Name = "key", Principal = "peer",
SecretHash = "existing-peppered-hash", CreatedUtc = Timestamp }],
};
}
private static ClusterNode Node(string id) => new()
{
NodeId = id, ClusterId = "cluster-local", Host = id.Split(':')[0], ApplicationUri = "urn:" + id,
CreatedAt = Timestamp, CreatedBy = "test",
};
private static DataConnection Connection(string id) => new()
{
DataConnectionId = id, ClusterId = "cluster-local", Enabled = true,
ConsumerNodeIds = [NodeA, NodeB], TargetMode = DataTargetMode.Cluster,
ExpectedClusterId = "cluster-remote", EligibleTargetNodeIds = ["remote-a", "remote-b"],
Endpoints = ["https://node-b:7443", "https://node-b-backup:7443"],
SecretReference = "secret:data/upstream", SecretScopeClusterId = "cluster-local",
AllowedOperations = DataOperations.Browse | DataOperations.Read,
};
private static RemoteNamespaceMapping Mapping(string id, string connectionId) => new()
{
RemoteNamespaceMappingId = id, ClusterId = "cluster-local", DataConnectionId = connectionId,
Enabled = true, ConsumerNodeIds = [NodeA, NodeB], Realm = DataRealm.Raw, RemoteRealm = DataRealm.Raw,
LocalParentKind = "RawFolder", LocalParentId = "local-root", BranchName = id,
RemoteRootEntityId = "remote-root", RemoteNamespaceUri = "https://zb.com/otopcua/raw", RemoteIdentifierKind = "string",
RemoteIdentifier = "remote-root", AllowedOperations = DataOperations.Browse,
};
private static DataExport Export(string id) => new()
{
DataExportId = id, ClusterId = "cluster-local", Enabled = true, Realm = DataRealm.Raw,
RootKind = "RawFolder", RootEntityId = "local-root", PrincipalId = "peer",
AllowedOperations = DataOperations.Browse | DataOperations.Read,
};
private static string Inflate(byte[] blob)
{
using var gzip = new GZipStream(new MemoryStream(blob), CompressionMode.Decompress);
using var reader = new StreamReader(gzip, Encoding.UTF8);
return reader.ReadToEnd();
}
}