feat: deploy scoped grpc data connection configuration

This commit is contained in:
Joseph Doherty
2026-11-15 22:46:12 -05:00
parent 443e083403
commit f2a9a525bb
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 =>