feat: deploy scoped grpc data connection configuration

This commit is contained in:
Joseph Doherty
2026-11-15 22:46:12 -05:00
parent a323373a45
commit d5b3653012
20 changed files with 4190 additions and 6 deletions
@@ -0,0 +1,32 @@
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Configuration.Entities;
/// <summary>A directional, node-scoped connection to an expected data-service identity.</summary>
public sealed class DataConnection
{
public Guid DataConnectionRowId { get; set; }
public string DataConnectionId { get; set; } = "";
public string ClusterId { get; set; } = "";
public long Revision { get; set; } = 1;
public bool Enabled { get; set; }
public List<string> ConsumerNodeIds { get; set; } = [];
public DataTargetMode TargetMode { get; set; }
public DataConsistency Consistency { get; set; } = DataConsistency.Primary;
public string ExpectedClusterId { get; set; } = "";
public string? ExpectedNodeId { get; set; }
public List<string> EligibleTargetNodeIds { get; set; } = [];
public List<string> Endpoints { get; set; } = [];
/// <summary>Non-secret reference; its value is resolved on consumer nodes.</summary>
public string SecretReference { get; set; } = "";
public string SecretScopeClusterId { get; set; } = "";
public DataOperations AllowedOperations { get; set; }
public int TimeoutMilliseconds { get; set; } = 5000;
public int MaxBatchItems { get; set; } = 1000;
public int MaxPageItems { get; set; } = 500;
public int MaxMessageBytes { get; set; } = 4 * 1024 * 1024;
public int MaxStreams { get; set; } = 100;
public int MaxMonitoredItems { get; set; } = 10000;
public long MaxPendingBytes { get; set; } = 4 * 1024 * 1024;
public byte[] RowVersion { get; set; } = [];
}
@@ -0,0 +1,23 @@
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Configuration.Entities;
/// <summary>Origin-local export grant for a named authenticated peer principal.</summary>
public sealed class DataExport
{
public Guid DataExportRowId { get; set; }
public string DataExportId { get; set; } = "";
public string ClusterId { get; set; } = "";
public long Revision { get; set; } = 1;
public bool Enabled { get; set; }
public DataRealm Realm { get; set; }
public string RootKind { get; set; } = "";
public string RootEntityId { get; set; } = "";
public string PrincipalId { get; set; } = "";
public DataOperations AllowedOperations { get; set; }
public int MaxBatchItems { get; set; } = 1000;
public int MaxPageItems { get; set; } = 500;
public int MaxMonitoredItems { get; set; } = 10000;
public int MaxStreams { get; set; } = 100;
public byte[] RowVersion { get; set; } = [];
}
@@ -0,0 +1,36 @@
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Configuration.Entities;
/// <summary>A local realm-qualified branch projection, not a synthetic locally owned tag.</summary>
public sealed class RemoteNamespaceMapping
{
public Guid RemoteNamespaceMappingRowId { get; set; }
public string RemoteNamespaceMappingId { get; set; } = "";
public string ClusterId { get; set; } = "";
public string DataConnectionId { get; set; } = "";
public long Revision { get; set; } = 1;
public bool Enabled { get; set; }
public List<string> ConsumerNodeIds { get; set; } = [];
public DataRealm Realm { get; set; }
public DataRealm RemoteRealm { get; set; }
public string LocalParentKind { get; set; } = "";
public string LocalParentId { get; set; } = "";
public string BranchName { get; set; } = "";
public string RemoteRootEntityId { get; set; } = "";
public string RemoteNamespaceUri { get; set; } = "";
public string RemoteIdentifierKind { get; set; } = "";
public string RemoteIdentifier { get; set; } = "";
/// <summary>Optional leaf type expectation; branch types are verified as catalog metadata arrives.</summary>
public DataValueKind? ExpectedValueKind { get; set; }
public DataValueKind? ExpectedArrayElementKind { get; set; }
public DataOperations AllowedOperations { get; set; }
public bool WriteThrough { get; set; }
public int MaxProjectionNodes { get; set; } = 10000;
public int MaxProjectionDepth { get; set; } = 32;
public int MetadataLeaseMilliseconds { get; set; } = 15000;
public int StaleTimeoutMilliseconds { get; set; } = 30000;
public int SamplingIntervalMilliseconds { get; set; } = 1000;
public int PublishingIntervalMilliseconds { get; set; } = 1000;
public byte[] RowVersion { get; set; } = [];
}
@@ -3,7 +3,7 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Enums;
/// <summary>ACL scope level. Per <c>acl-design.md</c> §"Scope Hierarchy".</summary>
/// <remarks>
/// ⚠️ <b>Append new members only — never insert.</b> SQL Server stores this as a string
/// (<c>nvarchar(16)</c>, so a member name must also stay ≤ 16 characters), but the deployment
/// (<c>nvarchar(32)</c>, so a member name must also stay ≤ 32 characters), but the deployment
/// artifact serialises it as the <b>integer ordinal</b> and the node-side decoder reads it back
/// with <c>Enum.IsDefined</c>. Inserting a member mid-enum silently re-maps every grant in every
/// already-deployed artifact to a different scope level.
@@ -59,4 +59,7 @@ public enum NodeAclScopeKind
/// <summary>A raw-tree tag group. <c>ScopeId</c> is a <c>TagGroup.TagGroupId</c>. (v3; appended.)</summary>
RawTagGroup,
/// <summary>A realm-qualified remote mapping, scoped by its logical ID.</summary>
RemoteNamespaceMapping,
}
@@ -0,0 +1,195 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations
{
/// <inheritdoc />
public partial class AddGrpcDataConnections : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<string>(
name: "ScopeKind",
table: "NodeAcl",
type: "nvarchar(32)",
maxLength: 32,
nullable: false,
oldClrType: typeof(string),
oldType: "nvarchar(16)",
oldMaxLength: 16);
migrationBuilder.CreateTable(
name: "DataConnection",
columns: table => new
{
DataConnectionRowId = table.Column<Guid>(type: "uniqueidentifier", nullable: false, defaultValueSql: "NEWSEQUENTIALID()"),
DataConnectionId = table.Column<string>(type: "nvarchar(64)", maxLength: 64, nullable: true),
ClusterId = table.Column<string>(type: "nvarchar(64)", maxLength: 64, nullable: false),
Revision = table.Column<long>(type: "bigint", nullable: false),
Enabled = table.Column<bool>(type: "bit", nullable: false),
ConsumerNodeIds = table.Column<string>(type: "nvarchar(max)", nullable: false),
TargetMode = table.Column<int>(type: "int", nullable: false),
Consistency = table.Column<int>(type: "int", nullable: false),
ExpectedClusterId = table.Column<string>(type: "nvarchar(64)", maxLength: 64, nullable: false),
ExpectedNodeId = table.Column<string>(type: "nvarchar(64)", maxLength: 64, nullable: true),
EligibleTargetNodeIds = table.Column<string>(type: "nvarchar(max)", nullable: false),
Endpoints = table.Column<string>(type: "nvarchar(max)", nullable: false),
SecretReference = table.Column<string>(type: "nvarchar(512)", maxLength: 512, nullable: false),
SecretScopeClusterId = table.Column<string>(type: "nvarchar(64)", maxLength: 64, nullable: false),
AllowedOperations = table.Column<int>(type: "int", nullable: false),
TimeoutMilliseconds = table.Column<int>(type: "int", nullable: false),
MaxBatchItems = table.Column<int>(type: "int", nullable: false),
MaxPageItems = table.Column<int>(type: "int", nullable: false),
MaxMessageBytes = table.Column<int>(type: "int", nullable: false),
MaxStreams = table.Column<int>(type: "int", nullable: false),
MaxMonitoredItems = table.Column<int>(type: "int", nullable: false),
MaxPendingBytes = table.Column<long>(type: "bigint", nullable: false),
RowVersion = table.Column<byte[]>(type: "rowversion", rowVersion: true, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_DataConnection", x => x.DataConnectionRowId);
table.CheckConstraint("CK_DataConnection_Limits", "[Revision] > 0 AND [TimeoutMilliseconds] > 0 AND [MaxBatchItems] > 0 AND [MaxPageItems] > 0 AND [MaxMessageBytes] > 0 AND [MaxStreams] > 0 AND [MaxMonitoredItems] > 0 AND [MaxPendingBytes] > 0");
table.ForeignKey(
name: "FK_DataConnection_ServerCluster_ClusterId",
column: x => x.ClusterId,
principalTable: "ServerCluster",
principalColumn: "ClusterId",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "DataExport",
columns: table => new
{
DataExportRowId = table.Column<Guid>(type: "uniqueidentifier", nullable: false, defaultValueSql: "NEWSEQUENTIALID()"),
DataExportId = table.Column<string>(type: "nvarchar(64)", maxLength: 64, nullable: true),
ClusterId = table.Column<string>(type: "nvarchar(64)", maxLength: 64, nullable: false),
Revision = table.Column<long>(type: "bigint", nullable: false),
Enabled = table.Column<bool>(type: "bit", nullable: false),
Realm = table.Column<int>(type: "int", nullable: false),
RootKind = table.Column<string>(type: "nvarchar(32)", maxLength: 32, nullable: false),
RootEntityId = table.Column<string>(type: "nvarchar(64)", maxLength: 64, nullable: false),
PrincipalId = table.Column<string>(type: "nvarchar(128)", maxLength: 128, nullable: false),
AllowedOperations = table.Column<int>(type: "int", nullable: false),
MaxBatchItems = table.Column<int>(type: "int", nullable: false),
MaxPageItems = table.Column<int>(type: "int", nullable: false),
MaxMonitoredItems = table.Column<int>(type: "int", nullable: false),
MaxStreams = table.Column<int>(type: "int", nullable: false),
RowVersion = table.Column<byte[]>(type: "rowversion", rowVersion: true, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_DataExport", x => x.DataExportRowId);
table.CheckConstraint("CK_DataExport_Limits", "[Revision] > 0 AND [MaxBatchItems] > 0 AND [MaxPageItems] > 0 AND [MaxMonitoredItems] > 0 AND [MaxStreams] > 0");
table.ForeignKey(
name: "FK_DataExport_ServerCluster_ClusterId",
column: x => x.ClusterId,
principalTable: "ServerCluster",
principalColumn: "ClusterId",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "RemoteNamespaceMapping",
columns: table => new
{
RemoteNamespaceMappingRowId = table.Column<Guid>(type: "uniqueidentifier", nullable: false, defaultValueSql: "NEWSEQUENTIALID()"),
RemoteNamespaceMappingId = table.Column<string>(type: "nvarchar(64)", maxLength: 64, nullable: true),
ClusterId = table.Column<string>(type: "nvarchar(64)", maxLength: 64, nullable: false),
DataConnectionId = table.Column<string>(type: "nvarchar(64)", maxLength: 64, nullable: false),
Revision = table.Column<long>(type: "bigint", nullable: false),
Enabled = table.Column<bool>(type: "bit", nullable: false),
ConsumerNodeIds = table.Column<string>(type: "nvarchar(max)", nullable: false),
Realm = table.Column<int>(type: "int", nullable: false),
RemoteRealm = table.Column<int>(type: "int", nullable: false),
LocalParentKind = table.Column<string>(type: "nvarchar(32)", maxLength: 32, nullable: false),
LocalParentId = table.Column<string>(type: "nvarchar(64)", maxLength: 64, nullable: false),
BranchName = table.Column<string>(type: "nvarchar(128)", maxLength: 128, nullable: false),
RemoteRootEntityId = table.Column<string>(type: "nvarchar(64)", maxLength: 64, nullable: false),
RemoteNamespaceUri = table.Column<string>(type: "nvarchar(512)", maxLength: 512, nullable: false),
RemoteIdentifierKind = table.Column<string>(type: "nvarchar(32)", maxLength: 32, nullable: false),
RemoteIdentifier = table.Column<string>(type: "nvarchar(512)", maxLength: 512, nullable: false),
ExpectedValueKind = table.Column<int>(type: "int", nullable: true),
ExpectedArrayElementKind = table.Column<int>(type: "int", nullable: true),
AllowedOperations = table.Column<int>(type: "int", nullable: false),
WriteThrough = table.Column<bool>(type: "bit", nullable: false),
MaxProjectionNodes = table.Column<int>(type: "int", nullable: false),
MaxProjectionDepth = table.Column<int>(type: "int", nullable: false),
MetadataLeaseMilliseconds = table.Column<int>(type: "int", nullable: false),
StaleTimeoutMilliseconds = table.Column<int>(type: "int", nullable: false),
SamplingIntervalMilliseconds = table.Column<int>(type: "int", nullable: false),
PublishingIntervalMilliseconds = table.Column<int>(type: "int", nullable: false),
RowVersion = table.Column<byte[]>(type: "rowversion", rowVersion: true, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_RemoteNamespaceMapping", x => x.RemoteNamespaceMappingRowId);
table.CheckConstraint("CK_RemoteNamespaceMapping_Limits", "[Revision] > 0 AND [MaxProjectionNodes] > 0 AND [MaxProjectionDepth] > 0 AND [MetadataLeaseMilliseconds] > 0 AND [StaleTimeoutMilliseconds] > 0 AND [SamplingIntervalMilliseconds] > 0 AND [PublishingIntervalMilliseconds] > 0");
table.ForeignKey(
name: "FK_RemoteNamespaceMapping_ServerCluster_ClusterId",
column: x => x.ClusterId,
principalTable: "ServerCluster",
principalColumn: "ClusterId",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_DataConnection_ClusterId",
table: "DataConnection",
column: "ClusterId");
migrationBuilder.CreateIndex(
name: "IX_DataConnection_DataConnectionId",
table: "DataConnection",
column: "DataConnectionId",
unique: true,
filter: "[DataConnectionId] IS NOT NULL");
migrationBuilder.CreateIndex(
name: "IX_DataExport_ClusterId",
table: "DataExport",
column: "ClusterId");
migrationBuilder.CreateIndex(
name: "IX_DataExport_DataExportId",
table: "DataExport",
column: "DataExportId",
unique: true,
filter: "[DataExportId] IS NOT NULL");
migrationBuilder.CreateIndex(
name: "IX_RemoteNamespaceMapping_ClusterId_Realm_LocalParentKind_LocalParentId_BranchName",
table: "RemoteNamespaceMapping",
columns: new[] { "ClusterId", "Realm", "LocalParentKind", "LocalParentId", "BranchName" },
unique: true);
migrationBuilder.CreateIndex(
name: "IX_RemoteNamespaceMapping_RemoteNamespaceMappingId",
table: "RemoteNamespaceMapping",
column: "RemoteNamespaceMappingId",
unique: true,
filter: "[RemoteNamespaceMappingId] IS NOT NULL");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "DataConnection");
migrationBuilder.DropTable(
name: "DataExport");
migrationBuilder.DropTable(
name: "RemoteNamespaceMapping");
// Keep the additive storage widening on rollback. Mapping ACL rows are retained in
// NodeAcl and can contain the 22-character scope name; shrinking would truncate or fail.
// Older binaries can use the wider column and ignore the unsupported scope.
}
}
}
@@ -345,6 +345,184 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations
});
});
modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.DataConnection", b =>
{
b.Property<Guid>("DataConnectionRowId")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier")
.HasDefaultValueSql("NEWSEQUENTIALID()");
b.Property<int>("AllowedOperations")
.HasColumnType("int");
b.Property<string>("ClusterId")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("nvarchar(64)");
b.Property<int>("Consistency")
.HasColumnType("int");
b.PrimitiveCollection<string>("ConsumerNodeIds")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("DataConnectionId")
.HasMaxLength(64)
.HasColumnType("nvarchar(64)");
b.PrimitiveCollection<string>("EligibleTargetNodeIds")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<bool>("Enabled")
.HasColumnType("bit");
b.PrimitiveCollection<string>("Endpoints")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("ExpectedClusterId")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("nvarchar(64)");
b.Property<string>("ExpectedNodeId")
.HasMaxLength(64)
.HasColumnType("nvarchar(64)");
b.Property<int>("MaxBatchItems")
.HasColumnType("int");
b.Property<int>("MaxMessageBytes")
.HasColumnType("int");
b.Property<int>("MaxMonitoredItems")
.HasColumnType("int");
b.Property<int>("MaxPageItems")
.HasColumnType("int");
b.Property<long>("MaxPendingBytes")
.HasColumnType("bigint");
b.Property<int>("MaxStreams")
.HasColumnType("int");
b.Property<long>("Revision")
.HasColumnType("bigint");
b.Property<byte[]>("RowVersion")
.IsConcurrencyToken()
.IsRequired()
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("rowversion");
b.Property<string>("SecretReference")
.IsRequired()
.HasMaxLength(512)
.HasColumnType("nvarchar(512)");
b.Property<string>("SecretScopeClusterId")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("nvarchar(64)");
b.Property<int>("TargetMode")
.HasColumnType("int");
b.Property<int>("TimeoutMilliseconds")
.HasColumnType("int");
b.HasKey("DataConnectionRowId");
b.HasIndex("ClusterId");
b.HasIndex("DataConnectionId")
.IsUnique()
.HasFilter("[DataConnectionId] IS NOT NULL");
b.ToTable("DataConnection", null, t =>
{
t.HasCheckConstraint("CK_DataConnection_Limits", "[Revision] > 0 AND [TimeoutMilliseconds] > 0 AND [MaxBatchItems] > 0 AND [MaxPageItems] > 0 AND [MaxMessageBytes] > 0 AND [MaxStreams] > 0 AND [MaxMonitoredItems] > 0 AND [MaxPendingBytes] > 0");
});
});
modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.DataExport", b =>
{
b.Property<Guid>("DataExportRowId")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier")
.HasDefaultValueSql("NEWSEQUENTIALID()");
b.Property<int>("AllowedOperations")
.HasColumnType("int");
b.Property<string>("ClusterId")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("nvarchar(64)");
b.Property<string>("DataExportId")
.HasMaxLength(64)
.HasColumnType("nvarchar(64)");
b.Property<bool>("Enabled")
.HasColumnType("bit");
b.Property<int>("MaxBatchItems")
.HasColumnType("int");
b.Property<int>("MaxMonitoredItems")
.HasColumnType("int");
b.Property<int>("MaxPageItems")
.HasColumnType("int");
b.Property<int>("MaxStreams")
.HasColumnType("int");
b.Property<string>("PrincipalId")
.IsRequired()
.HasMaxLength(128)
.HasColumnType("nvarchar(128)");
b.Property<int>("Realm")
.HasColumnType("int");
b.Property<long>("Revision")
.HasColumnType("bigint");
b.Property<string>("RootEntityId")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("nvarchar(64)");
b.Property<string>("RootKind")
.IsRequired()
.HasMaxLength(32)
.HasColumnType("nvarchar(32)");
b.Property<byte[]>("RowVersion")
.IsConcurrencyToken()
.IsRequired()
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("rowversion");
b.HasKey("DataExportRowId");
b.HasIndex("ClusterId");
b.HasIndex("DataExportId")
.IsUnique()
.HasFilter("[DataExportId] IS NOT NULL");
b.ToTable("DataExport", null, t =>
{
t.HasCheckConstraint("CK_DataExport_Limits", "[Revision] > 0 AND [MaxBatchItems] > 0 AND [MaxPageItems] > 0 AND [MaxMonitoredItems] > 0 AND [MaxStreams] > 0");
});
});
modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.Deployment", b =>
{
b.Property<Guid>("DeploymentId")
@@ -795,8 +973,8 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations
b.Property<string>("ScopeKind")
.IsRequired()
.HasMaxLength(16)
.HasColumnType("nvarchar(16)");
.HasMaxLength(32)
.HasColumnType("nvarchar(32)");
b.HasKey("NodeAclRowId");
@@ -967,6 +1145,129 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations
b.ToTable("RawFolder", (string)null);
});
modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.RemoteNamespaceMapping", b =>
{
b.Property<Guid>("RemoteNamespaceMappingRowId")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier")
.HasDefaultValueSql("NEWSEQUENTIALID()");
b.Property<int>("AllowedOperations")
.HasColumnType("int");
b.Property<string>("BranchName")
.IsRequired()
.HasMaxLength(128)
.HasColumnType("nvarchar(128)");
b.Property<string>("ClusterId")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("nvarchar(64)");
b.PrimitiveCollection<string>("ConsumerNodeIds")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("DataConnectionId")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("nvarchar(64)");
b.Property<bool>("Enabled")
.HasColumnType("bit");
b.Property<int?>("ExpectedArrayElementKind")
.HasColumnType("int");
b.Property<int?>("ExpectedValueKind")
.HasColumnType("int");
b.Property<string>("LocalParentId")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("nvarchar(64)");
b.Property<string>("LocalParentKind")
.IsRequired()
.HasMaxLength(32)
.HasColumnType("nvarchar(32)");
b.Property<int>("MaxProjectionDepth")
.HasColumnType("int");
b.Property<int>("MaxProjectionNodes")
.HasColumnType("int");
b.Property<int>("MetadataLeaseMilliseconds")
.HasColumnType("int");
b.Property<int>("PublishingIntervalMilliseconds")
.HasColumnType("int");
b.Property<int>("Realm")
.HasColumnType("int");
b.Property<string>("RemoteIdentifier")
.IsRequired()
.HasMaxLength(512)
.HasColumnType("nvarchar(512)");
b.Property<string>("RemoteIdentifierKind")
.IsRequired()
.HasMaxLength(32)
.HasColumnType("nvarchar(32)");
b.Property<string>("RemoteNamespaceMappingId")
.HasMaxLength(64)
.HasColumnType("nvarchar(64)");
b.Property<string>("RemoteNamespaceUri")
.IsRequired()
.HasMaxLength(512)
.HasColumnType("nvarchar(512)");
b.Property<int>("RemoteRealm")
.HasColumnType("int");
b.Property<string>("RemoteRootEntityId")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("nvarchar(64)");
b.Property<long>("Revision")
.HasColumnType("bigint");
b.Property<byte[]>("RowVersion")
.IsConcurrencyToken()
.IsRequired()
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("rowversion");
b.Property<int>("SamplingIntervalMilliseconds")
.HasColumnType("int");
b.Property<int>("StaleTimeoutMilliseconds")
.HasColumnType("int");
b.Property<bool>("WriteThrough")
.HasColumnType("bit");
b.HasKey("RemoteNamespaceMappingRowId");
b.HasIndex("RemoteNamespaceMappingId")
.IsUnique()
.HasFilter("[RemoteNamespaceMappingId] IS NOT NULL");
b.HasIndex("ClusterId", "Realm", "LocalParentKind", "LocalParentId", "BranchName")
.IsUnique();
b.ToTable("RemoteNamespaceMapping", null, t =>
{
t.HasCheckConstraint("CK_RemoteNamespaceMapping_Limits", "[Revision] > 0 AND [MaxProjectionNodes] > 0 AND [MaxProjectionDepth] > 0 AND [MetadataLeaseMilliseconds] > 0 AND [StaleTimeoutMilliseconds] > 0 AND [SamplingIntervalMilliseconds] > 0 AND [PublishingIntervalMilliseconds] > 0");
});
});
modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.Script", b =>
{
b.Property<Guid>("ScriptRowId")
@@ -1538,6 +1839,24 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations
b.Navigation("Node");
});
modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.DataConnection", b =>
{
b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ServerCluster", null)
.WithMany()
.HasForeignKey("ClusterId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.DataExport", b =>
{
b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ServerCluster", null)
.WithMany()
.HasForeignKey("ClusterId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.DriverInstance", b =>
{
b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ServerCluster", "Cluster")
@@ -1587,6 +1906,15 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations
.IsRequired();
});
modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.RemoteNamespaceMapping", b =>
{
b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ServerCluster", null)
.WithMany()
.HasForeignKey("ClusterId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.UnsArea", b =>
{
b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ServerCluster", "Cluster")
@@ -12,6 +12,10 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration;
public sealed class OtOpcUaConfigDbContext(DbContextOptions<OtOpcUaConfigDbContext> options)
: DbContext(options), IDataProtectionKeyContext
{
public DbSet<DataConnection> DataConnections => Set<DataConnection>();
public DbSet<DataExport> DataExports => Set<DataExport>();
public DbSet<RemoteNamespaceMapping> RemoteNamespaceMappings => Set<RemoteNamespaceMapping>();
/// <summary>Gets the DbSet of server clusters.</summary>
public DbSet<ServerCluster> ServerClusters => Set<ServerCluster>();
/// <summary>Gets the DbSet of cluster nodes.</summary>
@@ -73,6 +77,7 @@ public sealed class OtOpcUaConfigDbContext(DbContextOptions<OtOpcUaConfigDbConte
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
ConfigureDataConnectionEntities(modelBuilder);
ConfigureServerCluster(modelBuilder);
ConfigureClusterNode(modelBuilder);
ConfigureClusterNodeCredential(modelBuilder);
@@ -100,6 +105,62 @@ public sealed class OtOpcUaConfigDbContext(DbContextOptions<OtOpcUaConfigDbConte
ConfigureDataProtectionKey(modelBuilder);
}
private static void ConfigureDataConnectionEntities(ModelBuilder modelBuilder)
{
modelBuilder.Entity<DataConnection>(e =>
{
e.ToTable("DataConnection", t => t.HasCheckConstraint("CK_DataConnection_Limits",
"[Revision] > 0 AND [TimeoutMilliseconds] > 0 AND [MaxBatchItems] > 0 AND [MaxPageItems] > 0 AND [MaxMessageBytes] > 0 AND [MaxStreams] > 0 AND [MaxMonitoredItems] > 0 AND [MaxPendingBytes] > 0"));
e.HasKey(x => x.DataConnectionRowId);
e.Property(x => x.DataConnectionRowId).HasDefaultValueSql("NEWSEQUENTIALID()");
e.Property(x => x.DataConnectionId).HasMaxLength(64);
e.Property(x => x.ClusterId).HasMaxLength(64);
e.Property(x => x.ExpectedClusterId).HasMaxLength(64);
e.Property(x => x.ExpectedNodeId).HasMaxLength(64);
e.Property(x => x.SecretReference).HasMaxLength(512);
e.Property(x => x.SecretScopeClusterId).HasMaxLength(64);
e.Property(x => x.RowVersion).IsRowVersion();
e.HasIndex(x => x.DataConnectionId).IsUnique();
e.HasOne<ServerCluster>().WithMany().HasForeignKey(x => x.ClusterId).OnDelete(DeleteBehavior.Restrict);
});
modelBuilder.Entity<DataExport>(e =>
{
e.ToTable("DataExport", t => t.HasCheckConstraint("CK_DataExport_Limits",
"[Revision] > 0 AND [MaxBatchItems] > 0 AND [MaxPageItems] > 0 AND [MaxMonitoredItems] > 0 AND [MaxStreams] > 0"));
e.HasKey(x => x.DataExportRowId);
e.Property(x => x.DataExportRowId).HasDefaultValueSql("NEWSEQUENTIALID()");
e.Property(x => x.DataExportId).HasMaxLength(64);
e.Property(x => x.ClusterId).HasMaxLength(64);
e.Property(x => x.RootKind).HasMaxLength(32);
e.Property(x => x.RootEntityId).HasMaxLength(64);
e.Property(x => x.PrincipalId).HasMaxLength(128);
e.Property(x => x.RowVersion).IsRowVersion();
e.HasIndex(x => x.DataExportId).IsUnique();
e.HasOne<ServerCluster>().WithMany().HasForeignKey(x => x.ClusterId).OnDelete(DeleteBehavior.Restrict);
});
modelBuilder.Entity<RemoteNamespaceMapping>(e =>
{
e.ToTable("RemoteNamespaceMapping", t => t.HasCheckConstraint("CK_RemoteNamespaceMapping_Limits",
"[Revision] > 0 AND [MaxProjectionNodes] > 0 AND [MaxProjectionDepth] > 0 AND [MetadataLeaseMilliseconds] > 0 AND [StaleTimeoutMilliseconds] > 0 AND [SamplingIntervalMilliseconds] > 0 AND [PublishingIntervalMilliseconds] > 0"));
e.HasKey(x => x.RemoteNamespaceMappingRowId);
e.Property(x => x.RemoteNamespaceMappingRowId).HasDefaultValueSql("NEWSEQUENTIALID()");
e.Property(x => x.RemoteNamespaceMappingId).HasMaxLength(64);
e.Property(x => x.ClusterId).HasMaxLength(64);
e.Property(x => x.DataConnectionId).HasMaxLength(64);
e.Property(x => x.LocalParentKind).HasMaxLength(32);
e.Property(x => x.LocalParentId).HasMaxLength(64);
e.Property(x => x.BranchName).HasMaxLength(128);
e.Property(x => x.RemoteRootEntityId).HasMaxLength(64);
e.Property(x => x.RemoteNamespaceUri).HasMaxLength(512);
e.Property(x => x.RemoteIdentifierKind).HasMaxLength(32);
e.Property(x => x.RemoteIdentifier).HasMaxLength(512);
e.Property(x => x.RowVersion).IsRowVersion();
e.HasIndex(x => x.RemoteNamespaceMappingId).IsUnique();
e.HasIndex(x => new { x.ClusterId, x.Realm, x.LocalParentKind, x.LocalParentId, x.BranchName }).IsUnique();
e.HasOne<ServerCluster>().WithMany().HasForeignKey(x => x.ClusterId).OnDelete(DeleteBehavior.Restrict);
});
}
private static void ConfigureServerCluster(ModelBuilder modelBuilder)
{
modelBuilder.Entity<ServerCluster>(e =>
@@ -477,7 +538,7 @@ public sealed class OtOpcUaConfigDbContext(DbContextOptions<OtOpcUaConfigDbConte
e.Property(x => x.NodeAclId).HasMaxLength(64);
e.Property(x => x.ClusterId).HasMaxLength(64);
e.Property(x => x.Principal).HasMaxLength(256);
e.Property(x => x.ScopeKind).HasConversion<string>().HasMaxLength(16);
e.Property(x => x.ScopeKind).HasConversion<string>().HasMaxLength(32);
e.Property(x => x.ScopeId).HasMaxLength(64);
e.Property(x => x.PermissionFlags).HasConversion<int>();
e.Property(x => x.Notes).HasMaxLength(512);
@@ -0,0 +1,274 @@
using System.Text.RegularExpressions;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Commons.Types;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Configuration.Validation;
/// <summary>Validates deployed data-service configuration without resolving consumer-side secrets.</summary>
public static class DataConnectionValidator
{
private const DataOperations KnownOperations = DataOperations.Browse | DataOperations.Metadata |
DataOperations.Read | DataOperations.Write | DataOperations.Subscribe;
private static readonly StringComparer Ids = StringComparer.OrdinalIgnoreCase;
public static IReadOnlyList<ValidationError> Validate(DraftSnapshot draft)
{
ArgumentNullException.ThrowIfNull(draft);
var errors = new List<ValidationError>();
void Add(string code, string id, string message) => errors.Add(new(code, message, id));
bool Same(string? a, string? b) => Ids.Equals(a, b);
bool ValidOps(DataOperations operations) => operations != DataOperations.None && (operations & ~KnownOperations) == 0;
bool NodesValid(IEnumerable<string> ids, string owner)
{
var list = ids.ToList();
return list.Count > 0 && list.All(x => !string.IsNullOrWhiteSpace(x)) &&
list.Distinct(Ids).Count() == list.Count && list.All(id => draft.ClusterNodes.Any(n =>
Same(n.NodeId, id) && Same(n.ClusterId, owner) && n.Enabled));
}
bool ValidSegment(string? value, DataRealm realm) => realm == DataRealm.Uns
? UnsSegment.IsValid(value)
: value is not null && value.Length <= 128 && RawPaths.ValidateSegment(value) is null;
bool ValidEndpoint(string endpoint) => Uri.TryCreate(endpoint, UriKind.Absolute, out var uri) &&
uri.Scheme == Uri.UriSchemeHttps && string.IsNullOrEmpty(uri.UserInfo) &&
string.IsNullOrEmpty(uri.Query) && string.IsNullOrEmpty(uri.Fragment);
bool ValidSecretReference(string? reference) => reference is not null &&
Regex.IsMatch(reference, @"\Asecret:data/[A-Za-z0-9][A-Za-z0-9._/-]*\z", RegexOptions.CultureInvariant) &&
!reference.Contains("..", StringComparison.Ordinal);
void DuplicateIds(IEnumerable<string> ids, string kind)
{
foreach (var duplicate in ids.Where(id => !string.IsNullOrWhiteSpace(id))
.GroupBy(id => id, Ids).Where(group => group.Count() > 1))
{
Add("DataLogicalIdDuplicate", duplicate.Key, $"Duplicate {kind} logical ID.");
}
}
DuplicateIds(draft.DataConnections.Select(x => x.DataConnectionId), "connection");
DuplicateIds(draft.DataExports.Select(x => x.DataExportId), "export");
DuplicateIds(draft.RemoteNamespaceMappings.Select(x => x.RemoteNamespaceMappingId), "mapping");
foreach (var connection in draft.DataConnections)
{
var id = connection.DataConnectionId;
if ((connection.Enabled && connection.Endpoints.Count == 0) ||
connection.Endpoints.Any(endpoint => !string.IsNullOrWhiteSpace(endpoint) ? !ValidEndpoint(endpoint) : connection.Enabled))
{
Add("DataConnectionEndpointInvalid", id, "Endpoints must be absolute HTTPS URIs without credentials, query or fragment.");
}
if ((connection.Enabled || !string.IsNullOrWhiteSpace(connection.SecretReference)) &&
(!ValidSecretReference(connection.SecretReference) ||
((connection.Enabled || !string.IsNullOrWhiteSpace(connection.SecretScopeClusterId)) &&
!Same(connection.SecretScopeClusterId, connection.ClusterId))))
{
Add("DataConnectionSecretReferenceInvalid", id, "A cluster-scoped data secret reference is required.");
}
}
foreach (var connection in draft.DataConnections.Where(x => x.Enabled))
{
var id = connection.DataConnectionId;
if (string.IsNullOrWhiteSpace(id) || string.IsNullOrWhiteSpace(connection.ClusterId) || connection.Revision <= 0 ||
string.IsNullOrWhiteSpace(connection.ExpectedClusterId) || !Enum.IsDefined(connection.TargetMode) ||
connection.TargetMode == DataTargetMode.Unspecified || !Enum.IsDefined(connection.Consistency) ||
connection.Consistency == DataConsistency.Unspecified)
Add("DataConnectionIdentityInvalid", id, "Connection identity, target mode and consistency are required.");
if (!NodesValid(connection.ConsumerNodeIds, connection.ClusterId))
Add("DataConnectionConsumerScopeInvalid", id, "Consumers must be distinct enabled nodes owned by the connection cluster.");
if (connection.TargetMode == DataTargetMode.Node)
{
if (string.IsNullOrWhiteSpace(connection.ExpectedNodeId) || connection.EligibleTargetNodeIds.Count != 0)
Add("DataConnectionTargetInvalid", id, "Node targets require one expected node and no cluster target set.");
if (Same(connection.ClusterId, connection.ExpectedClusterId) &&
connection.ConsumerNodeIds.Any(n => Same(n, connection.ExpectedNodeId)))
Add("DataConnectionSelfRoute", id, "A consumer cannot target itself.");
if (Same(connection.ClusterId, connection.ExpectedClusterId) && !draft.ClusterNodes.Any(n =>
Same(n.ClusterId, connection.ClusterId) && Same(n.NodeId, connection.ExpectedNodeId)))
Add("DataConnectionTargetInvalid", id, "Same-cluster target node must exist in the declared cluster.");
}
else if (connection.TargetMode == DataTargetMode.Cluster)
{
if (connection.ExpectedNodeId is not null || connection.EligibleTargetNodeIds.Count == 0 ||
connection.EligibleTargetNodeIds.Any(string.IsNullOrWhiteSpace) ||
connection.EligibleTargetNodeIds.Distinct(Ids).Count() != connection.EligibleTargetNodeIds.Count)
Add("DataConnectionTargetInvalid", id, "Cluster targets require a distinct nonempty eligible node set.");
if (Same(connection.ClusterId, connection.ExpectedClusterId) && connection.ConsumerNodeIds.Any(consumer =>
!connection.EligibleTargetNodeIds.Any(target => !Same(target, consumer))))
Add("DataConnectionSelfRoute", id, "Each consumer requires an eligible nonself target.");
if (Same(connection.ClusterId, connection.ExpectedClusterId) && connection.EligibleTargetNodeIds.Any(target =>
!draft.ClusterNodes.Any(n => Same(n.ClusterId, connection.ClusterId) && Same(n.NodeId, target) && n.Enabled && !n.MaintenanceMode)))
Add("DataConnectionTargetInvalid", id, "Same-cluster eligible targets must be enabled and out of maintenance.");
}
if (!ValidOps(connection.AllowedOperations))
Add("DataConnectionOperationsInvalid", id, "Connection operations must be a supported nonempty subset.");
if (connection.TimeoutMilliseconds <= 0 || connection.MaxBatchItems <= 0 || connection.MaxPageItems <= 0 ||
connection.MaxMessageBytes <= 0 || connection.MaxStreams <= 0 || connection.MaxMonitoredItems <= 0 || connection.MaxPendingBytes <= 0)
Add("DataConnectionLimitInvalid", id, "Connection limits must be positive.");
}
// Resolve local entity ownership through existing trees. Projected mappings are never valid parents or exports.
string? Owner(string kind, string entityId) => kind switch
{
"Cluster" => draft.ServerClusters.FirstOrDefault(x => Same(x.ClusterId, entityId))?.ClusterId,
"RawFolder" => draft.RawFolders.FirstOrDefault(x => Same(x.RawFolderId, entityId))?.ClusterId,
"RawDriver" => draft.DriverInstances.FirstOrDefault(x => Same(x.DriverInstanceId, entityId))?.ClusterId,
"RawDevice" => DeviceOwner(entityId),
"RawTagGroup" => draft.TagGroups.FirstOrDefault(x => Same(x.TagGroupId, entityId)) is { } group ? DeviceOwner(group.DeviceId) : null,
"RawTag" => draft.Tags.FirstOrDefault(x => Same(x.TagId, entityId)) is { } tag ? DeviceOwner(tag.DeviceId) : null,
"UnsArea" => draft.UnsAreas.FirstOrDefault(x => Same(x.UnsAreaId, entityId))?.ClusterId,
"UnsLine" => LineOwner(entityId),
"Equipment" => draft.Equipment.FirstOrDefault(x => Same(x.EquipmentId, entityId)) is { } equipment ? LineOwner(equipment.UnsLineId) : null,
"UnsTagReference" => draft.UnsTagReferences.FirstOrDefault(x => Same(x.UnsTagReferenceId, entityId)) is { } reference ? EquipmentOwner(reference.EquipmentId) : null,
"VirtualTag" => draft.VirtualTags.FirstOrDefault(x => Same(x.VirtualTagId, entityId)) is { } virtualTag ? EquipmentOwner(virtualTag.EquipmentId) : null,
_ => null
};
string? DeviceOwner(string deviceId)
{
var device = draft.Devices.FirstOrDefault(x => Same(x.DeviceId, deviceId));
return device is null ? null : draft.DriverInstances.FirstOrDefault(x => Same(x.DriverInstanceId, device.DriverInstanceId))?.ClusterId;
}
string? EquipmentOwner(string equipmentId)
{
var equipment = draft.Equipment.FirstOrDefault(x => Same(x.EquipmentId, equipmentId));
return equipment is null ? null : LineOwner(equipment.UnsLineId);
}
string? LineOwner(string lineId)
{
var line = draft.UnsLines.FirstOrDefault(x => Same(x.UnsLineId, lineId));
return line is null ? null : draft.UnsAreas.FirstOrDefault(x => Same(x.UnsAreaId, line.UnsAreaId))?.ClusterId;
}
bool KindInRealm(string kind, DataRealm realm) => kind == "Cluster" || (realm switch
{
DataRealm.Raw => kind is "RawFolder" or "RawDriver" or "RawDevice" or "RawTagGroup" or "RawTag",
DataRealm.Uns => kind is "UnsArea" or "UnsLine" or "Equipment" or "UnsTagReference" or "VirtualTag",
_ => false
});
bool LocalCollision(RemoteNamespaceMapping m)
{
var name = m.BranchName;
bool Name(string? candidate) => string.Equals(candidate, name, StringComparison.Ordinal);
return m.LocalParentKind switch
{
"Cluster" when m.Realm == DataRealm.Raw => draft.RawFolders.Any(x => Same(x.ClusterId, m.ClusterId) && x.ParentRawFolderId is null && Name(x.Name)) || draft.DriverInstances.Any(x => Same(x.ClusterId, m.ClusterId) && x.RawFolderId is null && Name(x.Name)),
"Cluster" => draft.UnsAreas.Any(x => Same(x.ClusterId, m.ClusterId) && Name(x.Name)),
"RawFolder" => draft.RawFolders.Any(x => Same(x.ParentRawFolderId, m.LocalParentId) && Name(x.Name)) || draft.DriverInstances.Any(x => Same(x.RawFolderId, m.LocalParentId) && Name(x.Name)),
"RawDriver" => draft.Devices.Any(x => Same(x.DriverInstanceId, m.LocalParentId) && Name(x.Name)),
"RawDevice" => draft.TagGroups.Any(x => Same(x.DeviceId, m.LocalParentId) && x.ParentTagGroupId is null && Name(x.Name)) || draft.Tags.Any(x => Same(x.DeviceId, m.LocalParentId) && x.TagGroupId is null && Name(x.Name)),
"RawTagGroup" => draft.TagGroups.Any(x => Same(x.ParentTagGroupId, m.LocalParentId) && Name(x.Name)) || draft.Tags.Any(x => Same(x.TagGroupId, m.LocalParentId) && Name(x.Name)),
"UnsArea" => draft.UnsLines.Any(x => Same(x.UnsAreaId, m.LocalParentId) && Name(x.Name)),
"UnsLine" => draft.Equipment.Any(x => Same(x.UnsLineId, m.LocalParentId) && Name(x.Name)),
"Equipment" => draft.VirtualTags.Any(x => Same(x.EquipmentId, m.LocalParentId) && Name(x.Name)) || draft.ScriptedAlarms.Any(x => Same(x.EquipmentId, m.LocalParentId) && Name(x.Name)) || draft.UnsTagReferences.Any(x => Same(x.EquipmentId, m.LocalParentId) && Name(x.DisplayNameOverride ?? draft.Tags.FirstOrDefault(t => Same(t.TagId, x.TagId))?.Name)),
_ => false
};
}
bool RootIsAncestor(RemoteNamespaceMapping mapping)
{
var kind = mapping.LocalParentKind;
var current = mapping.LocalParentId;
var seen = new HashSet<string>(Ids);
while (!string.IsNullOrEmpty(current) && seen.Add(kind + ":" + current))
{
if (Same(current, mapping.RemoteRootEntityId)) return true;
switch (kind)
{
case "RawFolder":
var folder = draft.RawFolders.FirstOrDefault(x => Same(x.RawFolderId, current));
if (folder is null) return false;
current = folder.ParentRawFolderId ?? folder.ClusterId;
kind = folder.ParentRawFolderId is null ? "Cluster" : "RawFolder";
break;
case "RawDriver":
var driver = draft.DriverInstances.FirstOrDefault(x => Same(x.DriverInstanceId, current));
if (driver is null) return false;
current = driver.RawFolderId ?? driver.ClusterId;
kind = driver.RawFolderId is null ? "Cluster" : "RawFolder";
break;
case "RawDevice":
current = draft.Devices.FirstOrDefault(x => Same(x.DeviceId, current))?.DriverInstanceId ?? "";
kind = "RawDriver";
break;
case "RawTagGroup":
var group = draft.TagGroups.FirstOrDefault(x => Same(x.TagGroupId, current));
if (group is null) return false;
current = group.ParentTagGroupId ?? group.DeviceId;
kind = group.ParentTagGroupId is null ? "RawDevice" : "RawTagGroup";
break;
case "Equipment":
current = draft.Equipment.FirstOrDefault(x => Same(x.EquipmentId, current))?.UnsLineId ?? "";
kind = "UnsLine";
break;
case "UnsLine":
current = draft.UnsLines.FirstOrDefault(x => Same(x.UnsLineId, current))?.UnsAreaId ?? "";
kind = "UnsArea";
break;
case "UnsArea":
current = draft.UnsAreas.FirstOrDefault(x => Same(x.UnsAreaId, current))?.ClusterId ?? "";
kind = "Cluster";
break;
default:
return false;
}
}
return false;
}
foreach (var mapping in draft.RemoteNamespaceMappings.Where(x => x.Enabled))
{
var id = mapping.RemoteNamespaceMappingId;
var connection = draft.DataConnections.FirstOrDefault(x => Same(x.DataConnectionId, mapping.DataConnectionId));
if (string.IsNullOrWhiteSpace(id) || mapping.Revision <= 0 || connection is null || !connection.Enabled || !Same(connection.ClusterId, mapping.ClusterId))
Add("DataMappingConnectionInvalid", id, "An enabled mapping requires an enabled connection owned by the same cluster.");
if (!NodesValid(mapping.ConsumerNodeIds, mapping.ClusterId) || connection is null ||
mapping.ConsumerNodeIds.Any(n => !connection.ConsumerNodeIds.Contains(n, Ids)))
Add("DataMappingConsumerScopeInvalid", id, "Mapping consumers must be a nonempty subset of connection consumers.");
if (!Enum.IsDefined(mapping.Realm) || mapping.Realm == DataRealm.Unspecified || mapping.Realm != mapping.RemoteRealm)
Add("DataMappingRealmMismatch", id, "Local and remote realms must be the same supported realm.");
if (!KindInRealm(mapping.LocalParentKind, mapping.Realm) || mapping.LocalParentKind is "RawTag" or "UnsTagReference" or "VirtualTag" ||
!Same(Owner(mapping.LocalParentKind, mapping.LocalParentId), mapping.ClusterId))
Add("DataMappingParentInvalid", id, "Mapping parent must be a local entity in the selected realm and cluster.");
if (!ValidSegment(mapping.BranchName, mapping.Realm))
Add("DataMappingNameInvalid", id, "Mapping branch name must be a valid realm segment.");
var expectedNamespaceUri = mapping.RemoteRealm switch
{
DataRealm.Raw => V3NodeIds.RawNamespaceUri,
DataRealm.Uns => V3NodeIds.UnsNamespaceUri,
_ => null
};
if (string.IsNullOrWhiteSpace(mapping.RemoteRootEntityId) || expectedNamespaceUri is null ||
!string.Equals(mapping.RemoteNamespaceUri, expectedNamespaceUri, StringComparison.Ordinal) ||
string.IsNullOrWhiteSpace(mapping.RemoteIdentifierKind) || string.IsNullOrWhiteSpace(mapping.RemoteIdentifier))
Add("DataMappingRootInvalid", id, "A stable remote entity and canonical address are required.");
if (mapping.ExpectedValueKind is { } valueKind && (!Enum.IsDefined(valueKind) || valueKind == DataValueKind.Unspecified ||
(valueKind == DataValueKind.Array && (mapping.ExpectedArrayElementKind is not { } elementKind || !DataValue.IsSupportedArrayElementKind(elementKind))) ||
(valueKind != DataValueKind.Array && mapping.ExpectedArrayElementKind is not null)) ||
(mapping.ExpectedValueKind is null && mapping.ExpectedArrayElementKind is not null))
Add("DataMappingTypeInvalid", id, "Expected leaf value and array element types must be supported and consistent.");
if (connection is not null && draft.RemoteNamespaceMappings.Any(other => Same(other.ClusterId, connection.ExpectedClusterId) && Same(other.RemoteNamespaceMappingId, mapping.RemoteRootEntityId)))
Add("DataMappingProjectionLoop", id, "Projected mappings cannot be re-exported or mounted as roots.");
if (connection is not null && Same(connection.ExpectedClusterId, mapping.ClusterId) && RootIsAncestor(mapping))
Add("DataMappingProjectionLoop", id, "A root cannot be mounted under itself.");
if (LocalCollision(mapping) || draft.RemoteNamespaceMappings.Any(other => !ReferenceEquals(other, mapping) && other.Enabled &&
Same(other.ClusterId, mapping.ClusterId) && other.Realm == mapping.Realm && Same(other.LocalParentKind, mapping.LocalParentKind) &&
Same(other.LocalParentId, mapping.LocalParentId) && string.Equals(other.BranchName, mapping.BranchName, StringComparison.Ordinal)))
Add("DataMappingNameCollision", id, "A mapping branch collides with an existing sibling.");
if (!ValidOps(mapping.AllowedOperations) || connection is null || (mapping.AllowedOperations & ~connection.AllowedOperations) != 0 ||
(mapping.AllowedOperations.HasFlag(DataOperations.Write) && !mapping.WriteThrough))
Add("DataMappingOperationsInvalid", id, "Mapping operations must be permitted by the connection and write-through policy.");
if (mapping.MaxProjectionNodes <= 0 || mapping.MaxProjectionDepth <= 0 || mapping.MetadataLeaseMilliseconds <= 0 ||
mapping.StaleTimeoutMilliseconds <= 0 || mapping.SamplingIntervalMilliseconds <= 0 || mapping.PublishingIntervalMilliseconds <= 0)
Add("DataMappingLimitInvalid", id, "Mapping limits and intervals must be positive and the metadata lease bounded.");
}
foreach (var export in draft.DataExports.Where(x => x.Enabled))
{
var id = export.DataExportId;
if (string.IsNullOrWhiteSpace(id) || export.Revision <= 0 || string.IsNullOrWhiteSpace(export.PrincipalId) ||
!Enum.IsDefined(export.Realm) || export.Realm == DataRealm.Unspecified || !KindInRealm(export.RootKind, export.Realm) ||
!Same(Owner(export.RootKind, export.RootEntityId), export.ClusterId))
Add("DataExportRootInvalid", id, "Export requires a named principal and an origin-local root in its realm.");
if (!ValidOps(export.AllowedOperations)) Add("DataExportOperationsInvalid", id, "Export operations must be a supported nonempty subset.");
if (export.MaxBatchItems <= 0 || export.MaxPageItems <= 0 || export.MaxMonitoredItems <= 0 || export.MaxStreams <= 0)
Add("DataExportLimitInvalid", id, "Export limits must be positive.");
}
return errors;
}
}
@@ -74,6 +74,11 @@ public sealed class DraftSnapshot
/// </summary>
public IReadOnlyList<ServerCluster> ServerClusters { get; init; } = [];
/// <summary>Directional data connections, exports and mappings from the same consistent snapshot.</summary>
public IReadOnlyList<DataConnection> DataConnections { get; init; } = [];
public IReadOnlyList<DataExport> DataExports { get; init; } = [];
public IReadOnlyList<RemoteNamespaceMapping> RemoteNamespaceMappings { get; init; } = [];
/// <summary>Cluster-node rows; see <see cref="ServerClusters"/> for why they ride the snapshot.</summary>
public IReadOnlyList<ClusterNode> ClusterNodes { get; init; } = [];
@@ -72,6 +72,9 @@ public static class DraftSnapshotFactory
ClusterId = string.Empty, // global snapshot; rules compare entity ClusterId fields, not this
ServerClusters = await db.ServerClusters.AsNoTracking().OrderBy(x => x.ClusterId).ToListAsync(ct),
ClusterNodes = await db.ClusterNodes.AsNoTracking().OrderBy(x => x.NodeId).ToListAsync(ct),
DataConnections = await db.DataConnections.AsNoTracking().OrderBy(x => x.DataConnectionId).ToListAsync(ct),
DataExports = await db.DataExports.AsNoTracking().OrderBy(x => x.DataExportId).ToListAsync(ct),
RemoteNamespaceMappings = await db.RemoteNamespaceMappings.AsNoTracking().OrderBy(x => x.RemoteNamespaceMappingId).ToListAsync(ct),
// v3: Namespace entity retired — no namespace list to materialize. The Raw tree
// (RawFolders/TagGroups) + UnsTagReferences feed the v3 rules (charset, tagname length,
// effective-leaf uniqueness).
@@ -49,6 +49,7 @@ public static class DraftValidator
ValidateMTConnectSingleDevice(draft, errors);
errors.AddRange(HeidenhainDeployChecks.Errors(draft));
errors.AddRange(CredentialReferenceDeployChecks.Errors(draft));
errors.AddRange(DataConnectionValidator.Validate(draft));
ValidateNodeAclScopes(draft, errors);
return errors;
}
@@ -116,6 +117,7 @@ public static class DraftValidator
// sets, so "does this id name a row of the kind's type" and "which cluster owns it" cannot disagree.
// GroupBy/First rather than ToDictionary: a duplicated id is another rule's business, and throwing
// here would take down every remaining check in the same pass.
var mappingCluster = Link(draft.RemoteNamespaceMappings, m => m.RemoteNamespaceMappingId, m => m.ClusterId);
var folderCluster = Link(draft.RawFolders, f => f.RawFolderId, f => f.ClusterId);
var driverCluster = Link(draft.DriverInstances, d => d.DriverInstanceId, d => d.ClusterId);
var deviceDriver = Link(draft.Devices, d => d.DeviceId, d => d.DriverInstanceId);
@@ -206,6 +208,8 @@ public static class DraftValidator
// kind's chain is walked.
var (entity, exists, owner) = acl.ScopeKind switch
{
NodeAclScopeKind.RemoteNamespaceMapping =>
("RemoteNamespaceMapping", mappingCluster.ContainsKey(scopeId), mappingCluster.GetValueOrDefault(scopeId)),
NodeAclScopeKind.UnsArea =>
("UnsArea", areaCluster.ContainsKey(scopeId), areaCluster.GetValueOrDefault(scopeId)),
NodeAclScopeKind.UnsLine =>
@@ -52,6 +52,14 @@ public static class ConfigComposer
public static ConfigArtifact Compose(DraftSnapshot snapshot)
{
ArgumentNullException.ThrowIfNull(snapshot);
foreach (var connection in snapshot.DataConnections)
{
if (connection.Endpoints is null || connection.Endpoints.Any(endpoint =>
!string.IsNullOrWhiteSpace(endpoint) &&
(!Uri.TryCreate(endpoint, UriKind.Absolute, out var uri) || uri.Scheme != Uri.UriSchemeHttps ||
!string.IsNullOrEmpty(uri.UserInfo) || !string.IsNullOrEmpty(uri.Query) || !string.IsNullOrEmpty(uri.Fragment))))
throw new InvalidDataException($"Invalid endpoint in data connection '{connection.DataConnectionId}'.");
}
// v3 greenfield snapshot: the Raw tree (RawFolders → DriverInstances(+RawFolderId) → Devices(+DeviceConfig)
// → TagGroups → Tags(DeviceId/TagGroupId, no EquipmentId/FolderPath/DriverInstanceId)) plus the UNS
@@ -87,6 +95,20 @@ public static class ConfigComposer
Scripts = snapshot.Scripts,
VirtualTags = snapshot.VirtualTags,
ScriptedAlarms = snapshot.ScriptedAlarms,
DataConnections = snapshot.DataConnections.OrderBy(x => x.DataConnectionId, StringComparer.Ordinal).Select(connection =>
{
var copy = JsonSerializer.Deserialize<ZB.MOM.WW.OtOpcUa.Configuration.Entities.DataConnection>(JsonSerializer.SerializeToUtf8Bytes(connection, JsonOptions), JsonOptions)!;
copy.ConsumerNodeIds = copy.ConsumerNodeIds.OrderBy(x => x, StringComparer.Ordinal).ToList();
copy.EligibleTargetNodeIds = copy.EligibleTargetNodeIds.OrderBy(x => x, StringComparer.Ordinal).ToList();
return copy;
}).ToArray(),
DataExports = snapshot.DataExports.OrderBy(x => x.DataExportId, StringComparer.Ordinal).ToArray(),
RemoteNamespaceMappings = snapshot.RemoteNamespaceMappings.OrderBy(x => x.RemoteNamespaceMappingId, StringComparer.Ordinal).Select(mapping =>
{
var copy = JsonSerializer.Deserialize<ZB.MOM.WW.OtOpcUa.Configuration.Entities.RemoteNamespaceMapping>(JsonSerializer.SerializeToUtf8Bytes(mapping, JsonOptions), JsonOptions)!;
copy.ConsumerNodeIds = copy.ConsumerNodeIds.OrderBy(x => x, StringComparer.Ordinal).ToList();
return copy;
}).ToArray(),
};
return Pack(JsonSerializer.SerializeToUtf8Bytes(ordered, JsonOptions));
@@ -0,0 +1,313 @@
using System.Text.Json;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
public static partial class DeploymentArtifact
{
/// <summary>Read the node-effective data connections from an artifact.</summary>
public static IReadOnlyList<DataConnection> ParseDataConnections(
ReadOnlySpan<byte> blob,
string nodeId
)
{
using var parsed = Open(blob.ToArray());
return parsed.ParseDataConnections(nodeId);
}
/// <summary>Read the node-effective data exports from an artifact.</summary>
public static IReadOnlyList<DataExport> ParseDataExports(ReadOnlySpan<byte> blob, string nodeId)
{
using var parsed = Open(blob.ToArray());
return parsed.ParseDataExports(nodeId);
}
/// <summary>Read the node-effective remote namespace mappings from an artifact.</summary>
public static IReadOnlyList<RemoteNamespaceMapping> ParseRemoteNamespaceMappings(
ReadOnlySpan<byte> blob,
string nodeId
)
{
using var parsed = Open(blob.ToArray());
return parsed.ParseRemoteNamespaceMappings(nodeId);
}
}
internal sealed partial class ParsedDeploymentArtifact
{
private static readonly JsonSerializerOptions DataJsonOptions = new()
{
PropertyNameCaseInsensitive = true,
};
private static readonly StringComparer DataIds = StringComparer.OrdinalIgnoreCase;
public IReadOnlyList<DataConnection> ParseDataConnections(string nodeId)
{
var projection = ReadDataProjection(nodeId);
if (projection is null)
return [];
ValidateRows(
projection.Value.Snapshot,
projection.Value.Snapshot.DataConnections.Select(x => x.DataConnectionId)
);
return projection
.Value.Snapshot.DataConnections.Where(x => x.ConsumerNodeIds.Contains(nodeId, DataIds))
.ToArray();
}
public IReadOnlyList<DataExport> ParseDataExports(string nodeId)
{
var projection = ReadDataProjection(nodeId);
if (projection is null)
return [];
ValidateRows(
projection.Value.Snapshot,
projection.Value.Snapshot.DataExports.Select(x => x.DataExportId)
);
return projection.Value.Snapshot.DataExports.ToArray();
}
public IReadOnlyList<RemoteNamespaceMapping> ParseRemoteNamespaceMappings(string nodeId)
{
var projection = ReadDataProjection(nodeId);
if (projection is null)
return [];
var snapshot = projection.Value.Snapshot;
ValidateRows(
snapshot,
snapshot
.RemoteNamespaceMappings.Where(x =>
DataIds.Equals(x.ClusterId, projection.Value.ClusterId)
)
.Select(x => x.RemoteNamespaceMappingId)
.Concat(snapshot.DataConnections.Select(x => x.DataConnectionId))
);
return snapshot
.RemoteNamespaceMappings.Where(x =>
DataIds.Equals(x.ClusterId, projection.Value.ClusterId)
&& x.ConsumerNodeIds.Contains(nodeId, DataIds)
)
.ToArray();
}
private (DraftSnapshot Snapshot, string ClusterId)? ReadDataProjection(string nodeId)
{
ArgumentException.ThrowIfNullOrWhiteSpace(nodeId);
var root = Root;
if (root.ValueKind != JsonValueKind.Object)
return null;
if (
!root.TryGetProperty("DataConnections", out _)
&& !root.TryGetProperty("DataExports", out _)
&& !root.TryGetProperty("RemoteNamespaceMappings", out _)
)
return null;
var node = EnumerateArray(root, "Nodes")
.Where(x => DataIds.Equals(ReadDataString(x, "NodeId"), nodeId))
.ToArray();
if (
node.Length != 1
|| !IsExplicitTrue(node[0], "Enabled")
|| IsExplicitTrue(node[0], "MaintenanceMode")
)
return null;
var clusterId = ReadDataString(node[0], "ClusterId");
if (string.IsNullOrWhiteSpace(clusterId))
return null;
var cluster = EnumerateArray(root, "Clusters")
.Where(x => DataIds.Equals(ReadDataString(x, "ClusterId"), clusterId))
.ToArray();
if (cluster.Length != 1 || !IsExplicitTrue(cluster[0], "Enabled"))
return null;
var connections = ReadDataRows<DataConnection>(
root,
"DataConnections",
"DataConnectionId",
clusterId
);
var exports = ReadDataRows<DataExport>(root, "DataExports", "DataExportId", clusterId);
var mappings = ReadDataRows<RemoteNamespaceMapping>(
root,
"RemoteNamespaceMappings",
"RemoteNamespaceMappingId",
clusterId
);
// Only foreign mapping identity is needed to detect a projected root. Do not import
// foreign configuration or validate it as a local execution graph.
foreach (var foreign in EnumerateArray(root, "RemoteNamespaceMappings"))
{
var owner = ReadDataString(foreign, "ClusterId");
var id = ReadDataString(foreign, "RemoteNamespaceMappingId");
if (
!string.IsNullOrWhiteSpace(owner)
&& !DataIds.Equals(owner, clusterId)
&& !string.IsNullOrWhiteSpace(id)
)
mappings.Add(
new RemoteNamespaceMapping { ClusterId = owner, RemoteNamespaceMappingId = id }
);
}
foreach (var c in connections)
if (c.ConsumerNodeIds is null || c.EligibleTargetNodeIds is null || c.Endpoints is null)
throw InvalidRow(c.DataConnectionId);
foreach (var m in mappings)
if (m.ConsumerNodeIds is null)
throw InvalidRow(m.RemoteNamespaceMappingId);
var snapshot = new DraftSnapshot
{
GenerationId = 0,
ClusterId = clusterId,
ServerClusters = ReadTopology<ServerCluster>(root, "Clusters"),
ClusterNodes = ReadTopology<ClusterNode>(root, "Nodes"),
RawFolders = ReadTopology<RawFolder>(root, "RawFolders"),
DriverInstances = ReadTopology<DriverInstance>(root, "DriverInstances"),
Devices = ReadTopology<Device>(root, "Devices"),
TagGroups = ReadTopology<TagGroup>(root, "TagGroups"),
Tags = ReadTopology<Tag>(root, "Tags"),
UnsAreas = ReadTopology<UnsArea>(root, "UnsAreas"),
UnsLines = ReadTopology<UnsLine>(root, "UnsLines"),
Equipment = ReadTopology<Equipment>(root, "Equipment"),
UnsTagReferences = ReadTopology<UnsTagReference>(root, "UnsTagReferences"),
VirtualTags = ReadTopology<VirtualTag>(root, "VirtualTags"),
ScriptedAlarms = ReadTopology<ScriptedAlarm>(root, "ScriptedAlarms"),
DataConnections = connections,
DataExports = exports,
RemoteNamespaceMappings = mappings,
};
return (snapshot, clusterId);
}
private static JsonElement? DataProperty(JsonElement element, string property)
{
JsonElement? found = null;
foreach (var entry in element.EnumerateObject())
{
if (!DataIds.Equals(entry.Name, property))
continue;
if (found is not null)
throw InvalidRow(null);
found = entry.Value;
}
return found;
}
private static string? ReadDataString(JsonElement element, string property)
{
var value = DataProperty(element, property);
return value is { ValueKind: JsonValueKind.String } ? value.Value.GetString() : null;
}
private static bool IsExplicitTrue(JsonElement element, string property) =>
DataProperty(element, property) is { ValueKind: JsonValueKind.True };
private static void RejectDuplicateDataProperties(JsonElement element)
{
var names = new HashSet<string>(DataIds);
foreach (var property in element.EnumerateObject())
if (!names.Add(property.Name))
throw InvalidRow(null);
}
private static InvalidDataException InvalidRow(string? id) =>
new(
$"Invalid data configuration row '{(string.IsNullOrWhiteSpace(id) ? "<unknown>" : id)}'."
);
private static List<T> ReadDataRows<T>(
JsonElement root,
string name,
string idName,
string clusterId
)
{
if (!root.TryGetProperty(name, out var array))
return [];
if (array.ValueKind != JsonValueKind.Array)
throw new InvalidDataException($"Invalid {name} collection.");
var result = new List<T>();
foreach (var element in array.EnumerateArray())
{
if (element.ValueKind != JsonValueKind.Object)
throw InvalidRow(null);
RejectDuplicateDataProperties(element);
var owner = ReadDataString(element, "ClusterId");
var id = ReadDataString(element, idName);
if (string.IsNullOrWhiteSpace(owner))
{
if (IsExplicitTrue(element, "Enabled"))
throw InvalidRow(id);
continue;
}
if (!DataIds.Equals(owner, clusterId))
continue;
if (IsExplicitTrue(element, "Enabled") && string.IsNullOrWhiteSpace(id))
throw InvalidRow(null);
try
{
var row = element.Deserialize<T>(DataJsonOptions);
if (row is null)
throw InvalidRow(id);
var identity = row switch
{
DataConnection c => (c.Enabled, c.DataConnectionId, c.ClusterId),
DataExport e => (e.Enabled, e.DataExportId, e.ClusterId),
RemoteNamespaceMapping m => (
m.Enabled,
m.RemoteNamespaceMappingId,
m.ClusterId
),
_ => throw new InvalidOperationException("Unsupported data row type."),
};
if (
!DataIds.Equals(identity.Item3, clusterId)
|| (identity.Item1 && string.IsNullOrWhiteSpace(identity.Item2))
)
throw InvalidRow(identity.Item2);
result.Add(row);
}
catch (JsonException)
{
throw InvalidRow(id);
}
catch (NotSupportedException)
{
throw InvalidRow(id);
}
}
return result;
}
private static List<T> ReadTopology<T>(JsonElement root, string name)
{
if (!root.TryGetProperty(name, out var array))
return [];
if (array.ValueKind != JsonValueKind.Array)
throw new InvalidDataException($"Invalid {name} topology.");
try
{
if (array.EnumerateArray().Any(element => element.ValueKind != JsonValueKind.Object))
throw new InvalidDataException($"Invalid {name} topology.");
var rows = array.Deserialize<List<T>>(DataJsonOptions)
?? throw new InvalidDataException($"Invalid {name} topology.");
if (rows.Any(row => row is null))
throw new InvalidDataException($"Invalid {name} topology.");
return rows;
}
catch (JsonException)
{
throw new InvalidDataException($"Invalid {name} topology.");
}
}
private static void ValidateRows(DraftSnapshot snapshot, IEnumerable<string> ids)
{
var requested = ids.ToHashSet(DataIds);
var error = DataConnectionValidator
.Validate(snapshot)
.FirstOrDefault(x => x.Context is not null && requested.Contains(x.Context));
if (error is not null)
throw InvalidRow(error.Context);
}
}
@@ -124,7 +124,7 @@ public readonly record struct ClusterScope(ClusterFilterMode Mode, string? Clust
/// exist so the one-shot call sites (and every existing test) keep their exact shape and their lenient
/// empty/malformed contract.
/// </summary>
public static class DeploymentArtifact
public static partial class DeploymentArtifact
{
private static readonly JsonSerializerOptions JsonOptions = new()
{
@@ -442,7 +442,7 @@ public static class DeploymentArtifact
/// "results survive disposal" contract enforceable rather than merely documented.
/// </para>
/// </remarks>
internal sealed class ParsedDeploymentArtifact : IDisposable
internal sealed partial class ParsedDeploymentArtifact : IDisposable
{
private readonly JsonDocument _document;
@@ -0,0 +1,76 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Configuration.Tests.DataConnections;
[Trait("Category", "Unit")]
[Trait("Feature", "GrpcData")]
[Trait("Phase", "P02")]
public sealed class GrpcDataConfigurationTests
{
[Fact]
public void Defaults_are_disabled_and_secrets_are_references()
{
var connection = new DataConnection();
var mapping = new RemoteNamespaceMapping();
connection.Enabled.ShouldBeFalse();
mapping.Enabled.ShouldBeFalse();
mapping.WriteThrough.ShouldBeFalse();
typeof(DataConnection).GetProperties().Select(p => p.Name).ShouldNotContain("Secret");
}
[Fact]
public void Same_cluster_node_target_is_allowed_only_for_other_consumers()
{
var draft = GrpcDataMappingValidationTests.ValidDraft();
DataConnectionValidator.Validate(draft).ShouldBeEmpty();
draft.DataConnections[0].ConsumerNodeIds.Add("node-b");
DataConnectionValidator.Validate(draft).ShouldContain(e => e.Code == "DataConnectionSelfRoute");
}
[Fact]
public void Enabled_connection_requires_safe_endpoint_secret_reference_and_budgets()
{
var draft = GrpcDataMappingValidationTests.ValidDraft();
var connection = draft.DataConnections[0];
connection.Endpoints = ["http://remote.example:443"];
connection.SecretReference = "inline:password";
connection.MaxBatchItems = 0;
var errors = DataConnectionValidator.Validate(draft);
errors.ShouldContain(e => e.Code == "DataConnectionEndpointInvalid");
errors.ShouldContain(e => e.Code == "DataConnectionSecretReferenceInvalid");
errors.ShouldContain(e => e.Code == "DataConnectionLimitInvalid");
}
[Fact]
public void Disabled_drafts_allow_blanks_but_not_secrets_or_query_credentials()
{
var blank = new DraftSnapshot { GenerationId = 0, ClusterId = "cluster", DataConnections = [new DataConnection()] };
DataConnectionValidator.Validate(blank).ShouldBeEmpty();
var draft = new DraftSnapshot
{
GenerationId = 0, ClusterId = "cluster",
DataConnections = [new DataConnection { DataConnectionId = "draft", SecretReference = "plaintext", Endpoints = ["https://host/path?token=secret"] }]
};
var errors = DataConnectionValidator.Validate(draft);
errors.ShouldContain(e => e.Code == "DataConnectionSecretReferenceInvalid");
errors.ShouldContain(e => e.Code == "DataConnectionEndpointInvalid");
}
[Fact]
public void Duplicate_logical_ids_are_rejected_even_in_disabled_rows()
{
var draft = new DraftSnapshot
{
GenerationId = 0, ClusterId = "cluster",
DataConnections = [new DataConnection { DataConnectionId = "same" }, new DataConnection { DataConnectionId = "SAME" }],
DataExports = [new DataExport { DataExportId = "export" }, new DataExport { DataExportId = "EXPORT" }],
RemoteNamespaceMappings = [new RemoteNamespaceMapping { RemoteNamespaceMappingId = "mount" }, new RemoteNamespaceMapping { RemoteNamespaceMappingId = "MOUNT" }]
};
DataConnectionValidator.Validate(draft).Count(e => e.Code == "DataLogicalIdDuplicate").ShouldBe(3);
}
}
@@ -0,0 +1,95 @@
using Shouldly;
using Xunit;
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.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Configuration.Tests.DataConnections;
[Trait("Category", "Unit")]
[Trait("Feature", "GrpcData")]
[Trait("Phase", "P02")]
public sealed class GrpcDataMappingValidationTests
{
internal static DraftSnapshot ValidDraft(bool collision = false) => new()
{
GenerationId = 0, ClusterId = "cluster",
ClusterNodes = [Node("node-a"), Node("node-b")],
RawFolders = collision
? [new RawFolder { RawFolderId = "parent", ClusterId = "cluster", Name = "parent" },
new RawFolder { RawFolderId = "child", ClusterId = "cluster", ParentRawFolderId = "parent", Name = "remote" }]
: [new RawFolder { RawFolderId = "parent", ClusterId = "cluster", Name = "parent" }],
DataConnections = [new DataConnection
{
DataConnectionId = "connection", ClusterId = "cluster", Enabled = true,
ConsumerNodeIds = ["node-a"], TargetMode = DataTargetMode.Node,
ExpectedClusterId = "cluster", ExpectedNodeId = "node-b",
Endpoints = ["https://node-b:443"], SecretReference = "secret:data/key", SecretScopeClusterId = "cluster",
AllowedOperations = DataOperations.Browse | DataOperations.Read
}],
RemoteNamespaceMappings = [new RemoteNamespaceMapping
{
RemoteNamespaceMappingId = "mapping", ClusterId = "cluster", DataConnectionId = "connection",
Enabled = true, ConsumerNodeIds = ["node-a"], Realm = DataRealm.Raw, RemoteRealm = DataRealm.Raw,
LocalParentKind = "RawFolder", LocalParentId = "parent", BranchName = "remote",
RemoteRootEntityId = "remote-root", RemoteNamespaceUri = "https://zb.com/otopcua/raw", RemoteIdentifierKind = "string",
RemoteIdentifier = "root", AllowedOperations = DataOperations.Browse
}]
};
private static ClusterNode Node(string id) => new()
{
NodeId = id, ClusterId = "cluster", Host = id, ApplicationUri = "urn:" + id, CreatedBy = "test"
};
[Fact]
public void Mapping_requires_subset_same_realm_and_owned_parent()
{
var draft = ValidDraft();
var mapping = draft.RemoteNamespaceMappings[0];
mapping.ConsumerNodeIds.Add("node-b");
mapping.RemoteRealm = DataRealm.Uns;
mapping.LocalParentId = "missing";
var errors = DataConnectionValidator.Validate(draft);
errors.ShouldContain(e => e.Code == "DataMappingConsumerScopeInvalid");
errors.ShouldContain(e => e.Code == "DataMappingRealmMismatch");
errors.ShouldContain(e => e.Code == "DataMappingParentInvalid");
}
[Fact]
public void Mapping_branch_collisions_and_unsupported_operations_are_rejected()
{
var draft = ValidDraft(collision: true);
draft.RemoteNamespaceMappings[0].AllowedOperations = DataOperations.Write;
var errors = DataConnectionValidator.Validate(draft);
errors.ShouldContain(e => e.Code == "DataMappingNameCollision");
errors.ShouldContain(e => e.Code == "DataMappingOperationsInvalid");
}
[Fact]
public void Same_cluster_mapping_cannot_mount_its_ancestor_and_unknown_types_fail()
{
var draft = ValidDraft();
var mapping = draft.RemoteNamespaceMappings[0];
mapping.RemoteRootEntityId = "parent";
mapping.ExpectedValueKind = (DataValueKind)999;
var errors = DataConnectionValidator.Validate(draft);
errors.ShouldContain(e => e.Code == "DataMappingProjectionLoop");
errors.ShouldContain(e => e.Code == "DataMappingTypeInvalid");
}
[Fact]
public void Branch_names_and_namespace_uri_use_canonical_realm_rules()
{
var draft = ValidDraft();
var mapping = draft.RemoteNamespaceMappings[0];
mapping.BranchName = "bad/segment";
mapping.RemoteNamespaceUri = "https://zb.com/otopcua/uns";
var errors = DataConnectionValidator.Validate(draft);
errors.ShouldContain(e => e.Code == "DataMappingNameInvalid");
errors.ShouldContain(e => e.Code == "DataMappingRootInvalid");
}
}
@@ -0,0 +1,44 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
namespace ZB.MOM.WW.OtOpcUa.Configuration.Tests.DataConnections;
[Trait("Category", "Unit")]
[Trait("Feature", "GrpcData")]
[Trait("Phase", "P02")]
public sealed class GrpcDataSchemaModelTests
{
[Fact]
public void Rollback_preserves_acl_scope_storage_for_retained_mapping_grants()
{
using var db = new OtOpcUaConfigDbContext(new DbContextOptionsBuilder<OtOpcUaConfigDbContext>()
.UseSqlServer("Server=127.0.0.1,1;Database=design;Integrated Security=true;TrustServerCertificate=true").Options);
var migrations = db.Database.GetMigrations().ToArray();
migrations[^1].ShouldEndWith("_AddGrpcDataConnections");
var rollback = db.GetService<IMigrator>().GenerateScript(migrations[^1], migrations[^2]);
rollback.ShouldNotContain("ALTER COLUMN [ScopeKind]");
}
[Fact]
public void New_rows_have_keys_and_unique_logical_ids_without_database_access()
{
using var db = new OtOpcUaConfigDbContext(new DbContextOptionsBuilder<OtOpcUaConfigDbContext>()
.UseSqlServer("Server=localhost;Database=design;Integrated Security=true;TrustServerCertificate=true").Options);
foreach (var type in new[] { typeof(DataConnection), typeof(DataExport), typeof(RemoteNamespaceMapping) })
{
var entity = db.Model.FindEntityType(type).ShouldNotBeNull();
entity.FindPrimaryKey().ShouldNotBeNull();
entity.GetIndexes().ShouldContain(i => i.IsUnique);
}
((int)NodeAclScopeKind.RawTagGroup).ShouldBe(10);
((int)NodeAclScopeKind.RemoteNamespaceMapping).ShouldBe(11);
db.Model.FindEntityType(typeof(NodeAcl))!.FindProperty(nameof(NodeAcl.ScopeKind))!
.GetMaxLength().GetValueOrDefault().ShouldBeGreaterThanOrEqualTo(nameof(NodeAclScopeKind.RemoteNamespaceMapping).Length);
db.Database.HasPendingModelChanges().ShouldBeFalse();
}
}
@@ -0,0 +1,228 @@
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();
}
}
@@ -0,0 +1,496 @@
using System.Text;
using System.Text.Json.Nodes;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
[Trait("Category", "Unit")]
[Trait("Feature", "GrpcData")]
[Trait("Phase", "P02")]
public sealed class GrpcDataArtifactReadTests
{
private const string NodeA = "node-a";
private const string NodeB = "node-b";
[Theory]
[InlineData("{}")]
[InlineData(
"{\"Clusters\":[{\"ClusterId\":\"local\"}],\"Nodes\":[{\"NodeId\":\"node-a\",\"ClusterId\":\"local\",\"Enabled\":true}]}"
)]
[InlineData("{\"UnknownFutureArray\":[{\"Enabled\":true}]}")]
public void Old_artifacts_without_new_arrays_have_no_enabled_data_surface(string json)
{
using var parsed = DeploymentArtifact.Open(Encoding.UTF8.GetBytes(json));
parsed.ParseDataConnections(NodeA).ShouldBeEmpty();
parsed.ParseDataExports(NodeA).ShouldBeEmpty();
parsed.ParseRemoteNamespaceMappings(NodeA).ShouldBeEmpty();
}
[Fact]
public void A_only_peer_mount_is_not_returned_to_its_same_cluster_target_B()
{
using var parsed = DeploymentArtifact.Open(Blob(Fixture()));
var connection = parsed.ParseDataConnections(NodeA).ShouldHaveSingleItem();
connection.TargetMode.ShouldBe(DataTargetMode.Node);
connection.ExpectedNodeId.ShouldBe(NodeB);
connection.ExpectedClusterId.ShouldBe("local");
parsed
.ParseRemoteNamespaceMappings(NodeA)
.ShouldHaveSingleItem()
.RemoteNamespaceMappingId.ShouldBe("mapping-a");
parsed.ParseDataConnections(NodeB).ShouldBeEmpty();
parsed.ParseRemoteNamespaceMappings(NodeB).ShouldBeEmpty();
// B still owns the local export catalog; import consumer scope must not suppress it.
parsed.ParseDataExports(NodeB).ShouldHaveSingleItem().DataExportId.ShouldBe("export-a");
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void Unknown_node_never_inherits_a_single_clusters_new_data_surface(bool omitNodes)
{
var root = Fixture();
if (omitNodes)
root.Remove("Nodes");
using var parsed = DeploymentArtifact.Open(Blob(root));
parsed.ParseDataConnections("unlisted").ShouldBeEmpty();
parsed.ParseDataExports("unlisted").ShouldBeEmpty();
parsed.ParseRemoteNamespaceMappings("unlisted").ShouldBeEmpty();
}
[Theory]
[InlineData("node-disabled")]
[InlineData("node-maintenance")]
[InlineData("cluster-disabled")]
public void Ineligible_node_or_owner_cluster_has_no_new_data_surface(string state)
{
var root = Fixture();
if (state == "node-disabled")
root["Nodes"]![0]!["Enabled"] = false;
if (state == "node-maintenance")
root["Nodes"]![0]!["MaintenanceMode"] = true;
if (state == "cluster-disabled")
root["Clusters"]![0]!["Enabled"] = false;
using var parsed = DeploymentArtifact.Open(Blob(root));
parsed.ParseDataConnections(NodeA).ShouldBeEmpty();
parsed.ParseDataExports(NodeA).ShouldBeEmpty();
parsed.ParseRemoteNamespaceMappings(NodeA).ShouldBeEmpty();
}
[Fact]
public void Owner_cluster_filters_connections_mappings_and_origin_local_exports()
{
var root = Fixture();
root["Clusters"]!
.AsArray()
.Add(
JsonNode.Parse(
"""{"ClusterId":"other","Name":"Other","Enterprise":"ent","Site":"site","RedundancyMode":0,"CreatedBy":"test","Enabled":true}"""
)
);
root["Nodes"]!
.AsArray()
.Add(
JsonNode.Parse(
"""{"NodeId":"node-c","ClusterId":"other","Host":"node-c","ApplicationUri":"urn:node-c","CreatedBy":"test","Enabled":true}"""
)
);
root["RawFolders"]!
.AsArray()
.Add(
JsonNode.Parse(
"""{"RawFolderId":"other-root","ClusterId":"other","Name":"Other"}"""
)
);
var foreignConnection = root["DataConnections"]![0]!.DeepClone();
foreignConnection["DataConnectionId"] = "connection-other";
foreignConnection["ClusterId"] = "other";
foreignConnection["SecretScopeClusterId"] = "other";
foreignConnection["ConsumerNodeIds"] = new JsonArray("node-c");
root["DataConnections"]!.AsArray().Add(foreignConnection);
var foreignMapping = root["RemoteNamespaceMappings"]![0]!.DeepClone();
foreignMapping["RemoteNamespaceMappingId"] = "mapping-other";
foreignMapping["ClusterId"] = "other";
foreignMapping["DataConnectionId"] = "connection-other";
foreignMapping["LocalParentId"] = "other-root";
foreignMapping["ConsumerNodeIds"] = new JsonArray("node-c");
root["RemoteNamespaceMappings"]!.AsArray().Add(foreignMapping);
var foreignExport = root["DataExports"]![0]!.DeepClone();
foreignExport["DataExportId"] = "export-other";
foreignExport["ClusterId"] = "other";
foreignExport["RootEntityId"] = "other-root";
root["DataExports"]!.AsArray().Add(foreignExport);
using var parsed = DeploymentArtifact.Open(Blob(root));
parsed
.ParseDataConnections(NodeA)
.Select(x => x.DataConnectionId)
.ShouldBe(["connection-a"]);
parsed
.ParseRemoteNamespaceMappings(NodeA)
.Select(x => x.RemoteNamespaceMappingId)
.ShouldBe(["mapping-a"]);
parsed.ParseDataExports(NodeA).Select(x => x.DataExportId).ShouldBe(["export-a"]);
parsed
.ParseDataExports("node-c")
.ShouldHaveSingleItem()
.DataExportId.ShouldBe("export-other");
}
[Fact]
public void Disabled_rows_are_retained_within_scope_for_generation_reconciliation()
{
var root = Fixture();
root["DataConnections"]![0]!["Enabled"] = false;
root["DataExports"]![0]!["Enabled"] = false;
root["RemoteNamespaceMappings"]![0]!["Enabled"] = false;
using var parsed = DeploymentArtifact.Open(Blob(root));
parsed.ParseDataConnections(NodeA).ShouldHaveSingleItem().Enabled.ShouldBeFalse();
parsed.ParseDataExports(NodeA).ShouldHaveSingleItem().Enabled.ShouldBeFalse();
parsed.ParseRemoteNamespaceMappings(NodeA).ShouldHaveSingleItem().Enabled.ShouldBeFalse();
parsed.ParseDataConnections(NodeB).ShouldBeEmpty();
parsed.ParseRemoteNamespaceMappings(NodeB).ShouldBeEmpty();
}
[Fact]
public void Omitted_enabled_flags_never_enable_new_configuration_implicitly()
{
var root = Fixture();
root["DataConnections"]![0]!.AsObject().Remove("Enabled");
root["DataExports"]![0]!.AsObject().Remove("Enabled");
root["RemoteNamespaceMappings"]![0]!.AsObject().Remove("Enabled");
using var parsed = DeploymentArtifact.Open(Blob(root));
parsed.ParseDataConnections(NodeA).ShouldHaveSingleItem().Enabled.ShouldBeFalse();
parsed.ParseDataExports(NodeA).ShouldHaveSingleItem().Enabled.ShouldBeFalse();
parsed.ParseRemoteNamespaceMappings(NodeA).ShouldHaveSingleItem().Enabled.ShouldBeFalse();
}
[Theory]
[InlineData("ConsumerNodeIds", "[]")]
[InlineData("ConsumerNodeIds", "null")]
[InlineData("ConsumerNodeIds", "\"node-a\"")]
[InlineData("TargetMode", "0")]
[InlineData("TargetMode", "999")]
[InlineData("ExpectedNodeId", "null")]
[InlineData("ExpectedNodeId", "\"node-a\"")]
[InlineData("SecretReference", "\"\"")]
[InlineData("SecretScopeClusterId", "\"foreign\"")]
[InlineData("Endpoints", "null")]
[InlineData("Endpoints", "[\"http://node-b:7443\"]")]
[InlineData("AllowedOperations", "0")]
[InlineData("AllowedOperations", "1073741824")]
[InlineData("MaxBatchItems", "0")]
[InlineData("Revision", "0")]
public void Malformed_enabled_connection_fails_closed_with_row_diagnostics(
string field,
string value
)
{
var root = Fixture();
root["DataConnections"]![0]![field] = JsonNode.Parse(value);
using var parsed = DeploymentArtifact.Open(Blob(root));
var error = Should.Throw<InvalidDataException>(() => parsed.ParseDataConnections(NodeA));
error.Message.ShouldContain("connection-a");
}
[Theory]
[InlineData("Realm", "0")]
[InlineData("RemoteRealm", "2")]
[InlineData("DataConnectionId", "\"missing-connection\"")]
[InlineData("LocalParentId", "\"missing-parent\"")]
[InlineData("ConsumerNodeIds", "[\"node-a\",\"node-b\"]")]
[InlineData("AllowedOperations", "8")]
[InlineData("MaxProjectionNodes", "0")]
[InlineData("Revision", "0")]
public void Malformed_enabled_mapping_is_not_installed_with_inferred_permissions(
string field,
string value
)
{
var root = Fixture();
root["RemoteNamespaceMappings"]![0]![field] = JsonNode.Parse(value);
using var parsed = DeploymentArtifact.Open(Blob(root));
var error = Should.Throw<InvalidDataException>(() =>
parsed.ParseRemoteNamespaceMappings(NodeA)
);
error.Message.ShouldContain("mapping-a");
}
[Theory]
[InlineData("PrincipalId", "\"\"")]
[InlineData("Realm", "0")]
[InlineData("RootEntityId", "\"missing-origin\"")]
[InlineData("RootKind", "\"RemoteNamespaceMapping\"")]
[InlineData("AllowedOperations", "1073741824")]
[InlineData("Revision", "0")]
public void Malformed_enabled_export_cannot_become_a_broad_or_reexport_grant(
string field,
string value
)
{
var root = Fixture();
root["DataExports"]![0]![field] = JsonNode.Parse(value);
using var parsed = DeploymentArtifact.Open(Blob(root));
var error = Should.Throw<InvalidDataException>(() => parsed.ParseDataExports(NodeA));
error.Message.ShouldContain("export-a");
}
[Fact]
public void Missing_connection_array_does_not_leave_an_enabled_orphan_mount()
{
var root = Fixture();
root.Remove("DataConnections");
using var parsed = DeploymentArtifact.Open(Blob(root));
var error = Should.Throw<InvalidDataException>(() =>
parsed.ParseRemoteNamespaceMappings(NodeA)
);
error.Message.ShouldContain("mapping-a");
}
[Fact]
public void Presented_credentials_are_rejected_without_echoing_them_in_artifact_diagnostics()
{
const string presentedSecret = "presented-key-never-log-this";
var root = Fixture();
root["DataConnections"]![0]!["Endpoints"] = new JsonArray(
"https://peer:" + presentedSecret + "@node-b:7443"
);
using var parsed = DeploymentArtifact.Open(Blob(root));
var error = Should.Throw<InvalidDataException>(() => parsed.ParseDataConnections(NodeA));
error.Message.ShouldContain("connection-a");
error.Message.ShouldNotContain(presentedSecret);
}
[Fact]
public void New_projections_are_materialized_and_survive_document_disposal()
{
IReadOnlyList<DataConnection> connections;
IReadOnlyList<DataExport> exports;
IReadOnlyList<RemoteNamespaceMapping> mappings;
var root = Fixture();
root["RemoteNamespaceMappings"]![0]!["ExpectedValueKind"] = (int)DataValueKind.Array;
root["RemoteNamespaceMappings"]![0]!["ExpectedArrayElementKind"] = (int)
DataValueKind.UInt64;
using (var parsed = DeploymentArtifact.Open(Blob(root)))
{
connections = parsed.ParseDataConnections(NodeA);
exports = parsed.ParseDataExports(NodeA);
mappings = parsed.ParseRemoteNamespaceMappings(NodeA);
}
connections.ShouldHaveSingleItem().Endpoints.ShouldBe(["https://node-b:7443"]);
connections[0].ConsumerNodeIds.ShouldBe([NodeA]);
connections[0].SecretReference.ShouldBe("secret:data/upstream");
exports.ShouldHaveSingleItem().RootEntityId.ShouldBe("local-root");
mappings.ShouldHaveSingleItem().RemoteIdentifier.ShouldBe("origin-root");
mappings[0].WriteThrough.ShouldBeFalse();
mappings[0].ExpectedValueKind.ShouldBe(DataValueKind.Array);
mappings[0].ExpectedArrayElementKind.ShouldBe(DataValueKind.UInt64);
}
[Fact]
public void Static_facades_preserve_the_strict_scoped_projection()
{
var blob = Blob(Fixture());
DeploymentArtifact
.ParseDataConnections(blob, NodeA)
.ShouldHaveSingleItem()
.DataConnectionId.ShouldBe("connection-a");
DeploymentArtifact
.ParseDataExports(blob, NodeA)
.ShouldHaveSingleItem()
.DataExportId.ShouldBe("export-a");
DeploymentArtifact
.ParseRemoteNamespaceMappings(blob, NodeA)
.ShouldHaveSingleItem()
.RemoteNamespaceMappingId.ShouldBe("mapping-a");
DeploymentArtifact.ParseDataConnections(blob, "unlisted").ShouldBeEmpty();
DeploymentArtifact.ParseDataExports(blob, "unlisted").ShouldBeEmpty();
DeploymentArtifact.ParseRemoteNamespaceMappings(blob, "unlisted").ShouldBeEmpty();
var root = Fixture();
root["DataConnections"]![0]!["SecretReference"] = "";
Should
.Throw<InvalidDataException>(() =>
DeploymentArtifact.ParseDataConnections(Blob(root), NodeA)
)
.Message.ShouldContain("connection-a");
}
[Fact]
public void Foreign_projected_mapping_cannot_be_used_as_a_remote_root()
{
var root = Fixture();
root["DataConnections"]![0]!["ExpectedClusterId"] = "remote";
var foreign = root["RemoteNamespaceMappings"]![0]!.DeepClone();
foreign["ClusterId"] = "remote";
foreign["RemoteNamespaceMappingId"] = "origin-root";
root["RemoteNamespaceMappings"]!.AsArray().Add(foreign);
using var parsed = DeploymentArtifact.Open(Blob(root));
Should
.Throw<InvalidDataException>(() => parsed.ParseRemoteNamespaceMappings(NodeA))
.Message.ShouldContain("mapping-a");
}
[Fact]
public void Null_topology_rows_fail_closed_as_invalid_data()
{
var root = Fixture();
root["Nodes"]!.AsArray().Add((JsonNode?)null);
using var parsed = DeploymentArtifact.Open(Blob(root));
Should.Throw<InvalidDataException>(() => parsed.ParseDataConnections(NodeA));
}
[Theory]
[InlineData("DataConnections", "DataConnectionId", "missing")]
[InlineData("DataConnections", "DataConnectionId", "null")]
[InlineData("DataConnections", "DataConnectionId", "blank")]
[InlineData("DataExports", "DataExportId", "missing")]
[InlineData("DataExports", "DataExportId", "null")]
[InlineData("DataExports", "DataExportId", "blank")]
[InlineData("RemoteNamespaceMappings", "RemoteNamespaceMappingId", "missing")]
[InlineData("RemoteNamespaceMappings", "RemoteNamespaceMappingId", "null")]
[InlineData("RemoteNamespaceMappings", "RemoteNamespaceMappingId", "blank")]
public void Enabled_rows_require_logical_ids(string collection, string field, string shape)
{
var root = Fixture();
var row = root[collection]![0]!.AsObject();
if (shape == "missing")
row.Remove(field);
else if (shape == "null")
row[field] = null;
else
row[field] = " ";
using var parsed = DeploymentArtifact.Open(Blob(root));
var error = Should.Throw<InvalidDataException>(() =>
{
if (collection == "DataConnections")
parsed.ParseDataConnections(NodeA);
else if (collection == "DataExports")
parsed.ParseDataExports(NodeA);
else
parsed.ParseRemoteNamespaceMappings(NodeA);
});
error.Message.ShouldContain("<unknown>");
}
[Fact]
public void Null_id_cannot_hide_other_invalid_connection_fields()
{
var root = Fixture();
root["DataConnections"]![0]!["DataConnectionId"] = null;
root["DataConnections"]![0]!["TargetMode"] = 0;
using var parsed = DeploymentArtifact.Open(Blob(root));
Should
.Throw<InvalidDataException>(() => parsed.ParseDataConnections(NodeA))
.Message.ShouldContain("<unknown>");
}
[Theory]
[InlineData("DataConnections", "DataConnectionId")]
[InlineData("DataExports", "DataExportId")]
[InlineData("RemoteNamespaceMappings", "RemoteNamespaceMappingId")]
public void Lowercase_enabled_with_null_id_is_rejected(string collection, string idName)
{
var root = Fixture();
var row = root[collection]![0]!.AsObject();
row.Remove("Enabled");
row["enabled"] = true;
row[idName] = null;
using var parsed = DeploymentArtifact.Open(Blob(root));
Should.Throw<InvalidDataException>(() => ReadCollection(parsed, collection));
}
[Theory]
[InlineData("DataConnections", "DataConnectionId", "dataConnectionId")]
[InlineData("DataExports", "DataExportId", "dataExportId")]
[InlineData("RemoteNamespaceMappings", "RemoteNamespaceMappingId", "remoteNamespaceMappingId")]
public void Case_variant_shadow_id_is_rejected(string collection, string idName, string alias)
{
var root = Fixture();
root[collection]![0]!.AsObject().ContainsKey(idName).ShouldBeTrue();
root[collection]![0]![alias] = null;
using var parsed = DeploymentArtifact.Open(Blob(root));
Should.Throw<InvalidDataException>(() => ReadCollection(parsed, collection));
}
[Theory]
[InlineData("DataConnections")]
[InlineData("DataExports")]
[InlineData("RemoteNamespaceMappings")]
public void Case_variant_owner_cannot_override_local_scope(string collection)
{
var root = Fixture();
root[collection]![0]!["clusterId"] = "foreign";
using var parsed = DeploymentArtifact.Open(Blob(root));
Should.Throw<InvalidDataException>(() => ReadCollection(parsed, collection));
}
private static void ReadCollection(ParsedDeploymentArtifact parsed, string collection)
{
if (collection == "DataConnections")
parsed.ParseDataConnections(NodeA);
else if (collection == "DataExports")
parsed.ParseDataExports(NodeA);
else
parsed.ParseRemoteNamespaceMappings(NodeA);
}
private static byte[] Blob(JsonObject root) => Encoding.UTF8.GetBytes(root.ToJsonString());
private static JsonObject Fixture() =>
JsonNode
.Parse(
"""
{
"Clusters": [{"ClusterId":"local","Name":"Local","Enterprise":"ent","Site":"site","RedundancyMode":0,"CreatedBy":"test","Enabled":true}],
"Nodes": [
{"NodeId":"node-a","ClusterId":"local","Host":"node-a","ApplicationUri":"urn:node-a","CreatedBy":"test","Enabled":true,"MaintenanceMode":false},
{"NodeId":"node-b","ClusterId":"local","Host":"node-b","ApplicationUri":"urn:node-b","CreatedBy":"test","Enabled":true,"MaintenanceMode":false}
],
"RawFolders": [{"RawFolderId":"local-root","ClusterId":"local","Name":"Local"}],
"DataConnections": [{
"DataConnectionId":"connection-a","ClusterId":"local","Revision":3,"Enabled":true,
"ConsumerNodeIds":["node-a"],"TargetMode":1,"Consistency":1,
"ExpectedClusterId":"local","ExpectedNodeId":"node-b","EligibleTargetNodeIds":[],
"Endpoints":["https://node-b:7443"],"SecretReference":"secret:data/upstream",
"SecretScopeClusterId":"local","AllowedOperations":5
}],
"DataExports": [{
"DataExportId":"export-a","ClusterId":"local","Revision":4,"Enabled":true,
"Realm":1,"RootKind":"RawFolder","RootEntityId":"local-root",
"PrincipalId":"peer","AllowedOperations":5
}],
"RemoteNamespaceMappings": [{
"RemoteNamespaceMappingId":"mapping-a","ClusterId":"local","DataConnectionId":"connection-a",
"Revision":5,"Enabled":true,"ConsumerNodeIds":["node-a"],"Realm":1,"RemoteRealm":1,
"LocalParentKind":"RawFolder","LocalParentId":"local-root","BranchName":"Remote",
"RemoteRootEntityId":"origin-root","RemoteNamespaceUri":"https://zb.com/otopcua/raw","RemoteIdentifierKind":"string",
"RemoteIdentifier":"origin-root","AllowedOperations":1,"WriteThrough":false
}]
}
"""
)!
.AsObject();
}